@openchamber/web 1.15.0 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +5 -5
  2. package/dist/assets/{DiagramView-HR2xZxJ8.js → DiagramView-Elkp8b4l.js} +1 -1
  3. package/dist/assets/{MarkdownRendererImpl-sm01Q7R7.js → MarkdownRendererImpl-DLhrL6oX.js} +3 -3
  4. package/dist/assets/{MultiRunWindow-DlFUaNQK.js → MultiRunWindow-DVpNCqnE.js} +1 -1
  5. package/dist/assets/{OnboardingScreen-DVRz82mJ.js → OnboardingScreen-CpcR0gyq.js} +1 -1
  6. package/dist/assets/SessionSwitcherDropdown-DHO5Je6v.js +1 -0
  7. package/dist/assets/{SettingsWindow-CkInZcj7.js → SettingsWindow-Bewo7vwh.js} +1 -1
  8. package/dist/assets/{TerminalView-D_9BAjtv.js → TerminalView-D9C7fNLm.js} +3 -3
  9. package/dist/assets/es-D9nOo8Wx.js +15 -0
  10. package/dist/assets/fr-DEF71lgt.js +13 -0
  11. package/dist/assets/index-BklNmnVr.js +2 -0
  12. package/dist/assets/index-C3uMIExE.css +1 -0
  13. package/dist/assets/ja-CpNfaEje.js +15 -0
  14. package/dist/assets/ko-DLS_rnE-.js +15 -0
  15. package/dist/assets/main-B0CxEOP5.js +237 -0
  16. package/dist/assets/{main-DzNa8r0N.js → main-Ck3ZNw8-.js} +2 -2
  17. package/dist/assets/miniChat-BAJj2Ome.js +2 -0
  18. package/dist/assets/mobile-CJoX4Cdj.js +2 -0
  19. package/dist/assets/pl-BjtFn5-n.js +15 -0
  20. package/dist/assets/pt-BR-C0_4Rnzn.js +15 -0
  21. package/dist/assets/renderElectronMiniChatApp-D4-OXCXM.js +2 -0
  22. package/dist/assets/renderMobileApp-DHWdI195.js +16 -0
  23. package/dist/assets/runtimeEndpointReset-B0P2DED1.js +167 -0
  24. package/dist/assets/uk-BDu4E0s0.js +15 -0
  25. package/dist/assets/{useAppFontEffects-DzBg8hrC.js → useAppFontEffects-9LFMCKYW.js} +195 -136
  26. package/dist/assets/zh-CN-BcwMqxIR.js +15 -0
  27. package/dist/assets/zh-TW-bNDQjKEu.js +15 -0
  28. package/dist/index.html +3 -3
  29. package/dist/mini-chat.html +3 -3
  30. package/dist/mobile.html +3 -3
  31. package/package.json +1 -1
  32. package/server/index.js +106 -1
  33. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  34. package/server/lib/notifications/apns-runtime.js +3 -1
  35. package/server/lib/notifications/runtime.js +135 -33
  36. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  37. package/server/lib/opencode/agents.js +3 -0
  38. package/server/lib/opencode/bootstrap-runtime.js +5 -0
  39. package/server/lib/opencode/core-routes.js +75 -2
  40. package/server/lib/opencode/core-routes.test.js +81 -0
  41. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  42. package/server/lib/opencode/settings-helpers.js +30 -0
  43. package/server/lib/opencode/settings-helpers.test.js +14 -0
  44. package/server/lib/opencode/settings-normalization-runtime.js +19 -4
  45. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  46. package/server/lib/opencode/settings-runtime.js +25 -0
  47. package/server/lib/opencode/shutdown-runtime.js +2 -0
  48. package/server/lib/opencode/tunnel-auth.js +4 -9
  49. package/server/lib/package-manager.js +1 -1
  50. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  51. package/server/lib/permission-auto-accept/runtime.js +263 -0
  52. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  53. package/server/lib/projects/project-config.js +8 -0
  54. package/server/lib/quota/DOCUMENTATION.md +5 -2
  55. package/server/lib/quota/credentials/providers.js +43 -0
  56. package/server/lib/quota/credentials/store.js +48 -0
  57. package/server/lib/quota/credentials/store.test.js +26 -0
  58. package/server/lib/quota/opencode-go-credentials.js +11 -0
  59. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  60. package/server/lib/quota/providers/codex.js +7 -4
  61. package/server/lib/quota/providers/codex.test.js +48 -0
  62. package/server/lib/quota/providers/cursor.js +28 -39
  63. package/server/lib/quota/providers/index.js +7 -0
  64. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  65. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  66. package/server/lib/quota/providers/opencode-go.js +70 -0
  67. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  68. package/server/lib/quota/routes.js +78 -7
  69. package/server/lib/quota/routes.test.js +40 -0
  70. package/server/lib/relay/DOCUMENTATION.md +20 -0
  71. package/server/lib/relay/host-lock.js +101 -0
  72. package/server/lib/relay/host-lock.test.js +129 -0
  73. package/server/lib/relay/identity.js +24 -4
  74. package/server/lib/relay/service.js +95 -8
  75. package/server/lib/relay/signing-key.js +30 -7
  76. package/server/lib/scheduled-tasks/runtime.js +104 -0
  77. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  78. package/server/lib/session-goal/objectives.js +61 -0
  79. package/server/lib/session-goal/routes.js +36 -0
  80. package/server/lib/session-goal/runtime.js +764 -0
  81. package/server/lib/small-model/DOCUMENTATION.md +3 -1
  82. package/server/lib/small-model/call.js +45 -8
  83. package/server/lib/small-model/call.test.js +338 -0
  84. package/server/lib/small-model/index.js +1 -0
  85. package/dist/assets/SessionSwitcherDropdown-DvoOalMY.js +0 -1
  86. package/dist/assets/es-cjUissX4.js +0 -15
  87. package/dist/assets/fr-DqbXnTdK.js +0 -13
  88. package/dist/assets/index-Dg0nmvQU.css +0 -1
  89. package/dist/assets/index-ltrmNGAf.js +0 -2
  90. package/dist/assets/ja-Cetyq6Eg.js +0 -15
  91. package/dist/assets/ko-DtunWisP.js +0 -15
  92. package/dist/assets/main-BC0m8s1v.js +0 -236
  93. package/dist/assets/miniChat-BRYDE-Se.js +0 -2
  94. package/dist/assets/mobile-C3QJVA97.js +0 -2
  95. package/dist/assets/pl-DctGLgve.js +0 -15
  96. package/dist/assets/pt-BR-CXPhf78S.js +0 -15
  97. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +0 -2
  98. package/dist/assets/renderMobileApp-wkBjh5WR.js +0 -16
  99. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +0 -167
  100. package/dist/assets/uk-Bdrc-kqF.js +0 -15
  101. package/dist/assets/zh-CN-CeCVKrHP.js +0 -15
  102. package/dist/assets/zh-TW-CoqiQING.js +0 -15
@@ -1,236 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalView-D_9BAjtv.js","assets/vendor-.bun-BE757pvp.js","assets/useAppFontEffects-DzBg8hrC.js","assets/index-ltrmNGAf.js","assets/index-Dg0nmvQU.css","assets/runtimeEndpointReset-C42u8PvG.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-DvoOalMY.js","assets/DiagramView-HR2xZxJ8.js","assets/SettingsWindow-CkInZcj7.js","assets/MultiRunWindow-DlFUaNQK.js","assets/OnboardingScreen-DVRz82mJ.js"])))=>i.map(i=>d[i]);
2
- import{j as s,b as mt,a as oo,R as i,d as Of,p as dc,L as zh,r as Xe,N as Lf,u as ba,l as vo,n as ya,D as wa,q as va,S as Vl,v as _l,w as uc,C as fc,O as $l,T as Wh,W as Uh,X as Hh,Y as Gh,$ as ai,a0 as Kh,a1 as qh,F as Yh,a2 as Qh,a3 as Jh,a4 as Xh,a5 as Bf,a6 as Zh,a7 as ep,a8 as zl,a9 as tp,s as sp,m as np,aa as md,ab as hd,ac as pd,ad as rp,ae as ip,af as op,ag as ap,ah as lp,ai as cp,_ as ao,aj as gd,ak as xd,al as bd,I as dp}from"./vendor-.bun-BE757pvp.js";import{q as mc,t as cr,v as Zi,w as yd,x as up,y as Sa,z as Vf,A as fp,h as Ns,k as Lo,u as Ee,B as mp,C as Va,D as Yr,E as _f,d as Hr,F as ja,G as $f,H as zf,I as Gr,J as Wl,K as hp,L as pp,R as wd,M as vd,e as qs,N as gp,O as xp,P as Wf,Q as Uf,S as hc,o as Jn,T as bp,b as Pi,U as yp,r as pc,V as wp,W as gc,m as Hf,X as vp,Y as Sp,a as Ui,Z as ra,_ as ia,$ as jp,a0 as Np,a1 as kp,a2 as Sd,a3 as jd,a4 as Nd,a5 as kd,a6 as Cp,f as Cd,l as Ad,a7 as Ap,a8 as Dp,a9 as Tp,n as Pp,p as Ip}from"./index-ltrmNGAf.js";import{c as bt,v as Ie,aA as xs,I as A,y as dr,t as ce,aB as Zs,aC as Fr,aD as en,aE as tn,d as Xn,aF as Or,o as qr,aG as Dd,aH as kt,aI as Ct,aJ as At,aK as Rp,am as Po,aL as Na,aM as li,an as Io,ao as Gf,aj as xc,aN as Kf,aO as Ep,Y as ss,G as ft,aP as Mp,ac as qf,u as Sr,E as bc,b as ks,Z as Mi,aQ as Yf,aR as Qf,aS as Jf,aT as Fp,aU as Op,_ as yc,aV as _a,aW as ci,aX as wc,aY as oa,a3 as Xs,aZ as Lp,a_ as Xf,a$ as Bp,b0 as Zf,b1 as vc,b2 as Ys,b3 as zs,B as ze,b4 as Es,b5 as Ms,b6 as mi,b7 as Vp,b8 as _p,b9 as Wo,ba as Rn,bb as em,bc as tm,ag as Sc,bd as $p,be as Td,bf as Pd,bg as Ti,w as Mn,bh as Fi,bi as eo,bj as zp,bk as Wp,bl as Up,bm as Hp,bn as $a,bo as za,bp as Wa,bq as Ua,br as di,bs as fi,bt as Gp,bu as Kp,bv as an,bw as qp,bx as Yp,by as Qp,bz as Jp,bA as Xp,p as Ii,bB as jc,bC as Zp,bD as eg,bE as tg,bF as sg,bG as ng,bH as rg,bI as ig,bJ as En,bK as Un,bL as Hn,bM as Cn,bN as Gn,bO as Rs,bP as og,D as to,M as Ha,S as Ga,bQ as ag,bR as ur,bS as lg,e as hi,h as Nc,f as Ka,bT as cg,bU as sm,bV as dg,bW as ug,i as kc,bX as fg,j as wn,bY as qa,ah as Er,n as mg,bZ as hg,b_ as ol,b$ as pg,c0 as gg,F as Kr,c1 as Cc,c2 as Ya,c3 as fn,c4 as lo,q as Ri,c5 as nm,af as xg,c6 as bg,c7 as yg,c8 as wg,c9 as al,ca as vg,z as pi,A as Id,C as Rd,cb as Ed,cc as rm,cd as Md,ce as Fd,cf as im,cg as Sg,ch as om,x as Od,J as jg,ci as ll,cj as Ac,ck as Ng,cl as kg,cm as Cg,cn as Bo,co as Ag,cp as cl,cq as am,cr as lm,cs as Dc,ct as Dg,a2 as Tc,cu as cm,cv as Uo,cw as Tg,r as Mr,cx as Pg,cy as dm,cz as Ig,cA as Rg,cB as Ld,cC as um,cD as fm,cE as mm,L as Pc,P as Ic,N as Rc,R as ka,cF as Ca,cG as $n,cH as Eg,cI as Ul,cJ as Mg,cK as Fg,cL as Og,cM as Bd,cN as Lg,cO as Bg,cP as Ec,cQ as hm,cR as Vg,cS as _g,cT as $g,cU as zg,cV as Vd,cW as _d,cX as Wg,cY as Ug,cZ as Hg,c_ as Gg,c$ as Kg,d0 as qg,T as Yg,d1 as $d,d2 as Qg,d3 as pm,U as Jg,d4 as Xg,H as Zg,K as ex,d5 as tx,d6 as sx,d7 as nx,d8 as rx,d9 as ix,da as ox,db as ax,dc as lx,dd as cx,de as Aa,df as dx,dg as zd,dh as ux,di as fx,dj as mx,dk as co,dl as hx,dm as Wd,dn as px,dp as gx,dq as xx,dr as bx,a as gm,ds as xm,dt as yx,du as wx,dv as vx,dw as aa,ae as Sx,dx as jx,dy as Ud,dz as Nx,$ as kx,a0 as Cx,a1 as Ax,a4 as Hd,a5 as Gd,a6 as Kd,a7 as bm,a8 as ym,av as Dx,aw as Tx,ax as Px,ay as Ix,az as Rx,ar as Ex,as as Mx,at as Fx,au as Ox}from"./useAppFontEffects-DzBg8hrC.js";import{I as qd,q as Lx,s as Yd,t as Bx,v as Qd,w as ti,x as Vx,y as dl,z as Ro,U as Da,B as Ta,E as so,F as Vo,G as no,n as wm,j as vm,l as mn,m as _x,Q as Sm,H as $x,J as zx,K as Wx,M as Hl,L as jm,P as Nm,R as Ux,T as Hx,C as Gx,a as Kx,V as Mc,W as km,X as Fc,Y as Oc,Z as Lc,_ as Cm,$ as Am,a0 as Gl,a1 as Dm,a2 as Kl,a3 as la,a4 as qx,a5 as Yx,a6 as Qx,u as So,N as Jx,D as Xx,d as Zx,o as eb,i as ql,a7 as tb,a8 as sb,h as nb,a9 as rb,aa as ib,c as ob,e as ab,O as Tm,f as lb,ab as cb}from"./runtimeEndpointReset-C42u8PvG.js";import{S as db,C as ub,W as fb,g as Bc,r as mb,n as rs,i as Eo,d as ro,c as qi,a as Jd,b as hb,e as jo,f as Pm,h as pb,j as gb,u as ul}from"./SessionSwitcherDropdown-DvoOalMY.js";function Im(t){const{drafts:e,editingDraftId:n,commentText:r,onTextChange:o,selection:a,isDragging:c,fileLabel:l,newWidgetId:d,mapDraftToRange:f,onSave:m,onCancel:u,onEdit:p,onDelete:x}=t,y=[];for(const b of e){const g=f(b);if(b.id===n){y.push({afterLine:g.end,id:`edit-${b.id}`,content:s.jsx(qd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:g,isEditing:!0,onSave:m,onCancel:u},`edit-${b.id}`)});continue}y.push({afterLine:g.end,id:`card-${b.id}`,content:s.jsx(Lx,{draft:b,onEdit:()=>p(b),onDelete:()=>x(b)},`card-${b.id}`)})}if(a&&!n&&!c){const b={...a,start:Math.min(a.start,a.end),end:Math.max(a.start,a.end)};y.push({afterLine:b.end,id:d,content:s.jsx(qd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:b,isEditing:!1,onSave:m,onCancel:u},d)})}return y}function Xd(t){const e=mt.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 f;e[9]===Symbol.for("react.memo_cache_sentinel")?(f=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]=f):f=e[9];let m;return e[10]!==n||e[11]!==r||e[12]!==d?(m=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:d,...r,children:f}),e[10]=n,e[11]=r,e[12]=d,e[13]=m):m=e[13],m}const ui=[{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"}],Yl="finder",Ql=new Set(["finder","terminal"]),Vc=t=>typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32"&&t.id==="finder"?{...t,label:"Explorer",appName:"File Explorer"}:t,Jl=t=>{if(!t)return null;const e=ui.find(n=>n.id===t)??null;return e?Vc(e):null},fl=()=>ui.filter(t=>Ql.has(t.id)).map(t=>({...Vc(t)})),xb=()=>{if(typeof window>"u")return Yl;const t=window.localStorage.getItem("openInAppId");return t&&Jl(t)?t:Yl};let ml=!1,_i=!1,si=!1,ni=0,No=null;const Zd=()=>{No&&(clearTimeout(No),No=null)},wr=oo()((t,e)=>({selectedAppId:xb(),availableApps:fl(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(ml||typeof window>"u")return;ml=!0;const n=(d,f=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:fl(),hasLoadedApps:f});return}const m=new Set(d.map(y=>y.name)),u=new Map(d.map(y=>[y.name,y.iconDataUrl??void 0])),x=ui.filter(y=>m.has(y.appName)||Ql.has(y.id)).map(y=>({...Vc(y),iconDataUrl:u.get(y.appName)}));t({availableApps:x,hasLoadedApps:!0})},r=async d=>{if(!cr()||!Zi()||_i||e().hasLoadedApps&&!d)return;const m=ui.map(u=>u.appName);Zd(),_i=!0,si=!1,t({isScanning:!0});try{const{apps:u,success:p,hasCache:x,isCacheStale:y}=await yd(m,d),b=p&&!x&&u.length===0&&ni<3;if(t({isCacheStale:x?y:!1}),n(u,p?!b:!1),p){if(b){const h=[800,1600,3200][ni]??3200;ni+=1,si=!0,No=setTimeout(()=>{r()},h);return}ni=0,si=!1;return}if(ni<3){const h=[1e3,3e3,7e3][ni]??7e3;ni+=1,si=!0,No=setTimeout(()=>{r()},h)}}finally{_i=!1,si||t({isScanning:!1})}};r();const o=d=>{const f=d.detail,m=f&&typeof f.openInAppId=="string"&&f.openInAppId.length>0&&Jl(f.openInAppId)?f.openInAppId:null;m&&(window.localStorage.setItem("openInAppId",m),t({selectedAppId:m}))},a=()=>{r()},c=d=>{const f=d.detail;Array.isArray(f)&&(ni=3,si=!1,t({isScanning:!1,isCacheStale:!1}),n(f))};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(ml||e().initialize(),!cr()||!Zi()||_i||e().hasLoadedApps&&!n)return;const o=ui.map(a=>a.appName);Zd(),n&&t({hasLoadedApps:!1}),_i=!0,si=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await yd(o,n),d=new Set(a.map(p=>p.name)),f=new Map(a.map(p=>[p.name,p.iconDataUrl??void 0])),u=ui.filter(p=>d.has(p.appName)||Ql.has(p.id)).map(p=>({...p,iconDataUrl:f.get(p.appName)}));t({availableApps:u.length>0?u:fl(),hasLoadedApps:u.length>0,isCacheStale:c?l:!1})}finally{_i=!1,si||t({isScanning:!1})}},selectApp:async n=>{Jl(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await mc({openInAppId:n}))}})),bb="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",yb="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",hl=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__OPENCHAMBER_PLATFORM__!=="win32"?bb:t.id==="terminal"?yb:void 0}),eu=t=>{const e=mt.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,f=r||o;if(f&&!a){let p;e[2]===Symbol.for("react.memo_cache_sentinel")?(p=()=>c(!0),e[2]=p):p=e[2];let x;return e[3]!==f?(x=s.jsx("img",{src:f,alt:"",className:"h-4 w-4 rounded-sm",onError:p}),e[3]=f,e[4]=x):x=e[4],x}let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=Ie("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=m):m=e[5];let u;return e[6]!==d?(u=s.jsx("span",{className:m,children:d}),e[6]=d,e[7]=u):u=e[7],u},wb=t=>{const e=mt.c(75),{directory:n,className:r}=t,{t:o}=bt(),a=wr(vb),c=wr(Sb),l=wr(jb),d=wr(Nb),f=wr(kb),m=wr(Cb),u=wr(Ab);let p,x;e[0]!==f?(p=()=>{f()},x=[f],e[0]=f,e[1]=p,e[2]=x):(p=e[1],x=e[2]),i.useEffect(p,x);const y=cr()&&Zi();let b;e:{let we;e[3]!==c||e[4]!==a?(we=c.find($=>$.id===a)??c.find(Db)??c[0]??ui[0],e[3]=c,e[4]=a,e[5]=we):we=e[5];const fe=we;if(fe){let $;e[6]!==fe?($=hl(fe),e[6]=fe,e[7]=$):$=e[7],b=$;break e}let Me;e[8]===Symbol.for("react.memo_cache_sentinel")?(Me=hl(ui[0]),e[8]=Me):Me=e[8],b=Me}const g=b;if(!y||!n||c.length===0)return null;let h;e[9]!==n?(h=async we=>{await up(n,we.id,we.appName)||await Sa(n,we.appName)},e[9]=n,e[10]=h):h=e[10];const C=h;let w;e[11]!==C||e[12]!==u?(w=async we=>{await u(we.id),await C(we)},e[11]=C,e[12]=u,e[13]=w):w=e[13];const S=w;let N;e[14]!==n||e[15]!==o?(N=async()=>{(await dr(n)).ok&&ce.success(o("openInApp.toast.pathCopied"))},e[14]=n,e[15]=o,e[16]=N):N=e[16];const k=N;let j;e[17]!==r?(j=Ie("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]=j):j=e[18];let D;e[19]!==C||e[20]!==g?(D=()=>{C(g)},e[19]=C,e[20]=g,e[21]=D):D=e[21];const O=d&&"animate-pulse";let v;e[22]!==O?(v=Ie("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",O),e[22]=O,e[23]=v):v=e[23];let M;e[24]!==g.label||e[25]!==o?(M=o("openInApp.actions.openInAria",{app:g.label}),e[24]=g.label,e[25]=o,e[26]=M):M=e[26];let I;e[27]!==g.fallbackIconDataUrl||e[28]!==g.iconDataUrl||e[29]!==g.label?(I=s.jsx(eu,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:g.fallbackIconDataUrl}),e[27]=g.fallbackIconDataUrl,e[28]=g.iconDataUrl,e[29]=g.label,e[30]=I):I=e[30];let E;e[31]!==v||e[32]!==M||e[33]!==I||e[34]!==D?(E=s.jsx("button",{type:"button",onClick:D,className:v,"aria-label":M,children:I}),e[31]=v,e[32]=M,e[33]=I,e[34]=D,e[35]=E):E=e[35];let B;e[36]===Symbol.for("react.memo_cache_sentinel")?(B=Ie("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]=B):B=e[36];let P;e[37]!==o?(P=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=P):P=e[38];let W;e[39]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=W):W=e[39];let _;e[40]!==P?(_=s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:B,"aria-label":P,children:W})}),e[40]=P,e[41]=_):_=e[41];let V;e[42]!==k?(V=()=>{k()},e[42]=k,e[43]=V):V=e[43];let R;e[44]===Symbol.for("react.memo_cache_sentinel")?(R=s.jsx(A,{name:"file-copy",className:"h-4 w-4"}),e[44]=R):R=e[44];let ne;e[45]!==o?(ne=o("openInApp.actions.copyPath"),e[45]=o,e[46]=ne):ne=e[46];let ie;e[47]!==ne?(ie=s.jsx("span",{className:"typography-ui-label text-foreground",children:ne}),e[47]=ne,e[48]=ie):ie=e[48];let J;e[49]!==V||e[50]!==ie?(J=s.jsxs(xs,{className:"flex items-center gap-2",onClick:V,children:[R,ie]}),e[49]=V,e[50]=ie,e[51]=J):J=e[51];let U;e[52]===Symbol.for("react.memo_cache_sentinel")?(U=s.jsx(Fr,{}),e[52]=U):U=e[52];let ee;if(e[53]!==c||e[54]!==S||e[55]!==g.id){let we;e[57]!==S||e[58]!==g.id?(we=fe=>{const Me=hl(fe);return s.jsxs(xs,{className:"flex items-center gap-2",onClick:()=>{S(fe)},children:[s.jsx(eu,{label:fe.label,iconDataUrl:fe.iconDataUrl,fallbackIconDataUrl:Me.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:fe.label}),g.id===fe.id?s.jsx(A,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},fe.id)},e[57]=S,e[58]=g.id,e[59]=we):we=e[59],ee=c.map(we),e[53]=c,e[54]=S,e[55]=g.id,e[56]=ee}else ee=e[56];let ae;e[60]!==l||e[61]!==m||e[62]!==o?(ae=l?s.jsxs(xs,{className:"flex items-center gap-2",onClick:()=>{m(!0)},children:[s.jsx(A,{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]=m,e[62]=o,e[63]=ae):ae=e[63];let de;e[64]!==J||e[65]!==ee||e[66]!==ae?(de=s.jsxs(en,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[J,U,ee,ae]}),e[64]=J,e[65]=ee,e[66]=ae,e[67]=de):de=e[67];let ye;e[68]!==_||e[69]!==de?(ye=s.jsxs(tn,{children:[_,de]}),e[68]=_,e[69]=de,e[70]=ye):ye=e[70];let se;return e[71]!==E||e[72]!==ye||e[73]!==j?(se=s.jsxs("div",{className:j,children:[E,ye]}),e[71]=E,e[72]=ye,e[73]=j,e[74]=se):se=e[74],se};function vb(t){return t.selectedAppId}function Sb(t){return t.availableApps}function jb(t){return t.isCacheStale}function Nb(t){return t.isScanning}function kb(t){return t.initialize}function Cb(t){return t.loadInstalledApps}function Ab(t){return t.selectApp}function Db(t){return t.id===Yl}const Tb=1e6,Pb="terminal-store";let tu=!1;const pl=t=>typeof t=="object"&&t!==null,Ib=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function Tn(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const gl=(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}),xl=t=>({tabs:[t],activeTabId:t.id}),br=(t,e)=>t.tabs.findIndex(n=>n.id===e),Vs=oo()(Of(dc((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Tn(n);r&&t(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),c=`tab-${o.nextTabId}`,l=gl(c,"Terminal");return a.set(r,xl(l)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=Tn(n);return e().sessions.get(r)},getActiveTab:n=>{const r=Tn(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=Tn(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,m=`Terminal ${(l?.tabs.length??0)+1}`,u=gl(o,m);return l?c.set(r,{...l,tabs:[...l.tabs,u]}):c.set(r,xl(u)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Tn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);return!l||l.activeTabId===r||br(l,r)<0?a:(c.set(o,{...l,activeTabId:r}),{sessions:c})})},setTabLabel:(n,r,o)=>{const a=Tn(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),f=d.get(a);if(!f)return l;const m=br(f,r);if(m<0||f.tabs[m]?.label===c)return l;const u=[...f.tabs];return u[m]={...u[m],label:c},d.set(a,{...f,tabs:u}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=Tn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=o?.trim()||null;if(d.tabs[f]?.iconKey===m)return c;const u=[...d.tabs];return u[f]={...u[f],iconKey:m},l.set(a,{...d,tabs:u}),{sessions:l}})},closeTab:async(n,r)=>{const o=Tn(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await fp(l)}catch{}t(d=>{const f=new Map(d.sessions),m=f.get(o);if(!m)return d;const u=br(m,r);if(u<0)return d;const p=m.tabs.filter(g=>g.id!==r),x=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,g])=>!(g.directory===o&&g.tabId===r))),y=Object.keys(x).length!==Object.keys(d.projectActionRuns).length;if(p.length===0){const g=`tab-${d.nextTabId}`,h=gl(g,"Terminal");return f.set(o,xl(h)),{sessions:f,nextTabId:d.nextTabId+1,...y?{projectActionRuns:x}:{}}}let b=m.activeTabId;return m.activeTabId===r&&(b=p[Math.min(u,p.length-1)]?.id??p[0]?.id??null),f.set(o,{...m,tabs:p,activeTabId:b}),{sessions:f,...y?{projectActionRuns:x}:{}}})},setTabSessionId:(n,r,o)=>{const a=Tn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=d.tabs[f],u=o!==null&&m.terminalSessionId!==o,p=o?"running":m.terminalSessionId?"exited":m.lifecycle,x={...m,terminalSessionId:o,lifecycle:p,isConnecting:!1,...u?{bufferChunks:[],bufferLength:0}:{}},y=[...d.tabs];return y[f]=x,l.set(a,{...d,tabs:y}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=Tn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=[...d.tabs];return m[f]={...m[f],lifecycle:o,isConnecting:!1},l.set(a,{...d,tabs:m}),{sessions:l}})},setConnecting:(n,r,o)=>{const a=Tn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=[...d.tabs];return m[f]={...m[f],isConnecting:o},l.set(a,{...d,tabs:m}),{sessions:l}})},appendToBuffer:(n,r,o)=>{if(!o)return;const a=Tn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=d.tabs[f],u=c.nextChunkId,p={id:u,data:o},x=[...m.bufferChunks,p];let y=m.bufferLength+o.length;for(;y>Tb&&x.length>1;){const g=x.shift();if(!g)break;y-=g.data.length}const b=[...d.tabs];return b[f]={...m,bufferChunks:x,bufferLength:y},l.set(a,{...d,tabs:b}),{sessions:l,nextChunkId:u+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=Tn(n);t(l=>{const d=new Map(l.sessions),f=d.get(c);if(!f)return l;const m=br(f,r);if(m<0)return l;const u=f.tabs[m],p=a.autoOpened??u.previewAutoOpened,x=a.locked??u.previewUrlLocked;if(u.previewUrl===o&&u.previewAutoOpened===p&&u.previewUrlLocked===x)return l;const y=[...f.tabs];return y[m]={...u,previewUrl:o,previewAutoOpened:p,previewUrlLocked:x},d.set(c,{...f,tabs:y}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Tn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=br(l,r);if(d<0)return a;const f=l.tabs[d];if(!f.previewUrl||f.previewAutoOpened)return a;const m=[...l.tabs];return m[d]={...f,previewAutoOpened:!0},c.set(o,{...l,tabs:m}),{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=Tn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=br(l,r);if(d<0)return a;const f=[...l.tabs];return f[d]={...f[d],bufferChunks:[],bufferLength:0},c.set(o,{...l,tabs:f}),{sessions:c}})},removeDirectory:n=>{const r=Tn(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:Pb,storage:zh(()=>Vf()),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(!pl(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,f]=l;if(typeof d!="string"||!pl(f))continue;const m=Array.isArray(f.tabs)?f.tabs:[],u=[];for(const y of m){if(!pl(y))continue;const b=typeof y.id=="string"?y.id:null;if(!b)continue;const g=Ib(b);g!==null&&(o=Math.max(o,g));const h=typeof y.terminalSessionId=="string"||y.terminalSessionId===null?y.terminalSessionId:null,C=y.lifecycle,w=C==="idle"||C==="running"||C==="exited"?C:h?"running":"idle";u.push({id:b,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:h,lifecycle:w,createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(u.length===0)continue;const p=typeof f.activeTabId=="string"?f.activeTabId:null,x=p?u.some(y=>y.id===p):!1;r.set(d,{tabs:u,activeTabId:x?p: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"&&!tu){tu=!0;const t=Vs.persist,e=()=>{Vs.getState().hasHydrated||Vs.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const Rb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Eb=["dev","start","preview","serve"];async function Mb(t,e,n){if(!t)return null;const r=Lb(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=Bb(n);if(o){const a=await Vb(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 Fb(t)){const o=await Ob(),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 Fb(t){const e=`${t}/index.html`,n=await Pa(e,t);return typeof n=="string"&&n.trim().length>0}async function Ob(){try{const t=await Ns("/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 Lb(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(Eb.some(o=>n.includes(o)))return e}return null}function Bb(t){for(const{pattern:e}of Rb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function Vb(t){const e=await Pa(`${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 Pa(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Pa(t,e){if(e?.trim())try{const r=new URLSearchParams({path:t,directory:e,optional:"true"}),o=await Ns(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Lo()?.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 Ns(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function _b(t){try{const e=await Pa(`${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 $b=t=>new Promise(e=>{window.setTimeout(e,t)}),zb="\x1B",Wb=new RegExp(`${zb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ub=/https?:\/\/[^\s<>'"`]+/gi,er="__openchamber_auto_discover_preview__",Hb=15e3,Gb=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},Kb=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}},qb=t=>{const n=t.replace(Wb,"").match(Ub);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(),f=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",m=l.pathname||"/",u=m.split("/").filter(Boolean).length,p=m==="/"||m==="",x=!!(l.search||l.hash);let y=0;return f&&(y+=50),p&&(y+=30),y-=Math.min(u*5,20),x&&(y-=10),y};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},Rm=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=bt(),{terminal:c,runtime:l}=Xn(),{isMobile:d}=Or(),f=i.useMemo(()=>cr(),[]),m=Yd(z=>z.instances),u=Yd(z=>z.load),p=Ee(z=>z.setBottomTerminalOpen),x=Ee(z=>z.setActiveMainTab),y=Ee(z=>z.setSettingsPage),b=Ee(z=>z.setSettingsDialogOpen),g=Ee(z=>z.setSettingsProjectsSelectedId),h=Ee(z=>z.openContextPreview),C=Vs(z=>z.sessions),w=Vs(z=>z.ensureDirectory),S=Vs(z=>z.setTabLabel),N=Vs(z=>z.setTabIconKey),k=Vs(z=>z.setActiveTab),j=Vs(z=>z.setConnecting),D=Vs(z=>z.setTabSessionId),O=Vs(z=>z.setTabPreviewUrl),v=Vs(z=>z.projectActionRuns),M=Vs(z=>z.setProjectActionRun),I=Vs(z=>z.updateProjectActionRunStatus),E=Vs(z=>z.removeProjectActionRun),[B,P]=i.useState([]),[W,_]=i.useState(null),[V,R]=i.useState(!1),ne=i.useRef({}),ie=i.useRef({}),J=i.useRef({}),U=i.useRef({}),ee=i.useRef(0),ae=t?.id??null,de=t?.path??"",ye=i.useMemo(()=>ae?{id:ae,path:de}:null,[ae,de]);i.useEffect(()=>{f&&u().catch(()=>{})},[f,u]);const se=i.useCallback(async z=>{await qr(z)},[]),we=i.useCallback(async()=>{if(!ye)return;const z=ee.current+1;ee.current=z,R(!0);try{const pe=await Dd(ye);if(ee.current!==z)return;const Ae=pe.actions;P(Ae),_(G=>G===er||G&&Ae.some(ke=>ke.id===G)?G:null)}catch{if(ee.current!==z)return}finally{ee.current===z&&R(!1)}},[ye]),fe=i.useMemo(()=>Bx(e||ye?.path||""),[e,ye?.path]),Me=i.useMemo(()=>W?B.find(z=>z.id===W)??null:null,[B,W]),$=i.useMemo(()=>({id:er,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),K=!d,q=i.useMemo(()=>K?[$,...B]:B,[B,$,K]);i.useEffect(()=>{we()},[we]),i.useEffect(()=>{if(typeof window>"u")return;const z=pe=>{const Ae=pe.detail;ae&&(Ae?.projectId&&Ae.projectId!==ae||we())};return window.addEventListener(Qd,z),()=>{window.removeEventListener(Qd,z)}},[we,ae]),i.useEffect(()=>{W&&(W===er&&K||B.some(z=>z.id===W)||_(null))},[B,K,W]),i.useEffect(()=>{for(const[z,pe]of Object.entries(v)){const G=C.get(pe.directory)?.tabs.find(ke=>ke.id===pe.tabId);(!G||G.terminalSessionId!==pe.sessionId)&&E(z)}},[v,E,C]),i.useEffect(()=>{for(const[z,pe]of Object.entries(v)){const Ae=ie.current[z]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};ie.current[z]=Ae;const G=q.find(Ve=>Ve.id===pe.actionId);if(!G)continue;const Le=C.get(pe.directory)?.tabs.find(Ve=>Ve.id===pe.tabId);if(!Le||!Array.isArray(Le.bufferChunks)||Le.bufferChunks.length===0)continue;const Te=Le.bufferChunks.filter(Ve=>Ae.lastSeenChunkId===null?!0:Ve.id>Ae.lastSeenChunkId);if(Te.length===0)continue;const Z=Te.map(Ve=>Ve.data).join(""),F=`${Ae.tail}${Z}`,re=!Ae.openedUrl&&G.autoOpenUrl===!0?qb(F):null,te=Te[Te.length-1]?.id??Ae.lastSeenChunkId;if(Ae.lastSeenChunkId=te,Ae.tail=F.slice(-512),re)if(Ae.openedUrl=!0,Ae.openInPreview){const Ve=v[z];Ve&&(O(Ve.directory,Ve.tabId,re,{locked:!1,autoOpened:!1}),Ve.status==="waiting-for-preview"&&I(z,"running"),window.clearTimeout(U.current[z]),delete U.current[z],h(Ve.directory,re))}else se(re),ce.success(a("projectActions.toast.openedUrlFromOutput"));ie.current[z]=Ae}for(const z of Object.keys(ie.current))v[z]||(delete ie.current[z],window.clearTimeout(U.current[z]),delete U.current[z])},[q,h,se,v,O,a,C,I]);const me=i.useCallback(async(z,pe={})=>{if(!fe)throw new Error(a("projectActions.error.noActiveDirectory"));const Ae=ti(fe,z.id);w(fe);const G=Vs.getState(),ke=G.getDirectoryState(fe);let Le=ne.current[Ae]||null;const Te=Le?!!ke?.tabs.some(re=>re.id===Le):!1;(!Le||!Te)&&(Le=G.createTab(fe),ne.current[Ae]=Le),S(fe,Le,`Action: ${z.name}`),N(fe,Le,z.icon||"play"),pe.revealTerminal!==!1&&(k(fe,Le),p(!0),x("terminal"));const F=Vs.getState().getDirectoryState(fe)?.tabs.find(re=>re.id===Le);return{key:Ae,tabId:Le,sessionId:F?.terminalSessionId??null}},[w,fe,x,k,p,N,S,a]),je=i.useCallback(async z=>{if(l.isVSCode||!o&&d)return;if(!fe){ce.error(a("projectActions.error.noActiveDirectoryForAction"));return}const pe=ti(fe,z.id),Ae=v[pe];if(!(Ae&&Ae.status==="running"))try{const G=z.id===er?await(async()=>{const[Je,nt]=await Promise.all([Dd({id:ye?.id??"",path:fe}),_b(fe)]),xt=await Mb(fe,Je.actions,nt);if(!xt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:er,name:a("projectActions.actions.autoDiscover"),command:xt.command,icon:"search",autoOpenUrl:!0,openUrl:xt.previewUrlHint||""}})():z,ke=G.autoOpenUrl===!0&&(G.openUrl||"").trim().length>0,{key:Le,tabId:Te,sessionId:Z}=await me(G,{revealTerminal:!ke&&z.id!==er});let F=Z,re=!1;if(!F){j(fe,Te,!0);try{F=(await c.createSession({cwd:fe})).sessionId,re=!0,D(fe,Te,F)}finally{j(fe,Te,!1)}}if(!F)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));re&&await $b(350),G.id===er&&(J.current[Le]?.(),j(fe,Te,!0),J.current[Le]=mp(F,Je=>{Je.type==="data"&&typeof Je.data=="string"&&Je.data.length>0&&Vs.getState().appendToBuffer(fe,Te,Je.data),Je.type==="exit"&&(Vs.getState().setTabLifecycle(fe,Te,"exited"),Vs.getState().setConnecting(fe,Te,!1),Vs.getState().removeProjectActionRun(Le),delete ie.current[Le],J.current[Le]?.(),delete J.current[Le],window.clearTimeout(U.current[Le]),delete U.current[Le])},()=>{Vs.getState().setConnecting(fe,Te,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const te=G.autoOpenUrl===!0&&f&&(G.desktopOpenSshForward||"").trim().length>0,Ve=G.autoOpenUrl?Kb(G.openUrl):null,Ye=G.autoOpenUrl&&f?Vx(G.desktopOpenSshForward,m):null;M({key:Le,directory:fe,actionId:G.id,tabId:Te,sessionId:F,status:G.id===er&&!Ve?"waiting-for-preview":"running"}),window.clearTimeout(U.current[Le]),delete U.current[Le],G.id===er&&!Ve&&(U.current[Le]=window.setTimeout(()=>{Vs.getState().updateProjectActionRunStatus(Le,"running"),delete U.current[Le]},Hb)),Ye?(O(fe,Te,null,{locked:!0}),se(Ye),ce.success(a("projectActions.toast.openedForwardedUrl"))):Ve?(O(fe,Te,Ve,{locked:!0,autoOpened:!0}),h(fe,Ve),ce.success(a("projectActions.toast.openedActionUrl"))):ke?(O(fe,Te,null,{locked:!0}),ce.error(a("projectActions.error.invalidCustomUrlFormat"))):te?(O(fe,Te,null,{locked:!0}),ce.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):O(fe,Te,null,{locked:!1,autoOpened:!1}),ie.current[Le]={lastSeenChunkId:null,openedUrl:!!Ye||!!Ve||ke,tail:"",openInPreview:G.id===er};const Ke=Gb(G.command.trim().replace(/\r\n|\r/g,`
3
- `));await c.sendInput(F,`${Ke}\r`)}catch(G){E(pe),delete ie.current[pe],J.current[pe]?.(),delete J.current[pe],window.clearTimeout(U.current[pe]),delete U.current[pe],ce.error(G instanceof Error?G.message:a("projectActions.error.failedToRunAction"))}},[m,me,o,d,f,fe,se,h,v,l.isVSCode,E,j,M,O,D,ye?.id,a,c]),Oe=i.useCallback(async z=>{const pe=ti(fe,z.id),Ae=v[pe];if(!Ae)return;I(pe,"stopping");try{await c.sendInput(Ae.sessionId,"")}catch{}if(await new Promise(Le=>{window.setTimeout(Le,1e3)}),Vs.getState().getDirectoryState(Ae.directory)?.tabs.find(Le=>Le.id===Ae.tabId)?.terminalSessionId===Ae.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:Ae.sessionId})}catch{}else try{await c.close(Ae.sessionId)}catch{}D(Ae.directory,Ae.tabId,null)}E(pe),delete ie.current[pe],J.current[pe]?.(),delete J.current[pe],window.clearTimeout(U.current[pe]),delete U.current[pe]},[fe,v,E,D,c,I]),Be=i.useCallback(()=>{const z=Me??q[0];if(!z)return;const pe=ti(fe,z.id),Ae=v[pe];if(Ae?.status!=="stopping"){if(Ae){Oe(z);return}je(z)}},[q,fe,je,v,Me,Oe]),Fe=i.useCallback((z,pe=!1)=>{if(_(z.id),!pe){je(z);return}const Ae=ti(fe,z.id),G=v[Ae];if(G?.status!=="stopping"){if(G){Oe(z);return}je(z)}},[fe,je,v,Oe]),ue=i.useCallback(()=>{ye?.id&&(g(ye.id),y("projects"),b(!0))},[b,y,g,ye?.id]);if(l.isVSCode||!o&&d||!ye||!fe)return null;const Re=Me??q[0]??null;if(!Re)return null;const xe=Re.icon||"play",oe=Re.id===er?"search":dl[xe]||"play",ve=ti(fe,Re.id),Se=v[ve],le=Se?.status==="stopping",T=Se?.status==="waiting-for-preview",L=Se?C.get(Se.directory)?.tabs.find(z=>z.id===Se.tabId)?.previewUrl??null:null,he=!!(Se&&L),ge=()=>{!Se||!L||h(Se.directory,L)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:V||le,className:Ie("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:Be,"aria-label":Se?a("projectActions.actions.stopNamedAria",{name:Re.name}):a("projectActions.actions.runNamedAria",{name:Re.name}),children:le||T?s.jsx(A,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):Se?s.jsx(A,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(A,{name:oe,className:"h-5 w-5"})}),he?s.jsxs(kt,{children:[s.jsx(Ct,{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:ge,children:s.jsx(A,{name:"global",className:"h-4 w-4"})})}),s.jsx(At,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(tn,{children:[s.jsx(Zs,{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(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(en,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(xs,{className:"flex items-center gap-2",onClick:ue,children:[s.jsx(A,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Fr,{}),q.map(z=>{const pe=z.icon||"play",Ae=z.id===er?"search":dl[pe]||"play",G=ti(fe,z.id),ke=v[G],Le=!!ke,Te=ke?.status==="stopping";return s.jsxs(xs,{className:"flex items-center gap-2",onClick:()=>{Fe(z,!0)},children:[s.jsx(A,{name:Ae,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:z.name}),Te||ke?.status==="waiting-for-preview"?s.jsx(A,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?s.jsx(A,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},z.id)})]})]})]}):s.jsxs("div",{className:Ie("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:Be,disabled:V||le,className:Ie("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":Se?a("projectActions.actions.stopNamedAria",{name:Re.name}):a("projectActions.actions.runNamedAria",{name:Re.name}),children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:le||T?s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):Se?s.jsx(A,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(A,{name:oe,className:"h-4 w-4"})})}),he?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ge,className:Ie(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(A,{name:"global",className:"h-4 w-4"})})}),s.jsx(At,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:Ie(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(A,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(en,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(xs,{className:"flex items-center gap-2",onClick:ue,children:[s.jsx(A,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Fr,{}),q.map(z=>{const pe=z.icon||"play",Ae=z.id===er?"search":dl[pe]||"play",G=ti(fe,z.id),ke=v[G],Le=!!ke,Te=ke?.status==="stopping";return s.jsxs(xs,{className:"flex items-center gap-2",onClick:()=>{Fe(z,!0)},children:[s.jsx(A,{name:Ae,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:z.name}),Te||ke?.status==="waiting-for-preview"?s.jsx(A,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?s.jsx(A,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},z.id)})]})]})]})},Qa="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",Yb="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",Ho=i.memo(function(e){const n=mt.c(17),{visible:r,title:o,ariaLabel:a,onClick:c,className:l,Icon:d,iconClassName:f,pressed:m}=e,u=r===void 0?!0:r,p=m===void 0?!1:m;if(!u)return null;const x=l??Qa,y=p&&"bg-interactive-selection text-interactive-selection-foreground";let b;n[0]!==x||n[1]!==y?(b=Ie(x,y),n[0]=x,n[1]=y,n[2]=b):b=n[2];const g=f??"h-[18px] w-[18px]";let h;n[3]!==d||n[4]!==g?(h=s.jsx(A,{name:d,className:g}),n[3]=d,n[4]=g,n[5]=h):h=n[5];let C;n[6]!==a||n[7]!==c||n[8]!==p||n[9]!==b||n[10]!==h?(C=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,"aria-label":a,"aria-pressed":p,className:b,children:h})}),n[6]=a,n[7]=c,n[8]=p,n[9]=b,n[10]=h,n[11]=C):C=n[11];let w;n[12]!==o?(w=s.jsx(At,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=w):w=n[13];let S;return n[14]!==C||n[15]!==w?(S=s.jsxs(kt,{children:[C,w]}),n[14]=C,n[15]=w,n[16]=S):S=n[16],S}),Qb=i.memo(function(e){const n=mt.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:f}=e,{t:m}=bt();if(!o?.connected||r)return null;if(a.length>1){let y;n[0]===Symbol.for("react.memo_cache_sentinel")?(y=Ie(Qa,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),n[0]=y):y=n[0];let b;n[1]!==l||n[2]!==m?(b=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[1]=l,n[2]=m,n[3]=b):b=n[3];let g;n[4]!==c||n[5]!==l||n[6]!==m?(g=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(A,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=m,n[7]=g):g=n[7];let h;n[8]!==d||n[9]!==b||n[10]!==g?(h=s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:y,title:b,disabled:d,children:g})}),n[8]=d,n[9]=b,n[10]=g,n[11]=h):h=n[11];let C;n[12]!==m?(C=m("header.github.accountsTitle"),n[12]=m,n[13]=C):C=n[13];let w;n[14]!==C?(w=s.jsx(Ep,{className:"typography-ui-header font-semibold text-foreground",children:C}),n[14]=C,n[15]=w):w=n[15];let S;n[16]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(Fr,{}),n[16]=S):S=n[16];let N;if(n[17]!==a||n[18]!==f||n[19]!==d||n[20]!==m){let D;n[22]!==f||n[23]!==d||n[24]!==m?(D=O=>{const v=O.user,M=!!O.current,I=O.source==="gh-cli"?m("header.github.accountSource.cli"):m("header.github.accountSource.oauth");return s.jsxs(xs,{className:"gap-2",disabled:d,onSelect:()=>{M||f(O.id)},children:[v?.avatarUrl?s.jsx("img",{src:v.avatarUrl,alt:v.login?m("header.github.avatarWithLogin",{login:v.login}):m("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(A,{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:v?.name?.trim()||v?.login||"GitHub"}),v?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:v.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:I})]}):null]}),M?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]},O.id)},n[22]=f,n[23]=d,n[24]=m,n[25]=D):D=n[25],N=a.map(D),n[17]=a,n[18]=f,n[19]=d,n[20]=m,n[21]=N}else N=n[21];let k;n[26]!==w||n[27]!==N?(k=s.jsxs(en,{align:"end",className:"w-64",children:[w,S,N]}),n[26]=w,n[27]=N,n[28]=k):k=n[28];let j;return n[29]!==h||n[30]!==k?(j=s.jsxs(tn,{children:[h,k]}),n[29]=h,n[30]=k,n[31]=j):j=n[31],j}let u;n[32]!==l||n[33]!==m?(u=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[32]=l,n[33]=m,n[34]=u):u=n[34];let p;n[35]!==c||n[36]!==l||n[37]!==m?(p=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(A,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[35]=c,n[36]=l,n[37]=m,n[38]=p):p=n[38];let x;return n[39]!==u||n[40]!==p?(x=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:p}),n[39]=u,n[40]=p,n[41]=x):x=n[41],x}),Jb=i.memo(function(e){const n=mt.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:f,desktopServicesTab:m,setDesktopServicesTab:u,quotaResultsLength:p,fetchAllQuotas:x,servicesTabItems:y,quotaLastUpdated:b,quotaDisplayMode:g,quotaDisplayTabItems:h,handleDisplayModeChange:C,handleUsageRefresh:w,isQuotaLoading:S,isUsageRefreshSpinning:N,hasRateLimits:k,rateLimitGroups:j,expandedFamilies:D,toggleFamilyExpanded:O,shortcutLabel:v,showDevShutdown:M,isDevShutdownInFlight:I,onDevShutdown:E,remoteUpdateInfo:B,remoteUpdateChecking:P,remoteUpdateError:W,onOpenRemoteUpdate:_,showPredValues:V,timeFormatPreference:R}=e,{t:ne}=bt();let ie;n[0]!==m||n[1]!==x||n[2]!==p||n[3]!==f||n[4]!==d?(ie=Fe=>{d(Fe),Fe&&(f(),m==="usage"&&p===0&&x())},n[0]=m,n[1]=x,n[2]=p,n[3]=f,n[4]=d,n[5]=ie):ie=n[5];let J;n[6]!==o||n[7]!==r||n[8]!==ne?(J=r?ne("header.services.openWithCurrent",{current:o}):ne("header.services.open"),n[6]=o,n[7]=r,n[8]=ne,n[9]=J):J=n[9];const U=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let ee;n[10]!==U?(ee=Ie(Qa,U),n[10]=U,n[11]=ee):ee=n[11];let ae;n[12]===Symbol.for("react.memo_cache_sentinel")?(ae=s.jsx(A,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=ae):ae=n[12];let de;n[13]!==a||n[14]!==r?(de=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=de):de=n[15];let ye;n[16]!==J||n[17]!==ee||n[18]!==de?(ye=s.jsx(Ct,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":J,className:ee,children:[ae,de]})})}),n[16]=J,n[17]=ee,n[18]=de,n[19]=ye):ye=n[19];let se;n[20]!==o||n[21]!==r||n[22]!==v||n[23]!==ne?(se=r?ne("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:v("toggle_services_menu"),nextTab:v("cycle_services_tab")}):ne("header.services.tooltip.servicesWithShortcuts",{toggle:v("toggle_services_menu"),nextTab:v("cycle_services_tab")}),n[20]=o,n[21]=r,n[22]=v,n[23]=ne,n[24]=se):se=n[24];let we;n[25]!==se?(we=s.jsx(At,{children:s.jsx("p",{children:se})}),n[25]=se,n[26]=we):we=n[26];let fe;n[27]!==ye||n[28]!==we?(fe=s.jsxs(kt,{children:[ye,we]}),n[27]=ye,n[28]=we,n[29]=fe):fe=n[29];let Me;n[30]!==x||n[31]!==p||n[32]!==u?(Me=Fe=>{const ue=Fe;u(ue),ue==="usage"&&p===0&&x()},n[30]=x,n[31]=p,n[32]=u,n[33]=Me):Me=n[33];let $;n[34]!==m||n[35]!==y||n[36]!==Me?($=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(Ro,{items:y,activeId:m,onSelect:Me,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=m,n[35]=y,n[36]=Me,n[37]=$):$=n[37];let K;n[38]!==c||n[39]!==m||n[40]!==r||n[41]!==l||n[42]!==_||n[43]!==P||n[44]!==W||n[45]!==B||n[46]!==d||n[47]!==ne?(K=r&&m==="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:ne("header.services.remoteUpdate.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:B?.available?ne("header.services.remoteUpdate.available",{version:B.version||""}):P?ne("header.services.remoteUpdate.checking"):W||ne("header.services.remoteUpdate.upToDate")})]}),B?.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:_,children:ne("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(Rp,{embedded:!0,open:l&&m==="instance",onOpenChange:ey,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=m,n[40]=r,n[41]=l,n[42]=_,n[43]=P,n[44]=W,n[45]=B,n[46]=d,n[47]=ne,n[48]=K):K=n[48];let q;n[49]!==m||n[50]!==l?(q=m==="mcp"?s.jsx(vm,{active:l&&m==="mcp"}):null,n[49]=m,n[50]=l,n[51]=q):q=n[51];let me;n[52]!==m||n[53]!==D||n[54]!==C||n[55]!==w||n[56]!==k||n[57]!==S||n[58]!==N||n[59]!==g||n[60]!==h||n[61]!==b||n[62]!==j||n[63]!==V||n[64]!==ne||n[65]!==R||n[66]!==O?(me=m==="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:ne("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Em(b,R)})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-[10.5rem]",children:s.jsx(Ro,{items:h,activeId:g,onSelect:Fe=>{C(Fe)},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",className:"h-full"})}),s.jsx("button",{type:"button",className:Ie("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:w,disabled:S||N,"aria-label":ne("header.services.refreshRateLimitsAria"),children:s.jsx(A,{name:"refresh",className:Ie("h-4 w-4",N&&"animate-spin")})})]})]}),k?null:s.jsx("div",{className:"px-4 py-5 text-center",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:ne("header.services.noRateLimits")})}),s.jsx("div",{className:"space-y-2 px-3 py-2.5",children:j.map(Fe=>{const ue=D[Fe.providerId]??[];return s.jsxs("div",{className:"min-w-0 rounded-xl bg-[var(--surface-muted)] p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[s.jsx(Po,{providerId:Fe.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Fe.providerName})]}),Fe.entries.length===0&&(!Fe.modelFamilies||Fe.modelFamilies.length===0)?s.jsx("div",{children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Fe.error??ne("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3",children:[Fe.entries.map(Re=>{const[xe,oe]=Re,ve=g==="remaining"?oe.remainingPercent:oe.usedPercent,Se=Na(oe.usedPercent,oe.resetAt,oe.windowSeconds,xe),le=Se?.dailyAllocationPercent!=null?g==="remaining"?100-li(Se.elapsedRatio):li(Se.elapsedRatio):null,T=Io(oe.valueLabel,ve),L=Gf(oe.resetAt,oe.resetAfterFormatted??oe.resetAtFormatted,R);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:xc(xe)}),L?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:L}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:T==="-"?"":T})]}),s.jsx(Da,{percent:ve,tonePercent:oe.usedPercent,className:"h-1.5",expectedMarkerPercent:le}),Se&&V?s.jsx(Ta,{paceInfo:Se,compact:!0}):null]},`${Fe.providerId}-${xe}`)}),Fe.modelFamilies&&Fe.modelFamilies.length>0?s.jsx("div",{className:"space-y-0.5",children:Fe.modelFamilies.map(Re=>{const xe=Re.familyId??"other",oe=ue.includes(xe);return s.jsxs(so,{open:oe,onOpenChange:()=>O(Fe.providerId,xe),children:[s.jsxs(Vo,{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:Re.familyLabel}),oe?s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(A,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(no,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:Re.models.map(ve=>{const[Se,le]=ve,T=g==="remaining"?le.remainingPercent:le.usedPercent,L=Na(le.usedPercent,le.resetAt,le.windowSeconds),he=L?.dailyAllocationPercent!=null?g==="remaining"?100-li(L.elapsedRatio):li(L.elapsedRatio):null,ge=Io(le.valueLabel,T);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:wm(Se)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:ge==="-"?"":ge})]}),s.jsx(Da,{percent:T,tonePercent:le.usedPercent,className:"h-1.5",expectedMarkerPercent:he}),L&&V?s.jsx(Ta,{paceInfo:L,compact:!0}):null]},`${Fe.providerId}-${Se}`)})})})]},xe)})}):null]})]},Fe.providerId)})})]}):null,n[52]=m,n[53]=D,n[54]=C,n[55]=w,n[56]=k,n[57]=S,n[58]=N,n[59]=g,n[60]=h,n[61]=b,n[62]=j,n[63]=V,n[64]=ne,n[65]=R,n[66]=O,n[67]=me):me=n[67];let je;n[68]!==I||n[69]!==E||n[70]!==M||n[71]!==ne?(je=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(xs,{disabled:I,onSelect:()=>{E()},children:ne("header.services.shutdownDev")})})]}):null,n[68]=I,n[69]=E,n[70]=M,n[71]=ne,n[72]=je):je=n[72];let Oe;n[73]!==$||n[74]!==K||n[75]!==q||n[76]!==me||n[77]!==je?(Oe=s.jsxs(en,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[$,K,q,me,je]}),n[73]=$,n[74]=K,n[75]=q,n[76]=me,n[77]=je,n[78]=Oe):Oe=n[78];let Be;return n[79]!==l||n[80]!==ie||n[81]!==fe||n[82]!==Oe?(Be=s.jsxs(tn,{open:l,onOpenChange:ie,children:[fe,Oe]}),n[79]=l,n[80]=ie,n[81]=fe,n[82]=Oe,n[83]=Be):Be=n[83],Be}),Xb=(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??""),Zb=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},Em=(t,e)=>{if(!t)return"-";try{return Kf(t,e,{fallback:"-"})}catch{return"-"}},Pn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},ri=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,su=({onToggleLeftDrawer:t,onToggleRightDrawer:e,leftDrawerOpen:n,rightDrawerOpen:r})=>{const{t:o}=bt(),a=Ee(Y=>Y.setSessionSwitcherOpen),c=Ee(Y=>Y.toggleSidebar),l=Ee(Y=>Y.isSidebarOpen),d=Ee(Y=>Y.toggleBottomTerminal),f=Ee(Y=>Y.toggleRightSidebar),m=Ee(Y=>Y.openContextOverview),u=Ee(Y=>Y.openContextPlan),p=Ee(Y=>Y.openContextBrowser),x=Ee(Y=>Y.openContextPanelTab),y=Ee(Y=>Y.closeContextPanel),b=Ee(Y=>Y.contextPanelByDirectory),g=Ee(Y=>Y.activeMainTab),h=Ee(Y=>Y.setActiveMainTab),C=Ee(Y=>Y.shortcutOverrides),w=Ee(Y=>Y.timeFormatPreference),S=ss(Y=>Y.getCurrentModel),N=Xn(),[k,j]=i.useState(!1),D=ft(Y=>Y.getContextUsage),O=ft(Y=>!!Y.newSessionDraft?.open),v=ft(Y=>Y.currentSessionId),M=Mp(v??""),I=qf(v??null),E=Sr(Y=>Y.activeSessions),B=bc(),P=ks(Y=>Y.activeProjectId?Y.projects.find(tt=>tt.id===Y.activeProjectId)??null:null),W=i.useMemo(()=>{if(!P)return null;const Y=P.label?.trim();if(Y)return Y;const tt=P.path.split(/[\\/]/).filter(Boolean);return tt[tt.length-1]??null},[P]),_=mn(Y=>Y.results),V=mn(Y=>Y.fetchAllQuotas),R=mn(Y=>Y.isLoading),ne=mn(Y=>Y.lastUpdated),ie=mn(Y=>Y.displayMode),J=mn(Y=>Y.showPredValues),U=mn(Y=>Y.dropdownProviderIds),ee=mn(Y=>Y.loadSettings),ae=mn(Y=>Y.setDisplayMode),{isMobile:de}=Or(),ye=Mi(Y=>Y.status),se=Mi(Y=>Y.setStatus),we=i.useRef(null),[fe,Me]=i.useState(()=>typeof window>"u"?!1:cr()),$=i.useMemo(()=>Va(),[]),K=Yf(),[q,me]=i.useState(!1),je=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),Oe=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32",[]),Be=i.useMemo(()=>{if(typeof window>"u")return null;const Y=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof Y=="number"&&Number.isFinite(Y)&&Y>0)return Y;if(typeof navigator>"u")return null;const tt=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!tt)return null;const pt=Number.parseInt(tt[1],10),St=Number.parseInt(tt[2],10);return Number.isNaN(pt)?null:pt===10?St:pt},[]);Xe.useEffect(()=>{typeof window>"u"||Me(cr())},[]);const Fe=S(),ue=Fe&&typeof Fe.limit=="object"&&Fe.limit!==null?Fe.limit:null,Re=ue&&typeof ue.context=="number"?ue.context:0,xe=ue&&typeof ue.output=="number"?ue.output:0,oe=D(Re,xe),[ve,Se]=i.useState(null),le=!v||M;Xe.useEffect(()=>{if(!v){Se(Y=>Y===null?Y:null);return}if(oe&&oe.totalTokens>0){Se(Y=>Xb(Y,oe)?Y:oe);return}le&&Se(Y=>Y===null?Y:null)},[oe,v,le]);const T=Ee(Y=>Y.isSessionSwitcherOpen),L=ye?.connected?ye.user?.avatarUrl??null:null,he=ye?.connected?ye.user?.login??null:null,ge=ye?.accounts??[],[z,pe]=i.useState(!1),[Ae,G]=i.useState(!1),[ke,Le]=i.useState(!1),[Te,Z]=i.useState(!1),[F,re]=i.useState("Local"),[te,Ve]=i.useState(!0),[Ye,Ke]=i.useState(!1),[Je,nt]=i.useState(null),[xt,jt]=i.useState(!1),[Mt,Et]=i.useState(null),Ut=i.useMemo(()=>Zb(F),[F]),[zt,Ht]=i.useState(fe?"instance":"usage"),[_t,Gt]=i.useState("usage");Xe.useEffect(()=>{!fe&&zt==="instance"&&Ht("usage")},[zt,fe]);const Ce=i.useMemo(()=>Yr(),[]),Qe=!Ce&&g==="chat"&&!!ve&&ve.totalTokens>0,et=ve&&ve.contextLimit>0?Math.min(999,ve.totalTokens/ve.contextLimit*100):0,yt=i.useCallback(async()=>{if(!(typeof window>"u"||!fe))try{if(Zi()){re("Local"),Ve(!0);return}Ve(!1);const Y=await _f(),tt=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,pt=Hr();if(pt&&ja(pt,tt)){re("Local"),Ve(!0);return}const St=Y.hosts.find(Kt=>pt?ja(pt,$f(Kt)):!1);if(St?.label?.trim()){re(zf(St.label.trim()));return}re("Instance")}catch{re("Local"),Ve(!0)}},[fe]);Xe.useEffect(()=>{yt()},[yt]);const We=i.useCallback(async()=>{if(te){nt(null),Et(null);return}jt(!0),Et(null);try{const Y=new URLSearchParams({appType:"web",instanceMode:"remote"}),tt=await Ns(`/api/openchamber/update-check?${Y.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!tt.ok)throw new Error(`Server responded with ${tt.status}`);const pt=await tt.json();nt({available:pt.available??!1,version:pt.version,currentVersion:pt.currentVersion??"unknown",body:pt.body,nextSuggestedCheckInSec:typeof pt.nextSuggestedCheckInSec=="number"?pt.nextSuggestedCheckInSec:void 0,packageManager:pt.packageManager,updateCommand:pt.updateCommand})}catch(Y){nt(null),Et(Y instanceof Error?Y.message:o("header.services.remoteUpdate.error"))}finally{jt(!1)}},[te,o]);i.useEffect(()=>{nt(null),Et(null),Ke(!1)},[te,F]),i.useEffect(()=>{if(!fe||te)return;const Y=3e3,tt=3600*1e3;let pt=!1,St=null;const Kt=ts=>{St=window.setTimeout(()=>{if(pt||typeof document<"u"&&document.visibilityState!=="visible"){Kt(tt);return}We().finally(()=>{pt||Kt(tt)})},ts)};return Kt(Y),()=>{pt=!0,St!==null&&window.clearTimeout(St)}},[We,te,F,fe]);const at=i.useCallback(()=>{if(Je?.available){Ke(!0);return}We()},[We,Je?.available]);_x();const qe=mn(Y=>Y.selectedModels),lt=mn(Y=>Y.expandedFamilies),Dt=mn(Y=>Y.toggleFamilyExpanded),us=i.useMemo(()=>{const Y=[];for(const tt of Sm){if(!U.includes(tt.id))continue;const pt=_.find(Ls=>Ls.providerId===tt.id),St=pt?.usage?.windows??{},Kt=pt?.usage?.models,ts=Object.entries(St),is={providerId:tt.id,providerName:tt.name,entries:ts,error:pt&&!pt.ok&&pt.configured?pt.error:void 0};if(Kt&&Object.keys(Kt).length>0){const Ls=qe[tt.id]??[],Gs=Ls.length>0,qn=$x(Kt,tt.id),Vn=zx(tt.id),Qr=Wx(Vn);is.modelFamilies=[];for(const xn of Qr){const nn=qn.get(xn.id)??[];if(nn.length===0)continue;const un=Gs?nn.filter(jn=>Ls.includes(jn)):nn;if(un.length===0)continue;const Sn=[];for(const jn of un){const mr=Kt[jn];if(mr?.windows){const ir=Object.entries(mr.windows);ir.length>0&&Sn.push([jn,ir[0][1]])}}Sn.length>0&&is.modelFamilies.push({familyId:xn.id,familyLabel:xn.label,models:Sn})}const gn=qn.get(null)??[],Jr=Gs?gn.filter(xn=>Ls.includes(xn)):gn;if(Jr.length>0){const xn=[];for(const nn of Jr){const un=Kt[nn];if(un?.windows){const Sn=Object.entries(un.windows);Sn.length>0&&xn.push([nn,Sn[0][1]])}}xn.length>0&&is.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:xn})}}(ts.length>0||is.modelFamilies&&is.modelFamilies.length>0||is.error)&&Y.push(is)}return Y},[U,_,qe,o]),Lt=us.length>0;i.useEffect(()=>{ee()},[ee]);const es=i.useCallback(async Y=>{ae(Y);try{await mc({usageDisplayMode:Y})}catch(tt){console.warn("Failed to update usage display mode:",tt)}},[ae]),os=i.useCallback(()=>{if(Te)return;Z(!0);const Y=new Promise(tt=>setTimeout(tt,500));Promise.all([V(),Y]).finally(()=>{Z(!1)})},[V,Te]),Qt=i.useMemo(()=>v?B.find(Y=>Y.id===v)??E.find(Y=>Y.id===v)??I??Qf().find(Y=>Y.id===v)??null:null,[v,I,E,B]),Ft=i.useRef(null),[Xt,as]=i.useState(0);i.useEffect(()=>{if(!v){Ft.current&&(Ft.current=null,as(St=>St+1));return}if(Qt){Ft.current={sessionId:v,session:Qt,expiresAt:Date.now()+2e3};return}const Y=Ft.current;if(!Y||Y.sessionId!==v)return;const tt=Y.expiresAt-Date.now();if(tt<=0){Ft.current=null,as(St=>St+1);return}const pt=window.setTimeout(()=>{Ft.current?.sessionId===v&&(Ft.current=null),as(St=>St+1)},tt);return()=>{window.clearTimeout(pt)}},[v,Qt]);const $t=(()=>{if(Qt)return Qt;if(!v)return null;const Y=Ft.current;return Y&&Y.sessionId===v&&Y.expiresAt>Date.now()?Y.session:null})(),bs=ft(Y=>v?Y.worktreeMetadata.get(v)?.path??"":""),Cs=ft(Y=>v?Y.worktreeMetadata.get(v)?.branch?.trim()??null:null),Tt=Jf(Y=>v?Y.getAttachment(v):void 0),Bt=i.useMemo(()=>Tt?Fp(Tt,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,Tt]),vt=i.useMemo(()=>Tt?Tt.legacy?"legacy":Tt.degraded?"degraded":Tt.worktreeStatus==="pending"?"pending":Tt.worktreeStatus==="missing"?"missing":Tt.worktreeStatus==="invalid"?"invalid":Tt.attentionReason?"attention":null:null,[Tt]),vs=i.useMemo(()=>Pn(bs||""),[bs]),hs=i.useMemo(()=>{const Y=typeof $t?.directory=="string"?$t.directory:"";return Pn(Y||"")},[$t?.directory]),He=ft(Y=>Y.newSessionDraft?.open?Pn(Y.newSessionDraft.bootstrapPendingDirectory??Y.newSessionDraft.directoryOverride??""):""),it=i.useMemo(()=>vs||hs||He,[He,hs,vs]),It=ft(Y=>{const tt=Pn(vs||hs||"");if(!tt)return null;for(const pt of Y.availableWorktreesByProject.values()){const Kt=pt.find(ts=>Pn(ts.path)===tt)?.branch?.trim();if(Kt)return Kt}return null}),Pt=Op(it||null)||Cs||It,ps=i.useMemo(()=>{if(!v)return W??"OpenChamber";const Y=$t?.title?.trim();return Y&&Y.length>0?Y:"Untitled Session"},[W,$t?.title,v]),ls=i.useMemo(()=>Pn(it||P?.path||""),[P?.path,it]),ns=i.useMemo(()=>P?{id:P.id,path:P.path}:null,[P]),Wt=i.useRef(null);i.useEffect(()=>{!ns||!ls||(Wt.current={projectRef:ns,directory:ls})},[ls,ns]);const ln=i.useMemo(()=>ns&&ls?{projectRef:ns,directory:ls}:Wt.current,[ls,ns]),fs=yc(Y=>Y.planModeEnabled),Fs=ft(Y=>Y.isSessionPlanAvailable),Ws=fs&&v?Fs(v):!1,sn=Ws,An=i.useRef("");i.useEffect(()=>{if(!fs){Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat");return}if(!v)return;const Y=`${v||"none"}:${hs||"none"}:${$t?.time?.created||0}:${$t?.slug||"none"}`;An.current!==Y&&(An.current=Y),!Ws&&Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat")},[fs,Ws,$t?.slug,$t?.time?.created,v,hs]);const vn=i.useCallback(async Y=>{if(!(!Y||z)){pe(!0);try{const tt=N.github?await N.github.authActivate(Y):await(async()=>{const pt=await Ns("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:Y})}),St=await pt.json().catch(()=>null);if(!pt.ok||!St)throw new Error(St?.error||pt.statusText);return St})();se(tt)}catch(tt){console.error("Failed to switch GitHub account:",tt)}finally{pe(!1)}}},[z,N.github,se]),be=i.useCallback(()=>{if(typeof document>"u")return;const Y=document.activeElement;if(!Y)return;const tt=Y.tagName;(tt==="INPUT"||tt==="TEXTAREA"||tt==="SELECT"||Y.isContentEditable)&&Y.blur()},[]),Ze=i.useCallback(()=>{if(de){be(),a(!T);return}c()},[be,de,T,a,c]),dt=i.useCallback(()=>{Gr("desktop_open_draft_mini_chat_window",{directory:Pn(it||P?.path||""),projectId:P?.id??null,apiBaseUrl:Hr(),clientToken:Wl()}).catch(Y=>{console.warn("[header] failed to open draft mini chat window",Y)})},[P?.id,P?.path,it]),wt=i.useCallback(()=>{if(O){dt();return}v&&Gr("desktop_open_session_mini_chat_window",{sessionId:v,directory:Pn(it||P?.path||""),apiBaseUrl:Hr(),clientToken:Wl()}).catch(Y=>{console.warn("[header] failed to open session mini chat window",Y)})},[P?.path,v,dt,O,it]),Vt=i.useCallback(()=>{const Y=Pn(it||"");if(!Y)return;const tt=b[Y];if(ri(tt)==="context"){y(Y);return}m(Y)},[y,b,m,it]),ht=i.useMemo(()=>{const Y=Pn(it||"");if(!Y)return!1;const tt=b[Y];return ri(tt)==="context"},[b,it]),cs=i.useCallback(()=>{const Y=Pn(it||"");if(!Y)return;const tt=b[Y];if(ri(tt)==="plan"){y(Y);return}u(Y)},[y,b,u,it]),ds=i.useCallback(()=>{const Y=Pn(it||"");if(!Y)return;const tt=b[Y];if(ri(tt)==="diff"){y(Y);return}x(Y,{mode:"diff",stagedDiff:!1})},[y,b,x,it]),Ss=i.useCallback(()=>{const Y=Pn(it||"");if(!Y)return;const tt=b[Y];if(ri(tt)==="browser"){y(Y);return}p(Y)},[y,b,p,it]),gs=i.useMemo(()=>{const Y=Pn(it||"");if(!Y)return!1;const tt=b[Y];return ri(tt)==="plan"},[b,it]),Ts=i.useMemo(()=>{const Y=Pn(it||"");if(!Y)return!1;const tt=b[Y];return ri(tt)==="diff"},[b,it]),Fn=i.useMemo(()=>{const Y=Pn(it||"");if(!Y)return!1;const tt=b[Y];return ri(tt)==="browser"},[b,it]),_s=Qa,hn=Yb,On=i.useMemo(()=>Ae?"services":n?"sessions":r?"git":g,[g,Ae,n,r]),Zn=i.useCallback(()=>{G(!1),n&&t&&t(),r&&e&&e(),!t&&T&&a(!1)},[T,n,t,e,r,a]),cn=i.useCallback(()=>{n||G(!1),t?.()},[n,t]),Ue=i.useCallback(()=>{r||G(!1),e?.()},[e,r]),Jt=i.useMemo(()=>fe&&je&&!q?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!fe||Oe)&&!Ce?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[fe,q,je,K,Ce,Oe]);Xe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Jt)},[Jt]);const As=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ps=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";Xe.useEffect(()=>{if(!fe||!je){me(!1);return}let Y=!1;const tt=async()=>{try{const St=await Gr("desktop_is_window_fullscreen");Y||me(St===!0)}catch{Y||me(!1)}},pt=()=>{tt()};return tt(),window.addEventListener("openchamber:window-resized",pt),()=>{Y=!0,window.removeEventListener("openchamber:window-resized",pt)}},[fe,je]);const $s=i.useMemo(()=>!fe||!je||Be===null?"":Be>=26?"h-12":Be<=15?"h-14":"",[fe,je,Be]),Qs=i.useMemo(()=>{if(!(fe&&!Oe||Ce))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[fe,Ce,Oe]),Us=i.useCallback(()=>{if(typeof document>"u")return;const Y=we.current?.getBoundingClientRect().height;Y&&document.documentElement.style.setProperty("--oc-header-height",`${Y}px`)},[]);Xe.useEffect(()=>{if(typeof window>"u")return;Us();const Y=we.current;if(!Y||typeof ResizeObserver>"u")return()=>{};let tt=0;const pt=()=>{tt||(tt=requestAnimationFrame(()=>{tt=0,Us()}))},St=new ResizeObserver(pt);return St.observe(Y),window.addEventListener("resize",pt),window.addEventListener("orientationchange",pt),()=>{tt&&cancelAnimationFrame(tt),St.disconnect(),window.removeEventListener("resize",pt),window.removeEventListener("orientationchange",pt)}},[Us]),Xe.useEffect(()=>{Us()},[Us,de,$s]);const Os=i.useCallback(async Y=>{const tt=Y.target;tt.closest(".app-region-no-drag")||tt.closest("button, a, input, select, textarea")||Y.button===0&&fe&&await hp()},[fe]),Ln=i.useMemo(()=>{if(de){const Y=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return sn&&Y.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),Y.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"}),Y}return[]},[de,sn,o]),fr=i.useCallback(Y=>_a(ci(Y,C)),[C]);Xe.useEffect(()=>{!de&&(g==="git"||g==="terminal"||g==="diff"||g==="files"||g==="context")&&h("chat")},[g,de,h]);const Kn=i.useMemo(()=>{const Y=[];return fe&&Y.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(A,{name:"server",className:"h-3.5 w-3.5"})}),Y.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(A,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(Hl,{className:"h-3.5 w-3.5"})}),Y},[fe,o]),ms=i.useMemo(()=>Kn.map(Y=>({id:Y.value,label:Y.label,icon:Y.icon})),[Kn]),Is=i.useMemo(()=>{if(typeof window>"u"||fe||Ce)return!1;const Y=window.location.hostname;return Y==="localhost"||Y==="127.0.0.1"||Y==="::1"},[fe,Ce]),jr=i.useCallback(async()=>{if(k)return;j(!0),Le(!1);const Y=[];let tt=!1;try{try{for(const[,pt]of Vs.getState().sessions.entries())for(const St of pt.tabs)St.previewUrl&&Y.push(St.previewUrl)}catch{}try{await pp({})}catch{}try{(await Ns("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:Y})})).ok?tt=!0:tt=(await Ns("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{tt||j(!1)}},[k,Le]),Bn=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),pn=i.useMemo(()=>Bn.map(Y=>({id:Y.value,label:Y.label})),[Bn]),Nr=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(A,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(Hl,{className:"h-3.5 w-3.5"})}],[o]);Xe.useEffect(()=>{const Y=tt=>{if(wc(tt)&&!tt.shiftKey&&!tt.altKey){const pt=parseInt(tt.key,10);pt>=1&&pt<=Ln.length&&(tt.preventDefault(),de&&(be(),Zn()),h(Ln[pt-1].id))}};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[be,Zn,de,h,Ln]),Xe.useEffect(()=>{const Y=tt=>{const pt=ci("toggle_services_menu",C);if(oa(tt,pt)){tt.preventDefault(),ke?Le(!1):(Le(!0),yt(),zt==="usage"&&_.length===0&&V());return}const St=ci("cycle_services_tab",C);if(oa(tt,St)){tt.preventDefault();const ts=Kn.map(qn=>qn.value);if(ts.length===0)return;const is=ts.indexOf(zt),Ls=is===-1?0:(is+1)%ts.length,Gs=ts[Ls];Ht(Gs),Le(!0),yt(),Gs==="usage"&&_.length===0&&V();return}const Kt=ci("toggle_context_plan",C);oa(tt,Kt)&&(tt.preventDefault(),cs())};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[C,ke,zt,Kn,_.length,V,yt,cs]);const kr=Y=>{const tt=g===Y.id,pt=Y.icon==="diff",St=pt?null:Y.icon,Kt=Y.id==="chat",ts=Ls=>pt?s.jsx(Xd,{size:Ls}):St?s.jsx(A,{name:St,className:`h-${Ls/4} w-${Ls/4}`}):null,is=s.jsxs("button",{type:"button",onClick:()=>h(Y.id),className:Ie("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",tt?"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",Kt&&!de&&"min-w-[100px] justify-center"),"aria-label":Y.label,"aria-selected":tt,role:"tab",children:[de?ts(20):s.jsxs(s.Fragment,{children:[ts(16),s.jsx("span",{className:"header-tab-label",children:Y.label})]}),Y.badge!==void 0&&Y.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:Y.badge})]});return s.jsx(i.Fragment,{children:is},Y.id)},Lr=Ce?null:s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.toggleChangesPanelAria"),"aria-pressed":Ts,onClick:ds,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(A,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(At,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),Cr=s.jsxs(s.Fragment,{children:[sn&&s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:cs,className:Ie(_s,gs&&"bg-[var(--interactive-hover)]"),children:s.jsx(A,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(At,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:fr("toggle_context_plan")})})})]}),s.jsx(wb,{directory:ls,className:"mr-1"}),s.jsx(Jb,{isDesktopApp:fe,currentInstanceLabel:F,compactCurrentInstanceLabel:Ut,currentInstanceIsLocal:te,isDesktopServicesOpen:ke,setIsDesktopServicesOpen:Le,refreshCurrentInstanceLabel:yt,desktopServicesTab:zt,setDesktopServicesTab:Ht,quotaResultsLength:_.length,fetchAllQuotas:V,servicesTabItems:ms,quotaLastUpdated:ne,quotaDisplayMode:ie,showPredValues:J,quotaDisplayTabItems:pn,handleDisplayModeChange:es,handleUsageRefresh:os,isQuotaLoading:R,isUsageRefreshSpinning:Te,hasRateLimits:Lt,rateLimitGroups:us,expandedFamilies:lt,toggleFamilyExpanded:Dt,shortcutLabel:fr,showDevShutdown:Is,isDevShutdownInFlight:k,onDevShutdown:jr,remoteUpdateInfo:Je,remoteUpdateChecking:xt,remoteUpdateError:Mt,onOpenRemoteUpdate:at,timeFormatPreference:w}),s.jsx(Ho,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:fr("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),de?null:s.jsx(Ho,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:Ss,pressed:Fn,Icon:"global"}),s.jsx(Ho,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:fr("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:f,Icon:"layout-right"}),s.jsx(Qb,{isMobile:de,githubAuthStatus:ye,githubAccounts:ge,githubAvatarUrl:L,githubLogin:he,isSwitchingGitHubAccount:z,handleGitHubAccountSwitch:vn})]}),nr=$&&(O||!!v),ws=()=>s.jsxs("div",{onMouseDown:Os,className:Ie("app-region-drag relative flex h-12 select-none items-center pr-3",$s),style:Qs,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:As}}),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:Ps}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(db,{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:O?o("sessions.switcher.draftTitle"):ps}),W||Pt||!O&&vt?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:[W?s.jsx("span",{className:"truncate",children:W}):null,Pt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:Pt})]}):null,!O&&vt?s.jsxs("span",{className:Ie("inline-flex min-w-0 items-center gap-0.5",vt==="attention"||vt==="invalid"||vt==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(A,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:Bt})]}):null]}):null]})}),Ln.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ln.map(Y=>kr(Y))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Qe&&ve?s.jsx(ub,{totalTokens:ve.totalTokens,percentage:et,colorPercentage:ve.percentage,contextLimit:ve.contextLimit,outputLimit:ve.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:Vt,pressed:ht,className:nr?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,Lr,s.jsx(Ho,{visible:nr,title:o(O?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(O?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:wt,className:Ie(_s,"mr-1"),Icon:"picture-in-picture-2"}),Cr,s.jsx(fb,{visible:Oe})]})]})]}),dn=()=>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:cn,className:Ie(hn,On==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(A,{name:"layout-left",className:"h-5 w-5"})}):T?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(A,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Ze,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(A,{name:"play-list-add",className:"h-5 w-5"})}),!t&&T&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!T||!!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:Ln.map(Y=>{const tt=g===Y.id,pt=Y.icon==="diff",St=pt?null:Y.icon;return s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{de&&(be(),Zn()),h(Y.id)},"aria-label":Y.label,"aria-selected":tt,role:"tab",className:Ie(hn,"relative rounded-lg",On===Y.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[pt?s.jsx(Xd,{className:"h-5 w-5"}):St?s.jsx(A,{name:St,className:"h-5 w-5"}):null,Y.badge!==void 0&&Y.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:Y.badge}),Y.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(At,{children:s.jsx("p",{children:Y.label})})]},Y.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[ln&&s.jsx(Rm,{projectRef:ln.projectRef,directory:ln.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(tn,{open:Ae,onOpenChange:Y=>{Y&&(n&&t&&t(),r&&e&&e()),G(Y),Y&&_.length===0&&V()},children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:Ie(hn,On==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(A,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(At,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(en,{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(Ro,{items:Nr,activeId:_t,onSelect:Y=>{const tt=Y;Gt(tt),tt==="usage"&&_.length===0&&V()},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:()=>G(!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(A,{name:"close",className:"h-5 w-5"})})]})}),_t==="mcp"&&s.jsx(vm,{active:Ae&&_t==="mcp"}),_t==="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:Em(ne,w)})]}),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:()=>es("usage"),className:Ie("typography-ui-label px-1 pb-0.5 transition-colors",ie==="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:()=>es("remaining"),className:Ie("typography-ui-label px-1 pb-0.5 transition-colors",ie==="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:Ie("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:os,disabled:R||Te,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(A,{name:"refresh",className:Ie("h-4 w-4",Te&&"animate-spin")})})]})]})}),!Lt&&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:us.map((Y,tt)=>s.jsxs(i.Fragment,{children:[tt>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(Po,{providerId:Y.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Y.providerName})]}),Y.entries.length===0&&(!Y.modelFamilies||Y.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Y.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[Y.entries.map(([pt,St])=>{const Kt=ie==="remaining"?St.remainingPercent:St.usedPercent,ts=Na(St.usedPercent,St.resetAt,St.windowSeconds,pt),is=ts?.dailyAllocationPercent!=null?ie==="remaining"?100-li(ts.elapsedRatio):li(ts.elapsedRatio):null,Ls=Io(St.valueLabel,Kt),Gs=Gf(St.resetAt,St.resetAfterFormatted??St.resetAtFormatted,w);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:xc(pt)}),Gs?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Gs}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Ls==="-"?"":Ls})]}),s.jsx(Da,{percent:Kt,tonePercent:St.usedPercent,className:"h-1.5",expectedMarkerPercent:is}),ts&&J?s.jsx(Ta,{paceInfo:ts,compact:!0}):null]},`${Y.providerId}-${pt}`)}),Y.modelFamilies&&Y.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:Y.modelFamilies.map(pt=>{const Kt=(lt[Y.providerId]??[]).includes(pt.familyId??"other");return s.jsxs(so,{open:Kt,onOpenChange:()=>Dt(Y.providerId,pt.familyId??"other"),children:[s.jsxs(Vo,{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:pt.familyLabel}),Kt?s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(A,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(no,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:pt.models.map(([ts,is])=>{const Ls=ie==="remaining"?is.remainingPercent:is.usedPercent,Gs=Na(is.usedPercent,is.resetAt,is.windowSeconds),qn=Gs?.dailyAllocationPercent!=null?ie==="remaining"?100-li(Gs.elapsedRatio):li(Gs.elapsedRatio):null,Vn=Io(is.valueLabel,Ls);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:wm(ts)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Vn==="-"?"":Vn})]}),s.jsx(Da,{percent:Ls,tonePercent:is.usedPercent,className:"h-1.5",expectedMarkerPercent:qn}),Gs&&J?s.jsx(Ta,{paceInfo:Gs,compact:!0}):null]},`${Y.providerId}-${ts}`)})})})]},pt.familyId??"other")})})]})]},Y.providerId))})]})]})})]}),e?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Ue,className:Ie(hn,"relative",On==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(A,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(At,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),rr=Ie("header-safe-area relative z-10 bg-background",de&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:we,className:rr,style:{"--padding-scale":"1"},children:de?dn():ws()}),s.jsx(jm,{open:Ye,onOpenChange:Ke,info:Je,downloading:!1,downloaded:!1,progress:null,error:Mt,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function ey(){}const nu=180,ru=640,ty=110,sy=t=>{const e=mt.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=bt(),c=Ee(ny),l=Ee(ry),d=Ee(iy),f=Ee(oy),[m,u]=i.useState(null),[p,x]=i.useState(!1),y=i.useRef(null),b=i.useRef(0),g=i.useRef(c||300),h=Math.min(ru,Math.max(nu,c||300));let C,w;e[0]!==n?(C=()=>{n||(u(null),x(!1))},w=[n],e[0]=n,e[1]=C,e[2]=w):(C=e[1],w=e[2]),i.useEffect(C,w);let S,N;e[3]!==l||e[4]!==r||e[5]!==n?(S=()=>{if(r||!n||!l)return;const ee=()=>{const ye=y.current?.parentElement?.getBoundingClientRect().height;if(!ye||ye<=0)return;const se=Math.max(0,Math.round(ye));u(we=>we===se?we:se)};ee();const ae=y.current?.parentElement;if(!ae)return;const de=new ResizeObserver(ee);return de.observe(ae),()=>{de.disconnect()}},N=[l,r,n],e[3]=l,e[4]=r,e[5]=n,e[6]=S,e[7]=N):(S=e[6],N=e[7]),i.useEffect(S,N);let k,j;if(e[8]!==l||e[9]!==r||e[10]!==p||e[11]!==d||e[12]!==f?(k=()=>{if(r||!p||l)return;const ee=de=>{const ye=b.current-de.clientY,se=Math.min(ru,Math.max(nu,g.current+ye));d(se)},ae=()=>{x(!1),Ee.getState().bottomTerminalHeight<=ty&&f(!1)};return window.addEventListener("pointermove",ee),window.addEventListener("pointerup",ae,{once:!0}),()=>{window.removeEventListener("pointermove",ee),window.removeEventListener("pointerup",ae)}},j=[l,r,p,d,f],e[8]=l,e[9]=r,e[10]=p,e[11]=d,e[12]=f,e[13]=k,e[14]=j):(k=e[13],j=e[14]),i.useEffect(k,j),r)return null;const D=n?l?Math.max(0,m??h):h:0,O=n&&l;let v;e[15]!==D||e[16]!==l||e[17]!==n?(v=ee=>{!n||l||(x(!0),b.current=ee.clientY,g.current=D,ee.preventDefault())},e[15]=D,e[16]=l,e[17]=n,e[18]=v):v=e[18];const M=v,I=O?"absolute inset-x-0 bottom-0 z-40":"relative",E=p?"transition-none":"transition-[height] duration-300 ease-in-out",B=(!n||O)&&"border-t-0";let P;e[19]!==B||e[20]!==I||e[21]!==E?(P=Ie("flex overflow-hidden border-t border-border bg-sidebar",I,E,B),e[19]=B,e[20]=I,e[21]=E,e[22]=P):P=e[22];let W;e[23]!==D||e[24]!==O?(W=O?{top:0}:{height:`${D}px`,minHeight:`${D}px`,maxHeight:`${D}px`},e[23]=D,e[24]=O,e[25]=W):W=e[25];const _=!n||!l&&D===0;let V;e[26]!==M||e[27]!==l||e[28]!==n||e[29]!==p||e[30]!==a?(V=n&&!l&&s.jsx("div",{className:Ie("absolute left-0 top-0 z-20 h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",p&&"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]=p,e[30]=a,e[31]=V):V=e[31];const R=!n&&"pointer-events-none select-none opacity-0";let ne;e[32]!==R?(ne=Ie("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",R),e[32]=R,e[33]=ne):ne=e[33];const ie=!n;let J;e[34]!==o||e[35]!==ne||e[36]!==ie?(J=s.jsx("div",{className:ne,"aria-hidden":ie,children:o}),e[34]=o,e[35]=ne,e[36]=ie,e[37]=J):J=e[37];let U;return e[38]!==P||e[39]!==W||e[40]!==_||e[41]!==V||e[42]!==J?(U=s.jsxs("section",{ref:y,className:P,style:W,"aria-hidden":_,children:[V,J]}),e[38]=P,e[39]=W,e[40]=_,e[41]=V,e[42]=J,e[43]=U):U=e[43],U};function ny(t){return t.bottomTerminalHeight}function ry(t){return t.isBottomTerminalExpanded}function iy(t){return t.setBottomTerminalHeight}function oy(t){return t.setBottomTerminalOpen}const iu=280,ou=280,au=500,ay=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=bt(),c=Ee(j=>j.sidebarWidth),l=Ee(j=>j.setSidebarWidth),[d,f]=i.useState(!1),m=i.useRef(0),u=i.useRef(c||iu),p=i.useRef(null),x=i.useRef(null),y=i.useRef(null),b=i.useCallback(j=>Math.min(au,Math.max(ou,j)),[]),g=i.useCallback(j=>{const D=y.current;D&&(D.style.width=`${j}px`,D.style.minWidth=`${j}px`,D.style.maxWidth=`${j}px`,D.style.setProperty("--oc-left-sidebar-width",`${j}px`))},[]);if(i.useEffect(()=>{e&&d&&f(!1)},[e,d]),i.useEffect(()=>{d||(p.current=null,x.current=null)},[d]),e)return null;const h=Math.min(au,Math.max(ou,c||iu)),C=t?h:0,w=j=>{if(t){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}x.current=j.pointerId,f(!0),m.current=j.clientX,u.current=C,p.current=C,g(C),j.preventDefault()}},S=j=>{if(e||!d||x.current!==j.pointerId)return;const D=j.clientX-m.current,O=b(u.current+D);p.current!==O&&(p.current=O,g(O))},N=j=>{if(x.current!==j.pointerId||e)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const D=b(p.current??C);x.current=null,p.current=null,f(!1),l(D)},k=d?p.current??C:C;return s.jsxs("aside",{ref:y,className:Ie("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:`${k}px`,minWidth:`${k}px`,maxWidth:`${k}px`,"--oc-left-sidebar-width":`${d?k:h}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:Ie("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:w,onPointerMove:S,onPointerUp:N,onPointerCancel:N,role:"separator","aria-orientation":"vertical","aria-label":a("sidebar.resize.leftPanelAria")}),s.jsxs("div",{className:Ie("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(Xs,{children:n})})]})]})},ly=()=>{const t=mt.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},Go=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function cy(){const t=ks(u=>u.activeProjectId?u.projects.find(p=>p.id===u.activeProjectId)??null:null),e=ft(u=>u.currentSessionId),n=qf(e??null),r=ft(u=>e?u.worktreeMetadata.get(e)?.path??"":""),o=ft(u=>u.newSessionDraft?.open?Go(u.newSessionDraft.bootstrapPendingDirectory??u.newSessionDraft.directoryOverride??""):""),a=i.useMemo(()=>Go(r||""),[r]),c=i.useMemo(()=>{const u=typeof n?.directory=="string"?n.directory:"";return Go(u||"")},[n?.directory]),l=a||c||o,d=i.useMemo(()=>Go(l||t?.path||""),[t?.path,l]),f=i.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),m=i.useRef(null);return i.useEffect(()=>{f&&d&&(m.current={projectRef:f,directory:d})},[d,f]),i.useMemo(()=>f&&d?{projectRef:f,directory:d}:m.current,[f,d])}const lu="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",dy=()=>{const t=mt.c(31),{t:e}=bt(),n=Ee(uy),r=Ee(fy),o=Ee(my),a=cy(),c=i.useRef(null),l=_a(ci("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const f=d,m=py;let u,p;t[0]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{if(typeof document>"u")return;const B=c.current;if(!B)return;const P=()=>{const _=B.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(_)}px`)};if(P(),typeof ResizeObserver>"u")return;const W=new ResizeObserver(P);return W.observe(B),()=>{W.disconnect()}},p=[],t[0]=u,t[1]=p):(u=t[0],p=t[1]),i.useEffect(u,p);const x="app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2";let y;t[2]===Symbol.for("react.memo_cache_sentinel")?(y={height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},t[2]=y):y=t[2];const b="flex items-center gap-2";let g;t[3]!==e?(g=f?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,"aria-label":e("header.actions.openAppMenuAria"),className:Ie(lu,"shrink-0"),children:s.jsx(A,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(At,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=g):g=t[4];const h=kt;let C;t[5]!==e?(C=e("header.actions.openSessionsAria"),t[5]=e,t[6]=C):C=t[6];let w,S;t[7]===Symbol.for("react.memo_cache_sentinel")?(w=Ie(lu,"shrink-0"),S=s.jsx(A,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=w,t[8]=S):(w=t[7],S=t[8]);let N;t[9]!==C||t[10]!==n?(N=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":C,className:w,children:S})}),t[9]=C,t[10]=n,t[11]=N):N=t[11];const k=At,j=e("header.actions.openSessionsWithShortcut",{shortcut:l});let D;t[12]!==j?(D=s.jsx("p",{children:j}),t[12]=j,t[13]=D):D=t[13];let O;t[14]!==k||t[15]!==D?(O=s.jsx(k,{children:D}),t[14]=k,t[15]=D,t[16]=O):O=t[16];let v;t[17]!==h||t[18]!==N||t[19]!==O?(v=s.jsxs(h,{children:[N,O]}),t[17]=h,t[18]=N,t[19]=O,t[20]=v):v=t[20];let M;t[21]!==r||t[22]!==a?(M=a?s.jsx(Rm,{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 I;t[24]!==v||t[25]!==M||t[26]!==g?(I=s.jsxs("div",{ref:c,className:b,children:[g,v,M]}),t[24]=v,t[25]=M,t[26]=g,t[27]=I):I=t[27];let E;return t[28]!==I||t[29]!==y?(E=s.jsx("div",{className:x,style:y,children:I}),t[28]=I,t[29]=y,t[30]=E):E=t[30],E};function uy(t){return t.toggleSidebar}function fy(t){return t.isSidebarOpen}function my(t){return t.shortcutOverrides}function hy(t){console.warn("[titlebar] failed to open app menu",t)}function py(t){const e=t.currentTarget.getBoundingClientRect();Gr("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(hy)}const cu=420,gy=({isOpen:t,children:e,className:n})=>{const{t:r}=bt(),o=Ee(N=>N.rightSidebarWidth),a=Ee(N=>N.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),f=i.useRef(o||cu),m=i.useRef(null),u=i.useRef(null),p=i.useRef(null),x=i.useCallback(N=>Math.min(wd,Math.max(vd,N)),[]),y=i.useCallback(N=>{const k=p.current;k&&(k.style.width=`${N}px`,k.style.minWidth=`${N}px`,k.style.maxWidth=`${N}px`,k.style.setProperty("--oc-right-sidebar-width",`${N}px`))},[]),b=Math.min(wd,Math.max(vd,o||cu)),g=t?b:0;i.useLayoutEffect(()=>{if(c)return;const N=p.current;N&&(N.style.minWidth="",N.style.maxWidth="")},[t,c,b]);const h=N=>{if(t){try{N.currentTarget.setPointerCapture(N.pointerId)}catch{}u.current=N.pointerId,l(!0),d.current=N.clientX,f.current=g,m.current=g,y(g),N.preventDefault()}},C=N=>{if(!c||u.current!==N.pointerId)return;const k=d.current-N.clientX,j=x(f.current+k);m.current!==j&&(m.current=j,y(j))},w=N=>{if(u.current!==N.pointerId)return;try{N.currentTarget.releasePointerCapture(N.pointerId)}catch{}const k=x(m.current??g);u.current=null,m.current=null,l(!1),a(k)},S=c?m.current??g:g;return s.jsxs("aside",{ref:p,className:Ie("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:`${S}px`,"--oc-right-sidebar-width":`${c?S:b}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||g===0,children:[t&&s.jsx("div",{className:Ie("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:h,onPointerMove:C,onPointerUp:w,onPointerCancel:w,role:"separator","aria-orientation":"vertical","aria-label":r("sidebar.resize.rightPanelAria")}),s.jsx("div",{className:Ie("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})]})},du=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function Mm(t){const e=mt.c(120),{t:n}=bt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,onConfirm:d}=t,f=l===void 0?!1:l,m=ss(Cy),u=ss(ky),p=Lp(Ny),x=ss(jy),y=ss(Sy),b=ss(vy),g=ss(wy),h=ss(yy);let C;e[0]!==h||e[1]!==b||e[2]!==y||e[3]!==g?(C=()=>du({providerID:y,modelID:b,variant:g,agent:h}),e[0]=h,e[1]=b,e[2]=y,e[3]=g,e[4]=C):C=e[4];const[w,S]=i.useState(C);let N,k;e[5]!==p||e[6]!==u||e[7]!==m||e[8]!==r||e[9]!==c?(N=()=>{r&&(m({directory:c,source:"todoSendDialog"}),u({directory:c}),p())},k=[r,m,u,p,c],e[5]=p,e[6]=u,e[7]=m,e[8]=r,e[9]=c,e[10]=N,e[11]=k):(N=e[10],k=e[11]),i.useEffect(N,k);let j,D;e[12]!==h||e[13]!==b||e[14]!==y||e[15]!==g||e[16]!==r?(j=()=>{r&&S(du({providerID:y,modelID:b,variant:g,agent:h}))},D=[r,y,b,g,h],e[12]=h,e[13]=b,e[14]=y,e[15]=g,e[16]=r,e[17]=j,e[18]=D):(j=e[17],D=e[18]),i.useEffect(j,D);let O,v;e[19]!==w.modelID||e[20]!==w.providerID||e[21]!==r||e[22]!==x?(O=()=>{if(!r||x.length===0)return;const ke=x.find(F=>F.id===w.providerID)??x[0],Le=Array.isArray(ke?.models)?ke.models:[],Te=Le.some(F=>F.id===w.modelID),Z=Le[0]?.id??"";ke?.id===w.providerID&&Te||S(F=>({...F,providerID:ke?.id??"",modelID:Te?F.modelID:Z,variant:""}))},v=[r,x,w.providerID,w.modelID],e[19]=w.modelID,e[20]=w.providerID,e[21]=r,e[22]=x,e[23]=O,e[24]=v):(O=e[23],v=e[24]),i.useEffect(O,v);const M=by;let I;if(e[25]!==w.modelID||e[26]!==w.providerID||e[27]!==x){let ke;e[29]!==w.providerID?(ke=Te=>Te.id===w.providerID,e[29]=w.providerID,e[30]=ke):ke=e[30],I=x.find(ke)?.models?.find(Te=>Te.id===w.modelID),e[25]=w.modelID,e[26]=w.providerID,e[27]=x,e[28]=I}else I=e[28];const E=I;let B;e[31]!==E?(B=E?.variants?Object.keys(E.variants):[],e[31]=E,e[32]=B):B=e[32];const P=B,W=P.length>0;let _,V;e[33]!==w.variant||e[34]!==W?(_=()=>{W||!w.variant||S(xy)},V=[W,w.variant],e[33]=w.variant,e[34]=W,e[35]=_,e[36]=V):(_=e[35],V=e[36]),i.useEffect(_,V);let R;e[37]!==w.modelID||e[38]!==w.providerID?(R=w.providerID.trim().length>0&&w.modelID.trim().length>0,e[37]=w.modelID,e[38]=w.providerID,e[39]=R):R=e[39];const ne=R;let ie;e[40]!==ne||e[41]!==w||e[42]!==d||e[43]!==f?(ie=()=>{!ne||f||d(w)},e[40]=ne,e[41]=w,e[42]=d,e[43]=f,e[44]=ie):ie=e[44];const J=ie;let U,ee;e[45]!==J||e[46]!==r?(U=()=>{if(!r)return;const ke=Le=>{(Le.metaKey||Le.ctrlKey)&&Le.key==="Enter"&&(Le.preventDefault(),J())};return window.addEventListener("keydown",ke),()=>window.removeEventListener("keydown",ke)},ee=[r,J],e[45]=J,e[46]=r,e[47]=U,e[48]=ee):(U=e[47],ee=e[48]),i.useEffect(U,ee);let ae;e[49]!==n||e[50]!==a?(ae=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[49]=n,e[50]=a,e[51]=ae):ae=e[51];const de=ae;let ye;e[52]!==o||e[53]!==f?(ye=ke=>{f||o(ke)},e[52]=o,e[53]=f,e[54]=ye):ye=e[54];let se;e[55]!==de?(se=s.jsx(Ys,{children:s.jsx(zs,{children:de})}),e[55]=de,e[56]=se):se=e[56];let we;e[57]!==n?(we=n("chat.modelControls.model"),e[57]=n,e[58]=we):we=e[58];let fe;e[59]!==we?(fe=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:we}),e[59]=we,e[60]=fe):fe=e[60];let Me;e[61]===Symbol.for("react.memo_cache_sentinel")?(Me=(ke,Le)=>{S(Te=>({...Te,providerID:ke,modelID:Le,variant:""}))},e[61]=Me):Me=e[61];let $;e[62]!==w.modelID||e[63]!==w.providerID?($=s.jsx(Xf,{providerId:w.providerID,modelId:w.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:Me}),e[62]=w.modelID,e[63]=w.providerID,e[64]=$):$=e[64];let K;e[65]!==fe||e[66]!==$?(K=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[fe,$]}),e[65]=fe,e[66]=$,e[67]=K):K=e[67];let q;e[68]!==n?(q=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[68]=n,e[69]=q):q=e[69];let me;e[70]!==q?(me=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:q}),e[70]=q,e[71]=me):me=e[71];const je=!W;let Oe;e[72]===Symbol.for("react.memo_cache_sentinel")?(Oe=ke=>S(Le=>({...Le,variant:ke})),e[72]=Oe):Oe=e[72];let Be;e[73]!==w.variant||e[74]!==je||e[75]!==P?(Be=s.jsx(Bp,{value:w.variant,options:P,disabled:je,onChange:Oe}),e[73]=w.variant,e[74]=je,e[75]=P,e[76]=Be):Be=e[76];let Fe;e[77]!==me||e[78]!==Be?(Fe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[me,Be]}),e[77]=me,e[78]=Be,e[79]=Fe):Fe=e[79];let ue;e[80]!==n?(ue=n("sessions.scheduledTasks.editor.agent.label"),e[80]=n,e[81]=ue):ue=e[81];let Re;e[82]!==ue?(Re=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ue}),e[82]=ue,e[83]=Re):Re=e[83];let xe;e[84]===Symbol.for("react.memo_cache_sentinel")?(xe=ke=>S(Le=>({...Le,agent:ke})),e[84]=xe):xe=e[84];let oe;e[85]!==w.agent?(oe=s.jsx(Zf,{agentName:w.agent,filter:M,dropdownPortalToBody:!0,onChange:xe}),e[85]=w.agent,e[86]=oe):oe=e[86];let ve;e[87]!==Re||e[88]!==oe?(ve=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Re,oe]}),e[87]=Re,e[88]=oe,e[89]=ve):ve=e[89];let Se;e[90]!==K||e[91]!==Fe||e[92]!==ve?(Se=s.jsxs("div",{className:"flex flex-col gap-4",children:[K,Fe,ve]}),e[90]=K,e[91]=Fe,e[92]=ve,e[93]=Se):Se=e[93];let le;e[94]!==o?(le=()=>o(!1),e[94]=o,e[95]=le):le=e[95];let T;e[96]!==n?(T=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[96]=n,e[97]=T):T=e[97];let L;e[98]!==f||e[99]!==le||e[100]!==T?(L=s.jsx(ze,{variant:"ghost",size:"sm",onClick:le,disabled:f,children:T}),e[98]=f,e[99]=le,e[100]=T,e[101]=L):L=e[101];const he=!ne||f;let ge;e[102]!==f||e[103]!==n?(ge=n(f?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[102]=f,e[103]=n,e[104]=ge):ge=e[104];let z;e[105]!==J||e[106]!==he||e[107]!==ge?(z=s.jsx(ze,{size:"sm",onClick:J,disabled:he,children:ge}),e[105]=J,e[106]=he,e[107]=ge,e[108]=z):z=e[108];let pe;e[109]!==L||e[110]!==z?(pe=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[L,z]}),e[109]=L,e[110]=z,e[111]=pe):pe=e[111];let Ae;e[112]!==se||e[113]!==Se||e[114]!==pe?(Ae=s.jsxs(Es,{className:"max-w-md overflow-visible",children:[se,Se,pe]}),e[112]=se,e[113]=Se,e[114]=pe,e[115]=Ae):Ae=e[115];let G;return e[116]!==r||e[117]!==ye||e[118]!==Ae?(G=s.jsx(Ms,{open:r,onOpenChange:ye,children:Ae}),e[116]=r,e[117]=ye,e[118]=Ae,e[119]=G):G=e[119],G}function xy(t){return{...t,variant:""}}function by(t){return vc(t.mode)}function yy(t){return t.currentAgentName||""}function wy(t){return t.currentVariant||""}function vy(t){return t.currentModelId}function Sy(t){return t.currentProviderId}function jy(t){return t.providers}function Ny(t){return t.loadAgents}function ky(t){return t.loadAgents}function Cy(t){return t.loadProviders}const Xl=5,Fm=15,Ko=new Map,ca=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},Ay=(t,e)=>{const n=ca(e);return Math.max(n*Xl,Math.min(n*Fm,n*t))},Dy=async(t,e)=>{const n=await zp(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},Ty=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,uu=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],fu=(t,e)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},Py=t=>{const e=mt.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:f,transition:m,isDragging:u}=uc(o);let p;e[2]!==f?(p=fc.Transform.toString(f),e[2]=f,e[3]=p):p=e[3];let x;e[4]!==p||e[5]!==m?(x={transform:p,transition:m},e[4]=p,e[5]=m,e[6]=x):x=e[6];const y=u&&"opacity-60";let b;e[7]!==y?(b=Ie(y),e[7]=y,e[8]=b):b=e[8];let g;e[9]!==a||e[10]!==r||e[11]!==u||e[12]!==c||e[13]!==d?(g=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]=g):g=e[14];let h;return e[15]!==l||e[16]!==x||e[17]!==b||e[18]!==g?(h=s.jsx("li",{ref:l,style:x,className:b,children:g}),e[15]=l,e[16]=x,e[17]=b,e[18]=g,e[19]=h):h=e[19],h},Iy=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=bt(),[c,l]=i.useState(!1),[d,f]=i.useState(""),[m,u]=i.useState([]),[p,x]=i.useState(""),[y,b]=i.useState(null),[g,h]=i.useState(()=>new Set),[C,w]=i.useState([]),[S,N]=i.useState(null),[k,j]=i.useState(!1),[D,O]=i.useState(0),v=i.useRef(!1),M=i.useRef(""),I=i.useRef(null),E=Ee(F=>F.todoPanelHeight),B=Ee(F=>F.setTodoPanelHeight),P=Ee(F=>F.notesPanelHeight),W=Ee(F=>F.setNotesPanelHeight),[_,V]=i.useState(!1),R=i.useRef(0),ne=i.useRef(E),ie=ft(F=>F.currentSessionId),J=ft(F=>F.createSession),U=ft(F=>F.initializeNewOpenChamberSession),ee=ft(F=>F.sendMessage),ae=ft(F=>F.setCurrentSession),de=mi(F=>F.setPendingInputText),ye=qs(F=>F.currentDirectory),se=Ee(F=>F.openContextPanelTab),we=Ee(F=>F.setActiveMainTab),fe=Ee(F=>F.setSessionSwitcherOpen),Me=Ee(F=>F.padding),$=i.useCallback(async(F,re)=>{if(!t)return!1;const te=t.id,Ye=(Ko.get(te)??Promise.resolve()).catch(()=>{}).then(()=>Vp(t,{notes:F,todos:re}));Ko.set(te,Ye);try{const Ke=await Ye;return Ke||ce.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),Ke}finally{Ko.get(te)===Ye&&Ko.delete(te)}},[t,a]);i.useEffect(()=>{if(!t){f(""),u([]),w([]),x(""),h(new Set);return}let F=!1;return l(!0),(async()=>{try{const re=await _p(t),te=await Promise.all(re.plans.map(Ve=>Dy(Ve,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(F)return;f(re.notes),u(uu(re.todos)),w(te),M.current=re.notes,v.current=!0,x(""),h(new Set)}catch{F||(ce.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),f(""),u([]),w([]),M.current="",v.current=!0)}finally{F||l(!1)}})(),()=>{F=!0}},[D,t,a]),i.useEffect(()=>{if(!t)return;const F=re=>{const te=re.detail;te?.projectId&&te.projectId!==t.id||O(Ve=>Ve+1)};return window.addEventListener("openchamber:project-plan-saved",F),window.addEventListener("openchamber:project-notes-updated",F),()=>{window.removeEventListener("openchamber:project-plan-saved",F),window.removeEventListener("openchamber:project-notes-updated",F)}},[t]),i.useEffect(()=>{if(m.length<7)return;const F=Ay(m.length,Me),re=ca(Me)*Xl;E!==F&&(E<re||E>F)&&B(F)},[m.length,Me,E,B]),i.useEffect(()=>{if(!_)return;const F=te=>{const Ve=te.clientY-R.current,Ye=Math.min(ca(Me)*Fm,Math.max(ca(Me)*Xl,ne.current+Ve));B(Ye)},re=()=>{V(!1)};return window.addEventListener("pointermove",F),window.addEventListener("pointerup",re,{once:!0}),window.addEventListener("pointercancel",re,{once:!0}),()=>{window.removeEventListener("pointermove",F),window.removeEventListener("pointerup",re),window.removeEventListener("pointercancel",re)}},[_,Me,B]);const K=i.useCallback(F=>{V(!0),R.current=F.clientY,ne.current=E,F.preventDefault()},[E]),q=i.useCallback(()=>{I.current!==null&&(window.clearTimeout(I.current),I.current=null)},[]),me=i.useCallback(()=>{q(),M.current=d,$(d,m)},[q,d,$,m]);i.useEffect(()=>{if(!(!t||!v.current)&&d!==M.current)return I.current=window.setTimeout(()=>{I.current=null,M.current=d,$(d,m)},400),()=>{q()}},[q,d,$,t,m]),i.useEffect(()=>()=>q(),[q]);const je=i.useCallback(()=>{const F=p.trim();if(!F)return;const re=fu(m,{id:Ty(),text:F.slice(0,Wo),completed:!1,createdAt:Date.now()});u(re),x(""),$(d,re)},[p,d,$,m]),Oe=i.useCallback(F=>{h(re=>{const te=new Set(re);return te.has(F)?te.delete(F):te.add(F),te})},[]),Be=i.useCallback((F,re)=>{const te=m.find(Je=>Je.id===F);if(!te||te.completed===re)return;const Ve=m.filter(Je=>Je.id!==F),Ye={...te,completed:re},Ke=re?[...Ve,Ye]:fu(Ve,Ye);u(Ke),$(d,Ke)},[d,$,m]),Fe=i.useCallback(F=>{const re=m.filter(te=>te.id!==F);u(re),$(d,re)},[d,$,m]),ue=i.useCallback(()=>{const F=m.filter(re=>!re.completed);F.length!==m.length&&(u(F),$(d,F))},[d,$,m]),Re=i.useCallback(F=>{const{active:re,over:te}=F;if(!te||re.id===te.id)return;const Ve=m.findIndex(Je=>Je.id===re.id),Ye=m.findIndex(Je=>Je.id===te.id);if(Ve===-1||Ye===-1)return;const Ke=uu(Lf(m,Ve,Ye));u(Ke),$(d,Ke)},[d,$,m]),xe=ba(vo(ya,{activationConstraint:{distance:8}})),oe=p.slice(0,Wo),ve=m.reduce((F,re)=>F+(re.completed?1:0),0),Se=i.useCallback(()=>{we("chat"),fe(!1)},[we,fe]),le=i.useCallback((F,re)=>{!t||y||N({kind:"session",todoId:F,todoText:re})},[t,y]),T=i.useCallback(F=>{if(!ie){ce.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}Se();const re=`\`\`\`md
4
- ${F}
5
- \`\`\``;de(re,"append"),ce.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[ie,r,Se,de,a]),L=i.useCallback((F,re)=>{if(!(!t||y)){if(!n){ce.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}N({kind:"worktree",todoId:F,todoText:re})}},[n,t,y,a]),he=i.useCallback(async F=>{if(!t||!S)return;const re=await Rn("plan.todo.visible",{todo_text:S.todoText}),Ve=[{synthetic:!0,text:await Rn("plan.todo.instructions",{todo_text:S.todoText})}];j(!0),b(S.todoId);try{Se();let Ye=null,Ke=t.path;if(S.kind==="worktree"){if(!n){ce.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const nt=await em(t.path,tm());if(!nt?.id)return;Ye=nt.id,Ke=nt.path}else{const nt=await J(void 0,t.path,null);if(!nt?.id){ce.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}Ye=nt.id,Ke=nt.directory??t.path,U(nt.id,ss.getState().agents??[])}if(!Ye)return;const Je=Sc.getState();Je.saveSessionModelSelection(Ye,F.providerID,F.modelID),F.agent.trim()&&(Je.saveSessionAgentSelection(Ye,F.agent),Je.saveAgentModelForSession(Ye,F.agent,F.providerID,F.modelID),Je.saveAgentModelVariantForSession(Ye,F.agent,F.providerID,F.modelID,F.variant||void 0)),ae(Ye,Ke),await ee(re,F.providerID,F.modelID,F.agent.trim()||void 0,void 0,void 0,Ve,F.variant||void 0),ce.success(S.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),N(null),r?.()}catch(Ye){const Ke=Ye instanceof Error?Ye.message:void 0;ce.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),Ke?{description:Ke}:void 0)}finally{j(!1),b(null)}},[n,J,U,r,S,t,Se,ee,ae,a]),ge=i.useRef(null),[z,pe]=i.useState(!1),[Ae,G]=i.useState(null),ke=i.useCallback(async F=>{if(!(!t||Ae)){G(F);try{if(!await $p(t,F)){ce.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}w(te=>te.filter(Ve=>Ve.id!==F)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{G(null)}}},[Ae,t,a]),Le=i.useCallback(async()=>{if(!t||z)return;const F=await gp({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(F.success&&F.path){pe(!0);try{const re=new URLSearchParams({path:F.path,allowOutsideWorkspace:"true"});F.outsideFileGrant&&re.set("outsideFileGrant",F.outsideFileGrant);const te=await Ns(`/api/fs/read?${re.toString()}`,{cache:"no-store"});if(!te.ok){ce.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const Ve=await te.text();if(!Ve.trim()){ce.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Ye=F.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Td(t,Ve,Ye)){ce.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),ce.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(re){const te=re instanceof Error?re.message:void 0;ce.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),te?{description:te}:void 0)}finally{pe(!1)}}else F.error==="Native file picker not available"&&ge.current?.click()},[z,t,a]),Te=i.useCallback(async F=>{if(!(!t||!F)){pe(!0);try{const re=await F.text();if(!re.trim()){ce.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const te=F.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Td(t,re,te)){ce.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),ce.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(re){const te=re instanceof Error?re.message:void 0;ce.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),te?{description:te}:void 0)}finally{pe(!1)}}},[t,a]),Z=i.useCallback(F=>{const re=t?.path?.trim(),te=ye?.trim()||re;te&&se(te,{mode:"plan",targetPath:F.path,dedupeKey:F.path,label:F.title})},[ye,se,t]);return t?s.jsxs("div",{className:Ie("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,"/",Pd]})]}),s.jsx(Ti,{value:d,onChange:F=>f(F.target.value.slice(0,Pd)),onBlur:me,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:P,onResizeHeightChange:W,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:m.length===1?a("rightSidebar.contextNotesTodo.todo.itemsSingle",{count:m.length}):a("rightSidebar.contextNotesTodo.todo.itemsPlural",{count:m.length})}),s.jsx("button",{type:"button",onClick:ue,disabled:c||ve===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:[oe.length,"/",Wo]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Mn,{value:oe,onChange:F=>x(F.target.value.slice(0,Wo)),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),je())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:je,disabled:c||oe.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(A,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:Ie("overflow-y-auto rounded-lg border border-border/60 bg-background/40",_&&"transition-none"),style:m.length<7?void 0:{height:`${E}px`,maxHeight:`${E}px`},children:m.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.todo.empty")}):s.jsx(wa,{sensors:xe,collisionDetection:va,onDragEnd:Re,children:s.jsx(Vl,{items:m.map(F=>F.id),strategy:_l,children:s.jsx("ul",{className:"divide-y divide-border/50",children:m.map(F=>{const re=g.has(F.id);return s.jsx(Py,{id:F.id,children:te=>s.jsxs("div",{className:Ie("flex gap-1.5 px-2.5 py-1.5",re?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:te.setActivatorNodeRef,...te.attributes,...te.listeners,onClick:Ve=>{Ve.preventDefault(),Ve.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:F.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:F.text}),children:s.jsx(A,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(Fi,{checked:F.completed,onChange:Ve=>Be(F.id,Ve),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:F.text})})}),s.jsx("button",{type:"button",onClick:()=>Oe(F.id),className:Ie("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",re?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",F.completed&&"text-muted-foreground line-through"),title:re?void 0:F.text,"aria-label":re?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:F.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:F.text}),children:F.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Fe(F.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:F.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:F.text}),children:s.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",disabled:y===F.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:F.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:F.text}),children:s.jsx(A,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(en,{align:"end",className:"w-56",children:[s.jsx(xs,{onClick:()=>T(F.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(xs,{onClick:()=>le(F.id,F.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(xs,{onClick:()=>{L(F.id,F.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},F.id)})})})})}),m.length>=7&&s.jsx("div",{className:Ie("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",_&&"bg-[var(--interactive-border)]"),onPointerDown:K,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:ge,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:F=>{const re=F.target.files?.[0]??null;Te(re),F.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Le,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(A,{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(F=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>Z(F),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:F.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(F.createdAt).toLocaleDateString(eo())})]}),s.jsx("button",{type:"button",onClick:()=>{ke(F.id)},disabled:Ae===F.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:F.title}),children:s.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},F.id))})})]}),s.jsx(Mm,{open:S!==null,onOpenChange:F=>{!F&&!k&&N(null)},target:S?.kind??"session",projectDirectory:t?.path??null,submitting:k,onConfirm:he})]}):s.jsx("div",{className:Ie("w-full min-w-0 p-3",o),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.empty.selectProject")})})},Om=12,Ry=[{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"}],Ey=t=>{const e=mt.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,f=a===void 0?900:a,m=c===void 0?Ry:c,u=Xe.useRef(!1);let p,x;e[0]!==n||e[1]!==l?(p=()=>{!n&&u.current&&l?.(),n&&(u.current=!0)},x=[n,l],e[0]=n,e[1]=l,e[2]=p,e[3]=x):(p=e[2],x=e[3]),Xe.useEffect(p,x);let y;e[4]===Symbol.for("react.memo_cache_sentinel")?(y=Array.from({length:Om},My),e[4]=y):y=e[4];const b=y;if(!n)return null;let g;e[5]!==o?(g=Ie("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=g):g=e[6];let h;if(e[7]!==d||e[8]!==m||e[9]!==f){let w;e[11]!==d||e[12]!==f?(w=S=>{const N={"--burst-delay":`${S.delay}ms`,"--burst-x":`${S.x}%`,"--burst-y":`${S.y}%`,"--firework-color":`var(${S.colorVar})`,"--firework-duration":`${f}ms`};return s.jsx("div",{className:"firework-burst",style:N,children:b.map((k,j)=>{const D=k.x*S.radius,O=k.y*S.radius,v={"--translate-x":`${D}px`,"--translate-y":`${O}px`,"--particle-delay":`${k.delay}ms`,color:`var(${S.colorVar})`};return s.jsx("span",{className:"firework-particle",style:v},`${S.id}-${j}-${d}`)})},`${S.id}-${d}`)},e[11]=d,e[12]=f,e[13]=w):w=e[13],h=m.map(w),e[7]=d,e[8]=m,e[9]=f,e[10]=h}else h=e[10];let C;return e[14]!==d||e[15]!==g||e[16]!==h?(C=s.jsx("div",{className:g,"aria-hidden":"true","data-burst-key":d,children:h}),e[14]=d,e[15]=g,e[16]=h,e[17]=C):C=e[17],C};function My(t,e){const n=Math.PI*2*e/Om;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const Fy=t=>{const e=mt.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]=Xe.useState(a),d=Xe.useRef(null);let f;e[3]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{d.current&&(window.clearTimeout(d.current),d.current=null)},e[3]=f):f=e[3];const m=f;let u;e[4]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{m(),l(Oy)},e[4]=u):u=e[4];const p=u;let x;e[5]!==o?(x=()=>{m(),l(Ly),d.current=window.setTimeout(()=>{l(By),d.current=null},o)},e[5]=o,e[6]=x):x=e[6];const y=x;let b,g;e[7]===Symbol.for("react.memo_cache_sentinel")?(b=()=>()=>m(),g=[m],e[7]=b,e[8]=g):(b=e[7],g=e[8]),Xe.useEffect(b,g);let h;return e[9]!==c.cycle||e[10]!==c.isActive||e[11]!==y?(h={isActive:c.isActive,burstKey:c.cycle,triggerFireworks:y,dismissFireworks:p},e[9]=c.cycle,e[10]=c.isActive,e[11]=y,e[12]=h):h=e[12],h};function Oy(t){return t.isActive?{...t,isActive:!1}:t}function Ly(t){return{isActive:!0,cycle:t.cycle+1}}function By(t){return t.isActive?{...t,isActive:!1}:t}const Lm=i.createContext(void 0),Vy=t=>{const e=mt.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=Fy();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 f;e[3]!==o||e[4]!==r?(f=s.jsx(Ey,{isActive:r,burstKey:o}),e[3]=o,e[4]=r,e[5]=f):f=e[5];let m;return e[6]!==n||e[7]!==f||e[8]!==d?(m=s.jsxs(Lm.Provider,{value:d,children:[n,f]}),e[6]=n,e[7]=f,e[8]=d,e[9]=m):m=e[9],m},_y=()=>{const t=i.useContext(Lm);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Bm="gitmojiCache",$y=1e3*60*60*24*7,Vm="1",zy="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",_m=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},bl=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Bm);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==Vm||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(_m),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},Wy=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:Vm};window.localStorage.setItem(Bm,JSON.stringify(e))}catch{return}},mu=t=>Date.now()-t.fetchedAt<$y;let qo=null;const ko=new Set,hu=async()=>{if(qo)return qo;const t=(async()=>{try{const e=await fetch(zy);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(_m):[];return Wy(r),ko.forEach(o=>o(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return ko.forEach(r=>r(n)),n}finally{qo=null}})();return qo=t,t},Uy=t=>{const[e,n]=i.useState(()=>t?bl()?.gitmojis??[]:[]),[r,o]=i.useState(!1),a=i.useRef(t);a.current=t,i.useEffect(()=>{if(!t){ko.delete(n),n([]),o(!1);return}const l=bl();if(l&&(n(l.gitmojis),mu(l)))return;ko.add(n),o(!0);let d=!1;return hu().finally(()=>{!d&&a.current&&o(!1)}),()=>{d=!0,ko.delete(n)}},[t]);const c=i.useCallback(async()=>{if(!a.current)return[];if(e.length>0)return e;const l=bl();return l&&mu(l)?l.gitmojis:hu()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:c}},pu=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function Hy(t,e,n){const r=mt.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[f,m]=await Promise.all([Wp(t),Up(t)]).catch(Gy);if(d)return;const u=pu(f),p=pu(m);if(!u||!p||p===u)return;const x=n||"",y=p.split("/").filter(Boolean).pop()||p;a({source:"sdk",path:p,projectDirectory:u,branch:x,label:x||y,name:y,worktreeRoot:p,worktreeStatus:"ready",headState:x?"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 Gy(){return["",""]}const uo=async(t,e)=>{const n=await Ns(`/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 go(t){return uo("plan",t)}async function Ky(t){return uo("conflict-details",{tempWorktreePath:t})}async function qy(t){return(await uo("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function Yy(t){return uo("run",{plan:t})}async function Qy(t){await uo("abort",{state:t})}async function Jy(t){return uo("continue",{state:t})}const Xy=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=bt(),d=ft(R=>R.currentSessionId),f=Ee(R=>R.setActiveMainTab),[m,u]=Xe.useState(!1),p=Xe.useRef(null),[x,y]=Xe.useState(o);Xe.useEffect(()=>{y(o)},[o]),Xe.useEffect(()=>{if(m){const R=setTimeout(()=>{p.current?.focus()},0);return()=>clearTimeout(R)}},[m]);const b=!!(t&&e&&x&&x!=="HEAD"&&e!==x),[g,h]=Xe.useState({kind:"idle"}),[C,w]=Xe.useState(!1),[S,N]=Xe.useState([]),k=Xe.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);Xe.useEffect(()=>{if(!k||typeof window>"u")return;const R=window.localStorage.getItem(k);if(!R)return;let ne=!1;try{const ie=JSON.parse(R);if(!ie?.tempWorktreePath||ie.repoRoot!==t){window.localStorage.removeItem(k);return}(async()=>{const J=await qy(ie.tempWorktreePath).catch(()=>!1);if(ne)return;if(!J){window.localStorage.removeItem(k);return}const U=await Ky(ie.tempWorktreePath).catch(()=>null);ne||U&&h({kind:"conflict",state:ie,details:U})})()}catch{window.localStorage.removeItem(k)}return()=>{ne=!0}},[k,t]),Xe.useEffect(()=>{if(!b){h({kind:"idle"});return}let R=!1;return h({kind:"loading"}),(async()=>{try{const ne=await go({repoRoot:t,sourceBranch:e,targetBranch:x});if(R)return;if(h({kind:"ready",plan:ne}),ne.commits.length>0){const J=ne.commits.slice(-50).reverse(),U=await Hp(t,J);R||(N(U),w(!1))}else R||(N([]),w(!1))}catch{R||h({kind:"idle"})}})(),()=>{R=!0}},[b,t,e,x,a]);const j=Xe.useCallback(R=>{d&&ft.getState().setWorktreeMetadata(d,{...n,createdFromBranch:R})},[d,n]),D=ft(R=>R.openNewSessionDraft),O=Xe.useCallback(async R=>{const ne=await Rn("git.integrate.cherrypick.resolve.visible",{current_commit:R.state.currentCommit,target_branch:R.state.targetBranch}),ie=await Rn("git.integrate.cherrypick.resolve.instructions",{repo_root:R.state.repoRoot,temp_worktree_path:R.state.tempWorktreePath,source_branch:R.state.sourceBranch,target_branch:R.state.targetBranch,current_commit:R.state.currentCommit}),J=`Cherry-pick conflict context (JSON)
6
- ${JSON.stringify({repoRoot:R.state.repoRoot,tempWorktreePath:R.state.tempWorktreePath,sourceBranch:R.state.sourceBranch,targetBranch:R.state.targetBranch,currentCommit:R.state.currentCommit,remainingCommits:R.state.remainingCommits,statusPorcelain:R.details.statusPorcelain,unmergedFiles:R.details.unmergedFiles,currentPatchMeta:R.details.currentPatchMeta,currentPatch:R.details.currentPatch,diff:R.details.diff},null,2)}`;return{visibleText:ne,instructionsText:ie,payloadText:J}},[]),v=mi(R=>R.setPendingInputText),M=mi(R=>R.setPendingSyntheticParts),I=Xe.useCallback(async(R,ne)=>{const ie=await O(R);if(ne){D({directoryOverride:R.state.tempWorktreePath,initialPrompt:ie.visibleText,syntheticParts:[{text:ie.instructionsText,synthetic:!0},{text:ie.payloadText,synthetic:!0}]}),f("chat");return}if(!d){ce.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}v(ie.visibleText,"replace"),M([{text:ie.instructionsText,synthetic:!0},{text:ie.payloadText,synthetic:!0}]),f("chat")},[d,f,O,D,v,M,l]),E=Xe.useCallback(async()=>{if(g.kind==="ready"){if(g.plan.commits.length===0){ce.message(l("gitView.integrate.noCommitsToMoveToast"));return}h({kind:"running",plan:g.plan});try{const R=await Yy(g.plan);if(R.kind==="success"){ce.success(l("gitView.integrate.commitsMovedToast"),{description:R.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:R.moved,branch:g.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:R.moved,branch:g.plan.targetBranch})});const ne=await go(g.plan);h({kind:"ready",plan:ne}),c?.();return}R.kind==="conflict"&&(ce.error(l("gitView.integrate.cherryPickConflictToast"),{description:l("gitView.integrate.cherryPickConflictDescription")}),h({kind:"conflict",state:R.state,details:R.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(R.state)))}catch(R){const ne=R instanceof Error?R.message:String(R);ce.error(l("gitView.integrate.failedToMoveToast"),{description:ne});const ie=await go({repoRoot:t,sourceBranch:e,targetBranch:x}).catch(()=>null);h(ie?{kind:"ready",plan:ie}:{kind:"idle"})}}},[g,c,t,e,x,k,l]),B=Xe.useCallback(async()=>{if(g.kind==="conflict")try{await Qy(g.state),ce.message(l("gitView.integrate.cherryPickAbortedToast")),k&&typeof window<"u"&&window.localStorage.removeItem(k)}finally{const R=await go({repoRoot:t,sourceBranch:e,targetBranch:x}).catch(()=>null);h(R?{kind:"ready",plan:R}:{kind:"idle"})}},[g,t,e,x,k,l]),P=Xe.useCallback(async()=>{if(g.kind==="conflict")try{const R=await Jy(g.state);if(R.kind==="success"){ce.success(l("gitView.integrate.cherryPickFinishedToast"));const ne=await go({repoRoot:t,sourceBranch:e,targetBranch:x}).catch(()=>null);h(ne?{kind:"ready",plan:ne}:{kind:"idle"}),k&&typeof window<"u"&&window.localStorage.removeItem(k),c?.();return}R.kind==="conflict"&&(h({kind:"conflict",state:R.state,details:R.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(R.state)))}catch(R){const ne=R instanceof Error?R.message:String(R);ce.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:ne})}},[g,t,e,x,c,k,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(A,{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")}),g.kind==="ready"&&g.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:g.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:g.kind==="loading"||g.kind==="running"?s.jsx(A,{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," → ",x]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(tn,{open:m,onOpenChange:u,children:[s.jsx(Zs,{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:x}),s.jsx(A,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(en,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:s.jsxs($a,{className:"h-full min-h-0",children:[s.jsx(za,{ref:p,placeholder:l("gitView.branch.searchPlaceholder"),onKeyDown:R=>R.stopPropagation()}),s.jsxs(Wa,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(Ua,{children:l("gitView.branch.empty")}),s.jsx(di,{heading:l("gitView.branch.localBranches"),children:r.map(R=>s.jsx(fi,{value:R,onSelect:()=>{y(R),j(R),u(!1)},children:R},R))})]})]})})]}),g.kind==="ready"?s.jsx(ze,{size:"sm",onClick:()=>{E()},disabled:!b||g.plan.commits.length===0,children:l("gitView.integrate.move")}):g.kind==="loading"?s.jsx(ze,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):g.kind==="running"?s.jsx(ze,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),g.kind==="ready"&&g.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),g.kind==="ready"&&g.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:[" (",g.plan.commits.length,")"]})]}),S.length>0&&g.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>w(R=>!R),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?S:S.slice(0,5)).map(R=>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:R.short}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:R.subject||R.sha})]},R.sha)),S.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.previewUnavailable")}),g.plan.commits.length>S.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:S.length})})]})]}),g.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:g.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:g.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.details.unmergedFiles.slice(0,6).map(R=>s.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:R},R)),g.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:g.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:()=>{B()},children:l("gitView.operation.abort")}),s.jsxs(ze,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{I({state:g.state,details:g.details},!1)},children:[s.jsx(A,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs(ze,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{I({state:g.state,details:g.details},!0)},children:[s.jsx(A,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.newSession")]}),s.jsx(ze,{size:"sm",className:"typography-meta",onClick:()=>{P()},children:l("gitView.operation.continue")})]})]})]})]})},Zy=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=bt(),[d,f]=i.useState([]),[m,u]=i.useState(!1),[p,x]=i.useState(""),[y,b]=i.useState(""),[g,h]=i.useState(null),[C,w]=i.useState({}),S=i.useCallback(async()=>{if(n){u(!0);try{const v=await Gp(n);f(v.stashes),w({})}catch(v){ce.error(v instanceof Error?v.message:l("gitView.stashes.toast.loadFailed"))}finally{u(!1)}}},[n,l]);i.useEffect(()=>{t&&S()},[S,t]),i.useEffect(()=>{if(!t||!n||d.length===0)return;let v=!1;const M=d.map(I=>I.ref);return Kp(n,M).then(I=>{v||w(I.counts)}).catch(()=>{}),()=>{v=!0}},[n,t,d]);const N=i.useMemo(()=>{const v=p.trim().toLowerCase();return v?d.filter(M=>`${M.ref} ${M.message} ${M.relativeTime}`.toLowerCase().includes(v)):d},[p,d]),k=i.useCallback(async v=>{await S(),await c?.(v)},[S,c]),j=async()=>{if(!(!n||g)){h("create");try{const v=await qp(n,{message:y.trim()||void 0});v.created?(ce.success(l("gitView.stashes.toast.created")),b("")):ce.info(l("gitView.stashes.toast.noChanges")),await k({affectsIndex:!!(v.created&&o)})}catch(v){ce.error(v instanceof Error?v.message:l("gitView.stashes.toast.createFailed"))}finally{h(null)}}},D=async(v,M)=>{if(!(!n||g)&&!(M==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:v.ref})))){h(`${M}:${v.ref}`);try{M==="apply"&&await Yp(n,{ref:v.ref}),M==="pop"&&await Qp(n,{ref:v.ref}),M==="drop"&&await Jp(n,{ref:v.ref});const I=M==="apply"?"gitView.stashes.toast.applySuccess":M==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";ce.success(l(I)),await k({affectsIndex:M!=="drop"})}catch(I){const E=M==="apply"?"gitView.stashes.toast.applyFailed":M==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";ce.error(I instanceof Error?I.message:l(E)),await k({affectsIndex:M!=="drop"})}finally{h(null)}}},O=g!==null;return s.jsx(Ms,{open:t,onOpenChange:e,children:s.jsxs(Es,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(Ys,{children:[s.jsxs(zs,{className:"flex items-center gap-2",children:[s.jsx(A,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(an,{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(Mn,{value:y,onChange:v=>b(v.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:O||!r,className:"flex-1"}),s.jsxs(ze,{onClick:j,disabled:!r||O||!n,children:[g==="create"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{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(A,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(Mn,{value:p,onChange:v=>x(v.target.value),placeholder:l("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto",children:m?s.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:s.jsx(A,{name:"loader-4",className:"size-5 animate-spin"})}):N.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:l(p?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):N.map((v,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:v.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{children:M===0&&!p.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:M+1})})}),s.jsx(At,{sideOffset:6,children:v.ref})]})," · ",v.relativeTime," · ",typeof C[v.ref]=="number"?l("gitView.stashes.fileCount",{count:C[v.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(yl,{label:l("gitView.stashes.actions.apply"),loading:g===`apply:${v.ref}`,onClick:()=>D(v,"apply"),disabled:O,children:s.jsx(A,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(yl,{label:l("gitView.stashes.actions.pop"),loading:g===`pop:${v.ref}`,onClick:()=>D(v,"pop"),disabled:O,children:s.jsx(A,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(yl,{label:l("gitView.stashes.actions.drop"),loading:g===`drop:${v.ref}`,onClick:()=>D(v,"drop"),disabled:O,destructive:!0,children:s.jsx(A,{name:"delete-bin",className:"size-4"})})]})]},v.ref))})]})})},yl=t=>{const e=mt.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,f=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let m;e[0]!==f?(m=Ie("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",f),e[0]=f,e[1]=m):m=e[1];let u;e[2]!==l||e[3]!==r?(u=r?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):l,e[2]=l,e[3]=r,e[4]=u):u=e[4];let p;e[5]!==o||e[6]!==n||e[7]!==c||e[8]!==d||e[9]!==m||e[10]!==u?(p=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:m,onClick:c,disabled:o,children:u})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=m,e[10]=u,e[11]=p):p=e[11];let x;e[12]!==n?(x=s.jsx(At,{sideOffset:6,children:n}),e[12]=n,e[13]=x):x=e[13];let y;return e[14]!==p||e[15]!==x?(y=s.jsxs(kt,{children:[p,x]}),e[14]=p,e[15]=x,e[16]=y):y=e[16],y},ew=t=>{const e=mt.c(16),{onOpenStashes:n}=t,{t:r}=bt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(A,{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 f;e[9]!==n||e[10]!==r?(f=n?s.jsxs(ze,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(A,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=f):f=e[11];let m;return e[12]!==c||e[13]!==d||e[14]!==f?(m=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,f]}),e[12]=c,e[13]=d,e[14]=f,e[15]=m):m=e[15],m},ii=8,tw=t=>{const e=mt.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,f=Math.max(r,a+1)*ii+ii/2,m=i.useRef(null),u=i.useRef(null);let p;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==f?(p=()=>{const h=m.current,C=u.current;if(!h||!C)return;const w=h.offsetHeight;if(w===0)return;const S=window.devicePixelRatio||1;C.width=f*S,C.height=w*S;const N=C.getContext("2d");if(!N)return;N.scale(S,S),N.clearRect(0,0,f,w);const k=w/2,j=a*ii+ii/2,D=getComputedStyle(C),O=D.getPropertyValue("--surface-muted-foreground").trim()||D.color,v=E=>{if(!E.startsWith("var("))return E;const B=E.slice(4,-1).trim();return D.getPropertyValue(B).trim()||O},M=[...l].sort(nw);for(const E of M){const B=E.fromLane*ii+ii/2,P=E.toLane*ii+ii/2,W=E.type==="passing"?.72:E.type==="branch-out"||E.type==="merge-in"?.95:1;N.beginPath(),N.strokeStyle=v(E.color),N.globalAlpha=W,N.lineWidth=1.25,N.lineCap="round";e:switch(E.type){case"passing":case"commit-lane":{N.moveTo(B,0),N.lineTo(B,w);break e}case"top-stub":{N.moveTo(B,0),N.lineTo(B,k);break e}case"bottom-stub":{N.moveTo(B,k),N.lineTo(B,w);break e}case"branch-out":{const _=(k+w)/2;N.moveTo(j,k),N.bezierCurveTo(j,_,P,_,P,w);break e}case"merge-in":{const _=k/2;N.moveTo(B,0),N.bezierCurveTo(B,_,j,_,j,k);break e}default:continue}N.stroke(),N.globalAlpha=1}const I=D.getPropertyValue("--background").trim()||D.getPropertyValue("--surface-background").trim();N.beginPath(),N.arc(j,k,4,0,Math.PI*2),N.fillStyle=v(c),N.fill(),N.beginPath(),N.arc(j,k,5,0,Math.PI*2),N.strokeStyle=I||O,N.lineWidth=2,N.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=f,e[4]=p):p=e[4];let x;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==f?(x=[n,a,c,l,r,o,f],e[5]=c,e[6]=l,e[7]=o,e[8]=a,e[9]=n,e[10]=r,e[11]=f,e[12]=x):x=e[12],i.useLayoutEffect(p,x);let y;e[13]!==f?(y={width:f,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=f,e[14]=y):y=e[14];let b;e[15]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx("canvas",{ref:u,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=b):b=e[15];let g;return e[16]!==y?(g=s.jsx("div",{ref:m,style:y,children:b}),e[16]=y,e[17]=g):g=e[17],g};function sw(t){return t==="branch-out"||t==="merge-in"}function nw(t,e){const n=sw;return(n(t.type)?1:0)-(n(e.type)?1:0)}const gu=15e3,xu=500,bu=12,yu=8*1024*1024,wu=t=>typeof t=="string"?0:(t.original?.length??0)+(t.modified?.length??0),vu=t=>{if(t.size<=bu){let o=0;for(const a of t.values())o+=wu(a);if(o<=yu)return t}const e=Array.from(t.entries()).reverse(),n=new Map;let r=0;for(const[o,a]of e){if(n.size>=bu)continue;const c=wu(a);r+c>yu&&n.size>0||(n.set(o,a),r+=c)}return new Map(Array.from(n.entries()).reverse())};function Su(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:jc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function rw(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 iw(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 ow=i.memo(({entry:t,mode:e="history",laned:n,totalLanes:r,isExpanded:o,onToggle:a,files:c,isLoadingFiles:l,onCopyHash:d,directory:f,onConflict:m,onActionSuccess:u})=>{const{t:p}=bt(),x=Ee(U=>U.timeFormatPreference),y=e==="graph",[b,g]=i.useState(null),[h,C]=i.useState(!1),[w,S]=i.useState(""),[N,k]=i.useState(null),[j,D]=i.useState(new Set),[O,v]=i.useState(new Map),[M,I]=i.useState(new Set),E=async()=>{if(f){g("checkout");try{await ig(f,t.hash),ce.success(p("gitView.history.actions.detachedHead")),u?.()}catch(U){ce.error(String(U.message))}finally{g(null)}}},B=async()=>{if(!(!f||!w.trim())){g("createBranch");try{await Zp(f,w.trim(),t.hash),C(!1),S(""),u?.()}catch(U){ce.error(String(U.message))}finally{g(null)}}},P=async()=>{if(f){g("cherryPick");try{const U=await rg(f,t.hash);U.conflict?m?.({conflict:!0,conflictFiles:U.conflictFiles,operation:"cherry-pick"}):u?.()}catch(U){ce.error(String(U.message))}finally{g(null)}}},W=async()=>{if(f){g("revert");try{const U=await ng(f,t.hash);U.conflict?m?.({conflict:!0,conflictFiles:U.conflictFiles,operation:"revert"}):u?.()}catch(U){ce.error(String(U.message))}finally{g(null)}}},_=async(U,ee=!1)=>{if(!(!f||b!==null)){g("reset");try{await eg(f,t.hash,U,ee),u?.()}catch(ae){ce.error(String(ae.message))}finally{g(null)}}},V=async()=>{if(!N)return;const U=N;switch(k(null),U){case"checkout":return E();case"cherryPick":return P();case"revert":return W();case"merge":return R();case"rebase":return ne();case"resetSoft":return _("soft");case"resetMixed":return _("mixed");case"resetHard":return _("hard",!0)}},R=async()=>{if(f){g("merge");try{const U=await sg(f,{branch:t.hash});U.conflict?m?.({conflict:!0,conflictFiles:U.conflictFiles,operation:"merge"}):u?.()}catch(U){ce.error(String(U.message))}finally{g(null)}}},ne=async()=>{if(f){g("rebase");try{const U=await tg(f,{onto:t.hash});U.conflict?m?.({conflict:!0,conflictFiles:U.conflictFiles,operation:"rebase"}):u?.()}catch(U){ce.error(String(U.message))}finally{g(null)}}},ie=i.useCallback(async U=>{const ee=U.path;if(!f){v(ae=>new Map(ae).set(ee,"error"));return}v(ae=>vu(new Map(ae).set(ee,"loading")));try{const ae=Xp(f,t.hash,U.path,!1),de=new Promise((se,we)=>{setTimeout(()=>we(new Error(`Timed out after ${gu}ms`)),gu)}),ye=await Promise.race([ae,de]);v(se=>vu(new Map(se).set(ee,ye)))}catch{v(ae=>new Map(ae).set(ee,"error"))}},[f,t.hash]),J=i.useCallback(async U=>{const ee=U.path;if(U.changeType==="R"||U.isBinary){D(se=>{const we=new Set(se);return we.has(ee)?we.delete(ee):we.add(ee),we});return}const ae=O.get(ee);if(j.has(ee)&&ae&&ae!=="error"){D(se=>{const we=new Set(se);return we.delete(ee),we});return}D(se=>{const we=new Set(se);return we.add(ee),we}),!(ae&&ae!=="error"||U.insertions+U.deletions>xu&&!M.has(ee))&&await ie(U)},[O,M,ie,j]);return s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:a,className:Ie("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",y?"hover:bg-[var(--interactive-hover)]/40":o?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[y&&n&&r!==void 0?s.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:s.jsx(tw,{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:[y?(()=>{const U=iw(t.refs);return U.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:U.map(ee=>s.jsx("span",{className:Ie("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",ee.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":ee.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:ee.label},ee.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:Su(t.date,x),children:Su(t.date,x)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:U=>{U.stopPropagation(),d(t.hash)},children:s.jsx(A,{name:"file-copy",className:"size-3"})})}),s.jsx(At,{sideOffset:8,children:p("gitView.history.copySha")})]})]})]})]}),o&&s.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[y&&N?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:p(`gitView.history.actions.${N}Confirm`)}),s.jsxs(ze,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:b!==null,onClick:U=>{U.stopPropagation(),V()},children:[b!==null?s.jsx(A,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.confirmButton")]}),s.jsx(ze,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:b!==null,onClick:U=>{U.stopPropagation(),k(null)},children:p("gitView.history.actions.cancelButton")})]}):y?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:b!==null,onClick:U=>{U.stopPropagation(),k("checkout")},children:p("gitView.history.actions.checkout")}),h?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("input",{autoFocus:!0,value:w,onChange:U=>S(U.target.value),onKeyDown:U=>{U.key==="Enter"&&B(),U.key==="Escape"&&(C(!1),S(""))},placeholder:p("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:!w.trim()||b!==null,onClick:U=>{U.stopPropagation(),B()},children:[b==="createBranch"?s.jsx(A,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.createBranchConfirm")]})]}):s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",onClick:U=>{U.stopPropagation(),C(!0)},children:p("gitView.history.actions.createBranch")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:U=>{U.stopPropagation(),k("cherryPick")},children:p("gitView.history.actions.cherryPick")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:U=>{U.stopPropagation(),k("revert")},children:p("gitView.history.actions.revert")}),s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:U=>U.stopPropagation(),children:[b==="reset"?s.jsx(A,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.reset")]})}),s.jsx(en,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(U=>s.jsx(xs,{disabled:b!==null,onSelect:ee=>{ee.stopPropagation(),k(`reset${U.charAt(0).toUpperCase()+U.slice(1)}`)},children:p(`gitView.history.actions.reset${U.charAt(0).toUpperCase()+U.slice(1)}`)},U))})]}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:U=>{U.stopPropagation(),k("merge")},children:p("gitView.history.actions.merge")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:U=>{U.stopPropagation(),k("rebase")},children:p("gitView.history.actions.rebase")})]}):null,l?s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:p("gitView.history.loadingFiles")})]}):c.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:p("gitView.history.noFiles")}):s.jsx("ul",{className:"space-y-0.5 py-2",children:c.map(U=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>J(U),className:Ie("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",j.has(U.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:Ie("font-semibold w-3 text-center shrink-0",rw(U.changeType)),children:U.changeType}),s.jsx("span",{className:"truncate text-foreground min-w-0",title:U.path,children:U.path}),!U.isBinary&&s.jsxs("span",{className:"shrink-0",children:[s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",U.insertions]}),s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",U.deletions]})]}),U.isBinary&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:p("gitView.history.binary")}),s.jsx(A,{name:j.has(U.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),j.has(U.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:U.changeType==="R"?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.renamedNoDiff")}):U.isBinary?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.binaryNoDiff")}):(()=>{const ee=U.insertions+U.deletions;if(!M.has(U.path)&&ee>xu)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:p("gitView.history.largeDiffTitle",{count:ee})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:p("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:()=>{I(de=>new Set(de).add(U.path)),ie(U)},children:p("gitView.history.renderDiffAnyway")})]});const ae=O.get(U.path);return ae==="loading"||ae===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.loadingDiff")}):ae==="error"?s.jsx("button",{type:"button",onClick:()=>J(U),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:p("gitView.history.diffError")}):s.jsx(Nm,{original:ae.original,modified:ae.modified,language:Ii(U.path)||"",fileName:U.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},U.path))})]})]})}),ju=["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 Yo(t){return ju[t%ju.length]}function aw(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let x=0;x<e.length;x++)e[x]===o.hash&&a.push(x);let c=a.length>0?a[0]:-1;if(c===-1){const x=e.indexOf(null);x!==-1?c=x:(c=e.length,e.push(null))}const l=a.slice(1),d=Yo(c),f=e[c]===o.hash,m=o.parents.length>0;m?e[c]=o.parents[0]:e[c]=null;const u=[];for(let x=1;x<o.parents.length;x++){const y=o.parents[x],b=e.indexOf(y);if(b!==-1)u.push(b);else{const g=e.indexOf(null),h=g!==-1?g:e.length;e[h]=y,h===e.length&&e.push(y),u.push(h)}}const p=[];f&&m?p.push({fromLane:c,toLane:c,color:d,type:"commit-lane"}):f&&!m?p.push({fromLane:c,toLane:c,color:d,type:"top-stub"}):!f&&m&&p.push({fromLane:c,toLane:c,color:d,type:"bottom-stub"});for(const x of l)p.push({fromLane:x,toLane:c,color:Yo(x),type:"merge-in"}),e[x]=null;for(const x of u)p.push({fromLane:c,toLane:x,color:Yo(x),type:"branch-out"});for(let x=0;x<e.length;x++)e[x]!==null&&x!==c&&(u.includes(x)||p.push({fromLane:x,toLane:x,color:Yo(x),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:p})}return n}const lw=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],cw=t=>{const e=mt.c(84),{mode:n,log:r,isLogLoading:o,logMaxCount:a,onLogMaxCountChange:c,expandedCommitHashes:l,onToggleCommit:d,commitFilesMap:f,loadingCommitHashes:m,onCopyHash:u,directory:p,showHeader:x,contentMaxHeightClassName:y,branchDivider:b,onConflict:g,onActionSuccess:h}=t,C=n===void 0?"history":n,w=x===void 0?!0:x,S=y===void 0?"max-h-[50vh]":y,N=b===void 0?null:b,{t:k}=bt(),[j,D]=i.useState(!0),O=C==="graph";let v;e[0]!==O||e[1]!==r?(v=O&&r?aw(r.all):[],e[0]=O,e[1]=r,e[2]=v):v=e[2];const M=v;let I;e[3]!==M?(I=Math.max(1,...M.map(dw)),e[3]=M,e[4]=I):I=e[4];const E=I;let B;e[5]!==M?(B=new Map(M.map(uw)),e[5]=M,e[6]=B):B=e[6];const P=B;if(!r)return null;const W=N!==null&&N.insertBeforeIndex>0&&N.insertBeforeIndex<r.all.length,_=N!==null&&N.insertBeforeIndex===r.all.length,V=W||_;let R;e[7]!==N||e[8]!==W||e[9]!==_||e[10]!==r.all?(R=W?r.all.slice(0,N.insertBeforeIndex):_?r.all:[],e[7]=N,e[8]=W,e[9]=_,e[10]=r.all,e[11]=R):R=e[11];const ne=R;let ie;if(e[12]!==N||e[13]!==f||e[14]!==S||e[15]!==p||e[16]!==l||e[17]!==W||e[18]!==V||e[19]!==O||e[20]!==o||e[21]!==P||e[22]!==m||e[23]!==r.all||e[24]!==a||e[25]!==E||e[26]!==C||e[27]!==h||e[28]!==g||e[29]!==u||e[30]!==c||e[31]!==d||e[32]!==k||e[33]!==ne){const Me=W?r.all.slice(N.insertBeforeIndex):[];let $;e[35]!==N?.direction?($=N?.direction==="down"?s.jsx(A,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(A,{name:"arrow-up",className:"size-3.5"}),e[35]=N?.direction,e[36]=$):$=e[36];const K=$;let q;e[37]!==f||e[38]!==p||e[39]!==l||e[40]!==O||e[41]!==P||e[42]!==m||e[43]!==E||e[44]!==C||e[45]!==h||e[46]!==g||e[47]!==u||e[48]!==d?(q=Be=>s.jsx("ul",{className:"divide-y divide-border/60",children:Be.map(Fe=>s.jsx(ow,{entry:Fe,mode:C,laned:O?P.get(Fe.hash):void 0,totalLanes:O?E:void 0,isExpanded:l.has(Fe.hash),onToggle:()=>d(Fe.hash),files:f.get(Fe.hash)??[],isLoadingFiles:m.has(Fe.hash),onCopyHash:u,directory:p,onConflict:g,onActionSuccess:h},Fe.hash))}),e[37]=f,e[38]=p,e[39]=l,e[40]=O,e[41]=P,e[42]=m,e[43]=E,e[44]=C,e[45]=h,e[46]=g,e[47]=u,e[48]=d,e[49]=q):q=e[49];const me=q;let je;e[50]!==o||e[51]!==r.all.length||e[52]!==a||e[53]!==c||e[54]!==k?(je=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(A,{name:"loader-4",className:"size-3 animate-spin"}),k("gitView.history.loadingMore")]}):k("gitView.history.loadMore")})}):null,e[50]=o,e[51]=r.all.length,e[52]=a,e[53]=c,e[54]=k,e[55]=je):je=e[55];const Oe=je;ie=s.jsx(En,{outerClassName:`min-h-0 ${S}`,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:k("gitView.history.noCommits")})}):V&&N?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col gap-0",children:[ne.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:me(ne)}):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:N.branchName,children:N.branchName}),K]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),Me.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:me(Me)}):null]}),Oe]}):s.jsxs(s.Fragment,{children:[me(r.all),Oe]})}),e[12]=N,e[13]=f,e[14]=S,e[15]=p,e[16]=l,e[17]=W,e[18]=V,e[19]=O,e[20]=o,e[21]=P,e[22]=m,e[23]=r.all,e[24]=a,e[25]=E,e[26]=C,e[27]=h,e[28]=g,e[29]=u,e[30]=c,e[31]=d,e[32]=k,e[33]=ne,e[34]=ie}else ie=e[34];const J=ie;if(!w){if(V){let $;return e[56]!==J?($=s.jsx("section",{className:"h-full min-h-0",children:J}),e[56]=J,e[57]=$):$=e[57],$}let Me;return e[58]!==J?(Me=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:J}),e[58]=J,e[59]=Me):Me=e[59],Me}let U;e[60]!==k?(U=k("gitView.history.title"),e[60]=k,e[61]=U):U=e[61];let ee;e[62]!==U?(ee=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:U}),e[62]=U,e[63]=ee):ee=e[63];let ae;e[64]!==o||e[65]!==j||e[66]!==a||e[67]!==c||e[68]!==k?(ae=j&&s.jsx("div",{onClick:fw,onPointerDown:mw,children:s.jsxs(Un,{value:String(a),onValueChange:Me=>c(Number(Me)),disabled:o,children:[s.jsx(Hn,{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(Cn,{placeholder:k("gitView.history.commitsPlaceholder")})}),s.jsx(Gn,{children:lw.map(Me=>s.jsx(Rs,{value:String(Me.value),children:k(Me.labelKey)},Me.value))})]})}),e[64]=o,e[65]=j,e[66]=a,e[67]=c,e[68]=k,e[69]=ae):ae=e[69];let de;e[70]!==j?(de=j?s.jsx(A,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(A,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=j,e[71]=de):de=e[71];let ye;e[72]!==ae||e[73]!==de?(ye=s.jsxs("div",{className:"flex items-center gap-2",children:[ae,de]}),e[72]=ae,e[73]=de,e[74]=ye):ye=e[74];let se;e[75]!==ee||e[76]!==ye?(se=s.jsxs(Vo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[ee,ye]}),e[75]=ee,e[76]=ye,e[77]=se):se=e[77];let we;e[78]!==J?(we=s.jsx(no,{children:J}),e[78]=J,e[79]=we):we=e[79];let fe;return e[80]!==j||e[81]!==se||e[82]!==we?(fe=s.jsxs(so,{open:j,onOpenChange:D,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[se,we]}),e[80]=j,e[81]=se,e[82]=we,e[83]=fe):fe=e[83],fe};function dw(t){return t.lane+1}function uw(t){return[t.commit.hash,t]}function fw(t){return t.stopPropagation()}function mw(t){return t.stopPropagation()}const $m=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},hw=9e4,pw=15e3,gw=5*6e4,xw=[2e3,5e3],bw=6e4,yw=2*6e4,ww=5*6e4,vw=4,Sw=720*6e4,jw="openchamber.github-pr-status",Nw=t=>t==="closed"||t==="merged",kw=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},Co=(t,e,n)=>`${t}::${e}`,Qo=new Map,Jo=new Map,xo=new Set,Nu=new Map,Cw=2;let Ia=0;const zm=[],Aw=()=>Ia<Cw?(Ia+=1,Promise.resolve()):new Promise(t=>{zm.push(t)}),Dw=()=>{const t=zm.shift();if(t){t();return}Ia=Math.max(0,Ia-1)},wo=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null}),Ra=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,_c=t=>{const e=Ra(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},Wm=(t,e)=>Object.entries(t).filter(([,n])=>_c(n)===e).map(([n])=>n),Tw=(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}}},Xo=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},Pw=(t,e,n)=>{const r=Wm(t,e),o=r.map(d=>Xo(t[d])).filter(d=>!!d);if(o.length===0)return null;const a=Xo(t[n]);if(a&&_c(t[n])===e)return a;const c=r.map(d=>t[d]).find(d=>!!(d?.resolvedRemoteName&&Xo(d)));if(c)return Xo(c);const l=o.find(d=>!!d.remoteName);return l||(o[0]??null)},Iw=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:Ra(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Rw=t=>({...wo(),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}),sr=oo()(dc((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,ensureEntry:n=>{t(r=>r.entries[n]?r:{entries:{...r.entries,[n]:wo()}})},setParams:(n,r)=>{t(o=>{const a=o.entries[n]??wo();return{entries:{...o.entries,[n]:Tw(a,r)}}})},startWatching:n=>{if(t(a=>{const c=a.entries[n]??wo();return{entries:{...a.entries,[n]:{...c,watchers:c.watchers+1}}}}),Qo.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=Jo.get(n)??[];l.push(c),Jo.set(n,l)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),xw.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 f=Date.now();if(f-a.lastDiscoveryPollAt<gw)return;t(m=>{const u=m.entries[n];return u?{entries:{...m.entries,[n]:{...u,lastDiscoveryPollAt:f}}}:m}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(Nw(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=kw(a.status)?bw:a.status?.checks&&a.status.checks.state!=="pending"?ww:yw;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},pw);Qo.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=Qo.get(n);typeof o=="number"&&window.clearInterval(o),Qo.delete(n);const a=Jo.get(n);a&&a.length>0&&a.forEach(c=>{window.clearTimeout(c)}),Jo.delete(n)},refresh:async(n,r)=>{const o=e(),a=o.entries[n],c=_c(a);if(!a||!c)return;const l=Wm(o.entries,c),d=l.some(u=>!!o.entries[u]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const f=Nu.get(c)??0;if(!r?.force&&Date.now()-f<hw||xo.has(c))return;const m=Pw(o.entries,c,n);if(m){if(xo.add(c),Nu.set(c,Date.now()),t(u=>{const p={...u.entries};return l.forEach(x=>{const y=p[x];y&&(p[x]={...y,lastRefreshAt:Date.now(),isLoading:r?.silent?y.isLoading:!0,error:null})}),{entries:p}}),m.githubAuthChecked&&m.githubConnected===!1){t(u=>{const p={...u.entries};return l.forEach(x=>{const y=p[x];y&&(p[x]={...y,status:{connected:!1},error:null,isLoading:r?.silent?y.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?y.isInitialStatusResolved:!0})}),{entries:p}}),xo.delete(c);return}if(!m.github?.prStatus){t(u=>{const p={...u.entries};return l.forEach(x=>{const y=p[x];y&&(p[x]={...y,status:null,error:"GitHub runtime API unavailable",isLoading:r?.silent?y.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?y.isInitialStatusResolved:!0})}),{entries:p}}),xo.delete(c);return}try{t(p=>({...p,activeRequestCount:p.activeRequestCount+1,totalRequestCount:p.totalRequestCount+1})),await Aw();let u;try{u=await m.github.prStatus(m.directory,m.branch,m.remoteName??void 0,{force:r?.force})}finally{Dw()}t(p=>{const x={...p.entries};return l.forEach(y=>{const b=x[y];if(!b)return;const g=b.status?.pr,h=u.pr,w=!!(h&&g&&h.number===g.number&&(!h.body||!h.body.trim())&&typeof g.body=="string"&&g.body.trim().length>0)&&h&&g?.body?{...u,pr:{...h,body:g.body}}:u,S=w.resolvedRemoteName??b.resolvedRemoteName??m.remoteName??null,N=Ra(b)??{directory:m.directory,branch:m.branch,remoteName:m.remoteName??null};x[y]={...b,status:w,error:null,isLoading:r?.silent?b.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?b.isInitialStatusResolved:!0,resolvedRemoteName:S,identity:{...N,remoteName:S??N.remoteName??null}}}),{entries:x}})}catch(u){const p=u instanceof Error?u.message:String(u);t(x=>{const y={...x.entries};return l.forEach(b=>{const g=y[b];g&&(y[b]={...g,error:p||"Failed to load PR status",isLoading:r?.silent?g.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?g.isInitialStatusResolved:!0})}),{entries:y}})}finally{xo.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:Co(c,l,a.remoteName??null)}).filter(a=>!!a)));await $m(o,vw,a=>e().refresh(a,r))},updateStatus:(n,r)=>{t(o=>{const a=o.entries[n]??wo();return{entries:{...o.entries,[n]:{...a,status:r(a.status)}}}})}}),{name:jw,storage:xp(),partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=Ra(e);if(!n?.directory||!n.branch)return!1;const r=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return r===0||Date.now()-r<Sw}).map(([e,n])=>[e,Iw(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).map(([o,a])=>[o,Rw(a)]))}}})),Ew=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"},Mw=t=>{const e=Ew(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}},Fw=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 wl=new Map,ku=new Map;const Ow=t=>{const e=mt.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=Mw(l);if(!d)continue;const f=Fw(d);o.set(c,f),a.set(c,d)}if(o.size===wl.size){let c=!0;for(const[l,d]of o)if(wl.get(l)!==d){c=!1;break}if(c)return ku}return wl=o,ku=a,a},e[0]=t,e[1]=n):n=e[1],sr(n)},Lw=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"}},Bw=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"},Vw=[2e3,5e3],Cu=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),oi=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):""},_w=(t,e)=>{const n=oi(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},$w=(t,e)=>`${t}::${e}`,$c=t=>{const e=String(t||"").trim();if(!e)return"";const n=e.indexOf("/");return n<=0?"":e.slice(0,n).trim()},vl=(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=$c(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)},zw=t=>t.startsWith("pr-"),Ww=(t,e)=>{const n=$c(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=>!zw(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},Sl=new Map,jl=qr;function Uw(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 f=await e.repoBranches(d.upstream.owner,d.upstream.repo);l||a(f)}catch{}}catch{}})(),()=>{l=!0}},[t,e]),{detectedUpstream:n,upstreamBranches:o}}const Hw=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=bt(),d=Ee(be=>be.timeFormatPreference),{github:f}=Xn(),m=Mi(be=>be.status),u=Mi(be=>be.hasChecked),p=Ee(be=>be.setSettingsDialogOpen),x=Ee(be=>be.setSettingsPage),y=Ee(be=>be.setActiveMainTab),b=ft(be=>be.currentSessionId),{isMobile:g,hasTouchInput:h}=Or(),C=i.useCallback(()=>{x("github"),p(!0)},[p,x]),w=i.useMemo(()=>$w(t,e),[t,e]),S=i.useMemo(()=>Sl.get(w)??null,[w]),N=sr(be=>be.ensureEntry),k=sr(be=>be.setParams),j=sr(be=>be.startWatching),D=sr(be=>be.stopWatching),O=sr(be=>be.refresh),v=sr(be=>be.updateStatus),[M,I]=i.useState(()=>S?.title??Cu(e)),[E,B]=i.useState(()=>S?.body??""),[P,W]=i.useState(()=>S?.draft??!1),[_,V]=i.useState(()=>S?.additionalContext??""),[R,ne]=i.useState(()=>{const be=typeof S?.targetBaseBranch=="string"?oi(S.targetBaseBranch):"";return be||oi(n)}),[ie,J]=i.useState("squash"),[U,ee]=i.useState(!1),[ae,de]=i.useState(!1),[ye,se]=i.useState(!1),[we,fe]=i.useState(!1),[Me,$]=i.useState(!1),[K,q]=i.useState(!1),[me,je]=i.useState(null),[Oe,Be]=i.useState(""),[Fe,ue]=i.useState(""),[Re,xe]=i.useState(!1),[oe,ve]=i.useState(!1),[Se,le]=i.useState(()=>vl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r})),[T,L]=i.useState(!1),{detectedUpstream:he,upstreamBranches:ge}=Uw(t,f);i.useEffect(()=>{L(!1)},[t]);const z=o.some(be=>be.name==="upstream"),Ae=!!(t&&e&&n&&(e!==n||(z||he!==null))),G=i.useMemo(()=>Co(t,e),[t,e]),ke=sr(be=>be.entries[G]),Le=ke?.isLoading??!1,Te=ke?.status??null,Z=ke?.error??null,F=ke?.isInitialStatusResolved??!1,re=i.useMemo(()=>{const be=T?null:Se?.name?.trim()||null,Ze=new Set;for(const Vt of a){const ht=_w(Vt,be);!ht||ht==="HEAD"||Ze.add(ht)}if(T)for(const Vt of ge)Vt&&Vt!=="HEAD"&&Ze.add(Vt);const dt=oi(n);dt&&dt!=="HEAD"&&Ze.add(dt);const wt=oi(R);return wt&&wt!=="HEAD"&&Ze.add(wt),Array.from(Ze).sort((Vt,ht)=>Vt.localeCompare(ht))},[n,a,Se?.name,R,ge,T]);i.useEffect(()=>{if(o.length===0){Se&&le(null);return}(!Se||!o.some(be=>be.name===Se.name))&&le(vl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r}))},[S?.selectedRemoteName,o,Se,r]),i.useEffect(()=>{const be=oi(n);if(!R&&be){ne(be);return}if(re.length!==0&&!re.includes(R)){const Ze=re.includes(be)?be:re[0];Ze&&ne(Ze)}},[re,n,R]);const[te,Ve]=i.useState(!1),[Ye,Ke]=i.useState(null),[Je,nt]=i.useState(!1),[xt,jt]=i.useState(new Set),[Mt,Et]=i.useState(!1),[Ut,zt]=i.useState(null),[Ht,_t]=i.useState(!1),Gt=i.useRef(new Set),Ce=i.useRef(null),Qe=i.useRef(!1),et=i.useRef(new Set),yt=i.useRef([]);i.useEffect(()=>{he&&!z&&L(!0)},[he,z]),i.useEffect(()=>{T&&he?.defaultBranch&&ne(he.defaultBranch)},[T,he?.defaultBranch]);const We=Te?.pr??null,at=We?`${t}#${We.number}`:null,qe=!!(at&&me===at);i.useEffect(()=>{if(!f?.prContext||!We||typeof We.body=="string"&&We.body.length>0)return;const be=`${t}#${We.number}`;if(Gt.current.has(be))return;Gt.current.add(be),je(be);let Ze=!1;return f.prContext(t,We.number,{includeDiff:!1,includeCheckDetails:!1}).then(dt=>{if(Ze)return;const wt=dt?.pr;wt&&v(G,Vt=>!Vt?.pr||Vt.pr.number!==We.number?Vt:{...Vt,pr:{...Vt.pr,body:wt.body||""}})}).catch(()=>{}).finally(()=>{Ze||je(dt=>dt===be?null:dt)}),()=>{Ze=!0}},[t,f,We,G,v]),i.useEffect(()=>{if(!We){q(!1),Be(""),ue(""),Ce.current=null;return}const be=Ce.current!==null&&Ce.current!==We.number;be&&q(!1),(!K||be)&&(Be(We.title||""),ue(We.body||"")),Ce.current=We.number},[K,We]);const lt=i.useCallback(async()=>{if(!f?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(We){Ve(!0),jt(new Set),nt(!0);try{const be=await f.prContext(t,We.number,{includeDiff:!1,includeCheckDetails:!0});Ke(be)}catch(be){const Ze=be instanceof Error?be.message:String(be);ce.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:Ze})}finally{nt(!1)}}},[t,f,We,l]),Dt=i.useCallback(async()=>{if(!f?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(We){Et(!0),_t(!0);try{const be=await f.prContext(t,We.number,{includeDiff:!1,includeCheckDetails:!1});zt(be)}catch(be){const Ze=be instanceof Error?be.message:String(be);ce.error(l("gitView.pr.toast.loadCommentsFailed"),{description:Ze})}finally{_t(!1)}}},[t,f,We,l]),us=i.useCallback(be=>{if(!be)return"";const Ze=Date.parse(be);return Number.isFinite(Ze)?jc(Ze,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):be},[d]),Lt=i.useMemo(()=>{const be=m?.user?.login;return typeof be=="string"?be.trim():""},[m]),es=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)]",[]),os=i.useCallback(be=>{const Ze=Lt.toLowerCase(),dt=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return be.replace(dt,(wt,Vt,ht)=>{const cs=`@${ht}`,ds=ht.toLowerCase();return`${Vt}[${cs}](https://github.com/${ds}${Ze&&ds===Ze?"?oc-self-mention=1":""})`})},[Lt]),Qt=i.useMemo(()=>{const be=(Ut?.issueComments??[]).map(wt=>({id:`issue-${wt.id}`,body:wt.body||"",authorName:wt.author?.name||wt.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:wt.author?.login||null,avatarUrl:wt.author?.avatarUrl||null,createdAt:wt.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),Ze=(Ut?.reviewComments??[]).map(wt=>({id:`review-${wt.id}`,body:wt.body||"",authorName:wt.author?.name||wt.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:wt.author?.login||null,avatarUrl:wt.author?.avatarUrl||null,createdAt:wt.createdAt,context:l("gitView.pr.comments.reviewContext"),path:wt.path||null,line:wt.line??null})),dt=[...be,...Ze];return dt.sort((wt,Vt)=>{const ht=wt.createdAt?Date.parse(wt.createdAt):0,cs=Vt.createdAt?Date.parse(Vt.createdAt):0,ds=Number.isFinite(ht)?ht:0,Ss=Number.isFinite(cs)?cs:0;return ds-Ss}),dt},[Ut,l]),Ft=i.useCallback(()=>{if(!b)return ce.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:be,currentModelId:Ze,currentAgentName:dt,currentVariant:wt}=ss.getState(),Vt=Sc.getState().lastUsedProvider,ht=be||Vt?.providerID,cs=Ze||Vt?.modelID;return!ht||!cs?(ce.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:b,providerID:ht,modelID:cs,currentAgentName:dt??null,currentVariant:wt??null}},[b,l]),Xt=i.useCallback((be,Ze,dt,wt)=>{ft.getState().sendMessage(Ze,be.providerID,be.modelID,be.currentAgentName??void 0,void 0,void 0,[{text:dt,synthetic:!0},{text:wt,synthetic:!0}],be.currentVariant??void 0).catch(Vt=>{const ht=Vt instanceof Error?Vt.message:String(Vt);ce.error(l("gitView.pr.toast.sendMessageFailed"),{description:ht})})},[l]),as=i.useCallback(be=>{const Ze=be.status||"unknown",dt=be.conclusion??void 0,wt=dt?`${Ze} / ${dt}`:Ze,Vt=be.app?.name||be.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:be.name}),s.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:Vt?`${Vt} · ${wt}`:wt})]}),be.detailsUrl?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:be.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(A,{name:"external-link",className:"size-4"}),"Open"]})}):null]}),be.output?.title?s.jsx("div",{className:"typography-micro text-foreground",children:be.output.title}):null,be.output?.summary?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:be.output.summary}):null,be.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:be.output.text}):null,Array.isArray(be.annotations)&&be.annotations.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",be.annotations.length>20?` (showing 20/${be.annotations.length})`:""]}),s.jsx("div",{className:"space-y-1",children:be.annotations.slice(0,20).map((ht,cs)=>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:[ht.title||ht.level||"Issue",ht.path?` · ${ht.path}`:"",typeof ht.startLine=="number"?`:${ht.startLine}`:"",typeof ht.endLine=="number"&&ht.endLine!==ht.startLine?`-${ht.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:ht.message}),ht.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:ht.rawDetails}):null]},`${ht.path||"file"}:${ht.startLine||cs}:${cs}`))})]}):null,be.job?.steps&&be.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:be.job.steps.map((ht,cs)=>{const ds=(ht.conclusion||"").toLowerCase(),Ss=ds&&!["success","neutral","skipped"].includes(ds),gs=`${be.id??"run"}:${be.job?.jobId??"job"}:${ht.number??cs}:${ht.name}`,Ts=xt.has(gs);return Ss?s.jsxs(so,{open:Ts,children:[s.jsxs("button",{type:"button",onClick:()=>{jt(Fn=>{const _s=new Set(Fn);return _s.has(gs)?_s.delete(gs):_s.add(gs),_s})},className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-left "+(Ss?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[Ts?s.jsx(A,{name:"arrow-down-s",className:"size-4"}):s.jsx(A,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:ht.name}),ht.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:ht.conclusion}):null]}),s.jsx(no,{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 ht.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",ht.number]}):null,ht.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",ht.status]}):null,ht.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",ht.conclusion]}):null,ht.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",us(ht.startedAt)]}):null,ht.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",us(ht.completedAt)]}):null]})})]},gs):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:ht.name}),ht.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:ht.conclusion}):null]},gs)})})]}):null]})},[xt,us,l]),$t=i.useCallback(async()=>{if(y("chat"),!f?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!We)return;const be=Ft();if(be)try{const Ze=await f.prContext(t,We.number,{includeDiff:!1,includeCheckDetails:!0}),wt=(Ze.checkRuns??[]).filter(Ss=>{const gs=typeof Ss.conclusion=="string"?Ss.conclusion.toLowerCase():"";return gs?!["success","neutral","skipped"].includes(gs):!1});if(wt.length===0){ce.message(l("gitView.pr.toast.noFailedChecks"));return}const Vt=await Rn("github.pr.checks.review.visible"),ht=await Rn("github.pr.checks.review.instructions"),cs=wt.flatMap(Ss=>(Array.isArray(Ss.annotations)?Ss.annotations:[]).map(Ts=>({run:Ss.name,level:Ts.level,title:Ts.title,path:Ts.path,startLine:Ts.startLine,endLine:Ts.endLine,message:Ts.message,rawDetails:Ts.rawDetails}))),ds=`GitHub PR failed checks (JSON)
7
- ${JSON.stringify({repo:Ze.repo??null,pr:Ze.pr??null,failedChecks:wt,failedAnnotations:cs},null,2)}`;Xt(be,Vt,ht,ds)}catch(Ze){const dt=Ze instanceof Error?Ze.message:String(Ze);ce.error(l("gitView.pr.toast.loadChecksFailed"),{description:dt})}},[t,Xt,f,We,Ft,y,l]),bs=i.useCallback(async()=>{if(y("chat"),!f?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!We)return;const be=Ft();if(be)try{const Ze=await f.prContext(t,We.number,{includeDiff:!1,includeCheckDetails:!1}),dt=Ze.issueComments??[],wt=Ze.reviewComments??[];if(dt.length+wt.length===0){ce.message(l("gitView.pr.toast.noPrComments"));return}const ht=await Rn("github.pr.comments.review.visible"),cs=await Rn("github.pr.comments.review.instructions"),ds=`GitHub PR comments (JSON)
8
- ${JSON.stringify({repo:Ze.repo??null,pr:Ze.pr??null,issueComments:dt,reviewComments:wt},null,2)}`;Xt(be,ht,cs,ds)}catch(Ze){const dt=Ze instanceof Error?Ze.message:String(Ze);ce.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:dt})}},[t,Xt,f,We,Ft,y,l]),Cs=i.useCallback(async be=>{Et(!1),y("chat");const Ze=Ft();if(!Ze)return;const dt=await Rn("github.pr.comment.single.visible"),wt=await Rn("github.pr.comment.single.instructions"),Vt=`GitHub PR comment (JSON)
9
- ${JSON.stringify({repo:Ut?.repo??null,pr:Ut?.pr??We??null,comment:be},null,2)}`;Xt(Ze,dt,wt,Vt)},[Ut,Xt,We,Ft,y]),Tt=i.useCallback(async be=>{await O(G,be)},[G,O]),Bt=i.useCallback(()=>{yt.current.forEach(be=>{window.clearTimeout(be)}),yt.current=Vw.map(be=>window.setTimeout(()=>{Tt({force:!0,silent:!0,markInitialResolved:!0})},be))},[Tt]);i.useEffect(()=>{if(!f?.prStatus||!Ae||o.length<=1||Qe.current||Te?.pr)return;const be=`${w}::${Se?.name??""}`;if(et.current.has(be))return;et.current.add(be);const Ze=Ww(o,r).filter(Vt=>Vt.name!==Se?.name);if(Ze.length===0)return;let dt=!1;return(async()=>{for(const Vt of Ze){if(dt)return;try{if(!(await f.prStatus(t,e,Vt.name))?.pr)continue;if(dt)return;le(cs=>cs?.name===Vt.name?cs:Vt);return}catch{}}})(),()=>{dt=!0}},[e,Ae,t,f,o,Se?.name,w,Te?.pr,r]),i.useEffect(()=>{N(G),k(G,{directory:t,branch:e,remoteName:Se?.name??null,canShow:Ae,github:f,githubAuthChecked:u,githubConnected:m?.connected??null})},[e,Ae,t,N,f,u,m?.connected,G,Se?.name,k]),i.useEffect(()=>(j(G),()=>{D(G)}),[G,j,D]),i.useEffect(()=>{const be=Sl.get(w)??null;I(be?.title??Cu(e)),B(be?.body??""),W(be?.draft??!1),ne(be?.targetBaseBranch?oi(be.targetBaseBranch):oi(n));const Ze=vl(o,{selectedRemoteName:be?.selectedRemoteName,trackingBranch:r});le(dt=>dt?.name===Ze?.name?dt:Ze)},[n,e,o,w,r]),i.useEffect(()=>{Tt({markInitialResolved:!0})},[G,Tt]),i.useEffect(()=>{!Ae||!Se?.name||Tt({force:!0,silent:!0,markInitialResolved:!0})},[Ae,Tt,Se?.name]),i.useEffect(()=>{const be=Te?.resolvedRemoteName?.trim();if(!be||Qe.current)return;const Ze=o.find(dt=>dt.name===be);Ze&&le(dt=>dt?.name===Ze.name?dt:Ze)},[o,Te?.resolvedRemoteName]),i.useEffect(()=>{const be=Te?.pr?.state==="closed"||Te?.pr?.state==="merged",Ze=ke?.lastRefreshAt??0,dt=Date.now()-Ze>6e4,wt=!be&&dt,Vt=()=>{wt&&Tt({force:!0,silent:!0})},ht=()=>{document.visibilityState==="visible"&&wt&&Tt({force:!0,silent:!0})};return window.addEventListener("focus",Vt),document.addEventListener("visibilitychange",ht),()=>{window.removeEventListener("focus",Vt),document.removeEventListener("visibilitychange",ht)}},[Tt,Te?.pr?.state,ke?.lastRefreshAt]),i.useEffect(()=>{u&&m?.connected===!1&&Tt({force:!0,silent:!0,markInitialResolved:!0})},[u,m,Tt]),i.useEffect(()=>{!t||!e||Sl.set(w,{title:M,body:E,draft:P,additionalContext:_,targetBaseBranch:R,selectedRemoteName:Se?.name})},[w,M,E,P,_,R,Se?.name,t,e]),i.useEffect(()=>{const be=yt.current;return()=>{be.forEach(Ze=>{window.clearTimeout(Ze)}),yt.current=[]}},[]);const vt=i.useCallback(async()=>{if(!U&&t){ee(!0);try{const Ze={base:T&&he?.defaultBranchSha?he.defaultBranchSha:R,head:e};_&&(Ze.context=_);const dt=await og(t,Ze);dt.title?.trim()&&I(dt.title.trim()),dt.body?.trim()&&B(dt.body.trim()),c?.()}catch(be){const Ze=be instanceof Error?be.message:String(be);ce.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:Ze})}finally{ee(!1)}}},[_,e,he?.defaultBranchSha,t,U,c,R,l,T]),vs=i.useCallback(async()=>{if(!f?.prCreate){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}const be=M.trim();if(!be){ce.error(l("gitView.pr.toast.titleRequired"));return}const Ze=R.trim();if(!Ze){ce.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!T&&Ze===e){ce.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}de(!0);try{const dt=$c(r),wt=T&&he,Vt=await f.prCreate({directory:t,title:be,head:e,base:Ze,...E.trim()?{body:E}:{},draft:P,...wt?{targetRepo:{owner:he.owner,repo:he.repo},headRemote:"origin"}:{...Se?{remote:Se.name}:{},...dt&&dt!==Se?.name?{headRemote:dt}:{}}});ce.success(l("gitView.pr.toast.prCreated")),v(G,ht=>ht&&{...ht,pr:Vt}),await Tt({force:!0}),Bt()}catch(dt){const wt=dt instanceof Error?dt.message:String(dt);ce.error(l("gitView.pr.toast.createPrFailed"),{description:wt})}finally{de(!1)}},[E,e,he,t,P,f,G,Tt,Bt,Se,R,M,r,v,T,l]),hs=i.useCallback(async be=>{if(!f?.prMerge){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}fe(!0);try{const Ze=await f.prMerge({directory:t,number:be.number,method:ie});Ze.merged?ce.success(l("gitView.pr.toast.prMerged")):ce.message(l("gitView.pr.toast.prNotMerged"),{description:Ze.message||l("gitView.pr.notMergeable")}),await Tt({force:!0}),Bt()}catch(Ze){const dt=Ze instanceof Error?Ze.message:String(Ze);ce.error(l("gitView.pr.toast.mergeFailed"),{description:dt}),be.url&&jl(be.url)}finally{fe(!1)}},[t,f,ie,Tt,Bt,l]),He=i.useCallback(async be=>{if(!f?.prReady){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}$(!0);try{await f.prReady({directory:t,number:be.number}),ce.success(l("gitView.pr.toast.markedReady")),await Tt({force:!0}),Bt()}catch(Ze){const dt=Ze instanceof Error?Ze.message:String(Ze);ce.error(l("gitView.pr.toast.markReadyFailed"),{description:dt}),be.url&&jl(be.url)}finally{$(!1)}},[t,f,Tt,Bt,l]),it=i.useCallback(async be=>{if(!f?.prUpdate){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}const Ze=Oe.trim();if(!Ze){ce.error(l("gitView.pr.toast.titleRequired"));return}se(!0);try{const dt=await f.prUpdate({directory:t,number:be.number,title:Ze,body:Fe});v(G,wt=>wt&&{...wt,pr:{...wt.pr??be,...dt}}),q(!1),ce.success(l("gitView.pr.toast.prUpdated")),await Tt({force:!0}),Bt()}catch(dt){const wt=dt instanceof Error?dt.message:String(dt);ce.error(l("gitView.pr.toast.updatePrFailed"),{description:wt})}finally{se(!1)}},[t,Fe,Oe,f,G,Tt,Bt,v,l]);if(!Ae)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 It=Te?.repo?.url||null,Rt=T&&he?.url?he.url:It,Pt=Te?.checks??null,ps=!!Te?.canMerge,ls=!!Te?.connected,ns=u&&Te?.connected===!1,Wt=Bw(Te),ln=Wt?`var(--pr-${Wt})`:"var(--status-info)",fs=Wt==="draft"?"git-pr-draft":Wt==="merged"?"git-merge":Wt==="closed"?"git-close-pull-request":"git-pull-request",Fs=We?[`${We.state}${We.draft?" (draft)":""}`,We.mergeable===!1?l("gitView.pr.notMergeable"):null,We.state==="open"&&typeof We.mergeableState=="string"&&We.mergeableState&&We.mergeableState!=="unknown"?We.mergeableState:null].filter(Boolean).join(" · "):"",Ws=Pt?Pt.total>0?`${Pt.success}/${Pt.total} ${l("gitView.pr.checks.label")}`:`${Pt.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:[We?s.jsxs(kt,{children:[s.jsx(Ct,{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:()=>{jl(We.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(A,{name:fs,className:"size-4 shrink-0",style:{color:ln}})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(A,{name:fs,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")}),We?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",We.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Le?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(kt,{children:[s.jsx(Ct,{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:Le,onClick:()=>{Tt({force:!0})},"aria-label":l("gitView.pr.actions.refreshAria"),children:s.jsx(A,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),We?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:ln},children:Fs}),Pt?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${Lw(Pt.state)}`}),Ws]}):null,r&&Se&&r.split("/")[0]!==Se.name?s.jsxs("span",{className:"min-w-0 truncate",children:[r.split("/")[0]," → ",Se.name]}):null]}):null]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[ns?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,Z?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:Z}),Rt?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:s.jsxs("a",{href:Rt,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(A,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!We&&!F&&!Z&&!ns?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):We?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:[K?s.jsxs("div",{className:"space-y-2",children:[s.jsx(Mn,{value:Oe,onChange:be=>Be(be.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h}),s.jsx(Ti,{value:Fe,onChange:be=>ue(be.target.value),className:"min-h-[120px] bg-background/80",placeholder:l("gitView.pr.placeholder.description"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"typography-markdown text-xl font-semibold text-foreground break-words leading-snug",children:We.title}),We.body?.trim()?s.jsx(to,{content:We.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(qe?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),ps&&We.draft?s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.draftMustBeReady")}):null,ps?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:[We.state==="open"?K?s.jsxs(s.Fragment,{children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{q(!1),Be(We.title||""),ue(We.body||"")},disabled:ye,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(A,{name:"close",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>it(We),disabled:ye||!Oe.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:ye?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"check",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>q(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(A,{name:"edit",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,Pt?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:lt,disabled:Je,"aria-label":l("gitView.pr.actions.openChecksAria"),children:Je?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"information",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,Pt?.failure?s.jsxs(kt,{children:[s.jsx(Ct,{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:$t,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(A,{name:"error-warning",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:Dt,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(A,{name:"chat-4",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(kt,{children:[s.jsx(Ct,{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:bs,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(A,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),ps&&We.draft&&We.state==="open"?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>He(We),disabled:Me||we||ye||K,"aria-label":l("gitView.pr.actions.markReadyAria"),children:Me?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.markReady")})})]}):null]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:ps?s.jsxs(s.Fragment,{children:[s.jsxs(Un,{value:ie,onValueChange:be=>J(be),disabled:we||We.state!=="open",children:[s.jsx(Hn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(Cn,{})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(Rs,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(Rs,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>hs(We),disabled:we||Me||We.state!=="open"||We.draft||ye||K,"aria-label":l("gitView.pr.actions.mergePrAria"),children:we?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"git-merge",className:"size-4"})})}),s.jsx(At,{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)"})," → ",R," ",s.jsxs("span",{className:"opacity-60",children:["(",T&&he?"upstream":"remote",")"]})]})]}),Rt?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:Rt,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(A,{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(Mn,{value:M,onChange:be=>I(be.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.baseBranch")}),re.length>0?s.jsxs(Un,{value:R,onValueChange:ne,children:[s.jsx(Hn,{className:"h-9",children:s.jsx(Cn,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(Gn,{children:re.map(be=>s.jsx(Rs,{value:be,children:be},be))})]}):s.jsx(Mn,{value:R,onChange:be=>ne(be.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(Ti,{value:E,onChange:be=>B(be.target.value),className:"min-h-[110px]",placeholder:l("gitView.pr.placeholder.whatChanged"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}),s.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":P,onClick:()=>W(be=>!be),onKeyDown:be=>{(be.key===" "||be.key==="Enter")&&(be.preventDefault(),W(Ze=>!Ze))},children:[s.jsx(Fi,{size:"sm",checked:P,onChange:be=>W(be),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),g?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:()=>ve(!0),children:_.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),_.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(so,{open:Re,onOpenChange:xe,children:[s.jsxs(Vo,{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:Re?l("gitView.pr.actions.hide"):_.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(no,{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(Ti,{value:_,onChange:be=>V(be.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(Ha,{open:oe,onClose:()=>ve(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx(ze,{size:"sm",onClick:()=>ve(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ti,{value:_,onChange:be=>V(be.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:vt,disabled:U||ae,children:[U?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{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:vs,disabled:ae||!ls||!R.trim()||!T&&R.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:ae?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx(Ms,{open:te,onOpenChange:Ve,children:s.jsxs(Es,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(Ys,{children:[s.jsxs(zs,{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(an,{children:We?l("gitView.pr.numberLabel",{number:We.number}):l("gitView.pullRequest.title")})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[Je?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Je?null:s.jsx("div",{className:"space-y-3",children:Array.isArray(Ye?.checkRuns)&&Ye?.checkRuns.length>0?Ye.checkRuns.map((be,Ze)=>{const dt=`${be.id??"run"}:${be.job?.jobId??"job"}:${be.name}:${Ze}`;return s.jsx("div",{className:"p-1",children:as(be)},dt)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx(Ms,{open:Mt,onOpenChange:Et,children:s.jsxs(Es,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(Ys,{children:s.jsxs(zs,{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),We?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:We.number})}):null]})}),s.jsxs(Ga,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[Ht?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Ht?null:s.jsx("div",{className:"space-y-4",children:Qt.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Qt.map((be,Ze)=>{const dt=(be.authorName||"?").charAt(0).toUpperCase(),wt=Ze===Qt.length-1;return s.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[wt?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:be.avatarUrl?s.jsx("img",{src:be.avatarUrl,alt:be.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:dt})}),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:[be.authorName,be.authorLogin&&be.authorLogin!==be.authorName?` · @${be.authorLogin}`:""]}),be.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:us(be.createdAt)}):null,s.jsxs(kt,{children:[s.jsx(Ct,{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:()=>{Cs(be)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(A,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(At,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[be.context,be.path?` · ${be.path}`:"",be.line?`:${be.line}`:""]}),s.jsx(to,{content:os(be.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",es].filter(Boolean).join(" "),enableFileReferences:!1})]})]},be.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},Gw=t=>{const e=mt.c(150),{open:n,onOpenChange:r,conflictFiles:o,directory:a,operation:c,onAbort:l,onClearState:d}=t;let f;e[0]!==o?(f=o===void 0?[]:o,e[0]=o,e[1]=f):f=e[1];const m=f,{t:u}=bt(),p=ft(Kw),x=ft(qw),y=mi(Yw),b=mi(Qw),g=Ee(Jw),[h,C]=i.useState(!1),[w,S]=i.useState(null),[N,k]=i.useState(null);let j,D;e[2]!==a||e[3]!==n||e[4]!==u?(j=()=>{!n||!a||(C(!0),k(null),S(null),ag(a).then(T=>{S(T)}).catch(T=>{const L=T instanceof Error?T.message:u("gitView.conflict.loadFailed");k(L)}).finally(()=>{C(!1)}))},D=[n,a,u],e[2]=a,e[3]=n,e[4]=u,e[5]=j,e[6]=D):(j=e[5],D=e[6]),i.useEffect(j,D);let O;e[7]!==w||e[8]!==a||e[9]!==c?(O=async()=>{if(!w)return null;const T=c==="merge"?"merge":"rebase",L=w.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),he=c==="merge"?"git commit --no-edit":"git rebase --continue",ge=await Rn("git.conflict.resolve.visible",{operation_label:T,head_ref:L}),z=await Rn("git.conflict.resolve.instructions",{operation_label:T,directory:a,operation:c,head_info:w.headInfo||"N/A",continue_cmd:he}),pe=`${T} conflict context (JSON)
10
- ${JSON.stringify({directory:a,operation:w.operation,headInfo:w.headInfo,statusPorcelain:w.statusPorcelain,unmergedFiles:w.unmergedFiles,diff:w.diff},null,2)}`;return{visibleText:ge,instructionsText:z,payloadText:pe}},e[7]=w,e[8]=a,e[9]=c,e[10]=O):O=e[10];const v=O;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 I=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 B=E;let P;e[17]!==v||e[18]!==x||e[19]!==d||e[20]!==r||e[21]!==g||e[22]!==y||e[23]!==b||e[24]!==u?(P=async()=>{const T=await v();if(!T){ce.error(u("gitView.conflict.noDetailsAvailable"));return}if(!x){ce.error(u("gitView.conflict.noActiveSession"),{description:u("gitView.conflict.noActiveSessionDescription")});return}y(T.visibleText,"replace"),b([{text:T.instructionsText,synthetic:!0},{text:T.payloadText,synthetic:!0}]),g("chat"),d?.(),r(!1)},e[17]=v,e[18]=x,e[19]=d,e[20]=r,e[21]=g,e[22]=y,e[23]=b,e[24]=u,e[25]=P):P=e[25];const W=P;let _;e[26]!==v||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==p||e[31]!==g||e[32]!==u?(_=async()=>{const T=await v();if(!T){ce.error(u("gitView.conflict.noDetailsAvailable"));return}p({directoryOverride:a,initialPrompt:T.visibleText,syntheticParts:[{text:T.instructionsText,synthetic:!0},{text:T.payloadText,synthetic:!0}]}),g("chat"),d?.(),r(!1)},e[26]=v,e[27]=a,e[28]=d,e[29]=r,e[30]=p,e[31]=g,e[32]=u,e[33]=_):_=e[33];const V=_;let R,ne,ie,J,U,ee,ae,de,ye,se,we,fe,Me,$,K,q,me,je,Oe,Be,Fe,ue;if(e[34]!==w||e[35]!==m||e[36]!==x||e[37]!==I||e[38]!==B||e[39]!==W||e[40]!==V||e[41]!==h||e[42]!==N||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==u){const T=u(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),L=w?.unmergedFiles||m;ie=Ms,Fe=n,ue=r,ne=Es,Be="max-w-md w-[calc(100vw-2rem)]",$="flex flex-col gap-4 overflow-hidden";let he;e[69]===Symbol.for("react.memo_cache_sentinel")?(he=s.jsx(A,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=he):he=e[69];const ge=s.jsxs("div",{className:"flex items-center gap-2",children:[he,s.jsx(zs,{children:u("gitView.conflict.detectedTitle",{operation:T})})]});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 pe;e[73]!==z?(pe=s.jsx(an,{children:z}),e[73]=z,e[74]=pe):pe=e[74],e[75]!==ge||e[76]!==pe?(K=s.jsxs(Ys,{children:[ge,pe]}),e[75]=ge,e[76]=pe,e[77]=K):K=e[77],e[78]!==h||e[79]!==u?(q=h&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:u("gitView.conflict.loading")})]}),e[78]=h,e[79]=u,e[80]=q):q=e[80],e[81]!==N||e[82]!==u?(me=N&&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:N})}),e[81]=N,e[82]=u,e[83]=me):me=e[83],e[84]!==L||e[85]!==u?(je=L.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:L.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:L.map(Xw)})})]}),e[84]=L,e[85]=u,e[86]=je):je=e[86],e[87]!==w||e[88]!==u?(Oe=w?.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:w.headInfo})]}),e[87]=w,e[88]=u,e[89]=Oe):Oe=e[89],we="flex flex-col gap-2 pt-2";let Ae;e[90]!==V?(Ae=()=>{V()},e[90]=V,e[91]=Ae):Ae=e[91];const G=h||!w;let ke;e[92]!==h?(ke=h?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"add",className:"size-4"}),e[92]=h,e[93]=ke):ke=e[93];let Le;e[94]!==u?(Le=u("gitView.conflict.resolveNewSession"),e[94]=u,e[95]=Le):Le=e[95],e[96]!==Ae||e[97]!==G||e[98]!==ke||e[99]!==Le?(fe=s.jsxs(ze,{variant:"default",onClick:Ae,disabled:G,className:"w-full gap-2",children:[ke,Le]}),e[96]=Ae,e[97]=G,e[98]=ke,e[99]=Le,e[100]=fe):fe=e[100];let Te;e[101]!==W?(Te=()=>{W()},e[101]=W,e[102]=Te):Te=e[102];const Z=h||!w||!x;let F;e[103]!==h?(F=h?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"chat-1",className:"size-4"}),e[103]=h,e[104]=F):F=e[104];let re;e[105]!==u?(re=u("gitView.conflict.resolveCurrentSession"),e[105]=u,e[106]=re):re=e[106],e[107]!==Te||e[108]!==Z||e[109]!==F||e[110]!==re?(Me=s.jsxs(ze,{variant:"outline",onClick:Te,disabled:Z,className:"w-full gap-2",children:[F,re]}),e[107]=Te,e[108]=Z,e[109]=F,e[110]=re,e[111]=Me):Me=e[111],ye="flex gap-2 pt-1";let te;e[112]!==u?(te=u("gitView.conflict.continueLater"),e[112]=u,e[113]=te):te=e[113],e[114]!==B||e[115]!==te?(se=s.jsx(ze,{variant:"ghost",size:"sm",onClick:B,className:"flex-1",children:te}),e[114]=B,e[115]=te,e[116]=se):se=e[116],R=ze,J="destructive",U="sm",ee=I,ae="flex-1",de=u("gitView.conflict.abortOperation",{operation:T}),e[34]=w,e[35]=m,e[36]=x,e[37]=I,e[38]=B,e[39]=W,e[40]=V,e[41]=h,e[42]=N,e[43]=r,e[44]=n,e[45]=c,e[46]=u,e[47]=R,e[48]=ne,e[49]=ie,e[50]=J,e[51]=U,e[52]=ee,e[53]=ae,e[54]=de,e[55]=ye,e[56]=se,e[57]=we,e[58]=fe,e[59]=Me,e[60]=$,e[61]=K,e[62]=q,e[63]=me,e[64]=je,e[65]=Oe,e[66]=Be,e[67]=Fe,e[68]=ue}else R=e[47],ne=e[48],ie=e[49],J=e[50],U=e[51],ee=e[52],ae=e[53],de=e[54],ye=e[55],se=e[56],we=e[57],fe=e[58],Me=e[59],$=e[60],K=e[61],q=e[62],me=e[63],je=e[64],Oe=e[65],Be=e[66],Fe=e[67],ue=e[68];let Re;e[117]!==R||e[118]!==J||e[119]!==U||e[120]!==ee||e[121]!==ae||e[122]!==de?(Re=s.jsx(R,{variant:J,size:U,onClick:ee,className:ae,children:de}),e[117]=R,e[118]=J,e[119]=U,e[120]=ee,e[121]=ae,e[122]=de,e[123]=Re):Re=e[123];let xe;e[124]!==ye||e[125]!==se||e[126]!==Re?(xe=s.jsxs("div",{className:ye,children:[se,Re]}),e[124]=ye,e[125]=se,e[126]=Re,e[127]=xe):xe=e[127];let oe;e[128]!==we||e[129]!==fe||e[130]!==Me||e[131]!==xe?(oe=s.jsxs("div",{className:we,children:[fe,Me,xe]}),e[128]=we,e[129]=fe,e[130]=Me,e[131]=xe,e[132]=oe):oe=e[132];let ve;e[133]!==$||e[134]!==K||e[135]!==q||e[136]!==me||e[137]!==je||e[138]!==Oe||e[139]!==oe?(ve=s.jsxs("div",{className:$,children:[K,q,me,je,Oe,oe]}),e[133]=$,e[134]=K,e[135]=q,e[136]=me,e[137]=je,e[138]=Oe,e[139]=oe,e[140]=ve):ve=e[140];let Se;e[141]!==ne||e[142]!==Be||e[143]!==ve?(Se=s.jsx(ne,{className:Be,children:ve}),e[141]=ne,e[142]=Be,e[143]=ve,e[144]=Se):Se=e[144];let le;return e[145]!==ie||e[146]!==Fe||e[147]!==ue||e[148]!==Se?(le=s.jsx(ie,{open:Fe,onOpenChange:ue,children:Se}),e[145]=ie,e[146]=Fe,e[147]=ue,e[148]=Se,e[149]=le):le=e[149],le};function Kw(t){return t.openNewSessionDraft}function qw(t){return t.currentSessionId}function Yw(t){return t.setPendingInputText}function Qw(t){return t.setPendingSyntheticParts}function Jw(t){return t.setActiveMainTab}function Xw(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const Zw=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=bt(),[c,l]=i.useState(!0),[d,f]=i.useState(!1),m=a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),u=async()=>{f(!0);try{await o(c),e(!1)}catch(x){const y=x instanceof Error?x.message:`Failed to ${n}`;ce.error(y)}finally{f(!1)}},p=()=>{d||e(!1)};return s.jsx(Ms,{open:t,onOpenChange:d?void 0:e,children:s.jsxs(Es,{className:"max-w-md",children:[s.jsxs(Ys,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(A,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(zs,{children:a("gitView.stash.title")})]}),s.jsx(an,{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(Fi,{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(ur,{className:"gap-2",children:[s.jsx(ze,{variant:"ghost",size:"sm",onClick:p,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(A,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:m})})]})]})})},ev=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=bt(),[d,f]=i.useState(null),m=t&&t.head,u=e&&(e.headName||e.onto),p=m?"merge":u?"rebase":null;if(!p)return null;const x=async()=>{f("continue");try{await n()}finally{f(null)}},y=async()=>{f("abort");try{await r()}finally{f(null)}},b=d!==null,g=l(p==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),h=p==="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(A,{name:h,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:g})}),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:b||c,className:"gap-1.5",children:[s.jsx(A,{name:"sparkling",className:"size-4"}),l("gitView.operation.resolveWithAi")]}),d!=="continue"&&s.jsxs(ze,{variant:"ghost",size:"sm",onClick:y,disabled:b||c,className:"gap-1.5",children:[d==="abort"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs(ze,{variant:"default",size:"sm",onClick:x,disabled:b||c,className:"gap-1.5",children:[d==="continue"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{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")})]})})},tv=t=>{const e=mt.c(104),{currentBranch:n,localBranches:r,remoteBranches:o,onMerge:a,onRebase:c,disabled:l,isOperating:d,operationLogs:f,onOperationComplete:m,mode:u,defaultTargetBranch:p}=t,x=l===void 0?!1:l,y=d===void 0?!1:d,b=f===void 0?[]:f,g=u===void 0?"dialog":u,{t:h}=bt(),[C,w]=i.useState(!1),[S,N]=i.useState("merge"),[k,j]=i.useState(null),[D,O]=i.useState(!1),[v,M]=i.useState(""),I=i.useRef(null),E=i.useRef(null),B=x||y,P=n||h("gitView.branch.currentBranchFallback"),W=b.length>0&&b.every(sv),_=b.some(nv);let V;e[0]===Symbol.for("react.memo_cache_sentinel")?(V=()=>{E.current&&(E.current.scrollTop=E.current.scrollHeight)},e[0]=V):V=e[0],i.useEffect(V,[b]);let R;if(e[1]!==v||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Te=v.toLowerCase();let Z;e[6]!==o?(Z=new Set(o.map(rv).filter(Boolean)),e[6]=o,e[7]=Z):Z=e[7];const F=Z;let re;e[8]!==n||e[9]!==F?(re=Ve=>Ve!==n&&!F.has(Ve),e[8]=n,e[9]=F,e[10]=re):re=e[10];const te=r.filter(re);if(!Te){R=te;break e}R=te.filter(Ve=>Ve.toLowerCase().includes(Te))}e[1]=v,e[2]=n,e[3]=r,e[4]=o,e[5]=R}else R=e[5];const ne=R;let ie;if(e[11]!==v||e[12]!==o){e:{const Te=v.toLowerCase();if(!Te){ie=o;break e}ie=o.filter(Z=>Z.toLowerCase().includes(Te))}e[11]=v,e[12]=o,e[13]=ie}else ie=e[13];const J=ie;let U;e[14]!==p||e[15]!==r||e[16]!==o?(U=()=>p&&(o.includes(p)||r.includes(p))?p:null,e[14]=p,e[15]=r,e[16]=o,e[17]=U):U=e[17];const ee=U;let ae;e[18]!==ee||e[19]!==w?(ae=()=>{w(!0),j(ee()),N("merge"),M("")},e[18]=ee,e[19]=w,e[20]=ae):ae=e[20];const de=ae;let ye;e[21]===Symbol.for("react.memo_cache_sentinel")?(ye=Te=>{j(Te),O(!1),M("")},e[21]=ye):ye=e[21];const se=ye;let we;e[22]!==a||e[23]!==c||e[24]!==S||e[25]!==k?(we=()=>{k&&(S==="merge"?a(k):c(k))},e[22]=a,e[23]=c,e[24]=S,e[25]=k,e[26]=we):we=e[26];const fe=we;let Me;e[27]!==y||e[28]!==w?(Me=()=>{y||(j(null),N("merge"),M(""),w(!1))},e[27]=y,e[28]=w,e[29]=Me):Me=e[29];const $=Me,K=()=>{y&&!W||(W&&m?.(),j(null),N("merge"),M(""),w(!1))};let q,me;e[30]!==D?(q=()=>{D||M("")},me=[D],e[30]=D,e[31]=q,e[32]=me):(q=e[31],me=e[32]),i.useEffect(q,me);let je,Oe;e[33]!==g||e[34]!==ee||e[35]!==k?(je=()=>{g!=="inline"||k||j(ee())},Oe=[g,ee,k],e[33]=g,e[34]=ee,e[35]=k,e[36]=je,e[37]=Oe):(je=e[36],Oe=e[37]),i.useEffect(je,Oe);const ue=y?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:b.map(iv)})}),W?g==="dialog"?s.jsx(ur,{children:s.jsx(ze,{variant:"default",size:"sm",onClick:K,children:h(_?"gitView.common.close":"gitView.common.done")})}):s.jsx("div",{className:"flex justify-end",children:s.jsx(ze,{variant:"default",size:"sm",onClick:K,children:h(_?"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:h("gitView.branch.operation")}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>N("merge"),className:Ie("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",S==="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(A,{name:"git-merge",className:Ie("size-4",S==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Ie("typography-ui-label",S==="merge"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.merge")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.mergeDescription")})]}),s.jsxs("button",{type:"button",onClick:()=>N("rebase"),className:Ie("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",S==="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(A,{name:"git-branch",className:Ie("size-4",S==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Ie("typography-ui-label",S==="rebase"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.rebase")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.rebaseDescription")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:S==="merge"?h("gitView.branch.branchToMergeInto",{branch:P}):h("gitView.branch.branchToRebaseOnto")}),s.jsxs(tn,{open:D,onOpenChange:O,modal:!1,children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:Ie("truncate",!k&&"text-muted-foreground"),children:k||h("gitView.branch.selectBranch")}),s.jsx(A,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(en,{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($a,{className:"h-full min-h-0",children:[s.jsx(za,{ref:I,placeholder:h("gitView.branch.searchPlaceholder"),value:v,onValueChange:M,onKeyDown:ov}),s.jsxs(Wa,{className:"h-full min-h-0",disableHorizontal:!0,children:[s.jsx(Ua,{children:h("gitView.branch.empty")}),ne.length>0&&s.jsx(di,{heading:h("gitView.branch.localBranches"),children:ne.map(Te=>s.jsx(fi,{onSelect:()=>se(Te),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Te})},`local-${Te}`))}),ne.length>0&&J.length>0?s.jsx(lg,{}):null,J.length>0&&s.jsx(di,{heading:h("gitView.branch.remoteBranches"),children:J.map(Te=>s.jsx(fi,{onSelect:()=>se(Te),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Te})},`remote-${Te}`))})]})]})})]})]}),k?s.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:S==="merge"?s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryMergePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})," ",h("gitView.branch.summaryMergeInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:P})]}):s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryRebasePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:P})," ",h("gitView.branch.summaryRebaseInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})]})})}):null,g==="dialog"?s.jsxs(ur,{className:"gap-2 pt-1",children:[s.jsx(ze,{variant:"ghost",size:"sm",onClick:$,children:h("gitView.common.cancel")}),s.jsx(ze,{variant:"default",size:"sm",onClick:fe,disabled:!k,className:"gap-1.5",children:S==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"git-merge",className:"size-4"}),h("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"git-branch",className:"size-4"}),h("gitView.operation.rebase")]})})]}):s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(ze,{variant:"destructive",size:"sm",onClick:$,disabled:B,children:h("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx(ze,{variant:"default",size:"sm",onClick:fe,disabled:B||!k,children:h(S==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(g==="inline"){let Te;e[38]!==h?(Te=h("gitView.branch.updateTitle"),e[38]=h,e[39]=Te):Te=e[39];let Z;e[40]!==Te?(Z=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Te}),e[40]=Te,e[41]=Z):Z=e[41];let F;e[42]!==h?(F=h("gitView.branch.updateDescriptionPrefix"),e[42]=h,e[43]=F):F=e[43];let re;e[44]!==P?(re=s.jsx("span",{className:"font-mono text-foreground",children:P}),e[44]=P,e[45]=re):re=e[45];let te;e[46]!==F||e[47]!==re?(te=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[F," ",re,"."]}),e[46]=F,e[47]=re,e[48]=te):te=e[48];let Ve;e[49]!==Z||e[50]!==te?(Ve=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[Z,te]})}),e[49]=Z,e[50]=te,e[51]=Ve):Ve=e[51];let Ye;e[52]!==ue?(Ye=s.jsx("div",{className:"pt-3",children:ue}),e[52]=ue,e[53]=Ye):Ye=e[53];let Ke;return e[54]!==Ve||e[55]!==Ye?(Ke=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Ve,Ye]}),e[54]=Ve,e[55]=Ye,e[56]=Ke):Ke=e[56],Ke}let Re;e[57]!==y?(Re=y?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"git-merge",className:"size-4"}),e[57]=y,e[58]=Re):Re=e[58];let xe;e[59]!==h?(xe=h("gitView.branch.mergeRebase"),e[59]=h,e[60]=xe):xe=e[60];let oe;e[61]!==xe?(oe=s.jsx("span",{children:xe}),e[61]=xe,e[62]=oe):oe=e[62];let ve;e[63]!==de||e[64]!==B||e[65]!==Re||e[66]!==oe?(ve=s.jsx(Ct,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"sm",className:"gap-1.5",onClick:de,disabled:B,children:[Re,oe]})}),e[63]=de,e[64]=B,e[65]=Re,e[66]=oe,e[67]=ve):ve=e[67];let Se;e[68]!==h?(Se=h("gitView.branch.mergeRebaseTooltip"),e[68]=h,e[69]=Se):Se=e[69];let le;e[70]!==Se?(le=s.jsx(At,{sideOffset:8,children:Se}),e[70]=Se,e[71]=le):le=e[71];let T;e[72]!==ve||e[73]!==le?(T=s.jsxs(kt,{children:[ve,le]}),e[72]=ve,e[73]=le,e[74]=T):T=e[74];let L;e[75]!==K||e[76]!==w?(L=Te=>{Te?w(!0):K()},e[75]=K,e[76]=w,e[77]=L):L=e[77];let he;e[78]!==h?(he=h("gitView.branch.updateTitle"),e[78]=h,e[79]=he):he=e[79];let ge;e[80]!==he?(ge=s.jsx(zs,{children:he}),e[80]=he,e[81]=ge):ge=e[81];let z;e[82]!==_||e[83]!==y||e[84]!==S||e[85]!==W||e[86]!==h||e[87]!==P?(z=y?h(W?_?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":S==="merge"?"gitView.branch.mergingInProgress":"gitView.branch.rebasingInProgress"):s.jsxs(s.Fragment,{children:[h("gitView.branch.dialogDescriptionPrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:P}),"."]}),e[82]=_,e[83]=y,e[84]=S,e[85]=W,e[86]=h,e[87]=P,e[88]=z):z=e[88];let pe;e[89]!==z?(pe=s.jsx(an,{children:z}),e[89]=z,e[90]=pe):pe=e[90];let Ae;e[91]!==ge||e[92]!==pe?(Ae=s.jsxs(Ys,{children:[ge,pe]}),e[91]=ge,e[92]=pe,e[93]=Ae):Ae=e[93];let G;e[94]!==ue||e[95]!==Ae?(G=s.jsxs(Es,{className:"max-w-md",children:[Ae,ue]}),e[94]=ue,e[95]=Ae,e[96]=G):G=e[96];let ke;e[97]!==C||e[98]!==L||e[99]!==G?(ke=s.jsx(Ms,{open:C,onOpenChange:L,children:G}),e[97]=C,e[98]=L,e[99]=G,e[100]=ke):ke=e[100];let Le;return e[101]!==T||e[102]!==ke?(Le=s.jsxs(s.Fragment,{children:[T,ke]}),e[101]=T,e[102]=ke,e[103]=Le):Le=e[103],Le};function sv(t){return t.status==="done"||t.status==="error"}function nv(t){return t.status==="error"}function rv(t){return t.slice(t.indexOf("/")+1)}function iv(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(A,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(A,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(A,{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:Ie("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 ov(t){return t.stopPropagation()}const av=({runMutation:t,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:o})=>{const a=[];let c=!1;return{enqueue:d=>{const f=a[a.length-1];if(f?.directory===d.directory&&f.direction===d.direction){d.paths.forEach(m=>f.paths.add(m));return}a.push(d)},flush:()=>{if(c)return;const d=a.shift();if(!d)return;c=!0;const f={directory:d.directory,direction:d.direction,paths:Array.from(d.paths),rollback:d.rollback};(async()=>{try{await t(f),e(f)}catch(m){n(f,m)}finally{r(f.paths),c=!1,a.length>0&&o()}})()},clear:()=>{a.length=0},size:()=>a.length,isRunning:()=>c}},Au="oc.git.actionTab",lv=15e3,cv=t=>t==="commit"||t==="branch"||t==="pr",dv=40,uv=20,Du={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:"},fv=(t,e)=>{const n=t.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,o=n.match(r);if(o){const l=o[1],d=Du[l];if(d)return e.find(f=>f.code===d)||null}const a=n.split(" ")[0],c=Du[a];return c&&e.find(l=>l.code===c)||null},mv=20,Wi=new Map,hv=(t,e)=>{if(Wi.delete(t),Wi.set(t,e),Wi.size>mv){const n=Wi.keys().next().value;n!==void 0&&Wi.delete(n)}},Wr=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Tu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},pv=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},Zl=({isActive:t})=>{const{t:e}=bt(),{git:n}=Xn(),r=hi(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=ft(Q=>Q.currentSessionId),f=ft(Q=>Q.newSessionDraft),m=ft(Q=>Q.setDraftBootstrapPendingDirectory),u=ft(Q=>Q.worktreeMetadata),p=ft(Q=>Q.availableWorktrees),x=Wr(r),y=i.useMemo(()=>{if(!x)return;const Q=p.find(Ne=>Wr(Ne.path)===x);if(Q)return Q;for(const Ne of u.values())if(Wr(Ne.path)===x)return Ne},[p,x,u]),b=i.useMemo(()=>{if(d)return u.get(d)??y;if(f?.open)return y},[d,y,f?.open,u]),{profiles:g,globalIdentity:h,defaultGitIdentityId:C,loadProfiles:w,loadGlobalIdentity:S,loadDefaultGitIdentityId:N}=Ux($l(Q=>({profiles:Q.profiles,globalIdentity:Q.globalIdentity,defaultGitIdentityId:Q.defaultGitIdentityId,loadProfiles:Q.loadProfiles,loadGlobalIdentity:Q.loadGlobalIdentity,loadDefaultGitIdentityId:Q.loadDefaultGitIdentityId}))),k=Nc(r??null),j=Ka(r??null),D=Jf(Q=>d?Q.getAttachment(d):void 0),O=D?cg(D):[],v=D&&!D.degraded&&!D.legacy?D.worktreeRoot??void 0:void 0,M=Hy(r,b,j?.current??void 0),I=sm(r??null),E=dg(r??null),B=ug(r??null),P=kc(r??null),W=fg(r??null),{setActiveDirectory:_,fetchAll:V,ensureAll:R,fetchStatus:ne,fetchBranches:ie,fetchLog:J,setLogMaxCount:U,fetchIdentity:ee,prefetchDiffs:ae,moveStatusPathsOptimistically:de,restoreStatus:ye,bumpIndexRevision:se}=wn($l(Q=>({setActiveDirectory:Q.setActiveDirectory,fetchAll:Q.fetchAll,ensureAll:Q.ensureAll,fetchStatus:Q.fetchStatus,fetchBranches:Q.fetchBranches,fetchLog:Q.fetchLog,setLogMaxCount:Q.setLogMaxCount,fetchIdentity:Q.fetchIdentity,prefetchDiffs:Q.prefetchDiffs,moveStatusPathsOptimistically:Q.moveStatusPathsOptimistically,restoreStatus:Q.restoreStatus,bumpIndexRevision:Q.bumpIndexRevision}))),we=Ee(Q=>Q.isMobile),fe=Ee(Q=>Q.openContextDiff),Me=Ee(Q=>Q.navigateToDiff),$=Ee(Q=>Q.setRightSidebarOpen),K=i.useRef(null),q=i.useRef(null),me=i.useRef(null),je=i.useRef(null),Oe=i.useRef(!0);i.useEffect(()=>()=>{Oe.current=!1},[]);const Be=i.useCallback(()=>{q.current!==null&&(window.clearTimeout(q.current),q.current=null)},[]),Fe=i.useCallback(Q=>{Be(),q.current=window.setTimeout(()=>{q.current=null,Wr(Q)===Wr(r)&&ne(Q,n,{silent:!0})},lv)},[Be,r,ne,n]);i.useEffect(()=>Be,[Be]);const ue=i.useCallback(()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},[]),Re=i.useCallback(()=>{me.current===null&&(me.current=window.setTimeout(()=>{me.current=null,je.current?.()},0))},[]),xe=i.useCallback(async(Q,Ne,Pe)=>{if(Ne==="stage"){if(n.stageGitFiles){await n.stageGitFiles(Q,Pe);return}await Promise.all(Pe.map(_e=>n.stageGitFile(Q,_e)));return}if(n.unstageGitFiles){await n.unstageGitFiles(Q,Pe);return}await Promise.all(Pe.map(_e=>n.unstageGitFile(Q,_e)))},[n]),oe=i.useMemo(()=>av({runMutation:({directory:Q,direction:Ne,paths:Pe})=>xe(Q,Ne,Pe),onMutationComplete:({directory:Q})=>{se(Q),Fe(Q)},onMutationError:({directory:Q,direction:Ne,rollback:Pe},_e)=>{Pe?.(),se(Q),Fe(Q);const ut=e(Ne==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");ce.error(_e instanceof Error?_e.message:ut)},onPathsComplete:Q=>{et(Ne=>{const Pe=new Set(Ne);return Q.forEach(_e=>Pe.delete(_e)),Pe})},scheduleFlush:Re}),[se,xe,Re,Fe,e]);i.useEffect(()=>(je.current=oe.flush,()=>{je.current=null}),[oe]),i.useEffect(()=>()=>oe.clear(),[oe]),i.useEffect(()=>ue,[ue]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let Q=!1,Ne=null;const Pe=async()=>{try{const _e=await hg(r);if(Q)return;a(_e.status),_e.status==="pending"&&(Ne=window.setTimeout(()=>{Pe()},500))}catch{Q||a(null)}};return Pe(),()=>{Q=!0,Ne!==null&&window.clearTimeout(Ne)}},[t,r]),i.useEffect(()=>{const Q=K.current;K.current=o,!(!r||!n)&&(Q==="pending"&&o==="ready"&&(l(!0),V(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(m(null),l(!1)))},[r,V,n,m,o]);const ve=Wr(f?.bootstrapPendingDirectory??null),Se=!!(r&&ve&&ve===Wr(r)),T=!!(r&&(o==="pending"||Se))||c,L=i.useMemo(()=>r?Wi.get(r)??null:null,[r]),he=ss(Q=>Q.settingsGitmojiEnabled),[ge,z]=i.useState(null),{gitmojis:pe}=Uy(he);i.useEffect(()=>{const Q=v||M?.projectDirectory;if(!Q){z(null);return}let Ne=!1;return qa(Q).then(Pe=>{if(Ne)return;const _e=Pe.trim();z(_e&&_e!=="HEAD"?_e:null)}).catch(()=>{Ne||z(null)}),()=>{Ne=!0}},[v,M?.projectDirectory]);const[Ae,G]=i.useState(L?.commitMessage??""),[ke,Le]=i.useState([]),[Te,Z]=i.useState(!1),F=i.useRef(null),[re,te]=i.useState(null),[Ve,Ye]=i.useState(!1),[Ke,Je]=i.useState(null),[nt,xt]=i.useState(25),[jt,Mt]=i.useState(!1),{triggerFireworks:Et}=_y(),Ut=i.useRef(new Map),zt=i.useRef(0),Ht=i.useCallback(()=>{zt.current+=1,Oe.current&&Mt(!0)},[]),_t=i.useCallback(()=>{zt.current=Math.max(0,zt.current-1),Oe.current&&zt.current===0&&Mt(!1)},[]),[Gt,Ce]=i.useState(new Set),[Qe,et]=i.useState(new Set),[yt,We]=i.useState(!1),[at,qe]=i.useState(0),[lt,Dt]=i.useState(!1),[us,Lt]=i.useState(L?.generatedHighlights??[]),es=Qe.size>0||oe.size()>0||oe.isRunning(),os=i.useCallback(()=>{const Q=F.current;Q&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"})})})},[]),Qt=v||M?.projectDirectory||null,Ft=j?.current||null,Xt=i.useMemo(()=>{const Q=j?.tracking;return Q?Q.startsWith("origin/"):!0},[j?.tracking]),as=i.useMemo(()=>{const Q=M?.createdFromBranch,Ne=typeof Q=="string"?Q.trim():"",Pe=typeof j?.current=="string"?j.current.trim():"",_e=typeof ge=="string"?ge.trim():"";return Ne?Ne===Pe&&Ne.startsWith("opencode/")&&_e.length>0&&_e!==Ne?_e:Ne:_e||Pe||"HEAD"},[M?.createdFromBranch,j,ge]),$t=i.useCallback(()=>{Lt([])},[]),[bs,Cs]=i.useState(new Set),[Tt,Bt]=i.useState(new Map),[vt,vs]=i.useState(new Set),hs=i.useRef(Tt),He=i.useRef(vt),[it,It]=i.useState(null),[Rt,Pt]=i.useState(null),[ps,ls]=i.useState(""),[ns,Wt]=i.useState(null),ln=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(A,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(A,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(A,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[fs,Fs]=i.useState(()=>{if(typeof window>"u")return"commit";const Q=window.localStorage.getItem(Au);return Q==="worktree"?"branch":cv(Q)?Q:"commit"}),[Ws,sn]=i.useState([]),[An,vn]=i.useState(null),[be,Ze]=i.useState(null),[dt,wt]=i.useState([]),[Vt,ht]=i.useState(!1),[cs,ds]=i.useState([]),[Ss,gs]=i.useState("merge"),[Ts,Fn]=i.useState(null),[_s,hn]=i.useState(!1),[On,Zn]=i.useState(100),cn=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),Ue=i.useCallback((Q,Ne,Pe)=>{if(!cn||typeof window>"u")return;const _e={directory:Q,conflictFiles:Ne,operation:Pe};window.localStorage.setItem(cn,JSON.stringify(_e))},[cn]),Jt=i.useCallback(()=>{!cn||typeof window>"u"||window.localStorage.removeItem(cn)},[cn]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Au,fs)},[fs]),i.useEffect(()=>{if(!cn||typeof window>"u"||!r)return;const Q=window.localStorage.getItem(cn);if(Q)try{const Ne=JSON.parse(Q);if(Ne.directory!==r){window.localStorage.removeItem(cn);return}ds(Ne.conflictFiles??[]),gs(Ne.operation??"merge"),ht(!0)}catch{window.localStorage.removeItem(cn)}},[cn,r]);const[As,Ps]=i.useState(!1),[$s,Qs]=i.useState("merge"),[Us,Os]=i.useState(""),Ln=i.useCallback(Q=>{dr(Q).then(Ne=>{if(Ne.ok){ce.success(e("gitView.toast.commitHashCopied"));return}ce.error(e("gitView.toast.copyFailed"))})},[e]),fr=i.useCallback(Q=>{Cs(Ne=>{const Pe=new Set(Ne);return Pe.has(Q)?Pe.delete(Q):Pe.add(Q),Pe})},[]);i.useEffect(()=>{hs.current=Tt},[Tt]),i.useEffect(()=>{He.current=vt},[vt]),i.useEffect(()=>{if(!r||!n)return;const Q=Array.from(bs).filter(Pe=>!hs.current.has(Pe)&&!He.current.has(Pe));if(Q.length===0)return;let Ne=!1;return vs(Pe=>{const _e=new Set(Pe);for(const ut of Q)_e.add(ut);return He.current=_e,_e}),Promise.all(Q.map(Pe=>n.getCommitFiles(r,Pe).then(_e=>({hash:Pe,files:_e.files})).catch(_e=>(console.error("Failed to fetch commit files:",_e),{hash:Pe,files:[]})))).then(Pe=>{Ne||(Bt(_e=>{const ut=new Map(_e);for(const{hash:Nt,files:qt}of Pe)ut.set(Nt,qt);return hs.current=ut,ut}),vs(_e=>{const ut=new Set(_e);for(const{hash:Nt}of Pe)ut.delete(Nt);return He.current=ut,ut}))}),()=>{Ne=!0,vs(Pe=>{let _e=!1;const ut=new Set(Pe);for(const Nt of Q)ut.delete(Nt)&&(_e=!0);return _e?(He.current=ut,ut):Pe})}},[bs,r,n]),i.useEffect(()=>{r&&hv(r,{directory:r,commitMessage:Ae,generatedHighlights:us})},[Ae,r,us]),i.useEffect(()=>{t&&(w(),S(),N())},[t,w,S,N]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){Pt(null);return}let Q=!1;return n.getRemoteUrl(r).then(Ne=>{Q||Pt(Ne)}).catch(()=>{Q||Pt(null)}),()=>{Q=!0}},[t,r,n]);const Kn=i.useCallback(async()=>{if(!r||!n?.getRemotes){sn([]);return}try{const Q=await n.getRemotes(r);Oe.current&&sn(Q)}catch{Oe.current&&sn([])}},[r,n]);i.useEffect(()=>{t&&Kn()},[t,Kn]),i.useEffect(()=>{t&&r&&(_(r),R(r,n))},[t,r,_,R,n]),i.useEffect(()=>{if(t&&r)return Er.onGitRefreshHint(Q=>{Wr(Q.directory)===Wr(r)&&ne(r,n)})},[t,r,ne,n]);const ms=i.useCallback(async(Q=!0)=>{if(r)try{await Promise.all([ne(r,n),ie(r,n)])}catch(Ne){if(Q){const Pe=Ne instanceof Error?Ne.message:e("gitView.toast.refreshRepositoryFailed");ce.error(Pe)}}},[r,n,ne,ie,e]),Is=i.useCallback(async()=>{r&&await J(r,n,nt)},[r,n,J,nt]),jr=i.useCallback(async()=>{r&&await ee(r,n)},[r,n,ee]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||k!==!0)return;const Q=typeof C=="string"?C.trim():"";if(!Q||Q==="global"||Ut.current.get(r)===Q)return;let Pe=!1;return(async()=>{try{const ut=await n.hasLocalIdentity?.(r);if(Pe||ut===!0)return;Ht(),await n.setGitIdentity(r,Q),Ut.current.set(r,Q),await jr()}catch(ut){console.warn("Failed to auto-apply default git identity:",ut)}finally{Pe||_t()}})(),()=>{Pe=!0}},[t,Ht,r,C,_t,n,k,jr]);const Bn=i.useMemo(()=>j?[...j.files??[]].sort((Ne,Pe)=>Ne.path.localeCompare(Pe.path)):[],[j]),pn=i.useMemo(()=>Bn.filter(Tu),[Bn]),Nr=i.useMemo(()=>Bn.filter(pv),[Bn]);i.useEffect(()=>{if(!r||Bn.length===0)return;const Q=[],Ne=new Set,Pe=ut=>{!ut||Ne.has(ut)||(Ne.add(ut),Q.push(ut))};if(pn.forEach(ut=>Pe(ut.path)),ke.forEach(Pe),Bn.slice(0,uv).forEach(ut=>Pe(ut.path)),Q.length===0)return;const _e=window.setTimeout(()=>{ae(r,n,Q,{maxFiles:dv})},120);return()=>{window.clearTimeout(_e)}},[Bn,r,n,ae,pn,ke]);const kr=Q=>Q?.pushed[0]?.remote||j?.tracking?.split("/")[0]||ts.find(Ne=>Ne.name==="origin")?.name||ts[0]?.name||"origin",Lr=async(Q,Ne)=>{if(r){te(Q);try{const Pe=_e=>{const ut=`${_e.name}/`,Nt=j?.tracking?.startsWith(ut)?j.tracking.slice(ut.length):void 0;return{remote:_e.name,branch:Nt,rebase:!0}};if(Q==="fetch"){if(!Ne)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:Ne.name}),ce.success(e("gitView.toast.fetchedFromRemote",{name:Ne.name}))}else if(Q==="pull"){if(!Ne)throw new Error("No remote available for pull");const _e=await n.gitPull(r,Pe(Ne));ce.success(_e.files.length===1?e("gitView.toast.pulledFilesSingle",{count:_e.files.length,name:Ne.name}):e("gitView.toast.pulledFilesPlural",{count:_e.files.length,name:Ne.name}))}else if(Q==="push"){const _e=await n.gitPush(r);ce.success(e("gitView.toast.pushedToUpstream",{name:kr(_e)}))}else if(Q==="sync"){if(!Ne)throw new Error("No remote available for sync");let _e=0,ut=!1;await n.gitFetch(r,{remote:Ne.name});const Nt=await n.getGitStatus(r);if((Nt.behind??0)>0){if((Nt.files?.length??0)>0){ce.error(e("gitView.toast.commitOrStashBeforeSync"));return}_e=(await n.gitPull(r,Pe(Ne))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),ut=!0),_e>0&&ut?ce.success(_e===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:_e,name:Ne.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:_e,name:Ne.name})):_e>0?ce.success(_e===1?e("gitView.toast.pulledFilesSingle",{count:_e,name:Ne.name}):e("gitView.toast.pulledFilesPlural",{count:_e,name:Ne.name})):ut?ce.success(e("gitView.toast.pushedToUpstream",{name:Ne.name})):ce.success(e("gitView.toast.alreadyUpToDate"))}await ms(!1),await Is()}catch(Pe){const _e=Pe instanceof Error?Pe.message:e("gitView.toast.syncActionFailed",{action:Q==="sync"?e("gitView.sync.syncChanges"):Q==="pull"?e("gitView.sync.pull"):Q});ce.error(_e)}finally{te(null)}}},Cr=i.useCallback(async Q=>{if(!r)return;const Ne=Q.name.trim();if(!Ne){ce.error(e("gitView.toast.remoteNameRequired"));return}if(Ne==="origin"){ce.error(e("gitView.toast.cannotRemoveOriginRemote"));return}vn(Ne);try{await n.removeRemote(r,{remote:Ne}),ce.success(e("gitView.toast.removedRemote",{name:Ne})),await Promise.all([ms(!1),Kn()])}catch(Pe){const _e=Pe instanceof Error?Pe.message:`Failed to remove ${Ne}`;ce.error(_e)}finally{vn(null)}},[r,n,Kn,ms,e]),nr=async(Q={})=>{if(!r)return;if(!Ae.trim()){ce.error(e("gitView.toast.enterCommitMessage"));return}const Ne=pn.map(_e=>_e.path).sort();if(Ne.length===0){ce.error(e("gitView.toast.stageFileToCommit"));return}const Pe=Q.pushAfter?"commitAndPush":"commit";Je(Pe);try{if(await n.createGitCommit(r,Ae.trim(),{files:Ne,stageFiles:[]}),se(r),ce.success(e("gitView.toast.commitCreated")),G(""),$t(),await ms(),Q.pushAfter){const _e=j?.tracking?.split("/")[0],ut=ts.find(Dr=>Dr.name===_e)??ts[0];if(!ut)throw new Error(e("mobile.changes.noRemote"));te("sync");const Nt=`${ut.name}/`,qt=j?.tracking?.startsWith(Nt)?j.tracking.slice(Nt.length):void 0;await n.gitFetch(r,{remote:ut.name});const Yt=await n.getGitStatus(r);if((Yt.behind??0)>0){if((Yt.files?.length??0)>0){ce.error(e("gitView.toast.commitOrStashBeforeSync")),await ms(!1);return}await n.gitPull(r,{remote:ut.name,branch:qt,rebase:!0})}const ys=await n.getGitStatus(r);let gr;(ys.ahead??0)>0&&(gr=await n.gitPush(r)),ce.success(e("gitView.toast.pushedToUpstream",{name:kr(gr)})),Et(),await ms(!1)}else await ms(!1);await Is(),qe(_e=>_e+1)}catch(_e){const ut=_e instanceof Error?_e.message:e("gitView.toast.createCommitFailed");ce.error(ut)}finally{Je(null),Q.pushAfter&&te(null)}},ws=i.useCallback(async()=>{if(!r)return;const Q=pn.map(Ne=>Ne.path).sort();if(Q.length===0){ce.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:Q.length}),Dt(!0);try{const{message:Ne}=await mg(r,Q),Pe=Ne.subject?.trim()??"",_e=Array.isArray(Ne.highlights)?Ne.highlights:[];if(Pe){let ut=Pe;if(he&&pe.length>0){const Nt=fv(Pe,pe);if(Nt){const{code:qt,emoji:Yt}=Nt;!Pe.startsWith(qt)&&!Pe.startsWith(Yt)&&(ut=`${qt} ${Pe}`)}}G(ut)}Lt(_e),os()}catch(Ne){console.error("[git-generation][browser] GitView generate handler failed",{message:Ne instanceof Error?Ne.message:String(Ne),error:Ne});const Pe=Ne instanceof Error?Ne.message:e("gitView.toast.generateCommitMessageFailed");ce.error(Pe)}finally{Dt(!1)}},[r,pn,he,pe,os,e]),dn=Q=>Q.reason==="attention"?`${Q.attentionReason} in progress`:Q.reason==="missing"?"worktree is missing":"worktree is invalid",rr=async(Q,Ne)=>{if(!r||!j)return;const Pe=ol(D);if(Pe.length>0){ce.error(e("gitView.toast.cannotCreateBranch",{reason:dn(Pe[0])}));return}const _e=j.current??null,ut=Ne?.name??"origin";try{await n.createBranch(r,Q,_e??"HEAD"),ce.success(e("gitView.toast.createdBranch",{name:Q})),await n.checkoutBranch(r,Q);let Nt=!1;try{await n.gitPush(r,{remote:ut,branch:Q,options:["--set-upstream"]}),Nt=!0}catch(qt){const Yt=qt instanceof Error?qt.message:`Unable to push new branch to ${ut}.`;ce.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Yt]})})}await ms(),await Is(),Nt&&ce.success(e("gitView.toast.upstreamSet",{branch:Q,remote:ut}))}catch(Nt){const qt=Nt instanceof Error?Nt.message:e("gitView.toast.createBranchFailed");throw ce.error(qt),Nt}},Y=async(Q,Ne)=>{if(!r)return;const Pe=ol(D);if(Pe.length>0){ce.error(e("gitView.toast.cannotRenameBranch",{reason:dn(Pe[0])}));return}try{await n.renameBranch(r,Q,Ne),ce.success(e("gitView.toast.renamedBranch",{oldName:Q,newName:Ne})),await ms(),await Is()}catch(_e){const ut=_e instanceof Error?_e.message:e("gitView.toast.renameBranchFailed",{oldName:Q,newName:Ne});ce.error(ut)}},tt=async Q=>{if(!r)return;const Ne=ol(D);if(Ne.length>0){ce.error(e("gitView.toast.cannotCheckout",{reason:dn(Ne[0])}));return}const Pe=Q.replace(/^remotes\//,"");if(j?.current!==Pe)try{await n.checkoutBranch(r,Pe),ce.success(e("gitView.toast.checkedOut",{name:Pe})),await ms(),await Is()}catch(_e){const ut=_e instanceof Error?_e.message:e("gitView.toast.checkoutFailed",{name:Pe});ce.error(ut)}},pt=async Q=>{if(r){Ht();try{await n.setGitIdentity(r,Q.id),ce.success(e("gitView.toast.appliedIdentity",{name:Q.name})),await jr()}catch(Ne){const Pe=Ne instanceof Error?Ne.message:e("gitView.toast.applyIdentityFailed");ce.error(Pe)}finally{_t()}}},St=i.useMemo(()=>I?.all?I.all.filter(Q=>!Q.startsWith("remotes/")).sort():[],[I]),Kt=i.useMemo(()=>I?.all?I.all.filter(Q=>Q.startsWith("remotes/")).map(Q=>Q.replace(/^remotes\//,"")).sort():[],[I]),ts=i.useMemo(()=>{if(Ws.length>0)return Ws;const Q=new Set,Ne=j?.tracking?.trim();Ne&&Ne.includes("/")&&Q.add(Ne.split("/")[0]);for(const Pe of Kt){const _e=Pe.indexOf("/");_e>0&&Q.add(Pe.slice(0,_e))}return Q.size===0&&Rt&&Q.add("origin"),Array.from(Q).map(Pe=>({name:Pe,fetchUrl:Rt??"",pushUrl:Rt??""}))},[Ws,Kt,Rt,j?.tracking]),is=i.useMemo(()=>{const Q=new Set(ts.map(ut=>ut.name)),Ne=ut=>{if(!ut)return"";let Nt=ut.trim();if(!Nt||Nt==="HEAD")return"";if(St.includes(Nt))return Nt;Nt.startsWith("refs/heads/")&&(Nt=Nt.slice(11)),Nt.startsWith("heads/")&&(Nt=Nt.slice(6)),Nt.startsWith("remotes/")&&(Nt=Nt.slice(8));const qt=Nt.indexOf("/");if(qt>0){const Yt=Nt.slice(0,qt);if(Q.has(Yt)){const ys=Nt.slice(qt+1).trim();ys&&(Nt=ys)}}return Nt},Pe=Ne(typeof M?.createdFromBranch=="string"?M.createdFromBranch:"");if(Pe)return Pe;const _e=Ne(typeof ge=="string"?ge:"");return _e||(St.includes("main")?"main":St.includes("master")?"master":St.includes("develop")?"develop":"main")},[ts,St,ge,M?.createdFromBranch]),Ls=i.useMemo(()=>ts.map(Pe=>Pe.name).map(Pe=>`${Pe}/${is}`).find(Pe=>Kt.includes(Pe))??is,[is,ts,Kt]),Gs=i.useMemo(()=>{const Q=new Map;h&&Q.set(h.id,h);let Ne=null;if(Rt)try{let Pe=Rt.trim();Pe.startsWith("git@")&&(Pe=`https://${Pe.slice(4).replace(":","/")}`),Pe.endsWith(".git")&&(Pe=Pe.slice(0,-4));const _e=new URL(Pe);Ne=_e.hostname+_e.pathname}catch{}for(const Pe of g){if(Pe.authType!=="token"){Q.set(Pe.id,Pe);continue}const _e=Pe.host;if(!_e){Q.set(Pe.id,Pe);continue}if(!_e.includes("/")){Q.set(Pe.id,Pe);continue}Ne&&Ne===_e&&Q.set(Pe.id,Pe)}return Array.from(Q.values())},[g,h,Rt]),qn=i.useMemo(()=>{if(B?.userName&&B?.userEmail){const Q=g.find(Ne=>Ne.userName===B.userName&&Ne.userEmail===B.userEmail);return Q||(h&&h.userName===B.userName&&h.userEmail===B.userEmail?h:{id:"local-config",name:B.userName,userName:B.userName,userEmail:B.userEmail,sshKey:B.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return h??null},[B,g,h]),Vn=pn.length,Qr=P||re!==null||Ke!==null,gn=j?.current??null,Jr=!!(M&&Qt&&Ft&&Xt),xn=!!(r&&gn),nn=!!gn,un=Jr&&Qt&&Ft&&M?{repoRoot:Qt,sourceBranch:Ft,worktreeMetadata:M}:null,Sn=i.useMemo(()=>!xn||!r||!gn?null:{directory:r,branch:gn},[xn,gn,r]);i.useEffect(()=>{if(!r||!n||!E?.all?.length||!gn||!is||gn===is){It(null);return}let Q=!1;return(async()=>{try{const Pe=await n.getGitLog(r,{from:is,to:"HEAD",maxCount:nt});if(Q)return;const _e=new Set((Pe?.all??[]).map(Nt=>Nt.hash).filter(Nt=>typeof Nt=="string"&&Nt.length>0));if(_e.size===0){It(null);return}const ut=E.all.findIndex(Nt=>!_e.has(Nt.hash));if(ut===0){It(null);return}if(ut===-1){It({insertBeforeIndex:E.all.length,branchName:gn,direction:"up"});return}It({insertBeforeIndex:ut,branchName:gn,direction:"up"})}catch{Q||It(null)}})(),()=>{Q=!0}},[is,gn,r,n,E,nt]),i.useEffect(()=>{Fn(null)},[r]),i.useEffect(()=>{if(ns!=="graph"||!r){ns!=="graph"&&Fn(null);return}let Q=!1;return hn(!0),n.getGitLog(r,{maxCount:On,all:!0}).then(Ne=>{Q||Fn(Ne)}).catch(Ne=>{console.error("Failed to fetch graph log:",Ne)}).finally(()=>{Q||hn(!1)}),()=>{Q=!0}},[ns,r,On,n]);const jn=i.useCallback((Q,Ne)=>{if(!r||Q.length===0)return;const Pe=Array.from(new Set(Q));et(ut=>{const Nt=new Set(ut);return Pe.forEach(qt=>Nt.add(qt)),Nt});const _e=de(r,Pe,Ne);oe.enqueue({directory:r,direction:Ne,paths:new Set(Pe),rollback:()=>ye(r,_e)}),Re()},[r,oe,de,ye,Re]),mr=i.useCallback(async Q=>{if(r){Ce(Ne=>{const Pe=new Set(Ne);return Pe.add(Q),Pe});try{await n.revertGitFile(r,Q,{scope:"working"}),ce.success(e("gitView.toast.revertedFile",{path:Q})),await ms(!1)}catch(Ne){const Pe=Ne instanceof Error?Ne.message:e("gitView.toast.revertFailed");ce.error(Pe)}finally{Ce(Ne=>{const Pe=new Set(Ne);return Pe.delete(Q),Pe})}}},[r,ms,n,e]),ir=i.useCallback(async(Q,Ne,Pe="all")=>{if(!r||Q.length===0)return;const _e=Array.from(new Set(Q));if(yt||_e.some(Yt=>Gt.has(Yt)))return;const ut=new Set(pn.map(Yt=>Yt.path)),Nt=Pe==="all"&&_e.some(Yt=>ut.has(Yt));Ne&&We(!0),Ce(Yt=>{const ys=new Set(Yt);return _e.forEach(gr=>ys.add(gr)),ys});const qt=[];try{if(await Promise.all(_e.map(async Yt=>{try{await n.revertGitFile(r,Yt,{scope:Pe})}catch(ys){qt.push({path:Yt,message:ys instanceof Error?ys.message:e("gitView.toast.revertFailed")})}})),Nt&&qt.length<_e.length&&se(r),await ms(!1),qt.length===0)ce.success(_e.length===1?e("gitView.toast.revertedFilesSingle",{count:_e.length}):e("gitView.toast.revertedFilesPlural",{count:_e.length}));else if(qt.length===_e.length)ce.error(qt[0]?.message||e("gitView.toast.revertFailed"));else{const Yt=_e.length-qt.length;ce.warning(Yt===1?e("gitView.toast.revertedSomeSingle",{success:Yt,failed:qt.length}):e("gitView.toast.revertedSomePlural",{success:Yt,failed:qt.length}))}}finally{Ce(Yt=>{const ys=new Set(Yt);return _e.forEach(gr=>ys.delete(gr)),ys}),Ne&&We(!1)}},[se,r,n,yt,ms,Gt,pn,e]),Ar=i.useCallback(async Q=>{await ir(Q,!0)},[ir]),gi=i.useCallback(async Q=>{await ir(Q,!1,"working")},[ir]),or=i.useCallback((Q,Ne)=>{if(r&&!we){fe(r,Q,Ne);return}Me(Q,Ne),we&&$(!1)},[r,we,Me,fe,$]),xi=i.useCallback(()=>Ye(!0),[]),Br=i.useMemo(()=>{const Q=[];return pn.length>0&&Q.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:pn,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:Ne=>e("gitView.changes.unstageFileAria",{path:Ne}),onActionFile:Ne=>{jn([Ne],"unstage")},onActionAll:Ne=>{jn(Ne,"unstage")},onViewDiff:Ne=>or(Ne,!0),onRevertFile:mr,showRevertActions:!1,accent:!0}),Nr.length>0&&Q.push({id:"unstaged",title:e("gitView.changes.title"),entries:Nr,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:Ne=>e("gitView.changes.stageFileAria",{path:Ne}),onActionFile:Ne=>{jn([Ne],"stage")},onActionAll:Ne=>{jn(Ne,"stage")},onViewDiff:Ne=>or(Ne,!1),onRevertFile:mr}),Q},[mr,or,jn,pn,e,Nr]),Xr=i.useCallback(Q=>{if(Q.length===0)return;const Ne=Q.map(Pe=>Pe.trim()).filter(Boolean);if(Ne.length===0){$t();return}G(Pe=>{const _e=Pe.trim(),ut=_e.length>0?`
11
-
12
- `:"";return`${_e}${ut}${Ne.join(`
13
- `)}`.trim()}),$t()},[$t]),Dn=i.useCallback((Q,Ne)=>{const Pe=Ne||Q;G(_e=>{const ut=_e.trimStart();return ut.startsWith(Q)||Ne&&ut.startsWith(Ne)?_e:`${Pe.endsWith(" ")?Pe:`${Pe} `}${_e}`.trimStart()}),ls(""),Z(!1)},[]),ar=i.useCallback(Q=>{const Ne=Q instanceof Error?Q.message.toLowerCase():"";return Ne.includes("uncommitted changes")||Ne.includes("local changes")||Ne.includes("your local changes would be overwritten")||Ne.includes("please commit your changes or stash them")||Ne.includes("cannot rebase: you have unstaged changes")||Ne.includes("error: cannot pull with rebase")},[]),Js=i.useCallback((Q,Ne)=>{wt(Pe=>[...Pe,{message:Q,status:Ne,timestamp:Date.now()}])},[]),Hs=i.useCallback((Q,Ne)=>{wt(Pe=>{if(Pe.length===0)return Pe;const _e=[...Pe];return _e[_e.length-1]={..._e[_e.length-1],status:Q,...Ne?{message:Ne}:{}},_e})},[]),Vr=i.useCallback(()=>{wt([])},[]),Oi=i.useCallback(()=>{wt([]),Ze(null)},[]),Zr=i.useCallback(Q=>{const Ne=Q.trim(),Pe=new Set(ts.map(ut=>ut.name)),_e=Ne.indexOf("/");if(_e>0){const ut=Ne.slice(0,_e),Nt=Ne.slice(_e+1);if(Pe.has(ut)&&Nt)return{branch:Ne,remote:ut,remoteBranch:Nt}}for(const ut of ts){const Nt=`${ut.name}/${Ne}`;if(Kt.includes(Nt))return{branch:Nt,remote:ut.name,remoteBranch:Ne}}return{branch:Ne,remote:null,remoteBranch:null}},[ts,Kt]),hr=i.useCallback(async Q=>{if(!r)return;Ze("merge"),Vr();const Ne=j?.current,Pe=Zr(Q);try{Pe.remote&&Pe.remoteBranch&&(Js(`Fetching ${Pe.remote}/${Pe.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Pe.remote,branch:Pe.remoteBranch}),Hs("done",`Fetched ${Pe.remote}/${Pe.remoteBranch}`)),Js(`Merging ${Pe.branch} into ${Ne}...`,"running");const _e=await n.merge(r,{branch:Pe.branch});_e.conflict?(Hs("error","Merge conflicts detected"),ds(_e.conflictFiles??[]),gs("merge"),ht(!0),Ue(r,_e.conflictFiles??[],"merge")):(Hs("done",`Merged ${Pe.branch} into ${Ne}`),Jt(),Js("Refreshing repository status...","running"),await ms(),await Is(),Hs("done","Repository status updated"))}catch(_e){if(ar(_e))Hs("error","Uncommitted changes detected"),Qs("merge"),Os(Pe.branch),Ps(!0);else{const ut=_e instanceof Error?_e.message:`Failed to merge ${Pe.branch}`;Hs("error",ut)}}},[r,n,j,Zr,ms,Is,ar,Ue,Jt,Js,Hs,Vr]),bi=i.useCallback(async Q=>{if(!r)return;Ze("rebase"),Vr();const Ne=j?.current,Pe=Zr(Q);try{Pe.remote&&Pe.remoteBranch&&(Js(`Fetching ${Pe.remote}/${Pe.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Pe.remote,branch:Pe.remoteBranch}),Hs("done",`Fetched ${Pe.remote}/${Pe.remoteBranch}`)),Js(`Rebasing ${Ne} onto ${Pe.branch}...`,"running");const _e=await n.rebase(r,{onto:Pe.branch});_e.conflict?(Hs("error","Rebase conflicts detected"),ds(_e.conflictFiles??[]),gs("rebase"),ht(!0),Ue(r,_e.conflictFiles??[],"rebase")):(Hs("done",`Rebased ${Ne} onto ${Pe.branch}`),Jt(),Js("Refreshing repository status...","running"),await ms(),await Is(),Hs("done","Repository status updated"))}catch(_e){if(ar(_e))Hs("error","Uncommitted changes detected"),Qs("rebase"),Os(Pe.branch),Ps(!0);else{const ut=_e instanceof Error?_e.message:`Failed to rebase onto ${Pe.branch}`;Hs("error",ut)}}},[r,n,j,Zr,ms,Is,ar,Ue,Jt,Js,Hs,Vr]),bn=i.useCallback(async()=>{if(r)try{Ss==="merge"?(await n.abortMerge(r),ce.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),ce.success(e("gitView.toast.rebaseAborted"))),Jt(),await ms(),await Is()}catch(Q){const Ne=Q instanceof Error?Q.message:`Failed to abort ${Ss}`;ce.error(Ne)}},[r,n,Ss,ms,Is,Jt,e]),pr=i.useMemo(()=>j?.files?j.files.some(Q=>Q.index==="U"||Q.working_dir==="U"||Q.index==="A"&&Q.working_dir==="A"||Q.index==="D"&&Q.working_dir==="D"):!1,[j?.files]),_r=i.useCallback(async()=>{if(r)try{const Q=!!j?.mergeInProgress?.head,Ne=!!(j?.rebaseInProgress?.headName||j?.rebaseInProgress?.onto);if(Q){const Pe=await n.continueMerge(r);Pe.conflict?(ds(Pe.conflictFiles??[]),gs("merge"),ht(!0),Ue(r,Pe.conflictFiles??[],"merge"),ce.error(e("gitView.toast.mergeConflictsDetected"))):(Jt(),ce.success(e("gitView.toast.mergeCompleted")),await ms(),await Is())}else if(Ne){const Pe=await n.continueRebase(r);Pe.conflict?(ds(Pe.conflictFiles??[]),gs("rebase"),ht(!0),Ue(r,Pe.conflictFiles??[],"rebase"),ce.error(e("gitView.toast.rebaseConflictsDetected"))):(Jt(),ce.success(e("gitView.toast.rebaseStepCompleted")),await ms(),await Is())}}catch(Q){const Ne=Q instanceof Error?Q.message:e("gitView.toast.continueOperationFailed");ce.error(Ne)}},[r,n,j,ms,Is,Ue,Jt,e]),yi=i.useCallback(async()=>{if(r)try{!!j?.mergeInProgress?.head?(await n.abortMerge(r),ce.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),ce.success(e("gitView.toast.rebaseAborted"))),Jt(),await ms(),await Is()}catch(Q){const Ne=Q instanceof Error?Q.message:e("gitView.toast.abortOperationFailed");ce.error(Ne)}},[r,n,j,ms,Is,Jt,e]),$r=i.useCallback(()=>{if(!r)return;const Ne=!!j?.mergeInProgress?.head?"merge":"rebase",Pe=j?.files?.filter(_e=>_e.index==="U"||_e.working_dir==="U").map(_e=>_e.path)??[];Pe.length>0&&ds(Pe),gs(Ne),ht(!0)},[r,j]),Li=i.useCallback(async Q=>{if(!r)return;const Ne=j?.current,Pe=$s,_e=Us,ut=(j?.files??[]).some(Tu);try{await n.stash(r,{message:`Auto-stash before ${Pe} with ${_e}`,includeUntracked:!0}),ut&&se(r)}catch(Yt){const ys=Yt instanceof Error?Yt.message:"Failed to stash changes";ce.error(ys);return}let Nt=!1,qt=!1;try{if(Pe==="merge"){const Yt=await n.merge(r,{branch:_e});Yt.conflict?(qt=!0,ds(Yt.conflictFiles??[]),gs("merge"),ht(!0)):(Nt=!0,ce.success(e("gitView.toast.mergedIntoBranch",{branch:_e,currentBranch:Ne||""})))}else{const Yt=await n.rebase(r,{onto:_e});Yt.conflict?(qt=!0,ds(Yt.conflictFiles??[]),gs("rebase"),ht(!0)):(Nt=!0,ce.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:Ne||"",branch:_e})))}if(Q&&Nt)try{await n.stashPop(r),se(r),ce.success(e("gitView.toast.stashedRestored"))}catch(Yt){const ys=Yt instanceof Error?Yt.message:e("gitView.toast.restoreStashFailed");ce.error(ys)}else Q&&qt&&ce.info(e("gitView.toast.restoreStashManually"));await ms(),await Is()}catch(Yt){if(Q)try{await n.stashPop(r),se(r)}catch{}throw Yt}},[se,r,n,j,$s,Us,ms,Is,e]),rn=i.useCallback(Q=>{xt(Q),r&&(U(r,Q),J(r,n,Q))},[r,J,n,U]),wi=i.useCallback(Q=>{Zn(Q)},[]),Bi=i.useCallback(()=>{Wt(null),r&&(ne(r,n),ie(r,n),J(r,n,nt))},[r,ne,ie,J,nt,n]),mo=i.useCallback(Q=>{if(Q.conflict){if(Q.operation==="cherry-pick"||Q.operation==="revert"){ce.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:Q.conflictFiles?.join(", ")??"unknown files"})}),r&&(ne(r,n),ie(r,n),J(r,n,nt));return}ds(Q.conflictFiles??[]),gs(Q.operation),ht(!0),r&&Ue(r,Q.conflictFiles??[],Q.operation)}},[e,ds,gs,ht,Ue,r,ne,ie,J,nt,n]);return r?k===null||k===!0&&!j?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(A,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):k===!1?T?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(A,{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(A,{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")}),O.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:Ie("flex h-full flex-col overflow-hidden"),children:[s.jsx(Hx,{status:j,localBranches:St,remoteBranches:Kt,branchInfo:I?.branches,syncAction:re,remotes:ts,onFetch:Q=>Lr("fetch",Q),onSync:Q=>Lr("sync",Q),onRemoveRemote:Cr,removingRemoteName:An,onCheckoutBranch:tt,onCreateBranch:rr,onRenameBranch:Y,activeIdentityProfile:qn,availableIdentities:Gs,onSelectIdentity:pt,isApplyingIdentity:jt,isWorktreeMode:!!M,onOpenHistory:()=>Wt("history"),onOpenGraph:()=>Wt("graph"),onOpenStashes:xi,actionTabItems:ln,activeActionTab:fs,onSelectActionTab:Q=>Fs(Q)}),r&&(j?.mergeInProgress?.head||j?.rebaseInProgress?.headName||j?.rebaseInProgress?.onto)&&s.jsx(ev,{mergeInProgress:j?.mergeInProgress,rebaseInProgress:j?.rebaseInProgress,onContinue:_r,onAbort:yi,onResolveWithAI:$r,hasUnresolvedConflicts:pr,isLoading:P}),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:Ie("min-w-0 min-h-0 h-full flex flex-col"),children:s.jsxs(En,{as:Ga,ref:F,outerClassName:"flex-1 min-h-0",className:Ie("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[fs==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(Bn?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(Gx,{groups:Br,diffStats:j?.diffStats,revertingPaths:Gt,isRevertingAll:yt,onVisiblePathsChange:Le,onRevertAll:Ar,onRevertDirectory:gi,headerBackgroundClassName:"bg-background"})}),s.jsx(Kx,{stagedCount:Vn,commitMessage:Ae,onCommitMessageChange:G,generatedHighlights:us,onInsertHighlights:Xr,onGenerateMessage:ws,isGeneratingMessage:lt,onCommit:()=>nr({pushAfter:!1}),onCommitAndPush:()=>nr({pushAfter:!0}),commitAction:Ke,hasPendingIndexMutation:es,gitmojiEnabled:he,onOpenGitmojiPicker:()=>Z(!0)})]}):s.jsx(ew,{onOpenStashes:()=>Ye(!0)})}):null,fs==="branch"?s.jsx("div",{className:"space-y-4",children:nn?s.jsxs(s.Fragment,{children:[s.jsx(tv,{mode:"inline",currentBranch:j?.current,localBranches:St,remoteBranches:Kt,defaultTargetBranch:Ls,onMerge:hr,onRebase:bi,disabled:Qr,isOperating:be!==null,operationLogs:dt,onOperationComplete:Oi}),un?s.jsx(Xy,{repoRoot:un.repoRoot,sourceBranch:un.sourceBranch,worktreeMetadata:un.worktreeMetadata,localBranches:St,defaultTargetBranch:as,refreshKey:at,onRefresh:()=>{r&&(ne(r,n),ie(r,n),J(r,n,nt))}},un.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,fs==="pr"?s.jsx("div",{className:"space-y-4",children:Sn?s.jsx(Hw,{directory:Sn.directory,branch:Sn.branch,baseBranch:is,trackingBranch:j?.tracking??void 0,remotes:Ws,remoteBranches:Kt,onGeneratedDescription:os}):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(Ms,{open:ns!==null,onOpenChange:Q=>{Q||Wt(null)},children:s.jsxs(Es,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(Ys,{children:[s.jsx(zs,{children:e(ns==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(an,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(cw,{mode:ns==="graph"?"graph":"history",log:ns==="graph"?Ts??E:E,isLogLoading:ns==="graph"&&_s||W,logMaxCount:ns==="graph"?On:nt,onLogMaxCountChange:ns==="graph"?wi:rn,expandedCommitHashes:bs,onToggleCommit:fr,commitFilesMap:Tt,loadingCommitHashes:vt,onCopyHash:Ln,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:ns==="graph"?null:it,onConflict:ns==="graph"?mo:void 0,onActionSuccess:ns==="graph"?Bi:void 0})})]})}),s.jsx(Zy,{open:Ve,onOpenChange:Ye,directory:r,hasUncommittedChanges:(j?.files?.length??0)>0,hasStagedChanges:pn.length>0,uncommittedFileCount:j?.files?.length??0,onChanged:async Q=>{r&&Q?.affectsIndex&&se(r),await ms(!1),await Is()}}),s.jsx(Ms,{open:Te,onOpenChange:Z,children:s.jsxs(Es,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(Ys,{className:"px-4 pt-4",children:s.jsx(zs,{children:e("gitView.gitmoji.title")})}),s.jsxs($a,{className:"h-[420px]",children:[s.jsx(za,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:ps,onValueChange:ls}),s.jsxs(Wa,{children:[s.jsx(Ua,{children:e("gitView.gitmoji.empty")}),s.jsx(di,{children:(pe.length===0?[]:pe.filter(Q=>{const Ne=ps.trim().toLowerCase();return Ne?Q.emoji.includes(Ne)||Q.code.toLowerCase().includes(Ne)||Q.description.toLowerCase().includes(Ne):!0})).map(Q=>s.jsxs(fi,{onSelect:()=>Dn(Q.emoji,Q.code),children:[s.jsx("span",{className:"text-lg",children:Q.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Q.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:Q.description})]},Q.code))})]})]})]})}),r&&s.jsx(Gw,{open:Vt,onOpenChange:ht,conflictFiles:cs,directory:r,operation:Ss,onAbort:bn,onClearState:Jt}),s.jsx(Zw,{open:As,onOpenChange:Ps,operation:$s,targetBranch:Us,onConfirm:Li})]}):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")})})},ec=5e3,gv=(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},Nl=(t,e)=>pg(gg.getState().dictionary,t,e),xv=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"},bv=async(t,e)=>{if(t.readFile)return(await t.readFile(e,{optional:!0})).content??"";const n=new URLSearchParams({path:e,optional:"true"}),r=await Ns(`/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()},zc=async(t,e)=>{try{const n=await bv(t,e);return gv(n,ec)>ec?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:xv(n)}}},Wc=t=>{if(t==="too-large"){const e=ec.toLocaleString(eo());return Nl("contextFileOpen.failure.tooLarge",{count:e})}return Nl(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},yv=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),In=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},Um=(t,e)=>{const n=In(e),r=In(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},wv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),vv=new Set(["node_modules"]),Sv=t=>vv.has(t),jv=t=>{const e=In(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},Nv=8,Rr=new Map,kv=t=>{const e=Rr.get(t);return e?(e.touchedAt=Date.now(),Rr.delete(t),Rr.set(t,e),e):null},kl=t=>{const e=Rr.get(t);if(e)return e.touchedAt=Date.now(),e;if(Rr.size>=Nv){const r=Rr.keys().next().value;r!==void 0&&Rr.delete(r)}const n={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Rr.set(t,n),n},Cv=t=>{Rr.delete(t)},Hm=(t,e)=>s.jsx(Kr,{filePath:t,extension:e}),Av=t=>{const e=mt.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},Dv=t=>{const e=mt.c(73),{node:n,root:r,isExpanded:o,isActive:a,status:c,badge:l,permissions:d,downloadFile:f,onSelect:m,onToggle:u,onRevealPath:p,onOpenDialog:x}=t,{t:y}=bt(),b=n.type==="directory",{canRename:g,canCreateFile:h,canCreateFolder:C,canDelete:w,canReveal:S}=d,[N,k]=i.useState(!1),[j,D]=i.useState(!1);let O;e[0]!==h||e[1]!==C||e[2]!==w||e[3]!==g||e[4]!==S?(O=Me=>{!g&&!h&&!C&&!w&&!S||(Me?.preventDefault(),D(!0))},e[0]=h,e[1]=C,e[2]=w,e[3]=g,e[4]=S,e[5]=O):O=e[5];const v=O;let M;e[6]!==b||e[7]!==n||e[8]!==m||e[9]!==u?(M=()=>{b?u(n.path):m(n)},e[6]=b,e[7]=n,e[8]=m,e[9]=u,e[10]=M):M=e[10];const I=M;let E;e[11]===Symbol.for("react.memo_cache_sentinel")?(E=Me=>{Me.stopPropagation(),D(!1),k(!0)},e[11]=E):E=e[11];const B=E;let P;e[12]!==h||e[13]!==C||e[14]!==w||e[15]!==g||e[16]!==S||e[17]!==f||e[18]!==b||e[19]!==n||e[20]!==x||e[21]!==p||e[22]!==y?(P=Me=>{const{Item:$,Separator:K}=Me;return s.jsxs(s.Fragment,{children:[g&&s.jsxs($,{onClick:q=>{q.stopPropagation(),x("rename",n)},children:[s.jsx(A,{name:"edit",className:"mr-2 h-4 w-4"})," ",y("sidebarFilesTree.menu.rename")]}),s.jsxs($,{onClick:q=>{q.stopPropagation(),dr(n.path).then(me=>{if(me.ok){ce.success(y("sidebarFilesTree.toast.pathCopied"));return}ce.error(y("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(A,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",y("sidebarFilesTree.menu.copyPath")]}),!b&&f&&s.jsxs($,{onClick:q=>{q.stopPropagation(),f(n.path).catch(me=>{console.error("Download failed:",me),ce.error(y("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(A,{name:"download",className:"mr-2 h-4 w-4"})," ",y("sidebarFilesTree.menu.save")]}),S&&s.jsxs($,{onClick:q=>{q.stopPropagation(),p(n.path)},children:[s.jsx(A,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",y(Cc())]}),b&&(h||C)&&s.jsxs(s.Fragment,{children:[s.jsx(K,{}),h&&s.jsxs($,{onClick:q=>{q.stopPropagation(),x("createFile",n)},children:[s.jsx(A,{name:"file-add",className:"mr-2 h-4 w-4"})," ",y("sidebarFilesTree.menu.newFile")]}),C&&s.jsxs($,{onClick:q=>{q.stopPropagation(),x("createFolder",n)},children:[s.jsx(A,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",y("sidebarFilesTree.menu.newFolder")]})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx(K,{}),s.jsxs($,{onClick:q=>{q.stopPropagation(),x("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",y("sidebarFilesTree.menu.delete")]})]})]})},e[12]=h,e[13]=C,e[14]=w,e[15]=g,e[16]=S,e[17]=f,e[18]=b,e[19]=n,e[20]=x,e[21]=p,e[22]=y,e[23]=P):P=e[23];const W=P;let _;e[24]!==n.path||e[25]!==r?(_=Me=>{const $=Um(r,n.path);!$||$==="."||(Me.dataTransfer.setData("application/x-openchamber-file-path",$),Me.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=_):_=e[26];const V=_;let R;e[27]!==v?(R=s.jsx("div",{className:"group relative flex items-center",onContextMenu:v}),e[27]=v,e[28]=R):R=e[28];const ne=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let ie;e[29]!==ne?(ie=Ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",ne,"cursor-grab active:cursor-grabbing"),e[29]=ne,e[30]=ie):ie=e[30];let J;e[31]!==b||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(J=b?o?s.jsx(A,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(A,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Hm(n.path,n.extension),e[31]=b,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=J):J=e[35];let U;e[36]!==n.name||e[37]!==n.path?(U=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]=U):U=e[38];let ee;e[39]!==b||e[40]!==c?(ee=!b&&c&&s.jsx(Av,{status:c}),e[39]=b,e[40]=c,e[41]=ee):ee=e[41];let ae;e[42]!==l||e[43]!==b?(ae=b&&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]=b,e[44]=ae):ae=e[44];let de;e[45]!==v||e[46]!==V||e[47]!==I||e[48]!==U||e[49]!==ee||e[50]!==ae||e[51]!==ie||e[52]!==J?(de=s.jsxs("button",{type:"button",onClick:I,onContextMenu:v,draggable:!0,onDragStart:V,className:ie,children:[J,U,ee,ae]}),e[45]=v,e[46]=V,e[47]=I,e[48]=U,e[49]=ee,e[50]=ae,e[51]=ie,e[52]=J,e[53]=de):de=e[53];let ye;e[54]!==h||e[55]!==C||e[56]!==w||e[57]!==g||e[58]!==S||e[59]!==N||e[60]!==W||e[61]!==y?(ye=(g||h||C||w||S)&&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(tn,{open:N,onOpenChange:k,children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:B,title:y("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":y("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(A,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:y("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(en,{align:"end",side:"bottom",onCloseAutoFocus:()=>k(!1),children:W({Item:xs,Separator:Fr})})]})}),e[54]=h,e[55]=C,e[56]=w,e[57]=g,e[58]=S,e[59]=N,e[60]=W,e[61]=y,e[62]=ye):ye=e[62];let se;e[63]!==de||e[64]!==ye||e[65]!==R?(se=s.jsxs(Oc,{render:R,children:[de,ye]}),e[63]=de,e[64]=ye,e[65]=R,e[66]=se):se=e[66];let we;e[67]!==W?(we=s.jsx(Mc,{className:"min-w-[180px]",children:W({Item:Fc,Separator:km})}),e[67]=W,e[68]=we):we=e[68];let fe;return e[69]!==j||e[70]!==se||e[71]!==we?(fe=s.jsxs(Lc,{open:j,onOpenChange:D,children:[se,we]}),e[69]=j,e[70]=se,e[71]=we,e[72]=fe):fe=e[72],fe},Tv=(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,Pv=i.memo(Dv,Tv),Iv=()=>{const{t}=bt(),{files:e}=Xn(),n=hi()??"",r=In(n.trim()),o=Wf(),a=Uf(),c=hc(T=>T.searchFiles),l=Ee(T=>T.openContextFile),d=Ka(n),[f,m]=i.useState(""),u=Ya(f,200),p=i.useRef(null),[x,y]=i.useState([]),[b,g]=i.useState(!1),[h,C]=i.useState({}),[w,S]=i.useState({}),N=i.useRef(new Set),k=i.useRef(new Set);i.useEffect(()=>{if(!r){C({}),S({}),N.current=new Set;return}const T=kv(r);T?(C({...T.childrenByDir}),S({...T.loadErrorsByDir}),N.current=new Set(T.loadedDirs)):(C({}),S({}),N.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const T=kl(r);T.childrenByDir=h},[r,h]),i.useEffect(()=>{if(!r)return;const T=kl(r);T.loadErrorsByDir=w},[r,w]),i.useEffect(()=>{if(!r)return;const T=kl(r);T.loadedDirs=new Set(N.current)},[r,h,w]),i.useEffect(()=>()=>{if(!r)return;const T=Rr.get(r);T&&T.loadedDirs.size===0&&Object.keys(T.childrenByDir).length===0&&Cv(r)},[r]);const j=i.useMemo(()=>[],[]),D=i.useMemo(()=>[],[]),O=fn(T=>r?T.byRoot[r]?.expandedPaths??j:j),v=fn(T=>r?T.byRoot[r]?.selectedPath??null:null),M=fn(T=>T.setSelectedPath),I=fn(T=>T.addOpenPath),E=fn(T=>T.removeOpenPathsByPrefix),B=fn(T=>T.toggleExpandedPath),P=Ee(T=>r?T.contextPanelByDirectory[r]?.tabs??D:D),W=i.useMemo(()=>new Set(P.map(T=>T.mode==="file"?T.targetPath:null).filter(T=>typeof T=="string"&&T.length>0).map(T=>In(T))),[P]),[_,V]=i.useState(null),[R,ne]=i.useState(null),[ie,J]=i.useState(""),[U,ee]=i.useState(!1),ae=!!e.writeFile,de=!!e.createDirectory,ye=!!e.rename,se=!!e.delete,we=!!e.revealPath,fe=i.useMemo(()=>({canRename:ye,canCreateFile:ae,canCreateFolder:de,canDelete:se,canReveal:we}),[ye,ae,de,se,we]),Me=i.useCallback(T=>{e.revealPath&&e.revealPath(T).catch(()=>{ce.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),$=i.useCallback((T,L)=>{V(T),ne(L),J(T==="rename"&&L.name||""),ee(!1)},[]),K=i.useCallback((T,L)=>{const he=L.filter(ge=>ge&&typeof ge.name=="string"&&ge.name.length>0).filter(ge=>o||!ge.name.startsWith(".")).filter(ge=>a||!Sv(ge.name)).map(ge=>{const z=ge.name,pe=In(ge.path||""),Ae=pe?wv(pe)?pe:In(`${T}/${pe}`):In(`${T}/${z}`),G=ge.isDirectory?"directory":"file",ke=G==="file"&&z.includes(".")?z.split(".").pop()?.toLowerCase():void 0;return{name:z,path:Ae,type:G,extension:ke}});return yv(he)},[a,o]),q=i.useCallback(async(T,L)=>{const he=In(T.trim());if(!he||N.current.has(he)||k.current.has(he))return;k.current=new Set(k.current),k.current.add(he);const ge=e.listDirectory?e.listDirectory(he).then(z=>z.entries.map(pe=>({name:pe.name,path:pe.path,isDirectory:pe.isDirectory}))):Jn.listLocalDirectory(he).then(z=>z.map(pe=>({name:pe.name,path:pe.path,isDirectory:pe.isDirectory})));try{const z=await ge;if(L?.())return;const pe=K(he,z);N.current=new Set(N.current),N.current.add(he),S(Ae=>{if(!Ae[he])return Ae;const G={...Ae};return delete G[he],G}),C(Ae=>({...Ae,[he]:pe}))}catch(z){if(L?.())return;const pe=z instanceof Error?z.message:String(z??"");console.error("Failed to load sidebar directory:",z),S(Ae=>({...Ae,[he]:pe}))}finally{k.current=new Set(k.current),k.current.delete(he)}},[e,K]),me=i.useCallback(async()=>{r&&(N.current=new Set,k.current=new Set,S({}),C(T=>Object.keys(T).length===0?T:{}),await q(r))},[q,r]),je=i.useCallback(async T=>{if(!T){await me();return}const L=In(T);N.current=new Set(N.current),N.current.delete(L),k.current=new Set(k.current),k.current.delete(L),await q(L)},[q,me]);i.useEffect(()=>{r&&(N.current=new Set,k.current=new Set,S({}),C(T=>Object.keys(T).length===0?T:{}),q(r))},[q,r,o,a]),i.useEffect(()=>{if(!r||O.length===0)return;const T=O.map(ge=>In(ge)).filter(ge=>!!ge&&ge!==r&&ge.startsWith(`${r}/`)&&!N.current.has(ge)&&!k.current.has(ge)).sort((ge,z)=>ge.split("/").length-z.split("/").length);if(T.length===0)return;let L=!1;const he=()=>L;return(async()=>{for(let ge=0;ge<T.length&&!L;ge+=3){const z=T.slice(ge,ge+3);await Promise.all(z.map(pe=>q(pe,he)))}})(),()=>{L=!0}},[O,q,r]),i.useEffect(()=>{if(!n){y([]),g(!1);return}const T=u.trim();if(!T){y([]),g(!1);return}let L=!1;return g(!0),c(n,T,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(he=>{if(L)return;const z=he.filter(pe=>a||!jv(pe.path)).map(pe=>({name:pe.name,path:In(pe.path),type:"file",extension:pe.extension,relativePath:pe.relativePath}));y(z)}).catch(()=>{L||y([])}).finally(()=>{L||g(!1)}),()=>{L=!0}},[n,u,c,o,a]);const Oe=i.useMemo(()=>{const T=new Map;if(!d?.files)return T;for(const L of d.files)L.index==="A"||L.working_dir==="?"?T.set(L.path,"git-added"):L.index==="D"?T.set(L.path,"git-deleted"):(L.index==="M"||L.working_dir==="M")&&T.set(L.path,"git-modified");return T},[d]),Be=i.useMemo(()=>{const T=new Map;if(!d?.files||!r)return T;for(const L of d.files){const he=L.index==="M"||L.working_dir==="M",ge=L.index==="A"||L.working_dir==="?";if(!he&&!ge)continue;const z=L.path.split("/");if(z.length<=1)continue;let pe=r;for(let Ae=0;Ae<z.length-1;Ae++){pe=`${pe}/${z[Ae]}`;let G=T.get(pe);G||(G={modified:0,added:0},T.set(pe,G)),he&&G.modified++,ge&&G.added++}}return T},[d,r]),Fe=i.useCallback(T=>{if(W.has(T))return"open";if(Oe.size===0)return null;const L=T.startsWith(r+"/")?T.slice(r.length+1):T;return Oe.get(L)??null},[W,Oe,r]),ue=i.useCallback(T=>{if(Be.size===0)return null;const L=Be.get(T);return L&&L.modified+L.added>0?L:null},[Be]),Re=i.useCallback(async T=>{if(!r)return;const L=await zc(e,T.path);if(!L.ok){ce.error(Wc(L.reason));return}M(r,T.path),I(r,T.path),l(r,T.path)},[I,e,l,r,M]),xe=i.useCallback(async T=>{const L=In(T);r&&(B(r,L),N.current.has(L)||await q(L))},[q,r,B]),oe=i.useCallback(async T=>{if(T?.preventDefault(),!R||!_)return;ee(!0);const L=()=>ee(!1),he=()=>V(null);if(_==="createFile"){if(!ie.trim()){ce.error(t("sidebarFilesTree.toast.filenameRequired")),L();return}if(!e.writeFile){ce.error(t("sidebarFilesTree.toast.writeNotSupported")),L();return}const ge=R.path,z=ge?`${ge}/`:"",pe=In(`${z}${ie.trim()}`);await e.writeFile(pe,"").then(async Ae=>{Ae.success&&(ce.success(t("sidebarFilesTree.toast.fileCreated")),await je(ge)),he()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally(L);return}if(_==="createFolder"){if(!ie.trim()){ce.error(t("sidebarFilesTree.toast.folderNameRequired")),L();return}const ge=R.path,z=ge?`${ge}/`:"",pe=In(`${z}${ie.trim()}`);await e.createDirectory(pe).then(async Ae=>{Ae.success&&(ce.success(t("sidebarFilesTree.toast.folderCreated")),await je(ge)),he()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally(L);return}if(_==="rename"){if(!ie.trim()){ce.error(t("sidebarFilesTree.toast.nameRequired")),L();return}if(!e.rename){ce.error(t("sidebarFilesTree.toast.renameNotSupported")),L();return}const ge=R.path,z=ge.split("/").slice(0,-1).join("/"),pe=z?`${z}/`:"",Ae=In(`${pe}${ie.trim()}`);await e.rename(ge,Ae).then(async G=>{G.success&&(ce.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await je(z),r&&E(r,ge),(v===ge||v&&v.startsWith(`${ge}/`))&&M(r,null)),he()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally(L);return}if(_==="delete"){if(!e.delete){ce.error(t("sidebarFilesTree.toast.deleteNotSupported")),L();return}const ge=R.path,z=ge.split("/").slice(0,-1).join("/");await e.delete(ge).then(async pe=>{pe.success&&(ce.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await je(z),r&&E(r,ge),(v===ge||v&&v.startsWith(ge+"/"))&&M(r,null)),he()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally(L);return}L()},[_,R,ie,e,je,E,r,v,M,t]);function ve(T,L){const he=h[T]??[];return he.map((ge,z)=>{const pe=ge.type==="directory",Ae=pe&&O.includes(ge.path),G=v===ge.path,ke=z===he.length-1;return s.jsxs("li",{className:"relative",children:[L>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),ke&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),s.jsx(Pv,{node:ge,root:r,isExpanded:Ae,isActive:G,status:pe?void 0:Fe(ge.path),badge:pe?ue(ge.path):void 0,permissions:fe,downloadFile:e.downloadFile,onSelect:Re,onToggle:xe,onRevealPath:Me,onOpenDialog:$}),pe&&Ae&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[w[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:w[ge.path],children:w[ge.path]}),s.jsxs(ze,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{je(ge.path)},children:[s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,ve(ge.path,L+1)]})]},ge.path)})}const Se=!!(r&&h[r]),le=r?w[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(A,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(Mn,{ref:p,value:f,onChange:T=>m(T.target.value),placeholder:t("sidebarFilesTree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),f.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:()=>{m(""),p.current?.focus()},children:s.jsx(A,{name:"close",className:"h-4 w-4"})}):null]}),ae&&s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>$("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(A,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),de&&s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>$("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(A,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{me()},className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.refreshTitle"),"aria-label":t("sidebarFilesTree.actions.refreshTitle"),children:s.jsx(A,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx(En,{outerClassName:"flex-1 min-h-0",className:"p-2",children:s.jsx("ul",{className:"flex flex-col",children:b?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):x.length>0?x.map(T=>{const L=v===T.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>Re(T),draggable:!0,onDragStart:he=>{const ge=T.relativePath||Um(r??"",T.path);!ge||ge==="."||(he.dataTransfer.setData("application/x-openchamber-file-path",ge),he.dataTransfer.effectAllowed="copy")},className:Ie("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",L?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:T.path,children:[Hm(T.path,T.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:T.relativePath??T.path})]})},T.path)}):le?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{children:le}),s.jsxs(ze,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{me()},children:[s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):Se&&r?ve(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx(Ms,{open:!!_,onOpenChange:T=>!T&&V(null),children:s.jsxs(Es,{children:[s.jsxs(Ys,{children:[s.jsxs(zs,{children:[_==="createFile"&&t("sidebarFilesTree.dialog.createFile.title"),_==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.title"),_==="rename"&&t("sidebarFilesTree.dialog.rename.title"),_==="delete"&&t("sidebarFilesTree.dialog.delete.title")]}),s.jsxs(an,{children:[_==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:R?.path??t("sidebarFilesTree.dialog.rootFallback")}),_==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:R?.path??t("sidebarFilesTree.dialog.rootFallback")}),_==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:R?.name??""}),_==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:R?.name??""})]})]}),_!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(Mn,{value:ie,onChange:T=>J(T.target.value),placeholder:t(_==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:T=>{T.key==="Enter"&&oe()},autoFocus:!0})}),s.jsxs(ur,{children:[s.jsx(ze,{variant:"outline",onClick:()=>V(null),disabled:U,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx(ze,{variant:_==="delete"?"destructive":"default",onClick:()=>{oe()},disabled:U||_!=="delete"&&!ie.trim(),children:U?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):t(_==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},Rv=t=>t==="git"||t==="files"||t==="context",Ev="files",Mv=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function Fv(t,e,n,r){const o=mt.c(6),{git:a}=Xn(),c=wn(Ov),l=!!(t&&a&&e&&n==="git"&&r!=="git");let d,f;o[0]!==t||o[1]!==c||o[2]!==a||o[3]!==l?(d=()=>{if(!l||!t||!a)return;c(t,a);const m=window.setInterval(()=>{Mv()&&c(t,a)},1e4);return()=>window.clearInterval(m)},f=[l,t,a,c],o[0]=t,o[1]=c,o[2]=a,o[3]=l,o[4]=d,o[5]=f):(d=o[4],f=o[5]),i.useEffect(d,f)}function Ov(t){return t.ensureStatus}const Gm=()=>{const t=mt.c(17),e=ks(Bv),n=ks(Vv),r=qs(_v),o=wn($v);let a;e:{if(e){let y;t[0]!==e||t[1]!==n?(y=n.find(b=>b.id===e)??n[0]??null,t[0]=e,t[1]=n,t[2]=y):y=t[2],a=y;break e}a=n[0]??null}const c=a;let l;e:{if(!c){l=null;break e}let y;t[3]!==c.id||t[4]!==c.path?(y={id:c.id,path:c.path},t[3]=c.id,t[4]=c.path,t[5]=y):y=t[5],l=y}const d=l;let f;e:{if(!c){f=null;break e}let y;t[6]!==c.label||t[7]!==c.path||t[8]!==r?(y=c.label?.trim()||lo(c.path,r)||c.path,t[6]=c.label,t[7]=c.path,t[8]=r,t[9]=y):y=t[9],f=y}const m=f;let u;e:{if(!c){u=!1;break e}let y;t[10]!==c.path||t[11]!==o?(y=o.get(c.path)?.isGitRepo,t[10]=c.path,t[11]=o,t[12]=y):y=t[12],u=y===!0}const p=u;let x;return t[13]!==p||t[14]!==m||t[15]!==d?(x=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(Iy,{projectRef:d,projectLabel:m,canCreateWorktree:p})}),t[13]=p,t[14]=m,t[15]=d,t[16]=x):x=t[16],x},Lv=()=>{const t=mt.c(57),{t:e}=bt(),n=Ee(zv),r=Ee(Wv),o=Ee(Uv),a=Ee(Hv),c=hi();Fv(c,o,n,a);const l=a==="git"?"git":a==="context"?"context":null;let d,f;t[0]!==l||t[1]!==n||t[2]!==r?(d=()=>{l&&n===l&&r(Ev)},f=[l,n,r],t[0]=l,t[1]=n,t[2]=r,t[3]=d,t[4]=f):(d=t[3],f=t[4]),i.useEffect(d,f);let m;t[5]!==e?(m=e("layout.rightSidebar.git"),t[5]=e,t[6]=m):m=t[6];let u;t[7]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(A,{name:"git-branch",className:"h-3.5 w-3.5"}),t[7]=u):u=t[7];let p;t[8]!==m?(p={id:"git",label:m,icon:u},t[8]=m,t[9]=p):p=t[9];let x;t[10]!==e?(x=e("layout.rightSidebar.files"),t[10]=e,t[11]=x):x=t[11];let y;t[12]===Symbol.for("react.memo_cache_sentinel")?(y=s.jsx(A,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=y):y=t[12];let b;t[13]!==x?(b={id:"files",label:x,icon:y},t[13]=x,t[14]=b):b=t[14];let g;t[15]!==e?(g=e("layout.rightSidebar.context"),t[15]=e,t[16]=g):g=t[16];let h;t[17]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(A,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=h):h=t[17];let C;t[18]!==g?(C={id:"context",label:g,icon:h},t[18]=g,t[19]=C):C=t[19];let w;t[20]!==C||t[21]!==p||t[22]!==b?(w=[p,b,C],t[20]=C,t[21]=p,t[22]=b,t[23]=w):w=t[23];const S=w;let N;t[24]!==l||t[25]!==S?(N=l?S.filter(ae=>ae.id!==l):S,t[24]=l,t[25]=S,t[26]=N):N=t[26];const k=N,j=o&&n==="git"&&l!=="git";let D;t[27]!==r?(D=ae=>{Rv(ae)&&r(ae)},t[27]=r,t[28]=D):D=t[28];const O=D;let v;t[29]!==O||t[30]!==n||t[31]!==k?(v=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(Ro,{items:k,activeId:n,onSelect:O,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=O,t[30]=n,t[31]=k,t[32]=v):v=t[32];const M=n!=="git"&&"hidden";let I;t[33]!==M?(I=Ie("h-full",M),t[33]=M,t[34]=I):I=t[34];let E;t[35]!==j?(E=s.jsx(Zl,{isActive:j}),t[35]=j,t[36]=E):E=t[36];let B;t[37]!==I||t[38]!==E?(B=s.jsx("div",{className:I,children:E}),t[37]=I,t[38]=E,t[39]=B):B=t[39];const P=n!=="files"&&"hidden";let W;t[40]!==P?(W=Ie("h-full",P),t[40]=P,t[41]=W):W=t[41];let _;t[42]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx(Iv,{}),t[42]=_):_=t[42];let V;t[43]!==W?(V=s.jsx("div",{className:W,children:_}),t[43]=W,t[44]=V):V=t[44];const R=n!=="context"&&"hidden";let ne;t[45]!==R?(ne=Ie("h-full",R),t[45]=R,t[46]=ne):ne=t[46];let ie;t[47]===Symbol.for("react.memo_cache_sentinel")?(ie=s.jsx(Gm,{}),t[47]=ie):ie=t[47];let J;t[48]!==ne?(J=s.jsx("div",{className:ne,children:ie}),t[48]=ne,t[49]=J):J=t[49];let U;t[50]!==B||t[51]!==V||t[52]!==J?(U=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[B,V,J]}),t[50]=B,t[51]=V,t[52]=J,t[53]=U):U=t[53];let ee;return t[54]!==v||t[55]!==U?(ee=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[v,U]}),t[54]=v,t[55]=U,t[56]=ee):ee=t[56],ee};function Bv(t){return t.activeProjectId}function Vv(t){return t.projects}function _v(t){return t.homeDirectory}function $v(t){return t.directories}function zv(t){return t.rightSidebarTab}function Wv(t){return t.setRightSidebarTab}function Uv(t){return t.isRightSidebarOpen}function Hv(t){return t.activeMainTab}const Gv=64,Kv=3,ji=new Map,qv=(t,e,n=Kv)=>{const r=`${t}\0${n}\0${e}`,o=ji.get(r);if(o)return ji.delete(r),ji.set(r,o),o;const a=Qv(e),c=a?Wh(Uh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??Iu(t):Hh(Yv(t,e))[0]?.files[0]??Iu(t);for(ji.set(r,c);ji.size>Gv;){const l=ji.keys().next().value;if(!l)break;ji.delete(l)}return c},Yv=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
14
- ===================================================================
15
- --- ${t}
16
- +++ ${t}
17
- ${e}`,Qv=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 f;for(const m of c.split(/\r?\n/)){if(m.startsWith("diff --git ")||m.startsWith("@@ "))break;if(m.startsWith("\\")){if(f==="-"||f===" "){const u=l.at(-1);u&&(u.newline=!1)}if(f==="+"||f===" "){const u=d.at(-1);u&&(u.newline=!1)}continue}if(m.startsWith("-")){l.push({text:m.slice(1),newline:!0}),f="-";continue}if(m.startsWith("+")){d.push({text:m.slice(1),newline:!0}),f="+";continue}m.startsWith(" ")&&(l.push({text:m.slice(1),newline:!0}),d.push({text:m.slice(1),newline:!0}),f=" ")}return{before:Pu(l),after:Pu(d)}},Pu=t=>t.map(e=>e.text+(e.newline?`
18
- `:"")).join(""),Iu=t=>Gh({name:t,contents:""},{name:t,contents:""}),Ru=t=>{if(!t)return null;const e=t.split(`
19
- `);let n=null;for(const r of e){const o=r.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(o){const a=Number.parseInt(o[1]??"",10);n=Number.isFinite(a)&&a>=1?a:null;continue}if(n!==null){if(r.startsWith(" ")){n+=1;continue}if(r.startsWith("+"))return n;if(r.startsWith("-"))return Math.max(1,n)}}return null},Jv=1100,Xv=15e3,Eu=500,Mu=300,Zv=1e6,e1=3,t1=t=>t<=6?t:t<=12?6:t<=25?4:2,s1=i.memo(()=>{const t=mt.c(4),{t:e}=bt();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}),Km={"?":{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"}},n1=Km.M,r1=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"},qm=t=>{const e=r1(t);return Km[e]??n1},i1=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!=="?")},Ou=t=>!!t.working_dir?.trim()||t.index==="?",o1=(t,e)=>wg(t,e),Lu=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Bu=(t,e)=>{const n=t.split(`
20
- `),r=e.split(`
21
- `),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},a1=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),l1=t=>Array.isArray(t)?t.filter(e=>!e||typeof e!="object"?!1:typeof e.file=="string"):[],c1=t=>t==="added"?"A":t==="deleted"?"D":"M",Ym=(t,e,n)=>a1(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:qv(t,e),contextMode:n},Qm=(t,e,n)=>{const r=t??0,o=e??0;return!r&&!o?null:s.jsxs("span",{className:Ie("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]})},d1=i.memo(t=>{const e=mt.c(53),{scope:n,workingCount:r,stagedCount:o,turnCount:a,onScopeChange:c}=t,{t:l}=bt(),[d,f]=i.useState(!1),m=n==="staged"?o:n==="turn"?a:r;let u;e[0]!==n||e[1]!==l?(u=l(n==="staged"?"diffView.scope.staged":n==="turn"?"diffView.scope.lastTurn":"diffView.scope.changed"),e[0]=n,e[1]=l,e[2]=u):u=e[2];const p=u;let x;e[3]!==l?(x=l("diffView.scope.selectorAria"),e[3]=l,e[4]=x):x=e[4];let y;e[5]!==m?(y=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",m]}),e[5]=m,e[6]=y):y=e[6];let b;e[7]!==p||e[8]!==y?(b=s.jsxs("span",{className:"whitespace-nowrap",children:[p,y]}),e[7]=p,e[8]=y,e[9]=b):b=e[9];let g;e[10]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(A,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=g):g=e[10];let h;e[11]!==x||e[12]!==b?(h=s.jsx(Zs,{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":x,children:[b,g]})}),e[11]=x,e[12]=b,e[13]=h):h=e[13];let C;e[14]!==c?(C=_=>{(_==="working"||_==="staged"||_==="turn")&&(c?.(_),f(!1))},e[14]=c,e[15]=C):C=e[15];let w;e[16]!==l?(w=l("diffView.scope.changed"),e[16]=l,e[17]=w):w=e[17];let S;e[18]!==w?(S=s.jsx("span",{children:w}),e[18]=w,e[19]=S):S=e[19];let N;e[20]!==r?(N=s.jsx("span",{className:"typography-meta text-muted-foreground",children:r}),e[20]=r,e[21]=N):N=e[21];let k;e[22]!==N||e[23]!==S?(k=s.jsx(al,{value:"working",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[S,N]})}),e[22]=N,e[23]=S,e[24]=k):k=e[24];let j;e[25]!==l?(j=l("diffView.scope.staged"),e[25]=l,e[26]=j):j=e[26];let D;e[27]!==j?(D=s.jsx("span",{children:j}),e[27]=j,e[28]=D):D=e[28];let O;e[29]!==o?(O=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=O):O=e[30];let v;e[31]!==D||e[32]!==O?(v=s.jsx(al,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[D,O]})}),e[31]=D,e[32]=O,e[33]=v):v=e[33];let M;e[34]!==l?(M=l("diffView.scope.lastTurn"),e[34]=l,e[35]=M):M=e[35];let I;e[36]!==M?(I=s.jsx("span",{children:M}),e[36]=M,e[37]=I):I=e[37];let E;e[38]!==a?(E=s.jsx("span",{className:"typography-meta text-muted-foreground",children:a}),e[38]=a,e[39]=E):E=e[39];let B;e[40]!==I||e[41]!==E?(B=s.jsx(al,{value:"turn",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[I,E]})}),e[40]=I,e[41]=E,e[42]=B):B=e[42];let P;e[43]!==n||e[44]!==k||e[45]!==v||e[46]!==B||e[47]!==C?(P=s.jsx(en,{align:"start",className:"w-40",children:s.jsxs(vg,{value:n,onValueChange:C,children:[k,v,B]})}),e[43]=n,e[44]=k,e[45]=v,e[46]=B,e[47]=C,e[48]=P):P=e[48];let W;return e[49]!==d||e[50]!==P||e[51]!==h?(W=s.jsxs(tn,{open:d,onOpenChange:f,children:[h,P]}),e[49]=d,e[50]=P,e[51]=h,e[52]=W):W=e[52],W}),u1=i.memo(t=>{const e=mt.c(11),{changedFiles:n,selectedFile:r,onSelectFile:o}=t,{t:a}=bt();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=f=>{const m=qm(f),u=r===f.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(f.path),className:Ie("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(Kr,{filePath:f.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:m.color},title:a(m.descriptionKey),"aria-label":a(m.descriptionKey),children:m.code}),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:f.path,children:f.path}),Qm(f.insertions,f.deletions)]})},f.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(En,{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}),f1=i.memo(t=>{const e=mt.c(20),{filePath:n,diff:r,renderSideBySide:o}=t,{t:a}=bt(),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",f=o?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m={contain:"layout"},e[0]=m):m=e[0];let u;e[1]!==r.original||e[2]!==n||e[3]!==c||e[4]!==f||e[5]!==o||e[6]!==a?(u=c&&s.jsxs("div",{className:f,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]=f,e[5]=o,e[6]=a,e[7]=u):u=e[7];let p;e[8]!==r.modified||e[9]!==n||e[10]!==l||e[11]!==c||e[12]!==f||e[13]!==o||e[14]!==a?(p=l&&s.jsxs("div",{className:f,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]=f,e[13]=o,e[14]=a,e[15]=p):p=e[15];let x;return e[16]!==d||e[17]!==u||e[18]!==p?(x=s.jsx("div",{className:"w-full overflow-auto p-4",style:m,children:s.jsxs("div",{className:d,children:[u,p]})}),e[16]=d,e[17]=u,e[18]=p,e[19]=x):x=e[19],x}),m1=i.memo(t=>{const e=mt.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=Ii(n)||"text",e[0]=n,e[1]=c):c=e[1];const l=c;if(r.isBinary){let m;return e[2]===Symbol.for("react.memo_cache_sentinel")?(m=s.jsx(s1,{}),e[2]=m):m=e[2],m}if(Ri(n)){let m;return e[3]!==r||e[4]!==n||e[5]!==o?(m=s.jsx(f1,{filePath:n,diff:r,renderSideBySide:o}),e[3]=r,e[4]=n,e[5]=o,e[6]=m):m=e[6],m}let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={contain:"layout"},e[7]=d):d=e[7];let f;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?(f=s.jsx("div",{className:"w-full",style:d,children:s.jsx(Nm,{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]=f):f=e[15],f}),h1=i.memo(t=>{const e=mt.c(7),{filePath:n,staged:r,busyAction:o,disabled:a,onAction:c}=t,{t:l}=bt();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(Cl,{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(Cl,{label:l("gitView.changes.revertFileAria",{path:n}),icon:"arrow-go-back",loading:o==="discard",disabled:a,tone:"failure",onClick:()=>c("discard")}),s.jsx(Cl,{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}),Cl=t=>{const e=mt.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)]",f=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let m;e[0]!==d||e[1]!==f?(m=Ie("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,f),e[0]=d,e[1]=f,e[2]=m):m=e[2];let u;e[3]!==l?(u=y=>{y.stopPropagation(),l()},e[3]=l,e[4]=u):u=e[4];let p;e[5]!==r||e[6]!==o?(p=o?s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(A,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=p):p=e[7];let x;return e[8]!==a||e[9]!==n||e[10]!==m||e[11]!==u||e[12]!==p?(x=s.jsx(ze,{variant:"ghost",size:"sm",className:m,disabled:a,title:n,"aria-label":n,onClick:u,children:p}),e[8]=a,e[9]=n,e[10]=m,e[11]=u,e[12]=p,e[13]=x):x=e[13],x},p1=i.memo(({directory:t,file:e,layout:n,wrapLines:r,isSelected:o,isExpanded:a,isMounted:c,onSelect:l,onExpandedChange:d,registerSectionRef:f,showOpenInEditorAction:m=!1,isOpeningInEditor:u=!1,onOpenInEditor:p,staged:x=!1,loadFullFiles:y=!1,initialDiffData:b=null})=>{const{t:g}=bt(),{git:h}=Xn(),C=wn(i.useCallback(K=>K.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),w=wn(K=>K.setDiff),S=wn(K=>K.fetchStatus),N=Ee(K=>K.setDiffFileLayout),[k,j]=i.useState(0),[D,O]=i.useState(null),[v,M]=i.useState(!1),[I,E]=i.useState(null),[B,P]=i.useState(!1),[W,_]=i.useState(null),[V,R]=i.useState(null),ne=i.useRef(null),ie=i.useRef(null),J=i.useMemo(()=>qm(e),[e]),U=n==="side-by-side",ee=y?"full":"patch",ae=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,de=i.useMemo(()=>b||(x?V:W||(C?{original:C.original,modified:C.modified,isBinary:C.isBinary,contextMode:"full"}:null)),[C,b,W,x,V]),ye=de?.contextMode===ee,se=i.useCallback(K=>{ie.current=K,f(e.path,K)},[e.path,f]),we=i.useCallback(K=>{d(e.path,K)},[e.path,d]),fe=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{x?R(null):_(null),O(null),ne.current=null},[ae,x]),i.useEffect(()=>{if(!a||!c)return;if(!t||b||de&&ye){ne.current=null,M(!1);return}const K=`${t}::${e.path}::${x?"staged":"unstaged"}::${ae}::${ee}::${k}`;if(ne.current===K)return;ne.current=K,O(null),M(!0);let q=!1;const me=y?Zv:e1,je=Ri(e.path)?h.getGitFileDiff(t,{path:e.path,staged:x}):h.getGitDiff(t,{path:e.path,staged:x,contextLines:me}),Oe=Xv,Be=new Promise((Fe,ue)=>{setTimeout(()=>ue(new Error(`Timed out after ${Oe}ms`)),Oe)});return Promise.race([je,Be]).then(Fe=>{if(!q){if("diff"in Fe){const ue=Ym(e.path,Fe.diff,ee);x?R(ue):_(ue)}else{const ue={original:Fe.original??"",modified:Fe.modified??"",isBinary:Fe.isBinary,contextMode:"full"};x?R(ue):w(t,e.path,ue)}M(!1)}}).catch(Fe=>{if(q)return;const ue=Fe instanceof Error?Fe.message:String(Fe);O(ue),M(!1)}),()=>{q=!0,ne.current===K&&(ne.current=null)}},[ee,de,ye,k,t,e.path,ae,h,b,a,c,y,w,x]);const Me=i.useCallback(()=>{we(!a),fe()},[we,fe,a]),$=i.useCallback(async K=>{if(!(!t||I!==null)){E(K);try{K==="stage"?await h.stageGitFile(t,e.path):K==="unstage"?await h.unstageGitFile(t,e.path):await h.revertGitFile(t,e.path,{scope:"working"}),j(q=>q+1),await S(t,h)}catch(q){const me=K==="unstage"?"gitView.toast.unstageFileFailed":K==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";ce.error(q instanceof Error?q.message:g(me))}finally{E(q=>q===K?null:q)}}},[t,S,e.path,I,h,g]);return s.jsxs("div",{ref:se,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:Me,onKeyDown:K=>{K.target===K.currentTarget&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),Me())},className:Ie("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(A,{name:"arrow-down-s",className:"size-4"}):s.jsx(A,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:J.color},title:g(J.descriptionKey),"aria-label":g(J.descriptionKey),children:J.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(Kr,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const K=e.path.lastIndexOf("/");if(K===-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 q=e.path.slice(0,K),me=e.path.slice(K+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:q}),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:me})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[Qm(e.insertions,e.deletions),m&&p?s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:g("diffView.actions.openFileInEditorAtChange"),onClick:K=>{K.stopPropagation(),p(e.path,de)},disabled:u,children:u?s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(A,{name:"edit",className:"size-3.5"})}):null,s.jsx(nm,{mode:U?"side-by-side":"unified",onModeChange:K=>{const q=K==="side-by-side"?"side-by-side":"inline";N(e.path,q)},className:"opacity-70"})]})]})}),a&&s.jsxs("div",{className:"relative bg-background overflow-hidden",children:[!c&&!D?s.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,D?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:g("diffView.state.failedToLoadDiff")}),s.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:D}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>j(K=>K+1),children:g("diffView.actions.retry")})]}):null,c&&v&&!de&&!D?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),g("diffView.state.loadingDiff")]}):null,c&&de&&!B&&e.insertions+e.deletions>Eu?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:g("diffView.state.largeDiff",{count:e.insertions+e.deletions})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:g("diffView.state.largeDiffDescription")}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>P(!0),children:g("diffView.actions.renderAnyway")})]}):null,c&&de&&(B||e.insertions+e.deletions<=Eu)?s.jsxs(s.Fragment,{children:[s.jsx(m1,{filePath:e.path,diff:de,renderSideBySide:U,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(h1,{filePath:e.path,staged:x,busyAction:I,disabled:I!==null,onAction:$})})})]}):null]})]})}),Jm=({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}=bt(),{git:f,files:m}=Xn(),u=hi(),{screenWidth:p,isMobile:x}=Or(),y=Nc(u??null),b=Ka(u??null),g=kc(u??null),h=wn(Ce=>Ce.setActiveDirectory),C=wn(Ce=>Ce.ensureStatus),w=wn(Ce=>Ce.fetchStatus),S=wn(Ce=>Ce.setDiff),[N,k]=i.useState(null),[j,D]=i.useState(!1),[O,v]=i.useState(null),[M,I]=i.useState(()=>new Set),[E,B]=i.useState(()=>new Set),[P,W]=i.useState(!1),[_,V]=i.useState(0),[R,ne]=i.useState(!1),[ie,J]=i.useState(!1),[U,ee]=i.useState(o);i.useEffect(()=>{ee(o)},[o]);const ae=Ee(Ce=>Ce.pendingDiffFile),de=Ee(Ce=>Ce.pendingDiffStaged),ye=Ee(Ce=>Ce.pendingDiffScope),se=Ee(Ce=>Ce.setPendingDiffFile),we=Ee(Ce=>Ce.diffLayoutPreference),fe=Ee(Ce=>Ce.diffFileLayout),Me=Ee(Ce=>Ce.setDiffFileLayout),$=Ee(Ce=>Ce.diffWrapLines),K=Ee(Ce=>Ce.setDiffWrapLines),q=Ee(Ce=>Ce.openContextFileAtLine),me=ft(Ce=>Ce.currentSessionId),je=xg(me??"",u??void 0),Oe=$,Be=U==="staged"?!0:U==="working"?!1:null,Fe=Be??j,ue=x||p<=768,Re=!!me&&U!=="turn"&&!ue&&!Yr(),xe=!t&&!ue&&p>=1024,oe=i.useRef(null),ve=i.useRef(new Map),Se=i.useRef(null),le=i.useRef(null),T=i.useRef(!1),L=i.useRef(null),he=i.useRef(null),ge=i.useCallback(()=>{Se.current=null,T.current=!1,v(null),le.current!==null&&(window.cancelAnimationFrame(le.current),le.current=null)},[]),z=i.useCallback(Ce=>{I(Qe=>{if(Qe.has(Ce))return Qe;const et=new Set(Qe);return et.add(Ce),et})},[]),pe=i.useMemo(()=>{for(let Ce=je.length-1;Ce>=0;Ce-=1){const Qe=je[Ce];if(Qe.role==="user")return l1(Qe.summary?.diffs)}return[]},[je]),Ae=i.useMemo(()=>{const Ce=new Map;for(const Qe of pe)if(Qe.file){if(typeof Qe.patch=="string"){Ce.set(Qe.file,Ym(Qe.file,Qe.patch,"patch"));continue}Ce.set(Qe.file,{original:Qe.before??"",modified:Qe.after??"",contextMode:"full"})}return Ce},[pe]),G=i.useMemo(()=>{if(U==="turn")return pe.map(et=>({path:et.file??"",index:"",working_dir:c1(et.status),insertions:et.additions??0,deletions:et.deletions??0,isNew:et.status==="added"})).filter(et=>et.path).sort((et,yt)=>et.path.localeCompare(yt.path));if(!b?.files)return[];const Ce=b.diffStats??{},Qe=U==="staged"?Fu:U==="working"?Ou:()=>!0;return b.files.filter(Qe).map(et=>({...et,insertions:Ce[et.path]?.insertions??0,deletions:Ce[et.path]?.deletions??0,isNew:i1(et)})).sort((et,yt)=>et.path.localeCompare(yt.path))},[U,pe,b]),ke=i.useMemo(()=>b?.files?b.files.filter(Ou).length:0,[b]),Le=i.useMemo(()=>b?.files?b.files.filter(Fu).length:0,[b]),Te=pe.length,Z=i.useMemo(()=>G.map(Ce=>Ce.path).join("\0"),[G]);i.useEffect(()=>{const Ce=Z?Z.split("\0"):[],Qe=new Set(Ce),et=`${u??""}:${U}:${e?"collapsed":"default"}`,yt=he.current!==et;he.current=et,I(We=>{if(yt){const lt=e?0:t1(Ce.length);return new Set(Ce.slice(0,lt))}let at=!1;const qe=new Set;for(const lt of We){if(!Qe.has(lt)){at=!0;continue}qe.add(lt)}return at?qe:We}),B(We=>{if(yt)return new Set;let at=!1;const qe=new Set;for(const lt of We){if(!Qe.has(lt)){at=!0;continue}qe.add(lt)}return at?qe:We})},[U,Z,u,e]);const F=i.useCallback(()=>{L.current=null;const Ce=oe.current;if(!Ce)return;const Qe=Ce.getBoundingClientRect(),et=Qe.top-Mu,yt=Qe.bottom+Mu,We={};for(const[at,qe]of ve.current){if(!qe||!M.has(at))continue;const lt=qe.getBoundingClientRect();lt.bottom<et||lt.top>yt||(We[at]=!0)}B(at=>{let qe=!1;const lt=new Set(at);for(const Dt of Object.keys(We))lt.has(Dt)||(lt.add(Dt),qe=!0);return qe?lt:at})},[M]),re=i.useCallback(()=>{typeof window>"u"||L.current===null&&(L.current=window.requestAnimationFrame(F))},[F]);i.useEffect(()=>{const Ce=oe.current;if(Ce)return re(),Ce.addEventListener("scroll",re,{passive:!0}),window.addEventListener("resize",re),()=>{Ce.removeEventListener("scroll",re),window.removeEventListener("resize",re),L.current!==null&&(window.cancelAnimationFrame(L.current),L.current=null)}},[G,M,re]);const te=i.useCallback(Ce=>{const Qe=fe[Ce.path];if(Qe)return Qe;if(we==="inline")return"inline";if(we==="side-by-side")return"side-by-side";const et=p<Jv;return Ce.isNew||et?"inline":"side-by-side"},[fe,we,p]),Ve=i.useMemo(()=>G.length===0?null:G.every(Ce=>te(Ce)==="side-by-side")?"side-by-side":"inline",[G,te]);i.useEffect(()=>{u&&(h(u),C(u,f))},[u,h,C,f]),i.useEffect(()=>{if(u)return Er.onGitRefreshHint(Ce=>{Lu(Ce.directory)===Lu(u)&&w(u,f)})},[u,w,f]),i.useEffect(()=>{U!=="all"&&!ye||ae&&(ye&&ee(ye),k(ae),D(ye==="staged"||!ye&&de),se(null),T.current=!0,Se.current=ae,z(ae),V(Ce=>Ce+1))},[U,z,ae,ye,de,se]),i.useEffect(()=>{if(U==="all")return;const Ce=c?.trim();Ce&&(k(Ce),D(U==="staged"),T.current=!0,Se.current=Ce,z(Ce),V(Qe=>Qe+1))},[U,z,c]),i.useEffect(()=>{if(!N)return;G.some(Qe=>Qe.path===N)||(k(null),D(!1))},[G,N]);const Ye=i.useCallback((Ce,Qe)=>{const et=ve.current;Qe?et.set(Ce,Qe):et.delete(Ce),re()},[re]),Ke=i.useCallback((Ce,Qe)=>{ge(),I(et=>{const yt=et.has(Ce);if(Qe===yt)return et;const We=new Set(et);return Qe?We.add(Ce):We.delete(Ce),We}),Qe||B(et=>{if(!et.has(Ce))return et;const yt=new Set(et);return yt.delete(Ce),yt}),re()},[ge,re]),Je=i.useCallback(()=>{ge(),I(Ce=>Ce.size>0?new Set:new Set(G.map(Qe=>Qe.path))),B(new Set),re()},[ge,G,re]),nt=i.useCallback(async Ce=>{if(!me)return;const Qe=ft.getState().getDirectoryForSession(me)||u||"";if(!Qe){ce.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}J(!0);try{await bg({originalSessionID:me,directory:Qe,providerID:Ce.providerID,modelID:Ce.modelID,agent:Ce.agent||void 0,variant:Ce.variant||void 0,generateHandoff:Ce.generateHandoff,returnAfterHandoffRequest:Ce.generateHandoff,autoReview:Ce.autoReview}),ne(!1)}catch(et){console.error("[review-flow] failed to start review flow",et),ce.error(et instanceof Error?et.message:d("diffView.reviewDialog.toast.startFailed"))}finally{J(!1)}},[me,u,d]),xt=i.useCallback(Ce=>{const Qe=ve.current.get(Ce),et=oe.current;if(!Qe||!et)return!1;const yt=et.getBoundingClientRect(),at=Qe.getBoundingClientRect().top-yt.top,qe=Math.max(0,et.scrollHeight-et.clientHeight);return et.scrollTop=Math.min(qe,Math.max(0,et.scrollTop+at)),!0},[]);i.useEffect(()=>{if(!Se.current)return;let Qe=0;const et=20;let yt=!1;const We=()=>{yt||(yt=!0,Se.current=null,T.current=!1,v(null),le.current!==null&&(window.cancelAnimationFrame(le.current),le.current=null))},at=()=>{if(yt){le.current=null;return}const qe=Se.current;if(!qe){We(),le.current=null;return}if(!xt(qe)){Qe+=1,Qe<et?le.current=window.requestAnimationFrame(at):(We(),le.current=null);return}n&&T.current&&v(qe),We()};return le.current=window.requestAnimationFrame(at),()=>{yt=!0,le.current!==null&&(window.cancelAnimationFrame(le.current),le.current=null)}},[n,_,xt]);const jt=i.useCallback(Ce=>{},[]),Mt=i.useCallback(Ce=>{ge(),k(Ce),D(!1),T.current=!0,Se.current=Ce,z(Ce),V(Qe=>Qe+1),xt(Ce)},[ge,z,xt]),Et=i.useCallback(Ce=>{const Qe=Ce==="side-by-side"?"side-by-side":"inline";G.forEach(et=>{Me(et.path,Qe)})},[G,Me]),[Ut,zt]=i.useState(null),Ht=i.useCallback(async(Ce,Qe)=>{if(!(!u||!Ce)){zt(Ce);try{let et=null;if(Qe?.patch&&!Qe.isBinary&&!Ri(Ce)?et=Ru(Qe.patch):Qe&&Qe.contextMode==="full"&&!Qe.isBinary&&!Ri(Ce)&&(et=Bu(Qe.original,Qe.modified)),et===null)try{const lt=await f.getGitDiff(u,{path:Ce,staged:Fe,contextLines:3});et=Ru(lt.diff)}catch{et=null}let yt=Qe;if(et===null||!yt){const lt=await f.getGitFileDiff(u,{path:Ce,staged:Fe});yt={original:lt.original??"",modified:lt.modified??"",isBinary:lt.isBinary},Fe||S(u,Ce,yt)}const We=et??(yt.isBinary||Ri(Ce)?1:Bu(yt.original,yt.modified)),at=o1(u,Ce),qe=await zc(m,at);if(!qe.ok){ce.error(Wc(qe.reason));return}q(u,at,We,1)}finally{zt(et=>et===Ce?null:et)}}},[Fe,u,m,f,q,S]),_t=()=>{if(!u)return null;const Ce=Qe=>Be!==null?Be:j&&Qe===N;return s.jsxs("div",{className:Ie("flex min-w-0 flex-1 min-h-0 h-full",l?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[xe&&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:G.length})]}),s.jsx(u1,{changedFiles:G,selectedFile:null,onSelectFile:Mt})]}),s.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:s.jsx(En,{ref:oe,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:G.map(Qe=>s.jsx(p1,{directory:u,file:Qe,layout:te(Qe),wrapLines:Oe,isSelected:!1,isExpanded:M.has(Qe.path),isMounted:E.has(Qe.path)||Qe.path===O,onSelect:jt,onExpandedChange:Ke,registerSectionRef:Ye,showOpenInEditorAction:r&&U!=="turn",isOpeningInEditor:Ut===Qe.path,onOpenInEditor:(et,yt)=>{Ht(et,yt)},staged:Ce(Qe.path),loadFullFiles:P,initialDiffData:U==="turn"?Ae.get(Qe.path)??null:null},Qe.path))})})})]})},Gt=()=>u?U!=="turn"&&g&&!b?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),d("diffView.state.loadingRepositoryStatus")]}):U!=="turn"&&y===!1?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.notGitRepository")}):G.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d(U==="turn"?"diffView.state.noLastTurnChanges":"diffView.state.cleanWorkingTree")}):_t():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:[!x&&(U==="working"||U==="staged"||U==="turn"?s.jsx(d1,{scope:U,workingCount:ke,stagedCount:Le,turnCount:Te,onScopeChange:Ce=>{ee(Ce),a?.(Ce)}}):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:g&&!b?d("diffView.state.loadingChanges"):G.length===1?d("diffView.summary.changedFilesSingle",{count:G.length}):d("diffView.summary.changedFilesPlural",{count:G.length})})})),G.length>0&&s.jsxs(ze,{variant:"ghost",size:"sm",onClick:Je,className:Ie("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(A,{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")})]}),G.length>0&&Re&&s.jsxs(ze,{variant:"default",size:"sm",onClick:()=>ne(!0),disabled:ie,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[ie?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),G.length>0&&s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>W(Ce=>!Ce),"aria-pressed":P,"aria-label":d(P?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:Ie("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",P&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(A,{name:"file-download",className:"size-4"})})}),s.jsx(At,{children:s.jsx("p",{children:d(P?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),G.length>0&&s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>K(!$),className:Ie("h-5 w-5 p-0 transition-opacity",Oe?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(Oe?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(A,{name:"text-wrap",className:"size-4"})}),Ve&&s.jsx(nm,{mode:Ve==="side-by-side"?"side-by-side":"unified",onModeChange:Et})]}),s.jsx(yg,{open:R,onOpenChange:ne,projectDirectory:u??null,submitting:ie,onConfirm:nt}),Gt()]})},g1=(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)},Vu=(t,e)=>{const n=t.state.doc.lineAt(e.main.head);return{lineNumber:n.number,character:e.main.head-n.from+1,selection:e}},_u=(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:Kh.cursor(a),effects:ai.scrollIntoView(a,{y:"center"})})};function x1({open:t,onOpenChange:e,view:n,variant:r="overlay"}){const{t:o}=bt(),[a,c]=i.useState(""),l=i.useRef(null),d=i.useRef(!1),f=i.useRef(null),m=i.useRef(null),u=i.useMemo(()=>g1(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=Vu(n,n.state.selection),c(""))},[t,n]),i.useEffect(()=>{t&&window.requestAnimationFrame(()=>{m.current?.focus(),m.current?.select()})},[t]),i.useEffect(()=>{if(!(!t||!n||!l.current)){if(u===null){const{selection:g}=l.current;n.dispatch({selection:g,effects:ai.scrollIntoView(g.main.from,{y:"center"})});return}_u(n,u,l.current.character)}},[u,t,n]);const p=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:g}=l.current;n.dispatch({selection:g,effects:ai.scrollIntoView(g.main.from,{y:"center"})})},[n]),x=i.useCallback(g=>{g||p(),e(g)},[e,p]),y=i.useCallback(()=>{!n||u===null||!l.current||(d.current=!0,_u(n,u,l.current.character),e(!1),n.focus())},[u,e,n]);i.useEffect(()=>{if(!t)return;const g=C=>{const w=f.current,S=C.target;!w||!(S instanceof Node)||w.contains(S)||x(!1)},h=C=>{C.key==="Escape"&&(C.preventDefault(),x(!1))};return document.addEventListener("pointerdown",g,!0),document.addEventListener("keydown",h,!0),()=>{document.removeEventListener("pointerdown",g,!0),document.removeEventListener("keydown",h,!0)}},[x,t,r]);const b=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(u===null){const g=l.current??Vu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:g.lineNumber,max:n.state.doc.lines})}return o("goToLineDialog.helper.goToLine",{line:u})},[u,o,n]);return r==="inline"?t?s.jsxs("div",{ref:f,className:"ml-1 flex h-6 items-center gap-1",children:[s.jsx(Mn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:g=>c(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),y())},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:y,disabled:!n||u===null,className:"h-6 px-2",children:o("goToLineDialog.actions.go")})]}):null:s.jsx("div",{ref:f,className:Ie("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(Mn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:g=>c(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),y())},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:b})]})})}const b1='<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 $u(){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 y1=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),[f,m]=i.useState($u),u=i.useRef(e),p=i.useRef(e);p.current!==e&&(p.current=e,u.current=e,c.current=e);const x=i.useRef(f);x.current!==f&&(x.current=f,u.current=c.current);const y=i.useRef(null);i.useEffect(()=>{const h=()=>m($u());h();const C=new MutationObserver(h);return C.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>C.disconnect()},[]),i.useEffect(()=>{const h=setTimeout(()=>{y.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(h)},[]),i.useImperativeHandle(a,()=>({getXml:()=>c.current}));const b=i.useCallback(()=>{!e&&!d.current&&(d.current=!0,setTimeout(()=>{l.current?.template({})},500))},[e]),g=i.useCallback(h=>{c.current=h.xml,o?.(h.xml)},[o]);return s.jsx("div",{ref:y,className:Ie("h-full w-full",r),children:s.jsx(qh,{ref:l,xml:u.current||b1,autosave:!0,urlParameters:{ui:n?"simple":f?"dark":"kennedy",spin:!0,libraries:!n,chrome:n,nav:n,layers:n,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:g},f?"dark":"light")})}),w1=t=>{const e=Ks(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},v1=t=>{const e=mt.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 m;e[2]===Symbol.for("react.memo_cache_sentinel")?(m=()=>a(!0),e[2]=m):m=e[2];let u;return e[3]!==r?(u=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:m}),e[3]=r,e[4]=u):u=e[4],u}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=Ie("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 f;return e[6]!==l?(f=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=f):f=e[7],f},S1=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Ks=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},j1=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Hi=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,Ea=(t,e)=>{const n=Ks(e),r=Ks(t);if(!n||!r)return!1;const o=Hi(n),a=Hi(r);return a===o||a.startsWith(`${o}/`)},zu=(t,e)=>{const n=Ks(e),r=Ks(t);if(!Ea(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},tc=(t,e)=>{if(!e)return"";const n=Ks(e);if(!t||!Ea(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},N1=new Set(["node_modules"]),k1=t=>{const e=mt.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},Wu=t=>{const e=mt.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 p=r.current,x=o.current;if(!p||!x)return;const y=()=>{c(x.scrollWidth>p.clientWidth+1)};y();const b=new ResizeObserver(y);return b.observe(p),b.observe(x),()=>{b.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 f;e[3]!==n?(f=s.jsx("span",{ref:o,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:n}),e[3]=n,e[4]=f):f=e[4];let m;e[5]!==n||e[6]!==a?(m=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]=m):m=e[7];let u;return e[8]!==f||e[9]!==m?(u=s.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[f,m]}),e[8]=f,e[9]=m,e[10]=u):u=e[10],u},C1=t=>N1.has(t),A1=t=>{const e=Ks(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},D1=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},Uu=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")},bo=2e5,Xm="openchamber:files:auto-save-enabled",T1=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
22
- `:`
23
- `},Zm=t=>t.replace(/\r\n/g,`
24
- `).replace(/\r/g,`
25
- `),P1=(t,e)=>{const n=Zm(t);return e===`\r
26
- `?n.replace(/\n/g,`\r
27
- `):n},I1=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(Xm)!=="false"}catch{return!0}},eh=(t,e)=>s.jsx(Kr,{filePath:t,extension:e}),Hu=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},R1=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="json"||e==="jsonc"||e==="json5"||e==="geojson"},Zo=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="html"||e==="htm"},E1=t=>{const e=mt.c(83),{node:n,root:r,isExpanded:o,isActive:a,isMobile:c,alwaysShowActions:l,status:d,badge:f,permissions:m,downloadFile:u,contextMenuPath:p,setContextMenuPath:x,rightClickMenuPath:y,setRightClickMenuPath:b,onSelect:g,onToggle:h,onRevealPath:C,onOpenDialog:w}=t,{t:S}=bt(),N=n.type==="directory",{canRename:k,canCreateFile:j,canCreateFolder:D,canDelete:O,canReveal:v}=m;let M;e[0]!==j||e[1]!==D||e[2]!==O||e[3]!==k||e[4]!==v||e[5]!==n.path||e[6]!==b?(M=me=>{!k&&!j&&!D&&!O&&!v||(me?.preventDefault(),b(n.path))},e[0]=j,e[1]=D,e[2]=O,e[3]=k,e[4]=v,e[5]=n.path,e[6]=b,e[7]=M):M=e[7];const I=M;let E;e[8]!==N||e[9]!==n||e[10]!==g||e[11]!==h?(E=()=>{N?h(n.path):g(n)},e[8]=N,e[9]=n,e[10]=g,e[11]=h,e[12]=E):E=e[12];const B=E;let P;e[13]!==n.path||e[14]!==x||e[15]!==b?(P=me=>{me.stopPropagation(),b(null),x(n.path)},e[13]=n.path,e[14]=x,e[15]=b,e[16]=P):P=e[16];const W=P;let _;e[17]!==j||e[18]!==D||e[19]!==O||e[20]!==k||e[21]!==v||e[22]!==u||e[23]!==N||e[24]!==n||e[25]!==w||e[26]!==C||e[27]!==r||e[28]!==S?(_=me=>{const{Item:je,Separator:Oe}=me;return s.jsxs(s.Fragment,{children:[k&&s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),w("rename",n)},children:[s.jsx(A,{name:"edit",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.rename")]}),s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),dr(n.path).then(Fe=>{if(Fe.ok){ce.success(S("sidebarFilesTree.toast.pathCopied"));return}ce.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(A,{name:"file-copy",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.copyPath")]}),s.jsxs(je,{onClick:Be=>{Be.stopPropagation();const Fe=tc(r,n.path)||n.path;dr(Fe).then(ue=>{if(ue.ok){ce.success(S("filesView.toast.relativePathCopied"));return}ce.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(A,{name:"file-copy-2",className:"mr-2 size-4"})," ",S("filesView.tree.menu.copyRelativePath")]}),!N&&u&&s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),u(n.path).catch(Fe=>{console.error("Download failed:",Fe),ce.error(S("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(A,{name:"download",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.save")]}),v&&s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),C(n.path)},children:[s.jsx(A,{name:"folder-received",className:"mr-2 size-4"})," ",S(Cc())]}),N&&(j||D)&&s.jsxs(s.Fragment,{children:[s.jsx(Oe,{}),j&&s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),w("createFile",n)},children:[s.jsx(A,{name:"file-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFile")]}),D&&s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),w("createFolder",n)},children:[s.jsx(A,{name:"folder-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFolder")]})]}),O&&s.jsxs(s.Fragment,{children:[s.jsx(Oe,{}),s.jsxs(je,{onClick:Be=>{Be.stopPropagation(),w("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"delete-bin",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.delete")]})]})]})},e[17]=j,e[18]=D,e[19]=O,e[20]=k,e[21]=v,e[22]=u,e[23]=N,e[24]=n,e[25]=w,e[26]=C,e[27]=r,e[28]=S,e[29]=_):_=e[29];const V=_,R=y===n.path;let ne;e[30]!==n.path||e[31]!==b?(ne=me=>b(me?n.path:null),e[30]=n.path,e[31]=b,e[32]=ne):ne=e[32];const ie=c?void 0:I;let J;e[33]!==ie?(J=s.jsx("div",{className:"group relative flex items-center",onContextMenu:ie}),e[33]=ie,e[34]=J):J=e[34];const U=c?void 0:I,ee=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let ae;e[35]!==ee?(ae=Ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",ee),e[35]=ee,e[36]=ae):ae=e[36];let de;e[37]!==N||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(de=N?o?s.jsx(A,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(A,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):eh(n.path,n.extension),e[37]=N,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=de):de=e[41];let ye;e[42]!==n.name||e[43]!==n.path?(ye=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]=ye):ye=e[44];let se;e[45]!==N||e[46]!==d?(se=!N&&d&&s.jsx(k1,{status:d}),e[45]=N,e[46]=d,e[47]=se):se=e[47];let we;e[48]!==f||e[49]!==N?(we=N&&f&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[f.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",f.modified]}),f.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",f.added]})]}),e[48]=f,e[49]=N,e[50]=we):we=e[50];let fe;e[51]!==B||e[52]!==ae||e[53]!==de||e[54]!==ye||e[55]!==se||e[56]!==we||e[57]!==U?(fe=s.jsxs("button",{type:"button",onClick:B,onContextMenu:U,className:ae,children:[de,ye,se,we]}),e[51]=B,e[52]=ae,e[53]=de,e[54]=ye,e[55]=se,e[56]=we,e[57]=U,e[58]=fe):fe=e[58];let Me;e[59]!==l||e[60]!==j||e[61]!==D||e[62]!==O||e[63]!==k||e[64]!==v||e[65]!==p||e[66]!==W||e[67]!==c||e[68]!==n.path||e[69]!==V||e[70]!==x?(Me=(k||j||D||O||v)&&s.jsx("div",{className:Ie("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(tn,{open:p===n.path,onOpenChange:me=>x(me?n.path:null),children:[s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"icon",className:"size-6",onClick:W,children:s.jsx(A,{name:"more-2-fill",className:"size-4"})})}),s.jsx(en,{align:"end",side:"bottom",onCloseAutoFocus:()=>x(null),children:V({Item:xs,Separator:Fr})})]})}),e[59]=l,e[60]=j,e[61]=D,e[62]=O,e[63]=k,e[64]=v,e[65]=p,e[66]=W,e[67]=c,e[68]=n.path,e[69]=V,e[70]=x,e[71]=Me):Me=e[71];let $;e[72]!==fe||e[73]!==Me||e[74]!==J?($=s.jsxs(Oc,{render:J,children:[fe,Me]}),e[72]=fe,e[73]=Me,e[74]=J,e[75]=$):$=e[75];let K;e[76]!==V?(K=s.jsx(Mc,{className:"min-w-[180px]",children:V({Item:Fc,Separator:km})}),e[76]=V,e[77]=K):K=e[77];let q;return e[78]!==$||e[79]!==K||e[80]!==R||e[81]!==ne?(q=s.jsxs(Lc,{open:R,onOpenChange:ne,children:[$,K]}),e[78]=$,e[79]=K,e[80]=R,e[81]=ne,e[82]=q):q=e[82],q},M1=t=>{const e=mt.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:f}=t,{t:m}=bt(),u=!!n;let p;e[0]!==d?(p=R=>!R&&d(),e[0]=d,e[1]=p):p=e[1];let x;e[2]!==n||e[3]!==m?(x=n==="createFile"&&m("filesView.dialog.createFile.title"),e[2]=n,e[3]=m,e[4]=x):x=e[4];let y;e[5]!==n||e[6]!==m?(y=n==="createFolder"&&m("filesView.dialog.createFolder.title"),e[5]=n,e[6]=m,e[7]=y):y=e[7];let b;e[8]!==n||e[9]!==m?(b=n==="rename"&&m("filesView.dialog.rename.title"),e[8]=n,e[9]=m,e[10]=b):b=e[10];let g;e[11]!==n||e[12]!==m?(g=n==="delete"&&m("filesView.dialog.delete.title"),e[11]=n,e[12]=m,e[13]=g):g=e[13];let h;e[14]!==x||e[15]!==y||e[16]!==b||e[17]!==g?(h=s.jsxs(zs,{children:[x,y,b,g]}),e[14]=x,e[15]=y,e[16]=b,e[17]=g,e[18]=h):h=e[18];let C;e[19]!==n||e[20]!==r?.path||e[21]!==m?(C=n==="createFile"&&m("filesView.dialog.createFile.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[19]=n,e[20]=r?.path,e[21]=m,e[22]=C):C=e[22];let w;e[23]!==n||e[24]!==r?.path||e[25]!==m?(w=n==="createFolder"&&m("filesView.dialog.createFolder.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[23]=n,e[24]=r?.path,e[25]=m,e[26]=w):w=e[26];let S;e[27]!==n||e[28]!==r?.name||e[29]!==m?(S=n==="rename"&&m("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=m,e[30]=S):S=e[30];let N;e[31]!==n||e[32]!==r?.name||e[33]!==m?(N=n==="delete"&&m("filesView.dialog.delete.description",{name:r?.name??""}),e[31]=n,e[32]=r?.name,e[33]=m,e[34]=N):N=e[34];let k;e[35]!==S||e[36]!==N||e[37]!==C||e[38]!==w?(k=s.jsxs(an,{children:[C,w,S,N]}),e[35]=S,e[36]=N,e[37]=C,e[38]=w,e[39]=k):k=e[39];let j;e[40]!==k||e[41]!==h?(j=s.jsxs(Ys,{children:[h,k]}),e[40]=k,e[41]=h,e[42]=j):j=e[42];let D;e[43]!==n||e[44]!==o||e[45]!==f||e[46]!==a||e[47]!==l||e[48]!==m?(D=n!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(Mn,{value:o,onChange:R=>a(R.target.value),placeholder:m(n==="rename"?"filesView.dialog.rename.placeholder":"filesView.dialog.namePlaceholder"),onKeyDown:R=>{R.key==="Enter"&&l()},ref:f})}),e[43]=n,e[44]=o,e[45]=f,e[46]=a,e[47]=l,e[48]=m,e[49]=D):D=e[49];let O;e[50]!==m?(O=m("filesView.dialog.cancel"),e[50]=m,e[51]=O):O=e[51];let v;e[52]!==c||e[53]!==d||e[54]!==O?(v=s.jsx(ze,{variant:"outline",onClick:d,disabled:c,children:O}),e[52]=c,e[53]=d,e[54]=O,e[55]=v):v=e[55];const M=n==="delete"?"destructive":"default";let I;e[56]!==l?(I=()=>{l()},e[56]=l,e[57]=I):I=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 B;e[62]!==n||e[63]!==c||e[64]!==m?(B=c?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):m(n==="delete"?"filesView.dialog.delete.confirm":"filesView.dialog.confirm"),e[62]=n,e[63]=c,e[64]=m,e[65]=B):B=e[65];let P;e[66]!==M||e[67]!==I||e[68]!==E||e[69]!==B?(P=s.jsx(ze,{variant:M,onClick:I,disabled:E,children:B}),e[66]=M,e[67]=I,e[68]=E,e[69]=B,e[70]=P):P=e[70];let W;e[71]!==v||e[72]!==P?(W=s.jsxs(ur,{children:[v,P]}),e[71]=v,e[72]=P,e[73]=W):W=e[73];let _;e[74]!==f||e[75]!==j||e[76]!==D||e[77]!==W?(_=s.jsxs(Es,{initialFocus:f,children:[j,D,W]}),e[74]=f,e[75]=j,e[76]=D,e[77]=W,e[78]=_):_=e[78];let V;return e[79]!==u||e[80]!==p||e[81]!==_?(V=s.jsx(Ms,{open:u,onOpenChange:p,children:_}),e[79]=u,e[80]=p,e[81]=_,e[82]=V):V=e[82],V},Al=(t,e,n)=>{const r=mt.c(8),[o,a]=i.useState(""),[c,l]=i.useState(0);let d,f;r[0]!==t||r[1]!==n||r[2]!==e?(d=()=>{if(!t){a("");return}let u=!1;a("");const p=Hr(),x=yp(p);pc(p).then(b=>{u||!b||(a(t),e(null))}).catch(b=>{u||(e(b instanceof Error?b.message:n),a(t))});const y=wp(()=>{u||(a(t),l(F1),e(null))});return()=>{u=!0,x(),y()}},f=[t,e,n],r[0]=t,r[1]=n,r[2]=e,r[3]=d,r[4]=f):(d=r[3],f=r[4]),i.useEffect(d,f);let m;return r[5]!==c||r[6]!==o?(m={readyKey:o,nonce:c},r[5]=c,r[6]=o,r[7]=m):m=r[7],m},th=({mode:t="full"})=>{const{t:e}=bt(),{files:n,runtime:r}=Xn(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=pi(),{isMobile:d,isTablet:f,screenWidth:m}=Or(),u=d||f,p=Wf(),x=Uf(),y=hi()??"",b=Ks(y.trim()),g=d||t!=="editor-only",h=t==="editor-only"&&!d,C=hc(H=>H.searchFiles),w=Ka(y),[S,N]=i.useState(""),k=Ya(S,200),j=i.useRef(null),[D,O]=i.useState(!1),[v,M]=i.useState(!0),[I,E]=i.useState(!1),[B,P]=i.useState(!1),[W,_]=i.useState(!1),V=i.useRef(null),R=i.useRef(0),ne=i.useCallback(H=>{R.current=Math.max(0,R.current+(H?1:-1))},[]),ie=i.useCallback(H=>H instanceof Element?H.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!W)return;const H=De=>{R.current>0||ie(De.target)||V.current&&!V.current.contains(De.target)&&_(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[ie,W]);const[J,U]=i.useState("edit"),[ee,ae]=i.useState("edit"),[de,ye]=i.useState("tree"),[se,we]=i.useState("edit"),[fe,Me]=i.useState("preview"),[$,K]=i.useState(0),q=i.useRef({}),me=i.useRef({}),je=i.useRef({}),Oe=i.useRef({}),Be=i.useMemo(()=>a.find(H=>H.metadata.id===c)??Id(!1),[a,c]),Fe=i.useMemo(()=>a.find(H=>H.metadata.id===l)??Id(!0),[a,l]);i.useEffect(()=>{Rd(Be),Rd(Fe)},[Be,Fe]);const ue=i.useMemo(()=>[],[]),Re=fn(H=>b?H.byRoot[b]?.openPaths??ue:ue),xe=fn(H=>b?H.byRoot[b]?.selectedPath??null:null),oe=fn(H=>b?H.byRoot[b]?.expandedPaths??ue:ue),ve=fn(H=>H.addOpenPath),Se=fn(H=>H.removeOpenPath),le=fn(H=>H.removeOpenPathsByPrefix),T=fn(H=>H.removeExpandedPathsByPrefix),L=fn(H=>H.setSelectedPath),he=fn(H=>H.toggleExpandedPath),ge=fn(H=>H.expandPaths),z=i.useCallback(H=>{const De=Ks(H),$e=De.split("/"),Ge=$e[$e.length-1]||De,ct=Ge.includes(".")?Ge.split(".").pop()?.toLowerCase():void 0;return{name:Ge,path:De,type:"file",extension:ct}},[]),pe=i.useMemo(()=>Re.map(z),[Re,z]),Ae=i.useMemo(()=>{if(xe){const H=Hi(xe);if(Re.some(De=>Hi(De)===H))return xe}return Re[0]??null},[Re,xe]),G=i.useMemo(()=>Ae?z(Ae):null,[Ae,z]),ke=G?.path??"";i.useEffect(()=>{if(!b||!xe)return;const H=Hi(xe);Re.some($e=>Hi($e)===H)||L(b,Re[0]??null)},[Re,b,xe,L]);const Le=!!(b&&ke&&!Ea(ke,b)),Te=Le?Ed(ke):void 0,Z=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&Le,outsideFileGrant:Te,directory:b||void 0}),[t,Le,Te,b]),F=i.useRef(null),[re,te]=i.useState({left:!1,right:!1}),Ve=i.useCallback(()=>{const H=F.current;H&&te({left:H.scrollLeft>2,right:H.scrollLeft+H.clientWidth<H.scrollWidth-2})},[]),Ye=i.useRef(Ve);Ye.current=Ve,i.useEffect(()=>{const H=F.current;if(!H)return;const De=()=>Ye.current();De(),H.addEventListener("scroll",De,{passive:!0});const $e=new ResizeObserver(De);return $e.observe(H),()=>{H.removeEventListener("scroll",De),$e.disconnect()}},[pe.length]);const[Ke,Je]=i.useState({}),[nt,xt]=i.useState({}),jt=i.useRef(new Set),Mt=i.useRef(new Set),Et=i.useRef(new Map),Ut=i.useRef(0),[zt,Ht]=i.useState([]),[_t,Gt]=i.useState(!1),[Ce,Qe]=i.useState(""),{isPlaying:et,play:yt,stop:We}=rm(),[at,qe]=i.useState(!1),[lt,Dt]=i.useState(null),[us,Lt]=i.useState(""),es=i.useRef(""),[os,Qt]=i.useState(null),[Ft,Xt]=i.useState(""),[as,$t]=i.useState(!1),[bs,Cs]=i.useState(`
28
- `),Tt=i.useRef(null),Bt=i.useRef(null),vt=i.useRef(null),vs=i.useRef(""),hs=i.useRef(""),He=i.useRef(null),it=i.useRef(null),It=i.useRef(null),Rt=i.useRef(0),[Pt,ps]=i.useState("idle"),[ls,ns]=i.useState(!1),[Wt,ln]=i.useState(I1),[fs,Fs]=i.useState(!1),Ws=i.useRef(null),sn=i.useRef(null),An=i.useRef(null),vn=i.useRef(!1),be=i.useRef(null),Ze=i.useRef(null),dt=i.useRef(null),wt=i.useRef(null),[Vt,ht]=i.useState(0),cs=i.useRef(null),ds=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{cs.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(cs.current),cs.current=null)},[]);const[Ss,gs]=i.useState(null),[Ts,Fn]=i.useState(null),[_s,hn]=i.useState(""),[On,Zn]=i.useState(!1),[cn,Ue]=i.useState(null),[Jt,As]=i.useState(null),[Ps,$s]=i.useState(!1),[Qs,Us]=i.useState(!1),[Os,Ln]=i.useState(!1),fr=!!n.writeFile,Kn=!!n.createDirectory,ms=!!n.rename,Is=!!n.delete,jr=!!n.revealPath,Bn=wr(H=>H.availableApps),pn=wr(H=>H.isCacheStale),Nr=wr(H=>H.initialize),kr=wr(H=>H.loadInstalledApps);i.useEffect(()=>{Nr()},[Nr]);const Lr=i.useCallback(H=>{n.revealPath&&n.revealPath(H).catch(()=>{ce.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),Cr=i.useCallback(async H=>{if(!G?.path||await bp(G.path,H.id,H.appName)||await Sa(G.path,H.appName))return;const Ge=w1(G.path)||b;Ge&&await Sa(Ge,H.appName)||ce.error(e("filesView.toast.openInAppFailed",{app:H.appName}))},[b,G?.path,e]),nr=i.useCallback((H,De)=>{gs(H),Fn(De),hn(H==="rename"&&De.name||""),Zn(!1)},[]),[ws,dn]=i.useState(null),rr=i.useRef(!1),Y=i.useRef(null),[tt,pt]=i.useState(!1),St=Ee(H=>H.setMainTabGuard),Kt=Ee(H=>H.pendingFileNavigation),ts=Ee(H=>H.setPendingFileNavigation),is=Ee(H=>H.pendingFileFocusPath),Ls=Ee(H=>H.setPendingFileFocusPath),Gs=Ee(H=>H.shortcutOverrides),qn=Ee(H=>H.fileEditorKeymap),Vn=ss(H=>H.settingsDefaultFileViewerPreview),Qr=ss(H=>H.showMessageTTSButtons),gn=Ee(H=>H.expandedEditorToolbar);i.useEffect(()=>{const H=()=>{rr.current=!1,Y.current=null,pt(!1)};return document.addEventListener("mouseup",H),()=>document.removeEventListener("mouseup",H)},[]),i.useEffect(()=>()=>{be.current!==null&&window.clearTimeout(be.current),Ze.current!==null&&window.clearTimeout(Ze.current)},[]);const Jr=i.useCallback((H,De)=>{const $e=H.split(`
29
- `),Ge=Math.max(1,De.start),ct=Math.min($e.length,De.end);return Ge>ct?"":$e.slice(Ge-1,ct).join(`
30
- `)},[]),xn=Cm({source:"file",fileLabel:G?.path??null,language:G?.path&&Ii(G.path)||"text",getCodeForRange:H=>Jr(Ce,Am(H)),toStoreRange:H=>({startLine:H.start,endLine:H.end}),fromDraftRange:H=>({start:H.startLine,end:H.endLine})}),{drafts:nn,commentText:un,setCommentText:Sn,editingDraftId:jn,setSelection:mr,saveComment:ir,cancel:Ar,reset:gi,startEdit:or,deleteDraft:xi}=xn;i.useEffect(()=>{dn(null),gi(),St(null),Xt(""),$t(!1)},[G?.path,gi,St]),i.useEffect(()=>{mr(ws)},[ws,mr]),i.useEffect(()=>{if(!ws&&!jn)return;const H=$e=>{const Ge=$e.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]")||un.trim()||(dn(null),Ar())},De=setTimeout(()=>{document.addEventListener("click",H)},100);return()=>{clearTimeout(De),document.removeEventListener("click",H)}},[Ar,un,jn,ws]);const Br=i.useCallback((H,De)=>{const $e=De??ws??void 0;De&&dn(De),ir(H,$e),dn(null)},[ws,ir]),Xr=i.useCallback((H,De)=>{const $e=[];for(const Ge of De){if(!(Ge&&typeof Ge.name=="string"&&Ge.name.length>0)||!p&&Ge.name.startsWith(".")||!x&&C1(Ge.name))continue;const ct=Ge.name,rt=Ks(Ge.path||""),Zt=rt?j1(rt)?rt:Ks(`${H}/${rt}`):Ks(`${H}/${ct}`),js=Ge.isDirectory?"directory":"file",Ds=js==="file"&&ct.includes(".")?ct.split(".").pop()?.toLowerCase():void 0;$e.push({name:ct,path:Zt,type:js,extension:Ds})}return S1($e)},[x,p]),Dn=i.useCallback(async H=>{const De=Ks(H.trim());if(!De||jt.current.has(De)||Mt.current.has(De))return;Mt.current=new Set(Mt.current),Mt.current.add(De);const $e=Ut.current+1;Ut.current=$e,Et.current=new Map(Et.current),Et.current.set(De,$e);const Ge=()=>Et.current.get(De)===$e;await(n.listDirectory?n.listDirectory(De).then(rt=>rt.entries.map(Zt=>({name:Zt.name,path:Zt.path,isDirectory:Zt.isDirectory}))):Jn.listLocalDirectory(De).then(rt=>rt.map(Zt=>({name:Zt.name,path:Zt.path,isDirectory:Zt.isDirectory})))).then(rt=>{if(!Ge())return;const Zt=Xr(De,rt);jt.current=new Set(jt.current),jt.current.add(De),xt(js=>{if(!js[De])return js;const Ds={...js};return delete Ds[De],Ds}),Je(js=>({...js,[De]:Zt}))}).catch(rt=>{if(!Ge())return;const Zt=rt instanceof Error?rt.message:String(rt??"");if(Zt==="Directory not found"&&b&&De!==b){T(b,De),xt(js=>{if(!js[De])return js;const Ds={...js};return delete Ds[De],Ds});return}console.error("Failed to load files directory:",rt),xt(js=>({...js,[De]:Zt}))}).finally(()=>{Ge()&&(Et.current=new Map(Et.current),Et.current.delete(De),Mt.current=new Set(Mt.current),Mt.current.delete(De))})},[n,Xr,T,b]),ar=i.useCallback(async()=>{b&&(jt.current=new Set,Mt.current=new Set,Et.current=new Map,xt({}),Je(H=>Object.keys(H).length===0?H:{}),await Dn(b))},[Dn,b]),Js=i.useCallback(async H=>{if(!H){await ar();return}const De=Ks(H);jt.current=new Set(jt.current),jt.current.delete(De),Mt.current=new Set(Mt.current),Mt.current.delete(De),await Dn(De)},[Dn,ar]),Hs=i.useRef(""),Vr=i.useRef("");i.useEffect(()=>{if(!b)return;const H=`${b}|h${p?"1":"0"}|g${x?"1":"0"}`,De=Hs.current!==b,$e=Vr.current!==H;!De&&!$e||(De&&(Hs.current=b,Qe(""),Dt(null),Lt(""),Qt(null),O(!1)),$e&&(Vr.current=H,jt.current=new Set,Mt.current=new Set,Et.current=new Map,xt({}),Je(Ge=>Object.keys(Ge).length===0?Ge:{}),Dn(b)))},[Dn,b,x,p]),i.useEffect(()=>{if(!n.listDirectory)return;const H=()=>{if(!document.hidden&&oe.length>0)for(const De of oe)Js(De)};return document.addEventListener("visibilitychange",H),()=>document.removeEventListener("visibilitychange",H)},[oe,n.listDirectory,Js]),i.useEffect(()=>{if(!n.listDirectory||oe.length===0)return;const H=setInterval(()=>{if(!document.hidden)for(const De of oe)Js(De)},8e3);return()=>clearInterval(H)},[oe,n.listDirectory,Js]);const Oi=i.useCallback(async H=>{if(H?.preventDefault(),!Ts||!Ss)return;Zn(!0);const De=()=>{gs(null)},$e=ct=>{ce.error(ct)},Ge=()=>{Zn(!1)};if(Ss==="createFile"){if(!_s.trim()){$e(e("sidebarFilesTree.toast.filenameRequired")),Ge();return}if(!n.writeFile){$e(e("sidebarFilesTree.toast.writeNotSupported")),Ge();return}const ct=Ts.path,rt=ct?`${ct}/`:"",Zt=Ks(`${rt}${_s.trim()}`);await n.writeFile(Zt,"").then(async js=>{js.success&&(ce.success(e("sidebarFilesTree.toast.fileCreated")),await Js(ct)),De()}).catch(()=>$e(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(Ss==="createFolder"){if(!_s.trim()){$e(e("sidebarFilesTree.toast.folderNameRequired")),Ge();return}const ct=Ts.path,rt=ct?`${ct}/`:"",Zt=Ks(`${rt}${_s.trim()}`);await n.createDirectory(Zt).then(async js=>{js.success&&(ce.success(e("sidebarFilesTree.toast.folderCreated")),await Js(ct)),De()}).catch(()=>$e(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(Ss==="rename"){if(!_s.trim()){$e(e("sidebarFilesTree.toast.nameRequired")),Ge();return}if(!n.rename){$e(e("sidebarFilesTree.toast.renameNotSupported")),Ge();return}const ct=Ts.path,rt=ct.split("/").slice(0,-1).join("/"),Zt=rt?`${rt}/`:"",js=Ks(`${Zt}${_s.trim()}`);await n.rename(ct,js).then(async Ds=>{Ds.success&&(ce.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await Js(rt),b&&le(b,ct),(G?.path===ct||G?.path.startsWith(`${ct}/`))&&(b&&L(b,null),Qe(""),Dt(null),Lt(""),Qt(null),d&&O(!1))),De()}).catch(()=>$e(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(Ss==="delete"){if(!n.delete){$e(e("sidebarFilesTree.toast.deleteNotSupported")),Ge();return}const ct=Ts.path,rt=ct.split("/").slice(0,-1).join("/");await n.delete(ct).then(async Zt=>{Zt.success&&(ce.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await Js(rt),b&&le(b,ct),(G?.path===ct||G?.path.startsWith(`${ct}/`))&&(b&&L(b,null),Qe(""),Dt(null),Lt(""),Qt(null),d&&O(!1))),De()}).catch(()=>$e(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}Ge()},[Ss,Ts,_s,n,Js,d,le,b,G?.path,L,e]);i.useEffect(()=>{if(!y){Ht([]),Gt(!1);return}const H=k.trim();if(!H){Ht([]),Gt(!1);return}let De=!1;return Gt(!0),C(y,H,150,{includeHidden:p,respectGitignore:!x,type:"file"}).then($e=>{if(De)return;const ct=$e.filter(rt=>x||!A1(rt.path)).map(rt=>({name:rt.name,path:Ks(rt.path),type:"file",extension:rt.extension,relativePath:rt.relativePath}));Ht(ct)}).catch(()=>{De||Ht([])}).finally(()=>{De||Gt(!1)}),()=>{De=!0}},[y,k,C,p,x]);const Zr=i.useCallback(async(H,De)=>{if(n.readFile)return(await n.readFile(H,{...De??{},directory:b||void 0})).content??"";const $e=new URLSearchParams({path:H});De?.allowOutsideWorkspace&&$e.set("allowOutsideWorkspace","true"),De?.outsideFileGrant&&$e.set("outsideFileGrant",De.outsideFileGrant),De?.optional&&$e.set("optional","true"),b&&$e.set("directory",b);const Ge=await Ns(`/api/fs/read?${$e.toString()}`,{cache:De?.optional?"no-store":"default"});if(!Ge.ok){const ct=await Ge.json().catch(()=>({error:Ge.statusText}));throw new Error(ct.error||e("filesView.error.readFileFailed"))}return Ge.text()},[n,b,e]),hr=i.useCallback(async(H,De)=>{if(n.statFile){const $e=await n.statFile(H,{...De??{},directory:b||void 0});return{path:$e.path,size:$e.size,mtimeMs:$e.mtimeMs}}return null},[n,b]);i.useEffect(()=>{if(!b||!n.statFile||Re.length===0)return;let H=!1;const De=[...Re];return Promise.all(De.map(async $e=>{try{const Ge=await n.statFile?.($e,{directory:b||void 0});!H&&Ge&&!Ge.isFile&&le(b,$e)}catch(Ge){!H&&Uu(Ge)&&le(b,$e)}})),()=>{H=!0}},[n,Re,le,b]);const bi=i.useMemo(()=>Ce.length>bo?`${Ce.slice(0,bo)}
31
-
32
- … truncated …`:Ce,[Ce]),bn=Ft!==bi,pr=i.useCallback(async()=>{if(!G||!n.writeFile)return ce.error(e("filesView.toast.savingNotSupported")),!1;if(!bn)return!0;if(Ft===""&&Ce!==""&&os!==G.path)return console.warn(`[saveDraft] refusing to save empty draft for "${G.path}" (${Ce.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;$t(!0);try{const H=P1(Ft,bs);return(await n.writeFile(G.path,H))?.success?(Qe(Ft),G?.path&&Md(G.path)&&(vs.current=Ft,hs.current=Ft),hr(G.path).then($e=>{$e&&(It.current=$e)}).catch(()=>{}),!0):(ce.error(e("filesView.toast.writeFileFailed")),!1)}catch(H){return ce.error(H instanceof Error?H.message:e("filesView.toast.saveFailed")),!1}finally{$t(!1)}},[Ft,Ce,n,bn,bs,os,hr,G,e]);i.useEffect(()=>{if(!bn){St(null);return}const H=De=>vn.current?(vn.current=!1,!0):(Fs(!0),sn.current=De,!1);return St(H),()=>{Ee.getState().mainTabGuard===H&&St(null)}},[bn,St]),i.useEffect(()=>{try{window.localStorage.setItem(Xm,Wt?"true":"false")}catch{}},[Wt]),i.useEffect(()=>{Wt||(ps("idle"),Bt.current&&(clearTimeout(Bt.current),Bt.current=null))},[Wt]);const _r=1500;i.useEffect(()=>{const H=!!(G&&n.writeFile);if(!(!Wt||!bn||!H||as))return Bt.current=setTimeout(()=>{pr().then(De=>{De&&(ps("saved"),setTimeout(()=>ps("idle"),2e3))})},_r),()=>{Bt.current&&(clearTimeout(Bt.current),Bt.current=null)}},[Wt,Ft,bn,G,n.writeFile,as,pr]),i.useEffect(()=>{ps("idle")},[G?.path]),i.useEffect(()=>{const H=De=>{wc(De)&&(De.key.toLowerCase()==="s"?(De.preventDefault(),Bt.current&&(clearTimeout(Bt.current),Bt.current=null),as||pr().then($e=>{$e&&(ps("saved"),setTimeout(()=>ps("idle"),2e3))})):De.key.toLowerCase()==="f"&&(De.preventDefault(),P(!0)))};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[as,pr]);const yi=i.useCallback(async H=>{const De=Rt.current+1;Rt.current=De;const $e=()=>{if(!b)return!1;const Ds=fn.getState().byRoot[b],xr=Ds?.selectedPath??Ds?.openPaths[0]??null;return Rt.current===De&&xr===H.path};Dt(null),Lt(""),Qt(null);const Ge=Ri(H.path),ct=H.path.toLowerCase().endsWith(".svg"),rt=Fd(H.path);if(d&&O(!0),r.isDesktop&&Ge&&!ct){Qe(""),Xt(""),qe(!0);return}if(!r.isDesktop&&Ge&&!ct){Qe(""),Xt(""),Qt(H.path),qe(!1);return}if(rt){Qe(""),Xt(""),Qt(H.path),qe(!1);return}qe(!0);const Zt=Ed(H.path),js={allowOutsideWorkspace:t==="editor-only"&&!!b&&!Ea(H.path,b),outsideFileGrant:Zt};await Zr(H.path,js).then(Ds=>{if(!$e())return;const xr=Zm(Ds);Cs(T1(Ds)),Qe(xr),vs.current=xr,hs.current=xr,Xt(xr.length>bo?`${xr.slice(0,bo)}
33
-
34
- … truncated …`:xr),Qt(H.path),hr(H.path,js).then(lr=>{lr&&$e()&&(It.current=lr)}).catch(()=>{})}).catch(Ds=>{if($e()){if(D1(Ds)){if(qe(!1),b&&L(b,null),Dt(null),Qe(""),Xt(""),Qt(null),It.current=null,S.trim().length>0&&N(""),d&&O(!1),b){const lr=[...zu(H.path,b),H.path];lr.length>0&&ge(b,lr);for(const rl of lr)jt.current.has(rl)||Dn(rl)}return}if(Uu(Ds)){b&&le(b,H.path),Qe(""),Xt(""),Dt(null),It.current=null,d&&O(!1);return}Qe(""),Xt(""),Dt(Ds instanceof Error?Ds.message:e("filesView.error.readFileFailed")),It.current=null}}).finally(()=>{$e()&&qe(!1)})},[ge,d,Dn,t,Zr,hr,le,b,r.isDesktop,S,L,e]),$r=i.useCallback(async(H,De)=>{if(!b)return;const $e=zu(H,b),Ge=De?[...$e,H]:$e;Ge.length>0&&ge(b,Ge);const ct=Ge.map(rt=>{if(!jt.current.has(rt))return Dn(rt)}).filter(Boolean);await Promise.all(ct)},[ge,Dn,b]),Li=i.useCallback((H,De)=>{const $e=De.findIndex(Ge=>Ge.path===H);return $e===-1||De.length<=1?null:De[$e+1]??De[$e-1]??null},[]),rn=i.useCallback(async H=>{if(vn.current)vn.current=!1;else if(bn){Fs(!0),Ws.current=H;return}b&&(L(b,H.path),ve(b,H.path),$r(H.path,!1)),Dt(null),Lt(""),Qe(""),vs.current="",hs.current="",Xt(""),Qt(null),d&&O(!0)},[ve,$r,bn,d,b,L]);i.useEffect(()=>{G?.path&&$r(G.path,!1)},[$r,G?.path]),i.useEffect(()=>{if(!G){Rt.current+=1,qe(!1);return}os!==G.path&&yi(G)},[yi,os,G]);const wi=i.useRef(bn);wi.current=bn,i.useEffect(()=>{if(!G?.path||os!==G.path)return;let H=!1;const De=window.setInterval(()=>{document.hidden||hr(G.path,Z).then($e=>{if(H||!$e)return;const Ge=It.current;if(!Ge||Ge.path!==G.path){It.current=$e;return}const ct=$e.mtimeMs!==void 0&&Ge.mtimeMs!==void 0&&$e.mtimeMs!==Ge.mtimeMs,rt=$e.size!==Ge.size;!ct&&!rt||wi.current||(It.current=$e,Qt(null))}).catch(()=>{})},2e3);return()=>{H=!0,window.clearInterval(De)}},[os,hr,G?.path,Z]);const Bi=i.useCallback(()=>{const H=Ws.current,De=sn.current,$e=An.current;if(Ws.current=null,sn.current=null,An.current=null,vn.current=!0,Fs(!1),Xt(bi),$e){b&&Se(b,$e),G?.path===$e&&(H?rn(H):(b&&L(b,null),Qe(""),Dt(null),Lt(""),Qt(null),d&&O(!1)));return}if(H){rn(H);return}De&&(St(null),Ee.getState().setActiveMainTab(De))},[bi,rn,d,Se,b,G?.path,St,L]),mo=i.useCallback(async()=>{const H=Ws.current,De=sn.current,$e=An.current;if(!await pr()){vn.current=!1;return}if(Ws.current=null,sn.current=null,An.current=null,vn.current=!0,Fs(!1),$e){b&&Se(b,$e),G?.path===$e&&(H?await rn(H):(b&&L(b,null),Qe(""),Dt(null),Lt(""),Qt(null),d&&O(!1)));return}if(H){await rn(H);return}De&&(St(null),Ee.getState().setActiveMainTab(De))},[rn,d,Se,b,pr,G?.path,St,L]),Q=i.useCallback(H=>{const De=G?.path===H,$e=Li(H,pe);if(De&&bn){Fs(!0),Ws.current=$e,An.current=H;return}if(b&&Se(b,H),!!De){if($e){rn($e);return}b&&L(b,null),Qe(""),Dt(null),Lt(""),Qt(null),d&&O(!1)}},[Li,rn,bn,d,pe,Se,b,G?.path,L]),Ne=i.useCallback(H=>{if(Re.includes(H))return"open";if(w?.files){const De=H.startsWith(b+"/")?H.slice(b.length+1):H,$e=w.files.find(Ge=>Ge.path===De);if($e){if($e.index==="A"||$e.working_dir==="?")return"git-added";if($e.index==="D")return"git-deleted";if($e.index==="M"||$e.working_dir==="M")return"git-modified"}}return null},[Re,w,b]),Pe=i.useCallback(H=>{if(!w?.files)return null;const De=H.startsWith(b+"/")?H.slice(b.length+1):H,$e=De?`${De}/`:"";let Ge=0,ct=0;for(const rt of w.files)rt.path.startsWith($e)&&((rt.index==="M"||rt.working_dir==="M")&&Ge++,(rt.index==="A"||rt.working_dir==="?")&&ct++);return Ge+ct>0?{modified:Ge,added:ct}:null},[w,b]),_e=i.useCallback(async H=>{const De=Ks(H);b&&(he(b,De),jt.current.has(De)||await Dn(De))},[Dn,b,he]),ut=i.useMemo(()=>({canRename:ms,canCreateFile:fr,canCreateFolder:Kn,canDelete:Is,canReveal:jr}),[ms,fr,Kn,Is,jr]);function Nt(H,De){const $e=Ke[H]??[];return $e.map((Ge,ct)=>{const rt=Ge.type==="directory",Zt=rt&&oe.includes(Ge.path),js=G?.path===Ge.path,Ds=ct===$e.length-1;return s.jsxs("li",{className:"relative",children:[De>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ds&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(E1,{node:Ge,root:b,isExpanded:Zt,isActive:js,isMobile:d,alwaysShowActions:u,status:rt?void 0:Ne(Ge.path),badge:rt?Pe(Ge.path):void 0,permissions:ut,downloadFile:n.downloadFile,contextMenuPath:cn,setContextMenuPath:Ue,rightClickMenuPath:Jt,setRightClickMenuPath:As,onSelect:rn,onToggle:_e,onRevealPath:Lr,onOpenDialog:nr}),rt&&Zt&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[nt[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:nt[Ge.path],children:nt[Ge.path]}),s.jsxs(ze,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Js(Ge.path)},children:[s.jsx(A,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,Nt(Ge.path,De+1)]})]},Ge.path)})}const qt=!!(G?.path&&Ri(G.path)),Yt=!!(G?.path&&G.path.toLowerCase().endsWith(".svg")),ys=!!(G?.path&&Fd(G.path)),gr=i.useMemo(()=>Ks(Kt?.path??""),[Kt?.path]),Dr=!!(Kt&&gr&&ke&&ke===gr&&!at&&!lt&&!qt&&!ys),Tr=i.useMemo(()=>tc(b,ke),[ke,b]),Xa=!!(G&&(!qt||Yt)&&!ys&&Ce.length>0),Za=!!(G&&Tr.length>0),X=!!(G&&!Le&&!qt&&!ys&&n.writeFile&&Ce.length<=bo),ot=!!(G?.path&&Hu(G.path)),st=!!(G?.path&&R1(G.path)),gt=!!(G?.path&&Zo(G.path)),Ot=!!(G?.path&&Md(G.path)),on=!!(G&&!qt&&!ys)&&!ot&&!Ot&&!(gt&&se==="preview"),yn=i.useMemo(()=>ke?im(ke):null,[ke]),[Nn,kn]=i.useState(null);i.useEffect(()=>{let H=!1;const De=G?.path;if(!De||yn){kn(null);return}return kn(null),Sg(De).then($e=>{H||kn($e)}),()=>{H=!0}},[G?.path,yn]),i.useEffect(()=>{!X&&J==="edit"&&U("view")},[X,J]);const _n="openchamber:files:md-viewer-mode",ei="openchamber:files:html-viewer-mode",vi="openchamber:files:json-viewer-mode";i.useEffect(()=>{const H=G?.path;if(!H)return;const De=Vn?"view":"edit";U(q.current[H]??De);let $e=Vn?"preview":"edit";try{const rt=localStorage.getItem(_n);(rt==="preview"||rt==="edit")&&($e=rt)}catch{}ae(me.current[H]??$e);let Ge=Vn?"preview":"edit";try{const rt=localStorage.getItem(ei);(rt==="preview"||rt==="edit")&&(Ge=rt)}catch{}we(je.current[H]??Ge),Me(Oe.current[H]??"preview");let ct=Vn?"tree":"text";try{const rt=localStorage.getItem(vi);(rt==="tree"||rt==="text")&&(ct=rt)}catch{}ye(ct)},[G?.path,Vn]);const ho=i.useCallback(H=>{const De=G?.path;De&&(q.current[De]=H),U(H)},[G?.path]),Ph=i.useCallback(H=>{const De=G?.path;De&&(me.current[De]=H),ae(H);try{localStorage.setItem(_n,H)}catch{}},[G?.path]),po=i.useCallback(()=>ee,[ee]),Ih=i.useCallback(H=>{ye(H);try{localStorage.setItem(vi,H)}catch{}},[]),Rh=i.useCallback(H=>{const De=G?.path;De&&(je.current[De]=H),we(H);try{localStorage.setItem(ei,H)}catch{}},[G?.path]),Eh=i.useCallback(H=>{const De=G?.path;if(De&&(Oe.current[De]=H),vt.current&&(clearTimeout(vt.current),vt.current=null),He.current!==null&&(cancelAnimationFrame(He.current),He.current=null),H==="edit")Xt(vs.current||Ce),Me(H);else{vs.current=Ft;const $e=De;Me("edit"),He.current=requestAnimationFrame(()=>{He.current=requestAnimationFrame(()=>{He.current=null,!(b&&$e&&fn.getState().byRoot[b]?.selectedPath!==$e)&&(K(Ge=>Ge+1),Me("preview"))})});return}},[Ft,Ce,b,G?.path]),el=i.useCallback(async(H,De)=>{if(!n.writeFile||De===hs.current)return!1;if(!(await n.writeFile(H,De))?.success)return ce.error(e("filesView.toast.writeFileFailed")),!1;vs.current=De,hs.current=De,Xt(De);const Ge=await hr(H,Z).catch(()=>null);return Ge&&(It.current=Ge),!0},[n,hr,Z,e]);i.useEffect(()=>()=>{vt.current&&(clearTimeout(vt.current),vt.current=null),He.current!==null&&(cancelAnimationFrame(He.current),He.current=null)},[fe,G?.path]);const Mh=i.useCallback(H=>{if(vs.current=H,!G?.path||fe!=="preview"||!n.writeFile)return;vt.current&&clearTimeout(vt.current);const De=G.path;vt.current=setTimeout(()=>{vt.current=null,el(De,H).then($e=>{$e&&(ns(!0),setTimeout(()=>ns(!1),1500))}).catch($e=>{ce.error($e instanceof Error?$e.message:e("filesView.toast.saveFailed"))})},_r)},[fe,n.writeFile,el,G?.path,e]),Fh=i.useMemo(()=>Ot&&(vs.current||Ft)||Ce,[Ft,Ce,Ot]),Qc=i.useCallback(()=>se,[se]);i.useEffect(()=>{const H=$e=>{const Ge=$e?"view":"edit",ct=$e?"preview":"edit",rt=$e?"tree":"text";for(const Zt of Re)q.current[Zt]=Ge,Hu(Zt)&&(me.current[Zt]=ct),Zo(Zt)&&(je.current[Zt]=ct);U(Ge),ae(ct),we(ct),ye(rt);try{localStorage.setItem(_n,ct),localStorage.setItem(ei,ct),localStorage.setItem(vi,rt)}catch{}},De=$e=>{const Ge=!!$e.detail?.enabled;H(Ge)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",De),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",De)}},[Re]),i.useEffect(()=>{if(!Kt||!b)return;const H=()=>{typeof window>"u"||cs.current===null&&(cs.current=window.requestAnimationFrame(()=>{cs.current=null,ht(zr=>zr+1)}))},De=(zr,Si)=>{if(zr.state.doc.length!==Si.length)return!1;if(Si.length===0)return!0;const il=Math.min(128,Si.length);if(zr.state.sliceDoc(0,il)!==Si.slice(0,il))return!1;const fd=Math.max(0,Si.length-il);return zr.state.sliceDoc(fd,Si.length)===Si.slice(fd)},$e=Ks(Kt.path);if(!$e){ts(null),ds.current={key:"",attempts:0};return}const Ge=`${$e}:${Kt.line}:${Kt.column??1}`;if(ds.current.key!==Ge&&(ds.current={key:Ge,attempts:0}),G?.path!==$e){if(fs)return;rn(z($e));return}if(at||os!==$e)return;if(lt||qt||ys){ts(null),ds.current={key:"",attempts:0};return}if(!X)return;if(J!=="edit"){U("edit");return}const ct=dt.current;if(!ct){H();return}if(!De(ct,Ft)){H();return}const rt=Math.max(1,Math.min(Kt.line,ct.state.doc.lines)),Zt=ct.state.doc.line(rt),js=Math.max(1,Kt.column||1),Ds=Math.max(0,Zt.to-Zt.from),xr=Math.min(Ds,js-1),lr=Zt.from+xr;if(!(ct.state.selection.main.head===lr)||ds.current.attempts===0){ds.current.attempts+=1,ct.dispatch({selection:{anchor:lr},effects:ai.scrollIntoView(lr,{y:"center"})}),ct.focus(),H();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const zr=dt.current;zr&&(zr.dispatch({selection:{anchor:lr},effects:ai.scrollIntoView(lr,{y:"center"})}),zr.focus())}),ts(null),ds.current={key:"",attempts:0}},[X,fs,Ft,Vt,lt,at,qt,ys,os,rn,Kt,b,G?.path,ts,J,z]),i.useEffect(()=>{if(!is||!b)return;const H=Ks(is);if(!H){Ls(null);return}if(G?.path!==H){if(fs)return;rn(z(H));return}if(!(at||os!==H||lt||qt||ys)){if(X&&J==="edit"){const De=dt.current;if(!De)return;De.focus()}Ls(null)}},[X,fs,lt,at,rn,qt,ys,os,is,b,G?.path,Ls,J,z]);const Vi=i.useCallback(H=>{if(!d||!H||!H.hasFocus||typeof window>"u")return;const De=window.visualViewport;if(!De)return;const $e=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,$e-(De.offsetTop+De.height))<=0)return;const ct=H.state.selection.main.head,rt=H.coordsAtPos(ct);if(!rt)return;const Zt=Math.round(De.offsetTop+De.height),Ds=rt.bottom+20-Zt;Ds<=0||(H.scrollDOM.scrollTop+=Ds)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const H=()=>{window.requestAnimationFrame(()=>{Vi(dt.current)})},De=window.visualViewport;return De?.addEventListener("resize",H),De?.addEventListener("scroll",H,{passive:!0}),document.addEventListener("selectionchange",H),()=>{De?.removeEventListener("resize",H),De?.removeEventListener("scroll",H),document.removeEventListener("selectionchange",H)}},[d,Vi]),i.useEffect(()=>{if(!X||J!=="edit"||d)return;const H=ci("open_go_to_line",Gs),De=$e=>{const Ge=$e.target;if(Ge?.closest('[role="dialog"]'))return;const ct=!!Ge?.closest(".cm-editor");Ge?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!ct||!document.activeElement?.closest(".cm-editor")||oa($e,H)&&($e.preventDefault(),Ln(!0))};return window.addEventListener("keydown",De),()=>window.removeEventListener("keydown",De)},[X,d,Gs,J]);const Jc=i.useMemo(()=>{if(!G?.path)return[Gl(o)];const H=Ii(G.path),De=[Gl(o,H?{syntaxColors:!1}:void 0)],$e=yn??Nn;return $e&&De.push($e),H&&De.push(Dm({language:H,themeName:o.metadata.id,theme:om(o)})),v&&De.push(ai.lineWrapping),d&&De.push(ai.updateListener.of(Ge=>{Ge.view.hasFocus&&(Ge.selectionSet||Ge.focusChanged||Ge.viewportChanged||Ge.geometryChanged)&&window.requestAnimationFrame(()=>{Vi(Ge.view)})})),De},[o,G?.path,yn,Nn,v,d,Vi]),Xc=i.useMemo(()=>({light:Be.metadata.id,dark:Fe.metadata.id}),[Be.metadata.id,Fe.metadata.id]),_o=G?.path&&qt&&!r.isDesktop&&!Yt?`${G.path}|${Z.allowOutsideWorkspace?"outside":"workspace"}|${Z.outsideFileGrant??""}`:"",$o=G?.path&&ys?`${G.path}|${Z.allowOutsideWorkspace?"outside":"workspace"}|${Z.outsideFileGrant??""}`:"",zo=G?.path&&gt&&se==="preview"&&!r.isVSCode?G.path:"",tl=e("filesView.error.readFileFailed"),{readyKey:Zc,nonce:ed}=Al(_o,Dt,tl),{readyKey:td,nonce:Oh}=Al(zo,Dt,tl),{readyKey:sd,nonce:nd}=Al($o,Dt,tl),rd=!!(_o&&Zc!==_o),Lh=!!(zo&&td!==zo),id=!!($o&&sd!==$o),od=G?.path&&qt?r.isDesktop?Yt?`data:${Od(G.path)};utf8,${encodeURIComponent(Ce)}`:us:Yt?`data:${Od(G.path)};utf8,${encodeURIComponent(Ce)}`:Zc===_o?Pi().authenticatedAsset("/api/fs/raw",{path:G.path,allowOutsideWorkspace:Z.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Z.outsideFileGrant,directory:b||void 0}):"":"",ad=G?.path&&ys&&sd===$o?Pi().authenticatedAsset("/api/fs/raw",{path:G.path,allowOutsideWorkspace:Z.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Z.outsideFileGrant,directory:b||void 0}):"",ld=i.useCallback(H=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:ad,className:"h-full w-full border-0",title:H.name},nd)}),[ad,nd]);i.useEffect(()=>{let H=!1;return(async()=>{if(!r.isDesktop||!G?.path||!qt||Yt){es.current&&(URL.revokeObjectURL(es.current),es.current=""),Lt("");return}Dt(null),es.current&&(URL.revokeObjectURL(es.current),es.current=""),await(n.readFileBinary?n.readFileBinary(G.path,Z).then(Ge=>Ge.dataUrl):(async()=>{const Ge=await Ns("/api/fs/raw",{query:{path:G.path,allowOutsideWorkspace:Z.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Z.outsideFileGrant,directory:b||void 0}});if(!Ge.ok)throw new Error(e("filesView.error.readFileFailed"));const ct=await Ge.blob(),rt=URL.createObjectURL(ct);return H?(URL.revokeObjectURL(rt),""):(es.current=rt,rt)})()).then(Ge=>{H||(Lt(Ge),Qt(G.path))}).catch(Ge=>{es.current&&(URL.revokeObjectURL(es.current),es.current=""),H||(Lt(""),Dt(Ge instanceof Error?Ge.message:e("filesView.error.readFileFailed")),Qt(null))}).finally(()=>{H||qe(!1)})})(),()=>{H=!0}},[n,qt,Yt,b,r.isDesktop,G?.path,Z,e]),i.useEffect(()=>()=>{es.current&&(URL.revokeObjectURL(es.current),es.current="")},[]);const Bh=i.useCallback(()=>gs(null),[]),Vh=i.useMemo(()=>Im({drafts:nn,editingDraftId:jn,commentText:un,onTextChange:Sn,selection:ws,isDragging:tt,fileLabel:G?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:H=>({start:H.startLine,end:H.endLine}),onSave:Br,onCancel:()=>{dn(null),Ar()},onEdit:H=>{or(H),dn({start:H.startLine,end:H.endLine})},onDelete:xi}),[Ar,un,xi,jn,nn,Br,tt,ws,G?.path,Sn,or]),cd=i.useCallback((H,De)=>s.jsx("div",{className:"h-full",children:s.jsx(Yh,{file:{name:H.name,contents:De,lang:Ii(H.path)||void 0},options:{disableFileHeader:!0,overflow:v?"wrap":"scroll",theme:Xc,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,Xc,v]),sl=({exitFullscreenOnly:H=!1,layout:De="floating"}={})=>{if(!G)return null;const Ge=De==="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",ct=(rt,Zt)=>s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:Zt})}),s.jsx(At,{side:"bottom",sideOffset:6,children:rt})]});return s.jsxs("div",{className:Ge,children:[X&&J==="edit"&&s.jsxs(s.Fragment,{children:[as?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):Wt&&Pt==="saved"&&!bn?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(A,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):bn?ct(e(Wt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${ll()}+S`}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{pr()},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(Wt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${ll()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${ll()}+S`}),children:s.jsx(A,{name:"save-3",className:"size-4"})})):null,ct(e(Wt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>ln(rt=>!rt),className:Ie("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",Wt?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(Wt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(Wt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:Wt?s.jsx(A,{name:"file-check-fill",className:"size-4"}):s.jsx(A,{name:"file-check",className:"size-4"})}))]}),s.jsxs(tn,{onOpenChange:ne,children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Zs,{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(A,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(en,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Bn.map(rt=>s.jsxs(xs,{className:"flex items-center gap-2",onClick:()=>{Cr(rt)},children:[s.jsx(v1,{label:rt.label,iconDataUrl:rt.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:rt.label})]},rt.id)),pn?s.jsxs(xs,{className:"flex items-center gap-2",onClick:()=>{kr(!0)},children:[s.jsx(A,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!qt&&!ys&&s.jsxs(s.Fragment,{children:[ct(e(v?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>M(!v),className:Ie("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",v?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(v?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(A,{name:"text-wrap",className:"size-4"})})),J==="edit"&&s.jsxs(s.Fragment,{children:[ct(e("filesView.editor.findInFile"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:rt=>{P(!B),rt.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(A,{name:"search",className:"size-4"})})),ct(e("filesView.editor.goToLine"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:rt=>{Ln(Zt=>!Zt),rt.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(A,{name:"menu-fold-2",className:"size-4"})})),s.jsx(x1,{open:Os,onOpenChange:Ln,view:dt.current,variant:"inline"})]})]}),on&&X&&!st&&!gt&&s.jsx(la,{currentMode:J==="view"?"preview":"edit",onToggle:()=>{ho(J==="view"?"edit":"view")}}),(ot||Zo(G?.path??""))&&s.jsx(la,{currentMode:ot?po():Qc(),onToggle:()=>{Zo(G?.path??"")?Rh(Qc()==="preview"?"edit":"preview"):Ph(po()==="preview"?"edit":"preview")}}),ot&&po()==="preview"&&Qr&&s.jsxs(kt,{children:[s.jsx(Ct,{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(et?"filesView.tts.stopSpeaking":"filesView.tts.readAloud"),onClick:()=>{et?We():Ce.trim()&&yt(Ce)},children:et?s.jsx(A,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"volume-up",className:"size-4"})})}),s.jsx(At,{sideOffset:8,children:e(et?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),Ot&&s.jsxs(s.Fragment,{children:[s.jsx(la,{currentMode:fe,onToggle:()=>Eh(fe==="preview"?"edit":"preview")}),fe==="preview"&&s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{const rt=it.current?.getXml();if(vt.current&&(clearTimeout(vt.current),vt.current=null),G?.path&&rt){if(!await el(G.path,rt))return;ns(!0),setTimeout(()=>ns(!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:ls?s.jsx(A,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"save-3",className:"size-4"})})]}),st&&ct(e(de==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>Ih(de==="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(de==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:de==="tree"?s.jsx(A,{name:"code-sslash",className:"size-4"}):s.jsx(A,{name:"node-tree",className:"size-4"})})),Xa&&ct(e("filesView.editor.copyFileContents"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await dr(Ce)).ok?($s(!0),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{$s(!1)},1200)):ce.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:Ps?s.jsx(A,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"clipboard",className:"size-4"})})),Za&&ct(e("filesView.editor.copyFilePathTitle",{path:Tr}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await dr(Tr)).ok?(Us(!0),Ze.current!==null&&window.clearTimeout(Ze.current),Ze.current=window.setTimeout(()=>{Us(!1)},1200)):ce.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:Tr}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:Tr}),children:Qs?s.jsx(A,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&&ct(e("filesView.editor.saveFile"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{const rt=n.downloadFile;rt&&rt(G.path).catch(Zt=>{console.error("Download failed:",Zt),ce.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(A,{name:"download",className:"size-4"})})),H?ct(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(A,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&&ct(e(I?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>E(!I),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(I?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(I?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:I?s.jsx(A,{name:"fullscreen-exit",className:"size-4"}):s.jsx(A,{name:"fullscreen",className:"size-4"})}))]})},nl=s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[s.jsx(Ms,{open:fs,onOpenChange:H=>{H||Fs(!0)},children:s.jsxs(Es,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(Ys,{children:[s.jsx(zs,{children:e("filesView.unsaved.title")}),s.jsx(an,{children:e("filesView.unsaved.description")})]}),s.jsxs(ur,{children:[s.jsx(ze,{variant:"outline",onClick:()=>{mo()},disabled:as,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:Bi,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:Ie("flex flex-col flex-shrink-0",g&&"border-b border-border/40"),children:[g?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&D&&s.jsx("button",{type:"button",onClick:()=>O(!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(A,{name:"arrow-left-s",className:"size-5"})}),d?G?s.jsxs(tn,{children:[s.jsx(Zs,{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(Kr,{filePath:G.path,extension:G.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Wu,{name:G.name}),s.jsx(A,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(en,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:pe.map(H=>{const De=G?.path===H.path;return s.jsxs(xs,{onSelect:$e=>{if($e.target.closest("[data-close-open-file]")){$e.preventDefault();return}De||rn(H)},className:Ie("flex min-w-0 items-center justify-between gap-2 overflow-hidden",De&&"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(Kr,{filePath:H.path,extension:H.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Wu,{name:H.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:$e=>{$e.preventDefault(),$e.stopPropagation()},onClick:$e=>{$e.preventDefault(),$e.stopPropagation(),Q(H.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:H.name}),children:s.jsx(A,{name:"close",className:"size-3.5"})})]},H.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):pe.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[re.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"}),re.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:F,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:pe.map(H=>{const De=G?.path===H.path;return s.jsxs("div",{title:tc(b,H.path),className:Ie("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",De?"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(Kr,{filePath:H.path,extension:H.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{De||rn(H)},className:"max-w-[12rem] truncate text-left",children:H.name}),s.jsx("button",{type:"button",onClick:$e=>{$e.stopPropagation(),Q(H.path)},className:Ie("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!De&&!u&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:H.name}),children:s.jsx(A,{name:"close",className:"size-3.5"})})]},H.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,gn&&!d&&G?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:[Tr?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Tr,children:Tr}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:sl({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[G&&!B&&!(gn&&!d)&&s.jsx("div",{ref:V,className:"absolute right-3 top-3 z-30",onMouseEnter:()=>_(!0),onMouseLeave:()=>{R.current>0||_(!1)},children:W?sl():s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>_(!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(A,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})}),s.jsx(En,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:G?at||rd||id?h?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(A,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.loading")]}):lt?s.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:lt}):qt?s.jsx("div",{className:"flex h-full items-center justify-center p-3",children:s.jsx("img",{src:od,alt:G?.name??e("filesView.editor.imageAltFallback"),className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},ed)}):ys?ld(G):G&&Ot&&fe==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(y1,{ref:it,xml:Fh,onChange:Mh},`${G.path}:${$}`)}):G&&st&&de==="tree"?s.jsx(Xs,{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(jg,{jsonString:Ce,maxHeight:"100%",initiallyExpandedDepth:2})})}):G&&ot&&po()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-3",children:[Ce.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(Ce.length/1024)})}),s.jsx(Xs,{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(to,{content:Ce,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):G&&gt&&se==="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&&td===zo?(()=>{const H=G.path.split("/").map(De=>encodeURIComponent(De)).join("/");return Pi().authenticatedAsset(`/api/fs/serve${H.startsWith("/")?H:`/${H}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const H=G.path.substring(0,G.path.lastIndexOf("/")+1);return H?Ce.replace(/<head([^>]*)>/i,`<head$1><base href="${H}">`):Ce})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")},Oh)}):G&&on&&J==="view"?cd(G,Ft):s.jsxs("div",{className:Ie("relative h-full",Dr&&"overflow-hidden"),ref:wt,children:[s.jsx("div",{className:Ie("h-full",Dr&&"invisible"),children:s.jsx(Kl,{value:Ft,onChange:Xt,readOnly:!X,vimMode:qn==="vim",extensions:Jc,className:"h-full",blockWidgets:Vh,onViewReady:H=>{dt.current=H,ht(De=>De+1),window.requestAnimationFrame(()=>{Vi(H)})},onViewDestroy:()=>{dt.current&&(dt.current=null),ht(H=>H+1)},enableSearch:!0,searchOpen:B,onSearchOpenChange:P,highlightLines:ws?{start:Math.min(ws.start,ws.end),end:Math.max(ws.start,ws.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(H,De,$e)=>{if(!($e instanceof MouseEvent)||$e.button!==0)return!1;$e.preventDefault();const Ge=H.state.doc.lineAt(De.from).number;if(ws&&!$e.shiftKey&&Math.min(ws.start,ws.end)===Ge&&Math.max(ws.start,ws.end)===Ge)return dn(null),Ar(),rr.current=!1,Y.current=null,pt(!1),!0;if(d&&ws&&!$e.shiftKey){const ct=Math.min(ws.start,ws.end,Ge),rt=Math.max(ws.start,ws.end,Ge);return dn({start:ct,end:rt}),rr.current=!1,Y.current=null,pt(!1),!0}if(rr.current=!0,Y.current=Ge,pt(!0),ws&&$e.shiftKey){const ct=Math.min(ws.start,Ge),rt=Math.max(ws.end,Ge);dn({start:ct,end:rt})}else dn({start:Ge,end:Ge});return!0},mouseover:(H,De,$e)=>{if(!($e instanceof MouseEvent)||$e.buttons!==1||!rr.current||Y.current===null)return!1;const Ge=H.state.doc.lineAt(De.from).number,ct=Math.min(Y.current,Ge),rt=Math.max(Y.current,Ge);return dn({start:ct,end:rt}),pt(!0),!1},mouseup:()=>(rr.current=!1,Y.current=null,pt(!1),!1)}}})}),Dr&&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(A,{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")})})]})]}),_h=!!(b&&Ke[b]),dd=b?nt[b]:null,ud=s.jsxs("section",{className:Ie("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:Ie("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(A,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(Mn,{ref:j,value:S,onChange:H=>N(H.target.value),placeholder:e("filesView.tree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),S.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:()=>{N(""),j.current?.focus()},children:s.jsx(A,{name:"close",className:"size-4"})})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>nr("createFile",{path:y,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(A,{name:"file-add",className:"size-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>nr("createFolder",{path:y,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(A,{name:"folder-add",className:"size-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{ar()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(A,{name:"refresh",className:"size-4"})})})}),s.jsx(At,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx(En,{outerClassName:"flex-1 min-h-0",className:Ie("py-2",d?"px-3":"px-2"),children:s.jsx("ul",{className:"flex flex-col",children:_t?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):zt.length>0?zt.map(H=>{const De=G?.path===H.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{rn(H)},className:Ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",De?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[eh(H.path,H.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:H.path,children:H.relativePath??H.path})]})},H.path)}):dd?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:dd}),s.jsxs(ze,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ar()},children:[s.jsx(A,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):_h?Nt(b,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),$h=t==="full"&&I&&G&&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:sl({exitFullscreenOnly:!0})}),s.jsx(En,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:at||rd||id?h?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(A,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):lt?s.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:lt}):qt?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("img",{src:od,alt:G.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},ed)}):ys?ld(G):ot&&po()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-4",children:[Ce.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(Ce.length/1024)})}),s.jsx(Xs,{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(to,{content:Ce,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):on&&J==="view"?cd(G,Ft):s.jsxs("div",{className:Ie("relative h-full",Dr&&"overflow-hidden"),children:[s.jsx("div",{className:Ie("h-full",Dr&&"invisible"),children:s.jsx(Kl,{value:Ft,onChange:Xt,readOnly:!X,vimMode:qn==="vim",extensions:Jc,className:"h-full",onViewReady:H=>{dt.current=H,window.requestAnimationFrame(()=>{Vi(H)})},onViewDestroy:()=>{dt.current&&(dt.current=null)}})}),Dr&&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(A,{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(M1,{activeDialog:Ss,dialogData:Ts,dialogInputValue:_s,onDialogInputChange:hn,isDialogSubmitting:On,onDialogSubmit:Oi,onClose:Bh,inputRef:Tt}),$h,d?D?nl:ud: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:nl})}):s.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[m>=700&&s.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:ud}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:nl})]})]})};function F1(t){return t+1}const vr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Dl=(t,e)=>{const n=vr(t),r=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},O1=(t,e,n)=>Dl(Dl(Dl(t,".opencode"),"plans"),`${e}-${n}.md`),L1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,B1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},V1=(t,e)=>{const n=vr(e.currentDirectory),r=vr(e.homeDirectory),o=vr(t);return n&&o.startsWith(n+"/")?o.slice(n.length+1):r&&o===r?"~":r&&o.startsWith(r+"/")?`~${o.slice(r.length)}`:o},_1=(t,e,n)=>{const r=vr(t.trim());if(!r)return null;const o=n?e.find(c=>c.id===n)??null:null;if(o?.path){const c=vr(o.path);if(r===c||r.startsWith(`${c}/`))return{id:o.id,path:o.path}}const a=e.filter(c=>{const l=vr(c.path);return r===l||r.startsWith(`${l}/`)}).sort((c,l)=>vr(l.path).length-vr(c.path).length)[0];return a?{id:a.id,path:a.path}:null},sh=({targetPath:t=null})=>{const{t:e}=bt(),n=ft(te=>te.currentSessionId),r=ft(te=>te.createSession),o=ft(te=>te.initializeNewOpenChamberSession),a=ft(te=>te.sendMessage),c=ft(te=>te.setCurrentSession),l=Ac(),d=qs(te=>te.homeDirectory),f=yc(te=>te.planModeEnabled),m=ks(te=>te.projects),u=ks(te=>te.activeProjectId),p=wn(te=>te.directories),x=hi()??"",y=Ee(te=>te.setActiveMainTab),b=Ee(te=>te.setSessionSwitcherOpen),g=Xn(),{isMobile:h}=Or(),{currentTheme:C}=pi(),w=i.useMemo(()=>n?l.find(te=>te.id===n)??null:null,[n,l]),S=i.useMemo(()=>{const te=typeof w?.directory=="string"?w.directory:"";return vr(te||"")},[w?.directory]),N=i.useMemo(()=>vr(x||S),[x,S]),k=i.useMemo(()=>_1(N,m,u),[u,N,m]),j=i.useMemo(()=>k?p.get(k.path)?.isGitRepo===!0:!1,[k,p]),[D,O]=i.useState(null),[v,M]=i.useState(!1),[I,E]=i.useState(null),B=i.useMemo(()=>!I||!S||!d?I:V1(I,{currentDirectory:S,homeDirectory:d}),[I,S,d]),[P,W]=i.useState(""),{isPlaying:_,play:V,stop:R}=rm(),ne=ss(te=>te.showMessageTTSButtons),[ie,J]=i.useState(null),U=i.useMemo(()=>B&&B.split("/").pop()||e("planView.file.defaultName"),[B,e]),ee=i.useMemo(()=>P.trim()&&Ng(P).title||e("planView.title.default"),[P,e]),ae=i.useMemo(()=>ee.trim()||e("planView.title.default"),[ee,e]),[de,ye]=i.useState(!1),[se,we]=i.useState(!1),[fe,Me]=i.useState("edit"),$=i.useRef(null),[K,q]=i.useState(null),me=i.useRef(null),je=i.useRef(null),Oe="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const te=localStorage.getItem(Oe);if(!te)return;const Ve=JSON.parse(te);(Ve==="preview"||Ve==="edit")&&Me(Ve)}catch{}},[]);const Be=i.useCallback(te=>{Me(te);try{localStorage.setItem(Oe,JSON.stringify(te))}catch{}},[]),Fe=i.useRef(!1),ue=i.useRef(null),[Re,xe]=i.useState(!1);i.useEffect(()=>{const te=()=>{Fe.current=!1,ue.current=null,xe(!1)};return document.addEventListener("mouseup",te),()=>document.removeEventListener("mouseup",te)},[]);const oe=i.useCallback((te,Ve)=>{const Ye=te.split(`
35
- `),Ke=Math.max(1,Ve.start),Je=Math.min(Ye.length,Ve.end);return Ke>Je?"":Ye.slice(Ke-1,Je).join(`
36
- `)},[]),ve=Cm({source:"plan",fileLabel:U,language:I&&Ii(I)||"markdown",getCodeForRange:te=>oe(P,Am(te)),toStoreRange:te=>({startLine:te.start,endLine:te.end}),fromDraftRange:te=>({start:te.startLine,end:te.endLine})}),{drafts:Se,commentText:le,setCommentText:T,editingDraftId:L,setSelection:he,saveComment:ge,cancel:z,reset:pe,startEdit:Ae,deleteDraft:G}=ve;i.useEffect(()=>{q(null),pe()},[P,pe]),i.useEffect(()=>{he(K)},[K,he]);const ke=i.useCallback(()=>{q(null),z()},[z]),Le=i.useCallback((te,Ve)=>{Ve&&q(Ve),ge(te,Ve??K??void 0),q(null)},[K,ge]);i.useEffect(()=>{if(!K)return;const te=Ye=>{const Ke=Ye.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]")||le.trim()||(q(null),z())},Ve=window.setTimeout(()=>{document.addEventListener("click",te)},100);return()=>{window.clearTimeout(Ve),document.removeEventListener("click",te)}},[z,le,L,h,K]);const Te=i.useMemo(()=>{const te=I?Ii(I):null,Ve=!!te&&te!=="markdown",Ye=[Gl(C,Ve?{syntaxColors:!1}:void 0)],Ke=im(I||"plan.md");return Ke&&Ye.push(Ke),Ve&&te&&Ye.push(Dm({language:te,themeName:C.metadata.id,theme:om(C)})),Ye.push(ai.lineWrapping),Ye},[C,I]);i.useEffect(()=>{if(!f&&!t){E(null),W(""),ye(!1);return}let te=!1;const Ve=async Ke=>{if(g.files?.readFile)return(await g.files.readFile(Ke))?.content??"";const Je=Lo()?.files;if(Je?.readFile)return(await Je.readFile(Ke,{optional:!0}))?.content??"";const nt=await Ns(`/api/fs/read?path=${encodeURIComponent(Ke)}&optional=true`,{cache:"no-store"});if(!nt.ok)throw new Error(`Failed to read plan file (${nt.status})`);return nt.text()};return(async()=>{if(E(null),W(""),J(null),t){ye(!0);try{const Ke=await Ve(t);if(te)return;E(t),W(Ke)}catch{if(te)return;E(null),W("")}finally{te||ye(!1)}return}if(!w?.slug||!w?.time?.created||!S){E(null),W("");return}ye(!0);try{const Ke=O1(S,w.time.created,w.slug),Je=B1(L1(w.time.created,w.slug),d||null);let nt=null,xt=null;try{xt=await Ve(Ke),nt=Ke}catch{}if(!nt)try{xt=await Ve(Je),nt=Je}catch{}if(te)return;if(!nt||xt===null){E(null),W("");return}E(nt),W(xt)}catch{if(te)return;E(null),W("")}finally{te||ye(!1)}})(),()=>{te=!0}},[d,f,g.files,S,w?.slug,w?.time?.created,t]),i.useEffect(()=>{if(!I){J(null);return}const te=window.setTimeout(async()=>{J(null);try{if(g.files?.writeFile){if(!(await g.files.writeFile(I,P))?.success)throw new Error(e("planView.error.writeFailed"))}else{const Ve=await Ns("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:I,content:P})});if(!Ve.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:Ve.status}))}}catch(Ve){J(Ve instanceof Error?Ve.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(te)}},[P,I,g.files,e]),i.useEffect(()=>()=>{$.current!==null&&window.clearTimeout($.current)},[]);const Z=i.useCallback(()=>{y("chat"),b(!1)},[y,b]),F=i.useCallback(async te=>{if(!k||!D)return;const Ve=await Rn(D.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:ae}),Ke=[{synthetic:!0,text:await Rn(D.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:ae,plan_path:I??""})}];M(!0);try{Z();let Je=null,nt=k.path;if(D.target==="worktree"){if(!j)return;const jt=await em(k.path,tm());if(!jt?.id)return;Je=jt.id,nt=jt.path}else{const jt=await r(void 0,k.path,null);if(!jt?.id)return;Je=jt.id,nt=jt.directory??k.path,o(jt.id,ss.getState().agents??[])}if(!Je)return;const xt=Sc.getState();xt.saveSessionModelSelection(Je,te.providerID,te.modelID),te.agent.trim()&&(xt.saveSessionAgentSelection(Je,te.agent),xt.saveAgentModelForSession(Je,te.agent,te.providerID,te.modelID),xt.saveAgentModelVariantForSession(Je,te.agent,te.providerID,te.modelID,te.variant||void 0)),c(Je,nt),await a(Ve,te.providerID,te.modelID,te.agent.trim()||void 0,void 0,void 0,Ke,te.variant||void 0),O(null)}finally{M(!1)}},[j,r,k,o,D,I,Z,a,ae,c]),re=i.useMemo(()=>Im({drafts:Se,editingDraftId:L,commentText:le,onTextChange:T,selection:K,isDragging:Re,fileLabel:U,newWidgetId:"plan-new-comment-input",mapDraftToRange:te=>({start:te.startLine,end:te.endLine}),onSave:Le,onCancel:ke,onEdit:te=>{Ae(te),q({start:te.startLine,end:te.endLine})},onDelete:G}),[le,G,L,ke,Le,Re,K,Se,U,T,Ae]);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:ee}),ie?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:ie,children:e("planView.error.saveFailed")}):null]}),I?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(tn,{children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.improvePlanAria"),disabled:!P.trim(),children:s.jsx(A,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(At,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(en,{align:"end",children:[s.jsx(xs,{onClick:()=>O({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(xs,{onClick:()=>O({action:"improve",target:"worktree"}),disabled:!j,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(tn,{children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.implementPlanAria"),disabled:!P.trim(),children:s.jsx(A,{name:"code-ai",className:"size-4"})})})}),s.jsx(At,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(en,{align:"end",children:[s.jsx(xs,{onClick:()=>O({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(xs,{onClick:()=>O({action:"implement",target:"worktree"}),disabled:!j,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(la,{currentMode:fe,onToggle:()=>Be(fe==="preview"?"edit":"preview")}),fe==="preview"&&ne&&s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(_?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{_?R():P.trim()&&V(P)},children:_?s.jsx(A,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(At,{sideOffset:8,children:e(_?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await dr(P)).ok&&(we(!0),$.current!==null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{we(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:se?s.jsx(A,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(Mm,{open:D!==null,onOpenChange:te=>{!te&&!v&&O(null)},target:D?.target??"session",projectDirectory:k?.path??null,submitting:v,onConfirm:F}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(En,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:de?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:fe==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(Xs,{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(to,{content:P,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:je,children:s.jsx(Kl,{value:P,onChange:W,readOnly:!1,className:"h-full",extensions:Te,onViewReady:te=>{me.current=te},onViewDestroy:()=>{me.current=null},blockWidgets:re,highlightLines:K?{start:Math.min(K.start,K.end),end:Math.max(K.start,K.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(te,Ve,Ye)=>{if(!(Ye instanceof MouseEvent)||Ye.button!==0)return!1;Ye.preventDefault();const Ke=te.state.doc.lineAt(Ve.from).number;if(K&&!Ye.shiftKey&&Math.min(K.start,K.end)===Ke&&Math.max(K.start,K.end)===Ke)return q(null),z(),Fe.current=!1,ue.current=null,xe(!1),!0;if(h&&K&&!Ye.shiftKey){const Je=Math.min(K.start,K.end,Ke),nt=Math.max(K.start,K.end,Ke);return q({start:Je,end:nt}),Fe.current=!1,ue.current=null,xe(!1),!0}if(Fe.current=!0,ue.current=Ke,xe(!0),K&&Ye.shiftKey){const Je=Math.min(K.start,Ke),nt=Math.max(K.end,Ke);q({start:Je,end:nt})}else q({start:Ke,end:Ke});return!0},mouseover:(te,Ve,Ye)=>{if(!(Ye instanceof MouseEvent)||Ye.buttons!==1||!Fe.current||ue.current===null)return!1;const Ke=te.state.doc.lineAt(Ve.from).number,Je=Math.min(ue.current,Ke),nt=Math.max(ue.current,Ke);return q({start:Je,end:nt}),xe(!0),!1},mouseup:()=>(Fe.current=!1,ue.current=null,xe(!1),!1)}}})})})})})})]})},Uc=t=>t,sc=t=>{const e=Uc(t).type;return typeof e=="string"?e:""},$1=t=>{const e=Uc(t).tool;return typeof e=="string"?e:""},z1=t=>{const e=Uc(t).text;return typeof e=="string"?e:""},W1=t=>{const e=sc(t);return e==="tool"?$1(t).trim().toLowerCase()||"tool":e||"unknown"},U1=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=W1(n);e.includes(r)||e.push(r)}return e.join(" + ")},H1=t=>t.replace(/\s+/g," ").trim(),G1=t=>{for(const n of t)if(sc(n)==="text"){const r=H1(z1(n));if(r.length===0)continue;return r}const e=t.filter(n=>sc(n)!=="text").length;return e===0?"":`${e} attachment${e===1?"":"s"}`},K1=(t,e,n)=>`${n(t)} / ${n(e)}`,q1=t=>{if(t==="12h")return!0;if(t==="24h")return!1},Y1=(t,e)=>{if(!t||!Number.isFinite(t))return"-";const n=q1(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}})},nc={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},da={user:0,assistant:0,tool:0,other:0},Ci=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Tl=t=>{const e=t.info.tokens,n=e!==void 0?e:t.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof n=="number")return{...nc,total:Ci(n)};if(!n||typeof n!="object")return nc;const r=n,o=Ci(r.input),a=Ci(r.output),c=Ci(r.reasoning),l=Ci(r.cache?.read),d=Ci(r.cache?.write);return{input:o,output:a,reasoning:c,cacheRead:l,cacheWrite:d,total:o+a+c+l+d}},Q1=(...t)=>{for(const e of t)if(typeof e=="string"&&e.trim().length>0)return e;return""},tr=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+tr(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+tr(n),0):0,J1=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...da,assistant:tr(n.text)+tr(n.content)};const o=Q1(n.text,n.content,n.value,n.source?.value,n.source?.text?.value);return r==="tool"||e==="tool"?{user:0,assistant:0,tool:tr(n.input)+tr(n.output)+tr(n.error)+tr(n.call?.input)+tr(n.call?.output)+tr(n.call?.error)+tr(n.raw)+Math.round(tr(n.metadata)*.25)+Math.round(tr(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}},Gu=(t,e)=>({user:t.user+e.user,assistant:t.assistant+e.assistant,tool:t.tool+e.tool,other:t.other+e.other}),X1=t=>{const e=Bo(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},Z1=(t,e)=>{if(t.length===0)return{...da};const n=t.reduce((r,o)=>{const a=X1(o);let c={...da};for(const l of o.parts)c=Gu(c,J1(l,a));return Gu(r,c)},{...da});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)}},Ai=t=>t.toLocaleString(eo()),e0=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(eo(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(eo(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),t0=(t,e)=>!t||!Number.isFinite(t)?"-":jc(t,e,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),s0=(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}},n0=()=>{const t=mt.c(202),{t:e}=bt(),n=Ee(r0);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),f=ft(i0),m=Ac(),u=kg(f??""),p=ss(o0);let x;t[1]===Symbol.for("react.memo_cache_sentinel")?(x=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(a0),l(null)},t[1]=x):x=t[1];let y;t[2]!==f?(y=[f],t[2]=f,t[3]=y):y=t[3],i.useEffect(x,y);let b,g;t[4]===Symbol.for("react.memo_cache_sentinel")?(b=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},g=[],t[4]=b,t[5]=g):(b=t[4],g=t[5]),i.useEffect(b,g);let h;t[6]===Symbol.for("react.memo_cache_sentinel")?(h=async(lt,Dt)=>{(await dr(Dt)).ok?(l(lt),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(Lt=>Lt===lt?null:Lt),d.current=null},2e3)):l(null)},t[6]=h):h=t[6];const C=h;let w;t[7]!==f||t[8]!==m?(w=f?m.find(lt=>lt.id===f)??null:null,t[7]=f,t[8]=m,t[9]=w):w=t[9];const S=w;let N,k,j,D,O,v;if(t[10]!==p||t[11]!==u){N=u.filter(l0);let lt;t[18]!==u?(lt=u.filter(c0),t[18]=u,t[19]=lt):lt=t[19],v=lt;let Dt=null;for(let Lt=N.length-1;Lt>=0;Lt=Lt-1,Lt){const es=N[Lt];if(Tl(es).total>0){Dt=es;break}}D=Dt?Tl(Dt):nc,k=Cg({input:D.input,cache:{read:D.cacheRead,write:D.cacheWrite}}),O=N.reduce(d0,0);const us=Dt?.info??null;j=s0(p,us?.providerID||"",us?.modelID||""),t[10]=p,t[11]=u,t[12]=N,t[13]=k,t[14]=j,t[15]=D,t[16]=O,t[17]=v}else N=t[12],k=t[13],j=t[14],D=t[15],O=t[16],v=t[17];const M=j,I=M.contextLimit,E=I&&I>0?Math.min(999,D.total/I*100):0;let B;if(t[20]!==u){const lt=[...u].reverse().find(u0)?.info?.system||"";B=Z1(u,lt),t[20]=u,t[21]=B}else B=t[21];const P=B,W=P.user,_=P.assistant,V=P.tool,R=Math.max(0,D.input-W-_-V),ne=W+_+V+R,ie=u[0]?.info?.time?.created,J=u.length>0?u[u.length-1]?.info?.time?.created:null;let U;t[22]!==S?.title||t[23]!==e?(U=S?.title||e("contextSidebar.session.untitled"),t[22]=S?.title,t[23]=e,t[24]=U):U=t[24];const ee=S?.time?.created??ie??null,ae=J??S?.time?.created??null;let de;t[25]!==_||t[26]!==R||t[27]!==V||t[28]!==W?(de={user:W,assistant:_,tool:V,other:R},t[25]=_,t[26]=R,t[27]=V,t[28]=W,t[29]=de):de=t[29];let ye;t[30]!==N.length||t[31]!==ne||t[32]!==k||t[33]!==I||t[34]!==M||t[35]!==u.length||t[36]!==ee||t[37]!==ae||t[38]!==de||t[39]!==U||t[40]!==D||t[41]!==O||t[42]!==E||t[43]!==v.length?(ye={sessionTitle:U,messagesCount:u.length,userMessagesCount:v.length,assistantMessagesCount:N.length,createdAt:ee,lastActivityAt:ae,providerModel:M,tokenBreakdown:D,usagePercent:E,cacheHitRate:k,totalAssistantCost:O,contextLimit:I,breakdown:de,breakdownTotal:ne},t[30]=N.length,t[31]=ne,t[32]=k,t[33]=I,t[34]=M,t[35]=u.length,t[36]=ee,t[37]=ae,t[38]=de,t[39]=U,t[40]=D,t[41]=O,t[42]=E,t[43]=v.length,t[44]=ye):ye=t[44];const se=ye;if(!f){let lt;t[45]!==e?(lt=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=lt):lt=t[46];let Dt;return t[47]!==lt?(Dt=s.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:lt}),t[47]=lt,t[48]=Dt):Dt=t[48],Dt}let we;t[49]!==e?(we=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=we):we=t[50];let fe;t[51]!==we||t[52]!==se.breakdown.user?(fe={key:"user",label:we,value:se.breakdown.user,color:"var(--status-success)"},t[51]=we,t[52]=se.breakdown.user,t[53]=fe):fe=t[53];let Me;t[54]!==e?(Me=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=Me):Me=t[55];let $;t[56]!==Me||t[57]!==se.breakdown.assistant?($={key:"assistant",label:Me,value:se.breakdown.assistant,color:"var(--primary-base)"},t[56]=Me,t[57]=se.breakdown.assistant,t[58]=$):$=t[58];let K;t[59]!==e?(K=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=K):K=t[60];let q;t[61]!==K||t[62]!==se.breakdown.tool?(q={key:"tool",label:K,value:se.breakdown.tool,color:"var(--status-warning)"},t[61]=K,t[62]=se.breakdown.tool,t[63]=q):q=t[63];let me;t[64]!==e?(me=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=me):me=t[65];let je;t[66]!==me||t[67]!==se.breakdown.other?(je={key:"other",label:me,value:se.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=me,t[67]=se.breakdown.other,t[68]=je):je=t[68];let Oe;t[69]!==fe||t[70]!==$||t[71]!==q||t[72]!==je?(Oe=[fe,$,q,je],t[69]=fe,t[70]=$,t[71]=q,t[72]=je,t[73]=Oe):Oe=t[73];const Be=Oe;let Fe;t[74]!==se.sessionTitle?(Fe=s.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:se.sessionTitle}),t[74]=se.sessionTitle,t[75]=Fe):Fe=t[75];let ue;t[76]!==se.providerModel.modelName||t[77]!==se.providerModel.providerName?(ue=s.jsxs("span",{children:[se.providerModel.providerName," / ",se.providerModel.modelName]}),t[76]=se.providerModel.modelName,t[77]=se.providerModel.providerName,t[78]=ue):ue=t[78];let Re;t[79]!==n||t[80]!==se.createdAt?(Re=se.createdAt&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:t0(se.createdAt,n)})]}),t[79]=n,t[80]=se.createdAt,t[81]=Re):Re=t[81];let xe;t[82]!==ue||t[83]!==Re?(xe=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:[ue,Re]}),t[82]=ue,t[83]=Re,t[84]=xe):xe=t[84];let oe;t[85]!==Fe||t[86]!==xe?(oe=s.jsxs("div",{className:"mb-6",children:[Fe,xe]}),t[85]=Fe,t[86]=xe,t[87]=oe):oe=t[87];let ve;t[88]!==e?(ve=e("contextSidebar.section.context"),t[88]=e,t[89]=ve):ve=t[89];let Se;t[90]!==ve?(Se=s.jsx("span",{className:"typography-micro text-muted-foreground",children:ve}),t[90]=ve,t[91]=Se):Se=t[91];let le;t[92]!==se.tokenBreakdown.total?(le=Ai(se.tokenBreakdown.total),t[92]=se.tokenBreakdown.total,t[93]=le):le=t[93];let T;t[94]!==se.contextLimit?(T=se.contextLimit?` / ${Ai(se.contextLimit)}`:"",t[94]=se.contextLimit,t[95]=T):T=t[95];let L;t[96]!==le||t[97]!==T?(L=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[le,T]}),t[96]=le,t[97]=T,t[98]=L):L=t[98];let he;t[99]!==Se||t[100]!==L?(he=s.jsxs("div",{className:"flex items-baseline justify-between",children:[Se,L]}),t[99]=Se,t[100]=L,t[101]=he):he=t[101];let ge;t[102]!==se.usagePercent?(ge=se.usagePercent>0&&s.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,se.usagePercent)}%`,backgroundColor:se.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}}),t[102]=se.usagePercent,t[103]=ge):ge=t[103];let z;t[104]!==ge?(z=s.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:ge}),t[104]=ge,t[105]=z):z=t[105];let pe;t[106]!==e||t[107]!==se.usagePercent?(pe=e("contextSidebar.context.percentUsed",{percent:se.usagePercent.toFixed(1)}),t[106]=e,t[107]=se.usagePercent,t[108]=pe):pe=t[108];let Ae;t[109]!==pe?(Ae=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:pe}),t[109]=pe,t[110]=Ae):Ae=t[110];let G;t[111]!==he||t[112]!==z||t[113]!==Ae?(G=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[he,z,Ae]}),t[111]=he,t[112]=z,t[113]=Ae,t[114]=G):G=t[114];let ke;t[115]!==e?(ke=e("contextSidebar.stats.messages"),t[115]=e,t[116]=ke):ke=t[116];let Le;t[117]!==se.messagesCount?(Le=Ai(se.messagesCount),t[117]=se.messagesCount,t[118]=Le):Le=t[118];let Te;t[119]!==ke||t[120]!==Le?(Te={label:ke,value:Le},t[119]=ke,t[120]=Le,t[121]=Te):Te=t[121];let Z;t[122]!==e?(Z=e("contextSidebar.stats.user"),t[122]=e,t[123]=Z):Z=t[123];let F;t[124]!==se.userMessagesCount?(F=Ai(se.userMessagesCount),t[124]=se.userMessagesCount,t[125]=F):F=t[125];let re;t[126]!==Z||t[127]!==F?(re={label:Z,value:F},t[126]=Z,t[127]=F,t[128]=re):re=t[128];let te;t[129]!==e?(te=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=te):te=t[130];let Ve;t[131]!==se.assistantMessagesCount?(Ve=Ai(se.assistantMessagesCount),t[131]=se.assistantMessagesCount,t[132]=Ve):Ve=t[132];let Ye;t[133]!==te||t[134]!==Ve?(Ye={label:te,value:Ve},t[133]=te,t[134]=Ve,t[135]=Ye):Ye=t[135];let Ke;t[136]!==e?(Ke=e("contextSidebar.stats.cost"),t[136]=e,t[137]=Ke):Ke=t[137];let Je;t[138]!==se.totalAssistantCost?(Je=e0(se.totalAssistantCost),t[138]=se.totalAssistantCost,t[139]=Je):Je=t[139];let nt;t[140]!==Ke||t[141]!==Je?(nt={label:Ke,value:Je},t[140]=Ke,t[141]=Je,t[142]=nt):nt=t[142];let xt;t[143]!==Te||t[144]!==re||t[145]!==Ye||t[146]!==nt?(xt=[Te,re,Ye,nt],t[143]=Te,t[144]=re,t[145]=Ye,t[146]=nt,t[147]=xt):xt=t[147];const jt=xt;let Mt;t[148]!==jt?(Mt=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:jt.map(f0)}),t[148]=jt,t[149]=Mt):Mt=t[149];let Et;t[150]!==e?(Et=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Et):Et=t[151];let Ut;t[152]!==Et?(Ut=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Et}),t[152]=Et,t[153]=Ut):Ut=t[153];let zt;t[154]!==e||t[155]!==se.cacheHitRate.hasInput||t[156]!==se.cacheHitRate.percent||t[157]!==se.tokenBreakdown.cacheRead||t[158]!==se.tokenBreakdown.cacheWrite||t[159]!==se.tokenBreakdown.input||t[160]!==se.tokenBreakdown.output||t[161]!==se.tokenBreakdown.reasoning?(zt=s.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:e("contextSidebar.tokens.input"),value:se.tokenBreakdown.input,format:"count"},{label:e("contextSidebar.tokens.output"),value:se.tokenBreakdown.output,format:"count"},{label:e("contextSidebar.tokens.reasoning"),value:se.tokenBreakdown.reasoning,format:"count"},{label:e("contextSidebar.tokens.cacheRead"),value:se.tokenBreakdown.cacheRead,format:"count"},{label:e("contextSidebar.tokens.cacheWrite"),value:se.tokenBreakdown.cacheWrite,format:"count"},{label:e("contextSidebar.tokens.cacheHit"),value:se.cacheHitRate.hasInput?se.cacheHitRate.percent:null,format:"percent"}].map(m0)}),t[154]=e,t[155]=se.cacheHitRate.hasInput,t[156]=se.cacheHitRate.percent,t[157]=se.tokenBreakdown.cacheRead,t[158]=se.tokenBreakdown.cacheWrite,t[159]=se.tokenBreakdown.input,t[160]=se.tokenBreakdown.output,t[161]=se.tokenBreakdown.reasoning,t[162]=zt):zt=t[162];let Ht;t[163]!==Ut||t[164]!==zt?(Ht=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[Ut,zt]}),t[163]=Ut,t[164]=zt,t[165]=Ht):Ht=t[165];let _t;t[166]!==Be||t[167]!==se.breakdownTotal?(_t=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:Be.map(lt=>lt.value<=0||se.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${lt.value/se.breakdownTotal*100}%`,backgroundColor:lt.color}},lt.key))}),t[166]=Be,t[167]=se.breakdownTotal,t[168]=_t):_t=t[168];let Gt;t[169]!==Be||t[170]!==se.breakdownTotal?(Gt=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:Be.map(lt=>{const Dt=se.breakdownTotal>0?lt.value/se.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:lt.color}}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[lt.label," ",s.jsxs("span",{className:"tabular-nums",children:[Dt.toFixed(0),"%"]})]})]},lt.key)})}),t[169]=Be,t[170]=se.breakdownTotal,t[171]=Gt):Gt=t[171];let Ce;t[172]!==_t||t[173]!==Gt?(Ce=s.jsxs("div",{className:"mb-6",children:[_t,Gt]}),t[172]=_t,t[173]=Gt,t[174]=Ce):Ce=t[174];let Qe;t[175]!==e?(Qe=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=Qe):Qe=t[176];let et;t[177]!==Qe?(et=s.jsx("div",{className:"typography-micro text-muted-foreground",children:Qe}),t[177]=Qe,t[178]=et):et=t[178];let yt;if(t[179]!==c||t[180]!==o||t[181]!==u||t[182]!==e||t[183]!==n){let lt;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(lt=Dt=>{const Lt=Bo(Dt.info).role,es=Lt==="assistant",os=Lt==="user",Qt=o[Dt.info.id]===!0,Ft=c===Dt.info.id,Xt=Dt.info.time?.created??null,as=U1(Dt.parts),$t=es?Tl({info:Dt.info,parts:Dt.parts}):null,bs=os?G1(Dt.parts):"",Cs=Y1(Xt,n),Tt=as||"—",Bt=$t?K1($t.input,$t.output,Ai):"",vt=Lt||"unknown",vs=as?`${vt}: ${as}`:vt,hs=Qt?JSON.stringify({info:Dt.info,parts:Dt.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":Qt,onClick:()=>{a(He=>({...He,[Dt.info.id]:He[Dt.info.id]!==!0}))},children:s.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:es?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[os?s.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",bs]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:es?Tt:vs}),es&&s.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:Bt})]}),s.jsx("span",{className:"text-right text-muted-foreground",children:Cs})]})}),Qt&&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:He=>{He.stopPropagation(),C(Dt.info.id,hs)},"aria-label":e(Ft?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Ft?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Ft?s.jsx(A,{name:"check",className:"size-3.5"}):s.jsx(A,{name:"file-copy",className:"size-3.5"})})}),s.jsx(Ag,{language:"json",code:hs,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},Dt.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=lt):lt=t[189],yt=[...u].reverse().map(lt),t[179]=c,t[180]=o,t[181]=u,t[182]=e,t[183]=n,t[184]=yt}else yt=t[184];let We;t[190]!==yt?(We=s.jsx("div",{className:"mt-2.5 space-y-1",children:yt}),t[190]=yt,t[191]=We):We=t[191];let at;t[192]!==et||t[193]!==We?(at=s.jsxs("div",{children:[et,We]}),t[192]=et,t[193]=We,t[194]=at):at=t[194];let qe;return t[195]!==oe||t[196]!==G||t[197]!==Mt||t[198]!==Ht||t[199]!==Ce||t[200]!==at?(qe=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:[oe,G,Mt,Ht,Ce,at]})}),t[195]=oe,t[196]=G,t[197]=Mt,t[198]=Ht,t[199]=Ce,t[200]=at,t[201]=qe):qe=t[201],qe};function r0(t){return t.timeFormatPreference}function i0(t){return t.currentSessionId}function o0(t){return t.providers}function a0(t){return Object.keys(t).length>0?{}:t}function l0(t){return Bo(t.info).role==="assistant"}function c0(t){return Bo(t.info).isUser}function d0(t,e){const n=Ci(e.info.cost);return t+n}function u0(t){return Bo(t.info).isUser&&typeof t.info.system=="string"}function f0(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 m0(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)}%`:Ai(t.value):"—"})]},t.label)}const h0=(t,e,n)=>JSON.stringify({sessionID:t,directory:e||"",readOnly:n===!0}),p0=(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()},g0=(t,e,n,r,o,a)=>{const c=h0(n,r,o),l=t.get(e);if(l?.signature===c)return l.src;const d=p0(n,r,o,a);return t.set(e,{signature:c,src:d}),d},x0=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"),Yi=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"&&x0(e.center)&&Ku(e.attributes)&&Ku(e.computedStyle)&&Array.isArray(e.ancestry)},Hc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([x,y])=>`${x}="${y}"`).join(" "),d=r.computedStyle,f=r.bounds,m=r.center,u=a.replace(/[.:]+$/g,""),p=r.ancestry.map(x=>x.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}`,p?`- Ancestry: ${p}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(f.x)}, y=${Math.round(f.y)}, width=${Math.round(f.width)}, height=${Math.round(f.height)}`,`- Center: x=${Math.round(m.x)}, y=${Math.round(m.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(x=>typeof x=="string").join(`
37
- `)},nh=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Gr("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((y,b)=>{o.onload=()=>y(),o.onerror=()=>b(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),f=document.createElement("canvas");f.width=Math.floor(a*d),f.height=Math.floor(c*d);const m=f.getContext("2d");if(!m)return null;m.scale(d,d),m.drawImage(o,0,0,a,c);const u=a/Math.max(1,n.width),p=c/Math.max(1,n.height);m.fillStyle="rgba(37, 99, 235, 0.28)",m.strokeStyle="rgb(37, 99, 235)",m.lineWidth=Math.max(2,2*u),m.fillRect(e.bounds.x*u,e.bounds.y*p,e.bounds.width*u,e.bounds.height*p),m.strokeRect(e.bounds.x*u,e.bounds.y*p,e.bounds.width*u,e.bounds.height*p);const x=await new Promise(y=>f.toBlob(y,"image/jpeg",.82));return x?new File([x],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(n){return console.warn("[preview] failed to capture annotation screenshot:",n),null}return await R0(t,e)},Gc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((g,h)=>{c.onload=()=>g(),c.onerror=()=>h(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),m=Math.min(1,1200/l),u=document.createElement("canvas");u.width=Math.floor(l*m),u.height=Math.floor(d*m);const p=u.getContext("2d");if(!p)return null;p.scale(m,m),p.drawImage(c,0,0,l,d);const x=l/Math.max(1,r||l),y=d/Math.max(1,o||d);p.fillStyle="rgba(37, 99, 235, 0.14)",p.strokeStyle="rgb(37, 99, 235)",p.lineWidth=Math.max(2,2*x),p.fillRect(a.bounds.x*x,a.bounds.y*y,a.bounds.width*x,a.bounds.height*y),p.strokeRect(a.bounds.x*x,a.bounds.y*y,a.bounds.width*x,a.bounds.height*y);const b=await new Promise(g=>u.toBlob(g,"image/jpeg",.82));return b?new File([b],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Qi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Qn=new Map,Pl=new Map,b0=3e4,Kc=t=>{const e=Qn.get(t);return e?e.expiresAt-Date.now()<=b0?(Qn.delete(t),null):e:null},y0=t=>{try{return new URL(t).origin}catch{return t}};function rh(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 ih=t=>new Promise((e,n)=>{const r=new FileReader;r.onloadend=()=>e(typeof r.result=="string"?r.result:Qi),r.onerror=()=>n(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),w0=async(t,e=.82)=>{const n=await new Promise(r=>t.toBlob(r,"image/jpeg",e));return n&&(await ih(n)).split(",",2)[1]||""},v0=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},ua=(...t)=>{v0()&&console.info("[preview-capture]",...t)},oh=(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}`:"",f=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(n.push({selector:`${l}${d}${f}`,scrollTop:a,scrollLeft:c,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),n.length>=e)break}}catch{}return n},Ao="data-oc-fixed-pin",S0=(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(Ao,JSON.stringify({top:l.top+n,left:l.left+e,width:l.width,height:l.height})),o.push(c);const d=c.tagName.toLowerCase(),f=typeof c.className=="string"&&c.className?`.${c.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";a.push({selector:`${d}${f}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return ua("tagged fixed elements",a),()=>{for(const c of o)try{c.removeAttribute(Ao)}catch{}}},j0={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${Ao}]`)){let r;try{r=JSON.parse(n.getAttribute(Ao)||"")}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(Ao)}}},Gi="data-oc-scroll-pin",N0=t=>{const e=[],n=oh(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,f=l.scrollLeft||0;if(d<=0&&f<=0)continue;const m=l!==a&&l!==c;m&&l.setAttribute(Gi,JSON.stringify({top:d,left:f})),e.push({el:l,top:d,left:f,tagged:m})}}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(Gi)}catch{}},snapshot:n}},k0={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(`[${Gi}]`)){let o;try{o=JSON.parse(r.getAttribute(Gi)||"")}catch{r.removeAttribute(Gi);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(Gi)}}},Il=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await ih(await n.blob()):null}catch{return null}},C0=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=Kc(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=Pl.get(e),o=r??(async()=>{try{const c=await Ns("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!c.ok)return Qn.delete(e),null;const l=await c.json(),d=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",f=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Qn.delete(e),null;const m={proxyBasePath:d,expiresAt:f};return Qn.set(e,m),m}catch{return Qn.delete(e),null}finally{Pl.delete(e)}})();r||Pl.set(e,o);const a=await o;return a?`${a.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},ah=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 Il(n.toString(),"include")??Qi;const r=await C0(n),o=r?await Il(r,"include"):null;return o||(await Il(n.toString(),"omit")??Qi)}catch{return Qi}},A0=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 ah(a,e);r=r.replace(o[0],`url("${c}")`)}return r},qu=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),lh=t=>{const e=t.style.cssText;return()=>{t.style.cssText=e}},D0=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},T0=(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 f=l.getBoundingClientRect();if(f.width<=0||f.height<=0||f.right<0||f.bottom<0||f.left>e||f.top>n)continue;const m=o.getComputedStyle(l);if(m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)continue;const u=m.getPropertyValue("text-wrap"),p=m.getPropertyValue("text-wrap-mode"),x=m.whiteSpace.includes("nowrap")||u==="nowrap"||p==="nowrap",y=f.height<=D0(m)*1.7;!x&&(!y||f.width>e*.72)||(r.push(lh(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]?.()}},P0=(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(f=>{const m=a.getComputedStyle(f);if(m.position!=="fixed"||m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)return!1;const u=f.getBoundingClientRect();return u.width>0&&u.height>0&&u.right>=0&&u.bottom>=0&&u.left<=e&&u.top<=n}).filter((f,m,u)=>!u.some((p,x)=>x<m&&p.contains(f)));for(const f of d){const m=f.getBoundingClientRect(),u=a.getComputedStyle(f),p=Math.ceil(m.width)+8,x=Math.ceil(m.height)+2;r?.add(f),o.push(lh(f)),f.style.position="absolute",f.style.top=`${m.top+l}px`,f.style.left=`${m.left+c}px`,f.style.right="auto",f.style.bottom="auto",f.style.width=`${p}px`,f.style.minWidth=`${p}px`,f.style.height=`${x}px`,f.style.minHeight=`${x}px`,f.style.margin="0",f.style.boxSizing="border-box",f.style.transform="none",u.zIndex!=="auto"&&(f.style.zIndex=u.zIndex)}return()=>{for(let f=o.length-1;f>=0;f-=1)o[f]?.()}},ch=async(t,e,n,r={})=>{const o=[],a=t.defaultView??window,c=u=>{if(u===t.documentElement||u===t.body)return!0;try{const p=u.getBoundingClientRect();return p.width>0&&p.height>0&&p.right>=0&&p.bottom>=0&&p.left<=e&&p.top<=n}catch{return!1}};if(r.applyLayoutWorkarounds){const u=new WeakSet;o.push(P0(t,e,n,u)),o.push(T0(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 p=Array.from(u.querySelectorAll("source"));if(p.length===0)continue;const x=p.map(y=>({source:y,srcset:y.getAttribute("srcset"),sizes:y.getAttribute("sizes")}));o.push(()=>{for(const y of x)y.srcset===null?y.source.removeAttribute("srcset"):y.source.setAttribute("srcset",y.srcset),y.sizes===null?y.source.removeAttribute("sizes"):y.source.setAttribute("sizes",y.sizes)});for(const y of p)y.removeAttribute("srcset"),y.removeAttribute("sizes")}const f=Array.from(t.images).filter(u=>c(u));await Promise.all(f.map(async u=>{const p=l.get(u)||u.currentSrc||u.src||u.getAttribute("src")||"";if(!p)return;await qu(u);const x=await ah(p,t),y={src:u.getAttribute("src"),srcset:u.getAttribute("srcset"),sizes:u.getAttribute("sizes")};o.push(()=>{y.src===null?u.removeAttribute("src"):u.setAttribute("src",y.src),y.srcset===null?u.removeAttribute("srcset"):u.setAttribute("srcset",y.srcset),y.sizes===null?u.removeAttribute("sizes"):u.setAttribute("sizes",y.sizes)}),u.removeAttribute("srcset"),u.removeAttribute("sizes"),u.setAttribute("src",x||Qi),await qu(u)}));const m=Array.from(t.querySelectorAll("*")).filter(c);return await Promise.all(m.map(async u=>{const p=a.getComputedStyle(u).backgroundImage;if(!p||p==="none"||!p.includes("url("))return;const x=await A0(p,t);if(x===p)return;const y=u.style.backgroundImage;o.push(()=>{u.style.backgroundImage=y}),u.style.backgroundImage=x})),()=>{for(let u=o.length-1;u>=0;u-=1)try{o[u]?.()}catch{}}};async function I0(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,f=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,m=n.scrollX||0,u=n.scrollY||0,p=n.pageXOffset||0,x=n.pageYOffset||0,y=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,b=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,g=o.scrollLeft||0,h=o.scrollTop||0,C=d?.scrollLeft||0,w=d?.scrollTop||0,S=f?.scrollLeft||0,N=f?.scrollTop||0,k=Math.max(m,p,y,g,C,S),j=Math.max(u,x,b,h,w,N);ua("scroll sources",{windowScrollX:m,windowScrollY:u,pageScrollX:p,pageScrollY:x,visualViewportScrollX:y,visualViewportScrollY:b,rootScrollX:g,rootScrollY:h,bodyScrollX:C,bodyScrollY:w,scrollingElementScrollX:S,scrollingElementScrollY:N,scrollingElementTag:f?.tagName?.toLowerCase()??null,resolvedScrollX:k,resolvedScrollY:j,nestedScrolledElements:oh(r)});const D=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),O=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),v=Math.min(2,Math.max(1,window.devicePixelRatio||1)),M=o.style.scrollBehavior,I=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const E=N0(r);ua("nested scroll snapshot",E.snapshot);let B=()=>{},P=()=>{};try{await r.fonts?.ready.catch(()=>{}),B=await ch(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(k,j),P=S0(r,k,j),E.reapply();const W={backgroundColor:rh(r),cache:"disabled",dpr:v,embedFonts:!0,fast:!1,height:O,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[j0,k0],quality:.82,width:D},V=await(await Xh(o,W)).toCanvas();if(!V.width||!V.height)return null;const R=V.width/Math.max(1,D),ne=V.height/Math.max(1,O),ie=Math.min(V.width,Math.max(1,Math.round(c*R))),J=Math.min(V.height,Math.max(1,Math.round(l*ne))),U=Math.max(0,V.width-ie),ee=Math.max(0,V.height-J),ae=Math.min(U,Math.max(0,Math.round(k*R))),de=Math.min(ee,Math.max(0,Math.round(j*ne)));ua("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:D,captureHeight:O,canvasWidth:V.width,canvasHeight:V.height,xScale:R,yScale:ne,sourceX:ae,sourceY:de,sourceWidth:ie,sourceHeight:J});const ye=r.createElement("canvas");ye.width=ie,ye.height=J;const se=ye.getContext("2d");if(!se)return null;se.drawImage(V,ae,de,ie,J,0,0,ie,J);const we=await w0(ye,.82);return we?await Gc(we,c,l,c,l,e):null}finally{P(),E.cleanup(),B(),n.scrollTo(k,j),E.reapply(),o.style.scrollBehavior=M,d&&(d.style.scrollBehavior=I)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function R0(t,e){const n=await I0(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)),f=r.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,m=r.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,u=o.body,p=Math.max(d,a.scrollHeight||0,u?.scrollHeight||0),x=Math.min(2,Math.max(1,window.devicePixelRatio||1)),y=a.style.scrollBehavior,b=u?.style.scrollBehavior??"";a.style.scrollBehavior="auto",u&&(u.style.scrollBehavior="auto");let g="",h=()=>{};try{await o.fonts?.ready.catch(()=>{}),h=await ch(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(f,m);const w=await Qh(a).catch(()=>"");g=await Jh(a,{quality:.82,pixelRatio:x,width:l,height:d,backgroundColor:rh(o),imagePlaceholder:Qi,fontEmbedCSS:w||void 0,style:{transform:`translate(${-f}px, ${-m}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${p}px`},cacheBust:!0})}finally{h(),r.scrollTo(f,m),a.style.scrollBehavior=y,u&&(u.style.scrollBehavior=b)}const C=g.split(",",2)[1]||"";return C?await Gc(C,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const dh=380,E0=1400,uh=600,M0=24,Ma=new Map,Yu=200,F0=(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",O0=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},fh=t=>Number.isFinite(t)?Math.min(E0,Math.max(dh,Math.round(t))):uh,L0=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},Rl=(t,e)=>{const n=fh(t),r=L0(e);return r===null?n:Math.min(n,Math.max(1,r))},B0=(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},V0=(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"),_0=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},$0=(t,e,n)=>{if(t.mode==="chat"){const r=fa(t.dedupeKey);if(r){const a=e.get(r)?.trim();if(a)return a}const o=t.sessionTitleFallback?.trim();return o||n("contextPanel.mode.chat")}if(t.label)return t.label;if(t.mode==="file")return _0(t.targetPath)||n("contextPanel.mode.files");if(t.mode==="preview"){const r=t.targetPath;if(r)try{const o=new URL(r);return o.host||o.hostname||n("contextPanel.mode.preview")}catch{}return n("contextPanel.mode.preview")}return t.mode==="diff"?n("contextPanel.mode.diff"):V0(t.mode,n)},z0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(Kr,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(A,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(A,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(A,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(A,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(A,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(A,{name:"global",className:"h-3.5 w-3.5"})},fa=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,W0=(t,e)=>{if(t.size!==e.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0},U0=(t,e)=>{if(e.length===0)return Ma;const n=new Set(e),r=new Map;for(const o of t){if(!n.has(o.id))continue;const a=o.title?.trim();a&&r.set(o.id,a)}return r.size===0?Ma:r},H0=(t,e)=>{const n=am(t),r=i.useRef(Ma),o=i.useRef(e);return o.current=e,i.useSyncExternalStore(n.subscribe,i.useCallback(()=>{const a=U0(n.getState().session,o.current);return W0(r.current,a)?r.current:(r.current=a,a)},[n]),()=>Ma)},mh=`new Promise((resolve) => {
38
- const existing = document.getElementById('__openchamber_desktop_browser_overlay');
39
- if (existing) existing.remove();
40
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
41
- try { window.__openchamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
42
- }
43
- const overlay = document.createElement('div');
44
- overlay.id = '__openchamber_desktop_browser_overlay';
45
- 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;';
46
- document.documentElement.appendChild(overlay);
47
- const cssEscape = (value) => {
48
- try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
49
- };
50
- const selectorPart = (element) => {
51
- const tag = element.tagName.toLowerCase();
52
- if (element.id) return tag + '#' + cssEscape(element.id);
53
- const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
54
- return tag + className;
55
- };
56
- const metadata = (element) => {
57
- const rect = element.getBoundingClientRect();
58
- const style = getComputedStyle(element);
59
- const ancestry = [];
60
- let current = element;
61
- while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
62
- ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
63
- current = current.parentElement;
64
- }
65
- const attrs = {};
66
- for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
67
- const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
68
- return {
69
- frame: 'top',
70
- tag: element.tagName.toLowerCase(),
71
- text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
72
- selector: element.id ? '#' + cssEscape(element.id) : path,
73
- path,
74
- bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
75
- center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
76
- attributes: attrs,
77
- 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 },
78
- ancestry,
79
- };
80
- };
81
- const move = (event) => {
82
- const element = document.elementFromPoint(event.clientX, event.clientY);
83
- if (!element || element === overlay || element === document.documentElement || element === document.body) return;
84
- const rect = element.getBoundingClientRect();
85
- overlay.style.display = 'block';
86
- overlay.style.left = rect.left + 'px';
87
- overlay.style.top = rect.top + 'px';
88
- overlay.style.width = rect.width + 'px';
89
- overlay.style.height = rect.height + 'px';
90
- };
91
- const cleanup = () => {
92
- window.removeEventListener('mousemove', move, true);
93
- window.removeEventListener('click', click, true);
94
- window.removeEventListener('keydown', keydown, true);
95
- if (window.__openchamberDesktopBrowserCancelInspect === cancel) {
96
- delete window.__openchamberDesktopBrowserCancelInspect;
97
- }
98
- };
99
- const cancel = () => {
100
- cleanup();
101
- overlay.remove();
102
- resolve(null);
103
- };
104
- const click = (event) => {
105
- event.preventDefault();
106
- event.stopPropagation();
107
- const element = document.elementFromPoint(event.clientX, event.clientY);
108
- const result = element ? metadata(element) : null;
109
- cleanup();
110
- overlay.remove();
111
- resolve(result);
112
- };
113
- const keydown = (event) => {
114
- if (event.key !== 'Escape') return;
115
- cancel();
116
- };
117
- window.__openchamberDesktopBrowserCancelInspect = cancel;
118
- window.addEventListener('mousemove', move, true);
119
- window.addEventListener('click', click, true);
120
- window.addEventListener('keydown', keydown, true);
121
- });`,ma=`(() => {
122
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
123
- window.__openchamberDesktopBrowserCancelInspect();
124
- return;
125
- }
126
- const overlay = document.getElementById('__openchamber_desktop_browser_overlay');
127
- if (overlay) overlay.remove();
128
- })()`,G0=`(() => {
129
- if (window.__openchamberSameWebviewNavigationInstalled) return;
130
- window.__openchamberSameWebviewNavigationInstalled = true;
131
-
132
- const navigate = (rawUrl) => {
133
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
134
- try {
135
- const url = new URL(rawUrl, window.location.href);
136
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
137
- window.location.assign(url.href);
138
- return true;
139
- } catch (_error) {
140
- return false;
141
- }
142
- };
143
-
144
- const originalOpen = window.open.bind(window);
145
- window.open = (url, target, features) => {
146
- if (navigate(url)) return null;
147
- return originalOpen(url, target, features);
148
- };
149
-
150
- document.addEventListener('click', (event) => {
151
- if (event.defaultPrevented) return;
152
- const target = event.target;
153
- if (!(target instanceof Element)) return;
154
- const anchor = target.closest('a[target="_blank"][href]');
155
- if (!(anchor instanceof HTMLAnchorElement)) return;
156
- if (!navigate(anchor.href)) return;
157
- event.preventDefault();
158
- event.stopPropagation();
159
- }, true);
160
- })()`,Do=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"}},Qu=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)},K0=(t,e)=>t.length<=e?t:`${t.slice(0,e-3)}...`,hh=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Ju=(t,e,n)=>{const r=hh(e);t.postMessage(n,r)},q0=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}},Xu=t=>{if(!t)return t;try{const e=new URL(t);return e.searchParams.delete("ocPreview"),e.searchParams.delete("oc_preview_token"),e.searchParams.delete("oc_client_token"),e.searchParams.delete("oc_url_token"),e.toString()}catch{return t}},Y0=({rawUrl:t,onNavigate:e})=>{const{t:n}=bt(),{currentTheme:r}=pi(),[o,a]=i.useReducer(ue=>ue+1,0),[c,l]=i.useReducer(ue=>ue+1,0),[d,f]=i.useState({status:"idle"}),[m,u]=i.useState(""),p=i.useRef(null),x=i.useRef(1),[y,b]=i.useState(!1),[g,h]=i.useState(!1),[C,w]=i.useState("all"),[S,N]=i.useState([]),[k,j]=i.useState(!1),[D,O]=i.useState(null),v=ft(ue=>ue.currentSessionId),M=ft(ue=>ue.newSessionDraft?.open),I=Dc(ue=>ue.addDraft),E=mi(ue=>ue.addAttachedFile);let B=null;try{B=t?new URL(t):null}catch{B=null}const P=B?B.hostname==="localhost"||B.hostname==="127.0.0.1"||B.hostname==="::1"||B.hostname==="[::1]"||B.hostname==="0.0.0.0":!1,W=B?B.hostname==="0.0.0.0"?new URL(B.toString().replace("0.0.0.0","127.0.0.1")):B:null,_=W?W.toString():"",V=_?`${Hr()||"same-origin"}|${_}`:"",R=r.metadata.variant;i.useEffect(()=>{if(!_||!P){f({status:"idle"});return}const ue=Kc(V);if(ue?.previewToken){f({status:"ready",proxyBasePath:ue.proxyBasePath,previewToken:ue.previewToken,expiresAt:ue.expiresAt});return}ue&&Qn.delete(V);let Re=!1;return f({status:"loading"}),(async()=>{try{const xe=await Ns("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:_})});if(!xe.ok){Qn.delete(V);const T=await xe.json().catch(()=>({})),L=typeof T?.error=="string"?T.error:`HTTP ${xe.status}`;Re||f({status:"error",message:L});return}const oe=await xe.json(),ve=typeof oe.proxyBasePath=="string"?oe.proxyBasePath:"",Se=typeof oe.previewToken=="string"?oe.previewToken:"",le=typeof oe.expiresAt=="number"?oe.expiresAt:0;if(!ve||!Se){Qn.delete(V),Re||f({status:"error",message:n("contextPanel.preview.proxyError")});return}Qn.set(V,{proxyBasePath:ve,previewToken:Se,expiresAt:le}),Re||f({status:"ready",proxyBasePath:ve,previewToken:Se,expiresAt:le})}catch(xe){if(Qn.delete(V),!Re){const oe=xe instanceof Error?xe.message:String(xe);f({status:"error",message:oe})}}})(),()=>{Re=!0}},[P,V,c,n,_]);const ne=W&&(W.protocol==="http:"||W.protocol==="https:")?W.toString():"",ie=P&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!ie){u("");return}let ue=!1;return u(""),pc(Hr()).then(Re=>{!ue&&Re&&u(ie)}).catch(()=>{}),()=>{ue=!0}},[ie]);const J=P&&d.status==="ready"&&W&&m===ie?(()=>{const ue=W.pathname||"/",Re=new URLSearchParams(W.search);Re.delete("oc_url_token"),Re.delete("oc_client_token"),Re.set("ocPreview",String(o)),Re.set("oc_preview_token",d.previewToken||"");const xe=Re.toString(),oe=W.hash||"";return Pi().authenticatedAsset(`${d.proxyBasePath}${ue}${xe?`?${xe}`:""}${oe}`)})():"",U=P?J:ne,ee=P?q0(J):ne,ae=P&&(d.status==="loading"||d.status==="idle"||m!==ie),de=P&&d.status==="error",ye=i.useCallback(ue=>{const Re=v??(M?"draft":null);if(!Re){ce.error(n("contextPanel.preview.inspect.attachNoSession"));return}const xe=t||U||"",oe=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},ve=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let Se=!1;try{const le=p.current,T=le?await nh(le,ue):null;T&&(await E(T),Se=!0)}catch{Se=!1}I({sessionKey:Re,source:"preview-annotation",fileLabel:xe||"preview",startLine:1,endLine:1,code:Hc({pageUrl:xe,viewport:oe,devicePixelRatio:ve,target:ue,screenshotAttached:Se,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),ce.success(n("contextPanel.preview.inspect.attached"))})()},[E,I,v,U,M,t,n]);i.useEffect(()=>{b(!1),N([]),h(!1),w("all"),j(!1),O(null),x.current=1},[U]),i.useEffect(()=>{const ue=p.current?.contentWindow;!y||!ue||Ju(ue,J,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[y,k,J]),i.useEffect(()=>{const ue=p.current?.contentWindow;!y||!ue||Ju(ue,J,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:R})},[y,R,J]),i.useEffect(()=>{if(!k||typeof window>"u")return;const ue=Re=>{Re.key==="Escape"&&(Re.preventDefault(),Re.stopImmediatePropagation(),j(!1))};return window.addEventListener("keydown",ue,!0),()=>window.removeEventListener("keydown",ue,!0)},[k]),i.useEffect(()=>{if(!P||typeof window>"u")return;const ue=oe=>{if(typeof oe=="string")return oe;if(oe==null)return"";try{return JSON.stringify(oe)}catch{return String(oe)}},Re=oe=>{const ve=x.current;x.current+=1,N(Se=>{const le=[...Se,{...oe,id:ve}];return le.length>Yu?le.slice(le.length-Yu):le})},xe=oe=>{if(oe.source!==p.current?.contentWindow)return;const ve=oe.data;if(!(!ve||ve.source!=="openchamber-preview-bridge"||ve.version!==1)){if(ve.type==="ready"){b(!0);return}if(ve.type==="console"){const Se=ve.level==="error"||ve.level==="warn"||ve.level==="info"||ve.level==="debug"?ve.level:"log",le=Array.isArray(ve.args)?ve.args.map(ue).filter(Boolean):[];Re({level:Se,message:le.join(" "),ts:typeof ve.ts=="number"?ve.ts:Date.now()});return}if(ve.type==="runtime-error"){const Se=ue(ve.filename),le=typeof ve.line=="number"?ve.line:null,T=typeof ve.column=="number"?ve.column:null,L=Se?`${Se}${le!==null?`:${le}${T!==null?`:${T}`:""}`:""}`:"",he=ue(ve.stack);Re({level:"runtime",message:ue(ve.message)||n("contextPanel.preview.console.runtimeError"),details:[L,he].filter(Boolean).join(`
161
- `),ts:typeof ve.ts=="number"?ve.ts:Date.now()});return}if(ve.type==="resource-error"){const Se=ue(ve.tag)||"resource",le=ue(ve.url);Re({level:"resource",message:le?`${Se}: ${le}`:Se,details:ue(ve.outerHTML),ts:typeof ve.ts=="number"?ve.ts:Date.now()});return}if(ve.type==="hover"){O(Yi(ve.target)?ve.target:null);return}if(ve.type==="select"&&Yi(ve.target)){O(ve.target),j(!1),ye(ve.target);return}if(ve.type==="navigate-preview"){const Se=typeof ve.url=="string"?ve.url:"",le=ve.navigation==="external"?"external":"proxy";if(Se&&le==="external"){qr(Se);return}Se&&e(Se)}}};return window.addEventListener("message",xe),()=>{window.removeEventListener("message",xe)}},[ye,P,e,n]);const se=S.filter(ue=>ue.level==="error"||ue.level==="runtime"||ue.level==="resource").length,we=S.filter(ue=>F0(ue,C)),fe=i.useCallback(()=>{const ue=[`Preview URL: ${t||U||""}`,`Events: ${S.length}`,""].join(`
162
- `),Re=S.map(xe=>{const oe=new Date(xe.ts).toISOString(),ve=xe.details?`
163
- ${xe.details}`:"";return`[${oe}] [${xe.level}] ${xe.message}${ve}`}).join(`
164
- `);dr(`${ue}${Re}`).then(xe=>{xe.ok?ce.success(n("contextPanel.preview.console.copied")):ce.error(n("contextPanel.preview.console.copyFailed"))})},[S,U,t,n]),Me=i.useCallback(()=>{const ue=v??(M?"draft":null);if(!ue){ce.error(n("contextPanel.preview.console.attachNoSession"));return}const Re=[`Preview URL: ${t||U||""}`,`Events: ${S.length}`,""].join(`
165
- `),xe=S.map(oe=>{const ve=new Date(oe.ts).toISOString(),Se=oe.details?`
166
- ${oe.details}`:"";return`[${ve}] [${oe.level}] ${oe.message}${Se}`}).join(`
167
- `);I({sessionKey:ue,source:"preview-console",fileLabel:t||U||"preview",startLine:1,endLine:Math.max(1,S.length),code:`${Re}${xe}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),ce.success(n("contextPanel.preview.console.attached"))},[I,S,v,U,M,t,n]),[$,K]=i.useState("unknown"),q=i.useRef(0),me=i.useRef(0),je=15e3;i.useEffect(()=>{if(!J){K("unknown"),q.current=0,me.current=0;return}let ue=!1;return q.current||(q.current=Date.now(),me.current=0),K("unknown"),(async()=>{const xe=await(async()=>{try{return await Ns(J,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(ue)return;if(!xe){K("unreachable");return}if(xe.status===403||xe.status===404){Qn.delete(V),f({status:"loading"}),l();return}if(xe.status!==502){K("reachable");return}const oe=q.current||Date.now();if(Date.now()-oe<je){K("starting"),me.current+=1;const Se=me.current,le=Math.min(2e3,250*Math.pow(2,Math.min(4,Se)));setTimeout(()=>{ue||a()},le).unref?.();return}K("unreachable")})(),()=>{ue=!0}},[V,J,o]);const Oe=P&&d.status==="ready"&&($==="unknown"||$==="starting"),Be=P&&d.status==="ready"&&$==="unreachable",Fe=i.useCallback(ue=>{if(!P||d.status!=="ready"||typeof window>"u")return;const Re=ue.currentTarget.contentWindow;if(Re)try{const xe=Re.location,oe=hh(J);if(xe.origin!==oe||xe.pathname.startsWith(d.proxyBasePath))return;const ve=`${d.proxyBasePath}${xe.pathname}${xe.search}${xe.hash}`;Re.location.replace(ve)}catch{}},[P,J,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:ee||t,children:ee||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:!U,children:s.jsx(A,{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:()=>{ne&&qr(ne)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!ne,children:s.jsx(A,{name:"external-link",className:"h-3.5 w-3.5"})}),P?s.jsx(ze,{type:"button",size:"sm",variant:k?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>j(ue=>!ue),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!y,children:s.jsx(A,{name:"cursor",className:"h-3.5 w-3.5"})}):null,P?s.jsxs(ze,{type:"button",size:"sm",variant:g?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>h(ue=>!ue),title:n(y?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),"aria-label":n(y?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),disabled:!y&&S.length===0,children:[s.jsx(A,{name:"terminal-box",className:"h-3.5 w-3.5"}),se>0?s.jsx("span",{className:"typography-micro text-status-error",children:se}):null]}):null]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[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.startingServer")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.startingServerHint")})]}):Be?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")})]}):U&&(!P||$==="reachable")?s.jsxs("div",{className:"relative h-full w-full",children:[s.jsx("iframe",{ref:p,src:U,title:n("contextPanel.preview.iframeTitle"),className:"h-full w-full border-0",style:{colorScheme:R},onLoad:Fe,sandbox:P?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${U}:${o}`),k&&D?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:D.bounds.x,top:D.bounds.y,width:D.bounds.width,height:D.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:[D.tag,D.text?` · ${D.text}`:""]})}):null]}):ae?s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.loading")}):de?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")}),g?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:Me,disabled:S.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:fe,disabled:S.length===0,children:n("contextPanel.preview.console.copy")}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:()=>N([]),disabled:S.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(ue=>s.jsx(ze,{type:"button",size:"xs",variant:C===ue?"secondary":"ghost",onClick:()=>w(ue),children:n(ue==="all"?"contextPanel.preview.console.filter.all":ue==="errors"?"contextPanel.preview.console.filter.errors":ue==="warnings"?"contextPanel.preview.console.filter.warnings":"contextPanel.preview.console.filter.logs")},ue))}),s.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:S.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.empty")}):we.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):we.map(ue=>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:Ie("shrink-0 uppercase",ue.level==="error"||ue.level==="runtime"||ue.level==="resource"?"text-status-error":ue.level==="warn"?"text-status-warning":"text-muted-foreground"),children:ue.level}),s.jsx("span",{className:"min-w-0 break-words text-foreground",children:ue.message})]})},ue.id))})]}):null]})]})},Q0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,J0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=bt(),o=i.useRef(null),a=Ee($=>$.setContextPanelTabTargetPath),c=Do(t),l=c!=="about:blank"?c:"",[d,f]=i.useState(l),[m,u]=i.useState(l),[p,x]=i.useState(l),[y,b]=i.useState(()=>l?[l]:[]),[g,h]=i.useState(()=>l?0:-1),[C,w]=i.useReducer($=>$+1,0),[S,N]=i.useState(!!l),[k,j]=i.useState(!1),[D,O]=i.useState(null),[v,M]=i.useState({status:"idle"}),[I,E]=i.useState(""),B=ft($=>$.currentSessionId),P=ft($=>$.newSessionDraft?.open),W=Dc($=>$.addDraft),_=mi($=>$.addAttachedFile),V=i.useCallback($=>{!$||$==="about:blank"||!e||!n||a(e,n,$)},[e,n,a]),R=i.useCallback(($,K)=>{const q=Do($),me=q!=="about:blank"?q:"";u(me),f(me),K?.inFrame?N(!1):(x(me),N(!!me)),V(me),b(je=>{if(!me)return h(-1),[];if(K?.replaceHistory)return je;const Oe=g>=0?je.slice(0,g+1):[];if(Oe[Oe.length-1]===me)return h(Oe.length-1),Oe;const Fe=[...Oe,me];return h(Fe.length-1),Fe})},[g,V]),ne=i.useCallback($=>{const K=y[$];K&&(h($),u(K),x(K),f(K),N(!0),V(K))},[y,V]),ie=i.useCallback(()=>{if(m){N(!0);try{o.current?.contentWindow?.location.reload()}catch{w()}}},[m]);i.useEffect(()=>{if(!p){M({status:"idle"});return}const $=y0(p),K=Kc($);if(K?.previewToken){M({status:"ready",proxyBasePath:K.proxyBasePath,previewToken:K.previewToken,expiresAt:K.expiresAt});return}K&&Qn.delete($);let q=!1;return M({status:"loading"}),N(!0),(async()=>{try{const me=await Ns("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:p,allowExternal:!0})});if(!me.ok){const ue=await me.json().catch(()=>({})),Re=typeof ue?.error=="string"?ue.error:`HTTP ${me.status}`;q||M({status:"error",message:Re});return}const je=await me.json(),Oe=typeof je.proxyBasePath=="string"?je.proxyBasePath:"",Be=typeof je.previewToken=="string"?je.previewToken:"",Fe=typeof je.expiresAt=="number"?je.expiresAt:0;if(!Oe||!Be){q||M({status:"error",message:r("contextPanel.preview.proxyError")});return}Qn.set($,{proxyBasePath:Oe,previewToken:Be,expiresAt:Fe}),q||M({status:"ready",proxyBasePath:Oe,previewToken:Be,expiresAt:Fe})}catch(me){if(!q){const je=me instanceof Error?me.message:String(me);M({status:"error",message:je})}}})(),()=>{q=!0}},[p,r]);const J=p&&v.status==="ready"?`${v.proxyBasePath}|${v.previewToken||""}|${C}`:"";i.useEffect(()=>{if(!J){E("");return}let $=!1;return E(""),pc(Hr()).then(K=>{!$&&K&&E(J)}).catch(()=>{}),()=>{$=!0}},[J]);const U=i.useMemo(()=>{if(I!==J||!p||v.status!=="ready")return"";try{const $=new URL(p),K=$.pathname||"/",q=new URLSearchParams($.search);q.delete("oc_url_token"),q.delete("oc_client_token"),q.set("ocPreview",String(C)),q.set("oc_preview_token",v.previewToken||"");const me=q.toString();return Pi().authenticatedAsset(`${v.proxyBasePath}${K}${me?`?${me}`:""}${$.hash}`)}catch{return""}},[p,v,J,C,I]),ee=U||(v.status==="error"?p:""),ae=i.useCallback($=>{if(!$||!p||v.status!=="ready")return"";try{const K=new URL($,window.location.origin),q=v.proxyBasePath.endsWith("/")?v.proxyBasePath.slice(0,-1):v.proxyBasePath;if(K.origin!==window.location.origin||!K.pathname.startsWith(q))return"";const me=K.pathname.slice(q.length)||"/",je=new URL(p).origin;return Xu(new URL(`${me}${K.search}${K.hash}`,je).toString())}catch{return""}},[p,v]),de=i.useCallback($=>{if(!$||!p||v.status!=="ready")return"";try{const K=new URL($,window.location.origin),q=new URL(p).origin;if(K.origin!==window.location.origin||q===window.location.origin)return"";const me=v.proxyBasePath.endsWith("/")?v.proxyBasePath.slice(0,-1):v.proxyBasePath;return K.pathname.startsWith(me)?"":Xu(new URL(`${K.pathname}${K.search}${K.hash}`,q).toString())}catch{return""}},[p,v]),ye=i.useCallback($=>{const K=o.current?.contentWindow;K&&K.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:$},window.location.origin)},[]),se=i.useCallback(async $=>{const K=B??(P?"draft":null);if(!K){ce.error(r("contextPanel.preview.inspect.attachNoSession"));return}const q=o.current,me=q?.contentWindow,je=q?.getBoundingClientRect(),Oe={width:Number.isFinite(me?.innerWidth)?me?.innerWidth??je?.width??0:je?.width??0,height:Number.isFinite(me?.innerHeight)?me?.innerHeight??je?.height??0:je?.height??0},Be=q?await nh(q,$):null,Fe=!!Be;Be&&await _(Be),W({sessionKey:K,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Hc({pageUrl:m,viewport:Oe,devicePixelRatio:window.devicePixelRatio||1,target:$,screenshotAttached:Fe,intro:r(Fe?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),ce.success(r("contextPanel.preview.inspect.attached"))},[_,W,B,m,P,r]),we=i.useCallback(()=>{const $=o.current;O(null),ye(!1),$&&Qu($,ma).catch(()=>{})},[ye]);i.useEffect(()=>{if(!k)return;const $=K=>{K.key==="Escape"&&(K.preventDefault(),K.stopImmediatePropagation(),j(!1),we())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[we,k]),i.useEffect(()=>()=>we(),[we]),i.useEffect(()=>{const $=K=>{if(K.source!==o.current?.contentWindow)return;const q=K.data;if(!(!q||q.source!=="openchamber-preview-bridge"||q.version!==1)){if(q.type==="ready"){const me=typeof q.url=="string"?q.url:"",je=ae(me);je&&je!==m&&R(je,{inFrame:!0});return}if(q.type==="hover"){O(Yi(q.target)?q.target:null);return}if(q.type==="select"&&Yi(q.target)){O(null),j(!1),ye(!1),se(q.target);return}if(q.type==="navigate-preview"){const me=typeof q.url=="string"?q.url:"",je=de(me);if(je){R(je);return}me&&R(me)}}};return window.addEventListener("message",$),()=>window.removeEventListener("message",$)},[R,se,m,ae,de,ye]);const fe=i.useCallback(()=>{const $=o.current;if(!(!$||!m)){if(k){j(!1),we();return}if(U){O(null),j(!0),ye(!0);return}j(!0),(async()=>{try{const K=await Qu($,mh);if(j(!1),!K||!Yi(K))return;await se(K)}catch{j(!1),ce.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[se,we,m,k,ye,U,r]),Me=i.useCallback(()=>{try{const $=o.current?.contentWindow?.location.href||"",K=de($);if(K){R(K,{inFrame:!0});return}}catch{}N(!1),k&&U&&ye(!0)},[R,de,k,ye,U]);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:g<=0,onClick:()=>ne(g-1),children:s.jsx(A,{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:g<0||g>=y.length-1,onClick:()=>ne(g+1),children:s.jsx(A,{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:!m,onClick:ie,children:s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:$=>{$.preventDefault(),R(d)},children:s.jsx("input",{value:d,onChange:$=>f($.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:!m,onClick:fe,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(A,{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:!m,onClick:()=>{qr(m)},children:s.jsx(A,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[ee?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:ee,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:Me},`${n}:${C}`),k&&D?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:D.bounds.x,top:D.bounds.y,width:D.bounds.width,height:D.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:[D.tag,D.text?` · ${D.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(Tc,{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")})]}),S?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}=bt(),o=i.useRef(null),a=Ee(v=>v.setContextPanelTabTargetPath),c=Do(t),l=c!=="about:blank"?c:"",d=i.useRef(Do(t)),[f,m]=i.useState(l),[u,p]=i.useState(l),[x,y]=i.useState(!1),[b,g]=i.useState(!0),h=i.useRef(null),C=b,w=i.useCallback(v=>{!v||v==="about:blank"||!e||!n||a(e,n,v)},[e,n,a]),S=ft(v=>v.currentSessionId),N=ft(v=>v.newSessionDraft?.open),k=Dc(v=>v.addDraft),j=mi(v=>v.addAttachedFile);i.useEffect(()=>{const v=o.current;if(!v)return;const M=()=>{try{const _=v.getURL();_&&_!=="about:blank"&&(p(_),m(_),w(_))}catch{}},I=_=>{const V=_.detail;typeof V?.url=="string"&&V.url&&(p(V.url),m(V.url),w(V.url))},E=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>g(!0),200)},B=()=>{h.current&&clearTimeout(h.current),g(!1),M()},P=_=>{const V=_.detail;if(V?.disposition==="new-window"||V?.disposition==="foreground-tab"||V?.disposition==="background-tab"){_.preventDefault();const R=o.current;typeof R?.loadURL=="function"&&V.url&&R.loadURL(V.url)}},W=()=>{try{v.executeJavaScript?.(G0,!0).catch(()=>{})}catch{}};v.addEventListener("did-navigate",I),v.addEventListener("did-navigate-in-page",I),v.addEventListener("did-start-loading",E),v.addEventListener("did-stop-loading",B),v.addEventListener("new-window",P),v.addEventListener("dom-ready",W);try{v.isLoading()||(g(!1),M())}catch{}return W(),()=>{h.current&&clearTimeout(h.current),v.removeEventListener("did-navigate",I),v.removeEventListener("did-navigate-in-page",I),v.removeEventListener("did-start-loading",E),v.removeEventListener("did-stop-loading",B),v.removeEventListener("new-window",P),v.removeEventListener("dom-ready",W)}},[w]),i.useEffect(()=>{const v=setTimeout(()=>g(!1),3e4);return()=>clearTimeout(v)},[]),i.useEffect(()=>{if(!x)return;const v=M=>{if(M.key!=="Escape")return;M.preventDefault(),M.stopImmediatePropagation(),y(!1);const I=o.current;try{I?.executeJavaScript?.(ma).catch(()=>{})}catch{}};return window.addEventListener("keydown",v,!0),()=>window.removeEventListener("keydown",v,!0)},[x]),i.useEffect(()=>{const v=o.current;return()=>{try{const M=v?.getURL?.();M&&M!=="about:blank"&&a(e,n,M)}catch{}try{v?.executeJavaScript?.(ma).catch(()=>{})}catch{}}},[e,n,a]);const D=i.useCallback(v=>{const M=o.current;if(typeof M?.loadURL!="function")return;const I=Do(v);try{M.loadURL(I)}catch{}},[]),O=i.useCallback(()=>{const v=o.current;if(v){if(x){y(!1);try{v.executeJavaScript?.(ma).catch(()=>{})}catch{}return}y(!0),v.executeJavaScript?.(mh,!0).then(async M=>{if(y(!1),!M||!Yi(M))return;const I=S??(N?"draft":null);if(!I){ce.error(r("contextPanel.preview.inspect.attachNoSession"));return}const E=typeof v.getWebContentsId=="function"?v.getWebContentsId():null;if(E==null)return;const B=await Dg("desktop_browser_capture_page",{webContentsId:E}),P=await v.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),W=Number.isFinite(P?.width)?P.width:B.width,_=Number.isFinite(P?.height)?P.height:B.height,V=await Gc(B.base64,B.width,B.height,W,_,M),R=!!V;V&&await j(V),k({sessionKey:I,source:"preview-annotation",fileLabel:u||"browser",startLine:1,endLine:1,code:Hc({pageUrl:u,viewport:{width:W,height:_},devicePixelRatio:window.devicePixelRatio||1,target:M,screenshotAttached:R,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),ce.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>y(!1))}},[j,k,S,u,x,N,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(A,{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(A,{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(A,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:v=>{v.preventDefault(),D(f)},children:s.jsx("input",{value:f,onChange:v=>m(v.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:x?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:O,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(A,{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:()=>{qr(u)},children:s.jsx(A,{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:d.current,partition:"persist:openchamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!u||u==="about:blank")&&!b?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(Tc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")})]}):null,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]})]})},Z0=()=>{const{t}=bt(),e=hi()??"",n=i.useMemo(()=>O0(e),[e]),r=Ee(T=>n?T.contextPanelByDirectory[n]:void 0),o=Ee(T=>T.closeContextPanel),a=Ee(T=>T.closeContextPanelTab),c=Ee(T=>T.openContextPanelTab),l=Ee(T=>T.toggleContextPanelExpanded),d=Ee(T=>T.setContextPanelWidth),f=Ee(T=>T.setActiveContextPanelTab),m=Ee(T=>T.reorderContextPanelTabs),u=fn(T=>T.setSelectedPath),p=Ee(T=>T.openContextPreview),{themeMode:x,setThemeMode:y,lightThemeId:b,darkThemeId:g,currentTheme:h}=pi(),C=i.useMemo(()=>r?.tabs??[],[r?.tabs]),w=C.find(T=>T.id===r?.activeTabId)??C[C.length-1]??null,S=!!(r?.isOpen&&w),N=!!(S&&r?.expanded),k=fh(r?.width??uh),j=i.useMemo(()=>{const T=[];for(const L of C){if(L.mode!=="chat")continue;const he=fa(L.dedupeKey);he&&!T.includes(he)&&T.push(he)}return T},[C]),D=H0(n||void 0,j),[O,v]=i.useState(!1),[M,I]=i.useState(!1),E=i.useRef(0),B=i.useRef(k),P=i.useRef(null),W=i.useRef(null),_=i.useRef(null),V=i.useRef(new Map),R=i.useRef(new Map),ne=i.useRef(!1),ie=i.useRef(S),J=i.useRef(null),U=i.useCallback(()=>{I(!0),J.current!==null&&window.cancelAnimationFrame(J.current),J.current=window.requestAnimationFrame(()=>{J.current=null,I(!1)})},[]);i.useEffect(()=>()=>{J.current!==null&&window.cancelAnimationFrame(J.current)},[]),i.useLayoutEffect(()=>{const T=ie.current;if(ie.current=S,!S){I(!1);return}T||U()},[S,U]),i.useEffect(()=>{if(!S||ne.current){ne.current=S;return}const T=window.requestAnimationFrame(()=>{_.current?.focus({preventScroll:!0})});return ne.current=!0,()=>window.cancelAnimationFrame(T)},[S]);const ee=i.useCallback(T=>{const L=_.current;L&&L.style.setProperty("--oc-context-panel-width",`${Rl(T,L)}px`)},[]),ae=i.useCallback(T=>{if(!(!S||N||!n)){try{T.currentTarget.setPointerCapture(T.pointerId)}catch{}W.current=T.pointerId,v(!0),E.current=T.clientX,B.current=k,P.current=k,ee(k),T.preventDefault()}},[ee,n,N,S,k]),de=i.useCallback(T=>{if(!O||W.current!==T.pointerId)return;const L=E.current-T.clientX,he=Rl(B.current+L,_.current);P.current!==he&&(P.current=he,ee(he))},[ee,O]),ye=i.useCallback(T=>{if(W.current!==T.pointerId||!n)return;try{T.currentTarget.releasePointerCapture(T.pointerId)}catch{}const L=Rl(P.current??k,_.current);U(),ee(L),P.current=L,d(n,L),v(!1),W.current=null},[ee,n,d,U,k]);i.useEffect(()=>{O||(P.current=null)},[O]);const se=i.useCallback(()=>{n&&o(n)},[o,n]),we=i.useCallback(()=>{n&&l(n)},[n,l]),fe=i.useCallback(T=>{T.key==="Escape"&&(T.preventDefault(),T.stopPropagation(),se())},[se]);i.useEffect(()=>{if(!(!n||!w)&&w.mode==="file"&&w.targetPath){u(n,w.targetPath,{allowOutsideRoot:!0});return}},[w,n,u]);const Me=w?.mode==="chat"?w.id:null,$=w?.mode==="chat"?fa(w.dedupeKey):null;i.useEffect(()=>{if(!S||!n||!$||typeof window>"u")return;const T=()=>{if(document.visibilityState==="hidden"||!document.hasFocus()){cl(n,$,!1);return}lm($),cl(n,$,!0)};T();const L=window.setInterval(T,1e4);return window.addEventListener("focus",T),window.addEventListener("blur",T),document.addEventListener("visibilitychange",T),()=>{window.clearInterval(L),window.removeEventListener("focus",T),window.removeEventListener("blur",T),document.removeEventListener("visibilitychange",T),cl(n,$,!1)}},[$,n,S]);const K=i.useCallback((T,L,he)=>g0(R.current,T,L,n||null,he,{mode:x,lightThemeId:b,darkThemeId:g,currentTheme:h}),[h,g,n,b,x]);i.useEffect(()=>{const T=new Set(C.map(L=>L.id));for(const L of R.current.keys())T.has(L)||R.current.delete(L)},[C]);const q=i.useCallback(T=>{!n||w?.mode!=="diff"||c(n,{mode:"diff",targetPath:w.targetPath,stagedDiff:T==="staged",diffScope:T})},[w,n,c]),me=i.useCallback(()=>{if(typeof window>"u")return;const T={themeMode:x,lightThemeId:b,darkThemeId:g,currentTheme:h};for(const L of V.current.values()){const he=L.contentWindow;if(!he)continue;const ge=he.__openchamberApplyThemeSync;if(typeof ge=="function")try{ge(T);continue}catch{}he.postMessage({type:"openchamber:theme-sync",payload:T},window.location.origin)}},[h,g,b,x]),je=i.useCallback(()=>{if(!(typeof window>"u"))for(const[T,L]of V.current.entries()){const he=L.contentWindow;if(!he)continue;const ge={visible:Me===T},z=he.__openchamberSetEmbeddedVisibility;if(typeof z=="function")try{z(ge);continue}catch{}he.postMessage({type:"openchamber:embedded-visibility",payload:ge},window.location.origin)}},[Me]);i.useEffect(()=>{if(typeof window>"u")return;const T=L=>{if(L.origin!==window.location.origin||!Array.from(V.current.values()).some(G=>G.contentWindow===L.source)||L.data?.type!=="openchamber:cycle-theme-request")return;const z=["light","dark","system"],Ae=(z.indexOf(x)+1)%z.length;y(z[Ae])};return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},[y,x]),i.useLayoutEffect(()=>{C.some(L=>L.mode==="chat")&&(me(),je())},[g,b,je,me,C,x]);const Oe=i.useMemo(()=>C.map(T=>{const L=$0(T,D,t),he=K0(L,M0),ge=B0(T.targetPath,e);return{id:T.id,label:he,icon:z0(T),title:ge?`${L}: ${ge}`:L,closeLabel:t("contextPanel.tab.closeTabAria",{label:he})}}),[e,D,t,C]),Be=w?.mode==="context"?s.jsx(n0,{}):w?.mode==="plan"?s.jsx(sh,{targetPath:w.targetPath}):w?.mode==="preview"?s.jsx(Y0,{rawUrl:w.targetPath??"",onNavigate:T=>p(e,T)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(A,{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")})]}),Fe=i.useMemo(()=>C.filter(T=>T.mode==="chat"),[C]),ue=i.useMemo(()=>C.filter(T=>T.mode==="browser"),[C]),Re=i.useMemo(()=>C.filter(T=>T.mode==="diff"),[C]),xe=Q0()?X0:J0,oe=i.useMemo(()=>C.some(T=>T.mode==="file"),[C]),ve=w?.mode==="file",Se=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(Ro,{items:Oe,activeId:w?.id??null,onSelect:T=>{n&&f(n,T)},onClose:T=>{n&&a(n,T)},onReorder:(T,L)=>{n&&m(n,T,L)},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:we,className:"h-7 w-7 p-0",title:t(N?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),"aria-label":t(N?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),children:N?s.jsx(A,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:se,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(A,{name:"close",className:"h-3.5 w-3.5"})})]})]}),le=S?N?{"--oc-context-panel-width":"100%",width:"100%",minWidth:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",minWidth:`min(${dh}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${O?P.current??k:k}px`}:{"--oc-context-panel-width":`${O?P.current??k:k}px`,width:0,minWidth:0,maxWidth:0,opacity:0,overflow:"hidden",visibility:"hidden"};return s.jsxs("aside",{ref:_,"data-context-panel":"true",tabIndex:-1,inert:!S||void 0,className:Ie("flex min-h-0 flex-col overflow-hidden bg-background",!N&&"border-l border-border/40",N?"absolute inset-0 z-20 min-w-0":"relative h-full flex-shrink-0",!S&&"pointer-events-none",O||!S||M?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:fe,style:le,children:[!N&&s.jsx("div",{className:Ie("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",O&&"bg-[var(--interactive-border)]"),onPointerDown:ae,onPointerMove:de,onPointerUp:ye,onPointerCancel:ye,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),Se,s.jsxs("div",{className:Ie("relative min-h-0 flex-1 overflow-hidden",O&&"pointer-events-none"),children:[oe?s.jsx("div",{className:Ie("absolute inset-0",ve?"block":"hidden"),children:s.jsx(th,{mode:"editor-only"})}):null,Fe.map(T=>{const L=fa(T.dedupeKey);if(!L)return null;const he=K(T.id,L,T.readOnly);return he?s.jsx("iframe",{ref:ge=>{if(!ge){V.current.delete(T.id);return}V.current.set(T.id,ge)},src:he,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:L}),className:Ie("absolute inset-0 h-full w-full border-0 bg-background",Me===T.id?"block":"hidden"),onLoad:()=>{me(),je()}},T.id):null}),ue.map(T=>s.jsx("div",{className:Ie("absolute inset-0",w?.id!==T.id&&"hidden"),children:s.jsx(xe,{initialUrl:T.targetPath??"",directory:n,tabID:T.id})},T.id)),Re.map(T=>s.jsx("div",{className:Ie("absolute inset-0",w?.id!==T.id&&"hidden"),children:s.jsx(Jm,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:T.diffScope??(T.stagedDiff?"staged":"working"),onDiffScopeChange:q,targetFilePath:T.targetPath,flushContent:!0})},T.id)),w?.mode!=="chat"&&!ve&&w?.mode!=="browser"&&w?.mode!=="diff"?Be:null]})]})},rc=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},eS=()=>{const t=mt.c(171),{t:e}=bt(),n=Ee(tS),r=Ee(sS),o=Ee(nS),a=Ee(rS),c=Ee(iS),l=Ee(oS),d=Ee(aS),f=Ee(lS),m=Ee(cS),u=Ee(dS),p=Ee(uS),x=Ee(fS),y=ft(mS),b=ft(hS),g=Sr(pS),h=qs(gS),C=ks(xS),w=hi(),S=hc(bS),{files:N,git:k}=Xn(),j=wn(yS),{isMobile:D}=Or();let O;t[0]!==w?(O=w?rc(w):null,t[0]=w,t[1]=O):O=t[1];const v=O,[M,I]=i.useState(""),E=Ya(M,200);let B;t[2]!==E?(B=E.trim(),t[2]=E,t[3]=B):B=t[3];const P=B;let W;t[4]!==M?(W=M.trim(),t[4]=M,t[5]=W):W=t[5];const _=W;let V,R;t[6]!==n?(V=()=>{n&&I("")},R=[n],t[6]=n,t[7]=V,t[8]=R):(V=t[7],R=t[8]),i.useEffect(V,R);let ne,ie;t[9]!==g||t[10]!==j||t[11]!==k||t[12]!==n?(ne=()=>{if(!n||!k)return;const We=setTimeout(()=>{const at=new Set;for(const qe of g){const lt=Mr(qe);!lt||at.has(lt)||(at.add(lt),j(lt,k))}},0);return()=>clearTimeout(We)},ie=[n,g,k,j],t[9]=g,t[10]=j,t[11]=k,t[12]=n,t[13]=ne,t[14]=ie):(ne=t[13],ie=t[14]),i.useEffect(ne,ie);let J;t[15]!==r?(J=()=>r(!1),t[15]=r,t[16]=J):J=t[16];const U=J;let ee;t[17]!==U?(ee=We=>()=>{U(),We()},t[17]=U,t[18]=ee):ee=t[18];const ae=ee;let de;t[19]!==C?.id||t[20]!==C?.path||t[21]!==h||t[22]!==D||t[23]!==u||t[24]!==y||t[25]!==ae||t[26]!==o||t[27]!==l||t[28]!==a||t[29]!==e||t[30]!==m||t[31]!==f||t[32]!==d?(de=()=>{const We=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(A,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:ae(()=>{o("chat"),l(!1),y()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(A,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:ae(wS)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(A,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:ae(vS)},{id:"toggle-sidebar",title:e(D?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(A,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(D?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:ae(()=>{if(D){const{isSessionSwitcherOpen:at}=Ee.getState();l(!at)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(A,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:ae(()=>f())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(A,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:ae(()=>m())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(A,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:ae(()=>{h&&u(h)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(A,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:ae(()=>a(!0))}];return Va()&&We.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(A,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:ae(()=>{Gr("desktop_open_draft_mini_chat_window",{directory:rc(h||C?.path||""),projectId:C?.id??null}).catch(SS)})}),We},t[19]=C?.id,t[20]=C?.path,t[21]=h,t[22]=D,t[23]=u,t[24]=y,t[25]=ae,t[26]=o,t[27]=l,t[28]=a,t[29]=e,t[30]=m,t[31]=f,t[32]=d,t[33]=de):de=t[33],C?.id,C?.path;let ye;t[34]!==de?(ye=de(),t[34]=de,t[35]=ye):ye=t[35];const se=ye;let we;t[36]===Symbol.for("react.memo_cache_sentinel")?(we=cr(),t[36]=we):we=t[36];const fe=we;let Me,$;t[37]===Symbol.for("react.memo_cache_sentinel")?(Me=Yr(),$=!fe&&gc(),t[37]=Me,t[38]=$):(Me=t[37],$=t[38]);let K;t[39]!==D?(K={isVSCode:Me,isWeb:$,isDesktop:fe,isMobile:D},t[39]=D,t[40]=K):K=t[40];const q=K;let me;if(t[41]!==ae||t[42]!==a||t[43]!==c||t[44]!==q){let We;t[46]!==q?(We=qe=>qe.isAvailable?qe.isAvailable(q):!0,t[46]=q,t[47]=We):We=t[47];let at;t[48]!==ae||t[49]!==a||t[50]!==c?(at=qe=>{const lt=Yx(qe.slug)??"settings-3",Dt=(qe.keywords??[]).join(" ");return{id:`settings:${qe.slug}`,title:qe.title,icon:qe.slug==="mcp"?s.jsx(Hl,{className:"mr-2 h-4 w-4"}):s.jsx(A,{name:lt,className:"mr-2 h-4 w-4"}),searchText:`${qe.title} ${qe.group} ${Dt}`,onSelect:ae(()=>{c(qe.slug),a(!0)})}},t[48]=ae,t[49]=a,t[50]=c,t[51]=at):at=t[51],me=qx.filter(jS).filter(We).map(at),t[41]=ae,t[42]=a,t[43]=c,t[44]=q,t[45]=me}else me=t[45];const je=me,Oe=NS;let Be;if(t[52]!==g){let We;t[54]===Symbol.for("react.memo_cache_sentinel")?(We=(at,qe)=>Oe(qe)-Oe(at),t[54]=We):We=t[54],Be=[...g].sort(We),t[52]=g,t[53]=Be}else Be=t[53];const Fe=Be,ue=cm(),Re=ft(kS);let xe;t[55]!==ue||t[56]!==Re?(xe=(We,at)=>{const qe=Re.get(We);return qe?.branch?qe.branch.trim()||null:at&&ue.get(at)?.trim()||null},t[55]=ue,t[56]=Re,t[57]=xe):xe=t[57];const oe=xe;let ve;t[58]===Symbol.for("react.memo_cache_sentinel")?(ve=[],t[58]=ve):ve=t[58];const[Se,le]=i.useState(ve),[T,L]=i.useState(!1);let he,ge;t[59]!==v||t[60]!==n||t[61]!==S||t[62]!==P?(he=()=>{if(!n){le([]),L(!1);return}if(!v||P.length===0){le([]),L(!1);return}let We=!1;return L(!0),S(v,P,10,{type:"file"}).then(at=>{We||le(at.map(CS))}).catch(()=>{We||le([])}).finally(()=>{We||L(!1)}),()=>{We=!0}},ge=[n,v,P,S],t[59]=v,t[60]=n,t[61]=S,t[62]=P,t[63]=he,t[64]=ge):(he=t[63],ge=t[64]),i.useEffect(he,ge);const z=_.length>0;let pe;e:{if(!z){let at;t[65]!==se?(at=se.map(AS),t[65]=se,t[66]=at):at=t[66],pe=at;break e}let We;t[67]!==se||t[68]!==_?(We=Uo(se,_,DS,{limit:7,noFuzzy:!0}),t[67]=se,t[68]=_,t[69]=We):We=t[69],pe=We}const Ae=pe;let G;e:{if(!z){let at;t[70]===Symbol.for("react.memo_cache_sentinel")?(at=[],t[70]=at):at=t[70],G=at;break e}let We;t[71]!==_||t[72]!==je?(We=Uo(je,_,TS,{limit:7,noFuzzy:!0}),t[71]=_,t[72]=je,t[73]=We):We=t[73],G=We}const ke=G;let Le;e:{if(!z){let at;t[74]!==Fe?(at=Fe.slice(0,5).map(PS),t[74]=Fe,t[75]=at):at=t[75],Le=at;break e}let We;t[76]!==_||t[77]!==Fe?(We=Uo(Fe,_,IS,{limit:7,threshold:.2}),t[76]=_,t[77]=Fe,t[78]=We):We=t[78],Le=We}const Te=Le;let Z;e:{if(!z||Se.length===0){let at;t[79]===Symbol.for("react.memo_cache_sentinel")?(at=[],t[79]=at):at=t[79],Z=at;break e}let We;t[80]!==Se||t[81]!==_?(We=Uo(Se,_,RS,{limit:10,threshold:.4}),t[80]=Se,t[81]=_,t[82]=We):We=t[82],Z=We}const F=Z;let re,te,Ve,Ye,Ke,Je,nt,xt,jt,Mt,Et,Ut,zt,Ht,_t;if(t[83]!==oe||t[84]!==U||t[85]!==v||t[86]!==N||t[87]!==z||t[88]!==n||t[89]!==p||t[90]!==M||t[91]!==Ae||t[92]!==F||t[93]!==Te||t[94]!==ke||t[95]!==r||t[96]!==b||t[97]!==x||t[98]!==e){const We=Ae.map(ES),at=ke.map(MS),qe=Te.map(FS);_t=z?F.map(OS):[];let lt;e:{if(!z){lt=["commands","sessions"];break e}const Bt=LS,vt=[{key:"commands",score:Bt(Ae)},{key:"settings",score:Bt(ke)},{key:"sessions",score:Bt(Te)},{key:"files",score:Bt(F)}];vt.sort(BS),lt=vt.map(VS)}const Dt=lt;let us;t[114]!==U||t[115]!==b?(us=Bt=>{U(),b(Bt.id,Mr(Bt))},t[114]=U,t[115]=b,t[116]=us):us=t[116];const Lt=us;let es;t[117]!==U||t[118]!==v||t[119]!==N||t[120]!==p?(es=async Bt=>{if(!v)return;const vt=await zc(N,Bt);if(!vt.ok){ce.error(Wc(vt.reason));return}p(v,Bt),U()},t[117]=U,t[118]=v,t[119]=N,t[120]=p,t[121]=es):es=t[121];const os=es;let Qt;t[122]!==x?(Qt=Bt=>_a(ci(Bt,x)),t[122]=x,t[123]=Qt):Qt=t[123];const Ft=Qt;Ye=Ms,Ut=n,zt=r;let Xt;t[124]!==e?(Xt=e("commandPalette.title"),t[124]=e,t[125]=Xt):Xt=t[125];let as;t[126]!==Xt?(as=s.jsx(zs,{children:Xt}),t[126]=Xt,t[127]=as):as=t[127];let $t;t[128]!==e?($t=e("commandPalette.description"),t[128]=e,t[129]=$t):$t=t[129];let bs;t[130]!==$t?(bs=s.jsx(an,{children:$t}),t[130]=$t,t[131]=bs):bs=t[131],t[132]!==as||t[133]!==bs?(Ht=s.jsxs(Ys,{className:"sr-only",children:[as,bs]}),t[132]=as,t[133]=bs,t[134]=Ht):Ht=t[134],Ve=Es,Mt="overflow-hidden p-0",Et=!0,te=$a,nt=!1,xt="[&_[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 Cs;t[135]!==e?(Cs=e("commandPalette.input.placeholder"),t[135]=e,t[136]=Cs):Cs=t[136],t[137]!==M||t[138]!==Cs?(jt=s.jsx(za,{value:M,onValueChange:I,placeholder:Cs}),t[137]=M,t[138]=Cs,t[139]=jt):jt=t[139],re=Wa;let Tt;t[140]!==e?(Tt=e("commandPalette.empty.noResults"),t[140]=e,t[141]=Tt):Tt=t[141],t[142]!==Tt?(Ke=s.jsx(Ua,{children:Tt}),t[142]=Tt,t[143]=Ke):Ke=t[143],Je=Dt.map(Bt=>Bt==="commands"&&We.length>0?s.jsx(di,{children:We.map(vt=>s.jsxs(fi,{value:vt.id,onSelect:vt.onSelect,children:[vt.icon,s.jsx("span",{children:vt.title}),vt.shortcutId?s.jsx(Tg,{children:Ft(vt.shortcutId)}):null]},vt.id))},"commands"):Bt==="settings"&&at.length>0?s.jsx(di,{children:at.map(_S)},"settings"):Bt==="sessions"&&qe.length>0?s.jsx(di,{children:qe.map(vt=>{const vs=vt.title||e("commandPalette.session.untitled"),hs=Mr(vt),He=oe(vt.id,hs);return s.jsxs(fi,{value:`session:${vt.id}`,onSelect:()=>Lt(vt),children:[s.jsx(A,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:vs}),He?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:He})]}):null]},vt.id)})},"sessions"):Bt==="files"&&_t.length>0?s.jsx(di,{children:_t.map(vt=>{const vs=Pg(vt.relativePath||vt.name,{maxLength:80});return s.jsxs(fi,{value:`file:${vt.path}`,onSelect:()=>{os(vt.path)},children:[s.jsx(Kr,{filePath:vt.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":vt.relativePath,children:vs})]},`file:${vt.path}`)})},"files"):null),t[83]=oe,t[84]=U,t[85]=v,t[86]=N,t[87]=z,t[88]=n,t[89]=p,t[90]=M,t[91]=Ae,t[92]=F,t[93]=Te,t[94]=ke,t[95]=r,t[96]=b,t[97]=x,t[98]=e,t[99]=re,t[100]=te,t[101]=Ve,t[102]=Ye,t[103]=Ke,t[104]=Je,t[105]=nt,t[106]=xt,t[107]=jt,t[108]=Mt,t[109]=Et,t[110]=Ut,t[111]=zt,t[112]=Ht,t[113]=_t}else re=t[99],te=t[100],Ve=t[101],Ye=t[102],Ke=t[103],Je=t[104],nt=t[105],xt=t[106],jt=t[107],Mt=t[108],Et=t[109],Ut=t[110],zt=t[111],Ht=t[112],_t=t[113];let Gt;t[144]!==z||t[145]!==T||t[146]!==e||t[147]!==_t?(Gt=z&&T&&_t.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]=T,t[146]=e,t[147]=_t,t[148]=Gt):Gt=t[148];let Ce;t[149]!==re||t[150]!==Ke||t[151]!==Je||t[152]!==Gt?(Ce=s.jsxs(re,{children:[Ke,Je,Gt]}),t[149]=re,t[150]=Ke,t[151]=Je,t[152]=Gt,t[153]=Ce):Ce=t[153];let Qe;t[154]!==te||t[155]!==nt||t[156]!==xt||t[157]!==jt||t[158]!==Ce?(Qe=s.jsxs(te,{shouldFilter:nt,className:xt,children:[jt,Ce]}),t[154]=te,t[155]=nt,t[156]=xt,t[157]=jt,t[158]=Ce,t[159]=Qe):Qe=t[159];let et;t[160]!==Ve||t[161]!==Mt||t[162]!==Et||t[163]!==Qe?(et=s.jsx(Ve,{className:Mt,showCloseButton:Et,children:Qe}),t[160]=Ve,t[161]=Mt,t[162]=Et,t[163]=Qe,t[164]=et):et=t[164];let yt;return t[165]!==Ye||t[166]!==Ut||t[167]!==zt||t[168]!==Ht||t[169]!==et?(yt=s.jsxs(Ye,{open:Ut,onOpenChange:zt,children:[Ht,et]}),t[165]=Ye,t[166]=Ut,t[167]=zt,t[168]=Ht,t[169]=et,t[170]=yt):yt=t[170],yt};function tS(t){return t.isCommandPaletteOpen}function sS(t){return t.setCommandPaletteOpen}function nS(t){return t.setActiveMainTab}function rS(t){return t.setSettingsDialogOpen}function iS(t){return t.setSettingsPage}function oS(t){return t.setSessionSwitcherOpen}function aS(t){return t.toggleSidebar}function lS(t){return t.toggleRightSidebar}function cS(t){return t.toggleBottomTerminal}function dS(t){return t.openContextOverview}function uS(t){return t.openContextFile}function fS(t){return t.shortcutOverrides}function mS(t){return t.openNewSessionDraft}function hS(t){return t.setCurrentSession}function pS(t){return t.activeSessions}function gS(t){return t.currentDirectory}function xS(t){return t.getActiveProject()}function bS(t){return t.searchFiles}function yS(t){return t.ensureStatus}function wS(){dm()}function vS(){Er.requestDirectoryDialog()}function SS(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function jS(t){return t.slug!=="home"}function NS(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function kS(t){return t.worktreeMetadata}function CS(t){return{path:rc(t.path),name:t.name,relativePath:t.relativePath}}function AS(t){return{item:t,score:0}}function DS(t){return t.searchText}function TS(t){return t.searchText}function PS(t){return{item:t,score:0}}function IS(t){return t.title||""}function RS(t){return t.name}function ES(t){return t.item}function MS(t){return t.item}function FS(t){return t.item}function OS(t){return t.item}function LS(t){return t.length?t[0].score:1/0}function BS(t,e){return t.score-e.score}function VS(t){return t.key}function _S(t){return s.jsxs(fi,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const Zu=(t,e,n)=>Rg(t)?_a(ci(t,n)):e,$S=()=>{const t=mt.c(68),{t:e}=bt(),n=Ee(zS),r=Ee(WS),o=Ee(US);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=Ig(),t[0]=a):a=t[0];const c=a;let l,d,f,m,u,p,x,y,b;if(t[1]!==n||t[2]!==r||t[3]!==o||t[4]!==e){const P=[{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=Ms,y=n,b=r,l=Es,p="max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden";let W;t[14]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx(A,{name:"settings-3",className:"h-5 w-5"}),t[14]=W):W=t[14];let _;t[15]!==e?(_=e("helpDialog.title"),t[15]=e,t[16]=_):_=t[16];let V;t[17]!==_?(V=s.jsxs(zs,{className:"flex items-center gap-2",children:[W,_]}),t[17]=_,t[18]=V):V=t[18];let R;t[19]!==e?(R=e("helpDialog.description"),t[19]=e,t[20]=R):R=t[20];let ne;t[21]!==R?(ne=s.jsx(an,{children:R}),t[21]=R,t[22]=ne):ne=t[22],t[23]!==V||t[24]!==ne?(x=s.jsxs(Ys,{children:[V,ne]}),t[23]=V,t[24]=ne,t[25]=x):x=t[25],u="flex-1 overflow-y-auto mt-3 pr-1",f="space-y-4",m=P.map(ie=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(ie.categoryKey)}),s.jsx("div",{className:"space-y-1",children:ie.items.map(J=>{const U=J.id?Zu(J.id,Array.isArray(J.keys)?J.keys[0]:J.keys,o):Array.isArray(J.keys)?J.keys:J.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:[J.icon&&s.jsx(A,{name:J.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(J.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(U)?U:[U]).map((ee,ae)=>s.jsxs(i.Fragment,{children:[ae>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:ee})]},`${ee}-${ae}`))})]},J.id||J.descriptionKey)})})]},ie.categoryKey)),t[1]=n,t[2]=r,t[3]=o,t[4]=e,t[5]=l,t[6]=d,t[7]=f,t[8]=m,t[9]=u,t[10]=p,t[11]=x,t[12]=y,t[13]=b}else l=t[5],d=t[6],f=t[7],m=t[8],u=t[9],p=t[10],x=t[11],y=t[12],b=t[13];let g;t[26]!==f||t[27]!==m?(g=s.jsx("div",{className:f,children:m}),t[26]=f,t[27]=m,t[28]=g):g=t[28];let h;t[29]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(A,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),t[29]=h):h=t[29];let C;t[30]!==e?(C=e("helpDialog.proTips.title"),t[30]=e,t[31]=C):C=t[31];let w;t[32]!==C?(w=s.jsx("p",{className:"font-medium mb-1",children:C}),t[32]=C,t[33]=w):w=t[33];let S;t[34]!==o||t[35]!==e?(S=e("helpDialog.proTips.commandPalette",{shortcut:Zu("open_command_palette",`${c} P`,o)}),t[34]=o,t[35]=e,t[36]=S):S=t[36];let N;t[37]!==S?(N=s.jsxs("li",{children:["• ",S]}),t[37]=S,t[38]=N):N=t[38];let k;t[39]!==e?(k=e("helpDialog.proTips.recentSessions"),t[39]=e,t[40]=k):k=t[40];let j;t[41]!==k?(j=s.jsxs("li",{children:["• ",k]}),t[41]=k,t[42]=j):j=t[42];let D;t[43]!==e?(D=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=D):D=t[44];let O;t[45]!==D?(O=s.jsxs("li",{children:["• ",D]}),t[45]=D,t[46]=O):O=t[46];let v;t[47]!==N||t[48]!==j||t[49]!==O?(v=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[N,j,O]}),t[47]=N,t[48]=j,t[49]=O,t[50]=v):v=t[50];let M;t[51]!==w||t[52]!==v?(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:[h,s.jsxs("div",{className:"typography-meta text-muted-foreground",children:[w,v]})]})}),t[51]=w,t[52]=v,t[53]=M):M=t[53];let I;t[54]!==M||t[55]!==u||t[56]!==g?(I=s.jsxs("div",{className:u,children:[g,M]}),t[54]=M,t[55]=u,t[56]=g,t[57]=I):I=t[57];let E;t[58]!==l||t[59]!==I||t[60]!==p||t[61]!==x?(E=s.jsxs(l,{className:p,children:[x,I]}),t[58]=l,t[59]=I,t[60]=p,t[61]=x,t[62]=E):E=t[62];let B;return t[63]!==d||t[64]!==E||t[65]!==y||t[66]!==b?(B=s.jsx(d,{open:y,onOpenChange:b,children:E}),t[63]=d,t[64]=E,t[65]=y,t[66]=b,t[67]=B):B=t[67],B};function zS(t){return t.isHelpDialogOpen}function WS(t){return t.setHelpDialogOpen}function US(t){return t.shortcutOverrides}const HS=()=>{const t=mt.c(32),{t:e}=bt(),n=Ee(GS),r=Ee(KS),o=Ee(qS);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await dr(o)).ok){ce.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}ce.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(zs,{children:l}),t[5]=l,t[6]=d):d=t[6];let f;t[7]!==e?(f=e("openCodeStatusDialog.description"),t[7]=e,t[8]=f):f=t[8];let m;t[9]!==f?(m=s.jsx(an,{children:f}),t[9]=f,t[10]=m):m=t[10];let u;t[11]!==d||t[12]!==m?(u=s.jsxs(Ys,{children:[d,m]}),t[11]=d,t[12]=m,t[13]=u):u=t[13];let p;t[14]!==e?(p=e("openCodeStatusDialog.actions.copy"),t[14]=e,t[15]=p):p=t[15];let x;t[16]!==c||t[17]!==p?(x=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:p})}),t[16]=c,t[17]=p,t[18]=x):x=t[18];let y;t[19]!==o||t[20]!==e?(y=o||e("openCodeStatusDialog.empty.noData"),t[19]=o,t[20]=e,t[21]=y):y=t[21];let b;t[22]!==y?(b=s.jsx("pre",{className:"max-h-[60vh] overflow-auto rounded-lg bg-surface-muted p-4 typography-code text-foreground whitespace-pre-wrap",children:y}),t[22]=y,t[23]=b):b=t[23];let g;t[24]!==u||t[25]!==x||t[26]!==b?(g=s.jsxs(Es,{className:"max-w-2xl",children:[u,x,b]}),t[24]=u,t[25]=x,t[26]=b,t[27]=g):g=t[27];let h;return t[28]!==n||t[29]!==r||t[30]!==g?(h=s.jsx(Ms,{open:n,onOpenChange:r,children:g}),t[28]=n,t[29]=r,t[30]=g,t[31]=h):h=t[31],h};function GS(t){return t.isOpenCodeStatusDialogOpen}function KS(t){return t.setOpenCodeStatusDialogOpen}function qS(t){return t.openCodeStatusText}const YS=180,ef=600,QS=1,JS=6,XS=({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(()=>Yr(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<QS&&a.current.length>0;){const m=a.current.shift();if(!m)break;ft.getState().currentSessionId!==m&&(Ld(m).renderable||(c.current.add(m),r(m).catch(()=>{}).finally(()=>{c.current.delete(m),d()})))}},[r,l]),f=i.useCallback(m=>{if(l||!m||m===t||typeof window>"u"||Ld(m).renderable||c.current.has(m)||a.current.includes(m))return;a.current.length>=JS&&a.current.shift();const u=o.current.get(m);u!==void 0&&window.clearTimeout(u);const p=window.setTimeout(()=>{o.current.delete(m),a.current.push(m),d()},YS);o.current.set(m,p)},[t,l,d]);i.useEffect(()=>{if(l||!t||e.length===0)return;const m=window.setTimeout(()=>{const u=e.findIndex(p=>p.id===t);u<0||(f(e[u-1]?.id),f(e[u+1]?.id))},ef);return()=>window.clearTimeout(m)},[t,l,f,e]),i.useEffect(()=>{if(l||!t||n.length===0)return;const m=window.setTimeout(()=>{const u=n.indexOf(t);u<0||(f(n[u-1]),f(n[u+1]))},ef);return()=>window.clearTimeout(m)},[t,l,n,f]),i.useEffect(()=>{const m=o.current;return()=>{m.forEach(u=>{clearTimeout(u)}),m.clear(),a.current=[]}},[])};let Ji=null,Xi=null,ha=null,Mo=0,Fa=null;const Ei=new Set,ZS=3e4,ej=45e3,ph=()=>{ha&&(clearTimeout(ha),ha=null)},gh=()=>{if(Xi||Ei.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Mo,5)),ZS);Xi=setTimeout(()=>{Xi=null,Mo+=1,qc()},t)},Fo=()=>{ph(),Ji&&Ji.close(),Ji=null},tf=()=>{ph(),Ei.size!==0&&(ha=setTimeout(()=>{Fo(),gh()},ej))},tj=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}},sj=t=>{if(t.type==="openchamber:event-stream-ready"){Mo=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 Ei)d(l)},qc=()=>{if(typeof window>"u"||Ei.size===0||typeof EventSource!="function"||Ji&&Ji.readyState!==EventSource.CLOSED)return;Fo();const t=new EventSource(Pi().sse("/api/openchamber/events"));t.onopen=()=>{tf()},t.onmessage=e=>{tf();const n=tj(e.data);n&&sj(n)},t.onerror=()=>{Fo(),gh()},Ji=t},nj=()=>{Fa||typeof window>"u"||(Fa=Hf(()=>{Fo(),Mo=0,qc()}))},rj=()=>{Fa?.(),Fa=null},xh=t=>(Ei.add(t),nj(),qc(),()=>{Ei.delete(t),Ei.size===0&&(Xi&&(clearTimeout(Xi),Xi=null),Mo=0,Fo(),rj())}),Ja=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},io=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},ij=async t=>{const e=io(t),n=await Ns(`/api/projects/${encodeURIComponent(e)}/scheduled-tasks`);if(!n.ok)throw new Error(await Ja(n,"Failed to load scheduled tasks"));const r=await n.json().catch(()=>null);return!r||!Array.isArray(r.tasks)?[]:r.tasks},sf=async(t,e)=>{const n=io(t),r=await Ns(`/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 Ja(r,"Failed to save scheduled task"));const o=await r.json().catch(()=>null);return!o||!Array.isArray(o.tasks)?[]:o.tasks},oj=async(t,e)=>{const n=io(t),r=io(e),o=await Ns(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}`,{method:"DELETE",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Ja(o,"Failed to delete scheduled task"));const a=await o.json().catch(()=>null);return!a||!Array.isArray(a.tasks)?[]:a.tasks},aj=async(t,e)=>{const n=io(t),r=io(e),o=await Ns(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}/run`,{method:"POST",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Ja(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 bh(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return Bf.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function lj(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=Bf.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 cj=[{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"}],yh=[0,1,2,3,4,5,6],ic=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"],nf=()=>{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}`},pa=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},rf=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},dj=(t,e,n)=>{const r=pa(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},of=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),uj=(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(),f=[];for(let m=0;m<42;m+=1){const u=m-c+1;if(u<=0){const p=d+u;f.push({date:new Date(n,r-1,p),inCurrentMonth:!1});continue}if(u>l){f.push({date:new Date(n,r+1,u-l),inCurrentMonth:!1});continue}f.push({date:new Date(n,r,u),inCurrentMonth:!0})}return f},fj=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}},Ni=(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")}`},fo=(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"},af=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:fo(t,{min:1,max:12}),ea=t=>/^[0-5][0-9]$/.test(t)?t:fo(t,{max:59}),mj=(t,e)=>fo(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),lf=(t,e)=>fo(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),hj=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}},pj=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}},gj=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return yh.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},xj=(t,e)=>[...t.slice(e),...t.slice(0,e)],Yn=t=>{const e=mt.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},cf=t=>{const e=mt.c(84),{value:n,onChange:r,use24Hour:o,hourAriaLabel:a,minuteAriaLabel:c,periodAriaLabel:l,amLabel:d,pmLabel:f}=t;let m;e[0]!==n?(m=fj(n),e[0]=n,e[1]=m):m=e[1];const u=m,p=Xe.useRef(null),x=Xe.useRef(null),[y,b]=Xe.useState(null),[g,h]=Xe.useState(null),C=Xe.useRef(null),w=Xe.useRef(null);let S;e[2]===Symbol.for("react.memo_cache_sentinel")?(S=xe=>{C.current=xe,b(xe)},e[2]=S):S=e[2];const N=S;let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=xe=>{w.current=xe,h(xe)},e[3]=k):k=e[3];const j=k,D=Nj,O=kj,v=Cj;let M;e[4]!==r||e[5]!==u.meridiem||e[6]!==u.minute||e[7]!==o?(M=xe=>{const oe=xe.replace(/\D/g,"").slice(0,2);N(oe),oe.length===2&&(r(o?v(D(oe),u.minute):Ni(af(oe),u.minute,u.meridiem)),N(null),x.current?.focus())},e[4]=r,e[5]=u.meridiem,e[6]=u.minute,e[7]=o,e[8]=M):M=e[8];const I=M;let E;e[9]!==r||e[10]!==u.meridiem||e[11]!==u.minute||e[12]!==o?(E=()=>{const xe=C.current;if(xe!==null&&(N(null),xe.length!==0)){if(o){r(v(D(xe.padStart(2,"0")),u.minute));return}r(Ni(af(xe.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 B=E;let P;e[14]!==r||e[15]!==u.hour12||e[16]!==u.hour24||e[17]!==u.meridiem||e[18]!==o?(P=xe=>{const oe=xe.replace(/\D/g,"").slice(0,2);j(oe),oe.length===2&&(r(o?v(u.hour24,ea(oe)):Ni(u.hour12,ea(oe),u.meridiem)),j(null))},e[14]=r,e[15]=u.hour12,e[16]=u.hour24,e[17]=u.meridiem,e[18]=o,e[19]=P):P=e[19];const W=P;let _;e[20]!==r||e[21]!==u.hour12||e[22]!==u.hour24||e[23]!==u.meridiem||e[24]!==o?(_=()=>{const xe=w.current;xe!==null&&(j(null),xe.length!==0&&r(o?v(u.hour24,ea(xe.padStart(2,"0"))):Ni(u.hour12,ea(xe.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]=_):_=e[25];const V=_;let R;e[26]!==r||e[27]!==u.hour12||e[28]!==u.hour24||e[29]!==u.meridiem||e[30]!==u.minute||e[31]!==o?(R=xe=>r(o?v(O(u.hour24,xe),u.minute):Ni(mj(u.hour12,xe),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]=R):R=e[32];const ne=R;let ie;e[33]!==r||e[34]!==u.hour12||e[35]!==u.hour24||e[36]!==u.meridiem||e[37]!==u.minute||e[38]!==o?(ie=xe=>r(o?v(u.hour24,lf(u.minute,xe)):Ni(u.hour12,lf(u.minute,xe),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]=ie):ie=e[39];const J=ie;let U;e[40]!==r||e[41]!==u.hour12||e[42]!==u.meridiem||e[43]!==u.minute?(U=xe=>{xe!==u.meridiem&&r(Ni(u.hour12,u.minute,xe))},e[40]=r,e[41]=u.hour12,e[42]=u.meridiem,e[43]=u.minute,e[44]=U):U=e[44];const ee=U;let ae;e[45]!==B||e[46]!==ne?(ae=xe=>{if(xe.key==="ArrowRight"){xe.preventDefault(),B(),x.current?.focus();return}(xe.key==="ArrowUp"||xe.key==="ArrowDown")&&(xe.preventDefault(),N(null),ne(xe.key==="ArrowUp"?1:-1))},e[45]=B,e[46]=ne,e[47]=ae):ae=e[47];const de=ae;let ye;e[48]!==V||e[49]!==J?(ye=xe=>{if(xe.key==="ArrowLeft"&&(xe.currentTarget.selectionStart??0)===0){xe.preventDefault(),V(),p.current?.focus();return}(xe.key==="ArrowUp"||xe.key==="ArrowDown")&&(xe.preventDefault(),j(null),J(xe.key==="ArrowUp"?1:-1))},e[48]=V,e[49]=J,e[50]=ye):ye=e[50];const se=ye,we=o?"px-2":"pl-2 pr-1";let fe;e[51]!==we?(fe=Ie("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",we),e[51]=we,e[52]=fe):fe=e[52];const Me=y??(o?u.hour24:u.hour12);let $;e[53]!==I?($=xe=>I(xe.target.value),e[53]=I,e[54]=$):$=e[54];let K;e[55]===Symbol.for("react.memo_cache_sentinel")?(K=()=>N(""),e[55]=K):K=e[55];let q;e[56]!==B||e[57]!==a||e[58]!==de||e[59]!==Me||e[60]!==$?(q=s.jsx("input",{ref:p,inputMode:"numeric",value:Me,onChange:$,onKeyDown:de,onFocus:K,onBlur:B,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]=B,e[57]=a,e[58]=de,e[59]=Me,e[60]=$,e[61]=q):q=e[61];let me;e[62]===Symbol.for("react.memo_cache_sentinel")?(me=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=me):me=e[62];const je=g??u.minute;let Oe;e[63]!==W?(Oe=xe=>W(xe.target.value),e[63]=W,e[64]=Oe):Oe=e[64];let Be;e[65]===Symbol.for("react.memo_cache_sentinel")?(Be=()=>j(""),e[65]=Be):Be=e[65];let Fe;e[66]!==V||e[67]!==c||e[68]!==se||e[69]!==je||e[70]!==Oe?(Fe=s.jsx("input",{ref:x,inputMode:"numeric",value:je,onChange:Oe,onKeyDown:se,onFocus:Be,onBlur:V,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]=V,e[67]=c,e[68]=se,e[69]=je,e[70]=Oe,e[71]=Fe):Fe=e[71];let ue;e[72]!==d||e[73]!==u.meridiem||e[74]!==l||e[75]!==f||e[76]!==ee||e[77]!==o?(ue=o?null:s.jsxs(Un,{value:u.meridiem,onValueChange:xe=>ee(xe),children:[s.jsx(Hn,{"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(Cn,{})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"AM",children:d}),s.jsx(Rs,{value:"PM",children:f})]})]}),e[72]=d,e[73]=u.meridiem,e[74]=l,e[75]=f,e[76]=ee,e[77]=o,e[78]=ue):ue=e[78];let Re;return e[79]!==fe||e[80]!==q||e[81]!==Fe||e[82]!==ue?(Re=s.jsxs("div",{className:fe,children:[q,me,Fe,ue]}),e[79]=fe,e[80]=q,e[81]=Fe,e[82]=ue,e[83]=Re):Re=e[83],Re},df=t=>new Date(t.getFullYear(),t.getMonth(),1),bj=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},uf=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),yj=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"]},ff=(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:yj(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:nf(),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:nf(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent}}},wj=(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(!bh(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))},Sj=t=>{const e=mt.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?bh(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let f;e:{if(!d?.valid||!c.trim()){let R;e[2]===Symbol.for("react.memo_cache_sentinel")?(R=[],e[2]=R):R=e[2],f=R;break e}let V;e[3]!==c||e[4]!==n.schedule.timezone?(V=lj(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=V):V=e[5],f=V}const m=f;let u;e[6]!==n.schedule.timezone||e[7]!==o?(u=V=>new Intl.DateTimeFormat(o,{timeZone:n.schedule.timezone,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(V),e[6]=n.schedule.timezone,e[7]=o,e[8]=u):u=e[8];const p=u;let x;e[9]!==a?(x=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=x):x=e[10];let y;e[11]!==x?(y=s.jsx(Yn,{htmlFor:"sched-cron",required:!0,children:x}),e[11]=x,e[12]=y):y=e[12];let b;e[13]!==r?(b=V=>r(R=>({...R,schedule:{...R.schedule,cronExpression:V.target.value}})),e[13]=r,e[14]=b):b=e[14];let g;e[15]!==a?(g=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=g):g=e[16];let h;e[17]!==c||e[18]!==b||e[19]!==g?(h=s.jsx(Mn,{id:"sched-cron",value:c,onChange:b,placeholder:g,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=b,e[19]=g,e[20]=h):h=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 w;e[25]!==y||e[26]!==h||e[27]!==C?(w=s.jsxs("div",{className:"flex flex-col gap-1",children:[y,h,C]}),e[25]=y,e[26]=h,e[27]=C,e[28]=w):w=e[28];let S;e[29]!==p||e[30]!==m||e[31]!==a?(S=m.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:m.map(p).join(", ")})]}):null,e[29]=p,e[30]=m,e[31]=a,e[32]=S):S=e[32];let N;e[33]!==a?(N=a("sessions.scheduledTasks.editor.cronExpression.examples"),e[33]=a,e[34]=N):N=e[34];let k;e[35]!==N?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:N}),e[35]=N,e[36]=k):k=e[36];let j;e[37]!==r||e[38]!==a?(j=cj.map(V=>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(R=>({...R,schedule:{...R.schedule,cronExpression:V.expression}})),children:[s.jsx("span",{className:"font-mono",children:V.expression}),s.jsx("span",{className:"text-muted-foreground",children:a(V.labelKey)})]},V.expression)),e[37]=r,e[38]=a,e[39]=j):j=e[39];let D;e[40]!==j?(D=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:j}),e[40]=j,e[41]=D):D=e[41];let O;e[42]!==k||e[43]!==D?(O=s.jsxs("div",{className:"flex flex-col gap-1",children:[k,D]}),e[42]=k,e[43]=D,e[44]=O):O=e[44];let v;e[45]!==a?(v=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=v):v=e[46];let M;e[47]!==v?(M=s.jsx(Yn,{children:v}),e[47]=v,e[48]=M):M=e[48];let I;e[49]!==r?(I=V=>{r(R=>({...R,schedule:{...R.schedule,timezone:V}}))},e[49]=r,e[50]=I):I=e[50];let E;e[51]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),e[51]=E):E=e[51];let B;e[52]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(Gn,{children:ic.map(Aj)}),e[52]=B):B=e[52];let P;e[53]!==n.schedule.timezone||e[54]!==I?(P=s.jsxs(Un,{value:n.schedule.timezone,onValueChange:I,children:[E,B]}),e[53]=n.schedule.timezone,e[54]=I,e[55]=P):P=e[55];let W;e[56]!==M||e[57]!==P?(W=s.jsxs("div",{className:"flex flex-col gap-1",children:[M,P]}),e[56]=M,e[57]=P,e[58]=W):W=e[58];let _;return e[59]!==w||e[60]!==S||e[61]!==O||e[62]!==W?(_=s.jsxs("div",{className:"flex flex-col gap-3",children:[w,S,O,W]}),e[59]=w,e[60]=S,e[61]=O,e[62]=W,e[63]=_):_=e[63],_};function jj(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=bt(),l=ss(Z=>Z.loadProviders),d=ss(Z=>Z.loadAgents),f=ss(Z=>Z.providers),m=ss(Z=>Z.currentProviderId),u=ss(Z=>Z.currentModelId),p=ss(Z=>Z.currentVariant||""),x=ss(Z=>Z.currentAgentName||""),y=Ee(Z=>Z.timeFormatPreference),b=Ee(Z=>Z.weekStartPreference),g=Ee(Z=>Z.isMobile),[h,C]=Xe.useState(()=>ff(n,{providerID:m,modelID:u,variant:p,agent:x})),[w,S]=Xe.useState(!1),[N,k]=Xe.useState(!1),[j,D]=Xe.useState(!1),[O,v]=Xe.useState(""),[M,I]=Xe.useState(!1),[E,B]=Xe.useState(""),[P,W]=Xe.useState(!1),[_,V]=Xe.useState(""),[R,ne]=Xe.useState(()=>{const Z=pa(n?.schedule?.date||"")||new Date;return new Date(Z.getFullYear(),Z.getMonth(),1)}),ie=Xe.useRef(null),J=Xe.useRef(null),U=Xe.useRef(null),ee=Xe.useRef(null),ae=Xe.useRef(null),de=Xe.useMemo(()=>pj(c),[c]),ye=Xe.useMemo(()=>hj(c),[c]),se=Xe.useMemo(()=>y==="24h"?!0:y==="12h"?!1:de,[y,de]),we=Xe.useMemo(()=>b==="sunday"?0:b==="monday"?1:ye,[b,ye]),fe=Xe.useMemo(()=>{const Z=gj(c);return xj(yh.map(F=>({value:F,label:Z[F]||""})),we)},[c,we]);Xe.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),Xe.useEffect(()=>{if(!e)return;C(ff(n,{providerID:m,modelID:u,variant:p,agent:x}));const Z=pa(n?.schedule?.date||"")||new Date;ne(new Date(Z.getFullYear(),Z.getMonth(),1)),k(!1),I(!1),D(!1),B(""),v("")},[e,n,m,u,p,x]),Xe.useEffect(()=>{if(!N)return;const Z=F=>{ie.current&&!ie.current.contains(F.target)&&k(!1)};return document.addEventListener("mousedown",Z),()=>{document.removeEventListener("mousedown",Z)}},[N]);const Me=Xe.useMemo(()=>{const F=f.find(re=>re.id===h.execution.providerID)?.models?.find(re=>re.id===h.execution.modelID);return F?.variants?Object.keys(F.variants):[]},[f,h.execution.providerID,h.execution.modelID]),$=Me.length>0,K=Xe.useMemo(()=>!$||!h.execution.variant?"__default":Me.includes(h.execution.variant)?h.execution.variant:"__default",[h.execution.variant,$,Me]);Xe.useEffect(()=>{$||!h.execution.variant||C(Z=>({...Z,execution:{...Z.execution,variant:""}}))},[$,h.execution.variant]);const q=Xe.useCallback((Z,F)=>{C(re=>{const te=new Set(re.schedule.weekdays);return F?te.add(Z):te.delete(Z),{...re,schedule:{...re.schedule,weekdays:Array.from(te).sort((Ve,Ye)=>Ve-Ye)}}})},[]),me=Xe.useCallback((Z,F)=>{C(re=>{const te=re.schedule.times.slice();return te[Z]=F,{...re,schedule:{...re.schedule,times:te}}})},[]),je=Xe.useCallback(Z=>{C(F=>{const re=F.schedule.times.filter((te,Ve)=>Ve!==Z);return{...F,schedule:{...F.schedule,times:re.length>0?re:["09:00"]}}})},[]),Oe=Xe.useCallback(()=>{C(Z=>({...Z,schedule:{...Z.schedule,times:[...Z.schedule.times,"12:00"]}}))},[]),Be=Xe.useMemo(()=>bj(),[]),Fe=Xe.useMemo(()=>df(Be),[Be]),ue=Xe.useMemo(()=>{const Z=pa(h.schedule.onceDate);return Z?uf(Z,Be)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(Z):null},[h.schedule.onceDate,c,a,Be]),Re=Xe.useMemo(()=>df(R).getTime()<=Fe.getTime(),[R,Fe]),xe=Xe.useMemo(()=>fe.map(Z=>Z.label),[fe]),oe=Xe.useCallback(Z=>{C(F=>({...F,schedule:{...F.schedule,onceDate:Z}}))},[]),ve=Xe.useCallback((Z,F)=>{if(Z.startsWith("/")){const Ye=Z.indexOf(" "),Ke=Z.indexOf(`
168
- `),Je=Math.min(Ye===-1?Z.length:Ye,Ke===-1?Z.length:Ke);if(F<=Je&&Ye===-1){B(Z.substring(1,Je)),I(!0),D(!1),W(!1);return}}I(!1);const re=Z.substring(0,F),te=re.lastIndexOf("#");if(te!==-1){const Ye=te>0?re[te-1]:null,Ke=re.substring(te+1);if((!Ye||/\s/.test(Ye))&&!Ke.includes(" ")&&!Ke.includes(`
169
- `)){V(Ke),W(!0),D(!1);return}}W(!1);const Ve=re.lastIndexOf("@");if(Ve!==-1){const Ye=Ve>0?re[Ve-1]:null,Ke=re.substring(Ve+1);(!Ye||/\s/.test(Ye))&&!Ke.includes(" ")&&!Ke.includes(`
170
- `)?(v(Ke),D(!0)):D(!1);return}D(!1)},[]),Se=Xe.useCallback(Z=>{C(F=>({...F,execution:{...F.execution,prompt:Z}}))},[]),le=Xe.useCallback(Z=>{const F=h.execution.prompt,te=J.current?.selectionStart??F.length,Ye=F.substring(0,te).lastIndexOf("@"),Ke=Z.relativePath&&Z.relativePath.trim().length>0?Z.relativePath.trim():Z.path||Z.name,Je=Ye!==-1?Ye:te,nt=`${F.substring(0,Je)}@${Ke} ${F.substring(te)}`,xt=Je+Ke.length+2;Se(nt),D(!1),v(""),requestAnimationFrame(()=>{const jt=J.current;jt&&(jt.selectionStart=xt,jt.selectionEnd=xt,jt.focus()),ve(nt,xt)})},[h.execution.prompt,Se,ve]),T=Xe.useCallback(Z=>{const F=h.execution.prompt,te=J.current?.selectionStart??F.length,Ye=F.substring(0,te).lastIndexOf("@"),Ke=Ye!==-1?Ye:te,Je=`${F.substring(0,Ke)}@${Z} ${F.substring(te)}`,nt=Ke+Z.length+2;Se(Je),D(!1),v(""),requestAnimationFrame(()=>{const xt=J.current;xt&&(xt.selectionStart=nt,xt.selectionEnd=nt,xt.focus()),ve(Je,nt)})},[h.execution.prompt,Se,ve]),L=Xe.useCallback(Z=>{const F=`/${Z.name} `;Se(F),I(!1),B(""),W(!1),requestAnimationFrame(()=>{const re=J.current;re&&(re.focus(),re.selectionStart=re.value.length,re.selectionEnd=re.value.length),ve(F,F.length)})},[Se,ve]),he=Xe.useCallback((Z,F)=>{const re=h.execution.prompt,Ve=J.current?.selectionStart??re.length,Ke=re.substring(0,Ve).lastIndexOf("#"),Je=Ke!==-1?Ke:Ve,nt=`${re.substring(0,Je)}#${F} ${re.substring(Ve)}`,xt=Je+F.length+2;Se(nt),W(!1),V(""),requestAnimationFrame(()=>{const jt=J.current;jt&&(jt.selectionStart=xt,jt.selectionEnd=xt,jt.focus()),ve(nt,xt)})},[h.execution.prompt,Se,ve]),ge=Xe.useCallback(Z=>{if(M&&ee.current&&(Z.key==="Enter"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="Escape"||Z.key==="Tab")){Z.preventDefault(),ee.current.handleKeyDown(Z.key);return}j&&U.current&&(Z.key==="Enter"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="Escape"||Z.key==="Tab")&&(Z.preventDefault(),U.current.handleKeyDown(Z.key)),P&&ae.current&&(Z.key==="Enter"||Z.key==="ArrowUp"||Z.key==="ArrowDown"||Z.key==="Escape"||Z.key==="Tab")&&(Z.preventDefault(),ae.current.handleKeyDown(Z.key))},[M,j,P]),z=Xe.useCallback(async()=>{const Z=wj(h,a);if(Z){ce.error(Z);return}const F={...h.id?{id:h.id}:{},name:h.name.trim(),enabled:h.enabled,schedule:{kind:h.schedule.kind,timezone:h.schedule.timezone.trim(),...h.schedule.kind==="cron"?{cron:h.schedule.cronExpression.trim()}:h.schedule.kind==="once"?{date:h.schedule.onceDate,time:h.schedule.onceTime}:{times:vj(h.schedule.times),...h.schedule.kind==="weekly"?{weekdays:h.schedule.weekdays}:{}}},execution:{prompt:h.execution.prompt,providerID:h.execution.providerID,modelID:h.execution.modelID,...h.execution.variant.trim()?{variant:h.execution.variant.trim()}:{},...h.execution.agent.trim()?{agent:h.execution.agent.trim()}:{}},...h.state?{state:h.state}:{}};S(!0);try{await o(F),r(!1)}catch(re){ce.error(re instanceof Error?re.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{S(!1)}},[h,r,o,a]),pe=Xe.useId(),Ae=Xe.useCallback(()=>typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"], [data-slot="select-content"]'),[]),G=a(n?"sessions.scheduledTasks.editor.title.edit":"sessions.scheduledTasks.editor.title.new"),ke=a("sessions.scheduledTasks.editor.description"),Le=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(Yn,{htmlFor:"sched-name",required:!0,children:a("sessions.scheduledTasks.editor.taskName.label")}),s.jsx(Mn,{id:"sched-name",value:h.name,onChange:Z=>C(F=>({...F,name:Z.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(Yn,{children:a("sessions.scheduledTasks.editor.scheduleType.label")}),s.jsxs(Un,{value:h.schedule.kind,onValueChange:Z=>{C(F=>({...F,schedule:{...F.schedule,kind:Z,...Z==="cron"&&!F.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{children:Z=>a(Z==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":Z==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":Z==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(Rs,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(Rs,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(Rs,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),h.schedule.kind==="cron"?s.jsx(Sj,{draft:h,setDraft:C,locale:c,t:a}):h.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:ie,children:[s.jsx(Yn,{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:()=>k(Z=>!Z),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(A,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:dj(h.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"})]}),N?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:()=>ne(Z=>of(Z,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Re,children:s.jsx(A,{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(R)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>ne(Z=>of(Z,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(A,{name:"arrow-right-s",className:"h-4 w-4"})})]}),s.jsx("div",{className:"mb-1 grid grid-cols-7 gap-1 px-1",children:xe.map((Z,F)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:Z},`${Z}-${F}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:uj(R,we).map(({date:Z,inCurrentMonth:F})=>{const re=rf(Z),te=re===h.schedule.onceDate,Ve=uf(Z,Be),Ye=Z.getTime()<Be.getTime(),Ke=te?"bg-interactive-selection text-interactive-selection-foreground":Ye?"text-muted-foreground/40":F?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{Ye||(oe(re),k(!1))},disabled:Ye,className:["h-8 rounded-md typography-ui-label",Ke,Ve&&!te?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",Ye?"cursor-not-allowed opacity-45":""].join(" "),children:Z.getDate()},re)})}),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:ue||""}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:()=>{oe(rf(Be)),ne(new Date(Be.getFullYear(),Be.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(Yn,{children:a("sessions.scheduledTasks.editor.time.label")}),s.jsx(cf,{value:h.schedule.onceTime,use24Hour:se,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:Z=>C(F=>({...F,schedule:{...F.schedule,onceTime:Z}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Un,{value:h.schedule.timezone,onValueChange:Z=>{C(F=>({...F,schedule:{...F.schedule,timezone:Z}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),s.jsx(Gn,{children:ic.map(Z=>s.jsx(Rs,{value:Z,children:Z},Z))})]})]})]})]}):s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[h.schedule.kind==="weekly"?s.jsxs("div",{className:"flex flex-col gap-1 sm:col-span-2",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.weekdays.label")}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-2",children:fe.map(Z=>{const F=h.schedule.weekdays.includes(Z.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",F?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(Fi,{checked:F,onChange:re=>q(Z.value,re),ariaLabel:Z.label}),s.jsx("button",{type:"button",onClick:()=>q(Z.value,!F),className:"group-hover:text-foreground",children:Z.label})]},Z.value)})})]}):null,s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.times.label")}),s.jsx("div",{className:"flex flex-col gap-2",children:h.schedule.times.map((Z,F)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(cf,{value:Z,use24Hour:se,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:re=>me(F,re)}),h.schedule.times.length>1?s.jsx(ze,{type:"button",size:"icon",variant:"ghost",onClick:()=>je(F),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(A,{name:"close",className:"h-4 w-4"})}):null]},F))}),s.jsx("div",{children:s.jsxs(ze,{type:"button",size:"sm",variant:"outline",onClick:Oe,children:[s.jsx(A,{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(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Un,{value:h.schedule.timezone,onValueChange:Z=>{C(F=>({...F,schedule:{...F.schedule,timezone:Z}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),s.jsx(Gn,{children:ic.map(Z=>s.jsx(Rs,{value:Z,children:Z},Z))})]})]})]}),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(Yn,{required:!0,children:a("sessions.scheduledTasks.editor.model.label")}),s.jsx(Xf,{providerId:h.execution.providerID,modelId:h.execution.modelID,onChange:(Z,F)=>{C(re=>({...re,execution:{...re.execution,providerID:Z,modelID:F,variant:""}}))}})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.thinkingLevel.label")}),s.jsxs(Un,{value:K,disabled:!$,onValueChange:Z=>{C(F=>({...F,execution:{...F.execution,variant:Z==="__default"?"":Z}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{children:Z=>Z==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):Z})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),Me.map(Z=>s.jsx(Rs,{value:Z,children:Z},Z))]})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.agent.label")}),s.jsx(Zf,{agentName:h.execution.agent,filter:Z=>vc(Z.mode),onChange:Z=>C(F=>({...F,execution:{...F.execution,agent:Z}}))})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{htmlFor:"sched-prompt",required:!0,children:a("sessions.scheduledTasks.editor.prompt.label")}),s.jsxs("div",{className:"relative",children:[s.jsx(Ti,{id:"sched-prompt",ref:J,value:h.execution.prompt,onChange:Z=>{const F=Z.target.value;Se(F);const re=Z.target.selectionStart??F.length;ve(F,re)},onKeyDown:ge,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(um,{ref:ee,searchQuery:E,onCommandSelect:L,onClose:()=>I(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,j?s.jsx(fm,{ref:U,searchQuery:O,onFileSelect:le,onAgentSelect:T,onClose:()=>D(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,P?s.jsx(mm,{ref:ae,searchQuery:_,onSnippetSelect:he,onClose:()=>W(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]})]}),Te=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(Fi,{checked:h.enabled,onChange:Z=>C(F=>({...F,enabled:Z})),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:w,children:a("sessions.scheduledTasks.editor.actions.cancel")}),s.jsx(ze,{type:"button",size:"sm",onClick:z,disabled:w,children:a(w?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return g?s.jsx(Ha,{open:e,title:G,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:Z=>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:G}),Z]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:ke})]}),footer:Te,children:Le}):s.jsx(Ms,{open:e,onOpenChange:Z=>{!Z&&Ae()||r(Z)},children:s.jsxs(Es,{"aria-describedby":pe,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(an,{id:pe,className:"sr-only",children:ke}),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(zs,{className:"typography-ui-label font-medium text-foreground",children:G}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:ke})]})}),s.jsx(Ga,{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:Le})}),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:Te})})]})})}function Nj(t){return fo(t,{min:0,max:23})}function kj(t,e){return fo(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function Cj(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 Aj(t){return s.jsx(Rs,{value:t,children:t},t)}const Dj=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))},Tj=(t,e)=>{const n=Dj(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||""})},Pj=(t,e)=>!t||!Number.isFinite(t)?"":Kf(t,e),mf=(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),p=Math.round(r%a/o),x=p>0?`${u}h ${p}m`:`${u}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:x}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:x})}const d=Math.floor(r/c),f=Math.round(r%c/a),m=f>0?`${d}d ${f}h`:`${d}d`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:m}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:m})},Ij={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"}},Rj=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function Ej(){const{t}=bt(),e=Ee(P=>P.isScheduledTasksDialogOpen),n=Ee(P=>P.setScheduledTasksDialogOpen),r=Ee(P=>P.isMobile),o=Ee(P=>P.timeFormatPreference),a=ks(P=>P.projects),c=ks(P=>P.getActiveProject()),l=qs(P=>P.homeDirectory),{currentTheme:d}=pi(),[f,m]=Xe.useState(""),[u,p]=Xe.useState([]),[x,y]=Xe.useState(!0),[b,g]=Xe.useState(!1),[h,C]=Xe.useState(null),[w,S]=Xe.useState(null),N=Xe.useMemo(()=>a.find(P=>P.id===f)||null,[a,f]),k=Xe.useCallback(P=>{const W=P.label?.trim()||lo(P.path,l||void 0),_=P.icon?Pc[P.icon]:null,V=P.color?Ic[P.color]:void 0,R=_?s.jsx(A,{name:_,className:"h-3.5 w-3.5 shrink-0",style:V?{color:V}:void 0}):s.jsx(A,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:V?{color:V}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[P.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:P.iconBackground?{backgroundColor:P.iconBackground}:void 0,children:s.jsx(Rc,{project:{id:P.id,iconImage:P.iconImage??null},options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:R})}):R,s.jsx("span",{className:"truncate",children:W})]})},[l,d.metadata.variant,d.colors.surface.foreground]),j=Xe.useCallback(async(P,W)=>{if(!P){p([]);return}W?.silent||y(!0);try{const _=await ij(P);_.sort((V,R)=>{if(V.enabled!==R.enabled)return V.enabled?-1:1;const ne=V.name.localeCompare(R.name);return ne!==0?ne:(V.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(R.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),p(_)}catch(_){ce.error(_ instanceof Error?_.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),W?.silent||p([])}finally{W?.silent||y(!1)}},[t]);Xe.useEffect(()=>{if(!e)return;const P=c?.id||a[0]?.id||"";m(P),P?j(P):(p([]),y(!1))},[e,c,a,j]),Xe.useEffect(()=>{if(!e)return;let P=null;const W=xh(_=>{_.type==="scheduled-task-ran"&&_.projectId===f&&(P&&clearTimeout(P),P=setTimeout(()=>{j(f,{silent:!0})},400))});return()=>{P&&clearTimeout(P),W()}},[e,f,j]);const D=Xe.useCallback(async P=>{if(!f)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await sf(f,P),await j(f),ce.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[f,j,t]),O=Xe.useCallback(async(P,W)=>{if(f){S(P.id),p(_=>_.map(V=>V.id===P.id?{...V,enabled:W}:V));try{await sf(f,{...P,enabled:W}),await j(f,{silent:!0})}catch(_){ce.error(_ instanceof Error?_.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await j(f,{silent:!0})}finally{S(null)}}},[f,j,t]),v=Xe.useCallback(async P=>{if(!(!f||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:P.name})))){S(P.id);try{await oj(f,P.id),await j(f,{silent:!0}),ce.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(_){ce.error(_ instanceof Error?_.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{S(null)}}},[f,j,t]),M=Xe.useCallback(async P=>{if(f){S(P.id);try{await aj(f,P.id),await Promise.all([j(f,{silent:!0}),ka()]),ce.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch(W){ce.error(W instanceof Error?W.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{S(null)}}},[f,j,t]),I=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(Un,{value:f||"__none",onValueChange:P=>{const W=P==="__none"?"":P;m(W),W?j(W):p([])},children:[s.jsx(Hn,{className:r?"w-full":void 0,children:N?s.jsx(Cn,{children:k(N)}):s.jsx(Cn,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(Gn,{children:[a.length===0?s.jsx(Rs,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(P=>s.jsx(Rs,{value:P.id,children:k(P)},P.id))]})]})]}),E=()=>{C(null),g(!0)},B=s.jsxs("div",{className:"space-y-4",children:[r?I:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[I,s.jsxs(ze,{onClick:E,disabled:!f,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:x?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(A,{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(f?"sessions.scheduledTasks.dialog.empty.noTasks":"sessions.scheduledTasks.dialog.empty.selectProject")}):s.jsx("div",{className:"space-y-2.5",children:u.map(P=>{const W=w===P.id,_=P.state?.lastStatus||"idle",V=Ij[_],R=t(_==="success"?"sessions.scheduledTasks.dialog.status.success":_==="error"?"sessions.scheduledTasks.dialog.status.error":_==="running"?"sessions.scheduledTasks.dialog.status.running":"sessions.scheduledTasks.dialog.status.idle"),ne=P.state?.nextRunAt,ie=P.state?.lastRunAt;return s.jsxs("div",{className:Ie("rounded-lg border border-border p-4 transition-opacity",!P.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:P.name}),s.jsx("div",{className:"typography-micro truncate text-muted-foreground",children:Tj(P,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(A,{name:"timer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.nextRun.label")}),ne?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-foreground",children:mf(ne,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:Pj(ne,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(A,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),_==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(A,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):ie?s.jsxs(s.Fragment,{children:[V.tone!=="muted"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:`var(--status-${V.tone})`},children:[s.jsx(A,{name:V.Icon,className:"h-3.5 w-3.5"}),R]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:mf(ie,t)})]}):s.jsx("span",{children:t("sessions.scheduledTasks.dialog.lastRun.never")})]})]}),P.state?.lastError?s.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-md border p-2 typography-micro",style:Rj("error"),children:[s.jsx(A,{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:P.state.lastError})]}):null,s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("label",{className:Ie("inline-flex cursor-pointer items-center gap-2 typography-micro font-medium",P.enabled?"text-foreground":"text-muted-foreground",W&&"cursor-not-allowed opacity-50"),children:[s.jsx(Fi,{checked:P.enabled,onChange:J=>{O(P,J)},ariaLabel:P.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:P.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:P.name}),disabled:W}),P.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(P)},disabled:W,children:[s.jsx(A,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs(ze,{variant:"outline",size:"sm",onClick:()=>{C(P),g(!0)},disabled:W,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:P.name}),children:[s.jsx(A,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx(ze,{variant:"destructive",size:"sm",onClick:()=>{v(P)},disabled:W,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:P.name}),children:s.jsx(A,{name:"delete-bin",className:"h-4 w-4"})})]})]})]},P.id)})})})]});return s.jsxs(s.Fragment,{children:[r?s.jsx(Ha,{open:e,title:t("sessions.scheduledTasks.dialog.title"),onClose:()=>n(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:P=>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")}),P]}),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:!f,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:B}):s.jsx(Ms,{open:e,onOpenChange:n,children:s.jsxs(Es,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(Ys,{children:[s.jsx(zs,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(an,{children:t("sessions.scheduledTasks.dialog.description")})]}),B]})}),s.jsx(jj,{open:b,task:h,onOpenChange:g,onSave:D})]})}const Mj=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>rs(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(d=>Eo(d,t.normalizedPath,r)))(e.archivedSessions),c=e.sessions.filter(l=>l.time?.archived||rs(l.directory??null)?!1:Eo(l,t.normalizedPath,r));return ro([...a,...c])},Fj=t=>{const e=mt.c(12),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,isSessionsLoading:l,foldersMap:d,createFolder:f,addSessionToFolder:m,cleanupSessions:u}=t;let p,x;e[0]!==m||e[1]!==o||e[2]!==a||e[3]!==u||e[4]!==f||e[5]!==d||e[6]!==l||e[7]!==c||e[8]!==n||e[9]!==r?(p=()=>{l||n.forEach(y=>{const b=Bc(y.normalizedPath),g=Mj(y,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c}),h=new Set(g.map(Oj)),C=d[b]??[],w=new Map(C.map(Lj));g.forEach(S=>{const N=mb(S,y.normalizedPath),k=N.toLowerCase();let j=w.get(k);j||(j=f(b,N),w.set(k,j)),j.sessionIds.includes(S.id)||m(b,j.id,S.id)}),u(b,h)})},x=[n,r,o,a,c,l,d,f,m,u],e[0]=m,e[1]=o,e[2]=a,e[3]=u,e[4]=f,e[5]=d,e[6]=l,e[7]=c,e[8]=n,e[9]=r,e[10]=p,e[11]=x):(p=e[10],x=e[11]),i.useEffect(p,x)};function Oj(t){return t.id}function Lj(t){return[t.name.toLowerCase(),t]}const Bj=t=>{const e=mt.c(41),{normalizedProjects:n,getSessionsForProject:r,getArchivedSessionsForProject:o,availableWorktreesByProject:a,projectRepoStatus:c,projectRootBranches:l,lastRepoStatus:d,buildGroupedSessions:f,hasSessionSearchQuery:m,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:p,buildGroupSearchText:x,foldersMap:y}=t;let b;if(e[0]!==a||e[1]!==f||e[2]!==o||e[3]!==r||e[4]!==d||e[5]!==n||e[6]!==c||e[7]!==l){let v;e[9]!==a||e[10]!==f||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(v=M=>{const I=ro([...r(M),...o(M)]),E=a.get(M.normalizedPath)??[],B=c.has(M.id)?!!c.get(M.id):d,P=f(I,M.normalizedPath,E,l.get(M.id)??null,B);return{project:M,groups:P}},e[9]=a,e[10]=f,e[11]=o,e[12]=r,e[13]=d,e[14]=c,e[15]=l,e[16]=v):v=e[16],b=n.map(v),e[0]=a,e[1]=f,e[2]=o,e[3]=r,e[4]=d,e[5]=n,e[6]=c,e[7]=l,e[8]=b}else b=e[8];const g=b,h=g;let C;if(e[17]!==x||e[18]!==p||e[19]!==y||e[20]!==m||e[21]!==u||e[22]!==h){e:{const v=new WeakMap;if(!m){C=v;break e}const M=I=>I.reduce((E,B)=>E+1+M(B.children),0);h.forEach(I=>{I.groups.forEach(E=>{const B=p(E.sessions,u),P=M(B),W=x(E).includes(u),_=rs(E.directory??null),R=(_?y[_]??[]:[]).filter(ne=>ne.name.toLowerCase().includes(u)).length;v.set(E,{filteredNodes:B,matchedSessionCount:P,folderNameMatchCount:R,groupMatches:W,hasMatch:W||P>0||R>0})})}),C=v}e[17]=x,e[18]=p,e[19]=y,e[20]=m,e[21]=u,e[22]=h,e[23]=C}else C=e[23];const w=C;let S;e:{if(!m){S=h;break e}let v;if(e[24]!==w||e[25]!==h){let M;e[27]!==w?(M=I=>({...I,groups:I.groups.filter(E=>w.get(E)?.hasMatch===!0)}),e[27]=w,e[28]=M):M=e[28],v=h.map(M).filter(Vj),e[24]=w,e[25]=h,e[26]=v}else v=e[26];S=v}const N=S,k=m?N:h;let j;e:{if(!m){j=0;break e}let v;if(e[29]!==w||e[30]!==k){let M;e[32]!==w?(M=(I,E)=>I+E.groups.reduce((B,P)=>{const W=w.get(P);if(!W)return B;const _=W.folderNameMatchCount+(W.groupMatches?1:0);return B+W.matchedSessionCount+_},0),e[32]=w,e[33]=M):M=e[33],v=k.reduce(M,0),e[29]=w,e[30]=k,e[31]=v}else v=e[31];j=v}const D=j;let O;return e[34]!==w||e[35]!==g||e[36]!==D||e[37]!==N||e[38]!==k||e[39]!==h?(O={projectSections:g,visibleProjectSections:h,groupSearchDataByGroup:w,searchableProjectSections:N,sectionsForRender:k,searchMatchCount:D},e[34]=w,e[35]=g,e[36]=D,e[37]=N,e[38]=k,e[39]=h,e[40]=O):O=e[40],O};function Vj(t){return t.groups.length>0}const _j=t=>{const e=mt.c(26),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:c,handleSessionSelect:l,newSessionDraftOpen:d,mobileVariant:f,openNewSessionDraft:m,setActiveMainTab:u,setSessionSwitcherOpen:p}=t;let x,y;if(e[0]!==n){y=new Map,x=new Map;const k=(j,D,O,v)=>{y.has(j)||y.set(j,new Map);const M=y.get(j);v.forEach(I=>{const E=rs(I.worktree?.path??I.session.directory??O??D);M.set(I.session.id,{directory:E}),x.has(j)||x.set(j,{id:I.session.id,directory:E}),I.children.length>0&&k(j,D,E,I.children)})};n.forEach(j=>{j.groups.forEach(D=>{k(j.project.id,j.project.normalizedPath,D.directory,D.sessions)})}),e[0]=n,e[1]=x,e[2]=y}else x=e[1],y=e[2];let b;e[3]!==x||e[4]!==y?(b={metaByProject:y,firstSessionByProject:x},e[3]=x,e[4]=y,e[5]=b):b=e[5];const g=b,h=i.useRef(null);let C,w;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==f||e[11]!==d||e[12]!==m||e[13]!==n||e[14]!==g||e[15]!==u||e[16]!==a||e[17]!==p?(C=()=>{if(!r||d||Ee.getState().isNewWorktreeDialogOpen||h.current===r)return;const k=n.find(E=>E.project.id===r);if(!k)return;h.current=r;const j=g.metaByProject.get(r);if(c&&j&&j.has(c)){a(E=>{if(E.get(r)===c)return E;const B=new Map(E);return B.set(r,c),B});return}if(c&&j)return;if(!j||j.size===0){u("chat"),f&&p(!1),m({directoryOverride:k.project.normalizedPath});return}const D=o.get(r),O=D&&j.has(D)?D:null,v=g.firstSessionByProject.get(r)?.id??null,M=O??v;if(!M||M===c)return;const I=j.get(M)?.directory??null;l(M,I,r)},w=[r,o,c,l,d,f,m,n,g,u,p,a],e[6]=r,e[7]=o,e[8]=c,e[9]=l,e[10]=f,e[11]=d,e[12]=m,e[13]=n,e[14]=g,e[15]=u,e[16]=a,e[17]=p,e[18]=C,e[19]=w):(C=e[18],w=e[19]),i.useLayoutEffect(C,w);let S,N;e[20]!==r||e[21]!==c||e[22]!==g||e[23]!==a?(S=()=>{if(!r||!c)return;const k=g.metaByProject.get(r);!k||!k.has(c)||a(j=>{if(j.get(r)===c)return j;const D=new Map(j);return D.set(r,c),D})},N=[r,c,g,a],e[20]=r,e[21]=c,e[22]=g,e[23]=a,e[24]=S,e[25]=N):(S=e[24],N=e[25]),i.useEffect(S,N)},$j=t=>{const e=mt.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(zj)),f=[];return l.forEach(m=>{const u=d.get(m);u&&(f.push(u),d.delete(m))}),c.forEach(m=>{d.has(m.id)&&f.push(m)}),f},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 zj(t){return[t.id,t]}const ta=t=>!!t.time?.archived,Wj=t=>{const{t:e}=bt(),n=i.useCallback(c=>[c.label,c.branch??"",c.description??"",c.directory??""].join(" ").toLowerCase(),[]),r=i.useCallback(c=>{const l=rs(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 m=o(d.children,l);return m.length===0?[]:[{...d,children:m}]}):c,[r]),a=i.useCallback((c,l,d,f,m)=>{const u=rs(l??null),p=ro(c).sort((I,E)=>qi(I,E,t.pinnedSessionIds)),x=new Map(p.map(I=>[I.id,I])),y=new Map;p.forEach(I=>{const E=I.parentID;if(!E)return;const B=x.get(E);if(!B||ta(B)!==ta(I))return;const P=y.get(E)??[];P.push(I),y.set(E,P)}),y.forEach(I=>I.sort((E,B)=>qi(E,B,t.pinnedSessionIds)));const b=new Map;d.forEach(I=>{if(I.path){const E=rs(I.path)??I.path;b.set(E,I)}});const g=I=>{const E=rs(I.directory??null),B=t.worktreeMetadata.get(I.id)??null;if(B)return B;if(E){const P=b.get(E)??null;if(P&&E!==u)return P}return null},h=I=>{const E=y.get(I.id)??[];return{session:I,children:E.map(B=>h(B)),worktree:g(I)}},C=p.filter(I=>{const E=I.parentID;if(!E)return!0;const B=x.get(E);return B?ta(B)!==ta(I):!0}),w=new Map,S="__archived__",N=I=>{if(I.time?.archived)return S;if(t.isVSCode)return u??"__project_root__";const B=rs(t.worktreeMetadata.get(I.id)?.path??null)??Mr(I);return B?B!==u&&b.has(B)?B:B===u?u??"__project_root__":S:S};C.forEach(I=>{const E=h(I),B=N(I);w.has(B)||w.set(B,[]),w.get(B)?.push(E)});const k=u??"__project_root__",j=[{id:"root",label:m&&f&&f!=="HEAD"?e("sessions.sidebar.grouping.projectRootWithBranch",{branch:f}):e("sessions.sidebar.grouping.projectRoot"),branch:f??null,description:u?Ca(u,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:u,folderScopeKey:u,sessions:w.get(k)??[]}],D=new Map;d.forEach(I=>{const E=rs(I.path)??I.path,B=w.get(E)??[],P=B.length>0,W=B.reduce((_,V)=>{const R=Number(V.session.time?.updated??V.session.time?.created??0);return Number.isFinite(R)?Math.max(_,R):_},0);D.set(E,{hasActiveSession:P,lastUpdatedAt:W})});const O=[...d].sort((I,E)=>{const B=rs(I.path)??I.path,P=rs(E.path)??E.path,W=D.get(B)??{hasActiveSession:!1,lastUpdatedAt:0},_=D.get(P)??{hasActiveSession:!1,lastUpdatedAt:0};if(W.hasActiveSession!==_.hasActiveSession)return W.hasActiveSession?-1:1;if(W.hasActiveSession&&_.hasActiveSession)return _.lastUpdatedAt-W.lastUpdatedAt;const V=(I.label||I.branch||I.name||I.path||"").toLowerCase(),R=(E.label||E.branch||E.name||E.path||"").toLowerCase();return V.localeCompare(R)});(t.isVSCode?[]:O).forEach(I=>{const E=rs(I.path)??I.path,B=t.gitBranches.get(E)?.trim()||null,P=I.branch?.trim()||null,_=!!(B&&P&&I.label&&Jd(I.label)===Jd(P))?B:I.label||I.name||lo(E,t.homeDirectory)||E;j.push({id:`worktree:${E}`,label:_,branch:B||P,description:Ca(E,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:I,directory:E,folderScopeKey:E,sessions:w.get(E)??[]})});const M=w.get(S)??[];return M.length>0&&j.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?Bc(u):null,sessions:M}),j},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitBranches,t.isVSCode,e]);return{buildGroupSearchText:n,buildSessionSearchText:r,filterSessionNodesForSearch:o,buildGroupedSessions:a}},Uj=t=>{const e=mt.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 m=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(m)},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,f;e[4]!==n||e[5]!==a||e[6]!==r?(d=()=>{if(!n||typeof document>"u")return;const m=u=>{a.current&&(a.current.contains(u.target)||r(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},f=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=d,e[8]=f):(d=e[7],f=e[8]),i.useEffect(d,f)},Hj=t=>{const e=mt.c(42),{t:n}=bt(),[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=(W,_,V)=>{const R=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(V&&V!==t.activeProjectId&&t.setActiveProjectIdOnly(V),_&&_!==t.currentDirectory&&t.setDirectory(_,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),W===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(W),R();return}t.setCurrentSession(W,_??null),t.onSessionSelected?.(W),R()},e[2]=t,e[3]=d):d=e[3];const f=d;let m;e[4]!==t?(m=(W,_)=>{t.setEditingId(W),t.setEditTitle(_)},e[4]=t,e[5]=m):m=e[5];const u=m;let p;e[6]!==t?(p=async W=>{if(!t.editingId)return;const _=(W??t.editTitle).trim();_&&await t.updateSessionTitle(t.editingId,_),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=p):p=e[7];const x=p;let y;e[8]!==t?(y=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=y):y=e[9];const b=y;let g;e[10]!==t||e[11]!==n?(g=async W=>{const _=await t.shareSession(W.id);_&&_.share?.url?ce.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):ce.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=g):g=e[12];const h=g;let C;e[13]!==n?(C=(W,_)=>{dr(W).then(V=>{if(!V.ok){ce.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(_),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{ce.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=C):C=e[14];const w=C;let S;e[15]!==t||e[16]!==n?(S=async W=>{await t.unshareSession(W)?ce.success(n("sessions.sidebar.session.unshare.success")):ce.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=S):S=e[17];const N=S;let k;e[18]!==t.childrenMap?(k=W=>{const _=[],V=R=>{(t.childrenMap.get(R)??[]).forEach(ie=>{_.push(ie),V(ie.id)})};return V(W),_},e[18]=t.childrenMap,e[19]=k):k=e[19];const j=k,D=Kj;let O;e[20]!==t||e[21]!==j||e[22]!==n?(O=async(W,_,V)=>{const R=_?.archivedBucket===!0||_?.hardDelete===!0,ne=V?.descendantIds??D(j(W.id),R).map(qj);if(ne.length===0){(R?await t.deleteSession(W.id):await t.archiveSession(W.id))?ce.success(n(R?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):ce.error(n(R?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const ie=[W.id,...ne];if(R){const{deletedIds:ee,failedIds:ae}=await t.deleteSessions(ie);if(ae.length===0){const de=ee.length;ce.success(de===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:de}):n("sessions.sidebar.bulkActions.deletedPlural",{count:de}))}else ce.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:J,failedIds:U}=await t.archiveSessions(ie);J.length>0&&ce.success(J.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:J.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:J.length})),U.length>0&&ce.error(U.length===1?n("sessions.sidebar.bulkActions.failedArchiveSingle",{count:U.length}):n("sessions.sidebar.bulkActions.failedArchivePlural",{count:U.length}))},e[20]=t,e[21]=j,e[22]=n,e[23]=O):O=e[23];const v=O;let M;e[24]!==t||e[25]!==j||e[26]!==v?(M=(W,_)=>{const V=_?.archivedBucket===!0||_?.hardDelete===!0,R=D(j(W.id),V).map(Yj);if(!t.showDeletionDialog||_?.skipConfirm===!0){v(W,_,{descendantIds:R});return}t.setDeleteSessionConfirm({session:W,descendantCount:R.length,descendantIds:R,archivedBucket:V})},e[24]=t,e[25]=j,e[26]=v,e[27]=M):M=e[27];const I=M;let E;e[28]!==t||e[29]!==v?(E=async()=>{if(!t.deleteSessionConfirm)return;const{session:W,archivedBucket:_,descendantIds:V}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await v(W,{archivedBucket:_},{descendantIds:V})},e[28]=t,e[29]=v,e[30]=E):E=e[30];const B=E;let P;return e[31]!==B||e[32]!==r||e[33]!==b||e[34]!==w||e[35]!==I||e[36]!==x||e[37]!==u||e[38]!==f||e[39]!==h||e[40]!==N?(P={copiedSessionId:r,handleSessionSelect:f,handleSessionDoubleClick:u,handleSaveEdit:x,handleCancelEdit:b,handleShareSession:h,handleCopyShareUrl:w,handleUnshareSession:N,handleDeleteSession:I,confirmDeleteSession:B},e[31]=B,e[32]=r,e[33]=b,e[34]=w,e[35]=I,e[36]=x,e[37]=u,e[38]=f,e[39]=h,e[40]=N,e[41]=P):P=e[41],P};function Gj(t){return!t.time?.archived}function Kj(t,e){return e?t:t.filter(Gj)}function qj(t){return t.id}function Yj(t){return t.id}const Qj=["project:active:","project:archived:","recent:active:","recent:archived:"],Jj=t=>{const{isVSCode:e,hasLoadedGlobalSessions:n,safeStorage:r,keys:o,sessions:a,setPinnedSessionIds:c,groupOrderByProject:l,activeSessionByProject:d,collapsedGroups:f,setExpandedParents:m,setCollapsedProjects:u}=t,p=i.useRef(null),x=i.useRef(null),y=i.useCallback(()=>{if(e)return;const g=x.current;if(x.current=null,p.current=null,!g)return;const{projects:h}=ks.getState(),C=h.map(w=>({...w,sidebarCollapsed:g.has(w.id)}));mc({projects:C}).catch(()=>{})},[e]),b=i.useCallback(g=>{typeof window>"u"||e||(x.current=g,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{y()},700))},[e,y]);return i.useEffect(()=>()=>{typeof window<"u"&&p.current!==null&&window.clearTimeout(p.current),p.current=null,x.current=null},[]),i.useEffect(()=>{try{const g=r.getItem(o.sessionExpanded);if(g){const C=JSON.parse(g);Array.isArray(C)&&m(new Set(C.filter(w=>typeof w=="string")))}else{const C=r.getItem(o.sessionExpandedLegacy);if(C){try{const w=JSON.parse(C);if(Array.isArray(w)){const S=new Set;if(w.forEach(N=>{typeof N!="string"||N.length===0||Qj.forEach(k=>S.add(`${k}${N}`))}),S.size>0){m(S);try{r.setItem(o.sessionExpanded,JSON.stringify(Array.from(S)))}catch{}}}}catch{}try{r.removeItem?.(o.sessionExpandedLegacy)}catch{}}}const h=r.getItem(o.projectCollapse);if(h){const C=JSON.parse(h);Array.isArray(C)&&u(new Set(C.filter(w=>typeof w=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,u,m]),i.useEffect(()=>{if(!n||a.length===0)return;const g=new Set(a.map(h=>h.id));c(h=>{let C=!1;const w=new Set;return h.forEach(S=>{g.has(S)?w.add(S):C=!0}),C?w:h})},[n,a,c]),i.useEffect(()=>{try{const g=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(g))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const g=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(g))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(f)))}catch{}},[f,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:b}},Xj=t=>{const{normalizedProjects:e,gitRepoStatus:n,setProjectRepoStatus:r,setProjectRootBranches:o}=t,{git:a}=Xn(),c=wn(u=>u.ensureStatus);i.useEffect(()=>{if(!a||e.length===0){r(new Map);return}e.forEach(u=>{c(u.normalizedPath,a)})},[e,a,c,r]),i.useEffect(()=>{const u=new Map;e.forEach(p=>{u.set(p.id,n.get(p.normalizedPath)?.isGitRepo??null)}),r(u)},[e,n,r]);const l=i.useMemo(()=>e.map(u=>{const p=n.get(u.normalizedPath)?.branch??"";return`${u.id}:${p}`}).join("|"),[e,n]),d=i.useRef(new Map),f=i.useRef(new Map),m=5*6e4;i.useEffect(()=>{let u=!1;const p=setTimeout(()=>{(async()=>{const y=new Set(e.map(S=>S.id));for(const S of d.current.keys())y.has(S)||(d.current.delete(S),f.current.delete(S));const b=Date.now(),g=e.filter(S=>{const N=n.get(S.normalizedPath);if(N?.isGitRepo===!1)return d.current.delete(S.id),f.current.delete(S.id),!1;if(N?.isGitRepo!==!0||N.branch===null)return!1;const k=N.branch.trim(),j=`${S.normalizedPath}\0${k}`,D=d.current.get(S.id);if(D===j){const O=f.current.get(S.id);return O&&(O.at=b),!1}return!(D!==void 0&&b-(f.current.get(S.id)?.at??0)<m)});if(g.length===0)return;const h=await $m(g,2,async S=>{const N=n.get(S.normalizedPath)?.branch?.trim()??"",k=`${S.normalizedPath}\0${N}`,j=await qa(S.normalizedPath,N?{knownBranch:N}:void 0).catch(()=>null);return{id:S.id,inputKey:k,branch:j}});if(u)return;const C=h.filter(S=>S.branch);if(C.length===0)return;const w=Date.now();o(S=>{const N=new Map(S);return C.forEach(({id:k,branch:j})=>{j&&N.set(k,j)}),N}),C.forEach(({id:S,inputKey:N,branch:k})=>{d.current.set(S,N),k&&f.current.set(S,{branch:k,at:w})})})()},150);return()=>{u=!0,clearTimeout(p)}},[e,l,n,o])},Zj=t=>{const e=mt.c(19),{isVSCode:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,normalizedProjects:c}=t;let l;if(e[0]!==a||e[1]!==n||e[2]!==c){if(l=new Set,c.forEach(g=>{g.normalizedPath&&l.add(g.normalizedPath)}),!n)for(const g of a.values())for(const h of g){const C=rs(h.path);C&&l.add(C)}e[0]=a,e[1]=n,e[2]=c,e[3]=l}else l=e[3];const d=l;let f;e[4]!==d||e[5]!==r?(f=new Map,r.forEach(g=>{const h=Mr(g);if(!h||!d.has(h))return;const C=f.get(h)??[];C.push(g),f.set(h,C)}),e[4]=d,e[5]=r,e[6]=f):f=e[6];const m=f;let u;e[7]!==a||e[8]!==n||e[9]!==m?(u=g=>{const h=n?[]:a.get(g.normalizedPath)??[],C=[g.normalizedPath,...h.map(eN).filter(tN)],w=new Set,S=[];return C.forEach(N=>{(m.get(N)??[]).forEach(j=>{w.has(j.id)||(w.add(j.id),S.push(j))})}),S},e[7]=a,e[8]=n,e[9]=m,e[10]=u):u=e[10];const p=u;let x;e[11]!==o||e[12]!==a||e[13]!==n||e[14]!==r?(x=g=>{if(n){const k=o.filter(D=>{const O=rs(D.directory??null),v=rs(D.project?.worktree??null);return O?O===g.normalizedPath:v===g.normalizedPath}),j=r.filter(D=>D.time?.archived||rs(D.directory??null)?!1:rs(D.project?.worktree??null)===g.normalizedPath);return ro([...k,...j])}const h=n?[]:a.get(g.normalizedPath)??[],C=new Set([g.normalizedPath,...h.map(sN).filter(nN)]),S=(k=>k.filter(j=>Eo(j,g.normalizedPath,C)))(o),N=r.filter(k=>{if(k.time?.archived||rs(k.directory??null))return!1;const D=rs(k.project?.worktree??null);return D?D===g.normalizedPath||D.startsWith(`${g.normalizedPath}/`):!1});return ro([...S,...N])},e[11]=o,e[12]=a,e[13]=n,e[14]=r,e[15]=x):x=e[15];const y=x;let b;return e[16]!==y||e[17]!==p?(b={getSessionsForProject:p,getArchivedSessionsForProject:y},e[16]=y,e[17]=p,e[18]=b):b=e[18],b};function eN(t){return rs(t.path)??t.path}function tN(t){return!!t}function sN(t){return rs(t.path)??t.path}function nN(t){return!!t}const rN=t=>{const e=mt.c(10),{isSessionsLoading:n,hasLoadedGlobalSessions:r,sessions:o,archivedSessions:a,normalizedProjects:c,isVSCode:l,availableWorktreesByProject:d,cleanupSessions:f}=t;let m,u;e[0]!==a||e[1]!==d||e[2]!==f||e[3]!==r||e[4]!==n||e[5]!==l||e[6]!==c||e[7]!==o?(m=()=>{if(n||!r||o.length===0&&a.length===0)return;const p=new Map;o.forEach(b=>{const g=rs(b.directory??null);if(!g)return;const h=p.get(g);if(h){h.add(b.id);return}p.set(g,new Set([b.id]))}),c.forEach(b=>{const g=Bc(b.normalizedPath),h=l?[]:d.get(b.normalizedPath)??[],C=new Set([b.normalizedPath,...h.map(iN).filter(oN)]),w=ro([...a,...o.filter(S=>S.time?.archived||rs(S.directory??null)?!1:Eo(S,b.normalizedPath,C))]).filter(S=>Eo(S,b.normalizedPath,C));p.set(g,new Set(w.map(aN)))});const x=$n.getState().foldersMap;new Set([...Object.keys(x),...p.keys()]).forEach(b=>{f(b,p.get(b)??new Set)})},u=[a,d,f,r,n,l,c,o],e[0]=a,e[1]=d,e[2]=f,e[3]=r,e[4]=n,e[5]=l,e[6]=c,e[7]=o,e[8]=m,e[9]=u):(m=e[8],u=e[9]),i.useEffect(m,u)};function iN(t){return rs(t.path)??t.path}function oN(t){return!!t}function aN(t){return t.id}const lN=t=>{const e=mt.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 m=new IntersectionObserver(u=>{u.forEach(p=>{const x=p.target.dataset.projectId;x&&l(y=>{const b=new Set(y);return p.isIntersecting?b.delete(x):b.add(x),b})})},{threshold:0});return o.current.forEach(u=>{u&&m.observe(u)}),()=>m.disconnect()},e[1]=n,e[2]=o,e[3]=d):d=e[3];let f;return e[4]!==n||e[5]!==o||e[6]!==r?(f=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=f):f=e[7],i.useEffect(d,f),c},cN=t=>{const e=mt.c(10),{open:n,onOpenChange:r,project:o,onSave:a}=t;let c;e[0]!==a||e[1]!==n||e[2]!==o?(c=n&&o?s.jsx(Qx,{project:o,onIdentitySave:a}):null,e[0]=a,e[1]=n,e[2]=o,e[3]=c):c=e[3];let l;e[4]!==c?(l=s.jsx(Es,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(En,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:s.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:c})})}),e[4]=c,e[5]=l):l=e[5];let d;return e[6]!==r||e[7]!==n||e[8]!==l?(d=s.jsx(Ms,{open:n,onOpenChange:r,children:l}),e[6]=r,e[7]=n,e[8]=l,e[9]=d):d=e[9],d},dN=`**Help shape what OpenChamber becomes next!**
171
-
172
- Hey 👋,
173
-
174
- OpenChamber has grown mostly through word of mouth, GitHub issues, Discord feedback, and people telling me what is broken, confusing, or surprisingly useful.
175
-
176
- I'm planning the next chapter now - mobile, better remote access, a tighter VS Code ↔ desktop/web/mobile flow, and more, but before building too much, I want to hear from the people actually using it.
177
-
178
- I'm doing a round of short 1-on-1 calls. No sales pitch, no formal script - just a real conversation about how you use OpenChamber, what you love, what frustrates you, and what would make it much more valuable.
179
-
180
- You can book a call or use the short survey below.
181
-
182
- What you get:
183
-
184
- - A direct chance to influence the roadmap
185
- - Your pain points and feature requests prioritized with more context
186
- - A Power User role in Discord for people helping shape the product
187
- - My genuine thanks for helping make OpenChamber better
188
-
189
- **This project is what it is because of your feedback. Thank you, genuinely.**
190
-
191
- I'll remove this button in 10 days 🙂`;function uN(t){const e=mt.c(25),{open:n,onOpenChange:r}=t,{t:o}=bt();let a;e[0]!==o?(a=o("shareOpinion.dialog.title"),e[0]=o,e[1]=a):a=e[1];let c;e[2]!==a?(c=s.jsx(zs,{className:"sr-only",children:a}),e[2]=a,e[3]=c):c=e[3];let l;e[4]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(to,{content:dN,className:"typography-markdown-body",enableFileReferences:!1}),e[4]=l):l=e[4];let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(A,{name:"video-chat",className:"size-5 text-[var(--status-warning)]"}),e[5]=d):d=e[5];let f;e[6]!==o?(f=o("shareOpinion.actions.bookCall"),e[6]=o,e[7]=f):f=e[7];let m;e[8]!==f?(m=s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-2.5 typography-ui-label text-foreground hover:bg-[var(--interactive-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",onClick:mN,children:[d,f]}),e[8]=f,e[9]=m):m=e[9];let u;e[10]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(A,{name:"survey",className:"size-5 text-[var(--pr-merged)]"}),e[10]=u):u=e[10];let p;e[11]!==o?(p=o("shareOpinion.actions.shortSurvey"),e[11]=o,e[12]=p):p=e[12];let x;e[13]!==p?(x=s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-2.5 typography-ui-label text-foreground hover:bg-[var(--interactive-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",onClick:fN,children:[u,p]}),e[13]=p,e[14]=x):x=e[14];let y;e[15]!==m||e[16]!==x?(y=s.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[m,x]}),e[15]=m,e[16]=x,e[17]=y):y=e[17];let b;e[18]!==y||e[19]!==c?(b=s.jsxs(Es,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[c,l,y]}),e[18]=y,e[19]=c,e[20]=b):b=e[20];let g;return e[21]!==r||e[22]!==n||e[23]!==b?(g=s.jsx(Ms,{open:n,onOpenChange:r,children:b}),e[21]=r,e[22]=n,e[23]=b,e[24]=g):g=e[24],g}function fN(){qr("https://forms.gle/cdMVKUGs5QuLWkA86")}function mN(){qr("https://calendly.com/artmore/30min")}const hN=t=>{const e=mt.c(86),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:c,onRename:l,onDelete:d,renderSessionNode:f,getRenderExtras:m,groupDirectory:u,projectId:p,mobileVariant:x,alwaysShowActions:y,isRenaming:b,renameDraft:g,onRenameDraftChange:h,onRenameSave:C,onRenameCancel:w,droppableRef:S,isDropTarget:N,onNewSession:k,onNewSubFolder:j,depth:D,hideActions:O,archivedBucket:v}=t,I=y===void 0?x===void 0?!1:x:y,E=b===void 0?!1:b,B=g===void 0?"":g,P=N===void 0?!1:N,W=D===void 0?0:D,_=O===void 0?!1:O,V=v===void 0?!1:v,{t:R}=bt(),[ne,ie]=i.useState(!1),[J,U]=i.useState(""),ee=i.useRef(null),ae=E||ne,de=E?B:J;let ye;e[0]!==n.name?(ye=()=>{U(n.name),ie(!0)},e[0]=n.name,e[1]=ye):ye=e[1];const se=ye;let we;e[2]!==de||e[3]!==n.name||e[4]!==E||e[5]!==l||e[6]!==C?(we=()=>{const F=de.trim();F&&F!==n.name&&l(F),E&&C&&C(),ie(!1),U("")},e[2]=de,e[3]=n.name,e[4]=E,e[5]=l,e[6]=C,e[7]=we):we=e[7];const fe=we;let Me;e[8]!==E||e[9]!==w?(Me=()=>{E&&w&&w(),ie(!1),U("")},e[8]=E,e[9]=w,e[10]=Me):Me=e[10];const $=Me;let K;e[11]!==E||e[12]!==h?(K=F=>{E&&h?h(F):U(F)},e[11]=E,e[12]=h,e[13]=K):K=e[13];const q=K;let me,je;e[14]!==E?(me=()=>{if(!E)return;const F=()=>{const Ve=ee.current;Ve&&(Ve.focus(),Ve.select())},re=requestAnimationFrame(F),te=window.setTimeout(F,0);return()=>{cancelAnimationFrame(re),window.clearTimeout(te)}},je=[E],e[14]=E,e[15]=me,e[16]=je):(me=e[15],je=e[16]),i.useEffect(me,je);const Oe=a?"folder":"folder-open",Fe=W>0&&"ml-3";let ue;e[17]!==Fe?(ue=Ie("oc-folder",Fe),e[17]=Fe,e[18]=ue):ue=e[18];const Re=P&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let xe;e[19]!==Re?(xe=Ie("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",Re),e[19]=Re,e[20]=xe):xe=e[20];const oe=ae?void 0:c,ve=ae?void 0:"button",Se=ae?void 0:0;let le;e[21]!==c||e[22]!==ae?(le=ae?void 0:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),c())},e[21]=c,e[22]=ae,e[23]=le):le=e[23];let T;e[24]!==n.name||e[25]!==a||e[26]!==R?(T=a?R("sessions.sidebar.folderItem.expandAria",{folderName:n.name}):R("sessions.sidebar.folderItem.collapseAria",{folderName:n.name}),e[24]=n.name,e[25]=a,e[26]=R,e[27]=T):T=e[27];const L=V?I?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let he;e[28]!==L?(he=Ie("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",L),e[28]=L,e[29]=he):he=e[29];const ge=P?"text-primary":"text-muted-foreground";let z;e[30]!==ge?(z=Ie("h-3.5 w-3.5 flex-shrink-0",ge),e[30]=ge,e[31]=z):z=e[31];let pe;e[32]!==Oe||e[33]!==z?(pe=s.jsx(A,{name:Oe,className:z}),e[32]=Oe,e[33]=z,e[34]=pe):pe=e[34];let Ae;e[35]!==de||e[36]!==n.name||e[37]!==$||e[38]!==q||e[39]!==fe||e[40]!==a||e[41]!==P||e[42]!==ae||e[43]!==r||e[44]!==R?(Ae=ae?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:gN,onMouseDown:xN,onSubmit:F=>{F.preventDefault(),fe()},children:[s.jsx("input",{ref:ee,value:de,onChange:F=>q(F.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:R("sessions.sidebar.folderItem.namePlaceholder"),onClick:bN,onPointerDown:yN,onMouseDown:wN,onKeyDown:F=>{if(F.key==="Escape"){F.stopPropagation(),$();return}(F.key===" "||F.key==="Enter")&&F.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:vN,onPointerDown:SN,onMouseDown:jN,children:s.jsx(A,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),$()},onPointerDown:NN,onMouseDown:kN,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(A,{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:Ie("typography-ui-label font-semibold truncate",P?"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(A,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(A,{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]=$,e[38]=q,e[39]=fe,e[40]=a,e[41]=P,e[42]=ae,e[43]=r,e[44]=R,e[45]=Ae):Ae=e[45];let G;e[46]!==he||e[47]!==pe||e[48]!==Ae?(G=s.jsxs("div",{className:he,children:[pe,Ae]}),e[46]=he,e[47]=pe,e[48]=Ae,e[49]=G):G=e[49];let ke;e[50]!==I||e[51]!==V||e[52]!==W||e[53]!==n.name||e[54]!==se||e[55]!==_||e[56]!==d||e[57]!==k||e[58]!==j||e[59]!==ae||e[60]!==R?(ke=!ae&&(!_||V)?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:Ie("flex items-center gap-0.5 transition-opacity",I?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100",V&&"absolute right-0.5 top-1/2 z-10 -translate-y-1/2 px-0"),children:[!V&&k?s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),k()},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":R("sessions.sidebar.folderItem.newSessionAria",{folderName:n.name}),title:R("sessions.sidebar.project.actions.newSession"),children:s.jsx(A,{name:"add",className:"h-3.5 w-3.5"})}):null,!V&&j&&W===0?s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),j()},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":R("sessions.sidebar.folderItem.newSubfolderAria",{folderName:n.name}),title:R("sessions.sidebar.folderItem.newSubfolder"),children:s.jsx(A,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,V?null:s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),se()},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":R("sessions.sidebar.folderItem.renameAria",{folderName:n.name}),children:s.jsx(A,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:F=>{F.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":V?R("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):R("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=I,e[51]=V,e[52]=W,e[53]=n.name,e[54]=se,e[55]=_,e[56]=d,e[57]=k,e[58]=j,e[59]=ae,e[60]=R,e[61]=ke):ke=e[61];let Le;e[62]!==S||e[63]!==xe||e[64]!==oe||e[65]!==ve||e[66]!==Se||e[67]!==le||e[68]!==T||e[69]!==G||e[70]!==ke?(Le=s.jsxs("div",{ref:S,className:xe,onClick:oe,role:ve,tabIndex:Se,onKeyDown:le,"aria-label":T,children:[G,ke]}),e[62]=S,e[63]=xe,e[64]=oe,e[65]=ve,e[66]=Se,e[67]=le,e[68]=T,e[69]=G,e[70]=ke,e[71]=Le):Le=e[71];let Te;e[72]!==V||e[73]!==m||e[74]!==u||e[75]!==a||e[76]!==p||e[77]!==f||e[78]!==r||e[79]!==o||e[80]!==R?(Te=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(F=>f(F,0,u??null,p??null,V,void 0,"project",m?.(F))):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:R("sessions.sidebar.folderItem.emptyFolder")})]}),e[72]=V,e[73]=m,e[74]=u,e[75]=a,e[76]=p,e[77]=f,e[78]=r,e[79]=o,e[80]=R,e[81]=Te):Te=e[81];let Z;return e[82]!==ue||e[83]!==Le||e[84]!==Te?(Z=s.jsxs("div",{className:ue,children:[Le,Te]}),e[82]=ue,e[83]=Le,e[84]=Te,e[85]=Z):Z=e[85],Z},pN=i.memo(hN);function gN(t){return t.stopPropagation()}function xN(t){return t.stopPropagation()}function bN(t){return t.stopPropagation()}function yN(t){return t.stopPropagation()}function wN(t){return t.stopPropagation()}function vN(t){return t.stopPropagation()}function SN(t){return t.stopPropagation()}function jN(t){return t.stopPropagation()}function NN(t){return t.stopPropagation()}function kN(t){return t.stopPropagation()}const CN=t=>{const e=mt.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:f,listeners:m,setNodeRef:u,isDragging:p}=ep(d);let x;e[7]!==m?(x=h=>{h.stopPropagation(),m?.onPointerDown&&m.onPointerDown(h)},e[7]=m,e[8]=x):x=e[8];const y=x,b=p?"opacity-30":void 0;let g;return e[9]!==f||e[10]!==a||e[11]!==y||e[12]!==u||e[13]!==b?(g=s.jsx("div",{ref:u,...f,onPointerDown:y,className:b,children:a}),e[9]=f,e[10]=a,e[11]=y,e[12]=u,e[13]=b,e[14]=g):g=e[14],g},AN=t=>{const e=mt.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}=Zh(c);let f;e[5]!==r||e[6]!==d||e[7]!==l?(f=r(l,d),e[5]=r,e[6]=d,e[7]=l,e[8]=f):f=e[8];let m;return e[9]!==f?(m=s.jsx(s.Fragment,{children:f}),e[9]=f,e[10]=m):m=e[10],m},DN=t=>{const e=mt.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=ba(vo(ya,c)),[d,f]=i.useState(null),[m,u]=i.useState("Session"),[p,x]=i.useState(null),[y,b]=i.useState(null);if(!n){let j;return e[1]!==a?(j=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=j):j=e[2],j}let g;e[3]!==o?(g=j=>{f(null),x(null),b(null);const{active:D,over:O}=j;if(!O)return;const v=D.data.current,M=O.data.current;v?.type==="session"&&v.sessionId&&M?.type==="folder"&&M.folderId&&o(v.sessionId,M.folderId)},e[3]=o,e[4]=g):g=e[4];const h=g;let C,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(C=j=>{const D=j.active.data.current;if(D?.type==="session"&&D.sessionId){f(D.sessionId),u(D.sessionTitle??"Session");const O=j.active.rect.current.initial?.width,v=j.active.rect.current.initial?.height;x(typeof O=="number"?O:null),b(typeof v=="number"?v:null)}},w=()=>{f(null),x(null),b(null)},e[5]=C,e[6]=w):(C=e[5],w=e[6]);let S;e[7]!==y||e[8]!==d||e[9]!==m||e[10]!==p||e[11]!==r?(S=d&&r?s.jsxs("div",{style:{width:p?`${p}px`:"auto",height:y?`${y}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(A,{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:m})]}):null,e[7]=y,e[8]=d,e[9]=m,e[10]=p,e[11]=r,e[12]=S):S=e[12];let N;e[13]!==S?(N=s.jsx(zl,{children:S}),e[13]=S,e[14]=N):N=e[14];let k;return e[15]!==a||e[16]!==h||e[17]!==l||e[18]!==N?(k=s.jsxs(wa,{sensors:l,collisionDetection:va,onDragStart:C,onDragCancel:w,onDragEnd:h,children:[a,N]}),e[15]=a,e[16]=h,e[17]=l,e[18]=N,e[19]=k):k=e[19],k},Ki=(t,e,n)=>{if(!e)return;const r=o=>{let a=o.session.id===e;for(const c of o.children)a=r(c)||a;return a&&n.add(o.session.id),a};for(const o of t)r(o)},Ur=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if(Ur(n,e))return!0;return!1},Oa=t=>t.children.length===0?"":t.children.map(n=>n.children.length===0?n.session.id:`${n.session.id}:${Oa(n)}`).join("|"),Oo=(t,e,n,r)=>{if(!e)return null;const o=r?"archived":"active";let a=null;const c=l=>{if(`${n}:${o}:${l.session.id}`===e)return a=l.session.id,!0;for(const f of l.children)if(c(f))return!0;return!1};return t.forEach(l=>c(l)),a},Ir=oo()(dc(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}})),TN=50,PN=30,IN=28,$i=(t,e)=>e?t.sessions.some(n=>Ur(n,e)):!1,RN=(t,e,n)=>{const r=o=>{const a=o.session.id;return e.has(a)!==n.has(a)?!0:o.children.some(r)};return t.sessions.some(r)},EN=(t,e,n)=>{const r=o=>{const a=o.session.id;return e.get(a)!==n.get(a)?!0:o.children.some(r)};return t.sessions.some(r)},MN=(t,e,n)=>{const r=t.isArchivedBucket?"archived":"active",o=a=>{const c=`project:${r}:${a.session.id}`;return e.has(c)!==n.has(c)?!0:a.children.some(o)};return t.sessions.some(o)},FN=(t,e,n)=>{const r=o=>{const a=o.session.id;return(e.get(a)??o.session)!==(n.get(a)??o.session)?!0:o.children.some(r)};return t.sessions.some(r)},hf=t=>{if(t.projectId)return t.projectRepoStatus.has(t.projectId)?t.projectRepoStatus.get(t.projectId):void 0},ON=(t,e)=>{if(t.group!==e.group||t.groupKey!==e.groupKey||t.projectId!==e.projectId||t.hideGroupLabel!==e.hideGroupLabel||t.compactBodyPadding!==e.compactBodyPadding||t.groupSearchDataByGroup!==e.groupSearchDataByGroup||t.visibleSessionCount!==e.visibleSessionCount||t.collapsedGroups!==e.collapsedGroups&&t.collapsedGroups.has(t.groupKey)!==e.collapsedGroups.has(e.groupKey)||t.projectRepoStatus!==e.projectRepoStatus&&hf(t)!==hf(e)||t.pinnedSessionIds!==e.pinnedSessionIds&&RN(e.group,t.pinnedSessionIds,e.pinnedSessionIds)||t.expandedParents!==e.expandedParents&&MN(e.group,t.expandedParents,e.expandedParents)||t.sessionOrderIndex!==e.sessionOrderIndex&&EN(e.group,t.sessionOrderIndex,e.sessionOrderIndex)||t.currentSessionId!==e.currentSessionId&&($i(t.group,t.currentSessionId)||$i(e.group,e.currentSessionId))||t.editingId!==e.editingId&&($i(t.group,t.editingId)||$i(e.group,e.editingId))||t.editTitle!==e.editTitle&&($i(t.group,t.editingId)||$i(e.group,e.editingId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=Oo(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket),r=Oo(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket);if(n||r)return!1}if(t.liveSessionById!==e.liveSessionById&&FN(e.group,t.liveSessionById,e.liveSessionById))return!1;if(t.prVisualStateByDirectoryBranch!==e.prVisualStateByDirectoryBranch){const n=t.group?.directory&&t.group?.branch?t.prVisualStateByDirectoryBranch.get(`${t.group.directory}::${t.group.branch.trim()}`):void 0,r=e.group?.directory&&e.group?.branch?e.prVisualStateByDirectoryBranch.get(`${e.group.directory}::${e.group.branch.trim()}`):void 0;if(!Object.is(n,r))return!1}return t.hasSessionSearchQuery===e.hasSessionSearchQuery&&t.normalizedSessionSearchQuery===e.normalizedSessionSearchQuery&&t.hideDirectoryControls===e.hideDirectoryControls&&t.collapsedFolderIds===e.collapsedFolderIds&&t.toggleFolderCollapse===e.toggleFolderCollapse&&t.renameFolder===e.renameFolder&&t.deleteFolder===e.deleteFolder&&t.showDeletionDialog===e.showDeletionDialog&&t.setDeleteFolderConfirm===e.setDeleteFolderConfirm&&t.renderSessionNode===e.renderSessionNode&&t.lastRepoStatus===e.lastRepoStatus&&t.showMoreGroupSessions===e.showMoreGroupSessions&&t.resetGroupSessionLimit===e.resetGroupSessionLimit&&t.mobileVariant===e.mobileVariant&&t.alwaysShowActions===e.alwaysShowActions&&t.activeProjectId===e.activeProjectId&&t.setActiveProjectIdOnly===e.setActiveProjectIdOnly&&t.setActiveMainTab===e.setActiveMainTab&&t.setSessionSwitcherOpen===e.setSessionSwitcherOpen&&t.openNewSessionDraft===e.openNewSessionDraft&&t.addSessionToFolder===e.addSessionToFolder&&t.createFolderAndStartRename===e.createFolderAndStartRename&&t.renamingFolderId===e.renamingFolderId&&t.renameFolderDraft===e.renameFolderDraft&&t.setRenameFolderDraft===e.setRenameFolderDraft&&t.setRenamingFolderId===e.setRenamingFolderId&&t.onToggleCollapsedGroup===e.onToggleCollapsedGroup&&t.dragHandleProps===e.dragHandleProps&&t.scrollContainerRef===e.scrollContainerRef};function LN(t){const{t:e}=bt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:f,collapsedGroups:m,hideDirectoryControls:u,collapsedFolderIds:p,toggleFolderCollapse:x,renameFolder:y,deleteFolder:b,showDeletionDialog:g,setDeleteFolderConfirm:h,renderSessionNode:C,projectRepoStatus:w,lastRepoStatus:S,showMoreGroupSessions:N,resetGroupSessionLimit:k,mobileVariant:j,alwaysShowActions:D,activeProjectId:O,setActiveProjectIdOnly:v,setActiveMainTab:M,setSessionSwitcherOpen:I,openNewSessionDraft:E,addSessionToFolder:B,createFolderAndStartRename:P,renamingFolderId:W,renameFolderDraft:_,setRenameFolderDraft:V,setRenamingFolderId:R,pinnedSessionIds:ne,expandedParents:ie,sessionOrderIndex:J,currentSessionId:U,editingId:ee,openSidebarMenuKey:ae,prVisualStateByDirectoryBranch:de,onToggleCollapsedGroup:ye,dragHandleProps:se,compactBodyPadding:we=!1,scrollContainerRef:fe}=t,Me=i.useCallback((He,it)=>{const It=J.get(He.session.id),Rt=J.get(it.session.id);if(It!==void 0||Rt!==void 0){if(It===void 0)return 1;if(Rt===void 0)return-1;if(It!==Rt)return It-Rt}return qi(He.session,it.session,ne)},[ne,J]),$=c?d.get(n):null,K=Ir(He=>He.displayMode),q=$n(He=>He.foldersMap),me=K==="minimal"&&!Yr(),je=c?!1:m.has(r),Oe=u?10:5,Be=Math.max(Oe,f??Oe),Fe=c?$?.groupMatches===!0:!1,ue=c,Re=i.useMemo(()=>[...ue?$?.filteredNodes??[]:n.sessions].sort(Me),[Me,n.sessions,$?.filteredNodes,ue]),xe=n.folderScopeKey??rs(n.directory??null),oe=i.useMemo(()=>xe?q[xe]??[]:[],[xe,q]),ve=i.useMemo(()=>{const He=new Map,it=It=>{It.forEach(Rt=>{He.set(Rt.session.id,Rt),Rt.children.length>0&&it(Rt.children)})};return it(Re),He},[Re]),Se=i.useMemo(()=>oe.map(He=>{const it=He.sessionIds.map(It=>ve.get(It)).filter(It=>!!It).sort(Me);return{folder:He,nodes:it}}),[oe,ve,Me]),le=i.useMemo(()=>{const He=new Map(Se.map(Pt=>[Pt.folder.id,Pt])),it=new Map;for(const{folder:Pt}of Se){if(!Pt.parentId)continue;const ps=it.get(Pt.parentId);ps?ps.push(Pt.id):it.set(Pt.parentId,[Pt.id])}const It=new Map,Rt=Pt=>{const ps=It.get(Pt);if(ps!==void 0)return ps;const ls=He.get(Pt);if(!ls)return It.set(Pt,!1),!1;const ns=it.get(Pt)??[];if(n.isArchivedBucket&&ls.nodes.length===0){const fs=ns.some(Fs=>Rt(Fs));return It.set(Pt,fs),fs}if(!c||ls.folder.name.toLowerCase().includes(l)||ls.nodes.length>0)return It.set(Pt,!0),!0;const ln=ns.some(fs=>Rt(fs));return It.set(Pt,ln),ln};return Se.filter(({folder:Pt})=>Rt(Pt.id))},[Se,n.isArchivedBucket,c,l]),T=i.useMemo(()=>new Set(le.flatMap(He=>He.folder.sessionIds)),[le]),L=i.useMemo(()=>Re.filter(He=>!T.has(He.session.id)),[Re,T]),he=i.useMemo(()=>le.filter(({folder:He})=>!He.parentId),[le]),ge="project",z=i.useMemo(()=>{const He=new Set;return Ki(Re,U,He),le.forEach(({nodes:it})=>{Ki(it,U,He)}),He},[Re,le,U]),pe=i.useMemo(()=>{const He=new Set;return Ki(Re,ee,He),le.forEach(({nodes:it})=>{Ki(it,ee,He)}),He},[Re,le,ee]),Ae=i.useMemo(()=>{if(!ae)return null;const He=Oo(Re,ae,ge,!!n.isArchivedBucket);if(He)return He;for(const{nodes:it}of le){const It=Oo(it,ae,ge,!!n.isArchivedBucket);if(It)return It}return null},[ae,Re,le,n.isArchivedBucket]),G=i.useCallback(He=>{const it=new WeakMap,It=Rt=>{it.set(Rt,Oa(Rt));for(const Pt of Rt.children)It(Pt)};return He.forEach(It),it},[]),ke=i.useMemo(()=>G(Re),[G,Re]),Le=i.useMemo(()=>{const He=new WeakMap;return le.forEach(({nodes:it})=>{it.forEach(It=>He.set(It,Oa(It)))}),He},[le]),Te=i.useCallback(He=>ke.get(He)??Le.get(He)??"",[ke,Le]),Z=i.useCallback(He=>({subtreeContainsActive:z,subtreeContainsEditing:pe,menuOpenSessionId:Ae,nodeStructureKey:Te(He)}),[z,pe,Ae,Te]),F=L.length,re=n.isArchivedBucket||c?L:L.slice(0,Be),te=F-re.length,Ve=!n.isArchivedBucket&&!c&&F>Oe&&te===0,Ye=n.isArchivedBucket===!0&&!c&&re.length>=TN,Ke=n.isArchivedBucket!==!0&&!c&&re.length>=PN,Je=Ye||Ke,nt=n.isArchivedBucket?"archived":"active",xt=Je&&re.some(He=>{if(He.children.length===0)return!1;const it=`project:${nt}:${He.session.id}`;return ie.has(it)}),jt=i.useRef(null),[Mt,Et]=i.useState(null),[Ut,zt]=i.useState(0),[,Ht]=i.useState(0);i.useEffect(()=>{if(!Je)return;const He=jt.current;if(!He||typeof ResizeObserver>"u")return;const it=new ResizeObserver(()=>Ht(It=>It+1));return it.observe(He),()=>it.disconnect()},[Je]),i.useLayoutEffect(()=>{if(!Je){Mt!==null&&Et(null),Ut!==0&&zt(0);return}const He=jt.current;if(!He)return;let it=Mt;const It=fe?.current??null;if(It&&It.contains(He)){if(it=It,it!==Mt){Et(it);return}}else if(!it||!it.contains(He)){let Pt=He.parentElement;for(;Pt;){const ps=window.getComputedStyle(Pt);if(ps.overflowY==="auto"||ps.overflowY==="scroll"){it=Pt;break}Pt=Pt.parentElement}if(it!==Mt){Et(it);return}}if(!it)return;const Rt=He.getBoundingClientRect().top-it.getBoundingClientRect().top+it.scrollTop;zt(Pt=>Math.abs(Pt-Rt)<1?Pt:Rt)});const _t=Je&&Mt!==null,Gt=tp({count:re.length,enabled:_t,getScrollElement:()=>Mt,initialOffset:()=>Mt?.scrollTop??0,estimateSize:()=>IN,overscan:xt?20:8,scrollMargin:Ut,getItemKey:He=>re[He]?.session.id??He}),Ce=i.useCallback(He=>{const it=[],It=Rt=>{Rt.forEach(Pt=>{it.push(Pt.session),Pt.children.length>0&&It(Pt.children)})};return It(He),it},[]),Qe=i.useMemo(()=>Ce(Re),[Ce,Re]),et=i.useMemo(()=>{if(!n.isArchivedBucket)return new Map;const He=new Map,it=new Map;for(const{folder:Rt}of le){if(!Rt.parentId)continue;const Pt=it.get(Rt.parentId)??[];Pt.push(Rt.id),it.set(Rt.parentId,Pt)}const It=(Rt,Pt)=>{if(Pt.has(Rt))return[];Pt.add(Rt);const ps=le.find(({folder:Wt})=>Wt.id===Rt),ls=ps?Ce(ps.nodes):[],ns=it.get(Rt)??[];for(const Wt of ns)ls.push(...It(Wt,Pt));return ls};for(const{folder:Rt}of le)He.set(Rt.id,It(Rt.id,new Set));return He},[le,Ce,n.isArchivedBucket]);if(c&&!Fe&&he.length===0&&L.length===0)return null;const yt=o&&w.has(o)?!!w.get(o):S,We=rs(n.directory??null),at=n.branch?.trim()??null,qe=We&&at?de.get(`${We}::${at}`)??null:null,lt=!!(qe&&n.branch),Dt=!qe&&!n.isMain&&!!n.branch,us=qe?.visualState??null,Lt=qe&&qe.state==="open"&&qe.checks?e("sessions.sidebar.group.pr.checksPassed",{success:qe.checks.success,total:qe.checks.total}):null,es=qe&&qe.state==="open"&&qe.checks?[qe.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:qe.checks.failure}):null,qe.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:qe.checks.pending}):null].filter(He=>!!He).join(", "):null,os=qe&&qe.state==="open"?qe.mergeableState==="blocked"||qe.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):qe.mergeableState==="clean"||qe.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,Qt=qe&&qe.state==="open"&&qe.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:qe.mergeableState}):null,Ft=qe?.base??null,Xt=qe?.head??null,as=(()=>{if(!qe)return n.branch&&hb(n.branch,n.label)?{label:n.branch,color:null}:null;switch(qe.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return qe.canMerge===!0||qe.mergeableState==="clean"||qe.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:qe.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}})(),$t=as?.color??(us?`var(--pr-${us})`:void 0),bs=He=>{He.preventDefault(),He.stopPropagation();const it=qe?.url;it&&qr(it)},Cs=(He,it,It)=>{const Rt=le.filter(({folder:ls})=>ls.parentId===He.id),Pt=Rt.length>0?s.jsx(s.Fragment,{children:Rt.map(({folder:ls,nodes:ns})=>Cs(ls,ns,It+1))}):void 0,ps=et.get(He.id)??[];return s.jsx(AN,{folderId:He.id,children:(ls,ns)=>s.jsx(pN,{folder:He,sessions:it,subFolderItems:Pt,isCollapsed:c?!1:p.has(He.id),onToggle:()=>x(He.id),onRename:Wt=>{xe&&y(xe,He.id,Wt)},onDelete:()=>{if(n.isArchivedBucket){Er.requestDelete({sessions:ps,mode:"session"});return}if(!xe)return;if(!g){b(xe,He.id);return}const Wt=le.filter(({folder:fs})=>fs.parentId===He.id).length,ln=it.length;h({scopeKey:xe,folderId:He.id,folderName:He.name,subFolderCount:Wt,sessionCount:ln})},renderSessionNode:C,getRenderExtras:Te?Wt=>({subtreeContainsActive:z,subtreeContainsEditing:pe,menuOpenSessionId:Ae,nodeStructureKey:Te(Wt),childRenderExtrasFor:Z}):void 0,groupDirectory:n.directory,projectId:o,mobileVariant:j,alwaysShowActions:D,isRenaming:W===He.id,renameDraft:W===He.id?_:void 0,onRenameDraftChange:Wt=>V(Wt),onRenameSave:()=>{const Wt=_.trim();Wt&&xe&&y(xe,He.id,Wt),R(null),V("")},onRenameCancel:()=>{R(null),V("")},droppableRef:ls,isDropTarget:ns,depth:It,onNewSession:()=>{o&&o!==O&&v(o),M("chat"),j&&I(!1),E({directoryOverride:n.directory,targetFolderId:He.id})},onNewSubFolder:It===0?()=>{xe&&P(xe,He.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},He.id)},Tt=()=>he.map(({folder:He,nodes:it})=>Cs(He,it,0)),Bt=!!(!n.isMain&&n.worktree),vt=D?Bt?"pr-14":"pr-7":me?Bt?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":Bt?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",vs=s.jsxs(DN,{scopeKey:xe,hasFolders:le.length>0,onSessionDroppedOnFolder:(He,it)=>{xe&&B(xe,it,He)},children:[Tt(),Je?s.jsx("div",{ref:jt,children:_t?s.jsx("div",{style:{height:Gt.getTotalSize(),position:"relative"},children:Gt.getVirtualItems().map(He=>{const it=re[He.index];return it?s.jsx("div",{"data-index":He.index,ref:Gt.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${He.start-Ut}px)`},children:C(it,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:z,subtreeContainsEditing:pe,menuOpenSessionId:Ae,nodeStructureKey:Te(it),childRenderExtrasFor:Z})},it.session.id):null})}):re.map(He=>C(He,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:z,subtreeContainsEditing:pe,menuOpenSessionId:Ae,nodeStructureKey:Te(He),childRenderExtrasFor:Z}))}):re.map(He=>C(He,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:z,subtreeContainsEditing:pe,menuOpenSessionId:Ae,nodeStructureKey:Te(He),childRenderExtrasFor:Z})),F===0&&le.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,te>0?s.jsx("button",{type:"button",onClick:()=>N(r,re.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,Ve?s.jsx("button",{type:"button",onClick:()=>k(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]}),hs=we?"pb-2 pl-1":"pb-3 pl-4";return a?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:Ie("oc-group-body",hs),children:vs})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:Ie("group/gh relative flex items-start justify-between gap-1 py-1 min-w-0 rounded-md","cursor-pointer"),onClick:()=>ye(r),role:"button",tabIndex:0,onKeyDown:He=>{(He.key==="Enter"||He.key===" ")&&(He.preventDefault(),ye(r))},"aria-label":je?e("sessions.sidebar.group.expandAria",{label:n.label}):e("sessions.sidebar.group.collapseAria",{label:n.label}),"aria-expanded":!je,children:[s.jsx("div",{ref:se?.setActivatorNodeRef,className:Ie("min-w-0 flex flex-1 items-start gap-1 overflow-hidden pl-0.5 transition-[padding] cursor-grab active:cursor-grabbing",vt),...se?.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:lt&&qe?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(kt,{children:[s.jsx(Ct,{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(A,{name:"git-branch",className:Ie("h-3.5 w-3.5 shrink-0",D?"hidden":"group-hover/gh:hidden"),style:$t?{color:$t}:void 0}),s.jsx("span",{className:Ie("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:je?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),qe.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:He=>He.stopPropagation(),onClick:bs,children:["#",qe.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",qe.number]})]})}),s.jsx(At,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Ft||Xt?s.jsx("div",{className:"text-muted-foreground truncate",children:Ft&&Xt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Ft}),s.jsx(A,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Xt})]}):s.jsx("span",{children:Ft??Xt??""})}):null,Qt?s.jsx("div",{className:"text-muted-foreground truncate",children:Qt}):null,os||Lt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[os??"",os&&Lt?" • ":"",Lt??"",es?` (${es})`:""]}):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(A,{name:"archive",className:Ie("h-3.5 w-3.5 shrink-0 text-muted-foreground",D?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:Ie("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:je?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:jo(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(A,{name:"git-branch",className:Ie("h-3.5 w-3.5 shrink-0 text-muted-foreground",D?"hidden":"group-hover/gh:hidden"),style:$t?{color:$t}:void 0}),s.jsx("span",{className:Ie("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:je?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:jo(n.label,l)})]}):jo(n.label,l)}),Dt&&as?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(A,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||yt?lt&&qe?s.jsxs(kt,{children:[s.jsx(Ct,{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(A,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:$t?{color:$t}:void 0})})}),s.jsx(At,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Ft||Xt?s.jsx("div",{className:"text-muted-foreground truncate",children:Ft&&Xt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Ft}),s.jsx(A,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Xt})]}):s.jsx("span",{children:Ft??Xt??""})}):null,Qt?s.jsx("div",{className:"text-muted-foreground truncate",children:Qt}):null,os||Lt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[os??"",os&&Lt?" • ":"",Lt??"",es?` (${es})`:""]}):null]})})]}):s.jsx(A,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:$t?{color:$t}:void 0}):null,s.jsx("span",{className:Ie("min-w-0 truncate text-[11px] font-medium",!as.color&&"text-muted-foreground/80"),style:as.color?{color:as.color}:void 0,children:as.label})]}):null]})}),n.isArchivedBucket&&Qe.length>0?s.jsx("div",{className:Ie("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",D?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),Er.requestDelete({sessions:Qe,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(A,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(At,{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:Ie("absolute right-7 top-1/2 -translate-y-1/2 z-10 transition-opacity",D?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),Er.requestDelete({sessions:Qe,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(A,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteWorktree")})})]})}):null,n.directory?s.jsx("div",{className:Ie("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",D?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),o&&o!==O&&v(o),M("chat"),j&&I(!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(A,{name:"add",className:"h-4 w-4"})})}),s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),je?null:s.jsx("div",{className:Ie("oc-group-body",hs),children:vs})]})}const BN=i.memo(LN,ON);function VN(t){const e=mt.c(182),{t:n}=bt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:f,headerActionButtonClass:m,isSessionSearchOpen:u,setIsSessionSearchOpen:p,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:b,hasSessionSearchQuery:g,searchMatchCount:h,collapseAllProjects:C,expandAllProjects:w,openScheduledTasksDialog:S,selectionModeEnabled:N,onToggleSelectionMode:k}=t,j=Ir(GN),D=Ir(HN),O=Ir(UN),v=Ir(WN),M=Ir(zN),I=Ir($N);let E;e[0]===Symbol.for("react.memo_cache_sentinel")?(E=Yr(),e[0]=E):E=e[0];const B=!E;if(r)return null;let P;e[1]!==n?(P=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=P):P=e[2];let W;e[3]!==f?(W=s.jsx(A,{name:"folder-add",className:f}),e[3]=f,e[4]=W):W=e[4];let _;e[5]!==a||e[6]!==m||e[7]!==P||e[8]!==W?(_=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:m,"aria-label":P,children:W})}),e[5]=a,e[6]=m,e[7]=P,e[8]=W,e[9]=_):_=e[9];let V;e[10]!==n?(V=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=V):V=e[11];let R;e[12]!==V?(R=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:V})}),e[12]=V,e[13]=R):R=e[13];let ne;e[14]!==_||e[15]!==R?(ne=s.jsxs(kt,{children:[_,R]}),e[14]=_,e[15]=R,e[16]=ne):ne=e[16];let ie;e[17]!==n?(ie=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=ie):ie=e[18];let J;e[19]!==f?(J=s.jsx(A,{name:"chat-new",className:f}),e[19]=f,e[20]=J):J=e[20];let U;e[21]!==m||e[22]!==c||e[23]!==ie||e[24]!==J?(U=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:m,"aria-label":ie,children:J})}),e[21]=m,e[22]=c,e[23]=ie,e[24]=J,e[25]=U):U=e[25];let ee;e[26]!==n?(ee=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=ee):ee=e[27];let ae;e[28]!==ee?(ae=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ee})}),e[28]=ee,e[29]=ae):ae=e[29];let de;e[30]!==ae||e[31]!==U?(de=s.jsxs(kt,{children:[U,ae]}),e[30]=ae,e[31]=U,e[32]=de):de=e[32];let ye;e[33]!==n?(ye=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=ye):ye=e[34];const se=!l;let we;e[35]!==f?(we=s.jsx(Eg,{className:f}),e[35]=f,e[36]=we):we=e[36];let fe;e[37]!==m||e[38]!==d||e[39]!==ye||e[40]!==se||e[41]!==we?(fe=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:m,"aria-label":ye,disabled:se,children:we})}),e[37]=m,e[38]=d,e[39]=ye,e[40]=se,e[41]=we,e[42]=fe):fe=e[42];let Me;e[43]!==n?(Me=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=Me):Me=e[44];let $;e[45]!==Me?($=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Me})}),e[45]=Me,e[46]=$):$=e[46];let K;e[47]!==fe||e[48]!==$?(K=s.jsxs(kt,{children:[fe,$]}),e[47]=fe,e[48]=$,e[49]=K):K=e[49];let q;e[50]!==n?(q=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=q):q=e[51];let me;e[52]!==f?(me=s.jsx(A,{name:"calendar-schedule",className:f}),e[52]=f,e[53]=me):me=e[53];let je;e[54]!==m||e[55]!==S||e[56]!==q||e[57]!==me?(je=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:m,"aria-label":q,children:me})}),e[54]=m,e[55]=S,e[56]=q,e[57]=me,e[58]=je):je=e[58];let Oe;e[59]!==n?(Oe=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=Oe):Oe=e[60];let Be;e[61]!==Oe?(Be=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Oe})}),e[61]=Oe,e[62]=Be):Be=e[62];let Fe;e[63]!==je||e[64]!==Be?(Fe=s.jsxs(kt,{children:[je,Be]}),e[63]=je,e[64]=Be,e[65]=Fe):Fe=e[65];let ue;e[66]!==de||e[67]!==K||e[68]!==Fe||e[69]!==ne?(ue=s.jsxs("div",{className:"flex items-center gap-1.5",children:[ne,de,K,Fe]}),e[66]=de,e[67]=K,e[68]=Fe,e[69]=ne,e[70]=ue):ue=e[70];let Re;e[71]!==p?(Re=()=>p(_N),e[71]=p,e[72]=Re):Re=e[72];let xe;e[73]!==n?(xe=n("sessions.sidebar.header.actions.searchSessions"),e[73]=n,e[74]=xe):xe=e[74];let oe;e[75]!==f?(oe=s.jsx(A,{name:"search",className:f}),e[75]=f,e[76]=oe):oe=e[76];let ve;e[77]!==m||e[78]!==u||e[79]!==Re||e[80]!==xe||e[81]!==oe?(ve=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Re,className:m,"aria-label":xe,"aria-expanded":u,children:oe})}),e[77]=m,e[78]=u,e[79]=Re,e[80]=xe,e[81]=oe,e[82]=ve):ve=e[82];let Se;e[83]!==n?(Se=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=Se):Se=e[84];let le;e[85]!==Se?(le=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Se})}),e[85]=Se,e[86]=le):le=e[86];let T;e[87]!==ve||e[88]!==le?(T=s.jsxs(kt,{children:[ve,le]}),e[87]=ve,e[88]=le,e[89]=T):T=e[89];const L=N&&"bg-interactive-hover text-primary";let he;e[90]!==m||e[91]!==L?(he=Ie(m,L),e[90]=m,e[91]=L,e[92]=he):he=e[92];let ge;e[93]!==N||e[94]!==n?(ge=n(N?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=N,e[94]=n,e[95]=ge):ge=e[95];let z;e[96]!==f?(z=s.jsx(A,{name:"checkbox-multiple",className:f}),e[96]=f,e[97]=z):z=e[97];let pe;e[98]!==k||e[99]!==N||e[100]!==he||e[101]!==ge||e[102]!==z?(pe=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:he,"aria-label":ge,"aria-pressed":N,children:z})}),e[98]=k,e[99]=N,e[100]=he,e[101]=ge,e[102]=z,e[103]=pe):pe=e[103];let Ae;e[104]!==N||e[105]!==n?(Ae=n(N?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=N,e[105]=n,e[106]=Ae):Ae=e[106];let G;e[107]!==Ae?(G=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Ae})}),e[107]=Ae,e[108]=G):G=e[108];let ke;e[109]!==pe||e[110]!==G?(ke=s.jsxs(kt,{children:[pe,G]}),e[109]=pe,e[110]=G,e[111]=ke):ke=e[111];let Le;e[112]!==n?(Le=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[112]=n,e[113]=Le):Le=e[113];let Te;e[114]!==f?(Te=s.jsx(A,{name:"equalizer-2",className:f}),e[114]=f,e[115]=Te):Te=e[115];let Z;e[116]!==m||e[117]!==Le||e[118]!==Te?(Z=s.jsx(Ct,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":Le,children:Te})})}),e[116]=m,e[117]=Le,e[118]=Te,e[119]=Z):Z=e[119];let F;e[120]!==n?(F=n("sessions.sidebar.header.displayMode.label"),e[120]=n,e[121]=F):F=e[121];let re;e[122]!==F?(re=s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:F})}),e[122]=F,e[123]=re):re=e[123];let te;e[124]!==Z||e[125]!==re?(te=s.jsxs(kt,{children:[Z,re]}),e[124]=Z,e[125]=re,e[126]=te):te=e[126];let Ve;e[127]!==j||e[128]!==v||e[129]!==n?(Ve=B?s.jsxs(s.Fragment,{children:[s.jsxs(xs,{onClick:()=>v("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),j==="default"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(xs,{onClick:()=>v("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),j==="minimal"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[127]=j,e[128]=v,e[129]=n,e[130]=Ve):Ve=e[130];let Ye;e[131]!==O||e[132]!==o||e[133]!==D||e[134]!==n||e[135]!==I||e[136]!==M?(Ye=o?s.jsxs(s.Fragment,{children:[B?s.jsx(Fr,{}):null,s.jsxs(xs,{onClick:M,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showRecent")}),D?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(xs,{onClick:I,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),O?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[131]=O,e[132]=o,e[133]=D,e[134]=n,e[135]=I,e[136]=M,e[137]=Ye):Ye=e[137];let Ke;e[138]===Symbol.for("react.memo_cache_sentinel")?(Ke=s.jsx(Fr,{}),e[138]=Ke):Ke=e[138];let Je;e[139]===Symbol.for("react.memo_cache_sentinel")?(Je=s.jsx(A,{name:"contract-up-down",className:"h-4 w-4"}),e[139]=Je):Je=e[139];let nt;e[140]!==n?(nt=n("sessions.sidebar.header.displayMode.collapseAll"),e[140]=n,e[141]=nt):nt=e[141];let xt;e[142]!==nt?(xt=s.jsx("span",{children:nt}),e[142]=nt,e[143]=xt):xt=e[143];let jt;e[144]!==C||e[145]!==xt?(jt=s.jsxs(xs,{onClick:C,className:"flex items-center gap-2",children:[Je,xt]}),e[144]=C,e[145]=xt,e[146]=jt):jt=e[146];let Mt;e[147]===Symbol.for("react.memo_cache_sentinel")?(Mt=s.jsx(A,{name:"expand-up-down",className:"h-4 w-4"}),e[147]=Mt):Mt=e[147];let Et;e[148]!==n?(Et=n("sessions.sidebar.header.displayMode.expandAll"),e[148]=n,e[149]=Et):Et=e[149];let Ut;e[150]!==Et?(Ut=s.jsx("span",{children:Et}),e[150]=Et,e[151]=Ut):Ut=e[151];let zt;e[152]!==w||e[153]!==Ut?(zt=s.jsxs(xs,{onClick:w,className:"flex items-center gap-2",children:[Mt,Ut]}),e[152]=w,e[153]=Ut,e[154]=zt):zt=e[154];let Ht;e[155]!==Ve||e[156]!==Ye||e[157]!==jt||e[158]!==zt?(Ht=s.jsxs(en,{align:"end",className:"min-w-[160px]",children:[Ve,Ye,Ke,jt,zt]}),e[155]=Ve,e[156]=Ye,e[157]=jt,e[158]=zt,e[159]=Ht):Ht=e[159];let _t;e[160]!==te||e[161]!==Ht?(_t=s.jsxs(tn,{children:[te,Ht]}),e[160]=te,e[161]=Ht,e[162]=_t):_t=e[162];let Gt;e[163]!==T||e[164]!==ke||e[165]!==_t?(Gt=s.jsxs("div",{className:"flex items-center gap-1.5",children:[T,ke,_t]}),e[163]=T,e[164]=ke,e[165]=_t,e[166]=Gt):Gt=e[166];let Ce;e[167]!==ue||e[168]!==Gt?(Ce=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[ue,Gt]}),e[167]=ue,e[168]=Gt,e[169]=Ce):Ce=e[169];let Qe;e[170]!==g||e[171]!==u||e[172]!==h||e[173]!==x||e[174]!==y||e[175]!==p||e[176]!==b||e[177]!==n?(Qe=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:[g?s.jsx("span",{children:h===1?n("sessions.sidebar.header.search.matchCountSingle",{count:h}):n("sessions.sidebar.header.search.matchCountPlural",{count:h})}):s.jsx("span",{}),s.jsx("span",{children:n("sessions.sidebar.header.search.escapeHint")})]}),s.jsxs("div",{className:"relative",children:[s.jsx(A,{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:x,value:y,onChange:yt=>b(yt.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:yt=>{yt.key==="Escape"&&(yt.stopPropagation(),g?b(""):p(!1))}}),y.length>0?s.jsx("button",{type:"button",onClick:()=>b(""),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(A,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[170]=g,e[171]=u,e[172]=h,e[173]=x,e[174]=y,e[175]=p,e[176]=b,e[177]=n,e[178]=Qe):Qe=e[178];let et;return e[179]!==Ce||e[180]!==Qe?(et=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:[Ce,Qe]})}),e[179]=Ce,e[180]=Qe,e[181]=et):et=e[181],et}function _N(t){return!t}function $N(t){return t.toggleArchivedSessions}function zN(t){return t.toggleRecentSection}function WN(t){return t.setDisplayMode}function UN(t){return t.showArchivedSessions}function HN(t){return t.showRecentSection}function GN(t){return t.displayMode}const pf=7;function KN({sections:t,renderSessionNode:e,currentSessionId:n,editingId:r,openSidebarMenuKey:o,variant:a="section",initialVisibleCount:c=pf,batchSize:l=pf}){const{t:d}=bt(),[f,m]=i.useState(new Set),[u,p]=i.useState(new Map),x=a==="flat",y=i.useCallback(w=>{p(S=>{if(!S.has(w))return S;const N=new Map(S);return N.delete(w),N})},[]),b=i.useCallback(w=>{y(w),m(S=>{const N=new Set(S);return N.has(w)?N.delete(w):N.add(w),N})},[y]),g=i.useCallback((w,S,N)=>{p(k=>{const j=Math.min(N,S+l),D=new Map(k);return D.set(w,j),D})},[l]),h=i.useCallback(w=>{const S=new Set;Ki(w,n,S);const N=new Set;Ki(w,r,N);const k=Oo(w,o,"recent",!1),j=new WeakMap,D=v=>{j.set(v,Oa(v)),v.children.forEach(D)};w.forEach(D);const O=v=>({subtreeContainsActive:S,subtreeContainsEditing:N,menuOpenSessionId:k,nodeStructureKey:j.get(v)??"",childRenderExtrasFor:O});return v=>({subtreeContainsActive:S,subtreeContainsEditing:N,menuOpenSessionId:k,nodeStructureKey:j.get(v)??"",childRenderExtrasFor:O})},[n,r,o]),C=t.filter(w=>w.items.length>0);return C.length===0?null:s.jsx("div",{className:Ie(x?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1"),children:C.map(w=>{const S=f.has(w.key),N=Math.max(c,u.get(w.key)??c),k=w.items.slice(0,N),j=w.items.length-k.length,D=!x&&w.items.length>c&&j===0,O=h(k.map(M=>M.node)),v=M=>e(M.node,0,M.groupDirectory,M.projectId,!1,M.secondaryMeta,"recent",O(M.node));return x?s.jsxs("div",{className:"space-y-0.5",children:[k.map(v),j>0?s.jsx("button",{type:"button",onClick:()=>g(w.key,k.length,w.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:d("sessions.sidebar.group.showMore")}):null]},w.key):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("button",{type:"button",onClick:()=>b(w.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":!S,children:[s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground",children:S?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"text-[14px] font-normal text-foreground/95",children:w.title})]}),S?null:s.jsxs("div",{className:Ie("space-y-0.5 pl-7"),children:[k.map(v),j>0?s.jsx("button",{type:"button",onClick:()=>g(w.key,k.length,w.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:d("sessions.sidebar.group.showMore")}):null,D?s.jsx("button",{type:"button",onClick:()=>y(w.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:d("sessions.sidebar.group.showFewer")}):null]})]},w.key)})})}const El="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 qN(t){const e=mt.c(14),{onOpenSettings:n,onOpenShortcuts:r,onOpenAbout:o,onOpenUpdate:a,onOpenShareOpinion:c,showRuntimeButtons:l,showUpdateButton:d}=t,f=l===void 0?!0:l,m=d===void 0?!0:d,{t:u}=bt();let p;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==f||e[4]!==u?(p=f?s.jsxs(s.Fragment,{children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:El,"aria-label":u("sessions.sidebar.footer.actions.settings"),children:s.jsx(A,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(At,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:El,"aria-label":u("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(A,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(At,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:El,"aria-label":u("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(A,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(At,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=f,e[4]=u,e[5]=p):p=e[5];let x;e[6]!==c||e[7]!==a||e[8]!==m||e[9]!==u?(x=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:u("sessions.sidebar.footer.actions.update")}):s.jsx(ze,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--primary-base)]/15 bg-[var(--primary-base)]/5 text-[var(--primary-base)]/60 hover:bg-[var(--primary-base)]/10 hover:text-[var(--primary-base)]/75",onClick:c,children:u("sessions.sidebar.footer.actions.shareOpinion")}),e[6]=c,e[7]=a,e[8]=m,e[9]=u,e[10]=x):x=e[10];let y;return e[11]!==p||e[12]!==x?(y=s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-2.5 py-2",children:[p,x]}),e[11]=p,e[12]=x,e[13]=y):y=e[13],y}const YN=t=>{const e=mt.c(58),{id:n,projectLabel:r,projectDescription:o,projectIcon:a,projectColor:c,projectIconImage:l,projectIconBackground:d,isCollapsed:f,isActiveProject:m,isRepo:u,isDesktopShell:p,isStuck:x,hideDirectoryControls:y,alwaysShowActions:b,onToggle:g,onNewSession:h,onNewWorktreeSession:C,onRenameStart:w,onClose:S,sentinelRef:N,children:k,showCreateButtons:j,hideHeader:D,openSidebarMenuKey:O,setOpenSidebarMenuKey:v}=t,M=j===void 0?!0:j,I=D===void 0?!1:D,{t:E}=bt(),{currentTheme:B}=pi();let P;e[0]!==n?(P={id:n},e[0]=n,e[1]=P):P=e[1];const{attributes:W,listeners:_,setNodeRef:V,transform:R,transition:ne,isDragging:ie}=uc(P),J=i.useRef(!1),U=`project:${n}`,ee=O===U,[ae,de]=i.useState(!1),ye=a?Pc[a]:null,se=c?Ic[c]??null:null;let we;e[2]!==U||e[3]!==v?(we=le=>{le&&de(!1),v(le?U:null)},e[2]=U,e[3]=v,e[4]=we):we=e[4];const fe=we;let Me;e[5]!==y||e[6]!==u||e[7]!==S||e[8]!==h||e[9]!==w||e[10]!==M||e[11]!==E?(Me=le=>s.jsxs(s.Fragment,{children:[M&&!u&&!y&&h&&s.jsxs(le,{onClick:h,children:[s.jsx(A,{name:"add",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.newSession")]}),s.jsxs(le,{onClick:w,children:[s.jsx(A,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.edit")]}),s.jsxs(le,{onClick:S,className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"close",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.closeProject")]})]}),e[5]=y,e[6]=u,e[7]=S,e[8]=h,e[9]=w,e[10]=M,e[11]=E,e[12]=Me):Me=e[12];const $=Me,K=XN,q=ZN,me=ek;let je;e[13]===Symbol.for("react.memo_cache_sentinel")?(je=le=>{(le.button===2||le.button===0&&le.ctrlKey)&&(J.current=!0)},e[13]=je):je=e[13];const Oe=je;let Be;e[14]!==g?(Be=()=>{if(J.current){J.current=!1;return}g()},e[14]=g,e[15]=Be):Be=e[15];const Fe=Be;let ue;e[16]!==R?(ue=fc.Transform.toString(R),e[16]=R,e[17]=ue):ue=e[17];let Re;e[18]!==ue||e[19]!==ne?(Re={transform:ue,transition:ne},e[18]=ue,e[19]=ne,e[20]=Re):Re=e[20];const xe=ie&&"opacity-30";let oe;e[21]!==xe?(oe=Ie("relative",xe),e[21]=xe,e[22]=oe):oe=e[22];let ve;e[23]!==b||e[24]!==W||e[25]!==B||e[26]!==fe||e[27]!==Fe||e[28]!==y||e[29]!==I||e[30]!==se||e[31]!==n||e[32]!==m||e[33]!==f||e[34]!==ae||e[35]!==p||e[36]!==ee||e[37]!==u||e[38]!==x||e[39]!==_||e[40]!==h||e[41]!==C||e[42]!==o||e[43]!==d||e[44]!==l||e[45]!==ye||e[46]!==r||e[47]!==$||e[48]!==N||e[49]!==M||e[50]!==E?(ve=I?null:s.jsxs(s.Fragment,{children:[p&&s.jsx("div",{ref:N,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsxs(Lc,{open:ae,onOpenChange:de,children:[s.jsx(Oc,{render:s.jsx("div",{className:Ie("w-full text-left group/project select-none"),style:{backgroundColor:p&&x?"transparent":void 0},onContextMenu:le=>{y||(le.preventDefault(),de(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...W,children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:Oe,onClick:Fe,..._,className:Ie("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&&!y?b?"pr-20":"pr-7 group-hover/project:pr-20 group-focus-within/project:pr-20":b?"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:Ie("h-3.5 w-3.5 items-center justify-center text-muted-foreground",b?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:f?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),l?s.jsx("span",{className:Ie("h-3.5 w-3.5 items-center justify-center overflow-hidden rounded-[3px]",b?"hidden":"inline-flex group-hover/project:hidden group-focus-within/project:hidden"),style:d?{backgroundColor:d}:void 0,children:s.jsx(Rc,{project:{id:n,iconImage:l},options:{themeVariant:B.metadata.variant,iconColor:B.colors.surface.foreground},className:"h-full w-full object-contain",fallback:ye?s.jsx(A,{name:ye,className:"h-3.5 w-3.5",style:se?{color:se}:void 0}):s.jsx(A,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:se?{color:se}:void 0})})}):ye?s.jsx(A,{name:ye,className:Ie("h-3.5 w-3.5",b?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:se?{color:se}:void 0}):s.jsx(A,{name:"folder",className:Ie("h-3.5 w-3.5 text-muted-foreground/80",b?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:se?{color:se}:void 0})]}),s.jsx("span",{className:Ie("text-[14px] font-normal truncate lowercase",m?"text-foreground":"text-foreground group-hover/project:text-foreground"),children:r})]})}),s.jsx(At,{side:"right",sideOffset:8,children:o})]}),s.jsxs("div",{className:Ie("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",M?"right-7":"right-0.5"),children:[M&&u&&!y&&C?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),C()},className:Ie("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",b?"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(A,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,y?null:s.jsxs(tn,{open:ee,onOpenChange:fe,children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:Ie("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",ee?"opacity-100 pointer-events-auto":b?"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:q,onMouseDown:me,onClick:K,children:s.jsx(A,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(en,{align:"end",className:"min-w-[180px]",children:$(xs)})]})]}),M&&h?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),h()},className:Ie("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",b?"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(A,{name:"add",className:"h-4 w-4"})})}),s.jsx(At,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E(u?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(Mc,{className:"min-w-[180px]",children:$(Fc)})]})]}),e[23]=b,e[24]=W,e[25]=B,e[26]=fe,e[27]=Fe,e[28]=y,e[29]=I,e[30]=se,e[31]=n,e[32]=m,e[33]=f,e[34]=ae,e[35]=p,e[36]=ee,e[37]=u,e[38]=x,e[39]=_,e[40]=h,e[41]=C,e[42]=o,e[43]=d,e[44]=l,e[45]=ye,e[46]=r,e[47]=$,e[48]=N,e[49]=M,e[50]=E,e[51]=ve):ve=e[51];let Se;return e[52]!==k||e[53]!==V||e[54]!==oe||e[55]!==ve||e[56]!==Re?(Se=s.jsxs("div",{ref:V,style:Re,className:oe,children:[ve,k]}),e[52]=k,e[53]=V,e[54]=oe,e[55]=ve,e[56]=Re,e[57]=Se):Se=e[57],Se},QN=t=>{const e=mt.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:f,transform:m,transition:u,isDragging:p}=uc(c);let x;e[3]!==l||e[4]!==f?(x={listeners:l,setActivatorNodeRef:f},e[3]=l,e[4]=f,e[5]=x):x=e[5];const y=x;let b;e[6]!==m?(b=fc.Transform.toString(m),e[6]=m,e[7]=b):b=e[7];let g;e[8]!==b||e[9]!==u?(g={transform:b,transition:u},e[8]=b,e[9]=u,e[10]=g):g=e[10];const h=p&&"opacity-50";let C;e[11]!==h?(C=Ie("space-y-0.5 rounded-md",h),e[11]=h,e[12]=C):C=e[12];let w;e[13]!==o||e[14]!==y?(w=typeof o=="function"?o(y):o,e[13]=o,e[14]=y,e[15]=w):w=e[15];let S;return e[16]!==d||e[17]!==g||e[18]!==C||e[19]!==w?(S=s.jsx("div",{ref:d,style:g,className:C,children:w}),e[16]=d,e[17]=g,e[18]=C,e[19]=w,e[20]=S):S=e[20],S},JN=i.memo(QN);function XN(t){t.stopPropagation()}function ZN(t){t.stopPropagation()}function ek(t){t.stopPropagation()}function tk(t){const{t:e}=bt(),n=ba(vo(ya,{activationConstraint:{distance:8}}),vo(np,{coordinateGetter:sp})),r=ba(vo(ya,{activationConstraint:{distance:8}})),o=i.useRef(null),a=i.useRef(new Map),c=i.useRef(t.getOrderedGroups);c.current!==t.getOrderedGroups&&(c.current=t.getOrderedGroups,a.current.clear());const l=(d,f)=>{const m=a.current,u=m.get(d);if(u&&u.groups===f)return u.ordered;const p=t.getOrderedGroups(d,f);if(m.set(d,{groups:f,ordered:p}),m.size>256){const x=m.keys().next().value;x!==void 0&&m.delete(x)}return p};return t.sharedSessionsOnly?s.jsxs(En,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Ie("space-y-1 pb-1 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.hasSharedSessions?null:t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState]}):t.projectSections.length===0?s.jsxs(En,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Ie("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.emptyState]}):t.sectionsForRender.length===0?s.jsx(En,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Ie("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:t.searchEmptyState}):s.jsxs(En,{ref:o,useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Ie("space-y-1 pb-1 pl-2.5 pr-2 [overflow-anchor:none]",(t.mobileVariant,"")),children:[t.topContent,t.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const d=t.sectionsForRender.find(p=>p.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!d)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const f=d.groups.find(p=>p.isMain&&p.sessions.length>0)??d.groups.find(p=>p.sessions.length>0)??d.groups.find(p=>p.isMain)??d.groups[0];if(!f)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")});const m=d.groups.find(p=>p.isArchivedBucket);return[f,...m&&m.id!==f.id?[m]:[]].map(p=>{const x=`${d.project.id}:${p.id}`,y=p.id===f.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(p,x,d.project.id,y,null,!0,o)},x)})})()}):s.jsx(s.Fragment,{children:s.jsxs(wa,{sensors:n,collisionDetection:va,onDragEnd:d=>{if(t.isInlineEditing)return;const{active:f,over:m}=d;if(!m||f.id===m.id)return;const u=t.sectionsForRender.findIndex(x=>x.project.id===f.id),p=t.sectionsForRender.findIndex(x=>x.project.id===m.id);u===-1||p===-1||u===p||t.reorderProjects(u,p)},children:[s.jsx(Vl,{items:t.sectionsForRender.map(d=>d.project.id),strategy:_l,children:t.sectionsForRender.map(d=>{const f=d.project,m=f.id,u=Pm(f.label?.trim()||lo(f.normalizedPath,t.homeDirectory)||f.normalizedPath),p=Ca(f.normalizedPath,t.homeDirectory),x=t.collapsedProjects.has(m),y=m===t.activeProjectId,b=t.projectRepoStatus.get(m),g=l(m,d.groups),h=g.find(w=>w.isMain)??null,C=h?g.filter(w=>w.id!==h.id):g;return s.jsx(YN,{id:m,projectLabel:u,projectDescription:p,projectIcon:f.icon,projectColor:f.color,projectIconImage:f.iconImage,projectIconBackground:f.iconBackground,isCollapsed:x,isActiveProject:y,isRepo:!!b,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(m),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,alwaysShowActions:t.alwaysShowActions,onToggle:()=>t.toggleProject(m),onNewSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:f.normalizedPath})},onNewWorktreeSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.openNewWorktreeDialog()},onRenameStart:()=>t.openProjectEditDialog(m),onClose:()=>t.removeProject(m),sentinelRef:w=>{t.projectHeaderSentinelRefs.current.set(m,w)},showCreateButtons:!0,openSidebarMenuKey:t.openSidebarMenuKey,setOpenSidebarMenuKey:t.setOpenSidebarMenuKey,children:x?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:d.groups.length>0?s.jsxs(wa,{sensors:r,collisionDetection:va,onDragEnd:w=>{if(t.isInlineEditing)return;const{active:S,over:N}=w;if(!N||S.id===N.id)return;const k=C.findIndex(v=>v.id===S.id),j=C.findIndex(v=>v.id===N.id);if(k===-1||j===-1||k===j)return;const D=Lf(C,k,j).map(v=>v.id),O=h?[h.id,...D]:D;t.setGroupOrderByProject(v=>{const M=new Map(v);return M.set(m,O),M})},children:[h?t.renderGroupSessions(h,`${m}:${h.id}`,m,!0,null,void 0,o):null,s.jsx(Vl,{items:C.map(w=>w.id),strategy:_l,children:C.map(w=>{const S=`${m}:${w.id}`;return s.jsx(JN,{id:w.id,disabled:t.isInlineEditing,children:N=>t.renderGroupSessions(w,S,m,!1,N,void 0,o)},w.id)})}),s.jsx(zl,{dropAnimation:null})]}):s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")})})},m)})}),s.jsx(zl,{dropAnimation:null})]})})]})}function sk(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(eo(),{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 nk(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 rk(t){const e=t.info.role==="user"?"User":"Assistant",n=sk(t.info.time?.created),r=nk(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
192
-
193
- *${o}*`:`**${e}**`}function ik(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function wh(t){const e=rk(t),n=ik(t.parts).trim();return n?`${e}
194
-
195
- ${n}`:""}function vh(t,e){const n="#".repeat(Math.min(e+1,6)),r=t.agent?` — ${t.agent}`:"",o=`${n} Sub-agent: ${t.title}${r}
196
-
197
- ---
198
-
199
- `,a=t.records.map(wh).filter(Boolean).join(`
200
-
201
- ---
202
-
203
- `),c=[o+a];for(const l of t.children)c.push(vh(l,e+1));return c.join(`
204
-
205
- ---
206
-
207
- `)}function ok(t,e,n){const r=e?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
208
-
209
- *Exported on ${o}*
210
-
211
- ---
212
-
213
- `,c=t.map(wh).filter(Boolean).join(`
214
-
215
- ---
216
-
217
- `);let l=a+c;if(n&&n.length>0){const d=n.map(f=>vh(f,1)).join(`
218
-
219
- ---
220
-
221
- `);l+=`
222
-
223
- ---
224
-
225
- `+d}return l}function ak(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 lk(t,e){const n=await vp(e,t);if(n)return n;if(!Yr())return null;try{const r=await Lo()?.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 ck(t){const e=Lo()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await Sp(t)?!0:Sa(t)}function dk(){return Cc()}function uk(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 fk=(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},Wn=oo()((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 m=o&&o.length>0?[n,...o]:[n];if(c.has(n)){for(const p of m)c.delete(p);d===n&&(d=null)}else{for(const p of m)c.add(p);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],f=o.indexOf(d),m=o.indexOf(r);if(f<0||m<0)return;const[u,p]=f<=m?[f,m]:[m,f],x=o.slice(u,p+1),y=fk(x,c),g=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const h of y)g.add(h);t({selectedIds:g,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}))}}));let oc=!1;const ac=new Set;let gf=!1;function mk(){for(const t of ac)t()}function Yc(t){oc!==t&&(oc=t,mk())}function hk(t){t.key==="Shift"&&Yc(!0)}function pk(t){t.key==="Shift"&&Yc(!1)}function gk(){Yc(!1)}function xk(){gf||typeof window>"u"||(gf=!0,window.addEventListener("keydown",hk),window.addEventListener("keyup",pk),window.addEventListener("blur",gk))}function bk(t){return xk(),ac.add(t),()=>{ac.delete(t)}}function yk(){return oc}function wk(){return!1}function vk(){return Xe.useSyncExternalStore(bk,yk,wk)}const Sk=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,Sh=/^g[1-9]\d*$/,yo=(t,e,n,r,o)=>{if(!Sk.test(t)||e!==void 0&&!Sh.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}},ga=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 yo(n,void 0,e[1],e[2],void 0);if(e.length===4){const[,l,d,f]=e;return Sh.test(l)?yo(n,l,d,f,void 0):yo(n,void 0,l,d,f)}const[,r,o,a,c]=e;return r===""?yo(n,void 0,o,a,c):yo(n,r,o,a,c)},jk=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("/")},Nk=(t,e,n,r)=>{const o=[t];return r&&o.push(r),o.push(e,n,"fusion"),o.join("/")},jh=t=>{const e=mt.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=bt(),f=ss(kk),m=ss(Ck),u=ss(Ak);let p;e[0]!==f?(p=f(),e[0]=f,e[1]=p):p=e[1];const x=p;let y;e[2]!==x?(y=x.filter(Dk),e[2]=x,e[3]=y):y=e[3];const b=y;let g,h;e[4]!==x.length||e[5]!==m?(g=()=>{x.length===0&&m()},h=[x.length,m],e[4]=x.length,e[5]=m,e[6]=g,e[7]=h):(g=e[6],h=e[7]),i.useEffect(g,h);let C,w;e[8]!==u||e[9]!==a||e[10]!==r||e[11]!==b||e[12]!==n?(C=()=>{if(a)return;const I=n.trim();if(I.length>0&&b.some(P=>P.name===I))return;const E=typeof u=="string"&&u.trim().length>0?u.trim():null;if(E&&b.some(P=>P.name===E)){r(E);return}const B=b[0]?.name;B&&r(B)},w=[u,a,r,b,n],e[8]=u,e[9]=a,e[10]=r,e[11]=b,e[12]=n,e[13]=C,e[14]=w):(C=e[13],w=e[14]),i.useEffect(C,w);const S=n.trim().length>0?n:void 0;let N;e[15]!==o?(N=Ie("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]=N):N=e[16];let k;e[17]!==d?(k=d("multirun.agentSelector.placeholder"),e[17]=d,e[18]=k):k=e[18];let j;e[19]!==k?(j=s.jsx(Cn,{placeholder:k}),e[19]=k,e[20]=j):j=e[20];let D;e[21]!==c||e[22]!==N||e[23]!==j?(D=s.jsx(Hn,{id:c,size:"lg",className:N,children:j}),e[21]=c,e[22]=N,e[23]=j,e[24]=D):D=e[24];let O;e[25]!==b?(O=b.length>0&&s.jsx(Ul,{children:b.map(Tk)}),e[25]=b,e[26]=O):O=e[26];let v;e[27]!==l||e[28]!==O?(v=s.jsx(Gn,{fitContent:!0,portalToBody:l,children:O}),e[27]=l,e[28]=O,e[29]=v):v=e[29];let M;return e[30]!==a||e[31]!==r||e[32]!==S||e[33]!==D||e[34]!==v?(M=s.jsxs(Un,{value:S,onValueChange:r,disabled:a,children:[D,v]}),e[30]=a,e[31]=r,e[32]=S,e[33]=D,e[34]=v,e[35]=M):M=e[35],M};function kk(t){return t.getVisibleAgents}function Ck(t){return t.loadAgents}function Ak(t){return t.currentAgentName}function Dk(t){return vc(t.mode)}function Tk(t){return s.jsx(Rs,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const Nh="h-7",To=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Pk=t=>{const e=mt.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=Ie("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",Nh),e[0]=d):d=e[0];let f;e[1]!==n.providerID?(f=s.jsx(Po,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=f):f=e[2];let m;e[3]!==l?(m=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=m):m=e[4];let u;e[5]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(A,{name:"close",className:"h-3.5 w-3.5"}),e[5]=u):u=e[5];let p;e[6]!==a?(p=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:u}),e[6]=a,e[7]=p):p=e[7];let x;return e[8]!==f||e[9]!==m||e[10]!==p?(x=s.jsxs("div",{className:d,children:[f,m,p]}),e[8]=f,e[9]=m,e[10]=p,e[11]=x):x=e[11],x},kh=t=>{const e=mt.c(119),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:f,addButtonClassName:m,dropdownSide:u,dropdownClassName:p,containerClassName:x,triggerIcon:y}=t,b=d===void 0?!0:d,g=u===void 0?"top":u,{t:h}=bt(),C=ss(Ik),w=ss(Rk),S=Ee(Ek),N=Ee(Mk),{favoriteModelsList:k,recentModelsList:j}=Mg(),D=Ee(Fk),O=Ee(Ok),[v,M]=i.useState(!1),[I,E]=i.useState(""),[B,P]=i.useState(null),W=i.useRef(null),_=i.useRef(null),V=f===1,R=f===void 0||n.length<f||V;let ne;if(e[0]!==n){ne=new Map;for(const re of n){const te=`${re.providerID}:${re.modelID}`;ne.set(te,(ne.get(te)||0)+1)}e[0]=n,e[1]=ne}else ne=e[1];const ie=ne;let J;e[2]!==n?(J=re=>n.filter(Ve=>Ve.providerID===re.providerID&&Ve.modelID===re.modelID).findIndex(Ve=>Ve.instanceId===re.instanceId)+1,e[2]=n,e[3]=J):J=e[3];const U=J;let ee,ae;e[4]!==g||e[5]!==v?(ee=()=>{if(!v||!_.current)return;const re=_.current.getBoundingClientRect();if(g==="bottom"){const nt=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-re.bottom-16-112;P(Math.max(160,Math.min(320,nt)));return}let te=_.current.parentElement;for(;te&&!(te.getAttribute("role")==="dialog"||te.hasAttribute("data-scroll-shadow"));){const Ke=getComputedStyle(te);if(Ke.overflow==="auto"||Ke.overflow==="hidden"||Ke.overflowY==="auto"||Ke.overflowY==="hidden")break;te=te.parentElement}const Ve=te?te.getBoundingClientRect().top:0,Ye=re.top-Ve-16;P(Math.max(150,Math.min(300,Ye)))},ae=[g,v],e[4]=g,e[5]=v,e[6]=ee,e[7]=ae):(ee=e[6],ae=e[7]),i.useEffect(ee,ae);let de,ye;e[8]!==R||e[9]!==v?(de=()=>{!R&&v&&(M(!1),E(""))},ye=[R,v],e[8]=R,e[9]=v,e[10]=de,e[11]=ye):(de=e[10],ye=e[11]),i.useEffect(de,ye);let se,we;e[12]!==v?(se=()=>{if(!v)return;const re=te=>{W.current&&!W.current.contains(te.target)&&(M(!1),E(""))};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},we=[v],e[12]=v,e[13]=se,e[14]=we):(se=e[13],we=e[14]),i.useEffect(se,we);let fe;e[15]!==V||e[16]!==r||e[17]!==a||e[18]!==n.length?(fe=re=>{const te={providerID:re.providerID,modelID:re.modelID,displayName:re.model.name||re.modelID,instanceId:To()};V&&n.length>0&&a?a(0,te):r(te),V&&(M(!1),E(""))},e[15]=V,e[16]=r,e[17]=a,e[18]=n.length,e[19]=fe):fe=e[19];const Me=fe;let $;e[20]!==h?($=h("multirun.modelMultiSelect.search.placeholder"),e[20]=h,e[21]=$):$=e[21];let K;e[22]!==h?(K=h("multirun.modelMultiSelect.search.noResults"),e[22]=h,e[23]=K):K=e[23];let q;e[24]!==h?(q=h("multirun.modelMultiSelect.sections.favorites"),e[24]=h,e[25]=q):q=e[25];let me;e[26]!==h?(me=h("multirun.modelMultiSelect.sections.recent"),e[26]=h,e[27]=me):me=e[27];let je;e[28]!==h?(je=h("multirun.modelMultiSelect.keyboard.hint"),e[28]=h,e[29]=je):je=e[29];let Oe;e[30]!==h?(Oe=h("settings.agents.modelSelector.actions.favorite"),e[30]=h,e[31]=Oe):Oe=e[31];let Be;e[32]!==h?(Be=h("settings.agents.modelSelector.actions.unfavorite"),e[32]=h,e[33]=Be):Be=e[33];let Fe;e[34]!==h?(Fe=h("chat.modelControls.capabilities"),e[34]=h,e[35]=Fe):Fe=e[35];let ue;e[36]!==h?(ue=h("chat.modelControls.capability.toolCalling"),e[36]=h,e[37]=ue):ue=e[37];let Re;e[38]!==h?(Re=h("chat.modelControls.capability.reasoning"),e[38]=h,e[39]=Re):Re=e[39];let xe;e[40]!==h?(xe=h("chat.modelControls.input"),e[40]=h,e[41]=xe):xe=e[41];let oe;e[42]!==h?(oe=h("chat.modelControls.output"),e[42]=h,e[43]=oe):oe=e[43];let ve;e[44]!==h?(ve=h("chat.modelControls.costPerMillion"),e[44]=h,e[45]=ve):ve=e[45];let Se;e[46]!==$||e[47]!==K||e[48]!==q||e[49]!==me||e[50]!==je||e[51]!==Oe||e[52]!==Be||e[53]!==Fe||e[54]!==ue||e[55]!==Re||e[56]!==xe||e[57]!==oe||e[58]!==ve?(Se={searchPlaceholder:$,noResults:K,favorites:q,recent:me,keyboardHint:je,favorite:Oe,unfavorite:Be,capabilities:Fe,capabilityToolCalling:ue,capabilityReasoning:Re,input:xe,output:oe,costPerMillion:ve},e[46]=$,e[47]=K,e[48]=q,e[49]=me,e[50]=je,e[51]=Oe,e[52]=Be,e[53]=Fe,e[54]=ue,e[55]=Re,e[56]=xe,e[57]=oe,e[58]=ve,e[59]=Se):Se=e[59];const le=Se;let T;e[60]!==x?(T=Ie("relative",x),e[60]=x,e[61]=T):T=e[61];let L;e[62]!==m?(L=Ie(Nh,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",m),e[62]=m,e[63]=L):L=e[63];const he=!R;let ge;e[64]!==v?(ge=()=>{M(!v)},e[64]=v,e[65]=ge):ge=e[65];let z;e[66]!==y?(z=y??s.jsx(A,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=y,e[67]=z):z=e[67];let pe;e[68]!==l||e[69]!==h?(pe=l??h("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=h,e[70]=pe):pe=e[70];let Ae;e[71]!==L||e[72]!==he||e[73]!==ge||e[74]!==z||e[75]!==pe?(Ae=s.jsxs(ze,{ref:_,type:"button",variant:"outline",size:"sm",className:L,disabled:he,onClick:ge,children:[z,pe]}),e[71]=L,e[72]=he,e[73]=ge,e[74]=z,e[75]=pe,e[76]=Ae):Ae=e[76];let G;e[77]!==B||e[78]!==R||e[79]!==p||e[80]!==g||e[81]!==k||e[82]!==Me||e[83]!==D||e[84]!==N||e[85]!==v||e[86]!==le||e[87]!==ie||e[88]!==w||e[89]!==O||e[90]!==C||e[91]!==j||e[92]!==I||e[93]!==S?(G=v?s.jsx("div",{className:Ie("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",g==="top"?"bottom-full mb-1":"top-full mt-1",p),style:{background:"linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))"},children:s.jsx(Fg,{providers:C,providerOrder:O,favoriteModels:k,recentModels:j,modelsMetadata:w,hiddenModels:D,searchQuery:I,onSearchQueryChange:E,onSelect:Me,labels:le,selectionCount:re=>ie.get(`${re.providerID}:${re.modelID}`)||0,disabled:!R,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:B?`${B}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:v,isFavorite:re=>N(re.providerID,re.modelID),onToggleFavorite:re=>S(re.providerID,re.modelID),onEscape:()=>{M(!1),E("")}})}):null,e[77]=B,e[78]=R,e[79]=p,e[80]=g,e[81]=k,e[82]=Me,e[83]=D,e[84]=N,e[85]=v,e[86]=le,e[87]=ie,e[88]=w,e[89]=O,e[90]=C,e[91]=j,e[92]=I,e[93]=S,e[94]=G):G=e[94];let ke;e[95]!==T||e[96]!==Ae||e[97]!==G?(ke=s.jsxs("div",{className:T,ref:W,children:[Ae,G]}),e[95]=T,e[96]=Ae,e[97]=G,e[98]=ke):ke=e[98];let Le;e[99]!==U||e[100]!==ie||e[101]!==o||e[102]!==a||e[103]!==C||e[104]!==n||e[105]!==b||e[106]!==h?(Le=b&&n.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:n.map((re,te)=>{const Ve=`${re.providerID}:${re.modelID}`,Ye=ie.get(Ve)||1,Ke=U(re),nt=C.find(Et=>Et.id===re.providerID)?.models?.find(Et=>Et.id===re.modelID),xt=nt?.variants?Object.keys(nt.variants):[],jt=xt.length>0,Mt=re.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(Pk,{model:re,instanceIndex:Ke,totalSameModel:Ye,onRemove:()=>o(te)}),jt&&s.jsxs(Un,{value:Mt,onValueChange:Et=>{if(!a)return;a(te,{...re,variant:Et==="__default__"?void 0:Et})},children:[s.jsxs(Hn,{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(A,{name:"brain-ai-3",className:Ie("h-3.5 w-3.5 flex-shrink-0",Mt==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(Cn,{placeholder:h("multirun.modelMultiSelect.variant.placeholder"),children:Et=>Et==="__default__"?h("multirun.modelMultiSelect.variant.default"):Et})]}),s.jsxs(Gn,{fitContent:!0,children:[s.jsx(Rs,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:h("multirun.modelMultiSelect.variant.default")}),xt.map(Lk)]})]})]},re.instanceId)})}),e[99]=U,e[100]=ie,e[101]=o,e[102]=a,e[103]=C,e[104]=n,e[105]=b,e[106]=h,e[107]=Le):Le=e[107];let Te;e[108]!==ke||e[109]!==Le?(Te=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[ke,Le]}),e[108]=ke,e[109]=Le,e[110]=Te):Te=e[110];let Z;e[111]!==f||e[112]!==c||e[113]!==n.length||e[114]!==h?(Z=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:f!==void 0?h("multirun.modelMultiSelect.validation.minToMax",{min:c,max:f}):h("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[111]=f,e[112]=c,e[113]=n.length,e[114]=h,e[115]=Z):Z=e[115];let F;return e[116]!==Te||e[117]!==Z?(F=s.jsxs("div",{className:"space-y-2",children:[Te,Z]}),e[116]=Te,e[117]=Z,e[118]=F):F=e[118],F};function Ik(t){return t.providers}function Rk(t){return t.modelsMetadata}function Ek(t){return t.toggleFavoriteModel}function Mk(t){return t.isFavoriteModel}function Fk(t){return t.hiddenModels}function Ok(t){return t.providerOrder}function Lk(t){return s.jsx(Rs,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const Bk=(t,e,n)=>{const r=t.session.title?.trim()||t.session.id;return`
226
-
227
- --- RESULT ${n+1}: ${r} ---
228
- ${e.trim()}
229
- --- END RESULT ${n+1} ---`},xf=(t,e)=>ft.getState().getWorktreeMetadata(t)?.projectDirectory??e,Vk=async t=>{const e=t.directory??void 0,n=Og(t.session.id,e);if(n.length===0&&t.directory){const o=(await Jn.withDirectory(t.directory,()=>Jn.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(Lg(o.id,e)).trim()}return""};function _k({session:t,open:e,onOpenChange:n}){const{t:r}=bt(),o=bc(),a=Sr(V=>V.activeSessions),c=Sr(V=>V.archivedSessions),l=ss(V=>V.providers),d=ss(V=>V.currentProviderId),f=ss(V=>V.currentModelId),m=ss(V=>V.currentAgentName),[u,p]=i.useState(d??""),[x,y]=i.useState(f??""),[b,g]=i.useState(()=>d&&f?[{providerID:d,modelID:f,instanceId:To()}]:[]),[h,C]=i.useState(""),[w,S]=i.useState(m??""),[N,k]=i.useState([]),[j,D]=i.useState(!1),O=i.useMemo(()=>ga(t.title),[t.title]),v=i.useMemo(()=>{const V=new Map;for(const R of o)V.set(R.id,R);for(const R of a)V.set(R.id,R);for(const R of c)V.set(R.id,R);return t.id&&V.set(t.id,t),Array.from(V.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!O)return;const V=ft.getState().getDirectoryForSession(t.id),R=xf(t.id,V),ne=v.map(ie=>{const J=ga(ie.title);if(!J||J.groupSlug!==O.groupSlug||J.fusion||(J.runGroup??null)!==(O.runGroup??null))return null;const U=ft.getState().getDirectoryForSession(ie.id)??Mr(ie),ee=xf(ie.id,U);return R&&ee&&R!==ee?null:{session:ie,directory:U,projectDirectory:ee}}).filter(ie=>ie!==null).sort((ie,J)=>(ie.session.time?.created??0)-(J.session.time?.created??0));k(ne)},[v,e,O,t.id]);const I=l.find(V=>V.id===u)?.models.find(V=>V.id===x),E=I?.variants?Object.keys(I.variants):[],B=!!(O&&u&&x&&N.length>0&&!j),P=i.useCallback(V=>{g([V]),p(V.providerID),y(V.modelID),C("")},[]),W=b[0]?.displayName||b[0]?.modelID||r("multirun.fusion.model.placeholder"),_=async()=>{if(!(!O||!u||!x)){D(!0);try{const V=await Promise.all(N.map(ae=>Vk(ae))),R=N.map((ae,de)=>({source:ae,text:V[de]??""})).filter(ae=>ae.text.trim().length>0);if(R.length===0){ce.error(r("multirun.fusion.toast.noOutputs"));return}const ne=N[0]?.projectDirectory??N[0]?.directory??null,ie=Nk(O.groupSlug,u,x,O.runGroup),[J,U]=await Promise.all([Rn("session.fusion.visible"),Rn("session.fusion.instructions")]),ee=await ft.getState().createSession(ie,ne,null);if(!ee)throw new Error("Failed to create fusion session");ft.getState().setCurrentSession(ee.id,ne),n(!1),await Jn.sendMessage({id:ee.id,providerID:u,modelID:x,variant:h||void 0,agent:w||void 0,text:J,additionalParts:[{text:U,synthetic:!0},...R.map((ae,de)=>({text:Bk(ae.source,ae.text,de),synthetic:!0})),{text:`
230
-
231
- --- FUSION INPUTS END ---
232
- Now write the final fused answer.`,synthetic:!0}],directory:ne??Jn.getDirectory()})}catch(V){console.error("[MultiRunFusion] Failed to start fusion",V),ce.error(r("multirun.fusion.toast.failed"))}finally{D(!1)}}};return s.jsx(Ms,{open:e,onOpenChange:n,children:s.jsxs(Es,{className:"max-w-xl overflow-visible",children:[s.jsxs(Ys,{children:[s.jsx(zs,{children:r("multirun.fusion.title")}),s.jsx(an,{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(kh,{selectedModels:b,onAdd:P,onUpdate:(V,R)=>P(R),onRemove:()=>{g([]),p(""),y(""),C("")},maxModels:1,addButtonLabel:W,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(Po,{providerId:u,className:"h-3.5 w-3.5 mr-1"}):void 0})}),E.length>0?s.jsxs(Un,{value:h||"__default__",onValueChange:V=>C(V==="__default__"?"":V),children:[s.jsxs(Hn,{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(A,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(Cn,{children:V=>V==="__default__"?r("multirun.modelMultiSelect.variant.default"):V})]}),s.jsxs(Gn,{fitContent:!0,portalToBody:!0,children:[s.jsx(Rs,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),E.map(V=>s.jsx(Rs,{value:V,children:V},V))]})]}):null,s.jsx(jh,{value:w,onChange:S,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:N.length})}),s.jsx("div",{className:"max-h-56 space-y-1 overflow-auto rounded-lg border border-[var(--interactive-border)] p-1",children:N.map(V=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(Po,{providerId:ga(V.session.title)?.providerID??"",className:"h-4 w-4"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:V.session.title||V.session.id}),s.jsx("button",{type:"button",onClick:()=>k(R=>R.filter(ne=>ne.session.id!==V.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(A,{name:"close",className:"h-4 w-4"})})]},V.session.id))})]}),s.jsxs(ur,{children:[s.jsx(ze,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx(ze,{onClick:_,disabled:!B,children:r(j?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function $k(t){const e=mt.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 zk=i.memo(function(e){const n=mt.c(22),{archiveLabel:r,deleteLabel:o,buttonSizeClass:a,iconSizeClass:c,onPointerDown:l,onMouseDown:d,onArchive:f,onDelete:m}=e,u=vk(),p=u?o:r;let x;n[0]!==f||n[1]!==m||n[2]!==u?(x=k=>{if(u||k.shiftKey){m(k);return}f(k)},n[0]=f,n[1]=m,n[2]=u,n[3]=x):x=n[3];const y=x,b=u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground";let g;n[4]!==a||n[5]!==b?(g=Ie("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",b,a),n[4]=a,n[5]=b,n[6]=g):g=n[6];const h=u?"delete-bin":"archive";let C;n[7]!==c||n[8]!==h?(C=s.jsx(A,{name:h,className:c}),n[7]=c,n[8]=h,n[9]=C):C=n[9];let w;n[10]!==y||n[11]!==p||n[12]!==d||n[13]!==l||n[14]!==g||n[15]!==C?(w=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",className:g,"aria-label":p,onPointerDown:l,onMouseDown:d,onClick:y,onKeyDown:Yk,children:C})}),n[10]=y,n[11]=p,n[12]=d,n[13]=l,n[14]=g,n[15]=C,n[16]=w):w=n[16];let S;n[17]!==p?(S=s.jsx(At,{side:"left",sideOffset:8,children:p}),n[17]=p,n[18]=S):S=n[18];let N;return n[19]!==w||n[20]!==S?(N=s.jsxs(kt,{children:[w,S]}),n[19]=w,n[20]=S,n[21]=N):N=n[21],N});function Wk(t){const{t:e}=bt(),{node:n,depth:r=0,groupDirectory:o,projectId:a,archivedBucket:c=!1,currentSessionId:l,pinnedSessionIds:d,expandedParents:f,hasSessionSearchQuery:m,normalizedSessionSearchQuery:u,notifyOnSubtasks:p,editingId:x,setEditingId:y,editTitle:b,setEditTitle:g,handleSaveEdit:h,handleCancelEdit:C,toggleParent:w,handleSessionSelect:S,handleSessionDoubleClick:N,togglePinnedSession:k,handleShareSession:j,copiedSessionId:D,handleCopyShareUrl:O,handleUnshareSession:v,openSidebarMenuKey:M,setOpenSidebarMenuKey:I,renamingFolderId:E,getFoldersForScope:B,getSessionFolderId:P,removeSessionFromFolder:W,addSessionToFolder:_,createFolderAndStartRename:V,openContextPanelTab:R,handleDeleteSession:ne,mobileVariant:ie,alwaysShowActions:J,renderSessionNode:U,secondaryMeta:ee,renderContext:ae="project",subtreeContainsActive:de,subtreeContainsEditing:ye,menuOpenSessionId:se,childRenderExtrasFor:we,liveSessionById:fe}=t,Me=!!ee?.projectLabel,$=!!ee?.branchLabel,K=Ir(Ue=>Ue.displayMode),q=i.useMemo(()=>Yr(),[]),me=K==="minimal"||q,je=i.useMemo(()=>Va(),[]),Oe=i.useContext(Bg),Be=q?"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=q?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",ue=q,Re=!c&&!ie,xe=me?q?Re&&ue?"group-hover:pr-18":Re||ue?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":q?Re&&ue?"group-hover:pr-18":Re||ue?"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",ve=i.useRef(!1),[Se,le]=i.useState(!1),T=i.useRef(x);T.current=x;const L=i.useRef(null),he=i.useRef(h);he.current=h;const[ge,z]=i.useState(b),pe=i.useRef(ge);pe.current=ge;const Ae=i.useRef(null),G=i.useRef(null),ke=n.session,Le=fe.get(ke.id)??ke,Te=rs(ke.directory??null)??rs(o??null),Z=am(Te??void 0,{bootstrap:!c}),F=Ec(),re=Wn(Ue=>Ue.enabled),te=Wn(i.useCallback(Ue=>Ue.selectedIds.has(ke.id),[ke.id])),Ve=Wn(Ue=>Ue.toggleSelected),Ye=Wn(Ue=>Ue.setRange),Ke=i.useCallback(Ue=>{const Jt=[],As=Ps=>{Ps.children.forEach($s=>{Jt.push($s.session.id),As($s)})};return As(Ue),Jt},[]),[Je,nt]=i.useState(!1),[xt,jt]=i.useState(!0),Mt=`${ae}:${c?"archived":"active"}:${ke.id}`,Et=hm(i.useCallback(Ue=>!!Ue.sessionMemoryState.get(Vg(ke.id))?.isZombie,[ke.id])),Ut=_g(ke.id),zt=$g(ke.id,Te??void 0),Ht=l===ke.id,_t=Le.title||e("sessions.sidebar.session.untitled"),Gt=n.children.length>0,Ce=d.has(ke.id),Qe=Mt,et=m?!0:f.has(Qe),yt=!!Le.parentID,at=zg(ke.id)>0&&(!yt||p),qe=Le.time?.updated||Le.time?.created||Date.now(),lt=pb(qe),Dt=gb(qe),us=M===Mt,[Lt,es]=i.useState(!1),os=us||Lt,Qt=i.useMemo(()=>ga(Le.title)!==null,[Le.title]),[Ft,Xt]=i.useState(!1),as=q&&ae==="recent"&&!me,$t=q&&ae==="recent"&&me,bs=i.useMemo(()=>Ke(n).length,[Ke,n]),Cs=i.useCallback(async Ue=>{const Jt=[];let As=0;for(const Ps of Ue)try{await F.ensureSessionRenderable(Ps.session.id);const $s=Vd(Z.getState(),Ps.session.id).list,Qs=Ps.session.title||e("sessions.sidebar.session.export.untitledSubagent"),Us=Ps.session.agent,Os=await Cs(Ps.children);As+=Os.skipped,Jt.push({title:Qs,agent:Us,records:$s,children:Os.children})}catch{As+=Ke(Ps).length+1}return{children:Jt,skipped:As}},[Ke,Z,F,e]),Tt=i.useCallback(Ue=>{Ue<=0||ce.warning(Ue===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:Ue}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:Ue}))},[e]),Bt=i.useCallback(async Ue=>{if(!Te){ce.error(e("sessions.sidebar.session.export.nothingToExport"));return}await F.ensureSessionRenderable(ke.id);const Jt=Vd(Z.getState(),ke.id).list;if(Jt.length===0){ce.error(e("sessions.sidebar.session.export.nothingToExport"));return}let As,Ps=0;if(Ue&&n.children.length>0){const Os=await Cs(n.children);As=Os.children,Ps=Os.skipped}const $s=ok(Jt,Le.title??null,As),Qs=uk(Le.title??null),Us=await lk($s,Qs);if(Us){ce.success(e("sessions.sidebar.session.export.success"),{action:{label:e(dk()),onClick:()=>{ck(Us).then(Os=>{Os||ce.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),Tt(Ps);return}ak($s,Qs),ce.success(e("sessions.sidebar.session.export.success")),Tt(Ps)},[Cs,Z,n.children,Le.title,ke.id,Te,Tt,F,e]),vt=i.useCallback(async()=>{if(n.children.length>0){jt(!0),nt(!0);return}await Bt(!1)},[Bt,n.children.length]),vs=i.useCallback(()=>{Te&&Gr("desktop_open_session_mini_chat_window",{sessionId:ke.id,directory:Te,apiBaseUrl:Hr(),clientToken:Wl()}).catch(Ue=>{console.warn("[session-sidebar] failed to open mini chat window",Ue)})},[ke.id,Te]);if(i.useEffect(()=>{if(x!==ke.id)return;const Ue=Jt=>{G.current&&!G.current.contains(Jt.target)&&he.current(pe.current)};return document.addEventListener("mousedown",Ue),()=>document.removeEventListener("mousedown",Ue)},[x,ke.id]),i.useLayoutEffect(()=>{if(x!==ke.id){Ae.current===ke.id&&(Ae.current=null);return}Ae.current!==ke.id&&(Ae.current=ke.id,z(b))},[x,b,ke.id]),x===ke.id)return s.jsx("div",{className:Ie("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:G,className:"flex w-full items-center gap-2",onSubmit:Ue=>{Ue.preventDefault(),h(ge)},children:[s.jsx("input",{value:ge,onChange:Ue=>z(Ue.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:Ue=>{if(Ue.stopPropagation(),Ue.key==="Escape"){C();return}}}),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(A,{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(A,{name:"close",className:"size-4"})})]}),me?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:[Gt?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:et?s.jsx(A,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(A,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:lt}),Me?s.jsx("span",{className:"truncate",children:ee?.projectLabel}):null,$?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:ee?.branchLabel})]}):null]})})]})},ke.id);const hs=Ut?.type??"idle",He=hs==="busy"||hs==="retry",it=zt.length,Rt=He||!He&&at&&!Ht,Pt=He?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")}),ps=!J&&Gt&&(Rt||Ce),ls=Ce&&!Rt,ns=s.jsx(A,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}),Wt=Rt||ls?s.jsxs("span",{className:Ie("pointer-events-none absolute left-0.5 inline-flex h-3.5 w-3.5 items-center justify-center transition-opacity",me?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",ps?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[Rt?Pt:null,ls?ns:null]}):null,ln=Gt&&!J&&(Rt||Ce),fs=Gt?s.jsx("span",{role:"button",tabIndex:0,onClick:Ue=>{Ue.stopPropagation(),w(Qe)},onKeyDown:Ue=>{(Ue.key==="Enter"||Ue.key===" ")&&(Ue.preventDefault(),Ue.stopPropagation(),w(Qe))},style:{minWidth:14,minHeight:14},className:Ie("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",as?"absolute left-1.5 bottom-1":$t?"relative mr-0.5 shrink-0":Ie("absolute left-0.5",me?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!as&&!$t&&ln?"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(et?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:et?s.jsx(A,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(A,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Fs=Et?s.jsx(A,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Ws=Ue=>{Ue&&es(!1),I(Ue?Mt:null)},sn=Ue=>{if(!Ue&&L.current){const{id:Jt,title:As}=L.current;L.current=null,y(Jt),g(As)}},An=Ue=>{es(Ue)},vn=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),I(us?null:Mt)},be=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},Ze=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},dt=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},wt=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},Vt=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),I(null),ne(ke,{archivedBucket:c})},ht=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),I(null),ne(ke,{archivedBucket:c,hardDelete:!0,skipConfirm:!0})},cs=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},ds=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},Ss=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),Oe?.vscode?.executeCommand("openchamber.openSessionInEditor",ke.id,_t)},gs=Ue=>{if(ve.current){ve.current=!1;return}if(re){if(Ue?.preventDefault(),Ue?.stopPropagation(),Ue?.shiftKey){const As=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Qs=>Qs.getAttribute("data-session-row")).filter(Qs=>typeof Qs=="string"&&Qs.length>0),Ps=Wn.getState().anchorId,$s=new Map;$s.set(ke.id,Ke(n)),Ye(Ps,ke.id,As,Te??null,$s);return}Ve(ke.id,Te??null,Ke(n));return}S(ke.id,Te,a)},Ts=Ue=>{Ue.defaultPrevented||Ue.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||gs(Ue)},Fn=Ue=>{(Ue.button===2||Ue.button===0&&Ue.ctrlKey&&!re)&&(ve.current=!0)},_s=Ue=>{ie&&Ue.pointerType==="touch"&&le(!0)},hn=Ue=>{ie&&Ue.pointerType==="touch"&&le(!1)},On=({Item:Ue,Separator:Jt,Sub:As,SubTrigger:Ps,SubContent:$s})=>s.jsxs(s.Fragment,{children:[s.jsxs(Ue,{onClick:()=>{L.current={id:ke.id,title:_t}},className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(Ue,{onClick:()=>k(ke.id),className:"[&>svg]:mr-1",children:[Ce?s.jsx(A,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(A,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(Ce?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),Le.share?s.jsxs(s.Fragment,{children:[s.jsx(Ue,{onClick:()=>{Le.share?.url&&O(Le.share.url,ke.id)},className:"[&>svg]:mr-1",children:D===ke.id?s.jsxs(s.Fragment,{children:[s.jsx(A,{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(A,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(Ue,{onClick:()=>v(ke.id),className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.unshare")]})]}):s.jsxs(Ue,{onClick:()=>j(Le),className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(Ue,{onClick:()=>{vt()},className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),Qt?s.jsxs(Ue,{onClick:()=>Xt(!0),className:"[&>svg]:mr-1",children:[s.jsx($k,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,Te&&!c?(()=>{const Qs=B(Te),Us=P(Te,ke.id);return s.jsxs(s.Fragment,{children:[s.jsx(Jt,{}),s.jsxs(As,{children:[s.jsxs(Ps,{className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs($s,{className:"min-w-[180px]",children:[Qs.length===0?s.jsx(Ue,{disabled:!0,className:"text-muted-foreground",children:e("sessions.sidebar.folders.none")}):Qs.map(Os=>s.jsxs(Ue,{onClick:()=>{Us===Os.id?W(Te,ke.id):_(Te,Os.id,ke.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:Os.name}),Us===Os.id?s.jsx(A,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Os.id)),s.jsx(Jt,{}),s.jsxs(Ue,{onClick:()=>{const Os=V(Te);Os&&_(Te,Os.id,ke.id)},children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),Us?s.jsxs(Ue,{onClick:()=>{W(Te,ke.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,q?null:s.jsxs(Ue,{disabled:!Te,onClick:()=>{Te&&R(Te,{mode:"chat",dedupeKey:`session:${ke.id}`,label:_t,sessionTitleFallback:_t})},className:"[&>svg]:mr-1",children:[s.jsx(A,{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")})]}),je?s.jsxs(Ue,{disabled:!Te,onClick:vs,className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(Jt,{}),c?null:s.jsxs(Ue,{className:"[&>svg]:mr-1",onClick:()=>ne(ke,{archivedBucket:c}),children:[s.jsx(A,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.archive")]}),s.jsxs(Ue,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ne(ke,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(A,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),Zn=s.jsx(en,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(E||T.current),children:On({Item:xs,Separator:Fr,Sub:Gg,SubTrigger:Kg,SubContent:qg})}),cn=s.jsx(md,{children:s.jsx(hd,{className:"app-region-no-drag z-50",children:s.jsx(pd,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(E||T.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Ie(_d,"min-w-[180px]"),children:On({Item:({className:Ue,...Jt})=>s.jsx(op,{className:Ie(Wg,Ue),...Jt}),Separator:({className:Ue,...Jt})=>s.jsx(ap,{className:Ie(Ug,Ue),...Jt}),Sub:lp,SubTrigger:({className:Ue,children:Jt,...As})=>s.jsxs(cp,{className:Ie(Hg,Ue),...As,children:[Jt,s.jsx(A,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:Ue,children:Jt,...As})=>s.jsx(md,{children:s.jsx(hd,{className:"app-region-no-drag z-50",children:s.jsx(pd,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Ie(_d,Ue),...As,children:Jt})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(CN,{sessionId:ke.id,sessionDirectory:Te??null,sessionTitle:_t,children:s.jsxs(rp,{open:Lt,onOpenChange:An,onOpenChangeComplete:sn,children:[s.jsxs(ip,{render:s.jsx("div",{"data-session-row":ke.id,"data-session-scope":Te??"","data-session-archived":c?"1":"0",onClick:Ts,className:Ie("group relative my-0.5 flex cursor-pointer items-center rounded-md py-1 pr-1.5","-ml-3",r>0?"pl-[32px]":"pl-[18px]",Ht&&!te&&"bg-primary/10",te&&"bg-interactive-selection")}),children:[Wt,fs,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:me?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:_s,onPointerUp:hn,onPointerCancel:hn,onMouseDown:Fn,onClick:Ue=>gs(Ue),onDoubleClick:Ue=>{Ue.stopPropagation(),N(ke.id,_t)},className:Ie("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]",Se&&"bg-interactive-hover/70",J?q?xe:oe:xe),children:s.jsxs("div",{className:Ie("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Ie("block min-w-0 flex-1 truncate typography-ui-label font-normal",Ht?"text-primary":"text-foreground"),children:jo(_t,u)}),J?s.jsx("span",{className:"ml-2 flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Dt}):null,J?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:Ie("whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",os?"opacity-0":Fe),children:Dt})}),it>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(A,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:it})]}):null]})})}),q?null:s.jsx(At,{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:Ie("flex items-center gap-3 text-left text-muted-foreground",ee?.projectLabel?"justify-between":"justify-start"),children:[ee?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:ee.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:lt})]}),ee?.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(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:ee.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:_s,onPointerUp:hn,onPointerCancel:hn,onMouseDown:Fn,onClick:Ue=>gs(Ue),onDoubleClick:Ue=>{Ue.stopPropagation(),N(ke.id,_t)},className:Ie("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]",Se&&"bg-interactive-hover/70",J?q?xe:oe:xe),children:[s.jsxs("div",{className:Ie("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Ie("block min-w-0 flex-1 truncate typography-ui-label font-normal",Ht?"text-primary":"text-foreground"),children:jo(_t,u)}),it>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(A,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:it})]}):null]}),me?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:Ie("flex min-w-0 items-center gap-1.5 overflow-hidden",as&&Gt?"pl-4":""),children:[s.jsx("span",{className:"flex-shrink-0",children:lt}),Me?s.jsx("span",{className:"truncate",children:ee?.projectLabel}):null,$?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:ee?.branchLabel})]}):null]})})]})}),Fs&&!ie?s.jsx("div",{className:Ie("absolute top-1/2 -translate-y-1/2 z-10",me?"right-0":"right-[30px]"),children:Fs}):null,s.jsxs("div",{className:Ie("absolute right-0 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",os||J&&!q?"opacity-100":Ie("opacity-0",Be)),children:[Re?s.jsx(zk,{archiveLabel:e("sessions.sidebar.bulkActions.archive"),deleteLabel:e("sessions.sidebar.bulkActions.delete"),buttonSizeClass:me&&!J?"h-4 w-4":"h-6 w-6",iconSizeClass:me&&!J?"h-2.5 w-2.5":"h-3.5 w-3.5",onPointerDown:dt,onMouseDown:wt,onArchive:Vt,onDelete:ht}):null,ue?s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",className:Ie("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",me&&!J?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:cs,onMouseDown:ds,onClick:Ss,onKeyDown:Ue=>Ue.stopPropagation(),children:s.jsx(A,{name:"external-link",className:Ie(me&&!J?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(At,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(tn,{open:us,onOpenChange:Ws,onOpenChangeComplete:sn,children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:Ie("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",me&&!J?os?"h-4 w-4 opacity-100":Ie("h-4 w-4 opacity-0",Be):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:be,onMouseDown:Ze,onClick:vn,onKeyDown:Ue=>Ue.stopPropagation(),children:s.jsx(A,{name:"more-2",className:Ie(me&&!J?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),Zn]})]})]}),cn]})}),Gt&&et?n.children.map(Ue=>{const Jt=we?we(Ue):{subtreeContainsActive:de,subtreeContainsEditing:ye,menuOpenSessionId:se,nodeStructureKey:""};return U(Ue,r+1,Te??o,a,c,void 0,ae,Jt)}):null,s.jsx(Ms,{open:Je,onOpenChange:nt,children:s.jsxs(Es,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ys,{children:[s.jsx(zs,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(an,{children:bs===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:bs}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:bs})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:xt,onChange:Ue=>jt(Ue.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(ur,{children:[s.jsx(ze,{type:"button",onClick:()=>nt(!1),variant:"outline",size:"sm",children:e("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{type:"button",onClick:()=>{nt(!1),Bt(xt)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),Qt?s.jsx(_k,{session:Le,open:Ft,onOpenChange:Xt}):null]},ke.id)}const bf=t=>rs(t.session.directory??null),Uk=(t,e)=>(t?.projectLabel??null)===(e?.projectLabel??null)&&(t?.branchLabel??null)===(e?.branchLabel??null),Hk=t=>{if(!t.openSidebarMenuKey)return null;const e=t.archivedBucket?"archived":"active",n=`${t.renderContext??"project"}:${e}:`;return t.openSidebarMenuKey.startsWith(n)?t.openSidebarMenuKey.slice(n.length):null},sa=t=>t.menuOpenSessionId??Hk(t),zi=(t,e,n)=>e?n.has(t.node.session.id)?!0:Ur(t.node,e):!1,La=(t,e,n,r,o)=>{if(t.session.id!==e.session.id)return!0;const a=o(t);if(n.has(a)!==r.has(a)||t.children.length!==e.children.length)return!0;for(let c=0;c<t.children.length;c+=1)if(La(t.children[c],e.children[c],n,r,o))return!0;return!1},Ch=(t,e,n,r)=>{if(t.session.id!==e.session.id)return!0;const o=t.session.id;if((n.get(o)??t.session)!==(r.get(o)??e.session)||t.children.length!==e.children.length)return!0;for(let a=0;a<t.children.length;a+=1)if(Ch(t.children[a],e.children[a],n,r))return!0;return!1},Gk=(t,e)=>{if(t.hasSessionSearchQuery||e.hasSessionSearchQuery)return!1;const n=t.archivedBucket?"archived":"active",r=e.archivedBucket?"archived":"active";return La(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${t.renderContext??"project"}:${n}:${o.session.id}`)||La(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${e.renderContext??"project"}:${r}:${o.session.id}`)},Kk=(t,e)=>{if(t.node.session.id!==e.node.session.id||t.depth!==e.depth||t.groupDirectory!==e.groupDirectory||t.projectId!==e.projectId||t.archivedBucket!==e.archivedBucket||(t.renderContext??"project")!==(e.renderContext??"project")||t.mobileVariant!==e.mobileVariant||t.alwaysShowActions!==e.alwaysShowActions||t.hasSessionSearchQuery!==e.hasSessionSearchQuery||t.normalizedSessionSearchQuery!==e.normalizedSessionSearchQuery||t.notifyOnSubtasks!==e.notifyOnSubtasks||t.nodeStructureKey!==e.nodeStructureKey||bf(t.node)!==bf(e.node)||!Uk(t.secondaryMeta,e.secondaryMeta)||t.liveSessionById!==e.liveSessionById&&Ch(t.node,e.node,t.liveSessionById,e.liveSessionById)||t.pinnedSessionIds!==e.pinnedSessionIds&&La(t.node,e.node,t.pinnedSessionIds,e.pinnedSessionIds,n=>n.session.id)||t.expandedParents!==e.expandedParents&&Gk(t,e)||t.currentSessionId!==e.currentSessionId&&(zi(t,t.currentSessionId,t.subtreeContainsActive)||zi(e,e.currentSessionId,e.subtreeContainsActive))||t.editingId!==e.editingId&&(zi(t,t.editingId,t.subtreeContainsEditing)||zi(e,e.editingId,e.subtreeContainsEditing))||t.editTitle!==e.editTitle&&(zi(t,t.editingId,t.subtreeContainsEditing)||zi(e,e.editingId,e.subtreeContainsEditing))||t.copiedSessionId!==e.copiedSessionId&&(Ur(t.node,t.copiedSessionId)||Ur(e.node,e.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=sa(t),r=sa(e);if(Ur(t.node,n)||Ur(e.node,r))return!1}if(t.renamingFolderId!==e.renamingFolderId){const n=sa(t),r=sa(e);if(Ur(t.node,n)||Ur(e.node,r))return!1}return t.setEditingId===e.setEditingId&&t.setEditTitle===e.setEditTitle&&t.handleSaveEdit===e.handleSaveEdit&&t.handleCancelEdit===e.handleCancelEdit&&t.toggleParent===e.toggleParent&&t.handleSessionSelect===e.handleSessionSelect&&t.handleSessionDoubleClick===e.handleSessionDoubleClick&&t.togglePinnedSession===e.togglePinnedSession&&t.handleShareSession===e.handleShareSession&&t.handleCopyShareUrl===e.handleCopyShareUrl&&t.handleUnshareSession===e.handleUnshareSession&&t.setOpenSidebarMenuKey===e.setOpenSidebarMenuKey&&t.getFoldersForScope===e.getFoldersForScope&&t.getSessionFolderId===e.getSessionFolderId&&t.removeSessionFromFolder===e.removeSessionFromFolder&&t.addSessionToFolder===e.addSessionToFolder&&t.createFolderAndStartRename===e.createFolderAndStartRename&&t.openContextPanelTab===e.openContextPanelTab&&t.handleDeleteSession===e.handleDeleteSession&&t.renderSessionNode===e.renderSessionNode},qk=i.memo(Wk,Kk);function Yk(t){return t.stopPropagation()}function Qk(t){const e=mt.c(71),{t:n}=bt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,f,m,u,p,x,y,b,g,h;if(e[0]!==o||e[1]!==n||e[2]!==r){const R=n("sessions.sidebar.session.untitled");u=Ms,g=!!r,e[13]!==o?(h=ie=>{ie||o(null)},e[13]=o,e[14]=h):h=e[14],m=Es,y=!1,b="max-w-sm gap-5",f=Ys;let ne;e[15]!==n||e[16]!==r?.archivedBucket?(ne=r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.title"):n("sessions.sidebar.dialogs.archiveSession.title"),e[15]=n,e[16]=r?.archivedBucket,e[17]=ne):ne=e[17],e[18]!==ne?(x=s.jsx(zs,{children:ne}),e[18]=ne,e[19]=x):x=e[19],d=an,p=r&&r.descendantCount>0?r.archivedBucket?r.descendantCount===1?n("sessions.sidebar.dialogs.deleteSession.withOneSubtask",{sessionTitle:r.session.title||R,count:r.descendantCount}):n("sessions.sidebar.dialogs.deleteSession.withManySubtasks",{sessionTitle:r.session.title||R,count:r.descendantCount}):r.descendantCount===1?n("sessions.sidebar.dialogs.archiveSession.withOneSubtask",{sessionTitle:r.session.title||R,count:r.descendantCount}):n("sessions.sidebar.dialogs.archiveSession.withManySubtasks",{sessionTitle:r.session.title||R,count:r.descendantCount}):r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.single",{sessionTitle:r?.session.title||R}):n("sessions.sidebar.dialogs.archiveSession.single",{sessionTitle:r?.session.title||R}),e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=f,e[5]=m,e[6]=u,e[7]=p,e[8]=x,e[9]=y,e[10]=b,e[11]=g,e[12]=h}else d=e[3],f=e[4],m=e[5],u=e[6],p=e[7],x=e[8],y=e[9],b=e[10],g=e[11],h=e[12];let C;e[20]!==d||e[21]!==p?(C=s.jsx(d,{children:p}),e[20]=d,e[21]=p,e[22]=C):C=e[22];let w;e[23]!==f||e[24]!==x||e[25]!==C?(w=s.jsxs(f,{children:[x,C]}),e[23]=f,e[24]=x,e[25]=C,e[26]=w):w=e[26];let S;e[27]!==c||e[28]!==a?(S=()=>c(!a),e[27]=c,e[28]=a,e[29]=S):S=e[29];const N=!a;let k;e[30]!==a?(k=a?s.jsx(A,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(A,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[30]=a,e[31]=k):k=e[31];let j;e[32]!==n?(j=n("sessions.sidebar.dialogs.neverAsk"),e[32]=n,e[33]=j):j=e[33];let D;e[34]!==k||e[35]!==j||e[36]!==S||e[37]!==N?(D=s.jsxs("button",{type:"button",onClick:S,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":N,children:[k,j]}),e[34]=k,e[35]=j,e[36]=S,e[37]=N,e[38]=D):D=e[38];let O;e[39]!==o?(O=()=>o(null),e[39]=o,e[40]=O):O=e[40];let v;e[41]!==n?(v=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=v):v=e[42];let M;e[43]!==O||e[44]!==v?(M=s.jsx("button",{type:"button",onClick:O,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:v}),e[43]=O,e[44]=v,e[45]=M):M=e[45];let I;e[46]!==l?(I=()=>{l()},e[46]=l,e[47]=I):I=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 B;e[51]!==I||e[52]!==E?(B=s.jsx("button",{type:"button",onClick:I,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]=I,e[52]=E,e[53]=B):B=e[53];let P;e[54]!==M||e[55]!==B?(P=s.jsxs("div",{className:"flex items-center gap-2",children:[M,B]}),e[54]=M,e[55]=B,e[56]=P):P=e[56];let W;e[57]!==D||e[58]!==P?(W=s.jsxs(ur,{className:"w-full sm:items-center sm:justify-between",children:[D,P]}),e[57]=D,e[58]=P,e[59]=W):W=e[59];let _;e[60]!==m||e[61]!==y||e[62]!==W||e[63]!==b||e[64]!==w?(_=s.jsxs(m,{showCloseButton:y,className:b,children:[w,W]}),e[60]=m,e[61]=y,e[62]=W,e[63]=b,e[64]=w,e[65]=_):_=e[65];let V;return e[66]!==u||e[67]!==_||e[68]!==g||e[69]!==h?(V=s.jsx(u,{open:g,onOpenChange:h,children:_}),e[66]=u,e[67]=_,e[68]=g,e[69]=h,e[70]=V):V=e[70],V}function Jk(t){const e=mt.c(57),{t:n}=bt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t,d=r?.archivedBucket===!0,f=r?.sessionCount??0;let m;e[0]!==d||e[1]!==f||e[2]!==n?(m=n(d?f===1?"sessions.sidebar.dialogs.deleteSession.title":"sessions.sidebar.dialogs.deleteSessions.title":f===1?"sessions.sidebar.dialogs.archiveSession.title":"sessions.sidebar.dialogs.archiveSessions.title"),e[0]=d,e[1]=f,e[2]=n,e[3]=m):m=e[3];const u=m;let p;e[4]!==d||e[5]!==f||e[6]!==n?(p=d?f===1?n("sessions.sidebar.dialogs.deleteSessions.singleDescription",{count:f}):n("sessions.sidebar.dialogs.deleteSessions.pluralDescription",{count:f}):f===1?n("sessions.sidebar.dialogs.archiveSessions.singleDescription",{count:f}):n("sessions.sidebar.dialogs.archiveSessions.pluralDescription",{count:f}),e[4]=d,e[5]=f,e[6]=n,e[7]=p):p=e[7];const x=p,y=!!r;let b;e[8]!==o?(b=V=>{V||o(null)},e[8]=o,e[9]=b):b=e[9];let g;e[10]!==u?(g=s.jsx(zs,{children:u}),e[10]=u,e[11]=g):g=e[11];let h;e[12]!==x?(h=s.jsx(an,{children:x}),e[12]=x,e[13]=h):h=e[13];let C;e[14]!==g||e[15]!==h?(C=s.jsxs(Ys,{children:[g,h]}),e[14]=g,e[15]=h,e[16]=C):C=e[16];let w;e[17]!==c||e[18]!==a?(w=()=>c(!a),e[17]=c,e[18]=a,e[19]=w):w=e[19];const S=!a;let N;e[20]!==a?(N=a?s.jsx(A,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(A,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[20]=a,e[21]=N):N=e[21];let k;e[22]!==n?(k=n("sessions.sidebar.dialogs.neverAsk"),e[22]=n,e[23]=k):k=e[23];let j;e[24]!==k||e[25]!==w||e[26]!==S||e[27]!==N?(j=s.jsxs("button",{type:"button",onClick:w,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":S,children:[N,k]}),e[24]=k,e[25]=w,e[26]=S,e[27]=N,e[28]=j):j=e[28];let D;e[29]!==o?(D=()=>o(null),e[29]=o,e[30]=D):D=e[30];let O;e[31]!==n?(O=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=O):O=e[32];let v;e[33]!==D||e[34]!==O?(v=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:O}),e[33]=D,e[34]=O,e[35]=v):v=e[35];let M;e[36]!==l?(M=()=>{l()},e[36]=l,e[37]=M):M=e[37];let I;e[38]!==d||e[39]!==n?(I=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=I):I=e[40];let E;e[41]!==M||e[42]!==I?(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:I}),e[41]=M,e[42]=I,e[43]=E):E=e[43];let B;e[44]!==v||e[45]!==E?(B=s.jsxs("div",{className:"flex items-center gap-2",children:[v,E]}),e[44]=v,e[45]=E,e[46]=B):B=e[46];let P;e[47]!==j||e[48]!==B?(P=s.jsxs(ur,{className:"w-full sm:items-center sm:justify-between",children:[j,B]}),e[47]=j,e[48]=B,e[49]=P):P=e[49];let W;e[50]!==P||e[51]!==C?(W=s.jsxs(Es,{showCloseButton:!1,className:"max-w-sm gap-5",children:[C,P]}),e[50]=P,e[51]=C,e[52]=W):W=e[52];let _;return e[53]!==y||e[54]!==W||e[55]!==b?(_=s.jsx(Ms,{open:y,onOpenChange:b,children:W}),e[53]=y,e[54]=W,e[55]=b,e[56]=_):_=e[56],_}function Xk(t){const e=mt.c(36),{t:n}=bt(),{value:r,setValue:o,onConfirm:a}=t,c=!!r;let l;e[0]!==o?(l=N=>{N||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 f;e[4]!==d?(f=s.jsx(zs,{children:d}),e[4]=d,e[5]=f):f=e[5];let m;e[6]!==n||e[7]!==r?(m=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]=m):m=e[8];let u;e[9]!==m?(u=s.jsx(an,{children:m}),e[9]=m,e[10]=u):u=e[10];let p;e[11]!==f||e[12]!==u?(p=s.jsxs(Ys,{children:[f,u]}),e[11]=f,e[12]=u,e[13]=p):p=e[13];let x;e[14]!==o?(x=()=>o(null),e[14]=o,e[15]=x):x=e[15];let y;e[16]!==n?(y=n("sessions.sidebar.dialogs.cancel"),e[16]=n,e[17]=y):y=e[17];let b;e[18]!==x||e[19]!==y?(b=s.jsx("button",{type:"button",onClick:x,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:y}),e[18]=x,e[19]=y,e[20]=b):b=e[20];let g;e[21]!==n?(g=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=g):g=e[22];let h;e[23]!==a||e[24]!==g?(h=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:g}),e[23]=a,e[24]=g,e[25]=h):h=e[25];let C;e[26]!==h||e[27]!==b?(C=s.jsxs(ur,{children:[b,h]}),e[26]=h,e[27]=b,e[28]=C):C=e[28];let w;e[29]!==C||e[30]!==p?(w=s.jsxs(Es,{showCloseButton:!1,className:"max-w-sm gap-5",children:[p,C]}),e[29]=C,e[30]=p,e[31]=w):w=e[31];let S;return e[32]!==c||e[33]!==l||e[34]!==w?(S=s.jsx(Ms,{open:c,onOpenChange:l,children:w}),e[32]=c,e[33]=l,e[34]=w,e[35]=S):S=e[35],S}const Zk=t=>{const e=mt.c(46),{selectedCount:n,scopeKey:r,scopeFolders:o,archivedBucket:a,onMoveToFolder:c,onCreateFolderAndMove:l,onRemoveFromFolder:d,canRemoveFromFolder:f,onDelete:m,onDone:u}=t,{t:p}=bt(),x=!!r&&!a;let y;e[0]!==a||e[1]!==p?(y=p(a?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[0]=a,e[1]=p,e[2]=y):y=e[2];const b=y;let g;e[3]!==n||e[4]!==p?(g=p("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=p,e[5]=g):g=e[5];let h;e[6]!==g?(h=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:g}),e[6]=g,e[7]=h):h=e[7];let C;e[8]!==x||e[9]!==f||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==p?(C=x?s.jsxs(tn,{children:[s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(Zs,{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":p("sessions.sidebar.bulkActions.moveToFolder"),children:s.jsx(A,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(At,{side:"top",sideOffset:4,children:s.jsx("p",{children:p("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(en,{align:"end",className:"min-w-[180px]",children:[o.length===0?s.jsx(xs,{disabled:!0,className:"text-muted-foreground",children:p("sessions.sidebar.folders.none")}):o.map(W=>s.jsx(xs,{onClick:()=>c(W.id),children:s.jsx("span",{className:"flex-1 truncate",children:W.name})},W.id)),s.jsx(Fr,{}),s.jsxs(xs,{onClick:l,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.newFolderEllipsis")]}),f?s.jsxs(xs,{onClick:d,className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"close",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=x,e[9]=f,e[10]=l,e[11]=c,e[12]=d,e[13]=o,e[14]=p,e[15]=C):C=e[15];let w;e[16]===Symbol.for("react.memo_cache_sentinel")?(w=Ie("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]=w):w=e[16];let S;e[17]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(A,{name:"delete-bin",className:"h-4 w-4"}),e[17]=S):S=e[17];let N;e[18]!==b||e[19]!==m?(N=s.jsx(Ct,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,className:w,"aria-label":b,children:S})}),e[18]=b,e[19]=m,e[20]=N):N=e[20];let k;e[21]!==b?(k=s.jsx(At,{side:"top",sideOffset:4,children:s.jsx("p",{children:b})}),e[21]=b,e[22]=k):k=e[22];let j;e[23]!==N||e[24]!==k?(j=s.jsxs(kt,{children:[N,k]}),e[23]=N,e[24]=k,e[25]=j):j=e[25];let D;e[26]!==p?(D=p("sessions.sidebar.header.actions.exitSelection"),e[26]=p,e[27]=D):D=e[27];let O;e[28]===Symbol.for("react.memo_cache_sentinel")?(O=s.jsx(A,{name:"close",className:"h-4 w-4"}),e[28]=O):O=e[28];let v;e[29]!==u||e[30]!==D?(v=s.jsx(Ct,{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":D,children:O})}),e[29]=u,e[30]=D,e[31]=v):v=e[31];let M;e[32]!==p?(M=p("sessions.sidebar.header.actions.exitSelection"),e[32]=p,e[33]=M):M=e[33];let I;e[34]!==M?(I=s.jsx(At,{side:"top",sideOffset:4,children:s.jsx("p",{children:M})}),e[34]=M,e[35]=I):I=e[35];let E;e[36]!==v||e[37]!==I?(E=s.jsxs(kt,{children:[v,I]}),e[36]=v,e[37]=I,e[38]=E):E=e[38];let B;e[39]!==E||e[40]!==C||e[41]!==j?(B=s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[C,j,E]}),e[39]=E,e[40]=C,e[41]=j,e[42]=B):B=e[42];let P;return e[43]!==B||e[44]!==h?(P=s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-2.5 py-1.5",children:[h,B]}),e[43]=B,e[44]=h,e[45]=P):P=e[45],P},e2=t=>{const{t:e}=bt(),{isInlineEditing:n,showDeletionDialog:r,foldersMap:o,addSessionsToFolder:a,removeSessionsFromFolders:c,createFolderAndStartRename:l,archiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:m}=t,u=Wn(I=>I.enabled),p=Wn(I=>I.selectedIds.size),x=p>0,y=Wn(I=>I.selectedIds),b=Wn(I=>I.scopeKey),g=i.useCallback(()=>{Wn.getState().toggleMode()},[]),h=i.useCallback(()=>{Wn.getState().disable()},[]),C=i.useMemo(()=>{if(!x||typeof document>"u")return!1;let I=!1,E=!1;for(const B of y){const P=document.querySelectorAll(`[data-session-row="${CSS.escape(B)}"]`);for(const W of P)W.getAttribute("data-session-archived")==="1"?E=!0:I=!0}return E&&!I},[x,y]),w=i.useMemo(()=>{if(b)return b;if(!x||typeof document>"u")return null;for(const I of y){const B=document.querySelector(`[data-session-row="${CSS.escape(I)}"]`)?.getAttribute("data-session-scope");if(B&&B.length>0)return B}return null},[x,y,b]),S=i.useMemo(()=>w?o[w]??[]:[],[o,w]),N=i.useMemo(()=>{if(!w||!x)return!1;const I=o[w]??[];for(const E of I)for(const B of E.sessionIds)if(y.has(B))return!0;return!1},[o,w,x,y]),k=i.useCallback(I=>{!w||!x||a(w,I,Array.from(y))},[a,y,w,x]),j=i.useCallback(()=>{if(!w||!x)return;const I=l(w);I&&a(w,I.id,Array.from(y))},[a,l,y,w,x]),D=i.useCallback(()=>{!w||!x||c(w,Array.from(y))},[c,y,w,x]),O=i.useCallback(async()=>{const I=Array.from(y);if(I.length!==0){if(C){const{deletedIds:E,failedIds:B}=await f(I);E.length>0&&ce.success(E.length===1?e("sessions.sidebar.bulkActions.deletedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.deletedPlural",{count:E.length})),B.length>0&&ce.error(B.length===1?e("sessions.sidebar.bulkActions.failedDeleteSingle",{count:B.length}):e("sessions.sidebar.bulkActions.failedDeletePlural",{count:B.length}))}else{const{archivedIds:E,failedIds:B}=await d(I);E.length>0&&ce.success(E.length===1?e("sessions.sidebar.bulkActions.archivedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.archivedPlural",{count:E.length})),B.length>0&&ce.error(B.length===1?e("sessions.sidebar.bulkActions.failedArchiveSingle",{count:B.length}):e("sessions.sidebar.bulkActions.failedArchivePlural",{count:B.length}))}Wn.getState().clear()}},[d,C,f,y,e]),v=i.useCallback(()=>{if(!x)return;const I=y.size;if(!r){O();return}m({sessionCount:I,archivedBucket:C})},[C,O,y,r,m,x]),M=i.useCallback(async()=>{m(null),await O()},[O]);return i.useEffect(()=>{if(!u)return;const I=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=B=>{if(n)return;const P=B.target;if(P&&(P.tagName==="INPUT"||P.tagName==="TEXTAREA"||P.isContentEditable))return;const W=I?B.metaKey:B.ctrlKey;if(B.key==="Escape"){B.preventDefault(),Wn.getState().disable();return}if(W&&B.key==="Backspace"){B.preventDefault(),v();return}if(W&&(B.key==="a"||B.key==="A")){const _=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(_.length===0)return;B.preventDefault();const R=Wn.getState().scopeKey??_[0]?.getAttribute("data-session-scope")??null,ne=J=>R?J.getAttribute("data-session-scope")===R:!0,ie=_.filter(ne).map(J=>J.getAttribute("data-session-row")).filter(J=>typeof J=="string"&&J.length>0);if(ie.length===0)return;Wn.getState().replaceAll(ie,R||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[v,n,u]),{selectionModeEnabled:u,hasSelection:x,selectedIdsSize:p,bulkScopeIsArchived:C,derivedSelectionScope:w,bulkScopeFolders:S,bulkCanRemoveFromFolder:N,handleToggleSelectionMode:g,handleExitSelectionMode:h,handleBulkMoveToFolder:k,handleBulkCreateFolderAndMove:j,handleBulkRemoveFromFolder:D,handleBulkDelete:v,confirmBulkDelete:M}},t2=2880*60*1e3,s2=t=>!!t.parentID,n2=t=>!!t.time?.archived,lc=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},r2=t=>[...t].sort((e,n)=>lc(n)-lc(e)),i2=(t,e=Date.now())=>{const n=e-t2,r=t.filter(o=>n2(o)||s2(o)?!1:lc(o)>=n);return r2(r)},yf="openchamber.shareOpinionToast.dismissed.v2",na="oc.sessions.projectCollapse",wf="oc.sessions.groupOrder",vf="oc.sessions.groupCollapse",Sf="oc.sessions.activeSessionByProject",Ml="oc.sessions.expandedParents.v2",o2="oc.sessions.expandedParents",a2="oc.sessions.pinned",l2=(t,e,n)=>{const r=new Set;for(const o of t){const a=rs(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=rs(a.path)?.toLowerCase();c&&r.add(c)}return r},c2=(t,e,n)=>{if(t.time?.archived)return!0;const r=rs(Mr(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},d2=5*6e4,jf=new Set,Pr=t=>{const e=i.useRef(t);return e.current=t,i.useCallback((...n)=>e.current(...n),[])},Nf=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=bt(),[c,l]=i.useState(!1),[d,f]=i.useState(""),m=i.useRef(null),u=i.useRef(null),p=i.useRef(new Set),[x,y]=i.useState(null),[b,g]=i.useState(""),[h,C]=i.useState(null),[w,S]=i.useState(new Set),N=i.useMemo(()=>Ui(),[]),[k,j]=i.useState(new Set),[D,O]=i.useState(new Map),[v,M]=i.useState(new Map),I=Ee(X=>X.isNewWorktreeDialogOpen),E=Ee(X=>X.setNewWorktreeDialogOpen),[B,P]=i.useState(!1),[W,_]=i.useState(!1),[V,R]=i.useState(null),[ne,ie]=i.useState(null),[J,U]=i.useState(""),[ee,ae]=i.useState(null),[de,ye]=i.useState(null),[se,we]=i.useState(null),fe=ul(X=>X.ids),Me=ul(X=>X.setIds),$=ul(X=>X.toggle),[K,q]=i.useState(()=>{try{const X=Ui().getItem(vf);if(!X)return new Set;const ot=JSON.parse(X);return new Set(Array.isArray(ot)?ot.filter(st=>typeof st=="string"):[])}catch{return new Set}}),[me,je]=i.useState(()=>{try{const X=Ui().getItem(wf);if(!X)return new Map;const ot=JSON.parse(X),st=new Map;return Object.entries(ot).forEach(([gt,Ot])=>{Array.isArray(Ot)&&st.set(gt,Ot.filter(Bs=>typeof Bs=="string"))}),st}catch{return new Map}}),[Oe,Be]=i.useState(()=>{try{const X=Ui().getItem(Sf);if(!X)return new Map;const ot=JSON.parse(X),st=new Map;return Object.entries(ot).forEach(([gt,Ot])=>{typeof Ot=="string"&&Ot.length>0&&st.set(gt,Ot)}),st}catch{return new Map}}),[Fe,ue]=i.useState(new Map),Re=i.useRef(new Map),xe=i.useRef(0),oe=qs(X=>X.homeDirectory),ve=qs(X=>X.currentDirectory),Se=qs(X=>X.setDirectory),le=ks(X=>X.projects),T=ks(X=>X.activeProjectId),L=ks(X=>X.removeProject),he=ks(X=>X.setActiveProjectIdOnly),ge=ks(X=>X.updateProjectMeta),z=ks(X=>X.reorderProjects),pe=Ee(X=>X.setActiveMainTab),Ae=Ee(X=>X.openContextPanelTab),G=Ee(X=>X.setSettingsDialogOpen),ke=Ee(X=>X.toggleHelpDialog),Le=Ee(X=>X.setAboutDialogOpen),Te=Ee(X=>X.setSessionSwitcherOpen),Z=Ee(X=>X.setScheduledTasksDialogOpen),F=Ee(X=>X.openMultiRunLauncher),re=Ee(X=>X.notifyOnSubtasks),te=Ee(X=>X.showDeletionDialog),Ve=Ee(X=>X.setShowDeletionDialog),Ye=Ya(d,120),Ke=i.useMemo(()=>Ye.trim().toLowerCase(),[Ye]),Je=Ke.length>0,nt=$n(X=>X.collapsedFolderIds),xt=$n(X=>X.foldersMap),jt=$n(X=>X.getFoldersForScope),Mt=$n(X=>X.createFolder),Et=$n(X=>X.renameFolder),Ut=$n(X=>X.deleteFolder),zt=$n(X=>X.addSessionToFolder),Ht=$n(X=>X.addSessionsToFolder),_t=$n(X=>X.removeSessionFromFolder),Gt=$n(X=>X.removeSessionsFromFolders),Ce=$n(X=>X.toggleFolderCollapse),Qe=$n(X=>X.cleanupSessions),et=$n(X=>X.getSessionFolderId);Uj({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchContainerRef:m});const yt=cm(),We=Ec(),at=bc(),qe=i.useMemo(()=>Yr(),[]),lt=Sr(X=>X.hasLoaded),Dt=Sr(X=>X.activeSessions),us=Sr(X=>X.archivedSessions),Lt=ft(X=>X.currentSessionId),es=ft(X=>!!X.newSessionDraft?.open),os=ft(X=>X.setCurrentSession),Qt=ft(X=>X.updateSessionTitle),Ft=ft(X=>X.shareSession),Xt=ft(X=>X.unshareSession),as=ft(X=>X.worktreeMetadata),$t=ft(X=>X.availableWorktreesByProject),bs=ft(X=>X.openNewSessionDraft),Cs=i.useCallback(X=>{bs(X),qe&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[qe,bs]),Tt=So($l(X=>({checkForUpdates:X.checkForUpdates,available:X.available,runtimeType:X.runtimeType,info:X.info,downloading:X.downloading,downloaded:X.downloaded,progress:X.progress,error:X.error,downloadUpdate:X.downloadUpdate,restartToUpdate:X.restartToUpdate}))),Bt=i.useMemo(()=>l2(le,$t,{includeWorktrees:!qe}),[$t,qe,le]),vt=i.useMemo(()=>{const X=new Map(at.map(gt=>[gt.id,gt])),ot=Dt.map(gt=>{const Ot=X.get(gt.id);return Ot?Yg(Ot,gt):gt}),st=new Set(ot.map(gt=>gt.id));return at.forEach(gt=>{st.has(gt.id)||ot.push(gt)}),ot.filter(gt=>c2(gt,Bt,{allowUnknownDirectory:!qe,allowEmptyDirectorySet:!qe}))},[Dt,qe,Bt,at]),vs=i.useMemo(()=>at.map(X=>{const ot=rs(X.directory??null)??"";return`${X.id}:${X.title??""}:${X.time?.archived?1:0}:${ot}`}).join("|"),[at]),hs=i.useRef(at);i.useEffect(()=>{hs.current=at},[vs,at]);const He=i.useMemo(()=>new Map(at.map(X=>[X.id,X])),[at]),it=i.useMemo(()=>le.map(X=>`${X.id}:${rs(X.path)??""}`).join("|"),[le]),It=i.useRef(!1);i.useEffect(()=>{It.current||(It.current=!0,ka(hs.current))},[]);const Rt=i.useRef("");i.useEffect(()=>{let X=!1;const ot=async()=>{const st=ks.getState().projects;if(st.length===0)return;const gt=new Map,Ot=[],Bs=3;let on=0;const yn=Array.from({length:Bs},async()=>{for(;;){const Nn=on;if(on+=1,Nn>=st.length)return;const kn=st[Nn],_n=rs(kn.path);if(_n)try{if(!(wn.getState().directories.get(_n)?.isGitRepo??await pm(_n)))continue;const ho=await Jg({id:kn.id,path:_n});if(X||ho.length===0)continue;gt.set(_n,ho),Ot.push(...ho)}catch{}}});await Promise.all(yn),!X&&ft.setState({availableWorktrees:Ot,availableWorktreesByProject:gt})};if(Rt.current!==it)return Rt.current=it,ot(),()=>{X=!0}},[it]),i.useEffect(()=>{let X=null;const ot=xh(st=>{st.type==="scheduled-task-ran"&&(X&&clearTimeout(X),X=setTimeout(()=>{ka(hs.current)},500))});return()=>{X&&clearTimeout(X),ot()}},[]);const Pt=i.useMemo(()=>cr(),[]),{isTablet:ps}=Or(),ls=t||ps,{buildGroupSearchText:ns,filterSessionNodesForSearch:Wt,buildGroupedSessions:ln}=Wj({homeDirectory:oe,worktreeMetadata:as,pinnedSessionIds:fe,gitBranches:yt,isVSCode:qe}),{scheduleCollapsedProjectsPersist:fs}=Jj({isVSCode:qe,hasLoadedGlobalSessions:lt,safeStorage:N,keys:{sessionExpanded:Ml,sessionExpandedLegacy:o2,projectCollapse:na,sessionPinned:a2,groupOrder:wf,projectActiveSession:Sf,groupCollapse:vf},sessions:vt,setPinnedSessionIds:Me,groupOrderByProject:me,activeSessionByProject:Oe,collapsedGroups:K,setExpandedParents:S,setCollapsedProjects:j}),Fs=i.useMemo(()=>[...vt].sort((X,ot)=>qi(X,ot,fe)),[vt,fe]),Ws=i.useMemo(()=>Fs.map(X=>`${X.id}:${X.time?.updated??0}`).join("|"),[Fs]),sn=i.useRef(null),An=i.useMemo(()=>{const X=sn.current;if(X&&X.signature===Ws)return X.map;const ot=new Map(Fs.map((st,gt)=>[st.id,gt]));return sn.current={signature:Ws,map:ot},ot},[Ws,Fs]),vn=i.useMemo(()=>{const X=new Map;return Fs.forEach(ot=>{const st=ot.parentID;if(!st)return;const gt=X.get(st)??[];gt.push(ot),X.set(st,gt)}),X.forEach(ot=>ot.sort((st,gt)=>qi(st,gt,fe))),X},[Fs,fe]),be=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")})]}),Ze=i.useMemo(()=>le.find(X=>X.id===h)??null,[le,h]),dt=i.useCallback(X=>{h&&ge(h,{label:X.label,icon:X.icon,color:X.color,iconBackground:X.iconBackground,defaultModel:X.defaultModel??null})},[h,ge]),wt=i.useCallback(()=>{E(!0)},[E]),Vt=i.useCallback(()=>{const X=So.getState();if(X.available&&X.info){P(!0);return}Tt.checkForUpdates().then(()=>{const{available:ot,error:st}=So.getState();if(st){ce.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:st});return}if(!ot){ce.success(a("sessions.sidebar.updateCheck.latestVersion"));return}P(!0)})},[a,Tt]),ht=i.useCallback(()=>{_(!0)},[]);i.useEffect(()=>{if(typeof window>"u")return;try{if(window.localStorage.getItem(yf)==="true")return;window.localStorage.setItem(yf,"true")}catch{}const X=window.setTimeout(()=>{ce.info(a("shareOpinion.toast.title"),{description:a("shareOpinion.toast.description"),action:{label:a("shareOpinion.actions.shareOpinion"),onClick:()=>_(!0)},duration:12e3})},1e3);return()=>window.clearTimeout(X)},[a]);const cs=i.useCallback(()=>{t&&Te(!1),G(!0)},[t,Te,G]),ds=Tt.available&&(Tt.runtimeType==="desktop"||Tt.runtimeType==="web"),Ss=ft(X=>X.deleteSession),gs=ft(X=>X.deleteSessions),Ts=ft(X=>X.archiveSession),Fn=ft(X=>X.archiveSessions),{copiedSessionId:_s,handleSessionSelect:hn,handleSessionDoubleClick:On,handleSaveEdit:Zn,handleCancelEdit:cn,handleShareSession:Ue,handleCopyShareUrl:Jt,handleUnshareSession:As,handleDeleteSession:Ps,confirmDeleteSession:$s}=Hj({activeProjectId:T,currentDirectory:ve,currentSessionId:Lt,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:l,setActiveProjectIdOnly:he,setDirectory:Se,setActiveMainTab:pe,setSessionSwitcherOpen:Te,setCurrentSession:os,updateSessionTitle:Qt,shareSession:Ft,unshareSession:Xt,deleteSession:Ss,deleteSessions:gs,archiveSession:Ts,archiveSessions:Fn,childrenMap:vn,showDeletionDialog:te,setDeleteSessionConfirm:ae,deleteSessionConfirm:ee,setEditingId:y,setEditTitle:g,editingId:x,editTitle:b}),Qs=i.useCallback(()=>{if(!de)return;const{scopeKey:X,folderId:ot}=de;ye(null),Ut(X,ot)},[de,Ut]),Us=i.useCallback(()=>{Er.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!Lt)return;const ot=vt.find(gt=>gt.id===Lt)?.parentID;if(!ot)return;const st=[`project:active:${ot}`,`project:archived:${ot}`,`recent:active:${ot}`,`recent:archived:${ot}`];S(gt=>{if(st.every(Bs=>gt.has(Bs)))return gt;const Ot=new Set(gt);st.forEach(Bs=>Ot.add(Bs));try{N.setItem(Ml,JSON.stringify(Array.from(Ot)))}catch{}return Ot})},[Lt,vt,N]);const Os=i.useCallback(X=>{S(ot=>{const st=new Set(ot);st.has(X)?st.delete(X):st.add(X);try{N.setItem(Ml,JSON.stringify(Array.from(st)))}catch{}return st})},[N]),Ln=i.useCallback((X,ot)=>{if(!X)return null;ot&&nt.has(ot)&&Ce(ot);const st=Mt(X,a("sessions.sidebar.folder.newFolderName"),ot);return ie(st.id),U(st.name),st},[nt,Ce,Mt,a]),fr=Pr(hn),Kn=Pr(On),ms=Pr(Zn),Is=Pr(cn),jr=Pr(Ue),Bn=Pr(Jt),pn=Pr(As),Nr=Pr(Ps),kr=Pr(Ln),Lr=i.useCallback((X,ot)=>{M(st=>{const gt=new Map(st);return gt.set(X,ot+7),gt})},[]),Cr=i.useCallback(X=>{M(ot=>{if(!ot.has(X))return ot;const st=new Map(ot);return st.delete(X),st})},[]),nr=i.useCallback(X=>{M(ot=>{let st=!1;const gt=new Map(ot),Ot=`${X}:`;for(const Bs of gt.keys())Bs.startsWith(Ot)&&(gt.delete(Bs),st=!0);return st?gt:ot})},[]),ws=i.useCallback(()=>{xe.current=Date.now()+150,M(new Map),j(()=>{const X=new Set(le.map(ot=>ot.id));try{N.setItem(na,JSON.stringify(Array.from(X)))}catch{}return qe||fs(X),X})},[le,qe,N,fs]),dn=i.useCallback(()=>{xe.current=Date.now()+150,M(new Map),j(()=>{const X=new Set;try{N.setItem(na,JSON.stringify([]))}catch{}return qe||fs(X),X})},[qe,N,fs]),rr=i.useCallback(X=>{xe.current=Date.now()+150,nr(X),j(ot=>{const st=new Set(ot);st.has(X)?st.delete(X):st.add(X);try{N.setItem(na,JSON.stringify(Array.from(st)))}catch{}return qe||fs(st),st})},[qe,nr,N,fs]),Y=i.useMemo(()=>le.map(X=>({...X,normalizedPath:rs(X.path)})).filter(X=>!!X.normalizedPath),[le]),tt=i.useMemo(()=>Y.map(X=>X.normalizedPath),[Y]),pt=i.useMemo(()=>{const X=new Set;return Y.forEach(ot=>{if(ot.normalizedPath&&X.add(ot.normalizedPath),qe)return;($t.get(ot.normalizedPath)??[]).forEach(gt=>{const Ot=rs(gt.path);Ot&&X.add(Ot)})}),[...X].sort()},[$t,qe,Y]),St=i.useRef(null);i.useEffect(()=>{const X=new Set(pt),ot=St.current;if(St.current=X,!ot){qe&&pt.length>0&&$d(pt,hs.current);return}const st=pt.filter(gt=>!ot.has(gt));st.length!==0&&$d(st,hs.current)},[qe,pt]);const{github:Kt}=Xn(),ts=Mi(X=>X.status),is=Mi(X=>X.hasChecked),Ls=Qg(tt),Gs=sr(X=>X.ensureEntry),qn=sr(X=>X.setParams),Vn=sr(X=>X.refreshTargets);Xj({normalizedProjects:Y,gitRepoStatus:Ls,setProjectRepoStatus:O,setProjectRootBranches:ue});const Qr=ft(X=>X.isLoading);rN({isSessionsLoading:Qr,hasLoadedGlobalSessions:lt,sessions:vt,archivedSessions:us,normalizedProjects:Y,isVSCode:qe,availableWorktreesByProject:$t,cleanupSessions:Qe});const{getSessionsForProject:gn,getArchivedSessionsForProject:Jr}=Zj({isVSCode:qe,sessions:vt,archivedSessions:us,availableWorktreesByProject:$t,normalizedProjects:Y});Fj({normalizedProjects:Y,sessions:vt,archivedSessions:us,availableWorktreesByProject:$t,isVSCode:qe,isSessionsLoading:Qr,foldersMap:xt,createFolder:Mt,addSessionToFolder:zt,cleanupSessions:Qe});const xn=i.useRef(!1);T&&D.has(T)&&(xn.current=!!D.get(T));const{projectSections:nn,groupSearchDataByGroup:un,sectionsForRender:Sn,searchMatchCount:jn}=Bj({normalizedProjects:Y,getSessionsForProject:gn,getArchivedSessionsForProject:Jr,availableWorktreesByProject:$t,projectRepoStatus:D,projectRootBranches:Fe,lastRepoStatus:xn.current,buildGroupedSessions:ln,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:Ke,filterSessionNodesForSearch:Wt,buildGroupSearchText:ns,foldersMap:xt}),mr=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")})]});_j({projectSections:nn,activeProjectId:T,activeSessionByProject:Oe,setActiveSessionByProject:Be,currentSessionId:Lt,handleSessionSelect:hn,newSessionDraftOpen:es,mobileVariant:t,openNewSessionDraft:bs,setActiveMainTab:pe,setSessionSwitcherOpen:Te});const{getOrderedGroups:ir}=$j(me),Ar=i.useRef(!1);i.useEffect(()=>{if(Ar.current||nn.length===0)return;const X=nn.flatMap(ot=>ot.groups.filter(st=>st.isArchivedBucket).map(st=>`${ot.project.id}:${st.id}`));X.length>0&&q(ot=>new Set([...ot,...X])),Ar.current=!0},[nn]);const gi=i.useMemo(()=>{const X=new Map,ot=new Map;return nn.forEach(st=>{const gt=Pm(st.project.label?.trim()||lo(st.project.normalizedPath,oe)||st.project.normalizedPath);st.groups.forEach(Ot=>{const Bs=Ot.branch&&Ot.branch!=="HEAD"&&Ot.branch!==gt?Ot.branch:null,on={projectLabel:gt,branchLabel:Bs},yn=Nn=>{Nn.forEach(kn=>{const _n=st.project.normalizedPath.length,ei=ot.get(kn.session.id)??-1;_n<ei||(X.set(kn.session.id,{node:kn,projectId:st.project.id,groupDirectory:Ot.directory,secondaryMeta:on}),ot.set(kn.session.id,_n),kn.children.length>0&&yn(kn.children))})};yn(Ot.sessions)})}),X},[nn,oe]),or=Ir(X=>X.showRecentSection),xi=Ir(X=>X.showArchivedSessions),Br=i.useMemo(()=>!or||qe?[]:i2(vt).sort((X,ot)=>qi(X,ot,fe)),[qe,fe,vt,or]),Xr=i.useMemo(()=>{if(qe||!or)return[];const X=Br,ot=gt=>{const Ot=gi.get(gt.id),Bs=rs(gt.directory??null),on=Ot?.node??{session:gt,children:[],worktree:null},Nn=(Je?Wt([on],Ke):[on])[0];if(!Nn)return null;const kn=Ot?.secondaryMeta?{projectLabel:Ot.secondaryMeta.projectLabel,branchLabel:qe?null:Ot.secondaryMeta.branchLabel}:null;return{node:Nn,projectId:Ot?.projectId??null,groupDirectory:Ot?.groupDirectory??Bs,secondaryMeta:kn}},st=X.map(ot).filter(gt=>gt!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:st}]},[Br,Wt,Je,qe,Ke,gi,or,a]),Dn=i.useMemo(()=>Xr.some(X=>X.items.length>0),[Xr]),ar=i.useMemo(()=>new Set(Br.map(X=>X.id)),[Br]),Js=i.useMemo(()=>[...ar],[ar]);XS({currentSessionId:Lt,sortedSessions:Fs,recentSessionIds:Js,ensureSessionRenderable:We.ensureSessionRenderable});const Hs=i.useMemo(()=>xi?Sn:Sn.map(X=>({...X,groups:X.groups.filter(ot=>!ot.isArchivedBucket)})),[Sn,xi]),Vr=i.useMemo(()=>{const X=new Set;return Hs.forEach(ot=>{ot.groups.forEach(st=>{const gt=rs(st.directory??null),Ot=st.branch?.trim()||yt.get(gt||"")?.trim();!gt||!Ot||X.add(Co(gt,Ot))})}),[...X]},[yt,Hs]),Oi=Ow(Vr);i.useEffect(()=>{if(!is||!ts?.connected||!Kt)return;const X=[],ot=Date.now();if(Hs.forEach(gt=>{k.has(gt.project.id)||gt.groups.forEach(Ot=>{const Bs=rs(Ot.directory??null),on=Ot.branch?.trim()||yt.get(Bs||"")?.trim();if(!Bs||!on)return;const yn=Co(Bs,on),Nn=sr.getState().entries[yn],kn=!!Nn?.status?.pr,_n=`${Bs}::${on}`,ei=Math.max(Nn?.lastRefreshAt??0,Nn?.lastDiscoveryPollAt??0),vi=!!(Nn?.isInitialStatusResolved&&!kn&&(!p.current.has(_n)||ot-ei>=d2));(!Nn||!Nn.isInitialStatusResolved||vi)&&(vi&&p.current.add(_n),X.push({directory:Bs,branch:on}))})}),X.length===0)return;const st=new Map;X.forEach(gt=>{const Ot=Co(gt.directory,gt.branch,gt.remoteName??null);st.has(Ot)||st.set(Ot,gt)}),st.forEach((gt,Ot)=>{Gs(Ot),qn(Ot,{directory:gt.directory,branch:gt.branch,remoteName:gt.remoteName??null,canShow:!0,github:Kt,githubAuthChecked:is,githubConnected:ts.connected})}),Vn([...st.values()],{silent:!0,markInitialResolved:!0})},[k,Gs,Kt,is,ts?.connected,yt,Vn,Hs,qn]);const bi=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",bn="h-4.5 w-4.5",pr=lN({isDesktopShellRuntime:Pt,projectSections:nn,projectHeaderSentinelRefs:Re}),_r=Pr((X,ot=0,st,gt,Ot=!1,Bs,on="project",yn)=>s.jsx(qk,{node:X,depth:ot,groupDirectory:st,projectId:gt,archivedBucket:Ot,currentSessionId:Lt,pinnedSessionIds:fe,expandedParents:w,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:Ke,notifyOnSubtasks:re,editingId:x,setEditingId:y,editTitle:b,setEditTitle:g,handleSaveEdit:ms,handleCancelEdit:Is,toggleParent:Os,handleSessionSelect:fr,handleSessionDoubleClick:Kn,togglePinnedSession:$,handleShareSession:jr,copiedSessionId:_s,handleCopyShareUrl:Bn,handleUnshareSession:pn,openSidebarMenuKey:V,setOpenSidebarMenuKey:R,renamingFolderId:ne,getFoldersForScope:jt,getSessionFolderId:et,removeSessionFromFolder:_t,addSessionToFolder:zt,createFolderAndStartRename:kr,openContextPanelTab:Ae,handleDeleteSession:Nr,mobileVariant:t,alwaysShowActions:ls,renderSessionNode:_r,secondaryMeta:Bs,renderContext:on,subtreeContainsActive:yn?.subtreeContainsActive??jf,subtreeContainsEditing:yn?.subtreeContainsEditing??jf,menuOpenSessionId:yn?.menuOpenSessionId??null,nodeStructureKey:yn?.nodeStructureKey??"",childRenderExtrasFor:yn?.childRenderExtrasFor,liveSessionById:He})),yi=i.useCallback(X=>{Cr(X),q(ot=>{const st=new Set(ot);return st.has(X)?st.delete(X):st.add(X),st})},[Cr]),$r=i.useMemo(()=>{const X=new Map;for(const[ot,st]of Oi)X.set(ot,{visualState:st.visualState,number:st.number,url:st.url,state:st.prState,draft:st.draft,title:st.title,base:st.base,head:st.head,checks:st.checks,canMerge:st.canMerge,mergeableState:st.mergeableState,repo:st.repo});return X},[Oi]),Li=i.useCallback((X,ot,st,gt,Ot,Bs,on)=>s.jsx(BN,{group:X,groupKey:ot,projectId:st,hideGroupLabel:gt,compactBodyPadding:Bs,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:Ke,groupSearchDataByGroup:un,visibleSessionCount:v.get(ot),collapsedGroups:K,hideDirectoryControls:r,collapsedFolderIds:nt,toggleFolderCollapse:Ce,renameFolder:Et,deleteFolder:Ut,showDeletionDialog:te,setDeleteFolderConfirm:ye,renderSessionNode:_r,projectRepoStatus:D,lastRepoStatus:xn.current,showMoreGroupSessions:Lr,resetGroupSessionLimit:Cr,mobileVariant:t,alwaysShowActions:ls,activeProjectId:T,setActiveProjectIdOnly:he,setActiveMainTab:pe,setSessionSwitcherOpen:Te,openNewSessionDraft:Cs,addSessionToFolder:zt,createFolderAndStartRename:kr,renamingFolderId:ne,renameFolderDraft:J,setRenameFolderDraft:U,setRenamingFolderId:ie,pinnedSessionIds:fe,expandedParents:w,sessionOrderIndex:An,currentSessionId:Lt,editingId:x,editTitle:b,openSidebarMenuKey:V,liveSessionById:He,prVisualStateByDirectoryBranch:$r,onToggleCollapsedGroup:yi,dragHandleProps:Ot,scrollContainerRef:on}),[Je,Ke,un,v,K,r,nt,Ce,Et,Ut,te,_r,D,Lr,Cr,t,ls,T,he,pe,Te,Cs,zt,kr,ne,J,fe,w,An,Lt,x,b,V,He,$r,yi]),rn=!qe&&or&&!Je?s.jsx(KN,{sections:Xr,renderSessionNode:_r,currentSessionId:Lt,editingId:x,openSidebarMenuKey:V,variant:"section"}):null,wi=!!(ne||x||h),{selectionModeEnabled:Bi,hasSelection:mo,selectedIdsSize:Q,bulkScopeIsArchived:Ne,derivedSelectionScope:Pe,bulkScopeFolders:_e,bulkCanRemoveFromFolder:ut,handleToggleSelectionMode:Nt,handleExitSelectionMode:qt,handleBulkMoveToFolder:Yt,handleBulkCreateFolderAndMove:ys,handleBulkRemoveFromFolder:gr,handleBulkDelete:Dr,confirmBulkDelete:Tr}=e2({isInlineEditing:wi,showDeletionDialog:te,foldersMap:xt,addSessionsToFolder:Ht,removeSessionsFromFolders:Gt,createFolderAndStartRename:Ln,archiveSessions:Fn,deleteSessions:gs,setBulkDeleteConfirm:we}),Xa=i.useCallback(()=>{pe("chat"),t&&Te(!1),F()},[t,F,pe,Te]),Za=i.useCallback(()=>{pe("chat"),t&&Te(!1),bs()},[t,bs,pe,Te]);return s.jsxs("div",{ref:m,className:Ie("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(VN,{hideDirectoryControls:r,showRecentControls:!qe,handleOpenDirectoryDialog:Us,openNewSessionDraft:Za,canOpenMultiRun:le.length>0,openMultiRunLauncher:Xa,headerActionIconClass:bn,headerActionButtonClass:bi,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:Je,searchMatchCount:jn,collapseAllProjects:ws,expandAllProjects:dn,openScheduledTasksDialog:()=>Z(!0),selectionModeEnabled:Bi,onToggleSelectionMode:Nt}),s.jsx(tk,{topContent:rn,hasSharedSessions:Dn,sectionsForRender:Hs,projectSections:nn,activeProjectId:T,showOnlyMainWorkspace:o,hasSessionSearchQuery:Je,emptyState:be,searchEmptyState:mr,renderGroupSessions:Li,homeDirectory:oe,collapsedProjects:k,hideDirectoryControls:r,projectRepoStatus:D,isDesktopShellRuntime:Pt,stuckProjectHeaders:pr,mobileVariant:t,alwaysShowActions:ls,toggleProject:rr,setActiveProjectIdOnly:he,setActiveMainTab:pe,setSessionSwitcherOpen:Te,openNewSessionDraft:Cs,openNewWorktreeDialog:wt,openProjectEditDialog:C,removeProject:L,projectHeaderSentinelRefs:Re,reorderProjects:z,getOrderedGroups:ir,setGroupOrderByProject:je,openSidebarMenuKey:V,setOpenSidebarMenuKey:R,isInlineEditing:wi}),Bi&&mo?s.jsx(Zk,{selectedCount:Q,scopeKey:Pe,scopeFolders:_e,archivedBucket:Ne,onMoveToFolder:Yt,onCreateFolderAndMove:ys,onRemoveFromFolder:gr,canRemoveFromFolder:ut,onDelete:Dr,onDone:qt}):null,s.jsx(qN,{onOpenSettings:cs,onOpenShortcuts:ke,onOpenAbout:()=>Le(!0),onOpenUpdate:Vt,onOpenShareOpinion:ht,showRuntimeButtons:!qe,showUpdateButton:ds}),s.jsx(uN,{open:W,onOpenChange:_}),s.jsx(jm,{open:B,onOpenChange:P,info:Tt.info,downloading:Tt.downloading,downloaded:Tt.downloaded,progress:Tt.progress,error:Tt.error,onDownload:Tt.downloadUpdate,onRestart:Tt.restartToUpdate,runtimeType:Tt.runtimeType}),s.jsx(cN,{open:!!Ze,onOpenChange:X=>{X||C(null)},project:Ze,onSave:dt}),s.jsx(Jx,{open:I,onOpenChange:E,onWorktreeCreated:(X,ot)=>{if(pe("chat"),t&&Te(!1),ot?.sessionId){os(ot.sessionId,X);return}bs({directoryOverride:X,preserveDirectoryOverride:!0})}}),s.jsx(Ej,{}),s.jsx(Qk,{value:ee,setValue:ae,showDeletionDialog:te,setShowDeletionDialog:Ve,onConfirm:$s}),s.jsx(Xk,{value:de,setValue:ye,onConfirm:Qs}),s.jsx(Jk,{value:se,setValue:we,showDeletionDialog:te,setShowDeletionDialog:Ve,onConfirm:Tr})]})},ki=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,yr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},u2=()=>{const{t}=bt(),[e,n]=i.useState(!1),[r,o]=i.useState(!1),[a,c]=i.useState(null),[l,d]=i.useState([]),[f,m]=i.useState(!1),[u,p]=i.useState(!1),[x,y]=i.useState(!1),[b,g]=i.useState(!1),[h,C]=i.useState(new Set),w=ft(oe=>oe.getWorktreeMetadata),S=ft(oe=>oe.newSessionDraft),N=ft(oe=>oe.setNewSessionDraftTarget),k=ft(oe=>oe.setDraftBootstrapPendingDirectory),j=Xg,D=tx,O=ft(oe=>oe.deleteSessions),v=ft(oe=>oe.archiveSessions),M=Ee(oe=>oe.showDeletionDialog),I=Ee(oe=>oe.setShowDeletionDialog),E=qs(oe=>oe.currentDirectory),B=qs(oe=>oe.homeDirectory),P=qs(oe=>oe.isHomeReady),W=ks(oe=>oe.projects),_=ks(oe=>oe.activeProjectId),{isMobile:V,isTablet:R,hasTouchInput:ne}=Or(),ie=V||R||ne,J=i.useMemo(()=>{const ve=(_?W.find(Se=>Se.id===_)??null:null)?.path??E;return yr(ve)},[_,E,W]),U=i.useCallback(oe=>{const Se=yr(oe.projectDirectory)||J;return{id:(W.find(T=>yr(T.path)===Se)??null)?.id??`path:${Se}`,path:Se}},[J,W]),ee=b&&h.size>0,ae=i.useMemo(()=>{const oe=a?.worktree;return oe&&typeof oe.branch=="string"&&oe.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:ve})=>typeof ve.branch=="string"&&ve.branch.trim().length>0)},[a?.worktree,l]),de=a?.mode==="worktree",ye=de,se=x||!de||!ae,we=x||!de;i.useEffect(()=>{r||!P||W.length>0||(o(!0),n(!0))},[r,P,W.length]);const fe=i.useCallback(oe=>{c({sessions:oe.sessions,dateLabel:oe.dateLabel,mode:oe.mode??"session",worktree:oe.worktree??null})},[]),Me=i.useCallback(()=>{c(null),d([]),m(!1),p(!1),y(!1),g(!1),C(new Set)},[]),$=i.useCallback(async oe=>{if(oe.sessions.length===0)return;if(oe.sessions.length===1){const T=oe.sessions[0];await j(T.id)?ce.success(t("sessions.sidebar.session.delete.success")):ce.error(t("sessions.sidebar.session.delete.error"));return}const ve=oe.sessions.map(T=>T.id),{deletedIds:Se,failedIds:le}=await O(ve);if(Se.length>0){const T=le.length>0?le.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:le.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:le.length}):oe.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:oe.dateLabel}):void 0;ce.success(Se.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:Se.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:Se.length}),{description:ki(T)})}le.length>0&&ce.error(le.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:le.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:le.length}),{description:ki(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[j,O,t]);i.useEffect(()=>Er.onDeleteRequest(oe=>{if(!M&&(oe.mode??"session")==="session"){$(oe);return}fe(oe)}),[fe,M,$]),i.useEffect(()=>Er.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1),p(!1),g(!1),C(new Set);return}const oe=a.sessions.map(le=>{const T=w(le.id);return T?{session:le,metadata:T}:null}).filter(le=>!!le);d(oe),m(!1),g(!1),C(new Set);const ve=new Map;if(a.worktree?.path&&ve.set(yr(a.worktree.path),a.worktree),oe.forEach(({metadata:le})=>{le.path&&ve.set(yr(le.path),le)}),ve.size===0){g(!0);return}let Se=!1;return(async()=>{const le=new Map,T=new Set;await Promise.all(Array.from(ve.entries()).map(async([L,he])=>{try{const ge=await Zg(he.path);le.set(L,ge),ge?.isDirty&&T.add(L)}catch{he.status&&(le.set(L,he.status),he.status.isDirty&&T.add(L))}})).catch(L=>{console.warn("Failed to inspect worktree status before deletion:",L)}),!Se&&(C(T),g(!0),c(L=>{if(!L?.worktree?.path)return L;const he=yr(L.worktree.path),ge=le.get(he);if(!ge)return L;const z=L.worktree.status;return z?.isDirty===ge.isDirty&&z?.ahead===ge.ahead&&z?.behind===ge.behind&&z?.upstream===ge.upstream?L:{...L,worktree:{...L.worktree,status:ge}}}),d(L=>L.map(he=>{const ge=yr(he.metadata.path),z=le.get(ge);return z?{session:he.session,metadata:{...he.metadata,status:z}}:he})))})(),()=>{Se=!0}},[a,w]),i.useEffect(()=>{ae||m(!1)},[ae]);const K=i.useCallback(async(oe,ve)=>{const Se=f&&ae,le=U(oe),T=yr(oe.path),L=yr(le.path);try{await ex(le,oe,{deleteRemoteBranch:Se,deleteLocalBranch:ve});const he=yr(S?.directoryOverride);return S?.open&&T&&he===T&&L&&(k(null),N({projectId:le.id,directoryOverride:L},{force:!0})),yr(E)===T&&L&&qs.getState().setDirectory(L,{showOverlay:!1}),!0}catch(he){return ce.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:ki(he instanceof Error?he.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[ae,E,f,U,S?.directoryOverride,S?.open,k,N,t]),q=i.useCallback((oe,ve)=>{const Se=f&&ae;(async()=>{if(!await K(oe,ve))return;const T=t(Se?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");ce.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:ki(T)})})()},[ae,f,K,t]),me=i.useCallback(async()=>{if(a){y(!0);try{const oe=ye,ve=oe&&f,Se=oe&&u;if(a.sessions.length===0&&de&&a.worktree){q(a.worktree,Se),Me();return}if(a.sessions.length===1){const le=a.sessions[0];if(!(de?await D(le.id):await j(le.id,{archiveWorktree:!1,deleteRemoteBranch:ve,deleteLocalBranch:Se}))){ce.error(t(de?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),y(!1);return}const L=!de&&oe?t(ve?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;ce.success(t(de?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:ki(L),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const le=a.sessions.map(he=>he.id);let T=[],L=[];if(de){const he=await v(le);T=he.archivedIds,L=he.failedIds}else{const he=await O(le);T=he.deletedIds,L=he.failedIds}if(de&&a.worktree&&L.length===0&&q(a.worktree,Se),T.length>0){const he=!de&&oe?t(ve?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,z=[L.length>0?de?L.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:L.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:L.length}):L.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:L.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:L.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,he].filter(Boolean).join(" ");ce.success(de?T.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:T.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:T.length}):T.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:T.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:T.length}),{description:ki(z||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if(L.length>0&&(ce.error(de?L.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:L.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:L.length}):L.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:L.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:L.length}),{description:ki(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),T.length===0)){y(!1);return}}de&&a.sessions.length===1&&a.worktree&&q(a.worktree,Se),Me()}finally{y(!1)}}},[a,f,u,j,O,D,v,Me,ye,de,q,t]),je=a?.worktree??l[0]?.metadata??null,Oe=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}):"",Be=a?s.jsxs("div",{className:Ie(de?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:Ie(de?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[de&&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:Ie(de?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(oe=>s.jsxs("li",{className:Ie(de?"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:Ie(!de&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:oe.title||t("sessions.sidebar.session.untitled")})]},oe.id)),a.sessions.length>5&&s.jsx("li",{className:Ie(de?"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})})]})]}),de?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(A,{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")}),je?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:je.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:je?Ca(je.path,B):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),ee&&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,Fe=de?ae?s.jsxs("button",{type:"button",onClick:()=>{se||m(oe=>!oe)},disabled:se,className:Ie("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",se?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[f?s.jsx(A,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(A,{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,ue=de?s.jsxs("button",{type:"button",onClick:()=>{we||p(oe=>!oe)},disabled:we,className:Ie("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",we?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(A,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(A,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Re=de?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:[ue,Fe]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{variant:"ghost",onClick:Me,disabled:x,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{variant:"destructive",onClick:me,disabled:x,children:t(x?"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:()=>I(!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(A,{name:"checkbox-blank",className:"size-4"}):s.jsx(A,{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:Me,disabled:x,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{variant:"destructive",onClick:me,disabled:x,children:x?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),xe=de?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:[ie?s.jsx(Ha,{open:!!a,onClose:()=>{x||Me()},title:xe,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Re}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[Oe&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Oe}),Be]})}):s.jsx(Ms,{open:!!a,onOpenChange:oe=>{if(!oe){if(x)return;Me()}},children:s.jsxs(Es,{className:Ie(de?"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(Ys,{children:[s.jsxs(zs,{className:Ie(de&&"flex items-center gap-2"),children:[de&&s.jsx(A,{name:"delete-bin",className:"h-5 w-5"}),xe]}),Oe&&s.jsx(an,{children:Oe})]}),s.jsx("div",{className:Ie(de&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:Be}),s.jsx(ur,{className:"mt-2 gap-2 pt-1 pb-1",children:Re})]})}),s.jsx(Xx,{open:e,onOpenChange:n})]})},cc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),f2=(t,e)=>{const n=cc(t),r=cc(e);return`${n}-${r}`.substring(0,60)},kf=(t,e)=>`${t}/${e}`,m2=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},Cf=(t,e)=>{const n=m2(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};cx(t.id,n),ft.getState().markSessionAsOpenChamberCreated(t.id),Sr.getState().upsertSession(o);try{Aa().ensureChild(n,{bootstrap:!1}).setState(c=>{const l=c.session.findIndex(f=>f.id===t.id);if(l>=0&&c.session[l]===o)return c;const d=l>=0?c.session.map((f,m)=>m===l?o:f):[...c.session,o].sort((f,m)=>f.id.localeCompare(m.id));return{session:d,sessionTotal:Math.max(c.sessionTotal,d.length),limit:Math.max(c.limit,d.length)}})}catch{}return o},h2=()=>{const t=ks.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=qs.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},Fl=oo()(Of(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=h2();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,m=await pm(d)&&e.isolateRuns!==!1,u=cc(n),p=m?await qa(d):void 0,x=m?await sx(d):null,y=[],b=c?.filter(S=>S.trim().length>0)??[];for(let S=0;S<r.length;S++){const N=r[S],k=N.prompt,j=new Map;for(const O of N.models){const v=`${O.providerID}:${O.modelID}`;j.set(v,(j.get(v)||0)+1)}const D=new Map;for(const O of N.models){const v=`${O.providerID}:${O.modelID}`,M=j.get(v)||1,I=(D.get(v)||0)+1;D.set(v,I);const E=f2(O.providerID,O.modelID),B=r.length>1?`g${S+1}`:void 0,P=M>1?kf(u,`${E}/${I}`):kf(u,E),W=B?`${B}/${P}`:P,_=jk({groupSlug:u,runGroup:B,providerID:O.providerID,modelID:O.modelID,index:M>1?I:void 0});try{if(!m){const ie=await Jn.withDirectory(d,()=>Jn.createSession({title:_}));Cf(ie,d),y.push({sessionId:ie.id,worktreePath:d,providerID:O.providerID,modelID:O.modelID,variant:O.variant,prompt:k});continue}const V=await nx(l,{preferredName:W,mode:"new",branchName:W,worktreeName:W,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:b,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:x}),R={...V,createdFromBranch:p,kind:"standard"};await rx(l)&&await ix(V.path);const ne=await Jn.withDirectory(V.path,()=>Jn.createSession({title:_}));Cf(ne,V.path),ft.getState().setWorktreeMetadata(ne.id,R),y.push({sessionId:ne.id,worktreePath:V.path,providerID:O.providerID,modelID:O.modelID,variant:O.variant,prompt:k})}catch(V){console.warn("[MultiRun] Failed to create session:",V)}}}const g=c?.filter(S=>S.trim().length>0)??[];g.length>0&&ox(l,g).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const h=y.map(S=>S.sessionId),C=y[0]?.sessionId??null;if(h.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const w=a?.map(S=>({type:"file",mime:S.mime,filename:S.filename,url:S.url}));return(async()=>{try{const S=ax.getState().expandText;await Promise.allSettled(y.map(async N=>{try{const k=await S(N.prompt).catch(()=>N.prompt);await lx({sessionId:N.sessionId,directory:N.worktreePath,content:k,providerID:N.providerID,modelID:N.modelID,variant:N.variant,agent:o,files:w})}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(S){console.warn("[MultiRun] Failed to start runs:",S)}})(),t({isLoading:!1}),{groupSlug:u,sessionIds:h,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"})),p2="oc:lastWorktreeSourceBranch";function Ah(t){const e=mt.c(30),{git:n}=Xn(),r=sm(t),o=Nc(t),a=kc(t),c=dx(t),l=wn(w2),d=wn(y2);let f,m;e[0]!==t||e[1]!==d||e[2]!==n||e[3]!==o||e[4]!==a?(f=()=>{!t||!n||o!==null||a||d(t,n,{silent:!0})},m=[t,n,d,o,a],e[0]=t,e[1]=d,e[2]=n,e[3]=o,e[4]=a,e[5]=f,e[6]=m):(f=e[5],m=e[6]),i.useEffect(f,m);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 p=r?.all;let x;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==p?(x=[t,n,o,p,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=p,e[18]=x):x=e[18],i.useEffect(u,x);const y=a||o===!0&&c;let b;e:{if(!r?.all){let j;e[19]===Symbol.for("react.memo_cache_sentinel")?(j=[],e[19]=j):j=e[19],b=j;break e}let k;e[20]!==r.all?(k=r.all.filter(b2).sort(),e[20]=r.all,e[21]=k):k=e[21],b=k}const g=b;let h;e:{if(!r?.all){let j;e[22]===Symbol.for("react.memo_cache_sentinel")?(j=[],e[22]=j):j=e[22],h=j;break e}let k;e[23]!==r.all?(k=r.all.filter(x2).map(g2).sort(),e[23]=r.all,e[24]=k):k=e[24],h=k}const C=h;let w;e:{if(!t){w=null;break e}if(o!==null){w=o;break e}if(y){w=null;break e}w=r?.all?!0:null}const S=w;let N;return e[25]!==S||e[26]!==y||e[27]!==g||e[28]!==C?(N={localBranches:g,remoteBranches:C,isLoading:y,isGitRepository:S},e[25]=S,e[26]=y,e[27]=g,e[28]=C,e[29]=N):N=e[29],N}function g2(t){return t.replace(/^remotes\//,"")}function x2(t){return t.startsWith("remotes/")}function b2(t){return!t.startsWith("remotes/")}function y2(t){return t.fetchStatus}function w2(t){return t.fetchBranches}const v2=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=bt(),{localBranches:l,remoteBranches:d,isLoading:f,isGitRepository:m}=Ah(t),u=i.useMemo(()=>[...l,...d.map(x=>`remotes/${x}`)],[l,d]);i.useEffect(()=>{if(o||f||u.length===0||e&&u.includes(e))return;(async()=>{try{const y=t?await qa(t).catch(()=>null):null,b=localStorage.getItem(p2);b&&u.includes(b)?n(b):y&&u.includes(y)?n(y):u.includes("main")?n("main"):u.includes("master")?n("master"):u[0]&&n(u[0])}catch{}})()},[u,t,o,f,n,e]);const p=o||!m||f;return s.jsxs("div",{children:[s.jsxs(Un,{value:e,onValueChange:n,disabled:p,children:[s.jsx(Hn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(Cn,{placeholder:c(f?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(Gn,{className:"max-h-[280px] max-w-[320px]",children:f?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(Ul,{children:[s.jsx(zd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(x=>s.jsx(Rs,{value:x,className:"whitespace-normal break-all",children:x},x))]}),l.length>0&&d.length>0&&s.jsx(ux,{}),d.length>0&&s.jsxs(Ul,{children:[s.jsx(zd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(x=>s.jsx(Rs,{value:`remotes/${x}`,className:"whitespace-normal break-all",children:x},`remotes/${x}`))]})]})})]}),m===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},S2=10*1024*1024,Ol=5,xa=t=>{const e=mt.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(Ct,{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(A,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(kt,{children:[r,s.jsx(At,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},Di=t=>{const e=mt.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 f;return e[6]!==l||e[7]!==d?(f=s.jsxs("div",{className:"flex items-center gap-1.5",children:[l,d]}),e[6]=l,e[7]=d,e[8]=f):f=e[8],f},j2=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=bt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:To(),prompt:"",models:[]}]),[f,m]=i.useState(""),[u,p]=i.useState([]),[x,y]=i.useState(!1),[b,g]=i.useState([]),[h,C]=i.useState(!1),[w,S]=i.useState(!1),[N,k]=i.useState(!0),j=i.useRef(null),D=qs(L=>L.currentDirectory??null),O=qs(L=>L.homeDirectory??null),v=i.useMemo(()=>{if(typeof window>"u")return null;const L=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof L=="string"&&L.trim().length>0?L.trim():null},[]),M=ks(L=>L.activeProjectId),I=ks(L=>L.setActiveProjectIdOnly),E=ks(L=>L.projects),[B,P]=i.useState(()=>M??null);i.useEffect(()=>{if(M){P(M);return}!B&&E.length>0&&P(E[0].id)},[M,E,B]);const W=i.useMemo(()=>B?E.find(L=>L.id===B)??null:null,[E,B]),_=W?.path??D,V=i.useCallback(L=>{P(L),L!==M&&I(L)},[M,I]),{currentTheme:R}=pi(),ne=i.useCallback(L=>{const he=L.label?.trim()||lo(L.path,O),ge=L.icon?Pc[L.icon]:null,z=L.color?Ic[L.color]:void 0,pe=ge?s.jsx(A,{name:ge,className:"h-3.5 w-3.5 shrink-0",style:z?{color:z}:void 0}):s.jsx(A,{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:[L.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:L.iconBackground?{backgroundColor:L.iconBackground}:void 0,children:s.jsx(Rc,{project:{id:L.id,iconImage:L.iconImage??null},options:{themeVariant:R.metadata.variant,iconColor:R.colors.surface.foreground},className:"h-full w-full object-contain",fallback:pe})}):pe,s.jsx("span",{className:"truncate",children:he})]})},[O,R.metadata.variant,R.colors.surface.foreground]),ie=i.useMemo(()=>{if(W?.path)return{id:W.id,path:W.path};const L=D??v;return L?{id:`path:${L}`,path:L}:null},[W,D,v]),[J]=i.useState(()=>typeof window<"u"?cr():!1),U=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),ee=Yf(),ae=i.useMemo(()=>{if(typeof window>"u")return null;const L=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof L=="number"&&Number.isFinite(L)&&L>0)return L;if(typeof navigator>"u")return null;const he=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!he)return null;const ge=Number.parseInt(he[1],10),z=Number.parseInt(he[2],10);return Number.isNaN(ge)?null:ge===10?z:ge},[]),de=i.useMemo(()=>J&&U||ee?"pl-[5.5rem]":"pl-3",[J,U,ee]),ye=i.useMemo(()=>!J||!U||ae===null?"":ae>=26?"h-12":ae<=15?"h-14":"",[J,U,ae]),se=i.useCallback(async L=>{L.target.closest("button, a, input, select, textarea")||L.button===0&&J&&await fx()},[J]);i.useEffect(()=>{if(!n)return;const L=he=>{he.key==="Escape"&&(he.preventDefault(),he.stopPropagation(),n())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[n]);const[we,fe]=i.useState(""),{isLoading:Me,isGitRepository:$}=Ah(_),K=i.useRef(!1),q=$===!0,me=q&&N;i.useEffect(()=>{if($===!1){K.current=!0,k(!1);return}$===!0&&K.current&&(K.current=!1,k(!0))},[$]);const je=Fl(L=>L.createMultiRun),Oe=Fl(L=>L.error),Be=Fl(L=>L.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d(L=>{const he=[...L];return he.length>0&&!he[0].prompt.trim()&&(he[0]={...he[0],prompt:t}),he})},[t]),i.useEffect(()=>{if(!ie)return;let L=!1;return S(!0),(async()=>{try{const he=await mx(ie);L||g(he)}catch{}finally{L||S(!1)}})(),()=>{L=!0}},[ie]);const Fe=i.useCallback((L,he)=>{d(ge=>ge.map(z=>z.id===L?{...z,...he}:z))},[]),ue=i.useCallback(L=>{d(he=>he.filter(ge=>ge.id!==L))},[]),Re=i.useCallback(()=>{d(L=>[...L,{id:To(),prompt:"",models:[]}])},[]),xe=async L=>{const he=L.target.files;if(!he)return;let ge=0;for(let z=0;z<he.length;z++){const pe=he[z];if(pe.size>S2){ce.error(o("multirun.launcher.toast.fileTooLarge",{fileName:pe.name}));continue}try{const Ae=await new Promise((G,ke)=>{const Le=new FileReader;Le.onload=()=>G(Le.result),Le.onerror=ke,Le.readAsDataURL(pe)});p(G=>[...G,{id:To(),filename:pe.name,mimeType:pe.type||"application/octet-stream",size:pe.size,dataUrl:Ae}]),ge++}catch(Ae){console.error("File attach failed",Ae),ce.error(o("multirun.launcher.toast.attachFailed",{fileName:pe.name}))}}ge>0&&ce.success(ge===1?o("multirun.launcher.toast.attachedSingle",{count:ge}):o("multirun.launcher.toast.attachedPlural",{count:ge})),j.current&&(j.current.value="")},oe=L=>{p(he=>he.filter(ge=>ge.id!==L))},ve=i.useMemo(()=>l.reduce((L,he)=>L+he.models.length,0),[l]),Se=async L=>{L.preventDefault();const he=l.filter(ge=>ge.prompt.trim()&&ge.models.length>=1);if(he.length!==0&&!(ve<1)){y(!0),Be();try{B&&B!==M&&I(B);const ge=u.map(ke=>({mime:ke.mimeType,filename:ke.filename,url:ke.dataUrl})),z=b.filter(ke=>ke.trim().length>0),pe=he.map(ke=>({prompt:ke.prompt.trim(),models:ke.models.map(Le=>({providerID:Le.providerID,modelID:Le.modelID,displayName:Le.displayName,variant:Le.variant}))})),Ae={name:a.trim(),groups:pe,agent:f||void 0,worktreeBaseBranch:me?we:void 0,isolateRuns:me,files:ge.length>0?ge:void 0,setupCommands:z.length>0?z:void 0},G=await je(Ae);G&&(G.firstSessionId&&ft.getState().setCurrentSession(G.firstSessionId),e?.())}finally{y(!1)}}},le=!!(a.trim()&&l.some(L=>L.prompt.trim()&&L.models.length>=1)&&ve>=1&&_&&!Me&&($===!1||!me||we)),T=b.filter(L=>L.trim()).length;return s.jsxs("form",{onSubmit:Se,className:"flex flex-col h-full bg-background",children:[r?null:s.jsxs("header",{onMouseDown:se,className:Ie("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",de,ye),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(kt,{children:[s.jsx(Ct,{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(A,{name:"close",className:"h-5 w-5"})})}),s.jsx(At,{children:s.jsx("p",{children:o("multirun.launcher.actions.closeEsc")})})]})})]}),s.jsx(Ga,{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(Di,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),E.length>0?s.jsxs(Un,{value:B??void 0,onValueChange:V,children:[s.jsx(Hn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:W?s.jsx(Cn,{children:ne(W)}):s.jsx(Cn,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(Gn,{fitContent:!0,children:E.map(L=>s.jsx(Rs,{value:L.id,className:"max-w-[24rem]",children:ne(L)},L.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(Di,{htmlFor:"group-name",required:!0,info:s.jsx(xa,{children:o("multirun.launcher.groupName.info")}),children:o("multirun.launcher.groupName.label")}),s.jsx(Mn,{id:"group-name",value:a,onChange:L=>c(L.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(Di,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(xa,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(v2,{directory:_,value:we,onChange:fe,disabled:!me,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(Fi,{checked:N,onChange:k,disabled:!q,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(Di,{htmlFor:"multirun-agent",info:s.jsx(xa,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(jh,{value:f,onChange:m,id:"multirun-agent"})]})]}),s.jsxs(so,{open:h,onOpenChange:C,children:[s.jsxs(Vo,{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(A,{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")}),T>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:T}),s.jsx(A,{name:"arrow-down-s",className:Ie("h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto",h&&"rotate-180")})]}),s.jsx(no,{children:s.jsx("div",{className:"pt-2 space-y-1.5",children:w?s.jsx("p",{className:"typography-meta text-muted-foreground/70 px-2",children:o("multirun.launcher.setupCommands.loading")}):s.jsxs(s.Fragment,{children:[b.map((L,he)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(Mn,{value:L,onChange:ge=>{const z=[...b];z[he]=ge.target.value,g(z)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>g(b.filter((ge,z)=>z!==he)),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(A,{name:"close",className:"h-3.5 w-3.5"})})]},`${L}-${he}`)),s.jsxs("button",{type:"button",onClick:()=>g([...b,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(A,{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(Di,{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:j,type:"file",multiple:!0,className:"hidden",onChange:xe,accept:"*/*"}),s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>j.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(A,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(At,{children:o("multirun.launcher.attachments.tooltip")})]}),u.map(L=>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:[L.mimeType.startsWith("image/")?s.jsx(A,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(A,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:L.filename,children:L.filename}),s.jsx("button",{type:"button",onClick:()=>oe(L.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(A,{name:"close",className:"h-3 w-3"})})]},L.id))]})]}),l.map((L,he)=>s.jsx(N2,{group:L,groupIndex:he,canRemove:l.length>1,onUpdate:Fe,onRemove:ue},L.id)),s.jsxs("button",{type:"button",onClick:Re,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(A,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),Oe&&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:Oe})]})})}),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:[!me&&$!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(A,{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:!le||x,children:x?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:ve})})})]})})]})},N2=t=>{const e=mt.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=bt(),[d,f]=i.useState(!1),[m,u]=i.useState(""),[p,x]=i.useState(!1),[y,b]=i.useState(""),[g,h]=i.useState(!1),[C,w]=i.useState(""),S=i.useRef(null),N=i.useRef(null),k=i.useRef(null),j=i.useRef(null);let D;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(D=z=>{n.models.length>=Ol||a(n.id,{models:[...n.models,z]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=D):D=e[3];const O=D;let v;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(v=z=>{a(n.id,{models:n.models.filter((pe,Ae)=>Ae!==z)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=v):v=e[7];const M=v;let I;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(I=(z,pe)=>{a(n.id,{models:n.models.map((Ae,G)=>G===z?pe:Ae)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=I):I=e[11];const E=I;let B;e[12]===Symbol.for("react.memo_cache_sentinel")?(B=(z,pe)=>{if(z.startsWith("/")){const Le=z.indexOf(" "),Te=z.indexOf(`
233
- `),Z=Math.min(Le===-1?z.length:Le,Te===-1?z.length:Te);if(pe<=Z&&Le===-1){b(z.substring(1,Z)),x(!0),f(!1),h(!1);return}}x(!1);const Ae=z.substring(0,pe),G=Ae.lastIndexOf("#");if(G!==-1){const Le=G>0?Ae[G-1]:null,Te=Ae.substring(G+1);if((!Le||/\s/.test(Le))&&!Te.includes(" ")&&!Te.includes(`
234
- `)){w(Te),h(!0),f(!1);return}}h(!1);const ke=Ae.lastIndexOf("@");if(ke!==-1){const Le=ke>0?Ae[ke-1]:null,Te=Ae.substring(ke+1);(!Le||/\s/.test(Le))&&!Te.includes(" ")&&!Te.includes(`
235
- `)?(u(Te),f(!0)):f(!1);return}f(!1)},e[12]=B):B=e[12];const P=B;let W;e[13]!==n.id||e[14]!==a?(W=z=>{a(n.id,{prompt:z})},e[13]=n.id,e[14]=a,e[15]=W):W=e[15];const _=W;let V;e[16]!==n.prompt||e[17]!==_?(V=z=>{const pe=n.prompt,G=S.current?.selectionStart??pe.length,Le=pe.substring(0,G).lastIndexOf("@"),Te=z.relativePath&&z.relativePath.trim().length>0?z.relativePath.trim():z.path||z.name,Z=Le!==-1?Le:G,F=`${pe.substring(0,Z)}@${Te} ${pe.substring(G)}`,re=Z+Te.length+2;_(F),f(!1),u(""),requestAnimationFrame(()=>{const te=S.current;te&&(te.selectionStart=re,te.selectionEnd=re,te.focus()),P(F,re)})},e[16]=n.prompt,e[17]=_,e[18]=V):V=e[18];const R=V;let ne;e[19]!==n.prompt||e[20]!==_?(ne=z=>{const pe=n.prompt,G=S.current?.selectionStart??pe.length,Le=pe.substring(0,G).lastIndexOf("@"),Te=Le!==-1?Le:G,Z=`${pe.substring(0,Te)}@${z} ${pe.substring(G)}`,F=Te+z.length+2;_(Z),f(!1),u(""),requestAnimationFrame(()=>{const re=S.current;re&&(re.selectionStart=F,re.selectionEnd=F,re.focus()),P(Z,F)})},e[19]=n.prompt,e[20]=_,e[21]=ne):ne=e[21];const ie=ne;let J;e[22]!==_?(J=z=>{const pe=`/${z.name} `;_(pe),x(!1),b(""),h(!1),requestAnimationFrame(()=>{const Ae=S.current;Ae&&(Ae.focus(),Ae.selectionStart=Ae.value.length,Ae.selectionEnd=Ae.value.length),P(pe,pe.length)})},e[22]=_,e[23]=J):J=e[23];const U=J;let ee;e[24]!==n.prompt||e[25]!==_?(ee=(z,pe)=>{const Ae=n.prompt,ke=S.current?.selectionStart??Ae.length,Te=Ae.substring(0,ke).lastIndexOf("#"),Z=Te!==-1?Te:ke,F=`${Ae.substring(0,Z)}#${pe} ${Ae.substring(ke)}`,re=Z+pe.length+2;_(F),h(!1),w(""),requestAnimationFrame(()=>{const te=S.current;te&&(te.selectionStart=re,te.selectionEnd=re,te.focus()),P(F,re)})},e[24]=n.prompt,e[25]=_,e[26]=ee):ee=e[26];const ae=ee;let de;e[27]!==p||e[28]!==d||e[29]!==g?(de=z=>{if(p&&k.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")){z.preventDefault(),k.current.handleKeyDown(z.key);return}d&&N.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")&&(z.preventDefault(),N.current.handleKeyDown(z.key)),g&&j.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")&&(z.preventDefault(),j.current.handleKeyDown(z.key))},e[27]=p,e[28]=d,e[29]=g,e[30]=de):de=e[30];const ye=de,se=r+1;let we;e[31]!==l||e[32]!==se?(we=l("multirun.launcher.groups.groupLabel",{index:se}),e[31]=l,e[32]=se,e[33]=we):we=e[33];let fe;e[34]!==we?(fe=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:we}),e[34]=we,e[35]=fe):fe=e[35];let Me;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(Me=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(A,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=Me):Me=e[40];let $;e[41]!==fe||e[42]!==Me?($=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[fe,Me]}),e[41]=fe,e[42]=Me,e[43]=$):$=e[43];let K;e[44]!==l?(K=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=K):K=e[45];let q;e[46]!==K?(q=s.jsx(Di,{required:!0,children:K}),e[46]=K,e[47]=q):q=e[47];const me=n.prompt;let je;e[48]!==_?(je=z=>{const pe=z.target.value;_(pe);const Ae=z.target.selectionStart??pe.length;P(pe,Ae)},e[48]=_,e[49]=je):je=e[49];let Oe;e[50]!==l?(Oe=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=Oe):Oe=e[51];let Be;e[52]!==n.prompt||e[53]!==ye||e[54]!==je||e[55]!==Oe?(Be=s.jsx(Ti,{ref:S,value:me,onChange:je,onKeyDown:ye,placeholder:Oe,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]=ye,e[54]=je,e[55]=Oe,e[56]=Be):Be=e[56];let Fe;e[57]!==y||e[58]!==U||e[59]!==p?(Fe=p?s.jsx(um,{ref:k,searchQuery:y,onCommandSelect:U,onClose:()=>x(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=y,e[58]=U,e[59]=p,e[60]=Fe):Fe=e[60];let ue;e[61]!==ie||e[62]!==R||e[63]!==m||e[64]!==d?(ue=d?s.jsx(fm,{ref:N,searchQuery:m,onFileSelect:R,onAgentSelect:ie,onClose:()=>f(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=ie,e[62]=R,e[63]=m,e[64]=d,e[65]=ue):ue=e[65];let Re;e[66]!==ae||e[67]!==g||e[68]!==C?(Re=g?s.jsx(mm,{ref:j,searchQuery:C,onSnippetSelect:ae,onClose:()=>h(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=ae,e[67]=g,e[68]=C,e[69]=Re):Re=e[69];let xe;e[70]!==Be||e[71]!==Fe||e[72]!==ue||e[73]!==Re?(xe=s.jsxs("div",{className:"relative",children:[Be,Fe,ue,Re]}),e[70]=Be,e[71]=Fe,e[72]=ue,e[73]=Re,e[74]=xe):xe=e[74];let oe;e[75]!==q||e[76]!==xe?(oe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[q,xe]}),e[75]=q,e[76]=xe,e[77]=oe):oe=e[77];let ve;e[78]!==l?(ve=l("multirun.launcher.models.info",{max:Ol}),e[78]=l,e[79]=ve):ve=e[79];let Se;e[80]!==ve?(Se=s.jsx(xa,{children:ve}),e[80]=ve,e[81]=Se):Se=e[81];let le;e[82]!==l?(le=l("multirun.launcher.models.label"),e[82]=l,e[83]=le):le=e[83];let T;e[84]!==Se||e[85]!==le?(T=s.jsx(Di,{required:!0,info:Se,children:le}),e[84]=Se,e[85]=le,e[86]=T):T=e[86];let L;e[87]!==n.models||e[88]!==O||e[89]!==M||e[90]!==E?(L=s.jsx(kh,{selectedModels:n.models,onAdd:O,onRemove:M,onUpdate:E,minModels:1,maxModels:Ol}),e[87]=n.models,e[88]=O,e[89]=M,e[90]=E,e[91]=L):L=e[91];let he;e[92]!==T||e[93]!==L?(he=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[T,L]}),e[92]=T,e[93]=L,e[94]=he):he=e[94];let ge;return e[95]!==$||e[96]!==oe||e[97]!==he?(ge=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[$,oe,he]}),e[95]=$,e[96]=oe,e[97]=he,e[98]=ge):ge=e[98],ge},k2=i.createContext(null),C2=t=>{const e=mt.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(k2.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},Af=co(()=>ao(()=>import("./TerminalView-D_9BAjtv.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(t=>({default:t.TerminalView}))),A2=co(()=>ao(()=>import("./DiagramView-HR2xZxJ8.js"),__vite__mapDeps([8,1,3,4,2,5,6,7])).then(t=>({default:t.DiagramView}))),D2=co(()=>ao(()=>import("./runtimeEndpointReset-C42u8PvG.js").then(t=>t.ac),__vite__mapDeps([5,1,2,3,4,6])).then(t=>({default:t.SettingsView}))),T2=co(()=>ao(()=>import("./SettingsWindow-CkInZcj7.js"),__vite__mapDeps([9,1,2,3,4,5,6])).then(t=>({default:t.SettingsWindow}))),P2=co(()=>ao(()=>import("./MultiRunWindow-DlFUaNQK.js"),__vite__mapDeps([10,1,2,3,4,5,6,7])).then(t=>({default:t.MultiRunWindow}))),I2=()=>{const o=Ee(ee=>ee.isSidebarOpen),a=Ee(ee=>ee.isRightSidebarOpen),c=Ee(ee=>ee.isBottomTerminalOpen),l=Ee(ee=>ee.setRightSidebarOpen),d=Ee(ee=>ee.setBottomTerminalOpen),f=Ee(ee=>ee.activeMainTab),m=Ee(ee=>ee.setIsMobile),u=Ee(ee=>ee.isSessionSwitcherOpen),p=Ee(ee=>ee.isSettingsDialogOpen),x=Ee(ee=>ee.setSettingsDialogOpen),y=Ee(ee=>ee.isMultiRunLauncherOpen),b=Ee(ee=>ee.setMultiRunLauncherOpen),g=Ee(ee=>ee.multiRunLauncherPrefillPrompt),{isMobile:h,isTablet:C}=Or(),w=i.useRef(!1),S=i.useRef(!1),N=i.useRef(!1),[k,j]=i.useState(!1),[D,O]=i.useState(!1),[v,M]=i.useState(!1),[I,E]=i.useState(!1),B=i.useCallback(ee=>{j(ee),Ee.getState().setSessionSwitcherOpen(ee)},[]),P=i.useRef(!1),W=i.useRef(typeof window>"u"?0:window.innerWidth),_=gd(-W.current),V=Xe.useRef(0),R=gd(W.current),ne=Xe.useRef(0);Xe.useEffect(()=>{h&&(V.current=window.innerWidth,ne.current=window.innerWidth)},[h]),Xe.useEffect(()=>{if(!h){M(!1);return}k&&M(!0),xd(_,k?0:-V.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[k,h,_]),Xe.useEffect(()=>{if(!h){E(!1);return}P.current=D,D&&E(!0),xd(R,D?0:ne.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[h,D,R]),Xe.useEffect(()=>{if(h)return _.on("change",ee=>{const ae=V.current||W.current,de=k||ee>-ae+.5;M(ye=>ye===de?ye:de)})},[h,_,k]),Xe.useEffect(()=>{if(h)return R.on("change",ee=>{const ae=ne.current||W.current,de=D||ee<ae-.5;E(ye=>ye===de?ye:de)})},[h,D,R]),Xe.useEffect(()=>{h&&!u&&k&&B(!1)},[u,h,k,B]),Xe.useEffect(()=>{if(!h){N.current=!1;return}N.current||(N.current=!0,B(!1),O(!1),Ee.getState().isRightSidebarOpen&&l(!1))},[h,B,l]),Xe.useEffect(()=>{if(!h||f!=="chat"||k||D||p)return;let ee=!1,ae;const de=ye=>{ae=window.setTimeout(()=>{if(ee)return;const se=ft.getState(),we=Ee.getState();if(!(we.activeMainTab!=="chat"||we.isSettingsDialogOpen||se.currentSessionId||se.newSessionDraft?.open)){if(se.isLoading){de(250);return}se.openNewSessionDraft()}},ye)};return de(500),()=>{ee=!0,ae!==void 0&&window.clearTimeout(ae)}},[f,h,p,k,D]),Xe.useEffect(()=>{!h||!p||(B(!1),O(!1),a&&l(!1))},[h,p,a,B,l]),Zx(),i.useEffect(()=>{Ee.getState().isMobile!==h&&m(h)},[h,m]),i.useEffect(()=>{if(typeof window>"u")return;let ee;const ae=()=>{ee===void 0&&(ee=window.requestAnimationFrame(()=>{ee=void 0,Ee.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",ae),()=>{window.removeEventListener("resize",ae),ee!==void 0&&window.cancelAnimationFrame(ee)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let ee;const ae=()=>{const ye=Ee.getState(),se=window.innerWidth,we=window.innerHeight;if(!h&&!C){const fe=se<1140,Me=se>=1220;fe?ye.isRightSidebarOpen&&(l(!1),w.current=!0):Me&&w.current&&(l(!0),w.current=!1);const $=we<640,K=we>=700;$?ye.isBottomTerminalOpen&&(d(!1),S.current=!0):K&&S.current&&(d(!0),S.current=!1)}},de=()=>{ee===void 0&&(ee=window.requestAnimationFrame(()=>{ee=void 0,ae()}))};return ae(),window.addEventListener("resize",de),()=>{window.removeEventListener("resize",de),ee!==void 0&&window.cancelAnimationFrame(ee)}},[h,C,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const ee=Ee.subscribe((ae,de)=>{const ye=window.innerWidth,se=window.innerHeight,we=ye>=1220,fe=se>=700;ae.isRightSidebarOpen!==de.isRightSidebarOpen&&we&&(w.current=!1),ae.isBottomTerminalOpen!==de.isBottomTerminalOpen&&fe&&(S.current=!1)});return()=>{ee()}},[h,C,d,l]);const ie=i.useCallback(()=>{k&&B(!1),O(!D)},[k,D,B]),J=i.useMemo(()=>{switch(f){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(sh,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Zl,{isActive:!D})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Jm,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Af,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(th,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Gm,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(A2,{})});default:return null}},[f,D]),U=f==="chat";return s.jsx(eb,{children:s.jsxs("div",{"data-page-scroll-lock":"true",className:Ie("main-content-safe-area",h?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[s.jsx(eS,{}),s.jsx($S,{}),s.jsx(HS,{}),s.jsx(u2,{}),h?s.jsxs(C2,{value:{leftDrawerOpen:k,rightDrawerOpen:D,toggleLeftDrawer:()=>{const ee=!k;D&&O(!1),B(ee)},toggleRightDrawer:ie,leftDrawerX:_,rightDrawerX:R,leftDrawerWidth:V,rightDrawerWidth:ne,setMobileLeftDrawerOpen:B,setRightSidebarOpen:O},children:[!p&&s.jsx(su,{onToggleLeftDrawer:()=>{const ee=!k;D&&O(!1),B(ee)},onToggleRightDrawer:()=>{ie()},leftDrawerOpen:k,rightDrawerOpen:D}),s.jsx("div",{"data-page-scroll-lock":"true",className:Ie("flex flex-1 overflow-hidden relative",p&&"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:Ie("absolute inset-0",!U&&"invisible"),children:s.jsx(Xs,{children:s.jsx(ql,{})})}),J&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Xs,{children:J})}),y&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(Xs,{children:s.jsx(j2,{initialPrompt:g,onCreated:()=>b(!1),onCancel:()=>b(!1)})})}),v&&s.jsx(bd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:_},"aria-hidden":!k,children:s.jsx(Xs,{children:s.jsx(Nf,{mobileVariant:!0})})}),I&&s.jsx(bd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:R},"aria-hidden":!D,children:s.jsx(Xs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Zl,{isActive:D})})})})]})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(Xs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(D2,{onClose:()=>x(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(dy,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(ay,{isOpen:o,isMobile:h,className:"border-border/50",topBar:s.jsx(ly,{}),children:s.jsx(Nf,{})}),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(su,{}),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:Ie("absolute inset-0",!U&&"invisible"),children:s.jsx(Xs,{children:s.jsx(ql,{})})}),J&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Xs,{children:J})})]}),s.jsx(Z0,{})]})}),s.jsx(sy,{isOpen:c,isMobile:h,children:c?s.jsx(Xs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Af,{})})}):null})]}),s.jsx(gy,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(Xs,{children:s.jsx(Lv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(T2,{open:p,onOpenChange:x})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(P2,{open:y,onOpenChange:b,initialPrompt:g})})]})]})})},R2=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`},zn=t=>{const e=mt.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},Df=t=>{const e=mt.c(43),{title:n,snapshot:r,emptyLabel:o}=t,{t:a}=bt();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(F2,0),e[8]=r.entries,e[9]=d):d=e[9];const f=d;let m;e[10]!==n?(m=s.jsx("div",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:n}),e[10]=n,e[11]=m):m=e[11];let u;e[12]!==r.durationMs||e[13]!==r.startedAt||e[14]!==a?(u=r.startedAt?R2(r.durationMs):a("memoryDebugPanel.common.idle"),e[12]=r.durationMs,e[13]=r.startedAt,e[14]=a,e[15]=u):u=e[15];let p;e[16]!==u?(p=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:u}),e[16]=u,e[17]=p):p=e[17];let x;e[18]!==m||e[19]!==p?(x=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m,p]}),e[18]=m,e[19]=p,e[20]=x):x=e[20];let y;e[21]!==a?(y=a("memoryDebugPanel.metric.metrics"),e[21]=a,e[22]=y):y=e[22];let b;e[23]!==r.entries.length||e[24]!==y?(b=s.jsx(zn,{label:y,value:r.entries.length}),e[23]=r.entries.length,e[24]=y,e[25]=b):b=e[25];let g;e[26]!==a?(g=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=g):g=e[27];let h;e[28]!==g||e[29]!==f?(h=s.jsx(zn,{label:g,value:f}),e[28]=g,e[29]=f,e[30]=h):h=e[30];let C;e[31]!==a?(C=a("memoryDebugPanel.metric.lastUpdate"),e[31]=a,e[32]=C):C=e[32];let w;e[33]!==r.lastUpdatedAt||e[34]!==a?(w=r.lastUpdatedAt?a("memoryDebugPanel.common.live"):a("memoryDebugPanel.common.notAvailable"),e[33]=r.lastUpdatedAt,e[34]=a,e[35]=w):w=e[35];let S;e[36]!==C||e[37]!==w?(S=s.jsx(zn,{label:C,value:w}),e[36]=C,e[37]=w,e[38]=S):S=e[38];let N;e[39]!==h||e[40]!==S||e[41]!==b?(N=s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[b,h,S]}),e[39]=h,e[40]=S,e[41]=b,e[42]=N):N=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:[x,N,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(En,{outerClassName:"max-h-64",className:"pr-1",children:s.jsx("div",{className:"space-y-1",children:l.map(k=>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:k.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:k.count})}),s.jsx("span",{children:a("memoryDebugPanel.metric.avgValue",{value:k.avg})}),s.jsx("span",{children:a("memoryDebugPanel.metric.maxValue",{value:k.max})}),s.jsx("span",{children:a("memoryDebugPanel.metric.totalValue",{value:k.total})})]})]},k.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},E2=t=>{const e=mt.c(99),{onClose:n}=t,{t:r}=bt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=ft(O2),f=hm(L2),m=Ac(),u=hx(B2),p=sr(V2),[x,y]=i.useState(_2),[b,g]=i.useState($2);let h;e[0]!==x.entries?(h=new Map,x.entries.forEach(le=>{h.set(le.metric,le.count)}),e[0]=x.entries,e[1]=h):h=e[1];let C;e[2]!==h?(C=h.get("ui.message_list.render")??0,e[2]=h,e[3]=C):C=e[3];let w;e[4]!==h?(w=h.get("ui.message_list.render.streaming")??0,e[4]=h,e[5]=w):w=e[5];let S;e[6]!==h?(S=h.get("ui.chat_message.render")??0,e[6]=h,e[7]=S):S=e[7];let N;e[8]!==h?(N=h.get("ui.chat_message.render.streaming")??0,e[8]=h,e[9]=N):N=e[9];let k;e[10]!==h?(k=h.get("ui.chat_message.render.static_during_stream")??0,e[10]=h,e[11]=k):k=e[11];let j;e[12]!==h?(j=h.get("ui.chat_message.render.static_outside_active_turn_during_stream")??0,e[12]=h,e[13]=j):j=e[13];let D;e[14]!==C||e[15]!==w||e[16]!==S||e[17]!==N||e[18]!==k||e[19]!==j?(D={messageListRender:C,messageListRenderStreaming:w,chatMessageRender:S,chatMessageRenderStreaming:N,chatMessageRenderStaticDuringStream:k,chatMessageRenderStaticOutsideActiveTurnDuringStream:j},e[14]=C,e[15]=w,e[16]=S,e[17]=N,e[18]=k,e[19]=j,e[20]=D):D=e[20];const O=D;let v,M;e[21]===Symbol.for("react.memo_cache_sentinel")?(v=()=>{const le=()=>{y(ra()),g(ia())};le();const T=window.setInterval(le,500);return()=>window.clearInterval(T)},M=[],e[21]=v,e[22]=M):(v=e[21],M=e[22]),i.useEffect(v,M);let I,E;e[23]!==c?(I=()=>{if(c==="idle")return;const le=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(le)},E=[c],e[23]=c,e[24]=I,e[25]=E):(I=e[24],E=e[25]),i.useEffect(I,E);let B=0,P=0,W=0;for(const le of Object.keys(u)){const T=u[le]??[];P=P+T.length;for(const L of T)L.role==="user"?W=W+1:L.role==="assistant"&&(B=B+1)}let _;e[26]!==B||e[27]!==P||e[28]!==W?(_={assistant:B,total:P,user:W},e[26]=B,e[27]=P,e[28]=W,e[29]=_):_=e[29];const V=_;let R;if(e[30]!==d||e[31]!==u||e[32]!==f||e[33]!==m||e[34]!==r){let le;e[36]!==d||e[37]!==u||e[38]!==f||e[39]!==r?(le=T=>{const L=u[T.id]??[];let he=0,ge=0;for(const pe of L)pe.role==="user"?ge=ge+1:pe.role==="assistant"&&(he=he+1);const z=f.get(T.id);return{id:T.id,title:T.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:he,messageCount:L.length,userMessageCount:ge,isStreaming:z?.isStreaming||!1,isZombie:z?.isZombie||!1,backgroundCount:z?.backgroundMessageCount||0,lastAccessed:z?.lastAccessedAt||0,isCurrent:T.id===d}},e[36]=d,e[37]=u,e[38]=f,e[39]=r,e[40]=le):le=e[40],R=m.map(le).sort(z2),e[30]=d,e[31]=u,e[32]=f,e[33]=m,e[34]=r,e[35]=R}else R=e[35];const ne=R;let ie;e[41]!==u?(ie=Object.keys(u),e[41]=u,e[42]=ie):ie=e[42];const J=ie.length;let U;e[43]===Symbol.for("react.memo_cache_sentinel")?(U=async()=>{try{const le={generatedAt:new Date().toISOString(),ui:ra(),vscode:ia()};await navigator.clipboard.writeText(JSON.stringify(le,null,2)),l("copied")}catch{l("error")}},e[43]=U):U=e[43];const ee=U;let ae;e[44]===Symbol.for("react.memo_cache_sentinel")?(ae={backgroundColor:"color-mix(in srgb, var(--surface-background) 94%, transparent)"},e[44]=ae):ae=e[44];let de;e[45]!==o?(de=o==="memory"?s.jsx(A,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(A,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=de):de=e[46];let ye;e[47]!==r?(ye=r("memoryDebugPanel.title"),e[47]=r,e[48]=ye):ye=e[48];let se;e[49]!==ye?(se=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:ye}),e[49]=ye,e[50]=se):se=e[50];let we;e[51]!==de||e[52]!==se?(we=s.jsxs("div",{className:"flex items-center gap-2",children:[de,se]}),e[51]=de,e[52]=se,e[53]=we):we=e[53];let fe;e[54]!==o?(fe=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx(ze,{size:"xs",variant:"ghost",onClick:ee,children:s.jsx(A,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx(ze,{size:"xs",variant:"ghost",onClick:()=>{jp(),y(ra()),g(ia())},children:s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=fe):fe=e[55];let Me;e[56]!==n?(Me=n?s.jsx(ze,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(A,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=Me):Me=e[57];let $;e[58]!==fe||e[59]!==Me?($=s.jsxs("div",{className:"flex items-center gap-1",children:[fe,Me]}),e[58]=fe,e[59]=Me,e[60]=$):$=e[60];let K;e[61]!==we||e[62]!==$?(K=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[we,$]}),e[61]=we,e[62]=$,e[63]=K):K=e[63];let q;e[64]===Symbol.for("react.memo_cache_sentinel")?(q={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=q):q=e[64];const me=o==="memory"?"secondary":"ghost";let je;e[65]===Symbol.for("react.memo_cache_sentinel")?(je=()=>a("memory"),e[65]=je):je=e[65];let Oe;e[66]!==r?(Oe=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=Oe):Oe=e[67];let Be;e[68]!==me||e[69]!==Oe?(Be=s.jsx(ze,{size:"sm",variant:me,className:"flex-1",onClick:je,children:Oe}),e[68]=me,e[69]=Oe,e[70]=Be):Be=e[70];const Fe=o==="streaming"?"secondary":"ghost";let ue;e[71]===Symbol.for("react.memo_cache_sentinel")?(ue=()=>a("streaming"),e[71]=ue):ue=e[71];let Re;e[72]!==r?(Re=r("memoryDebugPanel.tabs.streaming"),e[72]=r,e[73]=Re):Re=e[73];let xe;e[74]!==Fe||e[75]!==Re?(xe=s.jsx(ze,{size:"sm",variant:Fe,className:"flex-1",onClick:ue,children:Re}),e[74]=Fe,e[75]=Re,e[76]=xe):xe=e[76];let oe;e[77]!==Be||e[78]!==xe?(oe=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:q,children:[Be,xe]}),e[77]=Be,e[78]=xe,e[79]=oe):oe=e[79];let ve;e[80]!==o||e[81]!==J||e[82]!==c||e[83]!==d||e[84]!==u||e[85]!==V||e[86]!==f||e[87]!==ne||e[88]!==m||e[89]!==O||e[90]!==x||e[91]!==r||e[92]!==p||e[93]!==b?(ve=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(zn,{label:r("memoryDebugPanel.metric.totalMessages"),value:V.total}),s.jsx(zn,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${J} / ${Wd.MAX_SESSIONS}`}),s.jsx(zn,{label:r("memoryDebugPanel.metric.userMessages"),value:V.user}),s.jsx(zn,{label:r("memoryDebugPanel.metric.assistantMessages"),value:V.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:px()})})]}),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:Wd.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:p})]})]}),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(En,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:ne.map(le=>s.jsxs("div",{className:"typography-meta flex items-center justify-between rounded p-1.5",style:{backgroundColor:le.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:le.title}),le.isStreaming?s.jsx(A,{name:"pulse",className:"h-3 w-3 animate-pulse text-[var(--status-info)]"}):null,le.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:le.assistantMessageCount,user:le.userMessageCount})}),s.jsx("span",{className:"font-mono text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.msgsValue",{count:le.messageCount})}),le.backgroundCount>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["+",le.backgroundCount]}):null]})]},le.id))})]}),s.jsx("div",{className:"flex gap-2 border-t border-[var(--interactive-border)] pt-2",children:s.jsxs(kt,{children:[s.jsx(Ct,{asChild:!0,children:s.jsx(ze,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:m.map(W2),currentSessionId:d,cachedSessions:Object.keys(u),messageRoleCounts:V,sessionMessageRoleCounts:ne.map(U2),memoryStates:Object.fromEntries(f)})},children:r("memoryDebugPanel.actions.logState")})}),s.jsx(At,{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:ee,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(zn,{label:r("memoryDebugPanel.metric.uiMetrics"),value:x.entries.length}),s.jsx(zn,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:b.entries.length}),s.jsx(zn,{label:r("memoryDebugPanel.metric.messageListRenders"),value:O.messageListRender}),s.jsx(zn,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:O.messageListRenderStreaming}),s.jsx(zn,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:O.chatMessageRender}),s.jsx(zn,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:O.chatMessageRenderStreaming}),s.jsx(zn,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:O.chatMessageRenderStaticDuringStream}),s.jsx(zn,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:O.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(Df,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:x,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),b.entries.length>0?s.jsx(Df,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:b,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=J,e[82]=c,e[83]=d,e[84]=u,e[85]=V,e[86]=f,e[87]=ne,e[88]=m,e[89]=O,e[90]=x,e[91]=r,e[92]=p,e[93]=b,e[94]=ve):ve=e[94];let Se;return e[95]!==K||e[96]!==oe||e[97]!==ve?(Se=s.jsxs(gx,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:ae,children:[K,oe,ve]}),e[95]=K,e[96]=oe,e[97]=ve,e[98]=Se):Se=e[98],Se},M2=E2;function F2(t,e){return t+e.count}function O2(t){return t.currentSessionId}function L2(t){return t.sessionMemoryState}function B2(t){return t.message}function V2(t){return t.totalRequestCount}function _2(){return ra()}function $2(){return ia()}function z2(t,e){return e.lastAccessed-t.lastAccessed}function W2(t){return{id:t.id,title:t.title}}function U2(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const H2=()=>{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()??"":""},G2=async()=>{const t=H2()||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")},Tf="openchamber:menu-action",Ll="openchamber:check-for-updates",K2=t=>{const e=ft(j=>j.openNewSessionDraft),n=Ee(j=>j.toggleCommandPalette),r=Ee(j=>j.setCommandPaletteOpen),o=Ee(j=>j.toggleHelpDialog),a=Ee(j=>j.toggleSidebar),c=Ee(j=>j.setSessionSwitcherOpen),l=Ee(j=>j.setActiveMainTab),d=Ee(j=>j.setSettingsDialogOpen),f=Ee(j=>j.setAboutDialogOpen),m=Ee(j=>j.toggleRightSidebar),u=Ee(j=>j.setRightSidebarOpen),p=Ee(j=>j.setRightSidebarTab),x=Ee(j=>j.toggleBottomTerminal),y=Ee(j=>j.setBottomTerminalExpanded),b=So(j=>j.checkForUpdates),{setThemeMode:g}=pi(),h=i.useRef(!1),C=i.useCallback(()=>{h.current||(h.current=!0,b().then(()=>{const{available:j,error:D}=So.getState();if(D){ce.error("Failed to check for updates",{description:D});return}j||ce.success("You are on the latest version")}).finally(()=>{h.current=!1}))},[b]),w=i.useCallback(()=>{Er.requestDirectoryDialog()},[]),S=i.useCallback(j=>{const D=xx();if(D.length===0)return;const O=ft.getState().currentSessionId,v=D.findIndex(E=>E.id===O);let M=j>0?0:D.length-1;v>=0&&(M=(v+j+D.length)%D.length);const I=D[M];I&&(l("chat"),c(!1),ft.getState().setCurrentSession(I.id))},[l,c]),N=i.useCallback(j=>{const{activeProjectId:D,projects:O,setActiveProject:v}=ks.getState();if(O.length===0)return;const M=O.findIndex(B=>B.id===D);let I=j>0?0:O.length-1;M>=0&&(I=(M+j+O.length)%O.length);const E=O[I];E&&v(E.id)},[]),k=i.useCallback(j=>{switch(j){case"about":f(!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),dm();break;case"change-workspace":w();break;case"toggle-right-sidebar":m();break;case"open-right-sidebar-git":u(!0),p("git");break;case"open-right-sidebar-files":u(!0),p("files");break;case"toggle-terminal":x();break;case"toggle-terminal-expanded":y(!Ee.getState().isBottomTerminalExpanded);break;case"copy":{const D=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(D)||G2();break}case"theme-light":g("light");break;case"theme-dark":g("dark");break;case"theme-system":g("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":qs.getState().goBack();break;case"go-forward":qs.getState().goForward();break;case"previous-session":S(-1);break;case"next-session":S(1);break;case"previous-project":N(-1);break;case"next-project":N(1);break;case"help-dialog":o();break;case"download-logs":{bx().catch(()=>{ce.error("Failed to collect OpenCode status")});break}}},[w,N,S,t,e,f,l,c,r,d,y,u,p,g,x,n,o,m,a]);i.useEffect(()=>{const j=O=>{const v=O.detail;v&&k(v)},D=()=>{C()};return window.addEventListener(Tf,j),window.addEventListener(Ll,D),()=>{window.removeEventListener(Tf,j),window.removeEventListener(Ll,D)}},[k,C]),i.useEffect(()=>{if(typeof window>"u")return;const D=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof D!="function")return;let O=null,v=null;return D("openchamber:menu-action",M=>{const I=M?.payload;typeof I=="string"&&k(I)}).then(M=>{O=M}).catch(()=>{}),D("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Ll))}).then(M=>{v=M}).catch(()=>{}),()=>{(async()=>{try{const I=O?.();I instanceof Promise&&await I}catch{}try{const I=v?.();I instanceof Promise&&await I}catch{}})()}},[k])},q2="openchamber:tray-action",Pf=5e3,Y2=120,Q2=45e3,Dh=20,If=()=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_PLATFORM__;return t==="darwin"||t==="win32"},J2=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},X2=t=>{const e=Array.isArray(t.questions)?t.questions[0]:void 0;return e?.header||e?.question||"Question"},Ba=t=>t.time?.updated??t.time?.created??0,Z2=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},eC=(t,e,n,r,o)=>{if(!t)return"";const a=Sx(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||Z2(t),d=aa(t);let f=d&&o.get(d)||"";if(!f){for(const[m,u]of wn.getState().directories)if(aa(m)===d){f=u.status?.current??"";break}}if(!f)for(const m of r.values()){const u=m.find(p=>aa(p.path)===d);if(u?.branch){f=u.branch;break}}return f?`${l} · ${f}`:l},tC=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=mn.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[m,u]of Object.entries(l.usage?.windows??{})){const p=r==="remaining"?u.remainingPercent:u.usedPercent;d.push({label:xc(m),value:Io(u.valueLabel,p)})}const f=!l.ok&&l.error?l.error:d.length===0?"No rate limits reported":null;a.push({provider:c.name,rows:d,status:f})}return{mode:r,groups:a}},sC=async()=>{try{if(Zi())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=Hr();if(e&&ja(e,t))return"Local OpenChamber";const r=(await _f()).hosts.find(o=>e?ja(e,$f(o)):!1);return r?.label?.trim()?zf(r.label.trim()):"Instance"}catch{return""}},nC=()=>{const t=new Map,e=new Map,n=[],r=new Map;let o;try{o=Aa()}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(aa(a)??a,l.vcs.branch);for(const d of l.session)d?.id&&r.set(d.id,d.title);for(const[d,f]of Object.entries(l.session_status??{})){const m=f?.type,u=m==="busy"?"busy":m==="retry"?"retry":"idle",p=t.get(d);(!p||p==="idle")&&t.set(d,u)}for(const[d,f]of Object.entries(l.permission??{}))for(const m of f??[]){if(!m?.id)continue;const u=m.sessionID||d;n.push({kind:"permission",id:m.id,sessionId:u,sessionTitle:"",label:J2(m),directory:a})}for(const[d,f]of Object.entries(l.question??{}))for(const m of f??[]){if(!m?.id)continue;const u=m.sessionID||d;n.push({kind:"question",id:m.id,sessionId:u,sessionTitle:"",label:X2(m),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},rC=()=>{const t=Sr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>Ba(o)-Ba(r)).slice(0,Dh).forEach(r=>{const o=Mr(r);o&&e.add(o)});const n=new Map;for(const r of t){if(!r?.id)continue;const o=Mr(r);if(!o||!e.has(o))continue;const a=n.get(o)??[];a.push(r.id),n.set(o,a)}return n},iC=t=>{const e=nC(),n=gm.getState().index.session,r=Sr.getState().activeSessions,o=new Map(e.titleById),a=new Map;for(const g of r)if(g?.id&&(g.title&&o.set(g.id,g.title),g.parentID)){const h=a.get(g.parentID)??[];h.push(g.id),a.set(g.parentID,h)}const c=g=>{const h=[],C=[...a.get(g)??[]],w=new Set;for(;C.length;){const S=C.pop();w.has(S)||(w.add(S),h.push(S),C.push(...a.get(S)??[]))}return h},l=xm.getState().statusById,d=g=>{const h=e.statusById.get(g);return h&&h!=="idle"?h:l.get(g)?.status??h??"idle"},f=g=>{const h=g.map(C=>d(C));return h.includes("busy")?"busy":h.includes("retry")?"retry":"idle"},m=ks.getState().projects,u=ft.getState().availableWorktreesByProject,p=r.filter(g=>g?.id&&!g.parentID).slice().sort((g,h)=>Ba(h)-Ba(g)).slice(0,Dh).map(g=>{const h=[g.id,...c(g.id)],C=Mr(g)??"";return{id:g.id,title:g.title||"Untitled session",status:f(h),branch:C?e.branchByDirectory.get(C)??"":"",unseen:h.reduce((w,S)=>w+(n.unseenCount[S]??0),0),hasError:h.some(w=>n.unseenHasError[w]??!1),directory:C,subtitle:eC(C,g,m,u,e.branchByDirectory)}}),x=e.approvals.map(g=>({...g,sessionTitle:o.get(g.sessionId)||""})),y=Ee.getState();let b=0;if(y.dockBadgeEnabled)for(const g of r){if(!g?.id||g.parentID)continue;let h=n.unseenCount[g.id]??0;h===0&&y.notifyOnSubtasks&&(h=c(g.id).reduce((C,w)=>C+(n.unseenCount[w]??0),0)),h>0&&(b+=1)}return{sessions:p,approvals:x,instanceName:t,usage:tC(),dockBadgeCount:b}},oC=()=>{i.useEffect(()=>{if(!If()||!Va())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const k=iC(r),j=JSON.stringify(k);j!==e&&(e=j,Gr("desktop_tray_update",k))};sC().then(k=>{t||(r=k,o())});const a=async()=>{const k=rC();await Promise.all([...k.entries()].map(async([j,D])=>{const O=await Jn.getSessionStatusForDirectory(j).catch(()=>null);t||O===null||wx(j,O,D)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},Y2))},l=new Map,d=()=>{if(t)return;let k;try{k=Aa()}catch{return}const j=new Set;for(const[D,O]of k.children.entries())j.add(D),l.has(D)||l.set(D,O.subscribe(()=>c()));for(const[D,O]of l)j.has(D)||(O(),l.delete(D))};let f=null;try{f=Aa().subscribeRegistry(()=>{d(),c()})}catch{}d();const m=gm.subscribe(()=>c()),u=Sr.subscribe(()=>c()),p=ks.subscribe(()=>c()),x=ft.subscribe(()=>c()),y=wn.subscribe(()=>c()),b=Ee.subscribe(()=>c()),g=xm.subscribe(()=>c());yx(Qf());const h=window.setInterval(()=>{ka()},Q2);a();const C=window.setInterval(()=>{a()},Pf),w=mn.subscribe(()=>c());mn.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:k,results:j}=mn.getState();k.length>0&&k.some(O=>!j.some(v=>v.providerId===O))&&mn.getState().fetchAllQuotas()});const S=window.setInterval(()=>{const k=mn.getState();k.autoRefresh&&k.dropdownProviderIds.length>0&&k.fetchAllQuotas()},Math.max(3e4,mn.getState().refreshIntervalMs||6e4)),N=window.setInterval(()=>{d(),o()},Pf);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(N),window.clearInterval(h),window.clearInterval(C),window.clearInterval(S),m(),u(),p(),x(),y(),b(),g(),w(),f?.();for(const k of l.values())k();l.clear()}},[]),i.useEffect(()=>{if(!If()||typeof window>"u")return;const e=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof e!="function")return;const n=o=>{o.type==="respond-permission"&&vx(o.sessionId,o.id,o.response).catch(()=>{ce.error("Failed to respond to permission request")})};let r=null;return e(q2,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{}}},[])},aC="/api/notifications/stream",lC=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),cC=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}},dC=t=>{const e=mt.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||cr()||!gc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(Pi().sse(aC));return a.onmessage=uC,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function uC(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Ee.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&lC())return;const r=cC(e);if(!r)return;Lo()?.notifications?.notifyAgentCompletion(r)}const Rf="pwa-install-toast-shown",Ef="pwa-install-toast-dismissed",fC=()=>{const t=mt.c(6),{browserTab:e}=tb(),{t:n}=bt(),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"||!gc()||!e)return;let d=null,f=null;const m=()=>{f!==null&&(ce.dismiss(f),f=null)},u=async()=>{if(!d)return;const y=d;d=null,m(),await y.prompt();const{outcome:b}=await y.userChoice;b==="accepted"&&ce.success(r.current("pwa.installPrompt.started"))},p=y=>{const b=y;if(typeof b.prompt!="function")return;b.preventDefault(),d=b;const g=Ui(),h=Vf();sb({dismissed:g.getItem(Ef),sessionShown:h.getItem(Rf),hasActiveToast:f!==null})&&(h.setItem(Rf,"true"),f=ce.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:()=>{Ui().setItem(Ef,"true"),m()}}}))},x=()=>{d=null,m(),ce.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",p),window.addEventListener("appinstalled",x),()=>{m(),window.removeEventListener("beforeinstallprompt",p),window.removeEventListener("appinstalled",x)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},mC=({open:t,onOpenChange:e})=>{const{t:n}=bt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,f]=i.useState(!1),[m,u]=i.useState(!1),[p,x]=i.useState(null),[y,b]=i.useState(!1);i.useCallback(async()=>{},[p,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const C=await Ns("/api/system/info");if(C.ok){const w=await C.json();if(typeof w.openchamberVersion=="string"&&w.openchamberVersion.trim()){a(w.openchamberVersion);return}}}catch{}a(await jx())})()},[t]),i.useEffect(()=>{if(!t)return;let h=!1;return(async()=>{try{const w=await Ns("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!w.ok)return;const S=await w.json().catch(()=>null),N=typeof S?.currentVersion=="string"?S.currentVersion.trim():"";!h&&N&&l(N)}catch{}})(),()=>{h=!0}},[t]),i.useEffect(()=>{{x(null),b(!1);return}},[t,r]);const g=o;return s.jsx(Ms,{open:t,onOpenChange:e,children:s.jsx(Es,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(Tc,{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:[g&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:g})}),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(A,{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(A,{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(A,{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")})]})})})},Bl=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},hC=(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},pC=()=>{const t=nb(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=Bl(a,"code"),l=rb(a),d=ib(a),f=Bl(a,"error"),m=Bl(a,"error_description");if(f){d&&Ns(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(m??f);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 p=await Ns(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`);if(p.ok){const x=await p.json().catch(()=>null);x?.name?.trim()&&(u={name:x.name.trim(),directory:typeof x.directory=="string"&&x.directory.trim()?x.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 Ns(`/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 Ns(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(hC(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"})})]})})},Mf=co(()=>ao(()=>import("./OnboardingScreen-DVRz82mJ.js"),__vite__mapDeps([11,1,3,4,2])).then(t=>({default:t.OnboardingScreen}))),gC=()=>{const t=mt.c(3),e=Ee(SC),n=Ee(jC);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(mC,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},xC=t=>{const e=mt.c(21),{onRetry:n,isRetrying:r}=t,{t:o}=bt();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 f;e[8]!==c||e[9]!==d?(f=s.jsxs("div",{className:"flex flex-col gap-2",children:[c,d]}),e[8]=c,e[9]=d,e[10]=f):f=e[10];let m;e[11]!==r||e[12]!==o?(m=o(r?"startup.initRecovery.retrying":"startup.initRecovery.retry"),e[11]=r,e[12]=o,e[13]=m):m=e[13];let u;e[14]!==r||e[15]!==n||e[16]!==m?(u=s.jsx(ze,{type:"button",onClick:n,disabled:r,children:m}),e[14]=r,e[15]=n,e[16]=m,e[17]=u):u=e[17];let p;return e[18]!==f||e[19]!==u?(p=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:[f,u]})}),e[18]=f,e[19]=u,e[20]=p):p=e[20],p},Ff=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",bC=()=>{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"}},yC=()=>typeof window>"u"?!1:window.location.pathname===cb,wC=t=>{const e=mt.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=qs(NC),c=ft(kC),l=ft(CC),d=Ec(),f=i.useRef(null);let m;e[0]!==n.directory?(m=Ff(n.directory),e[0]=n.directory,e[1]=m):m=e[1];const u=m;let p;e[2]!==a?(p=Ff(a),e[2]=a,e[3]=p):p=e[3];const x=p;let y,b;if(e[4]!==x||e[5]!==c||e[6]!==n.directory||e[7]!==n.sessionId||e[8]!==u||e[9]!==r||e[10]!==l||e[11]!==d?(y=()=>{if(r||u&&x!==u)return;const N=`${u}
236
- ${n.sessionId}`;f.current===N&&c===n.sessionId||(f.current=N,l(n.sessionId,n.directory),d.ensureSessionRenderable(n.sessionId,!0))},b=[x,c,n.directory,n.sessionId,u,r,l,d],e[4]=x,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]=y,e[13]=b):(y=e[12],b=e[13]),i.useEffect(y,b),u&&x!==u)return null;let g;e[14]!==o?(g=s.jsx(bm,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=g):g=e[15];let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(Tm,{}),e[16]=h):h=e[16];let C;e[17]!==n.readOnly?(C=s.jsx(ql,{readOnly:n.readOnly}),e[17]=n.readOnly,e[18]=C):C=e[18];let w;e[19]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx(ym,{}),e[19]=w):w=e[19];let S;return e[20]!==g||e[21]!==C?(S=s.jsxs(s.Fragment,{children:[g,h,C,w]}),e[20]=g,e[21]=C,e[22]=S):S=e[22],S};function vC({apis:t}){i.useEffect(()=>{Np("App:mounted"),kp()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=ss($=>$.initializeApp),n=ss($=>$.isInitialized),r=ss($=>$.isConnected),o=ss($=>$.providers.length),a=ss($=>$.agents.length),c=ss($=>$.loadProviders),l=ss($=>$.loadAgents),d=ft($=>$.error),f=ft($=>$.clearError),m=qs($=>$.currentDirectory),u=qs($=>$.setDirectory),p=qs($=>$.isSwitchingDirectory),[x,y]=i.useState(!1),b=Mi($=>$.refreshStatus),[g,h]=i.useState(()=>t.runtime.isVSCode),[C,w]=i.useState(!0),[S,N]=i.useState(!1),[k,j]=i.useState(0),[D,O]=i.useState(0),[v,M]=i.useState(!1),I=Ee($=>$.wideChatLayoutEnabled),E=Ee($=>$.mobileKeyboardMode),B=i.useMemo(()=>cr(),[]),P=yc($=>$.setPlanModeEnabled),[W,_]=i.useState(()=>Sd()),[V,R]=i.useState(()=>{const $=jd();return $!==null?Nd({isDesktopShell:!0,bootOutcome:$}):null}),ne=i.useRef(!1),ie=i.useMemo(()=>bC(),[]),J=!ie||C,U=i.useMemo(()=>yC(),[]);i.useEffect(()=>(kd(x),()=>{kd(!1)}),[x]),i.useEffect(()=>{Cp(E)},[E]),i.useEffect(()=>{h(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>Hf($=>{ob($),O(K=>K+1),N(!1),j(K=>K+1)}),[]);const ee=Ud($=>{const K=Cd();return Object.values($.runsByOriginalSessionID).filter(q=>q.status==="running"&&q.runtimeKey===K).map(q=>`${q.originalSessionID}:${q.phase}:${q.lastForwardedMessageID??""}:${q.expectedAssistantParentID??""}`).sort().join("|")});i.useEffect(()=>{if(ie)return;const $=Cd(),K=Object.values(Ud.getState().runsByOriginalSessionID).filter(q=>q.status==="running"&&q.runtimeKey===$);for(const q of K)Nx(q.originalSessionID)},[ee,ie,D]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",I),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[I]),i.useEffect(()=>(Ad(t),()=>Ad(null)),[t]),i.useEffect(()=>{ie||b(t.github,{force:!0})},[t.github,ie,b]),kx();const ae=W==="valid",de=V?.screen==="main";i.useEffect(()=>{if(!Ap({isDesktopShell:B,isInitialized:n,bootOutcomeKnown:ae,bootViewIsMain:de}))return;const $=setTimeout(()=>{const K=document.getElementById("initial-loading");K&&(K.classList.add("fade-out"),setTimeout(()=>{K.remove()},300))},150);return()=>clearTimeout($)},[B,n,ae,de]),i.useEffect(()=>{if(!B||W!=="malformed")return;const $=document.getElementById("initial-loading");$&&($.textContent="Desktop startup failed — please restart the app.")},[B,W]),i.useEffect(()=>{if(B)return;const $=setTimeout(()=>{const K=document.getElementById("initial-loading");K&&!n&&(K.classList.add("fade-out"),setTimeout(()=>{K.remove()},300))},5e3);return()=>clearTimeout($)},[B,n]),i.useEffect(()=>{let $=!1;return(async()=>{const q=await Ns("/health",{method:"GET"}).catch(()=>null);if(!q||!q.ok||$)return;const me=await q.json().catch(()=>null);if(!me||$)return;const je=me.planModeExperimentalEnabled;P(je===!0||je===1||je==="1"||je==="true")})(),()=>{$=!0}},[P]),i.useEffect(()=>{g||e()},[e,g]),i.useEffect(()=>{if(g||n)return;let $=!0,K,q=0;const me=10,je=1e3,Oe=async()=>{if(!$)return;if(q>=me){N(!0);return}const Be=ss.getState();if(Be.isInitialized){N(!1);return}q+=1,await Be.initializeApp();const Fe=ss.getState();if(!$)return;if(Fe.isInitialized){N(!1);return}if(q>=me){N(!0);return}const ue=Math.min(je*Math.pow(2,q-1),16e3);K=setTimeout(Oe,ue)};return K=setTimeout(Oe,je),()=>{$=!1,K&&clearTimeout(K)}},[k,n,g]),i.useEffect(()=>{n&&N(!1)},[n]),i.useEffect(()=>{if(!S)return;const $=document.getElementById("initial-loading");$&&($.classList.add("fade-out"),setTimeout(()=>{$.remove()},300))},[S]),i.useEffect(()=>{if(g||!r||o>0&&a>0)return;let $=!0,K=0;const q=15,me=async()=>{const Oe=ss.getState();if(!(Oe.providers.length>0&&Oe.agents.length>0))try{Oe.providers.length===0&&await c({source:"startupRecovery"}),ss.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};me();const je=setInterval(()=>{if($){if(++K>=q){clearInterval(je);return}me()}},2e3);return()=>{$=!1,clearInterval(je)}},[r,g,l,c,o,a]),i.useEffect(()=>{p||g||r&&Jn.setDirectory(m)},[m,p,r,g]),i.useEffect(()=>{if(!ie||typeof window>"u")return;const $=me=>{const je=me?.visible===!0;w(je)},K=me=>{if(me.origin!==window.location.origin)return;const je=me.data;je?.type==="openchamber:embedded-visibility"&&$(je.payload)},q=window;return q.__openchamberSetEmbeddedVisibility=$,window.addEventListener("message",K),()=>{window.removeEventListener("message",K),q.__openchamberSetEmbeddedVisibility===$&&delete q.__openchamberSetEmbeddedVisibility}},[ie]),i.useEffect(()=>{!ie?.directory||g||m!==ie.directory&&u(ie.directory,{showOverlay:!1})},[m,ie,g,u]),i.useEffect(()=>{if(!ie||typeof window>"u")return;const $=K=>{K.storageArea===window.localStorage&&K.key==="ui-store"&&Ee.persist.rehydrate()};return window.addEventListener("storage",$),()=>{window.removeEventListener("storage",$)}},[ie]),i.useEffect(()=>{if(typeof window>"u")return;const $=K=>{const q=K.detail,me=typeof q?.sessionId=="string"?q.sessionId.trim():"";if(!me)return;const je=typeof q?.directory=="string"&&q.directory.trim().length>0?q.directory.trim():null;Ee.getState().setActiveMainTab("chat"),ft.getState().setCurrentSession(me,je)};return window.addEventListener("openchamber:open-session",$),()=>window.removeEventListener("openchamber:open-session",$)},[]),i.useEffect(()=>{if(typeof window>"u")return;const $=()=>{const K=qs.getState().currentDirectory,{activeProjectId:q,projects:me}=ks.getState(),je=me.find(Oe=>Oe.id===q)??null;Gr("desktop_open_draft_mini_chat_window",{directory:K||je?.path||"",projectId:je?.id??null})};return window.addEventListener("openchamber:open-mini-chat",$),()=>window.removeEventListener("openchamber:open-mini-chat",$)},[]),i.useEffect(()=>{if(typeof window>"u")return;const $=()=>{const K=ft.getState().currentSessionId;K&&lm(K)};return window.addEventListener("focus",$),()=>window.removeEventListener("focus",$)},[]),i.useEffect(()=>{if(typeof window>"u")return;const $=K=>{const q=K.detail,me=typeof q?.directory=="string"&&q.directory.trim().length>0?q.directory.trim():null,je=typeof q?.projectId=="string"&&q.projectId.trim().length>0?q.projectId.trim():null;Ee.getState().setActiveMainTab("chat"),Ee.getState().setSessionSwitcherOpen(!1),ft.getState().openNewSessionDraft({selectedProjectId:je,directoryOverride:me,preserveDirectoryOverride:!!me})};return window.addEventListener("openchamber:open-draft-session",$),()=>window.removeEventListener("openchamber:open-draft-session",$)},[]),i.useEffect(()=>{if(typeof window>"u")return;const $=K=>{const q=K.detail,me=typeof q?.projectPath=="string"?q.projectPath.trim():"";if(!me)return;const je=ks.getState(),Oe=je.projects.find(Be=>Be.path===me);Oe?je.setActiveProject(Oe.id):je.addProject(me)};return window.addEventListener("openchamber:open-project",$),()=>window.removeEventListener("openchamber:open-project",$)},[]),i.useEffect(()=>{typeof window>"u"||!n||p||ne.current||(ne.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,p]),Cx({enabled:J}),dC({enabled:J}),fC(),Ax(),ab();const ye=i.useCallback(()=>{y($=>!$)},[]);K2(ye),oC(),i.useEffect(()=>{if(ie)return;const $=K=>{wc(K)&&K.shiftKey&&!K.altKey&&(K.code==="KeyD"||K.key.toLowerCase()==="d")&&(K.preventDefault(),y(me=>!me))};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[ie]),i.useEffect(()=>{ie||d&&setTimeout(()=>f(),5e3)},[f,ie,d]),i.useEffect(()=>{if(!B||W!=="not-injected")return;let $=!1,K=0;const q=200,me=2e3,je=50,Oe=()=>{if($)return;K++;const Be=Sd();if(Be!=="not-injected"){if($=!0,_(Be),Be==="valid"){const ue=jd();ue&&R(Nd({isDesktopShell:!0,bootOutcome:ue}))}return}const Fe=Math.min(q*Math.pow(1.1,K),me);if(K>=je){const ue=document.getElementById("initial-loading");ue&&!ue.textContent?.includes("taking longer")&&(ue.textContent="Desktop startup is taking longer than expected...")}window.setTimeout(Oe,Fe)};return window.setTimeout(Oe,q),()=>{$=!0}},[B,W]);const se=i.useCallback(async()=>{if(Dp({isDesktopShell:cr(),isDesktopLocalOriginActive:Zi()})){await Tp();return}window.location.reload()},[]),we=i.useCallback(async()=>{if(!v){N(!1),M(!0);try{await ss.getState().initializeApp()}finally{M(!1)}ss.getState().isInitialized||j($=>$+1)}},[v]),fe=$=>{if($.screen==="recovery")return $.variant};if(B&&V&&V.screen!=="main"){if(V.screen==="chooser")return s.jsx(Xs,{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(Mf,{mode:"first-launch",onCliAvailable:se,onChooseRemote:()=>{}})})})});const $=fe(V),K=V.screen==="recovery"&&"url"in V?V.url:void 0;return s.jsx(Xs,{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(Mf,{mode:"recovery",recoveryVariant:$,recoveryHostUrl:K,recoveryHostLabel:void 0,onCliAvailable:se})})})})}if(ie)return s.jsx(Xs,{children:s.jsx(Hd,{sdk:Jn.getSdkClient(),directory:m||"",children:s.jsx(Gd,{apis:t,children:s.jsx(Kd,{delayDuration:300,skipDelayDuration:150,children:s.jsx("div",{className:"h-full text-foreground bg-background",children:s.jsx(wC,{embeddedSessionChat:ie,isVSCodeRuntime:g,embeddedBackgroundWorkEnabled:J})})})})},D)});if(U)return s.jsx(Xs,{children:s.jsx(pC,{})});if(S&&!n&&!g&&!ie)return s.jsx(Xs,{children:s.jsx(xC,{onRetry:()=>{we()},isRetrying:v})});const Me=!n&&!B;return s.jsx(Xs,{children:s.jsx(Hd,{sdk:Jn.getSdkClient(),directory:m||"",children:s.jsx(Gd,{apis:t,children:s.jsx(Vy,{children:s.jsx(Kd,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:B?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(bm,{embeddedBackgroundWorkEnabled:J}),s.jsx(Tm,{}),s.jsx(I2,{}),s.jsx(ym,{}),!Me&&s.jsxs(s.Fragment,{children:[s.jsx(lb,{}),s.jsx(gC,{}),x&&s.jsx(M2,{onClose:()=>y(!1)})]})]})})})})},D)})}function SC(t){return t.isAboutDialogOpen}function jC(t){return t.setAboutDialogOpen}function NC(t){return t.currentDirectory}function kC(t){return t.currentSessionId}function CC(t){return t.setCurrentSession}const AC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();Dx();Pp().then(()=>{Promise.all([Ip(),Tx()]).catch(t=>{console.error("[main] settings init failed:",t)}),Px(),Ix(),Rx()}).catch(t=>{console.error("[main] appearance init failed:",t)});const Th=document.getElementById("root");if(!Th)throw new Error("Root element not found");dp.createRoot(Th).render(s.jsx(Xe.StrictMode,{children:s.jsx(Ex,{children:s.jsx(Mx,{children:s.jsx(Fx,{children:s.jsx(Ox,{children:s.jsx(vC,{apis:AC})})})})})}));const OC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{y1 as D,j2 as M,OC as m,Vs as u};