@openchamber/web 1.13.1 → 1.13.2

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 (90) hide show
  1. package/dist/assets/{DiagramView-la2P5DUr.js → DiagramView-l49NCoWI.js} +1 -1
  2. package/dist/assets/MarkdownRendererImpl-BspFAgXe.js +7 -0
  3. package/dist/assets/{MultiRunWindow-B9NPliTC.js → MultiRunWindow-BP1L8slG.js} +1 -1
  4. package/dist/assets/{NewWorktreeDialog-BnK_0_OO.js → NewWorktreeDialog-B2o615D_.js} +1 -1
  5. package/dist/assets/OnboardingScreen-DNQQWFmn.js +1 -0
  6. package/dist/assets/{SessionSwitcherDropdown-CuRsG7FM.js → SessionSwitcherDropdown-Bz03hrU9.js} +1 -1
  7. package/dist/assets/{SettingsWindow-Cs3xbqtf.js → SettingsWindow-L-jJDG3k.js} +1 -1
  8. package/dist/assets/{TerminalView-CLKpaKdm.js → TerminalView-CZYwjWYc.js} +1 -1
  9. package/dist/assets/index-Di3CDurc.css +1 -0
  10. package/dist/assets/index-DkRLSXEX.js +3 -0
  11. package/dist/assets/{main-B2rXVG8L.js → main-DmS7A2g8.js} +2 -2
  12. package/dist/assets/main-gqEqIL1b.js +214 -0
  13. package/dist/assets/miniChat-DZORfsku.js +2 -0
  14. package/dist/assets/mobile-DkitItmP.js +2 -0
  15. package/dist/assets/{renderElectronMiniChatApp-BLM-RCP0.js → renderElectronMiniChatApp-S7GCIhbH.js} +2 -2
  16. package/dist/assets/{renderMobileApp-BXScr4up.js → renderMobileApp-CxEnmaQL.js} +3 -3
  17. package/dist/assets/{useAppFontEffects-ByW8wOJM.js → useAppFontEffects-DkrfZHQv.js} +114 -114
  18. package/dist/assets/vendor--Dwc_TRgJ.css +1 -0
  19. package/dist/assets/{vendor-.bun-d5B0wgQr.js → vendor-.bun-CIlawBoH.js} +1 -1
  20. package/dist/index.html +5 -5
  21. package/dist/mini-chat.html +5 -5
  22. package/dist/mobile.html +5 -5
  23. package/package.json +1 -1
  24. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  25. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  26. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  27. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  28. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  29. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  30. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  31. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  32. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  33. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  34. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  35. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  36. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  37. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  38. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  39. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  40. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  41. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  42. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  43. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  44. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  45. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  46. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  47. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  48. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  49. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  50. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  51. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  52. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  53. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  54. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  55. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  56. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  57. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  58. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  59. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  60. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  61. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  62. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  63. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  64. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  65. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  66. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  67. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  68. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  69. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  70. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  71. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  72. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  73. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  74. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  75. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  76. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  77. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  78. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  79. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  80. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  81. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  82. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  83. package/dist/assets/MarkdownRendererImpl-CkGSBGo5.js +0 -8
  84. package/dist/assets/OnboardingScreen-laLzQZgy.js +0 -1
  85. package/dist/assets/index-68ujKCUc.js +0 -3
  86. package/dist/assets/index-C-aQ_xRH.css +0 -1
  87. package/dist/assets/main-CuEzPtRt.js +0 -214
  88. package/dist/assets/miniChat-DVXSR0vu.js +0 -2
  89. package/dist/assets/mobile-BgYrNCOf.js +0 -2
  90. package/dist/assets/vendor--V65Sl9C2.css +0 -1
@@ -1,214 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/useAppFontEffects-ByW8wOJM.js","assets/vendor-.bun-d5B0wgQr.js","assets/vendor--V65Sl9C2.css","assets/index-68ujKCUc.js","assets/index-C-aQ_xRH.css","assets/TerminalView-CLKpaKdm.js","assets/NewWorktreeDialog-BnK_0_OO.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-CuRsG7FM.js","assets/DiagramView-la2P5DUr.js","assets/SettingsWindow-Cs3xbqtf.js","assets/MultiRunWindow-B9NPliTC.js","assets/OnboardingScreen-laLzQZgy.js"])))=>i.map(i=>d[i]);
2
- import{j as s,e as ht,a as Zi,R as i,d as cm,p as Ql,b as dm,H as Qe,I as um,u as aa,l as mo,n as la,D as ca,q as da,S as Al,v as Dl,w as Xl,C as Zl,L as Tl,N as fh,O as hh,T as ph,W as gh,X as Xr,Y as xh,$ as bh,F as yh,a0 as wh,a1 as vh,a2 as jh,a3 as mm,a4 as Sh,a5 as Nh,a6 as Pl,a7 as kh,m as Ch,s as Ah,a8 as Kc,a9 as qc,aa as Yc,ab as Dh,ac as Th,ad as Ph,ae as Ih,af as Rh,ag as Eh,_ as Ai,ah as Jc,ai as Qc,aj as Xc,G as Mh}from"./vendor-.bun-d5B0wgQr.js";import{f as ec,h as er,j as Gi,k as Zc,l as Fh,m as ua,n as fm,p as Lh,e as gs,q as To,b as Me,t as Oh,v as Na,w as Fr,a as pr,x as Er,y as Il,z as Bh,A as _h,R as ed,B as td,u as Bs,C as Vh,D as bi,E as hm,F as pm,G as tc,o as Cn,H as $h,r as fo,g as wi,I as sc,J as gm,K as zh,L as Wh,M as qo,N as Yo,O as Uh,P as Hh,Q as Gh,S as sd,T as nd,U as rd,V as id,W as Kh,X as qh,d as od,Y as Yh,Z as Jh,_ as Qh,i as Xh,s as Zh}from"./index-68ujKCUc.js";import{u as jt,m as Te,ap as ls,I as T,p as tr,t as me,aq as $s,ar as Cr,as as zs,at as Ws,a as _n,au as Ar,av as Si,aw as ad,ax as Nt,ay as kt,az as Ct,aA as ep,ad as jo,aB as ma,aC as Zr,ae as So,af as xm,a6 as nc,aD as bm,aE as tp,Q as Ut,z as mt,aF as sp,a8 as rc,y as gr,x as ic,D as ds,R as Ni,aG as ym,aH as wm,aI as fa,aJ as vm,aK as jm,a5 as Sm,aL as Nm,aM as km,aN as np,aO as rp,T as oc,aP as ka,aQ as ei,aR as ac,aS as Jo,X as Vs,aT as ip,aU as Cm,aV as op,aW as Am,aX as Dm,aY as Ms,aZ as Ps,B as ze,a_ as ks,a$ as Cs,b0 as ri,b1 as ap,b2 as lp,b3 as Mo,b4 as vn,b5 as Tm,b6 as Pm,a2 as lc,b7 as cp,b8 as ld,b9 as cd,ba as yi,n as ln,bb as ki,bc as Ki,bd as dp,be as up,bf as mp,bg as fp,bh as Ca,bi as Aa,bj as Da,bk as Ta,bl as ti,bm as ni,bn as hp,bo as pp,bp as qs,bq as gp,br as xp,bs as bp,bt as yp,bu as wp,k as vi,bv as cc,bw as vp,bx as jp,by as Sp,bz as Np,bA as kp,bB as Cp,bC as Ap,bD as An,bE as Dn,bF as Tn,bG as fn,bH as Pn,bI as vs,bJ as Dp,w as No,M as Pa,S as Ia,bK as Tp,bL as qn,bM as Pp,b as ii,d as dc,c as Ra,bN as Ip,bO as Im,bP as Rp,bQ as Ep,e as uc,bR as Mp,f as an,bS as Ea,a3 as Nr,j as Fp,bT as Lp,bU as Ja,bV as Op,bW as Bp,F as Mr,bX as mc,bY as Ma,bZ as on,b_ as Ci,l as qi,b$ as Rm,c0 as _p,c1 as Vp,c2 as $p,c3 as dd,c4 as zp,q as Lr,r as ud,v as md,c5 as fd,c6 as Em,c7 as hd,c8 as pd,c9 as Mm,ca as Wp,cb as Fm,o as gd,J as Up,cc as Qa,cd as fc,ce as Hp,cf as Gp,cg as Kp,ch as Po,ci as qp,cj as hc,ck as Yp,cl as pc,cm as Lm,cn as Fo,co as Jp,cp as kr,cq as Qp,cr as Om,cs as Xp,ct as Zp,cu as xd,cv as Bm,cw as _m,cx as Vm,E as gc,P as Fa,G as La,L as ha,cy as pa,cz as Nn,H as eg,K as tg,cA as sg,cB as Rl,cC as ng,cD as rg,cE as ig,cF as bd,cG as og,cH as ag,cI as lg,cJ as xc,cK as $m,cL as cg,cM as dg,cN as ug,cO as mg,cP as yd,cQ as wd,cR as fg,cS as hg,cT as pg,cU as gg,cV as xg,cW as bg,N as yg,cX as vd,cY as wg,O as vg,cZ as jg,A as Sg,C as Ng,c_ as kg,c$ as Cg,d0 as Ag,d1 as Dg,d2 as Tg,d3 as Pg,d4 as Ig,d5 as Rg,d6 as ga,d7 as Eg,d8 as jd,d9 as Mg,da as Fg,db as Lg,dc as eo,dd as Og,de as Sd,df as Bg,dg as _g,dh as Vg,di as $g,dj as zm,dk as Wm,dl as zg,dm as Wg,dn as Ug,dp as Qo,aa as Hg,dq as Gg,dr as Kg,U as qg,V as Yg,W as Jg,Y as Nd,Z as kd,_ as Cd,ds as Qg,$ as Um,a0 as Hm,dt as Xg,ak as Zg,al as ex,am as tx,an as sx,ao as nx,ag as rx,ah as ix,ai as ox,aj as ax}from"./useAppFontEffects-ByW8wOJM.js";import{I as Ad,o as lx,p as Dd,q as cx,r as Td,t as Gr,s as dx,v as Xa,w as ko,U as xa,x as ba,y as Yi,z as Io,B as Ji,k as Gm,M as Km,i as Zs,j as ux,E as mx,F as fx,G as hx,l as El,H as qm,P as Ym,J as px,K as gx,C as xx,a as bx,L as bc,Q as Jm,R as yc,T as wc,V as vc,W as Qm,X as Xm,Y as Ml,Z as Zm,_ as Fl,$ as Xo,a0 as yx,a1 as wx,e as ho,N as vx,D as jx,u as Sx,n as Nx,m as Ll,a2 as kx,a3 as Cx,g as Ax,a4 as Dx,a5 as Tx,c as Px,O as ef,d as Ix,a6 as Rx}from"./NewWorktreeDialog-BnK_0_OO.js";import{S as Ex,C as Mx,W as Fx,g as jc,r as Lx,n as Gt,i as Co,d as Qi,c as $i,a as Pd,b as Ox,e as po,f as tf,h as Bx,j as _x,u as Za}from"./SessionSwitcherDropdown-CuRsG7FM.js";function sf(t){const{drafts:e,editingDraftId:n,commentText:r,onTextChange:o,selection:a,isDragging:c,fileLabel:l,newWidgetId:d,mapDraftToRange:m,onSave:f,onCancel:u,onEdit:g,onDelete:b}=t,h=[];for(const x of e){const y=m(x);if(x.id===n){h.push({afterLine:y.end,id:`edit-${x.id}`,content:s.jsx(Ad,{initialText:r,onTextChange:o,fileLabel:l,lineRange:y,isEditing:!0,onSave:f,onCancel:u},`edit-${x.id}`)});continue}h.push({afterLine:y.end,id:`card-${x.id}`,content:s.jsx(lx,{draft:x,onEdit:()=>g(x),onDelete:()=>b(x)},`card-${x.id}`)})}if(a&&!n&&!c){const x={...a,start:Math.min(a.start,a.end),end:Math.max(a.start,a.end)};h.push({afterLine:x.end,id:d,content:s.jsx(Ad,{initialText:r,onTextChange:o,fileLabel:l,lineRange:x,isEditing:!1,onSave:f,onCancel:u},d)})}return h}function Id(t){const e=ht.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const c=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let d;e[5]!==a||e[6]!==c||e[7]!==l?(d={width:c,height:l,...a},e[5]=a,e[6]=c,e[7]=l,e[8]=d):d=e[8];let m;e[9]===Symbol.for("react.memo_cache_sentinel")?(m=s.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"}),e[9]=m):m=e[9];let f;return e[10]!==n||e[11]!==r||e[12]!==d?(f=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:d,...r,children:m}),e[10]=n,e[11]=r,e[12]=d,e[13]=f):f=e[13],f}const si=[{id:"finder",label:"Finder",appName:"Finder"},{id:"terminal",label:"Terminal",appName:"Terminal"},{id:"iterm2",label:"iTerm2",appName:"iTerm"},{id:"ghostty",label:"Ghostty",appName:"Ghostty"},{id:"vscode",label:"VS Code",appName:"Visual Studio Code"},{id:"intellij",label:"IntelliJ",appName:"IntelliJ IDEA"},{id:"visual-studio",label:"Visual Studio",appName:"Visual Studio"},{id:"cursor",label:"Cursor",appName:"Cursor"},{id:"android-studio",label:"Android Studio",appName:"Android Studio"},{id:"pycharm",label:"PyCharm",appName:"PyCharm"},{id:"xcode",label:"Xcode",appName:"Xcode"},{id:"sublime-text",label:"Sublime",appName:"Sublime Text"},{id:"webstorm",label:"WebStorm",appName:"WebStorm"},{id:"rider",label:"Rider",appName:"Rider"},{id:"zed",label:"Zed",appName:"Zed"},{id:"phpstorm",label:"PhpStorm",appName:"PhpStorm"},{id:"eclipse",label:"Eclipse",appName:"Eclipse"},{id:"windsurf",label:"Windsurf",appName:"Windsurf"},{id:"vscodium",label:"VSCodium",appName:"VSCodium"},{id:"rustrover",label:"RustRover",appName:"RustRover"},{id:"kiro",label:"Kiro",appName:"Kiro"},{id:"antigravity",label:"Antigravity",appName:"Antigravity"},{id:"trae",label:"Trae",appName:"Trae"}],Ol="finder",Bl=new Set(["finder","terminal"]),Sc=t=>typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32"&&t.id==="finder"?{...t,label:"Explorer",appName:"File Explorer"}:t,_l=t=>{if(!t)return null;const e=si.find(n=>n.id===t)??null;return e?Sc(e):null},el=()=>si.filter(t=>Bl.has(t.id)).map(t=>({...Sc(t)})),Vx=()=>{if(typeof window>"u")return Ol;const t=window.localStorage.getItem("openInAppId");return t&&_l(t)?t:Ol};let tl=!1,Oi=!1,Kr=!1,qr=0,go=null;const Rd=()=>{go&&(clearTimeout(go),go=null)},fr=Zi()((t,e)=>({selectedAppId:Vx(),availableApps:el(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(tl||typeof window>"u")return;tl=!0;const n=(d,m=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:el(),hasLoadedApps:m});return}const f=new Set(d.map(h=>h.name)),u=new Map(d.map(h=>[h.name,h.iconDataUrl??void 0])),b=si.filter(h=>f.has(h.appName)||Bl.has(h.id)).map(h=>({...Sc(h),iconDataUrl:u.get(h.appName)}));t({availableApps:b,hasLoadedApps:!0})},r=async d=>{if(!er()||!Gi()||Oi||e().hasLoadedApps&&!d)return;const f=si.map(u=>u.appName);Rd(),Oi=!0,Kr=!1,t({isScanning:!0});try{const{apps:u,success:g,hasCache:b,isCacheStale:h}=await Zc(f,d),x=g&&!b&&u.length===0&&qr<3;if(t({isCacheStale:b?h:!1}),n(u,g?!x:!1),g){if(x){const p=[800,1600,3200][qr]??3200;qr+=1,Kr=!0,go=setTimeout(()=>{r()},p);return}qr=0,Kr=!1;return}if(qr<3){const p=[1e3,3e3,7e3][qr]??7e3;qr+=1,Kr=!0,go=setTimeout(()=>{r()},p)}}finally{Oi=!1,Kr||t({isScanning:!1})}};r();const o=d=>{const m=d.detail,f=m&&typeof m.openInAppId=="string"&&m.openInAppId.length>0&&_l(m.openInAppId)?m.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),t({selectedAppId:f}))},a=()=>{r()},c=d=>{const m=d.detail;Array.isArray(m)&&(qr=3,Kr=!1,t({isScanning:!1,isCacheStale:!1}),n(m))};window.addEventListener("openchamber:settings-synced",o),window.addEventListener("openchamber:app-ready",a),window.addEventListener("openchamber:installed-apps-updated",c),window.__openchamberAppReady&&r(),window.setTimeout(()=>{e().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(tl||e().initialize(),!er()||!Gi()||Oi||e().hasLoadedApps&&!n)return;const o=si.map(a=>a.appName);Rd(),n&&t({hasLoadedApps:!1}),Oi=!0,Kr=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await Zc(o,n),d=new Set(a.map(g=>g.name)),m=new Map(a.map(g=>[g.name,g.iconDataUrl??void 0])),u=si.filter(g=>d.has(g.appName)||Bl.has(g.id)).map(g=>({...g,iconDataUrl:m.get(g.appName)}));t({availableApps:u.length>0?u:el(),hasLoadedApps:u.length>0,isCacheStale:c?l:!1})}finally{Oi=!1,Kr||t({isScanning:!1})}},selectApp:async n=>{_l(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await ec({openInAppId:n}))}})),$x="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",zx="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",sl=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__OPENCHAMBER_PLATFORM__!=="win32"?$x:t.id==="terminal"?zx:void 0}),Ed=t=>{const e=ht.c(8),{label:n,iconDataUrl:r,fallbackIconDataUrl:o}=t,[a,c]=i.useState(!1);let l;e[0]!==n?(l=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=l):l=e[1];const d=l,m=r||o;if(m&&!a){let g;e[2]===Symbol.for("react.memo_cache_sentinel")?(g=()=>c(!0),e[2]=g):g=e[2];let b;return e[3]!==m?(b=s.jsx("img",{src:m,alt:"",className:"h-4 w-4 rounded-sm",onError:g}),e[3]=m,e[4]=b):b=e[4],b}let f;e[5]===Symbol.for("react.memo_cache_sentinel")?(f=Te("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=f):f=e[5];let u;return e[6]!==d?(u=s.jsx("span",{className:f,children:d}),e[6]=d,e[7]=u):u=e[7],u},Wx=t=>{const e=ht.c(75),{directory:n,className:r}=t,{t:o}=jt(),a=fr(Ux),c=fr(Hx),l=fr(Gx),d=fr(Kx),m=fr(qx),f=fr(Yx),u=fr(Jx);let g,b;e[0]!==m?(g=()=>{m()},b=[m],e[0]=m,e[1]=g,e[2]=b):(g=e[1],b=e[2]),i.useEffect(g,b);const h=er()&&Gi();let x;e:{let ve;e[3]!==c||e[4]!==a?(ve=c.find(q=>q.id===a)??c.find(Qx)??c[0]??si[0],e[3]=c,e[4]=a,e[5]=ve):ve=e[5];const J=ve;if(J){let q;e[6]!==J?(q=sl(J),e[6]=J,e[7]=q):q=e[7],x=q;break e}let H;e[8]===Symbol.for("react.memo_cache_sentinel")?(H=sl(si[0]),e[8]=H):H=e[8],x=H}const y=x;if(!h||!n||c.length===0)return null;let p;e[9]!==n?(p=async ve=>{await Fh(n,ve.id,ve.appName)||await ua(n,ve.appName)},e[9]=n,e[10]=p):p=e[10];const C=p;let v;e[11]!==C||e[12]!==u?(v=async ve=>{await u(ve.id),await C(ve)},e[11]=C,e[12]=u,e[13]=v):v=e[13];const k=v;let w;e[14]!==n||e[15]!==o?(w=async()=>{(await tr(n)).ok&&me.success(o("openInApp.toast.pathCopied"))},e[14]=n,e[15]=o,e[16]=w):w=e[16];const A=w;let S;e[17]!==r?(S=Te("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",r),e[17]=r,e[18]=S):S=e[18];let I;e[19]!==C||e[20]!==y?(I=()=>{C(y)},e[19]=C,e[20]=y,e[21]=I):I=e[21];const D=d&&"animate-pulse";let N;e[22]!==D?(N=Te("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",D),e[22]=D,e[23]=N):N=e[23];let M;e[24]!==y.label||e[25]!==o?(M=o("openInApp.actions.openInAria",{app:y.label}),e[24]=y.label,e[25]=o,e[26]=M):M=e[26];let P;e[27]!==y.fallbackIconDataUrl||e[28]!==y.iconDataUrl||e[29]!==y.label?(P=s.jsx(Ed,{label:y.label,iconDataUrl:y.iconDataUrl,fallbackIconDataUrl:y.fallbackIconDataUrl}),e[27]=y.fallbackIconDataUrl,e[28]=y.iconDataUrl,e[29]=y.label,e[30]=P):P=e[30];let E;e[31]!==N||e[32]!==M||e[33]!==P||e[34]!==I?(E=s.jsx("button",{type:"button",onClick:I,className:N,"aria-label":M,children:P}),e[31]=N,e[32]=M,e[33]=P,e[34]=I,e[35]=E):E=e[35];let V;e[36]===Symbol.for("react.memo_cache_sentinel")?(V=Te("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"),e[36]=V):V=e[36];let R;e[37]!==o?(R=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=R):R=e[38];let B;e[39]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(T,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=B):B=e[39];let O;e[40]!==R?(O=s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:V,"aria-label":R,children:B})}),e[40]=R,e[41]=O):O=e[41];let F;e[42]!==A?(F=()=>{A()},e[42]=A,e[43]=F):F=e[43];let _;e[44]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx(T,{name:"file-copy",className:"h-4 w-4"}),e[44]=_):_=e[44];let ie;e[45]!==o?(ie=o("openInApp.actions.copyPath"),e[45]=o,e[46]=ie):ie=e[46];let oe;e[47]!==ie?(oe=s.jsx("span",{className:"typography-ui-label text-foreground",children:ie}),e[47]=ie,e[48]=oe):oe=e[48];let ne;e[49]!==F||e[50]!==oe?(ne=s.jsxs(ls,{className:"flex items-center gap-2",onClick:F,children:[_,oe]}),e[49]=F,e[50]=oe,e[51]=ne):ne=e[51];let Y;e[52]===Symbol.for("react.memo_cache_sentinel")?(Y=s.jsx(Cr,{}),e[52]=Y):Y=e[52];let te;if(e[53]!==c||e[54]!==k||e[55]!==y.id){let ve;e[57]!==k||e[58]!==y.id?(ve=J=>{const H=sl(J);return s.jsxs(ls,{className:"flex items-center gap-2",onClick:()=>{k(J)},children:[s.jsx(Ed,{label:J.label,iconDataUrl:J.iconDataUrl,fallbackIconDataUrl:H.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:J.label}),y.id===J.id?s.jsx(T,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},J.id)},e[57]=k,e[58]=y.id,e[59]=ve):ve=e[59],te=c.map(ve),e[53]=c,e[54]=k,e[55]=y.id,e[56]=te}else te=e[56];let de;e[60]!==l||e[61]!==f||e[62]!==o?(de=l?s.jsxs(ls,{className:"flex items-center gap-2",onClick:()=>{f(!0)},children:[s.jsx(T,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:o("openInApp.actions.refreshApps")})]}):null,e[60]=l,e[61]=f,e[62]=o,e[63]=de):de=e[63];let be;e[64]!==ne||e[65]!==te||e[66]!==de?(be=s.jsxs(zs,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[ne,Y,te,de]}),e[64]=ne,e[65]=te,e[66]=de,e[67]=be):be=e[67];let ke;e[68]!==O||e[69]!==be?(ke=s.jsxs(Ws,{children:[O,be]}),e[68]=O,e[69]=be,e[70]=ke):ke=e[70];let ae;return e[71]!==E||e[72]!==ke||e[73]!==S?(ae=s.jsxs("div",{className:S,children:[E,ke]}),e[71]=E,e[72]=ke,e[73]=S,e[74]=ae):ae=e[74],ae};function Ux(t){return t.selectedAppId}function Hx(t){return t.availableApps}function Gx(t){return t.isCacheStale}function Kx(t){return t.isScanning}function qx(t){return t.initialize}function Yx(t){return t.loadInstalledApps}function Jx(t){return t.selectApp}function Qx(t){return t.id===Ol}const Xx=1e6,Zx="terminal-store";let Md=!1;const nl=t=>typeof t=="object"&&t!==null,eb=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function bn(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const rl=(t,e)=>({id:t,terminalSessionId:null,lifecycle:"idle",label:e,iconKey:null,bufferChunks:[],bufferLength:0,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),il=t=>({tabs:[t],activeTabId:t.id}),ur=(t,e)=>t.tabs.findIndex(n=>n.id===e),Ns=Zi()(cm(Ql((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=bn(n);r&&t(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),c=`tab-${o.nextTabId}`,l=rl(c,"Terminal");return a.set(r,il(l)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=bn(n);return e().sessions.get(r)},getActiveTab:n=>{const r=bn(n),o=e().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(c=>c.id===a)??o.tabs[0]:o.tabs[0]},createTab:n=>{const r=bn(n);if(!r)return"tab-invalid";const o=`tab-${e().nextTabId}`;return t(a=>{const c=new Map(a.sessions),l=c.get(r),d=a.nextTabId+1,f=`Terminal ${(l?.tabs.length??0)+1}`,u=rl(o,f);return l?c.set(r,{...l,tabs:[...l.tabs,u]}):c.set(r,il(u)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=bn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);return!l||l.activeTabId===r||ur(l,r)<0?a:(c.set(o,{...l,activeTabId:r}),{sessions:c})})},setTabLabel:(n,r,o)=>{const a=bn(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),m=d.get(a);if(!m)return l;const f=ur(m,r);if(f<0||m.tabs[f]?.label===c)return l;const u=[...m.tabs];return u[f]={...u[f],label:c},d.set(a,{...m,tabs:u}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=bn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const m=ur(d,r);if(m<0)return c;const f=o?.trim()||null;if(d.tabs[m]?.iconKey===f)return c;const u=[...d.tabs];return u[m]={...u[m],iconKey:f},l.set(a,{...d,tabs:u}),{sessions:l}})},closeTab:async(n,r)=>{const o=bn(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await Lh(l)}catch{}t(d=>{const m=new Map(d.sessions),f=m.get(o);if(!f)return d;const u=ur(f,r);if(u<0)return d;const g=f.tabs.filter(y=>y.id!==r),b=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,y])=>!(y.directory===o&&y.tabId===r))),h=Object.keys(b).length!==Object.keys(d.projectActionRuns).length;if(g.length===0){const y=`tab-${d.nextTabId}`,p=rl(y,"Terminal");return m.set(o,il(p)),{sessions:m,nextTabId:d.nextTabId+1,...h?{projectActionRuns:b}:{}}}let x=f.activeTabId;return f.activeTabId===r&&(x=g[Math.min(u,g.length-1)]?.id??g[0]?.id??null),m.set(o,{...f,tabs:g,activeTabId:x}),{sessions:m,...h?{projectActionRuns:b}:{}}})},setTabSessionId:(n,r,o)=>{const a=bn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const m=ur(d,r);if(m<0)return c;const f=d.tabs[m],u=o!==null&&f.terminalSessionId!==o,g=o?"running":f.terminalSessionId?"exited":f.lifecycle,b={...f,terminalSessionId:o,lifecycle:g,isConnecting:!1,...u?{bufferChunks:[],bufferLength:0}:{}},h=[...d.tabs];return h[m]=b,l.set(a,{...d,tabs:h}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=bn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const m=ur(d,r);if(m<0)return c;const f=[...d.tabs];return f[m]={...f[m],lifecycle:o,isConnecting:!1},l.set(a,{...d,tabs:f}),{sessions:l}})},setConnecting:(n,r,o)=>{const a=bn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const m=ur(d,r);if(m<0)return c;const f=[...d.tabs];return f[m]={...f[m],isConnecting:o},l.set(a,{...d,tabs:f}),{sessions:l}})},appendToBuffer:(n,r,o)=>{if(!o)return;const a=bn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const m=ur(d,r);if(m<0)return c;const f=d.tabs[m],u=c.nextChunkId,g={id:u,data:o},b=[...f.bufferChunks,g];let h=f.bufferLength+o.length;for(;h>Xx&&b.length>1;){const y=b.shift();if(!y)break;h-=y.data.length}const x=[...d.tabs];return x[m]={...f,bufferChunks:b,bufferLength:h},l.set(a,{...d,tabs:x}),{sessions:l,nextChunkId:u+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=bn(n);t(l=>{const d=new Map(l.sessions),m=d.get(c);if(!m)return l;const f=ur(m,r);if(f<0)return l;const u=m.tabs[f],g=a.autoOpened??u.previewAutoOpened,b=a.locked??u.previewUrlLocked;if(u.previewUrl===o&&u.previewAutoOpened===g&&u.previewUrlLocked===b)return l;const h=[...m.tabs];return h[f]={...u,previewUrl:o,previewAutoOpened:g,previewUrlLocked:b},d.set(c,{...m,tabs:h}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=bn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=ur(l,r);if(d<0)return a;const m=l.tabs[d];if(!m.previewUrl||m.previewAutoOpened)return a;const f=[...l.tabs];return f[d]={...m,previewAutoOpened:!0},c.set(o,{...l,tabs:f}),{sessions:c}})},setProjectActionRun:n=>{t(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)=>{t(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{t(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},clearBuffer:(n,r)=>{const o=bn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=ur(l,r);if(d<0)return a;const m=[...l.tabs];return m[d]={...m[d],bufferChunks:[],bufferLength:0},c.set(o,{...l,tabs:m}),{sessions:c}})},removeDirectory:n=>{const r=bn(n);t(o=>{const a=new Map(o.sessions);a.delete(r);const c=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,l])=>l.directory!==r));return{sessions:a,projectActionRuns:c}})},clearAll:()=>{t({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Zx,storage:dm(()=>fm()),partialize:t=>({sessions:Array.from(t.sessions.entries()).map(([e,n])=>[e,{activeTabId:n.activeTabId,tabs:n.tabs.map(r=>({id:r.id,label:r.label,iconKey:r.iconKey,terminalSessionId:r.terminalSessionId,lifecycle:r.lifecycle,createdAt:r.createdAt}))}]),nextTabId:t.nextTabId}),merge:(t,e)=>{if(!nl(t))return e;const n=Array.isArray(t.sessions)?t.sessions:[],r=new Map;let o=0;for(const l of n){if(!Array.isArray(l)||l.length!==2)continue;const[d,m]=l;if(typeof d!="string"||!nl(m))continue;const f=Array.isArray(m.tabs)?m.tabs:[],u=[];for(const h of f){if(!nl(h))continue;const x=typeof h.id=="string"?h.id:null;if(!x)continue;const y=eb(x);y!==null&&(o=Math.max(o,y));const p=typeof h.terminalSessionId=="string"||h.terminalSessionId===null?h.terminalSessionId:null,C=h.lifecycle,v=C==="idle"||C==="running"||C==="exited"?C:p?"running":"idle";u.push({id:x,label:typeof h.label=="string"?h.label:"Terminal",iconKey:typeof h.iconKey=="string"?h.iconKey:null,terminalSessionId:p,lifecycle:v,createdAt:typeof h.createdAt=="number"?h.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(u.length===0)continue;const g=typeof m.activeTabId=="string"?m.activeTabId:null,b=g?u.some(h=>h.id===g):!1;r.set(d,{tabs:u,activeTabId:b?g:u[0].id})}const a=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,c=Math.max(e.nextTabId,a,o+1);return{...e,sessions:r,nextChunkId:1,nextTabId:c,hasHydrated:!0}}})));if(typeof window<"u"&&!Md){Md=!0;const t=Ns.persist,e=()=>{Ns.getState().hasHydrated||Ns.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const tb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],sb=["dev","start","preview","serve"];async function nb(t,e,n){if(!t)return null;const r=ob(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=ab(n);if(o){const a=await lb(t);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 rb(t)){const o=await ib(),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 rb(t){const e=`${t}/index.html`,n=await ya(e,t);return typeof n=="string"&&n.trim().length>0}async function ib(){try{const t=await gs("/api/system/free-port",{cache:"no-store"});if(!t.ok)return null;const e=await t.json().catch(()=>null),n=typeof e?.port=="number"?e.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function ob(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(sb.some(o=>n.includes(o)))return e}return null}function ab(t){for(const{pattern:e}of tb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function lb(t){const e=await ya(`${t}/package.json`,t);if(e)try{const r=JSON.parse(e),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 ya(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function ya(t,e){if(e?.trim())try{const r=new URLSearchParams({path:t,directory:e,optional:"true"}),o=await gs(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=To()?.files;if(n?.readFile)try{const r=await n.readFile(t,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await gs(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function cb(t){try{const e=await ya(`${t}/package.json`,t);if(e==null)return null;const r=JSON.parse(e).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const db=t=>new Promise(e=>{window.setTimeout(e,t)}),ub="\x1B",mb=new RegExp(`${ub}\\[[0-9;?]*[ -/]*[@-~]`,"g"),fb=/https?:\/\/[^\s<>'"`]+/gi,Un="__openchamber_auto_discover_preview__",hb=15e3,pb=t=>{let e="";for(let n=0;n<t.length;n+=1){const r=t.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(e+=t[n])}return e},gb=t=>{const e=(t||"").trim();if(!e)return null;const n=/^https?:\/\//i.test(e)?e:`http://${e}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},xb=t=>{const n=t.replace(mb,"").match(fb);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 c=new URL(a);c.port&&c.port.length>0&&o.push({raw:a,parsed:c})}catch{}if(o.length>0){const a=c=>{const{parsed:l}=c,d=l.hostname.toLowerCase(),m=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=l.pathname||"/",u=f.split("/").filter(Boolean).length,g=f==="/"||f==="",b=!!(l.search||l.hash);let h=0;return m&&(h+=50),g&&(h+=30),h-=Math.min(u*5,20),b&&(h-=10),h};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},nf=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=jt(),{terminal:c,runtime:l}=_n(),{isMobile:d}=Ar(),m=i.useMemo(()=>er(),[]),f=Dd(z=>z.instances),u=Dd(z=>z.load),g=Me(z=>z.setBottomTerminalOpen),b=Me(z=>z.setActiveMainTab),h=Me(z=>z.setSettingsPage),x=Me(z=>z.setSettingsDialogOpen),y=Me(z=>z.setSettingsProjectsSelectedId),p=Me(z=>z.openContextPreview),C=Ns(z=>z.sessions),v=Ns(z=>z.ensureDirectory),k=Ns(z=>z.setTabLabel),w=Ns(z=>z.setTabIconKey),A=Ns(z=>z.setActiveTab),S=Ns(z=>z.setConnecting),I=Ns(z=>z.setTabSessionId),D=Ns(z=>z.setTabPreviewUrl),N=Ns(z=>z.projectActionRuns),M=Ns(z=>z.setProjectActionRun),P=Ns(z=>z.updateProjectActionRunStatus),E=Ns(z=>z.removeProjectActionRun),[V,R]=i.useState([]),[B,O]=i.useState(null),[F,_]=i.useState(!1),ie=i.useRef({}),oe=i.useRef({}),ne=i.useRef({}),Y=i.useRef({}),te=i.useRef(0),de=t?.id??null,be=t?.path??"",ke=i.useMemo(()=>de?{id:de,path:be}:null,[de,be]);i.useEffect(()=>{m&&u().catch(()=>{})},[m,u]);const ae=i.useCallback(async z=>{await Si(z)},[]),ve=i.useCallback(async()=>{if(!ke)return;const z=te.current+1;te.current=z,_(!0);try{const Ne=await ad(ke);if(te.current!==z)return;const U=Ne.actions;R(U),O(Ie=>Ie===Un||Ie&&U.some(_e=>_e.id===Ie)?Ie:null)}catch{if(te.current!==z)return}finally{te.current===z&&_(!1)}},[ke]),J=i.useMemo(()=>cx(e||ke?.path||""),[e,ke?.path]),H=i.useMemo(()=>B?V.find(z=>z.id===B)??null:null,[V,B]),q=i.useMemo(()=>({id:Un,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),ce=!d,fe=i.useMemo(()=>ce?[q,...V]:V,[V,q,ce]);i.useEffect(()=>{ve()},[ve]),i.useEffect(()=>{if(typeof window>"u")return;const z=Ne=>{const U=Ne.detail;de&&(U?.projectId&&U.projectId!==de||ve())};return window.addEventListener(Td,z),()=>{window.removeEventListener(Td,z)}},[ve,de]),i.useEffect(()=>{B&&(B===Un&&ce||V.some(z=>z.id===B)||O(null))},[V,ce,B]),i.useEffect(()=>{for(const[z,Ne]of Object.entries(N)){const Ie=C.get(Ne.directory)?.tabs.find(_e=>_e.id===Ne.tabId);(!Ie||Ie.terminalSessionId!==Ne.sessionId)&&E(z)}},[N,E,C]),i.useEffect(()=>{for(const[z,Ne]of Object.entries(N)){const U=oe.current[z]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};oe.current[z]=U;const Ie=fe.find($e=>$e.id===Ne.actionId);if(!Ie)continue;const Ve=C.get(Ne.directory)?.tabs.find($e=>$e.id===Ne.tabId);if(!Ve||!Array.isArray(Ve.bufferChunks)||Ve.bufferChunks.length===0)continue;const Le=Ve.bufferChunks.filter($e=>U.lastSeenChunkId===null?!0:$e.id>U.lastSeenChunkId);if(Le.length===0)continue;const X=Le.map($e=>$e.data).join(""),L=`${U.tail}${X}`,xe=!U.openedUrl&&Ie.autoOpenUrl===!0?xb(L):null,Q=Le[Le.length-1]?.id??U.lastSeenChunkId;if(U.lastSeenChunkId=Q,U.tail=L.slice(-512),xe)if(U.openedUrl=!0,U.openInPreview){const $e=N[z];$e&&(D($e.directory,$e.tabId,xe,{locked:!1,autoOpened:!1}),$e.status==="waiting-for-preview"&&P(z,"running"),window.clearTimeout(Y.current[z]),delete Y.current[z],p($e.directory,xe))}else ae(xe),me.success(a("projectActions.toast.openedUrlFromOutput"));oe.current[z]=U}for(const z of Object.keys(oe.current))N[z]||(delete oe.current[z],window.clearTimeout(Y.current[z]),delete Y.current[z])},[fe,p,ae,N,D,a,C,P]);const De=i.useCallback(async(z,Ne={})=>{if(!J)throw new Error(a("projectActions.error.noActiveDirectory"));const U=Gr(J,z.id);v(J);const Ie=Ns.getState(),_e=Ie.getDirectoryState(J);let Ve=ie.current[U]||null;const Le=Ve?!!_e?.tabs.some(xe=>xe.id===Ve):!1;(!Ve||!Le)&&(Ve=Ie.createTab(J),ie.current[U]=Ve),k(J,Ve,`Action: ${z.name}`),w(J,Ve,z.icon||"play"),Ne.revealTerminal!==!1&&(A(J,Ve),g(!0),b("terminal"));const L=Ns.getState().getDirectoryState(J)?.tabs.find(xe=>xe.id===Ve);return{key:U,tabId:Ve,sessionId:L?.terminalSessionId??null}},[v,J,b,A,g,w,k,a]),Re=i.useCallback(async z=>{if(l.isVSCode||!o&&d)return;if(!J){me.error(a("projectActions.error.noActiveDirectoryForAction"));return}const Ne=Gr(J,z.id),U=N[Ne];if(!(U&&U.status==="running"))try{const Ie=z.id===Un?await(async()=>{const[qe,Xe]=await Promise.all([ad({id:ke?.id??"",path:J}),cb(J)]),lt=await nb(J,qe.actions,Xe);if(!lt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:Un,name:a("projectActions.actions.autoDiscover"),command:lt.command,icon:"search",autoOpenUrl:!0,openUrl:lt.previewUrlHint||""}})():z,_e=Ie.autoOpenUrl===!0&&(Ie.openUrl||"").trim().length>0,{key:Ve,tabId:Le,sessionId:X}=await De(Ie,{revealTerminal:!_e&&z.id!==Un});let L=X,xe=!1;if(!L){S(J,Le,!0);try{L=(await c.createSession({cwd:J})).sessionId,xe=!0,I(J,Le,L)}finally{S(J,Le,!1)}}if(!L)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));xe&&await db(350),Ie.id===Un&&(ne.current[Ve]?.(),S(J,Le,!0),ne.current[Ve]=Oh(L,qe=>{qe.type==="data"&&typeof qe.data=="string"&&qe.data.length>0&&Ns.getState().appendToBuffer(J,Le,qe.data),qe.type==="exit"&&(Ns.getState().setTabLifecycle(J,Le,"exited"),Ns.getState().setConnecting(J,Le,!1),Ns.getState().removeProjectActionRun(Ve),delete oe.current[Ve],ne.current[Ve]?.(),delete ne.current[Ve],window.clearTimeout(Y.current[Ve]),delete Y.current[Ve])},()=>{Ns.getState().setConnecting(J,Le,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const Q=Ie.autoOpenUrl===!0&&m&&(Ie.desktopOpenSshForward||"").trim().length>0,$e=Ie.autoOpenUrl?gb(Ie.openUrl):null,He=Ie.autoOpenUrl&&m?dx(Ie.desktopOpenSshForward,f):null;M({key:Ve,directory:J,actionId:Ie.id,tabId:Le,sessionId:L,status:Ie.id===Un&&!$e?"waiting-for-preview":"running"}),window.clearTimeout(Y.current[Ve]),delete Y.current[Ve],Ie.id===Un&&!$e&&(Y.current[Ve]=window.setTimeout(()=>{Ns.getState().updateProjectActionRunStatus(Ve,"running"),delete Y.current[Ve]},hb)),He?(D(J,Le,null,{locked:!0}),ae(He),me.success(a("projectActions.toast.openedForwardedUrl"))):$e?(D(J,Le,$e,{locked:!0,autoOpened:!0}),p(J,$e),me.success(a("projectActions.toast.openedActionUrl"))):_e?(D(J,Le,null,{locked:!0}),me.error(a("projectActions.error.invalidCustomUrlFormat"))):Q?(D(J,Le,null,{locked:!0}),me.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):D(J,Le,null,{locked:!1,autoOpened:!1}),oe.current[Ve]={lastSeenChunkId:null,openedUrl:!!He||!!$e||_e,tail:"",openInPreview:Ie.id===Un};const Ke=pb(Ie.command.trim().replace(/\r\n|\r/g,`
3
- `));await c.sendInput(L,`${Ke}\r`)}catch(Ie){E(Ne),delete oe.current[Ne],ne.current[Ne]?.(),delete ne.current[Ne],window.clearTimeout(Y.current[Ne]),delete Y.current[Ne],me.error(Ie instanceof Error?Ie.message:a("projectActions.error.failedToRunAction"))}},[f,De,o,d,m,J,ae,p,N,l.isVSCode,E,S,M,D,I,ke?.id,a,c]),Fe=i.useCallback(async z=>{const Ne=Gr(J,z.id),U=N[Ne];if(!U)return;P(Ne,"stopping");try{await c.sendInput(U.sessionId,"")}catch{}if(await new Promise(Ve=>{window.setTimeout(Ve,1e3)}),Ns.getState().getDirectoryState(U.directory)?.tabs.find(Ve=>Ve.id===U.tabId)?.terminalSessionId===U.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:U.sessionId})}catch{}else try{await c.close(U.sessionId)}catch{}I(U.directory,U.tabId,null)}E(Ne),delete oe.current[Ne],ne.current[Ne]?.(),delete ne.current[Ne],window.clearTimeout(Y.current[Ne]),delete Y.current[Ne]},[J,N,E,I,c,P]),Oe=i.useCallback(()=>{const z=H??fe[0];if(!z)return;const Ne=Gr(J,z.id),U=N[Ne];if(U?.status!=="stopping"){if(U){Fe(z);return}Re(z)}},[fe,J,Re,N,H,Fe]),Ee=i.useCallback((z,Ne=!1)=>{if(O(z.id),!Ne){Re(z);return}const U=Gr(J,z.id),Ie=N[U];if(Ie?.status!=="stopping"){if(Ie){Fe(z);return}Re(z)}},[J,Re,N,Fe]),we=i.useCallback(()=>{ke?.id&&(y(ke.id),h("projects"),x(!0))},[x,h,y,ke?.id]);if(l.isVSCode||!o&&d||!ke||!J)return null;const Pe=H??fe[0]??null;if(!Pe)return null;const Se=Pe.icon||"play",ue=Pe.id===Un?"search":Xa[Se]||"play",K=Gr(J,Pe.id),he=N[K],se=he?.status==="stopping",G=he?.status==="waiting-for-preview",$=he?C.get(he.directory)?.tabs.find(z=>z.id===he.tabId)?.previewUrl??null:null,pe=!!(he&&$),ye=()=>{!he||!$||p(he.directory,$)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:F||se,className:Te("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:Oe,"aria-label":he?a("projectActions.actions.stopNamedAria",{name:Pe.name}):a("projectActions.actions.runNamedAria",{name:Pe.name}),children:se||G?s.jsx(T,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):he?s.jsx(T,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(T,{name:ue,className:"h-5 w-5"})}),pe?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.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":a("projectActions.actions.openPreview"),onClick:ye,children:s.jsx(T,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ct,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(Ws,{children:[s.jsx($s,{asChild:!0,children:s.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":a("projectActions.actions.chooseActionAria"),children:s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(zs,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ls,{className:"flex items-center gap-2",onClick:we,children:[s.jsx(T,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Cr,{}),fe.map(z=>{const Ne=z.icon||"play",U=z.id===Un?"search":Xa[Ne]||"play",Ie=Gr(J,z.id),_e=N[Ie],Ve=!!_e,Le=_e?.status==="stopping";return s.jsxs(ls,{className:"flex items-center gap-2",onClick:()=>{Ee(z,!0)},children:[s.jsx(T,{name:U,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:z.name}),Le||_e?.status==="waiting-for-preview"?s.jsx(T,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Ve?s.jsx(T,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},z.id)})]})]})]}):s.jsxs("div",{className:Te("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:[s.jsx("button",{type:"button",onClick:Oe,disabled:F||se,className:Te("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":he?a("projectActions.actions.stopNamedAria",{name:Pe.name}):a("projectActions.actions.runNamedAria",{name:Pe.name}),children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:se||G?s.jsx(T,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):he?s.jsx(T,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(T,{name:ue,className:"h-4 w-4"})})}),pe?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ye,className:Te(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":a("projectActions.actions.openPreview"),children:s.jsx(T,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ct,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(Ws,{children:[s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:Te(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":a("projectActions.actions.chooseActionAria"),children:s.jsx(T,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(zs,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ls,{className:"flex items-center gap-2",onClick:we,children:[s.jsx(T,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Cr,{}),fe.map(z=>{const Ne=z.icon||"play",U=z.id===Un?"search":Xa[Ne]||"play",Ie=Gr(J,z.id),_e=N[Ie],Ve=!!_e,Le=_e?.status==="stopping";return s.jsxs(ls,{className:"flex items-center gap-2",onClick:()=>{Ee(z,!0)},children:[s.jsx(T,{name:U,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:z.name}),Le||_e?.status==="waiting-for-preview"?s.jsx(T,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Ve?s.jsx(T,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},z.id)})]})]})]})},Oa="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",bb="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",Lo=i.memo(function(e){const n=ht.c(17),{visible:r,title:o,ariaLabel:a,onClick:c,className:l,Icon:d,iconClassName:m,pressed:f}=e,u=r===void 0?!0:r,g=f===void 0?!1:f;if(!u)return null;const b=l??Oa,h=g&&"bg-interactive-selection text-interactive-selection-foreground";let x;n[0]!==b||n[1]!==h?(x=Te(b,h),n[0]=b,n[1]=h,n[2]=x):x=n[2];const y=m??"h-[18px] w-[18px]";let p;n[3]!==d||n[4]!==y?(p=s.jsx(T,{name:d,className:y}),n[3]=d,n[4]=y,n[5]=p):p=n[5];let C;n[6]!==a||n[7]!==c||n[8]!==g||n[9]!==x||n[10]!==p?(C=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,"aria-label":a,"aria-pressed":g,className:x,children:p})}),n[6]=a,n[7]=c,n[8]=g,n[9]=x,n[10]=p,n[11]=C):C=n[11];let v;n[12]!==o?(v=s.jsx(Ct,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=v):v=n[13];let k;return n[14]!==C||n[15]!==v?(k=s.jsxs(Nt,{children:[C,v]}),n[14]=C,n[15]=v,n[16]=k):k=n[16],k}),yb=i.memo(function(e){const n=ht.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:m}=e,{t:f}=jt();if(!o?.connected||r)return null;if(a.length>1){let h;n[0]===Symbol.for("react.memo_cache_sentinel")?(h=Te(Oa,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),n[0]=h):h=n[0];let x;n[1]!==l||n[2]!==f?(x=l?f("header.github.connectedWithLogin",{login:l}):f("header.github.connected"),n[1]=l,n[2]=f,n[3]=x):x=n[3];let y;n[4]!==c||n[5]!==l||n[6]!==f?(y=c?s.jsx("img",{src:c,alt:l?f("header.github.avatarWithLogin",{login:l}):f("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(T,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=f,n[7]=y):y=n[7];let p;n[8]!==d||n[9]!==x||n[10]!==y?(p=s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:h,title:x,disabled:d,children:y})}),n[8]=d,n[9]=x,n[10]=y,n[11]=p):p=n[11];let C;n[12]!==f?(C=f("header.github.accountsTitle"),n[12]=f,n[13]=C):C=n[13];let v;n[14]!==C?(v=s.jsx(tp,{className:"typography-ui-header font-semibold text-foreground",children:C}),n[14]=C,n[15]=v):v=n[15];let k;n[16]===Symbol.for("react.memo_cache_sentinel")?(k=s.jsx(Cr,{}),n[16]=k):k=n[16];let w;if(n[17]!==a||n[18]!==m||n[19]!==d||n[20]!==f){let I;n[22]!==m||n[23]!==d||n[24]!==f?(I=D=>{const N=D.user,M=!!D.current,P=D.source==="gh-cli"?f("header.github.accountSource.cli"):f("header.github.accountSource.oauth");return s.jsxs(ls,{className:"gap-2",disabled:d,onSelect:()=>{M||m(D.id)},children:[N?.avatarUrl?s.jsx("img",{src:N.avatarUrl,alt:N.login?f("header.github.avatarWithLogin",{login:N.login}):f("header.github.avatar"),className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:s.jsx(T,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:N?.name?.trim()||N?.login||"GitHub"}),N?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:N.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:P})]}):null]}),M?s.jsx(T,{name:"check",className:"h-4 w-4 text-primary"}):null]},D.id)},n[22]=m,n[23]=d,n[24]=f,n[25]=I):I=n[25],w=a.map(I),n[17]=a,n[18]=m,n[19]=d,n[20]=f,n[21]=w}else w=n[21];let A;n[26]!==v||n[27]!==w?(A=s.jsxs(zs,{align:"end",className:"w-64",children:[v,k,w]}),n[26]=v,n[27]=w,n[28]=A):A=n[28];let S;return n[29]!==p||n[30]!==A?(S=s.jsxs(Ws,{children:[p,A]}),n[29]=p,n[30]=A,n[31]=S):S=n[31],S}let u;n[32]!==l||n[33]!==f?(u=l?f("header.github.connectedWithLogin",{login:l}):f("header.github.connected"),n[32]=l,n[33]=f,n[34]=u):u=n[34];let g;n[35]!==c||n[36]!==l||n[37]!==f?(g=c?s.jsx("img",{src:c,alt:l?f("header.github.avatarWithLogin",{login:l}):f("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(T,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[35]=c,n[36]=l,n[37]=f,n[38]=g):g=n[38];let b;return n[39]!==u||n[40]!==g?(b=s.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:u,children:g}),n[39]=u,n[40]=g,n[41]=b):b=n[41],b}),wb=i.memo(function(e){const n=ht.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:m,desktopServicesTab:f,setDesktopServicesTab:u,quotaResultsLength:g,fetchAllQuotas:b,servicesTabItems:h,quotaLastUpdated:x,quotaDisplayMode:y,quotaDisplayTabItems:p,handleDisplayModeChange:C,handleUsageRefresh:v,isQuotaLoading:k,isUsageRefreshSpinning:w,hasRateLimits:A,rateLimitGroups:S,expandedFamilies:I,toggleFamilyExpanded:D,shortcutLabel:N,showDevShutdown:M,isDevShutdownInFlight:P,onDevShutdown:E,remoteUpdateInfo:V,remoteUpdateChecking:R,remoteUpdateError:B,onOpenRemoteUpdate:O,showPredValues:F,timeFormatPreference:_}=e,{t:ie}=jt();let oe;n[0]!==f||n[1]!==b||n[2]!==g||n[3]!==m||n[4]!==d?(oe=Ee=>{d(Ee),Ee&&(m(),f==="usage"&&g===0&&b())},n[0]=f,n[1]=b,n[2]=g,n[3]=m,n[4]=d,n[5]=oe):oe=n[5];let ne;n[6]!==o||n[7]!==r||n[8]!==ie?(ne=r?ie("header.services.openWithCurrent",{current:o}):ie("header.services.open"),n[6]=o,n[7]=r,n[8]=ie,n[9]=ne):ne=n[9];const Y=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let te;n[10]!==Y?(te=Te(Oa,Y),n[10]=Y,n[11]=te):te=n[11];let de;n[12]===Symbol.for("react.memo_cache_sentinel")?(de=s.jsx(T,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=de):de=n[12];let be;n[13]!==a||n[14]!==r?(be=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=be):be=n[15];let ke;n[16]!==ne||n[17]!==te||n[18]!==be?(ke=s.jsx(kt,{asChild:!0,children:s.jsx($s,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":ne,className:te,children:[de,be]})})}),n[16]=ne,n[17]=te,n[18]=be,n[19]=ke):ke=n[19];let ae;n[20]!==o||n[21]!==r||n[22]!==N||n[23]!==ie?(ae=r?ie("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}):ie("header.services.tooltip.servicesWithShortcuts",{toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}),n[20]=o,n[21]=r,n[22]=N,n[23]=ie,n[24]=ae):ae=n[24];let ve;n[25]!==ae?(ve=s.jsx(Ct,{children:s.jsx("p",{children:ae})}),n[25]=ae,n[26]=ve):ve=n[26];let J;n[27]!==ke||n[28]!==ve?(J=s.jsxs(Nt,{children:[ke,ve]}),n[27]=ke,n[28]=ve,n[29]=J):J=n[29];let H;n[30]!==b||n[31]!==g||n[32]!==u?(H=Ee=>{const we=Ee;u(we),we==="usage"&&g===0&&b()},n[30]=b,n[31]=g,n[32]=u,n[33]=H):H=n[33];let q;n[34]!==f||n[35]!==h||n[36]!==H?(q=s.jsx("div",{className:"sticky top-0 z-20 px-2 pt-1.5 pb-px",children:s.jsx("div",{className:"h-9",children:s.jsx(ko,{items:h,activeId:f,onSelect:H,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=f,n[35]=h,n[36]=H,n[37]=q):q=n[37];let ce;n[38]!==c||n[39]!==f||n[40]!==r||n[41]!==l||n[42]!==O||n[43]!==R||n[44]!==B||n[45]!==V||n[46]!==d||n[47]!==ie?(ce=r&&f==="instance"?s.jsxs("div",{children:[c?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ie("header.services.remoteUpdate.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:V?.available?ie("header.services.remoteUpdate.available",{version:V.version||""}):R?ie("header.services.remoteUpdate.checking"):B||ie("header.services.remoteUpdate.upToDate")})]}),V?.available?s.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:O,children:ie("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(ep,{embedded:!0,open:l&&f==="instance",onOpenChange:Sb,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=f,n[40]=r,n[41]=l,n[42]=O,n[43]=R,n[44]=B,n[45]=V,n[46]=d,n[47]=ie,n[48]=ce):ce=n[48];let fe;n[49]!==f||n[50]!==l?(fe=f==="mcp"?s.jsx(Km,{active:l&&f==="mcp"}):null,n[49]=f,n[50]=l,n[51]=fe):fe=n[51];let De;n[52]!==f||n[53]!==I||n[54]!==C||n[55]!==v||n[56]!==A||n[57]!==k||n[58]!==w||n[59]!==y||n[60]!==p||n[61]!==x||n[62]!==S||n[63]!==F||n[64]!==ie||n[65]!==_||n[66]!==D?(De=f==="usage"?s.jsxs("div",{className:"overflow-x-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--interactive-border)] px-4 py-2.5",children:[s.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:ie("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:rf(x,_)})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-[10.5rem]",children:s.jsx(ko,{items:p,activeId:y,onSelect:Ee=>{C(Ee)},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",className:"h-full"})}),s.jsx("button",{type:"button",className:Te("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:v,disabled:k||w,"aria-label":ie("header.services.refreshRateLimitsAria"),children:s.jsx(T,{name:"refresh",className:Te("h-4 w-4",w&&"animate-spin")})})]})]}),A?null:s.jsx("div",{className:"px-4 py-5 text-center",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:ie("header.services.noRateLimits")})}),s.jsx("div",{className:"py-2",children:S.map((Ee,we)=>{const Pe=I[Ee.providerId]??[];return s.jsxs(i.Fragment,{children:[we>0?s.jsx("div",{className:"mx-4 my-2 border-t border-[var(--interactive-border)]"}):null,s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2",children:[s.jsx(jo,{providerId:Ee.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Ee.providerName})]}),Ee.entries.length===0&&(!Ee.modelFamilies||Ee.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Ee.error??ie("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[Ee.entries.map(Se=>{const[ue,K]=Se,he=y==="remaining"?K.remainingPercent:K.usedPercent,se=ma(K.usedPercent,K.resetAt,K.windowSeconds,ue),G=se?.dailyAllocationPercent!=null?y==="remaining"?100-Zr(se.elapsedRatio):Zr(se.elapsedRatio):null,$=So(K.valueLabel,he),pe=xm(K.resetAt,K.resetAfterFormatted??K.resetAtFormatted,_);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:nc(ue)}),pe?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:pe}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:$==="-"?"":$})]}),s.jsx(xa,{percent:he,tonePercent:K.usedPercent,className:"h-1.5",expectedMarkerPercent:G}),se&&F?s.jsx(ba,{paceInfo:se,compact:!0}):null]},`${Ee.providerId}-${ue}`)}),Ee.modelFamilies&&Ee.modelFamilies.length>0?s.jsx("div",{className:"space-y-0.5",children:Ee.modelFamilies.map(Se=>{const ue=Se.familyId??"other",K=Pe.includes(ue);return s.jsxs(Yi,{open:K,onOpenChange:()=>D(Ee.providerId,ue),children:[s.jsxs(Io,{className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Se.familyLabel}),K?s.jsx(T,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(T,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(Ji,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:Se.models.map(he=>{const[se,G]=he,$=y==="remaining"?G.remainingPercent:G.usedPercent,pe=ma(G.usedPercent,G.resetAt,G.windowSeconds),ye=pe?.dailyAllocationPercent!=null?y==="remaining"?100-Zr(pe.elapsedRatio):Zr(pe.elapsedRatio):null,z=So(G.valueLabel,$);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Gm(se)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:z==="-"?"":z})]}),s.jsx(xa,{percent:$,tonePercent:G.usedPercent,className:"h-1.5",expectedMarkerPercent:ye}),pe&&F?s.jsx(ba,{paceInfo:pe,compact:!0}):null]},`${Ee.providerId}-${se}`)})})})]},ue)})}):null]})]},Ee.providerId)})})]}):null,n[52]=f,n[53]=I,n[54]=C,n[55]=v,n[56]=A,n[57]=k,n[58]=w,n[59]=y,n[60]=p,n[61]=x,n[62]=S,n[63]=F,n[64]=ie,n[65]=_,n[66]=D,n[67]=De):De=n[67];let Re;n[68]!==P||n[69]!==E||n[70]!==M||n[71]!==ie?(Re=M?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mx-4 my-2 border-t border-[var(--interactive-border)]"}),s.jsx("div",{className:"px-2 pb-2",children:s.jsx(ls,{disabled:P,onSelect:()=>{E()},children:ie("header.services.shutdownDev")})})]}):null,n[68]=P,n[69]=E,n[70]=M,n[71]=ie,n[72]=Re):Re=n[72];let Fe;n[73]!==q||n[74]!==ce||n[75]!==fe||n[76]!==De||n[77]!==Re?(Fe=s.jsxs(zs,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[q,ce,fe,De,Re]}),n[73]=q,n[74]=ce,n[75]=fe,n[76]=De,n[77]=Re,n[78]=Fe):Fe=n[78];let Oe;return n[79]!==l||n[80]!==oe||n[81]!==J||n[82]!==Fe?(Oe=s.jsxs(Ws,{open:l,onOpenChange:oe,children:[J,Fe]}),n[79]=l,n[80]=oe,n[81]=J,n[82]=Fe,n[83]=Oe):Oe=n[83],Oe}),vb=(t,e)=>t===e?!0:!t||!e?!1:t.totalTokens===e.totalTokens&&t.percentage===e.percentage&&t.contextLimit===e.contextLimit&&(t.outputLimit??0)===(e.outputLimit??0)&&(t.normalizedOutput??0)===(e.normalizedOutput??0)&&t.thresholdLimit===e.thresholdLimit&&(t.lastMessageId??"")===(e.lastMessageId??""),jb=t=>{const e=t.trim();if(!e)return"";const n=e.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<e.length?`${a}...`:a}return e.length>12?`${e.slice(0,9).trimEnd()}...`:e},rf=(t,e)=>{if(!t)return"-";try{return bm(t,e,{fallback:"-"})}catch{return"-"}},yn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Yr=t=>!t?.isOpen||!Array.isArray(t.tabs)||t.tabs.length===0?null:(t.tabs.find(n=>n.id===t.activeTabId)??t.tabs[t.tabs.length-1])?.mode??null,Fd=({onToggleLeftDrawer:t,onToggleRightDrawer:e,leftDrawerOpen:n,rightDrawerOpen:r})=>{const{t:o}=jt(),a=Me(re=>re.setSessionSwitcherOpen),c=Me(re=>re.toggleSidebar),l=Me(re=>re.isSidebarOpen),d=Me(re=>re.toggleBottomTerminal),m=Me(re=>re.toggleRightSidebar),f=Me(re=>re.openContextOverview),u=Me(re=>re.openContextPlan),g=Me(re=>re.openContextBrowser),b=Me(re=>re.openContextPanelTab),h=Me(re=>re.closeContextPanel),x=Me(re=>re.contextPanelByDirectory),y=Me(re=>re.activeMainTab),p=Me(re=>re.setActiveMainTab),C=Me(re=>re.shortcutOverrides),v=Me(re=>re.timeFormatPreference),k=Ut(re=>re.getCurrentModel),w=_n(),[A,S]=i.useState(!1),I=mt(re=>re.getContextUsage),D=mt(re=>!!re.newSessionDraft?.open),N=mt(re=>re.currentSessionId),M=sp(N??""),P=rc(N??null),E=gr(re=>re.activeSessions),V=ic(),R=ds(re=>re.activeProjectId?re.projects.find(nt=>nt.id===re.activeProjectId)??null:null),B=i.useMemo(()=>{if(!R)return null;const re=R.label?.trim();if(re)return re;const nt=R.path.split(/[\\/]/).filter(Boolean);return nt[nt.length-1]??null},[R]),O=Zs(re=>re.results),F=Zs(re=>re.fetchAllQuotas),_=Zs(re=>re.isLoading),ie=Zs(re=>re.lastUpdated),oe=Zs(re=>re.displayMode),ne=Zs(re=>re.showPredValues),Y=Zs(re=>re.dropdownProviderIds),te=Zs(re=>re.loadSettings),de=Zs(re=>re.setDisplayMode),{isMobile:be}=Ar(),ke=Ni(re=>re.status),ae=Ni(re=>re.setStatus),ve=i.useRef(null),[J,H]=i.useState(()=>typeof window>"u"?!1:er()),q=i.useMemo(()=>Na(),[]),ce=ym(),[fe,De]=i.useState(!1),Re=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),Fe=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32",[]),Oe=i.useMemo(()=>{if(typeof window>"u")return null;const re=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof re=="number"&&Number.isFinite(re)&&re>0)return re;if(typeof navigator>"u")return null;const nt=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!nt)return null;const ot=Number.parseInt(nt[1],10),St=Number.parseInt(nt[2],10);return Number.isNaN(ot)?null:ot===10?St:ot},[]);Qe.useEffect(()=>{typeof window>"u"||H(er())},[]);const Ee=k(),we=Ee&&typeof Ee.limit=="object"&&Ee.limit!==null?Ee.limit:null,Pe=we&&typeof we.context=="number"?we.context:0,Se=we&&typeof we.output=="number"?we.output:0,ue=I(Pe,Se),[K,he]=i.useState(null),se=!N||M;Qe.useEffect(()=>{if(!N){he(re=>re===null?re:null);return}if(ue&&ue.totalTokens>0){he(re=>vb(re,ue)?re:ue);return}se&&he(re=>re===null?re:null)},[ue,N,se]);const G=Me(re=>re.isSessionSwitcherOpen),$=ke?.connected?ke.user?.avatarUrl??null:null,pe=ke?.connected?ke.user?.login??null:null,ye=ke?.accounts??[],[z,Ne]=i.useState(!1),[U,Ie]=i.useState(!1),[_e,Ve]=i.useState(!1),[Le,X]=i.useState(!1),[L,xe]=i.useState("Local"),[Q,$e]=i.useState(!0),[He,Ke]=i.useState(!1),[qe,Xe]=i.useState(null),[lt,bt]=i.useState(!1),[Be,Je]=i.useState(null),Ze=i.useMemo(()=>jb(L),[L]),[pt,At]=i.useState(J?"instance":"usage"),[vt,at]=i.useState("usage");Qe.useEffect(()=>{!J&&pt==="instance"&&At("usage")},[pt,J]);const ct=i.useMemo(()=>Fr(),[]),Ot=!ct&&y==="chat"&&!!K&&K.totalTokens>0,Zt=K&&K.contextLimit>0?Math.min(999,K.totalTokens/K.contextLimit*100):0,Et=i.useCallback(async()=>{if(!(typeof window>"u"||!J))try{if(Gi()){xe("Local"),$e(!0);return}$e(!1);const re=await wm(),nt=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,ot=pr();if(ot&&fa(ot,nt)){xe("Local"),$e(!0);return}const St=re.hosts.find(Yt=>ot?fa(ot,vm(Yt)):!1);if(St?.label?.trim()){xe(jm(St.label.trim()));return}xe("Instance")}catch{xe("Local"),$e(!0)}},[J]);Qe.useEffect(()=>{Et()},[Et]);const ge=i.useCallback(async()=>{if(Q){Xe(null),Je(null);return}bt(!0),Je(null);try{const re=new URLSearchParams({appType:"web",instanceMode:"remote"}),nt=await gs(`/api/openchamber/update-check?${re.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!nt.ok)throw new Error(`Server responded with ${nt.status}`);const ot=await nt.json();Xe({available:ot.available??!1,version:ot.version,currentVersion:ot.currentVersion??"unknown",body:ot.body,nextSuggestedCheckInSec:typeof ot.nextSuggestedCheckInSec=="number"?ot.nextSuggestedCheckInSec:void 0,packageManager:ot.packageManager,updateCommand:ot.updateCommand})}catch(re){Xe(null),Je(re instanceof Error?re.message:o("header.services.remoteUpdate.error"))}finally{bt(!1)}},[Q,o]);i.useEffect(()=>{Xe(null),Je(null),Ke(!1)},[Q,L]),i.useEffect(()=>{if(!J||Q)return;const re=3e3,nt=3600*1e3;let ot=!1,St=null;const Yt=Ht=>{St=window.setTimeout(()=>{if(ot||typeof document<"u"&&document.visibilityState!=="visible"){Yt(nt);return}ge().finally(()=>{ot||Yt(nt)})},Ht)};return Yt(re),()=>{ot=!0,St!==null&&window.clearTimeout(St)}},[ge,Q,L,J]);const st=i.useCallback(()=>{if(qe?.available){Ke(!0);return}ge()},[ge,qe?.available]);ux();const wt=Zs(re=>re.selectedModels),tt=Zs(re=>re.expandedFamilies),ut=Zs(re=>re.toggleFamilyExpanded),Mt=i.useMemo(()=>{const re=[];for(const nt of Sm){if(!Y.includes(nt.id))continue;const ot=O.find(ps=>ps.providerId===nt.id),St=ot?.usage?.windows??{},Yt=ot?.usage?.models,Ht=Object.entries(St),is={providerId:nt.id,providerName:nt.name,entries:Ht,error:ot&&!ot.ok&&ot.configured?ot.error:void 0};if(Yt&&Object.keys(Yt).length>0){const ps=wt[nt.id]??[],cs=ps.length>0,Fs=mx(Yt,nt.id),hn=fx(nt.id),or=hx(hn);is.modelFamilies=[];for(const mn of or){const Hs=Fs.get(mn.id)??[];if(Hs.length===0)continue;const Sn=cs?Hs.filter(zn=>ps.includes(zn)):Hs;if(Sn.length===0)continue;const pn=[];for(const zn of Sn){const Tr=Yt[zn];if(Tr?.windows){const Jn=Object.entries(Tr.windows);Jn.length>0&&pn.push([zn,Jn[0][1]])}}pn.length>0&&is.modelFamilies.push({familyId:mn.id,familyLabel:mn.label,models:pn})}const Xs=Fs.get(null)??[],yr=cs?Xs.filter(mn=>ps.includes(mn)):Xs;if(yr.length>0){const mn=[];for(const Hs of yr){const Sn=Yt[Hs];if(Sn?.windows){const pn=Object.entries(Sn.windows);pn.length>0&&mn.push([Hs,pn[0][1]])}}mn.length>0&&is.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:mn})}}(Ht.length>0||is.modelFamilies&&is.modelFamilies.length>0||is.error)&&re.push(is)}return re},[Y,O,wt,o]),It=Mt.length>0;i.useEffect(()=>{te()},[te]);const zt=i.useCallback(async re=>{de(re);try{await ec({usageDisplayMode:re})}catch(nt){console.warn("Failed to update usage display mode:",nt)}},[de]),ss=i.useCallback(()=>{if(Le)return;X(!0);const re=new Promise(nt=>setTimeout(nt,500));Promise.all([F(),re]).finally(()=>{X(!1)})},[F,Le]),Bt=i.useMemo(()=>N?V.find(re=>re.id===N)??E.find(re=>re.id===N)??P??Nm().find(re=>re.id===N)??null:null,[N,P,E,V]),Ft=i.useRef(null),[Jt,es]=i.useState(0);i.useEffect(()=>{if(!N){Ft.current&&(Ft.current=null,es(St=>St+1));return}if(Bt){Ft.current={sessionId:N,session:Bt,expiresAt:Date.now()+2e3};return}const re=Ft.current;if(!re||re.sessionId!==N)return;const nt=re.expiresAt-Date.now();if(nt<=0){Ft.current=null,es(St=>St+1);return}const ot=window.setTimeout(()=>{Ft.current?.sessionId===N&&(Ft.current=null),es(St=>St+1)},nt);return()=>{window.clearTimeout(ot)}},[N,Bt]);const Lt=(()=>{if(Bt)return Bt;if(!N)return null;const re=Ft.current;return re&&re.sessionId===N&&re.expiresAt>Date.now()?re.session:null})(),Pt=mt(re=>N?re.worktreeMetadata.get(N)?.path??"":""),Kt=mt(re=>N?re.worktreeMetadata.get(N)?.branch?.trim()??null:null),yt=km(re=>N?re.getAttachment(N):void 0),$t=i.useMemo(()=>yt?np(yt,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,yt]),Dt=i.useMemo(()=>yt?yt.legacy?"legacy":yt.degraded?"degraded":yt.worktreeStatus==="pending"?"pending":yt.worktreeStatus==="missing"?"missing":yt.worktreeStatus==="invalid"?"invalid":yt.attentionReason?"attention":null:null,[yt]),fs=i.useMemo(()=>yn(Pt||""),[Pt]),ms=i.useMemo(()=>{const re=typeof Lt?.directory=="string"?Lt.directory:"";return yn(re||"")},[Lt?.directory]),xs=mt(re=>re.newSessionDraft?.open?yn(re.newSessionDraft.bootstrapPendingDirectory??re.newSessionDraft.directoryOverride??""):""),gt=i.useMemo(()=>fs||ms||xs,[xs,ms,fs]),qt=mt(re=>{const nt=yn(fs||ms||"");if(!nt)return null;for(const ot of re.availableWorktreesByProject.values()){const Yt=ot.find(Ht=>yn(Ht.path)===nt)?.branch?.trim();if(Yt)return Yt}return null}),os=rp(gt||null)||Kt||qt,Is=i.useMemo(()=>{if(!N)return B??"OpenChamber";const re=Lt?.title?.trim();return re&&re.length>0?re:"Untitled Session"},[B,Lt?.title,N]),As=i.useMemo(()=>yn(gt||R?.path||""),[R?.path,gt]),Xt=i.useMemo(()=>R?{id:R.id,path:R.path}:null,[R]),Rs=i.useRef(null);i.useEffect(()=>{!Xt||!As||(Rs.current={projectRef:Xt,directory:As})},[As,Xt]);const In=i.useMemo(()=>Xt&&As?{projectRef:Xt,directory:As}:Rs.current,[As,Xt]),Ds=oc(re=>re.planModeEnabled),Ys=mt(re=>re.isSessionPlanAvailable),Us=Ds&&N?Ys(N):!1,bs=Us,Yn=i.useRef("");i.useEffect(()=>{if(!Ds){Me.getState().activeMainTab==="plan"&&Me.getState().setActiveMainTab("chat");return}if(!N)return;const re=`${N||"none"}:${ms||"none"}:${Lt?.time?.created||0}:${Lt?.slug||"none"}`;Yn.current!==re&&(Yn.current=re),!Us&&Me.getState().activeMainTab==="plan"&&Me.getState().setActiveMainTab("chat")},[Ds,Us,Lt?.slug,Lt?.time?.created,N,ms]);const en=i.useCallback(async re=>{if(!(!re||z)){Ne(!0);try{const nt=w.github?await w.github.authActivate(re):await(async()=>{const ot=await gs("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:re})}),St=await ot.json().catch(()=>null);if(!ot.ok||!St)throw new Error(St?.error||ot.statusText);return St})();ae(nt)}catch(nt){console.error("Failed to switch GitHub account:",nt)}finally{Ne(!1)}}},[z,w.github,ae]),je=i.useCallback(()=>{if(typeof document>"u")return;const re=document.activeElement;if(!re)return;const nt=re.tagName;(nt==="INPUT"||nt==="TEXTAREA"||nt==="SELECT"||re.isContentEditable)&&re.blur()},[]),et=i.useCallback(()=>{if(be){je(),a(!G);return}c()},[je,be,G,a,c]),ft=i.useCallback(()=>{Er("desktop_open_draft_mini_chat_window",{directory:yn(gt||R?.path||""),projectId:R?.id??null,apiBaseUrl:pr(),clientToken:Il()}).catch(re=>{console.warn("[header] failed to open draft mini chat window",re)})},[R?.id,R?.path,gt]),Ae=i.useCallback(()=>{if(D){ft();return}N&&Er("desktop_open_session_mini_chat_window",{sessionId:N,directory:yn(gt||R?.path||""),apiBaseUrl:pr(),clientToken:Il()}).catch(re=>{console.warn("[header] failed to open session mini chat window",re)})},[R?.path,N,ft,D,gt]),xt=i.useCallback(()=>{const re=yn(gt||"");if(!re)return;const nt=x[re];if(Yr(nt)==="context"){h(re);return}f(re)},[h,x,f,gt]),rt=i.useMemo(()=>{const re=yn(gt||"");if(!re)return!1;const nt=x[re];return Yr(nt)==="context"},[x,gt]),_t=i.useCallback(()=>{const re=yn(gt||"");if(!re)return;const nt=x[re];if(Yr(nt)==="plan"){h(re);return}u(re)},[h,x,u,gt]),Vt=i.useCallback(()=>{const re=yn(gt||"");if(!re)return;const nt=x[re];if(Yr(nt)==="diff"){h(re);return}b(re,{mode:"diff",stagedDiff:!1})},[h,x,b,gt]),ns=i.useCallback(()=>{const re=yn(gt||"");if(!re)return;const nt=x[re];if(Yr(nt)==="browser"){h(re);return}g(re)},[h,x,g,gt]),rs=i.useMemo(()=>{const re=yn(gt||"");if(!re)return!1;const nt=x[re];return Yr(nt)==="plan"},[x,gt]),ts=i.useMemo(()=>{const re=yn(gt||"");if(!re)return!1;const nt=x[re];return Yr(nt)==="diff"},[x,gt]),cn=i.useMemo(()=>{const re=yn(gt||"");if(!re)return!1;const nt=x[re];return Yr(nt)==="browser"},[x,gt]),_s=Oa,tn=bb,Rn=i.useMemo(()=>U?"services":n?"sessions":r?"git":y,[y,U,n,r]),jn=i.useCallback(()=>{Ie(!1),n&&t&&t(),r&&e&&e(),!t&&G&&a(!1)},[G,n,t,e,r,a]),dn=i.useCallback(()=>{n||Ie(!1),t?.()},[n,t]),Es=i.useCallback(()=>{r||Ie(!1),e?.()},[e,r]),js=i.useMemo(()=>J&&Re&&!fe?"5.5rem":ce?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!J||Fe)&&!ct?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[J,fe,Re,ce,ct,Fe]);Qe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",js)},[js]);const Or=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",En=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";Qe.useEffect(()=>{if(!J||!Re){De(!1);return}let re=!1;const nt=async()=>{try{const St=await Er("desktop_is_window_fullscreen");re||De(St===!0)}catch{re||De(!1)}},ot=()=>{nt()};return nt(),window.addEventListener("openchamber:window-resized",ot),()=>{re=!0,window.removeEventListener("openchamber:window-resized",ot)}},[J,Re]);const sr=i.useMemo(()=>!J||!Re||Oe===null?"":Oe>=26?"h-12":Oe<=15?"h-14":"",[J,Re,Oe]),Br=i.useMemo(()=>{if(!(J&&!Fe||ct))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))"}},[J,ct,Fe]),Vn=i.useCallback(()=>{if(typeof document>"u")return;const re=ve.current?.getBoundingClientRect().height;re&&document.documentElement.style.setProperty("--oc-header-height",`${re}px`)},[]);Qe.useEffect(()=>{if(typeof window>"u")return;Vn();const re=ve.current;if(!re||typeof ResizeObserver>"u")return()=>{};let nt=0;const ot=()=>{nt||(nt=requestAnimationFrame(()=>{nt=0,Vn()}))},St=new ResizeObserver(ot);return St.observe(re),window.addEventListener("resize",ot),window.addEventListener("orientationchange",ot),()=>{nt&&cancelAnimationFrame(nt),St.disconnect(),window.removeEventListener("resize",ot),window.removeEventListener("orientationchange",ot)}},[Vn]),Qe.useEffect(()=>{Vn()},[Vn,be,sr]);const _r=i.useCallback(async re=>{const nt=re.target;nt.closest(".app-region-no-drag")||nt.closest("button, a, input, select, textarea")||re.button===0&&J&&await Bh()},[J]),Js=i.useMemo(()=>{if(be){const re=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return bs&&re.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),re.push({id:"diff",label:o("layout.mainTab.diff"),icon:"diff"},{id:"files",label:o("layout.mainTab.files"),icon:"folder-6"},{id:"terminal",label:o("layout.mainTab.terminal"),icon:"terminal-box"},{id:"context",label:o("layout.mainTab.context"),icon:"file-list-2"},{id:"diagram",label:o("layout.mainTab.diagram"),icon:"file"}),re}return[]},[be,bs,o]),nr=i.useCallback(re=>ka(ei(re,C)),[C]);Qe.useEffect(()=>{!be&&(y==="git"||y==="terminal"||y==="diff"||y==="files"||y==="context")&&p("chat")},[y,be,p]);const un=i.useMemo(()=>{const re=[];return J&&re.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(T,{name:"server",className:"h-3.5 w-3.5"})}),re.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(T,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(El,{className:"h-3.5 w-3.5"})}),re},[J,o]),as=i.useMemo(()=>un.map(re=>({id:re.value,label:re.label,icon:re.icon})),[un]),ws=i.useMemo(()=>{if(typeof window>"u"||J||ct)return!1;const re=window.location.hostname;return re==="localhost"||re==="127.0.0.1"||re==="::1"},[J,ct]),$n=i.useCallback(async()=>{if(A)return;S(!0),Ve(!1);const re=[];let nt=!1;try{try{for(const[,ot]of Ns.getState().sessions.entries())for(const St of ot.tabs)St.previewUrl&&re.push(St.previewUrl)}catch{}try{await _h({})}catch{}try{(await gs("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:re})})).ok?nt=!0:nt=(await gs("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{nt||S(!1)}},[A,Ve]),sn=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),Qs=i.useMemo(()=>sn.map(re=>({id:re.value,label:re.label})),[sn]),rr=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(T,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(El,{className:"h-3.5 w-3.5"})}],[o]);Qe.useEffect(()=>{const re=nt=>{if(ac(nt)&&!nt.shiftKey&&!nt.altKey){const ot=parseInt(nt.key,10);ot>=1&&ot<=Js.length&&(nt.preventDefault(),be&&(je(),jn()),p(Js[ot-1].id))}};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[je,jn,be,p,Js]),Qe.useEffect(()=>{const re=nt=>{const ot=ei("toggle_services_menu",C);if(Jo(nt,ot)){nt.preventDefault(),_e?Ve(!1):(Ve(!0),Et(),pt==="usage"&&O.length===0&&F());return}const St=ei("cycle_services_tab",C);if(Jo(nt,St)){nt.preventDefault();const Ht=un.map(Fs=>Fs.value);if(Ht.length===0)return;const is=Ht.indexOf(pt),ps=is===-1?0:(is+1)%Ht.length,cs=Ht[ps];At(cs),Ve(!0),Et(),cs==="usage"&&O.length===0&&F();return}const Yt=ei("toggle_context_plan",C);Jo(nt,Yt)&&(nt.preventDefault(),_t())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[C,_e,pt,un,O.length,F,Et,_t]);const xr=re=>{const nt=y===re.id,ot=re.icon==="diff",St=ot?null:re.icon,Yt=re.id==="chat",Ht=ps=>ot?s.jsx(Id,{size:ps}):St?s.jsx(T,{name:St,className:`h-${ps/4} w-${ps/4}`}):null,is=s.jsxs("button",{type:"button",onClick:()=>p(re.id),className:Te("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",nt?"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",Yt&&!be&&"min-w-[100px] justify-center"),"aria-label":re.label,"aria-selected":nt,role:"tab",children:[be?Ht(20):s.jsxs(s.Fragment,{children:[Ht(16),s.jsx("span",{className:"header-tab-label",children:re.label})]}),re.badge!==void 0&&re.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:re.badge})]});return s.jsx(i.Fragment,{children:is},re.id)},br=ct?null:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.toggleChangesPanelAria"),"aria-pressed":ts,onClick:Vt,className:_s,children:s.jsxs("span",{className:"relative h-5 w-5 overflow-hidden rounded-[2px]",children:[s.jsx("span",{className:"absolute left-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-success)]/25"}),s.jsx(T,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(Ct,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),Vr=s.jsxs(s.Fragment,{children:[bs&&s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:_t,className:Te(_s,rs&&"bg-[var(--interactive-hover)]"),children:s.jsx(T,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(Ct,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:nr("toggle_context_plan")})})})]}),s.jsx(Wx,{directory:As,className:"mr-1"}),s.jsx(wb,{isDesktopApp:J,currentInstanceLabel:L,compactCurrentInstanceLabel:Ze,currentInstanceIsLocal:Q,isDesktopServicesOpen:_e,setIsDesktopServicesOpen:Ve,refreshCurrentInstanceLabel:Et,desktopServicesTab:pt,setDesktopServicesTab:At,quotaResultsLength:O.length,fetchAllQuotas:F,servicesTabItems:as,quotaLastUpdated:ie,quotaDisplayMode:oe,showPredValues:ne,quotaDisplayTabItems:Qs,handleDisplayModeChange:zt,handleUsageRefresh:ss,isQuotaLoading:_,isUsageRefreshSpinning:Le,hasRateLimits:It,rateLimitGroups:Mt,expandedFamilies:tt,toggleFamilyExpanded:ut,shortcutLabel:nr,showDevShutdown:ws,isDevShutdownInFlight:A,onDevShutdown:$n,remoteUpdateInfo:qe,remoteUpdateChecking:lt,remoteUpdateError:Be,onOpenRemoteUpdate:st,timeFormatPreference:v}),s.jsx(Lo,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:nr("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),be?null:s.jsx(Lo,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:ns,pressed:cn,Icon:"global"}),s.jsx(Lo,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:nr("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:m,Icon:"layout-right"}),s.jsx(yb,{isMobile:be,githubAuthStatus:ke,githubAccounts:ye,githubAvatarUrl:$,githubLogin:pe,isSwitchingGitHubAccount:z,handleGitHubAccountSwitch:en})]}),Dr=q&&(D||!!N),$r=()=>s.jsxs("div",{onMouseDown:_r,className:Te("app-region-drag relative flex h-12 select-none items-center pr-3",sr),style:Br,role:"tablist","aria-label":o("header.navigation.mainAria"),children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:Or}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:En}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(Ex,{children:s.jsxs("button",{type:"button","aria-label":o("sessions.switcher.openAria"),className:"app-region-no-drag mr-3 flex min-w-0 flex-col items-start rounded-md px-1 py-0.5 -my-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:D?o("sessions.switcher.draftTitle"):Is}),B||os||!D&&Dt?s.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[B?s.jsx("span",{className:"truncate",children:B}):null,os?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(T,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:os})]}):null,!D&&Dt?s.jsxs("span",{className:Te("inline-flex min-w-0 items-center gap-0.5",Dt==="attention"||Dt==="invalid"||Dt==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(T,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:$t})]}):null]}):null]})}),Js.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Js.map(re=>xr(re))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ot&&K?s.jsx(Mx,{totalTokens:K.totalTokens,percentage:Zt,colorPercentage:K.percentage,contextLimit:K.contextLimit,outputLimit:K.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:xt,pressed:rt,className:Dr?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,br,s.jsx(Lo,{visible:Dr,title:o(D?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(D?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:Ae,className:Te(_s,"mr-1"),Icon:"picture-in-picture-2"}),Vr,s.jsx(Fx,{visible:Fe})]})]})]}),ir=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t?s.jsx("button",{type:"button",onClick:dn,className:Te(tn,Rn==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(T,{name:"layout-left",className:"h-5 w-5"})}):G?s.jsx("button",{type:"button",onClick:()=>a(!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":o("header.actions.backAria"),children:s.jsx(T,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:et,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":o("header.actions.openSessionsAria"),children:s.jsx(T,{name:"play-list-add",className:"h-5 w-5"})}),!t&&G&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!G||!!t)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:s.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain",children:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":o("header.navigation.mainAria"),children:Js.map(re=>{const nt=y===re.id,ot=re.icon==="diff",St=ot?null:re.icon;return s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{be&&(je(),jn()),p(re.id)},"aria-label":re.label,"aria-selected":nt,role:"tab",className:Te(tn,"relative rounded-lg",Rn===re.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ot?s.jsx(Id,{className:"h-5 w-5"}):St?s.jsx(T,{name:St,className:"h-5 w-5"}):null,re.badge!==void 0&&re.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:re.badge}),re.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":o("header.changes.availableAria")})]})}),s.jsx(Ct,{children:s.jsx("p",{children:re.label})})]},re.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[In&&s.jsx(nf,{projectRef:In.projectRef,directory:In.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(Ws,{open:U,onOpenChange:re=>{re&&(n&&t&&t(),r&&e&&e()),Ie(re),re&&O.length===0&&F()},children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:Te(tn,Rn==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(T,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(Ct,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(zs,{align:"end",sideOffset:0,positionerClassName:"!fixed !bottom-0 !left-0 !right-0 !top-[var(--oc-header-height,56px)] !transform-none",className:"h-full w-screen max-h-none rounded-none border-0 p-0 pt-1 overflow-hidden",children:s.jsxs("div",{className:"flex h-full flex-col bg-[var(--surface-elevated)]",children:[s.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)] px-2 py-px",children:s.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-0",children:[s.jsx("div",{className:"h-10 min-w-0 flex-1",children:s.jsx(ko,{items:rr,activeId:vt,onSelect:re=>{const nt=re;at(nt),nt==="usage"&&O.length===0&&F()},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})}),s.jsx("button",{type:"button",onClick:()=>Ie(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover","aria-label":o("header.services.closeAria"),children:s.jsx(T,{name:"close",className:"h-5 w-5"})})]})}),vt==="mcp"&&s.jsx(Km,{active:U&&vt==="mcp"}),vt==="usage"&&s.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden pb-[calc(4rem+env(safe-area-inset-bottom))]",children:[s.jsx("div",{className:"border-b border-[var(--interactive-border)]",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[s.jsxs("div",{className:"flex flex-col min-w-0 gap-0.5",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:o("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:rf(ie,v)})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"flex items-center h-6",children:[s.jsx("button",{type:"button",onClick:()=>zt("usage"),className:Te("typography-ui-label px-1 pb-0.5 transition-colors",oe==="usage"?"text-foreground border-b-2 border-[var(--primary-base)]":"text-muted-foreground hover:text-foreground"),children:o("header.services.used")}),s.jsx("span",{className:"text-muted-foreground typography-ui-label px-0.5",children:"·"}),s.jsx("button",{type:"button",onClick:()=>zt("remaining"),className:Te("typography-ui-label px-1 pb-0.5 transition-colors",oe==="remaining"?"text-foreground border-b-2 border-[var(--primary-base)]":"text-muted-foreground hover:text-foreground"),children:o("header.services.remaining")})]}),s.jsx("button",{type:"button",className:Te("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:ss,disabled:_||Le,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(T,{name:"refresh",className:Te("h-4 w-4",Le&&"animate-spin")})})]})]})}),!It&&s.jsx("div",{className:"px-4 py-6 text-center",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:o("header.services.noRateLimits")})}),s.jsx("div",{className:"py-1",children:Mt.map((re,nt)=>s.jsxs(i.Fragment,{children:[nt>0?s.jsx("div",{className:"mx-4 my-1 border-t border-[var(--interactive-border)]"}):null,s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2",children:[s.jsx(jo,{providerId:re.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:re.providerName})]}),re.entries.length===0&&(!re.modelFamilies||re.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:re.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[re.entries.map(([ot,St])=>{const Yt=oe==="remaining"?St.remainingPercent:St.usedPercent,Ht=ma(St.usedPercent,St.resetAt,St.windowSeconds,ot),is=Ht?.dailyAllocationPercent!=null?oe==="remaining"?100-Zr(Ht.elapsedRatio):Zr(Ht.elapsedRatio):null,ps=So(St.valueLabel,Yt),cs=xm(St.resetAt,St.resetAfterFormatted??St.resetAtFormatted,v);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:nc(ot)}),cs?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:cs}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:ps==="-"?"":ps})]}),s.jsx(xa,{percent:Yt,tonePercent:St.usedPercent,className:"h-1.5",expectedMarkerPercent:is}),Ht&&ne?s.jsx(ba,{paceInfo:Ht,compact:!0}):null]},`${re.providerId}-${ot}`)}),re.modelFamilies&&re.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:re.modelFamilies.map(ot=>{const Yt=(tt[re.providerId]??[]).includes(ot.familyId??"other");return s.jsxs(Yi,{open:Yt,onOpenChange:()=>ut(re.providerId,ot.familyId??"other"),children:[s.jsxs(Io,{className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:ot.familyLabel}),Yt?s.jsx(T,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(T,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(Ji,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:ot.models.map(([Ht,is])=>{const ps=oe==="remaining"?is.remainingPercent:is.usedPercent,cs=ma(is.usedPercent,is.resetAt,is.windowSeconds),Fs=cs?.dailyAllocationPercent!=null?oe==="remaining"?100-Zr(cs.elapsedRatio):Zr(cs.elapsedRatio):null,hn=So(is.valueLabel,ps);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Gm(Ht)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:hn==="-"?"":hn})]}),s.jsx(xa,{percent:ps,tonePercent:is.usedPercent,className:"h-1.5",expectedMarkerPercent:Fs}),cs&&ne?s.jsx(ba,{paceInfo:cs,compact:!0}):null]},`${re.providerId}-${Ht}`)})})})]},ot.familyId??"other")})})]})]},re.providerId))})]})]})})]}),e?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Es,className:Te(tn,"relative",Rn==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(T,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ct,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Mn=Te("header-safe-area relative z-10 bg-background",be&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:ve,className:Mn,style:{"--padding-scale":"1"},children:be?ir():$r()}),s.jsx(qm,{open:He,onOpenChange:Ke,info:qe,downloading:!1,downloaded:!1,progress:null,error:Be,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function Sb(){}const Ld=180,Od=640,Nb=110,kb=t=>{const e=ht.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=jt(),c=Me(Cb),l=Me(Ab),d=Me(Db),m=Me(Tb),[f,u]=i.useState(null),[g,b]=i.useState(!1),h=i.useRef(null),x=i.useRef(0),y=i.useRef(c||300),p=Math.min(Od,Math.max(Ld,c||300));let C,v;e[0]!==n?(C=()=>{n||(u(null),b(!1))},v=[n],e[0]=n,e[1]=C,e[2]=v):(C=e[1],v=e[2]),i.useEffect(C,v);let k,w;e[3]!==l||e[4]!==r||e[5]!==n?(k=()=>{if(r||!n||!l)return;const te=()=>{const ke=h.current?.parentElement?.getBoundingClientRect().height;if(!ke||ke<=0)return;const ae=Math.max(0,Math.round(ke));u(ve=>ve===ae?ve:ae)};te();const de=h.current?.parentElement;if(!de)return;const be=new ResizeObserver(te);return be.observe(de),()=>{be.disconnect()}},w=[l,r,n],e[3]=l,e[4]=r,e[5]=n,e[6]=k,e[7]=w):(k=e[6],w=e[7]),i.useEffect(k,w);let A,S;if(e[8]!==l||e[9]!==r||e[10]!==g||e[11]!==d||e[12]!==m?(A=()=>{if(r||!g||l)return;const te=be=>{const ke=x.current-be.clientY,ae=Math.min(Od,Math.max(Ld,y.current+ke));d(ae)},de=()=>{b(!1),Me.getState().bottomTerminalHeight<=Nb&&m(!1)};return window.addEventListener("pointermove",te),window.addEventListener("pointerup",de,{once:!0}),()=>{window.removeEventListener("pointermove",te),window.removeEventListener("pointerup",de)}},S=[l,r,g,d,m],e[8]=l,e[9]=r,e[10]=g,e[11]=d,e[12]=m,e[13]=A,e[14]=S):(A=e[13],S=e[14]),i.useEffect(A,S),r)return null;const I=n?l?Math.max(0,f??p):p:0,D=n&&l;let N;e[15]!==I||e[16]!==l||e[17]!==n?(N=te=>{!n||l||(b(!0),x.current=te.clientY,y.current=I,te.preventDefault())},e[15]=I,e[16]=l,e[17]=n,e[18]=N):N=e[18];const M=N,P=D?"absolute inset-x-0 bottom-0 z-40":"relative",E=g?"transition-none":"transition-[height] duration-300 ease-in-out",V=(!n||D)&&"border-t-0";let R;e[19]!==V||e[20]!==P||e[21]!==E?(R=Te("flex overflow-hidden border-t border-border bg-sidebar",P,E,V),e[19]=V,e[20]=P,e[21]=E,e[22]=R):R=e[22];let B;e[23]!==I||e[24]!==D?(B=D?{top:0}:{height:`${I}px`,minHeight:`${I}px`,maxHeight:`${I}px`},e[23]=I,e[24]=D,e[25]=B):B=e[25];const O=!n||!l&&I===0;let F;e[26]!==M||e[27]!==l||e[28]!==n||e[29]!==g||e[30]!==a?(F=n&&!l&&s.jsx("div",{className:Te("absolute left-0 top-0 z-20 h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",g&&"bg-[var(--interactive-border)]"),onPointerDown:M,role:"separator","aria-orientation":"horizontal","aria-label":a("terminalView.bottomDock.resizeAria")}),e[26]=M,e[27]=l,e[28]=n,e[29]=g,e[30]=a,e[31]=F):F=e[31];const _=!n&&"pointer-events-none select-none opacity-0";let ie;e[32]!==_?(ie=Te("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",_),e[32]=_,e[33]=ie):ie=e[33];const oe=!n;let ne;e[34]!==o||e[35]!==ie||e[36]!==oe?(ne=s.jsx("div",{className:ie,"aria-hidden":oe,children:o}),e[34]=o,e[35]=ie,e[36]=oe,e[37]=ne):ne=e[37];let Y;return e[38]!==R||e[39]!==B||e[40]!==O||e[41]!==F||e[42]!==ne?(Y=s.jsxs("section",{ref:h,className:R,style:B,"aria-hidden":O,children:[F,ne]}),e[38]=R,e[39]=B,e[40]=O,e[41]=F,e[42]=ne,e[43]=Y):Y=e[43],Y};function Cb(t){return t.bottomTerminalHeight}function Ab(t){return t.isBottomTerminalExpanded}function Db(t){return t.setBottomTerminalHeight}function Tb(t){return t.setBottomTerminalOpen}const Bd=280,_d=280,Vd=500,Pb=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=jt(),c=Me(S=>S.sidebarWidth),l=Me(S=>S.setSidebarWidth),[d,m]=i.useState(!1),f=i.useRef(0),u=i.useRef(c||Bd),g=i.useRef(null),b=i.useRef(null),h=i.useRef(null),x=i.useCallback(S=>Math.min(Vd,Math.max(_d,S)),[]),y=i.useCallback(S=>{const I=h.current;I&&(I.style.width=`${S}px`,I.style.minWidth=`${S}px`,I.style.maxWidth=`${S}px`,I.style.setProperty("--oc-left-sidebar-width",`${S}px`))},[]);if(i.useEffect(()=>{e&&d&&m(!1)},[e,d]),i.useEffect(()=>{d||(g.current=null,b.current=null)},[d]),e)return null;const p=Math.min(Vd,Math.max(_d,c||Bd)),C=t?p:0,v=S=>{if(t){try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}b.current=S.pointerId,m(!0),f.current=S.clientX,u.current=C,g.current=C,y(C),S.preventDefault()}},k=S=>{if(e||!d||b.current!==S.pointerId)return;const I=S.clientX-f.current,D=x(u.current+I);g.current!==D&&(g.current=D,y(D))},w=S=>{if(b.current!==S.pointerId||e)return;try{S.currentTarget.releasePointerCapture(S.pointerId)}catch{}const I=x(g.current??C);b.current=null,g.current=null,m(!1),l(I)},A=d?g.current??C:C;return s.jsxs("aside",{ref:h,className:Te("relative flex h-full overflow-hidden border-r border-border/40 will-change-[width] motion-reduce:transition-none","bg-sidebar oc-vibrancy-surface",!t&&"border-r-0",r),style:{width:`${A}px`,minWidth:`${A}px`,maxWidth:`${A}px`,"--oc-left-sidebar-width":`${d?A:p}px`,overflowX:"clip",transitionProperty:d?"none":"width, min-width, max-width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||C===0,children:[t&&s.jsx("div",{className:Te("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",d&&"bg-[var(--interactive-border)]"),onPointerDown:v,onPointerMove:k,onPointerUp:w,onPointerCancel:w,role:"separator","aria-orientation":"vertical","aria-label":a("sidebar.resize.leftPanelAria")}),s.jsxs("div",{className:Te("relative z-10 flex h-full shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",d&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[o,s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:s.jsx(Vs,{children:n})})]})]})},Ib=()=>{const t=ht.c(3);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e={height:"var(--oc-header-height, 3rem)"},t[0]=e):e=t[0];let n;t[1]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("div",{className:"app-region-drag shrink-0",style:{width:"var(--oc-titlebar-left-inset, 0.75rem)"}}),t[1]=n):n=t[1];let r;return t[2]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsxs("div",{"aria-hidden":!0,className:"flex shrink-0",style:e,children:[n,s.jsx("div",{className:"app-region-no-drag shrink-0",style:{width:"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)"}}),s.jsx("div",{className:"app-region-drag flex-1"})]}),t[2]=r):r=t[2],r},Oo=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function Rb(){const t=ds(u=>u.activeProjectId?u.projects.find(g=>g.id===u.activeProjectId)??null:null),e=mt(u=>u.currentSessionId),n=rc(e??null),r=mt(u=>e?u.worktreeMetadata.get(e)?.path??"":""),o=mt(u=>u.newSessionDraft?.open?Oo(u.newSessionDraft.bootstrapPendingDirectory??u.newSessionDraft.directoryOverride??""):""),a=i.useMemo(()=>Oo(r||""),[r]),c=i.useMemo(()=>{const u=typeof n?.directory=="string"?n.directory:"";return Oo(u||"")},[n?.directory]),l=a||c||o,d=i.useMemo(()=>Oo(l||t?.path||""),[t?.path,l]),m=i.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),f=i.useRef(null);return i.useEffect(()=>{m&&d&&(f.current={projectRef:m,directory:d})},[d,m]),i.useMemo(()=>m&&d?{projectRef:m,directory:d}:f.current,[m,d])}const $d="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",Eb=()=>{const t=ht.c(31),{t:e}=jt(),n=Me(Mb),r=Me(Fb),o=Me(Lb),a=Rb(),c=i.useRef(null),l=ka(ei("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const m=d,f=Bb;let u,g;t[0]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{if(typeof document>"u")return;const V=c.current;if(!V)return;const R=()=>{const O=V.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(O)}px`)};if(R(),typeof ResizeObserver>"u")return;const B=new ResizeObserver(R);return B.observe(V),()=>{B.disconnect()}},g=[],t[0]=u,t[1]=g):(u=t[0],g=t[1]),i.useEffect(u,g);const b="app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2";let h;t[2]===Symbol.for("react.memo_cache_sentinel")?(h={height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},t[2]=h):h=t[2];const x="flex items-center gap-2";let y;t[3]!==e?(y=m?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:f,"aria-label":e("header.actions.openAppMenuAria"),className:Te($d,"shrink-0"),children:s.jsx(T,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ct,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=y):y=t[4];const p=Nt;let C;t[5]!==e?(C=e("header.actions.openSessionsAria"),t[5]=e,t[6]=C):C=t[6];let v,k;t[7]===Symbol.for("react.memo_cache_sentinel")?(v=Te($d,"shrink-0"),k=s.jsx(T,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=v,t[8]=k):(v=t[7],k=t[8]);let w;t[9]!==C||t[10]!==n?(w=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":C,className:v,children:k})}),t[9]=C,t[10]=n,t[11]=w):w=t[11];const A=Ct,S=e("header.actions.openSessionsWithShortcut",{shortcut:l});let I;t[12]!==S?(I=s.jsx("p",{children:S}),t[12]=S,t[13]=I):I=t[13];let D;t[14]!==A||t[15]!==I?(D=s.jsx(A,{children:I}),t[14]=A,t[15]=I,t[16]=D):D=t[16];let N;t[17]!==p||t[18]!==w||t[19]!==D?(N=s.jsxs(p,{children:[w,D]}),t[17]=p,t[18]=w,t[19]=D,t[20]=N):N=t[20];let M;t[21]!==r||t[22]!==a?(M=a?s.jsx(nf,{projectRef:a.projectRef,directory:a.directory,className:r?"oc-vibrancy-pill":void 0}):null,t[21]=r,t[22]=a,t[23]=M):M=t[23];let P;t[24]!==N||t[25]!==M||t[26]!==y?(P=s.jsxs("div",{ref:c,className:x,children:[y,N,M]}),t[24]=N,t[25]=M,t[26]=y,t[27]=P):P=t[27];let E;return t[28]!==P||t[29]!==h?(E=s.jsx("div",{className:b,style:h,children:P}),t[28]=P,t[29]=h,t[30]=E):E=t[30],E};function Mb(t){return t.toggleSidebar}function Fb(t){return t.isSidebarOpen}function Lb(t){return t.shortcutOverrides}function Ob(t){console.warn("[titlebar] failed to open app menu",t)}function Bb(t){const e=t.currentTarget.getBoundingClientRect();Er("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(Ob)}const zd=420,_b=({isOpen:t,children:e,className:n})=>{const{t:r}=jt(),o=Me(w=>w.rightSidebarWidth),a=Me(w=>w.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),m=i.useRef(o||zd),f=i.useRef(null),u=i.useRef(null),g=i.useRef(null),b=i.useCallback(w=>Math.min(ed,Math.max(td,w)),[]),h=i.useCallback(w=>{const A=g.current;A&&(A.style.width=`${w}px`,A.style.minWidth=`${w}px`,A.style.maxWidth=`${w}px`,A.style.setProperty("--oc-right-sidebar-width",`${w}px`))},[]),x=Math.min(ed,Math.max(td,o||zd)),y=t?x:0,p=w=>{if(t){try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}u.current=w.pointerId,l(!0),d.current=w.clientX,m.current=y,f.current=y,h(y),w.preventDefault()}},C=w=>{if(!c||u.current!==w.pointerId)return;const A=d.current-w.clientX,S=b(m.current+A);f.current!==S&&(f.current=S,h(S))},v=w=>{if(u.current!==w.pointerId)return;try{w.currentTarget.releasePointerCapture(w.pointerId)}catch{}const A=b(f.current??y);u.current=null,f.current=null,l(!1),a(A)},k=c?f.current??y:y;return s.jsxs("aside",{ref:g,className:Te("relative flex h-full overflow-hidden border-l border-border/40 will-change-[width] motion-reduce:transition-none","bg-sidebar",!t&&"border-l-0",n),style:{width:`${k}px`,"--oc-right-sidebar-width":`${c?k:x}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||y===0,children:[t&&s.jsx("div",{className:Te("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",c&&"bg-[var(--interactive-border)]"),onPointerDown:p,onPointerMove:C,onPointerUp:v,onPointerCancel:v,role:"separator","aria-orientation":"vertical","aria-label":r("sidebar.resize.rightPanelAria")}),s.jsx("div",{className:Te("relative z-10 flex h-full min-h-0 shrink-0 flex-col pt-2 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",c&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-right-sidebar-width)"},"aria-hidden":!t,children:t?e:null})]})},Wd=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function of(t){const e=ht.c(120),{t:n}=jt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,onConfirm:d}=t,m=l===void 0?!1:l,f=Ut(Yb),u=Ut(qb),g=ip(Kb),b=Ut(Gb),h=Ut(Hb),x=Ut(Ub),y=Ut(Wb),p=Ut(zb);let C;e[0]!==p||e[1]!==x||e[2]!==h||e[3]!==y?(C=()=>Wd({providerID:h,modelID:x,variant:y,agent:p}),e[0]=p,e[1]=x,e[2]=h,e[3]=y,e[4]=C):C=e[4];const[v,k]=i.useState(C);let w,A;e[5]!==g||e[6]!==u||e[7]!==f||e[8]!==r||e[9]!==c?(w=()=>{r&&(f({directory:c,source:"todoSendDialog"}),u({directory:c}),g())},A=[r,f,u,g,c],e[5]=g,e[6]=u,e[7]=f,e[8]=r,e[9]=c,e[10]=w,e[11]=A):(w=e[10],A=e[11]),i.useEffect(w,A);let S,I;e[12]!==p||e[13]!==x||e[14]!==h||e[15]!==y||e[16]!==r?(S=()=>{r&&k(Wd({providerID:h,modelID:x,variant:y,agent:p}))},I=[r,h,x,y,p],e[12]=p,e[13]=x,e[14]=h,e[15]=y,e[16]=r,e[17]=S,e[18]=I):(S=e[17],I=e[18]),i.useEffect(S,I);let D,N;e[19]!==v.modelID||e[20]!==v.providerID||e[21]!==r||e[22]!==b?(D=()=>{if(!r||b.length===0)return;const _e=b.find(L=>L.id===v.providerID)??b[0],Ve=Array.isArray(_e?.models)?_e.models:[],Le=Ve.some(L=>L.id===v.modelID),X=Ve[0]?.id??"";_e?.id===v.providerID&&Le||k(L=>({...L,providerID:_e?.id??"",modelID:Le?L.modelID:X,variant:""}))},N=[r,b,v.providerID,v.modelID],e[19]=v.modelID,e[20]=v.providerID,e[21]=r,e[22]=b,e[23]=D,e[24]=N):(D=e[23],N=e[24]),i.useEffect(D,N);const M=$b;let P;if(e[25]!==v.modelID||e[26]!==v.providerID||e[27]!==b){let _e;e[29]!==v.providerID?(_e=Le=>Le.id===v.providerID,e[29]=v.providerID,e[30]=_e):_e=e[30],P=b.find(_e)?.models?.find(Le=>Le.id===v.modelID),e[25]=v.modelID,e[26]=v.providerID,e[27]=b,e[28]=P}else P=e[28];const E=P;let V;e[31]!==E?(V=E?.variants?Object.keys(E.variants):[],e[31]=E,e[32]=V):V=e[32];const R=V,B=R.length>0;let O,F;e[33]!==v.variant||e[34]!==B?(O=()=>{B||!v.variant||k(Vb)},F=[B,v.variant],e[33]=v.variant,e[34]=B,e[35]=O,e[36]=F):(O=e[35],F=e[36]),i.useEffect(O,F);let _;e[37]!==v.modelID||e[38]!==v.providerID?(_=v.providerID.trim().length>0&&v.modelID.trim().length>0,e[37]=v.modelID,e[38]=v.providerID,e[39]=_):_=e[39];const ie=_;let oe;e[40]!==ie||e[41]!==v||e[42]!==d||e[43]!==m?(oe=()=>{!ie||m||d(v)},e[40]=ie,e[41]=v,e[42]=d,e[43]=m,e[44]=oe):oe=e[44];const ne=oe;let Y,te;e[45]!==ne||e[46]!==r?(Y=()=>{if(!r)return;const _e=Ve=>{(Ve.metaKey||Ve.ctrlKey)&&Ve.key==="Enter"&&(Ve.preventDefault(),ne())};return window.addEventListener("keydown",_e),()=>window.removeEventListener("keydown",_e)},te=[r,ne],e[45]=ne,e[46]=r,e[47]=Y,e[48]=te):(Y=e[47],te=e[48]),i.useEffect(Y,te);let de;e[49]!==n||e[50]!==a?(de=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[49]=n,e[50]=a,e[51]=de):de=e[51];const be=de;let ke;e[52]!==o||e[53]!==m?(ke=_e=>{m||o(_e)},e[52]=o,e[53]=m,e[54]=ke):ke=e[54];let ae;e[55]!==be?(ae=s.jsx(Ms,{children:s.jsx(Ps,{children:be})}),e[55]=be,e[56]=ae):ae=e[56];let ve;e[57]!==n?(ve=n("chat.modelControls.model"),e[57]=n,e[58]=ve):ve=e[58];let J;e[59]!==ve?(J=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ve}),e[59]=ve,e[60]=J):J=e[60];let H;e[61]===Symbol.for("react.memo_cache_sentinel")?(H=(_e,Ve)=>{k(Le=>({...Le,providerID:_e,modelID:Ve,variant:""}))},e[61]=H):H=e[61];let q;e[62]!==v.modelID||e[63]!==v.providerID?(q=s.jsx(Cm,{providerId:v.providerID,modelId:v.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:H}),e[62]=v.modelID,e[63]=v.providerID,e[64]=q):q=e[64];let ce;e[65]!==J||e[66]!==q?(ce=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[J,q]}),e[65]=J,e[66]=q,e[67]=ce):ce=e[67];let fe;e[68]!==n?(fe=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[68]=n,e[69]=fe):fe=e[69];let De;e[70]!==fe?(De=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:fe}),e[70]=fe,e[71]=De):De=e[71];const Re=!B;let Fe;e[72]===Symbol.for("react.memo_cache_sentinel")?(Fe=_e=>k(Ve=>({...Ve,variant:_e})),e[72]=Fe):Fe=e[72];let Oe;e[73]!==v.variant||e[74]!==Re||e[75]!==R?(Oe=s.jsx(op,{value:v.variant,options:R,disabled:Re,onChange:Fe}),e[73]=v.variant,e[74]=Re,e[75]=R,e[76]=Oe):Oe=e[76];let Ee;e[77]!==De||e[78]!==Oe?(Ee=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[De,Oe]}),e[77]=De,e[78]=Oe,e[79]=Ee):Ee=e[79];let we;e[80]!==n?(we=n("sessions.scheduledTasks.editor.agent.label"),e[80]=n,e[81]=we):we=e[81];let Pe;e[82]!==we?(Pe=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:we}),e[82]=we,e[83]=Pe):Pe=e[83];let Se;e[84]===Symbol.for("react.memo_cache_sentinel")?(Se=_e=>k(Ve=>({...Ve,agent:_e})),e[84]=Se):Se=e[84];let ue;e[85]!==v.agent?(ue=s.jsx(Am,{agentName:v.agent,filter:M,dropdownPortalToBody:!0,onChange:Se}),e[85]=v.agent,e[86]=ue):ue=e[86];let K;e[87]!==Pe||e[88]!==ue?(K=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Pe,ue]}),e[87]=Pe,e[88]=ue,e[89]=K):K=e[89];let he;e[90]!==ce||e[91]!==Ee||e[92]!==K?(he=s.jsxs("div",{className:"flex flex-col gap-4",children:[ce,Ee,K]}),e[90]=ce,e[91]=Ee,e[92]=K,e[93]=he):he=e[93];let se;e[94]!==o?(se=()=>o(!1),e[94]=o,e[95]=se):se=e[95];let G;e[96]!==n?(G=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[96]=n,e[97]=G):G=e[97];let $;e[98]!==m||e[99]!==se||e[100]!==G?($=s.jsx(ze,{variant:"ghost",size:"sm",onClick:se,disabled:m,children:G}),e[98]=m,e[99]=se,e[100]=G,e[101]=$):$=e[101];const pe=!ie||m;let ye;e[102]!==m||e[103]!==n?(ye=n(m?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[102]=m,e[103]=n,e[104]=ye):ye=e[104];let z;e[105]!==ne||e[106]!==pe||e[107]!==ye?(z=s.jsx(ze,{size:"sm",onClick:ne,disabled:pe,children:ye}),e[105]=ne,e[106]=pe,e[107]=ye,e[108]=z):z=e[108];let Ne;e[109]!==$||e[110]!==z?(Ne=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[$,z]}),e[109]=$,e[110]=z,e[111]=Ne):Ne=e[111];let U;e[112]!==ae||e[113]!==he||e[114]!==Ne?(U=s.jsxs(ks,{className:"max-w-md overflow-visible",children:[ae,he,Ne]}),e[112]=ae,e[113]=he,e[114]=Ne,e[115]=U):U=e[115];let Ie;return e[116]!==r||e[117]!==ke||e[118]!==U?(Ie=s.jsx(Cs,{open:r,onOpenChange:ke,children:U}),e[116]=r,e[117]=ke,e[118]=U,e[119]=Ie):Ie=e[119],Ie}function Vb(t){return{...t,variant:""}}function $b(t){return Dm(t.mode)}function zb(t){return t.currentAgentName||""}function Wb(t){return t.currentVariant||""}function Ub(t){return t.currentModelId}function Hb(t){return t.currentProviderId}function Gb(t){return t.providers}function Kb(t){return t.loadAgents}function qb(t){return t.loadAgents}function Yb(t){return t.loadProviders}const Vl=5,af=15,Bo=new Map,Zo=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},Jb=(t,e)=>{const n=Zo(e);return Math.max(n*Vl,Math.min(n*af,n*t))},Qb=async(t,e)=>{const n=await dp(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},Xb=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Ud=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],Hd=(t,e)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},Zb=t=>{const e=ht.c(20),{id:n,children:r}=t;let o;e[0]!==n?(o={id:n},e[0]=n,e[1]=o):o=e[1];const{attributes:a,listeners:c,setNodeRef:l,setActivatorNodeRef:d,transform:m,transition:f,isDragging:u}=Xl(o);let g;e[2]!==m?(g=Zl.Transform.toString(m),e[2]=m,e[3]=g):g=e[3];let b;e[4]!==g||e[5]!==f?(b={transform:g,transition:f},e[4]=g,e[5]=f,e[6]=b):b=e[6];const h=u&&"opacity-60";let x;e[7]!==h?(x=Te(h),e[7]=h,e[8]=x):x=e[8];let y;e[9]!==a||e[10]!==r||e[11]!==u||e[12]!==c||e[13]!==d?(y=r({attributes:a,listeners:c,setActivatorNodeRef:d,isDragging:u}),e[9]=a,e[10]=r,e[11]=u,e[12]=c,e[13]=d,e[14]=y):y=e[14];let p;return e[15]!==l||e[16]!==b||e[17]!==x||e[18]!==y?(p=s.jsx("li",{ref:l,style:b,className:x,children:y}),e[15]=l,e[16]=b,e[17]=x,e[18]=y,e[19]=p):p=e[19],p},ey=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=jt(),[c,l]=i.useState(!1),[d,m]=i.useState(""),[f,u]=i.useState([]),[g,b]=i.useState(""),[h,x]=i.useState(null),[y,p]=i.useState(()=>new Set),[C,v]=i.useState([]),[k,w]=i.useState(null),[A,S]=i.useState(!1),[I,D]=i.useState(0),N=i.useRef(!1),M=i.useRef(""),P=i.useRef(null),E=Me(L=>L.todoPanelHeight),V=Me(L=>L.setTodoPanelHeight),R=Me(L=>L.notesPanelHeight),B=Me(L=>L.setNotesPanelHeight),[O,F]=i.useState(!1),_=i.useRef(0),ie=i.useRef(E),oe=mt(L=>L.currentSessionId),ne=mt(L=>L.createSession),Y=mt(L=>L.initializeNewOpenChamberSession),te=mt(L=>L.sendMessage),de=mt(L=>L.setCurrentSession),be=ri(L=>L.setPendingInputText),ke=Bs(L=>L.currentDirectory),ae=Me(L=>L.openContextPanelTab),ve=Me(L=>L.setActiveMainTab),J=Me(L=>L.setSessionSwitcherOpen),H=Me(L=>L.padding),q=i.useCallback(async(L,xe)=>{if(!t)return!1;const Q=t.id,He=(Bo.get(Q)??Promise.resolve()).catch(()=>{}).then(()=>ap(t,{notes:L,todos:xe}));Bo.set(Q,He);try{const Ke=await He;return Ke||me.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),Ke}finally{Bo.get(Q)===He&&Bo.delete(Q)}},[t,a]);i.useEffect(()=>{if(!t){m(""),u([]),v([]),b(""),p(new Set);return}let L=!1;return l(!0),(async()=>{try{const xe=await lp(t),Q=await Promise.all(xe.plans.map($e=>Qb($e,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(L)return;m(xe.notes),u(Ud(xe.todos)),v(Q),M.current=xe.notes,N.current=!0,b(""),p(new Set)}catch{L||(me.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),m(""),u([]),v([]),M.current="",N.current=!0)}finally{L||l(!1)}})(),()=>{L=!0}},[I,t,a]),i.useEffect(()=>{if(!t)return;const L=xe=>{const Q=xe.detail;Q?.projectId&&Q.projectId!==t.id||D($e=>$e+1)};return window.addEventListener("openchamber:project-plan-saved",L),window.addEventListener("openchamber:project-notes-updated",L),()=>{window.removeEventListener("openchamber:project-plan-saved",L),window.removeEventListener("openchamber:project-notes-updated",L)}},[t]),i.useEffect(()=>{if(f.length<7)return;const L=Jb(f.length,H),xe=Zo(H)*Vl;E!==L&&(E<xe||E>L)&&V(L)},[f.length,H,E,V]),i.useEffect(()=>{if(!O)return;const L=Q=>{const $e=Q.clientY-_.current,He=Math.min(Zo(H)*af,Math.max(Zo(H)*Vl,ie.current+$e));V(He)},xe=()=>{F(!1)};return window.addEventListener("pointermove",L),window.addEventListener("pointerup",xe,{once:!0}),window.addEventListener("pointercancel",xe,{once:!0}),()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",xe),window.removeEventListener("pointercancel",xe)}},[O,H,V]);const ce=i.useCallback(L=>{F(!0),_.current=L.clientY,ie.current=E,L.preventDefault()},[E]),fe=i.useCallback(()=>{P.current!==null&&(window.clearTimeout(P.current),P.current=null)},[]),De=i.useCallback(()=>{fe(),M.current=d,q(d,f)},[fe,d,q,f]);i.useEffect(()=>{if(!(!t||!N.current)&&d!==M.current)return P.current=window.setTimeout(()=>{P.current=null,M.current=d,q(d,f)},400),()=>{fe()}},[fe,d,q,t,f]),i.useEffect(()=>()=>fe(),[fe]);const Re=i.useCallback(()=>{const L=g.trim();if(!L)return;const xe=Hd(f,{id:Xb(),text:L.slice(0,Mo),completed:!1,createdAt:Date.now()});u(xe),b(""),q(d,xe)},[g,d,q,f]),Fe=i.useCallback(L=>{p(xe=>{const Q=new Set(xe);return Q.has(L)?Q.delete(L):Q.add(L),Q})},[]),Oe=i.useCallback((L,xe)=>{const Q=f.find(qe=>qe.id===L);if(!Q||Q.completed===xe)return;const $e=f.filter(qe=>qe.id!==L),He={...Q,completed:xe},Ke=xe?[...$e,He]:Hd($e,He);u(Ke),q(d,Ke)},[d,q,f]),Ee=i.useCallback(L=>{const xe=f.filter(Q=>Q.id!==L);u(xe),q(d,xe)},[d,q,f]),we=i.useCallback(()=>{const L=f.filter(xe=>!xe.completed);L.length!==f.length&&(u(L),q(d,L))},[d,q,f]),Pe=i.useCallback(L=>{const{active:xe,over:Q}=L;if(!Q||xe.id===Q.id)return;const $e=f.findIndex(qe=>qe.id===xe.id),He=f.findIndex(qe=>qe.id===Q.id);if($e===-1||He===-1)return;const Ke=Ud(um(f,$e,He));u(Ke),q(d,Ke)},[d,q,f]),Se=aa(mo(la,{activationConstraint:{distance:8}})),ue=g.slice(0,Mo),K=f.reduce((L,xe)=>L+(xe.completed?1:0),0),he=i.useCallback(()=>{ve("chat"),J(!1)},[ve,J]),se=i.useCallback((L,xe)=>{!t||h||w({kind:"session",todoId:L,todoText:xe})},[t,h]),G=i.useCallback(L=>{if(!oe){me.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}he();const xe=`\`\`\`md
4
- ${L}
5
- \`\`\``;be(xe,"append"),me.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[oe,r,he,be,a]),$=i.useCallback((L,xe)=>{if(!(!t||h)){if(!n){me.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}w({kind:"worktree",todoId:L,todoText:xe})}},[n,t,h,a]),pe=i.useCallback(async L=>{if(!t||!k)return;const xe=await vn("plan.todo.visible",{todo_text:k.todoText}),$e=[{synthetic:!0,text:await vn("plan.todo.instructions",{todo_text:k.todoText})}];S(!0),x(k.todoId);try{he();let He=null,Ke=t.path;if(k.kind==="worktree"){if(!n){me.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const Xe=await Tm(t.path,Pm());if(!Xe?.id)return;He=Xe.id,Ke=Xe.path}else{const Xe=await ne(void 0,t.path,null);if(!Xe?.id){me.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}He=Xe.id,Ke=Xe.directory??t.path,Y(Xe.id,Ut.getState().agents??[])}if(!He)return;const qe=lc.getState();qe.saveSessionModelSelection(He,L.providerID,L.modelID),L.agent.trim()&&(qe.saveSessionAgentSelection(He,L.agent),qe.saveAgentModelForSession(He,L.agent,L.providerID,L.modelID),qe.saveAgentModelVariantForSession(He,L.agent,L.providerID,L.modelID,L.variant||void 0)),de(He,Ke),await te(xe,L.providerID,L.modelID,L.agent.trim()||void 0,void 0,void 0,$e,L.variant||void 0),me.success(k.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),w(null),r?.()}catch(He){const Ke=He instanceof Error?He.message:void 0;me.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),Ke?{description:Ke}:void 0)}finally{S(!1),x(null)}},[n,ne,Y,r,k,t,he,te,de,a]),ye=i.useRef(null),[z,Ne]=i.useState(!1),[U,Ie]=i.useState(null),_e=i.useCallback(async L=>{if(!(!t||U)){Ie(L);try{if(!await cp(t,L)){me.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}v(Q=>Q.filter($e=>$e.id!==L)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{Ie(null)}}},[U,t,a]),Ve=i.useCallback(async()=>{if(!t||z)return;const L=await Vh({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(L.success&&L.path){Ne(!0);try{const xe=new URLSearchParams({path:L.path,allowOutsideWorkspace:"true"});L.outsideFileGrant&&xe.set("outsideFileGrant",L.outsideFileGrant);const Q=await gs(`/api/fs/read?${xe.toString()}`,{cache:"no-store"});if(!Q.ok){me.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const $e=await Q.text();if(!$e.trim()){me.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const He=L.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await ld(t,$e,He)){me.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),me.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(xe){const Q=xe instanceof Error?xe.message:void 0;me.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),Q?{description:Q}:void 0)}finally{Ne(!1)}}else L.error==="Native file picker not available"&&ye.current?.click()},[z,t,a]),Le=i.useCallback(async L=>{if(!(!t||!L)){Ne(!0);try{const xe=await L.text();if(!xe.trim()){me.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Q=L.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await ld(t,xe,Q)){me.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),me.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(xe){const Q=xe instanceof Error?xe.message:void 0;me.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),Q?{description:Q}:void 0)}finally{Ne(!1)}}},[t,a]),X=i.useCallback(L=>{const xe=t?.path?.trim(),Q=ke?.trim()||xe;Q&&ae(Q,{mode:"plan",targetPath:L.path,dedupeKey:L.path,label:L.title})},[ke,ae,t]);return t?s.jsxs("div",{className:Te("w-full min-w-0 space-y-3 p-3",o),children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:t.path,children:a("rightSidebar.contextNotesTodo.notes.title",{project:e?.trim()||t.path.split("/").filter(Boolean).pop()||t.path})}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[d.length,"/",cd]})]}),s.jsx(yi,{value:d,onChange:L=>m(L.target.value.slice(0,cd)),onBlur:De,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:R,onResizeHeightChange:B,useScrollShadow:!0,scrollShadowSize:56,disabled:c})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:a("rightSidebar.contextNotesTodo.todo.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:f.length===1?a("rightSidebar.contextNotesTodo.todo.itemsSingle",{count:f.length}):a("rightSidebar.contextNotesTodo.todo.itemsPlural",{count:f.length})}),s.jsx("button",{type:"button",onClick:we,disabled:c||K===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:a("rightSidebar.contextNotesTodo.todo.clearCompleted")})]}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue.length,"/",Mo]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(ln,{value:ue,onChange:L=>b(L.target.value.slice(0,Mo)),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),Re())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:Re,disabled:c||ue.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.addAria"),title:a("rightSidebar.contextNotesTodo.todo.addAria"),children:s.jsx(T,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:Te("overflow-y-auto rounded-lg border border-border/60 bg-background/40",O&&"transition-none"),style:f.length<7?void 0:{height:`${E}px`,maxHeight:`${E}px`},children:f.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.todo.empty")}):s.jsx(ca,{sensors:Se,collisionDetection:da,onDragEnd:Pe,children:s.jsx(Al,{items:f.map(L=>L.id),strategy:Dl,children:s.jsx("ul",{className:"divide-y divide-border/50",children:f.map(L=>{const xe=y.has(L.id);return s.jsx(Zb,{id:L.id,children:Q=>s.jsxs("div",{className:Te("flex gap-1.5 px-2.5 py-1.5",xe?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:Q.setActivatorNodeRef,...Q.attributes,...Q.listeners,onClick:$e=>{$e.preventDefault(),$e.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:L.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:L.text}),children:s.jsx(T,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(ki,{checked:L.completed,onChange:$e=>Oe(L.id,$e),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:L.text})})}),s.jsx("button",{type:"button",onClick:()=>Fe(L.id),className:Te("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",xe?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",L.completed&&"text-muted-foreground line-through"),title:xe?void 0:L.text,"aria-label":xe?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:L.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:L.text}),children:L.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Ee(L.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:L.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:L.text}),children:s.jsx(T,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(Ws,{children:[s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",disabled:h===L.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.send",{text:L.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:L.text}),children:s.jsx(T,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(zs,{align:"end",className:"w-56",children:[s.jsx(ls,{onClick:()=>G(L.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(ls,{onClick:()=>se(L.id,L.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(ls,{onClick:()=>{$(L.id,L.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},L.id)})})})})}),f.length>=7&&s.jsx("div",{className:Te("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",O&&"bg-[var(--interactive-border)]"),onPointerDown:ce,role:"separator","aria-orientation":"horizontal","aria-label":a("rightSidebar.contextNotesTodo.todo.resizeAria")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:a("rightSidebar.contextNotesTodo.plans.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:C.length===1?a("rightSidebar.contextNotesTodo.plans.filesSingle",{count:C.length}):a("rightSidebar.contextNotesTodo.plans.filesPlural",{count:C.length})})]}),s.jsx("input",{ref:ye,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:L=>{const xe=L.target.files?.[0]??null;Le(xe),L.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Ve,disabled:!t||z,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.plans.importFromFile"),title:a("rightSidebar.contextNotesTodo.plans.importFromFile"),children:s.jsx(T,{name:"add",className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:C.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.plans.empty")}):s.jsx("ul",{className:"divide-y divide-border/50",children:C.map(L=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>X(L),className:"flex min-w-0 flex-1 items-center justify-between gap-3 rounded-md px-1.5 py-1 text-left hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-foreground",children:L.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(L.createdAt).toLocaleDateString(Ki())})]}),s.jsx("button",{type:"button",onClick:()=>{_e(L.id)},disabled:U===L.id,className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",title:a("rightSidebar.contextNotesTodo.plans.deletePlan"),"aria-label":a("rightSidebar.contextNotesTodo.plans.deletePlanWithTitle",{title:L.title}),children:s.jsx(T,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},L.id))})})]}),s.jsx(of,{open:k!==null,onOpenChange:L=>{!L&&!A&&w(null)},target:k?.kind??"session",projectDirectory:t?.path??null,submitting:A,onConfirm:pe})]}):s.jsx("div",{className:Te("w-full min-w-0 p-3",o),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.empty.selectProject")})})},lf=12,ty=[{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"}],sy=t=>{const e=ht.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,m=a===void 0?900:a,f=c===void 0?ty:c,u=Qe.useRef(!1);let g,b;e[0]!==n||e[1]!==l?(g=()=>{!n&&u.current&&l?.(),n&&(u.current=!0)},b=[n,l],e[0]=n,e[1]=l,e[2]=g,e[3]=b):(g=e[2],b=e[3]),Qe.useEffect(g,b);let h;e[4]===Symbol.for("react.memo_cache_sentinel")?(h=Array.from({length:lf},ny),e[4]=h):h=e[4];const x=h;if(!n)return null;let y;e[5]!==o?(y=Te("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=y):y=e[6];let p;if(e[7]!==d||e[8]!==f||e[9]!==m){let v;e[11]!==d||e[12]!==m?(v=k=>{const w={"--burst-delay":`${k.delay}ms`,"--burst-x":`${k.x}%`,"--burst-y":`${k.y}%`,"--firework-color":`var(${k.colorVar})`,"--firework-duration":`${m}ms`};return s.jsx("div",{className:"firework-burst",style:w,children:x.map((A,S)=>{const I=A.x*k.radius,D=A.y*k.radius,N={"--translate-x":`${I}px`,"--translate-y":`${D}px`,"--particle-delay":`${A.delay}ms`,color:`var(${k.colorVar})`};return s.jsx("span",{className:"firework-particle",style:N},`${k.id}-${S}-${d}`)})},`${k.id}-${d}`)},e[11]=d,e[12]=m,e[13]=v):v=e[13],p=f.map(v),e[7]=d,e[8]=f,e[9]=m,e[10]=p}else p=e[10];let C;return e[14]!==d||e[15]!==y||e[16]!==p?(C=s.jsx("div",{className:y,"aria-hidden":"true","data-burst-key":d,children:p}),e[14]=d,e[15]=y,e[16]=p,e[17]=C):C=e[17],C};function ny(t,e){const n=Math.PI*2*e/lf;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const ry=t=>{const e=ht.c(13);let n;e[0]!==t?(n={},e[0]=t,e[1]=n):n=e[1];const{durationMs:r}=n,o=r===void 0?3400:r;let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a={isActive:!1,cycle:0},e[2]=a):a=e[2];const[c,l]=Qe.useState(a),d=Qe.useRef(null);let m;e[3]===Symbol.for("react.memo_cache_sentinel")?(m=()=>{d.current&&(window.clearTimeout(d.current),d.current=null)},e[3]=m):m=e[3];const f=m;let u;e[4]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{f(),l(iy)},e[4]=u):u=e[4];const g=u;let b;e[5]!==o?(b=()=>{f(),l(oy),d.current=window.setTimeout(()=>{l(ay),d.current=null},o)},e[5]=o,e[6]=b):b=e[6];const h=b;let x,y;e[7]===Symbol.for("react.memo_cache_sentinel")?(x=()=>()=>f(),y=[f],e[7]=x,e[8]=y):(x=e[7],y=e[8]),Qe.useEffect(x,y);let p;return e[9]!==c.cycle||e[10]!==c.isActive||e[11]!==h?(p={isActive:c.isActive,burstKey:c.cycle,triggerFireworks:h,dismissFireworks:g},e[9]=c.cycle,e[10]=c.isActive,e[11]=h,e[12]=p):p=e[12],p};function iy(t){return t.isActive?{...t,isActive:!1}:t}function oy(t){return{isActive:!0,cycle:t.cycle+1}}function ay(t){return t.isActive?{...t,isActive:!1}:t}const cf=i.createContext(void 0),ly=t=>{const e=ht.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=ry();let l;e[0]!==c||e[1]!==a?(l={triggerFireworks:a,dismissFireworks:c},e[0]=c,e[1]=a,e[2]=l):l=e[2];const d=l;let m;e[3]!==o||e[4]!==r?(m=s.jsx(sy,{isActive:r,burstKey:o}),e[3]=o,e[4]=r,e[5]=m):m=e[5];let f;return e[6]!==n||e[7]!==m||e[8]!==d?(f=s.jsxs(cf.Provider,{value:d,children:[n,m]}),e[6]=n,e[7]=m,e[8]=d,e[9]=f):f=e[9],f},cy=()=>{const t=i.useContext(cf);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},df="gitmojiCache",dy=1e3*60*60*24*7,uf="1",uy="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",mf=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},ol=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(df);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==uf||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(mf),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},my=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:uf};window.localStorage.setItem(df,JSON.stringify(e))}catch{return}},Gd=t=>Date.now()-t.fetchedAt<dy;let _o=null;const xo=new Set,Kd=async()=>{if(_o)return _o;const t=(async()=>{try{const e=await fetch(uy);if(!e.ok)throw new Error(`Failed to load gitmojis: ${e.statusText}`);const n=await e.json(),r=Array.isArray(n.gitmojis)?n.gitmojis.filter(mf):[];return my(r),xo.forEach(o=>o(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return xo.forEach(r=>r(n)),n}finally{_o=null}})();return _o=t,t},fy=t=>{const[e,n]=i.useState(()=>t?ol()?.gitmojis??[]:[]),[r,o]=i.useState(!1),a=i.useRef(t);a.current=t,i.useEffect(()=>{if(!t){xo.delete(n),n([]),o(!1);return}const l=ol();if(l&&(n(l.gitmojis),Gd(l)))return;xo.add(n),o(!0);let d=!1;return Kd().finally(()=>{!d&&a.current&&o(!1)}),()=>{d=!0,xo.delete(n)}},[t]);const c=i.useCallback(async()=>{if(!a.current)return[];if(e.length>0)return e;const l=ol();return l&&Gd(l)?l.gitmojis:Kd()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:c}},qd=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function hy(t,e,n){const r=ht.c(5),[o,a]=i.useState();let c,l;return r[0]!==n||r[1]!==t||r[2]!==e?(c=()=>{if(e){a(void 0);return}if(!t){a(void 0);return}a(void 0);let d=!1;return(async()=>{const[m,f]=await Promise.all([up(t),mp(t)]).catch(py);if(d)return;const u=qd(m),g=qd(f);if(!u||!g||g===u)return;const b=n||"",h=g.split("/").filter(Boolean).pop()||g;a({source:"sdk",path:g,projectDirectory:u,branch:b,label:b||h,name:h,worktreeRoot:g,worktreeStatus:"ready",headState:b?"branch":"unborn",worktreeSource:"existing"})})(),()=>{d=!0}},l=[t,e,n],r[0]=n,r[1]=t,r[2]=e,r[3]=c,r[4]=l):(c=r[3],l=r[4]),i.useEffect(c,l),e??o}function py(){return["",""]}const to=async(t,e)=>{const n=await gs(`/api/git/integrate/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>null);throw new Error(r?.error||`Git integrate request failed: ${n.statusText}`)}return n.json()};async function oo(t){return to("plan",t)}async function gy(t){return to("conflict-details",{tempWorktreePath:t})}async function xy(t){return(await to("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function by(t){return to("run",{plan:t})}async function yy(t){await to("abort",{state:t})}async function wy(t){return to("continue",{state:t})}const vy=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=jt(),d=mt(_=>_.currentSessionId),m=Me(_=>_.setActiveMainTab),[f,u]=Qe.useState(!1),g=Qe.useRef(null),[b,h]=Qe.useState(o);Qe.useEffect(()=>{h(o)},[o]),Qe.useEffect(()=>{if(f){const _=setTimeout(()=>{g.current?.focus()},0);return()=>clearTimeout(_)}},[f]);const x=!!(t&&e&&b&&b!=="HEAD"&&e!==b),[y,p]=Qe.useState({kind:"idle"}),[C,v]=Qe.useState(!1),[k,w]=Qe.useState([]),A=Qe.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);Qe.useEffect(()=>{if(!A||typeof window>"u")return;const _=window.localStorage.getItem(A);if(!_)return;let ie=!1;try{const oe=JSON.parse(_);if(!oe?.tempWorktreePath||oe.repoRoot!==t){window.localStorage.removeItem(A);return}(async()=>{const ne=await xy(oe.tempWorktreePath).catch(()=>!1);if(ie)return;if(!ne){window.localStorage.removeItem(A);return}const Y=await gy(oe.tempWorktreePath).catch(()=>null);ie||Y&&p({kind:"conflict",state:oe,details:Y})})()}catch{window.localStorage.removeItem(A)}return()=>{ie=!0}},[A,t]),Qe.useEffect(()=>{if(!x){p({kind:"idle"});return}let _=!1;return p({kind:"loading"}),(async()=>{try{const ie=await oo({repoRoot:t,sourceBranch:e,targetBranch:b});if(_)return;if(p({kind:"ready",plan:ie}),ie.commits.length>0){const ne=ie.commits.slice(-50).reverse(),Y=await fp(t,ne);_||(w(Y),v(!1))}else _||(w([]),v(!1))}catch{_||p({kind:"idle"})}})(),()=>{_=!0}},[x,t,e,b,a]);const S=Qe.useCallback(_=>{d&&mt.getState().setWorktreeMetadata(d,{...n,createdFromBranch:_})},[d,n]),I=mt(_=>_.openNewSessionDraft),D=Qe.useCallback(async _=>{const ie=await vn("git.integrate.cherrypick.resolve.visible",{current_commit:_.state.currentCommit,target_branch:_.state.targetBranch}),oe=await vn("git.integrate.cherrypick.resolve.instructions",{repo_root:_.state.repoRoot,temp_worktree_path:_.state.tempWorktreePath,source_branch:_.state.sourceBranch,target_branch:_.state.targetBranch,current_commit:_.state.currentCommit}),ne=`Cherry-pick conflict context (JSON)
6
- ${JSON.stringify({repoRoot:_.state.repoRoot,tempWorktreePath:_.state.tempWorktreePath,sourceBranch:_.state.sourceBranch,targetBranch:_.state.targetBranch,currentCommit:_.state.currentCommit,remainingCommits:_.state.remainingCommits,statusPorcelain:_.details.statusPorcelain,unmergedFiles:_.details.unmergedFiles,currentPatchMeta:_.details.currentPatchMeta,currentPatch:_.details.currentPatch,diff:_.details.diff},null,2)}`;return{visibleText:ie,instructionsText:oe,payloadText:ne}},[]),N=ri(_=>_.setPendingInputText),M=ri(_=>_.setPendingSyntheticParts),P=Qe.useCallback(async(_,ie)=>{const oe=await D(_);if(ie){I({directoryOverride:_.state.tempWorktreePath,initialPrompt:oe.visibleText,syntheticParts:[{text:oe.instructionsText,synthetic:!0},{text:oe.payloadText,synthetic:!0}]}),m("chat");return}if(!d){me.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}N(oe.visibleText,"replace"),M([{text:oe.instructionsText,synthetic:!0},{text:oe.payloadText,synthetic:!0}]),m("chat")},[d,m,D,I,N,M,l]),E=Qe.useCallback(async()=>{if(y.kind==="ready"){if(y.plan.commits.length===0){me.message(l("gitView.integrate.noCommitsToMoveToast"));return}p({kind:"running",plan:y.plan});try{const _=await by(y.plan);if(_.kind==="success"){me.success(l("gitView.integrate.commitsMovedToast"),{description:_.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:_.moved,branch:y.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:_.moved,branch:y.plan.targetBranch})});const ie=await oo(y.plan);p({kind:"ready",plan:ie}),c?.();return}_.kind==="conflict"&&(me.error(l("gitView.integrate.cherryPickConflictToast"),{description:l("gitView.integrate.cherryPickConflictDescription")}),p({kind:"conflict",state:_.state,details:_.details}),A&&typeof window<"u"&&window.localStorage.setItem(A,JSON.stringify(_.state)))}catch(_){const ie=_ instanceof Error?_.message:String(_);me.error(l("gitView.integrate.failedToMoveToast"),{description:ie});const oe=await oo({repoRoot:t,sourceBranch:e,targetBranch:b}).catch(()=>null);p(oe?{kind:"ready",plan:oe}:{kind:"idle"})}}},[y,c,t,e,b,A,l]),V=Qe.useCallback(async()=>{if(y.kind==="conflict")try{await yy(y.state),me.message(l("gitView.integrate.cherryPickAbortedToast")),A&&typeof window<"u"&&window.localStorage.removeItem(A)}finally{const _=await oo({repoRoot:t,sourceBranch:e,targetBranch:b}).catch(()=>null);p(_?{kind:"ready",plan:_}:{kind:"idle"})}},[y,t,e,b,A,l]),R=Qe.useCallback(async()=>{if(y.kind==="conflict")try{const _=await wy(y.state);if(_.kind==="success"){me.success(l("gitView.integrate.cherryPickFinishedToast"));const ie=await oo({repoRoot:t,sourceBranch:e,targetBranch:b}).catch(()=>null);p(ie?{kind:"ready",plan:ie}:{kind:"idle"}),A&&typeof window<"u"&&window.localStorage.removeItem(A),c?.();return}_.kind==="conflict"&&(p({kind:"conflict",state:_.state,details:_.details}),A&&typeof window<"u"&&window.localStorage.setItem(A,JSON.stringify(_.state)))}catch(_){const ie=_ instanceof Error?_.message:String(_);me.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:ie})}},[y,t,e,b,c,A,l]);return!t||!e?null:s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[s.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(T,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.integrate.title")}),y.kind==="ready"&&y.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:y.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:y.kind==="loading"||y.kind==="running"?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.integrate.moveCommits")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",b]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(Ws,{open:f,onOpenChange:u,children:[s.jsx($s,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"sm",className:"gap-1.5",children:[l("gitView.integrate.target"),s.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:b}),s.jsx(T,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(zs,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:s.jsxs(Ca,{className:"h-full min-h-0",children:[s.jsx(Aa,{ref:g,placeholder:l("gitView.branch.searchPlaceholder"),onKeyDown:_=>_.stopPropagation()}),s.jsxs(Da,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(Ta,{children:l("gitView.branch.empty")}),s.jsx(ti,{heading:l("gitView.branch.localBranches"),children:r.map(_=>s.jsx(ni,{value:_,onSelect:()=>{h(_),S(_),u(!1)},children:_},_))})]})]})})]}),y.kind==="ready"?s.jsx(ze,{size:"sm",onClick:()=>{E()},disabled:!x||y.plan.commits.length===0,children:l("gitView.integrate.move")}):y.kind==="loading"?s.jsx(ze,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):y.kind==="running"?s.jsx(ze,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),y.kind==="ready"&&y.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),y.kind==="ready"&&y.plan.commits.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"typography-meta text-foreground",children:[l("gitView.integrate.commitsToMove"),s.jsxs("span",{className:"text-muted-foreground",children:[" (",y.plan.commits.length,")"]})]}),k.length>0&&y.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>v(_=>!_),className:"typography-micro text-muted-foreground hover:text-foreground",children:l(C?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),s.jsxs("div",{className:"space-y-1",children:[(C?k:k.slice(0,5)).map(_=>s.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[s.jsx("span",{className:"font-mono text-xs text-muted-foreground flex-shrink-0",children:_.short}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:_.subject||_.sha})]},_.sha)),k.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.previewUnavailable")}),y.plan.commits.length>k.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:k.length})})]})]}),y.kind==="conflict"&&s.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[s.jsx("div",{className:"typography-meta text-foreground",children:l("gitView.integrate.conflictsInFiles",{count:y.details.unmergedFiles.length})}),s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[l("gitView.integrate.currentCommit"),": ",s.jsx("span",{className:"font-mono",children:y.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.details.unmergedFiles.slice(0,6).map(_=>s.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:_},_)),y.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:y.details.unmergedFiles.length-6})})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(ze,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{V()},children:l("gitView.operation.abort")}),s.jsxs(ze,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{P({state:y.state,details:y.details},!1)},children:[s.jsx(T,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs(ze,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{P({state:y.state,details:y.details},!0)},children:[s.jsx(T,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.newSession")]}),s.jsx(ze,{size:"sm",className:"typography-meta",onClick:()=>{R()},children:l("gitView.operation.continue")})]})]})]})]})},jy=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=jt(),[d,m]=i.useState([]),[f,u]=i.useState(!1),[g,b]=i.useState(""),[h,x]=i.useState(""),[y,p]=i.useState(null),[C,v]=i.useState({}),k=i.useCallback(async()=>{if(n){u(!0);try{const N=await hp(n);m(N.stashes),v({})}catch(N){me.error(N instanceof Error?N.message:l("gitView.stashes.toast.loadFailed"))}finally{u(!1)}}},[n,l]);i.useEffect(()=>{t&&k()},[k,t]),i.useEffect(()=>{if(!t||!n||d.length===0)return;let N=!1;const M=d.map(P=>P.ref);return pp(n,M).then(P=>{N||v(P.counts)}).catch(()=>{}),()=>{N=!0}},[n,t,d]);const w=i.useMemo(()=>{const N=g.trim().toLowerCase();return N?d.filter(M=>`${M.ref} ${M.message} ${M.relativeTime}`.toLowerCase().includes(N)):d},[g,d]),A=i.useCallback(async N=>{await k(),await c?.(N)},[k,c]),S=async()=>{if(!(!n||y)){p("create");try{const N=await gp(n,{message:h.trim()||void 0});N.created?(me.success(l("gitView.stashes.toast.created")),x("")):me.info(l("gitView.stashes.toast.noChanges")),await A({affectsIndex:!!(N.created&&o)})}catch(N){me.error(N instanceof Error?N.message:l("gitView.stashes.toast.createFailed"))}finally{p(null)}}},I=async(N,M)=>{if(!(!n||y)&&!(M==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:N.ref})))){p(`${M}:${N.ref}`);try{M==="apply"&&await xp(n,{ref:N.ref}),M==="pop"&&await bp(n,{ref:N.ref}),M==="drop"&&await yp(n,{ref:N.ref});const P=M==="apply"?"gitView.stashes.toast.applySuccess":M==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";me.success(l(P)),await A({affectsIndex:M!=="drop"})}catch(P){const E=M==="apply"?"gitView.stashes.toast.applyFailed":M==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";me.error(P instanceof Error?P.message:l(E)),await A({affectsIndex:M!=="drop"})}finally{p(null)}}},D=y!==null;return s.jsx(Cs,{open:t,onOpenChange:e,children:s.jsxs(ks,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(Ms,{children:[s.jsxs(Ps,{className:"flex items-center gap-2",children:[s.jsx(T,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(qs,{children:l("gitView.stashes.description")})]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[s.jsx(ln,{value:h,onChange:N=>x(N.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:D||!r,className:"flex-1"}),s.jsxs(ze,{onClick:S,disabled:!r||D||!n,children:[y==="create"?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"inbox-archive",className:"size-4"}),l("gitView.stashes.actions.stashCurrentWithCount",{count:a})]})]}),s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:l("gitView.stashes.includeUntrackedHint")})]}),s.jsxs("div",{className:"relative mt-2",children:[s.jsx(T,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(ln,{value:g,onChange:N=>b(N.target.value),placeholder:l("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto",children:f?s.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:s.jsx(T,{name:"loader-4",className:"size-5 animate-spin"})}):w.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:l(g?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):w.map((N,M)=>s.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[s.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[s.jsx("p",{className:"typography-small truncate text-foreground",children:N.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{children:M===0&&!g.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:M+1})})}),s.jsx(Ct,{sideOffset:6,children:N.ref})]})," · ",N.relativeTime," · ",typeof C[N.ref]=="number"?l("gitView.stashes.fileCount",{count:C[N.ref]}):l("gitView.stashes.fileCountLoading")]})]}),s.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[s.jsx(al,{label:l("gitView.stashes.actions.apply"),loading:y===`apply:${N.ref}`,onClick:()=>I(N,"apply"),disabled:D,children:s.jsx(T,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(al,{label:l("gitView.stashes.actions.pop"),loading:y===`pop:${N.ref}`,onClick:()=>I(N,"pop"),disabled:D,children:s.jsx(T,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(al,{label:l("gitView.stashes.actions.drop"),loading:y===`drop:${N.ref}`,onClick:()=>I(N,"drop"),disabled:D,destructive:!0,children:s.jsx(T,{name:"delete-bin",className:"size-4"})})]})]},N.ref))})]})})},al=t=>{const e=ht.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,m=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let f;e[0]!==m?(f=Te("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",m),e[0]=m,e[1]=f):f=e[1];let u;e[2]!==l||e[3]!==r?(u=r?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):l,e[2]=l,e[3]=r,e[4]=u):u=e[4];let g;e[5]!==o||e[6]!==n||e[7]!==c||e[8]!==d||e[9]!==f||e[10]!==u?(g=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:f,onClick:c,disabled:o,children:u})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=f,e[10]=u,e[11]=g):g=e[11];let b;e[12]!==n?(b=s.jsx(Ct,{sideOffset:6,children:n}),e[12]=n,e[13]=b):b=e[13];let h;return e[14]!==g||e[15]!==b?(h=s.jsxs(Nt,{children:[g,b]}),e[14]=g,e[15]=b,e[16]=h):h=e[16],h},Sy=t=>{const e=ht.c(16),{onOpenStashes:n}=t,{t:r}=jt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(T,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e[0]=o):o=e[0];let a;e[1]!==r?(a=r("gitView.empty.cleanTitle"),e[1]=r,e[2]=a):a=e[2];let c;e[3]!==a?(c=s.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:a}),e[3]=a,e[4]=c):c=e[4];let l;e[5]!==r?(l=r("gitView.empty.cleanDescription"),e[5]=r,e[6]=l):l=e[6];let d;e[7]!==l?(d=s.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:l}),e[7]=l,e[8]=d):d=e[8];let m;e[9]!==n||e[10]!==r?(m=n?s.jsxs(ze,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(T,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=m):m=e[11];let f;return e[12]!==c||e[13]!==d||e[14]!==m?(f=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,m]}),e[12]=c,e[13]=d,e[14]=m,e[15]=f):f=e[15],f},Jr=8,Ny=t=>{const e=ht.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,m=Math.max(r,a+1)*Jr+Jr/2,f=i.useRef(null),u=i.useRef(null);let g;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==m?(g=()=>{const p=f.current,C=u.current;if(!p||!C)return;const v=p.offsetHeight;if(v===0)return;const k=window.devicePixelRatio||1;C.width=m*k,C.height=v*k;const w=C.getContext("2d");if(!w)return;w.scale(k,k),w.clearRect(0,0,m,v);const A=v/2,S=a*Jr+Jr/2,I=getComputedStyle(C),D=I.getPropertyValue("--surface-muted-foreground").trim()||I.color,N=E=>{if(!E.startsWith("var("))return E;const V=E.slice(4,-1).trim();return I.getPropertyValue(V).trim()||D},M=[...l].sort(Cy);for(const E of M){const V=E.fromLane*Jr+Jr/2,R=E.toLane*Jr+Jr/2,B=E.type==="passing"?.72:E.type==="branch-out"||E.type==="merge-in"?.95:1;w.beginPath(),w.strokeStyle=N(E.color),w.globalAlpha=B,w.lineWidth=1.25,w.lineCap="round";e:switch(E.type){case"passing":case"commit-lane":{w.moveTo(V,0),w.lineTo(V,v);break e}case"top-stub":{w.moveTo(V,0),w.lineTo(V,A);break e}case"bottom-stub":{w.moveTo(V,A),w.lineTo(V,v);break e}case"branch-out":{const O=(A+v)/2;w.moveTo(S,A),w.bezierCurveTo(S,O,R,O,R,v);break e}case"merge-in":{const O=A/2;w.moveTo(V,0),w.bezierCurveTo(V,O,S,O,S,A);break e}default:continue}w.stroke(),w.globalAlpha=1}const P=I.getPropertyValue("--background").trim()||I.getPropertyValue("--surface-background").trim();w.beginPath(),w.arc(S,A,4,0,Math.PI*2),w.fillStyle=N(c),w.fill(),w.beginPath(),w.arc(S,A,5,0,Math.PI*2),w.strokeStyle=P||D,w.lineWidth=2,w.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=m,e[4]=g):g=e[4];let b;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==m?(b=[n,a,c,l,r,o,m],e[5]=c,e[6]=l,e[7]=o,e[8]=a,e[9]=n,e[10]=r,e[11]=m,e[12]=b):b=e[12],i.useLayoutEffect(g,b);let h;e[13]!==m?(h={width:m,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=m,e[14]=h):h=e[14];let x;e[15]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx("canvas",{ref:u,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=x):x=e[15];let y;return e[16]!==h?(y=s.jsx("div",{ref:f,style:h,children:x}),e[16]=h,e[17]=y):y=e[17],y};function ky(t){return t==="branch-out"||t==="merge-in"}function Cy(t,e){const n=ky;return(n(t.type)?1:0)-(n(e.type)?1:0)}const Yd=15e3,Jd=500,Qd=12,Xd=8*1024*1024,Zd=t=>typeof t=="string"?0:(t.original?.length??0)+(t.modified?.length??0),eu=t=>{if(t.size<=Qd){let o=0;for(const a of t.values())o+=Zd(a);if(o<=Xd)return t}const e=Array.from(t.entries()).reverse(),n=new Map;let r=0;for(const[o,a]of e){if(n.size>=Qd)continue;const c=Zd(a);r+c>Xd&&n.size>0||(n.set(o,a),r+=c)}return new Map(Array.from(n.entries()).reverse())};function tu(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:cc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ay(t){switch(t){case"A":return"text-[var(--status-success)]";case"D":return"text-[var(--status-error)]";case"M":return"text-[var(--status-warning)]";case"R":return"text-[var(--status-info)]";default:return"text-muted-foreground"}}function Dy(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{const n=e.startsWith("HEAD ->");return{label:n?e.replace("HEAD -> ",""):e.replace("tag: ",""),isHead:n,isTag:e.startsWith("tag: ")}}):[]}const Ty=i.memo(({entry:t,mode:e="history",laned:n,totalLanes:r,isExpanded:o,onToggle:a,files:c,isLoadingFiles:l,onCopyHash:d,directory:m,onConflict:f,onActionSuccess:u})=>{const{t:g}=jt(),b=Me(Y=>Y.timeFormatPreference),h=e==="graph",[x,y]=i.useState(null),[p,C]=i.useState(!1),[v,k]=i.useState(""),[w,A]=i.useState(null),[S,I]=i.useState(new Set),[D,N]=i.useState(new Map),[M,P]=i.useState(new Set),E=async()=>{if(m){y("checkout");try{await Ap(m,t.hash),me.success(g("gitView.history.actions.detachedHead")),u?.()}catch(Y){me.error(String(Y.message))}finally{y(null)}}},V=async()=>{if(!(!m||!v.trim())){y("createBranch");try{await vp(m,v.trim(),t.hash),C(!1),k(""),u?.()}catch(Y){me.error(String(Y.message))}finally{y(null)}}},R=async()=>{if(m){y("cherryPick");try{const Y=await Cp(m,t.hash);Y.conflict?f?.({conflict:!0,conflictFiles:Y.conflictFiles,operation:"cherry-pick"}):u?.()}catch(Y){me.error(String(Y.message))}finally{y(null)}}},B=async()=>{if(m){y("revert");try{const Y=await kp(m,t.hash);Y.conflict?f?.({conflict:!0,conflictFiles:Y.conflictFiles,operation:"revert"}):u?.()}catch(Y){me.error(String(Y.message))}finally{y(null)}}},O=async(Y,te=!1)=>{if(!(!m||x!==null)){y("reset");try{await jp(m,t.hash,Y,te),u?.()}catch(de){me.error(String(de.message))}finally{y(null)}}},F=async()=>{if(!w)return;const Y=w;switch(A(null),Y){case"checkout":return E();case"cherryPick":return R();case"revert":return B();case"merge":return _();case"rebase":return ie();case"resetSoft":return O("soft");case"resetMixed":return O("mixed");case"resetHard":return O("hard",!0)}},_=async()=>{if(m){y("merge");try{const Y=await Np(m,{branch:t.hash});Y.conflict?f?.({conflict:!0,conflictFiles:Y.conflictFiles,operation:"merge"}):u?.()}catch(Y){me.error(String(Y.message))}finally{y(null)}}},ie=async()=>{if(m){y("rebase");try{const Y=await Sp(m,{onto:t.hash});Y.conflict?f?.({conflict:!0,conflictFiles:Y.conflictFiles,operation:"rebase"}):u?.()}catch(Y){me.error(String(Y.message))}finally{y(null)}}},oe=i.useCallback(async Y=>{const te=Y.path;if(!m){N(de=>new Map(de).set(te,"error"));return}N(de=>eu(new Map(de).set(te,"loading")));try{const de=wp(m,t.hash,Y.path,!1),be=new Promise((ae,ve)=>{setTimeout(()=>ve(new Error(`Timed out after ${Yd}ms`)),Yd)}),ke=await Promise.race([de,be]);N(ae=>eu(new Map(ae).set(te,ke)))}catch{N(de=>new Map(de).set(te,"error"))}},[m,t.hash]),ne=i.useCallback(async Y=>{const te=Y.path;if(Y.changeType==="R"||Y.isBinary){I(ae=>{const ve=new Set(ae);return ve.has(te)?ve.delete(te):ve.add(te),ve});return}const de=D.get(te);if(S.has(te)&&de&&de!=="error"){I(ae=>{const ve=new Set(ae);return ve.delete(te),ve});return}I(ae=>{const ve=new Set(ae);return ve.add(te),ve}),!(de&&de!=="error"||Y.insertions+Y.deletions>Jd&&!M.has(te))&&await oe(Y)},[D,M,oe,S]);return s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:a,className:Te("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",h?"hover:bg-[var(--interactive-hover)]/40":o?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[h&&n&&r!==void 0?s.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:s.jsx(Ny,{laned:n,totalLanes:r,isExpanded:o})}):s.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),s.jsxs("div",{className:"min-w-0 flex-1",children:[h?(()=>{const Y=Dy(t.refs);return Y.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:Y.map(te=>s.jsx("span",{className:Te("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",te.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":te.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:te.label},te.label))}):null})():null,s.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:t.message}),s.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[s.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[s.jsx("span",{className:"truncate min-w-[3ch]",title:t.author_name,children:t.author_name}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("span",{className:"truncate min-w-0",title:tu(t.date,b),children:tu(t.date,b)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:Y=>{Y.stopPropagation(),d(t.hash)},children:s.jsx(T,{name:"file-copy",className:"size-3"})})}),s.jsx(Ct,{sideOffset:8,children:g("gitView.history.copySha")})]})]})]})]}),o&&s.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[h&&w?s.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:g(`gitView.history.actions.${w}Confirm`)}),s.jsxs(ze,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),F()},children:[x!==null?s.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.confirmButton")]}),s.jsx(ze,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),A(null)},children:g("gitView.history.actions.cancelButton")})]}):h?s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),A("checkout")},children:g("gitView.history.actions.checkout")}),p?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("input",{autoFocus:!0,value:v,onChange:Y=>k(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"&&V(),Y.key==="Escape"&&(C(!1),k(""))},placeholder:g("gitView.history.actions.createBranchPlaceholder"),className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),s.jsxs(ze,{variant:"outline",size:"xs",className:"h-6",disabled:!v.trim()||x!==null,onClick:Y=>{Y.stopPropagation(),V()},children:[x==="createBranch"?s.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.createBranchConfirm")]})]}):s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",onClick:Y=>{Y.stopPropagation(),C(!0)},children:g("gitView.history.actions.createBranch")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),A("cherryPick")},children:g("gitView.history.actions.cherryPick")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),A("revert")},children:g("gitView.history.actions.revert")}),s.jsxs(Ws,{children:[s.jsx($s,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:Y=>Y.stopPropagation(),children:[x==="reset"?s.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.reset")]})}),s.jsx(zs,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(Y=>s.jsx(ls,{disabled:x!==null,onSelect:te=>{te.stopPropagation(),A(`reset${Y.charAt(0).toUpperCase()+Y.slice(1)}`)},children:g(`gitView.history.actions.reset${Y.charAt(0).toUpperCase()+Y.slice(1)}`)},Y))})]}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),A("merge")},children:g("gitView.history.actions.merge")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:Y=>{Y.stopPropagation(),A("rebase")},children:g("gitView.history.actions.rebase")})]}):null,l?s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:g("gitView.history.loadingFiles")})]}):c.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:g("gitView.history.noFiles")}):s.jsx("ul",{className:"space-y-0.5 py-2",children:c.map(Y=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>ne(Y),className:Te("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",S.has(Y.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:Te("font-semibold w-3 text-center shrink-0",Ay(Y.changeType)),children:Y.changeType}),s.jsx("span",{className:"truncate text-foreground min-w-0",title:Y.path,children:Y.path}),!Y.isBinary&&s.jsxs("span",{className:"shrink-0",children:[s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",Y.insertions]}),s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",Y.deletions]})]}),Y.isBinary&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:g("gitView.history.binary")}),s.jsx(T,{name:S.has(Y.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),S.has(Y.path)&&s.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded border border-border/40 mx-2 mb-1","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:Y.changeType==="R"?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.renamedNoDiff")}):Y.isBinary?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.binaryNoDiff")}):(()=>{const te=Y.insertions+Y.deletions;if(!M.has(Y.path)&&te>Jd)return s.jsxs("div",{className:"flex flex-col items-start gap-1 px-3 py-2 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:g("gitView.history.largeDiffTitle",{count:te})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:g("gitView.history.largeDiffDescription")}),s.jsx(ze,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{P(be=>new Set(be).add(Y.path)),oe(Y)},children:g("gitView.history.renderDiffAnyway")})]});const de=D.get(Y.path);return de==="loading"||de===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.loadingDiff")}):de==="error"?s.jsx("button",{type:"button",onClick:()=>ne(Y),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:g("gitView.history.diffError")}):s.jsx(Ym,{original:de.original,modified:de.modified,language:vi(Y.path)||"",fileName:Y.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},Y.path))})]})]})}),su=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)","var(--syntax-keyword)","var(--syntax-string)","var(--status-info)"];function Vo(t){return su[t%su.length]}function Py(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let b=0;b<e.length;b++)e[b]===o.hash&&a.push(b);let c=a.length>0?a[0]:-1;if(c===-1){const b=e.indexOf(null);b!==-1?c=b:(c=e.length,e.push(null))}const l=a.slice(1),d=Vo(c),m=e[c]===o.hash,f=o.parents.length>0;f?e[c]=o.parents[0]:e[c]=null;const u=[];for(let b=1;b<o.parents.length;b++){const h=o.parents[b],x=e.indexOf(h);if(x!==-1)u.push(x);else{const y=e.indexOf(null),p=y!==-1?y:e.length;e[p]=h,p===e.length&&e.push(h),u.push(p)}}const g=[];m&&f?g.push({fromLane:c,toLane:c,color:d,type:"commit-lane"}):m&&!f?g.push({fromLane:c,toLane:c,color:d,type:"top-stub"}):!m&&f&&g.push({fromLane:c,toLane:c,color:d,type:"bottom-stub"});for(const b of l)g.push({fromLane:b,toLane:c,color:Vo(b),type:"merge-in"}),e[b]=null;for(const b of u)g.push({fromLane:c,toLane:b,color:Vo(b),type:"branch-out"});for(let b=0;b<e.length;b++)e[b]!==null&&b!==c&&(u.includes(b)||g.push({fromLane:b,toLane:b,color:Vo(b),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:g})}return n}const Iy=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],Ry=t=>{const e=ht.c(84),{mode:n,log:r,isLogLoading:o,logMaxCount:a,onLogMaxCountChange:c,expandedCommitHashes:l,onToggleCommit:d,commitFilesMap:m,loadingCommitHashes:f,onCopyHash:u,directory:g,showHeader:b,contentMaxHeightClassName:h,branchDivider:x,onConflict:y,onActionSuccess:p}=t,C=n===void 0?"history":n,v=b===void 0?!0:b,k=h===void 0?"max-h-[50vh]":h,w=x===void 0?null:x,{t:A}=jt(),[S,I]=i.useState(!0),D=C==="graph";let N;e[0]!==D||e[1]!==r?(N=D&&r?Py(r.all):[],e[0]=D,e[1]=r,e[2]=N):N=e[2];const M=N;let P;e[3]!==M?(P=Math.max(1,...M.map(Ey)),e[3]=M,e[4]=P):P=e[4];const E=P;let V;e[5]!==M?(V=new Map(M.map(My)),e[5]=M,e[6]=V):V=e[6];const R=V;if(!r)return null;const B=w!==null&&w.insertBeforeIndex>0&&w.insertBeforeIndex<r.all.length,O=w!==null&&w.insertBeforeIndex===r.all.length,F=B||O;let _;e[7]!==w||e[8]!==B||e[9]!==O||e[10]!==r.all?(_=B?r.all.slice(0,w.insertBeforeIndex):O?r.all:[],e[7]=w,e[8]=B,e[9]=O,e[10]=r.all,e[11]=_):_=e[11];const ie=_;let oe;if(e[12]!==w||e[13]!==m||e[14]!==k||e[15]!==g||e[16]!==l||e[17]!==B||e[18]!==F||e[19]!==D||e[20]!==o||e[21]!==R||e[22]!==f||e[23]!==r.all||e[24]!==a||e[25]!==E||e[26]!==C||e[27]!==p||e[28]!==y||e[29]!==u||e[30]!==c||e[31]!==d||e[32]!==A||e[33]!==ie){const H=B?r.all.slice(w.insertBeforeIndex):[];let q;e[35]!==w?.direction?(q=w?.direction==="down"?s.jsx(T,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(T,{name:"arrow-up",className:"size-3.5"}),e[35]=w?.direction,e[36]=q):q=e[36];const ce=q;let fe;e[37]!==m||e[38]!==g||e[39]!==l||e[40]!==D||e[41]!==R||e[42]!==f||e[43]!==E||e[44]!==C||e[45]!==p||e[46]!==y||e[47]!==u||e[48]!==d?(fe=Oe=>s.jsx("ul",{className:"divide-y divide-border/60",children:Oe.map(Ee=>s.jsx(Ty,{entry:Ee,mode:C,laned:D?R.get(Ee.hash):void 0,totalLanes:D?E:void 0,isExpanded:l.has(Ee.hash),onToggle:()=>d(Ee.hash),files:m.get(Ee.hash)??[],isLoadingFiles:f.has(Ee.hash),onCopyHash:u,directory:g,onConflict:y,onActionSuccess:p},Ee.hash))}),e[37]=m,e[38]=g,e[39]=l,e[40]=D,e[41]=R,e[42]=f,e[43]=E,e[44]=C,e[45]=p,e[46]=y,e[47]=u,e[48]=d,e[49]=fe):fe=e[49];const De=fe;let Re;e[50]!==o||e[51]!==r.all.length||e[52]!==a||e[53]!==c||e[54]!==A?(Re=r.all.length>=a?s.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:s.jsx(ze,{type:"button",variant:"ghost",size:"xs",onClick:()=>c(a+25),disabled:o,className:"px-3 text-muted-foreground hover:text-foreground",children:o?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(T,{name:"loader-4",className:"size-3 animate-spin"}),A("gitView.history.loadingMore")]}):A("gitView.history.loadMore")})}):null,e[50]=o,e[51]=r.all.length,e[52]=a,e[53]=c,e[54]=A,e[55]=Re):Re=e[55];const Fe=Re;oe=s.jsx(An,{outerClassName:`min-h-0 ${k}`,className:"h-full w-full",children:r.all.length===0?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:A("gitView.history.noCommits")})}):F&&w?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col gap-0",children:[ie.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:De(ie)}):null,s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5","aria-hidden":!0,children:[s.jsx("span",{className:"h-px flex-1 bg-border/60"}),s.jsxs("span",{className:"inline-flex max-w-[80%] items-center gap-1 typography-micro text-muted-foreground",children:[s.jsx("span",{className:"truncate",title:w.branchName,children:w.branchName}),ce]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),H.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:De(H)}):null]}),Fe]}):s.jsxs(s.Fragment,{children:[De(r.all),Fe]})}),e[12]=w,e[13]=m,e[14]=k,e[15]=g,e[16]=l,e[17]=B,e[18]=F,e[19]=D,e[20]=o,e[21]=R,e[22]=f,e[23]=r.all,e[24]=a,e[25]=E,e[26]=C,e[27]=p,e[28]=y,e[29]=u,e[30]=c,e[31]=d,e[32]=A,e[33]=ie,e[34]=oe}else oe=e[34];const ne=oe;if(!v){if(F){let q;return e[56]!==ne?(q=s.jsx("section",{className:"h-full min-h-0",children:ne}),e[56]=ne,e[57]=q):q=e[57],q}let H;return e[58]!==ne?(H=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:ne}),e[58]=ne,e[59]=H):H=e[59],H}let Y;e[60]!==A?(Y=A("gitView.history.title"),e[60]=A,e[61]=Y):Y=e[61];let te;e[62]!==Y?(te=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:Y}),e[62]=Y,e[63]=te):te=e[63];let de;e[64]!==o||e[65]!==S||e[66]!==a||e[67]!==c||e[68]!==A?(de=S&&s.jsx("div",{onClick:Fy,onPointerDown:Ly,children:s.jsxs(Dn,{value:String(a),onValueChange:H=>c(Number(H)),disabled:o,children:[s.jsx(Tn,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:o,children:s.jsx(fn,{placeholder:A("gitView.history.commitsPlaceholder")})}),s.jsx(Pn,{children:Iy.map(H=>s.jsx(vs,{value:String(H.value),children:A(H.labelKey)},H.value))})]})}),e[64]=o,e[65]=S,e[66]=a,e[67]=c,e[68]=A,e[69]=de):de=e[69];let be;e[70]!==S?(be=S?s.jsx(T,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(T,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=S,e[71]=be):be=e[71];let ke;e[72]!==de||e[73]!==be?(ke=s.jsxs("div",{className:"flex items-center gap-2",children:[de,be]}),e[72]=de,e[73]=be,e[74]=ke):ke=e[74];let ae;e[75]!==te||e[76]!==ke?(ae=s.jsxs(Io,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[te,ke]}),e[75]=te,e[76]=ke,e[77]=ae):ae=e[77];let ve;e[78]!==ne?(ve=s.jsx(Ji,{children:ne}),e[78]=ne,e[79]=ve):ve=e[79];let J;return e[80]!==S||e[81]!==ae||e[82]!==ve?(J=s.jsxs(Yi,{open:S,onOpenChange:I,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[ae,ve]}),e[80]=S,e[81]=ae,e[82]=ve,e[83]=J):J=e[83],J};function Ey(t){return t.lane+1}function My(t){return[t.commit.hash,t]}function Fy(t){return t.stopPropagation()}function Ly(t){return t.stopPropagation()}const ff=async(t,e,n)=>{if(t.length===0)return[];const r=Math.max(1,Math.min(e,t.length)),o=new Array(t.length);let a=0;const c=async()=>{for(;;){const l=a;if(a+=1,l>=t.length)return;o[l]=await n(t[l])}};return await Promise.all(Array.from({length:r},()=>c())),o},Oy=9e4,By=15e3,_y=5*6e4,Vy=[2e3,5e3],$y=6e4,zy=2*6e4,Wy=5*6e4,Uy=4,Hy=720*6e4,Gy="openchamber.github-pr-status",Ky=t=>t==="closed"||t==="merged",qy=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},bo=(t,e,n)=>`${t}::${e}`,$o=new Map,zo=new Map,ao=new Set,nu=new Map,uo=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null}),wa=t=>t?.params?.directory&&t.params.branch?{directory:t.params.directory,branch:t.params.branch,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null}:!t?.identity?.directory||!t.identity.branch?null:t.identity,Nc=t=>{const e=wa(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},hf=(t,e)=>Object.entries(t).filter(([,n])=>Nc(n)===e).map(([n])=>n),Yy=(t,e)=>{const n=e.remoteName??t.params?.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null;return{...t,params:t.params?{...t.params,...e,remoteName:n}:{...e,remoteName:n},identity:{directory:e.directory,branch:e.branch,remoteName:n}}},Wo=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},Jy=(t,e,n)=>{const r=hf(t,e),o=r.map(d=>Wo(t[d])).filter(d=>!!d);if(o.length===0)return null;const a=Wo(t[n]);if(a&&Nc(t[n])===e)return a;const c=r.map(d=>t[d]).find(d=>!!(d?.resolvedRemoteName&&Wo(d)));if(c)return Wo(c);const l=o.find(d=>!!d.remoteName);return l||(o[0]??null)},Qy=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:wa(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Xy=t=>({...uo(),status:t?.status??null,isInitialStatusResolved:t?.isInitialStatusResolved??!1,lastRefreshAt:t?.lastRefreshAt??0,lastDiscoveryPollAt:t?.lastDiscoveryPollAt??0,identity:t?.identity??null,resolvedRemoteName:t?.resolvedRemoteName??t?.status?.resolvedRemoteName??null}),Kn=Zi()(Ql((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,ensureEntry:n=>{t(r=>r.entries[n]?r:{entries:{...r.entries,[n]:uo()}})},setParams:(n,r)=>{t(o=>{const a=o.entries[n]??uo();return{entries:{...o.entries,[n]:Yy(a,r)}}})},startWatching:n=>{if(t(a=>{const c=a.entries[n]??uo();return{entries:{...a.entries,[n]:{...c,watchers:c.watchers+1}}}}),$o.has(n))return;const r=a=>{const c=window.setTimeout(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const d=e().entries[n];!d||d.watchers<=0||d.status?.pr||e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0})},a),l=zo.get(n)??[];l.push(c),zo.set(n,l)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),Vy.forEach(a=>r(a));const o=window.setInterval(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const a=e().entries[n];if(!a||a.watchers<=0)return;if(!!!a.status?.pr){const m=Date.now();if(m-a.lastDiscoveryPollAt<_y)return;t(f=>{const u=f.entries[n];return u?{entries:{...f.entries,[n]:{...u,lastDiscoveryPollAt:m}}}:f}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(Ky(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=qy(a.status)?$y:a.status?.checks&&a.status.checks.state!=="pending"?Wy:zy;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},By);$o.set(n,o)},stopWatching:n=>{t(c=>{const l=c.entries[n];if(!l)return c;const d=Math.max(0,l.watchers-1);return{entries:{...c.entries,[n]:{...l,watchers:d}}}});const r=e().entries[n];if(r&&r.watchers>0)return;const o=$o.get(n);typeof o=="number"&&window.clearInterval(o),$o.delete(n);const a=zo.get(n);a&&a.length>0&&a.forEach(c=>{window.clearTimeout(c)}),zo.delete(n)},refresh:async(n,r)=>{const o=e(),a=o.entries[n],c=Nc(a);if(!a||!c)return;const l=hf(o.entries,c),d=l.some(u=>!!o.entries[u]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const m=nu.get(c)??0;if(!r?.force&&Date.now()-m<Oy||ao.has(c))return;const f=Jy(o.entries,c,n);if(f){if(ao.add(c),nu.set(c,Date.now()),t(u=>{const g={...u.entries};return l.forEach(b=>{const h=g[b];h&&(g[b]={...h,lastRefreshAt:Date.now(),isLoading:r?.silent?h.isLoading:!0,error:null})}),{entries:g}}),f.githubAuthChecked&&f.githubConnected===!1){t(u=>{const g={...u.entries};return l.forEach(b=>{const h=g[b];h&&(g[b]={...h,status:{connected:!1},error:null,isLoading:r?.silent?h.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?h.isInitialStatusResolved:!0})}),{entries:g}}),ao.delete(c);return}if(!f.github?.prStatus){t(u=>{const g={...u.entries};return l.forEach(b=>{const h=g[b];h&&(g[b]={...h,status:null,error:"GitHub runtime API unavailable",isLoading:r?.silent?h.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?h.isInitialStatusResolved:!0})}),{entries:g}}),ao.delete(c);return}try{t(g=>({...g,activeRequestCount:g.activeRequestCount+1,totalRequestCount:g.totalRequestCount+1}));const u=await f.github.prStatus(f.directory,f.branch,f.remoteName??void 0,{force:r?.force});t(g=>{const b={...g.entries};return l.forEach(h=>{const x=b[h];if(!x)return;const y=x.status?.pr,p=u.pr,v=!!(p&&y&&p.number===y.number&&(!p.body||!p.body.trim())&&typeof y.body=="string"&&y.body.trim().length>0)&&p&&y?.body?{...u,pr:{...p,body:y.body}}:u,k=v.resolvedRemoteName??x.resolvedRemoteName??f.remoteName??null,w=wa(x)??{directory:f.directory,branch:f.branch,remoteName:f.remoteName??null};b[h]={...x,status:v,error:null,isLoading:r?.silent?x.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?x.isInitialStatusResolved:!0,resolvedRemoteName:k,identity:{...w,remoteName:k??w.remoteName??null}}}),{entries:b}})}catch(u){const g=u instanceof Error?u.message:String(u);t(b=>{const h={...b.entries};return l.forEach(x=>{const y=h[x];y&&(h[x]={...y,error:g||"Failed to load PR status",isLoading:r?.silent?y.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?y.isInitialStatusResolved:!0})}),{entries:h}})}finally{ao.delete(c),t(u=>({...u,activeRequestCount:Math.max(0,u.activeRequestCount-1)}))}}},refreshTargets:async(n,r)=>{const o=Array.from(new Set(n.map(a=>{const c=a.directory.trim(),l=a.branch.trim();return!c||!l?null:bo(c,l,a.remoteName??null)}).filter(a=>!!a)));await ff(o,Uy,a=>e().refresh(a,r))},updateStatus:(n,r)=>{t(o=>{const a=o.entries[n]??uo();return{entries:{...o.entries,[n]:{...a,status:r(a.status)}}}})}}),{name:Gy,storage:dm(()=>bi()),partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=wa(e);if(!n?.directory||!n.branch)return!1;const r=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return r===0||Date.now()-r<Hy}).map(([e,n])=>[e,Qy(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).map(([o,a])=>[o,Xy(a)]))}}})),Zy=t=>{const e=t?.pr;if(!e)return null;if(e.state==="merged")return"merged";if(e.state==="closed")return"closed";if(e.draft)return"draft";const n=t?.checks?.state==="failure",r=typeof e.mergeableState=="string"?e.mergeableState:"",o=e.mergeable===!1||r==="blocked"||r==="dirty";return n||o?"blocked":"open"},ew=t=>{const e=Zy(t.status??null),n=t.status?.pr;return!e||!n?.number?null:{number:n.number,visualState:e,prState:n.state,draft:!!n.draft,title:typeof n.title=="string"&&n.title.trim().length>0?n.title:null,url:typeof n.url=="string"&&n.url.trim().length>0?n.url:null,base:typeof n.base=="string"&&n.base.trim().length>0?n.base:null,head:typeof n.head=="string"&&n.head.trim().length>0?n.head:null,checks:t.status?.checks?{state:t.status.checks.state,total:t.status.checks.total,success:t.status.checks.success,failure:t.status.checks.failure,pending:t.status.checks.pending}:null,canMerge:typeof t.status?.canMerge=="boolean"?t.status.canMerge:null,mergeableState:typeof n.mergeableState=="string"?n.mergeableState:null,repo:t.status?.repo?{owner:t.status.repo.owner,repo:t.status.repo.repo}:null}},tw=t=>`${t.number}:${t.visualState}:${t.prState}:${t.draft}:${t.title??""}:${t.url??""}:${t.base??""}:${t.head??""}:${t.canMerge??""}:${t.mergeableState??""}:${t.checks?.state??""}:${t.checks?.total??""}:${t.checks?.success??""}:${t.checks?.failure??""}:${t.checks?.pending??""}:${t.repo?.owner??""}:${t.repo?.repo??""}`;let ll=new Map,ru=new Map;const sw=t=>{const e=ht.c(2);let n;return e[0]!==t?(n=r=>{const o=new Map,a=new Map;for(const c of t){const l=r.entries[c];if(!l)continue;const d=ew(l);if(!d)continue;const m=tw(d);o.set(c,m),a.set(c,d)}if(o.size===ll.size){let c=!0;for(const[l,d]of o)if(ll.get(l)!==d){c=!1;break}if(c)return ru}return ll=o,ru=a,a},e[0]=t,e[1]=n):n=e[1],Kn(n)},nw=t=>{switch(t){case"success":return"bg-[color:var(--status-success)]";case"failure":return"bg-[color:var(--status-error)]";case"pending":return"bg-[color:var(--status-warning)]";default:return"bg-muted-foreground/40"}},rw=t=>{const e=t?.pr;if(!e)return null;if(e.state==="merged")return"merged";if(e.state==="closed")return"closed";if(e.draft)return"draft";const n=t?.checks?.state==="failure",r=typeof e.mergeableState=="string"?e.mergeableState:"",o=e.mergeable===!1||r==="blocked"||r==="dirty";return n||o?"blocked":"open"},iw=[2e3,5e3],iu=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),Qr=t=>{let e=t.trim();return e?(e.startsWith("refs/heads/")&&(e=e.slice(11)),e.startsWith("heads/")&&(e=e.slice(6)),e.startsWith("remotes/")&&(e=e.slice(8)),e):""},ow=(t,e)=>{const n=Qr(t);if(!n||n.includes("->"))return"";if(e){const o=`${e}/`;return n.startsWith(o)?n.slice(o.length).trim():""}const r=n.indexOf("/");return r>0?n.slice(r+1).trim():n},aw=(t,e)=>`${t}::${e}`,kc=t=>{const e=String(t||"").trim();if(!e)return"";const n=e.indexOf("/");return n<=0?"":e.slice(0,n).trim()},cl=(t,e)=>{if(t.length===0)return null;const n=String(e.selectedRemoteName||"").trim();if(n){const a=t.find(c=>c.name===n);if(a)return a}const r=kc(e.trackingBranch);if(r){const a=r==="origin"?t.find(l=>l.name==="upstream"):null;if(a)return a;const c=t.find(l=>l.name===r);if(c)return c}const o=t.find(a=>a.name==="origin");return o||(t[0]??null)},lw=t=>t.startsWith("pr-"),cw=(t,e)=>{const n=kc(e),r=new Map(t.map(c=>[c.name,c])),o=[],a=c=>{c&&(o.some(l=>l.name===c.name)||o.push(c))};return n&&a(r.get(n)),a(r.get("upstream")),a(r.get("origin")),t.filter(c=>!lw(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},dl=new Map,ul=Si;function dw(t,e){const[n,r]=i.useState(null),[o,a]=i.useState([]),c=i.useRef(null);return i.useEffect(()=>{r(null),a([])},[t]),i.useEffect(()=>{if(!t||!e?.repoUpstream||c.current===t)return;c.current=t;let l=!1;return(async()=>{try{const d=await e.repoUpstream(t);if(l||!d?.isFork||!d.upstream||(r(d.upstream),!e.repoBranches))return;try{const m=await e.repoBranches(d.upstream.owner,d.upstream.repo);l||a(m)}catch{}}catch{}})(),()=>{l=!0}},[t,e]),{detectedUpstream:n,upstreamBranches:o}}const uw=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=jt(),d=Me(je=>je.timeFormatPreference),{github:m}=_n(),f=Ni(je=>je.status),u=Ni(je=>je.hasChecked),g=Me(je=>je.setSettingsDialogOpen),b=Me(je=>je.setSettingsPage),h=Me(je=>je.setActiveMainTab),x=mt(je=>je.currentSessionId),{isMobile:y,hasTouchInput:p}=Ar(),C=i.useCallback(()=>{b("github"),g(!0)},[g,b]),v=i.useMemo(()=>aw(t,e),[t,e]),k=i.useMemo(()=>dl.get(v)??null,[v]),w=Kn(je=>je.ensureEntry),A=Kn(je=>je.setParams),S=Kn(je=>je.startWatching),I=Kn(je=>je.stopWatching),D=Kn(je=>je.refresh),N=Kn(je=>je.updateStatus),[M,P]=i.useState(()=>k?.title??iu(e)),[E,V]=i.useState(()=>k?.body??""),[R,B]=i.useState(()=>k?.draft??!1),[O,F]=i.useState(()=>k?.additionalContext??""),[_,ie]=i.useState(()=>{const je=typeof k?.targetBaseBranch=="string"?Qr(k.targetBaseBranch):"";return je||Qr(n)}),[oe,ne]=i.useState("squash"),[Y,te]=i.useState(!1),[de,be]=i.useState(!1),[ke,ae]=i.useState(!1),[ve,J]=i.useState(!1),[H,q]=i.useState(!1),[ce,fe]=i.useState(!1),[De,Re]=i.useState(null),[Fe,Oe]=i.useState(""),[Ee,we]=i.useState(""),[Pe,Se]=i.useState(!1),[ue,K]=i.useState(!1),[he,se]=i.useState(()=>cl(o,{selectedRemoteName:k?.selectedRemoteName,trackingBranch:r})),[G,$]=i.useState(!1),{detectedUpstream:pe,upstreamBranches:ye}=dw(t,m);i.useEffect(()=>{$(!1)},[t]);const z=o.some(je=>je.name==="upstream"),U=!!(t&&e&&n&&(e!==n||(z||pe!==null))),Ie=i.useMemo(()=>bo(t,e),[t,e]),_e=Kn(je=>je.entries[Ie]),Ve=_e?.isLoading??!1,Le=_e?.status??null,X=_e?.error??null,L=_e?.isInitialStatusResolved??!1,xe=i.useMemo(()=>{const je=G?null:he?.name?.trim()||null,et=new Set;for(const xt of a){const rt=ow(xt,je);!rt||rt==="HEAD"||et.add(rt)}if(G)for(const xt of ye)xt&&xt!=="HEAD"&&et.add(xt);const ft=Qr(n);ft&&ft!=="HEAD"&&et.add(ft);const Ae=Qr(_);return Ae&&Ae!=="HEAD"&&et.add(Ae),Array.from(et).sort((xt,rt)=>xt.localeCompare(rt))},[n,a,he?.name,_,ye,G]);i.useEffect(()=>{if(o.length===0){he&&se(null);return}(!he||!o.some(je=>je.name===he.name))&&se(cl(o,{selectedRemoteName:k?.selectedRemoteName,trackingBranch:r}))},[k?.selectedRemoteName,o,he,r]),i.useEffect(()=>{const je=Qr(n);if(!_&&je){ie(je);return}if(xe.length!==0&&!xe.includes(_)){const et=xe.includes(je)?je:xe[0];et&&ie(et)}},[xe,n,_]);const[Q,$e]=i.useState(!1),[He,Ke]=i.useState(null),[qe,Xe]=i.useState(!1),[lt,bt]=i.useState(new Set),[Be,Je]=i.useState(!1),[Ze,pt]=i.useState(null),[At,vt]=i.useState(!1),at=i.useRef(new Set),ct=i.useRef(null),Ot=i.useRef(!1),Zt=i.useRef(new Set),Et=i.useRef([]);i.useEffect(()=>{pe&&!z&&$(!0)},[pe,z]),i.useEffect(()=>{G&&pe?.defaultBranch&&ie(pe.defaultBranch)},[G,pe?.defaultBranch]);const ge=Le?.pr??null,st=ge?`${t}#${ge.number}`:null,wt=!!(st&&De===st);i.useEffect(()=>{if(!m?.prContext||!ge||typeof ge.body=="string"&&ge.body.length>0)return;const je=`${t}#${ge.number}`;if(at.current.has(je))return;at.current.add(je),Re(je);let et=!1;return m.prContext(t,ge.number,{includeDiff:!1,includeCheckDetails:!1}).then(ft=>{if(et)return;const Ae=ft?.pr;Ae&&N(Ie,xt=>!xt?.pr||xt.pr.number!==ge.number?xt:{...xt,pr:{...xt.pr,body:Ae.body||""}})}).catch(()=>{}).finally(()=>{et||Re(ft=>ft===je?null:ft)}),()=>{et=!0}},[t,m,ge,Ie,N]),i.useEffect(()=>{if(!ge){fe(!1),Oe(""),we(""),ct.current=null;return}const je=ct.current!==null&&ct.current!==ge.number;je&&fe(!1),(!ce||je)&&(Oe(ge.title||""),we(ge.body||"")),ct.current=ge.number},[ce,ge]);const tt=i.useCallback(async()=>{if(!m?.prContext){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(ge){$e(!0),bt(new Set),Xe(!0);try{const je=await m.prContext(t,ge.number,{includeDiff:!1,includeCheckDetails:!0});Ke(je)}catch(je){const et=je instanceof Error?je.message:String(je);me.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:et})}finally{Xe(!1)}}},[t,m,ge,l]),ut=i.useCallback(async()=>{if(!m?.prContext){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(ge){Je(!0),vt(!0);try{const je=await m.prContext(t,ge.number,{includeDiff:!1,includeCheckDetails:!1});pt(je)}catch(je){const et=je instanceof Error?je.message:String(je);me.error(l("gitView.pr.toast.loadCommentsFailed"),{description:et})}finally{vt(!1)}}},[t,m,ge,l]),Mt=i.useCallback(je=>{if(!je)return"";const et=Date.parse(je);return Number.isFinite(et)?cc(et,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):je},[d]),It=i.useMemo(()=>{const je=f?.user?.login;return typeof je=="string"?je.trim():""},[f]),zt=i.useMemo(()=>"[&_a[href*='oc-self-mention=1']]:!text-[var(--primary-base)] [&_a[href*='oc-self-mention=1']]:font-semibold [&_a[href*='oc-self-mention=1']]:!no-underline [&_a[href*='oc-self-mention=1']:hover]:!text-[var(--primary-hover)]",[]),ss=i.useCallback(je=>{const et=It.toLowerCase(),ft=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return je.replace(ft,(Ae,xt,rt)=>{const _t=`@${rt}`,Vt=rt.toLowerCase();return`${xt}[${_t}](https://github.com/${Vt}${et&&Vt===et?"?oc-self-mention=1":""})`})},[It]),Bt=i.useMemo(()=>{const je=(Ze?.issueComments??[]).map(Ae=>({id:`issue-${Ae.id}`,body:Ae.body||"",authorName:Ae.author?.name||Ae.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:Ae.author?.login||null,avatarUrl:Ae.author?.avatarUrl||null,createdAt:Ae.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),et=(Ze?.reviewComments??[]).map(Ae=>({id:`review-${Ae.id}`,body:Ae.body||"",authorName:Ae.author?.name||Ae.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:Ae.author?.login||null,avatarUrl:Ae.author?.avatarUrl||null,createdAt:Ae.createdAt,context:l("gitView.pr.comments.reviewContext"),path:Ae.path||null,line:Ae.line??null})),ft=[...je,...et];return ft.sort((Ae,xt)=>{const rt=Ae.createdAt?Date.parse(Ae.createdAt):0,_t=xt.createdAt?Date.parse(xt.createdAt):0,Vt=Number.isFinite(rt)?rt:0,ns=Number.isFinite(_t)?_t:0;return Vt-ns}),ft},[Ze,l]),Ft=i.useCallback(()=>{if(!x)return me.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:je,currentModelId:et,currentAgentName:ft,currentVariant:Ae}=Ut.getState(),xt=lc.getState().lastUsedProvider,rt=je||xt?.providerID,_t=et||xt?.modelID;return!rt||!_t?(me.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:x,providerID:rt,modelID:_t,currentAgentName:ft??null,currentVariant:Ae??null}},[x,l]),Jt=i.useCallback((je,et,ft,Ae)=>{mt.getState().sendMessage(et,je.providerID,je.modelID,je.currentAgentName??void 0,void 0,void 0,[{text:ft,synthetic:!0},{text:Ae,synthetic:!0}],je.currentVariant??void 0).catch(xt=>{const rt=xt instanceof Error?xt.message:String(xt);me.error(l("gitView.pr.toast.sendMessageFailed"),{description:rt})})},[l]),es=i.useCallback(je=>{const et=je.status||"unknown",ft=je.conclusion??void 0,Ae=ft?`${et} / ${ft}`:et,xt=je.app?.name||je.app?.slug;return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground truncate",children:je.name}),s.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:xt?`${xt} · ${Ae}`:Ae})]}),je.detailsUrl?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:je.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(T,{name:"external-link",className:"size-4"}),"Open"]})}):null]}),je.output?.title?s.jsx("div",{className:"typography-micro text-foreground",children:je.output.title}):null,je.output?.summary?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:je.output.summary}):null,je.output?.text?s.jsx("div",{className:"rounded border border-border/40 bg-transparent px-2 py-2 typography-micro text-muted-foreground whitespace-pre-wrap max-h-48 overflow-y-auto",children:je.output.text}):null,Array.isArray(je.annotations)&&je.annotations.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",je.annotations.length>20?` (showing 20/${je.annotations.length})`:""]}),s.jsx("div",{className:"space-y-1",children:je.annotations.slice(0,20).map((rt,_t)=>s.jsxs("div",{className:"rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)]/40 px-2 py-2",children:[s.jsxs("div",{className:"typography-micro text-[var(--status-error)]",children:[rt.title||rt.level||"Issue",rt.path?` · ${rt.path}`:"",typeof rt.startLine=="number"?`:${rt.startLine}`:"",typeof rt.endLine=="number"&&rt.endLine!==rt.startLine?`-${rt.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:rt.message}),rt.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:rt.rawDetails}):null]},`${rt.path||"file"}:${rt.startLine||_t}:${_t}`))})]}):null,je.job?.steps&&je.job.steps.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.checks.steps")}),s.jsx("div",{className:"space-y-1",children:je.job.steps.map((rt,_t)=>{const Vt=(rt.conclusion||"").toLowerCase(),ns=Vt&&!["success","neutral","skipped"].includes(Vt),rs=`${je.id??"run"}:${je.job?.jobId??"job"}:${rt.number??_t}:${rt.name}`,ts=lt.has(rs);return ns?s.jsxs(Yi,{open:ts,children:[s.jsxs("button",{type:"button",onClick:()=>{bt(cn=>{const _s=new Set(cn);return _s.has(rs)?_s.delete(rs):_s.add(rs),_s})},className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-left "+(ns?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[ts?s.jsx(T,{name:"arrow-down-s",className:"size-4"}):s.jsx(T,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:rt.name}),rt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:rt.conclusion}):null]}),s.jsx(Ji,{children:s.jsxs("div",{className:"ml-6 mt-1 rounded border border-border/40 bg-transparent px-2 py-2 typography-micro text-muted-foreground space-y-1",children:[typeof rt.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",rt.number]}):null,rt.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",rt.status]}):null,rt.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",rt.conclusion]}):null,rt.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",Mt(rt.startedAt)]}):null,rt.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",Mt(rt.completedAt)]}):null]})})]},rs):s.jsxs("div",{className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-muted-foreground",children:[s.jsx("span",{className:"truncate",children:rt.name}),rt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:rt.conclusion}):null]},rs)})})]}):null]})},[lt,Mt,l]),Lt=i.useCallback(async()=>{if(h("chat"),!m?.prContext){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!ge)return;const je=Ft();if(je)try{const et=await m.prContext(t,ge.number,{includeDiff:!1,includeCheckDetails:!0}),Ae=(et.checkRuns??[]).filter(ns=>{const rs=typeof ns.conclusion=="string"?ns.conclusion.toLowerCase():"";return rs?!["success","neutral","skipped"].includes(rs):!1});if(Ae.length===0){me.message(l("gitView.pr.toast.noFailedChecks"));return}const xt=await vn("github.pr.checks.review.visible"),rt=await vn("github.pr.checks.review.instructions"),_t=Ae.flatMap(ns=>(Array.isArray(ns.annotations)?ns.annotations:[]).map(ts=>({run:ns.name,level:ts.level,title:ts.title,path:ts.path,startLine:ts.startLine,endLine:ts.endLine,message:ts.message,rawDetails:ts.rawDetails}))),Vt=`GitHub PR failed checks (JSON)
7
- ${JSON.stringify({repo:et.repo??null,pr:et.pr??null,failedChecks:Ae,failedAnnotations:_t},null,2)}`;Jt(je,xt,rt,Vt)}catch(et){const ft=et instanceof Error?et.message:String(et);me.error(l("gitView.pr.toast.loadChecksFailed"),{description:ft})}},[t,Jt,m,ge,Ft,h,l]),Pt=i.useCallback(async()=>{if(h("chat"),!m?.prContext){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!ge)return;const je=Ft();if(je)try{const et=await m.prContext(t,ge.number,{includeDiff:!1,includeCheckDetails:!1}),ft=et.issueComments??[],Ae=et.reviewComments??[];if(ft.length+Ae.length===0){me.message(l("gitView.pr.toast.noPrComments"));return}const rt=await vn("github.pr.comments.review.visible"),_t=await vn("github.pr.comments.review.instructions"),Vt=`GitHub PR comments (JSON)
8
- ${JSON.stringify({repo:et.repo??null,pr:et.pr??null,issueComments:ft,reviewComments:Ae},null,2)}`;Jt(je,rt,_t,Vt)}catch(et){const ft=et instanceof Error?et.message:String(et);me.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:ft})}},[t,Jt,m,ge,Ft,h,l]),Kt=i.useCallback(async je=>{Je(!1),h("chat");const et=Ft();if(!et)return;const ft=await vn("github.pr.comment.single.visible"),Ae=await vn("github.pr.comment.single.instructions"),xt=`GitHub PR comment (JSON)
9
- ${JSON.stringify({repo:Ze?.repo??null,pr:Ze?.pr??ge??null,comment:je},null,2)}`;Jt(et,ft,Ae,xt)},[Ze,Jt,ge,Ft,h]),yt=i.useCallback(async je=>{await D(Ie,je)},[Ie,D]),$t=i.useCallback(()=>{Et.current.forEach(je=>{window.clearTimeout(je)}),Et.current=iw.map(je=>window.setTimeout(()=>{yt({force:!0,silent:!0,markInitialResolved:!0})},je))},[yt]);i.useEffect(()=>{if(!m?.prStatus||!U||o.length<=1||Ot.current||Le?.pr)return;const je=`${v}::${he?.name??""}`;if(Zt.current.has(je))return;Zt.current.add(je);const et=cw(o,r).filter(xt=>xt.name!==he?.name);if(et.length===0)return;let ft=!1;return(async()=>{for(const xt of et){if(ft)return;try{if(!(await m.prStatus(t,e,xt.name))?.pr)continue;if(ft)return;se(_t=>_t?.name===xt.name?_t:xt);return}catch{}}})(),()=>{ft=!0}},[e,U,t,m,o,he?.name,v,Le?.pr,r]),i.useEffect(()=>{w(Ie),A(Ie,{directory:t,branch:e,remoteName:he?.name??null,canShow:U,github:m,githubAuthChecked:u,githubConnected:f?.connected??null})},[e,U,t,w,m,u,f?.connected,Ie,he?.name,A]),i.useEffect(()=>(S(Ie),()=>{I(Ie)}),[Ie,S,I]),i.useEffect(()=>{const je=dl.get(v)??null;P(je?.title??iu(e)),V(je?.body??""),B(je?.draft??!1),ie(je?.targetBaseBranch?Qr(je.targetBaseBranch):Qr(n));const et=cl(o,{selectedRemoteName:je?.selectedRemoteName,trackingBranch:r});se(ft=>ft?.name===et?.name?ft:et)},[n,e,o,v,r]),i.useEffect(()=>{yt({markInitialResolved:!0})},[Ie,yt]),i.useEffect(()=>{!U||!he?.name||yt({force:!0,silent:!0,markInitialResolved:!0})},[U,yt,he?.name]),i.useEffect(()=>{const je=Le?.resolvedRemoteName?.trim();if(!je||Ot.current)return;const et=o.find(ft=>ft.name===je);et&&se(ft=>ft?.name===et.name?ft:et)},[o,Le?.resolvedRemoteName]),i.useEffect(()=>{const je=Le?.pr?.state==="closed"||Le?.pr?.state==="merged",et=_e?.lastRefreshAt??0,ft=Date.now()-et>6e4,Ae=!je&&ft,xt=()=>{Ae&&yt({force:!0,silent:!0})},rt=()=>{document.visibilityState==="visible"&&Ae&&yt({force:!0,silent:!0})};return window.addEventListener("focus",xt),document.addEventListener("visibilitychange",rt),()=>{window.removeEventListener("focus",xt),document.removeEventListener("visibilitychange",rt)}},[yt,Le?.pr?.state,_e?.lastRefreshAt]),i.useEffect(()=>{u&&f?.connected===!1&&yt({force:!0,silent:!0,markInitialResolved:!0})},[u,f,yt]),i.useEffect(()=>{!t||!e||dl.set(v,{title:M,body:E,draft:R,additionalContext:O,targetBaseBranch:_,selectedRemoteName:he?.name})},[v,M,E,R,O,_,he?.name,t,e]),i.useEffect(()=>{const je=Et.current;return()=>{je.forEach(et=>{window.clearTimeout(et)}),Et.current=[]}},[]);const Dt=i.useCallback(async()=>{if(!Y&&t){te(!0);try{const et={base:G&&pe?.defaultBranchSha?pe.defaultBranchSha:_,head:e};O&&(et.context=O);const ft=await Dp(t,et);ft.title?.trim()&&P(ft.title.trim()),ft.body?.trim()&&V(ft.body.trim()),c?.()}catch(je){const et=je instanceof Error?je.message:String(je);me.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:et})}finally{te(!1)}}},[O,e,pe?.defaultBranchSha,t,Y,c,_,l,G]),fs=i.useCallback(async()=>{if(!m?.prCreate){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}const je=M.trim();if(!je){me.error(l("gitView.pr.toast.titleRequired"));return}const et=_.trim();if(!et){me.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!G&&et===e){me.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}be(!0);try{const ft=kc(r),Ae=G&&pe,xt=await m.prCreate({directory:t,title:je,head:e,base:et,...E.trim()?{body:E}:{},draft:R,...Ae?{targetRepo:{owner:pe.owner,repo:pe.repo},headRemote:"origin"}:{...he?{remote:he.name}:{},...ft&&ft!==he?.name?{headRemote:ft}:{}}});me.success(l("gitView.pr.toast.prCreated")),N(Ie,rt=>rt&&{...rt,pr:xt}),await yt({force:!0}),$t()}catch(ft){const Ae=ft instanceof Error?ft.message:String(ft);me.error(l("gitView.pr.toast.createPrFailed"),{description:Ae})}finally{be(!1)}},[E,e,pe,t,R,m,Ie,yt,$t,he,_,M,r,N,G,l]),ms=i.useCallback(async je=>{if(!m?.prMerge){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}J(!0);try{const et=await m.prMerge({directory:t,number:je.number,method:oe});et.merged?me.success(l("gitView.pr.toast.prMerged")):me.message(l("gitView.pr.toast.prNotMerged"),{description:et.message||l("gitView.pr.notMergeable")}),await yt({force:!0}),$t()}catch(et){const ft=et instanceof Error?et.message:String(et);me.error(l("gitView.pr.toast.mergeFailed"),{description:ft}),je.url&&ul(je.url)}finally{J(!1)}},[t,m,oe,yt,$t,l]),xs=i.useCallback(async je=>{if(!m?.prReady){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}q(!0);try{await m.prReady({directory:t,number:je.number}),me.success(l("gitView.pr.toast.markedReady")),await yt({force:!0}),$t()}catch(et){const ft=et instanceof Error?et.message:String(et);me.error(l("gitView.pr.toast.markReadyFailed"),{description:ft}),je.url&&ul(je.url)}finally{q(!1)}},[t,m,yt,$t,l]),gt=i.useCallback(async je=>{if(!m?.prUpdate){me.error(l("gitView.pr.toast.githubApiUnavailable"));return}const et=Fe.trim();if(!et){me.error(l("gitView.pr.toast.titleRequired"));return}ae(!0);try{const ft=await m.prUpdate({directory:t,number:je.number,title:et,body:Ee});N(Ie,Ae=>Ae&&{...Ae,pr:{...Ae.pr??je,...ft}}),fe(!1),me.success(l("gitView.pr.toast.prUpdated")),await yt({force:!0}),$t()}catch(ft){const Ae=ft instanceof Error?ft.message:String(ft);me.error(l("gitView.pr.toast.updatePrFailed"),{description:Ae})}finally{ae(!1)}},[t,Ee,Fe,m,Ie,yt,$t,N,l]);if(!U)return s.jsx("section",{className:"border-0 bg-transparent rounded-none",children:s.jsxs("div",{className:"space-y-1 pt-3",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:l("gitView.pullRequest.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pullRequest.availableOnFeatureBranches")})]})});const qt=Le?.repo?.url||null,hs=G&&pe?.url?pe.url:qt,os=Le?.checks??null,Is=!!Le?.canMerge,As=!!Le?.connected,Xt=u&&Le?.connected===!1,Rs=rw(Le),In=Rs?`var(--pr-${Rs})`:"var(--status-info)",Ds=Rs==="draft"?"git-pr-draft":Rs==="merged"?"git-merge":Rs==="closed"?"git-close-pull-request":"git-pull-request",Ys=ge?[`${ge.state}${ge.draft?" (draft)":""}`,ge.mergeable===!1?l("gitView.pr.notMergeable"):null,ge.state==="open"&&typeof ge.mergeableState=="string"&&ge.mergeableState&&ge.mergeableState!=="unknown"?ge.mergeableState:null].filter(Boolean).join(" · "):"",Us=os?os.total>0?`${os.success}/${os.total} ${l("gitView.pr.checks.label")}`:`${os.state} ${l("gitView.pr.checks.label")}`:"";return s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[s.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex flex-col gap-1",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[ge?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-border/60 bg-background/70 hover:bg-interactive-hover/60",onClick:()=>{ul(ge.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(T,{name:Ds,className:"size-4 shrink-0",style:{color:In}})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(T,{name:Ds,className:"size-4 shrink-0",style:{color:"var(--surface-muted-foreground)"}}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.pullRequest.title")}),ge?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",ge.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ve?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex size-5 items-center justify-center rounded hover:bg-interactive-hover/60 disabled:opacity-40",disabled:Ve,onClick:()=>{yt({force:!0})},"aria-label":l("gitView.pr.actions.refreshAria"),children:s.jsx(T,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),ge?s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 typography-micro text-muted-foreground",children:[s.jsx("span",{style:{color:In},children:Ys}),os?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${nw(os.state)}`}),Us]}):null,r&&he&&r.split("/")[0]!==he.name?s.jsxs("span",{className:"min-w-0 truncate",children:[r.split("/")[0]," → ",he.name]}):null]}):null]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[Xt?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.githubNotConnected")}),s.jsx(ze,{variant:"outline",size:"sm",onClick:C,className:"w-fit",children:l("gitView.pr.actions.openSettings")})]}):null,X?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.pr.statusUnavailable")}),s.jsx("div",{className:"typography-meta text-muted-foreground break-words",children:X}),hs?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:s.jsxs("a",{href:hs,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(T,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!ge&&!L&&!X&&!Xt?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):ge?s.jsx("div",{className:"flex flex-col gap-2",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[ce?s.jsxs("div",{className:"space-y-2",children:[s.jsx(ln,{value:Fe,onChange:je=>Oe(je.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:p?"on":"off",autoCapitalize:p?"sentences":"off",spellCheck:p}),s.jsx(yi,{value:Ee,onChange:je=>we(je.target.value),className:"min-h-[120px] bg-background/80",placeholder:l("gitView.pr.placeholder.description"),autoCorrect:p?"on":"off",autoCapitalize:p?"sentences":"off",spellCheck:p})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"typography-markdown text-xl font-semibold text-foreground break-words leading-snug",children:ge.title}),ge.body?.trim()?s.jsx(No,{content:ge.body,className:"typography-markdown-body text-muted-foreground break-words mt-1",enableFileReferences:!1}):s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap break-words mt-1",children:l(wt?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),Is&&ge.draft?s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.draftMustBeReady")}):null,Is?null:s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.noMergePermission")})]}),s.jsxs("div",{className:"order-first w-full flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[ge.state==="open"?ce?s.jsxs(s.Fragment,{children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{fe(!1),Oe(ge.title||""),we(ge.body||"")},disabled:ke,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(T,{name:"close",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>gt(ge),disabled:ke||!Fe.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:ke?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"check",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>fe(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(T,{name:"edit",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,os?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:tt,disabled:qe,"aria-label":l("gitView.pr.actions.openChecksAria"),children:qe?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"information",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,os?.failure?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Lt,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(T,{name:"error-warning",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:ut,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(T,{name:"chat-4",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Pt,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(T,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),Is&&ge.draft&&ge.state==="open"?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>xs(ge),disabled:H||ve||ke||ce,"aria-label":l("gitView.pr.actions.markReadyAria"),children:H?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.markReady")})})]}):null]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:Is?s.jsxs(s.Fragment,{children:[s.jsxs(Dn,{value:oe,onValueChange:je=>ne(je),disabled:ve||ge.state!=="open",children:[s.jsx(Tn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(fn,{})}),s.jsxs(Pn,{children:[s.jsx(vs,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(vs,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(vs,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>ms(ge),disabled:ve||H||ge.state!=="open"||ge.draft||ke||ce,"aria-label":l("gitView.pr.actions.mergePrAria"),children:ve?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"git-merge",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.mergePr")})})]})]}):null})]})]})}):s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.pr.createTitle")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," ",s.jsx("span",{className:"opacity-60",children:"(local)"})," → ",_," ",s.jsxs("span",{className:"opacity-60",children:["(",G&&pe?"upstream":"remote",")"]})]})]}),hs?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:hs,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(T,{name:"external-link",className:"size-4"}),l("gitView.pr.actions.repo")]})}):null]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.title")}),s.jsx(ln,{value:M,onChange:je=>P(je.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:p?"on":"off",autoCapitalize:p?"sentences":"off",spellCheck:p})]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.baseBranch")}),xe.length>0?s.jsxs(Dn,{value:_,onValueChange:ie,children:[s.jsx(Tn,{className:"h-9",children:s.jsx(fn,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(Pn,{children:xe.map(je=>s.jsx(vs,{value:je,children:je},je))})]}):s.jsx(ln,{value:_,onChange:je=>ie(je.target.value),placeholder:l("gitView.pr.placeholder.main")})]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.description")}),s.jsx(yi,{value:E,onChange:je=>V(je.target.value),className:"min-h-[110px]",placeholder:l("gitView.pr.placeholder.whatChanged"),autoCorrect:p?"on":"off",autoCapitalize:p?"sentences":"off",spellCheck:p})]}),s.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":R,onClick:()=>B(je=>!je),onKeyDown:je=>{(je.key===" "||je.key==="Enter")&&(je.preventDefault(),B(et=>!et))},children:[s.jsx(ki,{size:"sm",checked:R,onChange:je=>B(je),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),y?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx(ze,{variant:"outline",size:"sm",onClick:()=>K(!0),children:O.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),O.trim()&&s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("span",{className:"inline-flex items-center rounded-full bg-[var(--interactive-selection)] px-2 py-0.5 text-xs text-[var(--interactive-selection-foreground)]",children:l("gitView.pr.additionalContext.added")})})]}):s.jsxs(Yi,{open:Pe,onOpenChange:Se,children:[s.jsxs(Io,{className:"flex w-full items-center justify-between rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2 hover:bg-[var(--interactive-hover)]",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx("span",{className:"typography-micro text-[var(--primary-base)]",children:Pe?l("gitView.pr.actions.hide"):O.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(Ji,{children:s.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:[s.jsx(yi,{value:O,onChange:je=>F(je.target.value),className:"min-h-[100px] bg-transparent",placeholder:l("gitView.pr.placeholder.additionalContext")}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.hint")})]})})]}),s.jsx(Pa,{open:ue,onClose:()=>K(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx(ze,{size:"sm",onClick:()=>K(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(yi,{value:O,onChange:je=>F(je.target.value),className:"min-h-[200px] bg-transparent",placeholder:l("gitView.pr.placeholder.additionalContext"),autoFocus:!0}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.hint")})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ze,{variant:"outline",size:"sm",onClick:Dt,disabled:Y||de,children:[Y?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"ai-generate-2",className:"size-4 text-primary"}),l("gitView.commit.generate")]}),s.jsx("div",{className:"flex-1"}),s.jsxs(ze,{size:"sm",className:"min-w-[7.5rem] justify-center gap-2",onClick:fs,disabled:de||!As||!_.trim()||!G&&_.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:de?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx(Cs,{open:Q,onOpenChange:$e,children:s.jsxs(ks,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(Ms,{children:[s.jsxs(Ps,{className:"flex items-center gap-2",children:[s.jsx(T,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(qs,{children:ge?l("gitView.pr.numberLabel",{number:ge.number}):l("gitView.pullRequest.title")})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[qe?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(T,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,qe?null:s.jsx("div",{className:"space-y-3",children:Array.isArray(He?.checkRuns)&&He?.checkRuns.length>0?He.checkRuns.map((je,et)=>{const ft=`${je.id??"run"}:${je.job?.jobId??"job"}:${je.name}:${et}`;return s.jsx("div",{className:"p-1",children:es(je)},ft)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx(Cs,{open:Be,onOpenChange:Je,children:s.jsxs(ks,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(Ms,{children:s.jsxs(Ps,{className:"flex items-center gap-2",children:[s.jsx(T,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),ge?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:ge.number})}):null]})}),s.jsxs(Ia,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[At?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(T,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,At?null:s.jsx("div",{className:"space-y-4",children:Bt.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Bt.map((je,et)=>{const ft=(je.authorName||"?").charAt(0).toUpperCase(),Ae=et===Bt.length-1;return s.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[Ae?null:s.jsx("div",{className:"absolute left-4 top-[2.375rem] bottom-[0.375rem] w-px bg-border/60"}),s.jsx("div",{className:"absolute left-0 top-0 z-10 flex size-8 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-surface-elevated text-xs text-muted-foreground",children:je.avatarUrl?s.jsx("img",{src:je.avatarUrl,alt:je.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:ft})}),s.jsxs("div",{className:"rounded-lg bg-surface-elevated px-3 pt-0 pb-3 space-y-2",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1 typography-micro text-muted-foreground sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-1 sm:gap-y-1",children:[s.jsxs("span",{className:"text-foreground whitespace-nowrap",children:[je.authorName,je.authorLogin&&je.authorLogin!==je.authorName?` · @${je.authorLogin}`:""]}),je.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:Mt(je.createdAt)}):null,s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsxs(ze,{variant:"ghost",size:"sm",className:"h-6 px-0 has-[>svg]:px-0 sm:px-2 sm:has-[>svg]:px-2.5 text-[var(--status-success)] hover:bg-[var(--status-success-background)] hover:text-[var(--status-success)] justify-start",onClick:()=>{Kt(je)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(T,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(Ct,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[je.context,je.path?` · ${je.path}`:"",je.line?`:${je.line}`:""]}),s.jsx(No,{content:ss(je.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",zt].filter(Boolean).join(" "),enableFileReferences:!1})]})]},je.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},mw=t=>{const e=ht.c(150),{open:n,onOpenChange:r,conflictFiles:o,directory:a,operation:c,onAbort:l,onClearState:d}=t;let m;e[0]!==o?(m=o===void 0?[]:o,e[0]=o,e[1]=m):m=e[1];const f=m,{t:u}=jt(),g=mt(fw),b=mt(hw),h=ri(pw),x=ri(gw),y=Me(xw),[p,C]=i.useState(!1),[v,k]=i.useState(null),[w,A]=i.useState(null);let S,I;e[2]!==a||e[3]!==n||e[4]!==u?(S=()=>{!n||!a||(C(!0),A(null),k(null),Tp(a).then(G=>{k(G)}).catch(G=>{const $=G instanceof Error?G.message:u("gitView.conflict.loadFailed");A($)}).finally(()=>{C(!1)}))},I=[n,a,u],e[2]=a,e[3]=n,e[4]=u,e[5]=S,e[6]=I):(S=e[5],I=e[6]),i.useEffect(S,I);let D;e[7]!==v||e[8]!==a||e[9]!==c?(D=async()=>{if(!v)return null;const G=c==="merge"?"merge":"rebase",$=v.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),pe=c==="merge"?"git commit --no-edit":"git rebase --continue",ye=await vn("git.conflict.resolve.visible",{operation_label:G,head_ref:$}),z=await vn("git.conflict.resolve.instructions",{operation_label:G,directory:a,operation:c,head_info:v.headInfo||"N/A",continue_cmd:pe}),Ne=`${G} conflict context (JSON)
10
- ${JSON.stringify({directory:a,operation:v.operation,headInfo:v.headInfo,statusPorcelain:v.statusPorcelain,unmergedFiles:v.unmergedFiles,diff:v.diff},null,2)}`;return{visibleText:ye,instructionsText:z,payloadText:Ne}},e[7]=v,e[8]=a,e[9]=c,e[10]=D):D=e[10];const N=D;let M;e[11]!==l||e[12]!==r?(M=()=>{l(),r(!1)},e[11]=l,e[12]=r,e[13]=M):M=e[13];const P=M;let E;e[14]!==d||e[15]!==r?(E=()=>{d?.(),r(!1)},e[14]=d,e[15]=r,e[16]=E):E=e[16];const V=E;let R;e[17]!==N||e[18]!==b||e[19]!==d||e[20]!==r||e[21]!==y||e[22]!==h||e[23]!==x||e[24]!==u?(R=async()=>{const G=await N();if(!G){me.error(u("gitView.conflict.noDetailsAvailable"));return}if(!b){me.error(u("gitView.conflict.noActiveSession"),{description:u("gitView.conflict.noActiveSessionDescription")});return}h(G.visibleText,"replace"),x([{text:G.instructionsText,synthetic:!0},{text:G.payloadText,synthetic:!0}]),y("chat"),d?.(),r(!1)},e[17]=N,e[18]=b,e[19]=d,e[20]=r,e[21]=y,e[22]=h,e[23]=x,e[24]=u,e[25]=R):R=e[25];const B=R;let O;e[26]!==N||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==g||e[31]!==y||e[32]!==u?(O=async()=>{const G=await N();if(!G){me.error(u("gitView.conflict.noDetailsAvailable"));return}g({directoryOverride:a,initialPrompt:G.visibleText,syntheticParts:[{text:G.instructionsText,synthetic:!0},{text:G.payloadText,synthetic:!0}]}),y("chat"),d?.(),r(!1)},e[26]=N,e[27]=a,e[28]=d,e[29]=r,e[30]=g,e[31]=y,e[32]=u,e[33]=O):O=e[33];const F=O;let _,ie,oe,ne,Y,te,de,be,ke,ae,ve,J,H,q,ce,fe,De,Re,Fe,Oe,Ee,we;if(e[34]!==v||e[35]!==f||e[36]!==b||e[37]!==P||e[38]!==V||e[39]!==B||e[40]!==F||e[41]!==p||e[42]!==w||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==u){const G=u(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),$=v?.unmergedFiles||f;oe=Cs,Ee=n,we=r,ie=ks,Oe="max-w-md w-[calc(100vw-2rem)]",q="flex flex-col gap-4 overflow-hidden";let pe;e[69]===Symbol.for("react.memo_cache_sentinel")?(pe=s.jsx(T,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=pe):pe=e[69];const ye=s.jsxs("div",{className:"flex items-center gap-2",children:[pe,s.jsx(Ps,{children:u("gitView.conflict.detectedTitle",{operation:G})})]});let z;e[70]!==c||e[71]!==u?(z=u("gitView.conflict.detectedDescription",{operation:c}),e[70]=c,e[71]=u,e[72]=z):z=e[72];let Ne;e[73]!==z?(Ne=s.jsx(qs,{children:z}),e[73]=z,e[74]=Ne):Ne=e[74],e[75]!==ye||e[76]!==Ne?(ce=s.jsxs(Ms,{children:[ye,Ne]}),e[75]=ye,e[76]=Ne,e[77]=ce):ce=e[77],e[78]!==p||e[79]!==u?(fe=p&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:u("gitView.conflict.loading")})]}),e[78]=p,e[79]=u,e[80]=fe):fe=e[80],e[81]!==w||e[82]!==u?(De=w&&s.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:u("gitView.conflict.errorLoadingDetails",{message:w})}),e[81]=w,e[82]=u,e[83]=De):De=e[83],e[84]!==$||e[85]!==u?(Re=$.length>0&&s.jsxs("div",{className:"space-y-2 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:u("gitView.conflict.conflictedFiles")}),s.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:$.length})]}),s.jsx("div",{className:"bg-[var(--surface-elevated)] rounded-lg p-3 max-h-40 overflow-y-auto overflow-x-hidden",children:s.jsx("ul",{className:"space-y-1",children:$.map(bw)})})]}),e[84]=$,e[85]=u,e[86]=Re):Re=e[86],e[87]!==v||e[88]!==u?(Fe=v?.headInfo&&s.jsxs("div",{className:"space-y-1 overflow-hidden",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:u("gitView.conflict.headInfo")}),s.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:v.headInfo})]}),e[87]=v,e[88]=u,e[89]=Fe):Fe=e[89],ve="flex flex-col gap-2 pt-2";let U;e[90]!==F?(U=()=>{F()},e[90]=F,e[91]=U):U=e[91];const Ie=p||!v;let _e;e[92]!==p?(_e=p?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"add",className:"size-4"}),e[92]=p,e[93]=_e):_e=e[93];let Ve;e[94]!==u?(Ve=u("gitView.conflict.resolveNewSession"),e[94]=u,e[95]=Ve):Ve=e[95],e[96]!==U||e[97]!==Ie||e[98]!==_e||e[99]!==Ve?(J=s.jsxs(ze,{variant:"default",onClick:U,disabled:Ie,className:"w-full gap-2",children:[_e,Ve]}),e[96]=U,e[97]=Ie,e[98]=_e,e[99]=Ve,e[100]=J):J=e[100];let Le;e[101]!==B?(Le=()=>{B()},e[101]=B,e[102]=Le):Le=e[102];const X=p||!v||!b;let L;e[103]!==p?(L=p?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"chat-1",className:"size-4"}),e[103]=p,e[104]=L):L=e[104];let xe;e[105]!==u?(xe=u("gitView.conflict.resolveCurrentSession"),e[105]=u,e[106]=xe):xe=e[106],e[107]!==Le||e[108]!==X||e[109]!==L||e[110]!==xe?(H=s.jsxs(ze,{variant:"outline",onClick:Le,disabled:X,className:"w-full gap-2",children:[L,xe]}),e[107]=Le,e[108]=X,e[109]=L,e[110]=xe,e[111]=H):H=e[111],ke="flex gap-2 pt-1";let Q;e[112]!==u?(Q=u("gitView.conflict.continueLater"),e[112]=u,e[113]=Q):Q=e[113],e[114]!==V||e[115]!==Q?(ae=s.jsx(ze,{variant:"ghost",size:"sm",onClick:V,className:"flex-1",children:Q}),e[114]=V,e[115]=Q,e[116]=ae):ae=e[116],_=ze,ne="destructive",Y="sm",te=P,de="flex-1",be=u("gitView.conflict.abortOperation",{operation:G}),e[34]=v,e[35]=f,e[36]=b,e[37]=P,e[38]=V,e[39]=B,e[40]=F,e[41]=p,e[42]=w,e[43]=r,e[44]=n,e[45]=c,e[46]=u,e[47]=_,e[48]=ie,e[49]=oe,e[50]=ne,e[51]=Y,e[52]=te,e[53]=de,e[54]=be,e[55]=ke,e[56]=ae,e[57]=ve,e[58]=J,e[59]=H,e[60]=q,e[61]=ce,e[62]=fe,e[63]=De,e[64]=Re,e[65]=Fe,e[66]=Oe,e[67]=Ee,e[68]=we}else _=e[47],ie=e[48],oe=e[49],ne=e[50],Y=e[51],te=e[52],de=e[53],be=e[54],ke=e[55],ae=e[56],ve=e[57],J=e[58],H=e[59],q=e[60],ce=e[61],fe=e[62],De=e[63],Re=e[64],Fe=e[65],Oe=e[66],Ee=e[67],we=e[68];let Pe;e[117]!==_||e[118]!==ne||e[119]!==Y||e[120]!==te||e[121]!==de||e[122]!==be?(Pe=s.jsx(_,{variant:ne,size:Y,onClick:te,className:de,children:be}),e[117]=_,e[118]=ne,e[119]=Y,e[120]=te,e[121]=de,e[122]=be,e[123]=Pe):Pe=e[123];let Se;e[124]!==ke||e[125]!==ae||e[126]!==Pe?(Se=s.jsxs("div",{className:ke,children:[ae,Pe]}),e[124]=ke,e[125]=ae,e[126]=Pe,e[127]=Se):Se=e[127];let ue;e[128]!==ve||e[129]!==J||e[130]!==H||e[131]!==Se?(ue=s.jsxs("div",{className:ve,children:[J,H,Se]}),e[128]=ve,e[129]=J,e[130]=H,e[131]=Se,e[132]=ue):ue=e[132];let K;e[133]!==q||e[134]!==ce||e[135]!==fe||e[136]!==De||e[137]!==Re||e[138]!==Fe||e[139]!==ue?(K=s.jsxs("div",{className:q,children:[ce,fe,De,Re,Fe,ue]}),e[133]=q,e[134]=ce,e[135]=fe,e[136]=De,e[137]=Re,e[138]=Fe,e[139]=ue,e[140]=K):K=e[140];let he;e[141]!==ie||e[142]!==Oe||e[143]!==K?(he=s.jsx(ie,{className:Oe,children:K}),e[141]=ie,e[142]=Oe,e[143]=K,e[144]=he):he=e[144];let se;return e[145]!==oe||e[146]!==Ee||e[147]!==we||e[148]!==he?(se=s.jsx(oe,{open:Ee,onOpenChange:we,children:he}),e[145]=oe,e[146]=Ee,e[147]=we,e[148]=he,e[149]=se):se=e[149],se};function fw(t){return t.openNewSessionDraft}function hw(t){return t.currentSessionId}function pw(t){return t.setPendingInputText}function gw(t){return t.setPendingSyntheticParts}function xw(t){return t.setActiveMainTab}function bw(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const yw=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=jt(),[c,l]=i.useState(!0),[d,m]=i.useState(!1),f=a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),u=async()=>{m(!0);try{await o(c),e(!1)}catch(b){const h=b instanceof Error?b.message:`Failed to ${n}`;me.error(h)}finally{m(!1)}},g=()=>{d||e(!1)};return s.jsx(Cs,{open:t,onOpenChange:d?void 0:e,children:s.jsxs(ks,{className:"max-w-md",children:[s.jsxs(Ms,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(T,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(Ps,{children:a("gitView.stash.title")})]}),s.jsx(qs,{children:a("gitView.stash.description",{operation:n})})]}),s.jsxs("div",{className:"py-2",children:[s.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:a("gitView.stash.thisWill")}),s.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[s.jsx("li",{children:a("gitView.stash.stepStash")}),s.jsxs("li",{children:[a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase")," ",a(n==="merge"?"gitView.stash.mergeWith":"gitView.stash.rebaseOnto")," ",s.jsx("span",{className:"font-mono text-primary",children:r})]}),c&&s.jsx("li",{children:a("gitView.stash.stepRestore")})]})]}),s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(ki,{checked:c,onChange:l,disabled:d,ariaLabel:a("gitView.stash.restoreAria")}),s.jsx("span",{className:"typography-ui-label text-foreground cursor-pointer select-none",onClick:()=>!d&&l(!c),children:a("gitView.stash.restoreAfterOperation",{operation:n})})]}),s.jsxs(qn,{className:"gap-2",children:[s.jsx(ze,{variant:"ghost",size:"sm",onClick:g,disabled:d,children:a("gitView.common.cancel")}),s.jsx(ze,{variant:"default",size:"sm",onClick:u,disabled:d,className:"gap-1.5",children:d?s.jsxs(s.Fragment,{children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:f})})]})]})})},ww=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=jt(),[d,m]=i.useState(null),f=t&&t.head,u=e&&(e.headName||e.onto),g=f?"merge":u?"rebase":null;if(!g)return null;const b=async()=>{m("continue");try{await n()}finally{m(null)}},h=async()=>{m("abort");try{await r()}finally{m(null)}},x=d!==null,y=l(g==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),p=g==="merge"?"git-merge":"git-branch";let C="";return t?C=t.message?l("gitView.operation.mergingMessage",{message:t.message}):l("gitView.operation.mergeInProgressWithHead",{head:t.head}):e&&(C=e.headName?l("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):l("gitView.operation.rebaseInProgress")),s.jsx("div",{className:"bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[s.jsx(T,{name:p,className:"size-4 text-[var(--status-warning)] shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:l("gitView.operation.inProgressTitle",{operation:y})}),C&&s.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:C})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&o&&s.jsxs(ze,{variant:"outline",size:"sm",onClick:o,disabled:x||c,className:"gap-1.5",children:[s.jsx(T,{name:"sparkling",className:"size-4"}),l("gitView.operation.resolveWithAi")]}),d!=="continue"&&s.jsxs(ze,{variant:"ghost",size:"sm",onClick:h,disabled:x||c,className:"gap-1.5",children:[d==="abort"?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs(ze,{variant:"default",size:"sm",onClick:b,disabled:x||c,className:"gap-1.5",children:[d==="continue"?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"check",className:"size-4"}),l("gitView.operation.continue")]})]}),a&&s.jsx("p",{className:"typography-micro text-[var(--status-warning)]",children:l("gitView.operation.resolveConflictsHint")})]})})},vw=t=>{const e=ht.c(104),{currentBranch:n,localBranches:r,remoteBranches:o,onMerge:a,onRebase:c,disabled:l,isOperating:d,operationLogs:m,onOperationComplete:f,mode:u,defaultTargetBranch:g}=t,b=l===void 0?!1:l,h=d===void 0?!1:d,x=m===void 0?[]:m,y=u===void 0?"dialog":u,{t:p}=jt(),[C,v]=i.useState(!1),[k,w]=i.useState("merge"),[A,S]=i.useState(null),[I,D]=i.useState(!1),[N,M]=i.useState(""),P=i.useRef(null),E=i.useRef(null),V=b||h,R=n||p("gitView.branch.currentBranchFallback"),B=x.length>0&&x.every(jw),O=x.some(Sw);let F;e[0]===Symbol.for("react.memo_cache_sentinel")?(F=()=>{E.current&&(E.current.scrollTop=E.current.scrollHeight)},e[0]=F):F=e[0],i.useEffect(F,[x]);let _;if(e[1]!==N||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Le=N.toLowerCase();let X;e[6]!==o?(X=new Set(o.map(Nw).filter(Boolean)),e[6]=o,e[7]=X):X=e[7];const L=X;let xe;e[8]!==n||e[9]!==L?(xe=$e=>$e!==n&&!L.has($e),e[8]=n,e[9]=L,e[10]=xe):xe=e[10];const Q=r.filter(xe);if(!Le){_=Q;break e}_=Q.filter($e=>$e.toLowerCase().includes(Le))}e[1]=N,e[2]=n,e[3]=r,e[4]=o,e[5]=_}else _=e[5];const ie=_;let oe;if(e[11]!==N||e[12]!==o){e:{const Le=N.toLowerCase();if(!Le){oe=o;break e}oe=o.filter(X=>X.toLowerCase().includes(Le))}e[11]=N,e[12]=o,e[13]=oe}else oe=e[13];const ne=oe;let Y;e[14]!==g||e[15]!==r||e[16]!==o?(Y=()=>g&&(o.includes(g)||r.includes(g))?g:null,e[14]=g,e[15]=r,e[16]=o,e[17]=Y):Y=e[17];const te=Y;let de;e[18]!==te||e[19]!==v?(de=()=>{v(!0),S(te()),w("merge"),M("")},e[18]=te,e[19]=v,e[20]=de):de=e[20];const be=de;let ke;e[21]===Symbol.for("react.memo_cache_sentinel")?(ke=Le=>{S(Le),D(!1),M("")},e[21]=ke):ke=e[21];const ae=ke;let ve;e[22]!==a||e[23]!==c||e[24]!==k||e[25]!==A?(ve=()=>{A&&(k==="merge"?a(A):c(A))},e[22]=a,e[23]=c,e[24]=k,e[25]=A,e[26]=ve):ve=e[26];const J=ve;let H;e[27]!==h||e[28]!==v?(H=()=>{h||(S(null),w("merge"),M(""),v(!1))},e[27]=h,e[28]=v,e[29]=H):H=e[29];const q=H,ce=()=>{h&&!B||(B&&f?.(),S(null),w("merge"),M(""),v(!1))};let fe,De;e[30]!==I?(fe=()=>{I||M("")},De=[I],e[30]=I,e[31]=fe,e[32]=De):(fe=e[31],De=e[32]),i.useEffect(fe,De);let Re,Fe;e[33]!==y||e[34]!==te||e[35]!==A?(Re=()=>{y!=="inline"||A||S(te())},Fe=[y,te,A],e[33]=y,e[34]=te,e[35]=A,e[36]=Re,e[37]=Fe):(Re=e[36],Fe=e[37]),i.useEffect(Re,Fe);const we=h?s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{ref:E,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:s.jsx("div",{className:"space-y-2",children:x.map(kw)})}),B?y==="dialog"?s.jsx(qn,{children:s.jsx(ze,{variant:"default",size:"sm",onClick:ce,children:p(O?"gitView.common.close":"gitView.common.done")})}):s.jsx("div",{className:"flex justify-end",children:s.jsx(ze,{variant:"default",size:"sm",onClick:ce,children:p(O?"gitView.common.close":"gitView.common.done")})}):null]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:p("gitView.branch.operation")}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>w("merge"),className:Te("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",k==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(T,{name:"git-merge",className:Te("size-4",k==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Te("typography-ui-label",k==="merge"?"text-foreground":"text-muted-foreground"),children:p("gitView.operation.merge")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:p("gitView.branch.mergeDescription")})]}),s.jsxs("button",{type:"button",onClick:()=>w("rebase"),className:Te("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",k==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(T,{name:"git-branch",className:Te("size-4",k==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Te("typography-ui-label",k==="rebase"?"text-foreground":"text-muted-foreground"),children:p("gitView.operation.rebase")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:p("gitView.branch.rebaseDescription")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:k==="merge"?p("gitView.branch.branchToMergeInto",{branch:R}):p("gitView.branch.branchToRebaseOnto")}),s.jsxs(Ws,{open:I,onOpenChange:D,modal:!1,children:[s.jsx($s,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:Te("truncate",!A&&"text-muted-foreground"),children:A||p("gitView.branch.selectBranch")}),s.jsx(T,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(zs,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:s.jsxs(Ca,{className:"h-full min-h-0",children:[s.jsx(Aa,{ref:P,placeholder:p("gitView.branch.searchPlaceholder"),value:N,onValueChange:M,onKeyDown:Cw}),s.jsxs(Da,{className:"h-full min-h-0",disableHorizontal:!0,children:[s.jsx(Ta,{children:p("gitView.branch.empty")}),ie.length>0&&s.jsx(ti,{heading:p("gitView.branch.localBranches"),children:ie.map(Le=>s.jsx(ni,{onSelect:()=>ae(Le),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Le})},`local-${Le}`))}),ie.length>0&&ne.length>0?s.jsx(Pp,{}):null,ne.length>0&&s.jsx(ti,{heading:p("gitView.branch.remoteBranches"),children:ne.map(Le=>s.jsx(ni,{onSelect:()=>ae(Le),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Le})},`remote-${Le}`))})]})]})})]})]}),A?s.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:k==="merge"?s.jsxs(s.Fragment,{children:[p("gitView.branch.summaryMergePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:A})," ",p("gitView.branch.summaryMergeInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R})]}):s.jsxs(s.Fragment,{children:[p("gitView.branch.summaryRebasePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R})," ",p("gitView.branch.summaryRebaseInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:A})]})})}):null,y==="dialog"?s.jsxs(qn,{className:"gap-2 pt-1",children:[s.jsx(ze,{variant:"ghost",size:"sm",onClick:q,children:p("gitView.common.cancel")}),s.jsx(ze,{variant:"default",size:"sm",onClick:J,disabled:!A,className:"gap-1.5",children:k==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(T,{name:"git-merge",className:"size-4"}),p("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(T,{name:"git-branch",className:"size-4"}),p("gitView.operation.rebase")]})})]}):s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(ze,{variant:"destructive",size:"sm",onClick:q,disabled:V,children:p("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx(ze,{variant:"default",size:"sm",onClick:J,disabled:V||!A,children:p(k==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(y==="inline"){let Le;e[38]!==p?(Le=p("gitView.branch.updateTitle"),e[38]=p,e[39]=Le):Le=e[39];let X;e[40]!==Le?(X=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Le}),e[40]=Le,e[41]=X):X=e[41];let L;e[42]!==p?(L=p("gitView.branch.updateDescriptionPrefix"),e[42]=p,e[43]=L):L=e[43];let xe;e[44]!==R?(xe=s.jsx("span",{className:"font-mono text-foreground",children:R}),e[44]=R,e[45]=xe):xe=e[45];let Q;e[46]!==L||e[47]!==xe?(Q=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[L," ",xe,"."]}),e[46]=L,e[47]=xe,e[48]=Q):Q=e[48];let $e;e[49]!==X||e[50]!==Q?($e=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[X,Q]})}),e[49]=X,e[50]=Q,e[51]=$e):$e=e[51];let He;e[52]!==we?(He=s.jsx("div",{className:"pt-3",children:we}),e[52]=we,e[53]=He):He=e[53];let Ke;return e[54]!==$e||e[55]!==He?(Ke=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[$e,He]}),e[54]=$e,e[55]=He,e[56]=Ke):Ke=e[56],Ke}let Pe;e[57]!==h?(Pe=h?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"git-merge",className:"size-4"}),e[57]=h,e[58]=Pe):Pe=e[58];let Se;e[59]!==p?(Se=p("gitView.branch.mergeRebase"),e[59]=p,e[60]=Se):Se=e[60];let ue;e[61]!==Se?(ue=s.jsx("span",{children:Se}),e[61]=Se,e[62]=ue):ue=e[62];let K;e[63]!==be||e[64]!==V||e[65]!==Pe||e[66]!==ue?(K=s.jsx(kt,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"sm",className:"gap-1.5",onClick:be,disabled:V,children:[Pe,ue]})}),e[63]=be,e[64]=V,e[65]=Pe,e[66]=ue,e[67]=K):K=e[67];let he;e[68]!==p?(he=p("gitView.branch.mergeRebaseTooltip"),e[68]=p,e[69]=he):he=e[69];let se;e[70]!==he?(se=s.jsx(Ct,{sideOffset:8,children:he}),e[70]=he,e[71]=se):se=e[71];let G;e[72]!==K||e[73]!==se?(G=s.jsxs(Nt,{children:[K,se]}),e[72]=K,e[73]=se,e[74]=G):G=e[74];let $;e[75]!==ce||e[76]!==v?($=Le=>{Le?v(!0):ce()},e[75]=ce,e[76]=v,e[77]=$):$=e[77];let pe;e[78]!==p?(pe=p("gitView.branch.updateTitle"),e[78]=p,e[79]=pe):pe=e[79];let ye;e[80]!==pe?(ye=s.jsx(Ps,{children:pe}),e[80]=pe,e[81]=ye):ye=e[81];let z;e[82]!==O||e[83]!==h||e[84]!==k||e[85]!==B||e[86]!==p||e[87]!==R?(z=h?p(B?O?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":k==="merge"?"gitView.branch.mergingInProgress":"gitView.branch.rebasingInProgress"):s.jsxs(s.Fragment,{children:[p("gitView.branch.dialogDescriptionPrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R}),"."]}),e[82]=O,e[83]=h,e[84]=k,e[85]=B,e[86]=p,e[87]=R,e[88]=z):z=e[88];let Ne;e[89]!==z?(Ne=s.jsx(qs,{children:z}),e[89]=z,e[90]=Ne):Ne=e[90];let U;e[91]!==ye||e[92]!==Ne?(U=s.jsxs(Ms,{children:[ye,Ne]}),e[91]=ye,e[92]=Ne,e[93]=U):U=e[93];let Ie;e[94]!==we||e[95]!==U?(Ie=s.jsxs(ks,{className:"max-w-md",children:[U,we]}),e[94]=we,e[95]=U,e[96]=Ie):Ie=e[96];let _e;e[97]!==C||e[98]!==$||e[99]!==Ie?(_e=s.jsx(Cs,{open:C,onOpenChange:$,children:Ie}),e[97]=C,e[98]=$,e[99]=Ie,e[100]=_e):_e=e[100];let Ve;return e[101]!==G||e[102]!==_e?(Ve=s.jsxs(s.Fragment,{children:[G,_e]}),e[101]=G,e[102]=_e,e[103]=Ve):Ve=e[103],Ve};function jw(t){return t.status==="done"||t.status==="error"}function Sw(t){return t.status==="error"}function Nw(t){return t.slice(t.indexOf("/")+1)}function kw(t,e){return s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"mt-0.5 shrink-0",children:[t.status==="running"&&s.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(T,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(T,{name:"close",className:"size-3.5 text-destructive"}),t.status==="pending"&&s.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),s.jsx("span",{className:Te("typography-micro",t.status==="error"&&"text-destructive",t.status==="done"&&"text-muted-foreground",t.status==="running"&&"text-foreground",t.status==="pending"&&"text-muted-foreground/60"),children:t.message})]},e)}function Cw(t){return t.stopPropagation()}const Aw=({runMutation:t,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:o})=>{const a=[];let c=!1;return{enqueue:d=>{const m=a[a.length-1];if(m?.directory===d.directory&&m.direction===d.direction){d.paths.forEach(f=>m.paths.add(f));return}a.push(d)},flush:()=>{if(c)return;const d=a.shift();if(!d)return;c=!0;const m={directory:d.directory,direction:d.direction,paths:Array.from(d.paths),rollback:d.rollback};(async()=>{try{await t(m),e(m)}catch(f){n(m,f)}finally{r(m.paths),c=!1,a.length>0&&o()}})()},clear:()=>{a.length=0},size:()=>a.length,isRunning:()=>c}},ou="oc.git.actionTab",Dw=15e3,Tw=t=>t==="commit"||t==="branch"||t==="pr",Pw=40,Iw=20,au={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},Rw=(t,e)=>{const n=t.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,o=n.match(r);if(o){const l=o[1],d=au[l];if(d)return e.find(m=>m.code===d)||null}const a=n.split(" ")[0],c=au[a];return c&&e.find(l=>l.code===c)||null},Ew=20,Bi=new Map,Mw=(t,e)=>{if(Bi.delete(t),Bi.set(t,e),Bi.size>Ew){const n=Bi.keys().next().value;n!==void 0&&Bi.delete(n)}},Rr=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),lu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Fw=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},$l=({isActive:t})=>{const{t:e}=jt(),{git:n}=_n(),r=ii(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=mt(ee=>ee.currentSessionId),m=mt(ee=>ee.newSessionDraft),f=mt(ee=>ee.setDraftBootstrapPendingDirectory),u=mt(ee=>ee.worktreeMetadata),g=mt(ee=>ee.availableWorktrees),b=Rr(r),h=i.useMemo(()=>{if(!b)return;const ee=g.find(j=>Rr(j.path)===b);if(ee)return ee;for(const j of u.values())if(Rr(j.path)===b)return j},[g,b,u]),x=i.useMemo(()=>{if(d)return u.get(d)??h;if(m?.open)return h},[d,h,m?.open,u]),{profiles:y,globalIdentity:p,defaultGitIdentityId:C,loadProfiles:v,loadGlobalIdentity:k,loadDefaultGitIdentityId:w}=px(Tl(ee=>({profiles:ee.profiles,globalIdentity:ee.globalIdentity,defaultGitIdentityId:ee.defaultGitIdentityId,loadProfiles:ee.loadProfiles,loadGlobalIdentity:ee.loadGlobalIdentity,loadDefaultGitIdentityId:ee.loadDefaultGitIdentityId}))),A=dc(r??null),S=Ra(r??null),I=km(ee=>d?ee.getAttachment(d):void 0),D=I?Ip(I):[],N=I&&!I.degraded&&!I.legacy?I.worktreeRoot??void 0:void 0,M=hy(r,x,S?.current??void 0),P=Im(r??null),E=Rp(r??null),V=Ep(r??null),R=uc(r??null),B=Mp(r??null),{setActiveDirectory:O,fetchAll:F,ensureAll:_,fetchStatus:ie,fetchBranches:oe,fetchLog:ne,setLogMaxCount:Y,fetchIdentity:te,prefetchDiffs:de,moveStatusPathsOptimistically:be,restoreStatus:ke,bumpIndexRevision:ae}=an(Tl(ee=>({setActiveDirectory:ee.setActiveDirectory,fetchAll:ee.fetchAll,ensureAll:ee.ensureAll,fetchStatus:ee.fetchStatus,fetchBranches:ee.fetchBranches,fetchLog:ee.fetchLog,setLogMaxCount:ee.setLogMaxCount,fetchIdentity:ee.fetchIdentity,prefetchDiffs:ee.prefetchDiffs,moveStatusPathsOptimistically:ee.moveStatusPathsOptimistically,restoreStatus:ee.restoreStatus,bumpIndexRevision:ee.bumpIndexRevision}))),ve=Me(ee=>ee.isMobile),J=Me(ee=>ee.openContextDiff),H=Me(ee=>ee.navigateToDiff),q=Me(ee=>ee.setRightSidebarOpen),ce=i.useRef(null),fe=i.useRef(null),De=i.useRef(null),Re=i.useRef(null),Fe=i.useRef(!0);i.useEffect(()=>()=>{Fe.current=!1},[]);const Oe=i.useCallback(()=>{fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null)},[]),Ee=i.useCallback(ee=>{Oe(),fe.current=window.setTimeout(()=>{fe.current=null,Rr(ee)===Rr(r)&&ie(ee,n,{silent:!0})},Dw)},[Oe,r,ie,n]);i.useEffect(()=>Oe,[Oe]);const we=i.useCallback(()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},[]),Pe=i.useCallback(()=>{De.current===null&&(De.current=window.setTimeout(()=>{De.current=null,Re.current?.()},0))},[]),Se=i.useCallback(async(ee,j,Z)=>{if(j==="stage"){if(n.stageGitFiles){await n.stageGitFiles(ee,Z);return}await Promise.all(Z.map(le=>n.stageGitFile(ee,le)));return}if(n.unstageGitFiles){await n.unstageGitFiles(ee,Z);return}await Promise.all(Z.map(le=>n.unstageGitFile(ee,le)))},[n]),ue=i.useMemo(()=>Aw({runMutation:({directory:ee,direction:j,paths:Z})=>Se(ee,j,Z),onMutationComplete:({directory:ee})=>{ae(ee),Ee(ee)},onMutationError:({directory:ee,direction:j,rollback:Z},le)=>{Z?.(),ae(ee),Ee(ee);const We=e(j==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");me.error(le instanceof Error?le.message:We)},onPathsComplete:ee=>{Zt(j=>{const Z=new Set(j);return ee.forEach(le=>Z.delete(le)),Z})},scheduleFlush:Pe}),[ae,Se,Pe,Ee,e]);i.useEffect(()=>(Re.current=ue.flush,()=>{Re.current=null}),[ue]),i.useEffect(()=>()=>ue.clear(),[ue]),i.useEffect(()=>we,[we]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let ee=!1,j=null;const Z=async()=>{try{const le=await Lp(r);if(ee)return;a(le.status),le.status==="pending"&&(j=window.setTimeout(()=>{Z()},500))}catch{ee||a(null)}};return Z(),()=>{ee=!0,j!==null&&window.clearTimeout(j)}},[t,r]),i.useEffect(()=>{const ee=ce.current;ce.current=o,!(!r||!n)&&(ee==="pending"&&o==="ready"&&(l(!0),F(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(f(null),l(!1)))},[r,F,n,f,o]);const K=Rr(m?.bootstrapPendingDirectory??null),he=!!(r&&K&&K===Rr(r)),G=!!(r&&(o==="pending"||he))||c,$=i.useMemo(()=>r?Bi.get(r)??null:null,[r]),pe=Ut(ee=>ee.settingsGitmojiEnabled),[ye,z]=i.useState(null),{gitmojis:Ne}=fy(pe);i.useEffect(()=>{const ee=N||M?.projectDirectory;if(!ee){z(null);return}let j=!1;return Ea(ee).then(Z=>{if(j)return;const le=Z.trim();z(le&&le!=="HEAD"?le:null)}).catch(()=>{j||z(null)}),()=>{j=!0}},[N,M?.projectDirectory]);const[U,Ie]=i.useState($?.commitMessage??""),[_e,Ve]=i.useState([]),[Le,X]=i.useState(!1),L=i.useRef(null),[xe,Q]=i.useState(null),[$e,He]=i.useState(!1),[Ke,qe]=i.useState(null),[Xe,lt]=i.useState(25),[bt,Be]=i.useState(!1),{triggerFireworks:Je}=cy(),Ze=i.useRef(new Map),pt=i.useRef(0),At=i.useCallback(()=>{pt.current+=1,Fe.current&&Be(!0)},[]),vt=i.useCallback(()=>{pt.current=Math.max(0,pt.current-1),Fe.current&&pt.current===0&&Be(!1)},[]),[at,ct]=i.useState(new Set),[Ot,Zt]=i.useState(new Set),[Et,ge]=i.useState(!1),[st,wt]=i.useState(0),[tt,ut]=i.useState(!1),[Mt,It]=i.useState($?.generatedHighlights??[]),zt=Ot.size>0||ue.size()>0||ue.isRunning(),ss=i.useCallback(()=>{const ee=L.current;ee&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{ee.scrollTo({top:ee.scrollHeight,behavior:"smooth"})})})},[]),Bt=N||M?.projectDirectory||null,Ft=S?.current||null,Jt=i.useMemo(()=>{const ee=S?.tracking;return ee?ee.startsWith("origin/"):!0},[S?.tracking]),es=i.useMemo(()=>{const ee=M?.createdFromBranch,j=typeof ee=="string"?ee.trim():"",Z=typeof S?.current=="string"?S.current.trim():"",le=typeof ye=="string"?ye.trim():"";return j?j===Z&&j.startsWith("opencode/")&&le.length>0&&le!==j?le:j:le||Z||"HEAD"},[M?.createdFromBranch,S,ye]),Lt=i.useCallback(()=>{It([])},[]),[Pt,Kt]=i.useState(new Set),[yt,$t]=i.useState(new Map),[Dt,fs]=i.useState(new Set),ms=i.useRef(yt),xs=i.useRef(Dt),[gt,qt]=i.useState(null),[hs,os]=i.useState(null),[Is,As]=i.useState(""),[Xt,Rs]=i.useState(null),In=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(T,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(T,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(T,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[Ds,Ys]=i.useState(()=>{if(typeof window>"u")return"commit";const ee=window.localStorage.getItem(ou);return ee==="worktree"?"branch":Tw(ee)?ee:"commit"}),[Us,bs]=i.useState([]),[Yn,en]=i.useState(null),[je,et]=i.useState(null),[ft,Ae]=i.useState([]),[xt,rt]=i.useState(!1),[_t,Vt]=i.useState([]),[ns,rs]=i.useState("merge"),[ts,cn]=i.useState(null),[_s,tn]=i.useState(!1),[Rn,jn]=i.useState(100),dn=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),Es=i.useCallback((ee,j,Z)=>{if(!dn||typeof window>"u")return;const le={directory:ee,conflictFiles:j,operation:Z};window.localStorage.setItem(dn,JSON.stringify(le))},[dn]),js=i.useCallback(()=>{!dn||typeof window>"u"||window.localStorage.removeItem(dn)},[dn]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(ou,Ds)},[Ds]),i.useEffect(()=>{if(!dn||typeof window>"u"||!r)return;const ee=window.localStorage.getItem(dn);if(ee)try{const j=JSON.parse(ee);if(j.directory!==r){window.localStorage.removeItem(dn);return}Vt(j.conflictFiles??[]),rs(j.operation??"merge"),rt(!0)}catch{window.localStorage.removeItem(dn)}},[dn,r]);const[Or,En]=i.useState(!1),[sr,Br]=i.useState("merge"),[Vn,_r]=i.useState(""),Js=i.useCallback(ee=>{tr(ee).then(j=>{if(j.ok){me.success(e("gitView.toast.commitHashCopied"));return}me.error(e("gitView.toast.copyFailed"))})},[e]),nr=i.useCallback(ee=>{Kt(j=>{const Z=new Set(j);return Z.has(ee)?Z.delete(ee):Z.add(ee),Z})},[]);i.useEffect(()=>{ms.current=yt},[yt]),i.useEffect(()=>{xs.current=Dt},[Dt]),i.useEffect(()=>{if(!r||!n)return;const ee=Array.from(Pt).filter(Z=>!ms.current.has(Z)&&!xs.current.has(Z));if(ee.length===0)return;let j=!1;return fs(Z=>{const le=new Set(Z);for(const We of ee)le.add(We);return xs.current=le,le}),Promise.all(ee.map(Z=>n.getCommitFiles(r,Z).then(le=>({hash:Z,files:le.files})).catch(le=>(console.error("Failed to fetch commit files:",le),{hash:Z,files:[]})))).then(Z=>{j||($t(le=>{const We=new Map(le);for(const{hash:Ye,files:Tt}of Z)We.set(Ye,Tt);return ms.current=We,We}),fs(le=>{const We=new Set(le);for(const{hash:Ye}of Z)We.delete(Ye);return xs.current=We,We}))}),()=>{j=!0,fs(Z=>{let le=!1;const We=new Set(Z);for(const Ye of ee)We.delete(Ye)&&(le=!0);return le?(xs.current=We,We):Z})}},[Pt,r,n]),i.useEffect(()=>{r&&Mw(r,{directory:r,commitMessage:U,generatedHighlights:Mt})},[U,r,Mt]),i.useEffect(()=>{t&&(v(),k(),w())},[t,v,k,w]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){os(null);return}let ee=!1;return n.getRemoteUrl(r).then(j=>{ee||os(j)}).catch(()=>{ee||os(null)}),()=>{ee=!0}},[t,r,n]);const un=i.useCallback(async()=>{if(!r||!n?.getRemotes){bs([]);return}try{const ee=await n.getRemotes(r);Fe.current&&bs(ee)}catch{Fe.current&&bs([])}},[r,n]);i.useEffect(()=>{t&&un()},[t,un]),i.useEffect(()=>{t&&r&&(O(r),_(r,n))},[t,r,O,_,n]),i.useEffect(()=>{if(t&&r)return Nr.onGitRefreshHint(ee=>{Rr(ee.directory)===Rr(r)&&ie(r,n)})},[t,r,ie,n]);const as=i.useCallback(async(ee=!0)=>{if(r)try{await Promise.all([ie(r,n),oe(r,n)])}catch(j){if(ee){const Z=j instanceof Error?j.message:e("gitView.toast.refreshRepositoryFailed");me.error(Z)}}},[r,n,ie,oe,e]),ws=i.useCallback(async()=>{r&&await ne(r,n,Xe)},[r,n,ne,Xe]),$n=i.useCallback(async()=>{r&&await te(r,n)},[r,n,te]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||A!==!0)return;const ee=typeof C=="string"?C.trim():"";if(!ee||ee==="global"||Ze.current.get(r)===ee)return;let Z=!1;return(async()=>{try{const We=await n.hasLocalIdentity?.(r);if(Z||We===!0)return;At(),await n.setGitIdentity(r,ee),Ze.current.set(r,ee),await $n()}catch(We){console.warn("Failed to auto-apply default git identity:",We)}finally{Z||vt()}})(),()=>{Z=!0}},[t,At,r,C,vt,n,A,$n]);const sn=i.useMemo(()=>S?[...S.files??[]].sort((j,Z)=>j.path.localeCompare(Z.path)):[],[S]),Qs=i.useMemo(()=>sn.filter(lu),[sn]),rr=i.useMemo(()=>sn.filter(Fw),[sn]);i.useEffect(()=>{if(!r||sn.length===0)return;const ee=[],j=new Set,Z=We=>{!We||j.has(We)||(j.add(We),ee.push(We))};if(Qs.forEach(We=>Z(We.path)),_e.forEach(Z),sn.slice(0,Iw).forEach(We=>Z(We.path)),ee.length===0)return;const le=window.setTimeout(()=>{de(r,n,ee,{maxFiles:Pw})},120);return()=>{window.clearTimeout(le)}},[sn,r,n,de,Qs,_e]);const xr=ee=>ee?.pushed[0]?.remote||S?.tracking?.split("/")[0]||Ht.find(j=>j.name==="origin")?.name||Ht[0]?.name||"origin",br=async(ee,j)=>{if(r){Q(ee);try{const Z=le=>{const We=`${le.name}/`,Ye=S?.tracking?.startsWith(We)?S.tracking.slice(We.length):void 0;return{remote:le.name,branch:Ye,rebase:!0}};if(ee==="fetch"){if(!j)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:j.name}),me.success(e("gitView.toast.fetchedFromRemote",{name:j.name}))}else if(ee==="pull"){if(!j)throw new Error("No remote available for pull");const le=await n.gitPull(r,Z(j));me.success(le.files.length===1?e("gitView.toast.pulledFilesSingle",{count:le.files.length,name:j.name}):e("gitView.toast.pulledFilesPlural",{count:le.files.length,name:j.name}))}else if(ee==="push"){const le=await n.gitPush(r);me.success(e("gitView.toast.pushedToUpstream",{name:xr(le)}))}else if(ee==="sync"){if(!j)throw new Error("No remote available for sync");let le=0,We=!1;await n.gitFetch(r,{remote:j.name});const Ye=await n.getGitStatus(r);if((Ye.behind??0)>0){if((Ye.files?.length??0)>0){me.error(e("gitView.toast.commitOrStashBeforeSync"));return}le=(await n.gitPull(r,Z(j))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),We=!0),le>0&&We?me.success(le===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:le,name:j.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:le,name:j.name})):le>0?me.success(le===1?e("gitView.toast.pulledFilesSingle",{count:le,name:j.name}):e("gitView.toast.pulledFilesPlural",{count:le,name:j.name})):We?me.success(e("gitView.toast.pushedToUpstream",{name:j.name})):me.success(e("gitView.toast.alreadyUpToDate"))}await as(!1),await ws()}catch(Z){const le=Z instanceof Error?Z.message:e("gitView.toast.syncActionFailed",{action:ee==="sync"?e("gitView.sync.syncChanges"):ee==="pull"?e("gitView.sync.pull"):ee});me.error(le)}finally{Q(null)}}},Vr=i.useCallback(async ee=>{if(!r)return;const j=ee.name.trim();if(!j){me.error(e("gitView.toast.remoteNameRequired"));return}if(j==="origin"){me.error(e("gitView.toast.cannotRemoveOriginRemote"));return}en(j);try{await n.removeRemote(r,{remote:j}),me.success(e("gitView.toast.removedRemote",{name:j})),await Promise.all([as(!1),un()])}catch(Z){const le=Z instanceof Error?Z.message:`Failed to remove ${j}`;me.error(le)}finally{en(null)}},[r,n,un,as,e]),Dr=async(ee={})=>{if(!r)return;if(!U.trim()){me.error(e("gitView.toast.enterCommitMessage"));return}const j=Qs.map(le=>le.path).sort();if(j.length===0){me.error(e("gitView.toast.stageFileToCommit"));return}const Z=ee.pushAfter?"commitAndPush":"commit";qe(Z);try{if(await n.createGitCommit(r,U.trim(),{files:j,stageFiles:[]}),ae(r),me.success(e("gitView.toast.commitCreated")),Ie(""),Lt(),await as(),ee.pushAfter){const le=await n.gitPush(r);me.success(e("gitView.toast.pushedToUpstream",{name:xr(le)})),Je(),await as(!1)}else await as(!1);await ws(),wt(le=>le+1)}catch(le){const We=le instanceof Error?le.message:e("gitView.toast.createCommitFailed");me.error(We)}finally{qe(null),ee.pushAfter&&Q(null)}},$r=i.useCallback(async()=>{if(!r)return;const ee=Qs.map(j=>j.path).sort();if(ee.length===0){me.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:ee.length}),ut(!0);try{const{message:j}=await Fp(r,ee),Z=j.subject?.trim()??"",le=Array.isArray(j.highlights)?j.highlights:[];if(Z){let We=Z;if(pe&&Ne.length>0){const Ye=Rw(Z,Ne);if(Ye){const{code:Tt,emoji:Rt}=Ye;!Z.startsWith(Tt)&&!Z.startsWith(Rt)&&(We=`${Tt} ${Z}`)}}Ie(We)}It(le),ss()}catch(j){console.error("[git-generation][browser] GitView generate handler failed",{message:j instanceof Error?j.message:String(j),error:j});const Z=j instanceof Error?j.message:e("gitView.toast.generateCommitMessageFailed");me.error(Z)}finally{ut(!1)}},[r,Qs,pe,Ne,ss,e]),ir=ee=>ee.reason==="attention"?`${ee.attentionReason} in progress`:ee.reason==="missing"?"worktree is missing":"worktree is invalid",Mn=async(ee,j)=>{if(!r||!S)return;const Z=Ja(I);if(Z.length>0){me.error(e("gitView.toast.cannotCreateBranch",{reason:ir(Z[0])}));return}const le=S.current??null,We=j?.name??"origin";try{await n.createBranch(r,ee,le??"HEAD"),me.success(e("gitView.toast.createdBranch",{name:ee})),await n.checkoutBranch(r,ee);let Ye=!1;try{await n.gitPush(r,{remote:We,branch:ee,options:["--set-upstream"]}),Ye=!0}catch(Tt){const Rt=Tt instanceof Error?Tt.message:`Unable to push new branch to ${We}.`;me.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Rt]})})}await as(),await ws(),Ye&&me.success(e("gitView.toast.upstreamSet",{branch:ee,remote:We}))}catch(Ye){const Tt=Ye instanceof Error?Ye.message:e("gitView.toast.createBranchFailed");throw me.error(Tt),Ye}},re=async(ee,j)=>{if(!r)return;const Z=Ja(I);if(Z.length>0){me.error(e("gitView.toast.cannotRenameBranch",{reason:ir(Z[0])}));return}try{await n.renameBranch(r,ee,j),me.success(e("gitView.toast.renamedBranch",{oldName:ee,newName:j})),await as(),await ws()}catch(le){const We=le instanceof Error?le.message:e("gitView.toast.renameBranchFailed",{oldName:ee,newName:j});me.error(We)}},nt=async ee=>{if(!r)return;const j=Ja(I);if(j.length>0){me.error(e("gitView.toast.cannotCheckout",{reason:ir(j[0])}));return}const Z=ee.replace(/^remotes\//,"");if(S?.current!==Z)try{await n.checkoutBranch(r,Z),me.success(e("gitView.toast.checkedOut",{name:Z})),await as(),await ws()}catch(le){const We=le instanceof Error?le.message:e("gitView.toast.checkoutFailed",{name:Z});me.error(We)}},ot=async ee=>{if(r){At();try{await n.setGitIdentity(r,ee.id),me.success(e("gitView.toast.appliedIdentity",{name:ee.name})),await $n()}catch(j){const Z=j instanceof Error?j.message:e("gitView.toast.applyIdentityFailed");me.error(Z)}finally{vt()}}},St=i.useMemo(()=>P?.all?P.all.filter(ee=>!ee.startsWith("remotes/")).sort():[],[P]),Yt=i.useMemo(()=>P?.all?P.all.filter(ee=>ee.startsWith("remotes/")).map(ee=>ee.replace(/^remotes\//,"")).sort():[],[P]),Ht=i.useMemo(()=>{if(Us.length>0)return Us;const ee=new Set,j=S?.tracking?.trim();j&&j.includes("/")&&ee.add(j.split("/")[0]);for(const Z of Yt){const le=Z.indexOf("/");le>0&&ee.add(Z.slice(0,le))}return ee.size===0&&hs&&ee.add("origin"),Array.from(ee).map(Z=>({name:Z,fetchUrl:hs??"",pushUrl:hs??""}))},[Us,Yt,hs,S?.tracking]),is=i.useMemo(()=>{const ee=new Set(Ht.map(We=>We.name)),j=We=>{if(!We)return"";let Ye=We.trim();if(!Ye||Ye==="HEAD")return"";if(St.includes(Ye))return Ye;Ye.startsWith("refs/heads/")&&(Ye=Ye.slice(11)),Ye.startsWith("heads/")&&(Ye=Ye.slice(6)),Ye.startsWith("remotes/")&&(Ye=Ye.slice(8));const Tt=Ye.indexOf("/");if(Tt>0){const Rt=Ye.slice(0,Tt);if(ee.has(Rt)){const ys=Ye.slice(Tt+1).trim();ys&&(Ye=ys)}}return Ye},Z=j(typeof M?.createdFromBranch=="string"?M.createdFromBranch:"");if(Z)return Z;const le=j(typeof ye=="string"?ye:"");return le||(St.includes("main")?"main":St.includes("master")?"master":St.includes("develop")?"develop":"main")},[Ht,St,ye,M?.createdFromBranch]),ps=i.useMemo(()=>Ht.map(Z=>Z.name).map(Z=>`${Z}/${is}`).find(Z=>Yt.includes(Z))??is,[is,Ht,Yt]),cs=i.useMemo(()=>{const ee=new Map;p&&ee.set(p.id,p);let j=null;if(hs)try{let Z=hs.trim();Z.startsWith("git@")&&(Z=`https://${Z.slice(4).replace(":","/")}`),Z.endsWith(".git")&&(Z=Z.slice(0,-4));const le=new URL(Z);j=le.hostname+le.pathname}catch{}for(const Z of y){if(Z.authType!=="token"){ee.set(Z.id,Z);continue}const le=Z.host;if(!le){ee.set(Z.id,Z);continue}if(!le.includes("/")){ee.set(Z.id,Z);continue}j&&j===le&&ee.set(Z.id,Z)}return Array.from(ee.values())},[y,p,hs]),Fs=i.useMemo(()=>{if(V?.userName&&V?.userEmail){const ee=y.find(j=>j.userName===V.userName&&j.userEmail===V.userEmail);return ee||(p&&p.userName===V.userName&&p.userEmail===V.userEmail?p:{id:"local-config",name:V.userName,userName:V.userName,userEmail:V.userEmail,sshKey:V.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return p??null},[V,y,p]),hn=Qs.length,or=R||xe!==null||Ke!==null,Xs=S?.current??null,yr=!!(M&&Bt&&Ft&&Jt),mn=!!(r&&Xs),Hs=!!Xs,Sn=yr&&Bt&&Ft&&M?{repoRoot:Bt,sourceBranch:Ft,worktreeMetadata:M}:null,pn=i.useMemo(()=>!mn||!r||!Xs?null:{directory:r,branch:Xs},[mn,Xs,r]);i.useEffect(()=>{if(!r||!n||!E?.all?.length||!Xs||!is||Xs===is){qt(null);return}let ee=!1;return(async()=>{try{const Z=await n.getGitLog(r,{from:is,to:"HEAD",maxCount:Xe});if(ee)return;const le=new Set((Z?.all??[]).map(Ye=>Ye.hash).filter(Ye=>typeof Ye=="string"&&Ye.length>0));if(le.size===0){qt(null);return}const We=E.all.findIndex(Ye=>!le.has(Ye.hash));if(We===0){qt(null);return}if(We===-1){qt({insertBeforeIndex:E.all.length,branchName:Xs,direction:"up"});return}qt({insertBeforeIndex:We,branchName:Xs,direction:"up"})}catch{ee||qt(null)}})(),()=>{ee=!0}},[is,Xs,r,n,E,Xe]),i.useEffect(()=>{cn(null)},[r]),i.useEffect(()=>{if(Xt!=="graph"||!r){Xt!=="graph"&&cn(null);return}let ee=!1;return tn(!0),n.getGitLog(r,{maxCount:Rn,all:!0}).then(j=>{ee||cn(j)}).catch(j=>{console.error("Failed to fetch graph log:",j)}).finally(()=>{ee||tn(!1)}),()=>{ee=!0}},[Xt,r,Rn,n]);const zn=i.useCallback((ee,j)=>{if(!r||ee.length===0)return;const Z=Array.from(new Set(ee));Zt(We=>{const Ye=new Set(We);return Z.forEach(Tt=>Ye.add(Tt)),Ye});const le=be(r,Z,j);ue.enqueue({directory:r,direction:j,paths:new Set(Z),rollback:()=>ke(r,le)}),Pe()},[r,ue,be,ke,Pe]),Tr=i.useCallback(async ee=>{if(r){ct(j=>{const Z=new Set(j);return Z.add(ee),Z});try{await n.revertGitFile(r,ee,{scope:"working"}),me.success(e("gitView.toast.revertedFile",{path:ee})),await as(!1)}catch(j){const Z=j instanceof Error?j.message:e("gitView.toast.revertFailed");me.error(Z)}finally{ct(j=>{const Z=new Set(j);return Z.delete(ee),Z})}}},[r,as,n,e]),Jn=i.useCallback(async(ee,j,Z="all")=>{if(!r||ee.length===0)return;const le=Array.from(new Set(ee));if(Et||le.some(Rt=>at.has(Rt)))return;const We=new Set(Qs.map(Rt=>Rt.path)),Ye=Z==="all"&&le.some(Rt=>We.has(Rt));j&&ge(!0),ct(Rt=>{const ys=new Set(Rt);return le.forEach(Gs=>ys.add(Gs)),ys});const Tt=[];try{if(await Promise.all(le.map(async Rt=>{try{await n.revertGitFile(r,Rt,{scope:Z})}catch(ys){Tt.push({path:Rt,message:ys instanceof Error?ys.message:e("gitView.toast.revertFailed")})}})),Ye&&Tt.length<le.length&&ae(r),await as(!1),Tt.length===0)me.success(le.length===1?e("gitView.toast.revertedFilesSingle",{count:le.length}):e("gitView.toast.revertedFilesPlural",{count:le.length}));else if(Tt.length===le.length)me.error(Tt[0]?.message||e("gitView.toast.revertFailed"));else{const Rt=le.length-Tt.length;me.warning(Rt===1?e("gitView.toast.revertedSomeSingle",{success:Rt,failed:Tt.length}):e("gitView.toast.revertedSomePlural",{success:Rt,failed:Tt.length}))}}finally{ct(Rt=>{const ys=new Set(Rt);return le.forEach(Gs=>ys.delete(Gs)),ys}),j&&ge(!1)}},[ae,r,n,Et,as,at,Qs,e]),zr=i.useCallback(async ee=>{await Jn(ee,!0)},[Jn]),Di=i.useCallback(async ee=>{await Jn(ee,!1,"working")},[Jn]),Wn=i.useCallback((ee,j)=>{if(r&&!ve){J(r,ee,j);return}H(ee,j),ve&&q(!1)},[r,ve,H,J,q]),oi=i.useCallback(()=>He(!0),[]),ai=i.useMemo(()=>{const ee=[];return Qs.length>0&&ee.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:Qs,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:j=>e("gitView.changes.unstageFileAria",{path:j}),onActionFile:j=>{zn([j],"unstage")},onActionAll:j=>{zn(j,"unstage")},onViewDiff:j=>Wn(j,!0),onRevertFile:Tr,showRevertActions:!1,accent:!0}),rr.length>0&&ee.push({id:"unstaged",title:e("gitView.changes.title"),entries:rr,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:j=>e("gitView.changes.stageFileAria",{path:j}),onActionFile:j=>{zn([j],"stage")},onActionAll:j=>{zn(j,"stage")},onViewDiff:j=>Wn(j,!1),onRevertFile:Tr}),ee},[Tr,Wn,zn,Qs,e,rr]),Pr=i.useCallback(ee=>{if(ee.length===0)return;const j=ee.map(Z=>Z.trim()).filter(Boolean);if(j.length===0){Lt();return}Ie(Z=>{const le=Z.trim(),We=le.length>0?`
11
-
12
- `:"";return`${le}${We}${j.join(`
13
- `)}`.trim()}),Lt()},[Lt]),Ti=i.useCallback((ee,j)=>{const Z=j||ee;Ie(le=>{const We=le.trimStart();return We.startsWith(ee)||j&&We.startsWith(j)?le:`${Z.endsWith(" ")?Z:`${Z} `}${le}`.trimStart()}),As(""),X(!1)},[]),ar=i.useCallback(ee=>{const j=ee instanceof Error?ee.message.toLowerCase():"";return j.includes("uncommitted changes")||j.includes("local changes")||j.includes("your local changes would be overwritten")||j.includes("please commit your changes or stash them")||j.includes("cannot rebase: you have unstaged changes")||j.includes("error: cannot pull with rebase")},[]),gn=i.useCallback((ee,j)=>{Ae(Z=>[...Z,{message:ee,status:j,timestamp:Date.now()}])},[]),Qt=i.useCallback((ee,j)=>{Ae(Z=>{if(Z.length===0)return Z;const le=[...Z];return le[le.length-1]={...le[le.length-1],status:ee,...j?{message:j}:{}},le})},[]),lr=i.useCallback(()=>{Ae([])},[]),nn=i.useCallback(()=>{Ae([]),et(null)},[]),cr=i.useCallback(ee=>{const j=ee.trim(),Z=new Set(Ht.map(We=>We.name)),le=j.indexOf("/");if(le>0){const We=j.slice(0,le),Ye=j.slice(le+1);if(Z.has(We)&&Ye)return{branch:j,remote:We,remoteBranch:Ye}}for(const We of Ht){const Ye=`${We.name}/${j}`;if(Yt.includes(Ye))return{branch:Ye,remote:We.name,remoteBranch:j}}return{branch:j,remote:null,remoteBranch:null}},[Ht,Yt]),Fn=i.useCallback(async ee=>{if(!r)return;et("merge"),lr();const j=S?.current,Z=cr(ee);try{Z.remote&&Z.remoteBranch&&(gn(`Fetching ${Z.remote}/${Z.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Z.remote,branch:Z.remoteBranch}),Qt("done",`Fetched ${Z.remote}/${Z.remoteBranch}`)),gn(`Merging ${Z.branch} into ${j}...`,"running");const le=await n.merge(r,{branch:Z.branch});le.conflict?(Qt("error","Merge conflicts detected"),Vt(le.conflictFiles??[]),rs("merge"),rt(!0),Es(r,le.conflictFiles??[],"merge")):(Qt("done",`Merged ${Z.branch} into ${j}`),js(),gn("Refreshing repository status...","running"),await as(),await ws(),Qt("done","Repository status updated"))}catch(le){if(ar(le))Qt("error","Uncommitted changes detected"),Br("merge"),_r(Z.branch),En(!0);else{const We=le instanceof Error?le.message:`Failed to merge ${Z.branch}`;Qt("error",We)}}},[r,n,S,cr,as,ws,ar,Es,js,gn,Qt,lr]),wr=i.useCallback(async ee=>{if(!r)return;et("rebase"),lr();const j=S?.current,Z=cr(ee);try{Z.remote&&Z.remoteBranch&&(gn(`Fetching ${Z.remote}/${Z.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Z.remote,branch:Z.remoteBranch}),Qt("done",`Fetched ${Z.remote}/${Z.remoteBranch}`)),gn(`Rebasing ${j} onto ${Z.branch}...`,"running");const le=await n.rebase(r,{onto:Z.branch});le.conflict?(Qt("error","Rebase conflicts detected"),Vt(le.conflictFiles??[]),rs("rebase"),rt(!0),Es(r,le.conflictFiles??[],"rebase")):(Qt("done",`Rebased ${j} onto ${Z.branch}`),js(),gn("Refreshing repository status...","running"),await as(),await ws(),Qt("done","Repository status updated"))}catch(le){if(ar(le))Qt("error","Uncommitted changes detected"),Br("rebase"),_r(Z.branch),En(!0);else{const We=le instanceof Error?le.message:`Failed to rebase onto ${Z.branch}`;Qt("error",We)}}},[r,n,S,cr,as,ws,ar,Es,js,gn,Qt,lr]),Ls=i.useCallback(async()=>{if(r)try{ns==="merge"?(await n.abortMerge(r),me.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),me.success(e("gitView.toast.rebaseAborted"))),js(),await as(),await ws()}catch(ee){const j=ee instanceof Error?ee.message:`Failed to abort ${ns}`;me.error(j)}},[r,n,ns,as,ws,js,e]),no=i.useMemo(()=>S?.files?S.files.some(ee=>ee.index==="U"||ee.working_dir==="U"||ee.index==="A"&&ee.working_dir==="A"||ee.index==="D"&&ee.working_dir==="D"):!1,[S?.files]),Pi=i.useCallback(async()=>{if(r)try{const ee=!!S?.mergeInProgress?.head,j=!!(S?.rebaseInProgress?.headName||S?.rebaseInProgress?.onto);if(ee){const Z=await n.continueMerge(r);Z.conflict?(Vt(Z.conflictFiles??[]),rs("merge"),rt(!0),Es(r,Z.conflictFiles??[],"merge"),me.error(e("gitView.toast.mergeConflictsDetected"))):(js(),me.success(e("gitView.toast.mergeCompleted")),await as(),await ws())}else if(j){const Z=await n.continueRebase(r);Z.conflict?(Vt(Z.conflictFiles??[]),rs("rebase"),rt(!0),Es(r,Z.conflictFiles??[],"rebase"),me.error(e("gitView.toast.rebaseConflictsDetected"))):(js(),me.success(e("gitView.toast.rebaseStepCompleted")),await as(),await ws())}}catch(ee){const j=ee instanceof Error?ee.message:e("gitView.toast.continueOperationFailed");me.error(j)}},[r,n,S,as,ws,Es,js,e]),Qn=i.useCallback(async()=>{if(r)try{!!S?.mergeInProgress?.head?(await n.abortMerge(r),me.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),me.success(e("gitView.toast.rebaseAborted"))),js(),await as(),await ws()}catch(ee){const j=ee instanceof Error?ee.message:e("gitView.toast.abortOperationFailed");me.error(j)}},[r,n,S,as,ws,js,e]),li=i.useCallback(()=>{if(!r)return;const j=!!S?.mergeInProgress?.head?"merge":"rebase",Z=S?.files?.filter(le=>le.index==="U"||le.working_dir==="U").map(le=>le.path)??[];Z.length>0&&Vt(Z),rs(j),rt(!0)},[r,S]),rn=i.useCallback(async ee=>{if(!r)return;const j=S?.current,Z=sr,le=Vn,We=(S?.files??[]).some(lu);try{await n.stash(r,{message:`Auto-stash before ${Z} with ${le}`,includeUntracked:!0}),We&&ae(r)}catch(Rt){const ys=Rt instanceof Error?Rt.message:"Failed to stash changes";me.error(ys);return}let Ye=!1,Tt=!1;try{if(Z==="merge"){const Rt=await n.merge(r,{branch:le});Rt.conflict?(Tt=!0,Vt(Rt.conflictFiles??[]),rs("merge"),rt(!0)):(Ye=!0,me.success(e("gitView.toast.mergedIntoBranch",{branch:le,currentBranch:j||""})))}else{const Rt=await n.rebase(r,{onto:le});Rt.conflict?(Tt=!0,Vt(Rt.conflictFiles??[]),rs("rebase"),rt(!0)):(Ye=!0,me.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:j||"",branch:le})))}if(ee&&Ye)try{await n.stashPop(r),ae(r),me.success(e("gitView.toast.stashedRestored"))}catch(Rt){const ys=Rt instanceof Error?Rt.message:e("gitView.toast.restoreStashFailed");me.error(ys)}else ee&&Tt&&me.info(e("gitView.toast.restoreStashManually"));await as(),await ws()}catch(Rt){if(ee)try{await n.stashPop(r),ae(r)}catch{}throw Rt}},[ae,r,n,S,sr,Vn,as,ws,e]),Ln=i.useCallback(ee=>{lt(ee),r&&(Y(r,ee),ne(r,n,ee))},[r,ne,n,Y]),Wr=i.useCallback(ee=>{jn(ee)},[]),Ii=i.useCallback(()=>{Rs(null),r&&(ie(r,n),oe(r,n),ne(r,n,Xe))},[r,ie,oe,ne,Xe,n]),Ur=i.useCallback(ee=>{if(ee.conflict){if(ee.operation==="cherry-pick"||ee.operation==="revert"){me.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:ee.conflictFiles?.join(", ")??"unknown files"})}),r&&(ie(r,n),oe(r,n),ne(r,n,Xe));return}Vt(ee.conflictFiles??[]),rs(ee.operation),rt(!0),r&&Es(r,ee.conflictFiles??[],ee.operation)}},[e,Vt,rs,rt,Es,r,ie,oe,ne,Xe,n]);return r?A===null||A===!0&&!S?s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):A===!1?G?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(T,{name:"loader-4",className:"mb-3 size-6 animate-spin text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.worktreeSetupInProgress")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.worktreeSetupDescription")})]}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(T,{name:"git-branch",className:"mb-3 size-6 text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.notGitRepository")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.notGitRepositoryDescription")}),D.includes("open-without-worktree-features")?s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:e("gitView.empty.worktreeFeaturesUnavailable")}):null]}):s.jsxs("div",{className:Te("flex h-full flex-col overflow-hidden"),children:[s.jsx(gx,{status:S,localBranches:St,remoteBranches:Yt,branchInfo:P?.branches,syncAction:xe,remotes:Ht,onFetch:ee=>br("fetch",ee),onSync:ee=>br("sync",ee),onRemoveRemote:Vr,removingRemoteName:Yn,onCheckoutBranch:nt,onCreateBranch:Mn,onRenameBranch:re,activeIdentityProfile:Fs,availableIdentities:cs,onSelectIdentity:ot,isApplyingIdentity:bt,isWorktreeMode:!!M,onOpenHistory:()=>Rs("history"),onOpenGraph:()=>Rs("graph"),onOpenStashes:oi,actionTabItems:In,activeActionTab:Ds,onSelectActionTab:ee=>Ys(ee)}),r&&(S?.mergeInProgress?.head||S?.rebaseInProgress?.headName||S?.rebaseInProgress?.onto)&&s.jsx(ww,{mergeInProgress:S?.mergeInProgress,rebaseInProgress:S?.rebaseInProgress,onContinue:Pi,onAbort:Qn,onResolveWithAI:li,hasUnresolvedConflicts:no,isLoading:R}),s.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:s.jsx("div",{className:"h-full min-h-0 flex flex-col",children:s.jsx("div",{className:Te("min-w-0 min-h-0 h-full flex flex-col"),children:s.jsxs(An,{as:Ia,ref:L,outerClassName:"flex-1 min-h-0",className:Te("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[Ds==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(sn?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(xx,{groups:ai,diffStats:S?.diffStats,revertingPaths:at,isRevertingAll:Et,onVisiblePathsChange:Ve,onRevertAll:zr,onRevertDirectory:Di,headerBackgroundClassName:"bg-background"})}),s.jsx(bx,{stagedCount:hn,commitMessage:U,onCommitMessageChange:Ie,generatedHighlights:Mt,onInsertHighlights:Pr,onGenerateMessage:$r,isGeneratingMessage:tt,onCommit:()=>Dr({pushAfter:!1}),onCommitAndPush:()=>Dr({pushAfter:!0}),commitAction:Ke,hasPendingIndexMutation:zt,gitmojiEnabled:pe,onOpenGitmojiPicker:()=>X(!0)})]}):s.jsx(Sy,{onOpenStashes:()=>He(!0)})}):null,Ds==="branch"?s.jsx("div",{className:"space-y-4",children:Hs?s.jsxs(s.Fragment,{children:[s.jsx(vw,{mode:"inline",currentBranch:S?.current,localBranches:St,remoteBranches:Yt,defaultTargetBranch:ps,onMerge:Fn,onRebase:wr,disabled:or,isOperating:je!==null,operationLogs:ft,onOperationComplete:nn}),Sn?s.jsx(vy,{repoRoot:Sn.repoRoot,sourceBranch:Sn.sourceBranch,worktreeMetadata:Sn.worktreeMetadata,localBranches:St,defaultTargetBranch:es,refreshKey:st,onRefresh:()=>{r&&(ie(r,n),oe(r,n),ne(r,n,Xe))}},Sn.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,Ds==="pr"?s.jsx("div",{className:"space-y-4",children:pn?s.jsx(uw,{directory:pn.directory,branch:pn.branch,baseBranch:is,trackingBranch:S?.tracking??void 0,remotes:Us,remoteBranches:Yt,onGeneratedDescription:ss}):s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:e("gitView.pullRequest.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:e("gitView.pullRequest.createHint")})]})}):null]})})})}),s.jsx(Cs,{open:Xt!==null,onOpenChange:ee=>{ee||Rs(null)},children:s.jsxs(ks,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(Ms,{children:[s.jsx(Ps,{children:e(Xt==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(qs,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(Ry,{mode:Xt==="graph"?"graph":"history",log:Xt==="graph"?ts??E:E,isLogLoading:Xt==="graph"&&_s||B,logMaxCount:Xt==="graph"?Rn:Xe,onLogMaxCountChange:Xt==="graph"?Wr:Ln,expandedCommitHashes:Pt,onToggleCommit:nr,commitFilesMap:yt,loadingCommitHashes:Dt,onCopyHash:Js,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:Xt==="graph"?null:gt,onConflict:Xt==="graph"?Ur:void 0,onActionSuccess:Xt==="graph"?Ii:void 0})})]})}),s.jsx(jy,{open:$e,onOpenChange:He,directory:r,hasUncommittedChanges:(S?.files?.length??0)>0,hasStagedChanges:Qs.length>0,uncommittedFileCount:S?.files?.length??0,onChanged:async ee=>{r&&ee?.affectsIndex&&ae(r),await as(!1),await ws()}}),s.jsx(Cs,{open:Le,onOpenChange:X,children:s.jsxs(ks,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(Ms,{className:"px-4 pt-4",children:s.jsx(Ps,{children:e("gitView.gitmoji.title")})}),s.jsxs(Ca,{className:"h-[420px]",children:[s.jsx(Aa,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:Is,onValueChange:As}),s.jsxs(Da,{children:[s.jsx(Ta,{children:e("gitView.gitmoji.empty")}),s.jsx(ti,{children:(Ne.length===0?[]:Ne.filter(ee=>{const j=Is.trim().toLowerCase();return j?ee.emoji.includes(j)||ee.code.toLowerCase().includes(j)||ee.description.toLowerCase().includes(j):!0})).map(ee=>s.jsxs(ni,{onSelect:()=>Ti(ee.emoji,ee.code),children:[s.jsx("span",{className:"text-lg",children:ee.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:ee.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:ee.description})]},ee.code))})]})]})]})}),r&&s.jsx(mw,{open:xt,onOpenChange:rt,conflictFiles:_t,directory:r,operation:ns,onAbort:Ls,onClearState:js}),s.jsx(yw,{open:Or,onOpenChange:En,operation:sr,targetBranch:Vn,onConfirm:rn})]}):s.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:e("gitView.empty.selectSessionOrDirectory")})})},zl=5e3,Lw=(t,e)=>{if(!t)return 1;let n=1;for(let r=0;r<t.length;r+=1)if(t.charCodeAt(r)===10&&(n+=1,n>e))return n;return n},ml=(t,e)=>Op(Bp.getState().dictionary,t,e),Ow=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("file not found")||n.includes("not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")?"missing":"unreadable"},Bw=async(t,e)=>{if(t.readFile)return(await t.readFile(e,{optional:!0})).content??"";const n=new URLSearchParams({path:e,optional:"true"}),r=await gs(`/api/fs/read?${n.toString()}`,{cache:"no-store"});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to read file")}return r.text()},Cc=async(t,e)=>{try{const n=await Bw(t,e);return Lw(n,zl)>zl?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:Ow(n)}}},Ac=t=>{if(t==="too-large"){const e=zl.toLocaleString(Ki());return ml("contextFileOpen.failure.tooLarge",{count:e})}return ml(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},_w=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),wn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},pf=(t,e)=>{const n=wn(e),r=wn(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},Vw=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),$w=new Set(["node_modules"]),zw=t=>$w.has(t),Ww=t=>{const e=wn(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},Uw=8,Sr=new Map,Hw=t=>{const e=Sr.get(t);return e?(e.touchedAt=Date.now(),Sr.delete(t),Sr.set(t,e),e):null},fl=t=>{const e=Sr.get(t);if(e)return e.touchedAt=Date.now(),e;if(Sr.size>=Uw){const r=Sr.keys().next().value;r!==void 0&&Sr.delete(r)}const n={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Sr.set(t,n),n},Gw=t=>{Sr.delete(t)},gf=(t,e)=>s.jsx(Mr,{filePath:t,extension:e}),Kw=t=>{const e=ht.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},qw=t=>{const e=ht.c(73),{node:n,root:r,isExpanded:o,isActive:a,status:c,badge:l,permissions:d,downloadFile:m,onSelect:f,onToggle:u,onRevealPath:g,onOpenDialog:b}=t,{t:h}=jt(),x=n.type==="directory",{canRename:y,canCreateFile:p,canCreateFolder:C,canDelete:v,canReveal:k}=d,[w,A]=i.useState(!1),[S,I]=i.useState(!1);let D;e[0]!==p||e[1]!==C||e[2]!==v||e[3]!==y||e[4]!==k?(D=H=>{!y&&!p&&!C&&!v&&!k||(H?.preventDefault(),I(!0))},e[0]=p,e[1]=C,e[2]=v,e[3]=y,e[4]=k,e[5]=D):D=e[5];const N=D;let M;e[6]!==x||e[7]!==n||e[8]!==f||e[9]!==u?(M=()=>{x?u(n.path):f(n)},e[6]=x,e[7]=n,e[8]=f,e[9]=u,e[10]=M):M=e[10];const P=M;let E;e[11]===Symbol.for("react.memo_cache_sentinel")?(E=H=>{H.stopPropagation(),I(!1),A(!0)},e[11]=E):E=e[11];const V=E;let R;e[12]!==p||e[13]!==C||e[14]!==v||e[15]!==y||e[16]!==k||e[17]!==m||e[18]!==x||e[19]!==n||e[20]!==b||e[21]!==g||e[22]!==h?(R=H=>{const{Item:q,Separator:ce}=H;return s.jsxs(s.Fragment,{children:[y&&s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),b("rename",n)},children:[s.jsx(T,{name:"edit",className:"mr-2 h-4 w-4"})," ",h("sidebarFilesTree.menu.rename")]}),s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),tr(n.path).then(De=>{if(De.ok){me.success(h("sidebarFilesTree.toast.pathCopied"));return}me.error(h("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(T,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",h("sidebarFilesTree.menu.copyPath")]}),!x&&m&&s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),m(n.path).catch(De=>{console.error("Download failed:",De),me.error(h("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(T,{name:"download",className:"mr-2 h-4 w-4"})," ",h("sidebarFilesTree.menu.save")]}),k&&s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),g(n.path)},children:[s.jsx(T,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",h(mc())]}),x&&(p||C)&&s.jsxs(s.Fragment,{children:[s.jsx(ce,{}),p&&s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),b("createFile",n)},children:[s.jsx(T,{name:"file-add",className:"mr-2 h-4 w-4"})," ",h("sidebarFilesTree.menu.newFile")]}),C&&s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),b("createFolder",n)},children:[s.jsx(T,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",h("sidebarFilesTree.menu.newFolder")]})]}),v&&s.jsxs(s.Fragment,{children:[s.jsx(ce,{}),s.jsxs(q,{onClick:fe=>{fe.stopPropagation(),b("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(T,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",h("sidebarFilesTree.menu.delete")]})]})]})},e[12]=p,e[13]=C,e[14]=v,e[15]=y,e[16]=k,e[17]=m,e[18]=x,e[19]=n,e[20]=b,e[21]=g,e[22]=h,e[23]=R):R=e[23];const B=R;let O;e[24]!==n.path||e[25]!==r?(O=H=>{const q=pf(r,n.path);!q||q==="."||(H.dataTransfer.setData("application/x-openchamber-file-path",q),H.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=O):O=e[26];const F=O;let _;e[27]!==N?(_=s.jsx("div",{className:"group relative flex items-center",onContextMenu:N}),e[27]=N,e[28]=_):_=e[28];const ie=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let oe;e[29]!==ie?(oe=Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",ie,"cursor-grab active:cursor-grabbing"),e[29]=ie,e[30]=oe):oe=e[30];let ne;e[31]!==x||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(ne=x?o?s.jsx(T,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(T,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):gf(n.path,n.extension),e[31]=x,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=ne):ne=e[35];let Y;e[36]!==n.name||e[37]!==n.path?(Y=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:n.path,children:n.name}),e[36]=n.name,e[37]=n.path,e[38]=Y):Y=e[38];let te;e[39]!==x||e[40]!==c?(te=!x&&c&&s.jsx(Kw,{status:c}),e[39]=x,e[40]=c,e[41]=te):te=e[41];let de;e[42]!==l||e[43]!==x?(de=x&&l&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[l.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",l.modified]}),l.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",l.added]})]}),e[42]=l,e[43]=x,e[44]=de):de=e[44];let be;e[45]!==N||e[46]!==F||e[47]!==P||e[48]!==Y||e[49]!==te||e[50]!==de||e[51]!==oe||e[52]!==ne?(be=s.jsxs("button",{type:"button",onClick:P,onContextMenu:N,draggable:!0,onDragStart:F,className:oe,children:[ne,Y,te,de]}),e[45]=N,e[46]=F,e[47]=P,e[48]=Y,e[49]=te,e[50]=de,e[51]=oe,e[52]=ne,e[53]=be):be=e[53];let ke;e[54]!==p||e[55]!==C||e[56]!==v||e[57]!==y||e[58]!==k||e[59]!==w||e[60]!==B||e[61]!==h?(ke=(y||p||C||v||k)&&s.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:s.jsxs(Ws,{open:w,onOpenChange:A,children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx($s,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:V,title:h("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":h("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(T,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:h("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(zs,{align:"end",side:"bottom",onCloseAutoFocus:()=>A(!1),children:B({Item:ls,Separator:Cr})})]})}),e[54]=p,e[55]=C,e[56]=v,e[57]=y,e[58]=k,e[59]=w,e[60]=B,e[61]=h,e[62]=ke):ke=e[62];let ae;e[63]!==be||e[64]!==ke||e[65]!==_?(ae=s.jsxs(wc,{render:_,children:[be,ke]}),e[63]=be,e[64]=ke,e[65]=_,e[66]=ae):ae=e[66];let ve;e[67]!==B?(ve=s.jsx(bc,{className:"min-w-[180px]",children:B({Item:yc,Separator:Jm})}),e[67]=B,e[68]=ve):ve=e[68];let J;return e[69]!==S||e[70]!==ae||e[71]!==ve?(J=s.jsxs(vc,{open:S,onOpenChange:I,children:[ae,ve]}),e[69]=S,e[70]=ae,e[71]=ve,e[72]=J):J=e[72],J},Yw=(t,e)=>t.node===e.node&&t.root===e.root&&t.isExpanded===e.isExpanded&&t.isActive===e.isActive&&t.status===e.status&&t.badge===e.badge&&t.permissions===e.permissions&&t.downloadFile===e.downloadFile&&t.onSelect===e.onSelect&&t.onToggle===e.onToggle&&t.onRevealPath===e.onRevealPath&&t.onOpenDialog===e.onOpenDialog,Jw=i.memo(qw,Yw),Qw=()=>{const{t}=jt(),{files:e}=_n(),n=ii()??"",r=wn(n.trim()),o=hm(),a=pm(),c=tc(G=>G.searchFiles),l=Me(G=>G.openContextFile),d=Ra(n),[m,f]=i.useState(""),u=Ma(m,200),g=i.useRef(null),[b,h]=i.useState([]),[x,y]=i.useState(!1),[p,C]=i.useState({}),[v,k]=i.useState({}),w=i.useRef(new Set),A=i.useRef(new Set);i.useEffect(()=>{if(!r){C({}),k({}),w.current=new Set;return}const G=Hw(r);G?(C({...G.childrenByDir}),k({...G.loadErrorsByDir}),w.current=new Set(G.loadedDirs)):(C({}),k({}),w.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const G=fl(r);G.childrenByDir=p},[r,p]),i.useEffect(()=>{if(!r)return;const G=fl(r);G.loadErrorsByDir=v},[r,v]),i.useEffect(()=>{if(!r)return;const G=fl(r);G.loadedDirs=new Set(w.current)},[r,p,v]),i.useEffect(()=>()=>{if(!r)return;const G=Sr.get(r);G&&G.loadedDirs.size===0&&Object.keys(G.childrenByDir).length===0&&Gw(r)},[r]);const S=i.useMemo(()=>[],[]),I=i.useMemo(()=>[],[]),D=on(G=>r?G.byRoot[r]?.expandedPaths??S:S),N=on(G=>r?G.byRoot[r]?.selectedPath??null:null),M=on(G=>G.setSelectedPath),P=on(G=>G.addOpenPath),E=on(G=>G.removeOpenPathsByPrefix),V=on(G=>G.toggleExpandedPath),R=Me(G=>r?G.contextPanelByDirectory[r]?.tabs??I:I),B=i.useMemo(()=>new Set(R.map(G=>G.mode==="file"?G.targetPath:null).filter(G=>typeof G=="string"&&G.length>0).map(G=>wn(G))),[R]),[O,F]=i.useState(null),[_,ie]=i.useState(null),[oe,ne]=i.useState(""),[Y,te]=i.useState(!1),de=!!e.writeFile,be=!!e.createDirectory,ke=!!e.rename,ae=!!e.delete,ve=!!e.revealPath,J=i.useMemo(()=>({canRename:ke,canCreateFile:de,canCreateFolder:be,canDelete:ae,canReveal:ve}),[ke,de,be,ae,ve]),H=i.useCallback(G=>{e.revealPath&&e.revealPath(G).catch(()=>{me.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),q=i.useCallback((G,$)=>{F(G),ie($),ne(G==="rename"&&$.name||""),te(!1)},[]),ce=i.useCallback((G,$)=>{const pe=$.filter(ye=>ye&&typeof ye.name=="string"&&ye.name.length>0).filter(ye=>o||!ye.name.startsWith(".")).filter(ye=>a||!zw(ye.name)).map(ye=>{const z=ye.name,Ne=wn(ye.path||""),U=Ne?Vw(Ne)?Ne:wn(`${G}/${Ne}`):wn(`${G}/${z}`),Ie=ye.isDirectory?"directory":"file",_e=Ie==="file"&&z.includes(".")?z.split(".").pop()?.toLowerCase():void 0;return{name:z,path:U,type:Ie,extension:_e}});return _w(pe)},[a,o]),fe=i.useCallback(async(G,$)=>{const pe=wn(G.trim());if(!pe||w.current.has(pe)||A.current.has(pe))return;A.current=new Set(A.current),A.current.add(pe);const ye=e.listDirectory?e.listDirectory(pe).then(z=>z.entries.map(Ne=>({name:Ne.name,path:Ne.path,isDirectory:Ne.isDirectory}))):Cn.listLocalDirectory(pe).then(z=>z.map(Ne=>({name:Ne.name,path:Ne.path,isDirectory:Ne.isDirectory})));try{const z=await ye;if($?.())return;const Ne=ce(pe,z);w.current=new Set(w.current),w.current.add(pe),k(U=>{if(!U[pe])return U;const Ie={...U};return delete Ie[pe],Ie}),C(U=>({...U,[pe]:Ne}))}catch(z){if($?.())return;const Ne=z instanceof Error?z.message:String(z??"");console.error("Failed to load sidebar directory:",z),k(U=>({...U,[pe]:Ne}))}finally{A.current=new Set(A.current),A.current.delete(pe)}},[e,ce]),De=i.useCallback(async()=>{r&&(w.current=new Set,A.current=new Set,k({}),C(G=>Object.keys(G).length===0?G:{}),await fe(r))},[fe,r]),Re=i.useCallback(async G=>{if(!G){await De();return}const $=wn(G);w.current=new Set(w.current),w.current.delete($),A.current=new Set(A.current),A.current.delete($),await fe($)},[fe,De]);i.useEffect(()=>{r&&(w.current=new Set,A.current=new Set,k({}),C(G=>Object.keys(G).length===0?G:{}),fe(r))},[fe,r,o,a]),i.useEffect(()=>{if(!r||D.length===0)return;const G=D.map(ye=>wn(ye)).filter(ye=>!!ye&&ye!==r&&ye.startsWith(`${r}/`)&&!w.current.has(ye)&&!A.current.has(ye)).sort((ye,z)=>ye.split("/").length-z.split("/").length);if(G.length===0)return;let $=!1;const pe=()=>$;return(async()=>{for(let ye=0;ye<G.length&&!$;ye+=3){const z=G.slice(ye,ye+3);await Promise.all(z.map(Ne=>fe(Ne,pe)))}})(),()=>{$=!0}},[D,fe,r]),i.useEffect(()=>{if(!n){h([]),y(!1);return}const G=u.trim();if(!G){h([]),y(!1);return}let $=!1;return y(!0),c(n,G,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(pe=>{if($)return;const z=pe.filter(Ne=>a||!Ww(Ne.path)).map(Ne=>({name:Ne.name,path:wn(Ne.path),type:"file",extension:Ne.extension,relativePath:Ne.relativePath}));h(z)}).catch(()=>{$||h([])}).finally(()=>{$||y(!1)}),()=>{$=!0}},[n,u,c,o,a]);const Fe=i.useMemo(()=>{const G=new Map;if(!d?.files)return G;for(const $ of d.files)$.index==="A"||$.working_dir==="?"?G.set($.path,"git-added"):$.index==="D"?G.set($.path,"git-deleted"):($.index==="M"||$.working_dir==="M")&&G.set($.path,"git-modified");return G},[d]),Oe=i.useMemo(()=>{const G=new Map;if(!d?.files||!r)return G;for(const $ of d.files){const pe=$.index==="M"||$.working_dir==="M",ye=$.index==="A"||$.working_dir==="?";if(!pe&&!ye)continue;const z=$.path.split("/");if(z.length<=1)continue;let Ne=r;for(let U=0;U<z.length-1;U++){Ne=`${Ne}/${z[U]}`;let Ie=G.get(Ne);Ie||(Ie={modified:0,added:0},G.set(Ne,Ie)),pe&&Ie.modified++,ye&&Ie.added++}}return G},[d,r]),Ee=i.useCallback(G=>{if(B.has(G))return"open";if(Fe.size===0)return null;const $=G.startsWith(r+"/")?G.slice(r.length+1):G;return Fe.get($)??null},[B,Fe,r]),we=i.useCallback(G=>{if(Oe.size===0)return null;const $=Oe.get(G);return $&&$.modified+$.added>0?$:null},[Oe]),Pe=i.useCallback(async G=>{if(!r)return;const $=await Cc(e,G.path);if(!$.ok){me.error(Ac($.reason));return}M(r,G.path),P(r,G.path),l(r,G.path)},[P,e,l,r,M]),Se=i.useCallback(async G=>{const $=wn(G);r&&(V(r,$),w.current.has($)||await fe($))},[fe,r,V]),ue=i.useCallback(async G=>{if(G?.preventDefault(),!_||!O)return;te(!0);const $=()=>te(!1),pe=()=>F(null);if(O==="createFile"){if(!oe.trim()){me.error(t("sidebarFilesTree.toast.filenameRequired")),$();return}if(!e.writeFile){me.error(t("sidebarFilesTree.toast.writeNotSupported")),$();return}const ye=_.path,z=ye?`${ye}/`:"",Ne=wn(`${z}${oe.trim()}`);await e.writeFile(Ne,"").then(async U=>{U.success&&(me.success(t("sidebarFilesTree.toast.fileCreated")),await Re(ye)),pe()}).catch(()=>me.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}if(O==="createFolder"){if(!oe.trim()){me.error(t("sidebarFilesTree.toast.folderNameRequired")),$();return}const ye=_.path,z=ye?`${ye}/`:"",Ne=wn(`${z}${oe.trim()}`);await e.createDirectory(Ne).then(async U=>{U.success&&(me.success(t("sidebarFilesTree.toast.folderCreated")),await Re(ye)),pe()}).catch(()=>me.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}if(O==="rename"){if(!oe.trim()){me.error(t("sidebarFilesTree.toast.nameRequired")),$();return}if(!e.rename){me.error(t("sidebarFilesTree.toast.renameNotSupported")),$();return}const ye=_.path,z=ye.split("/").slice(0,-1).join("/"),Ne=z?`${z}/`:"",U=wn(`${Ne}${oe.trim()}`);await e.rename(ye,U).then(async Ie=>{Ie.success&&(me.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await Re(z),r&&E(r,ye),(N===ye||N&&N.startsWith(`${ye}/`))&&M(r,null)),pe()}).catch(()=>me.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}if(O==="delete"){if(!e.delete){me.error(t("sidebarFilesTree.toast.deleteNotSupported")),$();return}const ye=_.path,z=ye.split("/").slice(0,-1).join("/");await e.delete(ye).then(async Ne=>{Ne.success&&(me.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await Re(z),r&&E(r,ye),(N===ye||N&&N.startsWith(ye+"/"))&&M(r,null)),pe()}).catch(()=>me.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}$()},[O,_,oe,e,Re,E,r,N,M,t]);function K(G,$){const pe=p[G]??[];return pe.map((ye,z)=>{const Ne=ye.type==="directory",U=Ne&&D.includes(ye.path),Ie=N===ye.path,_e=z===pe.length-1;return s.jsxs("li",{className:"relative",children:[$>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),_e&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),s.jsx(Jw,{node:ye,root:r,isExpanded:U,isActive:Ie,status:Ne?void 0:Ee(ye.path),badge:Ne?we(ye.path):void 0,permissions:J,downloadFile:e.downloadFile,onSelect:Pe,onToggle:Se,onRevealPath:H,onOpenDialog:q}),Ne&&U&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[v[ye.path]?s.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:v[ye.path],children:v[ye.path]}),s.jsxs(ze,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Re(ye.path)},children:[s.jsx(T,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,K(ye.path,$+1)]})]},ye.path)})}const he=!!(r&&p[r]),se=r?v[r]:null;return s.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(T,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(ln,{ref:g,value:m,onChange:G=>f(G.target.value),placeholder:t("sidebarFilesTree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),m.trim().length>0?s.jsx("button",{type:"button","aria-label":t("sidebarFilesTree.search.clearAria"),className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{f(""),g.current?.focus()},children:s.jsx(T,{name:"close",className:"h-4 w-4"})}):null]}),de&&s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>q("createFile",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFileTitle"),"aria-label":t("sidebarFilesTree.actions.newFileTitle"),children:s.jsx(T,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),be&&s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>q("createFolder",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFolderTitle"),"aria-label":t("sidebarFilesTree.actions.newFolderTitle"),children:s.jsx(T,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{De()},className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.refreshTitle"),"aria-label":t("sidebarFilesTree.actions.refreshTitle"),children:s.jsx(T,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx(An,{outerClassName:"flex-1 min-h-0",className:"p-2",children:s.jsx("ul",{className:"flex flex-col",children:x?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):b.length>0?b.map(G=>{const $=N===G.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>Pe(G),draggable:!0,onDragStart:pe=>{const ye=G.relativePath||pf(r??"",G.path);!ye||ye==="."||(pe.dataTransfer.setData("application/x-openchamber-file-path",ye),pe.dataTransfer.effectAllowed="copy")},className:Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors cursor-grab active:cursor-grabbing",$?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:G.path,children:[gf(G.path,G.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:G.relativePath??G.path})]})},G.path)}):se?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{children:se}),s.jsxs(ze,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{De()},children:[s.jsx(T,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):he&&r?K(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx(Cs,{open:!!O,onOpenChange:G=>!G&&F(null),children:s.jsxs(ks,{children:[s.jsxs(Ms,{children:[s.jsxs(Ps,{children:[O==="createFile"&&t("sidebarFilesTree.dialog.createFile.title"),O==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.title"),O==="rename"&&t("sidebarFilesTree.dialog.rename.title"),O==="delete"&&t("sidebarFilesTree.dialog.delete.title")]}),s.jsxs(qs,{children:[O==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:_?.path??t("sidebarFilesTree.dialog.rootFallback")}),O==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:_?.path??t("sidebarFilesTree.dialog.rootFallback")}),O==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:_?.name??""}),O==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:_?.name??""})]})]}),O!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(ln,{value:oe,onChange:G=>ne(G.target.value),placeholder:t(O==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:G=>{G.key==="Enter"&&ue()},autoFocus:!0})}),s.jsxs(qn,{children:[s.jsx(ze,{variant:"outline",onClick:()=>F(null),disabled:Y,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx(ze,{variant:O==="delete"?"destructive":"default",onClick:()=>{ue()},disabled:Y||O!=="delete"&&!oe.trim(),children:Y?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t(O==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},Xw=t=>t==="git"||t==="files"||t==="context",Zw="files",ev=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function tv(t,e,n,r){const o=ht.c(6),{git:a}=_n(),c=an(sv),l=!!(t&&a&&e&&n==="git"&&r!=="git");let d,m;o[0]!==t||o[1]!==c||o[2]!==a||o[3]!==l?(d=()=>{if(!l||!t||!a)return;c(t,a);const f=window.setInterval(()=>{ev()&&c(t,a)},1e4);return()=>window.clearInterval(f)},m=[l,t,a,c],o[0]=t,o[1]=c,o[2]=a,o[3]=l,o[4]=d,o[5]=m):(d=o[4],m=o[5]),i.useEffect(d,m)}function sv(t){return t.ensureStatus}const xf=()=>{const t=ht.c(17),e=ds(rv),n=ds(iv),r=Bs(ov),o=an(av);let a;e:{if(e){let h;t[0]!==e||t[1]!==n?(h=n.find(x=>x.id===e)??n[0]??null,t[0]=e,t[1]=n,t[2]=h):h=t[2],a=h;break e}a=n[0]??null}const c=a;let l;e:{if(!c){l=null;break e}let h;t[3]!==c.id||t[4]!==c.path?(h={id:c.id,path:c.path},t[3]=c.id,t[4]=c.path,t[5]=h):h=t[5],l=h}const d=l;let m;e:{if(!c){m=null;break e}let h;t[6]!==c.label||t[7]!==c.path||t[8]!==r?(h=c.label?.trim()||Ci(c.path,r)||c.path,t[6]=c.label,t[7]=c.path,t[8]=r,t[9]=h):h=t[9],m=h}const f=m;let u;e:{if(!c){u=!1;break e}let h;t[10]!==c.path||t[11]!==o?(h=o.get(c.path)?.isGitRepo,t[10]=c.path,t[11]=o,t[12]=h):h=t[12],u=h===!0}const g=u;let b;return t[13]!==g||t[14]!==f||t[15]!==d?(b=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(ey,{projectRef:d,projectLabel:f,canCreateWorktree:g})}),t[13]=g,t[14]=f,t[15]=d,t[16]=b):b=t[16],b},nv=()=>{const t=ht.c(57),{t:e}=jt(),n=Me(lv),r=Me(cv),o=Me(dv),a=Me(uv),c=ii();tv(c,o,n,a);const l=a==="git"?"git":a==="context"?"context":null;let d,m;t[0]!==l||t[1]!==n||t[2]!==r?(d=()=>{l&&n===l&&r(Zw)},m=[l,n,r],t[0]=l,t[1]=n,t[2]=r,t[3]=d,t[4]=m):(d=t[3],m=t[4]),i.useEffect(d,m);let f;t[5]!==e?(f=e("layout.rightSidebar.git"),t[5]=e,t[6]=f):f=t[6];let u;t[7]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(T,{name:"git-branch",className:"h-3.5 w-3.5"}),t[7]=u):u=t[7];let g;t[8]!==f?(g={id:"git",label:f,icon:u},t[8]=f,t[9]=g):g=t[9];let b;t[10]!==e?(b=e("layout.rightSidebar.files"),t[10]=e,t[11]=b):b=t[11];let h;t[12]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(T,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=h):h=t[12];let x;t[13]!==b?(x={id:"files",label:b,icon:h},t[13]=b,t[14]=x):x=t[14];let y;t[15]!==e?(y=e("layout.rightSidebar.context"),t[15]=e,t[16]=y):y=t[16];let p;t[17]===Symbol.for("react.memo_cache_sentinel")?(p=s.jsx(T,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=p):p=t[17];let C;t[18]!==y?(C={id:"context",label:y,icon:p},t[18]=y,t[19]=C):C=t[19];let v;t[20]!==C||t[21]!==g||t[22]!==x?(v=[g,x,C],t[20]=C,t[21]=g,t[22]=x,t[23]=v):v=t[23];const k=v;let w;t[24]!==l||t[25]!==k?(w=l?k.filter(de=>de.id!==l):k,t[24]=l,t[25]=k,t[26]=w):w=t[26];const A=w,S=o&&n==="git"&&l!=="git";let I;t[27]!==r?(I=de=>{Xw(de)&&r(de)},t[27]=r,t[28]=I):I=t[28];const D=I;let N;t[29]!==D||t[30]!==n||t[31]!==A?(N=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(ko,{items:A,activeId:n,onSelect:D,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=D,t[30]=n,t[31]=A,t[32]=N):N=t[32];const M=n!=="git"&&"hidden";let P;t[33]!==M?(P=Te("h-full",M),t[33]=M,t[34]=P):P=t[34];let E;t[35]!==S?(E=s.jsx($l,{isActive:S}),t[35]=S,t[36]=E):E=t[36];let V;t[37]!==P||t[38]!==E?(V=s.jsx("div",{className:P,children:E}),t[37]=P,t[38]=E,t[39]=V):V=t[39];const R=n!=="files"&&"hidden";let B;t[40]!==R?(B=Te("h-full",R),t[40]=R,t[41]=B):B=t[41];let O;t[42]===Symbol.for("react.memo_cache_sentinel")?(O=s.jsx(Qw,{}),t[42]=O):O=t[42];let F;t[43]!==B?(F=s.jsx("div",{className:B,children:O}),t[43]=B,t[44]=F):F=t[44];const _=n!=="context"&&"hidden";let ie;t[45]!==_?(ie=Te("h-full",_),t[45]=_,t[46]=ie):ie=t[46];let oe;t[47]===Symbol.for("react.memo_cache_sentinel")?(oe=s.jsx(xf,{}),t[47]=oe):oe=t[47];let ne;t[48]!==ie?(ne=s.jsx("div",{className:ie,children:oe}),t[48]=ie,t[49]=ne):ne=t[49];let Y;t[50]!==V||t[51]!==F||t[52]!==ne?(Y=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[V,F,ne]}),t[50]=V,t[51]=F,t[52]=ne,t[53]=Y):Y=t[53];let te;return t[54]!==N||t[55]!==Y?(te=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[N,Y]}),t[54]=N,t[55]=Y,t[56]=te):te=t[56],te};function rv(t){return t.activeProjectId}function iv(t){return t.projects}function ov(t){return t.homeDirectory}function av(t){return t.directories}function lv(t){return t.rightSidebarTab}function cv(t){return t.setRightSidebarTab}function dv(t){return t.isRightSidebarOpen}function uv(t){return t.activeMainTab}const mv=64,fv=3,ui=new Map,hv=(t,e,n=fv)=>{const r=`${t}\0${n}\0${e}`,o=ui.get(r);if(o)return ui.delete(r),ui.set(r,o),o;const a=gv(e),c=a?fh(hh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??du(t):ph(pv(t,e))[0]?.files[0]??du(t);for(ui.set(r,c);ui.size>mv;){const l=ui.keys().next().value;if(!l)break;ui.delete(l)}return c},pv=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
14
- ===================================================================
15
- --- ${t}
16
- +++ ${t}
17
- ${e}`,gv=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(t))return;const e=[...t.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(e.length!==1)return;const n=e[0],r=Number.parseInt(n[1]??"",10),o=Number.parseInt(n[2]??"",10);if(r>1||o>1||!Number.isFinite(r)||!Number.isFinite(o))return;const a=(n.index??0)+n[0].length,c=t.slice(a),l=[],d=[];let m;for(const f of c.split(/\r?\n/)){if(f.startsWith("diff --git ")||f.startsWith("@@ "))break;if(f.startsWith("\\")){if(m==="-"||m===" "){const u=l.at(-1);u&&(u.newline=!1)}if(m==="+"||m===" "){const u=d.at(-1);u&&(u.newline=!1)}continue}if(f.startsWith("-")){l.push({text:f.slice(1),newline:!0}),m="-";continue}if(f.startsWith("+")){d.push({text:f.slice(1),newline:!0}),m="+";continue}f.startsWith(" ")&&(l.push({text:f.slice(1),newline:!0}),d.push({text:f.slice(1),newline:!0}),m=" ")}return{before:cu(l),after:cu(d)}},cu=t=>t.map(e=>e.text+(e.newline?`
18
- `:"")).join(""),du=t=>gh({name:t,contents:""},{name:t,contents:""}),xv=1100,bv=15e3,uu=500,mu=300,yv=1e6,wv=3,vv=t=>t<=6?t:t<=12?6:t<=25?4:2,jv=i.memo(()=>{const t=ht.c(4),{t:e}=jt();let n;t[0]!==e?(n=e("diffView.binary.unavailable"),t[0]=e,t[1]=n):n=t[1];let r;return t[2]!==n?(r=s.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:s.jsx("div",{className:"typography-meta text-muted-foreground",children:n})}),t[2]=n,t[3]=r):r=t[3],r}),bf={"?":{code:"?",color:"var(--status-info)",descriptionKey:"diffView.change.untracked"},A:{code:"A",color:"var(--status-success)",descriptionKey:"diffView.change.new"},D:{code:"D",color:"var(--status-error)",descriptionKey:"diffView.change.deleted"},R:{code:"R",color:"var(--status-info)",descriptionKey:"diffView.change.renamed"},C:{code:"C",color:"var(--status-info)",descriptionKey:"diffView.change.copied"},M:{code:"M",color:"var(--status-warning)",descriptionKey:"diffView.change.modified"}},Sv=bf.M,Nv=t=>{const e=t.index?.trim(),n=t.working_dir?.trim();return e&&e!=="?"?e.charAt(0):n?n.charAt(0):e?.charAt(0)||n?.charAt(0)||"M"},yf=t=>{const e=Nv(t);return bf[e]??Sv},kv=t=>{const{index:e,working_dir:n}=t;return e==="A"||n==="A"||e==="?"||n==="?"},fu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},hu=t=>!!t.working_dir?.trim()||t.index==="?",Cv=(t,e)=>$p(t,e),pu=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),gu=(t,e)=>{const n=t.split(`
19
- `),r=e.split(`
20
- `),o=Math.min(n.length,r.length);for(let a=0;a<o;a+=1)if(n[a]!==r[a])return a+1;return r.length>n.length?n.length+1:n.length>r.length?Math.max(1,r.length):1},Av=t=>{if(!t)return null;const e=t.match(/@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/m);if(!e)return null;const n=Number.parseInt(e[1],10);return!Number.isFinite(n)||n<1?null:n},Dv=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),Tv=(t,e,n)=>Dv(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:hv(t,e),contextMode:n},wf=(t,e,n)=>{const r=t??0,o=e??0;return!r&&!o?null:s.jsxs("span",{className:Te("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",n?.className),children:[r?s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",r]}):null,o?s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",o]}):null]})},Pv=i.memo(t=>{const e=ht.c(43),{scope:n,workingCount:r,stagedCount:o,onScopeChange:a}=t,{t:c}=jt(),[l,d]=i.useState(!1),m=n==="staged"?o:r;let f;e[0]!==n||e[1]!==c?(f=c(n==="staged"?"diffView.scope.staged":"diffView.scope.changed"),e[0]=n,e[1]=c,e[2]=f):f=e[2];const u=f;let g;e[3]!==c?(g=c("diffView.scope.selectorAria"),e[3]=c,e[4]=g):g=e[4];let b;e[5]!==m?(b=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",m]}),e[5]=m,e[6]=b):b=e[6];let h;e[7]!==u||e[8]!==b?(h=s.jsxs("span",{className:"whitespace-nowrap",children:[u,b]}),e[7]=u,e[8]=b,e[9]=h):h=e[9];let x;e[10]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx(T,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=x):x=e[10];let y;e[11]!==g||e[12]!==h?(y=s.jsx($s,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":g,children:[h,x]})}),e[11]=g,e[12]=h,e[13]=y):y=e[13];let p;e[14]!==a?(p=P=>{(P==="working"||P==="staged")&&(a?.(P),d(!1))},e[14]=a,e[15]=p):p=e[15];let C;e[16]!==c?(C=c("diffView.scope.changed"),e[16]=c,e[17]=C):C=e[17];let v;e[18]!==C?(v=s.jsx("span",{children:C}),e[18]=C,e[19]=v):v=e[19];let k;e[20]!==r?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:r}),e[20]=r,e[21]=k):k=e[21];let w;e[22]!==k||e[23]!==v?(w=s.jsx(dd,{value:"working",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[v,k]})}),e[22]=k,e[23]=v,e[24]=w):w=e[24];let A;e[25]!==c?(A=c("diffView.scope.staged"),e[25]=c,e[26]=A):A=e[26];let S;e[27]!==A?(S=s.jsx("span",{children:A}),e[27]=A,e[28]=S):S=e[28];let I;e[29]!==o?(I=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=I):I=e[30];let D;e[31]!==S||e[32]!==I?(D=s.jsx(dd,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[S,I]})}),e[31]=S,e[32]=I,e[33]=D):D=e[33];let N;e[34]!==n||e[35]!==w||e[36]!==D||e[37]!==p?(N=s.jsx(zs,{align:"start",className:"w-40",children:s.jsxs(zp,{value:n,onValueChange:p,children:[w,D]})}),e[34]=n,e[35]=w,e[36]=D,e[37]=p,e[38]=N):N=e[38];let M;return e[39]!==l||e[40]!==N||e[41]!==y?(M=s.jsxs(Ws,{open:l,onOpenChange:d,children:[y,N]}),e[39]=l,e[40]=N,e[41]=y,e[42]=M):M=e[42],M}),Iv=i.memo(t=>{const e=ht.c(11),{changedFiles:n,selectedFile:r,onSelectFile:o}=t,{t:a}=jt();if(n.length===0)return null;let c;if(e[0]!==n||e[1]!==o||e[2]!==r||e[3]!==a){let d;e[5]!==o||e[6]!==r||e[7]!==a?(d=m=>{const f=yf(m),u=r===m.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(m.path),className:Te("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",u?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[s.jsx(Mr,{filePath:m.path,className:"h-3.5 w-3.5 flex-shrink-0"}),s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:f.color},title:a(f.descriptionKey),"aria-label":a(f.descriptionKey),children:f.code}),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:m.path,children:m.path}),wf(m.insertions,m.deletions)]})},m.path)},e[5]=o,e[6]=r,e[7]=a,e[8]=d):d=e[8],c=n.map(d),e[0]=n,e[1]=o,e[2]=r,e[3]=a,e[4]=c}else c=e[4];let l;return e[9]!==c?(l=s.jsx(An,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:s.jsx("ul",{className:"flex flex-col gap-1",children:c})}),e[9]=c,e[10]=l):l=e[10],l}),Rv=i.memo(t=>{const e=ht.c(20),{filePath:n,diff:r,renderSideBySide:o}=t,{t:a}=jt(),c=r.original.length>0,l=r.modified.length>0,d=o?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",m=o?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";let f;e[0]===Symbol.for("react.memo_cache_sentinel")?(f={contain:"layout"},e[0]=f):f=e[0];let u;e[1]!==r.original||e[2]!==n||e[3]!==c||e[4]!==m||e[5]!==o||e[6]!==a?(u=c&&s.jsxs("div",{className:m,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a("diffView.image.original")}),s.jsx("img",{src:r.original,alt:a("diffView.image.originalAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[1]=r.original,e[2]=n,e[3]=c,e[4]=m,e[5]=o,e[6]=a,e[7]=u):u=e[7];let g;e[8]!==r.modified||e[9]!==n||e[10]!==l||e[11]!==c||e[12]!==m||e[13]!==o||e[14]!==a?(g=l&&s.jsxs("div",{className:m,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a(c?"diffView.image.modified":"diffView.image.new")}),s.jsx("img",{src:r.modified,alt:a("diffView.image.modifiedAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[8]=r.modified,e[9]=n,e[10]=l,e[11]=c,e[12]=m,e[13]=o,e[14]=a,e[15]=g):g=e[15];let b;return e[16]!==d||e[17]!==u||e[18]!==g?(b=s.jsx("div",{className:"w-full overflow-auto p-4",style:f,children:s.jsxs("div",{className:d,children:[u,g]})}),e[16]=d,e[17]=u,e[18]=g,e[19]=b):b=e[19],b}),Ev=i.memo(t=>{const e=ht.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=vi(n)||"text",e[0]=n,e[1]=c):c=e[1];const l=c;if(r.isBinary){let f;return e[2]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(jv,{}),e[2]=f):f=e[2],f}if(qi(n)){let f;return e[3]!==r||e[4]!==n||e[5]!==o?(f=s.jsx(Rv,{filePath:n,diff:r,renderSideBySide:o}),e[3]=r,e[4]=n,e[5]=o,e[6]=f):f=e[6],f}let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={contain:"layout"},e[7]=d):d=e[7];let m;return e[8]!==r.fileDiff||e[9]!==r.modified||e[10]!==r.original||e[11]!==n||e[12]!==l||e[13]!==o||e[14]!==a?(m=s.jsx("div",{className:"w-full",style:d,children:s.jsx(Ym,{original:r.original,modified:r.modified,fileDiff:r.fileDiff,language:l,fileName:n,renderSideBySide:o,wrapLines:a,layout:"inline"})}),e[8]=r.fileDiff,e[9]=r.modified,e[10]=r.original,e[11]=n,e[12]=l,e[13]=o,e[14]=a,e[15]=m):m=e[15],m}),Mv=i.memo(t=>{const e=ht.c(7),{filePath:n,staged:r,busyAction:o,disabled:a,onAction:c}=t,{t:l}=jt();let d;return e[0]!==o||e[1]!==a||e[2]!==n||e[3]!==c||e[4]!==r||e[5]!==l?(d=s.jsx("div",{className:"flex items-center gap-0.5 rounded-full border border-[var(--interactive-border)]/45 bg-[var(--surface-background)]/95 px-1 py-0.5 shadow-lg backdrop-blur-md",children:r?s.jsx(hl,{label:l("gitView.changes.unstageFileAria",{path:n}),icon:"arrow-go-back",loading:o==="unstage",disabled:a,onClick:()=>c("unstage")}):s.jsxs(s.Fragment,{children:[s.jsx(hl,{label:l("gitView.changes.revertFileAria",{path:n}),icon:"arrow-go-back",loading:o==="discard",disabled:a,tone:"failure",onClick:()=>c("discard")}),s.jsx(hl,{label:l("gitView.changes.stageFileAria",{path:n}),icon:"add",loading:o==="stage",disabled:a,tone:"success",onClick:()=>c("stage")})]})}),e[0]=o,e[1]=a,e[2]=n,e[3]=c,e[4]=r,e[5]=l,e[6]=d):d=e[6],d}),hl=t=>{const e=ht.c(14),{label:n,icon:r,loading:o,disabled:a,tone:c,onClick:l}=t,d=c==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",m=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let f;e[0]!==d||e[1]!==m?(f=Te("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",d,m),e[0]=d,e[1]=m,e[2]=f):f=e[2];let u;e[3]!==l?(u=h=>{h.stopPropagation(),l()},e[3]=l,e[4]=u):u=e[4];let g;e[5]!==r||e[6]!==o?(g=o?s.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(T,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=g):g=e[7];let b;return e[8]!==a||e[9]!==n||e[10]!==f||e[11]!==u||e[12]!==g?(b=s.jsx(ze,{variant:"ghost",size:"sm",className:f,disabled:a,title:n,"aria-label":n,onClick:u,children:g}),e[8]=a,e[9]=n,e[10]=f,e[11]=u,e[12]=g,e[13]=b):b=e[13],b},Fv=i.memo(({directory:t,file:e,layout:n,wrapLines:r,isSelected:o,isExpanded:a,isMounted:c,onSelect:l,onExpandedChange:d,registerSectionRef:m,showOpenInEditorAction:f=!1,isOpeningInEditor:u=!1,onOpenInEditor:g,staged:b=!1,loadFullFiles:h=!1})=>{const{t:x}=jt(),{git:y}=_n(),p=an(i.useCallback(q=>q.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),C=an(q=>q.setDiff),v=an(q=>q.fetchStatus),k=Me(q=>q.setDiffFileLayout),[w,A]=i.useState(0),[S,I]=i.useState(null),[D,N]=i.useState(!1),[M,P]=i.useState(null),[E,V]=i.useState(!1),[R,B]=i.useState(null),[O,F]=i.useState(null),_=i.useRef(null),ie=i.useRef(null),oe=i.useMemo(()=>yf(e),[e]),ne=n==="side-by-side",Y=h?"full":"patch",te=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,de=i.useMemo(()=>b?O:R||(p?{original:p.original,modified:p.modified,isBinary:p.isBinary,contextMode:"full"}:null),[p,R,b,O]),be=de?.contextMode===Y,ke=i.useCallback(q=>{ie.current=q,m(e.path,q)},[e.path,m]),ae=i.useCallback(q=>{d(e.path,q)},[e.path,d]),ve=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{b?F(null):B(null),I(null),_.current=null},[te,b]),i.useEffect(()=>{if(!a||!c)return;if(!t||de&&be){_.current=null,N(!1);return}const q=`${t}::${e.path}::${b?"staged":"unstaged"}::${te}::${Y}::${w}`;if(_.current===q)return;_.current=q,I(null),N(!0);let ce=!1;const fe=h?yv:wv,De=qi(e.path)?y.getGitFileDiff(t,{path:e.path,staged:b}):y.getGitDiff(t,{path:e.path,staged:b,contextLines:fe}),Re=bv,Fe=new Promise((Oe,Ee)=>{setTimeout(()=>Ee(new Error(`Timed out after ${Re}ms`)),Re)});return Promise.race([De,Fe]).then(Oe=>{if(!ce){if("diff"in Oe){const Ee=Tv(e.path,Oe.diff,Y);b?F(Ee):B(Ee)}else{const Ee={original:Oe.original??"",modified:Oe.modified??"",isBinary:Oe.isBinary,contextMode:"full"};b?F(Ee):C(t,e.path,Ee)}N(!1)}}).catch(Oe=>{if(ce)return;const Ee=Oe instanceof Error?Oe.message:String(Oe);I(Ee),N(!1)}),()=>{ce=!0,_.current===q&&(_.current=null)}},[Y,de,be,w,t,e.path,te,y,a,c,h,C,b]);const J=i.useCallback(()=>{ae(!a),ve()},[ae,ve,a]),H=i.useCallback(async q=>{if(!(!t||M!==null)){P(q);try{q==="stage"?await y.stageGitFile(t,e.path):q==="unstage"?await y.unstageGitFile(t,e.path):await y.revertGitFile(t,e.path,{scope:"working"}),A(ce=>ce+1),await v(t,y)}catch(ce){const fe=q==="unstage"?"gitView.toast.unstageFileFailed":q==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";me.error(ce instanceof Error?ce.message:x(fe))}finally{P(ce=>ce===q?null:ce)}}},[t,v,e.path,M,y,x]);return s.jsxs("div",{ref:ke,className:"scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0",children:[s.jsx("div",{className:"sticky top-0 z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80",children:s.jsxs("div",{role:"button",tabIndex:0,onClick:J,onKeyDown:q=>{q.target===q.currentTarget&&(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),J())},className:Te("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",o?"bg-[var(--interactive-selection)]/35":null),children:[s.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),s.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[s.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:a?s.jsx(T,{name:"arrow-down-s",className:"size-4"}):s.jsx(T,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:oe.color},title:x(oe.descriptionKey),"aria-label":x(oe.descriptionKey),children:oe.code}),s.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:e.path,children:s.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(Mr,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const q=e.path.lastIndexOf("/");if(q===-1)return s.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:e.path});const ce=e.path.slice(0,q),fe=e.path.slice(q+1);return s.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:ce}),s.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[s.jsx("span",{className:"text-muted-foreground",children:"/"}),s.jsx("span",{className:"text-foreground",children:fe})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[wf(e.insertions,e.deletions),f&&g?s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:x("diffView.actions.openFileInEditorAtChange"),onClick:q=>{q.stopPropagation(),g(e.path,de)},disabled:u,children:u?s.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(T,{name:"edit",className:"size-3.5"})}):null,s.jsx(Rm,{mode:ne?"side-by-side":"unified",onModeChange:q=>{const ce=q==="side-by-side"?"side-by-side":"inline";k(e.path,ce)},className:"opacity-70"})]})]})}),a&&s.jsxs("div",{className:"relative bg-background overflow-hidden",children:[!c&&!S?s.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,S?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:x("diffView.state.failedToLoadDiff")}),s.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:S}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>A(q=>q+1),children:x("diffView.actions.retry")})]}):null,c&&D&&!de&&!S?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),x("diffView.state.loadingDiff")]}):null,c&&de&&!E&&e.insertions+e.deletions>uu?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:x("diffView.state.largeDiff",{count:e.insertions+e.deletions})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:x("diffView.state.largeDiffDescription")}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>V(!0),children:x("diffView.actions.renderAnyway")})]}):null,c&&de&&(E||e.insertions+e.deletions<=uu)?s.jsxs(s.Fragment,{children:[s.jsx(Ev,{filePath:e.path,diff:de,renderSideBySide:ne,wrapLines:r}),s.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:s.jsx("div",{className:"pointer-events-auto",children:s.jsx(Mv,{filePath:e.path,staged:b,busyAction:M,disabled:M!==null,onAction:H})})})]}):null]})]})}),vf=({hideStackedFileSidebar:t=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:n=!1,showOpenInEditorAction:r=!1,diffScope:o="all",onDiffScopeChange:a,targetFilePath:c=null,flushContent:l=!1})=>{const{t:d}=jt(),{git:m,files:f}=_n(),u=ii(),{screenWidth:g,isMobile:b}=Ar(),h=dc(u??null),x=Ra(u??null),y=uc(u??null),p=an(Be=>Be.setActiveDirectory),C=an(Be=>Be.ensureStatus),v=an(Be=>Be.fetchStatus),k=an(Be=>Be.setDiff),[w,A]=i.useState(null),[S,I]=i.useState(!1),[D,N]=i.useState(null),[M,P]=i.useState(()=>new Set),[E,V]=i.useState(()=>new Set),[R,B]=i.useState(!1),[O,F]=i.useState(0),[_,ie]=i.useState(!1),[oe,ne]=i.useState(!1),Y=Me(Be=>Be.pendingDiffFile),te=Me(Be=>Be.pendingDiffStaged),de=Me(Be=>Be.setPendingDiffFile),be=Me(Be=>Be.diffLayoutPreference),ke=Me(Be=>Be.diffFileLayout),ae=Me(Be=>Be.setDiffFileLayout),ve=Me(Be=>Be.diffWrapLines),J=Me(Be=>Be.setDiffWrapLines),H=Me(Be=>Be.openContextFileAtLine),q=mt(Be=>Be.currentSessionId),ce=ve,fe=o==="staged"?!0:o==="working"?!1:null,De=fe??S,Re=b||g<=768,Fe=!!q&&!Re&&!Fr(),Oe=!t&&!Re&&g>=1024,Ee=i.useRef(null),we=i.useRef(new Map),Pe=i.useRef(null),Se=i.useRef(null),ue=i.useRef(!1),K=i.useRef(null),he=i.useRef(null),se=i.useCallback(()=>{Pe.current=null,ue.current=!1,N(null),Se.current!==null&&(window.cancelAnimationFrame(Se.current),Se.current=null)},[]),G=i.useCallback(Be=>{P(Je=>{if(Je.has(Be))return Je;const Ze=new Set(Je);return Ze.add(Be),Ze})},[]),$=i.useMemo(()=>{if(!x?.files)return[];const Be=x.diffStats??{},Je=o==="staged"?fu:o==="working"?hu:()=>!0;return x.files.filter(Je).map(Ze=>({...Ze,insertions:Be[Ze.path]?.insertions??0,deletions:Be[Ze.path]?.deletions??0,isNew:kv(Ze)})).sort((Ze,pt)=>Ze.path.localeCompare(pt.path))},[o,x]),pe=i.useMemo(()=>x?.files?x.files.filter(hu).length:0,[x]),ye=i.useMemo(()=>x?.files?x.files.filter(fu).length:0,[x]),z=i.useMemo(()=>$.map(Be=>Be.path).join("\0"),[$]);i.useEffect(()=>{const Be=z?z.split("\0"):[],Je=new Set(Be),Ze=`${u??""}:${o}:${e?"collapsed":"default"}`,pt=he.current!==Ze;he.current=Ze,P(At=>{if(pt){const ct=e?0:vv(Be.length);return new Set(Be.slice(0,ct))}let vt=!1;const at=new Set;for(const ct of At){if(!Je.has(ct)){vt=!0;continue}at.add(ct)}return vt?at:At}),V(At=>{if(pt)return new Set;let vt=!1;const at=new Set;for(const ct of At){if(!Je.has(ct)){vt=!0;continue}at.add(ct)}return vt?at:At})},[z,o,u,e]);const Ne=i.useCallback(()=>{K.current=null;const Be=Ee.current;if(!Be)return;const Je=Be.getBoundingClientRect(),Ze=Je.top-mu,pt=Je.bottom+mu,At={};for(const[vt,at]of we.current){if(!at||!M.has(vt))continue;const ct=at.getBoundingClientRect();ct.bottom<Ze||ct.top>pt||(At[vt]=!0)}V(vt=>{let at=!1;const ct=new Set(vt);for(const Ot of Object.keys(At))ct.has(Ot)||(ct.add(Ot),at=!0);return at?ct:vt})},[M]),U=i.useCallback(()=>{typeof window>"u"||K.current===null&&(K.current=window.requestAnimationFrame(Ne))},[Ne]);i.useEffect(()=>{const Be=Ee.current;if(Be)return U(),Be.addEventListener("scroll",U,{passive:!0}),window.addEventListener("resize",U),()=>{Be.removeEventListener("scroll",U),window.removeEventListener("resize",U),K.current!==null&&(window.cancelAnimationFrame(K.current),K.current=null)}},[$,M,U]);const Ie=i.useCallback(Be=>{const Je=ke[Be.path];if(Je)return Je;if(be==="inline")return"inline";if(be==="side-by-side")return"side-by-side";const Ze=g<xv;return Be.isNew||Ze?"inline":"side-by-side"},[ke,be,g]),_e=i.useMemo(()=>$.length===0?null:$.every(Be=>Ie(Be)==="side-by-side")?"side-by-side":"inline",[$,Ie]);i.useEffect(()=>{u&&(p(u),C(u,m))},[u,p,C,m]),i.useEffect(()=>{if(u)return Nr.onGitRefreshHint(Be=>{pu(Be.directory)===pu(u)&&v(u,m)})},[u,v,m]),i.useEffect(()=>{o==="all"&&Y&&(A(Y),I(te),de(null),ue.current=!0,Pe.current=Y,G(Y),F(Be=>Be+1))},[o,G,Y,te,de]),i.useEffect(()=>{if(o==="all")return;const Be=c?.trim();Be&&(A(Be),I(o==="staged"),ue.current=!0,Pe.current=Be,G(Be),F(Je=>Je+1))},[o,G,c]),i.useEffect(()=>{if(!w)return;$.some(Je=>Je.path===w)||(A(null),I(!1))},[$,w]);const Ve=i.useCallback((Be,Je)=>{const Ze=we.current;Je?Ze.set(Be,Je):Ze.delete(Be),U()},[U]),Le=i.useCallback((Be,Je)=>{se(),P(Ze=>{const pt=Ze.has(Be);if(Je===pt)return Ze;const At=new Set(Ze);return Je?At.add(Be):At.delete(Be),At}),Je||V(Ze=>{if(!Ze.has(Be))return Ze;const pt=new Set(Ze);return pt.delete(Be),pt}),U()},[se,U]),X=i.useCallback(()=>{se(),P(Be=>Be.size>0?new Set:new Set($.map(Je=>Je.path))),V(new Set),U()},[se,$,U]),L=i.useCallback(async Be=>{if(!q)return;const Je=mt.getState().getDirectoryForSession(q)||u||"";if(!Je){me.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}ne(!0);try{await _p({originalSessionID:q,directory:Je,providerID:Be.providerID,modelID:Be.modelID,agent:Be.agent||void 0,variant:Be.variant||void 0,generateHandoff:Be.generateHandoff,returnAfterHandoffRequest:Be.generateHandoff}),ie(!1)}catch(Ze){console.error("[review-flow] failed to start review flow",Ze),me.error(Ze instanceof Error?Ze.message:d("diffView.reviewDialog.toast.startFailed"))}finally{ne(!1)}},[q,u,d]),xe=i.useCallback(Be=>{const Je=we.current.get(Be),Ze=Ee.current;if(!Je||!Ze)return!1;const pt=Ze.getBoundingClientRect(),vt=Je.getBoundingClientRect().top-pt.top,at=Math.max(0,Ze.scrollHeight-Ze.clientHeight);return Ze.scrollTop=Math.min(at,Math.max(0,Ze.scrollTop+vt)),!0},[]);i.useEffect(()=>{if(!Pe.current)return;let Je=0;const Ze=20;let pt=!1;const At=()=>{pt||(pt=!0,Pe.current=null,ue.current=!1,N(null),Se.current!==null&&(window.cancelAnimationFrame(Se.current),Se.current=null))},vt=()=>{if(pt){Se.current=null;return}const at=Pe.current;if(!at){At(),Se.current=null;return}if(!xe(at)){Je+=1,Je<Ze?Se.current=window.requestAnimationFrame(vt):(At(),Se.current=null);return}n&&ue.current&&N(at),At()};return Se.current=window.requestAnimationFrame(vt),()=>{pt=!0,Se.current!==null&&(window.cancelAnimationFrame(Se.current),Se.current=null)}},[n,O,xe]);const Q=i.useCallback(Be=>{},[]),$e=i.useCallback(Be=>{se(),A(Be),I(!1),ue.current=!0,Pe.current=Be,G(Be),F(Je=>Je+1),xe(Be)},[se,G,xe]),He=i.useCallback(Be=>{const Je=Be==="side-by-side"?"side-by-side":"inline";$.forEach(Ze=>{ae(Ze.path,Je)})},[$,ae]),[Ke,qe]=i.useState(null),Xe=i.useCallback(async(Be,Je)=>{if(!(!u||!Be)){qe(Be);try{let Ze=null;if(Je&&!Je.isBinary&&!qi(Be)&&(Ze=gu(Je.original,Je.modified)),Ze===null)try{const ct=await m.getGitDiff(u,{path:Be,staged:De,contextLines:3});Ze=Av(ct.diff)}catch{Ze=null}let pt=Je;if(Ze===null||!pt){const ct=await m.getGitFileDiff(u,{path:Be,staged:De});pt={original:ct.original??"",modified:ct.modified??"",isBinary:ct.isBinary},De||k(u,Be,pt)}const At=Ze??(pt.isBinary||qi(Be)?1:gu(pt.original,pt.modified)),vt=Cv(u,Be),at=await Cc(f,vt);if(!at.ok){me.error(Ac(at.reason));return}H(u,vt,At,1)}finally{qe(Ze=>Ze===Be?null:Ze)}}},[De,u,f,m,H,k]),lt=()=>{if(!u)return null;const Be=Je=>fe!==null?fe:S&&Je===w;return s.jsxs("div",{className:Te("flex flex-1 min-h-0 h-full",l?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[Oe&&s.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:d("diffView.section.files")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:$.length})]}),s.jsx(Iv,{changedFiles:$,selectedFile:null,onSelectFile:$e})]}),s.jsx("div",{className:"relative flex-1 min-h-0 h-full",children:s.jsx(An,{ref:Ee,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:s.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:$.map(Je=>s.jsx(Fv,{directory:u,file:Je,layout:Ie(Je),wrapLines:ce,isSelected:!1,isExpanded:M.has(Je.path),isMounted:E.has(Je.path)||Je.path===D,onSelect:Q,onExpandedChange:Le,registerSectionRef:Ve,showOpenInEditorAction:r,isOpeningInEditor:Ke===Je.path,onOpenInEditor:(Ze,pt)=>{Xe(Ze,pt)},staged:Be(Je.path),loadFullFiles:R},Je.path))})})})]})},bt=()=>u?y&&!x?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),d("diffView.state.loadingRepositoryStatus")]}):h===!1?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.notGitRepository")}):$.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.cleanWorkingTree")}):lt():s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.selectSessionDirectory")});return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[!b&&(o==="working"||o==="staged"?s.jsx(Pv,{scope:o,workingCount:pe,stagedCount:ye,onScopeChange:a}):s.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:y&&!x?d("diffView.state.loadingChanges"):$.length===1?d("diffView.summary.changedFilesSingle",{count:$.length}):d("diffView.summary.changedFilesPlural",{count:$.length})})})),$.length>0&&s.jsxs(ze,{variant:"ghost",size:"sm",onClick:X,className:Te("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:M.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll"),children:[s.jsx(T,{name:"expand-up-down",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:M.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll")})]}),$.length>0&&Fe&&s.jsxs(ze,{variant:"default",size:"sm",onClick:()=>ie(!0),disabled:oe,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[oe?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(T,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),$.length>0&&s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>B(Be=>!Be),"aria-pressed":R,"aria-label":d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:Te("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",R&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(T,{name:"file-download",className:"size-4"})})}),s.jsx(Ct,{children:s.jsx("p",{children:d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),$.length>0&&s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>J(!ve),className:Te("h-5 w-5 p-0 transition-opacity",ce?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(ce?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(T,{name:"text-wrap",className:"size-4"})}),_e&&s.jsx(Rm,{mode:_e==="side-by-side"?"side-by-side":"unified",onModeChange:He})]}),s.jsx(Vp,{open:_,onOpenChange:ie,projectDirectory:u??null,submitting:oe,onConfirm:L}),bt()]})},Lv=(t,e)=>{if(!e)return null;const n=Number.parseInt(t.trim(),10);return!Number.isFinite(n)||n<1?null:Math.min(n,e.state.doc.lines)},xu=(t,e)=>{const n=t.state.doc.lineAt(e.main.head);return{lineNumber:n.number,character:e.main.head-n.from+1,selection:e}},bu=(t,e,n)=>{const r=t.state.doc.line(e),o=Math.max(1,Math.min(n,r.length+1)),a=r.from+o-1;t.dispatch({selection:xh.cursor(a),effects:Xr.scrollIntoView(a,{y:"center"})})};function Ov({open:t,onOpenChange:e,view:n,variant:r="overlay"}){const{t:o}=jt(),[a,c]=i.useState(""),l=i.useRef(null),d=i.useRef(!1),m=i.useRef(null),f=i.useRef(null),u=i.useMemo(()=>Lv(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=xu(n,n.state.selection),c(""))},[t,n]),i.useEffect(()=>{t&&window.requestAnimationFrame(()=>{f.current?.focus(),f.current?.select()})},[t]),i.useEffect(()=>{if(!(!t||!n||!l.current)){if(u===null){const{selection:y}=l.current;n.dispatch({selection:y,effects:Xr.scrollIntoView(y.main.from,{y:"center"})});return}bu(n,u,l.current.character)}},[u,t,n]);const g=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:y}=l.current;n.dispatch({selection:y,effects:Xr.scrollIntoView(y.main.from,{y:"center"})})},[n]),b=i.useCallback(y=>{y||g(),e(y)},[e,g]),h=i.useCallback(()=>{!n||u===null||!l.current||(d.current=!0,bu(n,u,l.current.character),e(!1),n.focus())},[u,e,n]);i.useEffect(()=>{if(!t)return;const y=C=>{const v=m.current,k=C.target;!v||!(k instanceof Node)||v.contains(k)||b(!1)},p=C=>{C.key==="Escape"&&(C.preventDefault(),b(!1))};return document.addEventListener("pointerdown",y,!0),document.addEventListener("keydown",p,!0),()=>{document.removeEventListener("pointerdown",y,!0),document.removeEventListener("keydown",p,!0)}},[b,t,r]);const x=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(u===null){const y=l.current??xu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:y.lineNumber,max:n.state.doc.lines})}return o("goToLineDialog.helper.goToLine",{line:u})},[u,o,n]);return r==="inline"?t?s.jsxs("div",{ref:m,className:"ml-1 flex h-6 items-center gap-1",children:[s.jsx(ln,{ref:f,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),h())},placeholder:o("goToLineDialog.field.linePlaceholderShort"),className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),s.jsx(ze,{variant:"outline",size:"xs",onClick:h,disabled:!n||u===null,className:"h-6 px-2",children:o("goToLineDialog.actions.go")})]}):null:s.jsx("div",{ref:m,className:Te("absolute left-3 top-3 z-40 w-[min(32rem,calc(100%-1.5rem))] rounded-xl border border-[var(--interactive-border)] bg-[color:color-mix(in_srgb,var(--surface-elevated)_94%,transparent)] p-2.5 shadow-lg backdrop-blur-sm transition-all",t?"pointer-events-auto translate-y-0 opacity-100":"pointer-events-none -translate-y-1 opacity-0"),children:s.jsxs("div",{className:"min-w-0",children:[s.jsx(ln,{ref:f,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),h())},placeholder:o("goToLineDialog.field.linePlaceholder"),className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),s.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:x})]})})}const Bv='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function yu(){if(typeof document>"u")return!1;const t=document.documentElement.getAttribute("data-theme");return t==="dark"||!t&&window.matchMedia("(prefers-color-scheme: dark)").matches}const _v=i.forwardRef(function({xml:e,readOnly:n,className:r,onChange:o},a){const c=i.useRef(e),l=i.useRef(null),d=i.useRef(!1),[m,f]=i.useState(yu),u=i.useRef(e),g=i.useRef(e);g.current!==e&&(g.current=e,u.current=e,c.current=e);const b=i.useRef(m);b.current!==m&&(b.current=m,u.current=c.current);const h=i.useRef(null);i.useEffect(()=>{const p=()=>f(yu());p();const C=new MutationObserver(p);return C.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>C.disconnect()},[]),i.useEffect(()=>{const p=setTimeout(()=>{h.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(p)},[]),i.useImperativeHandle(a,()=>({getXml:()=>c.current}));const x=i.useCallback(()=>{!e&&!d.current&&(d.current=!0,setTimeout(()=>{l.current?.template({})},500))},[e]),y=i.useCallback(p=>{c.current=p.xml,o?.(p.xml)},[o]);return s.jsx("div",{ref:h,className:Te("h-full w-full",r),children:s.jsx(bh,{ref:l,xml:u.current||Bv,autosave:!0,urlParameters:{ui:n?"simple":m?"dark":"kennedy",spin:!0,libraries:!n,chrome:n,nav:n,layers:n,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:x,onAutoSave:y},m?"dark":"light")})}),Vv=t=>{const e=Os(t);if(!e)return"";if(e==="/"||/^[A-Za-z]:\/$/.test(e))return e;const n=e.lastIndexOf("/");if(n<0)return e;if(n===0)return"/";const r=e.slice(0,n);return/^[A-Za-z]:$/.test(r)?`${r}/`:r},$v=t=>{const e=ht.c(8),{label:n,iconDataUrl:r}=t,[o,a]=i.useState(!1);let c;e[0]!==n?(c=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=c):c=e[1];const l=c;if(r&&!o){let f;e[2]===Symbol.for("react.memo_cache_sentinel")?(f=()=>a(!0),e[2]=f):f=e[2];let u;return e[3]!==r?(u=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:f}),e[3]=r,e[4]=u):u=e[4],u}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=Te("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=d):d=e[5];let m;return e[6]!==l?(m=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=m):m=e[7],m},zv=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Os=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",a=/^[A-Za-z]:\/$/.test(r);return!o&&!a&&(r=r.replace(/\/+$/,"")),r},Wv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),_i=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,va=(t,e)=>{const n=Os(e),r=Os(t);if(!n||!r)return!1;const o=_i(n),a=_i(r);return a===o||a.startsWith(`${o}/`)},wu=(t,e)=>{const n=Os(e),r=Os(t);if(!va(r,n))return[];const a=r.slice(n.length).replace(/^\//,"").split("/"),c=[];let l=n;for(let d=0;d<a.length-1;d++)l=l?`${l}/${a[d]}`:a[d],c.push(l);return c},Wl=(t,e)=>{if(!e)return"";const n=Os(e);if(!t||!va(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},Uv=new Set(["node_modules"]),Hv=t=>{const e=ht.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},vu=t=>{const e=ht.c(11),{name:n}=t,r=i.useRef(null),o=i.useRef(null),[a,c]=i.useState(!1);let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l=()=>{const g=r.current,b=o.current;if(!g||!b)return;const h=()=>{c(b.scrollWidth>g.clientWidth+1)};h();const x=new ResizeObserver(h);return x.observe(g),x.observe(b),()=>{x.disconnect()}},e[0]=l):l=e[0];let d;e[1]!==n?(d=[n],e[1]=n,e[2]=d):d=e[2],i.useLayoutEffect(l,d);let m;e[3]!==n?(m=s.jsx("span",{ref:o,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:n}),e[3]=n,e[4]=m):m=e[4];let f;e[5]!==n||e[6]!==a?(f=a?s.jsxs("span",{className:"open-file-name-marquee-track",children:[s.jsx("span",{className:"open-file-name-marquee-item",children:n}),s.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:n})]}):s.jsx("span",{className:"block min-w-0 truncate",children:n}),e[5]=n,e[6]=a,e[7]=f):f=e[7];let u;return e[8]!==m||e[9]!==f?(u=s.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[m,f]}),e[8]=m,e[9]=f,e[10]=u):u=e[10],u},Gv=t=>Uv.has(t),Kv=t=>{const e=Os(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},qv=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},ju=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},lo=2e5,jf="openchamber:files:auto-save-enabled",Yv=t=>{let e=0,n=0;for(let r=0;r<t.length;r+=1)t.charCodeAt(r)===10&&(r>0&&t.charCodeAt(r-1)===13?e+=1:n+=1);return e>n?`\r
21
- `:`
22
- `},Sf=t=>t.replace(/\r\n/g,`
23
- `).replace(/\r/g,`
24
- `),Jv=(t,e)=>{const n=Sf(t);return e===`\r
25
- `?n.replace(/\n/g,`\r
26
- `):n},Qv=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(jf)!=="false"}catch{return!0}},Nf=(t,e)=>s.jsx(Mr,{filePath:t,extension:e}),Su=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},Xv=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="json"||e==="jsonc"||e==="json5"||e==="geojson"},Uo=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="html"||e==="htm"},Zv=t=>{const e=ht.c(83),{node:n,root:r,isExpanded:o,isActive:a,isMobile:c,alwaysShowActions:l,status:d,badge:m,permissions:f,downloadFile:u,contextMenuPath:g,setContextMenuPath:b,rightClickMenuPath:h,setRightClickMenuPath:x,onSelect:y,onToggle:p,onRevealPath:C,onOpenDialog:v}=t,{t:k}=jt(),w=n.type==="directory",{canRename:A,canCreateFile:S,canCreateFolder:I,canDelete:D,canReveal:N}=f;let M;e[0]!==S||e[1]!==I||e[2]!==D||e[3]!==A||e[4]!==N||e[5]!==n.path||e[6]!==x?(M=De=>{!A&&!S&&!I&&!D&&!N||(De?.preventDefault(),x(n.path))},e[0]=S,e[1]=I,e[2]=D,e[3]=A,e[4]=N,e[5]=n.path,e[6]=x,e[7]=M):M=e[7];const P=M;let E;e[8]!==w||e[9]!==n||e[10]!==y||e[11]!==p?(E=()=>{w?p(n.path):y(n)},e[8]=w,e[9]=n,e[10]=y,e[11]=p,e[12]=E):E=e[12];const V=E;let R;e[13]!==n.path||e[14]!==b||e[15]!==x?(R=De=>{De.stopPropagation(),x(null),b(n.path)},e[13]=n.path,e[14]=b,e[15]=x,e[16]=R):R=e[16];const B=R;let O;e[17]!==S||e[18]!==I||e[19]!==D||e[20]!==A||e[21]!==N||e[22]!==u||e[23]!==w||e[24]!==n||e[25]!==v||e[26]!==C||e[27]!==r||e[28]!==k?(O=De=>{const{Item:Re,Separator:Fe}=De;return s.jsxs(s.Fragment,{children:[A&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),v("rename",n)},children:[s.jsx(T,{name:"edit",className:"mr-2 size-4"})," ",k("sidebarFilesTree.menu.rename")]}),s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),tr(n.path).then(Ee=>{if(Ee.ok){me.success(k("sidebarFilesTree.toast.pathCopied"));return}me.error(k("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(T,{name:"file-copy",className:"mr-2 size-4"})," ",k("sidebarFilesTree.menu.copyPath")]}),s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation();const Ee=Wl(r,n.path)||n.path;tr(Ee).then(we=>{if(we.ok){me.success(k("filesView.toast.relativePathCopied"));return}me.error(k("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(T,{name:"file-copy-2",className:"mr-2 size-4"})," ",k("filesView.tree.menu.copyRelativePath")]}),!w&&u&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),u(n.path).catch(Ee=>{console.error("Download failed:",Ee),me.error(k("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(T,{name:"download",className:"mr-2 size-4"})," ",k("sidebarFilesTree.menu.save")]}),N&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),C(n.path)},children:[s.jsx(T,{name:"folder-received",className:"mr-2 size-4"})," ",k(mc())]}),w&&(S||I)&&s.jsxs(s.Fragment,{children:[s.jsx(Fe,{}),S&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),v("createFile",n)},children:[s.jsx(T,{name:"file-add",className:"mr-2 size-4"})," ",k("sidebarFilesTree.menu.newFile")]}),I&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),v("createFolder",n)},children:[s.jsx(T,{name:"folder-add",className:"mr-2 size-4"})," ",k("sidebarFilesTree.menu.newFolder")]})]}),D&&s.jsxs(s.Fragment,{children:[s.jsx(Fe,{}),s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),v("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(T,{name:"delete-bin",className:"mr-2 size-4"})," ",k("sidebarFilesTree.menu.delete")]})]})]})},e[17]=S,e[18]=I,e[19]=D,e[20]=A,e[21]=N,e[22]=u,e[23]=w,e[24]=n,e[25]=v,e[26]=C,e[27]=r,e[28]=k,e[29]=O):O=e[29];const F=O,_=h===n.path;let ie;e[30]!==n.path||e[31]!==x?(ie=De=>x(De?n.path:null),e[30]=n.path,e[31]=x,e[32]=ie):ie=e[32];const oe=c?void 0:P;let ne;e[33]!==oe?(ne=s.jsx("div",{className:"group relative flex items-center",onContextMenu:oe}),e[33]=oe,e[34]=ne):ne=e[34];const Y=c?void 0:P,te=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let de;e[35]!==te?(de=Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",te),e[35]=te,e[36]=de):de=e[36];let be;e[37]!==w||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(be=w?o?s.jsx(T,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(T,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):Nf(n.path,n.extension),e[37]=w,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=be):be=e[41];let ke;e[42]!==n.name||e[43]!==n.path?(ke=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:n.path,children:n.name}),e[42]=n.name,e[43]=n.path,e[44]=ke):ke=e[44];let ae;e[45]!==w||e[46]!==d?(ae=!w&&d&&s.jsx(Hv,{status:d}),e[45]=w,e[46]=d,e[47]=ae):ae=e[47];let ve;e[48]!==m||e[49]!==w?(ve=w&&m&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[m.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",m.modified]}),m.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",m.added]})]}),e[48]=m,e[49]=w,e[50]=ve):ve=e[50];let J;e[51]!==V||e[52]!==de||e[53]!==be||e[54]!==ke||e[55]!==ae||e[56]!==ve||e[57]!==Y?(J=s.jsxs("button",{type:"button",onClick:V,onContextMenu:Y,className:de,children:[be,ke,ae,ve]}),e[51]=V,e[52]=de,e[53]=be,e[54]=ke,e[55]=ae,e[56]=ve,e[57]=Y,e[58]=J):J=e[58];let H;e[59]!==l||e[60]!==S||e[61]!==I||e[62]!==D||e[63]!==A||e[64]!==N||e[65]!==g||e[66]!==B||e[67]!==c||e[68]!==n.path||e[69]!==F||e[70]!==b?(H=(A||S||I||D||N)&&s.jsx("div",{className:Te("absolute right-1 top-1/2 -translate-y-1/2",l?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:s.jsxs(Ws,{open:g===n.path,onOpenChange:De=>b(De?n.path:null),children:[s.jsx($s,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"icon",className:"size-6",onClick:B,children:s.jsx(T,{name:"more-2-fill",className:"size-4"})})}),s.jsx(zs,{align:"end",side:"bottom",onCloseAutoFocus:()=>b(null),children:F({Item:ls,Separator:Cr})})]})}),e[59]=l,e[60]=S,e[61]=I,e[62]=D,e[63]=A,e[64]=N,e[65]=g,e[66]=B,e[67]=c,e[68]=n.path,e[69]=F,e[70]=b,e[71]=H):H=e[71];let q;e[72]!==J||e[73]!==H||e[74]!==ne?(q=s.jsxs(wc,{render:ne,children:[J,H]}),e[72]=J,e[73]=H,e[74]=ne,e[75]=q):q=e[75];let ce;e[76]!==F?(ce=s.jsx(bc,{className:"min-w-[180px]",children:F({Item:yc,Separator:Jm})}),e[76]=F,e[77]=ce):ce=e[77];let fe;return e[78]!==q||e[79]!==ce||e[80]!==_||e[81]!==ie?(fe=s.jsxs(vc,{open:_,onOpenChange:ie,children:[q,ce]}),e[78]=q,e[79]=ce,e[80]=_,e[81]=ie,e[82]=fe):fe=e[82],fe},e1=t=>{const e=ht.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:m}=t,{t:f}=jt(),u=!!n;let g;e[0]!==d?(g=_=>!_&&d(),e[0]=d,e[1]=g):g=e[1];let b;e[2]!==n||e[3]!==f?(b=n==="createFile"&&f("filesView.dialog.createFile.title"),e[2]=n,e[3]=f,e[4]=b):b=e[4];let h;e[5]!==n||e[6]!==f?(h=n==="createFolder"&&f("filesView.dialog.createFolder.title"),e[5]=n,e[6]=f,e[7]=h):h=e[7];let x;e[8]!==n||e[9]!==f?(x=n==="rename"&&f("filesView.dialog.rename.title"),e[8]=n,e[9]=f,e[10]=x):x=e[10];let y;e[11]!==n||e[12]!==f?(y=n==="delete"&&f("filesView.dialog.delete.title"),e[11]=n,e[12]=f,e[13]=y):y=e[13];let p;e[14]!==b||e[15]!==h||e[16]!==x||e[17]!==y?(p=s.jsxs(Ps,{children:[b,h,x,y]}),e[14]=b,e[15]=h,e[16]=x,e[17]=y,e[18]=p):p=e[18];let C;e[19]!==n||e[20]!==r?.path||e[21]!==f?(C=n==="createFile"&&f("filesView.dialog.createFile.description",{path:r?.path??f("filesView.dialog.rootFallback")}),e[19]=n,e[20]=r?.path,e[21]=f,e[22]=C):C=e[22];let v;e[23]!==n||e[24]!==r?.path||e[25]!==f?(v=n==="createFolder"&&f("filesView.dialog.createFolder.description",{path:r?.path??f("filesView.dialog.rootFallback")}),e[23]=n,e[24]=r?.path,e[25]=f,e[26]=v):v=e[26];let k;e[27]!==n||e[28]!==r?.name||e[29]!==f?(k=n==="rename"&&f("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=f,e[30]=k):k=e[30];let w;e[31]!==n||e[32]!==r?.name||e[33]!==f?(w=n==="delete"&&f("filesView.dialog.delete.description",{name:r?.name??""}),e[31]=n,e[32]=r?.name,e[33]=f,e[34]=w):w=e[34];let A;e[35]!==k||e[36]!==w||e[37]!==C||e[38]!==v?(A=s.jsxs(qs,{children:[C,v,k,w]}),e[35]=k,e[36]=w,e[37]=C,e[38]=v,e[39]=A):A=e[39];let S;e[40]!==A||e[41]!==p?(S=s.jsxs(Ms,{children:[p,A]}),e[40]=A,e[41]=p,e[42]=S):S=e[42];let I;e[43]!==n||e[44]!==o||e[45]!==m||e[46]!==a||e[47]!==l||e[48]!==f?(I=n!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(ln,{value:o,onChange:_=>a(_.target.value),placeholder:f(n==="rename"?"filesView.dialog.rename.placeholder":"filesView.dialog.namePlaceholder"),onKeyDown:_=>{_.key==="Enter"&&l()},ref:m})}),e[43]=n,e[44]=o,e[45]=m,e[46]=a,e[47]=l,e[48]=f,e[49]=I):I=e[49];let D;e[50]!==f?(D=f("filesView.dialog.cancel"),e[50]=f,e[51]=D):D=e[51];let N;e[52]!==c||e[53]!==d||e[54]!==D?(N=s.jsx(ze,{variant:"outline",onClick:d,disabled:c,children:D}),e[52]=c,e[53]=d,e[54]=D,e[55]=N):N=e[55];const M=n==="delete"?"destructive":"default";let P;e[56]!==l?(P=()=>{l()},e[56]=l,e[57]=P):P=e[57];let E;e[58]!==n||e[59]!==o||e[60]!==c?(E=c||n!=="delete"&&!o.trim(),e[58]=n,e[59]=o,e[60]=c,e[61]=E):E=e[61];let V;e[62]!==n||e[63]!==c||e[64]!==f?(V=c?s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):f(n==="delete"?"filesView.dialog.delete.confirm":"filesView.dialog.confirm"),e[62]=n,e[63]=c,e[64]=f,e[65]=V):V=e[65];let R;e[66]!==M||e[67]!==P||e[68]!==E||e[69]!==V?(R=s.jsx(ze,{variant:M,onClick:P,disabled:E,children:V}),e[66]=M,e[67]=P,e[68]=E,e[69]=V,e[70]=R):R=e[70];let B;e[71]!==N||e[72]!==R?(B=s.jsxs(qn,{children:[N,R]}),e[71]=N,e[72]=R,e[73]=B):B=e[73];let O;e[74]!==m||e[75]!==S||e[76]!==I||e[77]!==B?(O=s.jsxs(ks,{initialFocus:m,children:[S,I,B]}),e[74]=m,e[75]=S,e[76]=I,e[77]=B,e[78]=O):O=e[78];let F;return e[79]!==u||e[80]!==g||e[81]!==O?(F=s.jsx(Cs,{open:u,onOpenChange:g,children:O}),e[79]=u,e[80]=g,e[81]=O,e[82]=F):F=e[82],F},kf=({mode:t="full"})=>{const{t:e}=jt(),{files:n,runtime:r}=_n(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=Lr(),{isMobile:d,isTablet:m,screenWidth:f}=Ar(),u=d||m,g=hm(),b=pm(),h=ii()??"",x=Os(h.trim()),y=d||t!=="editor-only",p=t==="editor-only"&&!d,C=tc(W=>W.searchFiles),v=Ra(h),[k,w]=i.useState(""),A=Ma(k,200),S=i.useRef(null),[I,D]=i.useState(!1),[N,M]=i.useState(!0),[P,E]=i.useState(!1),[V,R]=i.useState(!1),[B,O]=i.useState(!1),F=i.useRef(null),_=i.useRef(0),ie=i.useCallback(W=>{_.current=Math.max(0,_.current+(W?1:-1))},[]),oe=i.useCallback(W=>W instanceof Element?W.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!B)return;const W=Ce=>{_.current>0||oe(Ce.target)||F.current&&!F.current.contains(Ce.target)&&O(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[oe,B]);const[ne,Y]=i.useState("edit"),[te,de]=i.useState("edit"),[be,ke]=i.useState("tree"),[ae,ve]=i.useState("edit"),[J,H]=i.useState("preview"),[q,ce]=i.useState(0),fe=i.useRef({}),De=i.useRef({}),Re=i.useRef({}),Fe=i.useRef({}),Oe=i.useMemo(()=>a.find(W=>W.metadata.id===c)??ud(!1),[a,c]),Ee=i.useMemo(()=>a.find(W=>W.metadata.id===l)??ud(!0),[a,l]);i.useEffect(()=>{md(Oe),md(Ee)},[Oe,Ee]);const we=i.useMemo(()=>[],[]),Pe=on(W=>x?W.byRoot[x]?.openPaths??we:we),Se=on(W=>x?W.byRoot[x]?.selectedPath??null:null),ue=on(W=>x?W.byRoot[x]?.expandedPaths??we:we),K=on(W=>W.addOpenPath),he=on(W=>W.removeOpenPath),se=on(W=>W.removeOpenPathsByPrefix),G=on(W=>W.setSelectedPath),$=on(W=>W.toggleExpandedPath),pe=on(W=>W.expandPaths),ye=i.useCallback(W=>{const Ce=Os(W),Ue=Ce.split("/"),Ge=Ue[Ue.length-1]||Ce,dt=Ge.includes(".")?Ge.split(".").pop()?.toLowerCase():void 0;return{name:Ge,path:Ce,type:"file",extension:dt}},[]),z=i.useMemo(()=>Pe.map(ye),[Pe,ye]),Ne=i.useMemo(()=>{if(Se){const W=_i(Se);if(Pe.some(Ce=>_i(Ce)===W))return Se}return Pe[0]??null},[Pe,Se]),U=i.useMemo(()=>Ne?ye(Ne):null,[Ne,ye]),Ie=U?.path??"";i.useEffect(()=>{if(!x||!Se)return;const W=_i(Se);Pe.some(Ue=>_i(Ue)===W)||G(x,Pe[0]??null)},[Pe,x,Se,G]);const _e=!!(x&&Ie&&!va(Ie,x)),Ve=_e?fd(Ie):void 0,Le=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&_e,outsideFileGrant:Ve,directory:x||void 0}),[t,_e,Ve,x]),X=i.useRef(null),[L,xe]=i.useState({left:!1,right:!1}),Q=i.useCallback(()=>{const W=X.current;W&&xe({left:W.scrollLeft>2,right:W.scrollLeft+W.clientWidth<W.scrollWidth-2})},[]),$e=i.useRef(Q);$e.current=Q,i.useEffect(()=>{const W=X.current;if(!W)return;const Ce=()=>$e.current();Ce(),W.addEventListener("scroll",Ce,{passive:!0});const Ue=new ResizeObserver(Ce);return Ue.observe(W),()=>{W.removeEventListener("scroll",Ce),Ue.disconnect()}},[z.length]);const[He,Ke]=i.useState({}),[qe,Xe]=i.useState({}),lt=i.useRef(new Set),bt=i.useRef(new Set),Be=i.useRef(new Map),Je=i.useRef(0),[Ze,pt]=i.useState([]),[At,vt]=i.useState(!1),[at,ct]=i.useState(""),{isPlaying:Ot,play:Zt,stop:Et}=Em(),[ge,st]=i.useState(!1),[wt,tt]=i.useState(null),[ut,Mt]=i.useState(""),It=i.useRef(""),[zt,ss]=i.useState(""),[Bt,Ft]=i.useState(""),[Jt,es]=i.useState(""),[Lt,Pt]=i.useState(null),[Kt,yt]=i.useState(""),[$t,Dt]=i.useState(!1),[fs,ms]=i.useState(`
27
- `),xs=i.useRef(null),gt=i.useRef(null),qt=i.useRef(null),hs=i.useRef(""),os=i.useRef(""),Is=i.useRef(null),As=i.useRef(null),Xt=i.useRef(null),Rs=i.useRef(0),[In,Ds]=i.useState("idle"),[Ys,Us]=i.useState(!1),[bs,Yn]=i.useState(Qv),[en,je]=i.useState(!1),et=i.useRef(null),ft=i.useRef(null),Ae=i.useRef(null),xt=i.useRef(!1),rt=i.useRef(null),_t=i.useRef(null),Vt=i.useRef(null),ns=i.useRef(null),[rs,ts]=i.useState(0),cn=i.useRef(null),_s=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{cn.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(cn.current),cn.current=null)},[]);const[tn,Rn]=i.useState(null),[jn,dn]=i.useState(null),[Es,js]=i.useState(""),[Or,En]=i.useState(!1),[sr,Br]=i.useState(null),[Vn,_r]=i.useState(null),[Js,nr]=i.useState(!1),[un,as]=i.useState(!1),[ws,$n]=i.useState(!1),sn=!!n.writeFile,Qs=!!n.createDirectory,rr=!!n.rename,xr=!!n.delete,br=!!n.revealPath,Vr=fr(W=>W.availableApps),Dr=fr(W=>W.isCacheStale),$r=fr(W=>W.initialize),ir=fr(W=>W.loadInstalledApps);i.useEffect(()=>{$r()},[$r]);const Mn=i.useCallback(W=>{n.revealPath&&n.revealPath(W).catch(()=>{me.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),re=i.useCallback(async W=>{if(!U?.path||await $h(U.path,W.id,W.appName)||await ua(U.path,W.appName))return;const Ge=Vv(U.path)||x;Ge&&await ua(Ge,W.appName)||me.error(e("filesView.toast.openInAppFailed",{app:W.appName}))},[x,U?.path,e]),nt=i.useCallback((W,Ce)=>{Rn(W),dn(Ce),js(W==="rename"&&Ce.name||""),En(!1)},[]),[ot,St]=i.useState(null),Yt=i.useRef(!1),Ht=i.useRef(null),[is,ps]=i.useState(!1),cs=Me(W=>W.setMainTabGuard),Fs=Me(W=>W.pendingFileNavigation),hn=Me(W=>W.setPendingFileNavigation),or=Me(W=>W.pendingFileFocusPath),Xs=Me(W=>W.setPendingFileFocusPath),yr=Me(W=>W.shortcutOverrides),mn=Me(W=>W.fileEditorKeymap),Hs=Ut(W=>W.settingsDefaultFileViewerPreview),Sn=Ut(W=>W.showMessageTTSButtons),pn=Me(W=>W.expandedEditorToolbar);i.useEffect(()=>{const W=()=>{Yt.current=!1,Ht.current=null,ps(!1)};return document.addEventListener("mouseup",W),()=>document.removeEventListener("mouseup",W)},[]),i.useEffect(()=>()=>{rt.current!==null&&window.clearTimeout(rt.current),_t.current!==null&&window.clearTimeout(_t.current)},[]);const zn=i.useCallback((W,Ce)=>{const Ue=W.split(`
28
- `),Ge=Math.max(1,Ce.start),dt=Math.min(Ue.length,Ce.end);return Ge>dt?"":Ue.slice(Ge-1,dt).join(`
29
- `)},[]),Tr=Qm({source:"file",fileLabel:U?.path??null,language:U?.path&&vi(U.path)||"text",getCodeForRange:W=>zn(at,Xm(W)),toStoreRange:W=>({startLine:W.start,endLine:W.end}),fromDraftRange:W=>({start:W.startLine,end:W.endLine})}),{drafts:Jn,commentText:zr,setCommentText:Di,editingDraftId:Wn,setSelection:oi,saveComment:ai,cancel:Pr,reset:Ti,startEdit:ar,deleteDraft:gn}=Tr;i.useEffect(()=>{St(null),Ti(),cs(null),yt(""),Dt(!1)},[U?.path,Ti,cs]),i.useEffect(()=>{oi(ot)},[ot,oi]),i.useEffect(()=>{if(!ot&&!Wn)return;const W=Ue=>{const Ge=Ue.target;Ge.closest('[data-comment-input="true"]')||Ge.closest('[data-comment-card="true"]')||Ge.closest(".cm-gutterElement")||Ge.closest("[data-sonner-toast]")||Ge.closest("[data-sonner-toaster]")||zr.trim()||(St(null),Pr())},Ce=setTimeout(()=>{document.addEventListener("click",W)},100);return()=>{clearTimeout(Ce),document.removeEventListener("click",W)}},[Pr,zr,Wn,ot]);const Qt=i.useCallback((W,Ce)=>{const Ue=Ce??ot??void 0;Ce&&St(Ce),ai(W,Ue),St(null)},[ot,ai]),lr=i.useCallback((W,Ce)=>{const Ue=[];for(const Ge of Ce){if(!(Ge&&typeof Ge.name=="string"&&Ge.name.length>0)||!g&&Ge.name.startsWith(".")||!b&&Gv(Ge.name))continue;const dt=Ge.name,it=Os(Ge.path||""),Wt=it?Wv(it)?it:Os(`${W}/${it}`):Os(`${W}/${dt}`),Ss=Ge.isDirectory?"directory":"file",Ts=Ss==="file"&&dt.includes(".")?dt.split(".").pop()?.toLowerCase():void 0;Ue.push({name:dt,path:Wt,type:Ss,extension:Ts})}return zv(Ue)},[b,g]),nn=i.useCallback(async W=>{const Ce=Os(W.trim());if(!Ce||lt.current.has(Ce)||bt.current.has(Ce))return;bt.current=new Set(bt.current),bt.current.add(Ce);const Ue=Je.current+1;Je.current=Ue,Be.current=new Map(Be.current),Be.current.set(Ce,Ue);const Ge=()=>Be.current.get(Ce)===Ue;await(n.listDirectory?n.listDirectory(Ce).then(it=>it.entries.map(Wt=>({name:Wt.name,path:Wt.path,isDirectory:Wt.isDirectory}))):Cn.listLocalDirectory(Ce).then(it=>it.map(Wt=>({name:Wt.name,path:Wt.path,isDirectory:Wt.isDirectory})))).then(it=>{if(!Ge())return;const Wt=lr(Ce,it);lt.current=new Set(lt.current),lt.current.add(Ce),Xe(Ss=>{if(!Ss[Ce])return Ss;const Ts={...Ss};return delete Ts[Ce],Ts}),Ke(Ss=>({...Ss,[Ce]:Wt}))}).catch(it=>{if(!Ge())return;const Wt=it instanceof Error?it.message:String(it??"");console.error("Failed to load files directory:",it),Xe(Ss=>({...Ss,[Ce]:Wt}))}).finally(()=>{Ge()&&(Be.current=new Map(Be.current),Be.current.delete(Ce),bt.current=new Set(bt.current),bt.current.delete(Ce))})},[n,lr]),cr=i.useCallback(async()=>{x&&(lt.current=new Set,bt.current=new Set,Be.current=new Map,Xe({}),Ke(W=>Object.keys(W).length===0?W:{}),await nn(x))},[nn,x]),Fn=i.useCallback(async W=>{if(!W){await cr();return}const Ce=Os(W);lt.current=new Set(lt.current),lt.current.delete(Ce),bt.current=new Set(bt.current),bt.current.delete(Ce),await nn(Ce)},[nn,cr]),wr=i.useRef(""),Ls=i.useRef("");i.useEffect(()=>{if(!x)return;const W=`${x}|h${g?"1":"0"}|g${b?"1":"0"}`,Ce=wr.current!==x,Ue=Ls.current!==W;!Ce&&!Ue||(Ce&&(wr.current=x,ct(""),tt(null),Mt(""),Pt(null),D(!1)),Ue&&(Ls.current=W,lt.current=new Set,bt.current=new Set,Be.current=new Map,Xe({}),Ke(Ge=>Object.keys(Ge).length===0?Ge:{}),nn(x)))},[nn,x,b,g]),i.useEffect(()=>{if(!n.listDirectory)return;const W=()=>{if(!document.hidden&&ue.length>0)for(const Ce of ue)Fn(Ce)};return document.addEventListener("visibilitychange",W),()=>document.removeEventListener("visibilitychange",W)},[ue,n.listDirectory,Fn]),i.useEffect(()=>{if(!n.listDirectory||ue.length===0)return;const W=setInterval(()=>{if(!document.hidden)for(const Ce of ue)Fn(Ce)},8e3);return()=>clearInterval(W)},[ue,n.listDirectory,Fn]);const no=i.useCallback(async W=>{if(W?.preventDefault(),!jn||!tn)return;En(!0);const Ce=()=>{Rn(null)},Ue=dt=>{me.error(dt)},Ge=()=>{En(!1)};if(tn==="createFile"){if(!Es.trim()){Ue(e("sidebarFilesTree.toast.filenameRequired")),Ge();return}if(!n.writeFile){Ue(e("sidebarFilesTree.toast.writeNotSupported")),Ge();return}const dt=jn.path,it=dt?`${dt}/`:"",Wt=Os(`${it}${Es.trim()}`);await n.writeFile(Wt,"").then(async Ss=>{Ss.success&&(me.success(e("sidebarFilesTree.toast.fileCreated")),await Fn(dt)),Ce()}).catch(()=>Ue(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(tn==="createFolder"){if(!Es.trim()){Ue(e("sidebarFilesTree.toast.folderNameRequired")),Ge();return}const dt=jn.path,it=dt?`${dt}/`:"",Wt=Os(`${it}${Es.trim()}`);await n.createDirectory(Wt).then(async Ss=>{Ss.success&&(me.success(e("sidebarFilesTree.toast.folderCreated")),await Fn(dt)),Ce()}).catch(()=>Ue(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(tn==="rename"){if(!Es.trim()){Ue(e("sidebarFilesTree.toast.nameRequired")),Ge();return}if(!n.rename){Ue(e("sidebarFilesTree.toast.renameNotSupported")),Ge();return}const dt=jn.path,it=dt.split("/").slice(0,-1).join("/"),Wt=it?`${it}/`:"",Ss=Os(`${Wt}${Es.trim()}`);await n.rename(dt,Ss).then(async Ts=>{Ts.success&&(me.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await Fn(it),x&&se(x,dt),(U?.path===dt||U?.path.startsWith(`${dt}/`))&&(x&&G(x,null),ct(""),tt(null),Mt(""),Pt(null),d&&D(!1))),Ce()}).catch(()=>Ue(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(tn==="delete"){if(!n.delete){Ue(e("sidebarFilesTree.toast.deleteNotSupported")),Ge();return}const dt=jn.path,it=dt.split("/").slice(0,-1).join("/");await n.delete(dt).then(async Wt=>{Wt.success&&(me.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await Fn(it),x&&se(x,dt),(U?.path===dt||U?.path.startsWith(`${dt}/`))&&(x&&G(x,null),ct(""),tt(null),Mt(""),Pt(null),d&&D(!1))),Ce()}).catch(()=>Ue(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}Ge()},[tn,jn,Es,n,Fn,d,se,x,U?.path,G,e]);i.useEffect(()=>{if(!h){pt([]),vt(!1);return}const W=A.trim();if(!W){pt([]),vt(!1);return}let Ce=!1;return vt(!0),C(h,W,150,{includeHidden:g,respectGitignore:!b,type:"file"}).then(Ue=>{if(Ce)return;const dt=Ue.filter(it=>b||!Kv(it.path)).map(it=>({name:it.name,path:Os(it.path),type:"file",extension:it.extension,relativePath:it.relativePath}));pt(dt)}).catch(()=>{Ce||pt([])}).finally(()=>{Ce||vt(!1)}),()=>{Ce=!0}},[h,A,C,g,b]);const Pi=i.useCallback(async(W,Ce)=>{if(n.readFile)return(await n.readFile(W,{...Ce??{},directory:x||void 0})).content??"";const Ue=new URLSearchParams({path:W});Ce?.allowOutsideWorkspace&&Ue.set("allowOutsideWorkspace","true"),Ce?.outsideFileGrant&&Ue.set("outsideFileGrant",Ce.outsideFileGrant),Ce?.optional&&Ue.set("optional","true"),x&&Ue.set("directory",x);const Ge=await gs(`/api/fs/read?${Ue.toString()}`,{cache:Ce?.optional?"no-store":"default"});if(!Ge.ok){const dt=await Ge.json().catch(()=>({error:Ge.statusText}));throw new Error(dt.error||e("filesView.error.readFileFailed"))}return Ge.text()},[n,x,e]),Qn=i.useCallback(async(W,Ce)=>{if(n.statFile){const Ue=await n.statFile(W,{...Ce??{},directory:x||void 0});return{path:Ue.path,size:Ue.size,mtimeMs:Ue.mtimeMs}}return null},[n,x]);i.useEffect(()=>{if(!x||!n.statFile||Pe.length===0)return;let W=!1;const Ce=[...Pe];return Promise.all(Ce.map(async Ue=>{try{const Ge=await n.statFile?.(Ue,{directory:x||void 0});!W&&Ge&&!Ge.isFile&&se(x,Ue)}catch(Ge){!W&&ju(Ge)&&se(x,Ue)}})),()=>{W=!0}},[n,Pe,se,x]);const li=i.useMemo(()=>at.length>lo?`${at.slice(0,lo)}
30
-
31
- … truncated …`:at,[at]),rn=Kt!==li,Ln=i.useCallback(async()=>{if(!U||!n.writeFile)return me.error(e("filesView.toast.savingNotSupported")),!1;if(!rn)return!0;if(Kt===""&&at!==""&&Lt!==U.path)return console.warn(`[saveDraft] refusing to save empty draft for "${U.path}" (${at.length} bytes were expected). The file may have been read during a concurrent write (O_TRUNC race). Try again after content finishes loading if the save was intentional.`),!1;Dt(!0);try{const W=Jv(Kt,fs);return(await n.writeFile(U.path,W))?.success?(ct(Kt),U?.path&&hd(U.path)&&(hs.current=Kt,os.current=Kt),Qn(U.path).then(Ue=>{Ue&&(Xt.current=Ue)}).catch(()=>{}),!0):(me.error(e("filesView.toast.writeFileFailed")),!1)}catch(W){return me.error(W instanceof Error?W.message:e("filesView.toast.saveFailed")),!1}finally{Dt(!1)}},[Kt,at,n,rn,fs,Lt,Qn,U,e]);i.useEffect(()=>{if(!rn){cs(null);return}const W=Ce=>xt.current?(xt.current=!1,!0):(je(!0),ft.current=Ce,!1);return cs(W),()=>{Me.getState().mainTabGuard===W&&cs(null)}},[rn,cs]),i.useEffect(()=>{try{window.localStorage.setItem(jf,bs?"true":"false")}catch{}},[bs]),i.useEffect(()=>{bs||(Ds("idle"),gt.current&&(clearTimeout(gt.current),gt.current=null))},[bs]);const Wr=1500;i.useEffect(()=>{const W=!!(U&&n.writeFile);if(!(!bs||!rn||!W||$t))return gt.current=setTimeout(()=>{Ln().then(Ce=>{Ce&&(Ds("saved"),setTimeout(()=>Ds("idle"),2e3))})},Wr),()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)}},[bs,Kt,rn,U,n.writeFile,$t,Ln]),i.useEffect(()=>{Ds("idle")},[U?.path]),i.useEffect(()=>{const W=Ce=>{ac(Ce)&&(Ce.key.toLowerCase()==="s"?(Ce.preventDefault(),gt.current&&(clearTimeout(gt.current),gt.current=null),$t||Ln().then(Ue=>{Ue&&(Ds("saved"),setTimeout(()=>Ds("idle"),2e3))})):Ce.key.toLowerCase()==="f"&&(Ce.preventDefault(),R(!0)))};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[$t,Ln]);const Ii=i.useCallback(async W=>{const Ce=Rs.current+1;Rs.current=Ce;const Ue=()=>{if(!x)return!1;const Ts=on.getState().byRoot[x],dr=Ts?.selectedPath??Ts?.openPaths[0]??null;return Rs.current===Ce&&dr===W.path};tt(null),Mt(""),Pt(null);const Ge=qi(W.path),dt=W.path.toLowerCase().endsWith(".svg"),it=pd(W.path);if(d&&D(!0),r.isDesktop&&Ge&&!dt){ct(""),yt(""),st(!0);return}if(!r.isDesktop&&Ge&&!dt){ct(""),yt(""),Pt(W.path),st(!1);return}if(it){ct(""),yt(""),Pt(W.path),st(!1);return}st(!0);const Wt=fd(W.path),Ss={allowOutsideWorkspace:t==="editor-only"&&!!x&&!va(W.path,x),outsideFileGrant:Wt};await Pi(W.path,Ss).then(Ts=>{if(!Ue())return;const dr=Sf(Ts);ms(Yv(Ts)),ct(dr),hs.current=dr,os.current=dr,yt(dr.length>lo?`${dr.slice(0,lo)}
32
-
33
- … truncated …`:dr),Pt(W.path),Qn(W.path,Ss).then(Zn=>{Zn&&Ue()&&(Xt.current=Zn)}).catch(()=>{})}).catch(Ts=>{if(Ue()){if(qv(Ts)){if(st(!1),x&&G(x,null),tt(null),ct(""),yt(""),Pt(null),Xt.current=null,k.trim().length>0&&w(""),d&&D(!1),x){const Zn=[...wu(W.path,x),W.path];Zn.length>0&&pe(x,Zn);for(const qa of Zn)lt.current.has(qa)||nn(qa)}return}if(ju(Ts)){x&&se(x,W.path),ct(""),yt(""),tt(null),Xt.current=null,d&&D(!1);return}ct(""),yt(""),tt(Ts instanceof Error?Ts.message:e("filesView.error.readFileFailed")),Xt.current=null}}).finally(()=>{Ue()&&st(!1)})},[pe,d,nn,t,Pi,Qn,se,x,r.isDesktop,k,G,e]),Ur=i.useCallback(async(W,Ce)=>{if(!x)return;const Ue=wu(W,x),Ge=Ce?[...Ue,W]:Ue;Ge.length>0&&pe(x,Ge);const dt=Ge.map(it=>{if(!lt.current.has(it))return nn(it)}).filter(Boolean);await Promise.all(dt)},[pe,nn,x]),ee=i.useCallback((W,Ce)=>{const Ue=Ce.findIndex(Ge=>Ge.path===W);return Ue===-1||Ce.length<=1?null:Ce[Ue+1]??Ce[Ue-1]??null},[]),j=i.useCallback(async W=>{if(xt.current)xt.current=!1;else if(rn){je(!0),et.current=W;return}x&&(G(x,W.path),K(x,W.path),Ur(W.path,!1)),tt(null),Mt(""),ct(""),hs.current="",os.current="",yt(""),Pt(null),d&&D(!0)},[K,Ur,rn,d,x,G]);i.useEffect(()=>{U?.path&&Ur(U.path,!1)},[Ur,U?.path]),i.useEffect(()=>{if(!U){Rs.current+=1,st(!1);return}Lt!==U.path&&Ii(U)},[Ii,Lt,U]);const Z=i.useRef(rn);Z.current=rn,i.useEffect(()=>{if(!U?.path||Lt!==U.path)return;let W=!1;const Ce=window.setInterval(()=>{document.hidden||Qn(U.path,Le).then(Ue=>{if(W||!Ue)return;const Ge=Xt.current;if(!Ge||Ge.path!==U.path){Xt.current=Ue;return}const dt=Ue.mtimeMs!==void 0&&Ge.mtimeMs!==void 0&&Ue.mtimeMs!==Ge.mtimeMs,it=Ue.size!==Ge.size;!dt&&!it||Z.current||(Xt.current=Ue,Pt(null))}).catch(()=>{})},2e3);return()=>{W=!0,window.clearInterval(Ce)}},[Lt,Qn,U?.path,Le]);const le=i.useCallback(()=>{const W=et.current,Ce=ft.current,Ue=Ae.current;if(et.current=null,ft.current=null,Ae.current=null,xt.current=!0,je(!1),yt(li),Ue){x&&he(x,Ue),U?.path===Ue&&(W?j(W):(x&&G(x,null),ct(""),tt(null),Mt(""),Pt(null),d&&D(!1)));return}if(W){j(W);return}Ce&&(cs(null),Me.getState().setActiveMainTab(Ce))},[li,j,d,he,x,U?.path,cs,G]),We=i.useCallback(async()=>{const W=et.current,Ce=ft.current,Ue=Ae.current;if(!await Ln()){xt.current=!1;return}if(et.current=null,ft.current=null,Ae.current=null,xt.current=!0,je(!1),Ue){x&&he(x,Ue),U?.path===Ue&&(W?await j(W):(x&&G(x,null),ct(""),tt(null),Mt(""),Pt(null),d&&D(!1)));return}if(W){await j(W);return}Ce&&(cs(null),Me.getState().setActiveMainTab(Ce))},[j,d,he,x,Ln,U?.path,cs,G]),Ye=i.useCallback(W=>{const Ce=U?.path===W,Ue=ee(W,z);if(Ce&&rn){je(!0),et.current=Ue,Ae.current=W;return}if(x&&he(x,W),!!Ce){if(Ue){j(Ue);return}x&&G(x,null),ct(""),tt(null),Mt(""),Pt(null),d&&D(!1)}},[ee,j,rn,d,z,he,x,U?.path,G]),Tt=i.useCallback(W=>{if(Pe.includes(W))return"open";if(v?.files){const Ce=W.startsWith(x+"/")?W.slice(x.length+1):W,Ue=v.files.find(Ge=>Ge.path===Ce);if(Ue){if(Ue.index==="A"||Ue.working_dir==="?")return"git-added";if(Ue.index==="D")return"git-deleted";if(Ue.index==="M"||Ue.working_dir==="M")return"git-modified"}}return null},[Pe,v,x]),Rt=i.useCallback(W=>{if(!v?.files)return null;const Ce=W.startsWith(x+"/")?W.slice(x.length+1):W,Ue=Ce?`${Ce}/`:"";let Ge=0,dt=0;for(const it of v.files)it.path.startsWith(Ue)&&((it.index==="M"||it.working_dir==="M")&&Ge++,(it.index==="A"||it.working_dir==="?")&&dt++);return Ge+dt>0?{modified:Ge,added:dt}:null},[v,x]),ys=i.useCallback(async W=>{const Ce=Os(W);x&&($(x,Ce),lt.current.has(Ce)||await nn(Ce))},[nn,x,$]),Gs=i.useMemo(()=>({canRename:rr,canCreateFile:sn,canCreateFolder:Qs,canDelete:xr,canReveal:br}),[rr,sn,Qs,xr,br]);function Ks(W,Ce){const Ue=He[W]??[];return Ue.map((Ge,dt)=>{const it=Ge.type==="directory",Wt=it&&ue.includes(Ge.path),Ss=U?.path===Ge.path,Ts=dt===Ue.length-1;return s.jsxs("li",{className:"relative",children:[Ce>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ts&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(Zv,{node:Ge,root:x,isExpanded:Wt,isActive:Ss,isMobile:d,alwaysShowActions:u,status:it?void 0:Tt(Ge.path),badge:it?Rt(Ge.path):void 0,permissions:Gs,downloadFile:n.downloadFile,contextMenuPath:sr,setContextMenuPath:Br,rightClickMenuPath:Vn,setRightClickMenuPath:_r,onSelect:j,onToggle:ys,onRevealPath:Mn,onOpenDialog:nt}),it&&Wt&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[qe[Ge.path]?s.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:qe[Ge.path],children:qe[Ge.path]}),s.jsxs(ze,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Fn(Ge.path)},children:[s.jsx(T,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,Ks(Ge.path,Ce+1)]})]},Ge.path)})}const us=!!(U?.path&&qi(U.path)),vr=!!(U?.path&&U.path.toLowerCase().endsWith(".svg")),xn=!!(U?.path&&pd(U.path)),Ec=i.useMemo(()=>Os(Fs?.path??""),[Fs?.path]),Ri=!!(Fs&&Ec&&Ie&&Ie===Ec&&!ge&&!wt&&!us&&!xn),Hr=i.useMemo(()=>Wl(x,Ie),[Ie,x]),Zf=!!(U&&(!us||vr)&&!xn&&at.length>0),eh=!!(U&&Hr.length>0),Xn=!!(U&&!_e&&!us&&!xn&&n.writeFile&&at.length<=lo),Ei=!!(U?.path&&Su(U.path)),_a=!!(U?.path&&Xv(U.path)),Ro=!!(U?.path&&Uo(U.path)),ro=!!(U?.path&&hd(U.path)),Va=!!(U&&!us&&!xn)&&!Ei&&!ro&&!(Ro&&ae==="preview"),Eo=i.useMemo(()=>Ie?Mm(Ie):null,[Ie]),[Mc,$a]=i.useState(null);i.useEffect(()=>{let W=!1;const Ce=U?.path;if(!Ce||Eo){$a(null);return}return $a(null),Wp(Ce).then(Ue=>{W||$a(Ue)}),()=>{W=!0}},[U?.path,Eo]),i.useEffect(()=>{!Xn&&ne==="edit"&&Y("view")},[Xn,ne]);const za="openchamber:files:md-viewer-mode",Wa="openchamber:files:html-viewer-mode",Ua="openchamber:files:json-viewer-mode";i.useEffect(()=>{const W=U?.path;if(!W)return;const Ce=Hs?"view":"edit";Y(fe.current[W]??Ce);let Ue=Hs?"preview":"edit";try{const it=localStorage.getItem(za);(it==="preview"||it==="edit")&&(Ue=it)}catch{}de(De.current[W]??Ue);let Ge=Hs?"preview":"edit";try{const it=localStorage.getItem(Wa);(it==="preview"||it==="edit")&&(Ge=it)}catch{}ve(Re.current[W]??Ge),H(Fe.current[W]??"preview");let dt=Hs?"tree":"text";try{const it=localStorage.getItem(Ua);(it==="tree"||it==="text")&&(dt=it)}catch{}ke(dt)},[U?.path,Hs]);const th=i.useCallback(W=>{const Ce=U?.path;Ce&&(fe.current[Ce]=W),Y(W)},[U?.path]),sh=i.useCallback(W=>{const Ce=U?.path;Ce&&(De.current[Ce]=W),de(W);try{localStorage.setItem(za,W)}catch{}},[U?.path]),io=i.useCallback(()=>te,[te]),nh=i.useCallback(W=>{ke(W);try{localStorage.setItem(Ua,W)}catch{}},[]),rh=i.useCallback(W=>{const Ce=U?.path;Ce&&(Re.current[Ce]=W),ve(W);try{localStorage.setItem(Wa,W)}catch{}},[U?.path]),ih=i.useCallback(W=>{const Ce=U?.path;if(Ce&&(Fe.current[Ce]=W),qt.current&&(clearTimeout(qt.current),qt.current=null),Is.current!==null&&(cancelAnimationFrame(Is.current),Is.current=null),W==="edit")yt(hs.current||at),H(W);else{hs.current=Kt;const Ue=Ce;H("edit"),Is.current=requestAnimationFrame(()=>{Is.current=requestAnimationFrame(()=>{Is.current=null,!(x&&Ue&&on.getState().byRoot[x]?.selectedPath!==Ue)&&(ce(Ge=>Ge+1),H("preview"))})});return}},[Kt,at,x,U?.path]),Ha=i.useCallback(async(W,Ce)=>{if(!n.writeFile||Ce===os.current)return!1;if(!(await n.writeFile(W,Ce))?.success)return me.error(e("filesView.toast.writeFileFailed")),!1;hs.current=Ce,os.current=Ce,yt(Ce);const Ge=await Qn(W,Le).catch(()=>null);return Ge&&(Xt.current=Ge),!0},[n,Qn,Le,e]);i.useEffect(()=>()=>{qt.current&&(clearTimeout(qt.current),qt.current=null),Is.current!==null&&(cancelAnimationFrame(Is.current),Is.current=null)},[J,U?.path]);const oh=i.useCallback(W=>{if(hs.current=W,!U?.path||J!=="preview"||!n.writeFile)return;qt.current&&clearTimeout(qt.current);const Ce=U.path;qt.current=setTimeout(()=>{qt.current=null,Ha(Ce,W).then(Ue=>{Ue&&(Us(!0),setTimeout(()=>Us(!1),1500))}).catch(Ue=>{me.error(Ue instanceof Error?Ue.message:e("filesView.toast.saveFailed"))})},Wr)},[J,n.writeFile,Ha,U?.path,e]),ah=i.useMemo(()=>ro&&(hs.current||Kt)||at,[Kt,at,ro]),Fc=i.useCallback(()=>ae,[ae]);i.useEffect(()=>{const W=Ue=>{const Ge=Ue?"view":"edit",dt=Ue?"preview":"edit",it=Ue?"tree":"text";for(const Wt of Pe)fe.current[Wt]=Ge,Su(Wt)&&(De.current[Wt]=dt),Uo(Wt)&&(Re.current[Wt]=dt);Y(Ge),de(dt),ve(dt),ke(it);try{localStorage.setItem(za,dt),localStorage.setItem(Wa,dt),localStorage.setItem(Ua,it)}catch{}},Ce=Ue=>{const Ge=!!Ue.detail?.enabled;W(Ge)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",Ce),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",Ce)}},[Pe]),i.useEffect(()=>{if(!Fs||!x)return;const W=()=>{typeof window>"u"||cn.current===null&&(cn.current=window.requestAnimationFrame(()=>{cn.current=null,ts(Ir=>Ir+1)}))},Ce=(Ir,di)=>{if(Ir.state.doc.length!==di.length)return!1;if(di.length===0)return!0;const Ya=Math.min(128,di.length);if(Ir.state.sliceDoc(0,Ya)!==di.slice(0,Ya))return!1;const Gc=Math.max(0,di.length-Ya);return Ir.state.sliceDoc(Gc,di.length)===di.slice(Gc)},Ue=Os(Fs.path);if(!Ue){hn(null),_s.current={key:"",attempts:0};return}const Ge=`${Ue}:${Fs.line}:${Fs.column??1}`;if(_s.current.key!==Ge&&(_s.current={key:Ge,attempts:0}),U?.path!==Ue){if(en)return;j(ye(Ue));return}if(ge||Lt!==Ue)return;if(wt||us||xn){hn(null),_s.current={key:"",attempts:0};return}if(!Xn)return;if(ne!=="edit"){Y("edit");return}const dt=Vt.current;if(!dt){W();return}if(!Ce(dt,Kt)){W();return}const it=Math.max(1,Math.min(Fs.line,dt.state.doc.lines)),Wt=dt.state.doc.line(it),Ss=Math.max(1,Fs.column||1),Ts=Math.max(0,Wt.to-Wt.from),dr=Math.min(Ts,Ss-1),Zn=Wt.from+dr;if(!(dt.state.selection.main.head===Zn)||_s.current.attempts===0){_s.current.attempts+=1,dt.dispatch({selection:{anchor:Zn},effects:Xr.scrollIntoView(Zn,{y:"center"})}),dt.focus(),W();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const Ir=Vt.current;Ir&&(Ir.dispatch({selection:{anchor:Zn},effects:Xr.scrollIntoView(Zn,{y:"center"})}),Ir.focus())}),hn(null),_s.current={key:"",attempts:0}},[Xn,en,Kt,rs,wt,ge,us,xn,Lt,j,Fs,x,U?.path,hn,ne,ye]),i.useEffect(()=>{if(!or||!x)return;const W=Os(or);if(!W){Xs(null);return}if(U?.path!==W){if(en)return;j(ye(W));return}if(!(ge||Lt!==W||wt||us||xn)){if(Xn&&ne==="edit"){const Ce=Vt.current;if(!Ce)return;Ce.focus()}Xs(null)}},[Xn,en,wt,ge,j,us,xn,Lt,or,x,U?.path,Xs,ne,ye]);const Mi=i.useCallback(W=>{if(!d||!W||!W.hasFocus||typeof window>"u")return;const Ce=window.visualViewport;if(!Ce)return;const Ue=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,Ue-(Ce.offsetTop+Ce.height))<=0)return;const dt=W.state.selection.main.head,it=W.coordsAtPos(dt);if(!it)return;const Wt=Math.round(Ce.offsetTop+Ce.height),Ts=it.bottom+20-Wt;Ts<=0||(W.scrollDOM.scrollTop+=Ts)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const W=()=>{window.requestAnimationFrame(()=>{Mi(Vt.current)})},Ce=window.visualViewport;return Ce?.addEventListener("resize",W),Ce?.addEventListener("scroll",W,{passive:!0}),document.addEventListener("selectionchange",W),()=>{Ce?.removeEventListener("resize",W),Ce?.removeEventListener("scroll",W),document.removeEventListener("selectionchange",W)}},[d,Mi]),i.useEffect(()=>{if(!Xn||ne!=="edit"||d)return;const W=ei("open_go_to_line",yr),Ce=Ue=>{const Ge=Ue.target;if(Ge?.closest('[role="dialog"]'))return;const dt=!!Ge?.closest(".cm-editor");Ge?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!dt||!document.activeElement?.closest(".cm-editor")||Jo(Ue,W)&&(Ue.preventDefault(),$n(!0))};return window.addEventListener("keydown",Ce),()=>window.removeEventListener("keydown",Ce)},[Xn,d,yr,ne]);const Lc=i.useMemo(()=>{if(!U?.path)return[Ml(o)];const W=vi(U.path),Ce=[Ml(o,W?{syntaxColors:!1}:void 0)],Ue=Eo??Mc;return Ue&&Ce.push(Ue),W&&Ce.push(Zm({language:W,themeName:o.metadata.id,theme:Fm(o)})),N&&Ce.push(Xr.lineWrapping),d&&Ce.push(Xr.updateListener.of(Ge=>{Ge.view.hasFocus&&(Ge.selectionSet||Ge.focusChanged||Ge.viewportChanged||Ge.geometryChanged)&&window.requestAnimationFrame(()=>{Mi(Ge.view)})})),Ce},[o,U?.path,Eo,Mc,N,d,Mi]),Oc=i.useMemo(()=>({light:Oe.metadata.id,dark:Ee.metadata.id}),[Oe.metadata.id,Ee.metadata.id]),Fi=U?.path&&us&&!r.isDesktop&&!vr?`${U.path}|${Le.allowOutsideWorkspace?"outside":"workspace"}|${Le.outsideFileGrant??""}`:"",ci=U?.path&&xn?`${U.path}|${Le.allowOutsideWorkspace?"outside":"workspace"}|${Le.outsideFileGrant??""}`:"",Li=U?.path&&Ro&&ae==="preview"&&!r.isVSCode?U.path:"";i.useEffect(()=>{if(!Fi){ss("");return}let W=!1;return ss(""),fo(pr()).then(Ce=>{!W&&Ce&&ss(Fi)}).catch(()=>{}),()=>{W=!0}},[Fi]);const Bc=!!(Fi&&zt!==Fi);i.useEffect(()=>{if(!Li){Ft("");return}let W=!1;return Ft(""),fo(pr()).then(Ce=>{!W&&Ce&&Ft(Li)}).catch(Ce=>{W||tt(Ce instanceof Error?Ce.message:e("filesView.error.readFileFailed"))}),()=>{W=!0}},[Li,e]);const lh=!!(Li&&Bt!==Li);i.useEffect(()=>{if(!ci){es("");return}let W=!1;return es(""),fo(pr()).then(Ce=>{!W&&Ce&&es(ci)}).catch(Ce=>{W||(tt(Ce instanceof Error?Ce.message:e("filesView.error.readFileFailed")),es(ci))}),()=>{W=!0}},[ci,e]);const _c=!!(ci&&Jt!==ci),Vc=U?.path&&us?r.isDesktop?vr?`data:${gd(U.path)};utf8,${encodeURIComponent(at)}`:ut:vr?`data:${gd(U.path)};utf8,${encodeURIComponent(at)}`:zt===Fi?wi().authenticatedAsset("/api/fs/raw",{path:U.path,allowOutsideWorkspace:Le.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Le.outsideFileGrant,directory:x||void 0}):"":"",$c=U?.path&&xn&&Jt===ci?wi().authenticatedAsset("/api/fs/raw",{path:U.path,allowOutsideWorkspace:Le.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Le.outsideFileGrant,directory:x||void 0}):"",zc=i.useCallback(W=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:$c,className:"h-full w-full border-0",title:W.name})}),[$c]);i.useEffect(()=>{let W=!1;return(async()=>{if(!r.isDesktop||!U?.path||!us||vr){It.current&&(URL.revokeObjectURL(It.current),It.current=""),Mt("");return}tt(null),It.current&&(URL.revokeObjectURL(It.current),It.current=""),await(n.readFileBinary?n.readFileBinary(U.path,Le).then(Ge=>Ge.dataUrl):(async()=>{const Ge=await gs("/api/fs/raw",{query:{path:U.path,allowOutsideWorkspace:Le.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Le.outsideFileGrant,directory:x||void 0}});if(!Ge.ok)throw new Error(e("filesView.error.readFileFailed"));const dt=await Ge.blob(),it=URL.createObjectURL(dt);return W?(URL.revokeObjectURL(it),""):(It.current=it,it)})()).then(Ge=>{W||(Mt(Ge),Pt(U.path))}).catch(Ge=>{It.current&&(URL.revokeObjectURL(It.current),It.current=""),W||(Mt(""),tt(Ge instanceof Error?Ge.message:e("filesView.error.readFileFailed")),Pt(null))}).finally(()=>{W||st(!1)})})(),()=>{W=!0}},[n,us,vr,x,r.isDesktop,U?.path,Le,e]),i.useEffect(()=>()=>{It.current&&(URL.revokeObjectURL(It.current),It.current="")},[]);const ch=i.useCallback(()=>Rn(null),[]),dh=i.useMemo(()=>sf({drafts:Jn,editingDraftId:Wn,commentText:zr,onTextChange:Di,selection:ot,isDragging:is,fileLabel:U?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:W=>({start:W.startLine,end:W.endLine}),onSave:Qt,onCancel:()=>{St(null),Pr()},onEdit:W=>{ar(W),St({start:W.startLine,end:W.endLine})},onDelete:gn}),[Pr,zr,gn,Wn,Jn,Qt,is,ot,U?.path,Di,ar]),Wc=i.useCallback((W,Ce)=>s.jsx("div",{className:"h-full",children:s.jsx(yh,{file:{name:W.name,contents:Ce,lang:vi(W.path)||void 0},options:{disableFileHeader:!0,overflow:N?"wrap":"scroll",theme:Oc,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,Oc,N]),Ga=({exitFullscreenOnly:W=!1,layout:Ce="floating"}={})=>{if(!U)return null;const Ge=Ce==="docked"?"pointer-events-auto flex flex-wrap items-center gap-1":"pointer-events-auto flex items-center gap-1 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-1 shadow-sm",dt=(it,Wt)=>s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:Wt})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:it})]});return s.jsxs("div",{className:Ge,children:[Xn&&ne==="edit"&&s.jsxs(s.Fragment,{children:[$t?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):bs&&In==="saved"&&!rn?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(T,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):rn?dt(e(bs?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${Qa()}+S`}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{Ln()},className:"h-6 gap-1 px-1 text-muted-foreground opacity-80 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:e(bs?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${Qa()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${Qa()}+S`}),children:s.jsx(T,{name:"save-3",className:"size-4"})})):null,dt(e(bs?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>Yn(it=>!it),className:Te("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",bs?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(bs?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(bs?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:bs?s.jsx(T,{name:"file-check-fill",className:"size-4"}):s.jsx(T,{name:"file-check",className:"size-4"})}))]}),s.jsxs(Ws,{onOpenChange:ie,children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx($s,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.openInDesktopApp"),"aria-label":e("filesView.editor.openInDesktopApp"),children:s.jsx(T,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(zs,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Vr.map(it=>s.jsxs(ls,{className:"flex items-center gap-2",onClick:()=>{re(it)},children:[s.jsx($v,{label:it.label,iconDataUrl:it.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:it.label})]},it.id)),Dr?s.jsxs(ls,{className:"flex items-center gap-2",onClick:()=>{ir(!0)},children:[s.jsx(T,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!us&&!xn&&s.jsxs(s.Fragment,{children:[dt(e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>M(!N),className:Te("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",N?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(T,{name:"text-wrap",className:"size-4"})})),ne==="edit"&&s.jsxs(s.Fragment,{children:[dt(e("filesView.editor.findInFile"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:it=>{R(!V),it.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.findInFile"),children:s.jsx(T,{name:"search",className:"size-4"})})),dt(e("filesView.editor.goToLine"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:it=>{$n(Wt=>!Wt),it.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.goToLine"),children:s.jsx(T,{name:"menu-fold-2",className:"size-4"})})),s.jsx(Ov,{open:ws,onOpenChange:$n,view:Vt.current,variant:"inline"})]})]}),Va&&Xn&&!_a&&!Ro&&s.jsx(Xo,{currentMode:ne==="view"?"preview":"edit",onToggle:()=>{th(ne==="view"?"edit":"view")}}),(Ei||Uo(U?.path??""))&&s.jsx(Xo,{currentMode:Ei?io():Fc(),onToggle:()=>{Uo(U?.path??"")?rh(Fc()==="preview"?"edit":"preview"):sh(io()==="preview"?"edit":"preview")}}),Ei&&io()==="preview"&&Sn&&s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent","aria-label":e(Ot?"filesView.tts.stopSpeaking":"filesView.tts.readAloud"),onClick:()=>{Ot?Et():at.trim()&&Zt(at)},children:Ot?s.jsx(T,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(T,{name:"volume-up",className:"size-4"})})}),s.jsx(Ct,{sideOffset:8,children:e(Ot?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),ro&&s.jsxs(s.Fragment,{children:[s.jsx(Xo,{currentMode:J,onToggle:()=>ih(J==="preview"?"edit":"preview")}),J==="preview"&&s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{const it=As.current?.getXml();if(qt.current&&(clearTimeout(qt.current),qt.current=null),U?.path&&it){if(!await Ha(U.path,it))return;Us(!0),setTimeout(()=>Us(!1),1500)}},className:"size-6 p-0 text-foreground hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.diagram.saveDiagram"),children:Ys?s.jsx(T,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(T,{name:"save-3",className:"size-4"})})]}),_a&&dt(e(be==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>nh(be==="tree"?"text":"tree"),className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:e(be==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:be==="tree"?s.jsx(T,{name:"code-sslash",className:"size-4"}):s.jsx(T,{name:"node-tree",className:"size-4"})})),Zf&&dt(e("filesView.editor.copyFileContents"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await tr(at)).ok?(nr(!0),rt.current!==null&&window.clearTimeout(rt.current),rt.current=window.setTimeout(()=>{nr(!1)},1200)):me.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFileContents"),"aria-label":e("filesView.editor.copyFileContents"),children:Js?s.jsx(T,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(T,{name:"clipboard",className:"size-4"})})),eh&&dt(e("filesView.editor.copyFilePathTitle",{path:Hr}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await tr(Hr)).ok?(as(!0),_t.current!==null&&window.clearTimeout(_t.current),_t.current=window.setTimeout(()=>{as(!1)},1200)):me.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFilePathTitle",{path:Hr}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:Hr}),children:un?s.jsx(T,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(T,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&&dt(e("filesView.editor.saveFile"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{const it=n.downloadFile;it&&it(U.path).catch(Wt=>{console.error("Download failed:",Wt),me.error(e("sidebarFilesTree.toast.operationFailed"))})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.saveFile"),"aria-label":e("filesView.editor.saveFile"),children:s.jsx(T,{name:"download",className:"size-4"})})),W?dt(e("filesView.editor.exitFullscreen"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>E(!1),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.exitFullscreen"),"aria-label":e("filesView.editor.exitFullscreen"),children:s.jsx(T,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&&dt(e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>E(!P),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:P?s.jsx(T,{name:"fullscreen-exit",className:"size-4"}):s.jsx(T,{name:"fullscreen",className:"size-4"})}))]})},Ka=s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[s.jsx(Cs,{open:en,onOpenChange:W=>{W||je(!0)},children:s.jsxs(ks,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(Ms,{children:[s.jsx(Ps,{children:e("filesView.unsaved.title")}),s.jsx(qs,{children:e("filesView.unsaved.description")})]}),s.jsxs(qn,{children:[s.jsx(ze,{variant:"outline",onClick:()=>{We()},disabled:$t,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:e("filesView.unsaved.saveChanges")}),s.jsx(ze,{variant:"destructive",onClick:le,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:Te("flex flex-col flex-shrink-0",y&&"border-b border-border/40"),children:[y?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&I&&s.jsx("button",{type:"button",onClick:()=>D(!1),"aria-label":e("filesView.editor.back"),className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(T,{name:"arrow-left-s",className:"size-5"})}),d?U?s.jsxs(Ws,{children:[s.jsx($s,{asChild:!0,children:s.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":e("filesView.editor.openFilesAria"),children:[s.jsx(Mr,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(vu,{name:U.name}),s.jsx(T,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(zs,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:z.map(W=>{const Ce=U?.path===W.path;return s.jsxs(ls,{onSelect:Ue=>{if(Ue.target.closest("[data-close-open-file]")){Ue.preventDefault();return}Ce||j(W)},className:Te("flex min-w-0 items-center justify-between gap-2 overflow-hidden",Ce&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[s.jsx(Mr,{filePath:W.path,extension:W.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(vu,{name:W.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:Ue=>{Ue.preventDefault(),Ue.stopPropagation()},onClick:Ue=>{Ue.preventDefault(),Ue.stopPropagation(),Ye(W.path)},className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":e("filesView.editor.closeFileAria",{name:W.name}),children:s.jsx(T,{name:"close",className:"size-3.5"})})]},W.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):z.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[L.left&&s.jsx("div",{className:"pointer-events-none absolute left-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-r from-background to-transparent"}),L.right&&s.jsx("div",{className:"pointer-events-none absolute right-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-l from-background to-transparent"}),s.jsx("div",{ref:X,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:z.map(W=>{const Ce=U?.path===W.path;return s.jsxs("div",{title:Wl(x,W.path),className:Te("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",Ce?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[s.jsx(Mr,{filePath:W.path,extension:W.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{Ce||j(W)},className:"max-w-[12rem] truncate text-left",children:W.name}),s.jsx("button",{type:"button",onClick:Ue=>{Ue.stopPropagation(),Ye(W.path)},className:Te("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Ce&&!u&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:W.name}),children:s.jsx(T,{name:"close",className:"size-3.5"})})]},W.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,pn&&!d&&U?s.jsxs("div",{className:"flex min-w-0 items-center gap-3 border-t border-border/40 bg-[var(--surface-subtle)] px-3 py-1",children:[Hr?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Hr,children:Hr}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:Ga({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[U&&!V&&!(pn&&!d)&&s.jsx("div",{ref:F,className:"absolute right-3 top-3 z-30",onMouseEnter:()=>O(!0),onMouseLeave:()=>{_.current>0||O(!1)},children:B?Ga():s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>O(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":e("filesView.editor.showControlsAria"),title:e("filesView.editor.controlsTitle"),children:s.jsx(T,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})}),s.jsx(An,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:U?ge||Bc||_c?p?s.jsx("div",{className:"p-3"}):s.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.loading")]}):wt?s.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:wt}):us?s.jsx("div",{className:"flex h-full items-center justify-center p-3",children:s.jsx("img",{src:Vc,alt:U?.name??e("filesView.editor.imageAltFallback"),className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):xn?zc(U):U&&ro&&J==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(_v,{ref:As,xml:ah,onChange:oh},`${U.path}:${q}`)}):U&&_a&&be==="tree"?s.jsx(Vs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.jsonViewerUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToTextMode")})]}),children:s.jsx("div",{className:"h-full overflow-auto",children:s.jsx(Up,{jsonString:at,maxHeight:"100%",initiallyExpandedDepth:2})})}):U&&Ei&&io()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-3",children:[at.length>500*1024&&s.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:e("filesView.warning.largeFilePreviewLimited",{sizeKb:Math.round(at.length/1024)})}),s.jsx(Vs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(No,{content:at,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):U&&Ro&&ae==="preview"?lh?s.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground typography-ui-label",children:e("common.loading")}):s.jsx("div",{className:"h-full overflow-hidden",children:s.jsx("iframe",{src:!r.isVSCode&&Bt===Li?(()=>{const W=U.path.split("/").map(Ce=>encodeURIComponent(Ce)).join("/");return wi().authenticatedAsset(`/api/fs/serve${W.startsWith("/")?W:`/${W}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const W=U.path.substring(0,U.path.lastIndexOf("/")+1);return W?at.replace(/<head([^>]*)>/i,`<head$1><base href="${W}">`):at})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")})}):U&&Va&&ne==="view"?Wc(U,Kt):s.jsxs("div",{className:Te("relative h-full",Ri&&"overflow-hidden"),ref:ns,children:[s.jsx("div",{className:Te("h-full",Ri&&"invisible"),children:s.jsx(Fl,{value:Kt,onChange:yt,readOnly:!Xn,vimMode:mn==="vim",extensions:Lc,className:"h-full",blockWidgets:dh,onViewReady:W=>{Vt.current=W,ts(Ce=>Ce+1),window.requestAnimationFrame(()=>{Mi(W)})},onViewDestroy:()=>{Vt.current&&(Vt.current=null),ts(W=>W+1)},enableSearch:!0,searchOpen:V,onSearchOpenChange:R,highlightLines:ot?{start:Math.min(ot.start,ot.end),end:Math.max(ot.start,ot.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(W,Ce,Ue)=>{if(!(Ue instanceof MouseEvent)||Ue.button!==0)return!1;Ue.preventDefault();const Ge=W.state.doc.lineAt(Ce.from).number;if(ot&&!Ue.shiftKey&&Math.min(ot.start,ot.end)===Ge&&Math.max(ot.start,ot.end)===Ge)return St(null),Pr(),Yt.current=!1,Ht.current=null,ps(!1),!0;if(d&&ot&&!Ue.shiftKey){const dt=Math.min(ot.start,ot.end,Ge),it=Math.max(ot.start,ot.end,Ge);return St({start:dt,end:it}),Yt.current=!1,Ht.current=null,ps(!1),!0}if(Yt.current=!0,Ht.current=Ge,ps(!0),ot&&Ue.shiftKey){const dt=Math.min(ot.start,Ge),it=Math.max(ot.end,Ge);St({start:dt,end:it})}else St({start:Ge,end:Ge});return!0},mouseover:(W,Ce,Ue)=>{if(!(Ue instanceof MouseEvent)||Ue.buttons!==1||!Yt.current||Ht.current===null)return!1;const Ge=W.state.doc.lineAt(Ce.from).number,dt=Math.min(Ht.current,Ge),it=Math.max(Ht.current,Ge);return St({start:dt,end:it}),ps(!0),!1},mouseup:()=>(Yt.current=!1,Ht.current=null,ps(!1),!1)}}})}),Ri&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]}):s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:e("filesView.editor.pickFileFromTree")})})]})]}),uh=!!(x&&He[x]),Uc=x?qe[x]:null,Hc=s.jsxs("section",{className:Te("flex min-h-0 flex-col overflow-hidden",d?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[s.jsx("div",{className:Te("flex flex-col gap-2 py-2",d?"px-3":"px-2"),children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx(T,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(ln,{ref:S,value:k,onChange:W=>w(W.target.value),placeholder:e("filesView.tree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),k.trim().length>0&&s.jsx("button",{type:"button","aria-label":e("filesView.tree.search.clearAria"),className:"absolute right-2 top-2 inline-flex size-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{w(""),S.current?.focus()},children:s.jsx(T,{name:"close",className:"size-4"})})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>nt("createFile",{path:h,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFileTitle"),"aria-label":e("filesView.tree.actions.newFileTitle"),children:s.jsx(T,{name:"file-add",className:"size-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>nt("createFolder",{path:h,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFolderTitle"),"aria-label":e("filesView.tree.actions.newFolderTitle"),children:s.jsx(T,{name:"folder-add",className:"size-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{cr()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(T,{name:"refresh",className:"size-4"})})})}),s.jsx(Ct,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx(An,{outerClassName:"flex-1 min-h-0",className:Te("py-2",d?"px-3":"px-2"),children:s.jsx("ul",{className:"flex flex-col",children:At?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):Ze.length>0?Ze.map(W=>{const Ce=U?.path===W.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{j(W)},className:Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Ce?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[Nf(W.path,W.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:W.path,children:W.relativePath??W.path})]})},W.path)}):Uc?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"text-[var(--status-error)]",children:Uc}),s.jsxs(ze,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{cr()},children:[s.jsx(T,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):uh?Ks(x,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),mh=t==="full"&&P&&U&&s.jsx("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[s.jsx("div",{className:"absolute right-4 top-4 z-30",children:Ga({exitFullscreenOnly:!0})}),s.jsx(An,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:ge||Bc||_c?p?s.jsx("div",{className:"p-4"}):s.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):wt?s.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:wt}):us?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("img",{src:Vc,alt:U.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"})}):xn?zc(U):Ei&&io()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-4",children:[at.length>500*1024&&s.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:e("filesView.warning.largeFilePreviewLimited",{sizeKb:Math.round(at.length/1024)})}),s.jsx(Vs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(No,{content:at,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):Va&&ne==="view"?Wc(U,Kt):s.jsxs("div",{className:Te("relative h-full",Ri&&"overflow-hidden"),children:[s.jsx("div",{className:Te("h-full",Ri&&"invisible"),children:s.jsx(Fl,{value:Kt,onChange:yt,readOnly:!Xn,vimMode:mn==="vim",extensions:Lc,className:"h-full",onViewReady:W=>{Vt.current=W,window.requestAnimationFrame(()=>{Mi(W)})},onViewDestroy:()=>{Vt.current&&(Vt.current=null)}})}),Ri&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]})})]})});return s.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[s.jsx(e1,{activeDialog:tn,dialogData:jn,dialogInputValue:Es,onDialogInputChange:js,isDialogSubmitting:Or,onDialogSubmit:no,onClose:ch,inputRef:xs}),mh,d?I?Ka:Hc:t==="editor-only"?s.jsx("div",{className:"flex flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden bg-background",children:Ka})}):s.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[f>=700&&s.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Hc}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:Ka})]})]})},hr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},pl=(t,e)=>{const n=hr(t),r=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},t1=(t,e,n)=>pl(pl(pl(t,".opencode"),"plans"),`${e}-${n}.md`),s1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,n1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},r1=(t,e)=>{const n=hr(e.currentDirectory),r=hr(e.homeDirectory),o=hr(t);return n&&o.startsWith(n+"/")?o.slice(n.length+1):r&&o===r?"~":r&&o.startsWith(r+"/")?`~${o.slice(r.length)}`:o},i1=(t,e,n)=>{const r=hr(t.trim());if(!r)return null;const o=n?e.find(c=>c.id===n)??null:null;if(o?.path){const c=hr(o.path);if(r===c||r.startsWith(`${c}/`))return{id:o.id,path:o.path}}const a=e.filter(c=>{const l=hr(c.path);return r===l||r.startsWith(`${l}/`)}).sort((c,l)=>hr(l.path).length-hr(c.path).length)[0];return a?{id:a.id,path:a.path}:null},Cf=({targetPath:t=null})=>{const{t:e}=jt(),n=mt(Q=>Q.currentSessionId),r=mt(Q=>Q.createSession),o=mt(Q=>Q.initializeNewOpenChamberSession),a=mt(Q=>Q.sendMessage),c=mt(Q=>Q.setCurrentSession),l=fc(),d=Bs(Q=>Q.homeDirectory),m=oc(Q=>Q.planModeEnabled),f=ds(Q=>Q.projects),u=ds(Q=>Q.activeProjectId),g=an(Q=>Q.directories),b=ii()??"",h=Me(Q=>Q.setActiveMainTab),x=Me(Q=>Q.setSessionSwitcherOpen),y=_n(),{isMobile:p}=Ar(),{currentTheme:C}=Lr(),v=i.useMemo(()=>n?l.find(Q=>Q.id===n)??null:null,[n,l]),k=i.useMemo(()=>{const Q=typeof v?.directory=="string"?v.directory:"";return hr(Q||"")},[v?.directory]),w=i.useMemo(()=>hr(b||k),[b,k]),A=i.useMemo(()=>i1(w,f,u),[u,w,f]),S=i.useMemo(()=>A?g.get(A.path)?.isGitRepo===!0:!1,[A,g]),[I,D]=i.useState(null),[N,M]=i.useState(!1),[P,E]=i.useState(null),V=i.useMemo(()=>!P||!k||!d?P:r1(P,{currentDirectory:k,homeDirectory:d}),[P,k,d]),[R,B]=i.useState(""),{isPlaying:O,play:F,stop:_}=Em(),ie=Ut(Q=>Q.showMessageTTSButtons),[oe,ne]=i.useState(null),Y=i.useMemo(()=>V&&V.split("/").pop()||e("planView.file.defaultName"),[V,e]),te=i.useMemo(()=>R.trim()&&Hp(R).title||e("planView.title.default"),[R,e]),de=i.useMemo(()=>te.trim()||e("planView.title.default"),[te,e]),[be,ke]=i.useState(!1),[ae,ve]=i.useState(!1),[J,H]=i.useState("edit"),q=i.useRef(null),[ce,fe]=i.useState(null),De=i.useRef(null),Re=i.useRef(null),Fe="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const Q=localStorage.getItem(Fe);if(!Q)return;const $e=JSON.parse(Q);($e==="preview"||$e==="edit")&&H($e)}catch{}},[]);const Oe=i.useCallback(Q=>{H(Q);try{localStorage.setItem(Fe,JSON.stringify(Q))}catch{}},[]),Ee=i.useRef(!1),we=i.useRef(null),[Pe,Se]=i.useState(!1);i.useEffect(()=>{const Q=()=>{Ee.current=!1,we.current=null,Se(!1)};return document.addEventListener("mouseup",Q),()=>document.removeEventListener("mouseup",Q)},[]);const ue=i.useCallback((Q,$e)=>{const He=Q.split(`
34
- `),Ke=Math.max(1,$e.start),qe=Math.min(He.length,$e.end);return Ke>qe?"":He.slice(Ke-1,qe).join(`
35
- `)},[]),K=Qm({source:"plan",fileLabel:Y,language:P&&vi(P)||"markdown",getCodeForRange:Q=>ue(R,Xm(Q)),toStoreRange:Q=>({startLine:Q.start,endLine:Q.end}),fromDraftRange:Q=>({start:Q.startLine,end:Q.endLine})}),{drafts:he,commentText:se,setCommentText:G,editingDraftId:$,setSelection:pe,saveComment:ye,cancel:z,reset:Ne,startEdit:U,deleteDraft:Ie}=K;i.useEffect(()=>{fe(null),Ne()},[R,Ne]),i.useEffect(()=>{pe(ce)},[ce,pe]);const _e=i.useCallback(()=>{fe(null),z()},[z]),Ve=i.useCallback((Q,$e)=>{$e&&fe($e),ye(Q,$e??ce??void 0),fe(null)},[ce,ye]);i.useEffect(()=>{if(!ce)return;const Q=He=>{const Ke=He.target;Ke.closest('[data-comment-card="true"]')||Ke.closest('[data-comment-input="true"]')||Ke.closest(".oc-block-widget")||Ke.closest(".cm-gutterElement")||Ke.closest("[data-sonner-toast]")||Ke.closest("[data-sonner-toaster]")||se.trim()||(fe(null),z())},$e=window.setTimeout(()=>{document.addEventListener("click",Q)},100);return()=>{window.clearTimeout($e),document.removeEventListener("click",Q)}},[z,se,$,p,ce]);const Le=i.useMemo(()=>{const Q=P?vi(P):null,$e=!!Q&&Q!=="markdown",He=[Ml(C,$e?{syntaxColors:!1}:void 0)],Ke=Mm(P||"plan.md");return Ke&&He.push(Ke),$e&&Q&&He.push(Zm({language:Q,themeName:C.metadata.id,theme:Fm(C)})),He.push(Xr.lineWrapping),He},[C,P]);i.useEffect(()=>{if(!m&&!t){E(null),B(""),ke(!1);return}let Q=!1;const $e=async Ke=>{if(y.files?.readFile)return(await y.files.readFile(Ke))?.content??"";const qe=To()?.files;if(qe?.readFile)return(await qe.readFile(Ke,{optional:!0}))?.content??"";const Xe=await gs(`/api/fs/read?path=${encodeURIComponent(Ke)}&optional=true`,{cache:"no-store"});if(!Xe.ok)throw new Error(`Failed to read plan file (${Xe.status})`);return Xe.text()};return(async()=>{if(E(null),B(""),ne(null),t){ke(!0);try{const Ke=await $e(t);if(Q)return;E(t),B(Ke)}catch{if(Q)return;E(null),B("")}finally{Q||ke(!1)}return}if(!v?.slug||!v?.time?.created||!k){E(null),B("");return}ke(!0);try{const Ke=t1(k,v.time.created,v.slug),qe=n1(s1(v.time.created,v.slug),d||null);let Xe=null,lt=null;try{lt=await $e(Ke),Xe=Ke}catch{}if(!Xe)try{lt=await $e(qe),Xe=qe}catch{}if(Q)return;if(!Xe||lt===null){E(null),B("");return}E(Xe),B(lt)}catch{if(Q)return;E(null),B("")}finally{Q||ke(!1)}})(),()=>{Q=!0}},[d,m,y.files,k,v?.slug,v?.time?.created,t]),i.useEffect(()=>{if(!P){ne(null);return}const Q=window.setTimeout(async()=>{ne(null);try{if(y.files?.writeFile){if(!(await y.files.writeFile(P,R))?.success)throw new Error(e("planView.error.writeFailed"))}else{const $e=await gs("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:P,content:R})});if(!$e.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:$e.status}))}}catch($e){ne($e instanceof Error?$e.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(Q)}},[R,P,y.files,e]),i.useEffect(()=>()=>{q.current!==null&&window.clearTimeout(q.current)},[]);const X=i.useCallback(()=>{h("chat"),x(!1)},[h,x]),L=i.useCallback(async Q=>{if(!A||!I)return;const $e=await vn(I.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:de}),Ke=[{synthetic:!0,text:await vn(I.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:de,plan_path:P??""})}];M(!0);try{X();let qe=null,Xe=A.path;if(I.target==="worktree"){if(!S)return;const bt=await Tm(A.path,Pm());if(!bt?.id)return;qe=bt.id,Xe=bt.path}else{const bt=await r(void 0,A.path,null);if(!bt?.id)return;qe=bt.id,Xe=bt.directory??A.path,o(bt.id,Ut.getState().agents??[])}if(!qe)return;const lt=lc.getState();lt.saveSessionModelSelection(qe,Q.providerID,Q.modelID),Q.agent.trim()&&(lt.saveSessionAgentSelection(qe,Q.agent),lt.saveAgentModelForSession(qe,Q.agent,Q.providerID,Q.modelID),lt.saveAgentModelVariantForSession(qe,Q.agent,Q.providerID,Q.modelID,Q.variant||void 0)),c(qe,Xe),await a($e,Q.providerID,Q.modelID,Q.agent.trim()||void 0,void 0,void 0,Ke,Q.variant||void 0),D(null)}finally{M(!1)}},[S,r,A,o,I,P,X,a,de,c]),xe=i.useMemo(()=>sf({drafts:he,editingDraftId:$,commentText:se,onTextChange:G,selection:ce,isDragging:Pe,fileLabel:Y,newWidgetId:"plan-new-comment-input",mapDraftToRange:Q=>({start:Q.startLine,end:Q.endLine}),onSave:Ve,onCancel:_e,onEdit:Q=>{U(Q),fe({start:Q.startLine,end:Q.endLine})},onDelete:Ie}),[se,Ie,$,_e,Ve,Pe,ce,he,Y,G,U]);return s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"typography-ui-label font-medium truncate",children:te}),oe?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:oe,children:e("planView.error.saveFailed")}):null]}),P?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(Ws,{children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx($s,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.improvePlanAria"),disabled:!R.trim(),children:s.jsx(T,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(Ct,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(zs,{align:"end",children:[s.jsx(ls,{onClick:()=>D({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(ls,{onClick:()=>D({action:"improve",target:"worktree"}),disabled:!S,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(Ws,{children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx($s,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.implementPlanAria"),disabled:!R.trim(),children:s.jsx(T,{name:"code-ai",className:"size-4"})})})}),s.jsx(Ct,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(zs,{align:"end",children:[s.jsx(ls,{onClick:()=>D({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(ls,{onClick:()=>D({action:"implement",target:"worktree"}),disabled:!S,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(Xo,{currentMode:J,onToggle:()=>Oe(J==="preview"?"edit":"preview")}),J==="preview"&&ie&&s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(O?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{O?_():R.trim()&&F(R)},children:O?s.jsx(T,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(T,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(Ct,{sideOffset:8,children:e(O?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await tr(R)).ok&&(ve(!0),q.current!==null&&window.clearTimeout(q.current),q.current=window.setTimeout(()=>{ve(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:ae?s.jsx(T,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(T,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(of,{open:I!==null,onOpenChange:Q=>{!Q&&!N&&D(null)},target:I?.target??"session",projectDirectory:A?.path??null,submitting:N,onConfirm:L}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(An,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:be?s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:e("planView.state.loading")}):s.jsx("div",{className:"relative h-full",children:s.jsx("div",{className:"h-full",children:J==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(Vs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("planView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("planView.error.switchToEditMode")})]}),children:s.jsx(No,{content:R,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:Re,children:s.jsx(Fl,{value:R,onChange:B,readOnly:!1,className:"h-full",extensions:Le,onViewReady:Q=>{De.current=Q},onViewDestroy:()=>{De.current=null},blockWidgets:xe,highlightLines:ce?{start:Math.min(ce.start,ce.end),end:Math.max(ce.start,ce.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(Q,$e,He)=>{if(!(He instanceof MouseEvent)||He.button!==0)return!1;He.preventDefault();const Ke=Q.state.doc.lineAt($e.from).number;if(ce&&!He.shiftKey&&Math.min(ce.start,ce.end)===Ke&&Math.max(ce.start,ce.end)===Ke)return fe(null),z(),Ee.current=!1,we.current=null,Se(!1),!0;if(p&&ce&&!He.shiftKey){const qe=Math.min(ce.start,ce.end,Ke),Xe=Math.max(ce.start,ce.end,Ke);return fe({start:qe,end:Xe}),Ee.current=!1,we.current=null,Se(!1),!0}if(Ee.current=!0,we.current=Ke,Se(!0),ce&&He.shiftKey){const qe=Math.min(ce.start,Ke),Xe=Math.max(ce.end,Ke);fe({start:qe,end:Xe})}else fe({start:Ke,end:Ke});return!0},mouseover:(Q,$e,He)=>{if(!(He instanceof MouseEvent)||He.buttons!==1||!Ee.current||we.current===null)return!1;const Ke=Q.state.doc.lineAt($e.from).number,qe=Math.min(we.current,Ke),Xe=Math.max(we.current,Ke);return fe({start:qe,end:Xe}),Se(!0),!1},mouseup:()=>(Ee.current=!1,we.current=null,Se(!1),!1)}}})})})})})})]})},o1=8,Dc=t=>t,Ul=t=>{const e=Dc(t).type;return typeof e=="string"?e:""},a1=t=>{const e=Dc(t).tool;return typeof e=="string"?e:""},l1=t=>{const e=Dc(t).text;return typeof e=="string"?e:""},c1=t=>{const e=Ul(t);return e==="tool"?a1(t).trim().toLowerCase()||"tool":e||"unknown"},d1=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=c1(n);e.includes(r)||e.push(r)}return e.join(" + ")},u1=(t,e=o1)=>typeof t!="string"?"":t.length<=e?t:t.slice(-e),m1=t=>t.replace(/\s+/g," ").trim(),f1=t=>{for(const n of t)if(Ul(n)==="text"){const r=m1(l1(n));if(r.length===0)continue;return r}const e=t.filter(n=>Ul(n)!=="text").length;return e===0?"":`${e} attachment${e===1?"":"s"}`},h1=(t,e,n)=>`${n(t)} / ${n(e)}`,p1=t=>{if(t==="12h")return!0;if(t==="24h")return!1},g1=(t,e)=>{if(!t||!Number.isFinite(t))return"-";const n=p1(e);return new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:n===!1?"2-digit":"numeric",minute:"2-digit",...n===void 0?{}:{hour12:n}})},Hl={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},ea={user:0,assistant:0,tool:0,other:0},hi=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,gl=t=>{const e=t.info.tokens,n=e!==void 0?e:t.parts.find(m=>m.tokens!==void 0)?.tokens;if(typeof n=="number")return{...Hl,total:hi(n)};if(!n||typeof n!="object")return Hl;const r=n,o=hi(r.input),a=hi(r.output),c=hi(r.reasoning),l=hi(r.cache?.read),d=hi(r.cache?.write);return{input:o,output:a,reasoning:c,cacheRead:l,cacheWrite:d,total:o+a+c+l+d}},x1=(...t)=>{for(const e of t)if(typeof e=="string"&&e.trim().length>0)return e;return""},Hn=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+Hn(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+Hn(n),0):0,b1=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...ea,assistant:Hn(n.text)+Hn(n.content)};const o=x1(n.text,n.content,n.value,n.source?.value,n.source?.text?.value);return r==="tool"||e==="tool"?{user:0,assistant:0,tool:Hn(n.input)+Hn(n.output)+Hn(n.error)+Hn(n.call?.input)+Hn(n.call?.output)+Hn(n.call?.error)+Hn(n.raw)+Math.round(Hn(n.metadata)*.25)+Math.round(Hn(n.state)*.1),other:0}:e==="user"?{user:o.length,assistant:0,tool:0,other:0}:e==="assistant"?{user:0,assistant:o.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:o.length}},Nu=(t,e)=>({user:t.user+e.user,assistant:t.assistant+e.assistant,tool:t.tool+e.tool,other:t.other+e.other}),y1=t=>{const e=Po(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},w1=(t,e)=>{if(t.length===0)return{...ea};const n=t.reduce((r,o)=>{const a=y1(o);let c={...ea};for(const l of o.parts)c=Nu(c,b1(l,a));return Nu(r,c)},{...ea});return n.user+=e.length,{user:Math.ceil(n.user/4),assistant:Math.ceil(n.assistant/4),tool:Math.ceil(n.tool/4),other:Math.ceil(n.other/4)}},pi=t=>t.toLocaleString(Ki()),v1=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(Ki(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(Ki(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),j1=(t,e)=>!t||!Number.isFinite(t)?"-":cc(t,e,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),S1=(t,e,n)=>{const r=t.find(a=>a.id===e),o=r?.models?.find(a=>a.id===n);return{providerName:r?.name||e||"-",modelName:o?.name||n||"-",contextLimit:typeof o?.limit?.context=="number"?o.limit.context:null}},N1=()=>{const t=ht.c(202),{t:e}=jt(),n=Me(k1);let r;t[0]===Symbol.for("react.memo_cache_sentinel")?(r={},t[0]=r):r=t[0];const[o,a]=i.useState(r),[c,l]=i.useState(null),d=i.useRef(null),m=mt(C1),f=fc(),u=Gp(m??""),g=Ut(A1);let b;t[1]===Symbol.for("react.memo_cache_sentinel")?(b=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(D1),l(null)},t[1]=b):b=t[1];let h;t[2]!==m?(h=[m],t[2]=m,t[3]=h):h=t[3],i.useEffect(b,h);let x,y;t[4]===Symbol.for("react.memo_cache_sentinel")?(x=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},y=[],t[4]=x,t[5]=y):(x=t[4],y=t[5]),i.useEffect(x,y);let p;t[6]===Symbol.for("react.memo_cache_sentinel")?(p=async(tt,ut)=>{(await tr(ut)).ok?(l(tt),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(It=>It===tt?null:It),d.current=null},2e3)):l(null)},t[6]=p):p=t[6];const C=p;let v;t[7]!==m||t[8]!==f?(v=m?f.find(tt=>tt.id===m)??null:null,t[7]=m,t[8]=f,t[9]=v):v=t[9];const k=v;let w,A,S,I,D,N;if(t[10]!==g||t[11]!==u){w=u.filter(T1);let tt;t[18]!==u?(tt=u.filter(P1),t[18]=u,t[19]=tt):tt=t[19],N=tt;let ut=null;for(let It=w.length-1;It>=0;It=It-1,It){const zt=w[It];if(gl(zt).total>0){ut=zt;break}}I=ut?gl(ut):Hl,A=Kp({input:I.input,cache:{read:I.cacheRead,write:I.cacheWrite}}),D=w.reduce(I1,0);const Mt=ut?.info??null;S=S1(g,Mt?.providerID||"",Mt?.modelID||""),t[10]=g,t[11]=u,t[12]=w,t[13]=A,t[14]=S,t[15]=I,t[16]=D,t[17]=N}else w=t[12],A=t[13],S=t[14],I=t[15],D=t[16],N=t[17];const M=S,P=M.contextLimit,E=P&&P>0?Math.min(999,I.total/P*100):0;let V;if(t[20]!==u){const tt=[...u].reverse().find(R1)?.info?.system||"";V=w1(u,tt),t[20]=u,t[21]=V}else V=t[21];const R=V,B=R.user,O=R.assistant,F=R.tool,_=Math.max(0,I.input-B-O-F),ie=B+O+F+_,oe=u[0]?.info?.time?.created,ne=u.length>0?u[u.length-1]?.info?.time?.created:null;let Y;t[22]!==k?.title||t[23]!==e?(Y=k?.title||e("contextSidebar.session.untitled"),t[22]=k?.title,t[23]=e,t[24]=Y):Y=t[24];const te=k?.time?.created??oe??null,de=ne??k?.time?.created??null;let be;t[25]!==O||t[26]!==_||t[27]!==F||t[28]!==B?(be={user:B,assistant:O,tool:F,other:_},t[25]=O,t[26]=_,t[27]=F,t[28]=B,t[29]=be):be=t[29];let ke;t[30]!==w.length||t[31]!==ie||t[32]!==A||t[33]!==P||t[34]!==M||t[35]!==u.length||t[36]!==te||t[37]!==de||t[38]!==be||t[39]!==Y||t[40]!==I||t[41]!==D||t[42]!==E||t[43]!==N.length?(ke={sessionTitle:Y,messagesCount:u.length,userMessagesCount:N.length,assistantMessagesCount:w.length,createdAt:te,lastActivityAt:de,providerModel:M,tokenBreakdown:I,usagePercent:E,cacheHitRate:A,totalAssistantCost:D,contextLimit:P,breakdown:be,breakdownTotal:ie},t[30]=w.length,t[31]=ie,t[32]=A,t[33]=P,t[34]=M,t[35]=u.length,t[36]=te,t[37]=de,t[38]=be,t[39]=Y,t[40]=I,t[41]=D,t[42]=E,t[43]=N.length,t[44]=ke):ke=t[44];const ae=ke;if(!m){let tt;t[45]!==e?(tt=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=tt):tt=t[46];let ut;return t[47]!==tt?(ut=s.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:tt}),t[47]=tt,t[48]=ut):ut=t[48],ut}let ve;t[49]!==e?(ve=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=ve):ve=t[50];let J;t[51]!==ve||t[52]!==ae.breakdown.user?(J={key:"user",label:ve,value:ae.breakdown.user,color:"var(--status-success)"},t[51]=ve,t[52]=ae.breakdown.user,t[53]=J):J=t[53];let H;t[54]!==e?(H=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=H):H=t[55];let q;t[56]!==H||t[57]!==ae.breakdown.assistant?(q={key:"assistant",label:H,value:ae.breakdown.assistant,color:"var(--primary-base)"},t[56]=H,t[57]=ae.breakdown.assistant,t[58]=q):q=t[58];let ce;t[59]!==e?(ce=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=ce):ce=t[60];let fe;t[61]!==ce||t[62]!==ae.breakdown.tool?(fe={key:"tool",label:ce,value:ae.breakdown.tool,color:"var(--status-warning)"},t[61]=ce,t[62]=ae.breakdown.tool,t[63]=fe):fe=t[63];let De;t[64]!==e?(De=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=De):De=t[65];let Re;t[66]!==De||t[67]!==ae.breakdown.other?(Re={key:"other",label:De,value:ae.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=De,t[67]=ae.breakdown.other,t[68]=Re):Re=t[68];let Fe;t[69]!==J||t[70]!==q||t[71]!==fe||t[72]!==Re?(Fe=[J,q,fe,Re],t[69]=J,t[70]=q,t[71]=fe,t[72]=Re,t[73]=Fe):Fe=t[73];const Oe=Fe;let Ee;t[74]!==ae.sessionTitle?(Ee=s.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:ae.sessionTitle}),t[74]=ae.sessionTitle,t[75]=Ee):Ee=t[75];let we;t[76]!==ae.providerModel.modelName||t[77]!==ae.providerModel.providerName?(we=s.jsxs("span",{children:[ae.providerModel.providerName," / ",ae.providerModel.modelName]}),t[76]=ae.providerModel.modelName,t[77]=ae.providerModel.providerName,t[78]=we):we=t[78];let Pe;t[79]!==n||t[80]!==ae.createdAt?(Pe=ae.createdAt&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:j1(ae.createdAt,n)})]}),t[79]=n,t[80]=ae.createdAt,t[81]=Pe):Pe=t[81];let Se;t[82]!==we||t[83]!==Pe?(Se=s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 typography-micro text-muted-foreground/70",children:[we,Pe]}),t[82]=we,t[83]=Pe,t[84]=Se):Se=t[84];let ue;t[85]!==Ee||t[86]!==Se?(ue=s.jsxs("div",{className:"mb-6",children:[Ee,Se]}),t[85]=Ee,t[86]=Se,t[87]=ue):ue=t[87];let K;t[88]!==e?(K=e("contextSidebar.section.context"),t[88]=e,t[89]=K):K=t[89];let he;t[90]!==K?(he=s.jsx("span",{className:"typography-micro text-muted-foreground",children:K}),t[90]=K,t[91]=he):he=t[91];let se;t[92]!==ae.tokenBreakdown.total?(se=pi(ae.tokenBreakdown.total),t[92]=ae.tokenBreakdown.total,t[93]=se):se=t[93];let G;t[94]!==ae.contextLimit?(G=ae.contextLimit?` / ${pi(ae.contextLimit)}`:"",t[94]=ae.contextLimit,t[95]=G):G=t[95];let $;t[96]!==se||t[97]!==G?($=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[se,G]}),t[96]=se,t[97]=G,t[98]=$):$=t[98];let pe;t[99]!==he||t[100]!==$?(pe=s.jsxs("div",{className:"flex items-baseline justify-between",children:[he,$]}),t[99]=he,t[100]=$,t[101]=pe):pe=t[101];let ye;t[102]!==ae.usagePercent?(ye=ae.usagePercent>0&&s.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,ae.usagePercent)}%`,backgroundColor:ae.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}}),t[102]=ae.usagePercent,t[103]=ye):ye=t[103];let z;t[104]!==ye?(z=s.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:ye}),t[104]=ye,t[105]=z):z=t[105];let Ne;t[106]!==e||t[107]!==ae.usagePercent?(Ne=e("contextSidebar.context.percentUsed",{percent:ae.usagePercent.toFixed(1)}),t[106]=e,t[107]=ae.usagePercent,t[108]=Ne):Ne=t[108];let U;t[109]!==Ne?(U=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:Ne}),t[109]=Ne,t[110]=U):U=t[110];let Ie;t[111]!==pe||t[112]!==z||t[113]!==U?(Ie=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[pe,z,U]}),t[111]=pe,t[112]=z,t[113]=U,t[114]=Ie):Ie=t[114];let _e;t[115]!==e?(_e=e("contextSidebar.stats.messages"),t[115]=e,t[116]=_e):_e=t[116];let Ve;t[117]!==ae.messagesCount?(Ve=pi(ae.messagesCount),t[117]=ae.messagesCount,t[118]=Ve):Ve=t[118];let Le;t[119]!==_e||t[120]!==Ve?(Le={label:_e,value:Ve},t[119]=_e,t[120]=Ve,t[121]=Le):Le=t[121];let X;t[122]!==e?(X=e("contextSidebar.stats.user"),t[122]=e,t[123]=X):X=t[123];let L;t[124]!==ae.userMessagesCount?(L=pi(ae.userMessagesCount),t[124]=ae.userMessagesCount,t[125]=L):L=t[125];let xe;t[126]!==X||t[127]!==L?(xe={label:X,value:L},t[126]=X,t[127]=L,t[128]=xe):xe=t[128];let Q;t[129]!==e?(Q=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=Q):Q=t[130];let $e;t[131]!==ae.assistantMessagesCount?($e=pi(ae.assistantMessagesCount),t[131]=ae.assistantMessagesCount,t[132]=$e):$e=t[132];let He;t[133]!==Q||t[134]!==$e?(He={label:Q,value:$e},t[133]=Q,t[134]=$e,t[135]=He):He=t[135];let Ke;t[136]!==e?(Ke=e("contextSidebar.stats.cost"),t[136]=e,t[137]=Ke):Ke=t[137];let qe;t[138]!==ae.totalAssistantCost?(qe=v1(ae.totalAssistantCost),t[138]=ae.totalAssistantCost,t[139]=qe):qe=t[139];let Xe;t[140]!==Ke||t[141]!==qe?(Xe={label:Ke,value:qe},t[140]=Ke,t[141]=qe,t[142]=Xe):Xe=t[142];let lt;t[143]!==Le||t[144]!==xe||t[145]!==He||t[146]!==Xe?(lt=[Le,xe,He,Xe],t[143]=Le,t[144]=xe,t[145]=He,t[146]=Xe,t[147]=lt):lt=t[147];const bt=lt;let Be;t[148]!==bt?(Be=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:bt.map(E1)}),t[148]=bt,t[149]=Be):Be=t[149];let Je;t[150]!==e?(Je=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Je):Je=t[151];let Ze;t[152]!==Je?(Ze=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Je}),t[152]=Je,t[153]=Ze):Ze=t[153];let pt;t[154]!==e||t[155]!==ae.cacheHitRate.hasInput||t[156]!==ae.cacheHitRate.percent||t[157]!==ae.tokenBreakdown.cacheRead||t[158]!==ae.tokenBreakdown.cacheWrite||t[159]!==ae.tokenBreakdown.input||t[160]!==ae.tokenBreakdown.output||t[161]!==ae.tokenBreakdown.reasoning?(pt=s.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:e("contextSidebar.tokens.input"),value:ae.tokenBreakdown.input,format:"count"},{label:e("contextSidebar.tokens.output"),value:ae.tokenBreakdown.output,format:"count"},{label:e("contextSidebar.tokens.reasoning"),value:ae.tokenBreakdown.reasoning,format:"count"},{label:e("contextSidebar.tokens.cacheRead"),value:ae.tokenBreakdown.cacheRead,format:"count"},{label:e("contextSidebar.tokens.cacheWrite"),value:ae.tokenBreakdown.cacheWrite,format:"count"},{label:e("contextSidebar.tokens.cacheHit"),value:ae.cacheHitRate.hasInput?ae.cacheHitRate.percent:null,format:"percent"}].map(M1)}),t[154]=e,t[155]=ae.cacheHitRate.hasInput,t[156]=ae.cacheHitRate.percent,t[157]=ae.tokenBreakdown.cacheRead,t[158]=ae.tokenBreakdown.cacheWrite,t[159]=ae.tokenBreakdown.input,t[160]=ae.tokenBreakdown.output,t[161]=ae.tokenBreakdown.reasoning,t[162]=pt):pt=t[162];let At;t[163]!==Ze||t[164]!==pt?(At=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[Ze,pt]}),t[163]=Ze,t[164]=pt,t[165]=At):At=t[165];let vt;t[166]!==Oe||t[167]!==ae.breakdownTotal?(vt=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:Oe.map(tt=>tt.value<=0||ae.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${tt.value/ae.breakdownTotal*100}%`,backgroundColor:tt.color}},tt.key))}),t[166]=Oe,t[167]=ae.breakdownTotal,t[168]=vt):vt=t[168];let at;t[169]!==Oe||t[170]!==ae.breakdownTotal?(at=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:Oe.map(tt=>{const ut=ae.breakdownTotal>0?tt.value/ae.breakdownTotal*100:0;return s.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:tt.color}}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[tt.label," ",s.jsxs("span",{className:"tabular-nums",children:[ut.toFixed(0),"%"]})]})]},tt.key)})}),t[169]=Oe,t[170]=ae.breakdownTotal,t[171]=at):at=t[171];let ct;t[172]!==vt||t[173]!==at?(ct=s.jsxs("div",{className:"mb-6",children:[vt,at]}),t[172]=vt,t[173]=at,t[174]=ct):ct=t[174];let Ot;t[175]!==e?(Ot=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=Ot):Ot=t[176];let Zt;t[177]!==Ot?(Zt=s.jsx("div",{className:"typography-micro text-muted-foreground",children:Ot}),t[177]=Ot,t[178]=Zt):Zt=t[178];let Et;if(t[179]!==c||t[180]!==o||t[181]!==u||t[182]!==e||t[183]!==n){let tt;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(tt=ut=>{const It=Po(ut.info).role,zt=It==="assistant",ss=It==="user",Bt=o[ut.info.id]===!0,Ft=c===ut.info.id,Jt=ut.info.time?.created??null,es=d1(ut.parts),Lt=zt?gl({info:ut.info,parts:ut.parts}):null,Pt=ss?f1(ut.parts):"",Kt=u1(ut.info.id),yt=g1(Jt,n),$t=es||"—",Dt=Lt?h1(Lt.input,Lt.output,pi):"",fs=It||"unknown",ms=es,xs=Bt?JSON.stringify({info:ut.info,parts:ut.parts},null,2):"";return s.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[s.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":Bt,onClick:()=>{a(gt=>({...gt,[ut.info.id]:gt[ut.info.id]!==!0}))},children:s.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:"auto minmax(0, 1fr) 5rem 4.5rem"},children:[ss?s.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",style:{gridColumn:"span 2"},children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",Pt]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:zt?"min-w-0 truncate text-muted-foreground":"typography-ui-label text-foreground",children:zt?$t:fs}),s.jsx("span",{className:zt?"text-right text-muted-foreground tabular-nums":"min-w-0 truncate text-muted-foreground",children:zt?Dt:ms})]}),s.jsx("span",{className:"text-right font-mono text-muted-foreground",children:Kt}),s.jsx("span",{className:"text-right text-muted-foreground",children:yt})]})}),Bt&&s.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:s.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[s.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:s.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:gt=>{gt.stopPropagation(),C(ut.info.id,xs)},"aria-label":e(Ft?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Ft?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Ft?s.jsx(T,{name:"check",className:"size-3.5"}):s.jsx(T,{name:"file-copy",className:"size-3.5"})})}),s.jsx(qp,{language:"json",code:xs,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},ut.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=tt):tt=t[189],Et=[...u].reverse().map(tt),t[179]=c,t[180]=o,t[181]=u,t[182]=e,t[183]=n,t[184]=Et}else Et=t[184];let ge;t[190]!==Et?(ge=s.jsx("div",{className:"mt-2.5 space-y-1",children:Et}),t[190]=Et,t[191]=ge):ge=t[191];let st;t[192]!==Zt||t[193]!==ge?(st=s.jsxs("div",{children:[Zt,ge]}),t[192]=Zt,t[193]=ge,t[194]=st):st=t[194];let wt;return t[195]!==ue||t[196]!==Ie||t[197]!==Be||t[198]!==At||t[199]!==ct||t[200]!==st?(wt=s.jsx("div",{className:"h-full overflow-y-auto bg-background",children:s.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[ue,Ie,Be,At,ct,st]})}),t[195]=ue,t[196]=Ie,t[197]=Be,t[198]=At,t[199]=ct,t[200]=st,t[201]=wt):wt=t[201],wt};function k1(t){return t.timeFormatPreference}function C1(t){return t.currentSessionId}function A1(t){return t.providers}function D1(t){return Object.keys(t).length>0?{}:t}function T1(t){return Po(t.info).role==="assistant"}function P1(t){return Po(t.info).isUser}function I1(t,e){const n=hi(e.info.cost);return t+n}function R1(t){return Po(t.info).isUser&&typeof t.info.system=="string"}function E1(t){return s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:t.label}),s.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:t.value})]},t.label)}function M1(t){return s.jsxs("div",{children:[s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:t.label}),s.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:t.value!==null&&t.value!==void 0?t.format==="percent"?`${t.value.toFixed(1)}%`:pi(t.value):"—"})]},t.label)}const F1=(t,e,n)=>JSON.stringify({sessionID:t,directory:e||"",readOnly:n===!0}),L1=(t,e,n,r)=>{if(typeof window>"u")return"";const o=new URL(window.location.pathname,window.location.origin);return o.searchParams.set("ocPanel","session-chat"),o.searchParams.set("sessionId",t),n?o.searchParams.set("readOnly","1"):o.searchParams.delete("readOnly"),e&&e.trim().length>0?o.searchParams.set("directory",e):o.searchParams.delete("directory"),o.searchParams.set("themeMode",r.mode),o.searchParams.set("lightThemeId",r.lightThemeId),o.searchParams.set("darkThemeId",r.darkThemeId),o.searchParams.set("themeVariant",r.currentTheme.metadata.variant==="dark"?"dark":"light"),o.searchParams.set("currentTheme",JSON.stringify(r.currentTheme)),o.hash="",o.toString()},O1=(t,e,n,r,o,a)=>{const c=F1(n,r,o),l=t.get(e);if(l?.signature===c)return l.src;const d=L1(n,r,o,a);return t.set(e,{signature:c,src:d}),d},B1=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.x=="number"&&typeof e.y=="number"},ku=t=>!t||typeof t!="object"?!1:Object.values(t).every(e=>typeof e=="string"),zi=t=>{if(!t||typeof t!="object")return!1;const e=t,n=e.bounds;return typeof e.tag=="string"&&typeof e.text=="string"&&typeof e.selector=="string"&&typeof e.path=="string"&&!!n&&typeof n?.x=="number"&&typeof n?.y=="number"&&typeof n?.width=="number"&&typeof n?.height=="number"&&B1(e.center)&&ku(e.attributes)&&ku(e.computedStyle)&&Array.isArray(e.ancestry)},Tc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([b,h])=>`${b}="${h}"`).join(" "),d=r.computedStyle,m=r.bounds,f=r.center,u=a.replace(/[.:]+$/g,""),g=r.ancestry.map(b=>b.selectorPart).join(" > ");return[`${u}:`,`Page: ${t||"preview"}`,`Viewport: ${e.width}x${e.height}, DPR ${n}`,`Screenshot: ${o?"attached":"not attached"}`,`Element: ${r.tag}`,c?`Text: ${c}`:null,`- Selector: ${r.selector}`,`- Path: ${r.path}`,g?`- Ancestry: ${g}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(m.x)}, y=${Math.round(m.y)}, width=${Math.round(m.width)}, height=${Math.round(m.height)}`,`- Center: x=${Math.round(f.x)}, y=${Math.round(f.y)}`,`Styles: display=${d.display}; position=${d.position}; font=${d.fontWeight} ${d.fontSize} / ${d.lineHeight} ${d.fontFamily}; color=${d.color}; background=${d.backgroundColor}; z-index=${d.zIndex}`].filter(b=>typeof b=="string").join(`
36
- `)},Af=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Er("desktop_capture_page_rect",{x:n.left,y:n.top,width:n.width,height:n.height});if(!r)throw new Error("Desktop screenshot capture is not available");const o=new Image;await new Promise((h,x)=>{o.onload=()=>h(),o.onerror=()=>x(new Error("Failed to load desktop preview screenshot")),o.src=`data:${r.mime};base64,${r.base64}`});const a=Math.max(1,o.naturalWidth||r.width||Math.floor(n.width)),c=Math.max(1,o.naturalHeight||r.height||Math.floor(n.height)),d=Math.min(1,1200/a),m=document.createElement("canvas");m.width=Math.floor(a*d),m.height=Math.floor(c*d);const f=m.getContext("2d");if(!f)return null;f.scale(d,d),f.drawImage(o,0,0,a,c);const u=a/Math.max(1,n.width),g=c/Math.max(1,n.height);f.fillStyle="rgba(37, 99, 235, 0.28)",f.strokeStyle="rgb(37, 99, 235)",f.lineWidth=Math.max(2,2*u),f.fillRect(e.bounds.x*u,e.bounds.y*g,e.bounds.width*u,e.bounds.height*g),f.strokeRect(e.bounds.x*u,e.bounds.y*g,e.bounds.width*u,e.bounds.height*g);const b=await new Promise(h=>m.toBlob(h,"image/jpeg",.82));return b?new File([b],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(n){return console.warn("[preview] failed to capture annotation screenshot:",n),null}return await Z1(t,e)},Pc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((y,p)=>{c.onload=()=>y(),c.onerror=()=>p(new Error("Failed to load desktop browser screenshot")),c.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,c.naturalWidth||e),d=Math.max(1,c.naturalHeight||n),f=Math.min(1,1200/l),u=document.createElement("canvas");u.width=Math.floor(l*f),u.height=Math.floor(d*f);const g=u.getContext("2d");if(!g)return null;g.scale(f,f),g.drawImage(c,0,0,l,d);const b=l/Math.max(1,r||l),h=d/Math.max(1,o||d);g.fillStyle="rgba(37, 99, 235, 0.14)",g.strokeStyle="rgb(37, 99, 235)",g.lineWidth=Math.max(2,2*b),g.fillRect(a.bounds.x*b,a.bounds.y*h,a.bounds.width*b,a.bounds.height*h),g.strokeRect(a.bounds.x*b,a.bounds.y*h,a.bounds.width*b,a.bounds.height*h);const x=await new Promise(y=>u.toBlob(y,"image/jpeg",.82));return x?new File([x],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Wi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Bn=new Map,xl=new Map,_1=3e4,Ic=t=>{const e=Bn.get(t);return e?e.expiresAt-Date.now()<=_1?(Bn.delete(t),null):e:null},V1=t=>{try{return new URL(t).origin}catch{return t}};function Df(t){const e="#ffffff",n=t.defaultView??window;try{const r=t.body?n.getComputedStyle(t.body).backgroundColor:"";if(r&&r!=="rgba(0, 0, 0, 0)"&&r!=="transparent")return r;const o=n.getComputedStyle(t.documentElement).backgroundColor;if(o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent")return o}catch{}return e}const Tf=t=>new Promise((e,n)=>{const r=new FileReader;r.onloadend=()=>e(typeof r.result=="string"?r.result:Wi),r.onerror=()=>n(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),$1=async(t,e=.82)=>{const n=await new Promise(r=>t.toBlob(r,"image/jpeg",e));return n&&(await Tf(n)).split(",",2)[1]||""},z1=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},ta=(...t)=>{z1()&&console.info("[preview-capture]",...t)},Pf=(t,e=8)=>{const n=[];try{const r=t.querySelectorAll("*");for(const o of r){const a=o.scrollTop||0,c=o.scrollLeft||0;if(a<=0&&c<=0)continue;const l=o.tagName.toLowerCase(),d=o.id?`#${o.id}`:"",m=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(n.push({selector:`${l}${d}${m}`,scrollTop:a,scrollLeft:c,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),n.length>=e)break}}catch{}return n},yo="data-oc-fixed-pin",W1=(t,e,n)=>{if(e<=0&&n<=0)return()=>{};const r=t.defaultView;if(!r)return()=>{};const o=[],a=[];try{for(const c of t.querySelectorAll("*")){if(r.getComputedStyle(c).position!=="fixed")continue;const l=c.getBoundingClientRect();if(!(l.width>0&&l.height>0))continue;c.setAttribute(yo,JSON.stringify({top:l.top+n,left:l.left+e,width:l.width,height:l.height})),o.push(c);const d=c.tagName.toLowerCase(),m=typeof c.className=="string"&&c.className?`.${c.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";a.push({selector:`${d}${m}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return ta("tagged fixed elements",a),()=>{for(const c of o)try{c.removeAttribute(yo)}catch{}}},U1={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${yo}]`)){let r;try{r=JSON.parse(n.getAttribute(yo)||"")}catch{continue}n.style.setProperty("position","absolute","important"),n.style.setProperty("top",`${r.top}px`,"important"),n.style.setProperty("left",`${r.left}px`,"important"),n.style.setProperty("right","auto","important"),n.style.setProperty("bottom","auto","important"),n.style.setProperty("width",`${r.width}px`,"important"),n.style.setProperty("height",`${r.height}px`,"important"),n.removeAttribute(yo)}}},Vi="data-oc-scroll-pin",H1=t=>{const e=[],n=Pf(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,m=l.scrollLeft||0;if(d<=0&&m<=0)continue;const f=l!==a&&l!==c;f&&l.setAttribute(Vi,JSON.stringify({top:d,left:m})),e.push({el:l,top:d,left:m,tagged:f})}}catch{}return{reapply:()=>{for(const a of e)try{a.el.scrollHeight,a.el.scrollTop!==a.top&&(a.el.scrollTop=a.top),a.el.scrollLeft!==a.left&&(a.el.scrollLeft=a.left)}catch{}},cleanup:()=>{for(const a of e)if(a.tagged)try{a.el.removeAttribute(Vi)}catch{}},snapshot:n}},G1={name:"oc-nested-scroll",afterClone(t){const e=t?.clone;if(!e||typeof e.querySelectorAll!="function")return;const n=e.ownerDocument;if(n)for(const r of e.querySelectorAll(`[${Vi}]`)){let o;try{o=JSON.parse(r.getAttribute(Vi)||"")}catch{r.removeAttribute(Vi);continue}const a=`translate(${-o.left}px, ${-o.top}px)`,c=r.children.length===1&&r.firstElementChild instanceof HTMLElement&&r.firstElementChild.style.willChange==="transform"?r.firstElementChild:null;if(c)c.style.transform=a;else{r.style.overflow="hidden";const l=n.createElement("div");for(l.style.transform=a,l.style.willChange="transform",l.style.display="inline-block",l.style.width="100%";r.firstChild;)l.appendChild(r.firstChild);r.appendChild(l)}r.removeAttribute(Vi)}}},bl=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await Tf(await n.blob()):null}catch{return null}},K1=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=Ic(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=xl.get(e),o=r??(async()=>{try{const c=await gs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!c.ok)return Bn.delete(e),null;const l=await c.json(),d=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",m=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Bn.delete(e),null;const f={proxyBasePath:d,expiresAt:m};return Bn.set(e,f),f}catch{return Bn.delete(e),null}finally{xl.delete(e)}})();r||xl.set(e,o);const a=await o;return a?`${a.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},If=async(t,e)=>{if(!t||t.startsWith("data:"))return t;try{const n=new URL(t,e.baseURI);if(n.origin===window.location.origin||n.protocol!=="http:"&&n.protocol!=="https:")return await bl(n.toString(),"include")??Wi;const r=await K1(n),o=r?await bl(r,"include"):null;return o||(await bl(n.toString(),"omit")??Wi)}catch{return Wi}},q1=async(t,e)=>{if(!t||t==="none"||!t.includes("url("))return t;const n=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let r=t;for(const o of n){const a=o[2]||"";if(!a||a.startsWith("data:"))continue;const c=await If(a,e);r=r.replace(o[0],`url("${c}")`)}return r},Cu=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),Rf=t=>{const e=t.style.cssText;return()=>{t.style.cssText=e}},Y1=t=>{const e=Number.parseFloat(t.lineHeight);if(Number.isFinite(e)&&e>0)return e;const n=Number.parseFloat(t.fontSize);return Number.isFinite(n)&&n>0?n*1.2:16},J1=(t,e,n)=>{const r=[],o=t.defaultView??window,c=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of c){const d=l.textContent?.replace(/\s+/g," ").trim()??"";if(!d||!d.includes(" "))continue;const m=l.getBoundingClientRect();if(m.width<=0||m.height<=0||m.right<0||m.bottom<0||m.left>e||m.top>n)continue;const f=o.getComputedStyle(l);if(f.display==="none"||f.visibility==="hidden"||Number(f.opacity)===0)continue;const u=f.getPropertyValue("text-wrap"),g=f.getPropertyValue("text-wrap-mode"),b=f.whiteSpace.includes("nowrap")||u==="nowrap"||g==="nowrap",h=m.height<=Y1(f)*1.7;!b&&(!h||m.width>e*.72)||(r.push(Rf(l)),l.style.whiteSpace="nowrap",l.style.overflowWrap="normal",l.style.wordBreak="normal",l.style.setProperty("text-wrap","nowrap"),l.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let l=r.length-1;l>=0;l-=1)r[l]?.()}},Q1=(t,e,n,r)=>{const o=[],a=t.defaultView??window,c=a.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=a.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,d=Array.from(t.querySelectorAll("*")).filter(m=>{const f=a.getComputedStyle(m);if(f.position!=="fixed"||f.display==="none"||f.visibility==="hidden"||Number(f.opacity)===0)return!1;const u=m.getBoundingClientRect();return u.width>0&&u.height>0&&u.right>=0&&u.bottom>=0&&u.left<=e&&u.top<=n}).filter((m,f,u)=>!u.some((g,b)=>b<f&&g.contains(m)));for(const m of d){const f=m.getBoundingClientRect(),u=a.getComputedStyle(m),g=Math.ceil(f.width)+8,b=Math.ceil(f.height)+2;r?.add(m),o.push(Rf(m)),m.style.position="absolute",m.style.top=`${f.top+l}px`,m.style.left=`${f.left+c}px`,m.style.right="auto",m.style.bottom="auto",m.style.width=`${g}px`,m.style.minWidth=`${g}px`,m.style.height=`${b}px`,m.style.minHeight=`${b}px`,m.style.margin="0",m.style.boxSizing="border-box",m.style.transform="none",u.zIndex!=="auto"&&(m.style.zIndex=u.zIndex)}return()=>{for(let m=o.length-1;m>=0;m-=1)o[m]?.()}},Ef=async(t,e,n,r={})=>{const o=[],a=t.defaultView??window,c=u=>{if(u===t.documentElement||u===t.body)return!0;try{const g=u.getBoundingClientRect();return g.width>0&&g.height>0&&g.right>=0&&g.bottom>=0&&g.left<=e&&g.top<=n}catch{return!1}};if(r.applyLayoutWorkarounds){const u=new WeakSet;o.push(Q1(t,e,n,u)),o.push(J1(t,e,n))}const l=new Map;for(const u of Array.from(t.images))l.set(u,u.currentSrc||u.src||u.getAttribute("src")||"");const d=Array.from(t.querySelectorAll("picture"));for(const u of d){const g=Array.from(u.querySelectorAll("source"));if(g.length===0)continue;const b=g.map(h=>({source:h,srcset:h.getAttribute("srcset"),sizes:h.getAttribute("sizes")}));o.push(()=>{for(const h of b)h.srcset===null?h.source.removeAttribute("srcset"):h.source.setAttribute("srcset",h.srcset),h.sizes===null?h.source.removeAttribute("sizes"):h.source.setAttribute("sizes",h.sizes)});for(const h of g)h.removeAttribute("srcset"),h.removeAttribute("sizes")}const m=Array.from(t.images).filter(u=>c(u));await Promise.all(m.map(async u=>{const g=l.get(u)||u.currentSrc||u.src||u.getAttribute("src")||"";if(!g)return;await Cu(u);const b=await If(g,t),h={src:u.getAttribute("src"),srcset:u.getAttribute("srcset"),sizes:u.getAttribute("sizes")};o.push(()=>{h.src===null?u.removeAttribute("src"):u.setAttribute("src",h.src),h.srcset===null?u.removeAttribute("srcset"):u.setAttribute("srcset",h.srcset),h.sizes===null?u.removeAttribute("sizes"):u.setAttribute("sizes",h.sizes)}),u.removeAttribute("srcset"),u.removeAttribute("sizes"),u.setAttribute("src",b||Wi),await Cu(u)}));const f=Array.from(t.querySelectorAll("*")).filter(c);return await Promise.all(f.map(async u=>{const g=a.getComputedStyle(u).backgroundImage;if(!g||g==="none"||!g.includes("url("))return;const b=await q1(g,t);if(b===g)return;const h=u.style.backgroundImage;o.push(()=>{u.style.backgroundImage=h}),u.style.backgroundImage=b})),()=>{for(let u=o.length-1;u>=0;u-=1)try{o[u]?.()}catch{}}};async function X1(t,e){try{const n=t.contentWindow,r=t.contentDocument??n?.document,o=r?.documentElement;if(!n||!r||!o)return null;const a=t.getBoundingClientRect(),c=Math.max(1,Math.ceil(n.innerWidth||t.clientWidth||a.width)),l=Math.max(1,Math.ceil(n.innerHeight||t.clientHeight||a.height)),d=r.body,m=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,f=n.scrollX||0,u=n.scrollY||0,g=n.pageXOffset||0,b=n.pageYOffset||0,h=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,x=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,y=o.scrollLeft||0,p=o.scrollTop||0,C=d?.scrollLeft||0,v=d?.scrollTop||0,k=m?.scrollLeft||0,w=m?.scrollTop||0,A=Math.max(f,g,h,y,C,k),S=Math.max(u,b,x,p,v,w);ta("scroll sources",{windowScrollX:f,windowScrollY:u,pageScrollX:g,pageScrollY:b,visualViewportScrollX:h,visualViewportScrollY:x,rootScrollX:y,rootScrollY:p,bodyScrollX:C,bodyScrollY:v,scrollingElementScrollX:k,scrollingElementScrollY:w,scrollingElementTag:m?.tagName?.toLowerCase()??null,resolvedScrollX:A,resolvedScrollY:S,nestedScrolledElements:Pf(r)});const I=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),D=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),N=Math.min(2,Math.max(1,window.devicePixelRatio||1)),M=o.style.scrollBehavior,P=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const E=H1(r);ta("nested scroll snapshot",E.snapshot);let V=()=>{},R=()=>{};try{await r.fonts?.ready.catch(()=>{}),V=await Ef(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(A,S),R=W1(r,A,S),E.reapply();const B={backgroundColor:Df(r),cache:"disabled",dpr:N,embedFonts:!0,fast:!1,height:D,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[U1,G1],quality:.82,width:I},F=await(await jh(o,B)).toCanvas();if(!F.width||!F.height)return null;const _=F.width/Math.max(1,I),ie=F.height/Math.max(1,D),oe=Math.min(F.width,Math.max(1,Math.round(c*_))),ne=Math.min(F.height,Math.max(1,Math.round(l*ie))),Y=Math.max(0,F.width-oe),te=Math.max(0,F.height-ne),de=Math.min(Y,Math.max(0,Math.round(A*_))),be=Math.min(te,Math.max(0,Math.round(S*ie)));ta("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:I,captureHeight:D,canvasWidth:F.width,canvasHeight:F.height,xScale:_,yScale:ie,sourceX:de,sourceY:be,sourceWidth:oe,sourceHeight:ne});const ke=r.createElement("canvas");ke.width=oe,ke.height=ne;const ae=ke.getContext("2d");if(!ae)return null;ae.drawImage(F,de,be,oe,ne,0,0,oe,ne);const ve=await $1(ke,.82);return ve?await Pc(ve,c,l,c,l,e):null}finally{R(),E.cleanup(),V(),n.scrollTo(A,S),E.reapply(),o.style.scrollBehavior=M,d&&(d.style.scrollBehavior=P)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function Z1(t,e){const n=await X1(t,e);if(n)return n;try{const r=t.contentWindow,o=t.contentDocument??r?.document,a=o?.documentElement;if(!r||!o||!a)return null;const c=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||c.width)),d=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||c.height)),m=r.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,f=r.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,u=o.body,g=Math.max(d,a.scrollHeight||0,u?.scrollHeight||0),b=Math.min(2,Math.max(1,window.devicePixelRatio||1)),h=a.style.scrollBehavior,x=u?.style.scrollBehavior??"";a.style.scrollBehavior="auto",u&&(u.style.scrollBehavior="auto");let y="",p=()=>{};try{await o.fonts?.ready.catch(()=>{}),p=await Ef(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(m,f);const v=await wh(a).catch(()=>"");y=await vh(a,{quality:.82,pixelRatio:b,width:l,height:d,backgroundColor:Df(o),imagePlaceholder:Wi,fontEmbedCSS:v||void 0,style:{transform:`translate(${-m}px, ${-f}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${g}px`},cacheBust:!0})}finally{p(),r.scrollTo(m,f),a.style.scrollBehavior=h,u&&(u.style.scrollBehavior=x)}const C=y.split(",",2)[1]||"";return C?await Pc(C,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const Mf=380,e0=1400,Ff=600,t0=24,Au=200,s0=(t,e)=>e==="all"?!0:e==="errors"?t.level==="error"||t.level==="runtime"||t.level==="resource":e==="warnings"?t.level==="warn":t.level==="log"||t.level==="info"||t.level==="debug",n0=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},Lf=t=>Number.isFinite(t)?Math.min(e0,Math.max(Mf,Math.round(t))):Ff,r0=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},yl=(t,e)=>{const n=Lf(t),r=r0(e);return r===null?n:Math.min(n,Math.max(1,r))},i0=(t,e)=>{if(!t)return"";const n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return r&&n.startsWith(r+"/")?n.slice(r.length+1):n},o0=(t,e)=>e(t==="chat"?"contextPanel.mode.chat":t==="file"?"contextPanel.mode.files":t==="diff"?"contextPanel.mode.diff":t==="plan"?"contextPanel.mode.plan":t==="preview"?"contextPanel.mode.preview":t==="browser"?"contextPanel.mode.browser":"contextPanel.mode.context"),a0=t=>{if(!t)return null;const e=t.replace(/\\/g,"/").trim();if(!e)return null;const n=e.split("/").filter(Boolean);return n.length===0?e:n[n.length-1]||null},l0=(t,e)=>{if(t.label)return t.label;if(t.mode==="file")return a0(t.targetPath)||e("contextPanel.mode.files");if(t.mode==="preview"){const n=t.targetPath;if(n)try{const r=new URL(n);return r.host||r.hostname||e("contextPanel.mode.preview")}catch{}return e("contextPanel.mode.preview")}return t.mode==="diff"?e("contextPanel.mode.diff"):o0(t.mode,e)},c0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(Mr,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(T,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(T,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(T,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(T,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(T,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(T,{name:"global",className:"h-3.5 w-3.5"})},d0=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,Of=`new Promise((resolve) => {
37
- const existing = document.getElementById('__openchamber_desktop_browser_overlay');
38
- if (existing) existing.remove();
39
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
40
- try { window.__openchamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
41
- }
42
- const overlay = document.createElement('div');
43
- overlay.id = '__openchamber_desktop_browser_overlay';
44
- overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
45
- document.documentElement.appendChild(overlay);
46
- const cssEscape = (value) => {
47
- try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
48
- };
49
- const selectorPart = (element) => {
50
- const tag = element.tagName.toLowerCase();
51
- if (element.id) return tag + '#' + cssEscape(element.id);
52
- const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
53
- return tag + className;
54
- };
55
- const metadata = (element) => {
56
- const rect = element.getBoundingClientRect();
57
- const style = getComputedStyle(element);
58
- const ancestry = [];
59
- let current = element;
60
- while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
61
- ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
62
- current = current.parentElement;
63
- }
64
- const attrs = {};
65
- for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
66
- const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
67
- return {
68
- frame: 'top',
69
- tag: element.tagName.toLowerCase(),
70
- text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
71
- selector: element.id ? '#' + cssEscape(element.id) : path,
72
- path,
73
- bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
74
- center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
75
- attributes: attrs,
76
- computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
77
- ancestry,
78
- };
79
- };
80
- const move = (event) => {
81
- const element = document.elementFromPoint(event.clientX, event.clientY);
82
- if (!element || element === overlay || element === document.documentElement || element === document.body) return;
83
- const rect = element.getBoundingClientRect();
84
- overlay.style.display = 'block';
85
- overlay.style.left = rect.left + 'px';
86
- overlay.style.top = rect.top + 'px';
87
- overlay.style.width = rect.width + 'px';
88
- overlay.style.height = rect.height + 'px';
89
- };
90
- const cleanup = () => {
91
- window.removeEventListener('mousemove', move, true);
92
- window.removeEventListener('click', click, true);
93
- window.removeEventListener('keydown', keydown, true);
94
- if (window.__openchamberDesktopBrowserCancelInspect === cancel) {
95
- delete window.__openchamberDesktopBrowserCancelInspect;
96
- }
97
- };
98
- const cancel = () => {
99
- cleanup();
100
- overlay.remove();
101
- resolve(null);
102
- };
103
- const click = (event) => {
104
- event.preventDefault();
105
- event.stopPropagation();
106
- const element = document.elementFromPoint(event.clientX, event.clientY);
107
- const result = element ? metadata(element) : null;
108
- cleanup();
109
- overlay.remove();
110
- resolve(result);
111
- };
112
- const keydown = (event) => {
113
- if (event.key !== 'Escape') return;
114
- cancel();
115
- };
116
- window.__openchamberDesktopBrowserCancelInspect = cancel;
117
- window.addEventListener('mousemove', move, true);
118
- window.addEventListener('click', click, true);
119
- window.addEventListener('keydown', keydown, true);
120
- });`,sa=`(() => {
121
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
122
- window.__openchamberDesktopBrowserCancelInspect();
123
- return;
124
- }
125
- const overlay = document.getElementById('__openchamber_desktop_browser_overlay');
126
- if (overlay) overlay.remove();
127
- })()`,u0=`(() => {
128
- if (window.__openchamberSameWebviewNavigationInstalled) return;
129
- window.__openchamberSameWebviewNavigationInstalled = true;
130
-
131
- const navigate = (rawUrl) => {
132
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
133
- try {
134
- const url = new URL(rawUrl, window.location.href);
135
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
136
- window.location.assign(url.href);
137
- return true;
138
- } catch (_error) {
139
- return false;
140
- }
141
- };
142
-
143
- const originalOpen = window.open.bind(window);
144
- window.open = (url, target, features) => {
145
- if (navigate(url)) return null;
146
- return originalOpen(url, target, features);
147
- };
148
-
149
- document.addEventListener('click', (event) => {
150
- if (event.defaultPrevented) return;
151
- const target = event.target;
152
- if (!(target instanceof Element)) return;
153
- const anchor = target.closest('a[target="_blank"][href]');
154
- if (!(anchor instanceof HTMLAnchorElement)) return;
155
- if (!navigate(anchor.href)) return;
156
- event.preventDefault();
157
- event.stopPropagation();
158
- }, true);
159
- })()`,wo=t=>{const e=t.trim();if(!e)return"about:blank";try{const n=new URL(e.includes("://")?e:`https://${e}`);return n.protocol!=="http:"&&n.protocol!=="https:"?"about:blank":n.toString()}catch{return"about:blank"}},Du=async(t,e)=>{const n=t.contentWindow;if(!n)throw new Error("Iframe window is not available");const o=n.eval.call(n,e);return await Promise.resolve(o)},m0=(t,e)=>t.length<=e?t:`${t.slice(0,e-3)}...`,Bf=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Tu=(t,e,n)=>{const r=Bf(e);t.postMessage(n,r)},f0=t=>{if(!t)return t;try{const e=new URL(t);return e.searchParams.delete("oc_preview_token"),e.searchParams.delete("oc_client_token"),e.searchParams.delete("oc_url_token"),e.toString()}catch{return t}},h0=({rawUrl:t,onNavigate:e})=>{const{t:n}=jt(),{currentTheme:r}=Lr(),[o,a]=i.useReducer(we=>we+1,0),[c,l]=i.useReducer(we=>we+1,0),[d,m]=i.useState({status:"idle"}),[f,u]=i.useState(""),g=i.useRef(null),b=i.useRef(1),[h,x]=i.useState(!1),[y,p]=i.useState(!1),[C,v]=i.useState("all"),[k,w]=i.useState([]),[A,S]=i.useState(!1),[I,D]=i.useState(null),N=mt(we=>we.currentSessionId),M=mt(we=>we.newSessionDraft?.open),P=hc(we=>we.addDraft),E=ri(we=>we.addAttachedFile);let V=null;try{V=t?new URL(t):null}catch{V=null}const R=V?V.hostname==="localhost"||V.hostname==="127.0.0.1"||V.hostname==="::1"||V.hostname==="[::1]"||V.hostname==="0.0.0.0":!1,B=V?V.hostname==="0.0.0.0"?new URL(V.toString().replace("0.0.0.0","127.0.0.1")):V:null,O=B?B.toString():"",F=O?`${pr()||"same-origin"}|${O}`:"",_=r.metadata.variant;i.useEffect(()=>{if(!O||!R){m({status:"idle"});return}const we=Ic(F);if(we?.previewToken){m({status:"ready",proxyBasePath:we.proxyBasePath,previewToken:we.previewToken,expiresAt:we.expiresAt});return}we&&Bn.delete(F);let Pe=!1;return m({status:"loading"}),(async()=>{try{const Se=await gs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:O})});if(!Se.ok){Bn.delete(F);const G=await Se.json().catch(()=>({})),$=typeof G?.error=="string"?G.error:`HTTP ${Se.status}`;Pe||m({status:"error",message:$});return}const ue=await Se.json(),K=typeof ue.proxyBasePath=="string"?ue.proxyBasePath:"",he=typeof ue.previewToken=="string"?ue.previewToken:"",se=typeof ue.expiresAt=="number"?ue.expiresAt:0;if(!K||!he){Bn.delete(F),Pe||m({status:"error",message:n("contextPanel.preview.proxyError")});return}Bn.set(F,{proxyBasePath:K,previewToken:he,expiresAt:se}),Pe||m({status:"ready",proxyBasePath:K,previewToken:he,expiresAt:se})}catch(Se){if(Bn.delete(F),!Pe){const ue=Se instanceof Error?Se.message:String(Se);m({status:"error",message:ue})}}})(),()=>{Pe=!0}},[R,F,c,n,O]);const ie=B&&(B.protocol==="http:"||B.protocol==="https:")?B.toString():"",oe=R&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!oe){u("");return}let we=!1;return u(""),fo(pr()).then(Pe=>{!we&&Pe&&u(oe)}).catch(()=>{}),()=>{we=!0}},[oe]);const ne=R&&d.status==="ready"&&B&&f===oe?(()=>{const we=B.pathname||"/",Pe=new URLSearchParams(B.search);Pe.set("ocPreview",String(o)),Pe.set("oc_preview_token",d.previewToken||"");const Se=Pe.toString(),ue=B.hash||"";return wi().authenticatedAsset(`${d.proxyBasePath}${we}${Se?`?${Se}`:""}${ue}`)})():"",Y=R?ne:ie,te=R?f0(ne):ie,de=R&&(d.status==="loading"||d.status==="idle"||f!==oe),be=R&&d.status==="error",ke=i.useCallback(we=>{const Pe=N??(M?"draft":null);if(!Pe){me.error(n("contextPanel.preview.inspect.attachNoSession"));return}const Se=t||Y||"",ue=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},K=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let he=!1;try{const se=g.current,G=se?await Af(se,we):null;G&&(await E(G),he=!0)}catch{he=!1}P({sessionKey:Pe,source:"preview-annotation",fileLabel:Se||"preview",startLine:1,endLine:1,code:Tc({pageUrl:Se,viewport:ue,devicePixelRatio:K,target:we,screenshotAttached:he,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),me.success(n("contextPanel.preview.inspect.attached"))})()},[E,P,N,Y,M,t,n]);i.useEffect(()=>{x(!1),w([]),p(!1),v("all"),S(!1),D(null),b.current=1},[Y]),i.useEffect(()=>{const we=g.current?.contentWindow;!h||!we||Tu(we,ne,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:A})},[h,A,ne]),i.useEffect(()=>{const we=g.current?.contentWindow;!h||!we||Tu(we,ne,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:_})},[h,_,ne]),i.useEffect(()=>{if(!A||typeof window>"u")return;const we=Pe=>{Pe.key==="Escape"&&(Pe.preventDefault(),Pe.stopImmediatePropagation(),S(!1))};return window.addEventListener("keydown",we,!0),()=>window.removeEventListener("keydown",we,!0)},[A]),i.useEffect(()=>{if(!R||typeof window>"u")return;const we=ue=>{if(typeof ue=="string")return ue;if(ue==null)return"";try{return JSON.stringify(ue)}catch{return String(ue)}},Pe=ue=>{const K=b.current;b.current+=1,w(he=>{const se=[...he,{...ue,id:K}];return se.length>Au?se.slice(se.length-Au):se})},Se=ue=>{if(ue.source!==g.current?.contentWindow)return;const K=ue.data;if(!(!K||K.source!=="openchamber-preview-bridge"||K.version!==1)){if(K.type==="ready"){x(!0);return}if(K.type==="console"){const he=K.level==="error"||K.level==="warn"||K.level==="info"||K.level==="debug"?K.level:"log",se=Array.isArray(K.args)?K.args.map(we).filter(Boolean):[];Pe({level:he,message:se.join(" "),ts:typeof K.ts=="number"?K.ts:Date.now()});return}if(K.type==="runtime-error"){const he=we(K.filename),se=typeof K.line=="number"?K.line:null,G=typeof K.column=="number"?K.column:null,$=he?`${he}${se!==null?`:${se}${G!==null?`:${G}`:""}`:""}`:"",pe=we(K.stack);Pe({level:"runtime",message:we(K.message)||n("contextPanel.preview.console.runtimeError"),details:[$,pe].filter(Boolean).join(`
160
- `),ts:typeof K.ts=="number"?K.ts:Date.now()});return}if(K.type==="resource-error"){const he=we(K.tag)||"resource",se=we(K.url);Pe({level:"resource",message:se?`${he}: ${se}`:he,details:we(K.outerHTML),ts:typeof K.ts=="number"?K.ts:Date.now()});return}if(K.type==="hover"){D(zi(K.target)?K.target:null);return}if(K.type==="select"&&zi(K.target)){D(K.target),S(!1),ke(K.target);return}if(K.type==="navigate-preview"){const he=typeof K.url=="string"?K.url:"",se=K.navigation==="external"?"external":"proxy";if(he&&se==="external"){Si(he);return}he&&e(he)}}};return window.addEventListener("message",Se),()=>{window.removeEventListener("message",Se)}},[ke,R,e,n]);const ae=k.filter(we=>we.level==="error"||we.level==="runtime"||we.level==="resource").length,ve=k.filter(we=>s0(we,C)),J=i.useCallback(()=>{const we=[`Preview URL: ${t||Y||""}`,`Events: ${k.length}`,""].join(`
161
- `),Pe=k.map(Se=>{const ue=new Date(Se.ts).toISOString(),K=Se.details?`
162
- ${Se.details}`:"";return`[${ue}] [${Se.level}] ${Se.message}${K}`}).join(`
163
- `);tr(`${we}${Pe}`).then(Se=>{Se.ok?me.success(n("contextPanel.preview.console.copied")):me.error(n("contextPanel.preview.console.copyFailed"))})},[k,Y,t,n]),H=i.useCallback(()=>{const we=N??(M?"draft":null);if(!we){me.error(n("contextPanel.preview.console.attachNoSession"));return}const Pe=[`Preview URL: ${t||Y||""}`,`Events: ${k.length}`,""].join(`
164
- `),Se=k.map(ue=>{const K=new Date(ue.ts).toISOString(),he=ue.details?`
165
- ${ue.details}`:"";return`[${K}] [${ue.level}] ${ue.message}${he}`}).join(`
166
- `);P({sessionKey:we,source:"preview-console",fileLabel:t||Y||"preview",startLine:1,endLine:Math.max(1,k.length),code:`${Pe}${Se}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),me.success(n("contextPanel.preview.console.attached"))},[P,k,N,Y,M,t,n]),[q,ce]=i.useState("unknown"),fe=i.useRef(0),De=i.useRef(0),Re=15e3;i.useEffect(()=>{if(!ne){ce("unknown"),fe.current=0,De.current=0;return}let we=!1;return fe.current||(fe.current=Date.now(),De.current=0),ce("unknown"),(async()=>{const Se=await(async()=>{try{return await gs(ne,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(we)return;if(!Se){ce("unreachable");return}if(Se.status===403||Se.status===404){Bn.delete(F),m({status:"loading"}),l();return}if(Se.status!==502){ce("reachable");return}const ue=fe.current||Date.now();if(Date.now()-ue<Re){ce("starting"),De.current+=1;const he=De.current,se=Math.min(2e3,250*Math.pow(2,Math.min(4,he)));setTimeout(()=>{we||a()},se).unref?.();return}ce("unreachable")})(),()=>{we=!0}},[F,ne,o]);const Fe=R&&d.status==="ready"&&(q==="unknown"||q==="starting"),Oe=R&&d.status==="ready"&&q==="unreachable",Ee=i.useCallback(we=>{if(!R||d.status!=="ready"||typeof window>"u")return;const Pe=we.currentTarget.contentWindow;if(Pe)try{const Se=Pe.location,ue=Bf(ne);if(Se.origin!==ue||Se.pathname.startsWith(d.proxyBasePath))return;const K=`${d.proxyBasePath}${Se.pathname}${Se.search}${Se.hash}`;Pe.location.replace(K)}catch{}},[R,ne,d]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:te||t,children:te||t||n("contextPanel.preview.empty")}),s.jsx(ze,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:n("contextPanel.preview.actions.reload"),"aria-label":n("contextPanel.preview.actions.reload"),disabled:!Y,children:s.jsx(T,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ie&&Si(ie)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!ie,children:s.jsx(T,{name:"external-link",className:"h-3.5 w-3.5"})}),R?s.jsx(ze,{type:"button",size:"sm",variant:A?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>S(we=>!we),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!h,children:s.jsx(T,{name:"cursor",className:"h-3.5 w-3.5"})}):null,R?s.jsxs(ze,{type:"button",size:"sm",variant:y?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>p(we=>!we),title:n(h?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),"aria-label":n(h?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),disabled:!h&&k.length===0,children:[s.jsx(T,{name:"terminal-box",className:"h-3.5 w-3.5"}),ae>0?s.jsx("span",{className:"typography-micro text-status-error",children:ae}):null]}):null]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Fe?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.startingServer")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.startingServerHint")})]}):Oe?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.upstreamUnreachable")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.upstreamUnreachableHint")}),s.jsx(ze,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:n("contextPanel.preview.actions.retry")})]}):Y&&(!R||q==="reachable")?s.jsxs("div",{className:"relative h-full w-full",children:[s.jsx("iframe",{ref:g,src:Y,title:n("contextPanel.preview.iframeTitle"),className:"h-full w-full border-0",style:{colorScheme:_},onLoad:Ee,sandbox:R?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${Y}:${o}`),A&&I?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:I.bounds.x,top:I.bounds.y,width:I.bounds.width,height:I.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[I.tag,I.text?` · ${I.text}`:""]})}):null]}):de?s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.loading")}):be?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.proxyError")}),d.status==="error"?s.jsx("div",{className:"text-center text-xs opacity-70",children:d.message}):null]}):s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.invalidUrl")}),y?s.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:n("contextPanel.preview.console.title")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:H,disabled:k.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:J,disabled:k.length===0,children:n("contextPanel.preview.console.copy")}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:()=>w([]),disabled:k.length===0,children:n("contextPanel.preview.console.clear")})]})]}),s.jsx("div",{className:"flex items-center gap-1 border-b border-border/30 px-3 py-1.5",children:["all","errors","warnings","logs"].map(we=>s.jsx(ze,{type:"button",size:"xs",variant:C===we?"secondary":"ghost",onClick:()=>v(we),children:n(we==="all"?"contextPanel.preview.console.filter.all":we==="errors"?"contextPanel.preview.console.filter.errors":we==="warnings"?"contextPanel.preview.console.filter.warnings":"contextPanel.preview.console.filter.logs")},we))}),s.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:k.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.empty")}):ve.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):ve.map(we=>s.jsx("div",{className:"border-b border-border/30 px-2 py-1 last:border-b-0",children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("span",{className:Te("shrink-0 uppercase",we.level==="error"||we.level==="runtime"||we.level==="resource"?"text-status-error":we.level==="warn"?"text-status-warning":"text-muted-foreground"),children:we.level}),s.jsx("span",{className:"min-w-0 break-words text-foreground",children:we.message})]})},we.id))})]}):null]})]})},p0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,g0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=jt(),o=i.useRef(null),a=Me(J=>J.setContextPanelTabTargetPath),c=wo(t),l=c!=="about:blank"?c:"",[d,m]=i.useState(l),[f,u]=i.useState(l),[g,b]=i.useState(()=>l?[l]:[]),[h,x]=i.useState(()=>l?0:-1),[y,p]=i.useReducer(J=>J+1,0),[C,v]=i.useState(!!l),[k,w]=i.useState(!1),[A,S]=i.useState(null),[I,D]=i.useState({status:"idle"}),[N,M]=i.useState(""),P=mt(J=>J.currentSessionId),E=mt(J=>J.newSessionDraft?.open),V=hc(J=>J.addDraft),R=ri(J=>J.addAttachedFile),B=i.useCallback(J=>{!J||J==="about:blank"||!e||!n||a(e,n,J)},[e,n,a]),O=i.useCallback((J,H)=>{const q=wo(J),ce=q!=="about:blank"?q:"";u(ce),m(ce),v(!!ce),B(ce),b(fe=>{if(!ce)return x(-1),[];if(H?.replaceHistory)return fe;const De=h>=0?fe.slice(0,h+1):[];if(De[De.length-1]===ce)return x(De.length-1),De;const Fe=[...De,ce];return x(Fe.length-1),Fe})},[h,B]),F=i.useCallback(J=>{const H=g[J];H&&(x(J),u(H),m(H),v(!0),B(H))},[g,B]),_=i.useCallback(()=>{if(f){v(!0);try{o.current?.contentWindow?.location.reload()}catch{p()}}},[f]);i.useEffect(()=>{if(!f){D({status:"idle"});return}const J=V1(f),H=Ic(J);if(H?.previewToken){D({status:"ready",proxyBasePath:H.proxyBasePath,previewToken:H.previewToken,expiresAt:H.expiresAt});return}H&&Bn.delete(J);let q=!1;return D({status:"loading"}),v(!0),(async()=>{try{const ce=await gs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:f,allowExternal:!0})});if(!ce.ok){const Oe=await ce.json().catch(()=>({})),Ee=typeof Oe?.error=="string"?Oe.error:`HTTP ${ce.status}`;q||D({status:"error",message:Ee});return}const fe=await ce.json(),De=typeof fe.proxyBasePath=="string"?fe.proxyBasePath:"",Re=typeof fe.previewToken=="string"?fe.previewToken:"",Fe=typeof fe.expiresAt=="number"?fe.expiresAt:0;if(!De||!Re){q||D({status:"error",message:r("contextPanel.preview.proxyError")});return}Bn.set(J,{proxyBasePath:De,previewToken:Re,expiresAt:Fe}),q||D({status:"ready",proxyBasePath:De,previewToken:Re,expiresAt:Fe})}catch(ce){if(!q){const fe=ce instanceof Error?ce.message:String(ce);D({status:"error",message:fe})}}})(),()=>{q=!0}},[f,r]);const ie=f&&I.status==="ready"?`${I.proxyBasePath}|${I.previewToken||""}|${y}`:"";i.useEffect(()=>{if(!ie){M("");return}let J=!1;return M(""),fo(pr()).then(H=>{!J&&H&&M(ie)}).catch(()=>{}),()=>{J=!0}},[ie]);const oe=i.useMemo(()=>{if(N!==ie||!f||I.status!=="ready")return"";try{const J=new URL(f),H=J.pathname||"/",q=new URLSearchParams(J.search);q.set("ocPreview",String(y)),q.set("oc_preview_token",I.previewToken||"");const ce=q.toString();return wi().authenticatedAsset(`${I.proxyBasePath}${H}${ce?`?${ce}`:""}${J.hash}`)}catch{return""}},[f,I,ie,y,N]),ne=oe||(I.status==="error"?f:""),Y=i.useCallback(J=>{if(!J||!f||I.status!=="ready")return"";try{const H=new URL(J,window.location.origin),q=I.proxyBasePath.endsWith("/")?I.proxyBasePath.slice(0,-1):I.proxyBasePath;if(H.origin!==window.location.origin||!H.pathname.startsWith(q))return"";const ce=H.pathname.slice(q.length)||"/",fe=new URL(f).origin;return new URL(`${ce}${H.search}${H.hash}`,fe).toString()}catch{return""}},[f,I]),te=i.useCallback(J=>{if(!J||!f||I.status!=="ready")return"";try{const H=new URL(J,window.location.origin),q=new URL(f).origin;if(H.origin!==window.location.origin||q===window.location.origin)return"";const ce=I.proxyBasePath.endsWith("/")?I.proxyBasePath.slice(0,-1):I.proxyBasePath;return H.pathname.startsWith(ce)?"":new URL(`${H.pathname}${H.search}${H.hash}`,q).toString()}catch{return""}},[f,I]),de=i.useCallback(J=>{const H=o.current?.contentWindow;H&&H.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:J},window.location.origin)},[]),be=i.useCallback(async J=>{const H=P??(E?"draft":null);if(!H){me.error(r("contextPanel.preview.inspect.attachNoSession"));return}const q=o.current,ce=q?.contentWindow,fe=q?.getBoundingClientRect(),De={width:Number.isFinite(ce?.innerWidth)?ce?.innerWidth??fe?.width??0:fe?.width??0,height:Number.isFinite(ce?.innerHeight)?ce?.innerHeight??fe?.height??0:fe?.height??0},Re=q?await Af(q,J):null,Fe=!!Re;Re&&await R(Re),V({sessionKey:H,source:"preview-annotation",fileLabel:f||"browser",startLine:1,endLine:1,code:Tc({pageUrl:f,viewport:De,devicePixelRatio:window.devicePixelRatio||1,target:J,screenshotAttached:Fe,intro:r(Fe?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),me.success(r("contextPanel.preview.inspect.attached"))},[R,V,P,f,E,r]),ke=i.useCallback(()=>{const J=o.current;S(null),de(!1),J&&Du(J,sa).catch(()=>{})},[de]);i.useEffect(()=>{if(!k)return;const J=H=>{H.key==="Escape"&&(H.preventDefault(),H.stopImmediatePropagation(),w(!1),ke())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[ke,k]),i.useEffect(()=>()=>ke(),[ke]),i.useEffect(()=>{const J=H=>{if(H.source!==o.current?.contentWindow)return;const q=H.data;if(!(!q||q.source!=="openchamber-preview-bridge"||q.version!==1)){if(q.type==="ready"){const ce=typeof q.url=="string"?q.url:"",fe=Y(ce);fe&&fe!==f&&O(fe);return}if(q.type==="hover"){S(zi(q.target)?q.target:null);return}if(q.type==="select"&&zi(q.target)){S(null),w(!1),de(!1),be(q.target);return}if(q.type==="navigate-preview"){const ce=typeof q.url=="string"?q.url:"",fe=te(ce);if(fe){O(fe);return}ce&&O(ce)}}};return window.addEventListener("message",J),()=>window.removeEventListener("message",J)},[O,be,f,Y,te,de]);const ae=i.useCallback(()=>{const J=o.current;if(!(!J||!f)){if(k){w(!1),ke();return}if(oe){S(null),w(!0),de(!0);return}w(!0),(async()=>{try{const H=await Du(J,Of);if(w(!1),!H||!zi(H))return;await be(H)}catch{w(!1),me.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[be,ke,f,k,de,oe,r]),ve=i.useCallback(()=>{try{const J=o.current?.contentWindow?.location.href||"",H=te(J);if(H){v(!0),O(H);return}}catch{}v(!1),k&&oe&&de(!0)},[O,te,k,de,oe]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:h<=0,onClick:()=>F(h-1),children:s.jsx(T,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:h<0||h>=g.length-1,onClick:()=>F(h+1),children:s.jsx(T,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!f,onClick:_,children:s.jsx(T,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:J=>{J.preventDefault(),O(d)},children:s.jsx("input",{value:d,onChange:J=>m(J.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx(ze,{type:"button",variant:k?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!f,onClick:ae,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(T,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!f,onClick:()=>{Si(f)},children:s.jsx(T,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[ne?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:ne,title:r("contextPanel.browser.empty"),className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:ve},`${ne}:${y}`),k&&A?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:A.bounds.x,top:A.bounds.y,width:A.bounds.width,height:A.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[A.tag,A.text?` · ${A.text}`:""]})}):null]}):s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(pc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")}),s.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:r("contextPanel.browser.emptyHint")}),s.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:r("contextPanel.browser.trustNotice")})]}),C?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},x0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=jt(),o=i.useRef(null),a=Me(D=>D.setContextPanelTabTargetPath),c=wo(t),l=c!=="about:blank"?c:"",[d,m]=i.useState(l),[f,u]=i.useState(l),[g,b]=i.useState(!1),[h,x]=i.useState(!0),y=i.useRef(null),p=h,C=i.useCallback(D=>{!D||D==="about:blank"||!e||!n||a(e,n,D)},[e,n,a]),v=mt(D=>D.currentSessionId),k=mt(D=>D.newSessionDraft?.open),w=hc(D=>D.addDraft),A=ri(D=>D.addAttachedFile);i.useEffect(()=>{const D=o.current;if(!D)return;const N=()=>{try{const B=D.getURL();B&&B!=="about:blank"&&(u(B),m(B),C(B))}catch{}},M=B=>{const O=B.detail;typeof O?.url=="string"&&O.url&&(u(O.url),m(O.url),C(O.url))},P=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>x(!0),200)},E=()=>{y.current&&clearTimeout(y.current),x(!1),N()},V=B=>{const O=B.detail;if(O?.disposition==="new-window"||O?.disposition==="foreground-tab"||O?.disposition==="background-tab"){B.preventDefault();const F=o.current;typeof F?.loadURL=="function"&&O.url&&F.loadURL(O.url)}},R=()=>{try{D.executeJavaScript?.(u0,!0).catch(()=>{})}catch{}};D.addEventListener("did-navigate",M),D.addEventListener("did-navigate-in-page",M),D.addEventListener("did-start-loading",P),D.addEventListener("did-stop-loading",E),D.addEventListener("new-window",V),D.addEventListener("dom-ready",R);try{D.isLoading()||(x(!1),N())}catch{}return R(),()=>{y.current&&clearTimeout(y.current),D.removeEventListener("did-navigate",M),D.removeEventListener("did-navigate-in-page",M),D.removeEventListener("did-start-loading",P),D.removeEventListener("did-stop-loading",E),D.removeEventListener("new-window",V),D.removeEventListener("dom-ready",R)}},[C]),i.useEffect(()=>{const D=setTimeout(()=>x(!1),3e4);return()=>clearTimeout(D)},[]),i.useEffect(()=>{if(!g)return;const D=N=>{if(N.key!=="Escape")return;N.preventDefault(),N.stopImmediatePropagation(),b(!1);const M=o.current;try{M?.executeJavaScript?.(sa).catch(()=>{})}catch{}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[g]),i.useEffect(()=>{const D=o.current;return()=>{try{const N=D?.getURL?.();N&&N!=="about:blank"&&a(e,n,N)}catch{}try{D?.executeJavaScript?.(sa).catch(()=>{})}catch{}}},[e,n,a]);const S=i.useCallback(D=>{const N=o.current;if(typeof N?.loadURL!="function")return;const M=wo(D);try{N.loadURL(M)}catch{}},[]),I=i.useCallback(()=>{const D=o.current;if(D){if(g){b(!1);try{D.executeJavaScript?.(sa).catch(()=>{})}catch{}return}b(!0),D.executeJavaScript?.(Of,!0).then(async N=>{if(b(!1),!N||!zi(N))return;const M=v??(k?"draft":null);if(!M){me.error(r("contextPanel.preview.inspect.attachNoSession"));return}const P=typeof D.getWebContentsId=="function"?D.getWebContentsId():null;if(P==null)return;const E=await Yp("desktop_browser_capture_page",{webContentsId:P}),V=await D.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),R=Number.isFinite(V?.width)?V.width:E.width,B=Number.isFinite(V?.height)?V.height:E.height,O=await Pc(E.base64,E.width,E.height,R,B,N),F=!!O;O&&await A(O),w({sessionKey:M,source:"preview-annotation",fileLabel:f||"browser",startLine:1,endLine:1,code:Tc({pageUrl:f,viewport:{width:R,height:B},devicePixelRatio:window.devicePixelRatio||1,target:N,screenshotAttached:F,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),me.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>b(!1))}},[A,w,v,f,g,k,r]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:s.jsx(T,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:s.jsx(T,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:s.jsx(T,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:D=>{D.preventDefault(),S(d)},children:s.jsx("input",{value:d,onChange:D=>m(D.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx(ze,{type:"button",variant:g?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:I,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(T,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{Si(f)},children:s.jsx(T,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[s.jsx("webview",{ref:o,src:wo(t),partition:"persist:openchamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!f||f==="about:blank")&&!h?s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(pc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")})]}):null,p?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},b0=()=>{const{t}=jt(),e=ii()??"",n=i.useMemo(()=>n0(e),[e]),r=Me(K=>n?K.contextPanelByDirectory[n]:void 0),o=Me(K=>K.closeContextPanel),a=Me(K=>K.closeContextPanelTab),c=Me(K=>K.openContextPanelTab),l=Me(K=>K.toggleContextPanelExpanded),d=Me(K=>K.setContextPanelWidth),m=Me(K=>K.setActiveContextPanelTab),f=Me(K=>K.reorderContextPanelTabs),u=on(K=>K.setSelectedPath),g=Me(K=>K.openContextPreview),{themeMode:b,setThemeMode:h,lightThemeId:x,darkThemeId:y,currentTheme:p}=Lr(),C=i.useMemo(()=>r?.tabs??[],[r?.tabs]),v=C.find(K=>K.id===r?.activeTabId)??C[C.length-1]??null,k=!!(r?.isOpen&&v),w=!!(k&&r?.expanded),A=Lf(r?.width??Ff),[S,I]=i.useState(!1),[D,N]=i.useState(!1),M=i.useRef(0),P=i.useRef(A),E=i.useRef(null),V=i.useRef(null),R=i.useRef(null),B=i.useRef(new Map),O=i.useRef(new Map),F=i.useRef(!1),_=i.useRef(k),ie=i.useRef(null),oe=i.useCallback(()=>{N(!0),ie.current!==null&&window.cancelAnimationFrame(ie.current),ie.current=window.requestAnimationFrame(()=>{ie.current=null,N(!1)})},[]);i.useEffect(()=>()=>{ie.current!==null&&window.cancelAnimationFrame(ie.current)},[]),i.useLayoutEffect(()=>{const K=_.current;if(_.current=k,!k){N(!1);return}K||oe()},[k,oe]),i.useEffect(()=>{if(!k||F.current){F.current=k;return}const K=window.requestAnimationFrame(()=>{R.current?.focus({preventScroll:!0})});return F.current=!0,()=>window.cancelAnimationFrame(K)},[k]);const ne=i.useCallback(K=>{const he=R.current;he&&he.style.setProperty("--oc-context-panel-width",`${yl(K,he)}px`)},[]),Y=i.useCallback(K=>{if(!(!k||w||!n)){try{K.currentTarget.setPointerCapture(K.pointerId)}catch{}V.current=K.pointerId,I(!0),M.current=K.clientX,P.current=A,E.current=A,ne(A),K.preventDefault()}},[ne,n,w,k,A]),te=i.useCallback(K=>{if(!S||V.current!==K.pointerId)return;const he=M.current-K.clientX,se=yl(P.current+he,R.current);E.current!==se&&(E.current=se,ne(se))},[ne,S]),de=i.useCallback(K=>{if(V.current!==K.pointerId||!n)return;try{K.currentTarget.releasePointerCapture(K.pointerId)}catch{}const he=yl(E.current??A,R.current);oe(),ne(he),E.current=he,d(n,he),I(!1),V.current=null},[ne,n,d,oe,A]);i.useEffect(()=>{S||(E.current=null)},[S]);const be=i.useCallback(()=>{n&&o(n)},[o,n]),ke=i.useCallback(()=>{n&&l(n)},[n,l]),ae=i.useCallback(K=>{K.key==="Escape"&&(K.preventDefault(),K.stopPropagation(),be())},[be]);i.useEffect(()=>{if(!(!n||!v)&&v.mode==="file"&&v.targetPath){u(n,v.targetPath,{allowOutsideRoot:!0});return}},[v,n,u]);const ve=v?.mode==="chat"?v.id:null,J=i.useCallback((K,he,se)=>O1(O.current,K,he,n||null,se,{mode:b,lightThemeId:x,darkThemeId:y,currentTheme:p}),[p,y,n,x,b]);i.useEffect(()=>{const K=new Set(C.map(he=>he.id));for(const he of O.current.keys())K.has(he)||O.current.delete(he)},[C]);const H=i.useCallback(K=>{!n||v?.mode!=="diff"||c(n,{mode:"diff",targetPath:v.targetPath,stagedDiff:K==="staged"})},[v,n,c]),q=i.useCallback(()=>{if(typeof window>"u")return;const K={themeMode:b,lightThemeId:x,darkThemeId:y,currentTheme:p};for(const he of B.current.values()){const se=he.contentWindow;if(!se)continue;const G=se.__openchamberApplyThemeSync;if(typeof G=="function")try{G(K);continue}catch{}se.postMessage({type:"openchamber:theme-sync",payload:K},window.location.origin)}},[p,y,x,b]),ce=i.useCallback(()=>{if(!(typeof window>"u"))for(const[K,he]of B.current.entries()){const se=he.contentWindow;if(!se)continue;const G={visible:ve===K},$=se.__openchamberSetEmbeddedVisibility;if(typeof $=="function")try{$(G);continue}catch{}se.postMessage({type:"openchamber:embedded-visibility",payload:G},window.location.origin)}},[ve]);i.useEffect(()=>{if(typeof window>"u")return;const K=he=>{if(he.origin!==window.location.origin||!Array.from(B.current.values()).some(z=>z.contentWindow===he.source)||he.data?.type!=="openchamber:cycle-theme-request")return;const $=["light","dark","system"],ye=($.indexOf(b)+1)%$.length;h($[ye])};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)},[h,b]),i.useLayoutEffect(()=>{C.some(he=>he.mode==="chat")&&(q(),ce())},[y,x,ce,q,C,b]);const fe=i.useMemo(()=>C.map(K=>{const he=l0(K,t),se=m0(he,t0),G=i0(K.targetPath,e);return{id:K.id,label:se,icon:c0(K),title:G?`${he}: ${G}`:he,closeLabel:t("contextPanel.tab.closeTabAria",{label:se})}}),[e,t,C]),De=v?.mode==="context"?s.jsx(N1,{}):v?.mode==="plan"?s.jsx(Cf,{targetPath:v.targetPath}):v?.mode==="preview"?s.jsx(h0,{rawUrl:v.targetPath??"",onNavigate:K=>g(e,K)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(T,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),s.jsx("div",{className:"typography-ui-header text-foreground",children:t("contextPanel.preview.title")}),s.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:t("contextPanel.preview.description")})]}),Re=i.useMemo(()=>C.filter(K=>K.mode==="chat"),[C]),Fe=i.useMemo(()=>C.filter(K=>K.mode==="browser"),[C]),Oe=i.useMemo(()=>C.filter(K=>K.mode==="diff"),[C]),Ee=p0()?x0:g0,we=i.useMemo(()=>C.some(K=>K.mode==="file"),[C]),Pe=v?.mode==="file",Se=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(ko,{items:fe,activeId:v?.id??null,onSelect:K=>{n&&m(n,K)},onClose:K=>{n&&a(n,K)},onReorder:(K,he)=>{n&&f(n,K,he)},layoutMode:"scrollable",variant:"default"}),s.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:ke,className:"h-7 w-7 p-0",title:t(w?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),"aria-label":t(w?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),children:w?s.jsx(T,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(T,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:be,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(T,{name:"close",className:"h-3.5 w-3.5"})})]})]}),ue=k?w?{"--oc-context-panel-width":"100%",width:"100%",minWidth:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",minWidth:`min(${Mf}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${S?E.current??A:A}px`}:{"--oc-context-panel-width":`${S?E.current??A:A}px`,width:0,minWidth:0,maxWidth:0,opacity:0,overflow:"hidden",visibility:"hidden"};return s.jsxs("aside",{ref:R,"data-context-panel":"true",tabIndex:-1,inert:!k||void 0,className:Te("flex min-h-0 flex-col overflow-hidden bg-background",!w&&"border-l border-border/40",w?"absolute inset-0 z-20 min-w-0":"relative h-full flex-shrink-0",!k&&"pointer-events-none",S||!k||D?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:ae,style:ue,children:[!w&&s.jsx("div",{className:Te("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",S&&"bg-[var(--interactive-border)]"),onPointerDown:Y,onPointerMove:te,onPointerUp:de,onPointerCancel:de,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),Se,s.jsxs("div",{className:Te("relative min-h-0 flex-1 overflow-hidden",S&&"pointer-events-none"),children:[we?s.jsx("div",{className:Te("absolute inset-0",Pe?"block":"hidden"),children:s.jsx(kf,{mode:"editor-only"})}):null,Re.map(K=>{const he=d0(K.dedupeKey);if(!he)return null;const se=J(K.id,he,K.readOnly);return se?s.jsx("iframe",{ref:G=>{if(!G){B.current.delete(K.id);return}B.current.set(K.id,G)},src:se,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:he}),className:Te("absolute inset-0 h-full w-full border-0 bg-background",ve===K.id?"block":"hidden"),onLoad:()=>{q(),ce()}},K.id):null}),Fe.map(K=>s.jsx("div",{className:Te("absolute inset-0",v?.id!==K.id&&"hidden"),children:s.jsx(Ee,{initialUrl:K.targetPath??"",directory:n,tabID:K.id})},K.id)),Oe.map(K=>s.jsx("div",{className:Te("absolute inset-0",v?.id!==K.id&&"hidden"),children:s.jsx(vf,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:K.stagedDiff?"staged":"working",onDiffScopeChange:H,targetFilePath:K.targetPath,flushContent:!0})},K.id)),v?.mode!=="chat"&&!Pe&&v?.mode!=="browser"&&v?.mode!=="diff"?De:null]})]})},Gl=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",a=/^[A-Za-z]:\/$/.test(r);return!o&&!a&&(r=r.replace(/\/+$/,"")),r},y0=()=>{const t=ht.c(171),{t:e}=jt(),n=Me(w0),r=Me(v0),o=Me(j0),a=Me(S0),c=Me(N0),l=Me(k0),d=Me(C0),m=Me(A0),f=Me(D0),u=Me(T0),g=Me(P0),b=Me(I0),h=mt(R0),x=mt(E0),y=gr(M0),p=Bs(F0),C=ds(L0),v=ii(),k=tc(O0),{files:w,git:A}=_n(),S=an(B0),{isMobile:I}=Ar();let D;t[0]!==v?(D=v?Gl(v):null,t[0]=v,t[1]=D):D=t[1];const N=D,[M,P]=i.useState(""),E=Ma(M,200);let V;t[2]!==E?(V=E.trim(),t[2]=E,t[3]=V):V=t[3];const R=V;let B;t[4]!==M?(B=M.trim(),t[4]=M,t[5]=B):B=t[5];const O=B;let F,_;t[6]!==n?(F=()=>{n&&P("")},_=[n],t[6]=n,t[7]=F,t[8]=_):(F=t[7],_=t[8]),i.useEffect(F,_);let ie,oe;t[9]!==y||t[10]!==S||t[11]!==A||t[12]!==n?(ie=()=>{if(!n||!A)return;const ge=setTimeout(()=>{const st=new Set;for(const wt of y){const tt=kr(wt);!tt||st.has(tt)||(st.add(tt),S(tt,A))}},0);return()=>clearTimeout(ge)},oe=[n,y,A,S],t[9]=y,t[10]=S,t[11]=A,t[12]=n,t[13]=ie,t[14]=oe):(ie=t[13],oe=t[14]),i.useEffect(ie,oe);let ne;t[15]!==r?(ne=()=>r(!1),t[15]=r,t[16]=ne):ne=t[16];const Y=ne;let te;t[17]!==Y?(te=ge=>()=>{Y(),ge()},t[17]=Y,t[18]=te):te=t[18];const de=te;let be;t[19]!==C?.id||t[20]!==C?.path||t[21]!==p||t[22]!==I||t[23]!==u||t[24]!==h||t[25]!==de||t[26]!==o||t[27]!==l||t[28]!==a||t[29]!==e||t[30]!==f||t[31]!==m||t[32]!==d?(be=()=>{const ge=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(T,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:de(()=>{o("chat"),l(!1),h()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(T,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:de(_0)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(T,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:de(V0)},{id:"toggle-sidebar",title:e(I?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(T,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(I?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:de(()=>{if(I){const{isSessionSwitcherOpen:st}=Me.getState();l(!st)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(T,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:de(()=>m())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(T,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:de(()=>f())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(T,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:de(()=>{p&&u(p)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(T,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:de(()=>a(!0))}];return Na()&&ge.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(T,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:de(()=>{Er("desktop_open_draft_mini_chat_window",{directory:Gl(p||C?.path||""),projectId:C?.id??null}).catch($0)})}),ge},t[19]=C?.id,t[20]=C?.path,t[21]=p,t[22]=I,t[23]=u,t[24]=h,t[25]=de,t[26]=o,t[27]=l,t[28]=a,t[29]=e,t[30]=f,t[31]=m,t[32]=d,t[33]=be):be=t[33],C?.id,C?.path;let ke;t[34]!==be?(ke=be(),t[34]=be,t[35]=ke):ke=t[35];const ae=ke;let ve;t[36]===Symbol.for("react.memo_cache_sentinel")?(ve=er(),t[36]=ve):ve=t[36];const J=ve;let H,q;t[37]===Symbol.for("react.memo_cache_sentinel")?(H=Fr(),q=!J&&sc(),t[37]=H,t[38]=q):(H=t[37],q=t[38]);let ce;t[39]!==I?(ce={isVSCode:H,isWeb:q,isDesktop:J,isMobile:I},t[39]=I,t[40]=ce):ce=t[40];const fe=ce;let De;if(t[41]!==de||t[42]!==a||t[43]!==c||t[44]!==fe){let ge;t[46]!==fe?(ge=wt=>wt.isAvailable?wt.isAvailable(fe):!0,t[46]=fe,t[47]=ge):ge=t[47];let st;t[48]!==de||t[49]!==a||t[50]!==c?(st=wt=>{const tt=wx(wt.slug)??"settings-3",ut=(wt.keywords??[]).join(" ");return{id:`settings:${wt.slug}`,title:wt.title,icon:wt.slug==="mcp"?s.jsx(El,{className:"mr-2 h-4 w-4"}):s.jsx(T,{name:tt,className:"mr-2 h-4 w-4"}),searchText:`${wt.title} ${wt.group} ${ut}`,onSelect:de(()=>{c(wt.slug),a(!0)})}},t[48]=de,t[49]=a,t[50]=c,t[51]=st):st=t[51],De=yx.filter(z0).filter(ge).map(st),t[41]=de,t[42]=a,t[43]=c,t[44]=fe,t[45]=De}else De=t[45];const Re=De,Fe=W0;let Oe;if(t[52]!==y){let ge;t[54]===Symbol.for("react.memo_cache_sentinel")?(ge=(st,wt)=>Fe(wt)-Fe(st),t[54]=ge):ge=t[54],Oe=[...y].sort(ge),t[52]=y,t[53]=Oe}else Oe=t[53];const Ee=Oe,we=Lm(),Pe=mt(U0);let Se;t[55]!==we||t[56]!==Pe?(Se=(ge,st)=>{const wt=Pe.get(ge);return wt?.branch?wt.branch.trim()||null:st&&we.get(st)?.trim()||null},t[55]=we,t[56]=Pe,t[57]=Se):Se=t[57];const ue=Se;let K;t[58]===Symbol.for("react.memo_cache_sentinel")?(K=[],t[58]=K):K=t[58];const[he,se]=i.useState(K),[G,$]=i.useState(!1);let pe,ye;t[59]!==N||t[60]!==n||t[61]!==k||t[62]!==R?(pe=()=>{if(!n){se([]),$(!1);return}if(!N||R.length===0){se([]),$(!1);return}let ge=!1;return $(!0),k(N,R,10,{type:"file"}).then(st=>{ge||se(st.map(H0))}).catch(()=>{ge||se([])}).finally(()=>{ge||$(!1)}),()=>{ge=!0}},ye=[n,N,R,k],t[59]=N,t[60]=n,t[61]=k,t[62]=R,t[63]=pe,t[64]=ye):(pe=t[63],ye=t[64]),i.useEffect(pe,ye);const z=O.length>0;let Ne;e:{if(!z){let st;t[65]!==ae?(st=ae.map(G0),t[65]=ae,t[66]=st):st=t[66],Ne=st;break e}let ge;t[67]!==ae||t[68]!==O?(ge=Fo(ae,O,K0,{limit:7,noFuzzy:!0}),t[67]=ae,t[68]=O,t[69]=ge):ge=t[69],Ne=ge}const U=Ne;let Ie;e:{if(!z){let st;t[70]===Symbol.for("react.memo_cache_sentinel")?(st=[],t[70]=st):st=t[70],Ie=st;break e}let ge;t[71]!==O||t[72]!==Re?(ge=Fo(Re,O,q0,{limit:7,noFuzzy:!0}),t[71]=O,t[72]=Re,t[73]=ge):ge=t[73],Ie=ge}const _e=Ie;let Ve;e:{if(!z){let st;t[74]!==Ee?(st=Ee.slice(0,5).map(Y0),t[74]=Ee,t[75]=st):st=t[75],Ve=st;break e}let ge;t[76]!==O||t[77]!==Ee?(ge=Fo(Ee,O,J0,{limit:7,threshold:.2}),t[76]=O,t[77]=Ee,t[78]=ge):ge=t[78],Ve=ge}const Le=Ve;let X;e:{if(!z||he.length===0){let st;t[79]===Symbol.for("react.memo_cache_sentinel")?(st=[],t[79]=st):st=t[79],X=st;break e}let ge;t[80]!==he||t[81]!==O?(ge=Fo(he,O,Q0,{limit:10,threshold:.4}),t[80]=he,t[81]=O,t[82]=ge):ge=t[82],X=ge}const L=X;let xe,Q,$e,He,Ke,qe,Xe,lt,bt,Be,Je,Ze,pt,At,vt;if(t[83]!==ue||t[84]!==Y||t[85]!==N||t[86]!==w||t[87]!==z||t[88]!==n||t[89]!==g||t[90]!==M||t[91]!==U||t[92]!==L||t[93]!==Le||t[94]!==_e||t[95]!==r||t[96]!==x||t[97]!==b||t[98]!==e){const ge=U.map(X0),st=_e.map(Z0),wt=Le.map(ej);vt=z?L.map(tj):[];let tt;e:{if(!z){tt=["commands","sessions"];break e}const $t=sj,Dt=[{key:"commands",score:$t(U)},{key:"settings",score:$t(_e)},{key:"sessions",score:$t(Le)},{key:"files",score:$t(L)}];Dt.sort(nj),tt=Dt.map(rj)}const ut=tt;let Mt;t[114]!==Y||t[115]!==x?(Mt=$t=>{Y(),x($t.id,kr($t))},t[114]=Y,t[115]=x,t[116]=Mt):Mt=t[116];const It=Mt;let zt;t[117]!==Y||t[118]!==N||t[119]!==w||t[120]!==g?(zt=async $t=>{if(!N)return;const Dt=await Cc(w,$t);if(!Dt.ok){me.error(Ac(Dt.reason));return}g(N,$t),Y()},t[117]=Y,t[118]=N,t[119]=w,t[120]=g,t[121]=zt):zt=t[121];const ss=zt;let Bt;t[122]!==b?(Bt=$t=>ka(ei($t,b)),t[122]=b,t[123]=Bt):Bt=t[123];const Ft=Bt;He=Cs,Ze=n,pt=r;let Jt;t[124]!==e?(Jt=e("commandPalette.title"),t[124]=e,t[125]=Jt):Jt=t[125];let es;t[126]!==Jt?(es=s.jsx(Ps,{children:Jt}),t[126]=Jt,t[127]=es):es=t[127];let Lt;t[128]!==e?(Lt=e("commandPalette.description"),t[128]=e,t[129]=Lt):Lt=t[129];let Pt;t[130]!==Lt?(Pt=s.jsx(qs,{children:Lt}),t[130]=Lt,t[131]=Pt):Pt=t[131],t[132]!==es||t[133]!==Pt?(At=s.jsxs(Ms,{className:"sr-only",children:[es,Pt]}),t[132]=es,t[133]=Pt,t[134]=At):At=t[134],$e=ks,Be="overflow-hidden p-0",Je=!0,Q=Ca,Xe=!1,lt="[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta";let Kt;t[135]!==e?(Kt=e("commandPalette.input.placeholder"),t[135]=e,t[136]=Kt):Kt=t[136],t[137]!==M||t[138]!==Kt?(bt=s.jsx(Aa,{value:M,onValueChange:P,placeholder:Kt}),t[137]=M,t[138]=Kt,t[139]=bt):bt=t[139],xe=Da;let yt;t[140]!==e?(yt=e("commandPalette.empty.noResults"),t[140]=e,t[141]=yt):yt=t[141],t[142]!==yt?(Ke=s.jsx(Ta,{children:yt}),t[142]=yt,t[143]=Ke):Ke=t[143],qe=ut.map($t=>$t==="commands"&&ge.length>0?s.jsx(ti,{children:ge.map(Dt=>s.jsxs(ni,{value:Dt.id,onSelect:Dt.onSelect,children:[Dt.icon,s.jsx("span",{children:Dt.title}),Dt.shortcutId?s.jsx(Jp,{children:Ft(Dt.shortcutId)}):null]},Dt.id))},"commands"):$t==="settings"&&st.length>0?s.jsx(ti,{children:st.map(ij)},"settings"):$t==="sessions"&&wt.length>0?s.jsx(ti,{children:wt.map(Dt=>{const fs=Dt.title||e("commandPalette.session.untitled"),ms=kr(Dt),xs=ue(Dt.id,ms);return s.jsxs(ni,{value:`session:${Dt.id}`,onSelect:()=>It(Dt),children:[s.jsx(T,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:fs}),xs?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(T,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:xs})]}):null]},Dt.id)})},"sessions"):$t==="files"&&vt.length>0?s.jsx(ti,{children:vt.map(Dt=>{const fs=Qp(Dt.relativePath||Dt.name,{maxLength:80});return s.jsxs(ni,{value:`file:${Dt.path}`,onSelect:()=>{ss(Dt.path)},children:[s.jsx(Mr,{filePath:Dt.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":Dt.relativePath,children:fs})]},`file:${Dt.path}`)})},"files"):null),t[83]=ue,t[84]=Y,t[85]=N,t[86]=w,t[87]=z,t[88]=n,t[89]=g,t[90]=M,t[91]=U,t[92]=L,t[93]=Le,t[94]=_e,t[95]=r,t[96]=x,t[97]=b,t[98]=e,t[99]=xe,t[100]=Q,t[101]=$e,t[102]=He,t[103]=Ke,t[104]=qe,t[105]=Xe,t[106]=lt,t[107]=bt,t[108]=Be,t[109]=Je,t[110]=Ze,t[111]=pt,t[112]=At,t[113]=vt}else xe=t[99],Q=t[100],$e=t[101],He=t[102],Ke=t[103],qe=t[104],Xe=t[105],lt=t[106],bt=t[107],Be=t[108],Je=t[109],Ze=t[110],pt=t[111],At=t[112],vt=t[113];let at;t[144]!==z||t[145]!==G||t[146]!==e||t[147]!==vt?(at=z&&G&&vt.length===0?s.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:e("commandPalette.empty.searchingFiles")}):null,t[144]=z,t[145]=G,t[146]=e,t[147]=vt,t[148]=at):at=t[148];let ct;t[149]!==xe||t[150]!==Ke||t[151]!==qe||t[152]!==at?(ct=s.jsxs(xe,{children:[Ke,qe,at]}),t[149]=xe,t[150]=Ke,t[151]=qe,t[152]=at,t[153]=ct):ct=t[153];let Ot;t[154]!==Q||t[155]!==Xe||t[156]!==lt||t[157]!==bt||t[158]!==ct?(Ot=s.jsxs(Q,{shouldFilter:Xe,className:lt,children:[bt,ct]}),t[154]=Q,t[155]=Xe,t[156]=lt,t[157]=bt,t[158]=ct,t[159]=Ot):Ot=t[159];let Zt;t[160]!==$e||t[161]!==Be||t[162]!==Je||t[163]!==Ot?(Zt=s.jsx($e,{className:Be,showCloseButton:Je,children:Ot}),t[160]=$e,t[161]=Be,t[162]=Je,t[163]=Ot,t[164]=Zt):Zt=t[164];let Et;return t[165]!==He||t[166]!==Ze||t[167]!==pt||t[168]!==At||t[169]!==Zt?(Et=s.jsxs(He,{open:Ze,onOpenChange:pt,children:[At,Zt]}),t[165]=He,t[166]=Ze,t[167]=pt,t[168]=At,t[169]=Zt,t[170]=Et):Et=t[170],Et};function w0(t){return t.isCommandPaletteOpen}function v0(t){return t.setCommandPaletteOpen}function j0(t){return t.setActiveMainTab}function S0(t){return t.setSettingsDialogOpen}function N0(t){return t.setSettingsPage}function k0(t){return t.setSessionSwitcherOpen}function C0(t){return t.toggleSidebar}function A0(t){return t.toggleRightSidebar}function D0(t){return t.toggleBottomTerminal}function T0(t){return t.openContextOverview}function P0(t){return t.openContextFile}function I0(t){return t.shortcutOverrides}function R0(t){return t.openNewSessionDraft}function E0(t){return t.setCurrentSession}function M0(t){return t.activeSessions}function F0(t){return t.currentDirectory}function L0(t){return t.getActiveProject()}function O0(t){return t.searchFiles}function B0(t){return t.ensureStatus}function _0(){Om()}function V0(){Nr.requestDirectoryDialog()}function $0(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function z0(t){return t.slug!=="home"}function W0(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function U0(t){return t.worktreeMetadata}function H0(t){return{path:Gl(t.path),name:t.name,relativePath:t.relativePath}}function G0(t){return{item:t,score:0}}function K0(t){return t.searchText}function q0(t){return t.searchText}function Y0(t){return{item:t,score:0}}function J0(t){return t.title||""}function Q0(t){return t.name}function X0(t){return t.item}function Z0(t){return t.item}function ej(t){return t.item}function tj(t){return t.item}function sj(t){return t.length?t[0].score:1/0}function nj(t,e){return t.score-e.score}function rj(t){return t.key}function ij(t){return s.jsxs(ni,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const Pu=(t,e,n)=>Zp(t)?ka(ei(t,n)):e,oj=()=>{const t=ht.c(68),{t:e}=jt(),n=Me(aj),r=Me(lj),o=Me(cj);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=Xp(),t[0]=a):a=t[0];const c=a;let l,d,m,f,u,g,b,h,x;if(t[1]!==n||t[2]!==r||t[3]!==o||t[4]!==e){const R=[{categoryKey:"helpDialog.section.navigationCommands",items:[{id:"open_command_palette",descriptionKey:"helpDialog.item.openCommandPalette",icon:"command",keys:""},{id:"open_help",descriptionKey:"helpDialog.item.showKeyboardShortcuts",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"helpDialog.item.toggleSessionSidebar",icon:"layout-left",keys:""},{id:"cycle_agent",keys:"",descriptionKey:"helpDialog.item.cycleAgent",icon:"ai-agent"},{id:"open_model_selector",descriptionKey:"helpDialog.item.openModelSelector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"helpDialog.item.navigateModels",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"helpDialog.item.adjustThinkingMode",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"helpDialog.item.cycleThinkingVariant",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${c} + N`],descriptionKey:"helpDialog.item.newWindow",icon:"window"}]},{categoryKey:"helpDialog.section.sessionManagement",items:[{id:"new_chat",descriptionKey:"helpDialog.item.createNewSession",icon:"add",keys:""},{id:"new_chat_worktree",descriptionKey:"helpDialog.item.createNewWorktreeDraft",icon:"git-branch",keys:""},{id:"focus_input",descriptionKey:"helpDialog.item.focusChatInput",icon:"text",keys:""},{id:"abort_run",descriptionKey:"helpDialog.item.abortActiveRun",icon:"close-circle",keys:""}]},{categoryKey:"helpDialog.section.panels",items:[{id:"toggle_right_sidebar",descriptionKey:"helpDialog.item.toggleRightSidebar",icon:"layout-right",keys:""},{id:"open_right_sidebar_git",descriptionKey:"helpDialog.item.openRightSidebarGitTab",icon:"git-branch",keys:""},{id:"open_right_sidebar_files",descriptionKey:"helpDialog.item.openRightSidebarFilesTab",icon:"layout-right",keys:""},{id:"cycle_right_sidebar_tab",descriptionKey:"helpDialog.item.cycleRightSidebarTab",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{id:"toggle_terminal_expanded",descriptionKey:"helpDialog.item.toggleTerminalExpanded",icon:"window",keys:""},{id:"toggle_context_plan",descriptionKey:"helpDialog.item.togglePlanContextPanel",icon:"time",keys:""}]},{categoryKey:"helpDialog.section.interface",items:[{id:"cycle_theme",descriptionKey:"helpDialog.item.cycleTheme",icon:"palette",keys:""},{keys:[`${c} + 1...9`],descriptionKey:"helpDialog.item.switchProject",icon:"layout-left"},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"cycle_services_tab",descriptionKey:"helpDialog.item.cycleServicesTab",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"helpDialog.item.openSettings",icon:"settings-3",keys:""}]}];d=Cs,h=n,x=r,l=ks,g="max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden";let B;t[14]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(T,{name:"settings-3",className:"h-5 w-5"}),t[14]=B):B=t[14];let O;t[15]!==e?(O=e("helpDialog.title"),t[15]=e,t[16]=O):O=t[16];let F;t[17]!==O?(F=s.jsxs(Ps,{className:"flex items-center gap-2",children:[B,O]}),t[17]=O,t[18]=F):F=t[18];let _;t[19]!==e?(_=e("helpDialog.description"),t[19]=e,t[20]=_):_=t[20];let ie;t[21]!==_?(ie=s.jsx(qs,{children:_}),t[21]=_,t[22]=ie):ie=t[22],t[23]!==F||t[24]!==ie?(b=s.jsxs(Ms,{children:[F,ie]}),t[23]=F,t[24]=ie,t[25]=b):b=t[25],u="flex-1 overflow-y-auto mt-3 pr-1",m="space-y-4",f=R.map(oe=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(oe.categoryKey)}),s.jsx("div",{className:"space-y-1",children:oe.items.map(ne=>{const Y=ne.id?Pu(ne.id,Array.isArray(ne.keys)?ne.keys[0]:ne.keys,o):Array.isArray(ne.keys)?ne.keys:ne.keys.split(" / ");return s.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[ne.icon&&s.jsx(T,{name:ne.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(ne.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(Y)?Y:[Y]).map((te,de)=>s.jsxs(i.Fragment,{children:[de>0&&s.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:e("helpDialog.keyCombiner.or")}),s.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:te})]},`${te}-${de}`))})]},ne.id||ne.descriptionKey)})})]},oe.categoryKey)),t[1]=n,t[2]=r,t[3]=o,t[4]=e,t[5]=l,t[6]=d,t[7]=m,t[8]=f,t[9]=u,t[10]=g,t[11]=b,t[12]=h,t[13]=x}else l=t[5],d=t[6],m=t[7],f=t[8],u=t[9],g=t[10],b=t[11],h=t[12],x=t[13];let y;t[26]!==m||t[27]!==f?(y=s.jsx("div",{className:m,children:f}),t[26]=m,t[27]=f,t[28]=y):y=t[28];let p;t[29]===Symbol.for("react.memo_cache_sentinel")?(p=s.jsx(T,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),t[29]=p):p=t[29];let C;t[30]!==e?(C=e("helpDialog.proTips.title"),t[30]=e,t[31]=C):C=t[31];let v;t[32]!==C?(v=s.jsx("p",{className:"font-medium mb-1",children:C}),t[32]=C,t[33]=v):v=t[33];let k;t[34]!==o||t[35]!==e?(k=e("helpDialog.proTips.commandPalette",{shortcut:Pu("open_command_palette",`${c} P`,o)}),t[34]=o,t[35]=e,t[36]=k):k=t[36];let w;t[37]!==k?(w=s.jsxs("li",{children:["• ",k]}),t[37]=k,t[38]=w):w=t[38];let A;t[39]!==e?(A=e("helpDialog.proTips.recentSessions"),t[39]=e,t[40]=A):A=t[40];let S;t[41]!==A?(S=s.jsxs("li",{children:["• ",A]}),t[41]=A,t[42]=S):S=t[42];let I;t[43]!==e?(I=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=I):I=t[44];let D;t[45]!==I?(D=s.jsxs("li",{children:["• ",I]}),t[45]=I,t[46]=D):D=t[46];let N;t[47]!==w||t[48]!==S||t[49]!==D?(N=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[w,S,D]}),t[47]=w,t[48]=S,t[49]=D,t[50]=N):N=t[50];let M;t[51]!==v||t[52]!==N?(M=s.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:s.jsxs("div",{className:"flex items-start gap-2",children:[p,s.jsxs("div",{className:"typography-meta text-muted-foreground",children:[v,N]})]})}),t[51]=v,t[52]=N,t[53]=M):M=t[53];let P;t[54]!==M||t[55]!==u||t[56]!==y?(P=s.jsxs("div",{className:u,children:[y,M]}),t[54]=M,t[55]=u,t[56]=y,t[57]=P):P=t[57];let E;t[58]!==l||t[59]!==P||t[60]!==g||t[61]!==b?(E=s.jsxs(l,{className:g,children:[b,P]}),t[58]=l,t[59]=P,t[60]=g,t[61]=b,t[62]=E):E=t[62];let V;return t[63]!==d||t[64]!==E||t[65]!==h||t[66]!==x?(V=s.jsx(d,{open:h,onOpenChange:x,children:E}),t[63]=d,t[64]=E,t[65]=h,t[66]=x,t[67]=V):V=t[67],V};function aj(t){return t.isHelpDialogOpen}function lj(t){return t.setHelpDialogOpen}function cj(t){return t.shortcutOverrides}const dj=()=>{const t=ht.c(32),{t:e}=jt(),n=Me(uj),r=Me(mj),o=Me(fj);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await tr(o)).ok){me.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}me.error(e("openCodeStatusDialog.toast.copyFailed"))},t[0]=o,t[1]=e,t[2]=a):a=t[2];const c=a;let l;t[3]!==e?(l=e("openCodeStatusDialog.title"),t[3]=e,t[4]=l):l=t[4];let d;t[5]!==l?(d=s.jsx(Ps,{children:l}),t[5]=l,t[6]=d):d=t[6];let m;t[7]!==e?(m=e("openCodeStatusDialog.description"),t[7]=e,t[8]=m):m=t[8];let f;t[9]!==m?(f=s.jsx(qs,{children:m}),t[9]=m,t[10]=f):f=t[10];let u;t[11]!==d||t[12]!==f?(u=s.jsxs(Ms,{children:[d,f]}),t[11]=d,t[12]=f,t[13]=u):u=t[13];let g;t[14]!==e?(g=e("openCodeStatusDialog.actions.copy"),t[14]=e,t[15]=g):g=t[15];let b;t[16]!==c||t[17]!==g?(b=s.jsx("div",{className:"flex items-center justify-end",children:s.jsx("button",{type:"button",onClick:c,className:"app-region-no-drag inline-flex h-9 items-center justify-center rounded-md px-3 typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:g})}),t[16]=c,t[17]=g,t[18]=b):b=t[18];let h;t[19]!==o||t[20]!==e?(h=o||e("openCodeStatusDialog.empty.noData"),t[19]=o,t[20]=e,t[21]=h):h=t[21];let x;t[22]!==h?(x=s.jsx("pre",{className:"max-h-[60vh] overflow-auto rounded-lg bg-surface-muted p-4 typography-code text-foreground whitespace-pre-wrap",children:h}),t[22]=h,t[23]=x):x=t[23];let y;t[24]!==u||t[25]!==b||t[26]!==x?(y=s.jsxs(ks,{className:"max-w-2xl",children:[u,b,x]}),t[24]=u,t[25]=b,t[26]=x,t[27]=y):y=t[27];let p;return t[28]!==n||t[29]!==r||t[30]!==y?(p=s.jsx(Cs,{open:n,onOpenChange:r,children:y}),t[28]=n,t[29]=r,t[30]=y,t[31]=p):p=t[31],p};function uj(t){return t.isOpenCodeStatusDialogOpen}function mj(t){return t.setOpenCodeStatusDialogOpen}function fj(t){return t.openCodeStatusText}const hj=180,Iu=600,pj=1,gj=6,xj=({currentSessionId:t,sortedSessions:e,recentSessionIds:n=[],ensureSessionRenderable:r})=>{const o=i.useRef(new Map),a=i.useRef([]),c=i.useRef(new Set),l=i.useMemo(()=>Fr(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<pj&&a.current.length>0;){const f=a.current.shift();if(!f)break;mt.getState().currentSessionId!==f&&(xd(f).renderable||(c.current.add(f),r(f).catch(()=>{}).finally(()=>{c.current.delete(f),d()})))}},[r,l]),m=i.useCallback(f=>{if(l||!f||f===t||typeof window>"u"||xd(f).renderable||c.current.has(f)||a.current.includes(f))return;a.current.length>=gj&&a.current.shift();const u=o.current.get(f);u!==void 0&&window.clearTimeout(u);const g=window.setTimeout(()=>{o.current.delete(f),a.current.push(f),d()},hj);o.current.set(f,g)},[t,l,d]);i.useEffect(()=>{if(l||!t||e.length===0)return;const f=window.setTimeout(()=>{const u=e.findIndex(g=>g.id===t);u<0||(m(e[u-1]?.id),m(e[u+1]?.id))},Iu);return()=>window.clearTimeout(f)},[t,l,m,e]),i.useEffect(()=>{if(l||!t||n.length===0)return;const f=window.setTimeout(()=>{const u=n.indexOf(t);u<0||(m(n[u-1]),m(n[u+1]))},Iu);return()=>window.clearTimeout(f)},[t,l,n,m]),i.useEffect(()=>{const f=o.current;return()=>{f.forEach(u=>{clearTimeout(u)}),f.clear(),a.current=[]}},[])};let Ui=null,Hi=null,na=null,Ao=0,ja=null;const ji=new Set,bj=3e4,yj=45e3,_f=()=>{na&&(clearTimeout(na),na=null)},Vf=()=>{if(Hi||ji.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Ao,5)),bj);Hi=setTimeout(()=>{Hi=null,Ao+=1,Rc()},t)},Do=()=>{_f(),Ui&&Ui.close(),Ui=null},Ru=()=>{_f(),ji.size!==0&&(na=setTimeout(()=>{Do(),Vf()},yj))},wj=t=>{if(!t||t.trim().length===0)return null;try{const e=JSON.parse(t),n=typeof e?.type=="string"?e.type:"",r=e?.properties;return n?{type:n,properties:r}:null}catch{return null}},vj=t=>{if(t.type==="openchamber:event-stream-ready"){Ao=0;return}if(t.type==="openchamber:heartbeat"||t.type!=="openchamber:scheduled-task-ran")return;const e=t.properties&&typeof t.properties=="object"?t.properties:null,n=typeof e?.projectId=="string"?e.projectId:"",r=typeof e?.taskId=="string"?e.taskId:"",o=typeof e?.ranAt=="number"?e.ranAt:Date.now(),a=e?.status,c=a==="running"||a==="error"?a:"success";if(!n||!r)return;const l={type:"scheduled-task-ran",projectId:n,taskId:r,ranAt:o,status:c,...typeof e?.sessionId=="string"&&e.sessionId.length>0?{sessionId:e.sessionId}:{}};for(const d of ji)d(l)},Rc=()=>{if(typeof window>"u"||ji.size===0||typeof EventSource!="function"||Ui&&Ui.readyState!==EventSource.CLOSED)return;Do();const t=new EventSource(wi().sse("/api/openchamber/events"));t.onopen=()=>{Ru()},t.onmessage=e=>{Ru();const n=wj(e.data);n&&vj(n)},t.onerror=()=>{Do(),Vf()},Ui=t},jj=()=>{ja||typeof window>"u"||(ja=gm(()=>{Do(),Ao=0,Rc()}))},Sj=()=>{ja?.(),ja=null},$f=t=>(ji.add(t),jj(),Rc(),()=>{ji.delete(t),ji.size===0&&(Hi&&(clearTimeout(Hi),Hi=null),Ao=0,Do(),Sj())}),Ba=async(t,e)=>{try{const n=await t.json();if(n&&typeof n.error=="string"&&n.error.trim().length>0)return n.error}catch{return e}return e},Xi=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},Nj=async t=>{const e=Xi(t),n=await gs(`/api/projects/${encodeURIComponent(e)}/scheduled-tasks`);if(!n.ok)throw new Error(await Ba(n,"Failed to load scheduled tasks"));const r=await n.json().catch(()=>null);return!r||!Array.isArray(r.tasks)?[]:r.tasks},Eu=async(t,e)=>{const n=Xi(t),r=await gs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks`,{method:"PUT",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({task:e})});if(!r.ok)throw new Error(await Ba(r,"Failed to save scheduled task"));const o=await r.json().catch(()=>null);return!o||!Array.isArray(o.tasks)?[]:o.tasks},kj=async(t,e)=>{const n=Xi(t),r=Xi(e),o=await gs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}`,{method:"DELETE",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Ba(o,"Failed to delete scheduled task"));const a=await o.json().catch(()=>null);return!a||!Array.isArray(a.tasks)?[]:a.tasks},Cj=async(t,e)=>{const n=Xi(t),r=Xi(e),o=await gs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}/run`,{method:"POST",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Ba(o,"Failed to run scheduled task"));const a=await o.json().catch(()=>null);return{sessionId:typeof a?.sessionId=="string"&&a.sessionId.length>0?a.sessionId:void 0}};function zf(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return mm.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function Aj(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=mm.CronExpressionParser.parse(t,r),a=[];for(let c=0;c<n;c+=1){const l=o.next();l&&a.push(l.toDate())}return a}catch{return[]}}const Dj=[{expression:"*/5 * * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.every5min"},{expression:"0 * * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.everyHour"},{expression:"0 9 * * 1",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.monday9am"},{expression:"0 9,17 * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.9am5pm"},{expression:"0 0 1 * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.firstOfMonth"}],Wf=[0,1,2,3,4,5,6],Kl=typeof Intl<"u"&&typeof Intl.supportedValuesOf=="function"?Intl.supportedValuesOf("timeZone"):["UTC","Europe/Kyiv","Europe/London","Europe/Berlin","America/New_York","America/Los_Angeles","Asia/Tokyo"],Mu=()=>{const t=new Date,e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},ra=t=>{const e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!e)return null;const n=Number(e[1]),r=Number(e[2]),o=Number(e[3]),a=new Date(n,r-1,o);return Number.isNaN(a.getTime())||a.getFullYear()!==n||a.getMonth()!==r-1||a.getDate()!==o?null:a},Fu=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},Tj=(t,e,n)=>{const r=ra(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},Lu=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),Pj=(t,e)=>{const n=t.getFullYear(),r=t.getMonth(),c=(new Date(n,r,1).getDay()-e+7)%7,l=new Date(n,r+1,0).getDate(),d=new Date(n,r,0).getDate(),m=[];for(let f=0;f<42;f+=1){const u=f-c+1;if(u<=0){const g=d+u;m.push({date:new Date(n,r-1,g),inCurrentMonth:!1});continue}if(u>l){m.push({date:new Date(n,r+1,u-l),inCurrentMonth:!1});continue}m.push({date:new Date(n,r,u),inCurrentMonth:!0})}return m},Ij=t=>{const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour24:"00",hour12:"12",minute:"00",meridiem:"AM"};const n=Number(e[1]),r=e[2],o=n>=12?"PM":"AM",a=n%12===0?12:n%12;return{hour24:String(n).padStart(2,"0"),hour12:String(a).padStart(2,"0"),minute:r,meridiem:o}},mi=(t,e,n)=>{const r=Number(t),o=Number(e),a=Number.isFinite(r)?Math.min(12,Math.max(1,r)):12,c=Number.isFinite(o)?Math.min(59,Math.max(0,o)):0;let l=a%12;return n==="PM"&&(l+=12),`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`},so=(t,e)=>{const{max:n,min:r=0,loop:o=!1}=e;let a=Number.parseInt(t,10);return Number.isFinite(a)?(o?(a>n&&(a=r),a<r&&(a=n)):(a>n&&(a=n),a<r&&(a=r)),String(a).padStart(2,"0")):"00"},Ou=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:so(t,{min:1,max:12}),Ho=t=>/^[0-5][0-9]$/.test(t)?t:so(t,{max:59}),Rj=(t,e)=>so(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),Bu=(t,e)=>so(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),Ej=t=>{try{const e=Intl.Locale;if(typeof e!="function")return 1;const r=new e(t).weekInfo?.firstDay;return typeof r!="number"?1:r%7}catch{return 1}},Mj=t=>{try{const e=new Intl.DateTimeFormat(t,{hour:"numeric"}).resolvedOptions();return typeof e.hour12=="boolean"?!e.hour12:e.hourCycle==="h23"||e.hourCycle==="h24"}catch{return!0}},Fj=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return Wf.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},Lj=(t,e)=>[...t.slice(e),...t.slice(0,e)],On=t=>{const e=ht.c(6),{htmlFor:n,required:r,children:o}=t;let a;e[0]!==r?(a=r&&s.jsx("span",{className:"ml-0.5 text-destructive",children:"*"}),e[0]=r,e[1]=a):a=e[1];let c;return e[2]!==o||e[3]!==n||e[4]!==a?(c=s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,a]})}),e[2]=o,e[3]=n,e[4]=a,e[5]=c):c=e[5],c},_u=t=>{const e=ht.c(84),{value:n,onChange:r,use24Hour:o,hourAriaLabel:a,minuteAriaLabel:c,periodAriaLabel:l,amLabel:d,pmLabel:m}=t;let f;e[0]!==n?(f=Ij(n),e[0]=n,e[1]=f):f=e[1];const u=f,g=Qe.useRef(null),b=Qe.useRef(null),[h,x]=Qe.useState(null),[y,p]=Qe.useState(null),C=Qe.useRef(null),v=Qe.useRef(null);let k;e[2]===Symbol.for("react.memo_cache_sentinel")?(k=Se=>{C.current=Se,x(Se)},e[2]=k):k=e[2];const w=k;let A;e[3]===Symbol.for("react.memo_cache_sentinel")?(A=Se=>{v.current=Se,p(Se)},e[3]=A):A=e[3];const S=A,I=Wj,D=Uj,N=Hj;let M;e[4]!==r||e[5]!==u.meridiem||e[6]!==u.minute||e[7]!==o?(M=Se=>{const ue=Se.replace(/\D/g,"").slice(0,2);w(ue),ue.length===2&&(r(o?N(I(ue),u.minute):mi(Ou(ue),u.minute,u.meridiem)),w(null),b.current?.focus())},e[4]=r,e[5]=u.meridiem,e[6]=u.minute,e[7]=o,e[8]=M):M=e[8];const P=M;let E;e[9]!==r||e[10]!==u.meridiem||e[11]!==u.minute||e[12]!==o?(E=()=>{const Se=C.current;if(Se!==null&&(w(null),Se.length!==0)){if(o){r(N(I(Se.padStart(2,"0")),u.minute));return}r(mi(Ou(Se.padStart(2,"0")),u.minute,u.meridiem))}},e[9]=r,e[10]=u.meridiem,e[11]=u.minute,e[12]=o,e[13]=E):E=e[13];const V=E;let R;e[14]!==r||e[15]!==u.hour12||e[16]!==u.hour24||e[17]!==u.meridiem||e[18]!==o?(R=Se=>{const ue=Se.replace(/\D/g,"").slice(0,2);S(ue),ue.length===2&&(r(o?N(u.hour24,Ho(ue)):mi(u.hour12,Ho(ue),u.meridiem)),S(null))},e[14]=r,e[15]=u.hour12,e[16]=u.hour24,e[17]=u.meridiem,e[18]=o,e[19]=R):R=e[19];const B=R;let O;e[20]!==r||e[21]!==u.hour12||e[22]!==u.hour24||e[23]!==u.meridiem||e[24]!==o?(O=()=>{const Se=v.current;Se!==null&&(S(null),Se.length!==0&&r(o?N(u.hour24,Ho(Se.padStart(2,"0"))):mi(u.hour12,Ho(Se.padStart(2,"0")),u.meridiem)))},e[20]=r,e[21]=u.hour12,e[22]=u.hour24,e[23]=u.meridiem,e[24]=o,e[25]=O):O=e[25];const F=O;let _;e[26]!==r||e[27]!==u.hour12||e[28]!==u.hour24||e[29]!==u.meridiem||e[30]!==u.minute||e[31]!==o?(_=Se=>r(o?N(D(u.hour24,Se),u.minute):mi(Rj(u.hour12,Se),u.minute,u.meridiem)),e[26]=r,e[27]=u.hour12,e[28]=u.hour24,e[29]=u.meridiem,e[30]=u.minute,e[31]=o,e[32]=_):_=e[32];const ie=_;let oe;e[33]!==r||e[34]!==u.hour12||e[35]!==u.hour24||e[36]!==u.meridiem||e[37]!==u.minute||e[38]!==o?(oe=Se=>r(o?N(u.hour24,Bu(u.minute,Se)):mi(u.hour12,Bu(u.minute,Se),u.meridiem)),e[33]=r,e[34]=u.hour12,e[35]=u.hour24,e[36]=u.meridiem,e[37]=u.minute,e[38]=o,e[39]=oe):oe=e[39];const ne=oe;let Y;e[40]!==r||e[41]!==u.hour12||e[42]!==u.meridiem||e[43]!==u.minute?(Y=Se=>{Se!==u.meridiem&&r(mi(u.hour12,u.minute,Se))},e[40]=r,e[41]=u.hour12,e[42]=u.meridiem,e[43]=u.minute,e[44]=Y):Y=e[44];const te=Y;let de;e[45]!==V||e[46]!==ie?(de=Se=>{if(Se.key==="ArrowRight"){Se.preventDefault(),V(),b.current?.focus();return}(Se.key==="ArrowUp"||Se.key==="ArrowDown")&&(Se.preventDefault(),w(null),ie(Se.key==="ArrowUp"?1:-1))},e[45]=V,e[46]=ie,e[47]=de):de=e[47];const be=de;let ke;e[48]!==F||e[49]!==ne?(ke=Se=>{if(Se.key==="ArrowLeft"&&(Se.currentTarget.selectionStart??0)===0){Se.preventDefault(),F(),g.current?.focus();return}(Se.key==="ArrowUp"||Se.key==="ArrowDown")&&(Se.preventDefault(),S(null),ne(Se.key==="ArrowUp"?1:-1))},e[48]=F,e[49]=ne,e[50]=ke):ke=e[50];const ae=ke,ve=o?"px-2":"pl-2 pr-1";let J;e[51]!==ve?(J=Te("inline-flex h-9 w-fit items-center gap-1 rounded-md border border-border bg-background focus-within:ring-1 focus-within:ring-interactive-focusRing focus-within:border-interactive-focusRing",ve),e[51]=ve,e[52]=J):J=e[52];const H=h??(o?u.hour24:u.hour12);let q;e[53]!==P?(q=Se=>P(Se.target.value),e[53]=P,e[54]=q):q=e[54];let ce;e[55]===Symbol.for("react.memo_cache_sentinel")?(ce=()=>w(""),e[55]=ce):ce=e[55];let fe;e[56]!==V||e[57]!==a||e[58]!==be||e[59]!==H||e[60]!==q?(fe=s.jsx("input",{ref:g,inputMode:"numeric",value:H,onChange:q,onKeyDown:be,onFocus:ce,onBlur:V,maxLength:2,"aria-label":a,className:"h-7 w-7 shrink-0 rounded-sm bg-transparent text-center font-mono text-sm tabular-nums text-foreground outline-none caret-transparent focus:bg-interactive-hover"}),e[56]=V,e[57]=a,e[58]=be,e[59]=H,e[60]=q,e[61]=fe):fe=e[61];let De;e[62]===Symbol.for("react.memo_cache_sentinel")?(De=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=De):De=e[62];const Re=y??u.minute;let Fe;e[63]!==B?(Fe=Se=>B(Se.target.value),e[63]=B,e[64]=Fe):Fe=e[64];let Oe;e[65]===Symbol.for("react.memo_cache_sentinel")?(Oe=()=>S(""),e[65]=Oe):Oe=e[65];let Ee;e[66]!==F||e[67]!==c||e[68]!==ae||e[69]!==Re||e[70]!==Fe?(Ee=s.jsx("input",{ref:b,inputMode:"numeric",value:Re,onChange:Fe,onKeyDown:ae,onFocus:Oe,onBlur:F,maxLength:2,"aria-label":c,className:"h-7 w-7 shrink-0 rounded-sm bg-transparent text-center font-mono text-sm tabular-nums text-foreground outline-none caret-transparent focus:bg-interactive-hover"}),e[66]=F,e[67]=c,e[68]=ae,e[69]=Re,e[70]=Fe,e[71]=Ee):Ee=e[71];let we;e[72]!==d||e[73]!==u.meridiem||e[74]!==l||e[75]!==m||e[76]!==te||e[77]!==o?(we=o?null:s.jsxs(Dn,{value:u.meridiem,onValueChange:Se=>te(Se),children:[s.jsx(Tn,{"aria-label":l,className:"ml-1 h-7 w-fit border-0 bg-transparent pl-2 pr-1 shadow-none hover:bg-interactive-hover focus:ring-0",children:s.jsx(fn,{})}),s.jsxs(Pn,{children:[s.jsx(vs,{value:"AM",children:d}),s.jsx(vs,{value:"PM",children:m})]})]}),e[72]=d,e[73]=u.meridiem,e[74]=l,e[75]=m,e[76]=te,e[77]=o,e[78]=we):we=e[78];let Pe;return e[79]!==J||e[80]!==fe||e[81]!==Ee||e[82]!==we?(Pe=s.jsxs("div",{className:J,children:[fe,De,Ee,we]}),e[79]=J,e[80]=fe,e[81]=Ee,e[82]=we,e[83]=Pe):Pe=e[83],Pe},Vu=t=>new Date(t.getFullYear(),t.getMonth(),1),Oj=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},$u=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),Bj=t=>{if(!t)return["09:00"];const n=(Array.isArray(t.schedule.times)?t.schedule.times:t.schedule.time?[t.schedule.time]:[]).filter(o=>typeof o=="string"&&/^([01]\d|2[0-3]):([0-5]\d)$/.test(o)).map(o=>o.trim()),r=Array.from(new Set(n)).sort((o,a)=>o.localeCompare(a));return r.length>0?r:["09:00"]},zu=(t,e)=>{const n=Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";return t?{id:t.id,name:t.name,enabled:t.enabled,schedule:{kind:t.schedule.kind==="cron"?"cron":t.schedule.kind==="once"?"once":t.schedule.kind==="weekly"?"weekly":"daily",times:Bj(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:Mu(),onceTime:typeof t.schedule.time=="string"&&/^([01]\d|2[0-3]):([0-5]\d)$/.test(t.schedule.time)?t.schedule.time:"09:00",weekdays:Array.isArray(t.schedule.weekdays)?t.schedule.weekdays:[1],timezone:t.schedule.timezone||n,cronExpression:t.schedule.kind==="cron"&&typeof t.schedule.cron=="string"?t.schedule.cron:""},execution:{prompt:t.execution.prompt,providerID:t.execution.providerID,modelID:t.execution.modelID,variant:t.execution.variant||"",agent:t.execution.agent||""},state:t.state}:{name:"",enabled:!0,schedule:{kind:"daily",times:["09:00"],onceDate:Mu(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent}}},_j=(t,e)=>{if(!t.name.trim())return e("sessions.scheduledTasks.editor.validation.taskNameRequired");if(!t.execution.prompt.trim())return e("sessions.scheduledTasks.editor.validation.promptRequired");if(!t.execution.providerID.trim()||!t.execution.modelID.trim())return e("sessions.scheduledTasks.editor.validation.modelRequired");if(t.schedule.kind==="once"){if(!/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.onceDate))return e("sessions.scheduledTasks.editor.validation.dateFormat");if(!/^([01]\d|2[0-3]):([0-5]\d)$/.test(t.schedule.onceTime))return e("sessions.scheduledTasks.editor.validation.timeFormat")}else if(t.schedule.kind==="cron"){if(!t.schedule.cronExpression.trim())return e("sessions.scheduledTasks.editor.validation.cronRequired");if(!zf(t.schedule.cronExpression).valid)return e("sessions.scheduledTasks.editor.validation.cronInvalid")}else if(t.schedule.times.filter(r=>/^([01]\d|2[0-3]):([0-5]\d)$/.test(r)).length===0)return e("sessions.scheduledTasks.editor.validation.atLeastOneTime");return t.schedule.kind==="weekly"&&t.schedule.weekdays.length===0?e("sessions.scheduledTasks.editor.validation.atLeastOneWeekday"):t.schedule.timezone.trim()?null:e("sessions.scheduledTasks.editor.validation.timezoneRequired")},Vj=t=>{const e=t.filter(n=>/^([01]\d|2[0-3]):([0-5]\d)$/.test(n));return Array.from(new Set(e)).sort((n,r)=>n.localeCompare(r))},$j=t=>{const e=ht.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?zf(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let m;e:{if(!d?.valid||!c.trim()){let _;e[2]===Symbol.for("react.memo_cache_sentinel")?(_=[],e[2]=_):_=e[2],m=_;break e}let F;e[3]!==c||e[4]!==n.schedule.timezone?(F=Aj(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=F):F=e[5],m=F}const f=m;let u;e[6]!==n.schedule.timezone||e[7]!==o?(u=F=>new Intl.DateTimeFormat(o,{timeZone:n.schedule.timezone,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(F),e[6]=n.schedule.timezone,e[7]=o,e[8]=u):u=e[8];const g=u;let b;e[9]!==a?(b=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=b):b=e[10];let h;e[11]!==b?(h=s.jsx(On,{htmlFor:"sched-cron",required:!0,children:b}),e[11]=b,e[12]=h):h=e[12];let x;e[13]!==r?(x=F=>r(_=>({..._,schedule:{..._.schedule,cronExpression:F.target.value}})),e[13]=r,e[14]=x):x=e[14];let y;e[15]!==a?(y=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=y):y=e[16];let p;e[17]!==c||e[18]!==x||e[19]!==y?(p=s.jsx(ln,{id:"sched-cron",value:c,onChange:x,placeholder:y,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=x,e[19]=y,e[20]=p):p=e[20];let C;e[21]!==c||e[22]!==d||e[23]!==a?(C=d&&!d.valid&&c.trim()?s.jsx("span",{className:"typography-micro text-destructive",children:a("sessions.scheduledTasks.editor.validation.cronInvalid")}):null,e[21]=c,e[22]=d,e[23]=a,e[24]=C):C=e[24];let v;e[25]!==h||e[26]!==p||e[27]!==C?(v=s.jsxs("div",{className:"flex flex-col gap-1",children:[h,p,C]}),e[25]=h,e[26]=p,e[27]=C,e[28]=v):v=e[28];let k;e[29]!==g||e[30]!==f||e[31]!==a?(k=f.length>0?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:a("sessions.scheduledTasks.editor.cronExpression.nextRuns")}),s.jsx("span",{className:"typography-micro text-foreground",children:f.map(g).join(", ")})]}):null,e[29]=g,e[30]=f,e[31]=a,e[32]=k):k=e[32];let w;e[33]!==a?(w=a("sessions.scheduledTasks.editor.cronExpression.examples"),e[33]=a,e[34]=w):w=e[34];let A;e[35]!==w?(A=s.jsx("span",{className:"typography-meta text-muted-foreground",children:w}),e[35]=w,e[36]=A):A=e[36];let S;e[37]!==r||e[38]!==a?(S=Dj.map(F=>s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 typography-micro text-foreground hover:bg-interactive-hover",onClick:()=>r(_=>({..._,schedule:{..._.schedule,cronExpression:F.expression}})),children:[s.jsx("span",{className:"font-mono",children:F.expression}),s.jsx("span",{className:"text-muted-foreground",children:a(F.labelKey)})]},F.expression)),e[37]=r,e[38]=a,e[39]=S):S=e[39];let I;e[40]!==S?(I=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:S}),e[40]=S,e[41]=I):I=e[41];let D;e[42]!==A||e[43]!==I?(D=s.jsxs("div",{className:"flex flex-col gap-1",children:[A,I]}),e[42]=A,e[43]=I,e[44]=D):D=e[44];let N;e[45]!==a?(N=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=N):N=e[46];let M;e[47]!==N?(M=s.jsx(On,{children:N}),e[47]=N,e[48]=M):M=e[48];let P;e[49]!==r?(P=F=>{r(_=>({..._,schedule:{..._.schedule,timezone:F}}))},e[49]=r,e[50]=P):P=e[50];let E;e[51]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Tn,{className:"w-fit max-w-full",children:s.jsx(fn,{})}),e[51]=E):E=e[51];let V;e[52]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsx(Pn,{children:Kl.map(Gj)}),e[52]=V):V=e[52];let R;e[53]!==n.schedule.timezone||e[54]!==P?(R=s.jsxs(Dn,{value:n.schedule.timezone,onValueChange:P,children:[E,V]}),e[53]=n.schedule.timezone,e[54]=P,e[55]=R):R=e[55];let B;e[56]!==M||e[57]!==R?(B=s.jsxs("div",{className:"flex flex-col gap-1",children:[M,R]}),e[56]=M,e[57]=R,e[58]=B):B=e[58];let O;return e[59]!==v||e[60]!==k||e[61]!==D||e[62]!==B?(O=s.jsxs("div",{className:"flex flex-col gap-3",children:[v,k,D,B]}),e[59]=v,e[60]=k,e[61]=D,e[62]=B,e[63]=O):O=e[63],O};function zj(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=jt(),l=Ut(X=>X.loadProviders),d=Ut(X=>X.loadAgents),m=Ut(X=>X.providers),f=Ut(X=>X.currentProviderId),u=Ut(X=>X.currentModelId),g=Ut(X=>X.currentVariant||""),b=Ut(X=>X.currentAgentName||""),h=Me(X=>X.timeFormatPreference),x=Me(X=>X.weekStartPreference),y=Me(X=>X.isMobile),[p,C]=Qe.useState(()=>zu(n,{providerID:f,modelID:u,variant:g,agent:b})),[v,k]=Qe.useState(!1),[w,A]=Qe.useState(!1),[S,I]=Qe.useState(!1),[D,N]=Qe.useState(""),[M,P]=Qe.useState(!1),[E,V]=Qe.useState(""),[R,B]=Qe.useState(!1),[O,F]=Qe.useState(""),[_,ie]=Qe.useState(()=>{const X=ra(n?.schedule?.date||"")||new Date;return new Date(X.getFullYear(),X.getMonth(),1)}),oe=Qe.useRef(null),ne=Qe.useRef(null),Y=Qe.useRef(null),te=Qe.useRef(null),de=Qe.useRef(null),be=Qe.useMemo(()=>Mj(c),[c]),ke=Qe.useMemo(()=>Ej(c),[c]),ae=Qe.useMemo(()=>h==="24h"?!0:h==="12h"?!1:be,[h,be]),ve=Qe.useMemo(()=>x==="sunday"?0:x==="monday"?1:ke,[x,ke]),J=Qe.useMemo(()=>{const X=Fj(c);return Lj(Wf.map(L=>({value:L,label:X[L]||""})),ve)},[c,ve]);Qe.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),Qe.useEffect(()=>{if(!e)return;C(zu(n,{providerID:f,modelID:u,variant:g,agent:b}));const X=ra(n?.schedule?.date||"")||new Date;ie(new Date(X.getFullYear(),X.getMonth(),1)),A(!1),P(!1),I(!1),V(""),N("")},[e,n,f,u,g,b]),Qe.useEffect(()=>{if(!w)return;const X=L=>{oe.current&&!oe.current.contains(L.target)&&A(!1)};return document.addEventListener("mousedown",X),()=>{document.removeEventListener("mousedown",X)}},[w]);const H=Qe.useMemo(()=>{const L=m.find(xe=>xe.id===p.execution.providerID)?.models?.find(xe=>xe.id===p.execution.modelID);return L?.variants?Object.keys(L.variants):[]},[m,p.execution.providerID,p.execution.modelID]),q=H.length>0,ce=Qe.useMemo(()=>!q||!p.execution.variant?"__default":H.includes(p.execution.variant)?p.execution.variant:"__default",[p.execution.variant,q,H]);Qe.useEffect(()=>{q||!p.execution.variant||C(X=>({...X,execution:{...X.execution,variant:""}}))},[q,p.execution.variant]);const fe=Qe.useCallback((X,L)=>{C(xe=>{const Q=new Set(xe.schedule.weekdays);return L?Q.add(X):Q.delete(X),{...xe,schedule:{...xe.schedule,weekdays:Array.from(Q).sort(($e,He)=>$e-He)}}})},[]),De=Qe.useCallback((X,L)=>{C(xe=>{const Q=xe.schedule.times.slice();return Q[X]=L,{...xe,schedule:{...xe.schedule,times:Q}}})},[]),Re=Qe.useCallback(X=>{C(L=>{const xe=L.schedule.times.filter((Q,$e)=>$e!==X);return{...L,schedule:{...L.schedule,times:xe.length>0?xe:["09:00"]}}})},[]),Fe=Qe.useCallback(()=>{C(X=>({...X,schedule:{...X.schedule,times:[...X.schedule.times,"12:00"]}}))},[]),Oe=Qe.useMemo(()=>Oj(),[]),Ee=Qe.useMemo(()=>Vu(Oe),[Oe]),we=Qe.useMemo(()=>{const X=ra(p.schedule.onceDate);return X?$u(X,Oe)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(X):null},[p.schedule.onceDate,c,a,Oe]),Pe=Qe.useMemo(()=>Vu(_).getTime()<=Ee.getTime(),[_,Ee]),Se=Qe.useMemo(()=>J.map(X=>X.label),[J]),ue=Qe.useCallback(X=>{C(L=>({...L,schedule:{...L.schedule,onceDate:X}}))},[]),K=Qe.useCallback((X,L)=>{if(X.startsWith("/")){const He=X.indexOf(" "),Ke=X.indexOf(`
167
- `),qe=Math.min(He===-1?X.length:He,Ke===-1?X.length:Ke);if(L<=qe&&He===-1){V(X.substring(1,qe)),P(!0),I(!1),B(!1);return}}P(!1);const xe=X.substring(0,L),Q=xe.lastIndexOf("#");if(Q!==-1){const He=Q>0?xe[Q-1]:null,Ke=xe.substring(Q+1);if((!He||/\s/.test(He))&&!Ke.includes(" ")&&!Ke.includes(`
168
- `)){F(Ke),B(!0),I(!1);return}}B(!1);const $e=xe.lastIndexOf("@");if($e!==-1){const He=$e>0?xe[$e-1]:null,Ke=xe.substring($e+1);(!He||/\s/.test(He))&&!Ke.includes(" ")&&!Ke.includes(`
169
- `)?(N(Ke),I(!0)):I(!1);return}I(!1)},[]),he=Qe.useCallback(X=>{C(L=>({...L,execution:{...L.execution,prompt:X}}))},[]),se=Qe.useCallback(X=>{const L=p.execution.prompt,Q=ne.current?.selectionStart??L.length,He=L.substring(0,Q).lastIndexOf("@"),Ke=X.relativePath&&X.relativePath.trim().length>0?X.relativePath.trim():X.path||X.name,qe=He!==-1?He:Q,Xe=`${L.substring(0,qe)}@${Ke} ${L.substring(Q)}`,lt=qe+Ke.length+2;he(Xe),I(!1),N(""),requestAnimationFrame(()=>{const bt=ne.current;bt&&(bt.selectionStart=lt,bt.selectionEnd=lt,bt.focus()),K(Xe,lt)})},[p.execution.prompt,he,K]),G=Qe.useCallback(X=>{const L=p.execution.prompt,Q=ne.current?.selectionStart??L.length,He=L.substring(0,Q).lastIndexOf("@"),Ke=He!==-1?He:Q,qe=`${L.substring(0,Ke)}@${X} ${L.substring(Q)}`,Xe=Ke+X.length+2;he(qe),I(!1),N(""),requestAnimationFrame(()=>{const lt=ne.current;lt&&(lt.selectionStart=Xe,lt.selectionEnd=Xe,lt.focus()),K(qe,Xe)})},[p.execution.prompt,he,K]),$=Qe.useCallback(X=>{const L=`/${X.name} `;he(L),P(!1),V(""),B(!1),requestAnimationFrame(()=>{const xe=ne.current;xe&&(xe.focus(),xe.selectionStart=xe.value.length,xe.selectionEnd=xe.value.length),K(L,L.length)})},[he,K]),pe=Qe.useCallback((X,L)=>{const xe=p.execution.prompt,$e=ne.current?.selectionStart??xe.length,Ke=xe.substring(0,$e).lastIndexOf("#"),qe=Ke!==-1?Ke:$e,Xe=`${xe.substring(0,qe)}#${L} ${xe.substring($e)}`,lt=qe+L.length+2;he(Xe),B(!1),F(""),requestAnimationFrame(()=>{const bt=ne.current;bt&&(bt.selectionStart=lt,bt.selectionEnd=lt,bt.focus()),K(Xe,lt)})},[p.execution.prompt,he,K]),ye=Qe.useCallback(X=>{if(M&&te.current&&(X.key==="Enter"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="Escape"||X.key==="Tab")){X.preventDefault(),te.current.handleKeyDown(X.key);return}S&&Y.current&&(X.key==="Enter"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="Escape"||X.key==="Tab")&&(X.preventDefault(),Y.current.handleKeyDown(X.key)),R&&de.current&&(X.key==="Enter"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="Escape"||X.key==="Tab")&&(X.preventDefault(),de.current.handleKeyDown(X.key))},[M,S,R]),z=Qe.useCallback(async()=>{const X=_j(p,a);if(X){me.error(X);return}const L={...p.id?{id:p.id}:{},name:p.name.trim(),enabled:p.enabled,schedule:{kind:p.schedule.kind,timezone:p.schedule.timezone.trim(),...p.schedule.kind==="cron"?{cron:p.schedule.cronExpression.trim()}:p.schedule.kind==="once"?{date:p.schedule.onceDate,time:p.schedule.onceTime}:{times:Vj(p.schedule.times),...p.schedule.kind==="weekly"?{weekdays:p.schedule.weekdays}:{}}},execution:{prompt:p.execution.prompt,providerID:p.execution.providerID,modelID:p.execution.modelID,...p.execution.variant.trim()?{variant:p.execution.variant.trim()}:{},...p.execution.agent.trim()?{agent:p.execution.agent.trim()}:{}},...p.state?{state:p.state}:{}};k(!0);try{await o(L),r(!1)}catch(xe){me.error(xe instanceof Error?xe.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{k(!1)}},[p,r,o,a]),Ne=Qe.useId(),U=Qe.useCallback(()=>typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"], [data-slot="select-content"]'),[]),Ie=a(n?"sessions.scheduledTasks.editor.title.edit":"sessions.scheduledTasks.editor.title.new"),_e=a("sessions.scheduledTasks.editor.description"),Ve=s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(On,{htmlFor:"sched-name",required:!0,children:a("sessions.scheduledTasks.editor.taskName.label")}),s.jsx(ln,{id:"sched-name",value:p.name,onChange:X=>C(L=>({...L,name:X.target.value})),placeholder:a("sessions.scheduledTasks.editor.taskName.placeholder"),maxLength:80,className:"w-full sm:max-w-[220px]"})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.scheduleType.label")}),s.jsxs(Dn,{value:p.schedule.kind,onValueChange:X=>{C(L=>({...L,schedule:{...L.schedule,kind:X,...X==="cron"&&!L.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(Tn,{className:"w-fit max-w-full",children:s.jsx(fn,{children:X=>a(X==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":X==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":X==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(Pn,{children:[s.jsx(vs,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(vs,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(vs,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(vs,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),p.schedule.kind==="cron"?s.jsx($j,{draft:p,setDraft:C,locale:c,t:a}):p.schedule.kind==="once"?s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex flex-col gap-1",ref:oe,children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.date.label")}),s.jsxs("div",{className:"relative",children:[s.jsxs("button",{type:"button",className:"inline-flex h-9 w-fit max-w-full items-center justify-between gap-2 rounded-md border border-border bg-background px-3 text-left hover:bg-interactive-hover",onClick:()=>A(X=>!X),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(T,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Tj(p.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(T,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"})]}),w?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+6px)] z-50 w-[288px] rounded-xl border border-border bg-background p-3 shadow-sm",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover disabled:cursor-not-allowed disabled:opacity-40",onClick:()=>ie(X=>Lu(X,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Pe,children:s.jsx(T,{name:"arrow-left-s",className:"h-4 w-4"})}),s.jsx("div",{className:"typography-ui-label text-foreground",children:new Intl.DateTimeFormat(c,{month:"long",year:"numeric"}).format(_)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>ie(X=>Lu(X,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(T,{name:"arrow-right-s",className:"h-4 w-4"})})]}),s.jsx("div",{className:"mb-1 grid grid-cols-7 gap-1 px-1",children:Se.map((X,L)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:X},`${X}-${L}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:Pj(_,ve).map(({date:X,inCurrentMonth:L})=>{const xe=Fu(X),Q=xe===p.schedule.onceDate,$e=$u(X,Oe),He=X.getTime()<Oe.getTime(),Ke=Q?"bg-interactive-selection text-interactive-selection-foreground":He?"text-muted-foreground/40":L?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{He||(ue(xe),A(!1))},disabled:He,className:["h-8 rounded-md typography-ui-label",Ke,$e&&!Q?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",He?"cursor-not-allowed opacity-45":""].join(" "),children:X.getDate()},xe)})}),s.jsxs("div",{className:"mt-2 flex items-center justify-between border-t border-border pt-2",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:we||""}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:()=>{ue(Fu(Oe)),ie(new Date(Oe.getFullYear(),Oe.getMonth(),1))},children:a("sessions.scheduledTasks.editor.date.jumpToToday")})]})]}):null]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.time.label")}),s.jsx(_u,{value:p.schedule.onceTime,use24Hour:ae,hourAriaLabel:a("sessions.scheduledTasks.editor.time.hourAria"),minuteAriaLabel:a("sessions.scheduledTasks.editor.time.minuteAria"),periodAriaLabel:a("sessions.scheduledTasks.editor.time.periodAria"),amLabel:a("sessions.scheduledTasks.editor.time.period.am"),pmLabel:a("sessions.scheduledTasks.editor.time.period.pm"),onChange:X=>C(L=>({...L,schedule:{...L.schedule,onceTime:X}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Dn,{value:p.schedule.timezone,onValueChange:X=>{C(L=>({...L,schedule:{...L.schedule,timezone:X}}))},children:[s.jsx(Tn,{className:"w-fit max-w-full",children:s.jsx(fn,{})}),s.jsx(Pn,{children:Kl.map(X=>s.jsx(vs,{value:X,children:X},X))})]})]})]})]}):s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[p.schedule.kind==="weekly"?s.jsxs("div",{className:"flex flex-col gap-1 sm:col-span-2",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.weekdays.label")}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-2",children:J.map(X=>{const L=p.schedule.weekdays.includes(X.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",L?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(ki,{checked:L,onChange:xe=>fe(X.value,xe),ariaLabel:X.label}),s.jsx("button",{type:"button",onClick:()=>fe(X.value,!L),className:"group-hover:text-foreground",children:X.label})]},X.value)})})]}):null,s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.times.label")}),s.jsx("div",{className:"flex flex-col gap-2",children:p.schedule.times.map((X,L)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(_u,{value:X,use24Hour:ae,hourAriaLabel:a("sessions.scheduledTasks.editor.time.hourAria"),minuteAriaLabel:a("sessions.scheduledTasks.editor.time.minuteAria"),periodAriaLabel:a("sessions.scheduledTasks.editor.time.periodAria"),amLabel:a("sessions.scheduledTasks.editor.time.period.am"),pmLabel:a("sessions.scheduledTasks.editor.time.period.pm"),onChange:xe=>De(L,xe)}),p.schedule.times.length>1?s.jsx(ze,{type:"button",size:"icon",variant:"ghost",onClick:()=>Re(L),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(T,{name:"close",className:"h-4 w-4"})}):null]},L))}),s.jsx("div",{children:s.jsxs(ze,{type:"button",size:"sm",variant:"outline",onClick:Fe,children:[s.jsx(T,{name:"add",className:"mr-1 h-4 w-4"})," ",a("sessions.scheduledTasks.editor.times.add")]})})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Dn,{value:p.schedule.timezone,onValueChange:X=>{C(L=>({...L,schedule:{...L.schedule,timezone:X}}))},children:[s.jsx(Tn,{className:"w-fit max-w-full",children:s.jsx(fn,{})}),s.jsx(Pn,{children:Kl.map(X=>s.jsx(vs,{value:X,children:X},X))})]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(On,{required:!0,children:a("sessions.scheduledTasks.editor.model.label")}),s.jsx(Cm,{providerId:p.execution.providerID,modelId:p.execution.modelID,onChange:(X,L)=>{C(xe=>({...xe,execution:{...xe.execution,providerID:X,modelID:L,variant:""}}))}})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.thinkingLevel.label")}),s.jsxs(Dn,{value:ce,disabled:!q,onValueChange:X=>{C(L=>({...L,execution:{...L.execution,variant:X==="__default"?"":X}}))},children:[s.jsx(Tn,{className:"w-fit max-w-full",children:s.jsx(fn,{children:X=>X==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):X})}),s.jsxs(Pn,{children:[s.jsx(vs,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),H.map(X=>s.jsx(vs,{value:X,children:X},X))]})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(On,{children:a("sessions.scheduledTasks.editor.agent.label")}),s.jsx(Am,{agentName:p.execution.agent,filter:X=>Dm(X.mode),onChange:X=>C(L=>({...L,execution:{...L.execution,agent:X}}))})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(On,{htmlFor:"sched-prompt",required:!0,children:a("sessions.scheduledTasks.editor.prompt.label")}),s.jsxs("div",{className:"relative",children:[s.jsx(yi,{id:"sched-prompt",ref:ne,value:p.execution.prompt,onChange:X=>{const L=X.target.value;he(L);const xe=X.target.selectionStart??L.length;K(L,xe)},onKeyDown:ye,rows:8,placeholder:a("sessions.scheduledTasks.editor.prompt.placeholder"),className:"typography-meta min-h-[120px] max-h-[300px] resize-none overflow-y-auto"}),M?s.jsx(Bm,{ref:te,searchQuery:E,onCommandSelect:$,onClose:()=>P(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,S?s.jsx(_m,{ref:Y,searchQuery:D,onFileSelect:se,onAgentSelect:G,onClose:()=>I(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,R?s.jsx(Vm,{ref:de,searchQuery:O,onSnippetSelect:pe,onClose:()=>B(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]})]}),Le=s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("label",{className:"inline-flex items-center gap-2",children:[s.jsx(ki,{checked:p.enabled,onChange:X=>C(L=>({...L,enabled:X})),ariaLabel:a("sessions.scheduledTasks.editor.enabled.aria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.enabled.label")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(!1),disabled:v,children:a("sessions.scheduledTasks.editor.actions.cancel")}),s.jsx(ze,{type:"button",size:"sm",onClick:z,disabled:v,children:a(v?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return y?s.jsx(Pa,{open:e,title:Ie,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:X=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:Ie}),X]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:_e})]}),footer:Le,children:Ve}):s.jsx(Cs,{open:e,onOpenChange:X=>{!X&&U()||r(X)},children:s.jsxs(ks,{"aria-describedby":Ne,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(qs,{id:Ne,className:"sr-only",children:_e}),s.jsx("header",{className:"shrink-0 px-4 sm:px-6 pt-5 pb-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-2xl",children:[s.jsx(Ps,{className:"typography-ui-label font-medium text-foreground",children:Ie}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:_e})]})}),s.jsx(Ia,{className:"flex-1 min-h-0 overflow-auto [scrollbar-gutter:stable_both-edges]",size:64,hideTopShadow:!0,children:s.jsx("div",{className:"mx-auto w-full max-w-2xl px-4 sm:px-6 pb-5",children:Ve})}),s.jsx("div",{className:"shrink-0 px-4 sm:px-6 py-3",children:s.jsx("div",{className:"mx-auto w-full max-w-2xl",children:Le})})]})})}function Wj(t){return so(t,{min:0,max:23})}function Uj(t,e){return so(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function Hj(t,e){const n=Number(t),r=Number(e),o=Number.isFinite(n)?Math.min(23,Math.max(0,n)):0,a=Number.isFinite(r)?Math.min(59,Math.max(0,r)):0;return`${String(o).padStart(2,"0")}:${String(a).padStart(2,"0")}`}function Gj(t){return s.jsx(vs,{value:t,children:t},t)}const Kj=t=>{const n=(Array.isArray(t.schedule.times)?t.schedule.times:t.schedule.time?[t.schedule.time]:[]).filter(r=>typeof r=="string"&&/^([01]\d|2[0-3]):([0-5]\d)$/.test(r));return Array.from(new Set(n)).sort((r,o)=>r.localeCompare(o))},qj=(t,e)=>{const n=Kj(t).join(", ")||"--:--",r=o=>e(o===0?"sessions.scheduledTasks.dialog.schedule.weekdayShort.sun":o===1?"sessions.scheduledTasks.dialog.schedule.weekdayShort.mon":o===2?"sessions.scheduledTasks.dialog.schedule.weekdayShort.tue":o===3?"sessions.scheduledTasks.dialog.schedule.weekdayShort.wed":o===4?"sessions.scheduledTasks.dialog.schedule.weekdayShort.thu":o===5?"sessions.scheduledTasks.dialog.schedule.weekdayShort.fri":o===6?"sessions.scheduledTasks.dialog.schedule.weekdayShort.sat":"sessions.scheduledTasks.dialog.schedule.weekdayShort.unknown");if(t.schedule.kind==="daily")return t.schedule.timezone?e("sessions.scheduledTasks.dialog.schedule.dailyWithTimezone",{time:n,timezone:t.schedule.timezone}):e("sessions.scheduledTasks.dialog.schedule.daily",{time:n});if(t.schedule.kind==="weekly"){const o=Array.isArray(t.schedule.weekdays)?t.schedule.weekdays.map(a=>r(a)).join(", "):"";return t.schedule.timezone?e("sessions.scheduledTasks.dialog.schedule.weeklyWithTimezone",{days:o,time:n,timezone:t.schedule.timezone}):e("sessions.scheduledTasks.dialog.schedule.weekly",{days:o,time:n})}if(t.schedule.kind==="once"){const o=typeof t.schedule.date=="string"&&t.schedule.date.trim().length>0?t.schedule.date:e("sessions.scheduledTasks.dialog.schedule.unknownDate"),a=typeof t.schedule.time=="string"&&t.schedule.time.trim().length>0?t.schedule.time:"--:--";return t.schedule.timezone?e("sessions.scheduledTasks.dialog.schedule.onceWithTimezone",{date:o,time:a,timezone:t.schedule.timezone}):e("sessions.scheduledTasks.dialog.schedule.once",{date:o,time:a})}return t.schedule.timezone?e("sessions.scheduledTasks.dialog.schedule.cronWithTimezone",{cron:t.schedule.cron||"",timezone:t.schedule.timezone}):e("sessions.scheduledTasks.dialog.schedule.cron",{cron:t.schedule.cron||""})},Yj=(t,e)=>!t||!Number.isFinite(t)?"":bm(t,e),Wu=(t,e)=>{if(!t||!Number.isFinite(t))return"";const n=t-Date.now(),r=Math.abs(n),o=6e4,a=60*o,c=24*a,l=n>=0;if(r<o)return e(l?"sessions.scheduledTasks.dialog.relativeTime.inLessThanOneMinute":"sessions.scheduledTasks.dialog.relativeTime.justNow");if(r<a){const u=Math.round(r/o);return l?e("sessions.scheduledTasks.dialog.relativeTime.inMinutes",{count:u}):e("sessions.scheduledTasks.dialog.relativeTime.minutesAgo",{count:u})}if(r<c){const u=Math.floor(r/a),g=Math.round(r%a/o),b=g>0?`${u}h ${g}m`:`${u}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:b}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:b})}const d=Math.floor(r/c),m=Math.round(r%c/a),f=m>0?`${d}d ${m}h`:`${d}d`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:f}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:f})},Jj={success:{tone:"success",Icon:"checkbox-circle"},error:{tone:"error",Icon:"error-warning"},running:{tone:"warning",Icon:"loader-4",spin:!0},idle:{tone:"muted",Icon:"pulse"}},Qj=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function Xj(){const{t}=jt(),e=Me(R=>R.isScheduledTasksDialogOpen),n=Me(R=>R.setScheduledTasksDialogOpen),r=Me(R=>R.isMobile),o=Me(R=>R.timeFormatPreference),a=ds(R=>R.projects),c=ds(R=>R.getActiveProject()),l=Bs(R=>R.homeDirectory),{currentTheme:d}=Lr(),[m,f]=Qe.useState(""),[u,g]=Qe.useState([]),[b,h]=Qe.useState(!0),[x,y]=Qe.useState(!1),[p,C]=Qe.useState(null),[v,k]=Qe.useState(null),w=Qe.useMemo(()=>a.find(R=>R.id===m)||null,[a,m]),A=Qe.useCallback(R=>{const B=R.label?.trim()||Ci(R.path,l||void 0),O=R.icon?gc[R.icon]:null,F=R.color?Fa[R.color]:void 0,_=O?s.jsx(T,{name:O,className:"h-3.5 w-3.5 shrink-0",style:F?{color:F}:void 0}):s.jsx(T,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:F?{color:F}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[R.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:R.iconBackground?{backgroundColor:R.iconBackground}:void 0,children:s.jsx(La,{project:{id:R.id,iconImage:R.iconImage??null},options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:_})}):_,s.jsx("span",{className:"truncate",children:B})]})},[l,d.metadata.variant,d.colors.surface.foreground]),S=Qe.useCallback(async(R,B)=>{if(!R){g([]);return}B?.silent||h(!0);try{const O=await Nj(R);O.sort((F,_)=>{if(F.enabled!==_.enabled)return F.enabled?-1:1;const ie=F.name.localeCompare(_.name);return ie!==0?ie:(F.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(_.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),g(O)}catch(O){me.error(O instanceof Error?O.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),B?.silent||g([])}finally{B?.silent||h(!1)}},[t]);Qe.useEffect(()=>{if(!e)return;const R=c?.id||a[0]?.id||"";f(R),R?S(R):(g([]),h(!1))},[e,c,a,S]),Qe.useEffect(()=>{if(!e)return;let R=null;const B=$f(O=>{O.type==="scheduled-task-ran"&&O.projectId===m&&(R&&clearTimeout(R),R=setTimeout(()=>{S(m,{silent:!0})},400))});return()=>{R&&clearTimeout(R),B()}},[e,m,S]);const I=Qe.useCallback(async R=>{if(!m)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await Eu(m,R),await S(m),me.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[m,S,t]),D=Qe.useCallback(async(R,B)=>{if(m){k(R.id),g(O=>O.map(F=>F.id===R.id?{...F,enabled:B}:F));try{await Eu(m,{...R,enabled:B}),await S(m,{silent:!0})}catch(O){me.error(O instanceof Error?O.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await S(m,{silent:!0})}finally{k(null)}}},[m,S,t]),N=Qe.useCallback(async R=>{if(!(!m||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:R.name})))){k(R.id);try{await kj(m,R.id),await S(m,{silent:!0}),me.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(O){me.error(O instanceof Error?O.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{k(null)}}},[m,S,t]),M=Qe.useCallback(async R=>{if(m){k(R.id);try{await Cj(m,R.id),await Promise.all([S(m,{silent:!0}),ha()]),me.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch(B){me.error(B instanceof Error?B.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{k(null)}}},[m,S,t]),P=s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("sessions.scheduledTasks.dialog.project.label")}),s.jsxs(Dn,{value:m||"__none",onValueChange:R=>{const B=R==="__none"?"":R;f(B),B?S(B):g([])},children:[s.jsx(Tn,{className:r?"w-full":void 0,children:w?s.jsx(fn,{children:A(w)}):s.jsx(fn,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(Pn,{children:[a.length===0?s.jsx(vs,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(R=>s.jsx(vs,{value:R.id,children:A(R)},R.id))]})]})]}),E=()=>{C(null),y(!0)},V=s.jsxs("div",{className:"space-y-4",children:[r?P:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[P,s.jsxs(ze,{onClick:E,disabled:!m,children:[s.jsx(T,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:b?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(T,{name:"loader-4",className:"h-4 w-4 animate-spin"})," ",t("sessions.scheduledTasks.dialog.loading")]}):u.length===0?s.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 typography-meta text-muted-foreground",children:t(m?"sessions.scheduledTasks.dialog.empty.noTasks":"sessions.scheduledTasks.dialog.empty.selectProject")}):s.jsx("div",{className:"space-y-2.5",children:u.map(R=>{const B=v===R.id,O=R.state?.lastStatus||"idle",F=Jj[O],_=t(O==="success"?"sessions.scheduledTasks.dialog.status.success":O==="error"?"sessions.scheduledTasks.dialog.status.error":O==="running"?"sessions.scheduledTasks.dialog.status.running":"sessions.scheduledTasks.dialog.status.idle"),ie=R.state?.nextRunAt,oe=R.state?.lastRunAt;return s.jsxs("div",{className:Te("rounded-lg border border-border p-4 transition-opacity",!R.enabled&&"opacity-60"),children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-header truncate font-semibold text-foreground",children:R.name}),s.jsx("div",{className:"typography-micro truncate text-muted-foreground",children:qj(R,t)})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-5 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(T,{name:"timer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.nextRun.label")}),ie?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-foreground",children:Wu(ie,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:Yj(ie,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(T,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),O==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(T,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):oe?s.jsxs(s.Fragment,{children:[F.tone!=="muted"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:`var(--status-${F.tone})`},children:[s.jsx(T,{name:F.Icon,className:"h-3.5 w-3.5"}),_]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:Wu(oe,t)})]}):s.jsx("span",{children:t("sessions.scheduledTasks.dialog.lastRun.never")})]})]}),R.state?.lastError?s.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-md border p-2 typography-micro",style:Qj("error"),children:[s.jsx(T,{name:"error-warning",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"min-w-0 break-words",children:R.state.lastError})]}):null,s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("label",{className:Te("inline-flex cursor-pointer items-center gap-2 typography-micro font-medium",R.enabled?"text-foreground":"text-muted-foreground",B&&"cursor-not-allowed opacity-50"),children:[s.jsx(ki,{checked:R.enabled,onChange:ne=>{D(R,ne)},ariaLabel:R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:R.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:R.name}),disabled:B}),R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.enabled"):t("sessions.scheduledTasks.dialog.taskToggle.paused")]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsxs(ze,{variant:"outline",size:"sm",onClick:()=>{M(R)},disabled:B,children:[s.jsx(T,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs(ze,{variant:"outline",size:"sm",onClick:()=>{C(R),y(!0)},disabled:B,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:R.name}),children:[s.jsx(T,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx(ze,{variant:"destructive",size:"sm",onClick:()=>{N(R)},disabled:B,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:R.name}),children:s.jsx(T,{name:"delete-bin",className:"h-4 w-4"})})]})]})]},R.id)})})})]});return s.jsxs(s.Fragment,{children:[r?s.jsx(Pa,{open:e,title:t("sessions.scheduledTasks.dialog.title"),onClose:()=>n(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:R=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t("sessions.scheduledTasks.dialog.title")}),R]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:t("sessions.scheduledTasks.dialog.description")})]}),footer:s.jsxs(ze,{className:"w-full",onClick:E,disabled:!m,children:[s.jsx(T,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:V}):s.jsx(Cs,{open:e,onOpenChange:n,children:s.jsxs(ks,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(Ms,{children:[s.jsx(Ps,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(qs,{children:t("sessions.scheduledTasks.dialog.description")})]}),V]})}),s.jsx(zj,{open:x,task:p,onOpenChange:y,onSave:I})]})}const Zj=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>Gt(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(d=>Co(d,t.normalizedPath,r)))(e.archivedSessions),c=e.sessions.filter(l=>l.time?.archived||Gt(l.directory??null)?!1:Co(l,t.normalizedPath,r));return Qi([...a,...c])},eS=t=>{const e=ht.c(12),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,isSessionsLoading:l,foldersMap:d,createFolder:m,addSessionToFolder:f,cleanupSessions:u}=t;let g,b;e[0]!==f||e[1]!==o||e[2]!==a||e[3]!==u||e[4]!==m||e[5]!==d||e[6]!==l||e[7]!==c||e[8]!==n||e[9]!==r?(g=()=>{l||n.forEach(h=>{const x=jc(h.normalizedPath),y=Zj(h,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c}),p=new Set(y.map(tS)),C=d[x]??[],v=new Map(C.map(sS));y.forEach(k=>{const w=Lx(k,h.normalizedPath),A=w.toLowerCase();let S=v.get(A);S||(S=m(x,w),v.set(A,S)),S.sessionIds.includes(k.id)||f(x,S.id,k.id)}),u(x,p)})},b=[n,r,o,a,c,l,d,m,f,u],e[0]=f,e[1]=o,e[2]=a,e[3]=u,e[4]=m,e[5]=d,e[6]=l,e[7]=c,e[8]=n,e[9]=r,e[10]=g,e[11]=b):(g=e[10],b=e[11]),i.useEffect(g,b)};function tS(t){return t.id}function sS(t){return[t.name.toLowerCase(),t]}const nS=t=>{const e=ht.c(41),{normalizedProjects:n,getSessionsForProject:r,getArchivedSessionsForProject:o,availableWorktreesByProject:a,projectRepoStatus:c,projectRootBranches:l,lastRepoStatus:d,buildGroupedSessions:m,hasSessionSearchQuery:f,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:g,buildGroupSearchText:b,foldersMap:h}=t;let x;if(e[0]!==a||e[1]!==m||e[2]!==o||e[3]!==r||e[4]!==d||e[5]!==n||e[6]!==c||e[7]!==l){let N;e[9]!==a||e[10]!==m||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(N=M=>{const P=Qi([...r(M),...o(M)]),E=a.get(M.normalizedPath)??[],V=c.has(M.id)?!!c.get(M.id):d,R=m(P,M.normalizedPath,E,l.get(M.id)??null,V);return{project:M,groups:R}},e[9]=a,e[10]=m,e[11]=o,e[12]=r,e[13]=d,e[14]=c,e[15]=l,e[16]=N):N=e[16],x=n.map(N),e[0]=a,e[1]=m,e[2]=o,e[3]=r,e[4]=d,e[5]=n,e[6]=c,e[7]=l,e[8]=x}else x=e[8];const y=x,p=y;let C;if(e[17]!==b||e[18]!==g||e[19]!==h||e[20]!==f||e[21]!==u||e[22]!==p){e:{const N=new WeakMap;if(!f){C=N;break e}const M=P=>P.reduce((E,V)=>E+1+M(V.children),0);p.forEach(P=>{P.groups.forEach(E=>{const V=g(E.sessions,u),R=M(V),B=b(E).includes(u),O=Gt(E.directory??null),_=(O?h[O]??[]:[]).filter(ie=>ie.name.toLowerCase().includes(u)).length;N.set(E,{filteredNodes:V,matchedSessionCount:R,folderNameMatchCount:_,groupMatches:B,hasMatch:B||R>0||_>0})})}),C=N}e[17]=b,e[18]=g,e[19]=h,e[20]=f,e[21]=u,e[22]=p,e[23]=C}else C=e[23];const v=C;let k;e:{if(!f){k=p;break e}let N;if(e[24]!==v||e[25]!==p){let M;e[27]!==v?(M=P=>({...P,groups:P.groups.filter(E=>v.get(E)?.hasMatch===!0)}),e[27]=v,e[28]=M):M=e[28],N=p.map(M).filter(rS),e[24]=v,e[25]=p,e[26]=N}else N=e[26];k=N}const w=k,A=f?w:p;let S;e:{if(!f){S=0;break e}let N;if(e[29]!==v||e[30]!==A){let M;e[32]!==v?(M=(P,E)=>P+E.groups.reduce((V,R)=>{const B=v.get(R);if(!B)return V;const O=B.folderNameMatchCount+(B.groupMatches?1:0);return V+B.matchedSessionCount+O},0),e[32]=v,e[33]=M):M=e[33],N=A.reduce(M,0),e[29]=v,e[30]=A,e[31]=N}else N=e[31];S=N}const I=S;let D;return e[34]!==v||e[35]!==y||e[36]!==I||e[37]!==w||e[38]!==A||e[39]!==p?(D={projectSections:y,visibleProjectSections:p,groupSearchDataByGroup:v,searchableProjectSections:w,sectionsForRender:A,searchMatchCount:I},e[34]=v,e[35]=y,e[36]=I,e[37]=w,e[38]=A,e[39]=p,e[40]=D):D=e[40],D};function rS(t){return t.groups.length>0}const iS=t=>{const e=ht.c(34),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:c,handleSessionSelect:l,newSessionDraftOpen:d,mobileVariant:m,openNewSessionDraft:f,setActiveMainTab:u,setSessionSwitcherOpen:g,sessions:b,worktreeMetadata:h}=t;let x,y;if(e[0]!==n){y=new Map,x=new Map;const M=(P,E,V,R)=>{y.has(P)||y.set(P,new Map);const B=y.get(P);R.forEach(O=>{const F=Gt(O.worktree?.path??O.session.directory??V??E);B.set(O.session.id,{directory:F}),x.has(P)||x.set(P,{id:O.session.id,directory:F}),O.children.length>0&&M(P,E,F,O.children)})};n.forEach(P=>{P.groups.forEach(E=>{M(P.project.id,P.project.normalizedPath,E.directory,E.sessions)})}),e[0]=n,e[1]=x,e[2]=y}else x=e[1],y=e[2];let p;e[3]!==x||e[4]!==y?(p={metaByProject:y,firstSessionByProject:x},e[3]=x,e[4]=y,e[5]=p):p=e[5];const C=p,v=i.useRef(null);let k,w;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==m||e[11]!==d||e[12]!==f||e[13]!==n||e[14]!==C||e[15]!==u||e[16]!==a||e[17]!==g?(k=()=>{if(!r||d||Me.getState().isNewWorktreeDialogOpen||v.current===r)return;const M=n.find(F=>F.project.id===r);if(!M)return;v.current=r;const P=C.metaByProject.get(r);if(c&&P&&P.has(c)){a(F=>{if(F.get(r)===c)return F;const _=new Map(F);return _.set(r,c),_});return}if(!P||P.size===0){u("chat"),m&&g(!1),f({directoryOverride:M.project.normalizedPath});return}const E=o.get(r),V=E&&P.has(E)?E:null,R=C.firstSessionByProject.get(r)?.id??null,B=V??R;if(!B||B===c)return;const O=P.get(B)?.directory??null;l(B,O,r)},w=[r,o,c,l,d,m,f,n,C,u,g,a],e[6]=r,e[7]=o,e[8]=c,e[9]=l,e[10]=m,e[11]=d,e[12]=f,e[13]=n,e[14]=C,e[15]=u,e[16]=a,e[17]=g,e[18]=k,e[19]=w):(k=e[18],w=e[19]),i.useLayoutEffect(k,w);let A,S;e[20]!==r||e[21]!==c||e[22]!==C||e[23]!==a?(A=()=>{if(!r||!c)return;const M=C.metaByProject.get(r);!M||!M.has(c)||a(P=>{if(P.get(r)===c)return P;const E=new Map(P);return E.set(r,c),E})},S=[r,c,C,a],e[20]=r,e[21]=c,e[22]=C,e[23]=a,e[24]=A,e[25]=S):(A=e[24],S=e[25]),i.useEffect(A,S);let I;if(e[26]!==c||e[27]!==b||e[28]!==h){e:{if(!c){I=null;break e}const M=h.get(c)?.path;if(M){I=Gt(M)??M;break e}let P;e[30]!==c?(P=V=>V.id===c,e[30]=c,e[31]=P):P=e[31];const E=b.find(P);if(!E){I=null;break e}I=Gt(E.directory??null)}e[26]=c,e[27]=b,e[28]=h,e[29]=I}else I=e[29];const D=I;let N;return e[32]!==D?(N={currentSessionDirectory:D},e[32]=D,e[33]=N):N=e[33],N},oS=t=>{const e=ht.c(4);let n;e[0]!==t?(n=(a,c)=>{const l=t.get(a);if(!l||l.length===0)return c;const d=new Map(c.map(aS)),m=[];return l.forEach(f=>{const u=d.get(f);u&&(m.push(u),d.delete(f))}),c.forEach(f=>{d.has(f.id)&&m.push(f)}),m},e[0]=t,e[1]=n):n=e[1];const r=n;let o;return e[2]!==r?(o={getOrderedGroups:r},e[2]=r,e[3]=o):o=e[3],o};function aS(t){return[t.id,t]}const Go=t=>!!t.time?.archived,lS=t=>{const{t:e}=jt(),n=i.useCallback(c=>[c.label,c.branch??"",c.description??"",c.directory??""].join(" ").toLowerCase(),[]),r=i.useCallback(c=>{const l=Gt(c.directory??null)??"";return`${(c.title||e("sessions.sidebar.session.untitled")).trim()} ${l}`.toLowerCase()},[e]),o=i.useCallback((c,l)=>l?c.flatMap(d=>{if(r(d.session).includes(l))return[d];const f=o(d.children,l);return f.length===0?[]:[{...d,children:f}]}):c,[r]),a=i.useCallback((c,l,d,m,f)=>{const u=Gt(l??null),g=Qi(c).sort((P,E)=>$i(P,E,t.pinnedSessionIds)),b=new Map(g.map(P=>[P.id,P])),h=new Map;g.forEach(P=>{const E=P.parentID;if(!E)return;const V=b.get(E);if(!V||Go(V)!==Go(P))return;const R=h.get(E)??[];R.push(P),h.set(E,R)}),h.forEach(P=>P.sort((E,V)=>$i(E,V,t.pinnedSessionIds)));const x=new Map;d.forEach(P=>{if(P.path){const E=Gt(P.path)??P.path;x.set(E,P)}});const y=P=>{const E=Gt(P.directory??null),V=t.worktreeMetadata.get(P.id)??null;if(V)return V;if(E){const R=x.get(E)??null;if(R&&E!==u)return R}return null},p=P=>{const E=h.get(P.id)??[];return{session:P,children:E.map(V=>p(V)),worktree:y(P)}},C=g.filter(P=>{const E=P.parentID;if(!E)return!0;const V=b.get(E);return V?Go(V)!==Go(P):!0}),v=new Map,k="__archived__",w=P=>{if(P.time?.archived)return k;if(t.isVSCode)return u??"__project_root__";const V=Gt(t.worktreeMetadata.get(P.id)?.path??null)??kr(P);return V?V!==u&&x.has(V)?V:V===u?u??"__project_root__":k:k};C.forEach(P=>{const E=p(P),V=w(P);v.has(V)||v.set(V,[]),v.get(V)?.push(E)});const A=u??"__project_root__",S=[{id:"root",label:f&&m&&m!=="HEAD"?e("sessions.sidebar.grouping.projectRootWithBranch",{branch:m}):e("sessions.sidebar.grouping.projectRoot"),branch:m??null,description:u?pa(u,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:u,folderScopeKey:u,sessions:v.get(A)??[]}],I=new Map;d.forEach(P=>{const E=Gt(P.path)??P.path,V=v.get(E)??[],R=V.length>0,B=V.reduce((O,F)=>{const _=Number(F.session.time?.updated??F.session.time?.created??0);return Number.isFinite(_)?Math.max(O,_):O},0);I.set(E,{hasActiveSession:R,lastUpdatedAt:B})});const D=[...d].sort((P,E)=>{const V=Gt(P.path)??P.path,R=Gt(E.path)??E.path,B=I.get(V)??{hasActiveSession:!1,lastUpdatedAt:0},O=I.get(R)??{hasActiveSession:!1,lastUpdatedAt:0};if(B.hasActiveSession!==O.hasActiveSession)return B.hasActiveSession?-1:1;if(B.hasActiveSession&&O.hasActiveSession)return O.lastUpdatedAt-B.lastUpdatedAt;const F=(P.label||P.branch||P.name||P.path||"").toLowerCase(),_=(E.label||E.branch||E.name||E.path||"").toLowerCase();return F.localeCompare(_)});(t.isVSCode?[]:D).forEach(P=>{const E=Gt(P.path)??P.path,V=t.gitBranches.get(E)?.trim()||null,R=P.branch?.trim()||null,O=!!(V&&R&&P.label&&Pd(P.label)===Pd(R))?V:P.label||P.name||Ci(E,t.homeDirectory)||E;S.push({id:`worktree:${E}`,label:O,branch:V||R,description:pa(E,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:P,directory:E,folderScopeKey:E,sessions:v.get(E)??[]})});const M=v.get(k)??[];return M.length>0&&S.push({id:"archived",label:e("sessions.sidebar.grouping.archived"),branch:null,description:e("sessions.sidebar.grouping.archivedDescription"),isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:!t.isVSCode&&u?jc(u):null,sessions:M}),S},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitBranches,t.isVSCode,e]);return{buildGroupSearchText:n,buildSessionSearchText:r,filterSessionNodesForSearch:o,buildGroupedSessions:a}},cS=t=>{const e=ht.c(9),{isSessionSearchOpen:n,setIsSessionSearchOpen:r,sessionSearchInputRef:o,sessionSearchContainerRef:a}=t;let c,l;e[0]!==n||e[1]!==o?(c=()=>{if(!n||typeof window>"u")return;const f=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(f)},l=[n,o],e[0]=n,e[1]=o,e[2]=c,e[3]=l):(c=e[2],l=e[3]),i.useEffect(c,l);let d,m;e[4]!==n||e[5]!==a||e[6]!==r?(d=()=>{if(!n||typeof document>"u")return;const f=u=>{a.current&&(a.current.contains(u.target)||r(!1))};return document.addEventListener("mousedown",f),()=>document.removeEventListener("mousedown",f)},m=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=d,e[8]=m):(d=e[7],m=e[8]),i.useEffect(d,m)},dS=t=>{const e=ht.c(42),{t:n}=jt(),[r,o]=i.useState(null),a=i.useRef(null);let c,l;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=()=>()=>{a.current&&clearTimeout(a.current)},l=[],e[0]=c,e[1]=l):(c=e[0],l=e[1]),i.useEffect(c,l);let d;e[2]!==t?(d=(B,O,F)=>{const _=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(F&&F!==t.activeProjectId&&t.setActiveProjectIdOnly(F),O&&O!==t.currentDirectory&&t.setDirectory(O,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),B===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(B),_();return}t.setCurrentSession(B,O??null),t.onSessionSelected?.(B),_()},e[2]=t,e[3]=d):d=e[3];const m=d;let f;e[4]!==t?(f=(B,O)=>{t.setEditingId(B),t.setEditTitle(O)},e[4]=t,e[5]=f):f=e[5];const u=f;let g;e[6]!==t?(g=async()=>{if(!t.editingId)return;const B=t.editTitle.trim();B&&await t.updateSessionTitle(t.editingId,B),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=g):g=e[7];const b=g;let h;e[8]!==t?(h=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=h):h=e[9];const x=h;let y;e[10]!==t||e[11]!==n?(y=async B=>{const O=await t.shareSession(B.id);O&&O.share?.url?me.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):me.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=y):y=e[12];const p=y;let C;e[13]!==n?(C=(B,O)=>{tr(B).then(F=>{if(!F.ok){me.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(O),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{me.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=C):C=e[14];const v=C;let k;e[15]!==t||e[16]!==n?(k=async B=>{await t.unshareSession(B)?me.success(n("sessions.sidebar.session.unshare.success")):me.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=k):k=e[17];const w=k;let A;e[18]!==t.childrenMap?(A=B=>{const O=[],F=_=>{(t.childrenMap.get(_)??[]).forEach(oe=>{O.push(oe),F(oe.id)})};return F(B),O},e[18]=t.childrenMap,e[19]=A):A=e[19];const S=A,I=mS;let D;e[20]!==t||e[21]!==S||e[22]!==n?(D=async(B,O,F)=>{const _=O?.archivedBucket===!0||O?.hardDelete===!0,ie=F?.descendantIds??I(S(B.id),_).map(fS);if(ie.length===0){(_?await t.deleteSession(B.id):await t.archiveSession(B.id))?me.success(n(_?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):me.error(n(_?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const oe=[B.id,...ie];if(_){if(await t.deleteSession(B.id)){const de=ie.length+1;me.success(de===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:de}):n("sessions.sidebar.bulkActions.deletedPlural",{count:de}))}else me.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:ne,failedIds:Y}=await t.archiveSessions(oe);ne.length>0&&me.success(ne.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:ne.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:ne.length})),Y.length>0&&me.error(Y.length===1?n("sessions.sidebar.bulkActions.failedArchiveSingle",{count:Y.length}):n("sessions.sidebar.bulkActions.failedArchivePlural",{count:Y.length}))},e[20]=t,e[21]=S,e[22]=n,e[23]=D):D=e[23];const N=D;let M;e[24]!==t||e[25]!==S||e[26]!==N?(M=(B,O)=>{const F=O?.archivedBucket===!0||O?.hardDelete===!0,_=I(S(B.id),F).map(hS);if(!t.showDeletionDialog){N(B,O,{descendantIds:_});return}t.setDeleteSessionConfirm({session:B,descendantCount:_.length,descendantIds:_,archivedBucket:F})},e[24]=t,e[25]=S,e[26]=N,e[27]=M):M=e[27];const P=M;let E;e[28]!==t||e[29]!==N?(E=async()=>{if(!t.deleteSessionConfirm)return;const{session:B,archivedBucket:O,descendantIds:F}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await N(B,{archivedBucket:O},{descendantIds:F})},e[28]=t,e[29]=N,e[30]=E):E=e[30];const V=E;let R;return e[31]!==V||e[32]!==r||e[33]!==x||e[34]!==v||e[35]!==P||e[36]!==b||e[37]!==u||e[38]!==m||e[39]!==p||e[40]!==w?(R={copiedSessionId:r,handleSessionSelect:m,handleSessionDoubleClick:u,handleSaveEdit:b,handleCancelEdit:x,handleShareSession:p,handleCopyShareUrl:v,handleUnshareSession:w,handleDeleteSession:P,confirmDeleteSession:V},e[31]=V,e[32]=r,e[33]=x,e[34]=v,e[35]=P,e[36]=b,e[37]=u,e[38]=m,e[39]=p,e[40]=w,e[41]=R):R=e[41],R};function uS(t){return!t.time?.archived}function mS(t,e){return e?t:t.filter(uS)}function fS(t){return t.id}function hS(t){return t.id}const pS=["project:active:","project:archived:","recent:active:","recent:archived:"],gS=t=>{const{isVSCode:e,hasLoadedGlobalSessions:n,safeStorage:r,keys:o,sessions:a,setPinnedSessionIds:c,groupOrderByProject:l,activeSessionByProject:d,collapsedGroups:m,setExpandedParents:f,setCollapsedProjects:u}=t,g=i.useRef(null),b=i.useRef(null),h=i.useCallback(()=>{if(e)return;const y=b.current;if(b.current=null,g.current=null,!y)return;const{projects:p}=ds.getState(),C=p.map(v=>({...v,sidebarCollapsed:y.has(v.id)}));ec({projects:C}).catch(()=>{})},[e]),x=i.useCallback(y=>{typeof window>"u"||e||(b.current=y,g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{h()},700))},[e,h]);return i.useEffect(()=>()=>{typeof window<"u"&&g.current!==null&&window.clearTimeout(g.current),g.current=null,b.current=null},[]),i.useEffect(()=>{try{const y=r.getItem(o.sessionExpanded);if(y){const C=JSON.parse(y);Array.isArray(C)&&f(new Set(C.filter(v=>typeof v=="string")))}else{const C=r.getItem(o.sessionExpandedLegacy);if(C){try{const v=JSON.parse(C);if(Array.isArray(v)){const k=new Set;if(v.forEach(w=>{typeof w!="string"||w.length===0||pS.forEach(A=>k.add(`${A}${w}`))}),k.size>0){f(k);try{r.setItem(o.sessionExpanded,JSON.stringify(Array.from(k)))}catch{}}}}catch{}try{r.removeItem?.(o.sessionExpandedLegacy)}catch{}}}const p=r.getItem(o.projectCollapse);if(p){const C=JSON.parse(p);Array.isArray(C)&&u(new Set(C.filter(v=>typeof v=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,u,f]),i.useEffect(()=>{if(!n)return;const y=new Set(a.map(p=>p.id));c(p=>{let C=!1;const v=new Set;return p.forEach(k=>{y.has(k)?v.add(k):C=!0}),C?v:p})},[n,a,c]),i.useEffect(()=>{try{const y=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(y))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const y=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(y))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(m)))}catch{}},[m,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:x}},xS=t=>{const e=ht.c(26),{normalizedProjects:n,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=t,{git:c}=_n(),l=an(bS);let d,m;e[0]!==l||e[1]!==c||e[2]!==n||e[3]!==o?(d=()=>{if(!c||n.length===0){o(new Map);return}n.forEach(C=>{l(C.normalizedPath,c)})},m=[n,c,l,o],e[0]=l,e[1]=c,e[2]=n,e[3]=o,e[4]=d,e[5]=m):(d=e[4],m=e[5]),i.useEffect(d,m);let f,u;e[6]!==r||e[7]!==n||e[8]!==o?(f=()=>{const C=new Map;n.forEach(v=>{C.set(v.id,r.get(v.normalizedPath)?.isGitRepo??null)}),o(C)},u=[n,r,o],e[6]=r,e[7]=n,e[8]=o,e[9]=f,e[10]=u):(f=e[9],u=e[10]),i.useEffect(f,u);let g;if(e[11]!==r||e[12]!==n){let C;e[14]!==r?(C=v=>{const k=r.get(v.normalizedPath)?.branch??"";return`${v.id}:${k}`},e[14]=r,e[15]=C):C=e[15],g=n.map(C).join("|"),e[11]=r,e[12]=n,e[13]=g}else g=e[13];const b=g;let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=new Map,e[16]=h):h=e[16];const x=i.useRef(h);let y;e[17]!==r||e[18]!==n||e[19]!==a?(y=()=>{let C=!1;const v=setTimeout(()=>{(async()=>{const w=new Set(n.map(yS));for(const D of x.current.keys())w.has(D)||x.current.delete(D);const A=n.filter(D=>{const N=r.get(D.normalizedPath);if(N?.isGitRepo===!1)return x.current.delete(D.id),!1;if(N?.isGitRepo!==!0||N.branch===null)return!1;const M=N.branch.trim(),P=`${D.normalizedPath}\0${M}`,E=x.current.get(D.id);return E===void 0||E!==P});if(A.length===0)return;const S=await ff(A,2,async D=>{const N=r.get(D.normalizedPath)?.branch?.trim()??"",M=`${D.normalizedPath}\0${N}`,P=await Ea(D.normalizedPath,N?{knownBranch:N}:void 0).catch(wS);return{id:D.id,inputKey:M,branch:P}});if(C)return;const I=S.filter(vS);I.length!==0&&(a(D=>{const N=new Map(D);return I.forEach(M=>{const{id:P,branch:E}=M;E&&N.set(P,E)}),N}),I.forEach(D=>{const{id:N,inputKey:M}=D;x.current.set(N,M)}))})()},150);return()=>{C=!0,clearTimeout(v)}},e[17]=r,e[18]=n,e[19]=a,e[20]=y):y=e[20];let p;e[21]!==r||e[22]!==n||e[23]!==b||e[24]!==a?(p=[n,b,r,a],e[21]=r,e[22]=n,e[23]=b,e[24]=a,e[25]=p):p=e[25],i.useEffect(y,p)};function bS(t){return t.ensureStatus}function yS(t){return t.id}function wS(){return null}function vS(t){return t.branch}const jS=t=>{const e=ht.c(14),{isVSCode:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a}=t;let c;e[0]!==r?(c=new Map,r.forEach(b=>{const h=kr(b);if(!h)return;const x=c.get(h)??[];x.push(b),c.set(h,x)}),e[0]=r,e[1]=c):c=e[1];const l=c;let d;e[2]!==a||e[3]!==n||e[4]!==l?(d=b=>{const h=n?[]:a.get(b.normalizedPath)??[],x=[b.normalizedPath,...h.map(SS).filter(NS)],y=new Set,p=[];return x.forEach(C=>{(l.get(C)??[]).forEach(k=>{y.has(k.id)||(y.add(k.id),p.push(k))})}),p},e[2]=a,e[3]=n,e[4]=l,e[5]=d):d=e[5];const m=d;let f;e[6]!==o||e[7]!==a||e[8]!==n||e[9]!==r?(f=b=>{if(n){const v=o.filter(w=>{const A=Gt(w.directory??null),S=Gt(w.project?.worktree??null);return A?A===b.normalizedPath:S===b.normalizedPath}),k=r.filter(w=>w.time?.archived||Gt(w.directory??null)?!1:Gt(w.project?.worktree??null)===b.normalizedPath);return Qi([...v,...k])}const h=n?[]:a.get(b.normalizedPath)??[],x=new Set([b.normalizedPath,...h.map(kS).filter(CS)]),p=(v=>v.filter(k=>Co(k,b.normalizedPath,x)))(o),C=r.filter(v=>{if(v.time?.archived||Gt(v.directory??null))return!1;const w=Gt(v.project?.worktree??null);return w?w===b.normalizedPath||w.startsWith(`${b.normalizedPath}/`):!1});return Qi([...p,...C])},e[6]=o,e[7]=a,e[8]=n,e[9]=r,e[10]=f):f=e[10];const u=f;let g;return e[11]!==u||e[12]!==m?(g={getSessionsForProject:m,getArchivedSessionsForProject:u},e[11]=u,e[12]=m,e[13]=g):g=e[13],g};function SS(t){return Gt(t.path)??t.path}function NS(t){return!!t}function kS(t){return Gt(t.path)??t.path}function CS(t){return!!t}const AS=t=>{const e=ht.c(10),{isSessionsLoading:n,hasLoadedGlobalSessions:r,sessions:o,archivedSessions:a,normalizedProjects:c,isVSCode:l,availableWorktreesByProject:d,cleanupSessions:m}=t;let f,u;e[0]!==a||e[1]!==d||e[2]!==m||e[3]!==r||e[4]!==n||e[5]!==l||e[6]!==c||e[7]!==o?(f=()=>{if(n||!r)return;const g=new Map;o.forEach(x=>{const y=Gt(x.directory??null);if(!y)return;const p=g.get(y);if(p){p.add(x.id);return}g.set(y,new Set([x.id]))}),c.forEach(x=>{const y=jc(x.normalizedPath),p=l?[]:d.get(x.normalizedPath)??[],C=new Set([x.normalizedPath,...p.map(DS).filter(TS)]),v=Qi([...a,...o.filter(k=>k.time?.archived||Gt(k.directory??null)?!1:Co(k,x.normalizedPath,C))]).filter(k=>Co(k,x.normalizedPath,C));g.set(y,new Set(v.map(PS)))});const b=Nn.getState().foldersMap;new Set([...Object.keys(b),...g.keys()]).forEach(x=>{m(x,g.get(x)??new Set)})},u=[a,d,m,r,n,l,c,o],e[0]=a,e[1]=d,e[2]=m,e[3]=r,e[4]=n,e[5]=l,e[6]=c,e[7]=o,e[8]=f,e[9]=u):(f=e[8],u=e[9]),i.useEffect(f,u)};function DS(t){return Gt(t.path)??t.path}function TS(t){return!!t}function PS(t){return t.id}const IS=t=>{const e=ht.c(8),{isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=t;let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=new Set,e[0]=a):a=e[0];const[c,l]=i.useState(a);let d;e[1]!==n||e[2]!==o?(d=()=>{if(!n)return;const f=new IntersectionObserver(u=>{u.forEach(g=>{const b=g.target.dataset.projectId;b&&l(h=>{const x=new Set(h);return g.isIntersecting?x.delete(b):x.add(b),x})})},{threshold:0});return o.current.forEach(u=>{u&&f.observe(u)}),()=>f.disconnect()},e[1]=n,e[2]=o,e[3]=d):d=e[3];let m;return e[4]!==n||e[5]!==o||e[6]!==r?(m=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=m):m=e[7],i.useEffect(d,m),c},RS=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,wl=t=>{if(!t)return null;const e=t.trim();return e&&RS.test(e)?e.toLowerCase():null},ES=t=>{const e=ht.c(198),{open:n,onOpenChange:r,projectId:o,projectName:a,projectPath:c,initialIcon:l,initialColor:d,initialIconBackground:m,onSave:f}=t,u=l===void 0?null:l,g=d===void 0?null:d,b=m===void 0?null:m,{t:h}=jt(),x=ds(MS),y=ds(FS),p=ds(LS);let C;e[0]!==o?(C=gt=>gt.projects.find(qt=>qt.id===o)?.iconImage??null,e[0]=o,e[1]=C):C=e[1];const v=ds(C),{currentTheme:k}=Lr(),[w,A]=i.useState(a),[S,I]=i.useState(u),[D,N]=i.useState(g);let M;e[2]!==b?(M=wl(b),e[2]=b,e[3]=M):M=e[3];const[P,E]=i.useState(M),[V,R]=i.useState(!1),[B,O]=i.useState(!1),[F,_]=i.useState(!1),[ie,oe]=i.useState(!1),[ne,Y]=i.useState(null),[te,de]=i.useState(null),[be,ke]=i.useState(!1),ae=i.useRef(null);let ve;e[4]===Symbol.for("react.memo_cache_sentinel")?(ve=()=>{Y(null),de(OS)},e[4]=ve):ve=e[4];const J=ve;let H,q;e[5]!==g||e[6]!==u||e[7]!==b||e[8]!==n||e[9]!==a?(H=()=>{n&&(A(a),I(u),N(g),E(wl(b)),oe(!1),J(),ke(!1))},q=[n,a,u,g,b,J],e[5]=g,e[6]=u,e[7]=b,e[8]=n,e[9]=a,e[10]=H,e[11]=q):(H=e[10],q=e[11]),i.useEffect(H,q);let ce,fe;e[12]===Symbol.for("react.memo_cache_sentinel")?(fe=()=>()=>{J()},ce=[J],e[12]=ce,e[13]=fe):(ce=e[12],fe=e[13]),i.useEffect(fe,ce);let De,Re,Fe;if(e[14]!==D||e[15]!==v||e[16]!==S||e[17]!==P||e[18]!==w||e[19]!==r||e[20]!==f||e[21]!==ie||e[22]!==ne||e[23]!==o||e[24]!==y||e[25]!==h||e[26]!==x){let gt;e[30]!==D||e[31]!==S||e[32]!==P||e[33]!==w||e[34]!==r||e[35]!==f||e[36]!==ie||e[37]!==ne||e[38]!==o||e[39]!==y||e[40]!==h||e[41]!==x?(gt=async()=>{const qt=w.trim();if(!qt)return;if(ne){R(!0);const os=await x(o,ne);if(R(!1),!os.ok){me.error(os.error||h("projectEditDialog.toast.failedToUploadIcon"));return}me.success(h("projectEditDialog.toast.iconUpdated")),J(),oe(!1)}const hs=ie&&Fe;if(hs){O(!0);const os=await y(o);if(O(!1),!os.ok){me.error(os.error||h("projectEditDialog.toast.failedToRemoveIcon"));return}me.success(h("projectEditDialog.toast.iconRemoved")),oe(!1),E(null)}f({label:qt,icon:S,color:D,iconBackground:wl(hs?null:P)}),r(!1)},e[30]=D,e[31]=S,e[32]=P,e[33]=w,e[34]=r,e[35]=f,e[36]=ie,e[37]=ne,e[38]=o,e[39]=y,e[40]=h,e[41]=x,e[42]=gt):gt=e[42],Re=gt,De=D?Fa[D]??null:null,Fe=!!v,e[14]=D,e[15]=v,e[16]=S,e[17]=P,e[18]=w,e[19]=r,e[20]=f,e[21]=ie,e[22]=ne,e[23]=o,e[24]=y,e[25]=h,e[26]=x,e[27]=De,e[28]=Re,e[29]=Fe}else De=e[27],Re=e[28],Fe=e[29];const Oe=!!(ne&&te),Ee=v?.source==="custom",we=Fe&&!ie||Oe,Pe=we,ue=!be&&(Oe||Fe&&!ie);let K;e[43]===Symbol.for("react.memo_cache_sentinel")?(K=()=>{ke(!1)},e[43]=K):K=e[43];const he=v?.updatedAt;let se;e[44]!==o||e[45]!==he?(se=[o,he],e[44]=o,e[45]=he,e[46]=se):se=e[46],i.useEffect(K,se);let G;e[47]!==V||e[48]!==o?(G=gt=>{!o||!gt||V||(oe(!1),ke(!1),Y(gt),de(qt=>(qt&&URL.revokeObjectURL(qt),URL.createObjectURL(gt))))},e[47]=V,e[48]=o,e[49]=G):G=e[49];const $=G;let pe;e[50]!==Oe||e[51]!==Pe||e[52]!==Fe||e[53]!==B||e[54]!==o?(pe=()=>{!o||!Pe||B||(Oe&&J(),oe(!!Fe),ke(!1))},e[50]=Oe,e[51]=Pe,e[52]=Fe,e[53]=B,e[54]=o,e[55]=pe):pe=e[55];const ye=pe;let z;e[56]!==p||e[57]!==F||e[58]!==o||e[59]!==h?(z=async()=>{!o||F||(J(),oe(!1),ke(!1),_(!0),p(o).then(gt=>{if(!gt.ok){me.error(gt.error||h("projectEditDialog.toast.failedToDiscoverIcon"));return}if(gt.skipped){me.success(h("projectEditDialog.toast.customIconAlreadySet"));return}me.success(h("projectEditDialog.toast.iconDiscovered"))}).finally(()=>{_(!1)}))},e[56]=p,e[57]=F,e[58]=o,e[59]=h,e[60]=z):z=e[60];const Ne=z;let U;e[61]!==h?(U=h("projectEditDialog.title"),e[61]=h,e[62]=U):U=e[62];let Ie;e[63]!==U?(Ie=s.jsx(Ms,{className:"min-w-0",children:s.jsx(Ps,{children:U})}),e[63]=U,e[64]=Ie):Ie=e[64];let _e;e[65]!==h?(_e=h("projectEditDialog.field.name"),e[65]=h,e[66]=_e):_e=e[66];let Ve;e[67]!==_e?(Ve=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:_e}),e[67]=_e,e[68]=Ve):Ve=e[68];let Le;e[69]===Symbol.for("react.memo_cache_sentinel")?(Le=gt=>A(gt.target.value),e[69]=Le):Le=e[69];let X;e[70]!==h?(X=h("projectEditDialog.field.namePlaceholder"),e[70]=h,e[71]=X):X=e[71];let L;e[72]!==Re?(L=gt=>{gt.key==="Enter"&&(gt.preventDefault(),Re())},e[72]=Re,e[73]=L):L=e[73];let xe;e[74]!==w||e[75]!==X||e[76]!==L?(xe=s.jsx(ln,{value:w,onChange:Le,placeholder:X,onKeyDown:L,autoFocus:!0}),e[74]=w,e[75]=X,e[76]=L,e[77]=xe):xe=e[77];let Q;e[78]!==c?(Q=s.jsx("p",{className:"typography-meta text-muted-foreground truncate",title:c,children:c}),e[78]=c,e[79]=Q):Q=e[79];let $e;e[80]!==Ve||e[81]!==xe||e[82]!==Q?($e=s.jsxs("div",{className:"min-w-0 space-y-1.5",children:[Ve,xe,Q]}),e[80]=Ve,e[81]=xe,e[82]=Q,e[83]=$e):$e=e[83];let He;e[84]!==h?(He=h("projectEditDialog.field.color"),e[84]=h,e[85]=He):He=e[85];let Ke;e[86]!==He?(Ke=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:He}),e[86]=He,e[87]=Ke):Ke=e[87];let qe;e[88]===Symbol.for("react.memo_cache_sentinel")?(qe=()=>N(null),e[88]=qe):qe=e[88];const Xe=D===null?"border-foreground scale-110":"border-border hover:border-border/80";let lt;e[89]!==Xe?(lt=Te("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",Xe),e[89]=Xe,e[90]=lt):lt=e[90];let bt;e[91]!==h?(bt=h("projectEditDialog.option.none"),e[91]=h,e[92]=bt):bt=e[92];let Be;e[93]===Symbol.for("react.memo_cache_sentinel")?(Be=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[93]=Be):Be=e[93];let Je;e[94]!==lt||e[95]!==bt?(Je=s.jsx("button",{type:"button",onClick:qe,className:lt,title:bt,children:Be}),e[94]=lt,e[95]=bt,e[96]=Je):Je=e[96];let Ze;e[97]!==D?(Ze=eg.map(gt=>s.jsx("button",{type:"button",onClick:()=>N(gt.key),className:Te("w-8 h-8 rounded-lg border-2 transition-all",D===gt.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:gt.cssVar},title:gt.label},gt.key)),e[97]=D,e[98]=Ze):Ze=e[98];let pt;e[99]!==Je||e[100]!==Ze?(pt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Je,Ze]}),e[99]=Je,e[100]=Ze,e[101]=pt):pt=e[101];let At;e[102]!==Ke||e[103]!==pt?(At=s.jsxs("div",{className:"min-w-0 space-y-2",children:[Ke,pt]}),e[102]=Ke,e[103]=pt,e[104]=At):At=e[104];let vt;e[105]!==h?(vt=h("projectEditDialog.field.icon"),e[105]=h,e[106]=vt):vt=e[106];let at;e[107]!==vt?(at=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:vt}),e[107]=vt,e[108]=at):at=e[108];let ct;e[109]!==$?(ct=s.jsx("input",{ref:ae,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:gt=>{const qt=gt.target.files?.[0]??null;$(qt),gt.currentTarget.value=""}}),e[109]=$,e[110]=ct):ct=e[110];let Ot;e[111]===Symbol.for("react.memo_cache_sentinel")?(Ot=()=>I(null),e[111]=Ot):Ot=e[111];const Zt=S===null?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80";let Et;e[112]!==Zt?(Et=Te("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",Zt),e[112]=Zt,e[113]=Et):Et=e[113];let ge;e[114]!==h?(ge=h("projectEditDialog.option.none"),e[114]=h,e[115]=ge):ge=e[115];let st;e[116]===Symbol.for("react.memo_cache_sentinel")?(st=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[116]=st):st=e[116];let wt;e[117]!==Et||e[118]!==ge?(wt=s.jsx("button",{type:"button",onClick:Ot,className:Et,title:ge,children:st}),e[117]=Et,e[118]=ge,e[119]=wt):wt=e[119];let tt;e[120]!==De||e[121]!==S?(tt=tg.map(gt=>{const qt=gt.Icon;return s.jsx("button",{type:"button",onClick:()=>I(gt.key),className:Te("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",S===gt.key?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80"),title:gt.label,children:s.jsx(T,{name:qt,className:"w-4 h-4",style:De?{color:De}:void 0})},gt.key)}),e[120]=De,e[121]=S,e[122]=tt):tt=e[122];let ut;e[123]!==wt||e[124]!==tt?(ut=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[wt,tt]}),e[123]=wt,e[124]=tt,e[125]=ut):ut=e[125];let Mt;e[126]!==v||e[127]!==k||e[128]!==we||e[129]!==Oe||e[130]!==P||e[131]!==te||e[132]!==o||e[133]!==ue||e[134]!==h?(Mt=we&&ue&&s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:h("projectEditDialog.field.preview")}),s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-1",children:s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:P?{backgroundColor:P}:void 0,children:Oe&&te?s.jsx("img",{src:te,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>ke(!0)}):s.jsx(La,{project:{id:o,iconImage:v},options:{themeVariant:k.metadata.variant,iconColor:k.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>ke(!0)})})})]}),e[126]=v,e[127]=k,e[128]=we,e[129]=Oe,e[130]=P,e[131]=te,e[132]=o,e[133]=ue,e[134]=h,e[135]=Mt):Mt=e[135];let It;e[136]!==Ne||e[137]!==Ee||e[138]!==F||e[139]!==V||e[140]!==h?(It=!Ee&&s.jsxs(s.Fragment,{children:[s.jsx(ze,{size:"sm",variant:"outline",onClick:()=>ae.current?.click(),disabled:V,children:h(V?"projectEditDialog.actions.uploading":"projectEditDialog.actions.uploadIcon")}),s.jsx(ze,{size:"sm",variant:"outline",onClick:()=>{Ne()},disabled:F,children:h(F?"projectEditDialog.actions.discovering":"projectEditDialog.actions.discoverFavicon")})]}),e[136]=Ne,e[137]=Ee,e[138]=F,e[139]=V,e[140]=h,e[141]=It):It=e[141];let zt;e[142]!==ye||e[143]!==Pe||e[144]!==B||e[145]!==h?(zt=Pe&&s.jsx(ze,{size:"sm",variant:"outline",onClick:()=>{ye()},disabled:B,children:h(B?"projectEditDialog.actions.removing":"projectEditDialog.actions.removeProjectIcon")}),e[142]=ye,e[143]=Pe,e[144]=B,e[145]=h,e[146]=zt):zt=e[146];let ss;e[147]!==B||e[148]!==ie||e[149]!==h?(ss=ie&&s.jsx(ze,{size:"sm",variant:"outline",onClick:()=>oe(!1),disabled:B,children:h("projectEditDialog.actions.undoRemove")}),e[147]=B,e[148]=ie,e[149]=h,e[150]=ss):ss=e[150];let Bt;e[151]!==It||e[152]!==zt||e[153]!==ss?(Bt=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[It,zt,ss]}),e[151]=It,e[152]=zt,e[153]=ss,e[154]=Bt):Bt=e[154];let Ft;e[155]!==at||e[156]!==ct||e[157]!==ut||e[158]!==Mt||e[159]!==Bt?(Ft=s.jsxs("div",{className:"min-w-0 space-y-2",children:[at,ct,ut,Mt,Bt]}),e[155]=at,e[156]=ct,e[157]=ut,e[158]=Mt,e[159]=Bt,e[160]=Ft):Ft=e[160];let Jt;e[161]!==we||e[162]!==P||e[163]!==h?(Jt=we&&s.jsxs("div",{className:"min-w-0 space-y-2",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:h("projectEditDialog.field.iconBackground")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:P??"#000000",onChange:gt=>E(gt.target.value),className:"h-8 w-10 cursor-pointer rounded border border-border bg-transparent p-1","aria-label":h("projectEditDialog.field.iconBackgroundAria")}),s.jsx(ln,{value:P??"",onChange:gt=>E(gt.target.value),placeholder:"#000000",className:"h-8 w-[8.5rem]"}),s.jsx(ze,{size:"sm",variant:"outline",onClick:()=>E(null),children:h("projectEditDialog.actions.clear")})]})]}),e[161]=we,e[162]=P,e[163]=h,e[164]=Jt):Jt=e[164];let es;e[165]!==$e||e[166]!==At||e[167]!==Ft||e[168]!==Jt?(es=s.jsxs("div",{className:"min-w-0 space-y-5 py-1",children:[$e,At,Ft,Jt]}),e[165]=$e,e[166]=At,e[167]=Ft,e[168]=Jt,e[169]=es):es=e[169];let Lt;e[170]!==r?(Lt=()=>r(!1),e[170]=r,e[171]=Lt):Lt=e[171];let Pt;e[172]!==h?(Pt=h("projectEditDialog.actions.cancel"),e[172]=h,e[173]=Pt):Pt=e[173];let Kt;e[174]!==Lt||e[175]!==Pt?(Kt=s.jsx(ze,{variant:"ghost",onClick:Lt,children:Pt}),e[174]=Lt,e[175]=Pt,e[176]=Kt):Kt=e[176];let yt;e[177]!==B||e[178]!==V||e[179]!==w?(yt=!w.trim()||V||B,e[177]=B,e[178]=V,e[179]=w,e[180]=yt):yt=e[180];let $t;e[181]!==h?($t=h("projectEditDialog.actions.save"),e[181]=h,e[182]=$t):$t=e[182];let Dt;e[183]!==Re||e[184]!==yt||e[185]!==$t?(Dt=s.jsx(ze,{onClick:Re,disabled:yt,children:$t}),e[183]=Re,e[184]=yt,e[185]=$t,e[186]=Dt):Dt=e[186];let fs;e[187]!==Kt||e[188]!==Dt?(fs=s.jsxs(qn,{children:[Kt,Dt]}),e[187]=Kt,e[188]=Dt,e[189]=fs):fs=e[189];let ms;e[190]!==Ie||e[191]!==es||e[192]!==fs?(ms=s.jsxs(ks,{className:"max-w-md",children:[Ie,es,fs]}),e[190]=Ie,e[191]=es,e[192]=fs,e[193]=ms):ms=e[193];let xs;return e[194]!==r||e[195]!==n||e[196]!==ms?(xs=s.jsx(Cs,{open:n,onOpenChange:r,children:ms}),e[194]=r,e[195]=n,e[196]=ms,e[197]=xs):xs=e[197],xs};function MS(t){return t.uploadProjectIcon}function FS(t){return t.removeProjectIcon}function LS(t){return t.discoverProjectIcon}function OS(t){return t&&URL.revokeObjectURL(t),null}const BS=t=>{const e=ht.c(85),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:c,onRename:l,onDelete:d,renderSessionNode:m,groupDirectory:f,projectId:u,mobileVariant:g,alwaysShowActions:b,isRenaming:h,renameDraft:x,onRenameDraftChange:y,onRenameSave:p,onRenameCancel:C,droppableRef:v,isDropTarget:k,onNewSession:w,onNewSubFolder:A,depth:S,hideActions:I,archivedBucket:D}=t,M=b===void 0?g===void 0?!1:g:b,P=h===void 0?!1:h,E=x===void 0?"":x,V=k===void 0?!1:k,R=S===void 0?0:S,B=I===void 0?!1:I,O=D===void 0?!1:D,{t:F}=jt(),[_,ie]=i.useState(!1),[oe,ne]=i.useState(""),Y=i.useRef(null),te=P||_,de=P?E:oe;let be;e[0]!==n.name?(be=()=>{ne(n.name),ie(!0)},e[0]=n.name,e[1]=be):be=e[1];const ke=be;let ae;e[2]!==de||e[3]!==n.name||e[4]!==P||e[5]!==l||e[6]!==p?(ae=()=>{const X=de.trim();X&&X!==n.name&&l(X),P&&p&&p(),ie(!1),ne("")},e[2]=de,e[3]=n.name,e[4]=P,e[5]=l,e[6]=p,e[7]=ae):ae=e[7];const ve=ae;let J;e[8]!==P||e[9]!==C?(J=()=>{P&&C&&C(),ie(!1),ne("")},e[8]=P,e[9]=C,e[10]=J):J=e[10];const H=J;let q;e[11]!==P||e[12]!==y?(q=X=>{P&&y?y(X):ne(X)},e[11]=P,e[12]=y,e[13]=q):q=e[13];const ce=q;let fe,De;e[14]!==P?(fe=()=>{if(!P)return;const X=()=>{const Q=Y.current;Q&&(Q.focus(),Q.select())},L=requestAnimationFrame(X),xe=window.setTimeout(X,0);return()=>{cancelAnimationFrame(L),window.clearTimeout(xe)}},De=[P],e[14]=P,e[15]=fe,e[16]=De):(fe=e[15],De=e[16]),i.useEffect(fe,De);const Re=a?"folder":"folder-open",Oe=R>0&&"ml-3";let Ee;e[17]!==Oe?(Ee=Te("oc-folder",Oe),e[17]=Oe,e[18]=Ee):Ee=e[18];const we=V&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let Pe;e[19]!==we?(Pe=Te("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",we),e[19]=we,e[20]=Pe):Pe=e[20];const Se=te?void 0:c,ue=te?void 0:"button",K=te?void 0:0;let he;e[21]!==c||e[22]!==te?(he=te?void 0:X=>{(X.key==="Enter"||X.key===" ")&&(X.preventDefault(),c())},e[21]=c,e[22]=te,e[23]=he):he=e[23];let se;e[24]!==n.name||e[25]!==a||e[26]!==F?(se=a?F("sessions.sidebar.folderItem.expandAria",{folderName:n.name}):F("sessions.sidebar.folderItem.collapseAria",{folderName:n.name}),e[24]=n.name,e[25]=a,e[26]=F,e[27]=se):se=e[27];const G=O?M?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let $;e[28]!==G?($=Te("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",G),e[28]=G,e[29]=$):$=e[29];const pe=V?"text-primary":"text-muted-foreground";let ye;e[30]!==pe?(ye=Te("h-3.5 w-3.5 flex-shrink-0",pe),e[30]=pe,e[31]=ye):ye=e[31];let z;e[32]!==Re||e[33]!==ye?(z=s.jsx(T,{name:Re,className:ye}),e[32]=Re,e[33]=ye,e[34]=z):z=e[34];let Ne;e[35]!==de||e[36]!==n.name||e[37]!==H||e[38]!==ce||e[39]!==ve||e[40]!==a||e[41]!==V||e[42]!==te||e[43]!==r||e[44]!==F?(Ne=te?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:VS,onMouseDown:$S,onSubmit:X=>{X.preventDefault(),ve()},children:[s.jsx("input",{ref:Y,value:de,onChange:X=>ce(X.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:F("sessions.sidebar.folderItem.namePlaceholder"),onClick:zS,onPointerDown:WS,onMouseDown:US,onKeyDown:X=>{if(X.key==="Escape"){X.stopPropagation(),H();return}(X.key===" "||X.key==="Enter")&&X.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:HS,onPointerDown:GS,onMouseDown:KS,children:s.jsx(T,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:X=>{X.stopPropagation(),H()},onPointerDown:qS,onMouseDown:YS,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(T,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:Te("typography-ui-label font-semibold truncate",V?"text-primary":"text-muted-foreground"),children:n.name}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",r.length]}),a?s.jsx(T,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[35]=de,e[36]=n.name,e[37]=H,e[38]=ce,e[39]=ve,e[40]=a,e[41]=V,e[42]=te,e[43]=r,e[44]=F,e[45]=Ne):Ne=e[45];let U;e[46]!==$||e[47]!==z||e[48]!==Ne?(U=s.jsxs("div",{className:$,children:[z,Ne]}),e[46]=$,e[47]=z,e[48]=Ne,e[49]=U):U=e[49];let Ie;e[50]!==M||e[51]!==O||e[52]!==R||e[53]!==n.name||e[54]!==ke||e[55]!==B||e[56]!==d||e[57]!==w||e[58]!==A||e[59]!==te||e[60]!==F?(Ie=!te&&(!B||O)?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:Te("flex items-center gap-0.5 transition-opacity",M?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100",O&&"absolute right-0.5 top-1/2 z-10 -translate-y-1/2 px-0"),children:[!O&&w?s.jsx("button",{type:"button",onClick:X=>{X.stopPropagation(),w()},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":F("sessions.sidebar.folderItem.newSessionAria",{folderName:n.name}),title:F("sessions.sidebar.project.actions.newSession"),children:s.jsx(T,{name:"add",className:"h-3.5 w-3.5"})}):null,!O&&A&&R===0?s.jsx("button",{type:"button",onClick:X=>{X.stopPropagation(),A()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":F("sessions.sidebar.folderItem.newSubfolderAria",{folderName:n.name}),title:F("sessions.sidebar.folderItem.newSubfolder"),children:s.jsx(T,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,O?null:s.jsx("button",{type:"button",onClick:X=>{X.stopPropagation(),ke()},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":F("sessions.sidebar.folderItem.renameAria",{folderName:n.name}),children:s.jsx(T,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:X=>{X.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":O?F("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):F("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(T,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=M,e[51]=O,e[52]=R,e[53]=n.name,e[54]=ke,e[55]=B,e[56]=d,e[57]=w,e[58]=A,e[59]=te,e[60]=F,e[61]=Ie):Ie=e[61];let _e;e[62]!==v||e[63]!==Pe||e[64]!==Se||e[65]!==ue||e[66]!==K||e[67]!==he||e[68]!==se||e[69]!==U||e[70]!==Ie?(_e=s.jsxs("div",{ref:v,className:Pe,onClick:Se,role:ue,tabIndex:K,onKeyDown:he,"aria-label":se,children:[U,Ie]}),e[62]=v,e[63]=Pe,e[64]=Se,e[65]=ue,e[66]=K,e[67]=he,e[68]=se,e[69]=U,e[70]=Ie,e[71]=_e):_e=e[71];let Ve;e[72]!==O||e[73]!==f||e[74]!==a||e[75]!==u||e[76]!==m||e[77]!==r||e[78]!==o||e[79]!==F?(Ve=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(X=>m(X,0,f??null,u??null,O)):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:F("sessions.sidebar.folderItem.emptyFolder")})]}),e[72]=O,e[73]=f,e[74]=a,e[75]=u,e[76]=m,e[77]=r,e[78]=o,e[79]=F,e[80]=Ve):Ve=e[80];let Le;return e[81]!==Ee||e[82]!==_e||e[83]!==Ve?(Le=s.jsxs("div",{className:Ee,children:[_e,Ve]}),e[81]=Ee,e[82]=_e,e[83]=Ve,e[84]=Le):Le=e[84],Le},_S=i.memo(BS);function VS(t){return t.stopPropagation()}function $S(t){return t.stopPropagation()}function zS(t){return t.stopPropagation()}function WS(t){return t.stopPropagation()}function US(t){return t.stopPropagation()}function HS(t){return t.stopPropagation()}function GS(t){return t.stopPropagation()}function KS(t){return t.stopPropagation()}function qS(t){return t.stopPropagation()}function YS(t){return t.stopPropagation()}const JS=t=>{const e=ht.c(15),{sessionId:n,sessionDirectory:r,sessionTitle:o,children:a}=t,c=`session-drag:${n}`;let l;e[0]!==r||e[1]!==n||e[2]!==o?(l={type:"session",sessionId:n,sessionDirectory:r,sessionTitle:o},e[0]=r,e[1]=n,e[2]=o,e[3]=l):l=e[3];let d;e[4]!==c||e[5]!==l?(d={id:c,data:l},e[4]=c,e[5]=l,e[6]=d):d=e[6];const{attributes:m,listeners:f,setNodeRef:u,isDragging:g}=Sh(d);let b;e[7]!==f?(b=p=>{p.stopPropagation(),f?.onPointerDown&&f.onPointerDown(p)},e[7]=f,e[8]=b):b=e[8];const h=b,x=g?"opacity-30":void 0;let y;return e[9]!==m||e[10]!==a||e[11]!==h||e[12]!==u||e[13]!==x?(y=s.jsx("div",{ref:u,...m,onPointerDown:h,className:x,children:a}),e[9]=m,e[10]=a,e[11]=h,e[12]=u,e[13]=x,e[14]=y):y=e[14],y},QS=t=>{const e=ht.c(11),{folderId:n,children:r}=t,o=`folder-drop:${n}`;let a;e[0]!==n?(a={type:"folder",folderId:n},e[0]=n,e[1]=a):a=e[1];let c;e[2]!==o||e[3]!==a?(c={id:o,data:a},e[2]=o,e[3]=a,e[4]=c):c=e[4];const{setNodeRef:l,isOver:d}=Nh(c);let m;e[5]!==r||e[6]!==d||e[7]!==l?(m=r(l,d),e[5]=r,e[6]=d,e[7]=l,e[8]=m):m=e[8];let f;return e[9]!==m?(f=s.jsx(s.Fragment,{children:m}),e[9]=m,e[10]=f):f=e[10],f},XS=t=>{const e=ht.c(20),{scopeKey:n,hasFolders:r,onSessionDroppedOnFolder:o,children:a}=t;let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c={activationConstraint:{distance:8}},e[0]=c):c=e[0];const l=aa(mo(la,c)),[d,m]=i.useState(null),[f,u]=i.useState("Session"),[g,b]=i.useState(null),[h,x]=i.useState(null);if(!n){let S;return e[1]!==a?(S=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=S):S=e[2],S}let y;e[3]!==o?(y=S=>{m(null),b(null),x(null);const{active:I,over:D}=S;if(!D)return;const N=I.data.current,M=D.data.current;N?.type==="session"&&N.sessionId&&M?.type==="folder"&&M.folderId&&o(N.sessionId,M.folderId)},e[3]=o,e[4]=y):y=e[4];const p=y;let C,v;e[5]===Symbol.for("react.memo_cache_sentinel")?(C=S=>{const I=S.active.data.current;if(I?.type==="session"&&I.sessionId){m(I.sessionId),u(I.sessionTitle??"Session");const D=S.active.rect.current.initial?.width,N=S.active.rect.current.initial?.height;b(typeof D=="number"?D:null),x(typeof N=="number"?N:null)}},v=()=>{m(null),b(null),x(null)},e[5]=C,e[6]=v):(C=e[5],v=e[6]);let k;e[7]!==h||e[8]!==d||e[9]!==f||e[10]!==g||e[11]!==r?(k=d&&r?s.jsxs("div",{style:{width:g?`${g}px`:"auto",height:h?`${h}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2.5 py-1 shadow-none pointer-events-none",children:[s.jsx(T,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:f})]}):null,e[7]=h,e[8]=d,e[9]=f,e[10]=g,e[11]=r,e[12]=k):k=e[12];let w;e[13]!==k?(w=s.jsx(Pl,{children:k}),e[13]=k,e[14]=w):w=e[14];let A;return e[15]!==a||e[16]!==p||e[17]!==l||e[18]!==w?(A=s.jsxs(ca,{sensors:l,collisionDetection:da,onDragStart:C,onDragCancel:v,onDragEnd:p,children:[a,w]}),e[15]=a,e[16]=p,e[17]=l,e[18]=w,e[19]=A):A=e[19],A},jr=Zi()(Ql(t=>({displayMode:"minimal",showRecentSection:!0,showArchivedSessions:!1,setDisplayMode:e=>t({displayMode:e}),setShowRecentSection:e=>t({showRecentSection:e}),setShowArchivedSessions:e=>t({showArchivedSessions:e}),toggleRecentSection:()=>t(e=>({showRecentSection:!e.showRecentSection})),toggleArchivedSessions:()=>t(e=>({showArchivedSessions:!e.showArchivedSessions}))}),{name:"session-display-mode",version:1,migrate:(t,e)=>{const n=t??{};return e<1?{...n,displayMode:"minimal"}:n}})),ZS=50,Uu=28;function e2(t){const{t:e}=jt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:m,collapsedGroups:f,hideDirectoryControls:u,collapsedFolderIds:g,toggleFolderCollapse:b,renameFolder:h,deleteFolder:x,showDeletionDialog:y,setDeleteFolderConfirm:p,renderSessionNode:C,projectRepoStatus:v,lastRepoStatus:k,showMoreGroupSessions:w,resetGroupSessionLimit:A,mobileVariant:S,alwaysShowActions:I,activeProjectId:D,setActiveProjectIdOnly:N,setActiveMainTab:M,setSessionSwitcherOpen:P,openNewSessionDraft:E,addSessionToFolder:V,createFolderAndStartRename:R,renamingFolderId:B,renameFolderDraft:O,setRenameFolderDraft:F,setRenamingFolderId:_,pinnedSessionIds:ie,sessionOrderIndex:oe,prVisualStateByDirectoryBranch:ne,onToggleCollapsedGroup:Y,dragHandleProps:te,compactBodyPadding:de=!1}=t,be=i.useCallback((ge,st)=>{const wt=oe.get(ge.session.id),tt=oe.get(st.session.id);if(wt!==void 0||tt!==void 0){if(wt===void 0)return 1;if(tt===void 0)return-1;if(wt!==tt)return wt-tt}return $i(ge.session,st.session,ie)},[ie,oe]),ke=c?d.get(n):null,ae=jr(ge=>ge.displayMode),ve=Nn(ge=>ge.foldersMap),J=ae==="minimal"&&!Fr(),H=c?!1:f.has(r),q=u?10:5,ce=Math.max(q,m??q),fe=c?ke?.groupMatches===!0:!1,De=c,Re=i.useMemo(()=>[...De?ke?.filteredNodes??[]:n.sessions].sort(be),[be,n.sessions,ke?.filteredNodes,De]),Fe=n.folderScopeKey??Gt(n.directory??null),Oe=i.useMemo(()=>Fe?ve[Fe]??[]:[],[Fe,ve]),Ee=i.useMemo(()=>{const ge=new Map,st=wt=>{wt.forEach(tt=>{ge.set(tt.session.id,tt),tt.children.length>0&&st(tt.children)})};return st(Re),ge},[Re]),we=i.useMemo(()=>Oe.map(ge=>{const st=ge.sessionIds.map(wt=>Ee.get(wt)).filter(wt=>!!wt).sort(be);return{folder:ge,nodes:st}}),[Oe,Ee,be]),Pe=i.useMemo(()=>{const ge=new Map(we.map(ut=>[ut.folder.id,ut])),st=new Map;for(const{folder:ut}of we){if(!ut.parentId)continue;const Mt=st.get(ut.parentId);Mt?Mt.push(ut.id):st.set(ut.parentId,[ut.id])}const wt=new Map,tt=ut=>{const Mt=wt.get(ut);if(Mt!==void 0)return Mt;const It=ge.get(ut);if(!It)return wt.set(ut,!1),!1;const zt=st.get(ut)??[];if(n.isArchivedBucket&&It.nodes.length===0){const Ft=zt.some(Jt=>tt(Jt));return wt.set(ut,Ft),Ft}if(!c||It.folder.name.toLowerCase().includes(l)||It.nodes.length>0)return wt.set(ut,!0),!0;const Bt=zt.some(Ft=>tt(Ft));return wt.set(ut,Bt),Bt};return we.filter(({folder:ut})=>tt(ut.id))},[we,n.isArchivedBucket,c,l]),Se=i.useMemo(()=>new Set(Pe.flatMap(ge=>ge.folder.sessionIds)),[Pe]),ue=i.useMemo(()=>Re.filter(ge=>!Se.has(ge.session.id)),[Re,Se]),K=i.useMemo(()=>Pe.filter(({folder:ge})=>!ge.parentId),[Pe]),he=ue.length,se=n.isArchivedBucket||c?ue:ue.slice(0,ce),G=he-se.length,$=!n.isArchivedBucket&&!c&&he>q&&G===0,pe=n.isArchivedBucket===!0&&!c&&se.length>=ZS,ye=i.useRef(null),z=i.useRef(null),[Ne,U]=i.useState(null),[Ie,_e]=i.useState(0);if(i.useLayoutEffect(()=>{if(!pe){Ne!==null&&U(null),z.current=null,Ie!==0&&_e(0);return}const ge=ye.current;if(!ge)return;let st=Ne;if(!st||!st.contains(ge)){let tt=ge.parentElement;for(;tt;){const ut=window.getComputedStyle(tt);if(ut.overflowY==="auto"||ut.overflowY==="scroll"){st=tt;break}tt=tt.parentElement}if(st!==Ne){z.current=st,U(st);return}}if(!st)return;const wt=ge.getBoundingClientRect().top-st.getBoundingClientRect().top+st.scrollTop;_e(tt=>Math.abs(tt-wt)<1?tt:wt)}),c&&!fe&&K.length===0&&ue.length===0)return null;const Ve=ge=>{const st=[],wt=tt=>{tt.forEach(ut=>{st.push(ut.session),ut.children.length>0&&wt(ut.children)})};return wt(ge),st},Le=Ve(Re),X=o&&v.has(o)?!!v.get(o):k,L=Gt(n.directory??null),xe=n.branch?.trim()??null,Q=L&&xe?ne.get(`${L}::${xe}`)??null:null,$e=!!(Q&&n.branch),He=!Q&&!n.isMain&&!!n.branch,Ke=Q?.visualState??null,qe=Q&&Q.state==="open"&&Q.checks?e("sessions.sidebar.group.pr.checksPassed",{success:Q.checks.success,total:Q.checks.total}):null,Xe=Q&&Q.state==="open"&&Q.checks?[Q.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:Q.checks.failure}):null,Q.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:Q.checks.pending}):null].filter(ge=>!!ge).join(", "):null,lt=Q&&Q.state==="open"?Q.mergeableState==="blocked"||Q.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):Q.mergeableState==="clean"||Q.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,bt=Q&&Q.state==="open"&&Q.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:Q.mergeableState}):null,Be=Q?.base??null,Je=Q?.head??null,Ze=(()=>{if(!Q)return n.branch&&Ox(n.branch,n.label)?{label:n.branch,color:null}:null;switch(Q.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return Q.canMerge===!0||Q.mergeableState==="clean"||Q.checks?.state==="success"?{label:e("sessions.sidebar.group.pr.status.readyToMerge"),color:"var(--pr-open)"}:{label:e("sessions.sidebar.group.pr.status.open"),color:"var(--pr-open)"};case"blocked":return{label:Q.mergeableState==="dirty"?e("sessions.sidebar.group.pr.status.mergeConflicts"):e("sessions.sidebar.group.pr.status.mergeBlocked"),color:"var(--pr-blocked)"};case"draft":return{label:e("sessions.sidebar.group.pr.status.draft"),color:"var(--pr-draft)"};case"closed":return{label:e("sessions.sidebar.group.pr.status.closed"),color:"var(--pr-closed)"};default:return null}})(),pt=Ze?.color??(Ke?`var(--pr-${Ke})`:void 0),At=ge=>{ge.preventDefault(),ge.stopPropagation();const st=Q?.url;st&&Si(st)},vt=(ge,st,wt)=>{const tt=Pe.filter(({folder:zt})=>zt.parentId===ge.id),ut=tt.length>0?s.jsx(s.Fragment,{children:tt.map(({folder:zt,nodes:ss})=>vt(zt,ss,wt+1))}):void 0,Mt=zt=>{const ss=Pe.find(({folder:Ft})=>Ft.id===zt)?.nodes??[],Bt=Pe.filter(({folder:Ft})=>Ft.parentId===zt);return[...Ve(ss),...Bt.flatMap(({folder:Ft})=>Mt(Ft.id))]},It=n.isArchivedBucket?Mt(ge.id):[];return s.jsx(QS,{folderId:ge.id,children:(zt,ss)=>s.jsx(_S,{folder:ge,sessions:st,subFolderItems:ut,isCollapsed:c?!1:g.has(ge.id),onToggle:()=>b(ge.id),onRename:Bt=>{Fe&&h(Fe,ge.id,Bt)},onDelete:()=>{if(n.isArchivedBucket){Nr.requestDelete({sessions:It,mode:"session"});return}if(!Fe)return;if(!y){x(Fe,ge.id);return}const Bt=Pe.filter(({folder:Jt})=>Jt.parentId===ge.id).length,Ft=st.length;p({scopeKey:Fe,folderId:ge.id,folderName:ge.name,subFolderCount:Bt,sessionCount:Ft})},renderSessionNode:C,groupDirectory:n.directory,projectId:o,mobileVariant:S,alwaysShowActions:I,isRenaming:B===ge.id,renameDraft:B===ge.id?O:void 0,onRenameDraftChange:Bt=>F(Bt),onRenameSave:()=>{const Bt=O.trim();Bt&&Fe&&h(Fe,ge.id,Bt),_(null),F("")},onRenameCancel:()=>{_(null),F("")},droppableRef:zt,isDropTarget:ss,depth:wt,onNewSession:()=>{o&&o!==D&&N(o),M("chat"),S&&P(!1),E({directoryOverride:n.directory,targetFolderId:ge.id})},onNewSubFolder:wt===0?()=>{Fe&&R(Fe,ge.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},ge.id)},at=()=>K.map(({folder:ge,nodes:st})=>vt(ge,st,0)),ct=!!(!n.isMain&&n.worktree),Ot=I?ct?"pr-14":"pr-7":J?ct?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":ct?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",Zt=s.jsxs(XS,{scopeKey:Fe,hasFolders:Pe.length>0,onSessionDroppedOnFolder:(ge,st)=>{Fe&&V(Fe,st,ge)},children:[at(),pe?s.jsx("div",{ref:ye,children:s.jsx(kh,{data:se,itemSize:Uu,bufferSize:Uu*8,scrollRef:z,startMargin:Ie,children:ge=>C(ge,0,n.directory,o,!0)})}):se.map(ge=>C(ge,0,n.directory,o,n.isArchivedBucket===!0)),he===0&&Pe.length===0?s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:n.isArchivedBucket?e("sessions.sidebar.group.empty.noArchivedSessions"):e("sessions.sidebar.group.empty.noSessionsInWorkspace")}):null,G>0?s.jsx("button",{type:"button",onClick:()=>w(r,se.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showMore")}):null,$?s.jsx("button",{type:"button",onClick:()=>A(r),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showFewer")}):null]}),Et=de?"pb-2 pl-1":"pb-3 pl-4";return a?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:Te("oc-group-body",Et),children:Zt})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:Te("group/gh relative flex items-start justify-between gap-1 py-1 min-w-0 rounded-md","cursor-pointer"),onClick:()=>Y(r),role:"button",tabIndex:0,onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.preventDefault(),Y(r))},"aria-label":H?e("sessions.sidebar.group.expandAria",{label:n.label}):e("sessions.sidebar.group.collapseAria",{label:n.label}),"aria-expanded":!H,children:[s.jsx("div",{ref:te?.setActivatorNodeRef,className:Te("min-w-0 flex flex-1 items-start gap-1 overflow-hidden pl-0.5 transition-[padding] cursor-grab active:cursor-grabbing",Ot),...te?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"text-[14px] font-normal truncate text-foreground/92",children:$e&&Q?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 leading-none align-middle",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(T,{name:"git-branch",className:Te("h-3.5 w-3.5 shrink-0",I?"hidden":"group-hover/gh:hidden"),style:pt?{color:pt}:void 0}),s.jsx("span",{className:Te("text-muted-foreground h-3.5 w-3.5 items-center justify-center",I?"inline-flex":"hidden group-hover/gh:inline-flex"),children:H?s.jsx(T,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),Q.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:ge=>ge.stopPropagation(),onClick:At,children:["#",Q.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",Q.number]})]})}),s.jsx(Ct,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Be||Je?s.jsx("div",{className:"text-muted-foreground truncate",children:Be&&Je?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Be}),s.jsx(T,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Je})]}):s.jsx("span",{children:Be??Je??""})}):null,bt?s.jsx("div",{className:"text-muted-foreground truncate",children:bt}):null,lt||qe?s.jsxs("div",{className:"text-muted-foreground truncate",children:[lt??"",lt&&qe?" • ":"",qe??"",Xe?` (${Xe})`:""]}):null]})})]}),s.jsx("span",{className:"ml-1 min-w-0 flex-1 truncate leading-none align-middle",children:n.branch})]}):n.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(T,{name:"archive",className:Te("h-3.5 w-3.5 shrink-0 text-muted-foreground",I?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:Te("text-muted-foreground h-3.5 w-3.5 items-center justify-center",I?"inline-flex":"hidden group-hover/gh:inline-flex"),children:H?s.jsx(T,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:po(n.label,l)})]}):!n.isMain||n.worktree?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(T,{name:"git-branch",className:Te("h-3.5 w-3.5 shrink-0 text-muted-foreground",I?"hidden":"group-hover/gh:hidden"),style:pt?{color:pt}:void 0}),s.jsx("span",{className:Te("text-muted-foreground h-3.5 w-3.5 items-center justify-center",I?"inline-flex":"hidden group-hover/gh:inline-flex"),children:H?s.jsx(T,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:po(n.label,l)})]}):po(n.label,l)}),He&&Ze?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(T,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||X?$e&&Q?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:s.jsx(T,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:pt?{color:pt}:void 0})})}),s.jsx(Ct,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Be||Je?s.jsx("div",{className:"text-muted-foreground truncate",children:Be&&Je?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Be}),s.jsx(T,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Je})]}):s.jsx("span",{children:Be??Je??""})}):null,bt?s.jsx("div",{className:"text-muted-foreground truncate",children:bt}):null,lt||qe?s.jsxs("div",{className:"text-muted-foreground truncate",children:[lt??"",lt&&qe?" • ":"",qe??"",Xe?` (${Xe})`:""]}):null]})})]}):s.jsx(T,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:pt?{color:pt}:void 0}):null,s.jsx("span",{className:Te("min-w-0 truncate text-[11px] font-medium",!Ze.color&&"text-muted-foreground/80"),style:Ze.color?{color:Ze.color}:void 0,children:Ze.label})]}):null]})}),n.isArchivedBucket&&Le.length>0?s.jsx("div",{className:Te("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",I?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),Nr.requestDelete({sessions:Le,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":e("sessions.sidebar.group.actions.deleteArchivedInGroupAria",{label:n.label}),children:s.jsx(T,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteArchivedSessions")})})]})}):null,n.directory&&!n.isMain&&n.worktree?s.jsx("div",{className:Te("absolute right-7 top-1/2 -translate-y-1/2 z-10 transition-opacity",I?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),Nr.requestDelete({sessions:Le,mode:"worktree",worktree:n.worktree})},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":e("sessions.sidebar.group.actions.deleteGroupAria",{label:n.label}),children:s.jsx(T,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteWorktree")})})]})}):null,n.directory?s.jsx("div",{className:Te("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",I?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ge=>{ge.stopPropagation(),o&&o!==D&&N(o),M("chat"),S&&P(!1),E({directoryOverride:n.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":e("sessions.sidebar.group.actions.newDraftInGroupAria",{label:n.label}),children:s.jsx(T,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),H?null:s.jsx("div",{className:Te("oc-group-body",Et),children:Zt})]})}function t2(t){const e=ht.c(182),{t:n}=jt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:m,headerActionButtonClass:f,isSessionSearchOpen:u,setIsSessionSearchOpen:g,sessionSearchInputRef:b,sessionSearchQuery:h,setSessionSearchQuery:x,hasSessionSearchQuery:y,searchMatchCount:p,collapseAllProjects:C,expandAllProjects:v,openScheduledTasksDialog:k,selectionModeEnabled:w,onToggleSelectionMode:A}=t,S=jr(l2),I=jr(a2),D=jr(o2),N=jr(i2),M=jr(r2),P=jr(n2);let E;e[0]===Symbol.for("react.memo_cache_sentinel")?(E=Fr(),e[0]=E):E=e[0];const V=!E;if(r)return null;let R;e[1]!==n?(R=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=R):R=e[2];let B;e[3]!==m?(B=s.jsx(T,{name:"folder-add",className:m}),e[3]=m,e[4]=B):B=e[4];let O;e[5]!==a||e[6]!==f||e[7]!==R||e[8]!==B?(O=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:f,"aria-label":R,children:B})}),e[5]=a,e[6]=f,e[7]=R,e[8]=B,e[9]=O):O=e[9];let F;e[10]!==n?(F=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=F):F=e[11];let _;e[12]!==F?(_=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:F})}),e[12]=F,e[13]=_):_=e[13];let ie;e[14]!==O||e[15]!==_?(ie=s.jsxs(Nt,{children:[O,_]}),e[14]=O,e[15]=_,e[16]=ie):ie=e[16];let oe;e[17]!==n?(oe=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=oe):oe=e[18];let ne;e[19]!==m?(ne=s.jsx(T,{name:"chat-new",className:m}),e[19]=m,e[20]=ne):ne=e[20];let Y;e[21]!==f||e[22]!==c||e[23]!==oe||e[24]!==ne?(Y=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:f,"aria-label":oe,children:ne})}),e[21]=f,e[22]=c,e[23]=oe,e[24]=ne,e[25]=Y):Y=e[25];let te;e[26]!==n?(te=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=te):te=e[27];let de;e[28]!==te?(de=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:te})}),e[28]=te,e[29]=de):de=e[29];let be;e[30]!==de||e[31]!==Y?(be=s.jsxs(Nt,{children:[Y,de]}),e[30]=de,e[31]=Y,e[32]=be):be=e[32];let ke;e[33]!==n?(ke=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=ke):ke=e[34];const ae=!l;let ve;e[35]!==m?(ve=s.jsx(sg,{className:m}),e[35]=m,e[36]=ve):ve=e[36];let J;e[37]!==f||e[38]!==d||e[39]!==ke||e[40]!==ae||e[41]!==ve?(J=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:f,"aria-label":ke,disabled:ae,children:ve})}),e[37]=f,e[38]=d,e[39]=ke,e[40]=ae,e[41]=ve,e[42]=J):J=e[42];let H;e[43]!==n?(H=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=H):H=e[44];let q;e[45]!==H?(q=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:H})}),e[45]=H,e[46]=q):q=e[46];let ce;e[47]!==J||e[48]!==q?(ce=s.jsxs(Nt,{children:[J,q]}),e[47]=J,e[48]=q,e[49]=ce):ce=e[49];let fe;e[50]!==n?(fe=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=fe):fe=e[51];let De;e[52]!==m?(De=s.jsx(T,{name:"calendar-schedule",className:m}),e[52]=m,e[53]=De):De=e[53];let Re;e[54]!==f||e[55]!==k||e[56]!==fe||e[57]!==De?(Re=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:f,"aria-label":fe,children:De})}),e[54]=f,e[55]=k,e[56]=fe,e[57]=De,e[58]=Re):Re=e[58];let Fe;e[59]!==n?(Fe=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=Fe):Fe=e[60];let Oe;e[61]!==Fe?(Oe=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Fe})}),e[61]=Fe,e[62]=Oe):Oe=e[62];let Ee;e[63]!==Re||e[64]!==Oe?(Ee=s.jsxs(Nt,{children:[Re,Oe]}),e[63]=Re,e[64]=Oe,e[65]=Ee):Ee=e[65];let we;e[66]!==be||e[67]!==ce||e[68]!==Ee||e[69]!==ie?(we=s.jsxs("div",{className:"flex items-center gap-1.5",children:[ie,be,ce,Ee]}),e[66]=be,e[67]=ce,e[68]=Ee,e[69]=ie,e[70]=we):we=e[70];let Pe;e[71]!==g?(Pe=()=>g(s2),e[71]=g,e[72]=Pe):Pe=e[72];let Se;e[73]!==n?(Se=n("sessions.sidebar.header.actions.searchSessions"),e[73]=n,e[74]=Se):Se=e[74];let ue;e[75]!==m?(ue=s.jsx(T,{name:"search",className:m}),e[75]=m,e[76]=ue):ue=e[76];let K;e[77]!==f||e[78]!==u||e[79]!==Pe||e[80]!==Se||e[81]!==ue?(K=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Pe,className:f,"aria-label":Se,"aria-expanded":u,children:ue})}),e[77]=f,e[78]=u,e[79]=Pe,e[80]=Se,e[81]=ue,e[82]=K):K=e[82];let he;e[83]!==n?(he=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=he):he=e[84];let se;e[85]!==he?(se=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:he})}),e[85]=he,e[86]=se):se=e[86];let G;e[87]!==K||e[88]!==se?(G=s.jsxs(Nt,{children:[K,se]}),e[87]=K,e[88]=se,e[89]=G):G=e[89];const $=w&&"bg-interactive-hover text-primary";let pe;e[90]!==f||e[91]!==$?(pe=Te(f,$),e[90]=f,e[91]=$,e[92]=pe):pe=e[92];let ye;e[93]!==w||e[94]!==n?(ye=n(w?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=w,e[94]=n,e[95]=ye):ye=e[95];let z;e[96]!==m?(z=s.jsx(T,{name:"checkbox-multiple",className:m}),e[96]=m,e[97]=z):z=e[97];let Ne;e[98]!==A||e[99]!==w||e[100]!==pe||e[101]!==ye||e[102]!==z?(Ne=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:A,className:pe,"aria-label":ye,"aria-pressed":w,children:z})}),e[98]=A,e[99]=w,e[100]=pe,e[101]=ye,e[102]=z,e[103]=Ne):Ne=e[103];let U;e[104]!==w||e[105]!==n?(U=n(w?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=w,e[105]=n,e[106]=U):U=e[106];let Ie;e[107]!==U?(Ie=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:U})}),e[107]=U,e[108]=Ie):Ie=e[108];let _e;e[109]!==Ne||e[110]!==Ie?(_e=s.jsxs(Nt,{children:[Ne,Ie]}),e[109]=Ne,e[110]=Ie,e[111]=_e):_e=e[111];let Ve;e[112]!==n?(Ve=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[112]=n,e[113]=Ve):Ve=e[113];let Le;e[114]!==m?(Le=s.jsx(T,{name:"equalizer-2",className:m}),e[114]=m,e[115]=Le):Le=e[115];let X;e[116]!==f||e[117]!==Ve||e[118]!==Le?(X=s.jsx(kt,{asChild:!0,children:s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:f,"aria-label":Ve,children:Le})})}),e[116]=f,e[117]=Ve,e[118]=Le,e[119]=X):X=e[119];let L;e[120]!==n?(L=n("sessions.sidebar.header.displayMode.label"),e[120]=n,e[121]=L):L=e[121];let xe;e[122]!==L?(xe=s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:L})}),e[122]=L,e[123]=xe):xe=e[123];let Q;e[124]!==X||e[125]!==xe?(Q=s.jsxs(Nt,{children:[X,xe]}),e[124]=X,e[125]=xe,e[126]=Q):Q=e[126];let $e;e[127]!==S||e[128]!==N||e[129]!==n?($e=V?s.jsxs(s.Fragment,{children:[s.jsxs(ls,{onClick:()=>N("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),S==="default"?s.jsx(T,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(ls,{onClick:()=>N("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),S==="minimal"?s.jsx(T,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[127]=S,e[128]=N,e[129]=n,e[130]=$e):$e=e[130];let He;e[131]!==D||e[132]!==o||e[133]!==I||e[134]!==n||e[135]!==P||e[136]!==M?(He=o?s.jsxs(s.Fragment,{children:[V?s.jsx(Cr,{}):null,s.jsxs(ls,{onClick:M,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showRecent")}),I?s.jsx(T,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(ls,{onClick:P,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),D?s.jsx(T,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[131]=D,e[132]=o,e[133]=I,e[134]=n,e[135]=P,e[136]=M,e[137]=He):He=e[137];let Ke;e[138]===Symbol.for("react.memo_cache_sentinel")?(Ke=s.jsx(Cr,{}),e[138]=Ke):Ke=e[138];let qe;e[139]===Symbol.for("react.memo_cache_sentinel")?(qe=s.jsx(T,{name:"contract-up-down",className:"h-4 w-4"}),e[139]=qe):qe=e[139];let Xe;e[140]!==n?(Xe=n("sessions.sidebar.header.displayMode.collapseAll"),e[140]=n,e[141]=Xe):Xe=e[141];let lt;e[142]!==Xe?(lt=s.jsx("span",{children:Xe}),e[142]=Xe,e[143]=lt):lt=e[143];let bt;e[144]!==C||e[145]!==lt?(bt=s.jsxs(ls,{onClick:C,className:"flex items-center gap-2",children:[qe,lt]}),e[144]=C,e[145]=lt,e[146]=bt):bt=e[146];let Be;e[147]===Symbol.for("react.memo_cache_sentinel")?(Be=s.jsx(T,{name:"expand-up-down",className:"h-4 w-4"}),e[147]=Be):Be=e[147];let Je;e[148]!==n?(Je=n("sessions.sidebar.header.displayMode.expandAll"),e[148]=n,e[149]=Je):Je=e[149];let Ze;e[150]!==Je?(Ze=s.jsx("span",{children:Je}),e[150]=Je,e[151]=Ze):Ze=e[151];let pt;e[152]!==v||e[153]!==Ze?(pt=s.jsxs(ls,{onClick:v,className:"flex items-center gap-2",children:[Be,Ze]}),e[152]=v,e[153]=Ze,e[154]=pt):pt=e[154];let At;e[155]!==$e||e[156]!==He||e[157]!==bt||e[158]!==pt?(At=s.jsxs(zs,{align:"end",className:"min-w-[160px]",children:[$e,He,Ke,bt,pt]}),e[155]=$e,e[156]=He,e[157]=bt,e[158]=pt,e[159]=At):At=e[159];let vt;e[160]!==Q||e[161]!==At?(vt=s.jsxs(Ws,{children:[Q,At]}),e[160]=Q,e[161]=At,e[162]=vt):vt=e[162];let at;e[163]!==G||e[164]!==_e||e[165]!==vt?(at=s.jsxs("div",{className:"flex items-center gap-1.5",children:[G,_e,vt]}),e[163]=G,e[164]=_e,e[165]=vt,e[166]=at):at=e[166];let ct;e[167]!==we||e[168]!==at?(ct=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[we,at]}),e[167]=we,e[168]=at,e[169]=ct):ct=e[169];let Ot;e[170]!==y||e[171]!==u||e[172]!==p||e[173]!==b||e[174]!==h||e[175]!==g||e[176]!==x||e[177]!==n?(Ot=u?s.jsxs("div",{className:"pb-1",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:[y?s.jsx("span",{children:p===1?n("sessions.sidebar.header.search.matchCountSingle",{count:p}):n("sessions.sidebar.header.search.matchCountPlural",{count:p})}):s.jsx("span",{}),s.jsx("span",{children:n("sessions.sidebar.header.search.escapeHint")})]}),s.jsxs("div",{className:"relative",children:[s.jsx(T,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:b,value:h,onChange:Et=>x(Et.target.value),placeholder:n("sessions.sidebar.header.search.placeholder"),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:Et=>{Et.key==="Escape"&&(Et.stopPropagation(),y?x(""):g(!1))}}),h.length>0?s.jsx("button",{type:"button",onClick:()=>x(""),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":n("sessions.sidebar.header.search.clear"),children:s.jsx(T,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[170]=y,e[171]=u,e[172]=p,e[173]=b,e[174]=h,e[175]=g,e[176]=x,e[177]=n,e[178]=Ot):Ot=e[178];let Zt;return e[179]!==ct||e[180]!==Ot?(Zt=s.jsx("div",{className:"select-none flex-shrink-0 px-2.5 py-1",children:s.jsxs("div",{className:"flex h-auto min-h-8 flex-col gap-1",children:[ct,Ot]})}),e[179]=ct,e[180]=Ot,e[181]=Zt):Zt=e[181],Zt}function s2(t){return!t}function n2(t){return t.toggleArchivedSessions}function r2(t){return t.toggleRecentSection}function i2(t){return t.setDisplayMode}function o2(t){return t.showArchivedSessions}function a2(t){return t.showRecentSection}function l2(t){return t.displayMode}const Hu=7;function c2(t){const e=ht.c(30),{sections:n,renderSessionNode:r,variant:o,initialVisibleCount:a,batchSize:c}=t,l=o===void 0?"section":o,d=a===void 0?Hu:a,m=c===void 0?Hu:c,{t:f}=jt();let u;e[0]===Symbol.for("react.memo_cache_sentinel")?(u=new Set,e[0]=u):u=e[0];const[g,b]=i.useState(u);let h;e[1]===Symbol.for("react.memo_cache_sentinel")?(h=new Map,e[1]=h):h=e[1];const[x,y]=i.useState(h),p=l==="flat";let C;e[2]===Symbol.for("react.memo_cache_sentinel")?(C=P=>{y(E=>{if(!E.has(P))return E;const V=new Map(E);return V.delete(P),V})},e[2]=C):C=e[2];const v=C;let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=P=>{v(P),b(E=>{const V=new Set(E);return V.has(P)?V.delete(P):V.add(P),V})},e[3]=k):k=e[3];const w=k;let A;e[4]!==m?(A=(P,E,V)=>{y(R=>{const B=Math.min(V,E+m),O=new Map(R);return O.set(P,B),O})},e[4]=m,e[5]=A):A=e[5];const S=A;let I,D,N;if(e[6]!==g||e[7]!==p||e[8]!==d||e[9]!==r||e[10]!==n||e[11]!==S||e[12]!==f||e[13]!==x){D=Symbol.for("react.early_return_sentinel");e:{const P=n.filter(d2);if(P.length===0){D=null;break e}const E=p?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1";e[17]!==E?(N=Te(E),e[17]=E,e[18]=N):N=e[18];let V;e[19]!==g||e[20]!==p||e[21]!==d||e[22]!==r||e[23]!==S||e[24]!==f||e[25]!==x?(V=R=>{const B=g.has(R.key),O=Math.max(d,x.get(R.key)??d),F=R.items.slice(0,O),_=R.items.length-F.length,ie=!p&&R.items.length>d&&_===0;return p?s.jsxs("div",{className:"space-y-0.5",children:[F.map(oe=>r(oe.node,0,oe.groupDirectory,oe.projectId,!1,oe.secondaryMeta,"recent")),_>0?s.jsx("button",{type:"button",onClick:()=>S(R.key,F.length,R.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:f("sessions.sidebar.group.showMore")}):null]},R.key):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("button",{type:"button",onClick:()=>w(R.key),className:"group flex w-full items-center gap-1 rounded-md px-0.5 py-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-expanded":!B,children:[s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground",children:B?s.jsx(T,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"text-[14px] font-normal text-foreground/95",children:R.title})]}),B?null:s.jsxs("div",{className:Te("space-y-0.5 pl-7"),children:[F.map(oe=>r(oe.node,0,oe.groupDirectory,oe.projectId,!1,oe.secondaryMeta,"recent")),_>0?s.jsx("button",{type:"button",onClick:()=>S(R.key,F.length,R.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:f("sessions.sidebar.group.showMore")}):null,ie?s.jsx("button",{type:"button",onClick:()=>v(R.key),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:f("sessions.sidebar.group.showFewer")}):null]})]},R.key)},e[19]=g,e[20]=p,e[21]=d,e[22]=r,e[23]=S,e[24]=f,e[25]=x,e[26]=V):V=e[26],I=P.map(V)}e[6]=g,e[7]=p,e[8]=d,e[9]=r,e[10]=n,e[11]=S,e[12]=f,e[13]=x,e[14]=I,e[15]=D,e[16]=N}else I=e[14],D=e[15],N=e[16];if(D!==Symbol.for("react.early_return_sentinel"))return D;let M;return e[27]!==I||e[28]!==N?(M=s.jsx("div",{className:N,children:I}),e[27]=I,e[28]=N,e[29]=M):M=e[29],M}function d2(t){return t.items.length>0}const vl="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 u2(t){const e=ht.c(13),{onOpenSettings:n,onOpenShortcuts:r,onOpenAbout:o,onOpenUpdate:a,showRuntimeButtons:c,showUpdateButton:l}=t,d=c===void 0?!0:c,m=l===void 0?!0:l,{t:f}=jt();let u;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==d||e[4]!==f?(u=d?s.jsxs(s.Fragment,{children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:vl,"aria-label":f("sessions.sidebar.footer.actions.settings"),children:s.jsx(T,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(Ct,{side:"top",sideOffset:4,children:s.jsx("p",{children:f("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:vl,"aria-label":f("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(T,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(Ct,{side:"top",sideOffset:4,children:s.jsx("p",{children:f("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:vl,"aria-label":f("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(T,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(Ct,{side:"top",sideOffset:4,children:s.jsx("p",{children:f("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=f,e[5]=u):u=e[5];let g;e[6]!==a||e[7]!==m||e[8]!==f?(g=m?s.jsx(ze,{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:a,children:f("sessions.sidebar.footer.actions.update")}):null,e[6]=a,e[7]=m,e[8]=f,e[9]=g):g=e[9];let b;return e[10]!==u||e[11]!==g?(b=s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-2.5 py-2",children:[u,g]}),e[10]=u,e[11]=g,e[12]=b):b=e[12],b}const m2=t=>{const e=ht.c(58),{id:n,projectLabel:r,projectDescription:o,projectIcon:a,projectColor:c,projectIconImage:l,projectIconBackground:d,isCollapsed:m,isActiveProject:f,isRepo:u,isDesktopShell:g,isStuck:b,hideDirectoryControls:h,alwaysShowActions:x,onToggle:y,onNewSession:p,onNewWorktreeSession:C,onRenameStart:v,onClose:k,sentinelRef:w,children:A,showCreateButtons:S,hideHeader:I,openSidebarMenuKey:D,setOpenSidebarMenuKey:N}=t,M=S===void 0?!0:S,P=I===void 0?!1:I,{t:E}=jt(),{currentTheme:V}=Lr();let R;e[0]!==n?(R={id:n},e[0]=n,e[1]=R):R=e[1];const{attributes:B,listeners:O,setNodeRef:F,transform:_,transition:ie,isDragging:oe}=Xl(R),ne=i.useRef(!1),Y=`project:${n}`,te=D===Y,[de,be]=i.useState(!1),ke=a?gc[a]:null,ae=c?Fa[c]??null:null;let ve;e[2]!==Y||e[3]!==N?(ve=se=>{se&&be(!1),N(se?Y:null)},e[2]=Y,e[3]=N,e[4]=ve):ve=e[4];const J=ve;let H;e[5]!==h||e[6]!==u||e[7]!==k||e[8]!==p||e[9]!==v||e[10]!==M||e[11]!==E?(H=se=>s.jsxs(s.Fragment,{children:[M&&!u&&!h&&p&&s.jsxs(se,{onClick:p,children:[s.jsx(T,{name:"add",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.newSession")]}),s.jsxs(se,{onClick:v,children:[s.jsx(T,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.session.menu.rename")]}),s.jsxs(se,{onClick:k,className:"text-destructive focus:text-destructive",children:[s.jsx(T,{name:"close",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.closeProject")]})]}),e[5]=h,e[6]=u,e[7]=k,e[8]=p,e[9]=v,e[10]=M,e[11]=E,e[12]=H):H=e[12];const q=H,ce=p2,fe=g2,De=x2;let Re;e[13]===Symbol.for("react.memo_cache_sentinel")?(Re=se=>{(se.button===2||se.button===0&&se.ctrlKey)&&(ne.current=!0)},e[13]=Re):Re=e[13];const Fe=Re;let Oe;e[14]!==y?(Oe=()=>{if(ne.current){ne.current=!1;return}y()},e[14]=y,e[15]=Oe):Oe=e[15];const Ee=Oe;let we;e[16]!==_?(we=Zl.Transform.toString(_),e[16]=_,e[17]=we):we=e[17];let Pe;e[18]!==we||e[19]!==ie?(Pe={transform:we,transition:ie},e[18]=we,e[19]=ie,e[20]=Pe):Pe=e[20];const Se=oe&&"opacity-30";let ue;e[21]!==Se?(ue=Te("relative",Se),e[21]=Se,e[22]=ue):ue=e[22];let K;e[23]!==x||e[24]!==B||e[25]!==V||e[26]!==J||e[27]!==Ee||e[28]!==h||e[29]!==P||e[30]!==ae||e[31]!==n||e[32]!==f||e[33]!==m||e[34]!==de||e[35]!==g||e[36]!==te||e[37]!==u||e[38]!==b||e[39]!==O||e[40]!==p||e[41]!==C||e[42]!==o||e[43]!==d||e[44]!==l||e[45]!==ke||e[46]!==r||e[47]!==q||e[48]!==w||e[49]!==M||e[50]!==E?(K=P?null:s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{ref:w,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsxs(vc,{open:de,onOpenChange:be,children:[s.jsx(wc,{render:s.jsx("div",{className:Te("w-full text-left group/project select-none"),style:{backgroundColor:g&&b?"transparent":void 0},onContextMenu:se=>{h||(se.preventDefault(),be(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...B,children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:Fe,onClick:Ee,...O,className:Te("flex-1 min-w-0 flex items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing transition-[padding]",u&&!h?x?"pr-20":"pr-7 group-hover/project:pr-20 group-focus-within/project:pr-20":x?"pr-14":"pr-7 group-hover/project:pr-14 group-focus-within/project:pr-14"),children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:[s.jsx("span",{className:Te("h-3.5 w-3.5 items-center justify-center text-muted-foreground",x?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:m?s.jsx(T,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(T,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),l?s.jsx("span",{className:Te("h-3.5 w-3.5 items-center justify-center overflow-hidden rounded-[3px]",x?"hidden":"inline-flex group-hover/project:hidden group-focus-within/project:hidden"),style:d?{backgroundColor:d}:void 0,children:s.jsx(La,{project:{id:n,iconImage:l},options:{themeVariant:V.metadata.variant,iconColor:V.colors.surface.foreground},className:"h-full w-full object-contain",fallback:ke?s.jsx(T,{name:ke,className:"h-3.5 w-3.5",style:ae?{color:ae}:void 0}):s.jsx(T,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:ae?{color:ae}:void 0})})}):ke?s.jsx(T,{name:ke,className:Te("h-3.5 w-3.5",x?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:ae?{color:ae}:void 0}):s.jsx(T,{name:"folder",className:Te("h-3.5 w-3.5 text-muted-foreground/80",x?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:ae?{color:ae}:void 0})]}),s.jsx("span",{className:Te("text-[14px] font-normal truncate lowercase",f?"text-foreground":"text-foreground group-hover/project:text-foreground"),children:r})]})}),s.jsx(Ct,{side:"right",sideOffset:8,children:o})]}),s.jsxs("div",{className:Te("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",M?"right-7":"right-0.5"),children:[M&&u&&!h&&C?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),C()},className:Te("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground transition-opacity",x?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E("sessions.sidebar.project.actions.newWorktree"),children:s.jsx(T,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,h?null:s.jsxs(Ws,{open:te,onOpenChange:J,children:[s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",te?"opacity-100 pointer-events-auto":x?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E("sessions.sidebar.project.actions.projectMenu"),onPointerDown:fe,onMouseDown:De,onClick:ce,children:s.jsx(T,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(zs,{align:"end",className:"min-w-[180px]",children:q(ls)})]})]}),M&&p?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:se=>{se.stopPropagation(),p()},className:Te("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",x?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E(u?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession"),children:s.jsx(T,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ct,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E(u?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(bc,{className:"min-w-[180px]",children:q(yc)})]})]}),e[23]=x,e[24]=B,e[25]=V,e[26]=J,e[27]=Ee,e[28]=h,e[29]=P,e[30]=ae,e[31]=n,e[32]=f,e[33]=m,e[34]=de,e[35]=g,e[36]=te,e[37]=u,e[38]=b,e[39]=O,e[40]=p,e[41]=C,e[42]=o,e[43]=d,e[44]=l,e[45]=ke,e[46]=r,e[47]=q,e[48]=w,e[49]=M,e[50]=E,e[51]=K):K=e[51];let he;return e[52]!==A||e[53]!==F||e[54]!==ue||e[55]!==K||e[56]!==Pe?(he=s.jsxs("div",{ref:F,style:Pe,className:ue,children:[K,A]}),e[52]=A,e[53]=F,e[54]=ue,e[55]=K,e[56]=Pe,e[57]=he):he=e[57],he},f2=t=>{const e=ht.c(21),{id:n,disabled:r,children:o}=t,a=r===void 0?!1:r;let c;e[0]!==a||e[1]!==n?(c={id:n,disabled:a},e[0]=a,e[1]=n,e[2]=c):c=e[2];const{listeners:l,setNodeRef:d,setActivatorNodeRef:m,transform:f,transition:u,isDragging:g}=Xl(c);let b;e[3]!==l||e[4]!==m?(b={listeners:l,setActivatorNodeRef:m},e[3]=l,e[4]=m,e[5]=b):b=e[5];const h=b;let x;e[6]!==f?(x=Zl.Transform.toString(f),e[6]=f,e[7]=x):x=e[7];let y;e[8]!==x||e[9]!==u?(y={transform:x,transition:u},e[8]=x,e[9]=u,e[10]=y):y=e[10];const p=g&&"opacity-50";let C;e[11]!==p?(C=Te("space-y-0.5 rounded-md",p),e[11]=p,e[12]=C):C=e[12];let v;e[13]!==o||e[14]!==h?(v=typeof o=="function"?o(h):o,e[13]=o,e[14]=h,e[15]=v):v=e[15];let k;return e[16]!==d||e[17]!==y||e[18]!==C||e[19]!==v?(k=s.jsx("div",{ref:d,style:y,className:C,children:v}),e[16]=d,e[17]=y,e[18]=C,e[19]=v,e[20]=k):k=e[20],k},h2=i.memo(f2);function p2(t){t.stopPropagation()}function g2(t){t.stopPropagation()}function x2(t){t.stopPropagation()}function b2(t){const e=ht.c(31),{t:n}=jt();let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={activationConstraint:{distance:8}},e[0]=r):r=e[0];let o;e[1]===Symbol.for("react.memo_cache_sentinel")?(o={coordinateGetter:Ah},e[1]=o):o=e[1];const a=aa(mo(la,r),mo(Ch,o));let c;e[2]===Symbol.for("react.memo_cache_sentinel")?(c={activationConstraint:{distance:8}},e[2]=c):c=e[2];const l=aa(mo(la,c));if(t.sharedSessionsOnly){const g=(t.mobileVariant,"");let b;e[3]!==g?(b=Te("space-y-1 pb-1 pr-2",g),e[3]=g,e[4]=b):b=e[4];const h=t.hasSharedSessions?null:t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;let x;return e[5]!==t.topContent||e[6]!==b||e[7]!==h?(x=s.jsxs(An,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:b,children:[t.topContent,h]}),e[5]=t.topContent,e[6]=b,e[7]=h,e[8]=x):x=e[8],x}if(t.projectSections.length===0){const g=(t.mobileVariant,"");let b;e[9]!==g?(b=Te("space-y-1 pb-1 pl-2.5 pr-2",g),e[9]=g,e[10]=b):b=e[10];let h;return e[11]!==t.emptyState||e[12]!==t.topContent||e[13]!==b?(h=s.jsxs(An,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:b,children:[t.topContent,t.emptyState]}),e[11]=t.emptyState,e[12]=t.topContent,e[13]=b,e[14]=h):h=e[14],h}if(t.sectionsForRender.length===0){const g=(t.mobileVariant,"");let b;e[15]!==g?(b=Te("space-y-1 pb-1 pl-2.5 pr-2",g),e[15]=g,e[16]=b):b=e[16];let h;return e[17]!==t.searchEmptyState||e[18]!==b?(h=s.jsx(An,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:b,children:t.searchEmptyState}),e[17]=t.searchEmptyState,e[18]=b,e[19]=h):h=e[19],h}const d=(t.mobileVariant,"");let m;e[20]!==d?(m=Te("space-y-1 pb-1 pl-2.5 pr-2",d),e[20]=d,e[21]=m):m=e[21];let f;e[22]!==l||e[23]!==a||e[24]!==t||e[25]!==n?(f=t.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const g=t.sectionsForRender.find(y=>y.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!g)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const b=g.groups.find(C2)??g.groups.find(k2)??g.groups.find(N2)??g.groups[0];if(!b)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:n("sessions.sidebar.empty.noSessions.title")});const h=g.groups.find(S2);return[b,...h&&h.id!==b.id?[h]:[]].map(y=>{const p=`${g.project.id}:${y.id}`,C=y.id===b.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(y,p,g.project.id,C,null,!0)},p)})})()}):s.jsx(s.Fragment,{children:s.jsxs(ca,{sensors:a,collisionDetection:da,onDragEnd:g=>{if(t.isInlineEditing)return;const{active:b,over:h}=g;if(!h||b.id===h.id)return;const x=t.sectionsForRender.findIndex(p=>p.project.id===b.id),y=t.sectionsForRender.findIndex(p=>p.project.id===h.id);x===-1||y===-1||x===y||t.reorderProjects(x,y)},children:[s.jsx(Al,{items:t.sectionsForRender.map(j2),strategy:Dl,children:t.sectionsForRender.map(g=>{const b=g.project,h=b.id,x=tf(b.label?.trim()||Ci(b.normalizedPath,t.homeDirectory)||b.normalizedPath),y=pa(b.normalizedPath,t.homeDirectory),p=t.collapsedProjects.has(h),C=h===t.activeProjectId,v=t.projectRepoStatus.get(h),k=t.getOrderedGroups(h,g.groups),w=k.find(v2)??null,A=w?k.filter(S=>S.id!==w.id):k;return s.jsx(m2,{id:h,projectLabel:x,projectDescription:y,projectIcon:b.icon,projectColor:b.color,projectIconImage:b.iconImage,projectIconBackground:b.iconBackground,isCollapsed:p,isActiveProject:C,isRepo:!!v,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(h),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,alwaysShowActions:t.alwaysShowActions,onToggle:()=>t.toggleProject(h),onNewSession:()=>{h!==t.activeProjectId&&t.setActiveProjectIdOnly(h),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:b.normalizedPath})},onNewWorktreeSession:()=>{h!==t.activeProjectId&&t.setActiveProjectIdOnly(h),t.setActiveMainTab("chat"),t.openNewWorktreeDialog()},onRenameStart:()=>t.openProjectEditDialog(h),onClose:()=>t.removeProject(h),sentinelRef:S=>{t.projectHeaderSentinelRefs.current.set(h,S)},showCreateButtons:!0,openSidebarMenuKey:t.openSidebarMenuKey,setOpenSidebarMenuKey:t.setOpenSidebarMenuKey,children:p?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:g.groups.length>0?s.jsxs(ca,{sensors:l,collisionDetection:da,onDragEnd:S=>{if(t.isInlineEditing)return;const{active:I,over:D}=S;if(!D||I.id===D.id)return;const N=A.findIndex(V=>V.id===I.id),M=A.findIndex(V=>V.id===D.id);if(N===-1||M===-1||N===M)return;const P=um(A,N,M).map(w2),E=w?[w.id,...P]:P;t.setGroupOrderByProject(V=>{const R=new Map(V);return R.set(h,E),R})},children:[w?t.renderGroupSessions(w,`${h}:${w.id}`,h,!0):null,s.jsx(Al,{items:A.map(y2),strategy:Dl,children:A.map(S=>{const I=`${h}:${S.id}`;return s.jsx(h2,{id:S.id,disabled:t.isInlineEditing,children:D=>t.renderGroupSessions(S,I,h,!1,D)},S.id)})}),s.jsx(Pl,{dropAnimation:null})]}):s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:n("sessions.sidebar.empty.noSessions.title")})})},h)})}),s.jsx(Pl,{dropAnimation:null})]})}),e[22]=l,e[23]=a,e[24]=t,e[25]=n,e[26]=f):f=e[26];let u;return e[27]!==t.topContent||e[28]!==m||e[29]!==f?(u=s.jsxs(An,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:m,children:[t.topContent,f]}),e[27]=t.topContent,e[28]=m,e[29]=f,e[30]=u):u=e[30],u}function y2(t){return t.id}function w2(t){return t.id}function v2(t){return t.isMain}function j2(t){return t.project.id}function S2(t){return t.isArchivedBucket}function N2(t){return t.isMain}function k2(t){return t.sessions.length>0}function C2(t){return t.isMain&&t.sessions.length>0}function A2(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(Ki(),{month:"short"}),r=e.getDate(),o=e.getFullYear(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${a}:${c}`}function D2(t){if(t.info.role==="user")return"";const e=typeof t.info.providerID=="string"?t.info.providerID.trim():"",n=typeof t.info.modelID=="string"?t.info.modelID.trim():"";return e&&n?`${e}/${n}`:n||e}function T2(t){const e=t.info.role==="user"?"User":"Assistant",n=A2(t.info.time?.created),r=D2(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
170
-
171
- *${o}*`:`**${e}**`}function P2(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function Uf(t){const e=T2(t),n=P2(t.parts).trim();return n?`${e}
172
-
173
- ${n}`:""}function Hf(t,e){const n="#".repeat(Math.min(e+1,6)),r=t.agent?` — ${t.agent}`:"",o=`${n} Sub-agent: ${t.title}${r}
174
-
175
- ---
176
-
177
- `,a=t.records.map(Uf).filter(Boolean).join(`
178
-
179
- ---
180
-
181
- `),c=[o+a];for(const l of t.children)c.push(Hf(l,e+1));return c.join(`
182
-
183
- ---
184
-
185
- `)}function I2(t,e,n){const r=e?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
186
-
187
- *Exported on ${o}*
188
-
189
- ---
190
-
191
- `,c=t.map(Uf).filter(Boolean).join(`
192
-
193
- ---
194
-
195
- `);let l=a+c;if(n&&n.length>0){const d=n.map(m=>Hf(m,1)).join(`
196
-
197
- ---
198
-
199
- `);l+=`
200
-
201
- ---
202
-
203
- `+d}return l}function R2(t,e){const n=new Blob([t],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function E2(t,e){const n=await zh(e,t);if(n)return n;if(!Fr())return null;try{const r=await To()?.vscode?.saveMarkdown?.({fileName:e,content:t});if(!r||r.saved!==!0)return null;const o=typeof r.path=="string"?r.path.trim():"";return o.length>0?o:null}catch{return null}}async function M2(t){const e=To()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await Wh(t)?!0:ua(t)}function F2(){return mc()}function L2(t){const r=(t?.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 O2=(t,e)=>{if(!e)return Array.from(t);const n=[],r=new Set;for(const o of t){r.has(o)||(r.add(o),n.push(o));const a=e.get(o);if(a)for(const c of a)r.has(c)||(r.add(c),n.push(c))}return n},Gn=Zi()((t,e)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{e().enabled||t({enabled:!0})},disable:()=>{t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{e().enabled?t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):t({enabled:!0})},toggleSelected:(n,r,o)=>{const a=e(),c=new Set(a.selectedIds);let l=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(c.clear(),l=r,d=null):l===null&&r!==null&&(l=r);const f=o&&o.length>0?[n,...o]:[n];if(c.has(n)){for(const g of f)c.delete(g);d===n&&(d=null)}else{for(const g of f)c.add(g);d=n}c.size===0?t({selectedIds:c,scopeKey:null,anchorId:null}):t({selectedIds:c,scopeKey:l,anchorId:d})},setRange:(n,r,o,a,c)=>{const l=e();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],m=o.indexOf(d),f=o.indexOf(r);if(m<0||f<0)return;const[u,g]=m<=f?[m,f]:[f,m],b=o.slice(u,g+1),h=O2(b,c),y=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const p of h)y.add(p);t({selectedIds:y,scopeKey:a??l.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){t({selectedIds:new Set,scopeKey:null,anchorId:null});return}t({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{t({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=e();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?t({selectedIds:o,scopeKey:null,anchorId:null}):t({selectedIds:o}))}})),B2=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,Gf=/^g[1-9]\d*$/,co=(t,e,n,r,o)=>{if(!B2.test(t)||e!==void 0&&!Gf.test(e)||!n?.trim()||!r?.trim()||n!==n.trim()||r!==r.trim())return null;if(o===void 0)return{groupSlug:t,runGroup:e,providerID:n,modelID:r,fusion:!1};if(o==="fusion")return{groupSlug:t,runGroup:e,providerID:n,modelID:r,fusion:!0};if(!/^\d+$/.test(o))return null;const a=Number.parseInt(o,10);return!Number.isSafeInteger(a)||a<=0?null:{groupSlug:t,runGroup:e,providerID:n,modelID:r,index:a,fusion:!1}},ia=t=>{if(!t)return null;const e=t.split("/");if(e.length<3||e.length>5)return null;const[n]=e;if(e.length===3)return co(n,void 0,e[1],e[2],void 0);if(e.length===4){const[,l,d,m]=e;return Gf.test(l)?co(n,l,d,m,void 0):co(n,void 0,l,d,m)}const[,r,o,a,c]=e;return r===""?co(n,void 0,o,a,c):co(n,r,o,a,c)},_2=t=>{const e=[t.groupSlug];return t.runGroup&&e.push(t.runGroup),e.push(t.providerID,t.modelID),t.index!==void 0&&e.push(String(t.index)),e.join("/")},V2=(t,e,n,r)=>{const o=[t];return r&&o.push(r),o.push(e,n,"fusion"),o.join("/")},Kf=t=>{const e=ht.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=jt(),m=Ut($2),f=Ut(z2),u=Ut(W2);let g;e[0]!==m?(g=m(),e[0]=m,e[1]=g):g=e[1];const b=g;let h;e[2]!==b?(h=b.filter(U2),e[2]=b,e[3]=h):h=e[3];const x=h;let y,p;e[4]!==b.length||e[5]!==f?(y=()=>{b.length===0&&f()},p=[b.length,f],e[4]=b.length,e[5]=f,e[6]=y,e[7]=p):(y=e[6],p=e[7]),i.useEffect(y,p);let C,v;e[8]!==u||e[9]!==a||e[10]!==r||e[11]!==x||e[12]!==n?(C=()=>{if(a)return;const P=n.trim();if(P.length>0&&x.some(R=>R.name===P))return;const E=typeof u=="string"&&u.trim().length>0?u.trim():null;if(E&&x.some(R=>R.name===E)){r(E);return}const V=x[0]?.name;V&&r(V)},v=[u,a,r,x,n],e[8]=u,e[9]=a,e[10]=r,e[11]=x,e[12]=n,e[13]=C,e[14]=v):(C=e[13],v=e[14]),i.useEffect(C,v);const k=n.trim().length>0?n:void 0;let w;e[15]!==o?(w=Te("max-w-full typography-meta text-foreground !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 data-[popup-open]:!bg-[var(--interactive-active)]/70",o),e[15]=o,e[16]=w):w=e[16];let A;e[17]!==d?(A=d("multirun.agentSelector.placeholder"),e[17]=d,e[18]=A):A=e[18];let S;e[19]!==A?(S=s.jsx(fn,{placeholder:A}),e[19]=A,e[20]=S):S=e[20];let I;e[21]!==c||e[22]!==w||e[23]!==S?(I=s.jsx(Tn,{id:c,size:"lg",className:w,children:S}),e[21]=c,e[22]=w,e[23]=S,e[24]=I):I=e[24];let D;e[25]!==x?(D=x.length>0&&s.jsx(Rl,{children:x.map(H2)}),e[25]=x,e[26]=D):D=e[26];let N;e[27]!==l||e[28]!==D?(N=s.jsx(Pn,{fitContent:!0,portalToBody:l,children:D}),e[27]=l,e[28]=D,e[29]=N):N=e[29];let M;return e[30]!==a||e[31]!==r||e[32]!==k||e[33]!==I||e[34]!==N?(M=s.jsxs(Dn,{value:k,onValueChange:r,disabled:a,children:[I,N]}),e[30]=a,e[31]=r,e[32]=k,e[33]=I,e[34]=N,e[35]=M):M=e[35],M};function $2(t){return t.getVisibleAgents}function z2(t){return t.loadAgents}function W2(t){return t.currentAgentName}function U2(t){return t.mode!=="subagent"}function H2(t){return s.jsx(vs,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const qf="h-7",vo=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,G2=t=>{const e=ht.c(12),{model:n,instanceIndex:r,totalSameModel:o,onRemove:a}=t,c=n.displayName||`${n.providerID}/${n.modelID}`,l=o>1?`${c} (${r})`:c;let d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=Te("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",qf),e[0]=d):d=e[0];let m;e[1]!==n.providerID?(m=s.jsx(jo,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=m):m=e[2];let f;e[3]!==l?(f=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=f):f=e[4];let u;e[5]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(T,{name:"close",className:"h-3.5 w-3.5"}),e[5]=u):u=e[5];let g;e[6]!==a?(g=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:u}),e[6]=a,e[7]=g):g=e[7];let b;return e[8]!==m||e[9]!==f||e[10]!==g?(b=s.jsxs("div",{className:d,children:[m,f,g]}),e[8]=m,e[9]=f,e[10]=g,e[11]=b):b=e[11],b},Yf=t=>{const e=ht.c(118),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:m,addButtonClassName:f,dropdownSide:u,dropdownClassName:g,containerClassName:b,triggerIcon:h}=t,x=d===void 0?!0:d,y=u===void 0?"top":u,{t:p}=jt(),C=Ut(K2),v=Ut(q2),k=Me(Y2),w=Me(J2),{favoriteModelsList:A,recentModelsList:S}=ng(),I=Me(Q2),[D,N]=i.useState(!1),[M,P]=i.useState(""),[E,V]=i.useState(null),R=i.useRef(null),B=i.useRef(null),O=m===1,F=m===void 0||n.length<m||O;let _;if(e[0]!==n){_=new Map;for(const L of n){const xe=`${L.providerID}:${L.modelID}`;_.set(xe,(_.get(xe)||0)+1)}e[0]=n,e[1]=_}else _=e[1];const ie=_;let oe;e[2]!==n?(oe=L=>n.filter(Q=>Q.providerID===L.providerID&&Q.modelID===L.modelID).findIndex(Q=>Q.instanceId===L.instanceId)+1,e[2]=n,e[3]=oe):oe=e[3];const ne=oe;let Y,te;e[4]!==y||e[5]!==D?(Y=()=>{if(!D||!B.current)return;const L=B.current.getBoundingClientRect();if(y==="bottom"){const qe=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-L.bottom-16-112;V(Math.max(160,Math.min(320,qe)));return}let xe=B.current.parentElement;for(;xe&&!(xe.getAttribute("role")==="dialog"||xe.hasAttribute("data-scroll-shadow"));){const He=getComputedStyle(xe);if(He.overflow==="auto"||He.overflow==="hidden"||He.overflowY==="auto"||He.overflowY==="hidden")break;xe=xe.parentElement}const Q=xe?xe.getBoundingClientRect().top:0,$e=L.top-Q-16;V(Math.max(150,Math.min(300,$e)))},te=[y,D],e[4]=y,e[5]=D,e[6]=Y,e[7]=te):(Y=e[6],te=e[7]),i.useEffect(Y,te);let de,be;e[8]!==F||e[9]!==D?(de=()=>{!F&&D&&(N(!1),P(""))},be=[F,D],e[8]=F,e[9]=D,e[10]=de,e[11]=be):(de=e[10],be=e[11]),i.useEffect(de,be);let ke,ae;e[12]!==D?(ke=()=>{if(!D)return;const L=xe=>{R.current&&!R.current.contains(xe.target)&&(N(!1),P(""))};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},ae=[D],e[12]=D,e[13]=ke,e[14]=ae):(ke=e[13],ae=e[14]),i.useEffect(ke,ae);let ve;e[15]!==O||e[16]!==r||e[17]!==a||e[18]!==n.length?(ve=L=>{const xe={providerID:L.providerID,modelID:L.modelID,displayName:L.model.name||L.modelID,instanceId:vo()};O&&n.length>0&&a?a(0,xe):r(xe),O&&(N(!1),P(""))},e[15]=O,e[16]=r,e[17]=a,e[18]=n.length,e[19]=ve):ve=e[19];const J=ve;let H;e[20]!==p?(H=p("multirun.modelMultiSelect.search.placeholder"),e[20]=p,e[21]=H):H=e[21];let q;e[22]!==p?(q=p("multirun.modelMultiSelect.search.noResults"),e[22]=p,e[23]=q):q=e[23];let ce;e[24]!==p?(ce=p("multirun.modelMultiSelect.sections.favorites"),e[24]=p,e[25]=ce):ce=e[25];let fe;e[26]!==p?(fe=p("multirun.modelMultiSelect.sections.recent"),e[26]=p,e[27]=fe):fe=e[27];let De;e[28]!==p?(De=p("multirun.modelMultiSelect.keyboard.hint"),e[28]=p,e[29]=De):De=e[29];let Re;e[30]!==p?(Re=p("settings.agents.modelSelector.actions.favorite"),e[30]=p,e[31]=Re):Re=e[31];let Fe;e[32]!==p?(Fe=p("settings.agents.modelSelector.actions.unfavorite"),e[32]=p,e[33]=Fe):Fe=e[33];let Oe;e[34]!==p?(Oe=p("chat.modelControls.capabilities"),e[34]=p,e[35]=Oe):Oe=e[35];let Ee;e[36]!==p?(Ee=p("chat.modelControls.capability.toolCalling"),e[36]=p,e[37]=Ee):Ee=e[37];let we;e[38]!==p?(we=p("chat.modelControls.capability.reasoning"),e[38]=p,e[39]=we):we=e[39];let Pe;e[40]!==p?(Pe=p("chat.modelControls.input"),e[40]=p,e[41]=Pe):Pe=e[41];let Se;e[42]!==p?(Se=p("chat.modelControls.output"),e[42]=p,e[43]=Se):Se=e[43];let ue;e[44]!==p?(ue=p("chat.modelControls.costPerMillion"),e[44]=p,e[45]=ue):ue=e[45];let K;e[46]!==H||e[47]!==q||e[48]!==ce||e[49]!==fe||e[50]!==De||e[51]!==Re||e[52]!==Fe||e[53]!==Oe||e[54]!==Ee||e[55]!==we||e[56]!==Pe||e[57]!==Se||e[58]!==ue?(K={searchPlaceholder:H,noResults:q,favorites:ce,recent:fe,keyboardHint:De,favorite:Re,unfavorite:Fe,capabilities:Oe,capabilityToolCalling:Ee,capabilityReasoning:we,input:Pe,output:Se,costPerMillion:ue},e[46]=H,e[47]=q,e[48]=ce,e[49]=fe,e[50]=De,e[51]=Re,e[52]=Fe,e[53]=Oe,e[54]=Ee,e[55]=we,e[56]=Pe,e[57]=Se,e[58]=ue,e[59]=K):K=e[59];const he=K;let se;e[60]!==b?(se=Te("relative",b),e[60]=b,e[61]=se):se=e[61];let G;e[62]!==f?(G=Te(qf,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",f),e[62]=f,e[63]=G):G=e[63];const $=!F;let pe;e[64]!==D?(pe=()=>{N(!D)},e[64]=D,e[65]=pe):pe=e[65];let ye;e[66]!==h?(ye=h??s.jsx(T,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=h,e[67]=ye):ye=e[67];let z;e[68]!==l||e[69]!==p?(z=l??p("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=p,e[70]=z):z=e[70];let Ne;e[71]!==G||e[72]!==$||e[73]!==pe||e[74]!==ye||e[75]!==z?(Ne=s.jsxs(ze,{ref:B,type:"button",variant:"outline",size:"sm",className:G,disabled:$,onClick:pe,children:[ye,z]}),e[71]=G,e[72]=$,e[73]=pe,e[74]=ye,e[75]=z,e[76]=Ne):Ne=e[76];let U;e[77]!==E||e[78]!==F||e[79]!==g||e[80]!==y||e[81]!==A||e[82]!==J||e[83]!==I||e[84]!==w||e[85]!==D||e[86]!==he||e[87]!==ie||e[88]!==v||e[89]!==C||e[90]!==S||e[91]!==M||e[92]!==k?(U=D?s.jsx("div",{className:Te("absolute left-0 z-50 w-[min(420px,calc(100vw-2rem))] max-w-[calc(100vw-2rem)] flex flex-col overflow-hidden rounded-xl border border-border/50 shadow-lg",y==="top"?"bottom-full mb-1":"top-full mt-1",g),style:{background:"linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))"},children:s.jsx(rg,{providers:C,favoriteModels:A,recentModels:S,modelsMetadata:v,hiddenModels:I,searchQuery:M,onSearchQueryChange:P,onSelect:J,labels:he,selectionCount:L=>ie.get(`${L.providerID}:${L.modelID}`)||0,disabled:!F,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:E?`${E}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:D,isFavorite:L=>w(L.providerID,L.modelID),onToggleFavorite:L=>k(L.providerID,L.modelID),onEscape:()=>{N(!1),P("")}})}):null,e[77]=E,e[78]=F,e[79]=g,e[80]=y,e[81]=A,e[82]=J,e[83]=I,e[84]=w,e[85]=D,e[86]=he,e[87]=ie,e[88]=v,e[89]=C,e[90]=S,e[91]=M,e[92]=k,e[93]=U):U=e[93];let Ie;e[94]!==se||e[95]!==Ne||e[96]!==U?(Ie=s.jsxs("div",{className:se,ref:R,children:[Ne,U]}),e[94]=se,e[95]=Ne,e[96]=U,e[97]=Ie):Ie=e[97];let _e;e[98]!==ne||e[99]!==ie||e[100]!==o||e[101]!==a||e[102]!==C||e[103]!==n||e[104]!==x||e[105]!==p?(_e=x&&n.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:n.map((L,xe)=>{const Q=`${L.providerID}:${L.modelID}`,$e=ie.get(Q)||1,He=ne(L),qe=C.find(Be=>Be.id===L.providerID)?.models?.find(Be=>Be.id===L.modelID),Xe=qe?.variants?Object.keys(qe.variants):[],lt=Xe.length>0,bt=L.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(G2,{model:L,instanceIndex:He,totalSameModel:$e,onRemove:()=>o(xe)}),lt&&s.jsxs(Dn,{value:bt,onValueChange:Be=>{if(!a)return;a(xe,{...L,variant:Be==="__default__"?void 0:Be})},children:[s.jsxs(Tn,{size:"chip",className:"px-2 gap-1.5 rounded-md !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground",children:[s.jsx(T,{name:"brain-ai-3",className:Te("h-3.5 w-3.5 flex-shrink-0",bt==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(fn,{placeholder:p("multirun.modelMultiSelect.variant.placeholder"),children:Be=>Be==="__default__"?p("multirun.modelMultiSelect.variant.default"):Be})]}),s.jsxs(Pn,{fitContent:!0,children:[s.jsx(vs,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:p("multirun.modelMultiSelect.variant.default")}),Xe.map(X2)]})]})]},L.instanceId)})}),e[98]=ne,e[99]=ie,e[100]=o,e[101]=a,e[102]=C,e[103]=n,e[104]=x,e[105]=p,e[106]=_e):_e=e[106];let Ve;e[107]!==Ie||e[108]!==_e?(Ve=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[Ie,_e]}),e[107]=Ie,e[108]=_e,e[109]=Ve):Ve=e[109];let Le;e[110]!==m||e[111]!==c||e[112]!==n.length||e[113]!==p?(Le=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:m!==void 0?p("multirun.modelMultiSelect.validation.minToMax",{min:c,max:m}):p("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[110]=m,e[111]=c,e[112]=n.length,e[113]=p,e[114]=Le):Le=e[114];let X;return e[115]!==Ve||e[116]!==Le?(X=s.jsxs("div",{className:"space-y-2",children:[Ve,Le]}),e[115]=Ve,e[116]=Le,e[117]=X):X=e[117],X};function K2(t){return t.providers}function q2(t){return t.modelsMetadata}function Y2(t){return t.toggleFavoriteModel}function J2(t){return t.isFavoriteModel}function Q2(t){return t.hiddenModels}function X2(t){return s.jsx(vs,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const Z2=(t,e,n)=>{const r=t.session.title?.trim()||t.session.id;return`
204
-
205
- --- RESULT ${n+1}: ${r} ---
206
- ${e.trim()}
207
- --- END RESULT ${n+1} ---`},Gu=(t,e)=>mt.getState().getWorktreeMetadata(t)?.projectDirectory??e,eN=async t=>{const e=t.directory??void 0,n=ig(t.session.id,e);if(n.length===0&&t.directory){const o=(await Cn.withDirectory(t.directory,()=>Cn.getSdkClient().session.messages({sessionID:t.session.id,directory:t.directory??void 0,limit:50}))).data??[];for(let a=o.length-1;a>=0;a-=1){const c=o[a];if(c.info?.role==="assistant")return bd(c.parts??[]).trim()}return""}for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o.role==="assistant")return bd(og(o.id,e)).trim()}return""};function tN({session:t,open:e,onOpenChange:n}){const{t:r}=jt(),o=ic(),a=gr(F=>F.activeSessions),c=gr(F=>F.archivedSessions),l=Ut(F=>F.providers),d=Ut(F=>F.currentProviderId),m=Ut(F=>F.currentModelId),f=Ut(F=>F.currentAgentName),[u,g]=i.useState(d??""),[b,h]=i.useState(m??""),[x,y]=i.useState(()=>d&&m?[{providerID:d,modelID:m,instanceId:vo()}]:[]),[p,C]=i.useState(""),[v,k]=i.useState(f??""),[w,A]=i.useState([]),[S,I]=i.useState(!1),D=i.useMemo(()=>ia(t.title),[t.title]),N=i.useMemo(()=>{const F=new Map;for(const _ of o)F.set(_.id,_);for(const _ of a)F.set(_.id,_);for(const _ of c)F.set(_.id,_);return t.id&&F.set(t.id,t),Array.from(F.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!D)return;const F=mt.getState().getDirectoryForSession(t.id),_=Gu(t.id,F),ie=N.map(oe=>{const ne=ia(oe.title);if(!ne||ne.groupSlug!==D.groupSlug||ne.fusion||(ne.runGroup??null)!==(D.runGroup??null))return null;const Y=mt.getState().getDirectoryForSession(oe.id)??kr(oe),te=Gu(oe.id,Y);return _&&te&&_!==te?null:{session:oe,directory:Y,projectDirectory:te}}).filter(oe=>oe!==null).sort((oe,ne)=>(oe.session.time?.created??0)-(ne.session.time?.created??0));A(ie)},[N,e,D,t.id]);const P=l.find(F=>F.id===u)?.models.find(F=>F.id===b),E=P?.variants?Object.keys(P.variants):[],V=!!(D&&u&&b&&w.length>0&&!S),R=i.useCallback(F=>{y([F]),g(F.providerID),h(F.modelID),C("")},[]),B=x[0]?.displayName||x[0]?.modelID||r("multirun.fusion.model.placeholder"),O=async()=>{if(!(!D||!u||!b)){I(!0);try{const F=await Promise.all(w.map(de=>eN(de))),_=w.map((de,be)=>({source:de,text:F[be]??""})).filter(de=>de.text.trim().length>0);if(_.length===0){me.error(r("multirun.fusion.toast.noOutputs"));return}const ie=w[0]?.projectDirectory??w[0]?.directory??null,oe=V2(D.groupSlug,u,b,D.runGroup),[ne,Y]=await Promise.all([vn("session.fusion.visible"),vn("session.fusion.instructions")]),te=await mt.getState().createSession(oe,ie,null);if(!te)throw new Error("Failed to create fusion session");mt.getState().setCurrentSession(te.id,ie),n(!1),await Cn.sendMessage({id:te.id,providerID:u,modelID:b,variant:p||void 0,agent:v||void 0,text:ne,additionalParts:[{text:Y,synthetic:!0},..._.map((de,be)=>({text:Z2(de.source,de.text,be),synthetic:!0})),{text:`
208
-
209
- --- FUSION INPUTS END ---
210
- Now write the final fused answer.`,synthetic:!0}],directory:ie??Cn.getDirectory()})}catch(F){console.error("[MultiRunFusion] Failed to start fusion",F),me.error(r("multirun.fusion.toast.failed"))}finally{I(!1)}}};return s.jsx(Cs,{open:e,onOpenChange:n,children:s.jsxs(ks,{className:"max-w-xl overflow-visible",children:[s.jsxs(Ms,{children:[s.jsx(Ps,{children:r("multirun.fusion.title")}),s.jsx(qs,{children:r("multirun.fusion.description")})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("div",{className:"max-w-full",children:s.jsx(Yf,{selectedModels:x,onAdd:R,onUpdate:(F,_)=>R(_),onRemove:()=>{y([]),g(""),h(""),C("")},maxModels:1,addButtonLabel:B,showChips:!1,addButtonClassName:"h-8 w-fit max-w-[min(28rem,calc(100vw-8rem))] justify-start rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5",dropdownSide:"bottom",dropdownClassName:"w-[min(28rem,calc(100vw-8rem))]",triggerIcon:u?s.jsx(jo,{providerId:u,className:"h-3.5 w-3.5 mr-1"}):void 0})}),E.length>0?s.jsxs(Dn,{value:p||"__default__",onValueChange:F=>C(F==="__default__"?"":F),children:[s.jsxs(Tn,{size:"lg",className:"h-8 w-fit rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground px-3 py-1.5",children:[s.jsx(T,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(fn,{children:F=>F==="__default__"?r("multirun.modelMultiSelect.variant.default"):F})]}),s.jsxs(Pn,{fitContent:!0,portalToBody:!0,children:[s.jsx(vs,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),E.map(F=>s.jsx(vs,{value:F,children:F},F))]})]}):null,s.jsx(Kf,{value:v,onChange:k,portalToBody:!0,className:"h-8 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta font-medium text-foreground",children:r("multirun.fusion.sources.label",{count:w.length})}),s.jsx("div",{className:"max-h-56 space-y-1 overflow-auto rounded-lg border border-[var(--interactive-border)] p-1",children:w.map(F=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(jo,{providerId:ia(F.session.title)?.providerID??"",className:"h-4 w-4"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:F.session.title||F.session.id}),s.jsx("button",{type:"button",onClick:()=>A(_=>_.filter(ie=>ie.session.id!==F.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(T,{name:"close",className:"h-4 w-4"})})]},F.session.id))})]}),s.jsxs(qn,{children:[s.jsx(ze,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx(ze,{onClick:O,disabled:!V,children:r(S?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function sN(t){const e=ht.c(7);let n,r,o,a,c;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("path",{d:"M12 4.5v6.25M12 10.75v3.5M12 10.75H7.25A3.25 3.25 0 0 0 4 14v1.25M12 10.75h4.75A3.25 3.25 0 0 1 20 14v1.25",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),r=s.jsx("path",{d:"M9.25 7.25 12 4.5l2.75 2.75",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),o=s.jsx("circle",{cx:"4",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),a=s.jsx("circle",{cx:"12",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),c=s.jsx("circle",{cx:"20",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),e[0]=n,e[1]=r,e[2]=o,e[3]=a,e[4]=c):(n=e[0],r=e[1],o=e[2],a=e[3],c=e[4]);let l;return e[5]!==t?(l=s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",...t,children:[n,r,o,a,c]}),e[5]=t,e[6]=l):l=e[6],l}const Ku=t=>t.children.length===0?"":t.children.map(e=>`${e.session.id}:${e.children.length}`).join("|"),gi=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if(gi(n,e))return!0;return!1},ql=(t,e,n,r)=>{if(!e)return!1;if(`${n}:${r?"archived":"active"}:${t.session.id}`===e)return!0;for(const a of t.children)if(ql(a,e,n,r))return!0;return!1},nN=(t,e)=>{const n=t.node.session,r=e.node.session,o=n.id,a=r.id;if(o!==a||t.node.session!==e.node.session||Ku(t.node)!==Ku(e.node)||t.depth!==e.depth||t.groupDirectory!==e.groupDirectory||t.projectId!==e.projectId||t.archivedBucket!==e.archivedBucket)return!1;if(t.currentSessionId!==e.currentSessionId){const f=gi(t.node,t.currentSessionId),u=gi(e.node,e.currentSessionId);if(f||u)return!1}if(t.pinnedSessionIds.has(o)!==e.pinnedSessionIds.has(a))return!1;{const f=t.renderContext??"project",u=e.renderContext??"project",g=t.archivedBucket??!1,b=e.archivedBucket??!1,h=`${f}:${g?"archived":"active"}:${o}`,x=`${u}:${b?"archived":"active"}:${a}`;if(t.expandedParents.has(h)!==e.expandedParents.has(x))return!1}if(t.hasSessionSearchQuery!==e.hasSessionSearchQuery||t.normalizedSessionSearchQuery!==e.normalizedSessionSearchQuery||t.notifyOnSubtasks!==e.notifyOnSubtasks)return!1;if(t.editingId!==e.editingId){const f=gi(t.node,t.editingId),u=gi(e.node,e.editingId);if(f||u)return!1}if(t.editTitle!==e.editTitle){const f=gi(t.node,t.editingId),u=gi(e.node,e.editingId);if(f||u)return!1}if(t.copiedSessionId===o!=(e.copiedSessionId===a))return!1;const c=ql(t.node,t.openSidebarMenuKey,t.renderContext??"project",t.archivedBucket??!1),l=ql(e.node,e.openSidebarMenuKey,e.renderContext??"project",e.archivedBucket??!1);if(c!==l)return!1;const d=Gt(n.directory??null)??Gt(t.groupDirectory??null),m=Gt(r.directory??null)??Gt(e.groupDirectory??null);return!(d!==m||(t.secondaryMeta?.projectLabel??null)!==(e.secondaryMeta?.projectLabel??null)||(t.secondaryMeta?.branchLabel??null)!==(e.secondaryMeta?.branchLabel??null)||t.mobileVariant!==e.mobileVariant||t.alwaysShowActions!==e.alwaysShowActions||(t.renderContext??"project")!==(e.renderContext??"project")||t.renamingFolderId!==e.renamingFolderId)};function rN(t){const{t:e}=jt(),{node:n,depth:r=0,groupDirectory:o,projectId:a,archivedBucket:c=!1,currentSessionId:l,pinnedSessionIds:d,expandedParents:m,hasSessionSearchQuery:f,normalizedSessionSearchQuery:u,notifyOnSubtasks:g,editingId:b,setEditingId:h,editTitle:x,setEditTitle:y,handleSaveEdit:p,handleCancelEdit:C,toggleParent:v,handleSessionSelect:k,handleSessionDoubleClick:w,togglePinnedSession:A,handleShareSession:S,copiedSessionId:I,handleCopyShareUrl:D,handleUnshareSession:N,openSidebarMenuKey:M,setOpenSidebarMenuKey:P,renamingFolderId:E,getFoldersForScope:V,getSessionFolderId:R,removeSessionFromFolder:B,addSessionToFolder:O,createFolderAndStartRename:F,openContextPanelTab:_,handleDeleteSession:ie,mobileVariant:oe,alwaysShowActions:ne,renderSessionNode:Y,secondaryMeta:te,renderContext:de="project"}=t,be=!!te?.projectLabel,ke=!!te?.branchLabel,ae=jr(Ae=>Ae.displayMode),ve=i.useMemo(()=>Fr(),[]),J=ae==="minimal"||ve,H=i.useMemo(()=>Na(),[]),q=i.useContext(ag),ce=ve?"group-hover:opacity-100 group-hover:pointer-events-auto":"group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto",fe=ve?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",De=ve,Re=!c&&!oe,Fe=J?ve?Re&&De?"group-hover:pr-18":Re||De?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":ve?Re&&De?"group-hover:pr-18":Re||De?"group-hover:pr-12":"group-hover:pr-5":Re?"group-hover:pr-12 group-focus-within:pr-12":"group-hover:pr-5 group-focus-within:pr-5",Oe=Re?"pr-13":"pr-7",Ee=i.useRef(!1),[we,Pe]=i.useState(!1),Se=i.useRef(b);Se.current=b;const ue=i.useRef(null),K=i.useRef(p);K.current=p;const he=i.useRef(null),se=n.session,$=rc(se.id)??se,pe=Gt(se.directory??null)??Gt(o??null),ye=lg(pe??void 0,{bootstrap:!c}),z=xc(),Ne=Gn(Ae=>Ae.enabled),U=Gn(i.useCallback(Ae=>Ae.selectedIds.has(se.id),[se.id])),Ie=Gn(Ae=>Ae.toggleSelected),_e=Gn(Ae=>Ae.setRange),Ve=i.useCallback(Ae=>{const xt=[],rt=_t=>{_t.children.forEach(Vt=>{xt.push(Vt.session.id),rt(Vt)})};return rt(Ae),xt},[]),[Le,X]=i.useState(!1),[L,xe]=i.useState(!0),Q=`${de}:${c?"archived":"active"}:${se.id}`,$e=$m(i.useCallback(Ae=>!!Ae.sessionMemoryState.get(cg(se.id))?.isZombie,[se.id])),He=dg(se.id),Ke=ug(se.id,pe??void 0),qe=l===se.id,Xe=$.title||e("sessions.sidebar.session.untitled"),lt=n.children.length>0,bt=d.has(se.id),Be=Q,Je=f?!0:m.has(Be),Ze=!!$.parentID,At=mg(se.id)>0&&(!Ze||g),vt=$.time?.updated||$.time?.created||Date.now(),at=Bx(vt),ct=_x(vt),Ot=M===Q,[Zt,Et]=i.useState(!1),ge=Ot||Zt,st=i.useMemo(()=>ia($.title)!==null,[$.title]),[wt,tt]=i.useState(!1),ut=ve&&de==="recent"&&!J,Mt=ve&&de==="recent"&&J,It=i.useMemo(()=>Ve(n).length,[Ve,n]),zt=i.useCallback(async Ae=>{const xt=[];let rt=0;for(const _t of Ae)try{await z.ensureSessionRenderable(_t.session.id);const Vt=yd(ye.getState(),_t.session.id).list,ns=_t.session.title||e("sessions.sidebar.session.export.untitledSubagent"),rs=_t.session.agent,ts=await zt(_t.children);rt+=ts.skipped,xt.push({title:ns,agent:rs,records:Vt,children:ts.children})}catch{rt+=Ve(_t).length+1}return{children:xt,skipped:rt}},[Ve,ye,z,e]),ss=i.useCallback(Ae=>{Ae<=0||me.warning(Ae===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:Ae}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:Ae}))},[e]),Bt=i.useCallback(async Ae=>{if(!pe){me.error(e("sessions.sidebar.session.export.nothingToExport"));return}await z.ensureSessionRenderable(se.id);const xt=yd(ye.getState(),se.id).list;if(xt.length===0){me.error(e("sessions.sidebar.session.export.nothingToExport"));return}let rt,_t=0;if(Ae&&n.children.length>0){const ts=await zt(n.children);rt=ts.children,_t=ts.skipped}const Vt=I2(xt,$.title??null,rt),ns=L2($.title??null),rs=await E2(Vt,ns);if(rs){me.success(e("sessions.sidebar.session.export.success"),{action:{label:e(F2()),onClick:()=>{M2(rs).then(ts=>{ts||me.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),ss(_t);return}R2(Vt,ns),me.success(e("sessions.sidebar.session.export.success")),ss(_t)},[zt,ye,n.children,$.title,se.id,pe,ss,z,e]),Ft=i.useCallback(async()=>{if(n.children.length>0){xe(!0),X(!0);return}await Bt(!1)},[Bt,n.children.length]),Jt=i.useCallback(()=>{pe&&Er("desktop_open_session_mini_chat_window",{sessionId:se.id,directory:pe,apiBaseUrl:pr(),clientToken:Il()}).catch(Ae=>{console.warn("[session-sidebar] failed to open mini chat window",Ae)})},[se.id,pe]);if(i.useEffect(()=>{if(b!==se.id)return;const Ae=xt=>{he.current&&!he.current.contains(xt.target)&&K.current()};return document.addEventListener("mousedown",Ae),()=>document.removeEventListener("mousedown",Ae)},[b,se.id]),b===se.id)return s.jsx("div",{className:Te("group relative flex items-center rounded-sm px-1.5 py-1",r>0&&"pl-[20px]"),children:s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[s.jsxs("form",{ref:he,className:"flex w-full items-center gap-2",onSubmit:Ae=>{Ae.preventDefault(),p()},children:[s.jsx("input",{value:x,onChange:Ae=>y(Ae.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:e("sessions.sidebar.session.menu.rename"),onKeyDown:Ae=>{if(Ae.key==="Escape"){Ae.stopPropagation(),C();return}(Ae.key===" "||Ae.key==="Enter")&&Ae.stopPropagation()}}),s.jsx("button",{type:"submit","aria-label":e("sessions.sidebar.session.rename.save"),title:e("sessions.sidebar.session.rename.save"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(T,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:C,"aria-label":e("sessions.sidebar.session.rename.cancel"),title:e("sessions.sidebar.session.rename.cancel"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(T,{name:"close",className:"size-4"})})]}),J?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[lt?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Je?s.jsx(T,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(T,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:at}),be?s.jsx("span",{className:"truncate",children:te?.projectLabel}):null,ke?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(T,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:te?.branchLabel})]}):null]})})]})},se.id);const es=He?.type??"idle",Lt=es==="busy"||es==="retry",Pt=Ke.length,yt=Lt||!Lt&&At&&!qe,$t=Lt?s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary animate-busy-pulse","aria-label":e("sessions.sidebar.session.status.active"),title:e("sessions.sidebar.session.status.active")}):s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[var(--status-info)]","aria-label":e("sessions.sidebar.session.status.unread"),title:e("sessions.sidebar.session.status.unread")}),Dt=yt||bt?s.jsxs("span",{className:Te("pointer-events-none absolute inline-flex h-3.5 items-center justify-center gap-0.5 transition-opacity",J?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",yt&&bt?"left-[-6px] w-6":"left-0.5 w-3.5",lt&&!ne?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[yt?$t:null,bt?s.jsx(T,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}):null]}):null,fs=lt?s.jsx("span",{role:"button",tabIndex:0,onClick:Ae=>{Ae.stopPropagation(),v(Be)},onKeyDown:Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),Ae.stopPropagation(),v(Be))},className:Te("inline-flex h-3.5 w-3.5 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",ut?"absolute left-1.5 bottom-1":Mt?"relative mr-0.5 shrink-0":Te("absolute left-0.5",J?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!ut&&!Mt&&J&&yt&&!ne?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto":""),"aria-label":e(Je?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:Je?s.jsx(T,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(T,{name:"arrow-right-s",className:"h-3 w-3"})}):null,ms=$e?s.jsx(T,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,xs=Ae=>{Ae&&Et(!1),P(Ae?Q:null)},gt=Ae=>{if(!Ae&&ue.current){const{id:xt,title:rt}=ue.current;ue.current=null,h(xt),y(rt)}},qt=Ae=>{Et(Ae)},hs=Ae=>{Ae.preventDefault(),Ae.stopPropagation(),P(Ot?null:Q)},os=Ae=>{Ae.preventDefault(),Ae.stopPropagation()},Is=Ae=>{Ae.preventDefault(),Ae.stopPropagation()},As=Ae=>{Ae.preventDefault(),Ae.stopPropagation()},Xt=Ae=>{Ae.preventDefault(),Ae.stopPropagation()},Rs=Ae=>{Ae.preventDefault(),Ae.stopPropagation(),P(null),ie(se,{archivedBucket:c})},In=Ae=>{Ae.preventDefault(),Ae.stopPropagation()},Ds=Ae=>{Ae.preventDefault(),Ae.stopPropagation()},Ys=Ae=>{Ae.preventDefault(),Ae.stopPropagation(),q?.vscode?.executeCommand("openchamber.openSessionInEditor",se.id,Xe)},Us=Ae=>{if(Ee.current){Ee.current=!1;return}if(Ne){if(Ae?.preventDefault(),Ae?.stopPropagation(),Ae?.shiftKey){const rt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(ns=>ns.getAttribute("data-session-row")).filter(ns=>typeof ns=="string"&&ns.length>0),_t=Gn.getState().anchorId,Vt=new Map;Vt.set(se.id,Ve(n)),_e(_t,se.id,rt,pe??null,Vt);return}Ie(se.id,pe??null,Ve(n));return}k(se.id,pe,a)},bs=Ae=>{(Ae.button===2||Ae.button===0&&Ae.ctrlKey&&!Ne)&&(Ee.current=!0)},Yn=Ae=>{oe&&Ae.pointerType==="touch"&&Pe(!0)},en=Ae=>{oe&&Ae.pointerType==="touch"&&Pe(!1)},je=({Item:Ae,Separator:xt,Sub:rt,SubTrigger:_t,SubContent:Vt})=>s.jsxs(s.Fragment,{children:[s.jsxs(Ae,{onClick:()=>{ue.current={id:se.id,title:Xe}},className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(Ae,{onClick:()=>A(se.id),className:"[&>svg]:mr-1",children:[bt?s.jsx(T,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(T,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(bt?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),$.share?s.jsxs(s.Fragment,{children:[s.jsx(Ae,{onClick:()=>{$.share?.url&&D($.share.url,se.id)},className:"[&>svg]:mr-1",children:I===se.id?s.jsxs(s.Fragment,{children:[s.jsx(T,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),e("sessions.sidebar.session.menu.copied")]}):s.jsxs(s.Fragment,{children:[s.jsx(T,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(Ae,{onClick:()=>N(se.id),className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.unshare")]})]}):s.jsxs(Ae,{onClick:()=>S($),className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(Ae,{onClick:()=>{Ft()},className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),st?s.jsxs(Ae,{onClick:()=>tt(!0),className:"[&>svg]:mr-1",children:[s.jsx(sN,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,pe&&!c?(()=>{const ns=V(pe),rs=R(pe,se.id);return s.jsxs(s.Fragment,{children:[s.jsx(xt,{}),s.jsxs(rt,{children:[s.jsxs(_t,{className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs(Vt,{className:"min-w-[180px]",children:[ns.length===0?s.jsx(Ae,{disabled:!0,className:"text-muted-foreground",children:e("sessions.sidebar.folders.none")}):ns.map(ts=>s.jsxs(Ae,{onClick:()=>{rs===ts.id?B(pe,se.id):O(pe,ts.id,se.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:ts.name}),rs===ts.id?s.jsx(T,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},ts.id)),s.jsx(xt,{}),s.jsxs(Ae,{onClick:()=>{const ts=F(pe);ts&&O(pe,ts.id,se.id)},children:[s.jsx(T,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),rs?s.jsxs(Ae,{onClick:()=>{B(pe,se.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(T,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,ve?null:s.jsxs(Ae,{disabled:!pe,onClick:()=>{pe&&_(pe,{mode:"chat",dedupeKey:`session:${se.id}`,label:Xe})},className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"chat-4",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openInSidePanel")}),s.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:e("sessions.sidebar.session.menu.betaBadge")})]}),H?s.jsxs(Ae,{disabled:!pe,onClick:Jt,className:"[&>svg]:mr-1",children:[s.jsx(T,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(xt,{}),c?null:s.jsxs(Ae,{className:"[&>svg]:mr-1",onClick:()=>ie(se,{archivedBucket:c}),children:[s.jsx(T,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.archive")]}),s.jsxs(Ae,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ie(se,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(T,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),et=s.jsx(zs,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(E||Se.current),children:je({Item:ls,Separator:Cr,Sub:gg,SubTrigger:xg,SubContent:bg})}),ft=s.jsx(Kc,{children:s.jsx(qc,{className:"app-region-no-drag z-50",children:s.jsx(Yc,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(E||Se.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Te(wd,"min-w-[180px]"),children:je({Item:({className:Ae,...xt})=>s.jsx(Ph,{className:Te(fg,Ae),...xt}),Separator:({className:Ae,...xt})=>s.jsx(Ih,{className:Te(hg,Ae),...xt}),Sub:Rh,SubTrigger:({className:Ae,children:xt,...rt})=>s.jsxs(Eh,{className:Te(pg,Ae),...rt,children:[xt,s.jsx(T,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:Ae,children:xt,...rt})=>s.jsx(Kc,{children:s.jsx(qc,{className:"app-region-no-drag z-50",children:s.jsx(Yc,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Te(wd,Ae),...rt,children:xt})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(JS,{sessionId:se.id,sessionDirectory:pe??null,sessionTitle:Xe,children:s.jsxs(Dh,{open:Zt,onOpenChange:qt,onOpenChangeComplete:gt,children:[s.jsxs(Th,{render:s.jsx("div",{"data-session-row":se.id,"data-session-scope":pe??"","data-session-archived":c?"1":"0",className:Te("group relative my-0.5 flex items-center rounded-md py-1 pr-1.5","-ml-3",r>0?"pl-[32px]":"pl-[18px]",qe&&!U&&"bg-primary/10",U&&"bg-interactive-selection")}),children:[Dt,fs,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:J?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:Yn,onPointerUp:en,onPointerCancel:en,onMouseDown:bs,onClick:Ae=>Us(Ae),onDoubleClick:Ae=>{Ae.stopPropagation(),w(se.id,Xe)},className:Te("flex min-w-0 flex-1 cursor-pointer flex-col gap-0 overflow-hidden rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none transition-[padding]",we&&"bg-interactive-hover/70",ne?ve?Fe:Oe:Fe),children:s.jsxs("div",{className:Te("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Te("block min-w-0 flex-1 truncate typography-ui-label font-normal",qe?"text-primary":"text-foreground"),children:po(Xe,u)}),ne?s.jsx("span",{className:"ml-2 flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:ct}):null,ne?null:s.jsx("div",{className:"relative ml-1 flex h-4 min-w-4 flex-shrink-0 items-center justify-end",children:s.jsx("span",{className:Te("whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",ge?"opacity-0":fe),children:ct})}),Pt>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(T,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Pt})]}):null]})})}),ve?null:s.jsx(Ct,{side:"right",sideOffset:8,className:"max-w-xs text-left",children:s.jsxs("div",{className:"flex flex-col gap-1 text-left text-xs",children:[s.jsxs("div",{className:Te("flex items-center gap-3 text-left text-muted-foreground",te?.projectLabel?"justify-between":"justify-start"),children:[te?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:te.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:at})]}),te?.branchLabel?s.jsx("div",{className:"flex items-center gap-3 text-left text-muted-foreground justify-start",children:s.jsx("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(T,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:te.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:Yn,onPointerUp:en,onPointerCancel:en,onMouseDown:bs,onClick:Ae=>Us(Ae),onDoubleClick:Ae=>{Ae.stopPropagation(),w(se.id,Xe)},className:Te("flex min-w-0 flex-1 cursor-pointer flex-col gap-0 overflow-hidden rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none transition-[padding]",we&&"bg-interactive-hover/70",ne?ve?Fe:Oe:Fe),children:[s.jsxs("div",{className:Te("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Te("block min-w-0 flex-1 truncate typography-ui-label font-normal",qe?"text-primary":"text-foreground"),children:po(Xe,u)}),Pt>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(T,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Pt})]}):null]}),J?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:Te("flex min-w-0 items-center gap-1.5 overflow-hidden",ut&&lt?"pl-4":""),children:[s.jsx("span",{className:"flex-shrink-0",children:at}),be?s.jsx("span",{className:"truncate",children:te?.projectLabel}):null,ke?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(T,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:te?.branchLabel})]}):null]})})]})}),ms&&!oe?s.jsx("div",{className:Te("absolute top-1/2 -translate-y-1/2 z-10",J?"right-0":"right-[30px]"),children:ms}):null,s.jsxs("div",{className:Te("absolute right-0 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",ge||ne&&!ve?"opacity-100":Te("opacity-0",ce)),children:[Re?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",J&&!ne?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.bulkActions.archive"),onPointerDown:As,onMouseDown:Xt,onClick:Rs,onKeyDown:Ae=>Ae.stopPropagation(),children:s.jsx(T,{name:"archive",className:Te(J&&!ne?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Ct,{side:"left",sideOffset:8,children:e("sessions.sidebar.bulkActions.archive")})]}):null,De?s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",J&&!ne?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:In,onMouseDown:Ds,onClick:Ys,onKeyDown:Ae=>Ae.stopPropagation(),children:s.jsx(T,{name:"external-link",className:Te(J&&!ne?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Ct,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(Ws,{open:Ot,onOpenChange:xs,onOpenChangeComplete:gt,children:[s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",J&&!ne?ge?"h-4 w-4 opacity-100":Te("h-4 w-4 opacity-0",ce):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:os,onMouseDown:Is,onClick:hs,onKeyDown:Ae=>Ae.stopPropagation(),children:s.jsx(T,{name:"more-2",className:Te(J&&!ne?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),et]})]})]}),ft]})}),lt&&Je?n.children.map(Ae=>Y(Ae,r+1,pe??o,a,c,void 0,de)):null,s.jsx(Cs,{open:Le,onOpenChange:X,children:s.jsxs(ks,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ms,{children:[s.jsx(Ps,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(qs,{children:It===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:It}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:It})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:L,onChange:Ae=>xe(Ae.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(qn,{children:[s.jsx(ze,{type:"button",onClick:()=>X(!1),variant:"outline",size:"sm",children:e("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{type:"button",onClick:()=>{X(!1),Bt(L)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),st?s.jsx(tN,{session:$,open:wt,onOpenChange:tt}):null]},se.id)}const iN=i.memo(rN,nN);function oN(t){const e=ht.c(71),{t:n}=jt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,m,f,u,g,b,h,x,y,p;if(e[0]!==o||e[1]!==n||e[2]!==r){const _=n("sessions.sidebar.session.untitled");u=Cs,y=!!r,e[13]!==o?(p=oe=>{oe||o(null)},e[13]=o,e[14]=p):p=e[14],f=ks,h=!1,x="max-w-sm gap-5",m=Ms;let ie;e[15]!==n||e[16]!==r?.archivedBucket?(ie=r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.title"):n("sessions.sidebar.dialogs.archiveSession.title"),e[15]=n,e[16]=r?.archivedBucket,e[17]=ie):ie=e[17],e[18]!==ie?(b=s.jsx(Ps,{children:ie}),e[18]=ie,e[19]=b):b=e[19],d=qs,g=r&&r.descendantCount>0?r.archivedBucket?r.descendantCount===1?n("sessions.sidebar.dialogs.deleteSession.withOneSubtask",{sessionTitle:r.session.title||_,count:r.descendantCount}):n("sessions.sidebar.dialogs.deleteSession.withManySubtasks",{sessionTitle:r.session.title||_,count:r.descendantCount}):r.descendantCount===1?n("sessions.sidebar.dialogs.archiveSession.withOneSubtask",{sessionTitle:r.session.title||_,count:r.descendantCount}):n("sessions.sidebar.dialogs.archiveSession.withManySubtasks",{sessionTitle:r.session.title||_,count:r.descendantCount}):r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.single",{sessionTitle:r?.session.title||_}):n("sessions.sidebar.dialogs.archiveSession.single",{sessionTitle:r?.session.title||_}),e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=m,e[5]=f,e[6]=u,e[7]=g,e[8]=b,e[9]=h,e[10]=x,e[11]=y,e[12]=p}else d=e[3],m=e[4],f=e[5],u=e[6],g=e[7],b=e[8],h=e[9],x=e[10],y=e[11],p=e[12];let C;e[20]!==d||e[21]!==g?(C=s.jsx(d,{children:g}),e[20]=d,e[21]=g,e[22]=C):C=e[22];let v;e[23]!==m||e[24]!==b||e[25]!==C?(v=s.jsxs(m,{children:[b,C]}),e[23]=m,e[24]=b,e[25]=C,e[26]=v):v=e[26];let k;e[27]!==c||e[28]!==a?(k=()=>c(!a),e[27]=c,e[28]=a,e[29]=k):k=e[29];const w=!a;let A;e[30]!==a?(A=a?s.jsx(T,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(T,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[30]=a,e[31]=A):A=e[31];let S;e[32]!==n?(S=n("sessions.sidebar.dialogs.neverAsk"),e[32]=n,e[33]=S):S=e[33];let I;e[34]!==A||e[35]!==S||e[36]!==k||e[37]!==w?(I=s.jsxs("button",{type:"button",onClick:k,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":w,children:[A,S]}),e[34]=A,e[35]=S,e[36]=k,e[37]=w,e[38]=I):I=e[38];let D;e[39]!==o?(D=()=>o(null),e[39]=o,e[40]=D):D=e[40];let N;e[41]!==n?(N=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=N):N=e[42];let M;e[43]!==D||e[44]!==N?(M=s.jsx("button",{type:"button",onClick:D,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:N}),e[43]=D,e[44]=N,e[45]=M):M=e[45];let P;e[46]!==l?(P=()=>{l()},e[46]=l,e[47]=P):P=e[47];let E;e[48]!==n||e[49]!==r?.archivedBucket?(E=r?.archivedBucket?n("sessions.sidebar.bulkActions.delete"):n("sessions.sidebar.bulkActions.archive"),e[48]=n,e[49]=r?.archivedBucket,e[50]=E):E=e[50];let V;e[51]!==P||e[52]!==E?(V=s.jsx("button",{type:"button",onClick:P,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:E}),e[51]=P,e[52]=E,e[53]=V):V=e[53];let R;e[54]!==M||e[55]!==V?(R=s.jsxs("div",{className:"flex items-center gap-2",children:[M,V]}),e[54]=M,e[55]=V,e[56]=R):R=e[56];let B;e[57]!==I||e[58]!==R?(B=s.jsxs(qn,{className:"w-full sm:items-center sm:justify-between",children:[I,R]}),e[57]=I,e[58]=R,e[59]=B):B=e[59];let O;e[60]!==f||e[61]!==h||e[62]!==B||e[63]!==x||e[64]!==v?(O=s.jsxs(f,{showCloseButton:h,className:x,children:[v,B]}),e[60]=f,e[61]=h,e[62]=B,e[63]=x,e[64]=v,e[65]=O):O=e[65];let F;return e[66]!==u||e[67]!==O||e[68]!==y||e[69]!==p?(F=s.jsx(u,{open:y,onOpenChange:p,children:O}),e[66]=u,e[67]=O,e[68]=y,e[69]=p,e[70]=F):F=e[70],F}function aN(t){const e=ht.c(57),{t:n}=jt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t,d=r?.archivedBucket===!0,m=r?.sessionCount??0;let f;e[0]!==d||e[1]!==m||e[2]!==n?(f=n(d?m===1?"sessions.sidebar.dialogs.deleteSession.title":"sessions.sidebar.dialogs.deleteSessions.title":m===1?"sessions.sidebar.dialogs.archiveSession.title":"sessions.sidebar.dialogs.archiveSessions.title"),e[0]=d,e[1]=m,e[2]=n,e[3]=f):f=e[3];const u=f;let g;e[4]!==d||e[5]!==m||e[6]!==n?(g=d?m===1?n("sessions.sidebar.dialogs.deleteSessions.singleDescription",{count:m}):n("sessions.sidebar.dialogs.deleteSessions.pluralDescription",{count:m}):m===1?n("sessions.sidebar.dialogs.archiveSessions.singleDescription",{count:m}):n("sessions.sidebar.dialogs.archiveSessions.pluralDescription",{count:m}),e[4]=d,e[5]=m,e[6]=n,e[7]=g):g=e[7];const b=g,h=!!r;let x;e[8]!==o?(x=F=>{F||o(null)},e[8]=o,e[9]=x):x=e[9];let y;e[10]!==u?(y=s.jsx(Ps,{children:u}),e[10]=u,e[11]=y):y=e[11];let p;e[12]!==b?(p=s.jsx(qs,{children:b}),e[12]=b,e[13]=p):p=e[13];let C;e[14]!==y||e[15]!==p?(C=s.jsxs(Ms,{children:[y,p]}),e[14]=y,e[15]=p,e[16]=C):C=e[16];let v;e[17]!==c||e[18]!==a?(v=()=>c(!a),e[17]=c,e[18]=a,e[19]=v):v=e[19];const k=!a;let w;e[20]!==a?(w=a?s.jsx(T,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(T,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[20]=a,e[21]=w):w=e[21];let A;e[22]!==n?(A=n("sessions.sidebar.dialogs.neverAsk"),e[22]=n,e[23]=A):A=e[23];let S;e[24]!==A||e[25]!==v||e[26]!==k||e[27]!==w?(S=s.jsxs("button",{type:"button",onClick:v,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":k,children:[w,A]}),e[24]=A,e[25]=v,e[26]=k,e[27]=w,e[28]=S):S=e[28];let I;e[29]!==o?(I=()=>o(null),e[29]=o,e[30]=I):I=e[30];let D;e[31]!==n?(D=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=D):D=e[32];let N;e[33]!==I||e[34]!==D?(N=s.jsx("button",{type:"button",onClick:I,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:D}),e[33]=I,e[34]=D,e[35]=N):N=e[35];let M;e[36]!==l?(M=()=>{l()},e[36]=l,e[37]=M):M=e[37];let P;e[38]!==d||e[39]!==n?(P=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=P):P=e[40];let E;e[41]!==M||e[42]!==P?(E=s.jsx("button",{type:"button",onClick:M,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:P}),e[41]=M,e[42]=P,e[43]=E):E=e[43];let V;e[44]!==N||e[45]!==E?(V=s.jsxs("div",{className:"flex items-center gap-2",children:[N,E]}),e[44]=N,e[45]=E,e[46]=V):V=e[46];let R;e[47]!==S||e[48]!==V?(R=s.jsxs(qn,{className:"w-full sm:items-center sm:justify-between",children:[S,V]}),e[47]=S,e[48]=V,e[49]=R):R=e[49];let B;e[50]!==R||e[51]!==C?(B=s.jsxs(ks,{showCloseButton:!1,className:"max-w-sm gap-5",children:[C,R]}),e[50]=R,e[51]=C,e[52]=B):B=e[52];let O;return e[53]!==h||e[54]!==B||e[55]!==x?(O=s.jsx(Cs,{open:h,onOpenChange:x,children:B}),e[53]=h,e[54]=B,e[55]=x,e[56]=O):O=e[56],O}function lN(t){const e=ht.c(36),{t:n}=jt(),{value:r,setValue:o,onConfirm:a}=t,c=!!r;let l;e[0]!==o?(l=w=>{w||o(null)},e[0]=o,e[1]=l):l=e[1];let d;e[2]!==n?(d=n("sessions.sidebar.dialogs.deleteFolder.title"),e[2]=n,e[3]=d):d=e[3];let m;e[4]!==d?(m=s.jsx(Ps,{children:d}),e[4]=d,e[5]=m):m=e[5];let f;e[6]!==n||e[7]!==r?(f=r&&(r.subFolderCount>0||r.sessionCount>0)?r.subFolderCount>0?r.subFolderCount===1?n("sessions.sidebar.dialogs.deleteFolder.withOneSubfolder",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withManySubfolders",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withContentsNoSubfolders",{folderName:r.folderName}):n("sessions.sidebar.dialogs.deleteFolder.single",{folderName:r?.folderName??""}),e[6]=n,e[7]=r,e[8]=f):f=e[8];let u;e[9]!==f?(u=s.jsx(qs,{children:f}),e[9]=f,e[10]=u):u=e[10];let g;e[11]!==m||e[12]!==u?(g=s.jsxs(Ms,{children:[m,u]}),e[11]=m,e[12]=u,e[13]=g):g=e[13];let b;e[14]!==o?(b=()=>o(null),e[14]=o,e[15]=b):b=e[15];let h;e[16]!==n?(h=n("sessions.sidebar.dialogs.cancel"),e[16]=n,e[17]=h):h=e[17];let x;e[18]!==b||e[19]!==h?(x=s.jsx("button",{type:"button",onClick:b,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:h}),e[18]=b,e[19]=h,e[20]=x):x=e[20];let y;e[21]!==n?(y=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=y):y=e[22];let p;e[23]!==a||e[24]!==y?(p=s.jsx("button",{type:"button",onClick:a,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:y}),e[23]=a,e[24]=y,e[25]=p):p=e[25];let C;e[26]!==p||e[27]!==x?(C=s.jsxs(qn,{children:[x,p]}),e[26]=p,e[27]=x,e[28]=C):C=e[28];let v;e[29]!==C||e[30]!==g?(v=s.jsxs(ks,{showCloseButton:!1,className:"max-w-sm gap-5",children:[g,C]}),e[29]=C,e[30]=g,e[31]=v):v=e[31];let k;return e[32]!==c||e[33]!==l||e[34]!==v?(k=s.jsx(Cs,{open:c,onOpenChange:l,children:v}),e[32]=c,e[33]=l,e[34]=v,e[35]=k):k=e[35],k}const cN=t=>{const e=ht.c(46),{selectedCount:n,scopeKey:r,scopeFolders:o,archivedBucket:a,onMoveToFolder:c,onCreateFolderAndMove:l,onRemoveFromFolder:d,canRemoveFromFolder:m,onDelete:f,onDone:u}=t,{t:g}=jt(),b=!!r&&!a;let h;e[0]!==a||e[1]!==g?(h=g(a?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[0]=a,e[1]=g,e[2]=h):h=e[2];const x=h;let y;e[3]!==n||e[4]!==g?(y=g("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=g,e[5]=y):y=e[5];let p;e[6]!==y?(p=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:y}),e[6]=y,e[7]=p):p=e[7];let C;e[8]!==b||e[9]!==m||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==g?(C=b?s.jsxs(Ws,{children:[s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx($s,{asChild:!0,children:s.jsx("button",{type:"button",className:"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","aria-label":g("sessions.sidebar.bulkActions.moveToFolder"),children:s.jsx(T,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(Ct,{side:"top",sideOffset:4,children:s.jsx("p",{children:g("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(zs,{align:"end",className:"min-w-[180px]",children:[o.length===0?s.jsx(ls,{disabled:!0,className:"text-muted-foreground",children:g("sessions.sidebar.folders.none")}):o.map(B=>s.jsx(ls,{onClick:()=>c(B.id),children:s.jsx("span",{className:"flex-1 truncate",children:B.name})},B.id)),s.jsx(Cr,{}),s.jsxs(ls,{onClick:l,children:[s.jsx(T,{name:"add",className:"mr-1 h-4 w-4"}),g("sessions.sidebar.folders.newFolderEllipsis")]}),m?s.jsxs(ls,{onClick:d,className:"text-destructive focus:text-destructive",children:[s.jsx(T,{name:"close",className:"mr-1 h-4 w-4"}),g("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=b,e[9]=m,e[10]=l,e[11]=c,e[12]=d,e[13]=o,e[14]=g,e[15]=C):C=e[15];let v;e[16]===Symbol.for("react.memo_cache_sentinel")?(v=Te("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"),e[16]=v):v=e[16];let k;e[17]===Symbol.for("react.memo_cache_sentinel")?(k=s.jsx(T,{name:"delete-bin",className:"h-4 w-4"}),e[17]=k):k=e[17];let w;e[18]!==x||e[19]!==f?(w=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:f,className:v,"aria-label":x,children:k})}),e[18]=x,e[19]=f,e[20]=w):w=e[20];let A;e[21]!==x?(A=s.jsx(Ct,{side:"top",sideOffset:4,children:s.jsx("p",{children:x})}),e[21]=x,e[22]=A):A=e[22];let S;e[23]!==w||e[24]!==A?(S=s.jsxs(Nt,{children:[w,A]}),e[23]=w,e[24]=A,e[25]=S):S=e[25];let I;e[26]!==g?(I=g("sessions.sidebar.header.actions.exitSelection"),e[26]=g,e[27]=I):I=e[27];let D;e[28]===Symbol.for("react.memo_cache_sentinel")?(D=s.jsx(T,{name:"close",className:"h-4 w-4"}),e[28]=D):D=e[28];let N;e[29]!==u||e[30]!==I?(N=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:u,className:"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","aria-label":I,children:D})}),e[29]=u,e[30]=I,e[31]=N):N=e[31];let M;e[32]!==g?(M=g("sessions.sidebar.header.actions.exitSelection"),e[32]=g,e[33]=M):M=e[33];let P;e[34]!==M?(P=s.jsx(Ct,{side:"top",sideOffset:4,children:s.jsx("p",{children:M})}),e[34]=M,e[35]=P):P=e[35];let E;e[36]!==N||e[37]!==P?(E=s.jsxs(Nt,{children:[N,P]}),e[36]=N,e[37]=P,e[38]=E):E=e[38];let V;e[39]!==E||e[40]!==C||e[41]!==S?(V=s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[C,S,E]}),e[39]=E,e[40]=C,e[41]=S,e[42]=V):V=e[42];let R;return e[43]!==V||e[44]!==p?(R=s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-2.5 py-1.5",children:[p,V]}),e[43]=V,e[44]=p,e[45]=R):R=e[45],R},dN=2880*60*1e3,uN=t=>!!t.parentID,mN=t=>!!t.time?.archived,Yl=t=>{const e=t.time?.updated,n=t.time?.created;return typeof e=="number"&&Number.isFinite(e)?e:typeof n=="number"&&Number.isFinite(n)?n:0},fN=t=>[...t].sort((e,n)=>Yl(n)-Yl(e)),hN=(t,e=Date.now())=>{const n=e-dN,r=t.filter(o=>mN(o)||uN(o)?!1:Yl(o)>=n);return fN(r)},Ko="oc.sessions.projectCollapse",qu="oc.sessions.groupOrder",Yu="oc.sessions.groupCollapse",Ju="oc.sessions.activeSessionByProject",jl="oc.sessions.expandedParents.v2",pN="oc.sessions.expandedParents",gN="oc.sessions.pinned",xN=(t,e,n)=>{const r=new Set;for(const o of t){const a=Gt(o.path)?.toLowerCase();a&&r.add(a)}if(n?.includeWorktrees===!1)return r;for(const o of e.values())for(const a of o){const c=Gt(a.path)?.toLowerCase();c&&r.add(c)}return r},bN=(t,e,n)=>{if(t.time?.archived)return!0;const r=Gt(kr(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},yN=5*6e4,Qu=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=jt(),[c,l]=i.useState(!1),[d,m]=i.useState(""),f=i.useRef(null),u=i.useRef(null),g=i.useRef(new Set),[b,h]=i.useState(null),[x,y]=i.useState(""),[p,C]=i.useState(null),[v,k]=i.useState(new Set),w=i.useMemo(()=>bi(),[]),[A,S]=i.useState(new Set),[I,D]=i.useState(new Map),[N,M]=i.useState(new Map),P=Me(j=>j.isNewWorktreeDialogOpen),E=Me(j=>j.setNewWorktreeDialogOpen),[V,R]=i.useState(!1),[B,O]=i.useState(null),[F,_]=i.useState(null),[ie,oe]=i.useState(""),[ne,Y]=i.useState(null),[te,de]=i.useState(null),[be,ke]=i.useState(null),ae=Za(j=>j.ids),ve=Za(j=>j.setIds),J=Za(j=>j.toggle),[H,q]=i.useState(()=>{try{const j=bi().getItem(Yu);if(!j)return new Set;const Z=JSON.parse(j);return new Set(Array.isArray(Z)?Z.filter(le=>typeof le=="string"):[])}catch{return new Set}}),[ce,fe]=i.useState(()=>{try{const j=bi().getItem(qu);if(!j)return new Map;const Z=JSON.parse(j),le=new Map;return Object.entries(Z).forEach(([We,Ye])=>{Array.isArray(Ye)&&le.set(We,Ye.filter(Tt=>typeof Tt=="string"))}),le}catch{return new Map}}),[De,Re]=i.useState(()=>{try{const j=bi().getItem(Ju);if(!j)return new Map;const Z=JSON.parse(j),le=new Map;return Object.entries(Z).forEach(([We,Ye])=>{typeof Ye=="string"&&Ye.length>0&&le.set(We,Ye)}),le}catch{return new Map}}),[Fe,Oe]=i.useState(new Map),Ee=i.useRef(new Map),we=i.useRef(0),Pe=Bs(j=>j.homeDirectory),Se=Bs(j=>j.currentDirectory),ue=Bs(j=>j.setDirectory),K=ds(j=>j.projects),he=ds(j=>j.activeProjectId),se=ds(j=>j.removeProject),G=ds(j=>j.setActiveProjectIdOnly),$=ds(j=>j.updateProjectMeta),pe=ds(j=>j.reorderProjects),ye=Me(j=>j.setActiveMainTab),z=Me(j=>j.openContextPanelTab),Ne=Me(j=>j.setSettingsDialogOpen),U=Me(j=>j.toggleHelpDialog),Ie=Me(j=>j.setAboutDialogOpen),_e=Me(j=>j.setSessionSwitcherOpen),Ve=Me(j=>j.setScheduledTasksDialogOpen),Le=Me(j=>j.openMultiRunLauncher),X=Me(j=>j.notifyOnSubtasks),L=Me(j=>j.showDeletionDialog),xe=Me(j=>j.setShowDeletionDialog),Q=Ma(d,120),$e=i.useMemo(()=>Q.trim().toLowerCase(),[Q]),He=$e.length>0,Ke=Nn(j=>j.collapsedFolderIds),qe=Nn(j=>j.foldersMap),Xe=Nn(j=>j.getFoldersForScope),lt=Nn(j=>j.createFolder),bt=Nn(j=>j.renameFolder),Be=Nn(j=>j.deleteFolder),Je=Nn(j=>j.addSessionToFolder),Ze=Nn(j=>j.addSessionsToFolder),pt=Nn(j=>j.removeSessionFromFolder),At=Nn(j=>j.removeSessionsFromFolders),vt=Nn(j=>j.toggleFolderCollapse),at=Nn(j=>j.cleanupSessions),ct=Nn(j=>j.getSessionFolderId);cS({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchContainerRef:f});const Ot=Lm(),Zt=xc(),Et=ic(),ge=i.useMemo(()=>Fr(),[]),st=gr(j=>j.hasLoaded),wt=gr(j=>j.activeSessions),tt=gr(j=>j.archivedSessions),ut=mt(j=>j.currentSessionId),Mt=mt(j=>!!j.newSessionDraft?.open),It=mt(j=>j.setCurrentSession),zt=mt(j=>j.updateSessionTitle),ss=mt(j=>j.shareSession),Bt=mt(j=>j.unshareSession),Ft=mt(j=>j.worktreeMetadata),Jt=mt(j=>j.availableWorktreesByProject),es=mt(j=>j.openNewSessionDraft),Lt=i.useCallback(j=>{es(j),ge&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[ge,es]),Pt=ho(Tl(j=>({checkForUpdates:j.checkForUpdates,available:j.available,runtimeType:j.runtimeType,info:j.info,downloading:j.downloading,downloaded:j.downloaded,progress:j.progress,error:j.error,downloadUpdate:j.downloadUpdate,restartToUpdate:j.restartToUpdate}))),Kt=i.useMemo(()=>xN(K,Jt,{includeWorktrees:!ge}),[Jt,ge,K]),yt=i.useMemo(()=>{const j=new Map(Et.map(We=>[We.id,We])),Z=wt.map(We=>{const Ye=j.get(We.id);return Ye?yg(Ye,We):We}),le=new Set(Z.map(We=>We.id));return Et.forEach(We=>{le.has(We.id)||Z.push(We)}),Z.filter(We=>bN(We,Kt,{allowUnknownDirectory:!ge,allowEmptyDirectorySet:!ge}))},[wt,ge,Kt,Et]),$t=i.useMemo(()=>Et.map(j=>{const Z=Gt(j.directory??null)??"";return`${j.id}:${j.title??""}:${j.time?.archived?1:0}:${Z}`}).join("|"),[Et]),Dt=i.useRef(Et);i.useEffect(()=>{Dt.current=Et},[$t,Et]);const fs=i.useMemo(()=>K.map(j=>`${j.id}:${Gt(j.path)??""}`).join("|"),[K]),ms=i.useRef(!1);i.useEffect(()=>{ms.current||(ms.current=!0,ha(Dt.current))},[]),i.useEffect(()=>{let j=!1;return(async()=>{const le=ds.getState().projects;if(le.length===0)return;const We=new Map,Ye=[];await Promise.all(le.map(async Tt=>{const Rt=Gt(Tt.path);if(Rt)try{if(!(an.getState().directories.get(Rt)?.isGitRepo??await Ai(()=>import("./useAppFontEffects-ByW8wOJM.js").then(us=>us.f3),__vite__mapDeps([0,1,2,3,4])).then(us=>us.checkIsGitRepository(Rt))))return;const Ks=await vg({id:Tt.id,path:Rt});if(j||Ks.length===0)return;We.set(Rt,Ks),Ye.push(...Ks)}catch{}})),!j&&mt.setState({availableWorktrees:Ye,availableWorktreesByProject:We})})(),()=>{j=!0}},[fs]),i.useEffect(()=>{let j=null;const Z=$f(le=>{le.type==="scheduled-task-ran"&&(j&&clearTimeout(j),j=setTimeout(()=>{ha(Dt.current)},500))});return()=>{j&&clearTimeout(j),Z()}},[]);const xs=i.useMemo(()=>er(),[]),{isTablet:gt}=Ar(),qt=t||gt,{buildGroupSearchText:hs,filterSessionNodesForSearch:os,buildGroupedSessions:Is}=lS({homeDirectory:Pe,worktreeMetadata:Ft,pinnedSessionIds:ae,gitBranches:Ot,isVSCode:ge}),{scheduleCollapsedProjectsPersist:As}=gS({isVSCode:ge,hasLoadedGlobalSessions:st,safeStorage:w,keys:{sessionExpanded:jl,sessionExpandedLegacy:pN,projectCollapse:Ko,sessionPinned:gN,groupOrder:qu,projectActiveSession:Ju,groupCollapse:Yu},sessions:yt,setPinnedSessionIds:ve,groupOrderByProject:ce,activeSessionByProject:De,collapsedGroups:H,setExpandedParents:k,setCollapsedProjects:S}),Xt=i.useMemo(()=>[...yt].sort((j,Z)=>$i(j,Z,ae)),[yt,ae]),Rs=i.useMemo(()=>new Map(Xt.map((j,Z)=>[j.id,Z])),[Xt]),In=i.useMemo(()=>{const j=new Map;return Xt.forEach(Z=>{const le=Z.parentID;if(!le)return;const We=j.get(le)??[];We.push(Z),j.set(le,We)}),j.forEach(Z=>Z.sort((le,We)=>$i(le,We,ae))),j},[Xt,ae]),Ds=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:a("sessions.sidebar.empty.noSessions.title")}),s.jsx("p",{className:"typography-meta mt-1",children:a("sessions.sidebar.empty.noSessions.description")})]}),Ys=i.useMemo(()=>K.find(j=>j.id===p)??null,[K,p]),Us=i.useCallback(j=>{p&&($(p,j),C(null))},[p,$]),bs=i.useCallback(()=>{E(!0)},[E]),Yn=i.useCallback(()=>{const j=ho.getState();if(j.available&&j.info){R(!0);return}Pt.checkForUpdates().then(()=>{const{available:Z,error:le}=ho.getState();if(le){me.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:le});return}if(!Z){me.success(a("sessions.sidebar.updateCheck.latestVersion"));return}R(!0)})},[a,Pt]),en=i.useCallback(()=>{t&&_e(!1),Ne(!0)},[t,_e,Ne]),je=Pt.available&&(Pt.runtimeType==="desktop"||Pt.runtimeType==="web"),et=mt(j=>j.deleteSession),ft=mt(j=>j.deleteSessions),Ae=mt(j=>j.archiveSession),xt=mt(j=>j.archiveSessions),{copiedSessionId:rt,handleSessionSelect:_t,handleSessionDoubleClick:Vt,handleSaveEdit:ns,handleCancelEdit:rs,handleShareSession:ts,handleCopyShareUrl:cn,handleUnshareSession:_s,handleDeleteSession:tn,confirmDeleteSession:Rn}=dS({activeProjectId:he,currentDirectory:Se,currentSessionId:ut,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:m,setIsSessionSearchOpen:l,setActiveProjectIdOnly:G,setDirectory:ue,setActiveMainTab:ye,setSessionSwitcherOpen:_e,setCurrentSession:It,updateSessionTitle:zt,shareSession:ss,unshareSession:Bt,deleteSession:et,deleteSessions:ft,archiveSession:Ae,archiveSessions:xt,childrenMap:In,showDeletionDialog:L,setDeleteSessionConfirm:Y,deleteSessionConfirm:ne,setEditingId:h,setEditTitle:y,editingId:b,editTitle:x}),jn=i.useCallback(()=>{if(!te)return;const{scopeKey:j,folderId:Z}=te;de(null),Be(j,Z)},[te,Be]),dn=i.useCallback(()=>{Nr.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!ut)return;const Z=yt.find(We=>We.id===ut)?.parentID;if(!Z)return;const le=[`project:active:${Z}`,`project:archived:${Z}`,`recent:active:${Z}`,`recent:archived:${Z}`];k(We=>{if(le.every(Tt=>We.has(Tt)))return We;const Ye=new Set(We);le.forEach(Tt=>Ye.add(Tt));try{w.setItem(jl,JSON.stringify(Array.from(Ye)))}catch{}return Ye})},[ut,yt,w]);const Es=i.useCallback(j=>{k(Z=>{const le=new Set(Z);le.has(j)?le.delete(j):le.add(j);try{w.setItem(jl,JSON.stringify(Array.from(le)))}catch{}return le})},[w]),js=i.useCallback((j,Z)=>{if(!j)return null;Z&&Ke.has(Z)&&vt(Z);const le=lt(j,a("sessions.sidebar.folder.newFolderName"),Z);return _(le.id),oe(le.name),le},[Ke,vt,lt,a]),Or=i.useCallback((j,Z)=>{M(le=>{const We=new Map(le);return We.set(j,Z+7),We})},[]),En=i.useCallback(j=>{M(Z=>{if(!Z.has(j))return Z;const le=new Map(Z);return le.delete(j),le})},[]),sr=i.useCallback(j=>{M(Z=>{let le=!1;const We=new Map(Z),Ye=`${j}:`;for(const Tt of We.keys())Tt.startsWith(Ye)&&(We.delete(Tt),le=!0);return le?We:Z})},[]),Br=i.useCallback(()=>{we.current=Date.now()+150,M(new Map),S(()=>{const j=new Set(K.map(Z=>Z.id));try{w.setItem(Ko,JSON.stringify(Array.from(j)))}catch{}return ge||As(j),j})},[K,ge,w,As]),Vn=i.useCallback(()=>{we.current=Date.now()+150,M(new Map),S(()=>{const j=new Set;try{w.setItem(Ko,JSON.stringify([]))}catch{}return ge||As(j),j})},[ge,w,As]),_r=i.useCallback(j=>{we.current=Date.now()+150,sr(j),S(Z=>{const le=new Set(Z);le.has(j)?le.delete(j):le.add(j);try{w.setItem(Ko,JSON.stringify(Array.from(le)))}catch{}return ge||As(le),le})},[ge,sr,w,As]),Js=i.useMemo(()=>K.map(j=>({...j,normalizedPath:Gt(j.path)})).filter(j=>!!j.normalizedPath),[K]),nr=i.useMemo(()=>Js.map(j=>j.normalizedPath),[Js]),un=i.useMemo(()=>{const j=new Set;return Js.forEach(Z=>{if(Z.normalizedPath&&j.add(Z.normalizedPath),ge)return;(Jt.get(Z.normalizedPath)??[]).forEach(We=>{const Ye=Gt(We.path);Ye&&j.add(Ye)})}),[...j].sort()},[Jt,ge,Js]),as=i.useRef(null);i.useEffect(()=>{const j=new Set(un),Z=as.current;if(as.current=j,!Z){ge&&un.length>0&&vd(un,Dt.current);return}const le=un.filter(We=>!Z.has(We));le.length!==0&&vd(le,Dt.current)},[ge,un]);const{github:ws}=_n(),$n=Ni(j=>j.status),sn=Ni(j=>j.hasChecked),Qs=wg(nr),rr=Kn(j=>j.ensureEntry),xr=Kn(j=>j.setParams),br=Kn(j=>j.refreshTargets);xS({normalizedProjects:Js,gitRepoStatus:Qs,setProjectRepoStatus:D,setProjectRootBranches:Oe});const Vr=mt(j=>j.isLoading);AS({isSessionsLoading:Vr,hasLoadedGlobalSessions:st,sessions:yt,archivedSessions:tt,normalizedProjects:Js,isVSCode:ge,availableWorktreesByProject:Jt,cleanupSessions:at});const{getSessionsForProject:Dr,getArchivedSessionsForProject:$r}=jS({isVSCode:ge,sessions:yt,archivedSessions:tt,availableWorktreesByProject:Jt});eS({normalizedProjects:Js,sessions:yt,archivedSessions:tt,availableWorktreesByProject:Jt,isVSCode:ge,isSessionsLoading:Vr,foldersMap:qe,createFolder:lt,addSessionToFolder:Je,cleanupSessions:at});const ir=i.useRef(!1);he&&I.has(he)&&(ir.current=!!I.get(he));const{projectSections:Mn,groupSearchDataByGroup:re,sectionsForRender:nt,searchMatchCount:ot}=nS({normalizedProjects:Js,getSessionsForProject:Dr,getArchivedSessionsForProject:$r,availableWorktreesByProject:Jt,projectRepoStatus:I,projectRootBranches:Fe,lastRepoStatus:ir.current,buildGroupedSessions:Is,hasSessionSearchQuery:He,normalizedSessionSearchQuery:$e,filterSessionNodesForSearch:os,buildGroupSearchText:hs,foldersMap:qe}),St=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:a("sessions.sidebar.empty.noMatches.title")}),s.jsx("p",{className:"typography-meta mt-1",children:a("sessions.sidebar.empty.noMatches.description")})]}),{currentSessionDirectory:Yt}=iS({projectSections:Mn,activeProjectId:he,activeSessionByProject:De,setActiveSessionByProject:Re,currentSessionId:ut,handleSessionSelect:_t,newSessionDraftOpen:Mt,mobileVariant:t,openNewSessionDraft:es,setActiveMainTab:ye,setSessionSwitcherOpen:_e,sessions:yt,worktreeMetadata:Ft}),{getOrderedGroups:Ht}=oS(ce),is=i.useRef(!1);i.useEffect(()=>{if(is.current||Mn.length===0)return;const j=Mn.flatMap(Z=>Z.groups.filter(le=>le.isArchivedBucket).map(le=>`${Z.project.id}:${le.id}`));j.length>0&&q(Z=>new Set([...Z,...j])),is.current=!0},[Mn]);const ps=i.useMemo(()=>{const j=new Map,Z=new Map;return Mn.forEach(le=>{const We=tf(le.project.label?.trim()||Ci(le.project.normalizedPath,Pe)||le.project.normalizedPath);le.groups.forEach(Ye=>{const Tt=Ye.branch&&Ye.branch!=="HEAD"&&Ye.branch!==We?Ye.branch:null,Rt={projectLabel:We,branchLabel:Tt},ys=Gs=>{Gs.forEach(Ks=>{const us=le.project.normalizedPath.length,vr=Z.get(Ks.session.id)??-1;us<vr||(j.set(Ks.session.id,{node:Ks,projectId:le.project.id,groupDirectory:Ye.directory,secondaryMeta:Rt}),Z.set(Ks.session.id,us),Ks.children.length>0&&ys(Ks.children))})};ys(Ye.sessions)})}),j},[Mn,Pe]),cs=jr(j=>j.showRecentSection),Fs=jr(j=>j.showArchivedSessions),hn=i.useMemo(()=>!cs||ge?[]:hN(yt).sort((j,Z)=>$i(j,Z,ae)),[ge,ae,yt,cs]),or=i.useMemo(()=>{if(ge||!cs)return[];const j=hn,Z=We=>{const Ye=ps.get(We.id),Tt=Gt(We.directory??null),Rt=Ye?.node??{session:We,children:[],worktree:null},Gs=(He?os([Rt],$e):[Rt])[0];if(!Gs)return null;const Ks=Ye?.secondaryMeta?{projectLabel:Ye.secondaryMeta.projectLabel,branchLabel:ge?null:Ye.secondaryMeta.branchLabel}:null;return{node:Gs,projectId:Ye?.projectId??null,groupDirectory:Ye?.groupDirectory??Tt,secondaryMeta:Ks}},le=j.map(Z).filter(We=>We!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:le}]},[hn,os,He,ge,$e,ps,cs,a]),Xs=i.useMemo(()=>or.some(j=>j.items.length>0),[or]),yr=i.useMemo(()=>new Set(hn.map(j=>j.id)),[hn]),mn=i.useMemo(()=>[...yr],[yr]);xj({currentSessionId:ut,sortedSessions:Xt,recentSessionIds:mn,ensureSessionRenderable:Zt.ensureSessionRenderable});const Hs=i.useMemo(()=>Fs?nt:nt.map(j=>({...j,groups:j.groups.filter(Z=>!Z.isArchivedBucket)})),[nt,Fs]),Sn=i.useMemo(()=>{const j=new Set;return Hs.forEach(Z=>{Z.groups.forEach(le=>{const We=Gt(le.directory??null),Ye=le.branch?.trim()||Ot.get(We||"")?.trim();!We||!Ye||j.add(bo(We,Ye))})}),[...j]},[Ot,Hs]),pn=sw(Sn);i.useEffect(()=>{if(!sn||!$n?.connected||!ws)return;const j=[],Z=Date.now();if(Hs.forEach(We=>{A.has(We.project.id)||We.groups.forEach(Ye=>{const Tt=Gt(Ye.directory??null),Rt=Ye.branch?.trim()||Ot.get(Tt||"")?.trim();if(!Tt||!Rt)return;const ys=bo(Tt,Rt),Gs=Kn.getState().entries[ys],Ks=!!Gs?.status?.pr,us=`${Tt}::${Rt}`,vr=Math.max(Gs?.lastRefreshAt??0,Gs?.lastDiscoveryPollAt??0),xn=!!(Gs?.isInitialStatusResolved&&!Ks&&(!g.current.has(us)||Z-vr>=yN));(!Gs||!Gs.isInitialStatusResolved||xn)&&(xn&&g.current.add(us),j.push({directory:Tt,branch:Rt}))})}),j.length===0)return;const le=new Map;j.forEach(We=>{const Ye=bo(We.directory,We.branch,We.remoteName??null);le.has(Ye)||le.set(Ye,We)}),le.forEach((We,Ye)=>{rr(Ye),xr(Ye,{directory:We.directory,branch:We.branch,remoteName:We.remoteName??null,canShow:!0,github:ws,githubAuthChecked:sn,githubConnected:$n.connected})}),br([...le.values()],{silent:!0,markInitialResolved:!0})},[A,rr,ws,sn,$n?.connected,Ot,br,Hs,xr]);const Jn=t?"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed":"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",zr="h-4.5 w-4.5",Di=IS({isDesktopShellRuntime:xs,projectSections:Mn,projectHeaderSentinelRefs:Ee}),Wn=i.useCallback((j,Z=0,le,We,Ye=!1,Tt,Rt="project")=>s.jsx(iN,{node:j,depth:Z,groupDirectory:le,projectId:We,archivedBucket:Ye,currentSessionId:ut,pinnedSessionIds:ae,expandedParents:v,hasSessionSearchQuery:He,normalizedSessionSearchQuery:$e,notifyOnSubtasks:X,editingId:b,setEditingId:h,editTitle:x,setEditTitle:y,handleSaveEdit:ns,handleCancelEdit:rs,toggleParent:Es,handleSessionSelect:_t,handleSessionDoubleClick:Vt,togglePinnedSession:J,handleShareSession:ts,copiedSessionId:rt,handleCopyShareUrl:cn,handleUnshareSession:_s,openSidebarMenuKey:B,setOpenSidebarMenuKey:O,renamingFolderId:F,getFoldersForScope:Xe,getSessionFolderId:ct,removeSessionFromFolder:pt,addSessionToFolder:Je,createFolderAndStartRename:js,openContextPanelTab:z,handleDeleteSession:tn,mobileVariant:t,alwaysShowActions:qt,renderSessionNode:Wn,secondaryMeta:Tt,renderContext:Rt}),[ut,ae,v,He,$e,X,b,h,x,y,ns,rs,Es,_t,Vt,J,ts,rt,cn,_s,B,O,F,Xe,ct,pt,Je,js,z,tn,t,qt]),oi=i.useCallback(j=>{En(j),q(Z=>{const le=new Set(Z);return le.has(j)?le.delete(j):le.add(j),le})},[En]),ai=i.useMemo(()=>{const j=new Map;for(const[Z,le]of pn)j.set(Z,{visualState:le.visualState,number:le.number,url:le.url,state:le.prState,draft:le.draft,title:le.title,base:le.base,head:le.head,checks:le.checks,canMerge:le.canMerge,mergeableState:le.mergeableState,repo:le.repo});return j},[pn]),Pr=i.useCallback((j,Z,le,We,Ye,Tt)=>s.jsx(e2,{group:j,groupKey:Z,projectId:le,hideGroupLabel:We,compactBodyPadding:Tt,hasSessionSearchQuery:He,normalizedSessionSearchQuery:$e,groupSearchDataByGroup:re,visibleSessionCount:N.get(Z),collapsedGroups:H,hideDirectoryControls:r,collapsedFolderIds:Ke,toggleFolderCollapse:vt,renameFolder:bt,deleteFolder:Be,showDeletionDialog:L,setDeleteFolderConfirm:de,renderSessionNode:Wn,currentSessionDirectory:Yt,projectRepoStatus:I,lastRepoStatus:ir.current,showMoreGroupSessions:Or,resetGroupSessionLimit:En,mobileVariant:t,alwaysShowActions:qt,activeProjectId:he,setActiveProjectIdOnly:G,setActiveMainTab:ye,setSessionSwitcherOpen:_e,openNewSessionDraft:Lt,addSessionToFolder:Je,createFolderAndStartRename:js,renamingFolderId:F,renameFolderDraft:ie,setRenameFolderDraft:oe,setRenamingFolderId:_,pinnedSessionIds:ae,sessionOrderIndex:Rs,prVisualStateByDirectoryBranch:ai,onToggleCollapsedGroup:oi,dragHandleProps:Ye}),[He,$e,re,N,H,r,Ke,vt,bt,Be,L,Wn,Yt,I,Or,En,t,qt,he,G,ye,_e,Lt,Je,js,F,ie,ae,Rs,ai,oi]),Ti=!ge&&cs&&!He?s.jsx(c2,{sections:or,renderSessionNode:Wn,variant:"section"}):null,ar=!!(F||b||p),gn=Gn(j=>j.enabled),Qt=Gn(j=>j.selectedIds),lr=Gn(j=>j.scopeKey),nn=Gn,cr=i.useCallback(()=>{Gn.getState().toggleMode()},[]),Fn=i.useCallback(()=>{Gn.getState().disable()},[]),wr=i.useMemo(()=>{if(Qt.size===0||typeof document>"u")return!1;let j=!1,Z=!1;for(const le of Qt){const We=document.querySelectorAll(`[data-session-row="${CSS.escape(le)}"]`);for(const Ye of We)Ye.getAttribute("data-session-archived")==="1"?Z=!0:j=!0}return Z&&!j},[Qt]),Ls=i.useMemo(()=>{if(lr)return lr;if(Qt.size===0||typeof document>"u")return null;for(const j of Qt){const le=document.querySelector(`[data-session-row="${CSS.escape(j)}"]`)?.getAttribute("data-session-scope");if(le&&le.length>0)return le}return null},[Qt,lr]),no=i.useMemo(()=>Ls?qe[Ls]??[]:[],[qe,Ls]),Pi=i.useMemo(()=>{if(!Ls||Qt.size===0)return!1;const j=qe[Ls]??[];for(const Z of j)for(const le of Z.sessionIds)if(Qt.has(le))return!0;return!1},[qe,Ls,Qt]),Qn=i.useCallback(j=>{!Ls||Qt.size===0||Ze(Ls,j,Array.from(Qt))},[Ze,Qt,Ls]),li=i.useCallback(()=>{if(!Ls||Qt.size===0)return;const j=js(Ls);j&&Ze(Ls,j.id,Array.from(Qt))},[Ze,js,Qt,Ls]),rn=i.useCallback(()=>{!Ls||Qt.size===0||At(Ls,Array.from(Qt))},[At,Qt,Ls]),Ln=i.useCallback(async()=>{const j=Array.from(Qt);if(j.length!==0){if(wr){const{deletedIds:Z,failedIds:le}=await ft(j);Z.length>0&&me.success(Z.length===1?a("sessions.sidebar.bulkActions.deletedSingle",{count:Z.length}):a("sessions.sidebar.bulkActions.deletedPlural",{count:Z.length})),le.length>0&&me.error(le.length===1?a("sessions.sidebar.bulkActions.failedDeleteSingle",{count:le.length}):a("sessions.sidebar.bulkActions.failedDeletePlural",{count:le.length}))}else{const{archivedIds:Z,failedIds:le}=await xt(j);Z.length>0&&me.success(Z.length===1?a("sessions.sidebar.bulkActions.archivedSingle",{count:Z.length}):a("sessions.sidebar.bulkActions.archivedPlural",{count:Z.length})),le.length>0&&me.error(le.length===1?a("sessions.sidebar.bulkActions.failedArchiveSingle",{count:le.length}):a("sessions.sidebar.bulkActions.failedArchivePlural",{count:le.length}))}Gn.getState().clear()}},[xt,wr,ft,Qt,a]),Wr=i.useCallback(()=>{const j=Qt.size;if(j!==0){if(!L){Ln();return}ke({sessionCount:j,archivedBucket:wr})}},[wr,Ln,Qt,L]),Ii=i.useCallback(async()=>{ke(null),await Ln()},[Ln]);i.useEffect(()=>{if(!gn)return;const j=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),Z=le=>{if(ar)return;const We=le.target;if(We&&(We.tagName==="INPUT"||We.tagName==="TEXTAREA"||We.isContentEditable))return;const Ye=j?le.metaKey:le.ctrlKey;if(le.key==="Escape"){le.preventDefault(),Gn.getState().disable();return}if(Ye&&le.key==="Backspace"){le.preventDefault(),Wr();return}if(Ye&&(le.key==="a"||le.key==="A")){const Tt=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(Tt.length===0)return;le.preventDefault();const ys=nn.getState().scopeKey??Tt[0]?.getAttribute("data-session-scope")??null,Gs=us=>ys?us.getAttribute("data-session-scope")===ys:!0,Ks=Tt.filter(Gs).map(us=>us.getAttribute("data-session-row")).filter(us=>typeof us=="string"&&us.length>0);if(Ks.length===0)return;nn.getState().replaceAll(Ks,ys||null)}};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[Wr,ar,nn,gn]);const Ur=i.useCallback(()=>{ye("chat"),t&&_e(!1),Le()},[t,Le,ye,_e]),ee=i.useCallback(()=>{ye("chat"),t&&_e(!1),es()},[t,es,ye,_e]);return s.jsxs("div",{ref:f,className:Te("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(t2,{hideDirectoryControls:r,showRecentControls:!ge,handleOpenDirectoryDialog:dn,openNewSessionDraft:ee,canOpenMultiRun:K.length>0,openMultiRunLauncher:Ur,headerActionIconClass:zr,headerActionButtonClass:Jn,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchQuery:d,setSessionSearchQuery:m,hasSessionSearchQuery:He,searchMatchCount:ot,collapseAllProjects:Br,expandAllProjects:Vn,openScheduledTasksDialog:()=>Ve(!0),selectionModeEnabled:gn,onToggleSelectionMode:cr}),s.jsx(b2,{topContent:Ti,hasSharedSessions:Xs,sectionsForRender:Hs,projectSections:Mn,activeProjectId:he,showOnlyMainWorkspace:o,hasSessionSearchQuery:He,emptyState:Ds,searchEmptyState:St,renderGroupSessions:Pr,homeDirectory:Pe,collapsedProjects:A,hideDirectoryControls:r,projectRepoStatus:I,isDesktopShellRuntime:xs,stuckProjectHeaders:Di,mobileVariant:t,alwaysShowActions:qt,toggleProject:_r,setActiveProjectIdOnly:G,setActiveMainTab:ye,setSessionSwitcherOpen:_e,openNewSessionDraft:Lt,openNewWorktreeDialog:bs,openProjectEditDialog:C,removeProject:se,projectHeaderSentinelRefs:Ee,reorderProjects:pe,getOrderedGroups:Ht,setGroupOrderByProject:fe,openSidebarMenuKey:B,setOpenSidebarMenuKey:O,isInlineEditing:ar}),gn&&Qt.size>0?s.jsx(cN,{selectedCount:Qt.size,scopeKey:Ls,scopeFolders:no,archivedBucket:wr,onMoveToFolder:Qn,onCreateFolderAndMove:li,onRemoveFromFolder:rn,canRemoveFromFolder:Pi,onDelete:Wr,onDone:Fn}):null,s.jsx(u2,{onOpenSettings:en,onOpenShortcuts:U,onOpenAbout:()=>Ie(!0),onOpenUpdate:Yn,showRuntimeButtons:!ge,showUpdateButton:je}),s.jsx(qm,{open:V,onOpenChange:R,info:Pt.info,downloading:Pt.downloading,downloaded:Pt.downloaded,progress:Pt.progress,error:Pt.error,onDownload:Pt.downloadUpdate,onRestart:Pt.restartToUpdate,runtimeType:Pt.runtimeType}),Ys?s.jsx(ES,{open:!!Ys,onOpenChange:j=>{j||C(null)},projectId:Ys.id,projectName:Ys.label||Ci(Ys.path,Pe),projectPath:Ys.path,initialIcon:Ys.icon,initialColor:Ys.color,initialIconBackground:Ys.iconBackground,onSave:Us}):null,s.jsx(vx,{open:P,onOpenChange:E,onWorktreeCreated:(j,Z)=>{if(ye("chat"),t&&_e(!1),Z?.sessionId){It(Z.sessionId,j);return}es({directoryOverride:j,preserveDirectoryOverride:!0})}}),s.jsx(Xj,{}),s.jsx(oN,{value:ne,setValue:Y,showDeletionDialog:L,setShowDeletionDialog:xe,onConfirm:Rn}),s.jsx(lN,{value:te,setValue:de,onConfirm:jn}),s.jsx(aN,{value:be,setValue:ke,showDeletionDialog:L,setShowDeletionDialog:xe,onConfirm:Ii})]})},fi=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,mr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},wN=()=>{const{t}=jt(),[e,n]=i.useState(!1),[r,o]=i.useState(!1),[a,c]=i.useState(null),[l,d]=i.useState([]),[m,f]=i.useState(!1),[u,g]=i.useState(!1),[b,h]=i.useState(!1),[x,y]=i.useState(!1),[p,C]=i.useState(new Set),v=mt(ue=>ue.getWorktreeMetadata),k=mt(ue=>ue.newSessionDraft),w=mt(ue=>ue.setNewSessionDraftTarget),A=mt(ue=>ue.setDraftBootstrapPendingDirectory),S=jg,I=kg,D=mt(ue=>ue.deleteSessions),N=mt(ue=>ue.archiveSessions),M=Me(ue=>ue.showDeletionDialog),P=Me(ue=>ue.setShowDeletionDialog),E=Bs(ue=>ue.currentDirectory),V=Bs(ue=>ue.homeDirectory),R=Bs(ue=>ue.isHomeReady),B=ds(ue=>ue.projects),O=ds(ue=>ue.activeProjectId),{isMobile:F,isTablet:_,hasTouchInput:ie}=Ar(),oe=F||_||ie,ne=i.useMemo(()=>{const K=(O?B.find(he=>he.id===O)??null:null)?.path??E;return mr(K)},[O,E,B]),Y=i.useCallback(ue=>{const he=mr(ue.projectDirectory)||ne;return{id:(B.find(G=>mr(G.path)===he)??null)?.id??`path:${he}`,path:he}},[ne,B]),te=x&&p.size>0,de=i.useMemo(()=>{const ue=a?.worktree;return ue&&typeof ue.branch=="string"&&ue.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:K})=>typeof K.branch=="string"&&K.branch.trim().length>0)},[a?.worktree,l]),be=a?.mode==="worktree",ke=be,ae=b||!be||!de,ve=b||!be;i.useEffect(()=>{r||!R||B.length>0||(o(!0),n(!0))},[r,R,B.length]);const J=i.useCallback(ue=>{c({sessions:ue.sessions,dateLabel:ue.dateLabel,mode:ue.mode??"session",worktree:ue.worktree??null})},[]),H=i.useCallback(()=>{c(null),d([]),f(!1),g(!1),h(!1),y(!1),C(new Set)},[]),q=i.useCallback(async ue=>{if(ue.sessions.length===0)return;if(ue.sessions.length===1){const G=ue.sessions[0];await S(G.id)?me.success(t("sessions.sidebar.session.delete.success")):me.error(t("sessions.sidebar.session.delete.error"));return}const K=ue.sessions.map(G=>G.id),{deletedIds:he,failedIds:se}=await D(K);if(he.length>0){const G=se.length>0?se.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:se.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:se.length}):ue.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:ue.dateLabel}):void 0;me.success(he.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:he.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:he.length}),{description:fi(G)})}se.length>0&&me.error(se.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:se.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:se.length}),{description:fi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[S,D,t]);i.useEffect(()=>Nr.onDeleteRequest(ue=>{if(!M&&(ue.mode??"session")==="session"){q(ue);return}J(ue)}),[J,M,q]),i.useEffect(()=>Nr.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),f(!1),g(!1),y(!1),C(new Set);return}const ue=a.sessions.map(se=>{const G=v(se.id);return G?{session:se,metadata:G}:null}).filter(se=>!!se);d(ue),f(!1),y(!1),C(new Set);const K=new Map;if(a.worktree?.path&&K.set(mr(a.worktree.path),a.worktree),ue.forEach(({metadata:se})=>{se.path&&K.set(mr(se.path),se)}),K.size===0){y(!0);return}let he=!1;return(async()=>{const se=new Map,G=new Set;await Promise.all(Array.from(K.entries()).map(async([$,pe])=>{try{const ye=await Sg(pe.path);se.set($,ye),ye?.isDirty&&G.add($)}catch{pe.status&&(se.set($,pe.status),pe.status.isDirty&&G.add($))}})).catch($=>{console.warn("Failed to inspect worktree status before deletion:",$)}),!he&&(C(G),y(!0),c($=>{if(!$?.worktree?.path)return $;const pe=mr($.worktree.path),ye=se.get(pe);if(!ye)return $;const z=$.worktree.status;return z?.isDirty===ye.isDirty&&z?.ahead===ye.ahead&&z?.behind===ye.behind&&z?.upstream===ye.upstream?$:{...$,worktree:{...$.worktree,status:ye}}}),d($=>$.map(pe=>{const ye=mr(pe.metadata.path),z=se.get(ye);return z?{session:pe.session,metadata:{...pe.metadata,status:z}}:pe})))})(),()=>{he=!0}},[a,v]),i.useEffect(()=>{de||f(!1)},[de]);const ce=i.useCallback(async(ue,K)=>{const he=m&&de,se=Y(ue),G=mr(ue.path),$=mr(se.path);try{await Ng(se,ue,{deleteRemoteBranch:he,deleteLocalBranch:K});const pe=mr(k?.directoryOverride);return k?.open&&G&&pe===G&&$&&(A(null),w({projectId:se.id,directoryOverride:$},{force:!0})),mr(E)===G&&$&&Bs.getState().setDirectory($,{showOverlay:!1}),!0}catch(pe){return me.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:fi(pe instanceof Error?pe.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[de,E,m,Y,k?.directoryOverride,k?.open,A,w,t]),fe=i.useCallback((ue,K)=>{const he=m&&de;(async()=>{if(!await ce(ue,K))return;const G=t(he?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");me.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:fi(G)})})()},[de,m,ce,t]),De=i.useCallback(async()=>{if(a){h(!0);try{const ue=ke,K=ue&&m,he=ue&&u;if(a.sessions.length===0&&be&&a.worktree){fe(a.worktree,he),H();return}if(a.sessions.length===1){const se=a.sessions[0];if(!(be?await I(se.id):await S(se.id,{archiveWorktree:!1,deleteRemoteBranch:K,deleteLocalBranch:he}))){me.error(t(be?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),h(!1);return}const $=!be&&ue?t(K?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;me.success(t(be?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:fi($),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const se=a.sessions.map(pe=>pe.id);let G=[],$=[];if(be){const pe=await N(se);G=pe.archivedIds,$=pe.failedIds}else{const pe=await D(se);G=pe.deletedIds,$=pe.failedIds}if(be&&a.worktree&&$.length===0&&fe(a.worktree,he),G.length>0){const pe=!be&&ue?t(K?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,z=[$.length>0?be?$.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:$.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:$.length}):$.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:$.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:$.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,pe].filter(Boolean).join(" ");me.success(be?G.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:G.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:G.length}):G.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:G.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:G.length}),{description:fi(z||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if($.length>0&&(me.error(be?$.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:$.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:$.length}):$.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:$.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:$.length}),{description:fi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),G.length===0)){h(!1);return}}be&&a.sessions.length===1&&a.worktree&&fe(a.worktree,he),H()}finally{h(!1)}}},[a,m,u,S,D,I,N,H,ke,be,fe,t]),Re=a?.worktree??l[0]?.metadata??null,Fe=a?a.mode==="worktree"?a.sessions.length===0?t("sessions.sidebar.dialogs.worktreeDelete.descriptionNoLinked"):a.sessions.length===1?t("sessions.sidebar.dialogs.worktreeDelete.descriptionOneLinked",{count:a.sessions.length}):t("sessions.sidebar.dialogs.worktreeDelete.descriptionManyLinked",{count:a.sessions.length}):a.sessions.length===1?a.dateLabel?t("sessions.sidebar.dialogs.sessionDelete.descriptionOneWithDate",{dateLabel:a.dateLabel}):t("sessions.sidebar.dialogs.sessionDelete.descriptionOne"):a.dateLabel?t("sessions.sidebar.dialogs.sessionDelete.descriptionManyWithDate",{count:a.sessions.length,dateLabel:a.dateLabel}):t("sessions.sidebar.dialogs.sessionDelete.descriptionMany",{count:a.sessions.length}):"",Oe=a?s.jsxs("div",{className:Te(be?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:Te(be?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[be&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?t("sessions.sidebar.sessionDialogs.linkedSessionSingle"):t("sessions.sidebar.sessionDialogs.linkedSessionPlural")}),s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:a.sessions.length})]}),s.jsxs("ul",{className:Te(be?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(ue=>s.jsxs("li",{className:Te(be?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[s.jsx("span",{className:Te(!be&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:ue.title||t("sessions.sidebar.session.untitled")})]},ue.id)),a.sessions.length>5&&s.jsx("li",{className:Te(be?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:t("sessions.sidebar.dialogs.sessionList.more",{count:a.sessions.length-5})})]})]}),be?s.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(T,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:t("sessions.sidebar.sessionDialogs.worktree.label")}),Re?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Re.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Re?pa(Re.path,V):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),te&&s.jsx("p",{className:"typography-micro text-status-warning",children:t("sessions.sidebar.sessionDialogs.worktree.uncommittedWarning")})]}):s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:t("sessions.sidebar.sessionDialogs.delete.note")})})]}):null,Ee=be?de?s.jsxs("button",{type:"button",onClick:()=>{ae||f(ue=>!ue)},disabled:ae,className:Te("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ae?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[m?s.jsx(T,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(T,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteRemoteBranch")]}):s.jsx("span",{className:"text-xs text-muted-foreground/70",children:t("sessions.sidebar.sessionDialogs.actions.remoteBranchInfoUnavailable")}):null,we=be?s.jsxs("button",{type:"button",onClick:()=>{ve||g(ue=>!ue)},disabled:ve,className:Te("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ve?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(T,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(T,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Pe=be?s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[we,Ee]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{variant:"ghost",onClick:H,disabled:b,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{variant:"destructive",onClick:De,disabled:b,children:t(b?"sessions.sidebar.sessionDialogs.actions.deleting":"sessions.sidebar.sessionDialogs.actions.deleteWorktree")})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>P(!M),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":!M,children:[M?s.jsx(T,{name:"checkbox-blank",className:"size-4"}):s.jsx(T,{name:"checkbox",className:"size-4 text-primary"}),t("sessions.sidebar.dialogs.neverAsk")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{variant:"ghost",onClick:H,disabled:b,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{variant:"destructive",onClick:De,disabled:b,children:b?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),Se=be?t("sessions.sidebar.sessionDialogs.actions.deleteWorktree"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction");return s.jsxs(s.Fragment,{children:[oe?s.jsx(Pa,{open:!!a,onClose:()=>{b||H()},title:Se,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Pe}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[Fe&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Fe}),Oe]})}):s.jsx(Cs,{open:!!a,onOpenChange:ue=>{if(!ue){if(b)return;H()}},children:s.jsxs(ks,{className:Te(be?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[s.jsxs(Ms,{children:[s.jsxs(Ps,{className:Te(be&&"flex items-center gap-2"),children:[be&&s.jsx(T,{name:"delete-bin",className:"h-5 w-5"}),Se]}),Fe&&s.jsx(qs,{children:Fe})]}),s.jsx("div",{className:Te(be&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:Oe}),s.jsx(qn,{className:"mt-2 gap-2 pt-1 pb-1",children:Pe})]})}),s.jsx(jx,{open:e,onOpenChange:n})]})},Jl=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),vN=(t,e)=>{const n=Jl(t),r=Jl(e);return`${n}-${r}`.substring(0,60)},Xu=(t,e)=>`${t}/${e}`,jN=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},Zu=(t,e)=>{const n=jN(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};Rg(t.id,n),mt.getState().markSessionAsOpenChamberCreated(t.id),gr.getState().upsertSession(o);try{ga().ensureChild(n,{bootstrap:!1}).setState(c=>{const l=c.session.findIndex(m=>m.id===t.id);if(l>=0&&c.session[l]===o)return c;const d=l>=0?c.session.map((m,f)=>f===l?o:m):[...c.session,o].sort((m,f)=>m.id.localeCompare(f.id));return{session:d,sessionTotal:Math.max(c.sessionTotal,d.length),limit:Math.max(c.limit,d.length)}})}catch{}return o},SN=()=>{const t=ds.getState(),e=t.activeProjectId;if(!e)return null;const n=t.projects.find(o=>o.id===e);if(n?.path)return{id:n.id,path:n.path};const r=Bs.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},Sl=Zi()(cm(t=>({isLoading:!1,error:null,createMultiRun:async e=>{const n=e.name.trim(),{groups:r,agent:o,files:a,setupCommands:c}=e;if(!n)return t({error:"Group name is required"}),null;if(!r||r.length===0)return t({error:"At least one run group is required"}),null;for(let l=0;l<r.length;l++){if(!r[l].prompt.trim())return t({error:`Group ${l+1}: prompt is required`}),null;if(r[l].models.length<1)return t({error:`Group ${l+1}: select at least 1 model`}),null;if(r[l].models.length>5)return t({error:`Group ${l+1}: maximum 5 models allowed`}),null}t({isLoading:!0,error:null});try{const l=SN();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,f=await Cg(d)&&e.isolateRuns!==!1,u=Jl(n),g=f?await Ea(d):void 0,b=f?await Ag(d):null,h=[],x=c?.filter(k=>k.trim().length>0)??[];for(let k=0;k<r.length;k++){const w=r[k],A=w.prompt,S=new Map;for(const D of w.models){const N=`${D.providerID}:${D.modelID}`;S.set(N,(S.get(N)||0)+1)}const I=new Map;for(const D of w.models){const N=`${D.providerID}:${D.modelID}`,M=S.get(N)||1,P=(I.get(N)||0)+1;I.set(N,P);const E=vN(D.providerID,D.modelID),V=r.length>1?`g${k+1}`:void 0,R=M>1?Xu(u,`${E}/${P}`):Xu(u,E),B=V?`${V}/${R}`:R,O=_2({groupSlug:u,runGroup:V,providerID:D.providerID,modelID:D.modelID,index:M>1?P:void 0});try{if(!f){const oe=await Cn.withDirectory(d,()=>Cn.createSession({title:O}));Zu(oe,d),h.push({sessionId:oe.id,worktreePath:d,providerID:D.providerID,modelID:D.modelID,variant:D.variant,prompt:A});continue}const F=await Dg(l,{preferredName:B,mode:"new",branchName:B,worktreeName:B,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:x,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:b}),_={...F,createdFromBranch:g,kind:"standard"},ie=await Cn.withDirectory(F.path,()=>Cn.createSession({title:O}));Zu(ie,F.path),mt.getState().setWorktreeMetadata(ie.id,_),h.push({sessionId:ie.id,worktreePath:F.path,providerID:D.providerID,modelID:D.modelID,variant:D.variant,prompt:A})}catch(F){console.warn("[MultiRun] Failed to create session:",F)}}}const y=c?.filter(k=>k.trim().length>0)??[];y.length>0&&Tg(l,y).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const p=h.map(k=>k.sessionId),C=h[0]?.sessionId??null;if(p.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const v=a?.map(k=>({type:"file",mime:k.mime,filename:k.filename,url:k.url}));return(async()=>{try{const k=Pg.getState().expandText;await Promise.allSettled(h.map(async w=>{try{const A=await k(w.prompt).catch(()=>w.prompt);await Ig({sessionId:w.sessionId,directory:w.worktreePath,content:A,providerID:w.providerID,modelID:w.modelID,variant:w.variant,agent:o,files:v})}catch(A){console.warn("[MultiRun] Failed to start run:",A)}}))}catch(k){console.warn("[MultiRun] Failed to start runs:",k)}})(),t({isLoading:!1}),{groupSlug:u,sessionIds:p,firstSessionId:C}}catch(l){return t({error:l instanceof Error?l.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"})),NN="oc:lastWorktreeSourceBranch";function Jf(t){const e=ht.c(30),{git:n}=_n(),r=Im(t),o=dc(t),a=uc(t),c=Eg(t),l=an(TN),d=an(DN);let m,f;e[0]!==t||e[1]!==d||e[2]!==n||e[3]!==o||e[4]!==a?(m=()=>{!t||!n||o!==null||a||d(t,n,{silent:!0})},f=[t,n,d,o,a],e[0]=t,e[1]=d,e[2]=n,e[3]=o,e[4]=a,e[5]=m,e[6]=f):(m=e[5],f=e[6]),i.useEffect(m,f);let u;e[7]!==r?.all||e[8]!==t||e[9]!==l||e[10]!==n||e[11]!==o?(u=()=>{!t||!n||o===!0&&(r?.all||l(t,n))},e[7]=r?.all,e[8]=t,e[9]=l,e[10]=n,e[11]=o,e[12]=u):u=e[12];const g=r?.all;let b;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==g?(b=[t,n,o,g,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=g,e[18]=b):b=e[18],i.useEffect(u,b);const h=a||o===!0&&c;let x;e:{if(!r?.all){let S;e[19]===Symbol.for("react.memo_cache_sentinel")?(S=[],e[19]=S):S=e[19],x=S;break e}let A;e[20]!==r.all?(A=r.all.filter(AN).sort(),e[20]=r.all,e[21]=A):A=e[21],x=A}const y=x;let p;e:{if(!r?.all){let S;e[22]===Symbol.for("react.memo_cache_sentinel")?(S=[],e[22]=S):S=e[22],p=S;break e}let A;e[23]!==r.all?(A=r.all.filter(CN).map(kN).sort(),e[23]=r.all,e[24]=A):A=e[24],p=A}const C=p;let v;e:{if(!t){v=null;break e}if(o!==null){v=o;break e}if(h){v=null;break e}v=r?.all?!0:null}const k=v;let w;return e[25]!==k||e[26]!==h||e[27]!==y||e[28]!==C?(w={localBranches:y,remoteBranches:C,isLoading:h,isGitRepository:k},e[25]=k,e[26]=h,e[27]=y,e[28]=C,e[29]=w):w=e[29],w}function kN(t){return t.replace(/^remotes\//,"")}function CN(t){return t.startsWith("remotes/")}function AN(t){return!t.startsWith("remotes/")}function DN(t){return t.fetchStatus}function TN(t){return t.fetchBranches}const PN=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=jt(),{localBranches:l,remoteBranches:d,isLoading:m,isGitRepository:f}=Jf(t),u=i.useMemo(()=>[...l,...d.map(b=>`remotes/${b}`)],[l,d]);i.useEffect(()=>{if(o||m||u.length===0||e&&u.includes(e))return;(async()=>{try{const h=t?await Ea(t).catch(()=>null):null,x=localStorage.getItem(NN);x&&u.includes(x)?n(x):h&&u.includes(h)?n(h):u.includes("main")?n("main"):u.includes("master")?n("master"):u[0]&&n(u[0])}catch{}})()},[u,t,o,m,n,e]);const g=o||!f||m;return s.jsxs("div",{children:[s.jsxs(Dn,{value:e,onValueChange:n,disabled:g,children:[s.jsx(Tn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(fn,{placeholder:c(m?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(Pn,{className:"max-h-[280px] max-w-[320px]",children:m?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.loadingBranches")}):l.length===0&&d.length===0?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.noBranchesFound")}):s.jsxs(s.Fragment,{children:[l.length>0&&s.jsxs(Rl,{children:[s.jsx(jd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(b=>s.jsx(vs,{value:b,className:"whitespace-normal break-all",children:b},b))]}),l.length>0&&d.length>0&&s.jsx(Mg,{}),d.length>0&&s.jsxs(Rl,{children:[s.jsx(jd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(b=>s.jsx(vs,{value:`remotes/${b}`,className:"whitespace-normal break-all",children:b},`remotes/${b}`))]})]})})]}),f===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},IN=10*1024*1024,Nl=5,oa=t=>{const e=ht.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",tabIndex:-1,className:"inline-flex items-center justify-center text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:s.jsx(T,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(Nt,{children:[r,s.jsx(Ct,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},xi=t=>{const e=ht.c(9),{htmlFor:n,required:r,children:o,info:a}=t;let c;e[0]!==r?(c=r&&s.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),e[0]=r,e[1]=c):c=e[1];let l;e[2]!==o||e[3]!==n||e[4]!==c?(l=s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,c]}),e[2]=o,e[3]=n,e[4]=c,e[5]=l):l=e[5];const d=a&&a;let m;return e[6]!==l||e[7]!==d?(m=s.jsxs("div",{className:"flex items-center gap-1.5",children:[l,d]}),e[6]=l,e[7]=d,e[8]=m):m=e[8],m},RN=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=jt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:vo(),prompt:"",models:[]}]),[m,f]=i.useState(""),[u,g]=i.useState([]),[b,h]=i.useState(!1),[x,y]=i.useState([]),[p,C]=i.useState(!1),[v,k]=i.useState(!1),[w,A]=i.useState(!0),S=i.useRef(null),I=Bs($=>$.currentDirectory??null),D=Bs($=>$.homeDirectory??null),N=i.useMemo(()=>{if(typeof window>"u")return null;const $=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof $=="string"&&$.trim().length>0?$.trim():null},[]),M=ds($=>$.activeProjectId),P=ds($=>$.setActiveProjectIdOnly),E=ds($=>$.projects),[V,R]=i.useState(()=>M??null);i.useEffect(()=>{if(M){R(M);return}!V&&E.length>0&&R(E[0].id)},[M,E,V]);const B=i.useMemo(()=>V?E.find($=>$.id===V)??null:null,[E,V]),O=B?.path??I,F=i.useCallback($=>{R($),$!==M&&P($)},[M,P]),{currentTheme:_}=Lr(),ie=i.useCallback($=>{const pe=$.label?.trim()||Ci($.path,D),ye=$.icon?gc[$.icon]:null,z=$.color?Fa[$.color]:void 0,Ne=ye?s.jsx(T,{name:ye,className:"h-3.5 w-3.5 shrink-0",style:z?{color:z}:void 0}):s.jsx(T,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:z?{color:z}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[$.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:$.iconBackground?{backgroundColor:$.iconBackground}:void 0,children:s.jsx(La,{project:{id:$.id,iconImage:$.iconImage??null},options:{themeVariant:_.metadata.variant,iconColor:_.colors.surface.foreground},className:"h-full w-full object-contain",fallback:Ne})}):Ne,s.jsx("span",{className:"truncate",children:pe})]})},[D,_.metadata.variant,_.colors.surface.foreground]),oe=i.useMemo(()=>{if(B?.path)return{id:B.id,path:B.path};const $=I??N;return $?{id:`path:${$}`,path:$}:null},[B,I,N]),[ne]=i.useState(()=>typeof window<"u"?er():!1),Y=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),te=ym(),de=i.useMemo(()=>{if(typeof window>"u")return null;const $=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof $=="number"&&Number.isFinite($)&&$>0)return $;if(typeof navigator>"u")return null;const pe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!pe)return null;const ye=Number.parseInt(pe[1],10),z=Number.parseInt(pe[2],10);return Number.isNaN(ye)?null:ye===10?z:ye},[]),be=i.useMemo(()=>ne&&Y||te?"pl-[5.5rem]":"pl-3",[ne,Y,te]),ke=i.useMemo(()=>!ne||!Y||de===null?"":de>=26?"h-12":de<=15?"h-14":"",[ne,Y,de]),ae=i.useCallback(async $=>{$.target.closest("button, a, input, select, textarea")||$.button===0&&ne&&await Fg()},[ne]);i.useEffect(()=>{if(!n)return;const $=pe=>{pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),n())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[n]);const[ve,J]=i.useState(""),{isLoading:H,isGitRepository:q}=Jf(O),ce=i.useRef(!1),fe=q===!0,De=fe&&w;i.useEffect(()=>{if(q===!1){ce.current=!0,A(!1);return}q===!0&&ce.current&&(ce.current=!1,A(!0))},[q]);const Re=Sl($=>$.createMultiRun),Fe=Sl($=>$.error),Oe=Sl($=>$.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d($=>{const pe=[...$];return pe.length>0&&!pe[0].prompt.trim()&&(pe[0]={...pe[0],prompt:t}),pe})},[t]),i.useEffect(()=>{if(!oe)return;let $=!1;return k(!0),(async()=>{try{const pe=await Lg(oe);$||y(pe)}catch{}finally{$||k(!1)}})(),()=>{$=!0}},[oe]);const Ee=i.useCallback(($,pe)=>{d(ye=>ye.map(z=>z.id===$?{...z,...pe}:z))},[]),we=i.useCallback($=>{d(pe=>pe.filter(ye=>ye.id!==$))},[]),Pe=i.useCallback(()=>{d($=>[...$,{id:vo(),prompt:"",models:[]}])},[]),Se=async $=>{const pe=$.target.files;if(!pe)return;let ye=0;for(let z=0;z<pe.length;z++){const Ne=pe[z];if(Ne.size>IN){me.error(o("multirun.launcher.toast.fileTooLarge",{fileName:Ne.name}));continue}try{const U=await new Promise((Ie,_e)=>{const Ve=new FileReader;Ve.onload=()=>Ie(Ve.result),Ve.onerror=_e,Ve.readAsDataURL(Ne)});g(Ie=>[...Ie,{id:vo(),filename:Ne.name,mimeType:Ne.type||"application/octet-stream",size:Ne.size,dataUrl:U}]),ye++}catch(U){console.error("File attach failed",U),me.error(o("multirun.launcher.toast.attachFailed",{fileName:Ne.name}))}}ye>0&&me.success(ye===1?o("multirun.launcher.toast.attachedSingle",{count:ye}):o("multirun.launcher.toast.attachedPlural",{count:ye})),S.current&&(S.current.value="")},ue=$=>{g(pe=>pe.filter(ye=>ye.id!==$))},K=i.useMemo(()=>l.reduce(($,pe)=>$+pe.models.length,0),[l]),he=async $=>{$.preventDefault();const pe=l.filter(ye=>ye.prompt.trim()&&ye.models.length>=1);if(pe.length!==0&&!(K<1)){h(!0),Oe();try{V&&V!==M&&P(V);const ye=u.map(_e=>({mime:_e.mimeType,filename:_e.filename,url:_e.dataUrl})),z=x.filter(_e=>_e.trim().length>0),Ne=pe.map(_e=>({prompt:_e.prompt.trim(),models:_e.models.map(Ve=>({providerID:Ve.providerID,modelID:Ve.modelID,displayName:Ve.displayName,variant:Ve.variant}))})),U={name:a.trim(),groups:Ne,agent:m||void 0,worktreeBaseBranch:De?ve:void 0,isolateRuns:De,files:ye.length>0?ye:void 0,setupCommands:z.length>0?z:void 0},Ie=await Re(U);Ie&&(Ie.firstSessionId&&mt.getState().setCurrentSession(Ie.firstSessionId),e?.())}finally{h(!1)}}},se=!!(a.trim()&&l.some($=>$.prompt.trim()&&$.models.length>=1)&&K>=1&&O&&!H&&(q===!1||!De||ve)),G=x.filter($=>$.trim()).length;return s.jsxs("form",{onSubmit:he,className:"flex flex-col h-full bg-background",children:[r?null:s.jsxs("header",{onMouseDown:ae,className:Te("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",be,ke),style:{borderColor:"var(--interactive-border)"},children:[s.jsx("h1",{className:"typography-ui-label font-medium",children:o("multirun.launcher.title")}),n&&s.jsx("div",{className:"absolute right-0 flex items-center pr-3",children:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":o("multirun.launcher.actions.closeEsc"),className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:s.jsx(T,{name:"close",className:"h-5 w-5"})})}),s.jsx(Ct,{children:s.jsx("p",{children:o("multirun.launcher.actions.closeEsc")})})]})})]}),s.jsx(Ia,{className:"flex-1 min-h-0 overflow-auto",size:64,hideTopShadow:!0,children:s.jsx("div",{className:"mx-auto w-full max-w-2xl px-4 sm:px-6 py-5",children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:[s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(xi,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),E.length>0?s.jsxs(Dn,{value:V??void 0,onValueChange:F,children:[s.jsx(Tn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:B?s.jsx(fn,{children:ie(B)}):s.jsx(fn,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(Pn,{fitContent:!0,children:E.map($=>s.jsx(vs,{value:$.id,className:"max-w-[24rem]",children:ie($)},$.id))})]}):s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:o("multirun.launcher.project.empty")})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(xi,{htmlFor:"group-name",required:!0,info:s.jsx(oa,{children:o("multirun.launcher.groupName.info")}),children:o("multirun.launcher.groupName.label")}),s.jsx(ln,{id:"group-name",value:a,onChange:$=>c($.target.value),placeholder:o("multirun.launcher.groupName.placeholder"),className:"typography-meta w-full",required:!0})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(xi,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(oa,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(PN,{directory:O,value:ve,onChange:J,disabled:!De,id:"multirun-worktree-base-branch"}),s.jsxs("label",{className:"mt-1.5 flex w-fit items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(ki,{checked:w,onChange:A,disabled:!fe,ariaLabel:o("multirun.launcher.isolateRuns.label")}),s.jsx("span",{children:o("multirun.launcher.isolateRuns.label")})]})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(xi,{htmlFor:"multirun-agent",info:s.jsx(oa,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(Kf,{value:m,onChange:f,id:"multirun-agent"})]})]}),s.jsxs(Yi,{open:p,onOpenChange:C,children:[s.jsxs(Io,{className:"w-full flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-lg hover:bg-[var(--interactive-hover)]/50 transition-colors group",children:[s.jsx(T,{name:"terminal",className:"h-3.5 w-3.5 text-muted-foreground/70"}),s.jsx("span",{className:"typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors",children:o("multirun.launcher.setupCommands.label")}),G>0&&s.jsx("span",{className:"inline-flex items-center justify-center h-4 min-w-4 px-1 rounded-full typography-micro font-medium",style:{backgroundColor:"var(--primary-base)",color:"var(--primary-foreground)",fontSize:"0.625rem",lineHeight:1},children:G}),s.jsx(T,{name:"arrow-down-s",className:Te("h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto",p&&"rotate-180")})]}),s.jsx(Ji,{children:s.jsx("div",{className:"pt-2 space-y-1.5",children:v?s.jsx("p",{className:"typography-meta text-muted-foreground/70 px-2",children:o("multirun.launcher.setupCommands.loading")}):s.jsxs(s.Fragment,{children:[x.map(($,pe)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(ln,{value:$,onChange:ye=>{const z=[...x];z[pe]=ye.target.value,y(z)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>y(x.filter((ye,z)=>z!==pe)),className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":o("multirun.launcher.setupCommands.removeCommandAria"),children:s.jsx(T,{name:"close",className:"h-3.5 w-3.5"})})]},`${$}-${pe}`)),s.jsxs("button",{type:"button",onClick:()=>y([...x,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(T,{name:"add",className:"h-3 w-3"}),o("multirun.launcher.setupCommands.addCommand")]})]})})})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(xi,{htmlFor:"prompt",required:!0,children:o("multirun.launcher.attachments.label")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("input",{ref:S,type:"file",multiple:!0,className:"hidden",onChange:Se,accept:"*/*"}),s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>S.current?.click(),className:"inline-flex items-center gap-1 h-6 px-2 rounded-md typography-micro text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(T,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(Ct,{children:o("multirun.launcher.attachments.tooltip")})]}),u.map($=>s.jsxs("div",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md typography-micro border",style:{backgroundColor:"var(--surface-elevated)",borderColor:"var(--interactive-border)"},children:[$.mimeType.startsWith("image/")?s.jsx(T,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(T,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:$.filename,children:$.filename}),s.jsx("button",{type:"button",onClick:()=>ue($.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(T,{name:"close",className:"h-3 w-3"})})]},$.id))]})]}),l.map(($,pe)=>s.jsx(EN,{group:$,groupIndex:pe,canRemove:l.length>1,onUpdate:Ee,onRemove:we},$.id)),s.jsxs("button",{type:"button",onClick:Pe,className:"flex items-center gap-1.5 py-2 px-3 -mx-3 rounded-lg typography-meta font-medium text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(T,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),Fe&&s.jsx("div",{className:"px-3 py-2 rounded-lg typography-meta",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderWidth:1,borderColor:"var(--status-error-border)"},children:Fe})]})})}),s.jsx("div",{className:"shrink-0 px-4 sm:px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-2xl flex items-center justify-end gap-2",children:[!De&&q!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(T,{name:"information",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:o("multirun.launcher.project.gitRequired")})]}):null,s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:n,children:o("multirun.launcher.actions.cancel")}),s.jsx(ze,{type:"submit",size:"sm",disabled:!se||b,children:b?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:K})})})]})})]})},EN=t=>{const e=ht.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=jt(),[d,m]=i.useState(!1),[f,u]=i.useState(""),[g,b]=i.useState(!1),[h,x]=i.useState(""),[y,p]=i.useState(!1),[C,v]=i.useState(""),k=i.useRef(null),w=i.useRef(null),A=i.useRef(null),S=i.useRef(null);let I;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(I=z=>{n.models.length>=Nl||a(n.id,{models:[...n.models,z]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=I):I=e[3];const D=I;let N;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(N=z=>{a(n.id,{models:n.models.filter((Ne,U)=>U!==z)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=N):N=e[7];const M=N;let P;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(P=(z,Ne)=>{a(n.id,{models:n.models.map((U,Ie)=>Ie===z?Ne:U)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=P):P=e[11];const E=P;let V;e[12]===Symbol.for("react.memo_cache_sentinel")?(V=(z,Ne)=>{if(z.startsWith("/")){const Ve=z.indexOf(" "),Le=z.indexOf(`
211
- `),X=Math.min(Ve===-1?z.length:Ve,Le===-1?z.length:Le);if(Ne<=X&&Ve===-1){x(z.substring(1,X)),b(!0),m(!1),p(!1);return}}b(!1);const U=z.substring(0,Ne),Ie=U.lastIndexOf("#");if(Ie!==-1){const Ve=Ie>0?U[Ie-1]:null,Le=U.substring(Ie+1);if((!Ve||/\s/.test(Ve))&&!Le.includes(" ")&&!Le.includes(`
212
- `)){v(Le),p(!0),m(!1);return}}p(!1);const _e=U.lastIndexOf("@");if(_e!==-1){const Ve=_e>0?U[_e-1]:null,Le=U.substring(_e+1);(!Ve||/\s/.test(Ve))&&!Le.includes(" ")&&!Le.includes(`
213
- `)?(u(Le),m(!0)):m(!1);return}m(!1)},e[12]=V):V=e[12];const R=V;let B;e[13]!==n.id||e[14]!==a?(B=z=>{a(n.id,{prompt:z})},e[13]=n.id,e[14]=a,e[15]=B):B=e[15];const O=B;let F;e[16]!==n.prompt||e[17]!==O?(F=z=>{const Ne=n.prompt,Ie=k.current?.selectionStart??Ne.length,Ve=Ne.substring(0,Ie).lastIndexOf("@"),Le=z.relativePath&&z.relativePath.trim().length>0?z.relativePath.trim():z.path||z.name,X=Ve!==-1?Ve:Ie,L=`${Ne.substring(0,X)}@${Le} ${Ne.substring(Ie)}`,xe=X+Le.length+2;O(L),m(!1),u(""),requestAnimationFrame(()=>{const Q=k.current;Q&&(Q.selectionStart=xe,Q.selectionEnd=xe,Q.focus()),R(L,xe)})},e[16]=n.prompt,e[17]=O,e[18]=F):F=e[18];const _=F;let ie;e[19]!==n.prompt||e[20]!==O?(ie=z=>{const Ne=n.prompt,Ie=k.current?.selectionStart??Ne.length,Ve=Ne.substring(0,Ie).lastIndexOf("@"),Le=Ve!==-1?Ve:Ie,X=`${Ne.substring(0,Le)}@${z} ${Ne.substring(Ie)}`,L=Le+z.length+2;O(X),m(!1),u(""),requestAnimationFrame(()=>{const xe=k.current;xe&&(xe.selectionStart=L,xe.selectionEnd=L,xe.focus()),R(X,L)})},e[19]=n.prompt,e[20]=O,e[21]=ie):ie=e[21];const oe=ie;let ne;e[22]!==O?(ne=z=>{const Ne=`/${z.name} `;O(Ne),b(!1),x(""),p(!1),requestAnimationFrame(()=>{const U=k.current;U&&(U.focus(),U.selectionStart=U.value.length,U.selectionEnd=U.value.length),R(Ne,Ne.length)})},e[22]=O,e[23]=ne):ne=e[23];const Y=ne;let te;e[24]!==n.prompt||e[25]!==O?(te=(z,Ne)=>{const U=n.prompt,_e=k.current?.selectionStart??U.length,Le=U.substring(0,_e).lastIndexOf("#"),X=Le!==-1?Le:_e,L=`${U.substring(0,X)}#${Ne} ${U.substring(_e)}`,xe=X+Ne.length+2;O(L),p(!1),v(""),requestAnimationFrame(()=>{const Q=k.current;Q&&(Q.selectionStart=xe,Q.selectionEnd=xe,Q.focus()),R(L,xe)})},e[24]=n.prompt,e[25]=O,e[26]=te):te=e[26];const de=te;let be;e[27]!==g||e[28]!==d||e[29]!==y?(be=z=>{if(g&&A.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")){z.preventDefault(),A.current.handleKeyDown(z.key);return}d&&w.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")&&(z.preventDefault(),w.current.handleKeyDown(z.key)),y&&S.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")&&(z.preventDefault(),S.current.handleKeyDown(z.key))},e[27]=g,e[28]=d,e[29]=y,e[30]=be):be=e[30];const ke=be,ae=r+1;let ve;e[31]!==l||e[32]!==ae?(ve=l("multirun.launcher.groups.groupLabel",{index:ae}),e[31]=l,e[32]=ae,e[33]=ve):ve=e[33];let J;e[34]!==ve?(J=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:ve}),e[34]=ve,e[35]=J):J=e[35];let H;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(H=o&&s.jsx("button",{type:"button",onClick:()=>c(n.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":l("multirun.launcher.groups.removeGroup"),children:s.jsx(T,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=H):H=e[40];let q;e[41]!==J||e[42]!==H?(q=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[J,H]}),e[41]=J,e[42]=H,e[43]=q):q=e[43];let ce;e[44]!==l?(ce=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=ce):ce=e[45];let fe;e[46]!==ce?(fe=s.jsx(xi,{required:!0,children:ce}),e[46]=ce,e[47]=fe):fe=e[47];const De=n.prompt;let Re;e[48]!==O?(Re=z=>{const Ne=z.target.value;O(Ne);const U=z.target.selectionStart??Ne.length;R(Ne,U)},e[48]=O,e[49]=Re):Re=e[49];let Fe;e[50]!==l?(Fe=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=Fe):Fe=e[51];let Oe;e[52]!==n.prompt||e[53]!==ke||e[54]!==Re||e[55]!==Fe?(Oe=s.jsx(yi,{ref:k,value:De,onChange:Re,onKeyDown:ke,placeholder:Fe,className:"typography-meta min-h-[80px] max-h-[200px] resize-none overflow-y-auto field-sizing-content",required:!0}),e[52]=n.prompt,e[53]=ke,e[54]=Re,e[55]=Fe,e[56]=Oe):Oe=e[56];let Ee;e[57]!==h||e[58]!==Y||e[59]!==g?(Ee=g?s.jsx(Bm,{ref:A,searchQuery:h,onCommandSelect:Y,onClose:()=>b(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=h,e[58]=Y,e[59]=g,e[60]=Ee):Ee=e[60];let we;e[61]!==oe||e[62]!==_||e[63]!==f||e[64]!==d?(we=d?s.jsx(_m,{ref:w,searchQuery:f,onFileSelect:_,onAgentSelect:oe,onClose:()=>m(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=oe,e[62]=_,e[63]=f,e[64]=d,e[65]=we):we=e[65];let Pe;e[66]!==de||e[67]!==y||e[68]!==C?(Pe=y?s.jsx(Vm,{ref:S,searchQuery:C,onSnippetSelect:de,onClose:()=>p(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=de,e[67]=y,e[68]=C,e[69]=Pe):Pe=e[69];let Se;e[70]!==Oe||e[71]!==Ee||e[72]!==we||e[73]!==Pe?(Se=s.jsxs("div",{className:"relative",children:[Oe,Ee,we,Pe]}),e[70]=Oe,e[71]=Ee,e[72]=we,e[73]=Pe,e[74]=Se):Se=e[74];let ue;e[75]!==fe||e[76]!==Se?(ue=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[fe,Se]}),e[75]=fe,e[76]=Se,e[77]=ue):ue=e[77];let K;e[78]!==l?(K=l("multirun.launcher.models.info",{max:Nl}),e[78]=l,e[79]=K):K=e[79];let he;e[80]!==K?(he=s.jsx(oa,{children:K}),e[80]=K,e[81]=he):he=e[81];let se;e[82]!==l?(se=l("multirun.launcher.models.label"),e[82]=l,e[83]=se):se=e[83];let G;e[84]!==he||e[85]!==se?(G=s.jsx(xi,{required:!0,info:he,children:se}),e[84]=he,e[85]=se,e[86]=G):G=e[86];let $;e[87]!==n.models||e[88]!==D||e[89]!==M||e[90]!==E?($=s.jsx(Yf,{selectedModels:n.models,onAdd:D,onRemove:M,onUpdate:E,minModels:1,maxModels:Nl}),e[87]=n.models,e[88]=D,e[89]=M,e[90]=E,e[91]=$):$=e[91];let pe;e[92]!==G||e[93]!==$?(pe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[G,$]}),e[92]=G,e[93]=$,e[94]=pe):pe=e[94];let ye;return e[95]!==q||e[96]!==ue||e[97]!==pe?(ye=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[q,ue,pe]}),e[95]=q,e[96]=ue,e[97]=pe,e[98]=ye):ye=e[98],ye},MN=i.createContext(null),FN=t=>{const e=ht.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(MN.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},em=eo(()=>Ai(()=>import("./TerminalView-CLKpaKdm.js"),__vite__mapDeps([5,1,2,0,3,4,6,7,8])).then(t=>({default:t.TerminalView}))),LN=eo(()=>Ai(()=>import("./DiagramView-la2P5DUr.js"),__vite__mapDeps([9,1,2,3,4,0,6,7,8])).then(t=>({default:t.DiagramView}))),ON=eo(()=>Ai(()=>import("./NewWorktreeDialog-BnK_0_OO.js").then(t=>t.a7),__vite__mapDeps([6,1,2,0,3,4,7])).then(t=>({default:t.SettingsView}))),BN=eo(()=>Ai(()=>import("./SettingsWindow-Cs3xbqtf.js"),__vite__mapDeps([10,1,2,0,3,4,6,7])).then(t=>({default:t.SettingsWindow}))),_N=eo(()=>Ai(()=>import("./MultiRunWindow-B9NPliTC.js"),__vite__mapDeps([11,1,2,0,3,4,6,7,8])).then(t=>({default:t.MultiRunWindow}))),VN=()=>{const o=Me(te=>te.isSidebarOpen),a=Me(te=>te.isRightSidebarOpen),c=Me(te=>te.isBottomTerminalOpen),l=Me(te=>te.setRightSidebarOpen),d=Me(te=>te.setBottomTerminalOpen),m=Me(te=>te.activeMainTab),f=Me(te=>te.setIsMobile),u=Me(te=>te.isSessionSwitcherOpen),g=Me(te=>te.isSettingsDialogOpen),b=Me(te=>te.setSettingsDialogOpen),h=Me(te=>te.isMultiRunLauncherOpen),x=Me(te=>te.setMultiRunLauncherOpen),y=Me(te=>te.multiRunLauncherPrefillPrompt),{isMobile:p,isTablet:C}=Ar(),v=i.useRef(!1),k=i.useRef(!1),w=i.useRef(!1),[A,S]=i.useState(!1),[I,D]=i.useState(!1),[N,M]=i.useState(!1),[P,E]=i.useState(!1),V=i.useCallback(te=>{S(te),Me.getState().setSessionSwitcherOpen(te)},[]),R=i.useRef(!1),B=i.useRef(typeof window>"u"?0:window.innerWidth),O=Jc(-B.current),F=Qe.useRef(0),_=Jc(B.current),ie=Qe.useRef(0);Qe.useEffect(()=>{p&&(F.current=window.innerWidth,ie.current=window.innerWidth)},[p]),Qe.useEffect(()=>{if(!p){M(!1);return}A&&M(!0),Qc(O,A?0:-F.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[A,p,O]),Qe.useEffect(()=>{if(!p){E(!1);return}R.current=I,I&&E(!0),Qc(_,I?0:ie.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[p,I,_]),Qe.useEffect(()=>{if(p)return O.on("change",te=>{const de=F.current||B.current,be=A||te>-de+.5;M(ke=>ke===be?ke:be)})},[p,O,A]),Qe.useEffect(()=>{if(p)return _.on("change",te=>{const de=ie.current||B.current,be=I||te<de-.5;E(ke=>ke===be?ke:be)})},[p,I,_]),Qe.useEffect(()=>{p&&!u&&A&&V(!1)},[u,p,A,V]),Qe.useEffect(()=>{if(!p){w.current=!1;return}w.current||(w.current=!0,V(!1),D(!1),Me.getState().isRightSidebarOpen&&l(!1))},[p,V,l]),Qe.useEffect(()=>{if(!p||m!=="chat"||A||I||g)return;let te=!1,de;const be=ke=>{de=window.setTimeout(()=>{if(te)return;const ae=mt.getState(),ve=Me.getState();if(!(ve.activeMainTab!=="chat"||ve.isSettingsDialogOpen||ae.currentSessionId||ae.newSessionDraft?.open)){if(ae.isLoading){be(250);return}ae.openNewSessionDraft()}},ke)};return be(500),()=>{te=!0,de!==void 0&&window.clearTimeout(de)}},[m,p,g,A,I]),Qe.useEffect(()=>{!p||!g||(V(!1),D(!1),a&&l(!1))},[p,g,a,V,l]),Sx(),i.useEffect(()=>{Me.getState().isMobile!==p&&f(p)},[p,f]),i.useEffect(()=>{if(typeof window>"u")return;let te;const de=()=>{te===void 0&&(te=window.requestAnimationFrame(()=>{te=void 0,Me.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",de),()=>{window.removeEventListener("resize",de),te!==void 0&&window.cancelAnimationFrame(te)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let te;const de=()=>{const ke=Me.getState(),ae=window.innerWidth,ve=window.innerHeight;if(!p&&!C){const J=ae<1140,H=ae>=1220;J?ke.isRightSidebarOpen&&(l(!1),v.current=!0):H&&v.current&&(l(!0),v.current=!1);const q=ve<640,ce=ve>=700;q?ke.isBottomTerminalOpen&&(d(!1),k.current=!0):ce&&k.current&&(d(!0),k.current=!1)}},be=()=>{te===void 0&&(te=window.requestAnimationFrame(()=>{te=void 0,de()}))};return de(),window.addEventListener("resize",be),()=>{window.removeEventListener("resize",be),te!==void 0&&window.cancelAnimationFrame(te)}},[p,C,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const te=Me.subscribe((de,be)=>{const ke=window.innerWidth,ae=window.innerHeight,ve=ke>=1220,J=ae>=700;de.isRightSidebarOpen!==be.isRightSidebarOpen&&ve&&(v.current=!1),de.isBottomTerminalOpen!==be.isBottomTerminalOpen&&J&&(k.current=!1)});return()=>{te()}},[p,C,d,l]);const oe=i.useCallback(()=>{A&&V(!1),D(!I)},[A,I,V]),ne=i.useMemo(()=>{switch(m){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Cf,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx($l,{isActive:!I})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(vf,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(em,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(kf,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(xf,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(LN,{})});default:return null}},[m,I]),Y=m==="chat";return s.jsx(Nx,{children:s.jsxs("div",{"data-page-scroll-lock":"true",className:Te("main-content-safe-area",p?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[s.jsx(y0,{}),s.jsx(oj,{}),s.jsx(dj,{}),s.jsx(wN,{}),p?s.jsxs(FN,{value:{leftDrawerOpen:A,rightDrawerOpen:I,toggleLeftDrawer:()=>{const te=!A;I&&D(!1),V(te)},toggleRightDrawer:oe,leftDrawerX:O,rightDrawerX:_,leftDrawerWidth:F,rightDrawerWidth:ie,setMobileLeftDrawerOpen:V,setRightSidebarOpen:D},children:[!g&&s.jsx(Fd,{onToggleLeftDrawer:()=>{const te=!A;I&&D(!1),V(te)},onToggleRightDrawer:()=>{oe()},leftDrawerOpen:A,rightDrawerOpen:I}),s.jsx("div",{"data-page-scroll-lock":"true",className:Te("flex flex-1 overflow-hidden relative",g&&"hidden"),children:s.jsxs("main",{className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[s.jsx("div",{className:Te("absolute inset-0",!Y&&"invisible"),children:s.jsx(Vs,{children:s.jsx(Ll,{})})}),ne&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Vs,{children:ne})}),h&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(Vs,{children:s.jsx(RN,{initialPrompt:y,onCreated:()=>x(!1),onCancel:()=>x(!1)})})}),N&&s.jsx(Xc.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:O},"aria-hidden":!A,children:s.jsx(Vs,{children:s.jsx(Qu,{mobileVariant:!0})})}),P&&s.jsx(Xc.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:_},"aria-hidden":!I,children:s.jsx(Vs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx($l,{isActive:I})})})})]})}),g&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(Vs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(ON,{onClose:()=>b(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(Eb,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(Pb,{isOpen:o,isMobile:p,className:"border-border/50",topBar:s.jsx(Ib,{}),children:s.jsx(Qu,{})}),s.jsxs("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden bg-background","data-page-scroll-lock":"true",children:[s.jsx(Fd,{}),s.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden bg-background","data-page-scroll-lock":"true",children:[s.jsxs("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border/50 bg-background","data-page-scroll-lock":"true",children:[s.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden","data-page-scroll-lock":"true",children:s.jsxs("div",{className:"relative flex flex-1 min-h-0 min-w-0 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[s.jsx("div",{className:Te("absolute inset-0",!Y&&"invisible"),children:s.jsx(Vs,{children:s.jsx(Ll,{})})}),ne&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Vs,{children:ne})})]}),s.jsx(b0,{})]})}),s.jsx(kb,{isOpen:c,isMobile:p,children:c?s.jsx(Vs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(em,{})})}):null})]}),s.jsx(_b,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(Vs,{children:s.jsx(nv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(BN,{open:g,onOpenChange:b})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(_N,{open:h,onOpenChange:x,initialPrompt:y})})]})]})})},$N=t=>{if(t<1e3)return`${Math.round(t)}ms`;const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e/60),r=Math.round(e%60);return`${n}m ${r}s`},kn=t=>{const e=ht.c(8),{label:n,value:r}=t;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[0]=o):o=e[0];let a;e[1]!==n?(a=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:n}),e[1]=n,e[2]=a):a=e[2];let c;e[3]!==r?(c=s.jsx("div",{className:"typography-markdown font-semibold text-[var(--surface-foreground)]",children:r}),e[3]=r,e[4]=c):c=e[4];let l;return e[5]!==a||e[6]!==c?(l=s.jsxs("div",{className:"rounded-md p-2",style:o,children:[a,c]}),e[5]=a,e[6]=c,e[7]=l):l=e[7],l},tm=t=>{const e=ht.c(43),{title:n,snapshot:r,emptyLabel:o}=t,{t:a}=jt();let c;if(e[0]!==o||e[1]!==r.durationMs||e[2]!==r.entries||e[3]!==r.lastUpdatedAt||e[4]!==r.startedAt||e[5]!==a||e[6]!==n){const l=r.entries.slice(0,12);let d;e[8]!==r.entries?(d=r.entries.reduce(UN,0),e[8]=r.entries,e[9]=d):d=e[9];const m=d;let f;e[10]!==n?(f=s.jsx("div",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:n}),e[10]=n,e[11]=f):f=e[11];let u;e[12]!==r.durationMs||e[13]!==r.startedAt||e[14]!==a?(u=r.startedAt?$N(r.durationMs):a("memoryDebugPanel.common.idle"),e[12]=r.durationMs,e[13]=r.startedAt,e[14]=a,e[15]=u):u=e[15];let g;e[16]!==u?(g=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:u}),e[16]=u,e[17]=g):g=e[17];let b;e[18]!==f||e[19]!==g?(b=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[f,g]}),e[18]=f,e[19]=g,e[20]=b):b=e[20];let h;e[21]!==a?(h=a("memoryDebugPanel.metric.metrics"),e[21]=a,e[22]=h):h=e[22];let x;e[23]!==r.entries.length||e[24]!==h?(x=s.jsx(kn,{label:h,value:r.entries.length}),e[23]=r.entries.length,e[24]=h,e[25]=x):x=e[25];let y;e[26]!==a?(y=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=y):y=e[27];let p;e[28]!==y||e[29]!==m?(p=s.jsx(kn,{label:y,value:m}),e[28]=y,e[29]=m,e[30]=p):p=e[30];let C;e[31]!==a?(C=a("memoryDebugPanel.metric.lastUpdate"),e[31]=a,e[32]=C):C=e[32];let v;e[33]!==r.lastUpdatedAt||e[34]!==a?(v=r.lastUpdatedAt?a("memoryDebugPanel.common.live"):a("memoryDebugPanel.common.notAvailable"),e[33]=r.lastUpdatedAt,e[34]=a,e[35]=v):v=e[35];let k;e[36]!==C||e[37]!==v?(k=s.jsx(kn,{label:C,value:v}),e[36]=C,e[37]=v,e[38]=k):k=e[38];let w;e[39]!==p||e[40]!==k||e[41]!==x?(w=s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[x,p,k]}),e[39]=p,e[40]=k,e[41]=x,e[42]=w):w=e[42],c=s.jsxs("div",{className:"space-y-2 border-t border-[var(--interactive-border)] pt-2 first:border-t-0 first:pt-0",children:[b,w,l.length===0?s.jsx("div",{className:"rounded-md p-3 typography-meta text-[var(--surface-muted-foreground)]",style:{backgroundColor:"color-mix(in srgb, var(--surface-muted) 45%, transparent)"},children:o}):s.jsx(An,{outerClassName:"max-h-64",className:"pr-1",children:s.jsx("div",{className:"space-y-1",children:l.map(A=>s.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] p-2",style:{backgroundColor:"color-mix(in srgb, var(--surface-elevated) 88%, transparent)"},children:[s.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)] break-all",children:A.metric}),s.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:a("memoryDebugPanel.metric.countValue",{value:A.count})}),s.jsx("span",{children:a("memoryDebugPanel.metric.avgValue",{value:A.avg})}),s.jsx("span",{children:a("memoryDebugPanel.metric.maxValue",{value:A.max})}),s.jsx("span",{children:a("memoryDebugPanel.metric.totalValue",{value:A.total})})]})]},A.metric))})})]}),e[0]=o,e[1]=r.durationMs,e[2]=r.entries,e[3]=r.lastUpdatedAt,e[4]=r.startedAt,e[5]=a,e[6]=n,e[7]=c}else c=e[7];return c},zN=t=>{const e=ht.c(99),{onClose:n}=t,{t:r}=jt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=mt(HN),m=$m(GN),f=fc(),u=Og(KN),g=Kn(qN),[b,h]=i.useState(YN),[x,y]=i.useState(JN);let p;e[0]!==b.entries?(p=new Map,b.entries.forEach(se=>{p.set(se.metric,se.count)}),e[0]=b.entries,e[1]=p):p=e[1];let C;e[2]!==p?(C=p.get("ui.message_list.render")??0,e[2]=p,e[3]=C):C=e[3];let v;e[4]!==p?(v=p.get("ui.message_list.render.streaming")??0,e[4]=p,e[5]=v):v=e[5];let k;e[6]!==p?(k=p.get("ui.chat_message.render")??0,e[6]=p,e[7]=k):k=e[7];let w;e[8]!==p?(w=p.get("ui.chat_message.render.streaming")??0,e[8]=p,e[9]=w):w=e[9];let A;e[10]!==p?(A=p.get("ui.chat_message.render.static_during_stream")??0,e[10]=p,e[11]=A):A=e[11];let S;e[12]!==p?(S=p.get("ui.chat_message.render.static_outside_active_turn_during_stream")??0,e[12]=p,e[13]=S):S=e[13];let I;e[14]!==C||e[15]!==v||e[16]!==k||e[17]!==w||e[18]!==A||e[19]!==S?(I={messageListRender:C,messageListRenderStreaming:v,chatMessageRender:k,chatMessageRenderStreaming:w,chatMessageRenderStaticDuringStream:A,chatMessageRenderStaticOutsideActiveTurnDuringStream:S},e[14]=C,e[15]=v,e[16]=k,e[17]=w,e[18]=A,e[19]=S,e[20]=I):I=e[20];const D=I;let N,M;e[21]===Symbol.for("react.memo_cache_sentinel")?(N=()=>{const se=()=>{h(qo()),y(Yo())};se();const G=window.setInterval(se,500);return()=>window.clearInterval(G)},M=[],e[21]=N,e[22]=M):(N=e[21],M=e[22]),i.useEffect(N,M);let P,E;e[23]!==c?(P=()=>{if(c==="idle")return;const se=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(se)},E=[c],e[23]=c,e[24]=P,e[25]=E):(P=e[24],E=e[25]),i.useEffect(P,E);let V=0,R=0,B=0;for(const se of Object.keys(u)){const G=u[se]??[];R=R+G.length;for(const $ of G)$.role==="user"?B=B+1:$.role==="assistant"&&(V=V+1)}let O;e[26]!==V||e[27]!==R||e[28]!==B?(O={assistant:V,total:R,user:B},e[26]=V,e[27]=R,e[28]=B,e[29]=O):O=e[29];const F=O;let _;if(e[30]!==d||e[31]!==u||e[32]!==m||e[33]!==f||e[34]!==r){let se;e[36]!==d||e[37]!==u||e[38]!==m||e[39]!==r?(se=G=>{const $=u[G.id]??[];let pe=0,ye=0;for(const Ne of $)Ne.role==="user"?ye=ye+1:Ne.role==="assistant"&&(pe=pe+1);const z=m.get(G.id);return{id:G.id,title:G.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:pe,messageCount:$.length,userMessageCount:ye,isStreaming:z?.isStreaming||!1,isZombie:z?.isZombie||!1,backgroundCount:z?.backgroundMessageCount||0,lastAccessed:z?.lastAccessedAt||0,isCurrent:G.id===d}},e[36]=d,e[37]=u,e[38]=m,e[39]=r,e[40]=se):se=e[40],_=f.map(se).sort(QN),e[30]=d,e[31]=u,e[32]=m,e[33]=f,e[34]=r,e[35]=_}else _=e[35];const ie=_;let oe;e[41]!==u?(oe=Object.keys(u),e[41]=u,e[42]=oe):oe=e[42];const ne=oe.length;let Y;e[43]===Symbol.for("react.memo_cache_sentinel")?(Y=async()=>{try{const se={generatedAt:new Date().toISOString(),ui:qo(),vscode:Yo()};await navigator.clipboard.writeText(JSON.stringify(se,null,2)),l("copied")}catch{l("error")}},e[43]=Y):Y=e[43];const te=Y;let de;e[44]===Symbol.for("react.memo_cache_sentinel")?(de={backgroundColor:"color-mix(in srgb, var(--surface-background) 94%, transparent)"},e[44]=de):de=e[44];let be;e[45]!==o?(be=o==="memory"?s.jsx(T,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(T,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=be):be=e[46];let ke;e[47]!==r?(ke=r("memoryDebugPanel.title"),e[47]=r,e[48]=ke):ke=e[48];let ae;e[49]!==ke?(ae=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:ke}),e[49]=ke,e[50]=ae):ae=e[50];let ve;e[51]!==be||e[52]!==ae?(ve=s.jsxs("div",{className:"flex items-center gap-2",children:[be,ae]}),e[51]=be,e[52]=ae,e[53]=ve):ve=e[53];let J;e[54]!==o?(J=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx(ze,{size:"xs",variant:"ghost",onClick:te,children:s.jsx(T,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx(ze,{size:"xs",variant:"ghost",onClick:()=>{Uh(),h(qo()),y(Yo())},children:s.jsx(T,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=J):J=e[55];let H;e[56]!==n?(H=n?s.jsx(ze,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(T,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=H):H=e[57];let q;e[58]!==J||e[59]!==H?(q=s.jsxs("div",{className:"flex items-center gap-1",children:[J,H]}),e[58]=J,e[59]=H,e[60]=q):q=e[60];let ce;e[61]!==ve||e[62]!==q?(ce=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[ve,q]}),e[61]=ve,e[62]=q,e[63]=ce):ce=e[63];let fe;e[64]===Symbol.for("react.memo_cache_sentinel")?(fe={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=fe):fe=e[64];const De=o==="memory"?"secondary":"ghost";let Re;e[65]===Symbol.for("react.memo_cache_sentinel")?(Re=()=>a("memory"),e[65]=Re):Re=e[65];let Fe;e[66]!==r?(Fe=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=Fe):Fe=e[67];let Oe;e[68]!==De||e[69]!==Fe?(Oe=s.jsx(ze,{size:"sm",variant:De,className:"flex-1",onClick:Re,children:Fe}),e[68]=De,e[69]=Fe,e[70]=Oe):Oe=e[70];const Ee=o==="streaming"?"secondary":"ghost";let we;e[71]===Symbol.for("react.memo_cache_sentinel")?(we=()=>a("streaming"),e[71]=we):we=e[71];let Pe;e[72]!==r?(Pe=r("memoryDebugPanel.tabs.streaming"),e[72]=r,e[73]=Pe):Pe=e[73];let Se;e[74]!==Ee||e[75]!==Pe?(Se=s.jsx(ze,{size:"sm",variant:Ee,className:"flex-1",onClick:we,children:Pe}),e[74]=Ee,e[75]=Pe,e[76]=Se):Se=e[76];let ue;e[77]!==Oe||e[78]!==Se?(ue=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:fe,children:[Oe,Se]}),e[77]=Oe,e[78]=Se,e[79]=ue):ue=e[79];let K;e[80]!==o||e[81]!==ne||e[82]!==c||e[83]!==d||e[84]!==u||e[85]!==F||e[86]!==m||e[87]!==ie||e[88]!==f||e[89]!==D||e[90]!==b||e[91]!==r||e[92]!==g||e[93]!==x?(K=o==="memory"?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[s.jsx(kn,{label:r("memoryDebugPanel.metric.totalMessages"),value:F.total}),s.jsx(kn,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${ne} / ${Sd.MAX_SESSIONS}`}),s.jsx(kn,{label:r("memoryDebugPanel.metric.userMessages"),value:F.user}),s.jsx(kn,{label:r("memoryDebugPanel.metric.assistantMessages"),value:F.assistant})]}),s.jsxs("div",{className:"typography-meta space-y-1 border-t border-[var(--interactive-border)] pt-2",children:[s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.viewportWindow")}),s.jsx("span",{className:"text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.messagesValue",{count:Bg()})})]}),s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.zombieTimeout")}),s.jsx("span",{className:"text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.minutesValue",{count:Sd.ZOMBIE_TIMEOUT/1e3/60})})]}),s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.githubTotalRequests")}),s.jsx("span",{className:"text-[var(--surface-foreground)]",children:g})]})]}),s.jsxs("div",{className:"border-t border-[var(--interactive-border)] pt-2",children:[s.jsx("div",{className:"mb-1 typography-meta font-semibold text-[var(--surface-foreground)]",children:r("memoryDebugPanel.section.sessionsInMemory")}),s.jsx(An,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:ie.map(se=>s.jsxs("div",{className:"typography-meta flex items-center justify-between rounded p-1.5",style:{backgroundColor:se.isCurrent?"color-mix(in srgb, var(--interactive-selection) 22%, transparent)":"color-mix(in srgb, var(--surface-muted) 35%, transparent)"},children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[s.jsx("span",{className:"truncate text-[var(--surface-foreground)]",children:se.title}),se.isStreaming?s.jsx(T,{name:"pulse",className:"h-3 w-3 animate-pulse text-[var(--status-info)]"}):null,se.isZombie?s.jsx("span",{className:"text-[var(--status-warning)]",children:"!"}):null]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-mono text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.roleMsgsValue",{assistant:se.assistantMessageCount,user:se.userMessageCount})}),s.jsx("span",{className:"font-mono text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.msgsValue",{count:se.messageCount})}),se.backgroundCount>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["+",se.backgroundCount]}):null]})]},se.id))})]}),s.jsx("div",{className:"flex gap-2 border-t border-[var(--interactive-border)] pt-2",children:s.jsxs(Nt,{children:[s.jsx(kt,{asChild:!0,children:s.jsx(ze,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:f.map(XN),currentSessionId:d,cachedSessions:Object.keys(u),messageRoleCounts:F,sessionMessageRoleCounts:ie.map(ZN),memoryStates:Object.fromEntries(m)})},children:r("memoryDebugPanel.actions.logState")})}),s.jsx(Ct,{side:"top",children:r("memoryDebugPanel.tooltip.logCurrentState")})]})})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-[var(--interactive-border)] px-3 py-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:r(c==="copied"?"memoryDebugPanel.streaming.copy.copied":c==="error"?"memoryDebugPanel.streaming.copy.failed":"memoryDebugPanel.streaming.copy.hint")}),s.jsx(ze,{size:"xs",variant:"outline",onClick:te,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(kn,{label:r("memoryDebugPanel.metric.uiMetrics"),value:b.entries.length}),s.jsx(kn,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:x.entries.length}),s.jsx(kn,{label:r("memoryDebugPanel.metric.messageListRenders"),value:D.messageListRender}),s.jsx(kn,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:D.messageListRenderStreaming}),s.jsx(kn,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:D.chatMessageRender}),s.jsx(kn,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:D.chatMessageRenderStreaming}),s.jsx(kn,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:D.chatMessageRenderStaticDuringStream}),s.jsx(kn,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:D.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(tm,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:b,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),x.entries.length>0?s.jsx(tm,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:x,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=ne,e[82]=c,e[83]=d,e[84]=u,e[85]=F,e[86]=m,e[87]=ie,e[88]=f,e[89]=D,e[90]=b,e[91]=r,e[92]=g,e[93]=x,e[94]=K):K=e[94];let he;return e[95]!==ce||e[96]!==ue||e[97]!==K?(he=s.jsxs(_g,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:de,children:[ce,ue,K]}),e[95]=ce,e[96]=ue,e[97]=K,e[98]=he):he=e[98],he},WN=zN;function UN(t,e){return t+e.count}function HN(t){return t.currentSessionId}function GN(t){return t.sessionMemoryState}function KN(t){return t.message}function qN(t){return t.totalRequestCount}function YN(){return qo()}function JN(){return Yo()}function QN(t,e){return e.lastAccessed-t.lastAccessed}function XN(t){return{id:t.id,title:t.title}}function ZN(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const ek=()=>{if(typeof document>"u")return"";const t=document.activeElement;if(t instanceof HTMLTextAreaElement)return t.value.slice(t.selectionStart??0,t.selectionEnd??0);if(t instanceof HTMLInputElement){const e=t.type?.toLowerCase()??"text";if(["text","search","url","tel","password"].includes(e))return t.value.slice(t.selectionStart??0,t.selectionEnd??0)}return t instanceof HTMLElement&&t.isContentEditable?t.ownerDocument.defaultView?.getSelection?.()?.toString()??"":""},tk=async()=>{const t=ek()||window.getSelection()?.toString()||"";if(!t.trim())return!1;try{if(typeof navigator<"u"&&navigator.clipboard?.writeText)return await navigator.clipboard.writeText(t),!0}catch{}return document.execCommand("copy")},sm="openchamber:menu-action",kl="openchamber:check-for-updates",sk=t=>{const e=mt(S=>S.openNewSessionDraft),n=Me(S=>S.toggleCommandPalette),r=Me(S=>S.setCommandPaletteOpen),o=Me(S=>S.toggleHelpDialog),a=Me(S=>S.toggleSidebar),c=Me(S=>S.setSessionSwitcherOpen),l=Me(S=>S.setActiveMainTab),d=Me(S=>S.setSettingsDialogOpen),m=Me(S=>S.setAboutDialogOpen),f=Me(S=>S.toggleRightSidebar),u=Me(S=>S.setRightSidebarOpen),g=Me(S=>S.setRightSidebarTab),b=Me(S=>S.toggleBottomTerminal),h=Me(S=>S.setBottomTerminalExpanded),x=ho(S=>S.checkForUpdates),{setThemeMode:y}=Lr(),p=i.useRef(!1),C=i.useCallback(()=>{p.current||(p.current=!0,x().then(()=>{const{available:S,error:I}=ho.getState();if(I){me.error("Failed to check for updates",{description:I});return}S||me.success("You are on the latest version")}).finally(()=>{p.current=!1}))},[x]),v=i.useCallback(()=>{Nr.requestDirectoryDialog()},[]),k=i.useCallback(S=>{const I=Vg();if(I.length===0)return;const D=mt.getState().currentSessionId,N=I.findIndex(E=>E.id===D);let M=S>0?0:I.length-1;N>=0&&(M=(N+S+I.length)%I.length);const P=I[M];P&&(l("chat"),c(!1),mt.getState().setCurrentSession(P.id))},[l,c]),w=i.useCallback(S=>{const{activeProjectId:I,projects:D,setActiveProject:N}=ds.getState();if(D.length===0)return;const M=D.findIndex(V=>V.id===I);let P=S>0?0:D.length-1;M>=0&&(P=(M+S+D.length)%D.length);const E=D[P];E&&N(E.id)},[]),A=i.useCallback(S=>{switch(S){case"about":m(!0);break;case"settings":d(!0);break;case"command-palette":n();break;case"quick-open":r(!0);break;case"new-session":l("chat"),c(!1),e();break;case"new-worktree-session":l("chat"),c(!1),Om();break;case"change-workspace":v();break;case"toggle-right-sidebar":f();break;case"open-right-sidebar-git":u(!0),g("git");break;case"open-right-sidebar-files":u(!0),g("files");break;case"toggle-terminal":b();break;case"toggle-terminal-expanded":h(!Me.getState().isBottomTerminalExpanded);break;case"copy":{const I=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(I)||tk();break}case"theme-light":y("light");break;case"theme-dark":y("dark");break;case"theme-system":y("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":Bs.getState().goBack();break;case"go-forward":Bs.getState().goForward();break;case"previous-session":k(-1);break;case"next-session":k(1);break;case"previous-project":w(-1);break;case"next-project":w(1);break;case"help-dialog":o();break;case"download-logs":{$g().catch(()=>{me.error("Failed to collect OpenCode status")});break}}},[v,w,k,t,e,m,l,c,r,d,h,u,g,y,b,n,o,f,a]);i.useEffect(()=>{const S=D=>{const N=D.detail;N&&A(N)},I=()=>{C()};return window.addEventListener(sm,S),window.addEventListener(kl,I),()=>{window.removeEventListener(sm,S),window.removeEventListener(kl,I)}},[A,C]),i.useEffect(()=>{if(typeof window>"u")return;const I=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof I!="function")return;let D=null,N=null;return I("openchamber:menu-action",M=>{const P=M?.payload;typeof P=="string"&&A(P)}).then(M=>{D=M}).catch(()=>{}),I("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(kl))}).then(M=>{N=M}).catch(()=>{}),()=>{(async()=>{try{const P=D?.();P instanceof Promise&&await P}catch{}try{const P=N?.();P instanceof Promise&&await P}catch{}})()}},[A])},nk="openchamber:tray-action",nm=5e3,rk=120,ik=45e3,Qf=20,rm=()=>typeof window>"u"?!1:window.__OPENCHAMBER_PLATFORM__==="darwin",ok=t=>{const e=typeof t.permission=="string"?t.permission:"Permission",n=Array.isArray(t.patterns)?t.patterns.find(r=>typeof r=="string"&&r.trim()):"";return n?`${e}: ${n}`:e},ak=t=>{const e=Array.isArray(t.questions)?t.questions[0]:void 0;return e?.header||e?.question||"Question"},Sa=t=>t.time?.updated??t.time?.created??0,lk=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},ck=(t,e,n,r,o)=>{if(!t)return"";const a=Hg(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||lk(t),d=Qo(t);let m=d&&o.get(d)||"";if(!m){for(const[f,u]of an.getState().directories)if(Qo(f)===d){m=u.status?.current??"";break}}if(!m)for(const f of r.values()){const u=f.find(g=>Qo(g.path)===d);if(u?.branch){m=u.branch;break}}return m?`${l} · ${m}`:l},dk=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=Zs.getState(),r=n==="remaining"?"remaining":"usage";if(!e.length)return{mode:r,groups:[]};const o=new Map(t.map(c=>[c.providerId,c])),a=[];for(const c of Sm){if(!e.includes(c.id))continue;const l=o.get(c.id);if(!l||l.configured!==!0)continue;const d=[];for(const[f,u]of Object.entries(l.usage?.windows??{})){const g=r==="remaining"?u.remainingPercent:u.usedPercent;d.push({label:nc(f),value:So(u.valueLabel,g)})}const m=!l.ok&&l.error?l.error:d.length===0?"No rate limits reported":null;a.push({provider:c.name,rows:d,status:m})}return{mode:r,groups:a}},uk=async()=>{try{if(Gi())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=pr();if(e&&fa(e,t))return"Local OpenChamber";const r=(await wm()).hosts.find(o=>e?fa(e,vm(o)):!1);return r?.label?.trim()?jm(r.label.trim()):"Instance"}catch{return""}},mk=()=>{const t=new Map,e=new Map,n=[],r=new Map;let o;try{o=ga()}catch{return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}}for(const[a,c]of o.children.entries()){const l=c.getState();l.vcs?.branch&&e.set(Qo(a)??a,l.vcs.branch);for(const d of l.session)d?.id&&r.set(d.id,d.title);for(const[d,m]of Object.entries(l.session_status??{})){const f=m?.type,u=f==="busy"?"busy":f==="retry"?"retry":"idle",g=t.get(d);(!g||g==="idle")&&t.set(d,u)}for(const[d,m]of Object.entries(l.permission??{}))for(const f of m??[]){if(!f?.id)continue;const u=f.sessionID||d;n.push({kind:"permission",id:f.id,sessionId:u,sessionTitle:"",label:ok(f),directory:a})}for(const[d,m]of Object.entries(l.question??{}))for(const f of m??[]){if(!f?.id)continue;const u=f.sessionID||d;n.push({kind:"question",id:f.id,sessionId:u,sessionTitle:"",label:ak(f),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},fk=()=>{const t=gr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>Sa(o)-Sa(r)).slice(0,Qf).forEach(r=>{const o=kr(r);o&&e.add(o)});const n=new Map;for(const r of t){if(!r?.id)continue;const o=kr(r);if(!o||!e.has(o))continue;const a=n.get(o)??[];a.push(r.id),n.set(o,a)}return n},hk=t=>{const e=mk(),n=zm.getState().index.session,r=gr.getState().activeSessions,o=new Map(e.titleById),a=new Map;for(const h of r)if(h?.id&&(h.title&&o.set(h.id,h.title),h.parentID)){const x=a.get(h.parentID)??[];x.push(h.id),a.set(h.parentID,x)}const c=h=>{const x=[],y=[...a.get(h)??[]],p=new Set;for(;y.length;){const C=y.pop();p.has(C)||(p.add(C),x.push(C),y.push(...a.get(C)??[]))}return x},l=Wm.getState().statusById,d=h=>{const x=e.statusById.get(h);return x&&x!=="idle"?x:l.get(h)?.status??x??"idle"},m=h=>{const x=h.map(y=>d(y));return x.includes("busy")?"busy":x.includes("retry")?"retry":"idle"},f=ds.getState().projects,u=mt.getState().availableWorktreesByProject,g=r.filter(h=>h?.id&&!h.parentID).slice().sort((h,x)=>Sa(x)-Sa(h)).slice(0,Qf).map(h=>{const x=[h.id,...c(h.id)],y=kr(h)??"";return{id:h.id,title:h.title||"Untitled session",status:m(x),branch:y?e.branchByDirectory.get(y)??"":"",unseen:x.reduce((p,C)=>p+(n.unseenCount[C]??0),0),hasError:x.some(p=>n.unseenHasError[p]??!1),directory:y,subtitle:ck(y,h,f,u,e.branchByDirectory)}}),b=e.approvals.map(h=>({...h,sessionTitle:o.get(h.sessionId)||""}));return{sessions:g,approvals:b,instanceName:t,usage:dk()}},pk=()=>{i.useEffect(()=>{if(!rm()||!Na())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const w=hk(r),A=JSON.stringify(w);A!==e&&(e=A,Er("desktop_tray_update",w))};uk().then(w=>{t||(r=w,o())});const a=async()=>{const w=fk();await Promise.all([...w.entries()].map(async([A,S])=>{const I=await Cn.getSessionStatusForDirectory(A).catch(()=>null);t||I===null||Wg(A,I,S)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},rk))},l=new Map,d=()=>{if(t)return;let w;try{w=ga()}catch{return}const A=new Set;for(const[S,I]of w.children.entries())A.add(S),l.has(S)||l.set(S,I.subscribe(()=>c()));for(const[S,I]of l)A.has(S)||(I(),l.delete(S))};let m=null;try{m=ga().subscribeRegistry(()=>{d(),c()})}catch{}d();const f=zm.subscribe(()=>c()),u=gr.subscribe(()=>c()),g=ds.subscribe(()=>c()),b=mt.subscribe(()=>c()),h=an.subscribe(()=>c()),x=Wm.subscribe(()=>c());zg(Nm());const y=window.setInterval(()=>{ha()},ik);a();const p=window.setInterval(()=>{a()},nm),C=Zs.subscribe(()=>c());Zs.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:w,results:A}=Zs.getState();w.length>0&&w.some(I=>!A.some(D=>D.providerId===I))&&Zs.getState().fetchAllQuotas()});const v=window.setInterval(()=>{const w=Zs.getState();w.autoRefresh&&w.dropdownProviderIds.length>0&&w.fetchAllQuotas()},Math.max(3e4,Zs.getState().refreshIntervalMs||6e4)),k=window.setInterval(()=>{d(),o()},nm);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(k),window.clearInterval(y),window.clearInterval(p),window.clearInterval(v),f(),u(),g(),b(),h(),x(),C(),m?.();for(const w of l.values())w();l.clear()}},[]),i.useEffect(()=>{if(!rm()||typeof window>"u")return;const e=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof e!="function")return;const n=o=>{o.type==="respond-permission"&&Ug(o.sessionId,o.id,o.response).catch(()=>{me.error("Failed to respond to permission request")})};let r=null;return e(nk,o=>{const a=o?.payload;!a||typeof a!="object"||typeof a.type!="string"||n(a)}).then(o=>{r=o}).catch(()=>{}),()=>{try{const o=r?.();o instanceof Promise&&o.catch(()=>{})}catch{}}},[])},gk="/api/notifications/stream",xk=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),bk=t=>{if(!t||typeof t!="object")return null;const e=t,n=e.properties&&typeof e.properties=="object"?e.properties:null;return e.type!=="openchamber:notification"||!n?null:{title:typeof n.title=="string"?n.title:void 0,body:typeof n.body=="string"?n.body:void 0,tag:typeof n.tag=="string"?n.tag:void 0}},yk=t=>{const e=ht.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||er()||!sc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(wi().sse(gk));return a.onmessage=wk,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function wk(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Me.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&xk())return;const r=bk(e);if(!r)return;To()?.notifications?.notifyAgentCompletion(r)}const im="pwa-install-toast-shown",om="pwa-install-toast-dismissed",vk=()=>{const t=ht.c(6),{browserTab:e}=kx(),{t:n}=jt(),r=i.useRef(n);let o,a;t[0]!==n?(o=()=>{r.current=n},a=[n],t[0]=n,t[1]=o,t[2]=a):(o=t[1],a=t[2]),i.useEffect(o,a);let c,l;t[3]!==e?(c=()=>{if(typeof window>"u"||!sc()||!e)return;let d=null,m=null;const f=()=>{m!==null&&(me.dismiss(m),m=null)},u=async()=>{if(!d)return;const h=d;d=null,f(),await h.prompt();const{outcome:x}=await h.userChoice;x==="accepted"&&me.success(r.current("pwa.installPrompt.started"))},g=h=>{const x=h;if(typeof x.prompt!="function")return;x.preventDefault(),d=x;const y=bi(),p=fm();Cx({dismissed:y.getItem(om),sessionShown:p.getItem(im),hasActiveToast:m!==null})&&(p.setItem(im,"true"),m=me.info(r.current("pwa.installPrompt.description"),{duration:1/0,action:{label:r.current("pwa.installPrompt.action"),onClick:()=>{u()}},cancel:{label:r.current("pwa.installPrompt.dismiss"),onClick:()=>{bi().setItem(om,"true"),f()}}}))},b=()=>{d=null,f(),me.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",g),window.addEventListener("appinstalled",b),()=>{f(),window.removeEventListener("beforeinstallprompt",g),window.removeEventListener("appinstalled",b)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},jk=({open:t,onOpenChange:e})=>{const{t:n}=jt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,m]=i.useState(!1),[f,u]=i.useState(!1),[g,b]=i.useState(null),[h,x]=i.useState(!1);i.useCallback(async()=>{},[g,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const C=await gs("/api/system/info");if(C.ok){const v=await C.json();if(typeof v.openchamberVersion=="string"&&v.openchamberVersion.trim()){a(v.openchamberVersion);return}}}catch{}a(await Gg())})()},[t]),i.useEffect(()=>{if(!t)return;let p=!1;return(async()=>{try{const v=await gs("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!v.ok)return;const k=await v.json().catch(()=>null),w=typeof k?.currentVersion=="string"?k.currentVersion.trim():"";!p&&w&&l(w)}catch{}})(),()=>{p=!0}},[t]),i.useEffect(()=>{{b(null),x(!1);return}},[t,r]);const y=o;return s.jsx(Cs,{open:t,onOpenChange:e,children:s.jsx(ks,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(pc,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),s.jsxs("div",{className:"space-y-0.5 typography-meta text-muted-foreground",children:[y&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:y})}),c&&s.jsx("p",{children:n("aboutDialog.openCodeVersionLabel",{version:c})})]})]}),r,s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-center gap-4",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(T,{name:"github-fill",className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(T,{name:"discord-fill",className:"h-4 w-4"}),s.jsx("span",{children:"Discord"})]})]}),s.jsxs("a",{href:"https://x.com/openchamber_dev",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(T,{name:"twitter-xfill",className:"h-4 w-4"}),s.jsx("span",{children:"@openchamber_dev"})]})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:n("aboutDialog.footerNote")})]})})})},Cl=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},Sk=(t,e)=>{const n=t instanceof Error?t.message:e;return/oauth state required/i.test(n)?"Authorization session expired or was cleared during reload. Return to OpenChamber and click Authorize again.":n},Nk=()=>{const t=Ax(a=>a.completeAuth),[e,n]=i.useState("working"),[r,o]=i.useState("Completing MCP authorization...");return i.useEffect(()=>{if(typeof window>"u"){n("error"),o("Browser context unavailable.");return}const a=new URLSearchParams(window.location.search),c=Cl(a,"code"),l=Dx(a),d=Tx(a),m=Cl(a,"error"),f=Cl(a,"error_description");if(m){d&&gs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(f??m);return}(async()=>{try{if(!c)throw new Error("Missing OAuth authorization code. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");let u=l;if(!u&&d){const g=await gs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`);if(g.ok){const b=await g.json().catch(()=>null);b?.name?.trim()&&(u={name:b.name.trim(),directory:typeof b.directory=="string"&&b.directory.trim()?b.directory.trim():null})}}if(!u?.name)throw new Error("Authorization session details were not available. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");await t(u.name,c,u.directory),d&&await gs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("success"),o("Authorization completed. You can close this tab and return to OpenChamber.")}catch(u){d&&await gs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(Sk(u,"Failed to complete MCP authorization."))}})()},[t]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-6 py-12 text-foreground",children:s.jsxs("div",{className:"w-full max-w-xl rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-8 shadow-sm",children:[s.jsxs("div",{className:"space-y-3 text-center",children:[s.jsx("div",{className:e==="error"?"text-[var(--status-error)]":e==="success"?"text-[var(--status-success)]":"text-[var(--status-info)]",children:s.jsx("h1",{className:"typography-hero font-semibold",children:e==="working"?"Completing Authorization":e==="success"?"Authorization Complete":"Authorization Failed"})}),s.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}),e!=="working"&&s.jsx("div",{className:"mt-8 flex justify-center",children:s.jsx(ze,{type:"button",onClick:()=>{typeof window>"u"||window.location.replace("/")},children:"Return to OpenChamber"})})]})})},am=eo(()=>Ai(()=>import("./OnboardingScreen-laLzQZgy.js"),__vite__mapDeps([12,1,2,3,4,0])).then(t=>({default:t.OnboardingScreen}))),kk=()=>{const t=ht.c(3),e=Me(Ik),n=Me(Rk);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(jk,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},Ck=t=>{const e=ht.c(21),{onRetry:n,isRetrying:r}=t,{t:o}=jt();let a;e[0]!==o?(a=o("startup.initRecovery.title"),e[0]=o,e[1]=a):a=e[1];let c;e[2]!==a?(c=s.jsx("h1",{className:"typography-title text-foreground",children:a}),e[2]=a,e[3]=c):c=e[3];let l;e[4]!==o?(l=o("startup.initRecovery.description"),e[4]=o,e[5]=l):l=e[5];let d;e[6]!==l?(d=s.jsx("p",{className:"typography-body text-muted-foreground",children:l}),e[6]=l,e[7]=d):d=e[7];let m;e[8]!==c||e[9]!==d?(m=s.jsxs("div",{className:"flex flex-col gap-2",children:[c,d]}),e[8]=c,e[9]=d,e[10]=m):m=e[10];let f;e[11]!==r||e[12]!==o?(f=o(r?"startup.initRecovery.retrying":"startup.initRecovery.retry"),e[11]=r,e[12]=o,e[13]=f):f=e[13];let u;e[14]!==r||e[15]!==n||e[16]!==f?(u=s.jsx(ze,{type:"button",onClick:n,disabled:r,children:f}),e[14]=r,e[15]=n,e[16]=f,e[17]=u):u=e[17];let g;return e[18]!==m||e[19]!==u?(g=s.jsx("div",{className:"flex h-full items-center justify-center bg-background px-6 text-foreground",children:s.jsxs("div",{className:"flex max-w-md flex-col items-center gap-4 text-center",children:[m,u]})}),e[18]=m,e[19]=u,e[20]=g):g=e[20],g},lm=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",Ak=()=>{if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search);if(t.get("ocPanel")!=="session-chat")return null;const e=t.get("sessionId"),n=typeof e=="string"?e.trim():"";if(!n)return null;const r=t.get("directory"),o=typeof r=="string"&&r.trim().length>0?r.trim():null;return{sessionId:n,directory:o,readOnly:t.get("readOnly")==="1"||t.get("readOnly")==="true"}},Dk=()=>typeof window>"u"?!1:window.location.pathname===Rx,Tk=t=>{const e=ht.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=Bs(Ek),c=mt(Mk),l=mt(Fk),d=xc(),m=i.useRef(null);let f;e[0]!==n.directory?(f=lm(n.directory),e[0]=n.directory,e[1]=f):f=e[1];const u=f;let g;e[2]!==a?(g=lm(a),e[2]=a,e[3]=g):g=e[3];const b=g;let h,x;if(e[4]!==b||e[5]!==c||e[6]!==n.directory||e[7]!==n.sessionId||e[8]!==u||e[9]!==r||e[10]!==l||e[11]!==d?(h=()=>{if(r||u&&b!==u)return;const w=`${u}
214
- ${n.sessionId}`;m.current===w&&c===n.sessionId||(m.current=w,l(n.sessionId,n.directory),d.ensureSessionRenderable(n.sessionId,!0))},x=[b,c,n.directory,n.sessionId,u,r,l,d],e[4]=b,e[5]=c,e[6]=n.directory,e[7]=n.sessionId,e[8]=u,e[9]=r,e[10]=l,e[11]=d,e[12]=h,e[13]=x):(h=e[12],x=e[13]),i.useEffect(h,x),u&&b!==u)return null;let y;e[14]!==o?(y=s.jsx(Um,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=y):y=e[15];let p;e[16]===Symbol.for("react.memo_cache_sentinel")?(p=s.jsx(ef,{}),e[16]=p):p=e[16];let C;e[17]!==n.readOnly?(C=s.jsx(Ll,{readOnly:n.readOnly}),e[17]=n.readOnly,e[18]=C):C=e[18];let v;e[19]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx(Hm,{}),e[19]=v):v=e[19];let k;return e[20]!==y||e[21]!==C?(k=s.jsxs(s.Fragment,{children:[y,p,C,v]}),e[20]=y,e[21]=C,e[22]=k):k=e[22],k};function Pk({apis:t}){i.useEffect(()=>{Hh("App:mounted"),Gh()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=Ut(H=>H.initializeApp),n=Ut(H=>H.isInitialized),r=Ut(H=>H.isConnected),o=Ut(H=>H.providers.length),a=Ut(H=>H.agents.length),c=Ut(H=>H.loadProviders),l=Ut(H=>H.loadAgents),d=mt(H=>H.error),m=mt(H=>H.clearError),f=Bs(H=>H.currentDirectory),u=Bs(H=>H.setDirectory),g=Bs(H=>H.isSwitchingDirectory),[b,h]=i.useState(!1),x=Ni(H=>H.refreshStatus),[y,p]=i.useState(()=>t.runtime.isVSCode),[C,v]=i.useState(!0),[k,w]=i.useState(!1),[A,S]=i.useState(0),[I,D]=i.useState(0),[N,M]=i.useState(!1),P=Me(H=>H.wideChatLayoutEnabled),E=Me(H=>H.mobileKeyboardMode),V=i.useMemo(()=>er(),[]),R=oc(H=>H.setPlanModeEnabled),[B,O]=i.useState(()=>sd()),[F,_]=i.useState(()=>{const H=nd();return H!==null?rd({isDesktopShell:!0,bootOutcome:H}):null}),ie=i.useRef(!1),oe=i.useMemo(()=>Ak(),[]),ne=!oe||C,Y=i.useMemo(()=>Dk(),[]);i.useEffect(()=>(id(b),()=>{id(!1)}),[b]),i.useEffect(()=>{Kh(E)},[E]),i.useEffect(()=>{p(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>gm(H=>{mt.getState().prepareForRuntimeSwitch(H.previousRuntimeKey),Me.getState().prepareForRuntimeSwitch(H.previousRuntimeKey),qh(),Cn.reconnectToRuntimeBaseUrl(),Ut.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ds.getState().resetForRuntimeSwitch(),mt.getState().restoreForRuntimeSwitch(H.runtimeKey),Me.getState().restoreForRuntimeSwitch(H.runtimeKey),Kg(),D(q=>q+1),w(!1),S(q=>q+1)}),[]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",P),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[P]),i.useEffect(()=>(od(t),()=>od(null)),[t]),i.useEffect(()=>{oe||x(t.github,{force:!0})},[t.github,oe,x]),qg();const te=B==="valid",de=F?.screen==="main";i.useEffect(()=>{if(!Yh({isDesktopShell:V,isInitialized:n,bootOutcomeKnown:te,bootViewIsMain:de}))return;const H=setTimeout(()=>{const q=document.getElementById("initial-loading");q&&(q.classList.add("fade-out"),setTimeout(()=>{q.remove()},300))},150);return()=>clearTimeout(H)},[V,n,te,de]),i.useEffect(()=>{if(!V||B!=="malformed")return;const H=document.getElementById("initial-loading");H&&(H.textContent="Desktop startup failed — please restart the app.")},[V,B]),i.useEffect(()=>{if(V)return;const H=setTimeout(()=>{const q=document.getElementById("initial-loading");q&&!n&&(q.classList.add("fade-out"),setTimeout(()=>{q.remove()},300))},5e3);return()=>clearTimeout(H)},[V,n]),i.useEffect(()=>{let H=!1;return(async()=>{const ce=await gs("/health",{method:"GET"}).catch(()=>null);if(!ce||!ce.ok||H)return;const fe=await ce.json().catch(()=>null);if(!fe||H)return;const De=fe.planModeExperimentalEnabled;R(De===!0||De===1||De==="1"||De==="true")})(),()=>{H=!0}},[R]),i.useEffect(()=>{y||e()},[e,y]),i.useEffect(()=>{if(y||n)return;let H=!0,q,ce=0;const fe=10,De=1e3,Re=async()=>{if(!H)return;if(ce>=fe){w(!0);return}const Fe=Ut.getState();if(Fe.isInitialized){w(!1);return}ce+=1,await Fe.initializeApp();const Oe=Ut.getState();if(!H)return;if(Oe.isInitialized){w(!1);return}if(ce>=fe){w(!0);return}const Ee=Math.min(De*Math.pow(2,ce-1),16e3);q=setTimeout(Re,Ee)};return q=setTimeout(Re,De),()=>{H=!1,q&&clearTimeout(q)}},[A,n,y]),i.useEffect(()=>{n&&w(!1)},[n]),i.useEffect(()=>{if(!k)return;const H=document.getElementById("initial-loading");H&&(H.classList.add("fade-out"),setTimeout(()=>{H.remove()},300))},[k]),i.useEffect(()=>{if(y||!r||o>0&&a>0)return;let H=!0,q=0;const ce=15,fe=async()=>{const Re=Ut.getState();if(!(Re.providers.length>0&&Re.agents.length>0))try{Re.providers.length===0&&await c({source:"startupRecovery"}),Ut.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};fe();const De=setInterval(()=>{if(H){if(++q>=ce){clearInterval(De);return}fe()}},2e3);return()=>{H=!1,clearInterval(De)}},[r,y,l,c,o,a]),i.useEffect(()=>{g||y||r&&Cn.setDirectory(f)},[f,g,r,y]),i.useEffect(()=>{if(!oe||typeof window>"u")return;const H=fe=>{const De=fe?.visible===!0;v(De)},q=fe=>{if(fe.origin!==window.location.origin)return;const De=fe.data;De?.type==="openchamber:embedded-visibility"&&H(De.payload)},ce=window;return ce.__openchamberSetEmbeddedVisibility=H,window.addEventListener("message",q),()=>{window.removeEventListener("message",q),ce.__openchamberSetEmbeddedVisibility===H&&delete ce.__openchamberSetEmbeddedVisibility}},[oe]),i.useEffect(()=>{!oe?.directory||y||f!==oe.directory&&u(oe.directory,{showOverlay:!1})},[f,oe,y,u]),i.useEffect(()=>{if(!oe||typeof window>"u")return;const H=q=>{q.storageArea===window.localStorage&&q.key==="ui-store"&&Me.persist.rehydrate()};return window.addEventListener("storage",H),()=>{window.removeEventListener("storage",H)}},[oe]),i.useEffect(()=>{if(typeof window>"u")return;const H=q=>{const ce=q.detail,fe=typeof ce?.sessionId=="string"?ce.sessionId.trim():"";if(!fe)return;const De=typeof ce?.directory=="string"&&ce.directory.trim().length>0?ce.directory.trim():null;Me.getState().setActiveMainTab("chat"),mt.getState().setCurrentSession(fe,De)};return window.addEventListener("openchamber:open-session",H),()=>window.removeEventListener("openchamber:open-session",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=()=>{const q=Bs.getState().currentDirectory,{activeProjectId:ce,projects:fe}=ds.getState(),De=fe.find(Re=>Re.id===ce)??null;Er("desktop_open_draft_mini_chat_window",{directory:q||De?.path||"",projectId:De?.id??null})};return window.addEventListener("openchamber:open-mini-chat",H),()=>window.removeEventListener("openchamber:open-mini-chat",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=()=>{const q=mt.getState().currentSessionId;q&&Xg(q)};return window.addEventListener("focus",H),()=>window.removeEventListener("focus",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=q=>{const ce=q.detail,fe=typeof ce?.directory=="string"&&ce.directory.trim().length>0?ce.directory.trim():null,De=typeof ce?.projectId=="string"&&ce.projectId.trim().length>0?ce.projectId.trim():null;Me.getState().setActiveMainTab("chat"),Me.getState().setSessionSwitcherOpen(!1),mt.getState().openNewSessionDraft({selectedProjectId:De,directoryOverride:fe,preserveDirectoryOverride:!!fe})};return window.addEventListener("openchamber:open-draft-session",H),()=>window.removeEventListener("openchamber:open-draft-session",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=q=>{const ce=q.detail,fe=typeof ce?.projectPath=="string"?ce.projectPath.trim():"";if(!fe)return;const De=ds.getState(),Re=De.projects.find(Fe=>Fe.path===fe);Re?De.setActiveProject(Re.id):De.addProject(fe)};return window.addEventListener("openchamber:open-project",H),()=>window.removeEventListener("openchamber:open-project",H)},[]),i.useEffect(()=>{typeof window>"u"||!n||g||ie.current||(ie.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,g]),Yg({enabled:ne}),yk({enabled:ne}),vk(),Jg(),Px();const be=i.useCallback(()=>{h(H=>!H)},[]);sk(be),pk(),i.useEffect(()=>{if(oe)return;const H=q=>{ac(q)&&q.shiftKey&&!q.altKey&&(q.code==="KeyD"||q.key.toLowerCase()==="d")&&(q.preventDefault(),h(fe=>!fe))};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[oe]),i.useEffect(()=>{oe||d&&setTimeout(()=>m(),5e3)},[m,oe,d]),i.useEffect(()=>{if(!V||B!=="not-injected")return;let H=!1,q=0;const ce=200,fe=2e3,De=50,Re=()=>{if(H)return;q++;const Fe=sd();if(Fe!=="not-injected"){if(H=!0,O(Fe),Fe==="valid"){const Ee=nd();Ee&&_(rd({isDesktopShell:!0,bootOutcome:Ee}))}return}const Oe=Math.min(ce*Math.pow(1.1,q),fe);if(q>=De){const Ee=document.getElementById("initial-loading");Ee&&!Ee.textContent?.includes("taking longer")&&(Ee.textContent="Desktop startup is taking longer than expected...")}window.setTimeout(Re,Oe)};return window.setTimeout(Re,ce),()=>{H=!0}},[V,B]);const ke=i.useCallback(async()=>{if(Jh({isDesktopShell:er(),isDesktopLocalOriginActive:Gi()})){await Qh();return}window.location.reload()},[]),ae=i.useCallback(async()=>{if(!N){w(!1),M(!0);try{await Ut.getState().initializeApp()}finally{M(!1)}Ut.getState().isInitialized||S(H=>H+1)}},[N]),ve=H=>{if(H.screen==="recovery")return H.variant};if(V&&F&&F.screen!=="main"){if(F.screen==="chooser")return s.jsx(Vs,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-full"}),children:s.jsx(am,{mode:"first-launch",onCliAvailable:ke,onChooseRemote:()=>{}})})})});const H=ve(F),q=F.screen==="recovery"&&"url"in F?F.url:void 0;return s.jsx(Vs,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-full"}),children:s.jsx(am,{mode:"recovery",recoveryVariant:H,recoveryHostUrl:q,recoveryHostLabel:void 0,onCliAvailable:ke})})})})}if(oe)return s.jsx(Vs,{children:s.jsx(Nd,{sdk:Cn.getSdkClient(),directory:f||"",children:s.jsx(kd,{apis:t,children:s.jsx(Cd,{delayDuration:300,skipDelayDuration:150,children:s.jsx("div",{className:"h-full text-foreground bg-background",children:s.jsx(Tk,{embeddedSessionChat:oe,isVSCodeRuntime:y,embeddedBackgroundWorkEnabled:ne})})})})},I)});if(Y)return s.jsx(Vs,{children:s.jsx(Nk,{})});if(k&&!n&&!y&&!oe)return s.jsx(Vs,{children:s.jsx(Ck,{onRetry:()=>{ae()},isRetrying:N})});const J=!n&&!V;return s.jsx(Vs,{children:s.jsx(Nd,{sdk:Cn.getSdkClient(),directory:f||"",children:s.jsx(kd,{apis:t,children:s.jsx(ly,{children:s.jsx(Qg,{children:s.jsx(Cd,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:V?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(Um,{embeddedBackgroundWorkEnabled:ne}),s.jsx(ef,{}),s.jsx(VN,{}),s.jsx(Hm,{}),!J&&s.jsxs(s.Fragment,{children:[s.jsx(Ix,{}),s.jsx(kk,{}),b&&s.jsx(WN,{onClose:()=>h(!1)})]})]})})})})})},I)})}function Ik(t){return t.isAboutDialogOpen}function Rk(t){return t.setAboutDialogOpen}function Ek(t){return t.currentDirectory}function Mk(t){return t.currentSessionId}function Fk(t){return t.setCurrentSession}const Lk=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();Zg();Xh().then(()=>{Promise.all([Zh(),ex()]).catch(t=>{console.error("[main] settings init failed:",t)}),tx(),sx(),nx()}).catch(t=>{console.error("[main] appearance init failed:",t)});const Xf=document.getElementById("root");if(!Xf)throw new Error("Root element not found");Mh.createRoot(Xf).render(s.jsx(Qe.StrictMode,{children:s.jsx(rx,{children:s.jsx(ix,{children:s.jsx(ox,{children:s.jsx(ax,{children:s.jsx(Pk,{apis:Lk})})})})})}));const Gk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{_v as D,RN as M,Gk as m,Ns as u};