@openchamber/web 1.14.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-CIaZCGUT.js → DiagramView-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-Bsbr3i8y.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-CLm6tF5n.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-DF7-jlam.js → TerminalView-D_9BAjtv.js} +3 -3
  12. package/dist/assets/es-cjUissX4.js +15 -0
  13. package/dist/assets/fr-DqbXnTdK.js +13 -0
  14. package/dist/assets/index-Dg0nmvQU.css +1 -0
  15. package/dist/assets/index-ltrmNGAf.js +2 -0
  16. package/dist/assets/ja-Cetyq6Eg.js +15 -0
  17. package/dist/assets/ko-DtunWisP.js +15 -0
  18. package/dist/assets/main-BC0m8s1v.js +236 -0
  19. package/dist/assets/main-DzNa8r0N.js +2 -0
  20. package/dist/assets/miniChat-BRYDE-Se.js +2 -0
  21. package/dist/assets/mobile-C3QJVA97.js +2 -0
  22. package/dist/assets/pl-DctGLgve.js +15 -0
  23. package/dist/assets/pt-BR-CXPhf78S.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
  25. package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
  27. package/dist/assets/uk-Bdrc-kqF.js +15 -0
  28. package/dist/assets/{useAppFontEffects-DTO332li.js → useAppFontEffects-DzBg8hrC.js} +132 -116
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
  31. package/dist/assets/zh-TW-CoqiQING.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +157 -6
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/apns-runtime.js +9 -16
  41. package/server/lib/opencode/bootstrap-runtime.js +10 -0
  42. package/server/lib/opencode/core-routes.js +247 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/feature-routes-runtime.js +10 -0
  45. package/server/lib/opencode/models-metadata.js +61 -0
  46. package/server/lib/opencode/network-runtime.js +14 -1
  47. package/server/lib/opencode/network-runtime.test.js +29 -9
  48. package/server/lib/opencode/openchamber-routes.js +7 -40
  49. package/server/lib/opencode/proxy.js +47 -6
  50. package/server/lib/opencode/settings-helpers.js +16 -0
  51. package/server/lib/opencode/settings-helpers.test.js +11 -0
  52. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  53. package/server/lib/opencode/shutdown-runtime.js +2 -0
  54. package/server/lib/package-manager.js +18 -5
  55. package/server/lib/relay/DOCUMENTATION.md +78 -0
  56. package/server/lib/relay/cross-compat.test.js +135 -0
  57. package/server/lib/relay/e2ee.js +341 -0
  58. package/server/lib/relay/e2ee.test.js +124 -0
  59. package/server/lib/relay/host-client.js +389 -0
  60. package/server/lib/relay/host-client.test.js +280 -0
  61. package/server/lib/relay/identity.js +73 -0
  62. package/server/lib/relay/identity.test.js +78 -0
  63. package/server/lib/relay/service.js +247 -0
  64. package/server/lib/relay/signing-key.js +50 -0
  65. package/server/lib/relay/tunnel-codec.js +373 -0
  66. package/server/lib/relay/tunnel-codec.test.js +58 -0
  67. package/server/lib/relay/tunnel-host.js +462 -0
  68. package/server/lib/session-assist/DOCUMENTATION.md +66 -0
  69. package/server/lib/session-assist/runtime.js +394 -0
  70. package/server/lib/small-model/DOCUMENTATION.md +78 -0
  71. package/server/lib/small-model/call.js +380 -0
  72. package/server/lib/small-model/catalog.js +13 -0
  73. package/server/lib/small-model/index.js +167 -0
  74. package/server/lib/small-model/resolve.js +131 -0
  75. package/server/lib/small-model/resolve.test.js +197 -0
  76. package/server/lib/small-model/routes.js +44 -0
  77. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  78. package/server/lib/ui-auth/ui-auth.js +10 -0
  79. package/server/opencode-proxy.test.js +38 -0
  80. package/dist/assets/MarkdownRendererImpl-DWgOeIpO.js +0 -7
  81. package/dist/assets/OnboardingScreen-3IAKkM5k.js +0 -1
  82. package/dist/assets/SettingsWindow-K-ErjehP.js +0 -1
  83. package/dist/assets/es-DQIFCjC2.js +0 -15
  84. package/dist/assets/fr-CJRav0LS.js +0 -13
  85. package/dist/assets/index-5eUDDB6w.js +0 -2
  86. package/dist/assets/index-CgpE7F8T.css +0 -1
  87. package/dist/assets/ja-CjAaqvHO.js +0 -15
  88. package/dist/assets/ko-BEbFxvrd.js +0 -15
  89. package/dist/assets/main-C2put7uQ.js +0 -2
  90. package/dist/assets/main-DuQEoz31.js +0 -214
  91. package/dist/assets/miniChat-o3AAQ-8r.js +0 -2
  92. package/dist/assets/mobile-X0421aWz.js +0 -2
  93. package/dist/assets/pl-D4kzai5T.js +0 -15
  94. package/dist/assets/pt-BR-9Sk3esQZ.js +0 -15
  95. package/dist/assets/renderElectronMiniChatApp-CdDj0ms1.js +0 -2
  96. package/dist/assets/renderMobileApp-cZ_HZKSe.js +0 -16
  97. package/dist/assets/runtimeEndpointReset-BYLVW9e7.js +0 -167
  98. package/dist/assets/uk-DW_dTfoO.js +0 -15
  99. package/dist/assets/zh-CN-r2_euV7U.js +0 -15
  100. package/dist/assets/zh-TW-BdPx3NWh.js +0 -15
@@ -1,214 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalView-DF7-jlam.js","assets/vendor-.bun-C6iL44L9.js","assets/useAppFontEffects-DTO332li.js","assets/index-5eUDDB6w.js","assets/index-CgpE7F8T.css","assets/runtimeEndpointReset-BYLVW9e7.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-CLm6tF5n.js","assets/DiagramView-CIaZCGUT.js","assets/SettingsWindow-K-ErjehP.js","assets/MultiRunWindow-Bsbr3i8y.js","assets/OnboardingScreen-3IAKkM5k.js"])))=>i.map(i=>d[i]);
2
- import{j as s,b as ft,a as ro,R as i,d as Mf,p as uc,I as Vh,H as Xe,L as Ff,u as xa,k as yo,m as ba,D as ya,o as wa,S as Vl,v as $l,t as fc,C as mc,N as zl,O as $h,T as zh,W as Wh,X as Uh,Y as ni,$ as Hh,a0 as Gh,F as Kh,a1 as qh,a2 as Yh,a3 as Qh,a4 as Lf,a5 as Jh,a6 as Xh,a7 as Wl,a8 as Zh,s as ep,l as tp,a9 as fd,aa as md,ab as hd,ac as sp,ad as np,ae as rp,af as ip,ag as op,ah as ap,_ as io,ai as pd,aj as gd,ak as xd,G as lp}from"./vendor-.bun-C6iL44L9.js";import{k as hc,l as ur,m as Ji,n as bd,p as cp,q as va,t as Of,v as dp,h as Cs,d as Lo,u as Ee,w as up,x as Ba,y as Kr,a as Ur,z as Hr,A as Ul,B as fp,C as mp,R as yd,D as wd,b as Xs,E as hp,F as pp,G as Bf,H as _f,I as pc,o as Jn,J as gp,g as ki,K as xp,r as gc,L as bp,M as xc,f as Vf,N as yp,O as wp,P as zi,Q as na,S as ra,T as vp,U as jp,V as Sp,W as vd,X as jd,Y as Sd,Z as Nd,_ as Np,$ as kd,e as Cd,a0 as kp,a1 as Cp,a2 as Ap,i as Dp,j as Ip}from"./index-5eUDDB6w.js";import{c as kt,p as Pe,ax as bs,I,w as fr,t as le,ay as tn,az as Er,aA as sn,aB as nn,d as Xn,aC as Mr,aD as Di,aE as Ad,aF as Et,aG as Mt,aH as Ft,aI as Pp,aj as Do,aJ as ja,aK as ri,ak as Io,al as $f,ac as bc,aL as zf,aM as Tp,X as ss,D as ut,aN as Rp,ae as Wf,u as jr,C as yc,b as Ns,Y as Ii,aO as Uf,aP as Hf,aQ as Sa,aR as Gf,aS as Kf,aT as qf,aU as Yf,aV as Ep,aW as Mp,Z as wc,aX as _a,aY as ii,aZ as vc,a_ as ia,a2 as en,a$ as Fp,b0 as Qf,b1 as Lp,b2 as Jf,b3 as jc,b4 as Gs,b5 as Us,B as $e,b6 as Vs,b7 as $s,b8 as ci,b9 as Op,ba as Bp,bb as zo,bc as En,bd as Xf,be as Zf,a9 as Sc,bf as _p,bg as Dd,bh as Id,bi as Ni,q as jn,bj as Pi,bk as Xi,bl as Vp,bm as $p,bn as zp,bo as Wp,bp as Va,bq as $a,br as za,bs as Wa,bt as oi,bu as li,bv as Up,bw as Hp,bx as ln,by as Gp,bz as Kp,bA as qp,bB as Yp,bC as Qp,n as Ci,bD as Nc,bE as Jp,bF as Xp,bG as Zp,bH as eg,bI as tg,bJ as sg,bK as ng,bL as $n,bM as zn,bN as Wn,bO as Cn,bP as Un,bQ as Ms,bR as rg,A as Po,M as Ua,S as Ha,bS as ig,bT as or,bU as og,e as di,g as kc,f as Ga,bV as ag,bW as em,bX as lg,bY as cg,h as Cc,bZ as dg,i as vn,b_ as Ka,aa as Tr,m as ug,b$ as fg,c0 as al,c1 as mg,c2 as hg,F as Gr,c3 as Ac,c4 as qa,c5 as pn,c6 as Ti,o as Zi,c7 as tm,c8 as pg,c9 as gg,ca as xg,cb as Pd,cc as bg,x as qr,y as Td,z as Rd,cd as Ed,ce as sm,cf as Md,cg as Fd,ch as nm,ci as yg,cj as rm,v as Ld,J as wg,ck as ll,cl as Dc,cm as vg,cn as jg,co as Sg,cp as Oo,cq as Ng,cr as cl,cs as im,ct as om,cu as Ic,cv as kg,a1 as Pc,cw as am,cx as Wo,cy as Cg,r as Rr,cz as Ag,cA as lm,cB as Dg,cC as Ig,cD as Od,cE as cm,cF as dm,cG as um,H as Tc,P as Ya,K as Qa,O as Na,cH as ka,cI as Bn,L as Pg,N as Tg,cJ as Rg,cK as Hl,cL as Eg,cM as Mg,cN as Fg,cO as Bd,cP as Lg,cQ as Og,cR as Rc,cS as fm,cT as Bg,cU as _g,cV as Vg,cW as $g,cX as _d,cY as Vd,cZ as zg,c_ as Wg,c$ as Ug,d0 as Hg,d1 as Gg,d2 as Kg,Q as qg,d3 as $d,d4 as Yg,d5 as mm,R as Qg,d6 as Jg,E as Xg,G as Zg,d7 as ex,d8 as tx,d9 as sx,da as nx,db as rx,dc as ix,dd as ox,de as ax,df as lx,dg as Ca,dh as cx,di as zd,dj as dx,dk as ux,dl as fx,dm as oo,dn as mx,dp as Wd,dq as hx,dr as px,ds as gx,dt as xx,a as hm,du as pm,dv as bx,dw as yx,dx as wx,dy as oa,ag as vx,dz as jx,dA as Ud,dB as Sx,_ as Nx,$ as kx,a0 as Cx,a3 as Hd,a4 as Gd,a5 as Kd,a6 as gm,a7 as xm,as as Ax,at as Dx,au as Ix,av as Px,aw as Tx,ao as Rx,ap as Ex,aq as Mx,ar as Fx}from"./useAppFontEffects-DTO332li.js";import{I as qd,o as Lx,p as Yd,q as Ox,s as Qd,t as Jr,v as Bx,w as dl,x as To,U as Aa,y as Da,z as eo,B as Bo,E as to,k as bm,M as ym,i as gn,j as _x,Q as wm,F as Vx,G as $x,H as zx,l as Gl,J as vm,P as jm,K as Wx,L as Ux,C as Hx,a as Gx,R as Ec,T as Sm,V as Mc,W as Fc,X as Lc,Y as Nm,Z as km,_ as Kl,$ as Cm,a0 as ql,a1 as aa,a2 as Kx,a3 as qx,e as wo,N as Yx,D as Qx,u as Jx,n as Xx,m as Yl,a4 as Zx,a5 as eb,g as tb,a6 as sb,a7 as nb,r as rb,c as ib,O as Am,d as ob,a8 as ab}from"./runtimeEndpointReset-BYLVW9e7.js";import{S as lb,C as cb,W as db,g as Oc,r as ub,n as as,i as Ro,d as so,c as Gi,a as Jd,b as fb,e as vo,f as Dm,h as mb,j as hb,u as ul}from"./SessionSwitcherDropdown-CLm6tF5n.js";function Im(t){const{drafts:e,editingDraftId:n,commentText:r,onTextChange:o,selection:a,isDragging:c,fileLabel:l,newWidgetId:d,mapDraftToRange:u,onSave:m,onCancel:f,onEdit:p,onDelete:y}=t,g=[];for(const b of e){const x=u(b);if(b.id===n){g.push({afterLine:x.end,id:`edit-${b.id}`,content:s.jsx(qd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:x,isEditing:!0,onSave:m,onCancel:f},`edit-${b.id}`)});continue}g.push({afterLine:x.end,id:`card-${b.id}`,content:s.jsx(Lx,{draft:b,onEdit:()=>p(b),onDelete:()=>y(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)};g.push({afterLine:b.end,id:d,content:s.jsx(qd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:b,isEditing:!1,onSave:m,onCancel:f},d)})}return g}function Xd(t){const e=ft.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 u;e[9]===Symbol.for("react.memo_cache_sentinel")?(u=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]=u):u=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:u}),e[10]=n,e[11]=r,e[12]=d,e[13]=m):m=e[13],m}const ai=[{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"}],Ql="finder",Jl=new Set(["finder","terminal"]),Bc=t=>typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32"&&t.id==="finder"?{...t,label:"Explorer",appName:"File Explorer"}:t,Xl=t=>{if(!t)return null;const e=ai.find(n=>n.id===t)??null;return e?Bc(e):null},fl=()=>ai.filter(t=>Jl.has(t.id)).map(t=>({...Bc(t)})),pb=()=>{if(typeof window>"u")return Ql;const t=window.localStorage.getItem("openInAppId");return t&&Xl(t)?t:Ql};let ml=!1,Bi=!1,Xr=!1,Zr=0,jo=null;const Zd=()=>{jo&&(clearTimeout(jo),jo=null)},wr=ro()((t,e)=>({selectedAppId:pb(),availableApps:fl(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(ml||typeof window>"u")return;ml=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:fl(),hasLoadedApps:u});return}const m=new Set(d.map(g=>g.name)),f=new Map(d.map(g=>[g.name,g.iconDataUrl??void 0])),y=ai.filter(g=>m.has(g.appName)||Jl.has(g.id)).map(g=>({...Bc(g),iconDataUrl:f.get(g.appName)}));t({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!ur()||!Ji()||Bi||e().hasLoadedApps&&!d)return;const m=ai.map(f=>f.appName);Zd(),Bi=!0,Xr=!1,t({isScanning:!0});try{const{apps:f,success:p,hasCache:y,isCacheStale:g}=await bd(m,d),b=p&&!y&&f.length===0&&Zr<3;if(t({isCacheStale:y?g:!1}),n(f,p?!b:!1),p){if(b){const h=[800,1600,3200][Zr]??3200;Zr+=1,Xr=!0,jo=setTimeout(()=>{r()},h);return}Zr=0,Xr=!1;return}if(Zr<3){const h=[1e3,3e3,7e3][Zr]??7e3;Zr+=1,Xr=!0,jo=setTimeout(()=>{r()},h)}}finally{Bi=!1,Xr||t({isScanning:!1})}};r();const o=d=>{const u=d.detail,m=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Xl(u.openInAppId)?u.openInAppId:null;m&&(window.localStorage.setItem("openInAppId",m),t({selectedAppId:m}))},a=()=>{r()},c=d=>{const u=d.detail;Array.isArray(u)&&(Zr=3,Xr=!1,t({isScanning:!1,isCacheStale:!1}),n(u))};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(),!ur()||!Ji()||Bi||e().hasLoadedApps&&!n)return;const o=ai.map(a=>a.appName);Zd(),n&&t({hasLoadedApps:!1}),Bi=!0,Xr=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await bd(o,n),d=new Set(a.map(p=>p.name)),u=new Map(a.map(p=>[p.name,p.iconDataUrl??void 0])),f=ai.filter(p=>d.has(p.appName)||Jl.has(p.id)).map(p=>({...p,iconDataUrl:u.get(p.appName)}));t({availableApps:f.length>0?f:fl(),hasLoadedApps:f.length>0,isCacheStale:c?l:!1})}finally{Bi=!1,Xr||t({isScanning:!1})}},selectApp:async n=>{Xl(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await hc({openInAppId:n}))}})),gb="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",xb="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"?gb:t.id==="terminal"?xb:void 0}),eu=t=>{const e=ft.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,u=r||o;if(u&&!a){let p;e[2]===Symbol.for("react.memo_cache_sentinel")?(p=()=>c(!0),e[2]=p):p=e[2];let y;return e[3]!==u?(y=s.jsx("img",{src:u,alt:"",className:"h-4 w-4 rounded-sm",onError:p}),e[3]=u,e[4]=y):y=e[4],y}let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=Pe("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 f;return e[6]!==d?(f=s.jsx("span",{className:m,children:d}),e[6]=d,e[7]=f):f=e[7],f},bb=t=>{const e=ft.c(75),{directory:n,className:r}=t,{t:o}=kt(),a=wr(yb),c=wr(wb),l=wr(vb),d=wr(jb),u=wr(Sb),m=wr(Nb),f=wr(kb);let p,y;e[0]!==u?(p=()=>{u()},y=[u],e[0]=u,e[1]=p,e[2]=y):(p=e[1],y=e[2]),i.useEffect(p,y);const g=ur()&&Ji();let b;e:{let ke;e[3]!==c||e[4]!==a?(ke=c.find(O=>O.id===a)??c.find(Cb)??c[0]??ai[0],e[3]=c,e[4]=a,e[5]=ke):ke=e[5];const Y=ke;if(Y){let O;e[6]!==Y?(O=hl(Y),e[6]=Y,e[7]=O):O=e[7],b=O;break e}let ge;e[8]===Symbol.for("react.memo_cache_sentinel")?(ge=hl(ai[0]),e[8]=ge):ge=e[8],b=ge}const x=b;if(!g||!n||c.length===0)return null;let h;e[9]!==n?(h=async ke=>{await cp(n,ke.id,ke.appName)||await va(n,ke.appName)},e[9]=n,e[10]=h):h=e[10];const C=h;let w;e[11]!==C||e[12]!==f?(w=async ke=>{await f(ke.id),await C(ke)},e[11]=C,e[12]=f,e[13]=w):w=e[13];const v=w;let S;e[14]!==n||e[15]!==o?(S=async()=>{(await fr(n)).ok&&le.success(o("openInApp.toast.pathCopied"))},e[14]=n,e[15]=o,e[16]=S):S=e[16];const k=S;let j;e[17]!==r?(j=Pe("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 A;e[19]!==C||e[20]!==x?(A=()=>{C(x)},e[19]=C,e[20]=x,e[21]=A):A=e[21];const D=d&&"animate-pulse";let N;e[22]!==D?(N=Pe("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",D),e[22]=D,e[23]=N):N=e[23];let B;e[24]!==x.label||e[25]!==o?(B=o("openInApp.actions.openInAria",{app:x.label}),e[24]=x.label,e[25]=o,e[26]=B):B=e[26];let T;e[27]!==x.fallbackIconDataUrl||e[28]!==x.iconDataUrl||e[29]!==x.label?(T=s.jsx(eu,{label:x.label,iconDataUrl:x.iconDataUrl,fallbackIconDataUrl:x.fallbackIconDataUrl}),e[27]=x.fallbackIconDataUrl,e[28]=x.iconDataUrl,e[29]=x.label,e[30]=T):T=e[30];let E;e[31]!==N||e[32]!==B||e[33]!==T||e[34]!==A?(E=s.jsx("button",{type:"button",onClick:A,className:N,"aria-label":B,children:T}),e[31]=N,e[32]=B,e[33]=T,e[34]=A,e[35]=E):E=e[35];let _;e[36]===Symbol.for("react.memo_cache_sentinel")?(_=Pe("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]=_):_=e[36];let R;e[37]!==o?(R=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=R):R=e[38];let $;e[39]===Symbol.for("react.memo_cache_sentinel")?($=s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=$):$=e[39];let V;e[40]!==R?(V=s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:_,"aria-label":R,children:$})}),e[40]=R,e[41]=V):V=e[41];let z;e[42]!==k?(z=()=>{k()},e[42]=k,e[43]=z):z=e[43];let F;e[44]===Symbol.for("react.memo_cache_sentinel")?(F=s.jsx(I,{name:"file-copy",className:"h-4 w-4"}),e[44]=F):F=e[44];let ne;e[45]!==o?(ne=o("openInApp.actions.copyPath"),e[45]=o,e[46]=ne):ne=e[46];let te;e[47]!==ne?(te=s.jsx("span",{className:"typography-ui-label text-foreground",children:ne}),e[47]=ne,e[48]=te):te=e[48];let q;e[49]!==z||e[50]!==te?(q=s.jsxs(bs,{className:"flex items-center gap-2",onClick:z,children:[F,te]}),e[49]=z,e[50]=te,e[51]=q):q=e[51];let H;e[52]===Symbol.for("react.memo_cache_sentinel")?(H=s.jsx(Er,{}),e[52]=H):H=e[52];let X;if(e[53]!==c||e[54]!==v||e[55]!==x.id){let ke;e[57]!==v||e[58]!==x.id?(ke=Y=>{const ge=hl(Y);return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{v(Y)},children:[s.jsx(eu,{label:Y.label,iconDataUrl:Y.iconDataUrl,fallbackIconDataUrl:ge.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Y.label}),x.id===Y.id?s.jsx(I,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},Y.id)},e[57]=v,e[58]=x.id,e[59]=ke):ke=e[59],X=c.map(ke),e[53]=c,e[54]=v,e[55]=x.id,e[56]=X}else X=e[56];let oe;e[60]!==l||e[61]!==m||e[62]!==o?(oe=l?s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{m(!0)},children:[s.jsx(I,{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]=oe):oe=e[63];let ue;e[64]!==q||e[65]!==X||e[66]!==oe?(ue=s.jsxs(sn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[q,H,X,oe]}),e[64]=q,e[65]=X,e[66]=oe,e[67]=ue):ue=e[67];let Se;e[68]!==V||e[69]!==ue?(Se=s.jsxs(nn,{children:[V,ue]}),e[68]=V,e[69]=ue,e[70]=Se):Se=e[70];let Z;return e[71]!==E||e[72]!==Se||e[73]!==j?(Z=s.jsxs("div",{className:j,children:[E,Se]}),e[71]=E,e[72]=Se,e[73]=j,e[74]=Z):Z=e[74],Z};function yb(t){return t.selectedAppId}function wb(t){return t.availableApps}function vb(t){return t.isCacheStale}function jb(t){return t.isScanning}function Sb(t){return t.initialize}function Nb(t){return t.loadInstalledApps}function kb(t){return t.selectApp}function Cb(t){return t.id===Ql}const Ab=1e6,Db="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 Pn(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),_s=ro()(Mf(uc((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Pn(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=Pn(n);return e().sessions.get(r)},getActiveTab:n=>{const r=Pn(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=Pn(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}`,f=gl(o,m);return l?c.set(r,{...l,tabs:[...l.tabs,f]}):c.set(r,xl(f)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Pn(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=Pn(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),u=d.get(a);if(!u)return l;const m=br(u,r);if(m<0||u.tabs[m]?.label===c)return l;const f=[...u.tabs];return f[m]={...f[m],label:c},d.set(a,{...u,tabs:f}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=o?.trim()||null;if(d.tabs[u]?.iconKey===m)return c;const f=[...d.tabs];return f[u]={...f[u],iconKey:m},l.set(a,{...d,tabs:f}),{sessions:l}})},closeTab:async(n,r)=>{const o=Pn(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await dp(l)}catch{}t(d=>{const u=new Map(d.sessions),m=u.get(o);if(!m)return d;const f=br(m,r);if(f<0)return d;const p=m.tabs.filter(x=>x.id!==r),y=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,x])=>!(x.directory===o&&x.tabId===r))),g=Object.keys(y).length!==Object.keys(d.projectActionRuns).length;if(p.length===0){const x=`tab-${d.nextTabId}`,h=gl(x,"Terminal");return u.set(o,xl(h)),{sessions:u,nextTabId:d.nextTabId+1,...g?{projectActionRuns:y}:{}}}let b=m.activeTabId;return m.activeTabId===r&&(b=p[Math.min(f,p.length-1)]?.id??p[0]?.id??null),u.set(o,{...m,tabs:p,activeTabId:b}),{sessions:u,...g?{projectActionRuns:y}:{}}})},setTabSessionId:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=d.tabs[u],f=o!==null&&m.terminalSessionId!==o,p=o?"running":m.terminalSessionId?"exited":m.lifecycle,y={...m,terminalSessionId:o,lifecycle:p,isConnecting:!1,...f?{bufferChunks:[],bufferLength:0}:{}},g=[...d.tabs];return g[u]=y,l.set(a,{...d,tabs:g}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=[...d.tabs];return m[u]={...m[u],lifecycle:o,isConnecting:!1},l.set(a,{...d,tabs:m}),{sessions:l}})},setConnecting:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=[...d.tabs];return m[u]={...m[u],isConnecting:o},l.set(a,{...d,tabs:m}),{sessions:l}})},appendToBuffer:(n,r,o)=>{if(!o)return;const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=d.tabs[u],f=c.nextChunkId,p={id:f,data:o},y=[...m.bufferChunks,p];let g=m.bufferLength+o.length;for(;g>Ab&&y.length>1;){const x=y.shift();if(!x)break;g-=x.data.length}const b=[...d.tabs];return b[u]={...m,bufferChunks:y,bufferLength:g},l.set(a,{...d,tabs:b}),{sessions:l,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=Pn(n);t(l=>{const d=new Map(l.sessions),u=d.get(c);if(!u)return l;const m=br(u,r);if(m<0)return l;const f=u.tabs[m],p=a.autoOpened??f.previewAutoOpened,y=a.locked??f.previewUrlLocked;if(f.previewUrl===o&&f.previewAutoOpened===p&&f.previewUrlLocked===y)return l;const g=[...u.tabs];return g[m]={...f,previewUrl:o,previewAutoOpened:p,previewUrlLocked:y},d.set(c,{...u,tabs:g}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Pn(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 u=l.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const m=[...l.tabs];return m[d]={...u,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=Pn(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 u=[...l.tabs];return u[d]={...u[d],bufferChunks:[],bufferLength:0},c.set(o,{...l,tabs:u}),{sessions:c}})},removeDirectory:n=>{const r=Pn(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:Db,storage:Vh(()=>Of()),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,u]=l;if(typeof d!="string"||!pl(u))continue;const m=Array.isArray(u.tabs)?u.tabs:[],f=[];for(const g of m){if(!pl(g))continue;const b=typeof g.id=="string"?g.id:null;if(!b)continue;const x=Ib(b);x!==null&&(o=Math.max(o,x));const h=typeof g.terminalSessionId=="string"||g.terminalSessionId===null?g.terminalSessionId:null,C=g.lifecycle,w=C==="idle"||C==="running"||C==="exited"?C:h?"running":"idle";f.push({id:b,label:typeof g.label=="string"?g.label:"Terminal",iconKey:typeof g.iconKey=="string"?g.iconKey:null,terminalSessionId:h,lifecycle:w,createdAt:typeof g.createdAt=="number"?g.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(f.length===0)continue;const p=typeof u.activeTabId=="string"?u.activeTabId:null,y=p?f.some(g=>g.id===p):!1;r.set(d,{tabs:f,activeTabId:y?p:f[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=_s.persist,e=()=>{_s.getState().hasHydrated||_s.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const Pb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Tb=["dev","start","preview","serve"];async function Rb(t,e,n){if(!t)return null;const r=Fb(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=Lb(n);if(o){const a=await Ob(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 Eb(t)){const o=await Mb(),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 Eb(t){const e=`${t}/index.html`,n=await Ia(e,t);return typeof n=="string"&&n.trim().length>0}async function Mb(){try{const t=await Cs("/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 Fb(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(Tb.some(o=>n.includes(o)))return e}return null}function Lb(t){for(const{pattern:e}of Pb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function Ob(t){const e=await Ia(`${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 Ia(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Ia(t,e){if(e?.trim())try{const r=new URLSearchParams({path:t,directory:e,optional:"true"}),o=await Cs(`/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 Cs(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Bb(t){try{const e=await Ia(`${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)}),Vb="\x1B",$b=new RegExp(`${Vb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),zb=/https?:\/\/[^\s<>'"`]+/gi,nr="__openchamber_auto_discover_preview__",Wb=15e3,Ub=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},Hb=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}},Gb=t=>{const n=t.replace($b,"").match(zb);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(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",m=l.pathname||"/",f=m.split("/").filter(Boolean).length,p=m==="/"||m==="",y=!!(l.search||l.hash);let g=0;return u&&(g+=50),p&&(g+=30),g-=Math.min(f*5,20),y&&(g-=10),g};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},Pm=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=kt(),{terminal:c,runtime:l}=Xn(),{isMobile:d}=Mr(),u=i.useMemo(()=>ur(),[]),m=Yd(W=>W.instances),f=Yd(W=>W.load),p=Ee(W=>W.setBottomTerminalOpen),y=Ee(W=>W.setActiveMainTab),g=Ee(W=>W.setSettingsPage),b=Ee(W=>W.setSettingsDialogOpen),x=Ee(W=>W.setSettingsProjectsSelectedId),h=Ee(W=>W.openContextPreview),C=_s(W=>W.sessions),w=_s(W=>W.ensureDirectory),v=_s(W=>W.setTabLabel),S=_s(W=>W.setTabIconKey),k=_s(W=>W.setActiveTab),j=_s(W=>W.setConnecting),A=_s(W=>W.setTabSessionId),D=_s(W=>W.setTabPreviewUrl),N=_s(W=>W.projectActionRuns),B=_s(W=>W.setProjectActionRun),T=_s(W=>W.updateProjectActionRunStatus),E=_s(W=>W.removeProjectActionRun),[_,R]=i.useState([]),[$,V]=i.useState(null),[z,F]=i.useState(!1),ne=i.useRef({}),te=i.useRef({}),q=i.useRef({}),H=i.useRef({}),X=i.useRef(0),oe=t?.id??null,ue=t?.path??"",Se=i.useMemo(()=>oe?{id:oe,path:ue}:null,[oe,ue]);i.useEffect(()=>{u&&f().catch(()=>{})},[u,f]);const Z=i.useCallback(async W=>{await Di(W)},[]),ke=i.useCallback(async()=>{if(!Se)return;const W=X.current+1;X.current=W,F(!0);try{const be=await Ad(Se);if(X.current!==W)return;const ve=be.actions;R(ve),V(G=>G===nr||G&&ve.some(ye=>ye.id===G)?G:null)}catch{if(X.current!==W)return}finally{X.current===W&&F(!1)}},[Se]),Y=i.useMemo(()=>Ox(e||Se?.path||""),[e,Se?.path]),ge=i.useMemo(()=>$?_.find(W=>W.id===$)??null:null,[_,$]),O=i.useMemo(()=>({id:nr,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),se=!d,ee=i.useMemo(()=>se?[O,..._]:_,[_,O,se]);i.useEffect(()=>{ke()},[ke]),i.useEffect(()=>{if(typeof window>"u")return;const W=be=>{const ve=be.detail;oe&&(ve?.projectId&&ve.projectId!==oe||ke())};return window.addEventListener(Qd,W),()=>{window.removeEventListener(Qd,W)}},[ke,oe]),i.useEffect(()=>{$&&($===nr&&se||_.some(W=>W.id===$)||V(null))},[_,se,$]),i.useEffect(()=>{for(const[W,be]of Object.entries(N)){const G=C.get(be.directory)?.tabs.find(ye=>ye.id===be.tabId);(!G||G.terminalSessionId!==be.sessionId)&&E(W)}},[N,E,C]),i.useEffect(()=>{for(const[W,be]of Object.entries(N)){const ve=te.current[W]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};te.current[W]=ve;const G=ee.find(Oe=>Oe.id===be.actionId);if(!G)continue;const Le=C.get(be.directory)?.tabs.find(Oe=>Oe.id===be.tabId);if(!Le||!Array.isArray(Le.bufferChunks)||Le.bufferChunks.length===0)continue;const Re=Le.bufferChunks.filter(Oe=>ve.lastSeenChunkId===null?!0:Oe.id>ve.lastSeenChunkId);if(Re.length===0)continue;const J=Re.map(Oe=>Oe.data).join(""),L=`${ve.tail}${J}`,ae=!ve.openedUrl&&G.autoOpenUrl===!0?Gb(L):null,re=Re[Re.length-1]?.id??ve.lastSeenChunkId;if(ve.lastSeenChunkId=re,ve.tail=L.slice(-512),ae)if(ve.openedUrl=!0,ve.openInPreview){const Oe=N[W];Oe&&(D(Oe.directory,Oe.tabId,ae,{locked:!1,autoOpened:!1}),Oe.status==="waiting-for-preview"&&T(W,"running"),window.clearTimeout(H.current[W]),delete H.current[W],h(Oe.directory,ae))}else Z(ae),le.success(a("projectActions.toast.openedUrlFromOutput"));te.current[W]=ve}for(const W of Object.keys(te.current))N[W]||(delete te.current[W],window.clearTimeout(H.current[W]),delete H.current[W])},[ee,h,Z,N,D,a,C,T]);const je=i.useCallback(async(W,be={})=>{if(!Y)throw new Error(a("projectActions.error.noActiveDirectory"));const ve=Jr(Y,W.id);w(Y);const G=_s.getState(),ye=G.getDirectoryState(Y);let Le=ne.current[ve]||null;const Re=Le?!!ye?.tabs.some(ae=>ae.id===Le):!1;(!Le||!Re)&&(Le=G.createTab(Y),ne.current[ve]=Le),v(Y,Le,`Action: ${W.name}`),S(Y,Le,W.icon||"play"),be.revealTerminal!==!1&&(k(Y,Le),p(!0),y("terminal"));const L=_s.getState().getDirectoryState(Y)?.tabs.find(ae=>ae.id===Le);return{key:ve,tabId:Le,sessionId:L?.terminalSessionId??null}},[w,Y,y,k,p,S,v,a]),De=i.useCallback(async W=>{if(l.isVSCode||!o&&d)return;if(!Y){le.error(a("projectActions.error.noActiveDirectoryForAction"));return}const be=Jr(Y,W.id),ve=N[be];if(!(ve&&ve.status==="running"))try{const G=W.id===nr?await(async()=>{const[Je,nt]=await Promise.all([Ad({id:Se?.id??"",path:Y}),Bb(Y)]),gt=await Rb(Y,Je.actions,nt);if(!gt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:nr,name:a("projectActions.actions.autoDiscover"),command:gt.command,icon:"search",autoOpenUrl:!0,openUrl:gt.previewUrlHint||""}})():W,ye=G.autoOpenUrl===!0&&(G.openUrl||"").trim().length>0,{key:Le,tabId:Re,sessionId:J}=await je(G,{revealTerminal:!ye&&W.id!==nr});let L=J,ae=!1;if(!L){j(Y,Re,!0);try{L=(await c.createSession({cwd:Y})).sessionId,ae=!0,A(Y,Re,L)}finally{j(Y,Re,!1)}}if(!L)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));ae&&await _b(350),G.id===nr&&(q.current[Le]?.(),j(Y,Re,!0),q.current[Le]=up(L,Je=>{Je.type==="data"&&typeof Je.data=="string"&&Je.data.length>0&&_s.getState().appendToBuffer(Y,Re,Je.data),Je.type==="exit"&&(_s.getState().setTabLifecycle(Y,Re,"exited"),_s.getState().setConnecting(Y,Re,!1),_s.getState().removeProjectActionRun(Le),delete te.current[Le],q.current[Le]?.(),delete q.current[Le],window.clearTimeout(H.current[Le]),delete H.current[Le])},()=>{_s.getState().setConnecting(Y,Re,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const re=G.autoOpenUrl===!0&&u&&(G.desktopOpenSshForward||"").trim().length>0,Oe=G.autoOpenUrl?Hb(G.openUrl):null,qe=G.autoOpenUrl&&u?Bx(G.desktopOpenSshForward,m):null;B({key:Le,directory:Y,actionId:G.id,tabId:Re,sessionId:L,status:G.id===nr&&!Oe?"waiting-for-preview":"running"}),window.clearTimeout(H.current[Le]),delete H.current[Le],G.id===nr&&!Oe&&(H.current[Le]=window.setTimeout(()=>{_s.getState().updateProjectActionRunStatus(Le,"running"),delete H.current[Le]},Wb)),qe?(D(Y,Re,null,{locked:!0}),Z(qe),le.success(a("projectActions.toast.openedForwardedUrl"))):Oe?(D(Y,Re,Oe,{locked:!0,autoOpened:!0}),h(Y,Oe),le.success(a("projectActions.toast.openedActionUrl"))):ye?(D(Y,Re,null,{locked:!0}),le.error(a("projectActions.error.invalidCustomUrlFormat"))):re?(D(Y,Re,null,{locked:!0}),le.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):D(Y,Re,null,{locked:!1,autoOpened:!1}),te.current[Le]={lastSeenChunkId:null,openedUrl:!!qe||!!Oe||ye,tail:"",openInPreview:G.id===nr};const Ge=Ub(G.command.trim().replace(/\r\n|\r/g,`
3
- `));await c.sendInput(L,`${Ge}\r`)}catch(G){E(be),delete te.current[be],q.current[be]?.(),delete q.current[be],window.clearTimeout(H.current[be]),delete H.current[be],le.error(G instanceof Error?G.message:a("projectActions.error.failedToRunAction"))}},[m,je,o,d,u,Y,Z,h,N,l.isVSCode,E,j,B,D,A,Se?.id,a,c]),Be=i.useCallback(async W=>{const be=Jr(Y,W.id),ve=N[be];if(!ve)return;T(be,"stopping");try{await c.sendInput(ve.sessionId,"")}catch{}if(await new Promise(Le=>{window.setTimeout(Le,1e3)}),_s.getState().getDirectoryState(ve.directory)?.tabs.find(Le=>Le.id===ve.tabId)?.terminalSessionId===ve.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:ve.sessionId})}catch{}else try{await c.close(ve.sessionId)}catch{}A(ve.directory,ve.tabId,null)}E(be),delete te.current[be],q.current[be]?.(),delete q.current[be],window.clearTimeout(H.current[be]),delete H.current[be]},[Y,N,E,A,c,T]),Fe=i.useCallback(()=>{const W=ge??ee[0];if(!W)return;const be=Jr(Y,W.id),ve=N[be];if(ve?.status!=="stopping"){if(ve){Be(W);return}De(W)}},[ee,Y,De,N,ge,Be]),Me=i.useCallback((W,be=!1)=>{if(V(W.id),!be){De(W);return}const ve=Jr(Y,W.id),G=N[ve];if(G?.status!=="stopping"){if(G){Be(W);return}De(W)}},[Y,De,N,Be]),me=i.useCallback(()=>{Se?.id&&(x(Se.id),g("projects"),b(!0))},[b,g,x,Se?.id]);if(l.isVSCode||!o&&d||!Se||!Y)return null;const Ae=ge??ee[0]??null;if(!Ae)return null;const pe=Ae.icon||"play",ce=Ae.id===nr?"search":dl[pe]||"play",he=Jr(Y,Ae.id),Ne=N[he],fe=Ne?.status==="stopping",P=Ne?.status==="waiting-for-preview",M=Ne?C.get(Ne.directory)?.tabs.find(W=>W.id===Ne.tabId)?.previewUrl??null:null,de=!!(Ne&&M),xe=()=>{!Ne||!M||h(Ne.directory,M)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:z||fe,className:Pe("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:Fe,"aria-label":Ne?a("projectActions.actions.stopNamedAria",{name:Ae.name}):a("projectActions.actions.runNamedAria",{name:Ae.name}),children:fe||P?s.jsx(I,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):Ne?s.jsx(I,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(I,{name:ce,className:"h-5 w-5"})}),de?s.jsxs(Et,{children:[s.jsx(Mt,{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:xe,children:s.jsx(I,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(nn,{children:[s.jsx(tn,{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(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(sn,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(bs,{className:"flex items-center gap-2",onClick:me,children:[s.jsx(I,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Er,{}),ee.map(W=>{const be=W.icon||"play",ve=W.id===nr?"search":dl[be]||"play",G=Jr(Y,W.id),ye=N[G],Le=!!ye,Re=ye?.status==="stopping";return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Me(W,!0)},children:[s.jsx(I,{name:ve,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:W.name}),Re||ye?.status==="waiting-for-preview"?s.jsx(I,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?s.jsx(I,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},W.id)})]})]})]}):s.jsxs("div",{className:Pe("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:Fe,disabled:z||fe,className:Pe("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":Ne?a("projectActions.actions.stopNamedAria",{name:Ae.name}):a("projectActions.actions.runNamedAria",{name:Ae.name}),children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:fe||P?s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):Ne?s.jsx(I,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(I,{name:ce,className:"h-4 w-4"})})}),de?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:xe,className:Pe(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(I,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe(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(I,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(sn,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(bs,{className:"flex items-center gap-2",onClick:me,children:[s.jsx(I,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Er,{}),ee.map(W=>{const be=W.icon||"play",ve=W.id===nr?"search":dl[be]||"play",G=Jr(Y,W.id),ye=N[G],Le=!!ye,Re=ye?.status==="stopping";return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Me(W,!0)},children:[s.jsx(I,{name:ve,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:W.name}),Re||ye?.status==="waiting-for-preview"?s.jsx(I,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?s.jsx(I,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},W.id)})]})]})]})},Ja="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",Kb="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",Uo=i.memo(function(e){const n=ft.c(17),{visible:r,title:o,ariaLabel:a,onClick:c,className:l,Icon:d,iconClassName:u,pressed:m}=e,f=r===void 0?!0:r,p=m===void 0?!1:m;if(!f)return null;const y=l??Ja,g=p&&"bg-interactive-selection text-interactive-selection-foreground";let b;n[0]!==y||n[1]!==g?(b=Pe(y,g),n[0]=y,n[1]=g,n[2]=b):b=n[2];const x=u??"h-[18px] w-[18px]";let h;n[3]!==d||n[4]!==x?(h=s.jsx(I,{name:d,className:x}),n[3]=d,n[4]=x,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(Mt,{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(Ft,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=w):w=n[13];let v;return n[14]!==C||n[15]!==w?(v=s.jsxs(Et,{children:[C,w]}),n[14]=C,n[15]=w,n[16]=v):v=n[16],v}),qb=i.memo(function(e){const n=ft.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:u}=e,{t:m}=kt();if(!o?.connected||r)return null;if(a.length>1){let g;n[0]===Symbol.for("react.memo_cache_sentinel")?(g=Pe(Ja,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),n[0]=g):g=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 x;n[4]!==c||n[5]!==l||n[6]!==m?(x=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(I,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=m,n[7]=x):x=n[7];let h;n[8]!==d||n[9]!==b||n[10]!==x?(h=s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:g,title:b,disabled:d,children:x})}),n[8]=d,n[9]=b,n[10]=x,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(Tp,{className:"typography-ui-header font-semibold text-foreground",children:C}),n[14]=C,n[15]=w):w=n[15];let v;n[16]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx(Er,{}),n[16]=v):v=n[16];let S;if(n[17]!==a||n[18]!==u||n[19]!==d||n[20]!==m){let A;n[22]!==u||n[23]!==d||n[24]!==m?(A=D=>{const N=D.user,B=!!D.current,T=D.source==="gh-cli"?m("header.github.accountSource.cli"):m("header.github.accountSource.oauth");return s.jsxs(bs,{className:"gap-2",disabled:d,onSelect:()=>{B||u(D.id)},children:[N?.avatarUrl?s.jsx("img",{src:N.avatarUrl,alt:N.login?m("header.github.avatarWithLogin",{login:N.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(I,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:N?.name?.trim()||N?.login||"GitHub"}),N?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:N.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:T})]}):null]}),B?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]},D.id)},n[22]=u,n[23]=d,n[24]=m,n[25]=A):A=n[25],S=a.map(A),n[17]=a,n[18]=u,n[19]=d,n[20]=m,n[21]=S}else S=n[21];let k;n[26]!==w||n[27]!==S?(k=s.jsxs(sn,{align:"end",className:"w-64",children:[w,v,S]}),n[26]=w,n[27]=S,n[28]=k):k=n[28];let j;return n[29]!==h||n[30]!==k?(j=s.jsxs(nn,{children:[h,k]}),n[29]=h,n[30]=k,n[31]=j):j=n[31],j}let f;n[32]!==l||n[33]!==m?(f=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[32]=l,n[33]=m,n[34]=f):f=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(I,{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 y;return n[39]!==f||n[40]!==p?(y=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:f,children:p}),n[39]=f,n[40]=p,n[41]=y):y=n[41],y}),Yb=i.memo(function(e){const n=ft.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:u,desktopServicesTab:m,setDesktopServicesTab:f,quotaResultsLength:p,fetchAllQuotas:y,servicesTabItems:g,quotaLastUpdated:b,quotaDisplayMode:x,quotaDisplayTabItems:h,handleDisplayModeChange:C,handleUsageRefresh:w,isQuotaLoading:v,isUsageRefreshSpinning:S,hasRateLimits:k,rateLimitGroups:j,expandedFamilies:A,toggleFamilyExpanded:D,shortcutLabel:N,showDevShutdown:B,isDevShutdownInFlight:T,onDevShutdown:E,remoteUpdateInfo:_,remoteUpdateChecking:R,remoteUpdateError:$,onOpenRemoteUpdate:V,showPredValues:z,timeFormatPreference:F}=e,{t:ne}=kt();let te;n[0]!==m||n[1]!==y||n[2]!==p||n[3]!==u||n[4]!==d?(te=Me=>{d(Me),Me&&(u(),m==="usage"&&p===0&&y())},n[0]=m,n[1]=y,n[2]=p,n[3]=u,n[4]=d,n[5]=te):te=n[5];let q;n[6]!==o||n[7]!==r||n[8]!==ne?(q=r?ne("header.services.openWithCurrent",{current:o}):ne("header.services.open"),n[6]=o,n[7]=r,n[8]=ne,n[9]=q):q=n[9];const H=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let X;n[10]!==H?(X=Pe(Ja,H),n[10]=H,n[11]=X):X=n[11];let oe;n[12]===Symbol.for("react.memo_cache_sentinel")?(oe=s.jsx(I,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=oe):oe=n[12];let ue;n[13]!==a||n[14]!==r?(ue=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=ue):ue=n[15];let Se;n[16]!==q||n[17]!==X||n[18]!==ue?(Se=s.jsx(Mt,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":q,className:X,children:[oe,ue]})})}),n[16]=q,n[17]=X,n[18]=ue,n[19]=Se):Se=n[19];let Z;n[20]!==o||n[21]!==r||n[22]!==N||n[23]!==ne?(Z=r?ne("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}):ne("header.services.tooltip.servicesWithShortcuts",{toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}),n[20]=o,n[21]=r,n[22]=N,n[23]=ne,n[24]=Z):Z=n[24];let ke;n[25]!==Z?(ke=s.jsx(Ft,{children:s.jsx("p",{children:Z})}),n[25]=Z,n[26]=ke):ke=n[26];let Y;n[27]!==Se||n[28]!==ke?(Y=s.jsxs(Et,{children:[Se,ke]}),n[27]=Se,n[28]=ke,n[29]=Y):Y=n[29];let ge;n[30]!==y||n[31]!==p||n[32]!==f?(ge=Me=>{const me=Me;f(me),me==="usage"&&p===0&&y()},n[30]=y,n[31]=p,n[32]=f,n[33]=ge):ge=n[33];let O;n[34]!==m||n[35]!==g||n[36]!==ge?(O=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(To,{items:g,activeId:m,onSelect:ge,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=m,n[35]=g,n[36]=ge,n[37]=O):O=n[37];let se;n[38]!==c||n[39]!==m||n[40]!==r||n[41]!==l||n[42]!==V||n[43]!==R||n[44]!==$||n[45]!==_||n[46]!==d||n[47]!==ne?(se=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:_?.available?ne("header.services.remoteUpdate.available",{version:_.version||""}):R?ne("header.services.remoteUpdate.checking"):$||ne("header.services.remoteUpdate.upToDate")})]}),_?.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:V,children:ne("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(Pp,{embedded:!0,open:l&&m==="instance",onOpenChange:Xb,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=m,n[40]=r,n[41]=l,n[42]=V,n[43]=R,n[44]=$,n[45]=_,n[46]=d,n[47]=ne,n[48]=se):se=n[48];let ee;n[49]!==m||n[50]!==l?(ee=m==="mcp"?s.jsx(ym,{active:l&&m==="mcp"}):null,n[49]=m,n[50]=l,n[51]=ee):ee=n[51];let je;n[52]!==m||n[53]!==A||n[54]!==C||n[55]!==w||n[56]!==k||n[57]!==v||n[58]!==S||n[59]!==x||n[60]!==h||n[61]!==b||n[62]!==j||n[63]!==z||n[64]!==ne||n[65]!==F||n[66]!==D?(je=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:Tm(b,F)})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-[10.5rem]",children:s.jsx(To,{items:h,activeId:x,onSelect:Me=>{C(Me)},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",className:"h-full"})}),s.jsx("button",{type:"button",className:Pe("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:v||S,"aria-label":ne("header.services.refreshRateLimitsAria"),children:s.jsx(I,{name:"refresh",className:Pe("h-4 w-4",S&&"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:"py-2",children:j.map((Me,me)=>{const Ae=A[Me.providerId]??[];return s.jsxs(i.Fragment,{children:[me>0?s.jsx("div",{className:"mx-4 my-2 border-t border-[var(--interactive-border)]"}):null,s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2",children:[s.jsx(Do,{providerId:Me.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Me.providerName})]}),Me.entries.length===0&&(!Me.modelFamilies||Me.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Me.error??ne("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[Me.entries.map(pe=>{const[ce,he]=pe,Ne=x==="remaining"?he.remainingPercent:he.usedPercent,fe=ja(he.usedPercent,he.resetAt,he.windowSeconds,ce),P=fe?.dailyAllocationPercent!=null?x==="remaining"?100-ri(fe.elapsedRatio):ri(fe.elapsedRatio):null,M=Io(he.valueLabel,Ne),de=$f(he.resetAt,he.resetAfterFormatted??he.resetAtFormatted,F);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:bc(ce)}),de?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:de}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:M==="-"?"":M})]}),s.jsx(Aa,{percent:Ne,tonePercent:he.usedPercent,className:"h-1.5",expectedMarkerPercent:P}),fe&&z?s.jsx(Da,{paceInfo:fe,compact:!0}):null]},`${Me.providerId}-${ce}`)}),Me.modelFamilies&&Me.modelFamilies.length>0?s.jsx("div",{className:"space-y-0.5",children:Me.modelFamilies.map(pe=>{const ce=pe.familyId??"other",he=Ae.includes(ce);return s.jsxs(eo,{open:he,onOpenChange:()=>D(Me.providerId,ce),children:[s.jsxs(Bo,{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:pe.familyLabel}),he?s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(to,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:pe.models.map(Ne=>{const[fe,P]=Ne,M=x==="remaining"?P.remainingPercent:P.usedPercent,de=ja(P.usedPercent,P.resetAt,P.windowSeconds),xe=de?.dailyAllocationPercent!=null?x==="remaining"?100-ri(de.elapsedRatio):ri(de.elapsedRatio):null,W=Io(P.valueLabel,M);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:bm(fe)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:W==="-"?"":W})]}),s.jsx(Aa,{percent:M,tonePercent:P.usedPercent,className:"h-1.5",expectedMarkerPercent:xe}),de&&z?s.jsx(Da,{paceInfo:de,compact:!0}):null]},`${Me.providerId}-${fe}`)})})})]},ce)})}):null]})]},Me.providerId)})})]}):null,n[52]=m,n[53]=A,n[54]=C,n[55]=w,n[56]=k,n[57]=v,n[58]=S,n[59]=x,n[60]=h,n[61]=b,n[62]=j,n[63]=z,n[64]=ne,n[65]=F,n[66]=D,n[67]=je):je=n[67];let De;n[68]!==T||n[69]!==E||n[70]!==B||n[71]!==ne?(De=B?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(bs,{disabled:T,onSelect:()=>{E()},children:ne("header.services.shutdownDev")})})]}):null,n[68]=T,n[69]=E,n[70]=B,n[71]=ne,n[72]=De):De=n[72];let Be;n[73]!==O||n[74]!==se||n[75]!==ee||n[76]!==je||n[77]!==De?(Be=s.jsxs(sn,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[O,se,ee,je,De]}),n[73]=O,n[74]=se,n[75]=ee,n[76]=je,n[77]=De,n[78]=Be):Be=n[78];let Fe;return n[79]!==l||n[80]!==te||n[81]!==Y||n[82]!==Be?(Fe=s.jsxs(nn,{open:l,onOpenChange:te,children:[Y,Be]}),n[79]=l,n[80]=te,n[81]=Y,n[82]=Be,n[83]=Fe):Fe=n[83],Fe}),Qb=(t,e)=>t===e?!0:!t||!e?!1:t.totalTokens===e.totalTokens&&t.percentage===e.percentage&&t.contextLimit===e.contextLimit&&(t.outputLimit??0)===(e.outputLimit??0)&&(t.normalizedOutput??0)===(e.normalizedOutput??0)&&t.thresholdLimit===e.thresholdLimit&&(t.lastMessageId??"")===(e.lastMessageId??""),Jb=t=>{const e=t.trim();if(!e)return"";const n=e.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<e.length?`${a}...`:a}return e.length>12?`${e.slice(0,9).trimEnd()}...`:e},Tm=(t,e)=>{if(!t)return"-";try{return zf(t,e,{fallback:"-"})}catch{return"-"}},Tn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},ei=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}=kt(),a=Ee(Q=>Q.setSessionSwitcherOpen),c=Ee(Q=>Q.toggleSidebar),l=Ee(Q=>Q.isSidebarOpen),d=Ee(Q=>Q.toggleBottomTerminal),u=Ee(Q=>Q.toggleRightSidebar),m=Ee(Q=>Q.openContextOverview),f=Ee(Q=>Q.openContextPlan),p=Ee(Q=>Q.openContextBrowser),y=Ee(Q=>Q.openContextPanelTab),g=Ee(Q=>Q.closeContextPanel),b=Ee(Q=>Q.contextPanelByDirectory),x=Ee(Q=>Q.activeMainTab),h=Ee(Q=>Q.setActiveMainTab),C=Ee(Q=>Q.shortcutOverrides),w=Ee(Q=>Q.timeFormatPreference),v=ss(Q=>Q.getCurrentModel),S=Xn(),[k,j]=i.useState(!1),A=ut(Q=>Q.getContextUsage),D=ut(Q=>!!Q.newSessionDraft?.open),N=ut(Q=>Q.currentSessionId),B=Rp(N??""),T=Wf(N??null),E=jr(Q=>Q.activeSessions),_=yc(),R=Ns(Q=>Q.activeProjectId?Q.projects.find(tt=>tt.id===Q.activeProjectId)??null:null),$=i.useMemo(()=>{if(!R)return null;const Q=R.label?.trim();if(Q)return Q;const tt=R.path.split(/[\\/]/).filter(Boolean);return tt[tt.length-1]??null},[R]),V=gn(Q=>Q.results),z=gn(Q=>Q.fetchAllQuotas),F=gn(Q=>Q.isLoading),ne=gn(Q=>Q.lastUpdated),te=gn(Q=>Q.displayMode),q=gn(Q=>Q.showPredValues),H=gn(Q=>Q.dropdownProviderIds),X=gn(Q=>Q.loadSettings),oe=gn(Q=>Q.setDisplayMode),{isMobile:ue}=Mr(),Se=Ii(Q=>Q.status),Z=Ii(Q=>Q.setStatus),ke=i.useRef(null),[Y,ge]=i.useState(()=>typeof window>"u"?!1:ur()),O=i.useMemo(()=>Ba(),[]),se=Uf(),[ee,je]=i.useState(!1),De=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),Be=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32",[]),Fe=i.useMemo(()=>{if(typeof window>"u")return null;const Q=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof Q=="number"&&Number.isFinite(Q)&&Q>0)return Q;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),Pt=Number.parseInt(tt[2],10);return Number.isNaN(pt)?null:pt===10?Pt:pt},[]);Xe.useEffect(()=>{typeof window>"u"||ge(ur())},[]);const Me=v(),me=Me&&typeof Me.limit=="object"&&Me.limit!==null?Me.limit:null,Ae=me&&typeof me.context=="number"?me.context:0,pe=me&&typeof me.output=="number"?me.output:0,ce=A(Ae,pe),[he,Ne]=i.useState(null),fe=!N||B;Xe.useEffect(()=>{if(!N){Ne(Q=>Q===null?Q:null);return}if(ce&&ce.totalTokens>0){Ne(Q=>Qb(Q,ce)?Q:ce);return}fe&&Ne(Q=>Q===null?Q:null)},[ce,N,fe]);const P=Ee(Q=>Q.isSessionSwitcherOpen),M=Se?.connected?Se.user?.avatarUrl??null:null,de=Se?.connected?Se.user?.login??null:null,xe=Se?.accounts??[],[W,be]=i.useState(!1),[ve,G]=i.useState(!1),[ye,Le]=i.useState(!1),[Re,J]=i.useState(!1),[L,ae]=i.useState("Local"),[re,Oe]=i.useState(!0),[qe,Ge]=i.useState(!1),[Je,nt]=i.useState(null),[gt,yt]=i.useState(!1),[_e,Qe]=i.useState(null),st=i.useMemo(()=>Jb(L),[L]),[wt,Ct]=i.useState(Y?"instance":"usage"),[xt,St]=i.useState("usage");Xe.useEffect(()=>{!Y&&wt==="instance"&&Ct("usage")},[wt,Y]);const Ze=i.useMemo(()=>Kr(),[]),Ot=!Ze&&x==="chat"&&!!he&&he.totalTokens>0,ns=he&&he.contextLimit>0?Math.min(999,he.totalTokens/he.contextLimit*100):0,zt=i.useCallback(async()=>{if(!(typeof window>"u"||!Y))try{if(Ji()){ae("Local"),Oe(!0);return}Oe(!1);const Q=await Hf(),tt=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,pt=Ur();if(pt&&Sa(pt,tt)){ae("Local"),Oe(!0);return}const Pt=Q.hosts.find(es=>pt?Sa(pt,Gf(es)):!1);if(Pt?.label?.trim()){ae(Kf(Pt.label.trim()));return}ae("Instance")}catch{ae("Local"),Oe(!0)}},[Y]);Xe.useEffect(()=>{zt()},[zt]);const Ve=i.useCallback(async()=>{if(re){nt(null),Qe(null);return}yt(!0),Qe(null);try{const Q=new URLSearchParams({appType:"web",instanceMode:"remote"}),tt=await Cs(`/api/openchamber/update-check?${Q.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(Q){nt(null),Qe(Q instanceof Error?Q.message:o("header.services.remoteUpdate.error"))}finally{yt(!1)}},[re,o]);i.useEffect(()=>{nt(null),Qe(null),Ge(!1)},[re,L]),i.useEffect(()=>{if(!Y||re)return;const Q=3e3,tt=3600*1e3;let pt=!1,Pt=null;const es=is=>{Pt=window.setTimeout(()=>{if(pt||typeof document<"u"&&document.visibilityState!=="visible"){es(tt);return}Ve().finally(()=>{pt||es(tt)})},is)};return es(Q),()=>{pt=!0,Pt!==null&&window.clearTimeout(Pt)}},[Ve,re,L,Y]);const At=i.useCallback(()=>{if(Je?.available){Ge(!0);return}Ve()},[Ve,Je?.available]);_x();const ot=gn(Q=>Q.selectedModels),vt=gn(Q=>Q.expandedFamilies),bt=gn(Q=>Q.toggleFamilyExpanded),ls=i.useMemo(()=>{const Q=[];for(const tt of wm){if(!H.includes(tt.id))continue;const pt=V.find(Es=>Es.providerId===tt.id),Pt=pt?.usage?.windows??{},es=pt?.usage?.models,is=Object.entries(Pt),fs={providerId:tt.id,providerName:tt.name,entries:is,error:pt&&!pt.ok&&pt.configured?pt.error:void 0};if(es&&Object.keys(es).length>0){const Es=ot[tt.id]??[],Ys=Es.length>0,tr=Vx(es,tt.id),qn=$x(tt.id),Lr=zx(qn);fs.modelFamilies=[];for(const xn of Lr){const sr=tr.get(xn.id)??[];if(sr.length===0)continue;const bn=Ys?sr.filter(yn=>Es.includes(yn)):sr;if(bn.length===0)continue;const Ln=[];for(const yn of bn){const ar=es[yn];if(ar?.windows){const Dn=Object.entries(ar.windows);Dn.length>0&&Ln.push([yn,Dn[0][1]])}}Ln.length>0&&fs.modelFamilies.push({familyId:xn.id,familyLabel:xn.label,models:Ln})}const Bs=tr.get(null)??[],Or=Ys?Bs.filter(xn=>Es.includes(xn)):Bs;if(Or.length>0){const xn=[];for(const sr of Or){const bn=es[sr];if(bn?.windows){const Ln=Object.entries(bn.windows);Ln.length>0&&xn.push([sr,Ln[0][1]])}}xn.length>0&&fs.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:xn})}}(is.length>0||fs.modelFamilies&&fs.modelFamilies.length>0||fs.error)&&Q.push(fs)}return Q},[H,V,ot,o]),Wt=ls.length>0;i.useEffect(()=>{X()},[X]);const qt=i.useCallback(async Q=>{oe(Q);try{await hc({usageDisplayMode:Q})}catch(tt){console.warn("Failed to update usage display mode:",tt)}},[oe]),rs=i.useCallback(()=>{if(Re)return;J(!0);const Q=new Promise(tt=>setTimeout(tt,500));Promise.all([z(),Q]).finally(()=>{J(!1)})},[z,Re]),Ut=i.useMemo(()=>N?_.find(Q=>Q.id===N)??E.find(Q=>Q.id===N)??T??qf().find(Q=>Q.id===N)??null:null,[N,T,E,_]),Bt=i.useRef(null),[_t,Yt]=i.useState(0);i.useEffect(()=>{if(!N){Bt.current&&(Bt.current=null,Yt(Pt=>Pt+1));return}if(Ut){Bt.current={sessionId:N,session:Ut,expiresAt:Date.now()+2e3};return}const Q=Bt.current;if(!Q||Q.sessionId!==N)return;const tt=Q.expiresAt-Date.now();if(tt<=0){Bt.current=null,Yt(Pt=>Pt+1);return}const pt=window.setTimeout(()=>{Bt.current?.sessionId===N&&(Bt.current=null),Yt(Pt=>Pt+1)},tt);return()=>{window.clearTimeout(pt)}},[N,Ut]);const Ht=(()=>{if(Ut)return Ut;if(!N)return null;const Q=Bt.current;return Q&&Q.sessionId===N&&Q.expiresAt>Date.now()?Q.session:null})(),Zt=ut(Q=>N?Q.worktreeMetadata.get(N)?.path??"":""),ys=ut(Q=>N?Q.worktreeMetadata.get(N)?.branch?.trim()??null:null),Tt=Yf(Q=>N?Q.getAttachment(N):void 0),Vt=i.useMemo(()=>Tt?Ep(Tt,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,Tt]),Dt=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]),cs=i.useMemo(()=>Tn(Zt||""),[Zt]),us=i.useMemo(()=>{const Q=typeof Ht?.directory=="string"?Ht.directory:"";return Tn(Q||"")},[Ht?.directory]),He=ut(Q=>Q.newSessionDraft?.open?Tn(Q.newSessionDraft.bootstrapPendingDirectory??Q.newSessionDraft.directoryOverride??""):""),Ke=i.useMemo(()=>cs||us||He,[He,us,cs]),jt=ut(Q=>{const tt=Tn(cs||us||"");if(!tt)return null;for(const pt of Q.availableWorktreesByProject.values()){const es=pt.find(is=>Tn(is.path)===tt)?.branch?.trim();if(es)return es}return null}),Nt=Mp(Ke||null)||ys||jt,xs=i.useMemo(()=>{if(!N)return $??"OpenChamber";const Q=Ht?.title?.trim();return Q&&Q.length>0?Q:"Untitled Session"},[$,Ht?.title,N]),ps=i.useMemo(()=>Tn(Ke||R?.path||""),[R?.path,Ke]),os=i.useMemo(()=>R?{id:R.id,path:R.path}:null,[R]),Kt=i.useRef(null);i.useEffect(()=>{!os||!ps||(Kt.current={projectRef:os,directory:ps})},[ps,os]);const Fs=i.useMemo(()=>os&&ps?{projectRef:os,directory:ps}:Kt.current,[ps,os]),js=wc(Q=>Q.planModeEnabled),rn=ut(Q=>Q.isSessionPlanAvailable),Ks=js&&N?rn(N):!1,cn=Ks,Mn=i.useRef("");i.useEffect(()=>{if(!js){Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat");return}if(!N)return;const Q=`${N||"none"}:${us||"none"}:${Ht?.time?.created||0}:${Ht?.slug||"none"}`;Mn.current!==Q&&(Mn.current=Q),!Ks&&Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat")},[js,Ks,Ht?.slug,Ht?.time?.created,N,us]);const Ls=i.useCallback(async Q=>{if(!(!Q||W)){be(!0);try{const tt=S.github?await S.github.authActivate(Q):await(async()=>{const pt=await Cs("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:Q})}),Pt=await pt.json().catch(()=>null);if(!pt.ok||!Pt)throw new Error(Pt?.error||pt.statusText);return Pt})();Z(tt)}catch(tt){console.error("Failed to switch GitHub account:",tt)}finally{be(!1)}}},[W,S.github,Z]),we=i.useCallback(()=>{if(typeof document>"u")return;const Q=document.activeElement;if(!Q)return;const tt=Q.tagName;(tt==="INPUT"||tt==="TEXTAREA"||tt==="SELECT"||Q.isContentEditable)&&Q.blur()},[]),et=i.useCallback(()=>{if(ue){we(),a(!P);return}c()},[we,ue,P,a,c]),ct=i.useCallback(()=>{Hr("desktop_open_draft_mini_chat_window",{directory:Tn(Ke||R?.path||""),projectId:R?.id??null,apiBaseUrl:Ur(),clientToken:Ul()}).catch(Q=>{console.warn("[header] failed to open draft mini chat window",Q)})},[R?.id,R?.path,Ke]),It=i.useCallback(()=>{if(D){ct();return}N&&Hr("desktop_open_session_mini_chat_window",{sessionId:N,directory:Tn(Ke||R?.path||""),apiBaseUrl:Ur(),clientToken:Ul()}).catch(Q=>{console.warn("[header] failed to open session mini chat window",Q)})},[R?.path,N,ct,D,Ke]),Gt=i.useCallback(()=>{const Q=Tn(Ke||"");if(!Q)return;const tt=b[Q];if(ei(tt)==="context"){g(Q);return}m(Q)},[g,b,m,Ke]),mt=i.useMemo(()=>{const Q=Tn(Ke||"");if(!Q)return!1;const tt=b[Q];return ei(tt)==="context"},[b,Ke]),ms=i.useCallback(()=>{const Q=Tn(Ke||"");if(!Q)return;const tt=b[Q];if(ei(tt)==="plan"){g(Q);return}f(Q)},[g,b,f,Ke]),hs=i.useCallback(()=>{const Q=Tn(Ke||"");if(!Q)return;const tt=b[Q];if(ei(tt)==="diff"){g(Q);return}y(Q,{mode:"diff",stagedDiff:!1})},[g,b,y,Ke]),Ss=i.useCallback(()=>{const Q=Tn(Ke||"");if(!Q)return;const tt=b[Q];if(ei(tt)==="browser"){g(Q);return}p(Q)},[g,b,p,Ke]),ws=i.useMemo(()=>{const Q=Tn(Ke||"");if(!Q)return!1;const tt=b[Q];return ei(tt)==="plan"},[b,Ke]),Ds=i.useMemo(()=>{const Q=Tn(Ke||"");if(!Q)return!1;const tt=b[Q];return ei(tt)==="diff"},[b,Ke]),Hn=i.useMemo(()=>{const Q=Tn(Ke||"");if(!Q)return!1;const tt=b[Q];return ei(tt)==="browser"},[b,Ke]),zs=Ja,Sn=Kb,Fn=i.useMemo(()=>ve?"services":n?"sessions":r?"git":x,[x,ve,n,r]),Zn=i.useCallback(()=>{G(!1),n&&t&&t(),r&&e&&e(),!t&&P&&a(!1)},[P,n,t,e,r,a]),dn=i.useCallback(()=>{n||G(!1),t?.()},[n,t]),Ue=i.useCallback(()=>{r||G(!1),e?.()},[e,r]),Xt=i.useMemo(()=>Y&&De&&!ee?"5.5rem":se?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!Y||Be)&&!Ze?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[Y,ee,De,se,Ze,Be]);Xe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Xt)},[Xt]);const Is=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ts=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";Xe.useEffect(()=>{if(!Y||!De){je(!1);return}let Q=!1;const tt=async()=>{try{const Pt=await Hr("desktop_is_window_fullscreen");Q||je(Pt===!0)}catch{Q||je(!1)}},pt=()=>{tt()};return tt(),window.addEventListener("openchamber:window-resized",pt),()=>{Q=!0,window.removeEventListener("openchamber:window-resized",pt)}},[Y,De]);const Ws=i.useMemo(()=>!Y||!De||Fe===null?"":Fe>=26?"h-12":Fe<=15?"h-14":"",[Y,De,Fe]),qs=i.useMemo(()=>{if(!(Y&&!Be||Ze))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))"}},[Y,Ze,Be]),Hs=i.useCallback(()=>{if(typeof document>"u")return;const Q=ke.current?.getBoundingClientRect().height;Q&&document.documentElement.style.setProperty("--oc-header-height",`${Q}px`)},[]);Xe.useEffect(()=>{if(typeof window>"u")return;Hs();const Q=ke.current;if(!Q||typeof ResizeObserver>"u")return()=>{};let tt=0;const pt=()=>{tt||(tt=requestAnimationFrame(()=>{tt=0,Hs()}))},Pt=new ResizeObserver(pt);return Pt.observe(Q),window.addEventListener("resize",pt),window.addEventListener("orientationchange",pt),()=>{tt&&cancelAnimationFrame(tt),Pt.disconnect(),window.removeEventListener("resize",pt),window.removeEventListener("orientationchange",pt)}},[Hs]),Xe.useEffect(()=>{Hs()},[Hs,ue,Ws]);const Os=i.useCallback(async Q=>{const tt=Q.target;tt.closest(".app-region-no-drag")||tt.closest("button, a, input, select, textarea")||Q.button===0&&Y&&await fp()},[Y]),Gn=i.useMemo(()=>{if(ue){const Q=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return cn&&Q.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),Q.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"}),Q}return[]},[ue,cn,o]),mr=i.useCallback(Q=>_a(ii(Q,C)),[C]);Xe.useEffect(()=>{!ue&&(x==="git"||x==="terminal"||x==="diff"||x==="files"||x==="context")&&h("chat")},[x,ue,h]);const Kn=i.useMemo(()=>{const Q=[];return Y&&Q.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(I,{name:"server",className:"h-3.5 w-3.5"})}),Q.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(Gl,{className:"h-3.5 w-3.5"})}),Q},[Y,o]),gs=i.useMemo(()=>Kn.map(Q=>({id:Q.value,label:Q.label,icon:Q.icon})),[Kn]),Rs=i.useMemo(()=>{if(typeof window>"u"||Y||Ze)return!1;const Q=window.location.hostname;return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"},[Y,Ze]),Sr=i.useCallback(async()=>{if(k)return;j(!0),Le(!1);const Q=[];let tt=!1;try{try{for(const[,pt]of _s.getState().sessions.entries())for(const Pt of pt.tabs)Pt.previewUrl&&Q.push(Pt.previewUrl)}catch{}try{await mp({})}catch{}try{(await Cs("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:Q})})).ok?tt=!0:tt=(await Cs("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{tt||j(!1)}},[k,Le]),Nn=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),un=i.useMemo(()=>Nn.map(Q=>({id:Q.value,label:Q.label})),[Nn]),er=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(Gl,{className:"h-3.5 w-3.5"})}],[o]);Xe.useEffect(()=>{const Q=tt=>{if(vc(tt)&&!tt.shiftKey&&!tt.altKey){const pt=parseInt(tt.key,10);pt>=1&&pt<=Gn.length&&(tt.preventDefault(),ue&&(we(),Zn()),h(Gn[pt-1].id))}};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[we,Zn,ue,h,Gn]),Xe.useEffect(()=>{const Q=tt=>{const pt=ii("toggle_services_menu",C);if(ia(tt,pt)){tt.preventDefault(),ye?Le(!1):(Le(!0),zt(),wt==="usage"&&V.length===0&&z());return}const Pt=ii("cycle_services_tab",C);if(ia(tt,Pt)){tt.preventDefault();const is=Kn.map(tr=>tr.value);if(is.length===0)return;const fs=is.indexOf(wt),Es=fs===-1?0:(fs+1)%is.length,Ys=is[Es];Ct(Ys),Le(!0),zt(),Ys==="usage"&&V.length===0&&z();return}const es=ii("toggle_context_plan",C);ia(tt,es)&&(tt.preventDefault(),ms())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[C,ye,wt,Kn,V.length,z,zt,ms]);const Fr=Q=>{const tt=x===Q.id,pt=Q.icon==="diff",Pt=pt?null:Q.icon,es=Q.id==="chat",is=Es=>pt?s.jsx(Xd,{size:Es}):Pt?s.jsx(I,{name:Pt,className:`h-${Es/4} w-${Es/4}`}):null,fs=s.jsxs("button",{type:"button",onClick:()=>h(Q.id),className:Pe("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",es&&!ue&&"min-w-[100px] justify-center"),"aria-label":Q.label,"aria-selected":tt,role:"tab",children:[ue?is(20):s.jsxs(s.Fragment,{children:[is(16),s.jsx("span",{className:"header-tab-label",children:Q.label})]}),Q.badge!==void 0&&Q.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:Q.badge})]});return s.jsx(i.Fragment,{children:fs},Q.id)},Yr=Ze?null:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.toggleChangesPanelAria"),"aria-pressed":Ds,onClick:hs,className:zs,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(I,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),ui=s.jsxs(s.Fragment,{children:[cn&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:ms,className:Pe(zs,ws&&"bg-[var(--interactive-hover)]"),children:s.jsx(I,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:mr("toggle_context_plan")})})})]}),s.jsx(bb,{directory:ps,className:"mr-1"}),s.jsx(Yb,{isDesktopApp:Y,currentInstanceLabel:L,compactCurrentInstanceLabel:st,currentInstanceIsLocal:re,isDesktopServicesOpen:ye,setIsDesktopServicesOpen:Le,refreshCurrentInstanceLabel:zt,desktopServicesTab:wt,setDesktopServicesTab:Ct,quotaResultsLength:V.length,fetchAllQuotas:z,servicesTabItems:gs,quotaLastUpdated:ne,quotaDisplayMode:te,showPredValues:q,quotaDisplayTabItems:un,handleDisplayModeChange:qt,handleUsageRefresh:rs,isQuotaLoading:F,isUsageRefreshSpinning:Re,hasRateLimits:Wt,rateLimitGroups:ls,expandedFamilies:vt,toggleFamilyExpanded:bt,shortcutLabel:mr,showDevShutdown:Rs,isDevShutdownInFlight:k,onDevShutdown:Sr,remoteUpdateInfo:Je,remoteUpdateChecking:gt,remoteUpdateError:_e,onOpenRemoteUpdate:At,timeFormatPreference:w}),s.jsx(Uo,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:mr("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),ue?null:s.jsx(Uo,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:Ss,pressed:Hn,Icon:"global"}),s.jsx(Uo,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:mr("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:u,Icon:"layout-right"}),s.jsx(qb,{isMobile:ue,githubAuthStatus:Se,githubAccounts:xe,githubAvatarUrl:M,githubLogin:de,isSwitchingGitHubAccount:W,handleGitHubAccountSwitch:Ls})]}),hr=O&&(D||!!N),ds=()=>s.jsxs("div",{onMouseDown:Os,className:Pe("app-region-drag relative flex h-12 select-none items-center pr-3",Ws),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:Is}}),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:Ts}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(lb,{children:s.jsxs("button",{type:"button","aria-label":o("sessions.switcher.openAria"),className:"app-region-no-drag mr-3 flex min-w-0 flex-col items-start rounded-md px-1 py-0.5 -my-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:D?o("sessions.switcher.draftTitle"):xs}),$||Nt||!D&&Dt?s.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[$?s.jsx("span",{className:"truncate",children:$}):null,Nt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:Nt})]}):null,!D&&Dt?s.jsxs("span",{className:Pe("inline-flex min-w-0 items-center gap-0.5",Dt==="attention"||Dt==="invalid"||Dt==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(I,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:Vt})]}):null]}):null]})}),Gn.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Gn.map(Q=>Fr(Q))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ot&&he?s.jsx(cb,{totalTokens:he.totalTokens,percentage:ns,colorPercentage:he.percentage,contextLimit:he.contextLimit,outputLimit:he.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:Gt,pressed:mt,className:hr?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,Yr,s.jsx(Uo,{visible:hr,title:o(D?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(D?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:It,className:Pe(zs,"mr-1"),Icon:"picture-in-picture-2"}),ui,s.jsx(db,{visible:Be})]})]})]}),fn=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t?s.jsx("button",{type:"button",onClick:dn,className:Pe(Sn,Fn==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(I,{name:"layout-left",className:"h-5 w-5"})}):P?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(I,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:et,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.openSessionsAria"),children:s.jsx(I,{name:"play-list-add",className:"h-5 w-5"})}),!t&&P&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!P||!!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:Gn.map(Q=>{const tt=x===Q.id,pt=Q.icon==="diff",Pt=pt?null:Q.icon;return s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{ue&&(we(),Zn()),h(Q.id)},"aria-label":Q.label,"aria-selected":tt,role:"tab",className:Pe(Sn,"relative rounded-lg",Fn===Q.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[pt?s.jsx(Xd,{className:"h-5 w-5"}):Pt?s.jsx(I,{name:Pt,className:"h-5 w-5"}):null,Q.badge!==void 0&&Q.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:Q.badge}),Q.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(Ft,{children:s.jsx("p",{children:Q.label})})]},Q.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[Fs&&s.jsx(Pm,{projectRef:Fs.projectRef,directory:Fs.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(nn,{open:ve,onOpenChange:Q=>{Q&&(n&&t&&t(),r&&e&&e()),G(Q),Q&&V.length===0&&z()},children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:Pe(Sn,Fn==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(I,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(sn,{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(To,{items:er,activeId:xt,onSelect:Q=>{const tt=Q;St(tt),tt==="usage"&&V.length===0&&z()},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(I,{name:"close",className:"h-5 w-5"})})]})}),xt==="mcp"&&s.jsx(ym,{active:ve&&xt==="mcp"}),xt==="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:Tm(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:()=>qt("usage"),className:Pe("typography-ui-label px-1 pb-0.5 transition-colors",te==="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:()=>qt("remaining"),className:Pe("typography-ui-label px-1 pb-0.5 transition-colors",te==="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:Pe("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:rs,disabled:F||Re,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(I,{name:"refresh",className:Pe("h-4 w-4",Re&&"animate-spin")})})]})]})}),!Wt&&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:ls.map((Q,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(Do,{providerId:Q.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Q.providerName})]}),Q.entries.length===0&&(!Q.modelFamilies||Q.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Q.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[Q.entries.map(([pt,Pt])=>{const es=te==="remaining"?Pt.remainingPercent:Pt.usedPercent,is=ja(Pt.usedPercent,Pt.resetAt,Pt.windowSeconds,pt),fs=is?.dailyAllocationPercent!=null?te==="remaining"?100-ri(is.elapsedRatio):ri(is.elapsedRatio):null,Es=Io(Pt.valueLabel,es),Ys=$f(Pt.resetAt,Pt.resetAfterFormatted??Pt.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:bc(pt)}),Ys?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Ys}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Es==="-"?"":Es})]}),s.jsx(Aa,{percent:es,tonePercent:Pt.usedPercent,className:"h-1.5",expectedMarkerPercent:fs}),is&&q?s.jsx(Da,{paceInfo:is,compact:!0}):null]},`${Q.providerId}-${pt}`)}),Q.modelFamilies&&Q.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:Q.modelFamilies.map(pt=>{const es=(vt[Q.providerId]??[]).includes(pt.familyId??"other");return s.jsxs(eo,{open:es,onOpenChange:()=>bt(Q.providerId,pt.familyId??"other"),children:[s.jsxs(Bo,{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}),es?s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(to,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:pt.models.map(([is,fs])=>{const Es=te==="remaining"?fs.remainingPercent:fs.usedPercent,Ys=ja(fs.usedPercent,fs.resetAt,fs.windowSeconds),tr=Ys?.dailyAllocationPercent!=null?te==="remaining"?100-ri(Ys.elapsedRatio):ri(Ys.elapsedRatio):null,qn=Io(fs.valueLabel,Es);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:bm(is)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:qn==="-"?"":qn})]}),s.jsx(Aa,{percent:Es,tonePercent:fs.usedPercent,className:"h-1.5",expectedMarkerPercent:tr}),Ys&&q?s.jsx(Da,{paceInfo:Ys,compact:!0}):null]},`${Q.providerId}-${is}`)})})})]},pt.familyId??"other")})})]})]},Q.providerId))})]})]})})]}),e?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Ue,className:Pe(Sn,"relative",Fn==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(I,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ft,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),An=Pe("header-safe-area relative z-10 bg-background",ue&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:ke,className:An,style:{"--padding-scale":"1"},children:ue?fn():ds()}),s.jsx(vm,{open:qe,onOpenChange:Ge,info:Je,downloading:!1,downloaded:!1,progress:null,error:_e,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function Xb(){}const nu=180,ru=640,Zb=110,ey=t=>{const e=ft.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=kt(),c=Ee(ty),l=Ee(sy),d=Ee(ny),u=Ee(ry),[m,f]=i.useState(null),[p,y]=i.useState(!1),g=i.useRef(null),b=i.useRef(0),x=i.useRef(c||300),h=Math.min(ru,Math.max(nu,c||300));let C,w;e[0]!==n?(C=()=>{n||(f(null),y(!1))},w=[n],e[0]=n,e[1]=C,e[2]=w):(C=e[1],w=e[2]),i.useEffect(C,w);let v,S;e[3]!==l||e[4]!==r||e[5]!==n?(v=()=>{if(r||!n||!l)return;const X=()=>{const Se=g.current?.parentElement?.getBoundingClientRect().height;if(!Se||Se<=0)return;const Z=Math.max(0,Math.round(Se));f(ke=>ke===Z?ke:Z)};X();const oe=g.current?.parentElement;if(!oe)return;const ue=new ResizeObserver(X);return ue.observe(oe),()=>{ue.disconnect()}},S=[l,r,n],e[3]=l,e[4]=r,e[5]=n,e[6]=v,e[7]=S):(v=e[6],S=e[7]),i.useEffect(v,S);let k,j;if(e[8]!==l||e[9]!==r||e[10]!==p||e[11]!==d||e[12]!==u?(k=()=>{if(r||!p||l)return;const X=ue=>{const Se=b.current-ue.clientY,Z=Math.min(ru,Math.max(nu,x.current+Se));d(Z)},oe=()=>{y(!1),Ee.getState().bottomTerminalHeight<=Zb&&u(!1)};return window.addEventListener("pointermove",X),window.addEventListener("pointerup",oe,{once:!0}),()=>{window.removeEventListener("pointermove",X),window.removeEventListener("pointerup",oe)}},j=[l,r,p,d,u],e[8]=l,e[9]=r,e[10]=p,e[11]=d,e[12]=u,e[13]=k,e[14]=j):(k=e[13],j=e[14]),i.useEffect(k,j),r)return null;const A=n?l?Math.max(0,m??h):h:0,D=n&&l;let N;e[15]!==A||e[16]!==l||e[17]!==n?(N=X=>{!n||l||(y(!0),b.current=X.clientY,x.current=A,X.preventDefault())},e[15]=A,e[16]=l,e[17]=n,e[18]=N):N=e[18];const B=N,T=D?"absolute inset-x-0 bottom-0 z-40":"relative",E=p?"transition-none":"transition-[height] duration-300 ease-in-out",_=(!n||D)&&"border-t-0";let R;e[19]!==_||e[20]!==T||e[21]!==E?(R=Pe("flex overflow-hidden border-t border-border bg-sidebar",T,E,_),e[19]=_,e[20]=T,e[21]=E,e[22]=R):R=e[22];let $;e[23]!==A||e[24]!==D?($=D?{top:0}:{height:`${A}px`,minHeight:`${A}px`,maxHeight:`${A}px`},e[23]=A,e[24]=D,e[25]=$):$=e[25];const V=!n||!l&&A===0;let z;e[26]!==B||e[27]!==l||e[28]!==n||e[29]!==p||e[30]!==a?(z=n&&!l&&s.jsx("div",{className:Pe("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:B,role:"separator","aria-orientation":"horizontal","aria-label":a("terminalView.bottomDock.resizeAria")}),e[26]=B,e[27]=l,e[28]=n,e[29]=p,e[30]=a,e[31]=z):z=e[31];const F=!n&&"pointer-events-none select-none opacity-0";let ne;e[32]!==F?(ne=Pe("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",F),e[32]=F,e[33]=ne):ne=e[33];const te=!n;let q;e[34]!==o||e[35]!==ne||e[36]!==te?(q=s.jsx("div",{className:ne,"aria-hidden":te,children:o}),e[34]=o,e[35]=ne,e[36]=te,e[37]=q):q=e[37];let H;return e[38]!==R||e[39]!==$||e[40]!==V||e[41]!==z||e[42]!==q?(H=s.jsxs("section",{ref:g,className:R,style:$,"aria-hidden":V,children:[z,q]}),e[38]=R,e[39]=$,e[40]=V,e[41]=z,e[42]=q,e[43]=H):H=e[43],H};function ty(t){return t.bottomTerminalHeight}function sy(t){return t.isBottomTerminalExpanded}function ny(t){return t.setBottomTerminalHeight}function ry(t){return t.setBottomTerminalOpen}const iu=280,ou=280,au=500,iy=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=kt(),c=Ee(j=>j.sidebarWidth),l=Ee(j=>j.setSidebarWidth),[d,u]=i.useState(!1),m=i.useRef(0),f=i.useRef(c||iu),p=i.useRef(null),y=i.useRef(null),g=i.useRef(null),b=i.useCallback(j=>Math.min(au,Math.max(ou,j)),[]),x=i.useCallback(j=>{const A=g.current;A&&(A.style.width=`${j}px`,A.style.minWidth=`${j}px`,A.style.maxWidth=`${j}px`,A.style.setProperty("--oc-left-sidebar-width",`${j}px`))},[]);if(i.useEffect(()=>{e&&d&&u(!1)},[e,d]),i.useEffect(()=>{d||(p.current=null,y.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{}y.current=j.pointerId,u(!0),m.current=j.clientX,f.current=C,p.current=C,x(C),j.preventDefault()}},v=j=>{if(e||!d||y.current!==j.pointerId)return;const A=j.clientX-m.current,D=b(f.current+A);p.current!==D&&(p.current=D,x(D))},S=j=>{if(y.current!==j.pointerId||e)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const A=b(p.current??C);y.current=null,p.current=null,u(!1),l(A)},k=d?p.current??C:C;return s.jsxs("aside",{ref:g,className:Pe("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:Pe("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:v,onPointerUp:S,onPointerCancel:S,role:"separator","aria-orientation":"vertical","aria-label":a("sidebar.resize.leftPanelAria")}),s.jsxs("div",{className:Pe("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(en,{children:n})})]})]})},oy=()=>{const t=ft.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},Ho=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function ay(){const t=Ns(f=>f.activeProjectId?f.projects.find(p=>p.id===f.activeProjectId)??null:null),e=ut(f=>f.currentSessionId),n=Wf(e??null),r=ut(f=>e?f.worktreeMetadata.get(e)?.path??"":""),o=ut(f=>f.newSessionDraft?.open?Ho(f.newSessionDraft.bootstrapPendingDirectory??f.newSessionDraft.directoryOverride??""):""),a=i.useMemo(()=>Ho(r||""),[r]),c=i.useMemo(()=>{const f=typeof n?.directory=="string"?n.directory:"";return Ho(f||"")},[n?.directory]),l=a||c||o,d=i.useMemo(()=>Ho(l||t?.path||""),[t?.path,l]),u=i.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),m=i.useRef(null);return i.useEffect(()=>{u&&d&&(m.current={projectRef:u,directory:d})},[d,u]),i.useMemo(()=>u&&d?{projectRef:u,directory:d}:m.current,[u,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",ly=()=>{const t=ft.c(31),{t:e}=kt(),n=Ee(cy),r=Ee(dy),o=Ee(uy),a=ay(),c=i.useRef(null),l=_a(ii("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const u=d,m=my;let f,p;t[0]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{if(typeof document>"u")return;const _=c.current;if(!_)return;const R=()=>{const V=_.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(V)}px`)};if(R(),typeof ResizeObserver>"u")return;const $=new ResizeObserver(R);return $.observe(_),()=>{$.disconnect()}},p=[],t[0]=f,t[1]=p):(f=t[0],p=t[1]),i.useEffect(f,p);const y="app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2";let g;t[2]===Symbol.for("react.memo_cache_sentinel")?(g={height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},t[2]=g):g=t[2];const b="flex items-center gap-2";let x;t[3]!==e?(x=u?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,"aria-label":e("header.actions.openAppMenuAria"),className:Pe(lu,"shrink-0"),children:s.jsx(I,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ft,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=x):x=t[4];const h=Et;let C;t[5]!==e?(C=e("header.actions.openSessionsAria"),t[5]=e,t[6]=C):C=t[6];let w,v;t[7]===Symbol.for("react.memo_cache_sentinel")?(w=Pe(lu,"shrink-0"),v=s.jsx(I,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=w,t[8]=v):(w=t[7],v=t[8]);let S;t[9]!==C||t[10]!==n?(S=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":C,className:w,children:v})}),t[9]=C,t[10]=n,t[11]=S):S=t[11];const k=Ft,j=e("header.actions.openSessionsWithShortcut",{shortcut:l});let A;t[12]!==j?(A=s.jsx("p",{children:j}),t[12]=j,t[13]=A):A=t[13];let D;t[14]!==k||t[15]!==A?(D=s.jsx(k,{children:A}),t[14]=k,t[15]=A,t[16]=D):D=t[16];let N;t[17]!==h||t[18]!==S||t[19]!==D?(N=s.jsxs(h,{children:[S,D]}),t[17]=h,t[18]=S,t[19]=D,t[20]=N):N=t[20];let B;t[21]!==r||t[22]!==a?(B=a?s.jsx(Pm,{projectRef:a.projectRef,directory:a.directory,className:r?"oc-vibrancy-pill":void 0}):null,t[21]=r,t[22]=a,t[23]=B):B=t[23];let T;t[24]!==N||t[25]!==B||t[26]!==x?(T=s.jsxs("div",{ref:c,className:b,children:[x,N,B]}),t[24]=N,t[25]=B,t[26]=x,t[27]=T):T=t[27];let E;return t[28]!==T||t[29]!==g?(E=s.jsx("div",{className:y,style:g,children:T}),t[28]=T,t[29]=g,t[30]=E):E=t[30],E};function cy(t){return t.toggleSidebar}function dy(t){return t.isSidebarOpen}function uy(t){return t.shortcutOverrides}function fy(t){console.warn("[titlebar] failed to open app menu",t)}function my(t){const e=t.currentTarget.getBoundingClientRect();Hr("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(fy)}const cu=420,hy=({isOpen:t,children:e,className:n})=>{const{t:r}=kt(),o=Ee(S=>S.rightSidebarWidth),a=Ee(S=>S.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),u=i.useRef(o||cu),m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),y=i.useCallback(S=>Math.min(yd,Math.max(wd,S)),[]),g=i.useCallback(S=>{const k=p.current;k&&(k.style.width=`${S}px`,k.style.minWidth=`${S}px`,k.style.maxWidth=`${S}px`,k.style.setProperty("--oc-right-sidebar-width",`${S}px`))},[]),b=Math.min(yd,Math.max(wd,o||cu)),x=t?b:0,h=S=>{if(t){try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}f.current=S.pointerId,l(!0),d.current=S.clientX,u.current=x,m.current=x,g(x),S.preventDefault()}},C=S=>{if(!c||f.current!==S.pointerId)return;const k=d.current-S.clientX,j=y(u.current+k);m.current!==j&&(m.current=j,g(j))},w=S=>{if(f.current!==S.pointerId)return;try{S.currentTarget.releasePointerCapture(S.pointerId)}catch{}const k=y(m.current??x);f.current=null,m.current=null,l(!1),a(k)},v=c?m.current??x:x;return s.jsxs("aside",{ref:p,className:Pe("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:`${v}px`,"--oc-right-sidebar-width":`${c?v:b}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||x===0,children:[t&&s.jsx("div",{className:Pe("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:Pe("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 Rm(t){const e=ft.c(120),{t:n}=kt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,onConfirm:d}=t,u=l===void 0?!1:l,m=ss(Ny),f=ss(Sy),p=Fp(jy),y=ss(vy),g=ss(wy),b=ss(yy),x=ss(by),h=ss(xy);let C;e[0]!==h||e[1]!==b||e[2]!==g||e[3]!==x?(C=()=>du({providerID:g,modelID:b,variant:x,agent:h}),e[0]=h,e[1]=b,e[2]=g,e[3]=x,e[4]=C):C=e[4];const[w,v]=i.useState(C);let S,k;e[5]!==p||e[6]!==f||e[7]!==m||e[8]!==r||e[9]!==c?(S=()=>{r&&(m({directory:c,source:"todoSendDialog"}),f({directory:c}),p())},k=[r,m,f,p,c],e[5]=p,e[6]=f,e[7]=m,e[8]=r,e[9]=c,e[10]=S,e[11]=k):(S=e[10],k=e[11]),i.useEffect(S,k);let j,A;e[12]!==h||e[13]!==b||e[14]!==g||e[15]!==x||e[16]!==r?(j=()=>{r&&v(du({providerID:g,modelID:b,variant:x,agent:h}))},A=[r,g,b,x,h],e[12]=h,e[13]=b,e[14]=g,e[15]=x,e[16]=r,e[17]=j,e[18]=A):(j=e[17],A=e[18]),i.useEffect(j,A);let D,N;e[19]!==w.modelID||e[20]!==w.providerID||e[21]!==r||e[22]!==y?(D=()=>{if(!r||y.length===0)return;const ye=y.find(L=>L.id===w.providerID)??y[0],Le=Array.isArray(ye?.models)?ye.models:[],Re=Le.some(L=>L.id===w.modelID),J=Le[0]?.id??"";ye?.id===w.providerID&&Re||v(L=>({...L,providerID:ye?.id??"",modelID:Re?L.modelID:J,variant:""}))},N=[r,y,w.providerID,w.modelID],e[19]=w.modelID,e[20]=w.providerID,e[21]=r,e[22]=y,e[23]=D,e[24]=N):(D=e[23],N=e[24]),i.useEffect(D,N);const B=gy;let T;if(e[25]!==w.modelID||e[26]!==w.providerID||e[27]!==y){let ye;e[29]!==w.providerID?(ye=Re=>Re.id===w.providerID,e[29]=w.providerID,e[30]=ye):ye=e[30],T=y.find(ye)?.models?.find(Re=>Re.id===w.modelID),e[25]=w.modelID,e[26]=w.providerID,e[27]=y,e[28]=T}else T=e[28];const E=T;let _;e[31]!==E?(_=E?.variants?Object.keys(E.variants):[],e[31]=E,e[32]=_):_=e[32];const R=_,$=R.length>0;let V,z;e[33]!==w.variant||e[34]!==$?(V=()=>{$||!w.variant||v(py)},z=[$,w.variant],e[33]=w.variant,e[34]=$,e[35]=V,e[36]=z):(V=e[35],z=e[36]),i.useEffect(V,z);let F;e[37]!==w.modelID||e[38]!==w.providerID?(F=w.providerID.trim().length>0&&w.modelID.trim().length>0,e[37]=w.modelID,e[38]=w.providerID,e[39]=F):F=e[39];const ne=F;let te;e[40]!==ne||e[41]!==w||e[42]!==d||e[43]!==u?(te=()=>{!ne||u||d(w)},e[40]=ne,e[41]=w,e[42]=d,e[43]=u,e[44]=te):te=e[44];const q=te;let H,X;e[45]!==q||e[46]!==r?(H=()=>{if(!r)return;const ye=Le=>{(Le.metaKey||Le.ctrlKey)&&Le.key==="Enter"&&(Le.preventDefault(),q())};return window.addEventListener("keydown",ye),()=>window.removeEventListener("keydown",ye)},X=[r,q],e[45]=q,e[46]=r,e[47]=H,e[48]=X):(H=e[47],X=e[48]),i.useEffect(H,X);let oe;e[49]!==n||e[50]!==a?(oe=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[49]=n,e[50]=a,e[51]=oe):oe=e[51];const ue=oe;let Se;e[52]!==o||e[53]!==u?(Se=ye=>{u||o(ye)},e[52]=o,e[53]=u,e[54]=Se):Se=e[54];let Z;e[55]!==ue?(Z=s.jsx(Gs,{children:s.jsx(Us,{children:ue})}),e[55]=ue,e[56]=Z):Z=e[56];let ke;e[57]!==n?(ke=n("chat.modelControls.model"),e[57]=n,e[58]=ke):ke=e[58];let Y;e[59]!==ke?(Y=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ke}),e[59]=ke,e[60]=Y):Y=e[60];let ge;e[61]===Symbol.for("react.memo_cache_sentinel")?(ge=(ye,Le)=>{v(Re=>({...Re,providerID:ye,modelID:Le,variant:""}))},e[61]=ge):ge=e[61];let O;e[62]!==w.modelID||e[63]!==w.providerID?(O=s.jsx(Qf,{providerId:w.providerID,modelId:w.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:ge}),e[62]=w.modelID,e[63]=w.providerID,e[64]=O):O=e[64];let se;e[65]!==Y||e[66]!==O?(se=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[Y,O]}),e[65]=Y,e[66]=O,e[67]=se):se=e[67];let ee;e[68]!==n?(ee=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[68]=n,e[69]=ee):ee=e[69];let je;e[70]!==ee?(je=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ee}),e[70]=ee,e[71]=je):je=e[71];const De=!$;let Be;e[72]===Symbol.for("react.memo_cache_sentinel")?(Be=ye=>v(Le=>({...Le,variant:ye})),e[72]=Be):Be=e[72];let Fe;e[73]!==w.variant||e[74]!==De||e[75]!==R?(Fe=s.jsx(Lp,{value:w.variant,options:R,disabled:De,onChange:Be}),e[73]=w.variant,e[74]=De,e[75]=R,e[76]=Fe):Fe=e[76];let Me;e[77]!==je||e[78]!==Fe?(Me=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[je,Fe]}),e[77]=je,e[78]=Fe,e[79]=Me):Me=e[79];let me;e[80]!==n?(me=n("sessions.scheduledTasks.editor.agent.label"),e[80]=n,e[81]=me):me=e[81];let Ae;e[82]!==me?(Ae=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:me}),e[82]=me,e[83]=Ae):Ae=e[83];let pe;e[84]===Symbol.for("react.memo_cache_sentinel")?(pe=ye=>v(Le=>({...Le,agent:ye})),e[84]=pe):pe=e[84];let ce;e[85]!==w.agent?(ce=s.jsx(Jf,{agentName:w.agent,filter:B,dropdownPortalToBody:!0,onChange:pe}),e[85]=w.agent,e[86]=ce):ce=e[86];let he;e[87]!==Ae||e[88]!==ce?(he=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Ae,ce]}),e[87]=Ae,e[88]=ce,e[89]=he):he=e[89];let Ne;e[90]!==se||e[91]!==Me||e[92]!==he?(Ne=s.jsxs("div",{className:"flex flex-col gap-4",children:[se,Me,he]}),e[90]=se,e[91]=Me,e[92]=he,e[93]=Ne):Ne=e[93];let fe;e[94]!==o?(fe=()=>o(!1),e[94]=o,e[95]=fe):fe=e[95];let P;e[96]!==n?(P=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[96]=n,e[97]=P):P=e[97];let M;e[98]!==u||e[99]!==fe||e[100]!==P?(M=s.jsx($e,{variant:"ghost",size:"sm",onClick:fe,disabled:u,children:P}),e[98]=u,e[99]=fe,e[100]=P,e[101]=M):M=e[101];const de=!ne||u;let xe;e[102]!==u||e[103]!==n?(xe=n(u?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[102]=u,e[103]=n,e[104]=xe):xe=e[104];let W;e[105]!==q||e[106]!==de||e[107]!==xe?(W=s.jsx($e,{size:"sm",onClick:q,disabled:de,children:xe}),e[105]=q,e[106]=de,e[107]=xe,e[108]=W):W=e[108];let be;e[109]!==M||e[110]!==W?(be=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[M,W]}),e[109]=M,e[110]=W,e[111]=be):be=e[111];let ve;e[112]!==Z||e[113]!==Ne||e[114]!==be?(ve=s.jsxs(Vs,{className:"max-w-md overflow-visible",children:[Z,Ne,be]}),e[112]=Z,e[113]=Ne,e[114]=be,e[115]=ve):ve=e[115];let G;return e[116]!==r||e[117]!==Se||e[118]!==ve?(G=s.jsx($s,{open:r,onOpenChange:Se,children:ve}),e[116]=r,e[117]=Se,e[118]=ve,e[119]=G):G=e[119],G}function py(t){return{...t,variant:""}}function gy(t){return jc(t.mode)}function xy(t){return t.currentAgentName||""}function by(t){return t.currentVariant||""}function yy(t){return t.currentModelId}function wy(t){return t.currentProviderId}function vy(t){return t.providers}function jy(t){return t.loadAgents}function Sy(t){return t.loadAgents}function Ny(t){return t.loadProviders}const Zl=5,Em=15,Go=new Map,la=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},ky=(t,e)=>{const n=la(e);return Math.max(n*Zl,Math.min(n*Em,n*t))},Cy=async(t,e)=>{const n=await Vp(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},Ay=()=>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)]},Dy=t=>{const e=ft.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:u,transition:m,isDragging:f}=fc(o);let p;e[2]!==u?(p=mc.Transform.toString(u),e[2]=u,e[3]=p):p=e[3];let y;e[4]!==p||e[5]!==m?(y={transform:p,transition:m},e[4]=p,e[5]=m,e[6]=y):y=e[6];const g=f&&"opacity-60";let b;e[7]!==g?(b=Pe(g),e[7]=g,e[8]=b):b=e[8];let x;e[9]!==a||e[10]!==r||e[11]!==f||e[12]!==c||e[13]!==d?(x=r({attributes:a,listeners:c,setActivatorNodeRef:d,isDragging:f}),e[9]=a,e[10]=r,e[11]=f,e[12]=c,e[13]=d,e[14]=x):x=e[14];let h;return e[15]!==l||e[16]!==y||e[17]!==b||e[18]!==x?(h=s.jsx("li",{ref:l,style:y,className:b,children:x}),e[15]=l,e[16]=y,e[17]=b,e[18]=x,e[19]=h):h=e[19],h},Iy=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=kt(),[c,l]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState([]),[p,y]=i.useState(""),[g,b]=i.useState(null),[x,h]=i.useState(()=>new Set),[C,w]=i.useState([]),[v,S]=i.useState(null),[k,j]=i.useState(!1),[A,D]=i.useState(0),N=i.useRef(!1),B=i.useRef(""),T=i.useRef(null),E=Ee(L=>L.todoPanelHeight),_=Ee(L=>L.setTodoPanelHeight),R=Ee(L=>L.notesPanelHeight),$=Ee(L=>L.setNotesPanelHeight),[V,z]=i.useState(!1),F=i.useRef(0),ne=i.useRef(E),te=ut(L=>L.currentSessionId),q=ut(L=>L.createSession),H=ut(L=>L.initializeNewOpenChamberSession),X=ut(L=>L.sendMessage),oe=ut(L=>L.setCurrentSession),ue=ci(L=>L.setPendingInputText),Se=Xs(L=>L.currentDirectory),Z=Ee(L=>L.openContextPanelTab),ke=Ee(L=>L.setActiveMainTab),Y=Ee(L=>L.setSessionSwitcherOpen),ge=Ee(L=>L.padding),O=i.useCallback(async(L,ae)=>{if(!t)return!1;const re=t.id,qe=(Go.get(re)??Promise.resolve()).catch(()=>{}).then(()=>Op(t,{notes:L,todos:ae}));Go.set(re,qe);try{const Ge=await qe;return Ge||le.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),Ge}finally{Go.get(re)===qe&&Go.delete(re)}},[t,a]);i.useEffect(()=>{if(!t){u(""),f([]),w([]),y(""),h(new Set);return}let L=!1;return l(!0),(async()=>{try{const ae=await Bp(t),re=await Promise.all(ae.plans.map(Oe=>Cy(Oe,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(L)return;u(ae.notes),f(uu(ae.todos)),w(re),B.current=ae.notes,N.current=!0,y(""),h(new Set)}catch{L||(le.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),u(""),f([]),w([]),B.current="",N.current=!0)}finally{L||l(!1)}})(),()=>{L=!0}},[A,t,a]),i.useEffect(()=>{if(!t)return;const L=ae=>{const re=ae.detail;re?.projectId&&re.projectId!==t.id||D(Oe=>Oe+1)};return window.addEventListener("openchamber:project-plan-saved",L),window.addEventListener("openchamber:project-notes-updated",L),()=>{window.removeEventListener("openchamber:project-plan-saved",L),window.removeEventListener("openchamber:project-notes-updated",L)}},[t]),i.useEffect(()=>{if(m.length<7)return;const L=ky(m.length,ge),ae=la(ge)*Zl;E!==L&&(E<ae||E>L)&&_(L)},[m.length,ge,E,_]),i.useEffect(()=>{if(!V)return;const L=re=>{const Oe=re.clientY-F.current,qe=Math.min(la(ge)*Em,Math.max(la(ge)*Zl,ne.current+Oe));_(qe)},ae=()=>{z(!1)};return window.addEventListener("pointermove",L),window.addEventListener("pointerup",ae,{once:!0}),window.addEventListener("pointercancel",ae,{once:!0}),()=>{window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",ae),window.removeEventListener("pointercancel",ae)}},[V,ge,_]);const se=i.useCallback(L=>{z(!0),F.current=L.clientY,ne.current=E,L.preventDefault()},[E]),ee=i.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),je=i.useCallback(()=>{ee(),B.current=d,O(d,m)},[ee,d,O,m]);i.useEffect(()=>{if(!(!t||!N.current)&&d!==B.current)return T.current=window.setTimeout(()=>{T.current=null,B.current=d,O(d,m)},400),()=>{ee()}},[ee,d,O,t,m]),i.useEffect(()=>()=>ee(),[ee]);const De=i.useCallback(()=>{const L=p.trim();if(!L)return;const ae=fu(m,{id:Ay(),text:L.slice(0,zo),completed:!1,createdAt:Date.now()});f(ae),y(""),O(d,ae)},[p,d,O,m]),Be=i.useCallback(L=>{h(ae=>{const re=new Set(ae);return re.has(L)?re.delete(L):re.add(L),re})},[]),Fe=i.useCallback((L,ae)=>{const re=m.find(Je=>Je.id===L);if(!re||re.completed===ae)return;const Oe=m.filter(Je=>Je.id!==L),qe={...re,completed:ae},Ge=ae?[...Oe,qe]:fu(Oe,qe);f(Ge),O(d,Ge)},[d,O,m]),Me=i.useCallback(L=>{const ae=m.filter(re=>re.id!==L);f(ae),O(d,ae)},[d,O,m]),me=i.useCallback(()=>{const L=m.filter(ae=>!ae.completed);L.length!==m.length&&(f(L),O(d,L))},[d,O,m]),Ae=i.useCallback(L=>{const{active:ae,over:re}=L;if(!re||ae.id===re.id)return;const Oe=m.findIndex(Je=>Je.id===ae.id),qe=m.findIndex(Je=>Je.id===re.id);if(Oe===-1||qe===-1)return;const Ge=uu(Ff(m,Oe,qe));f(Ge),O(d,Ge)},[d,O,m]),pe=xa(yo(ba,{activationConstraint:{distance:8}})),ce=p.slice(0,zo),he=m.reduce((L,ae)=>L+(ae.completed?1:0),0),Ne=i.useCallback(()=>{ke("chat"),Y(!1)},[ke,Y]),fe=i.useCallback((L,ae)=>{!t||g||S({kind:"session",todoId:L,todoText:ae})},[t,g]),P=i.useCallback(L=>{if(!te){le.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}Ne();const ae=`\`\`\`md
4
- ${L}
5
- \`\`\``;ue(ae,"append"),le.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[te,r,Ne,ue,a]),M=i.useCallback((L,ae)=>{if(!(!t||g)){if(!n){le.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}S({kind:"worktree",todoId:L,todoText:ae})}},[n,t,g,a]),de=i.useCallback(async L=>{if(!t||!v)return;const ae=await En("plan.todo.visible",{todo_text:v.todoText}),Oe=[{synthetic:!0,text:await En("plan.todo.instructions",{todo_text:v.todoText})}];j(!0),b(v.todoId);try{Ne();let qe=null,Ge=t.path;if(v.kind==="worktree"){if(!n){le.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const nt=await Xf(t.path,Zf());if(!nt?.id)return;qe=nt.id,Ge=nt.path}else{const nt=await q(void 0,t.path,null);if(!nt?.id){le.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}qe=nt.id,Ge=nt.directory??t.path,H(nt.id,ss.getState().agents??[])}if(!qe)return;const Je=Sc.getState();Je.saveSessionModelSelection(qe,L.providerID,L.modelID),L.agent.trim()&&(Je.saveSessionAgentSelection(qe,L.agent),Je.saveAgentModelForSession(qe,L.agent,L.providerID,L.modelID),Je.saveAgentModelVariantForSession(qe,L.agent,L.providerID,L.modelID,L.variant||void 0)),oe(qe,Ge),await X(ae,L.providerID,L.modelID,L.agent.trim()||void 0,void 0,void 0,Oe,L.variant||void 0),le.success(v.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),S(null),r?.()}catch(qe){const Ge=qe instanceof Error?qe.message:void 0;le.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),Ge?{description:Ge}:void 0)}finally{j(!1),b(null)}},[n,q,H,r,v,t,Ne,X,oe,a]),xe=i.useRef(null),[W,be]=i.useState(!1),[ve,G]=i.useState(null),ye=i.useCallback(async L=>{if(!(!t||ve)){G(L);try{if(!await _p(t,L)){le.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}w(re=>re.filter(Oe=>Oe.id!==L)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{G(null)}}},[ve,t,a]),Le=i.useCallback(async()=>{if(!t||W)return;const L=await hp({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(L.success&&L.path){be(!0);try{const ae=new URLSearchParams({path:L.path,allowOutsideWorkspace:"true"});L.outsideFileGrant&&ae.set("outsideFileGrant",L.outsideFileGrant);const re=await Cs(`/api/fs/read?${ae.toString()}`,{cache:"no-store"});if(!re.ok){le.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const Oe=await re.text();if(!Oe.trim()){le.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const qe=L.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Dd(t,Oe,qe)){le.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),le.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(ae){const re=ae instanceof Error?ae.message:void 0;le.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),re?{description:re}:void 0)}finally{be(!1)}}else L.error==="Native file picker not available"&&xe.current?.click()},[W,t,a]),Re=i.useCallback(async L=>{if(!(!t||!L)){be(!0);try{const ae=await L.text();if(!ae.trim()){le.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const re=L.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Dd(t,ae,re)){le.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),le.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(ae){const re=ae instanceof Error?ae.message:void 0;le.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),re?{description:re}:void 0)}finally{be(!1)}}},[t,a]),J=i.useCallback(L=>{const ae=t?.path?.trim(),re=Se?.trim()||ae;re&&Z(re,{mode:"plan",targetPath:L.path,dedupeKey:L.path,label:L.title})},[Se,Z,t]);return t?s.jsxs("div",{className:Pe("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,"/",Id]})]}),s.jsx(Ni,{value:d,onChange:L=>u(L.target.value.slice(0,Id)),onBlur:je,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:R,onResizeHeightChange:$,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:me,disabled:c||he===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:[ce.length,"/",zo]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(jn,{value:ce,onChange:L=>y(L.target.value.slice(0,zo)),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),De())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:De,disabled:c||ce.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(I,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:Pe("overflow-y-auto rounded-lg border border-border/60 bg-background/40",V&&"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(ya,{sensors:pe,collisionDetection:wa,onDragEnd:Ae,children:s.jsx(Vl,{items:m.map(L=>L.id),strategy:$l,children:s.jsx("ul",{className:"divide-y divide-border/50",children:m.map(L=>{const ae=x.has(L.id);return s.jsx(Dy,{id:L.id,children:re=>s.jsxs("div",{className:Pe("flex gap-1.5 px-2.5 py-1.5",ae?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:re.setActivatorNodeRef,...re.attributes,...re.listeners,onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:L.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:L.text}),children:s.jsx(I,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(Pi,{checked:L.completed,onChange:Oe=>Fe(L.id,Oe),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:L.text})})}),s.jsx("button",{type:"button",onClick:()=>Be(L.id),className:Pe("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",ae?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",L.completed&&"text-muted-foreground line-through"),title:ae?void 0:L.text,"aria-label":ae?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:L.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:L.text}),children:L.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Me(L.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:L.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:L.text}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",disabled:g===L.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.send",{text:L.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:L.text}),children:s.jsx(I,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(sn,{align:"end",className:"w-56",children:[s.jsx(bs,{onClick:()=>P(L.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(bs,{onClick:()=>fe(L.id,L.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(bs,{onClick:()=>{M(L.id,L.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},L.id)})})})})}),m.length>=7&&s.jsx("div",{className:Pe("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",V&&"bg-[var(--interactive-border)]"),onPointerDown:se,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:xe,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:L=>{const ae=L.target.files?.[0]??null;Re(ae),L.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Le,disabled:!t||W,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(I,{name:"add",className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:C.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.plans.empty")}):s.jsx("ul",{className:"divide-y divide-border/50",children:C.map(L=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>J(L),className:"flex min-w-0 flex-1 items-center justify-between gap-3 rounded-md px-1.5 py-1 text-left hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-foreground",children:L.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(L.createdAt).toLocaleDateString(Xi())})]}),s.jsx("button",{type:"button",onClick:()=>{ye(L.id)},disabled:ve===L.id,className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",title:a("rightSidebar.contextNotesTodo.plans.deletePlan"),"aria-label":a("rightSidebar.contextNotesTodo.plans.deletePlanWithTitle",{title:L.title}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},L.id))})})]}),s.jsx(Rm,{open:v!==null,onOpenChange:L=>{!L&&!k&&S(null)},target:v?.kind??"session",projectDirectory:t?.path??null,submitting:k,onConfirm:de})]}):s.jsx("div",{className:Pe("w-full min-w-0 p-3",o),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.empty.selectProject")})})},Mm=12,Py=[{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"}],Ty=t=>{const e=ft.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,u=a===void 0?900:a,m=c===void 0?Py:c,f=Xe.useRef(!1);let p,y;e[0]!==n||e[1]!==l?(p=()=>{!n&&f.current&&l?.(),n&&(f.current=!0)},y=[n,l],e[0]=n,e[1]=l,e[2]=p,e[3]=y):(p=e[2],y=e[3]),Xe.useEffect(p,y);let g;e[4]===Symbol.for("react.memo_cache_sentinel")?(g=Array.from({length:Mm},Ry),e[4]=g):g=e[4];const b=g;if(!n)return null;let x;e[5]!==o?(x=Pe("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=x):x=e[6];let h;if(e[7]!==d||e[8]!==m||e[9]!==u){let w;e[11]!==d||e[12]!==u?(w=v=>{const S={"--burst-delay":`${v.delay}ms`,"--burst-x":`${v.x}%`,"--burst-y":`${v.y}%`,"--firework-color":`var(${v.colorVar})`,"--firework-duration":`${u}ms`};return s.jsx("div",{className:"firework-burst",style:S,children:b.map((k,j)=>{const A=k.x*v.radius,D=k.y*v.radius,N={"--translate-x":`${A}px`,"--translate-y":`${D}px`,"--particle-delay":`${k.delay}ms`,color:`var(${v.colorVar})`};return s.jsx("span",{className:"firework-particle",style:N},`${v.id}-${j}-${d}`)})},`${v.id}-${d}`)},e[11]=d,e[12]=u,e[13]=w):w=e[13],h=m.map(w),e[7]=d,e[8]=m,e[9]=u,e[10]=h}else h=e[10];let C;return e[14]!==d||e[15]!==x||e[16]!==h?(C=s.jsx("div",{className:x,"aria-hidden":"true","data-burst-key":d,children:h}),e[14]=d,e[15]=x,e[16]=h,e[17]=C):C=e[17],C};function Ry(t,e){const n=Math.PI*2*e/Mm;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const Ey=t=>{const e=ft.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 u;e[3]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{d.current&&(window.clearTimeout(d.current),d.current=null)},e[3]=u):u=e[3];const m=u;let f;e[4]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{m(),l(My)},e[4]=f):f=e[4];const p=f;let y;e[5]!==o?(y=()=>{m(),l(Fy),d.current=window.setTimeout(()=>{l(Ly),d.current=null},o)},e[5]=o,e[6]=y):y=e[6];const g=y;let b,x;e[7]===Symbol.for("react.memo_cache_sentinel")?(b=()=>()=>m(),x=[m],e[7]=b,e[8]=x):(b=e[7],x=e[8]),Xe.useEffect(b,x);let h;return e[9]!==c.cycle||e[10]!==c.isActive||e[11]!==g?(h={isActive:c.isActive,burstKey:c.cycle,triggerFireworks:g,dismissFireworks:p},e[9]=c.cycle,e[10]=c.isActive,e[11]=g,e[12]=h):h=e[12],h};function My(t){return t.isActive?{...t,isActive:!1}:t}function Fy(t){return{isActive:!0,cycle:t.cycle+1}}function Ly(t){return t.isActive?{...t,isActive:!1}:t}const Fm=i.createContext(void 0),Oy=t=>{const e=ft.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=Ey();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 u;e[3]!==o||e[4]!==r?(u=s.jsx(Ty,{isActive:r,burstKey:o}),e[3]=o,e[4]=r,e[5]=u):u=e[5];let m;return e[6]!==n||e[7]!==u||e[8]!==d?(m=s.jsxs(Fm.Provider,{value:d,children:[n,u]}),e[6]=n,e[7]=u,e[8]=d,e[9]=m):m=e[9],m},By=()=>{const t=i.useContext(Fm);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Lm="gitmojiCache",_y=1e3*60*60*24*7,Om="1",Vy="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Bm=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(Lm);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==Om||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(Bm),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},$y=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:Om};window.localStorage.setItem(Lm,JSON.stringify(e))}catch{return}},mu=t=>Date.now()-t.fetchedAt<_y;let Ko=null;const So=new Set,hu=async()=>{if(Ko)return Ko;const t=(async()=>{try{const e=await fetch(Vy);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(Bm):[];return $y(r),So.forEach(o=>o(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return So.forEach(r=>r(n)),n}finally{Ko=null}})();return Ko=t,t},zy=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){So.delete(n),n([]),o(!1);return}const l=bl();if(l&&(n(l.gitmojis),mu(l)))return;So.add(n),o(!0);let d=!1;return hu().finally(()=>{!d&&a.current&&o(!1)}),()=>{d=!0,So.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 Wy(t,e,n){const r=ft.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[u,m]=await Promise.all([$p(t),zp(t)]).catch(Uy);if(d)return;const f=pu(u),p=pu(m);if(!f||!p||p===f)return;const y=n||"",g=p.split("/").filter(Boolean).pop()||p;a({source:"sdk",path:p,projectDirectory:f,branch:y,label:y||g,name:g,worktreeRoot:p,worktreeStatus:"ready",headState:y?"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 Uy(){return["",""]}const ao=async(t,e)=>{const n=await Cs(`/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 ho(t){return ao("plan",t)}async function Hy(t){return ao("conflict-details",{tempWorktreePath:t})}async function Gy(t){return(await ao("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function Ky(t){return ao("run",{plan:t})}async function qy(t){await ao("abort",{state:t})}async function Yy(t){return ao("continue",{state:t})}const Qy=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=kt(),d=ut(F=>F.currentSessionId),u=Ee(F=>F.setActiveMainTab),[m,f]=Xe.useState(!1),p=Xe.useRef(null),[y,g]=Xe.useState(o);Xe.useEffect(()=>{g(o)},[o]),Xe.useEffect(()=>{if(m){const F=setTimeout(()=>{p.current?.focus()},0);return()=>clearTimeout(F)}},[m]);const b=!!(t&&e&&y&&y!=="HEAD"&&e!==y),[x,h]=Xe.useState({kind:"idle"}),[C,w]=Xe.useState(!1),[v,S]=Xe.useState([]),k=Xe.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);Xe.useEffect(()=>{if(!k||typeof window>"u")return;const F=window.localStorage.getItem(k);if(!F)return;let ne=!1;try{const te=JSON.parse(F);if(!te?.tempWorktreePath||te.repoRoot!==t){window.localStorage.removeItem(k);return}(async()=>{const q=await Gy(te.tempWorktreePath).catch(()=>!1);if(ne)return;if(!q){window.localStorage.removeItem(k);return}const H=await Hy(te.tempWorktreePath).catch(()=>null);ne||H&&h({kind:"conflict",state:te,details:H})})()}catch{window.localStorage.removeItem(k)}return()=>{ne=!0}},[k,t]),Xe.useEffect(()=>{if(!b){h({kind:"idle"});return}let F=!1;return h({kind:"loading"}),(async()=>{try{const ne=await ho({repoRoot:t,sourceBranch:e,targetBranch:y});if(F)return;if(h({kind:"ready",plan:ne}),ne.commits.length>0){const q=ne.commits.slice(-50).reverse(),H=await Wp(t,q);F||(S(H),w(!1))}else F||(S([]),w(!1))}catch{F||h({kind:"idle"})}})(),()=>{F=!0}},[b,t,e,y,a]);const j=Xe.useCallback(F=>{d&&ut.getState().setWorktreeMetadata(d,{...n,createdFromBranch:F})},[d,n]),A=ut(F=>F.openNewSessionDraft),D=Xe.useCallback(async F=>{const ne=await En("git.integrate.cherrypick.resolve.visible",{current_commit:F.state.currentCommit,target_branch:F.state.targetBranch}),te=await En("git.integrate.cherrypick.resolve.instructions",{repo_root:F.state.repoRoot,temp_worktree_path:F.state.tempWorktreePath,source_branch:F.state.sourceBranch,target_branch:F.state.targetBranch,current_commit:F.state.currentCommit}),q=`Cherry-pick conflict context (JSON)
6
- ${JSON.stringify({repoRoot:F.state.repoRoot,tempWorktreePath:F.state.tempWorktreePath,sourceBranch:F.state.sourceBranch,targetBranch:F.state.targetBranch,currentCommit:F.state.currentCommit,remainingCommits:F.state.remainingCommits,statusPorcelain:F.details.statusPorcelain,unmergedFiles:F.details.unmergedFiles,currentPatchMeta:F.details.currentPatchMeta,currentPatch:F.details.currentPatch,diff:F.details.diff},null,2)}`;return{visibleText:ne,instructionsText:te,payloadText:q}},[]),N=ci(F=>F.setPendingInputText),B=ci(F=>F.setPendingSyntheticParts),T=Xe.useCallback(async(F,ne)=>{const te=await D(F);if(ne){A({directoryOverride:F.state.tempWorktreePath,initialPrompt:te.visibleText,syntheticParts:[{text:te.instructionsText,synthetic:!0},{text:te.payloadText,synthetic:!0}]}),u("chat");return}if(!d){le.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}N(te.visibleText,"replace"),B([{text:te.instructionsText,synthetic:!0},{text:te.payloadText,synthetic:!0}]),u("chat")},[d,u,D,A,N,B,l]),E=Xe.useCallback(async()=>{if(x.kind==="ready"){if(x.plan.commits.length===0){le.message(l("gitView.integrate.noCommitsToMoveToast"));return}h({kind:"running",plan:x.plan});try{const F=await Ky(x.plan);if(F.kind==="success"){le.success(l("gitView.integrate.commitsMovedToast"),{description:F.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:F.moved,branch:x.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:F.moved,branch:x.plan.targetBranch})});const ne=await ho(x.plan);h({kind:"ready",plan:ne}),c?.();return}F.kind==="conflict"&&(le.error(l("gitView.integrate.cherryPickConflictToast"),{description:l("gitView.integrate.cherryPickConflictDescription")}),h({kind:"conflict",state:F.state,details:F.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(F.state)))}catch(F){const ne=F instanceof Error?F.message:String(F);le.error(l("gitView.integrate.failedToMoveToast"),{description:ne});const te=await ho({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(te?{kind:"ready",plan:te}:{kind:"idle"})}}},[x,c,t,e,y,k,l]),_=Xe.useCallback(async()=>{if(x.kind==="conflict")try{await qy(x.state),le.message(l("gitView.integrate.cherryPickAbortedToast")),k&&typeof window<"u"&&window.localStorage.removeItem(k)}finally{const F=await ho({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(F?{kind:"ready",plan:F}:{kind:"idle"})}},[x,t,e,y,k,l]),R=Xe.useCallback(async()=>{if(x.kind==="conflict")try{const F=await Yy(x.state);if(F.kind==="success"){le.success(l("gitView.integrate.cherryPickFinishedToast"));const ne=await ho({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(ne?{kind:"ready",plan:ne}:{kind:"idle"}),k&&typeof window<"u"&&window.localStorage.removeItem(k),c?.();return}F.kind==="conflict"&&(h({kind:"conflict",state:F.state,details:F.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(F.state)))}catch(F){const ne=F instanceof Error?F.message:String(F);le.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:ne})}},[x,t,e,y,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(I,{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")}),x.kind==="ready"&&x.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:x.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:x.kind==="loading"||x.kind==="running"?s.jsx(I,{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," → ",y]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(nn,{open:m,onOpenChange:f,children:[s.jsx(tn,{asChild:!0,children:s.jsxs($e,{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:y}),s.jsx(I,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(sn,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:s.jsxs(Va,{className:"h-full min-h-0",children:[s.jsx($a,{ref:p,placeholder:l("gitView.branch.searchPlaceholder"),onKeyDown:F=>F.stopPropagation()}),s.jsxs(za,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(Wa,{children:l("gitView.branch.empty")}),s.jsx(oi,{heading:l("gitView.branch.localBranches"),children:r.map(F=>s.jsx(li,{value:F,onSelect:()=>{g(F),j(F),f(!1)},children:F},F))})]})]})})]}),x.kind==="ready"?s.jsx($e,{size:"sm",onClick:()=>{E()},disabled:!b||x.plan.commits.length===0,children:l("gitView.integrate.move")}):x.kind==="loading"?s.jsx($e,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):x.kind==="running"?s.jsx($e,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),x.kind==="ready"&&x.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),x.kind==="ready"&&x.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:[" (",x.plan.commits.length,")"]})]}),v.length>0&&x.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>w(F=>!F),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?v:v.slice(0,5)).map(F=>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:F.short}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:F.subject||F.sha})]},F.sha)),v.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.previewUnavailable")}),x.plan.commits.length>v.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:v.length})})]})]}),x.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:x.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:x.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.details.unmergedFiles.slice(0,6).map(F=>s.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:F},F)),x.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:x.details.unmergedFiles.length-6})})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx($e,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{_()},children:l("gitView.operation.abort")}),s.jsxs($e,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{T({state:x.state,details:x.details},!1)},children:[s.jsx(I,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs($e,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{T({state:x.state,details:x.details},!0)},children:[s.jsx(I,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.newSession")]}),s.jsx($e,{size:"sm",className:"typography-meta",onClick:()=>{R()},children:l("gitView.operation.continue")})]})]})]})]})},Jy=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=kt(),[d,u]=i.useState([]),[m,f]=i.useState(!1),[p,y]=i.useState(""),[g,b]=i.useState(""),[x,h]=i.useState(null),[C,w]=i.useState({}),v=i.useCallback(async()=>{if(n){f(!0);try{const N=await Up(n);u(N.stashes),w({})}catch(N){le.error(N instanceof Error?N.message:l("gitView.stashes.toast.loadFailed"))}finally{f(!1)}}},[n,l]);i.useEffect(()=>{t&&v()},[v,t]),i.useEffect(()=>{if(!t||!n||d.length===0)return;let N=!1;const B=d.map(T=>T.ref);return Hp(n,B).then(T=>{N||w(T.counts)}).catch(()=>{}),()=>{N=!0}},[n,t,d]);const S=i.useMemo(()=>{const N=p.trim().toLowerCase();return N?d.filter(B=>`${B.ref} ${B.message} ${B.relativeTime}`.toLowerCase().includes(N)):d},[p,d]),k=i.useCallback(async N=>{await v(),await c?.(N)},[v,c]),j=async()=>{if(!(!n||x)){h("create");try{const N=await Gp(n,{message:g.trim()||void 0});N.created?(le.success(l("gitView.stashes.toast.created")),b("")):le.info(l("gitView.stashes.toast.noChanges")),await k({affectsIndex:!!(N.created&&o)})}catch(N){le.error(N instanceof Error?N.message:l("gitView.stashes.toast.createFailed"))}finally{h(null)}}},A=async(N,B)=>{if(!(!n||x)&&!(B==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:N.ref})))){h(`${B}:${N.ref}`);try{B==="apply"&&await Kp(n,{ref:N.ref}),B==="pop"&&await qp(n,{ref:N.ref}),B==="drop"&&await Yp(n,{ref:N.ref});const T=B==="apply"?"gitView.stashes.toast.applySuccess":B==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";le.success(l(T)),await k({affectsIndex:B!=="drop"})}catch(T){const E=B==="apply"?"gitView.stashes.toast.applyFailed":B==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";le.error(T instanceof Error?T.message:l(E)),await k({affectsIndex:B!=="drop"})}finally{h(null)}}},D=x!==null;return s.jsx($s,{open:t,onOpenChange:e,children:s.jsxs(Vs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(Gs,{children:[s.jsxs(Us,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(ln,{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(jn,{value:g,onChange:N=>b(N.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:D||!r,className:"flex-1"}),s.jsxs($e,{onClick:j,disabled:!r||D||!n,children:[x==="create"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{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(I,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(jn,{value:p,onChange:N=>y(N.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(I,{name:"loader-4",className:"size-5 animate-spin"})}):S.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:l(p?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):S.map((N,B)=>s.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[s.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[s.jsx("p",{className:"typography-small truncate text-foreground",children:N.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{children:B===0&&!p.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:B+1})})}),s.jsx(Ft,{sideOffset:6,children:N.ref})]})," · ",N.relativeTime," · ",typeof C[N.ref]=="number"?l("gitView.stashes.fileCount",{count:C[N.ref]}):l("gitView.stashes.fileCountLoading")]})]}),s.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[s.jsx(yl,{label:l("gitView.stashes.actions.apply"),loading:x===`apply:${N.ref}`,onClick:()=>A(N,"apply"),disabled:D,children:s.jsx(I,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(yl,{label:l("gitView.stashes.actions.pop"),loading:x===`pop:${N.ref}`,onClick:()=>A(N,"pop"),disabled:D,children:s.jsx(I,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(yl,{label:l("gitView.stashes.actions.drop"),loading:x===`drop:${N.ref}`,onClick:()=>A(N,"drop"),disabled:D,destructive:!0,children:s.jsx(I,{name:"delete-bin",className:"size-4"})})]})]},N.ref))})]})})},yl=t=>{const e=ft.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,u=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let m;e[0]!==u?(m=Pe("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",u),e[0]=u,e[1]=m):m=e[1];let f;e[2]!==l||e[3]!==r?(f=r?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):l,e[2]=l,e[3]=r,e[4]=f):f=e[4];let p;e[5]!==o||e[6]!==n||e[7]!==c||e[8]!==d||e[9]!==m||e[10]!==f?(p=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:m,onClick:c,disabled:o,children:f})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=m,e[10]=f,e[11]=p):p=e[11];let y;e[12]!==n?(y=s.jsx(Ft,{sideOffset:6,children:n}),e[12]=n,e[13]=y):y=e[13];let g;return e[14]!==p||e[15]!==y?(g=s.jsxs(Et,{children:[p,y]}),e[14]=p,e[15]=y,e[16]=g):g=e[16],g},Xy=t=>{const e=ft.c(16),{onOpenStashes:n}=t,{t:r}=kt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(I,{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 u;e[9]!==n||e[10]!==r?(u=n?s.jsxs($e,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(I,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=u):u=e[11];let m;return e[12]!==c||e[13]!==d||e[14]!==u?(m=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,u]}),e[12]=c,e[13]=d,e[14]=u,e[15]=m):m=e[15],m},ti=8,Zy=t=>{const e=ft.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,u=Math.max(r,a+1)*ti+ti/2,m=i.useRef(null),f=i.useRef(null);let p;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==u?(p=()=>{const h=m.current,C=f.current;if(!h||!C)return;const w=h.offsetHeight;if(w===0)return;const v=window.devicePixelRatio||1;C.width=u*v,C.height=w*v;const S=C.getContext("2d");if(!S)return;S.scale(v,v),S.clearRect(0,0,u,w);const k=w/2,j=a*ti+ti/2,A=getComputedStyle(C),D=A.getPropertyValue("--surface-muted-foreground").trim()||A.color,N=E=>{if(!E.startsWith("var("))return E;const _=E.slice(4,-1).trim();return A.getPropertyValue(_).trim()||D},B=[...l].sort(tw);for(const E of B){const _=E.fromLane*ti+ti/2,R=E.toLane*ti+ti/2,$=E.type==="passing"?.72:E.type==="branch-out"||E.type==="merge-in"?.95:1;S.beginPath(),S.strokeStyle=N(E.color),S.globalAlpha=$,S.lineWidth=1.25,S.lineCap="round";e:switch(E.type){case"passing":case"commit-lane":{S.moveTo(_,0),S.lineTo(_,w);break e}case"top-stub":{S.moveTo(_,0),S.lineTo(_,k);break e}case"bottom-stub":{S.moveTo(_,k),S.lineTo(_,w);break e}case"branch-out":{const V=(k+w)/2;S.moveTo(j,k),S.bezierCurveTo(j,V,R,V,R,w);break e}case"merge-in":{const V=k/2;S.moveTo(_,0),S.bezierCurveTo(_,V,j,V,j,k);break e}default:continue}S.stroke(),S.globalAlpha=1}const T=A.getPropertyValue("--background").trim()||A.getPropertyValue("--surface-background").trim();S.beginPath(),S.arc(j,k,4,0,Math.PI*2),S.fillStyle=N(c),S.fill(),S.beginPath(),S.arc(j,k,5,0,Math.PI*2),S.strokeStyle=T||D,S.lineWidth=2,S.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=u,e[4]=p):p=e[4];let y;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==u?(y=[n,a,c,l,r,o,u],e[5]=c,e[6]=l,e[7]=o,e[8]=a,e[9]=n,e[10]=r,e[11]=u,e[12]=y):y=e[12],i.useLayoutEffect(p,y);let g;e[13]!==u?(g={width:u,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=u,e[14]=g):g=e[14];let b;e[15]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx("canvas",{ref:f,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=b):b=e[15];let x;return e[16]!==g?(x=s.jsx("div",{ref:m,style:g,children:b}),e[16]=g,e[17]=x):x=e[17],x};function ew(t){return t==="branch-out"||t==="merge-in"}function tw(t,e){const n=ew;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 ju(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:Nc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function sw(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 nw(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 rw=i.memo(({entry:t,mode:e="history",laned:n,totalLanes:r,isExpanded:o,onToggle:a,files:c,isLoadingFiles:l,onCopyHash:d,directory:u,onConflict:m,onActionSuccess:f})=>{const{t:p}=kt(),y=Ee(H=>H.timeFormatPreference),g=e==="graph",[b,x]=i.useState(null),[h,C]=i.useState(!1),[w,v]=i.useState(""),[S,k]=i.useState(null),[j,A]=i.useState(new Set),[D,N]=i.useState(new Map),[B,T]=i.useState(new Set),E=async()=>{if(u){x("checkout");try{await ng(u,t.hash),le.success(p("gitView.history.actions.detachedHead")),f?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},_=async()=>{if(!(!u||!w.trim())){x("createBranch");try{await Jp(u,w.trim(),t.hash),C(!1),v(""),f?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},R=async()=>{if(u){x("cherryPick");try{const H=await sg(u,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"cherry-pick"}):f?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},$=async()=>{if(u){x("revert");try{const H=await tg(u,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"revert"}):f?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},V=async(H,X=!1)=>{if(!(!u||b!==null)){x("reset");try{await Xp(u,t.hash,H,X),f?.()}catch(oe){le.error(String(oe.message))}finally{x(null)}}},z=async()=>{if(!S)return;const H=S;switch(k(null),H){case"checkout":return E();case"cherryPick":return R();case"revert":return $();case"merge":return F();case"rebase":return ne();case"resetSoft":return V("soft");case"resetMixed":return V("mixed");case"resetHard":return V("hard",!0)}},F=async()=>{if(u){x("merge");try{const H=await eg(u,{branch:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"merge"}):f?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},ne=async()=>{if(u){x("rebase");try{const H=await Zp(u,{onto:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"rebase"}):f?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},te=i.useCallback(async H=>{const X=H.path;if(!u){N(oe=>new Map(oe).set(X,"error"));return}N(oe=>vu(new Map(oe).set(X,"loading")));try{const oe=Qp(u,t.hash,H.path,!1),ue=new Promise((Z,ke)=>{setTimeout(()=>ke(new Error(`Timed out after ${gu}ms`)),gu)}),Se=await Promise.race([oe,ue]);N(Z=>vu(new Map(Z).set(X,Se)))}catch{N(oe=>new Map(oe).set(X,"error"))}},[u,t.hash]),q=i.useCallback(async H=>{const X=H.path;if(H.changeType==="R"||H.isBinary){A(Z=>{const ke=new Set(Z);return ke.has(X)?ke.delete(X):ke.add(X),ke});return}const oe=D.get(X);if(j.has(X)&&oe&&oe!=="error"){A(Z=>{const ke=new Set(Z);return ke.delete(X),ke});return}A(Z=>{const ke=new Set(Z);return ke.add(X),ke}),!(oe&&oe!=="error"||H.insertions+H.deletions>xu&&!B.has(X))&&await te(H)},[D,B,te,j]);return s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:a,className:Pe("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",g?"hover:bg-[var(--interactive-hover)]/40":o?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[g&&n&&r!==void 0?s.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:s.jsx(Zy,{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:[g?(()=>{const H=nw(t.refs);return H.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:H.map(X=>s.jsx("span",{className:Pe("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",X.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":X.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:X.label},X.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:ju(t.date,y),children:ju(t.date,y)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:H=>{H.stopPropagation(),d(t.hash)},children:s.jsx(I,{name:"file-copy",className:"size-3"})})}),s.jsx(Ft,{sideOffset:8,children:p("gitView.history.copySha")})]})]})]})]}),o&&s.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[g&&S?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.${S}Confirm`)}),s.jsxs($e,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:b!==null,onClick:H=>{H.stopPropagation(),z()},children:[b!==null?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.confirmButton")]}),s.jsx($e,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:b!==null,onClick:H=>{H.stopPropagation(),k(null)},children:p("gitView.history.actions.cancelButton")})]}):g?s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.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:H=>v(H.target.value),onKeyDown:H=>{H.key==="Enter"&&_(),H.key==="Escape"&&(C(!1),v(""))},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($e,{variant:"outline",size:"xs",className:"h-6",disabled:!w.trim()||b!==null,onClick:H=>{H.stopPropagation(),_()},children:[b==="createBranch"?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.createBranchConfirm")]})]}):s.jsx($e,{variant:"outline",size:"xs",className:"h-6",onClick:H=>{H.stopPropagation(),C(!0)},children:p("gitView.history.actions.createBranch")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("cherryPick")},children:p("gitView.history.actions.cherryPick")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("revert")},children:p("gitView.history.actions.revert")}),s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>H.stopPropagation(),children:[b==="reset"?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.reset")]})}),s.jsx(sn,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(H=>s.jsx(bs,{disabled:b!==null,onSelect:X=>{X.stopPropagation(),k(`reset${H.charAt(0).toUpperCase()+H.slice(1)}`)},children:p(`gitView.history.actions.reset${H.charAt(0).toUpperCase()+H.slice(1)}`)},H))})]}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("merge")},children:p("gitView.history.actions.merge")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.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(I,{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(H=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>q(H),className:Pe("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",j.has(H.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:Pe("font-semibold w-3 text-center shrink-0",sw(H.changeType)),children:H.changeType}),s.jsx("span",{className:"truncate text-foreground min-w-0",title:H.path,children:H.path}),!H.isBinary&&s.jsxs("span",{className:"shrink-0",children:[s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",H.insertions]}),s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",H.deletions]})]}),H.isBinary&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:p("gitView.history.binary")}),s.jsx(I,{name:j.has(H.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),j.has(H.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:H.changeType==="R"?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.renamedNoDiff")}):H.isBinary?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.binaryNoDiff")}):(()=>{const X=H.insertions+H.deletions;if(!B.has(H.path)&&X>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:X})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:p("gitView.history.largeDiffDescription")}),s.jsx($e,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{T(ue=>new Set(ue).add(H.path)),te(H)},children:p("gitView.history.renderDiffAnyway")})]});const oe=D.get(H.path);return oe==="loading"||oe===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.loadingDiff")}):oe==="error"?s.jsx("button",{type:"button",onClick:()=>q(H),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(jm,{original:oe.original,modified:oe.modified,language:Ci(H.path)||"",fileName:H.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},H.path))})]})]})}),Su=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)","var(--syntax-keyword)","var(--syntax-string)","var(--status-info)"];function qo(t){return Su[t%Su.length]}function iw(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let y=0;y<e.length;y++)e[y]===o.hash&&a.push(y);let c=a.length>0?a[0]:-1;if(c===-1){const y=e.indexOf(null);y!==-1?c=y:(c=e.length,e.push(null))}const l=a.slice(1),d=qo(c),u=e[c]===o.hash,m=o.parents.length>0;m?e[c]=o.parents[0]:e[c]=null;const f=[];for(let y=1;y<o.parents.length;y++){const g=o.parents[y],b=e.indexOf(g);if(b!==-1)f.push(b);else{const x=e.indexOf(null),h=x!==-1?x:e.length;e[h]=g,h===e.length&&e.push(g),f.push(h)}}const p=[];u&&m?p.push({fromLane:c,toLane:c,color:d,type:"commit-lane"}):u&&!m?p.push({fromLane:c,toLane:c,color:d,type:"top-stub"}):!u&&m&&p.push({fromLane:c,toLane:c,color:d,type:"bottom-stub"});for(const y of l)p.push({fromLane:y,toLane:c,color:qo(y),type:"merge-in"}),e[y]=null;for(const y of f)p.push({fromLane:c,toLane:y,color:qo(y),type:"branch-out"});for(let y=0;y<e.length;y++)e[y]!==null&&y!==c&&(f.includes(y)||p.push({fromLane:y,toLane:y,color:qo(y),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:p})}return n}const ow=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],aw=t=>{const e=ft.c(84),{mode:n,log:r,isLogLoading:o,logMaxCount:a,onLogMaxCountChange:c,expandedCommitHashes:l,onToggleCommit:d,commitFilesMap:u,loadingCommitHashes:m,onCopyHash:f,directory:p,showHeader:y,contentMaxHeightClassName:g,branchDivider:b,onConflict:x,onActionSuccess:h}=t,C=n===void 0?"history":n,w=y===void 0?!0:y,v=g===void 0?"max-h-[50vh]":g,S=b===void 0?null:b,{t:k}=kt(),[j,A]=i.useState(!0),D=C==="graph";let N;e[0]!==D||e[1]!==r?(N=D&&r?iw(r.all):[],e[0]=D,e[1]=r,e[2]=N):N=e[2];const B=N;let T;e[3]!==B?(T=Math.max(1,...B.map(lw)),e[3]=B,e[4]=T):T=e[4];const E=T;let _;e[5]!==B?(_=new Map(B.map(cw)),e[5]=B,e[6]=_):_=e[6];const R=_;if(!r)return null;const $=S!==null&&S.insertBeforeIndex>0&&S.insertBeforeIndex<r.all.length,V=S!==null&&S.insertBeforeIndex===r.all.length,z=$||V;let F;e[7]!==S||e[8]!==$||e[9]!==V||e[10]!==r.all?(F=$?r.all.slice(0,S.insertBeforeIndex):V?r.all:[],e[7]=S,e[8]=$,e[9]=V,e[10]=r.all,e[11]=F):F=e[11];const ne=F;let te;if(e[12]!==S||e[13]!==u||e[14]!==v||e[15]!==p||e[16]!==l||e[17]!==$||e[18]!==z||e[19]!==D||e[20]!==o||e[21]!==R||e[22]!==m||e[23]!==r.all||e[24]!==a||e[25]!==E||e[26]!==C||e[27]!==h||e[28]!==x||e[29]!==f||e[30]!==c||e[31]!==d||e[32]!==k||e[33]!==ne){const ge=$?r.all.slice(S.insertBeforeIndex):[];let O;e[35]!==S?.direction?(O=S?.direction==="down"?s.jsx(I,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(I,{name:"arrow-up",className:"size-3.5"}),e[35]=S?.direction,e[36]=O):O=e[36];const se=O;let ee;e[37]!==u||e[38]!==p||e[39]!==l||e[40]!==D||e[41]!==R||e[42]!==m||e[43]!==E||e[44]!==C||e[45]!==h||e[46]!==x||e[47]!==f||e[48]!==d?(ee=Fe=>s.jsx("ul",{className:"divide-y divide-border/60",children:Fe.map(Me=>s.jsx(rw,{entry:Me,mode:C,laned:D?R.get(Me.hash):void 0,totalLanes:D?E:void 0,isExpanded:l.has(Me.hash),onToggle:()=>d(Me.hash),files:u.get(Me.hash)??[],isLoadingFiles:m.has(Me.hash),onCopyHash:f,directory:p,onConflict:x,onActionSuccess:h},Me.hash))}),e[37]=u,e[38]=p,e[39]=l,e[40]=D,e[41]=R,e[42]=m,e[43]=E,e[44]=C,e[45]=h,e[46]=x,e[47]=f,e[48]=d,e[49]=ee):ee=e[49];const je=ee;let De;e[50]!==o||e[51]!==r.all.length||e[52]!==a||e[53]!==c||e[54]!==k?(De=r.all.length>=a?s.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:s.jsx($e,{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(I,{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]=De):De=e[55];const Be=De;te=s.jsx($n,{outerClassName:`min-h-0 ${v}`,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")})}):z&&S?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:je(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:S.branchName,children:S.branchName}),se]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),ge.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:je(ge)}):null]}),Be]}):s.jsxs(s.Fragment,{children:[je(r.all),Be]})}),e[12]=S,e[13]=u,e[14]=v,e[15]=p,e[16]=l,e[17]=$,e[18]=z,e[19]=D,e[20]=o,e[21]=R,e[22]=m,e[23]=r.all,e[24]=a,e[25]=E,e[26]=C,e[27]=h,e[28]=x,e[29]=f,e[30]=c,e[31]=d,e[32]=k,e[33]=ne,e[34]=te}else te=e[34];const q=te;if(!w){if(z){let O;return e[56]!==q?(O=s.jsx("section",{className:"h-full min-h-0",children:q}),e[56]=q,e[57]=O):O=e[57],O}let ge;return e[58]!==q?(ge=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:q}),e[58]=q,e[59]=ge):ge=e[59],ge}let H;e[60]!==k?(H=k("gitView.history.title"),e[60]=k,e[61]=H):H=e[61];let X;e[62]!==H?(X=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:H}),e[62]=H,e[63]=X):X=e[63];let oe;e[64]!==o||e[65]!==j||e[66]!==a||e[67]!==c||e[68]!==k?(oe=j&&s.jsx("div",{onClick:dw,onPointerDown:uw,children:s.jsxs(zn,{value:String(a),onValueChange:ge=>c(Number(ge)),disabled:o,children:[s.jsx(Wn,{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(Un,{children:ow.map(ge=>s.jsx(Ms,{value:String(ge.value),children:k(ge.labelKey)},ge.value))})]})}),e[64]=o,e[65]=j,e[66]=a,e[67]=c,e[68]=k,e[69]=oe):oe=e[69];let ue;e[70]!==j?(ue=j?s.jsx(I,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=j,e[71]=ue):ue=e[71];let Se;e[72]!==oe||e[73]!==ue?(Se=s.jsxs("div",{className:"flex items-center gap-2",children:[oe,ue]}),e[72]=oe,e[73]=ue,e[74]=Se):Se=e[74];let Z;e[75]!==X||e[76]!==Se?(Z=s.jsxs(Bo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[X,Se]}),e[75]=X,e[76]=Se,e[77]=Z):Z=e[77];let ke;e[78]!==q?(ke=s.jsx(to,{children:q}),e[78]=q,e[79]=ke):ke=e[79];let Y;return e[80]!==j||e[81]!==Z||e[82]!==ke?(Y=s.jsxs(eo,{open:j,onOpenChange:A,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[Z,ke]}),e[80]=j,e[81]=Z,e[82]=ke,e[83]=Y):Y=e[83],Y};function lw(t){return t.lane+1}function cw(t){return[t.commit.hash,t]}function dw(t){return t.stopPropagation()}function uw(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},fw=9e4,mw=15e3,hw=5*6e4,pw=[2e3,5e3],gw=6e4,xw=2*6e4,bw=5*6e4,yw=4,ww=720*6e4,vw="openchamber.github-pr-status",jw=t=>t==="closed"||t==="merged",Sw=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},No=(t,e,n)=>`${t}::${e}`,Yo=new Map,Qo=new Map,po=new Set,Nu=new Map,Nw=2;let Pa=0;const Vm=[],kw=()=>Pa<Nw?(Pa+=1,Promise.resolve()):new Promise(t=>{Vm.push(t)}),Cw=()=>{const t=Vm.shift();if(t){t();return}Pa=Math.max(0,Pa-1)},bo=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null}),Ta=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=Ta(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},$m=(t,e)=>Object.entries(t).filter(([,n])=>_c(n)===e).map(([n])=>n),Aw=(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}}},Jo=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},Dw=(t,e,n)=>{const r=$m(t,e),o=r.map(d=>Jo(t[d])).filter(d=>!!d);if(o.length===0)return null;const a=Jo(t[n]);if(a&&_c(t[n])===e)return a;const c=r.map(d=>t[d]).find(d=>!!(d?.resolvedRemoteName&&Jo(d)));if(c)return Jo(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:Ta(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Pw=t=>({...bo(),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}),ir=ro()(uc((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,ensureEntry:n=>{t(r=>r.entries[n]?r:{entries:{...r.entries,[n]:bo()}})},setParams:(n,r)=>{t(o=>{const a=o.entries[n]??bo();return{entries:{...o.entries,[n]:Aw(a,r)}}})},startWatching:n=>{if(t(a=>{const c=a.entries[n]??bo();return{entries:{...a.entries,[n]:{...c,watchers:c.watchers+1}}}}),Yo.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=Qo.get(n)??[];l.push(c),Qo.set(n,l)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),pw.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 u=Date.now();if(u-a.lastDiscoveryPollAt<hw)return;t(m=>{const f=m.entries[n];return f?{entries:{...m.entries,[n]:{...f,lastDiscoveryPollAt:u}}}:m}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(jw(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=Sw(a.status)?gw:a.status?.checks&&a.status.checks.state!=="pending"?bw:xw;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},mw);Yo.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=Yo.get(n);typeof o=="number"&&window.clearInterval(o),Yo.delete(n);const a=Qo.get(n);a&&a.length>0&&a.forEach(c=>{window.clearTimeout(c)}),Qo.delete(n)},refresh:async(n,r)=>{const o=e(),a=o.entries[n],c=_c(a);if(!a||!c)return;const l=$m(o.entries,c),d=l.some(f=>!!o.entries[f]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const u=Nu.get(c)??0;if(!r?.force&&Date.now()-u<fw||po.has(c))return;const m=Dw(o.entries,c,n);if(m){if(po.add(c),Nu.set(c,Date.now()),t(f=>{const p={...f.entries};return l.forEach(y=>{const g=p[y];g&&(p[y]={...g,lastRefreshAt:Date.now(),isLoading:r?.silent?g.isLoading:!0,error:null})}),{entries:p}}),m.githubAuthChecked&&m.githubConnected===!1){t(f=>{const p={...f.entries};return l.forEach(y=>{const g=p[y];g&&(p[y]={...g,status:{connected:!1},error:null,isLoading:r?.silent?g.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?g.isInitialStatusResolved:!0})}),{entries:p}}),po.delete(c);return}if(!m.github?.prStatus){t(f=>{const p={...f.entries};return l.forEach(y=>{const g=p[y];g&&(p[y]={...g,status:null,error:"GitHub runtime API unavailable",isLoading:r?.silent?g.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?g.isInitialStatusResolved:!0})}),{entries:p}}),po.delete(c);return}try{t(p=>({...p,activeRequestCount:p.activeRequestCount+1,totalRequestCount:p.totalRequestCount+1})),await kw();let f;try{f=await m.github.prStatus(m.directory,m.branch,m.remoteName??void 0,{force:r?.force})}finally{Cw()}t(p=>{const y={...p.entries};return l.forEach(g=>{const b=y[g];if(!b)return;const x=b.status?.pr,h=f.pr,w=!!(h&&x&&h.number===x.number&&(!h.body||!h.body.trim())&&typeof x.body=="string"&&x.body.trim().length>0)&&h&&x?.body?{...f,pr:{...h,body:x.body}}:f,v=w.resolvedRemoteName??b.resolvedRemoteName??m.remoteName??null,S=Ta(b)??{directory:m.directory,branch:m.branch,remoteName:m.remoteName??null};y[g]={...b,status:w,error:null,isLoading:r?.silent?b.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?b.isInitialStatusResolved:!0,resolvedRemoteName:v,identity:{...S,remoteName:v??S.remoteName??null}}}),{entries:y}})}catch(f){const p=f instanceof Error?f.message:String(f);t(y=>{const g={...y.entries};return l.forEach(b=>{const x=g[b];x&&(g[b]={...x,error:p||"Failed to load PR status",isLoading:r?.silent?x.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?x.isInitialStatusResolved:!0})}),{entries:g}})}finally{po.delete(c),t(f=>({...f,activeRequestCount:Math.max(0,f.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:No(c,l,a.remoteName??null)}).filter(a=>!!a)));await _m(o,yw,a=>e().refresh(a,r))},updateStatus:(n,r)=>{t(o=>{const a=o.entries[n]??bo();return{entries:{...o.entries,[n]:{...a,status:r(a.status)}}}})}}),{name:vw,storage:pp(),partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=Ta(e);if(!n?.directory||!n.branch)return!1;const r=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return r===0||Date.now()-r<ww}).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,Pw(a)]))}}})),Tw=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"},Rw=t=>{const e=Tw(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}},Ew=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 Mw=t=>{const e=ft.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=Rw(l);if(!d)continue;const u=Ew(d);o.set(c,u),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],ir(n)},Fw=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"}},Lw=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"},Ow=[2e3,5e3],Cu=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),si=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):""},Bw=(t,e)=>{const n=si(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}`,Vc=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=Vc(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)},Vw=t=>t.startsWith("pr-"),$w=(t,e)=>{const n=Vc(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=>!Vw(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},jl=new Map,Sl=Di;function zw(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 u=await e.repoBranches(d.upstream.owner,d.upstream.repo);l||a(u)}catch{}}catch{}})(),()=>{l=!0}},[t,e]),{detectedUpstream:n,upstreamBranches:o}}const Ww=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=kt(),d=Ee(we=>we.timeFormatPreference),{github:u}=Xn(),m=Ii(we=>we.status),f=Ii(we=>we.hasChecked),p=Ee(we=>we.setSettingsDialogOpen),y=Ee(we=>we.setSettingsPage),g=Ee(we=>we.setActiveMainTab),b=ut(we=>we.currentSessionId),{isMobile:x,hasTouchInput:h}=Mr(),C=i.useCallback(()=>{y("github"),p(!0)},[p,y]),w=i.useMemo(()=>_w(t,e),[t,e]),v=i.useMemo(()=>jl.get(w)??null,[w]),S=ir(we=>we.ensureEntry),k=ir(we=>we.setParams),j=ir(we=>we.startWatching),A=ir(we=>we.stopWatching),D=ir(we=>we.refresh),N=ir(we=>we.updateStatus),[B,T]=i.useState(()=>v?.title??Cu(e)),[E,_]=i.useState(()=>v?.body??""),[R,$]=i.useState(()=>v?.draft??!1),[V,z]=i.useState(()=>v?.additionalContext??""),[F,ne]=i.useState(()=>{const we=typeof v?.targetBaseBranch=="string"?si(v.targetBaseBranch):"";return we||si(n)}),[te,q]=i.useState("squash"),[H,X]=i.useState(!1),[oe,ue]=i.useState(!1),[Se,Z]=i.useState(!1),[ke,Y]=i.useState(!1),[ge,O]=i.useState(!1),[se,ee]=i.useState(!1),[je,De]=i.useState(null),[Be,Fe]=i.useState(""),[Me,me]=i.useState(""),[Ae,pe]=i.useState(!1),[ce,he]=i.useState(!1),[Ne,fe]=i.useState(()=>vl(o,{selectedRemoteName:v?.selectedRemoteName,trackingBranch:r})),[P,M]=i.useState(!1),{detectedUpstream:de,upstreamBranches:xe}=zw(t,u);i.useEffect(()=>{M(!1)},[t]);const W=o.some(we=>we.name==="upstream"),ve=!!(t&&e&&n&&(e!==n||(W||de!==null))),G=i.useMemo(()=>No(t,e),[t,e]),ye=ir(we=>we.entries[G]),Le=ye?.isLoading??!1,Re=ye?.status??null,J=ye?.error??null,L=ye?.isInitialStatusResolved??!1,ae=i.useMemo(()=>{const we=P?null:Ne?.name?.trim()||null,et=new Set;for(const Gt of a){const mt=Bw(Gt,we);!mt||mt==="HEAD"||et.add(mt)}if(P)for(const Gt of xe)Gt&&Gt!=="HEAD"&&et.add(Gt);const ct=si(n);ct&&ct!=="HEAD"&&et.add(ct);const It=si(F);return It&&It!=="HEAD"&&et.add(It),Array.from(et).sort((Gt,mt)=>Gt.localeCompare(mt))},[n,a,Ne?.name,F,xe,P]);i.useEffect(()=>{if(o.length===0){Ne&&fe(null);return}(!Ne||!o.some(we=>we.name===Ne.name))&&fe(vl(o,{selectedRemoteName:v?.selectedRemoteName,trackingBranch:r}))},[v?.selectedRemoteName,o,Ne,r]),i.useEffect(()=>{const we=si(n);if(!F&&we){ne(we);return}if(ae.length!==0&&!ae.includes(F)){const et=ae.includes(we)?we:ae[0];et&&ne(et)}},[ae,n,F]);const[re,Oe]=i.useState(!1),[qe,Ge]=i.useState(null),[Je,nt]=i.useState(!1),[gt,yt]=i.useState(new Set),[_e,Qe]=i.useState(!1),[st,wt]=i.useState(null),[Ct,xt]=i.useState(!1),St=i.useRef(new Set),Ze=i.useRef(null),Ot=i.useRef(!1),ns=i.useRef(new Set),zt=i.useRef([]);i.useEffect(()=>{de&&!W&&M(!0)},[de,W]),i.useEffect(()=>{P&&de?.defaultBranch&&ne(de.defaultBranch)},[P,de?.defaultBranch]);const Ve=Re?.pr??null,At=Ve?`${t}#${Ve.number}`:null,ot=!!(At&&je===At);i.useEffect(()=>{if(!u?.prContext||!Ve||typeof Ve.body=="string"&&Ve.body.length>0)return;const we=`${t}#${Ve.number}`;if(St.current.has(we))return;St.current.add(we),De(we);let et=!1;return u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!1}).then(ct=>{if(et)return;const It=ct?.pr;It&&N(G,Gt=>!Gt?.pr||Gt.pr.number!==Ve.number?Gt:{...Gt,pr:{...Gt.pr,body:It.body||""}})}).catch(()=>{}).finally(()=>{et||De(ct=>ct===we?null:ct)}),()=>{et=!0}},[t,u,Ve,G,N]),i.useEffect(()=>{if(!Ve){ee(!1),Fe(""),me(""),Ze.current=null;return}const we=Ze.current!==null&&Ze.current!==Ve.number;we&&ee(!1),(!se||we)&&(Fe(Ve.title||""),me(Ve.body||"")),Ze.current=Ve.number},[se,Ve]);const vt=i.useCallback(async()=>{if(!u?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Ve){Oe(!0),yt(new Set),nt(!0);try{const we=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!0});Ge(we)}catch(we){const et=we instanceof Error?we.message:String(we);le.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:et})}finally{nt(!1)}}},[t,u,Ve,l]),bt=i.useCallback(async()=>{if(!u?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Ve){Qe(!0),xt(!0);try{const we=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!1});wt(we)}catch(we){const et=we instanceof Error?we.message:String(we);le.error(l("gitView.pr.toast.loadCommentsFailed"),{description:et})}finally{xt(!1)}}},[t,u,Ve,l]),ls=i.useCallback(we=>{if(!we)return"";const et=Date.parse(we);return Number.isFinite(et)?Nc(et,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):we},[d]),Wt=i.useMemo(()=>{const we=m?.user?.login;return typeof we=="string"?we.trim():""},[m]),qt=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)]",[]),rs=i.useCallback(we=>{const et=Wt.toLowerCase(),ct=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return we.replace(ct,(It,Gt,mt)=>{const ms=`@${mt}`,hs=mt.toLowerCase();return`${Gt}[${ms}](https://github.com/${hs}${et&&hs===et?"?oc-self-mention=1":""})`})},[Wt]),Ut=i.useMemo(()=>{const we=(st?.issueComments??[]).map(It=>({id:`issue-${It.id}`,body:It.body||"",authorName:It.author?.name||It.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:It.author?.login||null,avatarUrl:It.author?.avatarUrl||null,createdAt:It.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),et=(st?.reviewComments??[]).map(It=>({id:`review-${It.id}`,body:It.body||"",authorName:It.author?.name||It.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:It.author?.login||null,avatarUrl:It.author?.avatarUrl||null,createdAt:It.createdAt,context:l("gitView.pr.comments.reviewContext"),path:It.path||null,line:It.line??null})),ct=[...we,...et];return ct.sort((It,Gt)=>{const mt=It.createdAt?Date.parse(It.createdAt):0,ms=Gt.createdAt?Date.parse(Gt.createdAt):0,hs=Number.isFinite(mt)?mt:0,Ss=Number.isFinite(ms)?ms:0;return hs-Ss}),ct},[st,l]),Bt=i.useCallback(()=>{if(!b)return le.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:we,currentModelId:et,currentAgentName:ct,currentVariant:It}=ss.getState(),Gt=Sc.getState().lastUsedProvider,mt=we||Gt?.providerID,ms=et||Gt?.modelID;return!mt||!ms?(le.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:b,providerID:mt,modelID:ms,currentAgentName:ct??null,currentVariant:It??null}},[b,l]),_t=i.useCallback((we,et,ct,It)=>{ut.getState().sendMessage(et,we.providerID,we.modelID,we.currentAgentName??void 0,void 0,void 0,[{text:ct,synthetic:!0},{text:It,synthetic:!0}],we.currentVariant??void 0).catch(Gt=>{const mt=Gt instanceof Error?Gt.message:String(Gt);le.error(l("gitView.pr.toast.sendMessageFailed"),{description:mt})})},[l]),Yt=i.useCallback(we=>{const et=we.status||"unknown",ct=we.conclusion??void 0,It=ct?`${et} / ${ct}`:et,Gt=we.app?.name||we.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:we.name}),s.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:Gt?`${Gt} · ${It}`:It})]}),we.detailsUrl?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:we.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),"Open"]})}):null]}),we.output?.title?s.jsx("div",{className:"typography-micro text-foreground",children:we.output.title}):null,we.output?.summary?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:we.output.summary}):null,we.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:we.output.text}):null,Array.isArray(we.annotations)&&we.annotations.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",we.annotations.length>20?` (showing 20/${we.annotations.length})`:""]}),s.jsx("div",{className:"space-y-1",children:we.annotations.slice(0,20).map((mt,ms)=>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:[mt.title||mt.level||"Issue",mt.path?` · ${mt.path}`:"",typeof mt.startLine=="number"?`:${mt.startLine}`:"",typeof mt.endLine=="number"&&mt.endLine!==mt.startLine?`-${mt.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:mt.message}),mt.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:mt.rawDetails}):null]},`${mt.path||"file"}:${mt.startLine||ms}:${ms}`))})]}):null,we.job?.steps&&we.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:we.job.steps.map((mt,ms)=>{const hs=(mt.conclusion||"").toLowerCase(),Ss=hs&&!["success","neutral","skipped"].includes(hs),ws=`${we.id??"run"}:${we.job?.jobId??"job"}:${mt.number??ms}:${mt.name}`,Ds=gt.has(ws);return Ss?s.jsxs(eo,{open:Ds,children:[s.jsxs("button",{type:"button",onClick:()=>{yt(Hn=>{const zs=new Set(Hn);return zs.has(ws)?zs.delete(ws):zs.add(ws),zs})},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:[Ds?s.jsx(I,{name:"arrow-down-s",className:"size-4"}):s.jsx(I,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:mt.name}),mt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:mt.conclusion}):null]}),s.jsx(to,{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 mt.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",mt.number]}):null,mt.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",mt.status]}):null,mt.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",mt.conclusion]}):null,mt.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",ls(mt.startedAt)]}):null,mt.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",ls(mt.completedAt)]}):null]})})]},ws):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:mt.name}),mt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:mt.conclusion}):null]},ws)})})]}):null]})},[gt,ls,l]),Ht=i.useCallback(async()=>{if(g("chat"),!u?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Ve)return;const we=Bt();if(we)try{const et=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!0}),It=(et.checkRuns??[]).filter(Ss=>{const ws=typeof Ss.conclusion=="string"?Ss.conclusion.toLowerCase():"";return ws?!["success","neutral","skipped"].includes(ws):!1});if(It.length===0){le.message(l("gitView.pr.toast.noFailedChecks"));return}const Gt=await En("github.pr.checks.review.visible"),mt=await En("github.pr.checks.review.instructions"),ms=It.flatMap(Ss=>(Array.isArray(Ss.annotations)?Ss.annotations:[]).map(Ds=>({run:Ss.name,level:Ds.level,title:Ds.title,path:Ds.path,startLine:Ds.startLine,endLine:Ds.endLine,message:Ds.message,rawDetails:Ds.rawDetails}))),hs=`GitHub PR failed checks (JSON)
7
- ${JSON.stringify({repo:et.repo??null,pr:et.pr??null,failedChecks:It,failedAnnotations:ms},null,2)}`;_t(we,Gt,mt,hs)}catch(et){const ct=et instanceof Error?et.message:String(et);le.error(l("gitView.pr.toast.loadChecksFailed"),{description:ct})}},[t,_t,u,Ve,Bt,g,l]),Zt=i.useCallback(async()=>{if(g("chat"),!u?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Ve)return;const we=Bt();if(we)try{const et=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!1}),ct=et.issueComments??[],It=et.reviewComments??[];if(ct.length+It.length===0){le.message(l("gitView.pr.toast.noPrComments"));return}const mt=await En("github.pr.comments.review.visible"),ms=await En("github.pr.comments.review.instructions"),hs=`GitHub PR comments (JSON)
8
- ${JSON.stringify({repo:et.repo??null,pr:et.pr??null,issueComments:ct,reviewComments:It},null,2)}`;_t(we,mt,ms,hs)}catch(et){const ct=et instanceof Error?et.message:String(et);le.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:ct})}},[t,_t,u,Ve,Bt,g,l]),ys=i.useCallback(async we=>{Qe(!1),g("chat");const et=Bt();if(!et)return;const ct=await En("github.pr.comment.single.visible"),It=await En("github.pr.comment.single.instructions"),Gt=`GitHub PR comment (JSON)
9
- ${JSON.stringify({repo:st?.repo??null,pr:st?.pr??Ve??null,comment:we},null,2)}`;_t(et,ct,It,Gt)},[st,_t,Ve,Bt,g]),Tt=i.useCallback(async we=>{await D(G,we)},[G,D]),Vt=i.useCallback(()=>{zt.current.forEach(we=>{window.clearTimeout(we)}),zt.current=Ow.map(we=>window.setTimeout(()=>{Tt({force:!0,silent:!0,markInitialResolved:!0})},we))},[Tt]);i.useEffect(()=>{if(!u?.prStatus||!ve||o.length<=1||Ot.current||Re?.pr)return;const we=`${w}::${Ne?.name??""}`;if(ns.current.has(we))return;ns.current.add(we);const et=$w(o,r).filter(Gt=>Gt.name!==Ne?.name);if(et.length===0)return;let ct=!1;return(async()=>{for(const Gt of et){if(ct)return;try{if(!(await u.prStatus(t,e,Gt.name))?.pr)continue;if(ct)return;fe(ms=>ms?.name===Gt.name?ms:Gt);return}catch{}}})(),()=>{ct=!0}},[e,ve,t,u,o,Ne?.name,w,Re?.pr,r]),i.useEffect(()=>{S(G),k(G,{directory:t,branch:e,remoteName:Ne?.name??null,canShow:ve,github:u,githubAuthChecked:f,githubConnected:m?.connected??null})},[e,ve,t,S,u,f,m?.connected,G,Ne?.name,k]),i.useEffect(()=>(j(G),()=>{A(G)}),[G,j,A]),i.useEffect(()=>{const we=jl.get(w)??null;T(we?.title??Cu(e)),_(we?.body??""),$(we?.draft??!1),ne(we?.targetBaseBranch?si(we.targetBaseBranch):si(n));const et=vl(o,{selectedRemoteName:we?.selectedRemoteName,trackingBranch:r});fe(ct=>ct?.name===et?.name?ct:et)},[n,e,o,w,r]),i.useEffect(()=>{Tt({markInitialResolved:!0})},[G,Tt]),i.useEffect(()=>{!ve||!Ne?.name||Tt({force:!0,silent:!0,markInitialResolved:!0})},[ve,Tt,Ne?.name]),i.useEffect(()=>{const we=Re?.resolvedRemoteName?.trim();if(!we||Ot.current)return;const et=o.find(ct=>ct.name===we);et&&fe(ct=>ct?.name===et.name?ct:et)},[o,Re?.resolvedRemoteName]),i.useEffect(()=>{const we=Re?.pr?.state==="closed"||Re?.pr?.state==="merged",et=ye?.lastRefreshAt??0,ct=Date.now()-et>6e4,It=!we&&ct,Gt=()=>{It&&Tt({force:!0,silent:!0})},mt=()=>{document.visibilityState==="visible"&&It&&Tt({force:!0,silent:!0})};return window.addEventListener("focus",Gt),document.addEventListener("visibilitychange",mt),()=>{window.removeEventListener("focus",Gt),document.removeEventListener("visibilitychange",mt)}},[Tt,Re?.pr?.state,ye?.lastRefreshAt]),i.useEffect(()=>{f&&m?.connected===!1&&Tt({force:!0,silent:!0,markInitialResolved:!0})},[f,m,Tt]),i.useEffect(()=>{!t||!e||jl.set(w,{title:B,body:E,draft:R,additionalContext:V,targetBaseBranch:F,selectedRemoteName:Ne?.name})},[w,B,E,R,V,F,Ne?.name,t,e]),i.useEffect(()=>{const we=zt.current;return()=>{we.forEach(et=>{window.clearTimeout(et)}),zt.current=[]}},[]);const Dt=i.useCallback(async()=>{if(!H&&t){X(!0);try{const et={base:P&&de?.defaultBranchSha?de.defaultBranchSha:F,head:e};V&&(et.context=V);const ct=await rg(t,et);ct.title?.trim()&&T(ct.title.trim()),ct.body?.trim()&&_(ct.body.trim()),c?.()}catch(we){const et=we instanceof Error?we.message:String(we);le.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:et})}finally{X(!1)}}},[V,e,de?.defaultBranchSha,t,H,c,F,l,P]),cs=i.useCallback(async()=>{if(!u?.prCreate){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}const we=B.trim();if(!we){le.error(l("gitView.pr.toast.titleRequired"));return}const et=F.trim();if(!et){le.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!P&&et===e){le.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}ue(!0);try{const ct=Vc(r),It=P&&de,Gt=await u.prCreate({directory:t,title:we,head:e,base:et,...E.trim()?{body:E}:{},draft:R,...It?{targetRepo:{owner:de.owner,repo:de.repo},headRemote:"origin"}:{...Ne?{remote:Ne.name}:{},...ct&&ct!==Ne?.name?{headRemote:ct}:{}}});le.success(l("gitView.pr.toast.prCreated")),N(G,mt=>mt&&{...mt,pr:Gt}),await Tt({force:!0}),Vt()}catch(ct){const It=ct instanceof Error?ct.message:String(ct);le.error(l("gitView.pr.toast.createPrFailed"),{description:It})}finally{ue(!1)}},[E,e,de,t,R,u,G,Tt,Vt,Ne,F,B,r,N,P,l]),us=i.useCallback(async we=>{if(!u?.prMerge){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}Y(!0);try{const et=await u.prMerge({directory:t,number:we.number,method:te});et.merged?le.success(l("gitView.pr.toast.prMerged")):le.message(l("gitView.pr.toast.prNotMerged"),{description:et.message||l("gitView.pr.notMergeable")}),await Tt({force:!0}),Vt()}catch(et){const ct=et instanceof Error?et.message:String(et);le.error(l("gitView.pr.toast.mergeFailed"),{description:ct}),we.url&&Sl(we.url)}finally{Y(!1)}},[t,u,te,Tt,Vt,l]),He=i.useCallback(async we=>{if(!u?.prReady){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}O(!0);try{await u.prReady({directory:t,number:we.number}),le.success(l("gitView.pr.toast.markedReady")),await Tt({force:!0}),Vt()}catch(et){const ct=et instanceof Error?et.message:String(et);le.error(l("gitView.pr.toast.markReadyFailed"),{description:ct}),we.url&&Sl(we.url)}finally{O(!1)}},[t,u,Tt,Vt,l]),Ke=i.useCallback(async we=>{if(!u?.prUpdate){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}const et=Be.trim();if(!et){le.error(l("gitView.pr.toast.titleRequired"));return}Z(!0);try{const ct=await u.prUpdate({directory:t,number:we.number,title:et,body:Me});N(G,It=>It&&{...It,pr:{...It.pr??we,...ct}}),ee(!1),le.success(l("gitView.pr.toast.prUpdated")),await Tt({force:!0}),Vt()}catch(ct){const It=ct instanceof Error?ct.message:String(ct);le.error(l("gitView.pr.toast.updatePrFailed"),{description:It})}finally{Z(!1)}},[t,Me,Be,u,G,Tt,Vt,N,l]);if(!ve)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 jt=Re?.repo?.url||null,Lt=P&&de?.url?de.url:jt,Nt=Re?.checks??null,xs=!!Re?.canMerge,ps=!!Re?.connected,os=f&&Re?.connected===!1,Kt=Lw(Re),Fs=Kt?`var(--pr-${Kt})`:"var(--status-info)",js=Kt==="draft"?"git-pr-draft":Kt==="merged"?"git-merge":Kt==="closed"?"git-close-pull-request":"git-pull-request",rn=Ve?[`${Ve.state}${Ve.draft?" (draft)":""}`,Ve.mergeable===!1?l("gitView.pr.notMergeable"):null,Ve.state==="open"&&typeof Ve.mergeableState=="string"&&Ve.mergeableState&&Ve.mergeableState!=="unknown"?Ve.mergeableState:null].filter(Boolean).join(" · "):"",Ks=Nt?Nt.total>0?`${Nt.success}/${Nt.total} ${l("gitView.pr.checks.label")}`:`${Nt.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:[Ve?s.jsxs(Et,{children:[s.jsx(Mt,{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:()=>{Sl(Ve.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(I,{name:js,className:"size-4 shrink-0",style:{color:Fs}})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(I,{name:js,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")}),Ve?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",Ve.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Le?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(Et,{children:[s.jsx(Mt,{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(I,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),Ve?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:Fs},children:rn}),Nt?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${Fw(Nt.state)}`}),Ks]}):null,r&&Ne&&r.split("/")[0]!==Ne.name?s.jsxs("span",{className:"min-w-0 truncate",children:[r.split("/")[0]," → ",Ne.name]}):null]}):null]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[os?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.githubNotConnected")}),s.jsx($e,{variant:"outline",size:"sm",onClick:C,className:"w-fit",children:l("gitView.pr.actions.openSettings")})]}):null,J?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:J}),Lt?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:s.jsxs("a",{href:Lt,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!Ve&&!L&&!J&&!os?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):Ve?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:[se?s.jsxs("div",{className:"space-y-2",children:[s.jsx(jn,{value:Be,onChange:we=>Fe(we.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h}),s.jsx(Ni,{value:Me,onChange:we=>me(we.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:Ve.title}),Ve.body?.trim()?s.jsx(Po,{content:Ve.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(ot?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),xs&&Ve.draft?s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.draftMustBeReady")}):null,xs?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:[Ve.state==="open"?se?s.jsxs(s.Fragment,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{ee(!1),Fe(Ve.title||""),me(Ve.body||"")},disabled:Se,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(I,{name:"close",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>Ke(Ve),disabled:Se||!Be.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:Se?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"check",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>ee(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(I,{name:"edit",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,Nt?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:vt,disabled:Je,"aria-label":l("gitView.pr.actions.openChecksAria"),children:Je?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"information",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,Nt?.failure?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{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:Ht,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(I,{name:"error-warning",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:bt,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(I,{name:"chat-4",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{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:Zt,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(I,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),xs&&Ve.draft&&Ve.state==="open"?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>He(Ve),disabled:ge||ke||Se||se,"aria-label":l("gitView.pr.actions.markReadyAria"),children:ge?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.markReady")})})]}):null]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:xs?s.jsxs(s.Fragment,{children:[s.jsxs(zn,{value:te,onValueChange:we=>q(we),disabled:ke||Ve.state!=="open",children:[s.jsx(Wn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(Cn,{})}),s.jsxs(Un,{children:[s.jsx(Ms,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(Ms,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(Ms,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>us(Ve),disabled:ke||ge||Ve.state!=="open"||Ve.draft||Se||se,"aria-label":l("gitView.pr.actions.mergePrAria"),children:ke?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-merge",className:"size-4"})})}),s.jsx(Ft,{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)"})," → ",F," ",s.jsxs("span",{className:"opacity-60",children:["(",P&&de?"upstream":"remote",")"]})]})]}),Lt?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:Lt,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{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(jn,{value:B,onChange:we=>T(we.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")}),ae.length>0?s.jsxs(zn,{value:F,onValueChange:ne,children:[s.jsx(Wn,{className:"h-9",children:s.jsx(Cn,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(Un,{children:ae.map(we=>s.jsx(Ms,{value:we,children:we},we))})]}):s.jsx(jn,{value:F,onChange:we=>ne(we.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(Ni,{value:E,onChange:we=>_(we.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":R,onClick:()=>$(we=>!we),onKeyDown:we=>{(we.key===" "||we.key==="Enter")&&(we.preventDefault(),$(et=>!et))},children:[s.jsx(Pi,{size:"sm",checked:R,onChange:we=>$(we),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),x?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($e,{variant:"outline",size:"sm",onClick:()=>he(!0),children:V.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),V.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(eo,{open:Ae,onOpenChange:pe,children:[s.jsxs(Bo,{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:Ae?l("gitView.pr.actions.hide"):V.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(to,{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(Ni,{value:V,onChange:we=>z(we.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(Ua,{open:ce,onClose:()=>he(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx($e,{size:"sm",onClick:()=>he(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ni,{value:V,onChange:we=>z(we.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($e,{variant:"outline",size:"sm",onClick:Dt,disabled:H||oe,children:[H?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"ai-generate-2",className:"size-4 text-primary"}),l("gitView.commit.generate")]}),s.jsx("div",{className:"flex-1"}),s.jsxs($e,{size:"sm",className:"min-w-[7.5rem] justify-center gap-2",onClick:cs,disabled:oe||!ps||!F.trim()||!P&&F.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:oe?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx($s,{open:re,onOpenChange:Oe,children:s.jsxs(Vs,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(Gs,{children:[s.jsxs(Us,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(ln,{children:Ve?l("gitView.pr.numberLabel",{number:Ve.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(I,{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(qe?.checkRuns)&&qe?.checkRuns.length>0?qe.checkRuns.map((we,et)=>{const ct=`${we.id??"run"}:${we.job?.jobId??"job"}:${we.name}:${et}`;return s.jsx("div",{className:"p-1",children:Yt(we)},ct)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx($s,{open:_e,onOpenChange:Qe,children:s.jsxs(Vs,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(Gs,{children:s.jsxs(Us,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),Ve?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:Ve.number})}):null]})}),s.jsxs(Ha,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[Ct?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Ct?null:s.jsx("div",{className:"space-y-4",children:Ut.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Ut.map((we,et)=>{const ct=(we.authorName||"?").charAt(0).toUpperCase(),It=et===Ut.length-1;return s.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[It?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:we.avatarUrl?s.jsx("img",{src:we.avatarUrl,alt:we.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:ct})}),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:[we.authorName,we.authorLogin&&we.authorLogin!==we.authorName?` · @${we.authorLogin}`:""]}),we.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:ls(we.createdAt)}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs($e,{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:()=>{ys(we)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(I,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[we.context,we.path?` · ${we.path}`:"",we.line?`:${we.line}`:""]}),s.jsx(Po,{content:rs(we.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",qt].filter(Boolean).join(" "),enableFileReferences:!1})]})]},we.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},Uw=t=>{const e=ft.c(150),{open:n,onOpenChange:r,conflictFiles:o,directory:a,operation:c,onAbort:l,onClearState:d}=t;let u;e[0]!==o?(u=o===void 0?[]:o,e[0]=o,e[1]=u):u=e[1];const m=u,{t:f}=kt(),p=ut(Hw),y=ut(Gw),g=ci(Kw),b=ci(qw),x=Ee(Yw),[h,C]=i.useState(!1),[w,v]=i.useState(null),[S,k]=i.useState(null);let j,A;e[2]!==a||e[3]!==n||e[4]!==f?(j=()=>{!n||!a||(C(!0),k(null),v(null),ig(a).then(P=>{v(P)}).catch(P=>{const M=P instanceof Error?P.message:f("gitView.conflict.loadFailed");k(M)}).finally(()=>{C(!1)}))},A=[n,a,f],e[2]=a,e[3]=n,e[4]=f,e[5]=j,e[6]=A):(j=e[5],A=e[6]),i.useEffect(j,A);let D;e[7]!==w||e[8]!==a||e[9]!==c?(D=async()=>{if(!w)return null;const P=c==="merge"?"merge":"rebase",M=w.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),de=c==="merge"?"git commit --no-edit":"git rebase --continue",xe=await En("git.conflict.resolve.visible",{operation_label:P,head_ref:M}),W=await En("git.conflict.resolve.instructions",{operation_label:P,directory:a,operation:c,head_info:w.headInfo||"N/A",continue_cmd:de}),be=`${P} 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:xe,instructionsText:W,payloadText:be}},e[7]=w,e[8]=a,e[9]=c,e[10]=D):D=e[10];const N=D;let B;e[11]!==l||e[12]!==r?(B=()=>{l(),r(!1)},e[11]=l,e[12]=r,e[13]=B):B=e[13];const T=B;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 _=E;let R;e[17]!==N||e[18]!==y||e[19]!==d||e[20]!==r||e[21]!==x||e[22]!==g||e[23]!==b||e[24]!==f?(R=async()=>{const P=await N();if(!P){le.error(f("gitView.conflict.noDetailsAvailable"));return}if(!y){le.error(f("gitView.conflict.noActiveSession"),{description:f("gitView.conflict.noActiveSessionDescription")});return}g(P.visibleText,"replace"),b([{text:P.instructionsText,synthetic:!0},{text:P.payloadText,synthetic:!0}]),x("chat"),d?.(),r(!1)},e[17]=N,e[18]=y,e[19]=d,e[20]=r,e[21]=x,e[22]=g,e[23]=b,e[24]=f,e[25]=R):R=e[25];const $=R;let V;e[26]!==N||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==p||e[31]!==x||e[32]!==f?(V=async()=>{const P=await N();if(!P){le.error(f("gitView.conflict.noDetailsAvailable"));return}p({directoryOverride:a,initialPrompt:P.visibleText,syntheticParts:[{text:P.instructionsText,synthetic:!0},{text:P.payloadText,synthetic:!0}]}),x("chat"),d?.(),r(!1)},e[26]=N,e[27]=a,e[28]=d,e[29]=r,e[30]=p,e[31]=x,e[32]=f,e[33]=V):V=e[33];const z=V;let F,ne,te,q,H,X,oe,ue,Se,Z,ke,Y,ge,O,se,ee,je,De,Be,Fe,Me,me;if(e[34]!==w||e[35]!==m||e[36]!==y||e[37]!==T||e[38]!==_||e[39]!==$||e[40]!==z||e[41]!==h||e[42]!==S||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==f){const P=f(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),M=w?.unmergedFiles||m;te=$s,Me=n,me=r,ne=Vs,Fe="max-w-md w-[calc(100vw-2rem)]",O="flex flex-col gap-4 overflow-hidden";let de;e[69]===Symbol.for("react.memo_cache_sentinel")?(de=s.jsx(I,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=de):de=e[69];const xe=s.jsxs("div",{className:"flex items-center gap-2",children:[de,s.jsx(Us,{children:f("gitView.conflict.detectedTitle",{operation:P})})]});let W;e[70]!==c||e[71]!==f?(W=f("gitView.conflict.detectedDescription",{operation:c}),e[70]=c,e[71]=f,e[72]=W):W=e[72];let be;e[73]!==W?(be=s.jsx(ln,{children:W}),e[73]=W,e[74]=be):be=e[74],e[75]!==xe||e[76]!==be?(se=s.jsxs(Gs,{children:[xe,be]}),e[75]=xe,e[76]=be,e[77]=se):se=e[77],e[78]!==h||e[79]!==f?(ee=h&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:f("gitView.conflict.loading")})]}),e[78]=h,e[79]=f,e[80]=ee):ee=e[80],e[81]!==S||e[82]!==f?(je=S&&s.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:f("gitView.conflict.errorLoadingDetails",{message:S})}),e[81]=S,e[82]=f,e[83]=je):je=e[83],e[84]!==M||e[85]!==f?(De=M.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:f("gitView.conflict.conflictedFiles")}),s.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:M.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:M.map(Qw)})})]}),e[84]=M,e[85]=f,e[86]=De):De=e[86],e[87]!==w||e[88]!==f?(Be=w?.headInfo&&s.jsxs("div",{className:"space-y-1 overflow-hidden",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:f("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]=f,e[89]=Be):Be=e[89],ke="flex flex-col gap-2 pt-2";let ve;e[90]!==z?(ve=()=>{z()},e[90]=z,e[91]=ve):ve=e[91];const G=h||!w;let ye;e[92]!==h?(ye=h?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"add",className:"size-4"}),e[92]=h,e[93]=ye):ye=e[93];let Le;e[94]!==f?(Le=f("gitView.conflict.resolveNewSession"),e[94]=f,e[95]=Le):Le=e[95],e[96]!==ve||e[97]!==G||e[98]!==ye||e[99]!==Le?(Y=s.jsxs($e,{variant:"default",onClick:ve,disabled:G,className:"w-full gap-2",children:[ye,Le]}),e[96]=ve,e[97]=G,e[98]=ye,e[99]=Le,e[100]=Y):Y=e[100];let Re;e[101]!==$?(Re=()=>{$()},e[101]=$,e[102]=Re):Re=e[102];const J=h||!w||!y;let L;e[103]!==h?(L=h?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"chat-1",className:"size-4"}),e[103]=h,e[104]=L):L=e[104];let ae;e[105]!==f?(ae=f("gitView.conflict.resolveCurrentSession"),e[105]=f,e[106]=ae):ae=e[106],e[107]!==Re||e[108]!==J||e[109]!==L||e[110]!==ae?(ge=s.jsxs($e,{variant:"outline",onClick:Re,disabled:J,className:"w-full gap-2",children:[L,ae]}),e[107]=Re,e[108]=J,e[109]=L,e[110]=ae,e[111]=ge):ge=e[111],Se="flex gap-2 pt-1";let re;e[112]!==f?(re=f("gitView.conflict.continueLater"),e[112]=f,e[113]=re):re=e[113],e[114]!==_||e[115]!==re?(Z=s.jsx($e,{variant:"ghost",size:"sm",onClick:_,className:"flex-1",children:re}),e[114]=_,e[115]=re,e[116]=Z):Z=e[116],F=$e,q="destructive",H="sm",X=T,oe="flex-1",ue=f("gitView.conflict.abortOperation",{operation:P}),e[34]=w,e[35]=m,e[36]=y,e[37]=T,e[38]=_,e[39]=$,e[40]=z,e[41]=h,e[42]=S,e[43]=r,e[44]=n,e[45]=c,e[46]=f,e[47]=F,e[48]=ne,e[49]=te,e[50]=q,e[51]=H,e[52]=X,e[53]=oe,e[54]=ue,e[55]=Se,e[56]=Z,e[57]=ke,e[58]=Y,e[59]=ge,e[60]=O,e[61]=se,e[62]=ee,e[63]=je,e[64]=De,e[65]=Be,e[66]=Fe,e[67]=Me,e[68]=me}else F=e[47],ne=e[48],te=e[49],q=e[50],H=e[51],X=e[52],oe=e[53],ue=e[54],Se=e[55],Z=e[56],ke=e[57],Y=e[58],ge=e[59],O=e[60],se=e[61],ee=e[62],je=e[63],De=e[64],Be=e[65],Fe=e[66],Me=e[67],me=e[68];let Ae;e[117]!==F||e[118]!==q||e[119]!==H||e[120]!==X||e[121]!==oe||e[122]!==ue?(Ae=s.jsx(F,{variant:q,size:H,onClick:X,className:oe,children:ue}),e[117]=F,e[118]=q,e[119]=H,e[120]=X,e[121]=oe,e[122]=ue,e[123]=Ae):Ae=e[123];let pe;e[124]!==Se||e[125]!==Z||e[126]!==Ae?(pe=s.jsxs("div",{className:Se,children:[Z,Ae]}),e[124]=Se,e[125]=Z,e[126]=Ae,e[127]=pe):pe=e[127];let ce;e[128]!==ke||e[129]!==Y||e[130]!==ge||e[131]!==pe?(ce=s.jsxs("div",{className:ke,children:[Y,ge,pe]}),e[128]=ke,e[129]=Y,e[130]=ge,e[131]=pe,e[132]=ce):ce=e[132];let he;e[133]!==O||e[134]!==se||e[135]!==ee||e[136]!==je||e[137]!==De||e[138]!==Be||e[139]!==ce?(he=s.jsxs("div",{className:O,children:[se,ee,je,De,Be,ce]}),e[133]=O,e[134]=se,e[135]=ee,e[136]=je,e[137]=De,e[138]=Be,e[139]=ce,e[140]=he):he=e[140];let Ne;e[141]!==ne||e[142]!==Fe||e[143]!==he?(Ne=s.jsx(ne,{className:Fe,children:he}),e[141]=ne,e[142]=Fe,e[143]=he,e[144]=Ne):Ne=e[144];let fe;return e[145]!==te||e[146]!==Me||e[147]!==me||e[148]!==Ne?(fe=s.jsx(te,{open:Me,onOpenChange:me,children:Ne}),e[145]=te,e[146]=Me,e[147]=me,e[148]=Ne,e[149]=fe):fe=e[149],fe};function Hw(t){return t.openNewSessionDraft}function Gw(t){return t.currentSessionId}function Kw(t){return t.setPendingInputText}function qw(t){return t.setPendingSyntheticParts}function Yw(t){return t.setActiveMainTab}function Qw(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const Jw=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=kt(),[c,l]=i.useState(!0),[d,u]=i.useState(!1),m=a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),f=async()=>{u(!0);try{await o(c),e(!1)}catch(y){const g=y instanceof Error?y.message:`Failed to ${n}`;le.error(g)}finally{u(!1)}},p=()=>{d||e(!1)};return s.jsx($s,{open:t,onOpenChange:d?void 0:e,children:s.jsxs(Vs,{className:"max-w-md",children:[s.jsxs(Gs,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(Us,{children:a("gitView.stash.title")})]}),s.jsx(ln,{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(Pi,{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(or,{className:"gap-2",children:[s.jsx($e,{variant:"ghost",size:"sm",onClick:p,disabled:d,children:a("gitView.common.cancel")}),s.jsx($e,{variant:"default",size:"sm",onClick:f,disabled:d,className:"gap-1.5",children:d?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:m})})]})]})})},Xw=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=kt(),[d,u]=i.useState(null),m=t&&t.head,f=e&&(e.headName||e.onto),p=m?"merge":f?"rebase":null;if(!p)return null;const y=async()=>{u("continue");try{await n()}finally{u(null)}},g=async()=>{u("abort");try{await r()}finally{u(null)}},b=d!==null,x=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(I,{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:x})}),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($e,{variant:"outline",size:"sm",onClick:o,disabled:b||c,className:"gap-1.5",children:[s.jsx(I,{name:"sparkling",className:"size-4"}),l("gitView.operation.resolveWithAi")]}),d!=="continue"&&s.jsxs($e,{variant:"ghost",size:"sm",onClick:g,disabled:b||c,className:"gap-1.5",children:[d==="abort"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs($e,{variant:"default",size:"sm",onClick:y,disabled:b||c,className:"gap-1.5",children:[d==="continue"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{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")})]})})},Zw=t=>{const e=ft.c(104),{currentBranch:n,localBranches:r,remoteBranches:o,onMerge:a,onRebase:c,disabled:l,isOperating:d,operationLogs:u,onOperationComplete:m,mode:f,defaultTargetBranch:p}=t,y=l===void 0?!1:l,g=d===void 0?!1:d,b=u===void 0?[]:u,x=f===void 0?"dialog":f,{t:h}=kt(),[C,w]=i.useState(!1),[v,S]=i.useState("merge"),[k,j]=i.useState(null),[A,D]=i.useState(!1),[N,B]=i.useState(""),T=i.useRef(null),E=i.useRef(null),_=y||g,R=n||h("gitView.branch.currentBranchFallback"),$=b.length>0&&b.every(ev),V=b.some(tv);let z;e[0]===Symbol.for("react.memo_cache_sentinel")?(z=()=>{E.current&&(E.current.scrollTop=E.current.scrollHeight)},e[0]=z):z=e[0],i.useEffect(z,[b]);let F;if(e[1]!==N||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Re=N.toLowerCase();let J;e[6]!==o?(J=new Set(o.map(sv).filter(Boolean)),e[6]=o,e[7]=J):J=e[7];const L=J;let ae;e[8]!==n||e[9]!==L?(ae=Oe=>Oe!==n&&!L.has(Oe),e[8]=n,e[9]=L,e[10]=ae):ae=e[10];const re=r.filter(ae);if(!Re){F=re;break e}F=re.filter(Oe=>Oe.toLowerCase().includes(Re))}e[1]=N,e[2]=n,e[3]=r,e[4]=o,e[5]=F}else F=e[5];const ne=F;let te;if(e[11]!==N||e[12]!==o){e:{const Re=N.toLowerCase();if(!Re){te=o;break e}te=o.filter(J=>J.toLowerCase().includes(Re))}e[11]=N,e[12]=o,e[13]=te}else te=e[13];const q=te;let H;e[14]!==p||e[15]!==r||e[16]!==o?(H=()=>p&&(o.includes(p)||r.includes(p))?p:null,e[14]=p,e[15]=r,e[16]=o,e[17]=H):H=e[17];const X=H;let oe;e[18]!==X||e[19]!==w?(oe=()=>{w(!0),j(X()),S("merge"),B("")},e[18]=X,e[19]=w,e[20]=oe):oe=e[20];const ue=oe;let Se;e[21]===Symbol.for("react.memo_cache_sentinel")?(Se=Re=>{j(Re),D(!1),B("")},e[21]=Se):Se=e[21];const Z=Se;let ke;e[22]!==a||e[23]!==c||e[24]!==v||e[25]!==k?(ke=()=>{k&&(v==="merge"?a(k):c(k))},e[22]=a,e[23]=c,e[24]=v,e[25]=k,e[26]=ke):ke=e[26];const Y=ke;let ge;e[27]!==g||e[28]!==w?(ge=()=>{g||(j(null),S("merge"),B(""),w(!1))},e[27]=g,e[28]=w,e[29]=ge):ge=e[29];const O=ge,se=()=>{g&&!$||($&&m?.(),j(null),S("merge"),B(""),w(!1))};let ee,je;e[30]!==A?(ee=()=>{A||B("")},je=[A],e[30]=A,e[31]=ee,e[32]=je):(ee=e[31],je=e[32]),i.useEffect(ee,je);let De,Be;e[33]!==x||e[34]!==X||e[35]!==k?(De=()=>{x!=="inline"||k||j(X())},Be=[x,X,k],e[33]=x,e[34]=X,e[35]=k,e[36]=De,e[37]=Be):(De=e[36],Be=e[37]),i.useEffect(De,Be);const me=g?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(nv)})}),$?x==="dialog"?s.jsx(or,{children:s.jsx($e,{variant:"default",size:"sm",onClick:se,children:h(V?"gitView.common.close":"gitView.common.done")})}):s.jsx("div",{className:"flex justify-end",children:s.jsx($e,{variant:"default",size:"sm",onClick:se,children:h(V?"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:()=>S("merge"),className:Pe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",v==="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(I,{name:"git-merge",className:Pe("size-4",v==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Pe("typography-ui-label",v==="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:()=>S("rebase"),className:Pe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",v==="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(I,{name:"git-branch",className:Pe("size-4",v==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Pe("typography-ui-label",v==="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:v==="merge"?h("gitView.branch.branchToMergeInto",{branch:R}):h("gitView.branch.branchToRebaseOnto")}),s.jsxs(nn,{open:A,onOpenChange:D,modal:!1,children:[s.jsx(tn,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:Pe("truncate",!k&&"text-muted-foreground"),children:k||h("gitView.branch.selectBranch")}),s.jsx(I,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(sn,{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(Va,{className:"h-full min-h-0",children:[s.jsx($a,{ref:T,placeholder:h("gitView.branch.searchPlaceholder"),value:N,onValueChange:B,onKeyDown:rv}),s.jsxs(za,{className:"h-full min-h-0",disableHorizontal:!0,children:[s.jsx(Wa,{children:h("gitView.branch.empty")}),ne.length>0&&s.jsx(oi,{heading:h("gitView.branch.localBranches"),children:ne.map(Re=>s.jsx(li,{onSelect:()=>Z(Re),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Re})},`local-${Re}`))}),ne.length>0&&q.length>0?s.jsx(og,{}):null,q.length>0&&s.jsx(oi,{heading:h("gitView.branch.remoteBranches"),children:q.map(Re=>s.jsx(li,{onSelect:()=>Z(Re),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Re})},`remote-${Re}`))})]})]})})]})]}),k?s.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:v==="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:R})]}):s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryRebasePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R})," ",h("gitView.branch.summaryRebaseInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})]})})}):null,x==="dialog"?s.jsxs(or,{className:"gap-2 pt-1",children:[s.jsx($e,{variant:"ghost",size:"sm",onClick:O,children:h("gitView.common.cancel")}),s.jsx($e,{variant:"default",size:"sm",onClick:Y,disabled:!k,className:"gap-1.5",children:v==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"git-merge",className:"size-4"}),h("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"git-branch",className:"size-4"}),h("gitView.operation.rebase")]})})]}):s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx($e,{variant:"destructive",size:"sm",onClick:O,disabled:_,children:h("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx($e,{variant:"default",size:"sm",onClick:Y,disabled:_||!k,children:h(v==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(x==="inline"){let Re;e[38]!==h?(Re=h("gitView.branch.updateTitle"),e[38]=h,e[39]=Re):Re=e[39];let J;e[40]!==Re?(J=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Re}),e[40]=Re,e[41]=J):J=e[41];let L;e[42]!==h?(L=h("gitView.branch.updateDescriptionPrefix"),e[42]=h,e[43]=L):L=e[43];let ae;e[44]!==R?(ae=s.jsx("span",{className:"font-mono text-foreground",children:R}),e[44]=R,e[45]=ae):ae=e[45];let re;e[46]!==L||e[47]!==ae?(re=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[L," ",ae,"."]}),e[46]=L,e[47]=ae,e[48]=re):re=e[48];let Oe;e[49]!==J||e[50]!==re?(Oe=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[J,re]})}),e[49]=J,e[50]=re,e[51]=Oe):Oe=e[51];let qe;e[52]!==me?(qe=s.jsx("div",{className:"pt-3",children:me}),e[52]=me,e[53]=qe):qe=e[53];let Ge;return e[54]!==Oe||e[55]!==qe?(Ge=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Oe,qe]}),e[54]=Oe,e[55]=qe,e[56]=Ge):Ge=e[56],Ge}let Ae;e[57]!==g?(Ae=g?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-merge",className:"size-4"}),e[57]=g,e[58]=Ae):Ae=e[58];let pe;e[59]!==h?(pe=h("gitView.branch.mergeRebase"),e[59]=h,e[60]=pe):pe=e[60];let ce;e[61]!==pe?(ce=s.jsx("span",{children:pe}),e[61]=pe,e[62]=ce):ce=e[62];let he;e[63]!==ue||e[64]!==_||e[65]!==Ae||e[66]!==ce?(he=s.jsx(Mt,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"sm",className:"gap-1.5",onClick:ue,disabled:_,children:[Ae,ce]})}),e[63]=ue,e[64]=_,e[65]=Ae,e[66]=ce,e[67]=he):he=e[67];let Ne;e[68]!==h?(Ne=h("gitView.branch.mergeRebaseTooltip"),e[68]=h,e[69]=Ne):Ne=e[69];let fe;e[70]!==Ne?(fe=s.jsx(Ft,{sideOffset:8,children:Ne}),e[70]=Ne,e[71]=fe):fe=e[71];let P;e[72]!==he||e[73]!==fe?(P=s.jsxs(Et,{children:[he,fe]}),e[72]=he,e[73]=fe,e[74]=P):P=e[74];let M;e[75]!==se||e[76]!==w?(M=Re=>{Re?w(!0):se()},e[75]=se,e[76]=w,e[77]=M):M=e[77];let de;e[78]!==h?(de=h("gitView.branch.updateTitle"),e[78]=h,e[79]=de):de=e[79];let xe;e[80]!==de?(xe=s.jsx(Us,{children:de}),e[80]=de,e[81]=xe):xe=e[81];let W;e[82]!==V||e[83]!==g||e[84]!==v||e[85]!==$||e[86]!==h||e[87]!==R?(W=g?h($?V?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":v==="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:R}),"."]}),e[82]=V,e[83]=g,e[84]=v,e[85]=$,e[86]=h,e[87]=R,e[88]=W):W=e[88];let be;e[89]!==W?(be=s.jsx(ln,{children:W}),e[89]=W,e[90]=be):be=e[90];let ve;e[91]!==xe||e[92]!==be?(ve=s.jsxs(Gs,{children:[xe,be]}),e[91]=xe,e[92]=be,e[93]=ve):ve=e[93];let G;e[94]!==me||e[95]!==ve?(G=s.jsxs(Vs,{className:"max-w-md",children:[ve,me]}),e[94]=me,e[95]=ve,e[96]=G):G=e[96];let ye;e[97]!==C||e[98]!==M||e[99]!==G?(ye=s.jsx($s,{open:C,onOpenChange:M,children:G}),e[97]=C,e[98]=M,e[99]=G,e[100]=ye):ye=e[100];let Le;return e[101]!==P||e[102]!==ye?(Le=s.jsxs(s.Fragment,{children:[P,ye]}),e[101]=P,e[102]=ye,e[103]=Le):Le=e[103],Le};function ev(t){return t.status==="done"||t.status==="error"}function tv(t){return t.status==="error"}function sv(t){return t.slice(t.indexOf("/")+1)}function nv(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(I,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(I,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(I,{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:Pe("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 rv(t){return t.stopPropagation()}const iv=({runMutation:t,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:o})=>{const a=[];let c=!1;return{enqueue:d=>{const u=a[a.length-1];if(u?.directory===d.directory&&u.direction===d.direction){d.paths.forEach(m=>u.paths.add(m));return}a.push(d)},flush:()=>{if(c)return;const d=a.shift();if(!d)return;c=!0;const u={directory:d.directory,direction:d.direction,paths:Array.from(d.paths),rollback:d.rollback};(async()=>{try{await t(u),e(u)}catch(m){n(u,m)}finally{r(u.paths),c=!1,a.length>0&&o()}})()},clear:()=>{a.length=0},size:()=>a.length,isRunning:()=>c}},Au="oc.git.actionTab",ov=15e3,av=t=>t==="commit"||t==="branch"||t==="pr",lv=40,cv=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:"},dv=(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(u=>u.code===d)||null}const a=n.split(" ")[0],c=Du[a];return c&&e.find(l=>l.code===c)||null},uv=20,$i=new Map,fv=(t,e)=>{if($i.delete(t),$i.set(t,e),$i.size>uv){const n=$i.keys().next().value;n!==void 0&&$i.delete(n)}},zr=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Iu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},mv=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},ec=({isActive:t})=>{const{t:e}=kt(),{git:n}=Xn(),r=di(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=ut(K=>K.currentSessionId),u=ut(K=>K.newSessionDraft),m=ut(K=>K.setDraftBootstrapPendingDirectory),f=ut(K=>K.worktreeMetadata),p=ut(K=>K.availableWorktrees),y=zr(r),g=i.useMemo(()=>{if(!y)return;const K=p.find(Ce=>zr(Ce.path)===y);if(K)return K;for(const Ce of f.values())if(zr(Ce.path)===y)return Ce},[p,y,f]),b=i.useMemo(()=>{if(d)return f.get(d)??g;if(u?.open)return g},[d,g,u?.open,f]),{profiles:x,globalIdentity:h,defaultGitIdentityId:C,loadProfiles:w,loadGlobalIdentity:v,loadDefaultGitIdentityId:S}=Wx(zl(K=>({profiles:K.profiles,globalIdentity:K.globalIdentity,defaultGitIdentityId:K.defaultGitIdentityId,loadProfiles:K.loadProfiles,loadGlobalIdentity:K.loadGlobalIdentity,loadDefaultGitIdentityId:K.loadDefaultGitIdentityId}))),k=kc(r??null),j=Ga(r??null),A=Yf(K=>d?K.getAttachment(d):void 0),D=A?ag(A):[],N=A&&!A.degraded&&!A.legacy?A.worktreeRoot??void 0:void 0,B=Wy(r,b,j?.current??void 0),T=em(r??null),E=lg(r??null),_=cg(r??null),R=Cc(r??null),$=dg(r??null),{setActiveDirectory:V,fetchAll:z,ensureAll:F,fetchStatus:ne,fetchBranches:te,fetchLog:q,setLogMaxCount:H,fetchIdentity:X,prefetchDiffs:oe,moveStatusPathsOptimistically:ue,restoreStatus:Se,bumpIndexRevision:Z}=vn(zl(K=>({setActiveDirectory:K.setActiveDirectory,fetchAll:K.fetchAll,ensureAll:K.ensureAll,fetchStatus:K.fetchStatus,fetchBranches:K.fetchBranches,fetchLog:K.fetchLog,setLogMaxCount:K.setLogMaxCount,fetchIdentity:K.fetchIdentity,prefetchDiffs:K.prefetchDiffs,moveStatusPathsOptimistically:K.moveStatusPathsOptimistically,restoreStatus:K.restoreStatus,bumpIndexRevision:K.bumpIndexRevision}))),ke=Ee(K=>K.isMobile),Y=Ee(K=>K.openContextDiff),ge=Ee(K=>K.navigateToDiff),O=Ee(K=>K.setRightSidebarOpen),se=i.useRef(null),ee=i.useRef(null),je=i.useRef(null),De=i.useRef(null),Be=i.useRef(!0);i.useEffect(()=>()=>{Be.current=!1},[]);const Fe=i.useCallback(()=>{ee.current!==null&&(window.clearTimeout(ee.current),ee.current=null)},[]),Me=i.useCallback(K=>{Fe(),ee.current=window.setTimeout(()=>{ee.current=null,zr(K)===zr(r)&&ne(K,n,{silent:!0})},ov)},[Fe,r,ne,n]);i.useEffect(()=>Fe,[Fe]);const me=i.useCallback(()=>{je.current!==null&&(window.clearTimeout(je.current),je.current=null)},[]),Ae=i.useCallback(()=>{je.current===null&&(je.current=window.setTimeout(()=>{je.current=null,De.current?.()},0))},[]),pe=i.useCallback(async(K,Ce,Te)=>{if(Ce==="stage"){if(n.stageGitFiles){await n.stageGitFiles(K,Te);return}await Promise.all(Te.map(ze=>n.stageGitFile(K,ze)));return}if(n.unstageGitFiles){await n.unstageGitFiles(K,Te);return}await Promise.all(Te.map(ze=>n.unstageGitFile(K,ze)))},[n]),ce=i.useMemo(()=>iv({runMutation:({directory:K,direction:Ce,paths:Te})=>pe(K,Ce,Te),onMutationComplete:({directory:K})=>{Z(K),Me(K)},onMutationError:({directory:K,direction:Ce,rollback:Te},ze)=>{Te?.(),Z(K),Me(K);const dt=e(Ce==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");le.error(ze instanceof Error?ze.message:dt)},onPathsComplete:K=>{ns(Ce=>{const Te=new Set(Ce);return K.forEach(ze=>Te.delete(ze)),Te})},scheduleFlush:Ae}),[Z,pe,Ae,Me,e]);i.useEffect(()=>(De.current=ce.flush,()=>{De.current=null}),[ce]),i.useEffect(()=>()=>ce.clear(),[ce]),i.useEffect(()=>me,[me]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let K=!1,Ce=null;const Te=async()=>{try{const ze=await fg(r);if(K)return;a(ze.status),ze.status==="pending"&&(Ce=window.setTimeout(()=>{Te()},500))}catch{K||a(null)}};return Te(),()=>{K=!0,Ce!==null&&window.clearTimeout(Ce)}},[t,r]),i.useEffect(()=>{const K=se.current;se.current=o,!(!r||!n)&&(K==="pending"&&o==="ready"&&(l(!0),z(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(m(null),l(!1)))},[r,z,n,m,o]);const he=zr(u?.bootstrapPendingDirectory??null),Ne=!!(r&&he&&he===zr(r)),P=!!(r&&(o==="pending"||Ne))||c,M=i.useMemo(()=>r?$i.get(r)??null:null,[r]),de=ss(K=>K.settingsGitmojiEnabled),[xe,W]=i.useState(null),{gitmojis:be}=zy(de);i.useEffect(()=>{const K=N||B?.projectDirectory;if(!K){W(null);return}let Ce=!1;return Ka(K).then(Te=>{if(Ce)return;const ze=Te.trim();W(ze&&ze!=="HEAD"?ze:null)}).catch(()=>{Ce||W(null)}),()=>{Ce=!0}},[N,B?.projectDirectory]);const[ve,G]=i.useState(M?.commitMessage??""),[ye,Le]=i.useState([]),[Re,J]=i.useState(!1),L=i.useRef(null),[ae,re]=i.useState(null),[Oe,qe]=i.useState(!1),[Ge,Je]=i.useState(null),[nt,gt]=i.useState(25),[yt,_e]=i.useState(!1),{triggerFireworks:Qe}=By(),st=i.useRef(new Map),wt=i.useRef(0),Ct=i.useCallback(()=>{wt.current+=1,Be.current&&_e(!0)},[]),xt=i.useCallback(()=>{wt.current=Math.max(0,wt.current-1),Be.current&&wt.current===0&&_e(!1)},[]),[St,Ze]=i.useState(new Set),[Ot,ns]=i.useState(new Set),[zt,Ve]=i.useState(!1),[At,ot]=i.useState(0),[vt,bt]=i.useState(!1),[ls,Wt]=i.useState(M?.generatedHighlights??[]),qt=Ot.size>0||ce.size()>0||ce.isRunning(),rs=i.useCallback(()=>{const K=L.current;K&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{K.scrollTo({top:K.scrollHeight,behavior:"smooth"})})})},[]),Ut=N||B?.projectDirectory||null,Bt=j?.current||null,_t=i.useMemo(()=>{const K=j?.tracking;return K?K.startsWith("origin/"):!0},[j?.tracking]),Yt=i.useMemo(()=>{const K=B?.createdFromBranch,Ce=typeof K=="string"?K.trim():"",Te=typeof j?.current=="string"?j.current.trim():"",ze=typeof xe=="string"?xe.trim():"";return Ce?Ce===Te&&Ce.startsWith("opencode/")&&ze.length>0&&ze!==Ce?ze:Ce:ze||Te||"HEAD"},[B?.createdFromBranch,j,xe]),Ht=i.useCallback(()=>{Wt([])},[]),[Zt,ys]=i.useState(new Set),[Tt,Vt]=i.useState(new Map),[Dt,cs]=i.useState(new Set),us=i.useRef(Tt),He=i.useRef(Dt),[Ke,jt]=i.useState(null),[Lt,Nt]=i.useState(null),[xs,ps]=i.useState(""),[os,Kt]=i.useState(null),Fs=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(I,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(I,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(I,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[js,rn]=i.useState(()=>{if(typeof window>"u")return"commit";const K=window.localStorage.getItem(Au);return K==="worktree"?"branch":av(K)?K:"commit"}),[Ks,cn]=i.useState([]),[Mn,Ls]=i.useState(null),[we,et]=i.useState(null),[ct,It]=i.useState([]),[Gt,mt]=i.useState(!1),[ms,hs]=i.useState([]),[Ss,ws]=i.useState("merge"),[Ds,Hn]=i.useState(null),[zs,Sn]=i.useState(!1),[Fn,Zn]=i.useState(100),dn=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),Ue=i.useCallback((K,Ce,Te)=>{if(!dn||typeof window>"u")return;const ze={directory:K,conflictFiles:Ce,operation:Te};window.localStorage.setItem(dn,JSON.stringify(ze))},[dn]),Xt=i.useCallback(()=>{!dn||typeof window>"u"||window.localStorage.removeItem(dn)},[dn]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Au,js)},[js]),i.useEffect(()=>{if(!dn||typeof window>"u"||!r)return;const K=window.localStorage.getItem(dn);if(K)try{const Ce=JSON.parse(K);if(Ce.directory!==r){window.localStorage.removeItem(dn);return}hs(Ce.conflictFiles??[]),ws(Ce.operation??"merge"),mt(!0)}catch{window.localStorage.removeItem(dn)}},[dn,r]);const[Is,Ts]=i.useState(!1),[Ws,qs]=i.useState("merge"),[Hs,Os]=i.useState(""),Gn=i.useCallback(K=>{fr(K).then(Ce=>{if(Ce.ok){le.success(e("gitView.toast.commitHashCopied"));return}le.error(e("gitView.toast.copyFailed"))})},[e]),mr=i.useCallback(K=>{ys(Ce=>{const Te=new Set(Ce);return Te.has(K)?Te.delete(K):Te.add(K),Te})},[]);i.useEffect(()=>{us.current=Tt},[Tt]),i.useEffect(()=>{He.current=Dt},[Dt]),i.useEffect(()=>{if(!r||!n)return;const K=Array.from(Zt).filter(Te=>!us.current.has(Te)&&!He.current.has(Te));if(K.length===0)return;let Ce=!1;return cs(Te=>{const ze=new Set(Te);for(const dt of K)ze.add(dt);return He.current=ze,ze}),Promise.all(K.map(Te=>n.getCommitFiles(r,Te).then(ze=>({hash:Te,files:ze.files})).catch(ze=>(console.error("Failed to fetch commit files:",ze),{hash:Te,files:[]})))).then(Te=>{Ce||(Vt(ze=>{const dt=new Map(ze);for(const{hash:Rt,files:Qt}of Te)dt.set(Rt,Qt);return us.current=dt,dt}),cs(ze=>{const dt=new Set(ze);for(const{hash:Rt}of Te)dt.delete(Rt);return He.current=dt,dt}))}),()=>{Ce=!0,cs(Te=>{let ze=!1;const dt=new Set(Te);for(const Rt of K)dt.delete(Rt)&&(ze=!0);return ze?(He.current=dt,dt):Te})}},[Zt,r,n]),i.useEffect(()=>{r&&fv(r,{directory:r,commitMessage:ve,generatedHighlights:ls})},[ve,r,ls]),i.useEffect(()=>{t&&(w(),v(),S())},[t,w,v,S]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){Nt(null);return}let K=!1;return n.getRemoteUrl(r).then(Ce=>{K||Nt(Ce)}).catch(()=>{K||Nt(null)}),()=>{K=!0}},[t,r,n]);const Kn=i.useCallback(async()=>{if(!r||!n?.getRemotes){cn([]);return}try{const K=await n.getRemotes(r);Be.current&&cn(K)}catch{Be.current&&cn([])}},[r,n]);i.useEffect(()=>{t&&Kn()},[t,Kn]),i.useEffect(()=>{t&&r&&(V(r),F(r,n))},[t,r,V,F,n]),i.useEffect(()=>{if(t&&r)return Tr.onGitRefreshHint(K=>{zr(K.directory)===zr(r)&&ne(r,n)})},[t,r,ne,n]);const gs=i.useCallback(async(K=!0)=>{if(r)try{await Promise.all([ne(r,n),te(r,n)])}catch(Ce){if(K){const Te=Ce instanceof Error?Ce.message:e("gitView.toast.refreshRepositoryFailed");le.error(Te)}}},[r,n,ne,te,e]),Rs=i.useCallback(async()=>{r&&await q(r,n,nt)},[r,n,q,nt]),Sr=i.useCallback(async()=>{r&&await X(r,n)},[r,n,X]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||k!==!0)return;const K=typeof C=="string"?C.trim():"";if(!K||K==="global"||st.current.get(r)===K)return;let Te=!1;return(async()=>{try{const dt=await n.hasLocalIdentity?.(r);if(Te||dt===!0)return;Ct(),await n.setGitIdentity(r,K),st.current.set(r,K),await Sr()}catch(dt){console.warn("Failed to auto-apply default git identity:",dt)}finally{Te||xt()}})(),()=>{Te=!0}},[t,Ct,r,C,xt,n,k,Sr]);const Nn=i.useMemo(()=>j?[...j.files??[]].sort((Ce,Te)=>Ce.path.localeCompare(Te.path)):[],[j]),un=i.useMemo(()=>Nn.filter(Iu),[Nn]),er=i.useMemo(()=>Nn.filter(mv),[Nn]);i.useEffect(()=>{if(!r||Nn.length===0)return;const K=[],Ce=new Set,Te=dt=>{!dt||Ce.has(dt)||(Ce.add(dt),K.push(dt))};if(un.forEach(dt=>Te(dt.path)),ye.forEach(Te),Nn.slice(0,cv).forEach(dt=>Te(dt.path)),K.length===0)return;const ze=window.setTimeout(()=>{oe(r,n,K,{maxFiles:lv})},120);return()=>{window.clearTimeout(ze)}},[Nn,r,n,oe,un,ye]);const Fr=K=>K?.pushed[0]?.remote||j?.tracking?.split("/")[0]||is.find(Ce=>Ce.name==="origin")?.name||is[0]?.name||"origin",Yr=async(K,Ce)=>{if(r){re(K);try{const Te=ze=>{const dt=`${ze.name}/`,Rt=j?.tracking?.startsWith(dt)?j.tracking.slice(dt.length):void 0;return{remote:ze.name,branch:Rt,rebase:!0}};if(K==="fetch"){if(!Ce)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:Ce.name}),le.success(e("gitView.toast.fetchedFromRemote",{name:Ce.name}))}else if(K==="pull"){if(!Ce)throw new Error("No remote available for pull");const ze=await n.gitPull(r,Te(Ce));le.success(ze.files.length===1?e("gitView.toast.pulledFilesSingle",{count:ze.files.length,name:Ce.name}):e("gitView.toast.pulledFilesPlural",{count:ze.files.length,name:Ce.name}))}else if(K==="push"){const ze=await n.gitPush(r);le.success(e("gitView.toast.pushedToUpstream",{name:Fr(ze)}))}else if(K==="sync"){if(!Ce)throw new Error("No remote available for sync");let ze=0,dt=!1;await n.gitFetch(r,{remote:Ce.name});const Rt=await n.getGitStatus(r);if((Rt.behind??0)>0){if((Rt.files?.length??0)>0){le.error(e("gitView.toast.commitOrStashBeforeSync"));return}ze=(await n.gitPull(r,Te(Ce))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),dt=!0),ze>0&&dt?le.success(ze===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:ze,name:Ce.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:ze,name:Ce.name})):ze>0?le.success(ze===1?e("gitView.toast.pulledFilesSingle",{count:ze,name:Ce.name}):e("gitView.toast.pulledFilesPlural",{count:ze,name:Ce.name})):dt?le.success(e("gitView.toast.pushedToUpstream",{name:Ce.name})):le.success(e("gitView.toast.alreadyUpToDate"))}await gs(!1),await Rs()}catch(Te){const ze=Te instanceof Error?Te.message:e("gitView.toast.syncActionFailed",{action:K==="sync"?e("gitView.sync.syncChanges"):K==="pull"?e("gitView.sync.pull"):K});le.error(ze)}finally{re(null)}}},ui=i.useCallback(async K=>{if(!r)return;const Ce=K.name.trim();if(!Ce){le.error(e("gitView.toast.remoteNameRequired"));return}if(Ce==="origin"){le.error(e("gitView.toast.cannotRemoveOriginRemote"));return}Ls(Ce);try{await n.removeRemote(r,{remote:Ce}),le.success(e("gitView.toast.removedRemote",{name:Ce})),await Promise.all([gs(!1),Kn()])}catch(Te){const ze=Te instanceof Error?Te.message:`Failed to remove ${Ce}`;le.error(ze)}finally{Ls(null)}},[r,n,Kn,gs,e]),hr=async(K={})=>{if(!r)return;if(!ve.trim()){le.error(e("gitView.toast.enterCommitMessage"));return}const Ce=un.map(ze=>ze.path).sort();if(Ce.length===0){le.error(e("gitView.toast.stageFileToCommit"));return}const Te=K.pushAfter?"commitAndPush":"commit";Je(Te);try{if(await n.createGitCommit(r,ve.trim(),{files:Ce,stageFiles:[]}),Z(r),le.success(e("gitView.toast.commitCreated")),G(""),Ht(),await gs(),K.pushAfter){const ze=j?.tracking?.split("/")[0],dt=is.find(Ar=>Ar.name===ze)??is[0];if(!dt)throw new Error(e("mobile.changes.noRemote"));re("sync");const Rt=`${dt.name}/`,Qt=j?.tracking?.startsWith(Rt)?j.tracking.slice(Rt.length):void 0;await n.gitFetch(r,{remote:dt.name});const Jt=await n.getGitStatus(r);if((Jt.behind??0)>0){if((Jt.files?.length??0)>0){le.error(e("gitView.toast.commitOrStashBeforeSync")),await gs(!1);return}await n.gitPull(r,{remote:dt.name,branch:Qt,rebase:!0})}const vs=await n.getGitStatus(r);let gr;(vs.ahead??0)>0&&(gr=await n.gitPush(r)),le.success(e("gitView.toast.pushedToUpstream",{name:Fr(gr)})),Qe(),await gs(!1)}else await gs(!1);await Rs(),ot(ze=>ze+1)}catch(ze){const dt=ze instanceof Error?ze.message:e("gitView.toast.createCommitFailed");le.error(dt)}finally{Je(null),K.pushAfter&&re(null)}},ds=i.useCallback(async()=>{if(!r)return;const K=un.map(Ce=>Ce.path).sort();if(K.length===0){le.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:K.length}),bt(!0);try{const{message:Ce}=await ug(r,K),Te=Ce.subject?.trim()??"",ze=Array.isArray(Ce.highlights)?Ce.highlights:[];if(Te){let dt=Te;if(de&&be.length>0){const Rt=dv(Te,be);if(Rt){const{code:Qt,emoji:Jt}=Rt;!Te.startsWith(Qt)&&!Te.startsWith(Jt)&&(dt=`${Qt} ${Te}`)}}G(dt)}Wt(ze),rs()}catch(Ce){console.error("[git-generation][browser] GitView generate handler failed",{message:Ce instanceof Error?Ce.message:String(Ce),error:Ce});const Te=Ce instanceof Error?Ce.message:e("gitView.toast.generateCommitMessageFailed");le.error(Te)}finally{bt(!1)}},[r,un,de,be,rs,e]),fn=K=>K.reason==="attention"?`${K.attentionReason} in progress`:K.reason==="missing"?"worktree is missing":"worktree is invalid",An=async(K,Ce)=>{if(!r||!j)return;const Te=al(A);if(Te.length>0){le.error(e("gitView.toast.cannotCreateBranch",{reason:fn(Te[0])}));return}const ze=j.current??null,dt=Ce?.name??"origin";try{await n.createBranch(r,K,ze??"HEAD"),le.success(e("gitView.toast.createdBranch",{name:K})),await n.checkoutBranch(r,K);let Rt=!1;try{await n.gitPush(r,{remote:dt,branch:K,options:["--set-upstream"]}),Rt=!0}catch(Qt){const Jt=Qt instanceof Error?Qt.message:`Unable to push new branch to ${dt}.`;le.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Jt]})})}await gs(),await Rs(),Rt&&le.success(e("gitView.toast.upstreamSet",{branch:K,remote:dt}))}catch(Rt){const Qt=Rt instanceof Error?Rt.message:e("gitView.toast.createBranchFailed");throw le.error(Qt),Rt}},Q=async(K,Ce)=>{if(!r)return;const Te=al(A);if(Te.length>0){le.error(e("gitView.toast.cannotRenameBranch",{reason:fn(Te[0])}));return}try{await n.renameBranch(r,K,Ce),le.success(e("gitView.toast.renamedBranch",{oldName:K,newName:Ce})),await gs(),await Rs()}catch(ze){const dt=ze instanceof Error?ze.message:e("gitView.toast.renameBranchFailed",{oldName:K,newName:Ce});le.error(dt)}},tt=async K=>{if(!r)return;const Ce=al(A);if(Ce.length>0){le.error(e("gitView.toast.cannotCheckout",{reason:fn(Ce[0])}));return}const Te=K.replace(/^remotes\//,"");if(j?.current!==Te)try{await n.checkoutBranch(r,Te),le.success(e("gitView.toast.checkedOut",{name:Te})),await gs(),await Rs()}catch(ze){const dt=ze instanceof Error?ze.message:e("gitView.toast.checkoutFailed",{name:Te});le.error(dt)}},pt=async K=>{if(r){Ct();try{await n.setGitIdentity(r,K.id),le.success(e("gitView.toast.appliedIdentity",{name:K.name})),await Sr()}catch(Ce){const Te=Ce instanceof Error?Ce.message:e("gitView.toast.applyIdentityFailed");le.error(Te)}finally{xt()}}},Pt=i.useMemo(()=>T?.all?T.all.filter(K=>!K.startsWith("remotes/")).sort():[],[T]),es=i.useMemo(()=>T?.all?T.all.filter(K=>K.startsWith("remotes/")).map(K=>K.replace(/^remotes\//,"")).sort():[],[T]),is=i.useMemo(()=>{if(Ks.length>0)return Ks;const K=new Set,Ce=j?.tracking?.trim();Ce&&Ce.includes("/")&&K.add(Ce.split("/")[0]);for(const Te of es){const ze=Te.indexOf("/");ze>0&&K.add(Te.slice(0,ze))}return K.size===0&&Lt&&K.add("origin"),Array.from(K).map(Te=>({name:Te,fetchUrl:Lt??"",pushUrl:Lt??""}))},[Ks,es,Lt,j?.tracking]),fs=i.useMemo(()=>{const K=new Set(is.map(dt=>dt.name)),Ce=dt=>{if(!dt)return"";let Rt=dt.trim();if(!Rt||Rt==="HEAD")return"";if(Pt.includes(Rt))return Rt;Rt.startsWith("refs/heads/")&&(Rt=Rt.slice(11)),Rt.startsWith("heads/")&&(Rt=Rt.slice(6)),Rt.startsWith("remotes/")&&(Rt=Rt.slice(8));const Qt=Rt.indexOf("/");if(Qt>0){const Jt=Rt.slice(0,Qt);if(K.has(Jt)){const vs=Rt.slice(Qt+1).trim();vs&&(Rt=vs)}}return Rt},Te=Ce(typeof B?.createdFromBranch=="string"?B.createdFromBranch:"");if(Te)return Te;const ze=Ce(typeof xe=="string"?xe:"");return ze||(Pt.includes("main")?"main":Pt.includes("master")?"master":Pt.includes("develop")?"develop":"main")},[is,Pt,xe,B?.createdFromBranch]),Es=i.useMemo(()=>is.map(Te=>Te.name).map(Te=>`${Te}/${fs}`).find(Te=>es.includes(Te))??fs,[fs,is,es]),Ys=i.useMemo(()=>{const K=new Map;h&&K.set(h.id,h);let Ce=null;if(Lt)try{let Te=Lt.trim();Te.startsWith("git@")&&(Te=`https://${Te.slice(4).replace(":","/")}`),Te.endsWith(".git")&&(Te=Te.slice(0,-4));const ze=new URL(Te);Ce=ze.hostname+ze.pathname}catch{}for(const Te of x){if(Te.authType!=="token"){K.set(Te.id,Te);continue}const ze=Te.host;if(!ze){K.set(Te.id,Te);continue}if(!ze.includes("/")){K.set(Te.id,Te);continue}Ce&&Ce===ze&&K.set(Te.id,Te)}return Array.from(K.values())},[x,h,Lt]),tr=i.useMemo(()=>{if(_?.userName&&_?.userEmail){const K=x.find(Ce=>Ce.userName===_.userName&&Ce.userEmail===_.userEmail);return K||(h&&h.userName===_.userName&&h.userEmail===_.userEmail?h:{id:"local-config",name:_.userName,userName:_.userName,userEmail:_.userEmail,sshKey:_.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return h??null},[_,x,h]),qn=un.length,Lr=R||ae!==null||Ge!==null,Bs=j?.current??null,Or=!!(B&&Ut&&Bt&&_t),xn=!!(r&&Bs),sr=!!Bs,bn=Or&&Ut&&Bt&&B?{repoRoot:Ut,sourceBranch:Bt,worktreeMetadata:B}:null,Ln=i.useMemo(()=>!xn||!r||!Bs?null:{directory:r,branch:Bs},[xn,Bs,r]);i.useEffect(()=>{if(!r||!n||!E?.all?.length||!Bs||!fs||Bs===fs){jt(null);return}let K=!1;return(async()=>{try{const Te=await n.getGitLog(r,{from:fs,to:"HEAD",maxCount:nt});if(K)return;const ze=new Set((Te?.all??[]).map(Rt=>Rt.hash).filter(Rt=>typeof Rt=="string"&&Rt.length>0));if(ze.size===0){jt(null);return}const dt=E.all.findIndex(Rt=>!ze.has(Rt.hash));if(dt===0){jt(null);return}if(dt===-1){jt({insertBeforeIndex:E.all.length,branchName:Bs,direction:"up"});return}jt({insertBeforeIndex:dt,branchName:Bs,direction:"up"})}catch{K||jt(null)}})(),()=>{K=!0}},[fs,Bs,r,n,E,nt]),i.useEffect(()=>{Hn(null)},[r]),i.useEffect(()=>{if(os!=="graph"||!r){os!=="graph"&&Hn(null);return}let K=!1;return Sn(!0),n.getGitLog(r,{maxCount:Fn,all:!0}).then(Ce=>{K||Hn(Ce)}).catch(Ce=>{console.error("Failed to fetch graph log:",Ce)}).finally(()=>{K||Sn(!1)}),()=>{K=!0}},[os,r,Fn,n]);const yn=i.useCallback((K,Ce)=>{if(!r||K.length===0)return;const Te=Array.from(new Set(K));ns(dt=>{const Rt=new Set(dt);return Te.forEach(Qt=>Rt.add(Qt)),Rt});const ze=ue(r,Te,Ce);ce.enqueue({directory:r,direction:Ce,paths:new Set(Te),rollback:()=>Se(r,ze)}),Ae()},[r,ce,ue,Se,Ae]),ar=i.useCallback(async K=>{if(r){Ze(Ce=>{const Te=new Set(Ce);return Te.add(K),Te});try{await n.revertGitFile(r,K,{scope:"working"}),le.success(e("gitView.toast.revertedFile",{path:K})),await gs(!1)}catch(Ce){const Te=Ce instanceof Error?Ce.message:e("gitView.toast.revertFailed");le.error(Te)}finally{Ze(Ce=>{const Te=new Set(Ce);return Te.delete(K),Te})}}},[r,gs,n,e]),Dn=i.useCallback(async(K,Ce,Te="all")=>{if(!r||K.length===0)return;const ze=Array.from(new Set(K));if(zt||ze.some(Jt=>St.has(Jt)))return;const dt=new Set(un.map(Jt=>Jt.path)),Rt=Te==="all"&&ze.some(Jt=>dt.has(Jt));Ce&&Ve(!0),Ze(Jt=>{const vs=new Set(Jt);return ze.forEach(gr=>vs.add(gr)),vs});const Qt=[];try{if(await Promise.all(ze.map(async Jt=>{try{await n.revertGitFile(r,Jt,{scope:Te})}catch(vs){Qt.push({path:Jt,message:vs instanceof Error?vs.message:e("gitView.toast.revertFailed")})}})),Rt&&Qt.length<ze.length&&Z(r),await gs(!1),Qt.length===0)le.success(ze.length===1?e("gitView.toast.revertedFilesSingle",{count:ze.length}):e("gitView.toast.revertedFilesPlural",{count:ze.length}));else if(Qt.length===ze.length)le.error(Qt[0]?.message||e("gitView.toast.revertFailed"));else{const Jt=ze.length-Qt.length;le.warning(Jt===1?e("gitView.toast.revertedSomeSingle",{success:Jt,failed:Qt.length}):e("gitView.toast.revertedSomePlural",{success:Jt,failed:Qt.length}))}}finally{Ze(Jt=>{const vs=new Set(Jt);return ze.forEach(gr=>vs.delete(gr)),vs}),Ce&&Ve(!1)}},[Z,r,n,zt,gs,St,un,e]),Nr=i.useCallback(async K=>{await Dn(K,!0)},[Dn]),Br=i.useCallback(async K=>{await Dn(K,!1,"working")},[Dn]),kr=i.useCallback((K,Ce)=>{if(r&&!ke){Y(r,K,Ce);return}ge(K,Ce),ke&&O(!1)},[r,ke,ge,Y,O]),Ri=i.useCallback(()=>qe(!0),[]),fi=i.useMemo(()=>{const K=[];return un.length>0&&K.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:un,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:Ce=>e("gitView.changes.unstageFileAria",{path:Ce}),onActionFile:Ce=>{yn([Ce],"unstage")},onActionAll:Ce=>{yn(Ce,"unstage")},onViewDiff:Ce=>kr(Ce,!0),onRevertFile:ar,showRevertActions:!1,accent:!0}),er.length>0&&K.push({id:"unstaged",title:e("gitView.changes.title"),entries:er,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:Ce=>e("gitView.changes.stageFileAria",{path:Ce}),onActionFile:Ce=>{yn([Ce],"stage")},onActionAll:Ce=>{yn(Ce,"stage")},onViewDiff:Ce=>kr(Ce,!1),onRevertFile:ar}),K},[ar,kr,yn,un,e,er]),Ei=i.useCallback(K=>{if(K.length===0)return;const Ce=K.map(Te=>Te.trim()).filter(Boolean);if(Ce.length===0){Ht();return}G(Te=>{const ze=Te.trim(),dt=ze.length>0?`
11
-
12
- `:"";return`${ze}${dt}${Ce.join(`
13
- `)}`.trim()}),Ht()},[Ht]),on=i.useCallback((K,Ce)=>{const Te=Ce||K;G(ze=>{const dt=ze.trimStart();return dt.startsWith(K)||Ce&&dt.startsWith(Ce)?ze:`${Te.endsWith(" ")?Te:`${Te} `}${ze}`.trimStart()}),ps(""),J(!1)},[]),pr=i.useCallback(K=>{const Ce=K instanceof Error?K.message.toLowerCase():"";return Ce.includes("uncommitted changes")||Ce.includes("local changes")||Ce.includes("your local changes would be overwritten")||Ce.includes("please commit your changes or stash them")||Ce.includes("cannot rebase: you have unstaged changes")||Ce.includes("error: cannot pull with rebase")},[]),Qs=i.useCallback((K,Ce)=>{It(Te=>[...Te,{message:K,status:Ce,timestamp:Date.now()}])},[]),wn=i.useCallback((K,Ce)=>{It(Te=>{if(Te.length===0)return Te;const ze=[...Te];return ze[ze.length-1]={...ze[ze.length-1],status:K,...Ce?{message:Ce}:{}},ze})},[]),Qr=i.useCallback(()=>{It([])},[]),co=i.useCallback(()=>{It([]),et(null)},[]),_r=i.useCallback(K=>{const Ce=K.trim(),Te=new Set(is.map(dt=>dt.name)),ze=Ce.indexOf("/");if(ze>0){const dt=Ce.slice(0,ze),Rt=Ce.slice(ze+1);if(Te.has(dt)&&Rt)return{branch:Ce,remote:dt,remoteBranch:Rt}}for(const dt of is){const Rt=`${dt.name}/${Ce}`;if(es.includes(Rt))return{branch:Rt,remote:dt.name,remoteBranch:Ce}}return{branch:Ce,remote:null,remoteBranch:null}},[is,es]),lr=i.useCallback(async K=>{if(!r)return;et("merge"),Qr();const Ce=j?.current,Te=_r(K);try{Te.remote&&Te.remoteBranch&&(Qs(`Fetching ${Te.remote}/${Te.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Te.remote,branch:Te.remoteBranch}),wn("done",`Fetched ${Te.remote}/${Te.remoteBranch}`)),Qs(`Merging ${Te.branch} into ${Ce}...`,"running");const ze=await n.merge(r,{branch:Te.branch});ze.conflict?(wn("error","Merge conflicts detected"),hs(ze.conflictFiles??[]),ws("merge"),mt(!0),Ue(r,ze.conflictFiles??[],"merge")):(wn("done",`Merged ${Te.branch} into ${Ce}`),Xt(),Qs("Refreshing repository status...","running"),await gs(),await Rs(),wn("done","Repository status updated"))}catch(ze){if(pr(ze))wn("error","Uncommitted changes detected"),qs("merge"),Os(Te.branch),Ts(!0);else{const dt=ze instanceof Error?ze.message:`Failed to merge ${Te.branch}`;wn("error",dt)}}},[r,n,j,_r,gs,Rs,pr,Ue,Xt,Qs,wn,Qr]),Cr=i.useCallback(async K=>{if(!r)return;et("rebase"),Qr();const Ce=j?.current,Te=_r(K);try{Te.remote&&Te.remoteBranch&&(Qs(`Fetching ${Te.remote}/${Te.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Te.remote,branch:Te.remoteBranch}),wn("done",`Fetched ${Te.remote}/${Te.remoteBranch}`)),Qs(`Rebasing ${Ce} onto ${Te.branch}...`,"running");const ze=await n.rebase(r,{onto:Te.branch});ze.conflict?(wn("error","Rebase conflicts detected"),hs(ze.conflictFiles??[]),ws("rebase"),mt(!0),Ue(r,ze.conflictFiles??[],"rebase")):(wn("done",`Rebased ${Ce} onto ${Te.branch}`),Xt(),Qs("Refreshing repository status...","running"),await gs(),await Rs(),wn("done","Repository status updated"))}catch(ze){if(pr(ze))wn("error","Uncommitted changes detected"),qs("rebase"),Os(Te.branch),Ts(!0);else{const dt=ze instanceof Error?ze.message:`Failed to rebase onto ${Te.branch}`;wn("error",dt)}}},[r,n,j,_r,gs,Rs,pr,Ue,Xt,Qs,wn,Qr]),mn=i.useCallback(async()=>{if(r)try{Ss==="merge"?(await n.abortMerge(r),le.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),le.success(e("gitView.toast.rebaseAborted"))),Xt(),await gs(),await Rs()}catch(K){const Ce=K instanceof Error?K.message:`Failed to abort ${Ss}`;le.error(Ce)}},[r,n,Ss,gs,Rs,Xt,e]),cr=i.useMemo(()=>j?.files?j.files.some(K=>K.index==="U"||K.working_dir==="U"||K.index==="A"&&K.working_dir==="A"||K.index==="D"&&K.working_dir==="D"):!1,[j?.files]),Mi=i.useCallback(async()=>{if(r)try{const K=!!j?.mergeInProgress?.head,Ce=!!(j?.rebaseInProgress?.headName||j?.rebaseInProgress?.onto);if(K){const Te=await n.continueMerge(r);Te.conflict?(hs(Te.conflictFiles??[]),ws("merge"),mt(!0),Ue(r,Te.conflictFiles??[],"merge"),le.error(e("gitView.toast.mergeConflictsDetected"))):(Xt(),le.success(e("gitView.toast.mergeCompleted")),await gs(),await Rs())}else if(Ce){const Te=await n.continueRebase(r);Te.conflict?(hs(Te.conflictFiles??[]),ws("rebase"),mt(!0),Ue(r,Te.conflictFiles??[],"rebase"),le.error(e("gitView.toast.rebaseConflictsDetected"))):(Xt(),le.success(e("gitView.toast.rebaseStepCompleted")),await gs(),await Rs())}}catch(K){const Ce=K instanceof Error?K.message:e("gitView.toast.continueOperationFailed");le.error(Ce)}},[r,n,j,gs,Rs,Ue,Xt,e]),Fi=i.useCallback(async()=>{if(r)try{!!j?.mergeInProgress?.head?(await n.abortMerge(r),le.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),le.success(e("gitView.toast.rebaseAborted"))),Xt(),await gs(),await Rs()}catch(K){const Ce=K instanceof Error?K.message:e("gitView.toast.abortOperationFailed");le.error(Ce)}},[r,n,j,gs,Rs,Xt,e]),Vr=i.useCallback(()=>{if(!r)return;const Ce=!!j?.mergeInProgress?.head?"merge":"rebase",Te=j?.files?.filter(ze=>ze.index==="U"||ze.working_dir==="U").map(ze=>ze.path)??[];Te.length>0&&hs(Te),ws(Ce),mt(!0)},[r,j]),mi=i.useCallback(async K=>{if(!r)return;const Ce=j?.current,Te=Ws,ze=Hs,dt=(j?.files??[]).some(Iu);try{await n.stash(r,{message:`Auto-stash before ${Te} with ${ze}`,includeUntracked:!0}),dt&&Z(r)}catch(Jt){const vs=Jt instanceof Error?Jt.message:"Failed to stash changes";le.error(vs);return}let Rt=!1,Qt=!1;try{if(Te==="merge"){const Jt=await n.merge(r,{branch:ze});Jt.conflict?(Qt=!0,hs(Jt.conflictFiles??[]),ws("merge"),mt(!0)):(Rt=!0,le.success(e("gitView.toast.mergedIntoBranch",{branch:ze,currentBranch:Ce||""})))}else{const Jt=await n.rebase(r,{onto:ze});Jt.conflict?(Qt=!0,hs(Jt.conflictFiles??[]),ws("rebase"),mt(!0)):(Rt=!0,le.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:Ce||"",branch:ze})))}if(K&&Rt)try{await n.stashPop(r),Z(r),le.success(e("gitView.toast.stashedRestored"))}catch(Jt){const vs=Jt instanceof Error?Jt.message:e("gitView.toast.restoreStashFailed");le.error(vs)}else K&&Qt&&le.info(e("gitView.toast.restoreStashManually"));await gs(),await Rs()}catch(Jt){if(K)try{await n.stashPop(r),Z(r)}catch{}throw Jt}},[Z,r,n,j,Ws,Hs,gs,Rs,e]),an=i.useCallback(K=>{gt(K),r&&(H(r,K),q(r,n,K))},[r,q,n,H]),Li=i.useCallback(K=>{Zn(K)},[]),uo=i.useCallback(()=>{Kt(null),r&&(ne(r,n),te(r,n),q(r,n,nt))},[r,ne,te,q,nt,n]),fo=i.useCallback(K=>{if(K.conflict){if(K.operation==="cherry-pick"||K.operation==="revert"){le.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:K.conflictFiles?.join(", ")??"unknown files"})}),r&&(ne(r,n),te(r,n),q(r,n,nt));return}hs(K.conflictFiles??[]),ws(K.operation),mt(!0),r&&Ue(r,K.conflictFiles??[],K.operation)}},[e,hs,ws,mt,Ue,r,ne,te,q,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(I,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):k===!1?P?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(I,{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(I,{name:"git-branch",className:"mb-3 size-6 text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.notGitRepository")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.notGitRepositoryDescription")}),D.includes("open-without-worktree-features")?s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:e("gitView.empty.worktreeFeaturesUnavailable")}):null]}):s.jsxs("div",{className:Pe("flex h-full flex-col overflow-hidden"),children:[s.jsx(Ux,{status:j,localBranches:Pt,remoteBranches:es,branchInfo:T?.branches,syncAction:ae,remotes:is,onFetch:K=>Yr("fetch",K),onSync:K=>Yr("sync",K),onRemoveRemote:ui,removingRemoteName:Mn,onCheckoutBranch:tt,onCreateBranch:An,onRenameBranch:Q,activeIdentityProfile:tr,availableIdentities:Ys,onSelectIdentity:pt,isApplyingIdentity:yt,isWorktreeMode:!!B,onOpenHistory:()=>Kt("history"),onOpenGraph:()=>Kt("graph"),onOpenStashes:Ri,actionTabItems:Fs,activeActionTab:js,onSelectActionTab:K=>rn(K)}),r&&(j?.mergeInProgress?.head||j?.rebaseInProgress?.headName||j?.rebaseInProgress?.onto)&&s.jsx(Xw,{mergeInProgress:j?.mergeInProgress,rebaseInProgress:j?.rebaseInProgress,onContinue:Mi,onAbort:Fi,onResolveWithAI:Vr,hasUnresolvedConflicts:cr,isLoading:R}),s.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:s.jsx("div",{className:"h-full min-h-0 flex flex-col",children:s.jsx("div",{className:Pe("min-w-0 min-h-0 h-full flex flex-col"),children:s.jsxs($n,{as:Ha,ref:L,outerClassName:"flex-1 min-h-0",className:Pe("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[js==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(Nn?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(Hx,{groups:fi,diffStats:j?.diffStats,revertingPaths:St,isRevertingAll:zt,onVisiblePathsChange:Le,onRevertAll:Nr,onRevertDirectory:Br,headerBackgroundClassName:"bg-background"})}),s.jsx(Gx,{stagedCount:qn,commitMessage:ve,onCommitMessageChange:G,generatedHighlights:ls,onInsertHighlights:Ei,onGenerateMessage:ds,isGeneratingMessage:vt,onCommit:()=>hr({pushAfter:!1}),onCommitAndPush:()=>hr({pushAfter:!0}),commitAction:Ge,hasPendingIndexMutation:qt,gitmojiEnabled:de,onOpenGitmojiPicker:()=>J(!0)})]}):s.jsx(Xy,{onOpenStashes:()=>qe(!0)})}):null,js==="branch"?s.jsx("div",{className:"space-y-4",children:sr?s.jsxs(s.Fragment,{children:[s.jsx(Zw,{mode:"inline",currentBranch:j?.current,localBranches:Pt,remoteBranches:es,defaultTargetBranch:Es,onMerge:lr,onRebase:Cr,disabled:Lr,isOperating:we!==null,operationLogs:ct,onOperationComplete:co}),bn?s.jsx(Qy,{repoRoot:bn.repoRoot,sourceBranch:bn.sourceBranch,worktreeMetadata:bn.worktreeMetadata,localBranches:Pt,defaultTargetBranch:Yt,refreshKey:At,onRefresh:()=>{r&&(ne(r,n),te(r,n),q(r,n,nt))}},bn.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,js==="pr"?s.jsx("div",{className:"space-y-4",children:Ln?s.jsx(Ww,{directory:Ln.directory,branch:Ln.branch,baseBranch:fs,trackingBranch:j?.tracking??void 0,remotes:Ks,remoteBranches:es,onGeneratedDescription:rs}):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($s,{open:os!==null,onOpenChange:K=>{K||Kt(null)},children:s.jsxs(Vs,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(Gs,{children:[s.jsx(Us,{children:e(os==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(ln,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(aw,{mode:os==="graph"?"graph":"history",log:os==="graph"?Ds??E:E,isLogLoading:os==="graph"&&zs||$,logMaxCount:os==="graph"?Fn:nt,onLogMaxCountChange:os==="graph"?Li:an,expandedCommitHashes:Zt,onToggleCommit:mr,commitFilesMap:Tt,loadingCommitHashes:Dt,onCopyHash:Gn,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:os==="graph"?null:Ke,onConflict:os==="graph"?fo:void 0,onActionSuccess:os==="graph"?uo:void 0})})]})}),s.jsx(Jy,{open:Oe,onOpenChange:qe,directory:r,hasUncommittedChanges:(j?.files?.length??0)>0,hasStagedChanges:un.length>0,uncommittedFileCount:j?.files?.length??0,onChanged:async K=>{r&&K?.affectsIndex&&Z(r),await gs(!1),await Rs()}}),s.jsx($s,{open:Re,onOpenChange:J,children:s.jsxs(Vs,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(Gs,{className:"px-4 pt-4",children:s.jsx(Us,{children:e("gitView.gitmoji.title")})}),s.jsxs(Va,{className:"h-[420px]",children:[s.jsx($a,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:xs,onValueChange:ps}),s.jsxs(za,{children:[s.jsx(Wa,{children:e("gitView.gitmoji.empty")}),s.jsx(oi,{children:(be.length===0?[]:be.filter(K=>{const Ce=xs.trim().toLowerCase();return Ce?K.emoji.includes(Ce)||K.code.toLowerCase().includes(Ce)||K.description.toLowerCase().includes(Ce):!0})).map(K=>s.jsxs(li,{onSelect:()=>on(K.emoji,K.code),children:[s.jsx("span",{className:"text-lg",children:K.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:K.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:K.description})]},K.code))})]})]})]})}),r&&s.jsx(Uw,{open:Gt,onOpenChange:mt,conflictFiles:ms,directory:r,operation:Ss,onAbort:mn,onClearState:Xt}),s.jsx(Jw,{open:Is,onOpenChange:Ts,operation:Ws,targetBranch:Hs,onConfirm:mi})]}):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")})})},tc=5e3,hv=(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)=>mg(hg.getState().dictionary,t,e),pv=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"},gv=async(t,e)=>{if(t.readFile)return(await t.readFile(e,{optional:!0})).content??"";const n=new URLSearchParams({path:e,optional:"true"}),r=await Cs(`/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()},$c=async(t,e)=>{try{const n=await gv(t,e);return hv(n,tc)>tc?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:pv(n)}}},zc=t=>{if(t==="too-large"){const e=tc.toLocaleString(Xi());return Nl("contextFileOpen.failure.tooLarge",{count:e})}return Nl(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},xv=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Rn=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},zm=(t,e)=>{const n=Rn(e),r=Rn(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},bv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),yv=new Set(["node_modules"]),wv=t=>yv.has(t),vv=t=>{const e=Rn(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},jv=8,Pr=new Map,Sv=t=>{const e=Pr.get(t);return e?(e.touchedAt=Date.now(),Pr.delete(t),Pr.set(t,e),e):null},kl=t=>{const e=Pr.get(t);if(e)return e.touchedAt=Date.now(),e;if(Pr.size>=jv){const r=Pr.keys().next().value;r!==void 0&&Pr.delete(r)}const n={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Pr.set(t,n),n},Nv=t=>{Pr.delete(t)},Wm=(t,e)=>s.jsx(Gr,{filePath:t,extension:e}),kv=t=>{const e=ft.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},Cv=t=>{const e=ft.c(73),{node:n,root:r,isExpanded:o,isActive:a,status:c,badge:l,permissions:d,downloadFile:u,onSelect:m,onToggle:f,onRevealPath:p,onOpenDialog:y}=t,{t:g}=kt(),b=n.type==="directory",{canRename:x,canCreateFile:h,canCreateFolder:C,canDelete:w,canReveal:v}=d,[S,k]=i.useState(!1),[j,A]=i.useState(!1);let D;e[0]!==h||e[1]!==C||e[2]!==w||e[3]!==x||e[4]!==v?(D=ge=>{!x&&!h&&!C&&!w&&!v||(ge?.preventDefault(),A(!0))},e[0]=h,e[1]=C,e[2]=w,e[3]=x,e[4]=v,e[5]=D):D=e[5];const N=D;let B;e[6]!==b||e[7]!==n||e[8]!==m||e[9]!==f?(B=()=>{b?f(n.path):m(n)},e[6]=b,e[7]=n,e[8]=m,e[9]=f,e[10]=B):B=e[10];const T=B;let E;e[11]===Symbol.for("react.memo_cache_sentinel")?(E=ge=>{ge.stopPropagation(),A(!1),k(!0)},e[11]=E):E=e[11];const _=E;let R;e[12]!==h||e[13]!==C||e[14]!==w||e[15]!==x||e[16]!==v||e[17]!==u||e[18]!==b||e[19]!==n||e[20]!==y||e[21]!==p||e[22]!==g?(R=ge=>{const{Item:O,Separator:se}=ge;return s.jsxs(s.Fragment,{children:[x&&s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),y("rename",n)},children:[s.jsx(I,{name:"edit",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.rename")]}),s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),fr(n.path).then(je=>{if(je.ok){le.success(g("sidebarFilesTree.toast.pathCopied"));return}le.error(g("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.copyPath")]}),!b&&u&&s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),u(n.path).catch(je=>{console.error("Download failed:",je),le.error(g("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(I,{name:"download",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.save")]}),v&&s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),p(n.path)},children:[s.jsx(I,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",g(Ac())]}),b&&(h||C)&&s.jsxs(s.Fragment,{children:[s.jsx(se,{}),h&&s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),y("createFile",n)},children:[s.jsx(I,{name:"file-add",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.newFile")]}),C&&s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),y("createFolder",n)},children:[s.jsx(I,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.newFolder")]})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx(se,{}),s.jsxs(O,{onClick:ee=>{ee.stopPropagation(),y("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.delete")]})]})]})},e[12]=h,e[13]=C,e[14]=w,e[15]=x,e[16]=v,e[17]=u,e[18]=b,e[19]=n,e[20]=y,e[21]=p,e[22]=g,e[23]=R):R=e[23];const $=R;let V;e[24]!==n.path||e[25]!==r?(V=ge=>{const O=zm(r,n.path);!O||O==="."||(ge.dataTransfer.setData("application/x-openchamber-file-path",O),ge.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=V):V=e[26];const z=V;let F;e[27]!==N?(F=s.jsx("div",{className:"group relative flex items-center",onContextMenu:N}),e[27]=N,e[28]=F):F=e[28];const ne=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let te;e[29]!==ne?(te=Pe("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]=te):te=e[30];let q;e[31]!==b||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(q=b?o?s.jsx(I,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(I,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Wm(n.path,n.extension),e[31]=b,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=q):q=e[35];let H;e[36]!==n.name||e[37]!==n.path?(H=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]=H):H=e[38];let X;e[39]!==b||e[40]!==c?(X=!b&&c&&s.jsx(kv,{status:c}),e[39]=b,e[40]=c,e[41]=X):X=e[41];let oe;e[42]!==l||e[43]!==b?(oe=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]=oe):oe=e[44];let ue;e[45]!==N||e[46]!==z||e[47]!==T||e[48]!==H||e[49]!==X||e[50]!==oe||e[51]!==te||e[52]!==q?(ue=s.jsxs("button",{type:"button",onClick:T,onContextMenu:N,draggable:!0,onDragStart:z,className:te,children:[q,H,X,oe]}),e[45]=N,e[46]=z,e[47]=T,e[48]=H,e[49]=X,e[50]=oe,e[51]=te,e[52]=q,e[53]=ue):ue=e[53];let Se;e[54]!==h||e[55]!==C||e[56]!==w||e[57]!==x||e[58]!==v||e[59]!==S||e[60]!==$||e[61]!==g?(Se=(x||h||C||w||v)&&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(nn,{open:S,onOpenChange:k,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:_,title:g("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":g("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(I,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:g("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(sn,{align:"end",side:"bottom",onCloseAutoFocus:()=>k(!1),children:$({Item:bs,Separator:Er})})]})}),e[54]=h,e[55]=C,e[56]=w,e[57]=x,e[58]=v,e[59]=S,e[60]=$,e[61]=g,e[62]=Se):Se=e[62];let Z;e[63]!==ue||e[64]!==Se||e[65]!==F?(Z=s.jsxs(Fc,{render:F,children:[ue,Se]}),e[63]=ue,e[64]=Se,e[65]=F,e[66]=Z):Z=e[66];let ke;e[67]!==$?(ke=s.jsx(Ec,{className:"min-w-[180px]",children:$({Item:Mc,Separator:Sm})}),e[67]=$,e[68]=ke):ke=e[68];let Y;return e[69]!==j||e[70]!==Z||e[71]!==ke?(Y=s.jsxs(Lc,{open:j,onOpenChange:A,children:[Z,ke]}),e[69]=j,e[70]=Z,e[71]=ke,e[72]=Y):Y=e[72],Y},Av=(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,Dv=i.memo(Cv,Av),Iv=()=>{const{t}=kt(),{files:e}=Xn(),n=di()??"",r=Rn(n.trim()),o=Bf(),a=_f(),c=pc(P=>P.searchFiles),l=Ee(P=>P.openContextFile),d=Ga(n),[u,m]=i.useState(""),f=qa(u,200),p=i.useRef(null),[y,g]=i.useState([]),[b,x]=i.useState(!1),[h,C]=i.useState({}),[w,v]=i.useState({}),S=i.useRef(new Set),k=i.useRef(new Set);i.useEffect(()=>{if(!r){C({}),v({}),S.current=new Set;return}const P=Sv(r);P?(C({...P.childrenByDir}),v({...P.loadErrorsByDir}),S.current=new Set(P.loadedDirs)):(C({}),v({}),S.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const P=kl(r);P.childrenByDir=h},[r,h]),i.useEffect(()=>{if(!r)return;const P=kl(r);P.loadErrorsByDir=w},[r,w]),i.useEffect(()=>{if(!r)return;const P=kl(r);P.loadedDirs=new Set(S.current)},[r,h,w]),i.useEffect(()=>()=>{if(!r)return;const P=Pr.get(r);P&&P.loadedDirs.size===0&&Object.keys(P.childrenByDir).length===0&&Nv(r)},[r]);const j=i.useMemo(()=>[],[]),A=i.useMemo(()=>[],[]),D=pn(P=>r?P.byRoot[r]?.expandedPaths??j:j),N=pn(P=>r?P.byRoot[r]?.selectedPath??null:null),B=pn(P=>P.setSelectedPath),T=pn(P=>P.addOpenPath),E=pn(P=>P.removeOpenPathsByPrefix),_=pn(P=>P.toggleExpandedPath),R=Ee(P=>r?P.contextPanelByDirectory[r]?.tabs??A:A),$=i.useMemo(()=>new Set(R.map(P=>P.mode==="file"?P.targetPath:null).filter(P=>typeof P=="string"&&P.length>0).map(P=>Rn(P))),[R]),[V,z]=i.useState(null),[F,ne]=i.useState(null),[te,q]=i.useState(""),[H,X]=i.useState(!1),oe=!!e.writeFile,ue=!!e.createDirectory,Se=!!e.rename,Z=!!e.delete,ke=!!e.revealPath,Y=i.useMemo(()=>({canRename:Se,canCreateFile:oe,canCreateFolder:ue,canDelete:Z,canReveal:ke}),[Se,oe,ue,Z,ke]),ge=i.useCallback(P=>{e.revealPath&&e.revealPath(P).catch(()=>{le.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),O=i.useCallback((P,M)=>{z(P),ne(M),q(P==="rename"&&M.name||""),X(!1)},[]),se=i.useCallback((P,M)=>{const de=M.filter(xe=>xe&&typeof xe.name=="string"&&xe.name.length>0).filter(xe=>o||!xe.name.startsWith(".")).filter(xe=>a||!wv(xe.name)).map(xe=>{const W=xe.name,be=Rn(xe.path||""),ve=be?bv(be)?be:Rn(`${P}/${be}`):Rn(`${P}/${W}`),G=xe.isDirectory?"directory":"file",ye=G==="file"&&W.includes(".")?W.split(".").pop()?.toLowerCase():void 0;return{name:W,path:ve,type:G,extension:ye}});return xv(de)},[a,o]),ee=i.useCallback(async(P,M)=>{const de=Rn(P.trim());if(!de||S.current.has(de)||k.current.has(de))return;k.current=new Set(k.current),k.current.add(de);const xe=e.listDirectory?e.listDirectory(de).then(W=>W.entries.map(be=>({name:be.name,path:be.path,isDirectory:be.isDirectory}))):Jn.listLocalDirectory(de).then(W=>W.map(be=>({name:be.name,path:be.path,isDirectory:be.isDirectory})));try{const W=await xe;if(M?.())return;const be=se(de,W);S.current=new Set(S.current),S.current.add(de),v(ve=>{if(!ve[de])return ve;const G={...ve};return delete G[de],G}),C(ve=>({...ve,[de]:be}))}catch(W){if(M?.())return;const be=W instanceof Error?W.message:String(W??"");console.error("Failed to load sidebar directory:",W),v(ve=>({...ve,[de]:be}))}finally{k.current=new Set(k.current),k.current.delete(de)}},[e,se]),je=i.useCallback(async()=>{r&&(S.current=new Set,k.current=new Set,v({}),C(P=>Object.keys(P).length===0?P:{}),await ee(r))},[ee,r]),De=i.useCallback(async P=>{if(!P){await je();return}const M=Rn(P);S.current=new Set(S.current),S.current.delete(M),k.current=new Set(k.current),k.current.delete(M),await ee(M)},[ee,je]);i.useEffect(()=>{r&&(S.current=new Set,k.current=new Set,v({}),C(P=>Object.keys(P).length===0?P:{}),ee(r))},[ee,r,o,a]),i.useEffect(()=>{if(!r||D.length===0)return;const P=D.map(xe=>Rn(xe)).filter(xe=>!!xe&&xe!==r&&xe.startsWith(`${r}/`)&&!S.current.has(xe)&&!k.current.has(xe)).sort((xe,W)=>xe.split("/").length-W.split("/").length);if(P.length===0)return;let M=!1;const de=()=>M;return(async()=>{for(let xe=0;xe<P.length&&!M;xe+=3){const W=P.slice(xe,xe+3);await Promise.all(W.map(be=>ee(be,de)))}})(),()=>{M=!0}},[D,ee,r]),i.useEffect(()=>{if(!n){g([]),x(!1);return}const P=f.trim();if(!P){g([]),x(!1);return}let M=!1;return x(!0),c(n,P,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(de=>{if(M)return;const W=de.filter(be=>a||!vv(be.path)).map(be=>({name:be.name,path:Rn(be.path),type:"file",extension:be.extension,relativePath:be.relativePath}));g(W)}).catch(()=>{M||g([])}).finally(()=>{M||x(!1)}),()=>{M=!0}},[n,f,c,o,a]);const Be=i.useMemo(()=>{const P=new Map;if(!d?.files)return P;for(const M of d.files)M.index==="A"||M.working_dir==="?"?P.set(M.path,"git-added"):M.index==="D"?P.set(M.path,"git-deleted"):(M.index==="M"||M.working_dir==="M")&&P.set(M.path,"git-modified");return P},[d]),Fe=i.useMemo(()=>{const P=new Map;if(!d?.files||!r)return P;for(const M of d.files){const de=M.index==="M"||M.working_dir==="M",xe=M.index==="A"||M.working_dir==="?";if(!de&&!xe)continue;const W=M.path.split("/");if(W.length<=1)continue;let be=r;for(let ve=0;ve<W.length-1;ve++){be=`${be}/${W[ve]}`;let G=P.get(be);G||(G={modified:0,added:0},P.set(be,G)),de&&G.modified++,xe&&G.added++}}return P},[d,r]),Me=i.useCallback(P=>{if($.has(P))return"open";if(Be.size===0)return null;const M=P.startsWith(r+"/")?P.slice(r.length+1):P;return Be.get(M)??null},[$,Be,r]),me=i.useCallback(P=>{if(Fe.size===0)return null;const M=Fe.get(P);return M&&M.modified+M.added>0?M:null},[Fe]),Ae=i.useCallback(async P=>{if(!r)return;const M=await $c(e,P.path);if(!M.ok){le.error(zc(M.reason));return}B(r,P.path),T(r,P.path),l(r,P.path)},[T,e,l,r,B]),pe=i.useCallback(async P=>{const M=Rn(P);r&&(_(r,M),S.current.has(M)||await ee(M))},[ee,r,_]),ce=i.useCallback(async P=>{if(P?.preventDefault(),!F||!V)return;X(!0);const M=()=>X(!1),de=()=>z(null);if(V==="createFile"){if(!te.trim()){le.error(t("sidebarFilesTree.toast.filenameRequired")),M();return}if(!e.writeFile){le.error(t("sidebarFilesTree.toast.writeNotSupported")),M();return}const xe=F.path,W=xe?`${xe}/`:"",be=Rn(`${W}${te.trim()}`);await e.writeFile(be,"").then(async ve=>{ve.success&&(le.success(t("sidebarFilesTree.toast.fileCreated")),await De(xe)),de()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(M);return}if(V==="createFolder"){if(!te.trim()){le.error(t("sidebarFilesTree.toast.folderNameRequired")),M();return}const xe=F.path,W=xe?`${xe}/`:"",be=Rn(`${W}${te.trim()}`);await e.createDirectory(be).then(async ve=>{ve.success&&(le.success(t("sidebarFilesTree.toast.folderCreated")),await De(xe)),de()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(M);return}if(V==="rename"){if(!te.trim()){le.error(t("sidebarFilesTree.toast.nameRequired")),M();return}if(!e.rename){le.error(t("sidebarFilesTree.toast.renameNotSupported")),M();return}const xe=F.path,W=xe.split("/").slice(0,-1).join("/"),be=W?`${W}/`:"",ve=Rn(`${be}${te.trim()}`);await e.rename(xe,ve).then(async G=>{G.success&&(le.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await De(W),r&&E(r,xe),(N===xe||N&&N.startsWith(`${xe}/`))&&B(r,null)),de()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(M);return}if(V==="delete"){if(!e.delete){le.error(t("sidebarFilesTree.toast.deleteNotSupported")),M();return}const xe=F.path,W=xe.split("/").slice(0,-1).join("/");await e.delete(xe).then(async be=>{be.success&&(le.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await De(W),r&&E(r,xe),(N===xe||N&&N.startsWith(xe+"/"))&&B(r,null)),de()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(M);return}M()},[V,F,te,e,De,E,r,N,B,t]);function he(P,M){const de=h[P]??[];return de.map((xe,W)=>{const be=xe.type==="directory",ve=be&&D.includes(xe.path),G=N===xe.path,ye=W===de.length-1;return s.jsxs("li",{className:"relative",children:[M>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),ye&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),s.jsx(Dv,{node:xe,root:r,isExpanded:ve,isActive:G,status:be?void 0:Me(xe.path),badge:be?me(xe.path):void 0,permissions:Y,downloadFile:e.downloadFile,onSelect:Ae,onToggle:pe,onRevealPath:ge,onOpenDialog:O}),be&&ve&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[w[xe.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[xe.path],children:w[xe.path]}),s.jsxs($e,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{De(xe.path)},children:[s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,he(xe.path,M+1)]})]},xe.path)})}const Ne=!!(r&&h[r]),fe=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(I,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(jn,{ref:p,value:u,onChange:P=>m(P.target.value),placeholder:t("sidebarFilesTree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),u.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(I,{name:"close",className:"h-4 w-4"})}):null]}),oe&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>O("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(I,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),ue&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>O("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(I,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{je()},className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.refreshTitle"),"aria-label":t("sidebarFilesTree.actions.refreshTitle"),children:s.jsx(I,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx($n,{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(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):y.length>0?y.map(P=>{const M=N===P.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>Ae(P),draggable:!0,onDragStart:de=>{const xe=P.relativePath||zm(r??"",P.path);!xe||xe==="."||(de.dataTransfer.setData("application/x-openchamber-file-path",xe),de.dataTransfer.effectAllowed="copy")},className:Pe("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",M?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:P.path,children:[Wm(P.path,P.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:P.relativePath??P.path})]})},P.path)}):fe?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{children:fe}),s.jsxs($e,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{je()},children:[s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):Ne&&r?he(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx($s,{open:!!V,onOpenChange:P=>!P&&z(null),children:s.jsxs(Vs,{children:[s.jsxs(Gs,{children:[s.jsxs(Us,{children:[V==="createFile"&&t("sidebarFilesTree.dialog.createFile.title"),V==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.title"),V==="rename"&&t("sidebarFilesTree.dialog.rename.title"),V==="delete"&&t("sidebarFilesTree.dialog.delete.title")]}),s.jsxs(ln,{children:[V==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:F?.path??t("sidebarFilesTree.dialog.rootFallback")}),V==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:F?.path??t("sidebarFilesTree.dialog.rootFallback")}),V==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:F?.name??""}),V==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:F?.name??""})]})]}),V!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(jn,{value:te,onChange:P=>q(P.target.value),placeholder:t(V==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:P=>{P.key==="Enter"&&ce()},autoFocus:!0})}),s.jsxs(or,{children:[s.jsx($e,{variant:"outline",onClick:()=>z(null),disabled:H,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx($e,{variant:V==="delete"?"destructive":"default",onClick:()=>{ce()},disabled:H||V!=="delete"&&!te.trim(),children:H?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):t(V==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},Pv=t=>t==="git"||t==="files"||t==="context",Tv="files",Rv=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function Ev(t,e,n,r){const o=ft.c(6),{git:a}=Xn(),c=vn(Mv),l=!!(t&&a&&e&&n==="git"&&r!=="git");let d,u;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(()=>{Rv()&&c(t,a)},1e4);return()=>window.clearInterval(m)},u=[l,t,a,c],o[0]=t,o[1]=c,o[2]=a,o[3]=l,o[4]=d,o[5]=u):(d=o[4],u=o[5]),i.useEffect(d,u)}function Mv(t){return t.ensureStatus}const Um=()=>{const t=ft.c(17),e=Ns(Lv),n=Ns(Ov),r=Xs(Bv),o=vn(_v);let a;e:{if(e){let g;t[0]!==e||t[1]!==n?(g=n.find(b=>b.id===e)??n[0]??null,t[0]=e,t[1]=n,t[2]=g):g=t[2],a=g;break e}a=n[0]??null}const c=a;let l;e:{if(!c){l=null;break e}let g;t[3]!==c.id||t[4]!==c.path?(g={id:c.id,path:c.path},t[3]=c.id,t[4]=c.path,t[5]=g):g=t[5],l=g}const d=l;let u;e:{if(!c){u=null;break e}let g;t[6]!==c.label||t[7]!==c.path||t[8]!==r?(g=c.label?.trim()||Ti(c.path,r)||c.path,t[6]=c.label,t[7]=c.path,t[8]=r,t[9]=g):g=t[9],u=g}const m=u;let f;e:{if(!c){f=!1;break e}let g;t[10]!==c.path||t[11]!==o?(g=o.get(c.path)?.isGitRepo,t[10]=c.path,t[11]=o,t[12]=g):g=t[12],f=g===!0}const p=f;let y;return t[13]!==p||t[14]!==m||t[15]!==d?(y=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]=y):y=t[16],y},Fv=()=>{const t=ft.c(57),{t:e}=kt(),n=Ee(Vv),r=Ee($v),o=Ee(zv),a=Ee(Wv),c=di();Ev(c,o,n,a);const l=a==="git"?"git":a==="context"?"context":null;let d,u;t[0]!==l||t[1]!==n||t[2]!==r?(d=()=>{l&&n===l&&r(Tv)},u=[l,n,r],t[0]=l,t[1]=n,t[2]=r,t[3]=d,t[4]=u):(d=t[3],u=t[4]),i.useEffect(d,u);let m;t[5]!==e?(m=e("layout.rightSidebar.git"),t[5]=e,t[6]=m):m=t[6];let f;t[7]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5"}),t[7]=f):f=t[7];let p;t[8]!==m?(p={id:"git",label:m,icon:f},t[8]=m,t[9]=p):p=t[9];let y;t[10]!==e?(y=e("layout.rightSidebar.files"),t[10]=e,t[11]=y):y=t[11];let g;t[12]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(I,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=g):g=t[12];let b;t[13]!==y?(b={id:"files",label:y,icon:g},t[13]=y,t[14]=b):b=t[14];let x;t[15]!==e?(x=e("layout.rightSidebar.context"),t[15]=e,t[16]=x):x=t[16];let h;t[17]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(I,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=h):h=t[17];let C;t[18]!==x?(C={id:"context",label:x,icon:h},t[18]=x,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 v=w;let S;t[24]!==l||t[25]!==v?(S=l?v.filter(oe=>oe.id!==l):v,t[24]=l,t[25]=v,t[26]=S):S=t[26];const k=S,j=o&&n==="git"&&l!=="git";let A;t[27]!==r?(A=oe=>{Pv(oe)&&r(oe)},t[27]=r,t[28]=A):A=t[28];const D=A;let N;t[29]!==D||t[30]!==n||t[31]!==k?(N=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(To,{items:k,activeId:n,onSelect:D,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=D,t[30]=n,t[31]=k,t[32]=N):N=t[32];const B=n!=="git"&&"hidden";let T;t[33]!==B?(T=Pe("h-full",B),t[33]=B,t[34]=T):T=t[34];let E;t[35]!==j?(E=s.jsx(ec,{isActive:j}),t[35]=j,t[36]=E):E=t[36];let _;t[37]!==T||t[38]!==E?(_=s.jsx("div",{className:T,children:E}),t[37]=T,t[38]=E,t[39]=_):_=t[39];const R=n!=="files"&&"hidden";let $;t[40]!==R?($=Pe("h-full",R),t[40]=R,t[41]=$):$=t[41];let V;t[42]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsx(Iv,{}),t[42]=V):V=t[42];let z;t[43]!==$?(z=s.jsx("div",{className:$,children:V}),t[43]=$,t[44]=z):z=t[44];const F=n!=="context"&&"hidden";let ne;t[45]!==F?(ne=Pe("h-full",F),t[45]=F,t[46]=ne):ne=t[46];let te;t[47]===Symbol.for("react.memo_cache_sentinel")?(te=s.jsx(Um,{}),t[47]=te):te=t[47];let q;t[48]!==ne?(q=s.jsx("div",{className:ne,children:te}),t[48]=ne,t[49]=q):q=t[49];let H;t[50]!==_||t[51]!==z||t[52]!==q?(H=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[_,z,q]}),t[50]=_,t[51]=z,t[52]=q,t[53]=H):H=t[53];let X;return t[54]!==N||t[55]!==H?(X=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[N,H]}),t[54]=N,t[55]=H,t[56]=X):X=t[56],X};function Lv(t){return t.activeProjectId}function Ov(t){return t.projects}function Bv(t){return t.homeDirectory}function _v(t){return t.directories}function Vv(t){return t.rightSidebarTab}function $v(t){return t.setRightSidebarTab}function zv(t){return t.isRightSidebarOpen}function Wv(t){return t.activeMainTab}const Uv=64,Hv=3,bi=new Map,Gv=(t,e,n=Hv)=>{const r=`${t}\0${n}\0${e}`,o=bi.get(r);if(o)return bi.delete(r),bi.set(r,o),o;const a=qv(e),c=a?$h(zh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??Tu(t):Wh(Kv(t,e))[0]?.files[0]??Tu(t);for(bi.set(r,c);bi.size>Uv;){const l=bi.keys().next().value;if(!l)break;bi.delete(l)}return c},Kv=(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 u;for(const m of c.split(/\r?\n/)){if(m.startsWith("diff --git ")||m.startsWith("@@ "))break;if(m.startsWith("\\")){if(u==="-"||u===" "){const f=l.at(-1);f&&(f.newline=!1)}if(u==="+"||u===" "){const f=d.at(-1);f&&(f.newline=!1)}continue}if(m.startsWith("-")){l.push({text:m.slice(1),newline:!0}),u="-";continue}if(m.startsWith("+")){d.push({text:m.slice(1),newline:!0}),u="+";continue}m.startsWith(" ")&&(l.push({text:m.slice(1),newline:!0}),d.push({text:m.slice(1),newline:!0}),u=" ")}return{before:Pu(l),after:Pu(d)}},Pu=t=>t.map(e=>e.text+(e.newline?`
18
- `:"")).join(""),Tu=t=>Uh({name:t,contents:""},{name:t,contents:""}),Yv=1100,Qv=15e3,Ru=500,Eu=300,Jv=1e6,Xv=3,Zv=t=>t<=6?t:t<=12?6:t<=25?4:2,e1=i.memo(()=>{const t=ft.c(4),{t:e}=kt();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}),Hm={"?":{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"}},t1=Hm.M,s1=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"},Gm=t=>{const e=s1(t);return Hm[e]??t1},n1=t=>{const{index:e,working_dir:n}=t;return e==="A"||n==="A"||e==="?"||n==="?"},Mu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Fu=t=>!!t.working_dir?.trim()||t.index==="?",r1=(t,e)=>xg(t,e),Lu=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Ou=(t,e)=>{const n=t.split(`
19
- `),r=e.split(`
20
- `),o=Math.min(n.length,r.length);for(let a=0;a<o;a+=1)if(n[a]!==r[a])return a+1;return r.length>n.length?n.length+1:n.length>r.length?Math.max(1,r.length):1},i1=t=>{if(!t)return null;const e=t.match(/@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/m);if(!e)return null;const n=Number.parseInt(e[1],10);return!Number.isFinite(n)||n<1?null:n},o1=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),a1=(t,e,n)=>o1(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:Gv(t,e),contextMode:n},Km=(t,e,n)=>{const r=t??0,o=e??0;return!r&&!o?null:s.jsxs("span",{className:Pe("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]})},l1=i.memo(t=>{const e=ft.c(43),{scope:n,workingCount:r,stagedCount:o,onScopeChange:a}=t,{t:c}=kt(),[l,d]=i.useState(!1),u=n==="staged"?o:r;let m;e[0]!==n||e[1]!==c?(m=c(n==="staged"?"diffView.scope.staged":"diffView.scope.changed"),e[0]=n,e[1]=c,e[2]=m):m=e[2];const f=m;let p;e[3]!==c?(p=c("diffView.scope.selectorAria"),e[3]=c,e[4]=p):p=e[4];let y;e[5]!==u?(y=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",u]}),e[5]=u,e[6]=y):y=e[6];let g;e[7]!==f||e[8]!==y?(g=s.jsxs("span",{className:"whitespace-nowrap",children:[f,y]}),e[7]=f,e[8]=y,e[9]=g):g=e[9];let b;e[10]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx(I,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=b):b=e[10];let x;e[11]!==p||e[12]!==g?(x=s.jsx(tn,{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":p,children:[g,b]})}),e[11]=p,e[12]=g,e[13]=x):x=e[13];let h;e[14]!==a?(h=T=>{(T==="working"||T==="staged")&&(a?.(T),d(!1))},e[14]=a,e[15]=h):h=e[15];let C;e[16]!==c?(C=c("diffView.scope.changed"),e[16]=c,e[17]=C):C=e[17];let w;e[18]!==C?(w=s.jsx("span",{children:C}),e[18]=C,e[19]=w):w=e[19];let v;e[20]!==r?(v=s.jsx("span",{className:"typography-meta text-muted-foreground",children:r}),e[20]=r,e[21]=v):v=e[21];let S;e[22]!==v||e[23]!==w?(S=s.jsx(Pd,{value:"working",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[w,v]})}),e[22]=v,e[23]=w,e[24]=S):S=e[24];let k;e[25]!==c?(k=c("diffView.scope.staged"),e[25]=c,e[26]=k):k=e[26];let j;e[27]!==k?(j=s.jsx("span",{children:k}),e[27]=k,e[28]=j):j=e[28];let A;e[29]!==o?(A=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=A):A=e[30];let D;e[31]!==j||e[32]!==A?(D=s.jsx(Pd,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[j,A]})}),e[31]=j,e[32]=A,e[33]=D):D=e[33];let N;e[34]!==n||e[35]!==S||e[36]!==D||e[37]!==h?(N=s.jsx(sn,{align:"start",className:"w-40",children:s.jsxs(bg,{value:n,onValueChange:h,children:[S,D]})}),e[34]=n,e[35]=S,e[36]=D,e[37]=h,e[38]=N):N=e[38];let B;return e[39]!==l||e[40]!==N||e[41]!==x?(B=s.jsxs(nn,{open:l,onOpenChange:d,children:[x,N]}),e[39]=l,e[40]=N,e[41]=x,e[42]=B):B=e[42],B}),c1=i.memo(t=>{const e=ft.c(11),{changedFiles:n,selectedFile:r,onSelectFile:o}=t,{t:a}=kt();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=u=>{const m=Gm(u),f=r===u.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(u.path),className:Pe("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",f?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[s.jsx(Gr,{filePath:u.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:u.path,children:u.path}),Km(u.insertions,u.deletions)]})},u.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($n,{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}),d1=i.memo(t=>{const e=ft.c(20),{filePath:n,diff:r,renderSideBySide:o}=t,{t:a}=kt(),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",u=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 f;e[1]!==r.original||e[2]!==n||e[3]!==c||e[4]!==u||e[5]!==o||e[6]!==a?(f=c&&s.jsxs("div",{className:u,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]=u,e[5]=o,e[6]=a,e[7]=f):f=e[7];let p;e[8]!==r.modified||e[9]!==n||e[10]!==l||e[11]!==c||e[12]!==u||e[13]!==o||e[14]!==a?(p=l&&s.jsxs("div",{className:u,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]=u,e[13]=o,e[14]=a,e[15]=p):p=e[15];let y;return e[16]!==d||e[17]!==f||e[18]!==p?(y=s.jsx("div",{className:"w-full overflow-auto p-4",style:m,children:s.jsxs("div",{className:d,children:[f,p]})}),e[16]=d,e[17]=f,e[18]=p,e[19]=y):y=e[19],y}),u1=i.memo(t=>{const e=ft.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=Ci(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(e1,{}),e[2]=m):m=e[2],m}if(Zi(n)){let m;return e[3]!==r||e[4]!==n||e[5]!==o?(m=s.jsx(d1,{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 u;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?(u=s.jsx("div",{className:"w-full",style:d,children:s.jsx(jm,{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]=u):u=e[15],u}),f1=i.memo(t=>{const e=ft.c(7),{filePath:n,staged:r,busyAction:o,disabled:a,onAction:c}=t,{t:l}=kt();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=ft.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)]",u=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let m;e[0]!==d||e[1]!==u?(m=Pe("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,u),e[0]=d,e[1]=u,e[2]=m):m=e[2];let f;e[3]!==l?(f=g=>{g.stopPropagation(),l()},e[3]=l,e[4]=f):f=e[4];let p;e[5]!==r||e[6]!==o?(p=o?s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(I,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=p):p=e[7];let y;return e[8]!==a||e[9]!==n||e[10]!==m||e[11]!==f||e[12]!==p?(y=s.jsx($e,{variant:"ghost",size:"sm",className:m,disabled:a,title:n,"aria-label":n,onClick:f,children:p}),e[8]=a,e[9]=n,e[10]=m,e[11]=f,e[12]=p,e[13]=y):y=e[13],y},m1=i.memo(({directory:t,file:e,layout:n,wrapLines:r,isSelected:o,isExpanded:a,isMounted:c,onSelect:l,onExpandedChange:d,registerSectionRef:u,showOpenInEditorAction:m=!1,isOpeningInEditor:f=!1,onOpenInEditor:p,staged:y=!1,loadFullFiles:g=!1})=>{const{t:b}=kt(),{git:x}=Xn(),h=vn(i.useCallback(O=>O.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),C=vn(O=>O.setDiff),w=vn(O=>O.fetchStatus),v=Ee(O=>O.setDiffFileLayout),[S,k]=i.useState(0),[j,A]=i.useState(null),[D,N]=i.useState(!1),[B,T]=i.useState(null),[E,_]=i.useState(!1),[R,$]=i.useState(null),[V,z]=i.useState(null),F=i.useRef(null),ne=i.useRef(null),te=i.useMemo(()=>Gm(e),[e]),q=n==="side-by-side",H=g?"full":"patch",X=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,oe=i.useMemo(()=>y?V:R||(h?{original:h.original,modified:h.modified,isBinary:h.isBinary,contextMode:"full"}:null),[h,R,y,V]),ue=oe?.contextMode===H,Se=i.useCallback(O=>{ne.current=O,u(e.path,O)},[e.path,u]),Z=i.useCallback(O=>{d(e.path,O)},[e.path,d]),ke=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{y?z(null):$(null),A(null),F.current=null},[X,y]),i.useEffect(()=>{if(!a||!c)return;if(!t||oe&&ue){F.current=null,N(!1);return}const O=`${t}::${e.path}::${y?"staged":"unstaged"}::${X}::${H}::${S}`;if(F.current===O)return;F.current=O,A(null),N(!0);let se=!1;const ee=g?Jv:Xv,je=Zi(e.path)?x.getGitFileDiff(t,{path:e.path,staged:y}):x.getGitDiff(t,{path:e.path,staged:y,contextLines:ee}),De=Qv,Be=new Promise((Fe,Me)=>{setTimeout(()=>Me(new Error(`Timed out after ${De}ms`)),De)});return Promise.race([je,Be]).then(Fe=>{if(!se){if("diff"in Fe){const Me=a1(e.path,Fe.diff,H);y?z(Me):$(Me)}else{const Me={original:Fe.original??"",modified:Fe.modified??"",isBinary:Fe.isBinary,contextMode:"full"};y?z(Me):C(t,e.path,Me)}N(!1)}}).catch(Fe=>{if(se)return;const Me=Fe instanceof Error?Fe.message:String(Fe);A(Me),N(!1)}),()=>{se=!0,F.current===O&&(F.current=null)}},[H,oe,ue,S,t,e.path,X,x,a,c,g,C,y]);const Y=i.useCallback(()=>{Z(!a),ke()},[Z,ke,a]),ge=i.useCallback(async O=>{if(!(!t||B!==null)){T(O);try{O==="stage"?await x.stageGitFile(t,e.path):O==="unstage"?await x.unstageGitFile(t,e.path):await x.revertGitFile(t,e.path,{scope:"working"}),k(se=>se+1),await w(t,x)}catch(se){const ee=O==="unstage"?"gitView.toast.unstageFileFailed":O==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";le.error(se instanceof Error?se.message:b(ee))}finally{T(se=>se===O?null:se)}}},[t,w,e.path,B,x,b]);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:Y,onKeyDown:O=>{O.target===O.currentTarget&&(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),Y())},className:Pe("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(I,{name:"arrow-down-s",className:"size-4"}):s.jsx(I,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:te.color},title:b(te.descriptionKey),"aria-label":b(te.descriptionKey),children:te.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(Gr,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const O=e.path.lastIndexOf("/");if(O===-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 se=e.path.slice(0,O),ee=e.path.slice(O+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:se}),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:ee})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[Km(e.insertions,e.deletions),m&&p?s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:b("diffView.actions.openFileInEditorAtChange"),onClick:O=>{O.stopPropagation(),p(e.path,oe)},disabled:f,children:f?s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(I,{name:"edit",className:"size-3.5"})}):null,s.jsx(tm,{mode:q?"side-by-side":"unified",onModeChange:O=>{const se=O==="side-by-side"?"side-by-side":"inline";v(e.path,se)},className:"opacity-70"})]})]})}),a&&s.jsxs("div",{className:"relative bg-background overflow-hidden",children:[!c&&!j?s.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,j?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:b("diffView.state.failedToLoadDiff")}),s.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:j}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>k(O=>O+1),children:b("diffView.actions.retry")})]}):null,c&&D&&!oe&&!j?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),b("diffView.state.loadingDiff")]}):null,c&&oe&&!E&&e.insertions+e.deletions>Ru?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:b("diffView.state.largeDiff",{count:e.insertions+e.deletions})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:b("diffView.state.largeDiffDescription")}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>_(!0),children:b("diffView.actions.renderAnyway")})]}):null,c&&oe&&(E||e.insertions+e.deletions<=Ru)?s.jsxs(s.Fragment,{children:[s.jsx(u1,{filePath:e.path,diff:oe,renderSideBySide:q,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(f1,{filePath:e.path,staged:y,busyAction:B,disabled:B!==null,onAction:ge})})})]}):null]})]})}),qm=({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}=kt(),{git:u,files:m}=Xn(),f=di(),{screenWidth:p,isMobile:y}=Mr(),g=kc(f??null),b=Ga(f??null),x=Cc(f??null),h=vn(_e=>_e.setActiveDirectory),C=vn(_e=>_e.ensureStatus),w=vn(_e=>_e.fetchStatus),v=vn(_e=>_e.setDiff),[S,k]=i.useState(null),[j,A]=i.useState(!1),[D,N]=i.useState(null),[B,T]=i.useState(()=>new Set),[E,_]=i.useState(()=>new Set),[R,$]=i.useState(!1),[V,z]=i.useState(0),[F,ne]=i.useState(!1),[te,q]=i.useState(!1),H=Ee(_e=>_e.pendingDiffFile),X=Ee(_e=>_e.pendingDiffStaged),oe=Ee(_e=>_e.setPendingDiffFile),ue=Ee(_e=>_e.diffLayoutPreference),Se=Ee(_e=>_e.diffFileLayout),Z=Ee(_e=>_e.setDiffFileLayout),ke=Ee(_e=>_e.diffWrapLines),Y=Ee(_e=>_e.setDiffWrapLines),ge=Ee(_e=>_e.openContextFileAtLine),O=ut(_e=>_e.currentSessionId),se=ke,ee=o==="staged"?!0:o==="working"?!1:null,je=ee??j,De=y||p<=768,Be=!!O&&!De&&!Kr(),Fe=!t&&!De&&p>=1024,Me=i.useRef(null),me=i.useRef(new Map),Ae=i.useRef(null),pe=i.useRef(null),ce=i.useRef(!1),he=i.useRef(null),Ne=i.useRef(null),fe=i.useCallback(()=>{Ae.current=null,ce.current=!1,N(null),pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null)},[]),P=i.useCallback(_e=>{T(Qe=>{if(Qe.has(_e))return Qe;const st=new Set(Qe);return st.add(_e),st})},[]),M=i.useMemo(()=>{if(!b?.files)return[];const _e=b.diffStats??{},Qe=o==="staged"?Mu:o==="working"?Fu:()=>!0;return b.files.filter(Qe).map(st=>({...st,insertions:_e[st.path]?.insertions??0,deletions:_e[st.path]?.deletions??0,isNew:n1(st)})).sort((st,wt)=>st.path.localeCompare(wt.path))},[o,b]),de=i.useMemo(()=>b?.files?b.files.filter(Fu).length:0,[b]),xe=i.useMemo(()=>b?.files?b.files.filter(Mu).length:0,[b]),W=i.useMemo(()=>M.map(_e=>_e.path).join("\0"),[M]);i.useEffect(()=>{const _e=W?W.split("\0"):[],Qe=new Set(_e),st=`${f??""}:${o}:${e?"collapsed":"default"}`,wt=Ne.current!==st;Ne.current=st,T(Ct=>{if(wt){const Ze=e?0:Zv(_e.length);return new Set(_e.slice(0,Ze))}let xt=!1;const St=new Set;for(const Ze of Ct){if(!Qe.has(Ze)){xt=!0;continue}St.add(Ze)}return xt?St:Ct}),_(Ct=>{if(wt)return new Set;let xt=!1;const St=new Set;for(const Ze of Ct){if(!Qe.has(Ze)){xt=!0;continue}St.add(Ze)}return xt?St:Ct})},[W,o,f,e]);const be=i.useCallback(()=>{he.current=null;const _e=Me.current;if(!_e)return;const Qe=_e.getBoundingClientRect(),st=Qe.top-Eu,wt=Qe.bottom+Eu,Ct={};for(const[xt,St]of me.current){if(!St||!B.has(xt))continue;const Ze=St.getBoundingClientRect();Ze.bottom<st||Ze.top>wt||(Ct[xt]=!0)}_(xt=>{let St=!1;const Ze=new Set(xt);for(const Ot of Object.keys(Ct))Ze.has(Ot)||(Ze.add(Ot),St=!0);return St?Ze:xt})},[B]),ve=i.useCallback(()=>{typeof window>"u"||he.current===null&&(he.current=window.requestAnimationFrame(be))},[be]);i.useEffect(()=>{const _e=Me.current;if(_e)return ve(),_e.addEventListener("scroll",ve,{passive:!0}),window.addEventListener("resize",ve),()=>{_e.removeEventListener("scroll",ve),window.removeEventListener("resize",ve),he.current!==null&&(window.cancelAnimationFrame(he.current),he.current=null)}},[M,B,ve]);const G=i.useCallback(_e=>{const Qe=Se[_e.path];if(Qe)return Qe;if(ue==="inline")return"inline";if(ue==="side-by-side")return"side-by-side";const st=p<Yv;return _e.isNew||st?"inline":"side-by-side"},[Se,ue,p]),ye=i.useMemo(()=>M.length===0?null:M.every(_e=>G(_e)==="side-by-side")?"side-by-side":"inline",[M,G]);i.useEffect(()=>{f&&(h(f),C(f,u))},[f,h,C,u]),i.useEffect(()=>{if(f)return Tr.onGitRefreshHint(_e=>{Lu(_e.directory)===Lu(f)&&w(f,u)})},[f,w,u]),i.useEffect(()=>{o==="all"&&H&&(k(H),A(X),oe(null),ce.current=!0,Ae.current=H,P(H),z(_e=>_e+1))},[o,P,H,X,oe]),i.useEffect(()=>{if(o==="all")return;const _e=c?.trim();_e&&(k(_e),A(o==="staged"),ce.current=!0,Ae.current=_e,P(_e),z(Qe=>Qe+1))},[o,P,c]),i.useEffect(()=>{if(!S)return;M.some(Qe=>Qe.path===S)||(k(null),A(!1))},[M,S]);const Le=i.useCallback((_e,Qe)=>{const st=me.current;Qe?st.set(_e,Qe):st.delete(_e),ve()},[ve]),Re=i.useCallback((_e,Qe)=>{fe(),T(st=>{const wt=st.has(_e);if(Qe===wt)return st;const Ct=new Set(st);return Qe?Ct.add(_e):Ct.delete(_e),Ct}),Qe||_(st=>{if(!st.has(_e))return st;const wt=new Set(st);return wt.delete(_e),wt}),ve()},[fe,ve]),J=i.useCallback(()=>{fe(),T(_e=>_e.size>0?new Set:new Set(M.map(Qe=>Qe.path))),_(new Set),ve()},[fe,M,ve]),L=i.useCallback(async _e=>{if(!O)return;const Qe=ut.getState().getDirectoryForSession(O)||f||"";if(!Qe){le.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}q(!0);try{await pg({originalSessionID:O,directory:Qe,providerID:_e.providerID,modelID:_e.modelID,agent:_e.agent||void 0,variant:_e.variant||void 0,generateHandoff:_e.generateHandoff,returnAfterHandoffRequest:_e.generateHandoff,autoReview:_e.autoReview}),ne(!1)}catch(st){console.error("[review-flow] failed to start review flow",st),le.error(st instanceof Error?st.message:d("diffView.reviewDialog.toast.startFailed"))}finally{q(!1)}},[O,f,d]),ae=i.useCallback(_e=>{const Qe=me.current.get(_e),st=Me.current;if(!Qe||!st)return!1;const wt=st.getBoundingClientRect(),xt=Qe.getBoundingClientRect().top-wt.top,St=Math.max(0,st.scrollHeight-st.clientHeight);return st.scrollTop=Math.min(St,Math.max(0,st.scrollTop+xt)),!0},[]);i.useEffect(()=>{if(!Ae.current)return;let Qe=0;const st=20;let wt=!1;const Ct=()=>{wt||(wt=!0,Ae.current=null,ce.current=!1,N(null),pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null))},xt=()=>{if(wt){pe.current=null;return}const St=Ae.current;if(!St){Ct(),pe.current=null;return}if(!ae(St)){Qe+=1,Qe<st?pe.current=window.requestAnimationFrame(xt):(Ct(),pe.current=null);return}n&&ce.current&&N(St),Ct()};return pe.current=window.requestAnimationFrame(xt),()=>{wt=!0,pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null)}},[n,V,ae]);const re=i.useCallback(_e=>{},[]),Oe=i.useCallback(_e=>{fe(),k(_e),A(!1),ce.current=!0,Ae.current=_e,P(_e),z(Qe=>Qe+1),ae(_e)},[fe,P,ae]),qe=i.useCallback(_e=>{const Qe=_e==="side-by-side"?"side-by-side":"inline";M.forEach(st=>{Z(st.path,Qe)})},[M,Z]),[Ge,Je]=i.useState(null),nt=i.useCallback(async(_e,Qe)=>{if(!(!f||!_e)){Je(_e);try{let st=null;if(Qe&&!Qe.isBinary&&!Zi(_e)&&(st=Ou(Qe.original,Qe.modified)),st===null)try{const Ze=await u.getGitDiff(f,{path:_e,staged:je,contextLines:3});st=i1(Ze.diff)}catch{st=null}let wt=Qe;if(st===null||!wt){const Ze=await u.getGitFileDiff(f,{path:_e,staged:je});wt={original:Ze.original??"",modified:Ze.modified??"",isBinary:Ze.isBinary},je||v(f,_e,wt)}const Ct=st??(wt.isBinary||Zi(_e)?1:Ou(wt.original,wt.modified)),xt=r1(f,_e),St=await $c(m,xt);if(!St.ok){le.error(zc(St.reason));return}ge(f,xt,Ct,1)}finally{Je(st=>st===_e?null:st)}}},[je,f,m,u,ge,v]),gt=()=>{if(!f)return null;const _e=Qe=>ee!==null?ee:j&&Qe===S;return s.jsxs("div",{className:Pe("flex min-w-0 flex-1 min-h-0 h-full",l?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[Fe&&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:M.length})]}),s.jsx(c1,{changedFiles:M,selectedFile:null,onSelectFile:Oe})]}),s.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:s.jsx($n,{ref:Me,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:M.map(Qe=>s.jsx(m1,{directory:f,file:Qe,layout:G(Qe),wrapLines:se,isSelected:!1,isExpanded:B.has(Qe.path),isMounted:E.has(Qe.path)||Qe.path===D,onSelect:re,onExpandedChange:Re,registerSectionRef:Le,showOpenInEditorAction:r,isOpeningInEditor:Ge===Qe.path,onOpenInEditor:(st,wt)=>{nt(st,wt)},staged:_e(Qe.path),loadFullFiles:R},Qe.path))})})})]})},yt=()=>f?x&&!b?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),d("diffView.state.loadingRepositoryStatus")]}):g===!1?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.notGitRepository")}):M.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.cleanWorkingTree")}):gt():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:[!y&&(o==="working"||o==="staged"?s.jsx(l1,{scope:o,workingCount:de,stagedCount:xe,onScopeChange:a}):s.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:x&&!b?d("diffView.state.loadingChanges"):M.length===1?d("diffView.summary.changedFilesSingle",{count:M.length}):d("diffView.summary.changedFilesPlural",{count:M.length})})})),M.length>0&&s.jsxs($e,{variant:"ghost",size:"sm",onClick:J,className:Pe("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:B.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll"),children:[s.jsx(I,{name:"expand-up-down",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:B.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll")})]}),M.length>0&&Be&&s.jsxs($e,{variant:"default",size:"sm",onClick:()=>ne(!0),disabled:te,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[te?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),M.length>0&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>$(_e=>!_e),"aria-pressed":R,"aria-label":d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:Pe("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",R&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(I,{name:"file-download",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),M.length>0&&s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Y(!ke),className:Pe("h-5 w-5 p-0 transition-opacity",se?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(se?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(I,{name:"text-wrap",className:"size-4"})}),ye&&s.jsx(tm,{mode:ye==="side-by-side"?"side-by-side":"unified",onModeChange:qe})]}),s.jsx(gg,{open:F,onOpenChange:ne,projectDirectory:f??null,submitting:te,onConfirm:L}),yt()]})},h1=(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)},Bu=(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:Hh.cursor(a),effects:ni.scrollIntoView(a,{y:"center"})})};function p1({open:t,onOpenChange:e,view:n,variant:r="overlay"}){const{t:o}=kt(),[a,c]=i.useState(""),l=i.useRef(null),d=i.useRef(!1),u=i.useRef(null),m=i.useRef(null),f=i.useMemo(()=>h1(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=Bu(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(f===null){const{selection:x}=l.current;n.dispatch({selection:x,effects:ni.scrollIntoView(x.main.from,{y:"center"})});return}_u(n,f,l.current.character)}},[f,t,n]);const p=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:x}=l.current;n.dispatch({selection:x,effects:ni.scrollIntoView(x.main.from,{y:"center"})})},[n]),y=i.useCallback(x=>{x||p(),e(x)},[e,p]),g=i.useCallback(()=>{!n||f===null||!l.current||(d.current=!0,_u(n,f,l.current.character),e(!1),n.focus())},[f,e,n]);i.useEffect(()=>{if(!t)return;const x=C=>{const w=u.current,v=C.target;!w||!(v instanceof Node)||w.contains(v)||y(!1)},h=C=>{C.key==="Escape"&&(C.preventDefault(),y(!1))};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",h,!0),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",h,!0)}},[y,t,r]);const b=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(f===null){const x=l.current??Bu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:x.lineNumber,max:n.state.doc.lines})}return o("goToLineDialog.helper.goToLine",{line:f})},[f,o,n]);return r==="inline"?t?s.jsxs("div",{ref:u,className:"ml-1 flex h-6 items-center gap-1",children:[s.jsx(jn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:x=>c(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g())},placeholder:o("goToLineDialog.field.linePlaceholderShort"),className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),s.jsx($e,{variant:"outline",size:"xs",onClick:g,disabled:!n||f===null,className:"h-6 px-2",children:o("goToLineDialog.actions.go")})]}):null:s.jsx("div",{ref:u,className:Pe("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(jn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:x=>c(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g())},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 g1='<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 Vu(){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 x1=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),[u,m]=i.useState(Vu),f=i.useRef(e),p=i.useRef(e);p.current!==e&&(p.current=e,f.current=e,c.current=e);const y=i.useRef(u);y.current!==u&&(y.current=u,f.current=c.current);const g=i.useRef(null);i.useEffect(()=>{const h=()=>m(Vu());h();const C=new MutationObserver(h);return C.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>C.disconnect()},[]),i.useEffect(()=>{const h=setTimeout(()=>{g.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]),x=i.useCallback(h=>{c.current=h.xml,o?.(h.xml)},[o]);return s.jsx("div",{ref:g,className:Pe("h-full w-full",r),children:s.jsx(Gh,{ref:l,xml:f.current||g1,autosave:!0,urlParameters:{ui:n?"simple":u?"dark":"kennedy",spin:!0,libraries:!n,chrome:n,nav:n,layers:n,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:x},u?"dark":"light")})}),b1=t=>{const e=Js(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},y1=t=>{const e=ft.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 f;return e[3]!==r?(f=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:m}),e[3]=r,e[4]=f):f=e[4],f}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=Pe("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 u;return e[6]!==l?(u=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=u):u=e[7],u},w1=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Js=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},v1=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Wi=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,Ra=(t,e)=>{const n=Js(e),r=Js(t);if(!n||!r)return!1;const o=Wi(n),a=Wi(r);return a===o||a.startsWith(`${o}/`)},$u=(t,e)=>{const n=Js(e),r=Js(t);if(!Ra(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},sc=(t,e)=>{if(!e)return"";const n=Js(e);if(!t||!Ra(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},j1=new Set(["node_modules"]),S1=t=>{const e=ft.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},zu=t=>{const e=ft.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,y=o.current;if(!p||!y)return;const g=()=>{c(y.scrollWidth>p.clientWidth+1)};g();const b=new ResizeObserver(g);return b.observe(p),b.observe(y),()=>{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 u;e[3]!==n?(u=s.jsx("span",{ref:o,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:n}),e[3]=n,e[4]=u):u=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 f;return e[8]!==u||e[9]!==m?(f=s.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[u,m]}),e[8]=u,e[9]=m,e[10]=f):f=e[10],f},N1=t=>j1.has(t),k1=t=>{const e=Js(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},C1=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},Wu=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")},go=2e5,Ym="openchamber:files:auto-save-enabled",A1=t=>{let e=0,n=0;for(let r=0;r<t.length;r+=1)t.charCodeAt(r)===10&&(r>0&&t.charCodeAt(r-1)===13?e+=1:n+=1);return e>n?`\r
21
- `:`
22
- `},Qm=t=>t.replace(/\r\n/g,`
23
- `).replace(/\r/g,`
24
- `),D1=(t,e)=>{const n=Qm(t);return e===`\r
25
- `?n.replace(/\n/g,`\r
26
- `):n},I1=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(Ym)!=="false"}catch{return!0}},Jm=(t,e)=>s.jsx(Gr,{filePath:t,extension:e}),Uu=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},P1=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="json"||e==="jsonc"||e==="json5"||e==="geojson"},Xo=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="html"||e==="htm"},T1=t=>{const e=ft.c(83),{node:n,root:r,isExpanded:o,isActive:a,isMobile:c,alwaysShowActions:l,status:d,badge:u,permissions:m,downloadFile:f,contextMenuPath:p,setContextMenuPath:y,rightClickMenuPath:g,setRightClickMenuPath:b,onSelect:x,onToggle:h,onRevealPath:C,onOpenDialog:w}=t,{t:v}=kt(),S=n.type==="directory",{canRename:k,canCreateFile:j,canCreateFolder:A,canDelete:D,canReveal:N}=m;let B;e[0]!==j||e[1]!==A||e[2]!==D||e[3]!==k||e[4]!==N||e[5]!==n.path||e[6]!==b?(B=je=>{!k&&!j&&!A&&!D&&!N||(je?.preventDefault(),b(n.path))},e[0]=j,e[1]=A,e[2]=D,e[3]=k,e[4]=N,e[5]=n.path,e[6]=b,e[7]=B):B=e[7];const T=B;let E;e[8]!==S||e[9]!==n||e[10]!==x||e[11]!==h?(E=()=>{S?h(n.path):x(n)},e[8]=S,e[9]=n,e[10]=x,e[11]=h,e[12]=E):E=e[12];const _=E;let R;e[13]!==n.path||e[14]!==y||e[15]!==b?(R=je=>{je.stopPropagation(),b(null),y(n.path)},e[13]=n.path,e[14]=y,e[15]=b,e[16]=R):R=e[16];const $=R;let V;e[17]!==j||e[18]!==A||e[19]!==D||e[20]!==k||e[21]!==N||e[22]!==f||e[23]!==S||e[24]!==n||e[25]!==w||e[26]!==C||e[27]!==r||e[28]!==v?(V=je=>{const{Item:De,Separator:Be}=je;return s.jsxs(s.Fragment,{children:[k&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("rename",n)},children:[s.jsx(I,{name:"edit",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.rename")]}),s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),fr(n.path).then(Me=>{if(Me.ok){le.success(v("sidebarFilesTree.toast.pathCopied"));return}le.error(v("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.copyPath")]}),s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation();const Me=sc(r,n.path)||n.path;fr(Me).then(me=>{if(me.ok){le.success(v("filesView.toast.relativePathCopied"));return}le.error(v("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy-2",className:"mr-2 size-4"})," ",v("filesView.tree.menu.copyRelativePath")]}),!S&&f&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),f(n.path).catch(Me=>{console.error("Download failed:",Me),le.error(v("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(I,{name:"download",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.save")]}),N&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),C(n.path)},children:[s.jsx(I,{name:"folder-received",className:"mr-2 size-4"})," ",v(Ac())]}),S&&(j||A)&&s.jsxs(s.Fragment,{children:[s.jsx(Be,{}),j&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("createFile",n)},children:[s.jsx(I,{name:"file-add",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.newFile")]}),A&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("createFolder",n)},children:[s.jsx(I,{name:"folder-add",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.newFolder")]})]}),D&&s.jsxs(s.Fragment,{children:[s.jsx(Be,{}),s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"delete-bin",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.delete")]})]})]})},e[17]=j,e[18]=A,e[19]=D,e[20]=k,e[21]=N,e[22]=f,e[23]=S,e[24]=n,e[25]=w,e[26]=C,e[27]=r,e[28]=v,e[29]=V):V=e[29];const z=V,F=g===n.path;let ne;e[30]!==n.path||e[31]!==b?(ne=je=>b(je?n.path:null),e[30]=n.path,e[31]=b,e[32]=ne):ne=e[32];const te=c?void 0:T;let q;e[33]!==te?(q=s.jsx("div",{className:"group relative flex items-center",onContextMenu:te}),e[33]=te,e[34]=q):q=e[34];const H=c?void 0:T,X=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let oe;e[35]!==X?(oe=Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",X),e[35]=X,e[36]=oe):oe=e[36];let ue;e[37]!==S||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(ue=S?o?s.jsx(I,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(I,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):Jm(n.path,n.extension),e[37]=S,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=ue):ue=e[41];let Se;e[42]!==n.name||e[43]!==n.path?(Se=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]=Se):Se=e[44];let Z;e[45]!==S||e[46]!==d?(Z=!S&&d&&s.jsx(S1,{status:d}),e[45]=S,e[46]=d,e[47]=Z):Z=e[47];let ke;e[48]!==u||e[49]!==S?(ke=S&&u&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[u.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",u.modified]}),u.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",u.added]})]}),e[48]=u,e[49]=S,e[50]=ke):ke=e[50];let Y;e[51]!==_||e[52]!==oe||e[53]!==ue||e[54]!==Se||e[55]!==Z||e[56]!==ke||e[57]!==H?(Y=s.jsxs("button",{type:"button",onClick:_,onContextMenu:H,className:oe,children:[ue,Se,Z,ke]}),e[51]=_,e[52]=oe,e[53]=ue,e[54]=Se,e[55]=Z,e[56]=ke,e[57]=H,e[58]=Y):Y=e[58];let ge;e[59]!==l||e[60]!==j||e[61]!==A||e[62]!==D||e[63]!==k||e[64]!==N||e[65]!==p||e[66]!==$||e[67]!==c||e[68]!==n.path||e[69]!==z||e[70]!==y?(ge=(k||j||A||D||N)&&s.jsx("div",{className:Pe("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(nn,{open:p===n.path,onOpenChange:je=>y(je?n.path:null),children:[s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"icon",className:"size-6",onClick:$,children:s.jsx(I,{name:"more-2-fill",className:"size-4"})})}),s.jsx(sn,{align:"end",side:"bottom",onCloseAutoFocus:()=>y(null),children:z({Item:bs,Separator:Er})})]})}),e[59]=l,e[60]=j,e[61]=A,e[62]=D,e[63]=k,e[64]=N,e[65]=p,e[66]=$,e[67]=c,e[68]=n.path,e[69]=z,e[70]=y,e[71]=ge):ge=e[71];let O;e[72]!==Y||e[73]!==ge||e[74]!==q?(O=s.jsxs(Fc,{render:q,children:[Y,ge]}),e[72]=Y,e[73]=ge,e[74]=q,e[75]=O):O=e[75];let se;e[76]!==z?(se=s.jsx(Ec,{className:"min-w-[180px]",children:z({Item:Mc,Separator:Sm})}),e[76]=z,e[77]=se):se=e[77];let ee;return e[78]!==O||e[79]!==se||e[80]!==F||e[81]!==ne?(ee=s.jsxs(Lc,{open:F,onOpenChange:ne,children:[O,se]}),e[78]=O,e[79]=se,e[80]=F,e[81]=ne,e[82]=ee):ee=e[82],ee},R1=t=>{const e=ft.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:u}=t,{t:m}=kt(),f=!!n;let p;e[0]!==d?(p=F=>!F&&d(),e[0]=d,e[1]=p):p=e[1];let y;e[2]!==n||e[3]!==m?(y=n==="createFile"&&m("filesView.dialog.createFile.title"),e[2]=n,e[3]=m,e[4]=y):y=e[4];let g;e[5]!==n||e[6]!==m?(g=n==="createFolder"&&m("filesView.dialog.createFolder.title"),e[5]=n,e[6]=m,e[7]=g):g=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 x;e[11]!==n||e[12]!==m?(x=n==="delete"&&m("filesView.dialog.delete.title"),e[11]=n,e[12]=m,e[13]=x):x=e[13];let h;e[14]!==y||e[15]!==g||e[16]!==b||e[17]!==x?(h=s.jsxs(Us,{children:[y,g,b,x]}),e[14]=y,e[15]=g,e[16]=b,e[17]=x,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 v;e[27]!==n||e[28]!==r?.name||e[29]!==m?(v=n==="rename"&&m("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=m,e[30]=v):v=e[30];let S;e[31]!==n||e[32]!==r?.name||e[33]!==m?(S=n==="delete"&&m("filesView.dialog.delete.description",{name:r?.name??""}),e[31]=n,e[32]=r?.name,e[33]=m,e[34]=S):S=e[34];let k;e[35]!==v||e[36]!==S||e[37]!==C||e[38]!==w?(k=s.jsxs(ln,{children:[C,w,v,S]}),e[35]=v,e[36]=S,e[37]=C,e[38]=w,e[39]=k):k=e[39];let j;e[40]!==k||e[41]!==h?(j=s.jsxs(Gs,{children:[h,k]}),e[40]=k,e[41]=h,e[42]=j):j=e[42];let A;e[43]!==n||e[44]!==o||e[45]!==u||e[46]!==a||e[47]!==l||e[48]!==m?(A=n!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(jn,{value:o,onChange:F=>a(F.target.value),placeholder:m(n==="rename"?"filesView.dialog.rename.placeholder":"filesView.dialog.namePlaceholder"),onKeyDown:F=>{F.key==="Enter"&&l()},ref:u})}),e[43]=n,e[44]=o,e[45]=u,e[46]=a,e[47]=l,e[48]=m,e[49]=A):A=e[49];let D;e[50]!==m?(D=m("filesView.dialog.cancel"),e[50]=m,e[51]=D):D=e[51];let N;e[52]!==c||e[53]!==d||e[54]!==D?(N=s.jsx($e,{variant:"outline",onClick:d,disabled:c,children:D}),e[52]=c,e[53]=d,e[54]=D,e[55]=N):N=e[55];const B=n==="delete"?"destructive":"default";let T;e[56]!==l?(T=()=>{l()},e[56]=l,e[57]=T):T=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 _;e[62]!==n||e[63]!==c||e[64]!==m?(_=c?s.jsx(I,{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]=_):_=e[65];let R;e[66]!==B||e[67]!==T||e[68]!==E||e[69]!==_?(R=s.jsx($e,{variant:B,onClick:T,disabled:E,children:_}),e[66]=B,e[67]=T,e[68]=E,e[69]=_,e[70]=R):R=e[70];let $;e[71]!==N||e[72]!==R?($=s.jsxs(or,{children:[N,R]}),e[71]=N,e[72]=R,e[73]=$):$=e[73];let V;e[74]!==u||e[75]!==j||e[76]!==A||e[77]!==$?(V=s.jsxs(Vs,{initialFocus:u,children:[j,A,$]}),e[74]=u,e[75]=j,e[76]=A,e[77]=$,e[78]=V):V=e[78];let z;return e[79]!==f||e[80]!==p||e[81]!==V?(z=s.jsx($s,{open:f,onOpenChange:p,children:V}),e[79]=f,e[80]=p,e[81]=V,e[82]=z):z=e[82],z},Al=(t,e,n)=>{const r=ft.c(8),[o,a]=i.useState(""),[c,l]=i.useState(0);let d,u;r[0]!==t||r[1]!==n||r[2]!==e?(d=()=>{if(!t){a("");return}let f=!1;a("");const p=Ur(),y=xp(p);gc(p).then(b=>{f||!b||(a(t),e(null))}).catch(b=>{f||(e(b instanceof Error?b.message:n),a(t))});const g=bp(()=>{f||(a(t),l(E1),e(null))});return()=>{f=!0,y(),g()}},u=[t,e,n],r[0]=t,r[1]=n,r[2]=e,r[3]=d,r[4]=u):(d=r[3],u=r[4]),i.useEffect(d,u);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},Xm=({mode:t="full"})=>{const{t:e}=kt(),{files:n,runtime:r}=Xn(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=qr(),{isMobile:d,isTablet:u,screenWidth:m}=Mr(),f=d||u,p=Bf(),y=_f(),g=di()??"",b=Js(g.trim()),x=d||t!=="editor-only",h=t==="editor-only"&&!d,C=pc(U=>U.searchFiles),w=Ga(g),[v,S]=i.useState(""),k=qa(v,200),j=i.useRef(null),[A,D]=i.useState(!1),[N,B]=i.useState(!0),[T,E]=i.useState(!1),[_,R]=i.useState(!1),[$,V]=i.useState(!1),z=i.useRef(null),F=i.useRef(0),ne=i.useCallback(U=>{F.current=Math.max(0,F.current+(U?1:-1))},[]),te=i.useCallback(U=>U instanceof Element?U.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!$)return;const U=Ie=>{F.current>0||te(Ie.target)||z.current&&!z.current.contains(Ie.target)&&V(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[te,$]);const[q,H]=i.useState("edit"),[X,oe]=i.useState("edit"),[ue,Se]=i.useState("tree"),[Z,ke]=i.useState("edit"),[Y,ge]=i.useState("preview"),[O,se]=i.useState(0),ee=i.useRef({}),je=i.useRef({}),De=i.useRef({}),Be=i.useRef({}),Fe=i.useMemo(()=>a.find(U=>U.metadata.id===c)??Td(!1),[a,c]),Me=i.useMemo(()=>a.find(U=>U.metadata.id===l)??Td(!0),[a,l]);i.useEffect(()=>{Rd(Fe),Rd(Me)},[Fe,Me]);const me=i.useMemo(()=>[],[]),Ae=pn(U=>b?U.byRoot[b]?.openPaths??me:me),pe=pn(U=>b?U.byRoot[b]?.selectedPath??null:null),ce=pn(U=>b?U.byRoot[b]?.expandedPaths??me:me),he=pn(U=>U.addOpenPath),Ne=pn(U=>U.removeOpenPath),fe=pn(U=>U.removeOpenPathsByPrefix),P=pn(U=>U.removeExpandedPathsByPrefix),M=pn(U=>U.setSelectedPath),de=pn(U=>U.toggleExpandedPath),xe=pn(U=>U.expandPaths),W=i.useCallback(U=>{const Ie=Js(U),We=Ie.split("/"),Ye=We[We.length-1]||Ie,lt=Ye.includes(".")?Ye.split(".").pop()?.toLowerCase():void 0;return{name:Ye,path:Ie,type:"file",extension:lt}},[]),be=i.useMemo(()=>Ae.map(W),[Ae,W]),ve=i.useMemo(()=>{if(pe){const U=Wi(pe);if(Ae.some(Ie=>Wi(Ie)===U))return pe}return Ae[0]??null},[Ae,pe]),G=i.useMemo(()=>ve?W(ve):null,[ve,W]),ye=G?.path??"";i.useEffect(()=>{if(!b||!pe)return;const U=Wi(pe);Ae.some(We=>Wi(We)===U)||M(b,Ae[0]??null)},[Ae,b,pe,M]);const Le=!!(b&&ye&&!Ra(ye,b)),Re=Le?Ed(ye):void 0,J=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&Le,outsideFileGrant:Re,directory:b||void 0}),[t,Le,Re,b]),L=i.useRef(null),[ae,re]=i.useState({left:!1,right:!1}),Oe=i.useCallback(()=>{const U=L.current;U&&re({left:U.scrollLeft>2,right:U.scrollLeft+U.clientWidth<U.scrollWidth-2})},[]),qe=i.useRef(Oe);qe.current=Oe,i.useEffect(()=>{const U=L.current;if(!U)return;const Ie=()=>qe.current();Ie(),U.addEventListener("scroll",Ie,{passive:!0});const We=new ResizeObserver(Ie);return We.observe(U),()=>{U.removeEventListener("scroll",Ie),We.disconnect()}},[be.length]);const[Ge,Je]=i.useState({}),[nt,gt]=i.useState({}),yt=i.useRef(new Set),_e=i.useRef(new Set),Qe=i.useRef(new Map),st=i.useRef(0),[wt,Ct]=i.useState([]),[xt,St]=i.useState(!1),[Ze,Ot]=i.useState(""),{isPlaying:ns,play:zt,stop:Ve}=sm(),[At,ot]=i.useState(!1),[vt,bt]=i.useState(null),[ls,Wt]=i.useState(""),qt=i.useRef(""),[rs,Ut]=i.useState(null),[Bt,_t]=i.useState(""),[Yt,Ht]=i.useState(!1),[Zt,ys]=i.useState(`
27
- `),Tt=i.useRef(null),Vt=i.useRef(null),Dt=i.useRef(null),cs=i.useRef(""),us=i.useRef(""),He=i.useRef(null),Ke=i.useRef(null),jt=i.useRef(null),Lt=i.useRef(0),[Nt,xs]=i.useState("idle"),[ps,os]=i.useState(!1),[Kt,Fs]=i.useState(I1),[js,rn]=i.useState(!1),Ks=i.useRef(null),cn=i.useRef(null),Mn=i.useRef(null),Ls=i.useRef(!1),we=i.useRef(null),et=i.useRef(null),ct=i.useRef(null),It=i.useRef(null),[Gt,mt]=i.useState(0),ms=i.useRef(null),hs=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{ms.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(ms.current),ms.current=null)},[]);const[Ss,ws]=i.useState(null),[Ds,Hn]=i.useState(null),[zs,Sn]=i.useState(""),[Fn,Zn]=i.useState(!1),[dn,Ue]=i.useState(null),[Xt,Is]=i.useState(null),[Ts,Ws]=i.useState(!1),[qs,Hs]=i.useState(!1),[Os,Gn]=i.useState(!1),mr=!!n.writeFile,Kn=!!n.createDirectory,gs=!!n.rename,Rs=!!n.delete,Sr=!!n.revealPath,Nn=wr(U=>U.availableApps),un=wr(U=>U.isCacheStale),er=wr(U=>U.initialize),Fr=wr(U=>U.loadInstalledApps);i.useEffect(()=>{er()},[er]);const Yr=i.useCallback(U=>{n.revealPath&&n.revealPath(U).catch(()=>{le.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),ui=i.useCallback(async U=>{if(!G?.path||await gp(G.path,U.id,U.appName)||await va(G.path,U.appName))return;const Ye=b1(G.path)||b;Ye&&await va(Ye,U.appName)||le.error(e("filesView.toast.openInAppFailed",{app:U.appName}))},[b,G?.path,e]),hr=i.useCallback((U,Ie)=>{ws(U),Hn(Ie),Sn(U==="rename"&&Ie.name||""),Zn(!1)},[]),[ds,fn]=i.useState(null),An=i.useRef(!1),Q=i.useRef(null),[tt,pt]=i.useState(!1),Pt=Ee(U=>U.setMainTabGuard),es=Ee(U=>U.pendingFileNavigation),is=Ee(U=>U.setPendingFileNavigation),fs=Ee(U=>U.pendingFileFocusPath),Es=Ee(U=>U.setPendingFileFocusPath),Ys=Ee(U=>U.shortcutOverrides),tr=Ee(U=>U.fileEditorKeymap),qn=ss(U=>U.settingsDefaultFileViewerPreview),Lr=ss(U=>U.showMessageTTSButtons),Bs=Ee(U=>U.expandedEditorToolbar);i.useEffect(()=>{const U=()=>{An.current=!1,Q.current=null,pt(!1)};return document.addEventListener("mouseup",U),()=>document.removeEventListener("mouseup",U)},[]),i.useEffect(()=>()=>{we.current!==null&&window.clearTimeout(we.current),et.current!==null&&window.clearTimeout(et.current)},[]);const Or=i.useCallback((U,Ie)=>{const We=U.split(`
28
- `),Ye=Math.max(1,Ie.start),lt=Math.min(We.length,Ie.end);return Ye>lt?"":We.slice(Ye-1,lt).join(`
29
- `)},[]),xn=Nm({source:"file",fileLabel:G?.path??null,language:G?.path&&Ci(G.path)||"text",getCodeForRange:U=>Or(Ze,km(U)),toStoreRange:U=>({startLine:U.start,endLine:U.end}),fromDraftRange:U=>({start:U.startLine,end:U.endLine})}),{drafts:sr,commentText:bn,setCommentText:Ln,editingDraftId:yn,setSelection:ar,saveComment:Dn,cancel:Nr,reset:Br,startEdit:kr,deleteDraft:Ri}=xn;i.useEffect(()=>{fn(null),Br(),Pt(null),_t(""),Ht(!1)},[G?.path,Br,Pt]),i.useEffect(()=>{ar(ds)},[ds,ar]),i.useEffect(()=>{if(!ds&&!yn)return;const U=We=>{const Ye=We.target;Ye.closest('[data-comment-input="true"]')||Ye.closest('[data-comment-card="true"]')||Ye.closest(".cm-gutterElement")||Ye.closest("[data-sonner-toast]")||Ye.closest("[data-sonner-toaster]")||bn.trim()||(fn(null),Nr())},Ie=setTimeout(()=>{document.addEventListener("click",U)},100);return()=>{clearTimeout(Ie),document.removeEventListener("click",U)}},[Nr,bn,yn,ds]);const fi=i.useCallback((U,Ie)=>{const We=Ie??ds??void 0;Ie&&fn(Ie),Dn(U,We),fn(null)},[ds,Dn]),Ei=i.useCallback((U,Ie)=>{const We=[];for(const Ye of Ie){if(!(Ye&&typeof Ye.name=="string"&&Ye.name.length>0)||!p&&Ye.name.startsWith(".")||!y&&N1(Ye.name))continue;const lt=Ye.name,it=Js(Ye.path||""),ts=it?v1(it)?it:Js(`${U}/${it}`):Js(`${U}/${lt}`),ks=Ye.isDirectory?"directory":"file",Ps=ks==="file"&&lt.includes(".")?lt.split(".").pop()?.toLowerCase():void 0;We.push({name:lt,path:ts,type:ks,extension:Ps})}return w1(We)},[y,p]),on=i.useCallback(async U=>{const Ie=Js(U.trim());if(!Ie||yt.current.has(Ie)||_e.current.has(Ie))return;_e.current=new Set(_e.current),_e.current.add(Ie);const We=st.current+1;st.current=We,Qe.current=new Map(Qe.current),Qe.current.set(Ie,We);const Ye=()=>Qe.current.get(Ie)===We;await(n.listDirectory?n.listDirectory(Ie).then(it=>it.entries.map(ts=>({name:ts.name,path:ts.path,isDirectory:ts.isDirectory}))):Jn.listLocalDirectory(Ie).then(it=>it.map(ts=>({name:ts.name,path:ts.path,isDirectory:ts.isDirectory})))).then(it=>{if(!Ye())return;const ts=Ei(Ie,it);yt.current=new Set(yt.current),yt.current.add(Ie),gt(ks=>{if(!ks[Ie])return ks;const Ps={...ks};return delete Ps[Ie],Ps}),Je(ks=>({...ks,[Ie]:ts}))}).catch(it=>{if(!Ye())return;const ts=it instanceof Error?it.message:String(it??"");if(ts==="Directory not found"&&b&&Ie!==b){P(b,Ie),gt(ks=>{if(!ks[Ie])return ks;const Ps={...ks};return delete Ps[Ie],Ps});return}console.error("Failed to load files directory:",it),gt(ks=>({...ks,[Ie]:ts}))}).finally(()=>{Ye()&&(Qe.current=new Map(Qe.current),Qe.current.delete(Ie),_e.current=new Set(_e.current),_e.current.delete(Ie))})},[n,Ei,P,b]),pr=i.useCallback(async()=>{b&&(yt.current=new Set,_e.current=new Set,Qe.current=new Map,gt({}),Je(U=>Object.keys(U).length===0?U:{}),await on(b))},[on,b]),Qs=i.useCallback(async U=>{if(!U){await pr();return}const Ie=Js(U);yt.current=new Set(yt.current),yt.current.delete(Ie),_e.current=new Set(_e.current),_e.current.delete(Ie),await on(Ie)},[on,pr]),wn=i.useRef(""),Qr=i.useRef("");i.useEffect(()=>{if(!b)return;const U=`${b}|h${p?"1":"0"}|g${y?"1":"0"}`,Ie=wn.current!==b,We=Qr.current!==U;!Ie&&!We||(Ie&&(wn.current=b,Ot(""),bt(null),Wt(""),Ut(null),D(!1)),We&&(Qr.current=U,yt.current=new Set,_e.current=new Set,Qe.current=new Map,gt({}),Je(Ye=>Object.keys(Ye).length===0?Ye:{}),on(b)))},[on,b,y,p]),i.useEffect(()=>{if(!n.listDirectory)return;const U=()=>{if(!document.hidden&&ce.length>0)for(const Ie of ce)Qs(Ie)};return document.addEventListener("visibilitychange",U),()=>document.removeEventListener("visibilitychange",U)},[ce,n.listDirectory,Qs]),i.useEffect(()=>{if(!n.listDirectory||ce.length===0)return;const U=setInterval(()=>{if(!document.hidden)for(const Ie of ce)Qs(Ie)},8e3);return()=>clearInterval(U)},[ce,n.listDirectory,Qs]);const co=i.useCallback(async U=>{if(U?.preventDefault(),!Ds||!Ss)return;Zn(!0);const Ie=()=>{ws(null)},We=lt=>{le.error(lt)},Ye=()=>{Zn(!1)};if(Ss==="createFile"){if(!zs.trim()){We(e("sidebarFilesTree.toast.filenameRequired")),Ye();return}if(!n.writeFile){We(e("sidebarFilesTree.toast.writeNotSupported")),Ye();return}const lt=Ds.path,it=lt?`${lt}/`:"",ts=Js(`${it}${zs.trim()}`);await n.writeFile(ts,"").then(async ks=>{ks.success&&(le.success(e("sidebarFilesTree.toast.fileCreated")),await Qs(lt)),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ye);return}if(Ss==="createFolder"){if(!zs.trim()){We(e("sidebarFilesTree.toast.folderNameRequired")),Ye();return}const lt=Ds.path,it=lt?`${lt}/`:"",ts=Js(`${it}${zs.trim()}`);await n.createDirectory(ts).then(async ks=>{ks.success&&(le.success(e("sidebarFilesTree.toast.folderCreated")),await Qs(lt)),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ye);return}if(Ss==="rename"){if(!zs.trim()){We(e("sidebarFilesTree.toast.nameRequired")),Ye();return}if(!n.rename){We(e("sidebarFilesTree.toast.renameNotSupported")),Ye();return}const lt=Ds.path,it=lt.split("/").slice(0,-1).join("/"),ts=it?`${it}/`:"",ks=Js(`${ts}${zs.trim()}`);await n.rename(lt,ks).then(async Ps=>{Ps.success&&(le.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await Qs(it),b&&fe(b,lt),(G?.path===lt||G?.path.startsWith(`${lt}/`))&&(b&&M(b,null),Ot(""),bt(null),Wt(""),Ut(null),d&&D(!1))),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ye);return}if(Ss==="delete"){if(!n.delete){We(e("sidebarFilesTree.toast.deleteNotSupported")),Ye();return}const lt=Ds.path,it=lt.split("/").slice(0,-1).join("/");await n.delete(lt).then(async ts=>{ts.success&&(le.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await Qs(it),b&&fe(b,lt),(G?.path===lt||G?.path.startsWith(`${lt}/`))&&(b&&M(b,null),Ot(""),bt(null),Wt(""),Ut(null),d&&D(!1))),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ye);return}Ye()},[Ss,Ds,zs,n,Qs,d,fe,b,G?.path,M,e]);i.useEffect(()=>{if(!g){Ct([]),St(!1);return}const U=k.trim();if(!U){Ct([]),St(!1);return}let Ie=!1;return St(!0),C(g,U,150,{includeHidden:p,respectGitignore:!y,type:"file"}).then(We=>{if(Ie)return;const lt=We.filter(it=>y||!k1(it.path)).map(it=>({name:it.name,path:Js(it.path),type:"file",extension:it.extension,relativePath:it.relativePath}));Ct(lt)}).catch(()=>{Ie||Ct([])}).finally(()=>{Ie||St(!1)}),()=>{Ie=!0}},[g,k,C,p,y]);const _r=i.useCallback(async(U,Ie)=>{if(n.readFile)return(await n.readFile(U,{...Ie??{},directory:b||void 0})).content??"";const We=new URLSearchParams({path:U});Ie?.allowOutsideWorkspace&&We.set("allowOutsideWorkspace","true"),Ie?.outsideFileGrant&&We.set("outsideFileGrant",Ie.outsideFileGrant),Ie?.optional&&We.set("optional","true"),b&&We.set("directory",b);const Ye=await Cs(`/api/fs/read?${We.toString()}`,{cache:Ie?.optional?"no-store":"default"});if(!Ye.ok){const lt=await Ye.json().catch(()=>({error:Ye.statusText}));throw new Error(lt.error||e("filesView.error.readFileFailed"))}return Ye.text()},[n,b,e]),lr=i.useCallback(async(U,Ie)=>{if(n.statFile){const We=await n.statFile(U,{...Ie??{},directory:b||void 0});return{path:We.path,size:We.size,mtimeMs:We.mtimeMs}}return null},[n,b]);i.useEffect(()=>{if(!b||!n.statFile||Ae.length===0)return;let U=!1;const Ie=[...Ae];return Promise.all(Ie.map(async We=>{try{const Ye=await n.statFile?.(We,{directory:b||void 0});!U&&Ye&&!Ye.isFile&&fe(b,We)}catch(Ye){!U&&Wu(Ye)&&fe(b,We)}})),()=>{U=!0}},[n,Ae,fe,b]);const Cr=i.useMemo(()=>Ze.length>go?`${Ze.slice(0,go)}
30
-
31
- … truncated …`:Ze,[Ze]),mn=Bt!==Cr,cr=i.useCallback(async()=>{if(!G||!n.writeFile)return le.error(e("filesView.toast.savingNotSupported")),!1;if(!mn)return!0;if(Bt===""&&Ze!==""&&rs!==G.path)return console.warn(`[saveDraft] refusing to save empty draft for "${G.path}" (${Ze.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;Ht(!0);try{const U=D1(Bt,Zt);return(await n.writeFile(G.path,U))?.success?(Ot(Bt),G?.path&&Md(G.path)&&(cs.current=Bt,us.current=Bt),lr(G.path).then(We=>{We&&(jt.current=We)}).catch(()=>{}),!0):(le.error(e("filesView.toast.writeFileFailed")),!1)}catch(U){return le.error(U instanceof Error?U.message:e("filesView.toast.saveFailed")),!1}finally{Ht(!1)}},[Bt,Ze,n,mn,Zt,rs,lr,G,e]);i.useEffect(()=>{if(!mn){Pt(null);return}const U=Ie=>Ls.current?(Ls.current=!1,!0):(rn(!0),cn.current=Ie,!1);return Pt(U),()=>{Ee.getState().mainTabGuard===U&&Pt(null)}},[mn,Pt]),i.useEffect(()=>{try{window.localStorage.setItem(Ym,Kt?"true":"false")}catch{}},[Kt]),i.useEffect(()=>{Kt||(xs("idle"),Vt.current&&(clearTimeout(Vt.current),Vt.current=null))},[Kt]);const Mi=1500;i.useEffect(()=>{const U=!!(G&&n.writeFile);if(!(!Kt||!mn||!U||Yt))return Vt.current=setTimeout(()=>{cr().then(Ie=>{Ie&&(xs("saved"),setTimeout(()=>xs("idle"),2e3))})},Mi),()=>{Vt.current&&(clearTimeout(Vt.current),Vt.current=null)}},[Kt,Bt,mn,G,n.writeFile,Yt,cr]),i.useEffect(()=>{xs("idle")},[G?.path]),i.useEffect(()=>{const U=Ie=>{vc(Ie)&&(Ie.key.toLowerCase()==="s"?(Ie.preventDefault(),Vt.current&&(clearTimeout(Vt.current),Vt.current=null),Yt||cr().then(We=>{We&&(xs("saved"),setTimeout(()=>xs("idle"),2e3))})):Ie.key.toLowerCase()==="f"&&(Ie.preventDefault(),R(!0)))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[Yt,cr]);const Fi=i.useCallback(async U=>{const Ie=Lt.current+1;Lt.current=Ie;const We=()=>{if(!b)return!1;const Ps=pn.getState().byRoot[b],xr=Ps?.selectedPath??Ps?.openPaths[0]??null;return Lt.current===Ie&&xr===U.path};bt(null),Wt(""),Ut(null);const Ye=Zi(U.path),lt=U.path.toLowerCase().endsWith(".svg"),it=Fd(U.path);if(d&&D(!0),r.isDesktop&&Ye&&!lt){Ot(""),_t(""),ot(!0);return}if(!r.isDesktop&&Ye&&!lt){Ot(""),_t(""),Ut(U.path),ot(!1);return}if(it){Ot(""),_t(""),Ut(U.path),ot(!1);return}ot(!0);const ts=Ed(U.path),ks={allowOutsideWorkspace:t==="editor-only"&&!!b&&!Ra(U.path,b),outsideFileGrant:ts};await _r(U.path,ks).then(Ps=>{if(!We())return;const xr=Qm(Ps);ys(A1(Ps)),Ot(xr),cs.current=xr,us.current=xr,_t(xr.length>go?`${xr.slice(0,go)}
32
-
33
- … truncated …`:xr),Ut(U.path),lr(U.path,ks).then(dr=>{dr&&We()&&(jt.current=dr)}).catch(()=>{})}).catch(Ps=>{if(We()){if(C1(Ps)){if(ot(!1),b&&M(b,null),bt(null),Ot(""),_t(""),Ut(null),jt.current=null,v.trim().length>0&&S(""),d&&D(!1),b){const dr=[...$u(U.path,b),U.path];dr.length>0&&xe(b,dr);for(const il of dr)yt.current.has(il)||on(il)}return}if(Wu(Ps)){b&&fe(b,U.path),Ot(""),_t(""),bt(null),jt.current=null,d&&D(!1);return}Ot(""),_t(""),bt(Ps instanceof Error?Ps.message:e("filesView.error.readFileFailed")),jt.current=null}}).finally(()=>{We()&&ot(!1)})},[xe,d,on,t,_r,lr,fe,b,r.isDesktop,v,M,e]),Vr=i.useCallback(async(U,Ie)=>{if(!b)return;const We=$u(U,b),Ye=Ie?[...We,U]:We;Ye.length>0&&xe(b,Ye);const lt=Ye.map(it=>{if(!yt.current.has(it))return on(it)}).filter(Boolean);await Promise.all(lt)},[xe,on,b]),mi=i.useCallback((U,Ie)=>{const We=Ie.findIndex(Ye=>Ye.path===U);return We===-1||Ie.length<=1?null:Ie[We+1]??Ie[We-1]??null},[]),an=i.useCallback(async U=>{if(Ls.current)Ls.current=!1;else if(mn){rn(!0),Ks.current=U;return}b&&(M(b,U.path),he(b,U.path),Vr(U.path,!1)),bt(null),Wt(""),Ot(""),cs.current="",us.current="",_t(""),Ut(null),d&&D(!0)},[he,Vr,mn,d,b,M]);i.useEffect(()=>{G?.path&&Vr(G.path,!1)},[Vr,G?.path]),i.useEffect(()=>{if(!G){Lt.current+=1,ot(!1);return}rs!==G.path&&Fi(G)},[Fi,rs,G]);const Li=i.useRef(mn);Li.current=mn,i.useEffect(()=>{if(!G?.path||rs!==G.path)return;let U=!1;const Ie=window.setInterval(()=>{document.hidden||lr(G.path,J).then(We=>{if(U||!We)return;const Ye=jt.current;if(!Ye||Ye.path!==G.path){jt.current=We;return}const lt=We.mtimeMs!==void 0&&Ye.mtimeMs!==void 0&&We.mtimeMs!==Ye.mtimeMs,it=We.size!==Ye.size;!lt&&!it||Li.current||(jt.current=We,Ut(null))}).catch(()=>{})},2e3);return()=>{U=!0,window.clearInterval(Ie)}},[rs,lr,G?.path,J]);const uo=i.useCallback(()=>{const U=Ks.current,Ie=cn.current,We=Mn.current;if(Ks.current=null,cn.current=null,Mn.current=null,Ls.current=!0,rn(!1),_t(Cr),We){b&&Ne(b,We),G?.path===We&&(U?an(U):(b&&M(b,null),Ot(""),bt(null),Wt(""),Ut(null),d&&D(!1)));return}if(U){an(U);return}Ie&&(Pt(null),Ee.getState().setActiveMainTab(Ie))},[Cr,an,d,Ne,b,G?.path,Pt,M]),fo=i.useCallback(async()=>{const U=Ks.current,Ie=cn.current,We=Mn.current;if(!await cr()){Ls.current=!1;return}if(Ks.current=null,cn.current=null,Mn.current=null,Ls.current=!0,rn(!1),We){b&&Ne(b,We),G?.path===We&&(U?await an(U):(b&&M(b,null),Ot(""),bt(null),Wt(""),Ut(null),d&&D(!1)));return}if(U){await an(U);return}Ie&&(Pt(null),Ee.getState().setActiveMainTab(Ie))},[an,d,Ne,b,cr,G?.path,Pt,M]),K=i.useCallback(U=>{const Ie=G?.path===U,We=mi(U,be);if(Ie&&mn){rn(!0),Ks.current=We,Mn.current=U;return}if(b&&Ne(b,U),!!Ie){if(We){an(We);return}b&&M(b,null),Ot(""),bt(null),Wt(""),Ut(null),d&&D(!1)}},[mi,an,mn,d,be,Ne,b,G?.path,M]),Ce=i.useCallback(U=>{if(Ae.includes(U))return"open";if(w?.files){const Ie=U.startsWith(b+"/")?U.slice(b.length+1):U,We=w.files.find(Ye=>Ye.path===Ie);if(We){if(We.index==="A"||We.working_dir==="?")return"git-added";if(We.index==="D")return"git-deleted";if(We.index==="M"||We.working_dir==="M")return"git-modified"}}return null},[Ae,w,b]),Te=i.useCallback(U=>{if(!w?.files)return null;const Ie=U.startsWith(b+"/")?U.slice(b.length+1):U,We=Ie?`${Ie}/`:"";let Ye=0,lt=0;for(const it of w.files)it.path.startsWith(We)&&((it.index==="M"||it.working_dir==="M")&&Ye++,(it.index==="A"||it.working_dir==="?")&&lt++);return Ye+lt>0?{modified:Ye,added:lt}:null},[w,b]),ze=i.useCallback(async U=>{const Ie=Js(U);b&&(de(b,Ie),yt.current.has(Ie)||await on(Ie))},[on,b,de]),dt=i.useMemo(()=>({canRename:gs,canCreateFile:mr,canCreateFolder:Kn,canDelete:Rs,canReveal:Sr}),[gs,mr,Kn,Rs,Sr]);function Rt(U,Ie){const We=Ge[U]??[];return We.map((Ye,lt)=>{const it=Ye.type==="directory",ts=it&&ce.includes(Ye.path),ks=G?.path===Ye.path,Ps=lt===We.length-1;return s.jsxs("li",{className:"relative",children:[Ie>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ps&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(T1,{node:Ye,root:b,isExpanded:ts,isActive:ks,isMobile:d,alwaysShowActions:f,status:it?void 0:Ce(Ye.path),badge:it?Te(Ye.path):void 0,permissions:dt,downloadFile:n.downloadFile,contextMenuPath:dn,setContextMenuPath:Ue,rightClickMenuPath:Xt,setRightClickMenuPath:Is,onSelect:an,onToggle:ze,onRevealPath:Yr,onOpenDialog:hr}),it&&ts&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[nt[Ye.path]?s.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:nt[Ye.path],children:nt[Ye.path]}),s.jsxs($e,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Qs(Ye.path)},children:[s.jsx(I,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,Rt(Ye.path,Ie+1)]})]},Ye.path)})}const Qt=!!(G?.path&&Zi(G.path)),Jt=!!(G?.path&&G.path.toLowerCase().endsWith(".svg")),vs=!!(G?.path&&Fd(G.path)),gr=i.useMemo(()=>Js(es?.path??""),[es?.path]),Ar=!!(es&&gr&&ye&&ye===gr&&!At&&!vt&&!Qt&&!vs),ie=i.useMemo(()=>sc(b,ye),[ye,b]),at=!!(G&&(!Qt||Jt)&&!vs&&Ze.length>0),rt=!!(G&&ie.length>0),ht=!!(G&&!Le&&!Qt&&!vs&&n.writeFile&&Ze.length<=go),$t=!!(G?.path&&Uu(G.path)),As=!!(G?.path&&P1(G.path)),Zs=!!(G?.path&&Xo(G.path)),hn=!!(G?.path&&Md(G.path)),kn=!!(G&&!Qt&&!vs)&&!$t&&!hn&&!(Zs&&Z==="preview"),In=i.useMemo(()=>ye?nm(ye):null,[ye]),[hi,pi]=i.useState(null);i.useEffect(()=>{let U=!1;const Ie=G?.path;if(!Ie||In){pi(null);return}return pi(null),yg(Ie).then(We=>{U||pi(We)}),()=>{U=!0}},[G?.path,In]),i.useEffect(()=>{!ht&&q==="edit"&&H("view")},[ht,q]);const gi="openchamber:files:md-viewer-mode",Za="openchamber:files:html-viewer-mode",el="openchamber:files:json-viewer-mode";i.useEffect(()=>{const U=G?.path;if(!U)return;const Ie=qn?"view":"edit";H(ee.current[U]??Ie);let We=qn?"preview":"edit";try{const it=localStorage.getItem(gi);(it==="preview"||it==="edit")&&(We=it)}catch{}oe(je.current[U]??We);let Ye=qn?"preview":"edit";try{const it=localStorage.getItem(Za);(it==="preview"||it==="edit")&&(Ye=it)}catch{}ke(De.current[U]??Ye),ge(Be.current[U]??"preview");let lt=qn?"tree":"text";try{const it=localStorage.getItem(el);(it==="tree"||it==="text")&&(lt=it)}catch{}Se(lt)},[G?.path,qn]);const Ah=i.useCallback(U=>{const Ie=G?.path;Ie&&(ee.current[Ie]=U),H(U)},[G?.path]),Dh=i.useCallback(U=>{const Ie=G?.path;Ie&&(je.current[Ie]=U),oe(U);try{localStorage.setItem(gi,U)}catch{}},[G?.path]),mo=i.useCallback(()=>X,[X]),Ih=i.useCallback(U=>{Se(U);try{localStorage.setItem(el,U)}catch{}},[]),Ph=i.useCallback(U=>{const Ie=G?.path;Ie&&(De.current[Ie]=U),ke(U);try{localStorage.setItem(Za,U)}catch{}},[G?.path]),Th=i.useCallback(U=>{const Ie=G?.path;if(Ie&&(Be.current[Ie]=U),Dt.current&&(clearTimeout(Dt.current),Dt.current=null),He.current!==null&&(cancelAnimationFrame(He.current),He.current=null),U==="edit")_t(cs.current||Ze),ge(U);else{cs.current=Bt;const We=Ie;ge("edit"),He.current=requestAnimationFrame(()=>{He.current=requestAnimationFrame(()=>{He.current=null,!(b&&We&&pn.getState().byRoot[b]?.selectedPath!==We)&&(se(Ye=>Ye+1),ge("preview"))})});return}},[Bt,Ze,b,G?.path]),tl=i.useCallback(async(U,Ie)=>{if(!n.writeFile||Ie===us.current)return!1;if(!(await n.writeFile(U,Ie))?.success)return le.error(e("filesView.toast.writeFileFailed")),!1;cs.current=Ie,us.current=Ie,_t(Ie);const Ye=await lr(U,J).catch(()=>null);return Ye&&(jt.current=Ye),!0},[n,lr,J,e]);i.useEffect(()=>()=>{Dt.current&&(clearTimeout(Dt.current),Dt.current=null),He.current!==null&&(cancelAnimationFrame(He.current),He.current=null)},[Y,G?.path]);const Rh=i.useCallback(U=>{if(cs.current=U,!G?.path||Y!=="preview"||!n.writeFile)return;Dt.current&&clearTimeout(Dt.current);const Ie=G.path;Dt.current=setTimeout(()=>{Dt.current=null,tl(Ie,U).then(We=>{We&&(os(!0),setTimeout(()=>os(!1),1500))}).catch(We=>{le.error(We instanceof Error?We.message:e("filesView.toast.saveFailed"))})},Mi)},[Y,n.writeFile,tl,G?.path,e]),Eh=i.useMemo(()=>hn&&(cs.current||Bt)||Ze,[Bt,Ze,hn]),Yc=i.useCallback(()=>Z,[Z]);i.useEffect(()=>{const U=We=>{const Ye=We?"view":"edit",lt=We?"preview":"edit",it=We?"tree":"text";for(const ts of Ae)ee.current[ts]=Ye,Uu(ts)&&(je.current[ts]=lt),Xo(ts)&&(De.current[ts]=lt);H(Ye),oe(lt),ke(lt),Se(it);try{localStorage.setItem(gi,lt),localStorage.setItem(Za,lt),localStorage.setItem(el,it)}catch{}},Ie=We=>{const Ye=!!We.detail?.enabled;U(Ye)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",Ie),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",Ie)}},[Ae]),i.useEffect(()=>{if(!es||!b)return;const U=()=>{typeof window>"u"||ms.current===null&&(ms.current=window.requestAnimationFrame(()=>{ms.current=null,mt($r=>$r+1)}))},Ie=($r,xi)=>{if($r.state.doc.length!==xi.length)return!1;if(xi.length===0)return!0;const ol=Math.min(128,xi.length);if($r.state.sliceDoc(0,ol)!==xi.slice(0,ol))return!1;const ud=Math.max(0,xi.length-ol);return $r.state.sliceDoc(ud,xi.length)===xi.slice(ud)},We=Js(es.path);if(!We){is(null),hs.current={key:"",attempts:0};return}const Ye=`${We}:${es.line}:${es.column??1}`;if(hs.current.key!==Ye&&(hs.current={key:Ye,attempts:0}),G?.path!==We){if(js)return;an(W(We));return}if(At||rs!==We)return;if(vt||Qt||vs){is(null),hs.current={key:"",attempts:0};return}if(!ht)return;if(q!=="edit"){H("edit");return}const lt=ct.current;if(!lt){U();return}if(!Ie(lt,Bt)){U();return}const it=Math.max(1,Math.min(es.line,lt.state.doc.lines)),ts=lt.state.doc.line(it),ks=Math.max(1,es.column||1),Ps=Math.max(0,ts.to-ts.from),xr=Math.min(Ps,ks-1),dr=ts.from+xr;if(!(lt.state.selection.main.head===dr)||hs.current.attempts===0){hs.current.attempts+=1,lt.dispatch({selection:{anchor:dr},effects:ni.scrollIntoView(dr,{y:"center"})}),lt.focus(),U();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const $r=ct.current;$r&&($r.dispatch({selection:{anchor:dr},effects:ni.scrollIntoView(dr,{y:"center"})}),$r.focus())}),is(null),hs.current={key:"",attempts:0}},[ht,js,Bt,Gt,vt,At,Qt,vs,rs,an,es,b,G?.path,is,q,W]),i.useEffect(()=>{if(!fs||!b)return;const U=Js(fs);if(!U){Es(null);return}if(G?.path!==U){if(js)return;an(W(U));return}if(!(At||rs!==U||vt||Qt||vs)){if(ht&&q==="edit"){const Ie=ct.current;if(!Ie)return;Ie.focus()}Es(null)}},[ht,js,vt,At,an,Qt,vs,rs,fs,b,G?.path,Es,q,W]);const Oi=i.useCallback(U=>{if(!d||!U||!U.hasFocus||typeof window>"u")return;const Ie=window.visualViewport;if(!Ie)return;const We=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,We-(Ie.offsetTop+Ie.height))<=0)return;const lt=U.state.selection.main.head,it=U.coordsAtPos(lt);if(!it)return;const ts=Math.round(Ie.offsetTop+Ie.height),Ps=it.bottom+20-ts;Ps<=0||(U.scrollDOM.scrollTop+=Ps)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const U=()=>{window.requestAnimationFrame(()=>{Oi(ct.current)})},Ie=window.visualViewport;return Ie?.addEventListener("resize",U),Ie?.addEventListener("scroll",U,{passive:!0}),document.addEventListener("selectionchange",U),()=>{Ie?.removeEventListener("resize",U),Ie?.removeEventListener("scroll",U),document.removeEventListener("selectionchange",U)}},[d,Oi]),i.useEffect(()=>{if(!ht||q!=="edit"||d)return;const U=ii("open_go_to_line",Ys),Ie=We=>{const Ye=We.target;if(Ye?.closest('[role="dialog"]'))return;const lt=!!Ye?.closest(".cm-editor");Ye?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!lt||!document.activeElement?.closest(".cm-editor")||ia(We,U)&&(We.preventDefault(),Gn(!0))};return window.addEventListener("keydown",Ie),()=>window.removeEventListener("keydown",Ie)},[ht,d,Ys,q]);const Qc=i.useMemo(()=>{if(!G?.path)return[Kl(o)];const U=Ci(G.path),Ie=[Kl(o,U?{syntaxColors:!1}:void 0)],We=In??hi;return We&&Ie.push(We),U&&Ie.push(Cm({language:U,themeName:o.metadata.id,theme:rm(o)})),N&&Ie.push(ni.lineWrapping),d&&Ie.push(ni.updateListener.of(Ye=>{Ye.view.hasFocus&&(Ye.selectionSet||Ye.focusChanged||Ye.viewportChanged||Ye.geometryChanged)&&window.requestAnimationFrame(()=>{Oi(Ye.view)})})),Ie},[o,G?.path,In,hi,N,d,Oi]),Jc=i.useMemo(()=>({light:Fe.metadata.id,dark:Me.metadata.id}),[Fe.metadata.id,Me.metadata.id]),_o=G?.path&&Qt&&!r.isDesktop&&!Jt?`${G.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",Vo=G?.path&&vs?`${G.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",$o=G?.path&&Zs&&Z==="preview"&&!r.isVSCode?G.path:"",sl=e("filesView.error.readFileFailed"),{readyKey:Xc,nonce:Zc}=Al(_o,bt,sl),{readyKey:ed,nonce:Mh}=Al($o,bt,sl),{readyKey:td,nonce:sd}=Al(Vo,bt,sl),nd=!!(_o&&Xc!==_o),Fh=!!($o&&ed!==$o),rd=!!(Vo&&td!==Vo),id=G?.path&&Qt?r.isDesktop?Jt?`data:${Ld(G.path)};utf8,${encodeURIComponent(Ze)}`:ls:Jt?`data:${Ld(G.path)};utf8,${encodeURIComponent(Ze)}`:Xc===_o?ki().authenticatedAsset("/api/fs/raw",{path:G.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:b||void 0}):"":"",od=G?.path&&vs&&td===Vo?ki().authenticatedAsset("/api/fs/raw",{path:G.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:b||void 0}):"",ad=i.useCallback(U=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:od,className:"h-full w-full border-0",title:U.name},sd)}),[od,sd]);i.useEffect(()=>{let U=!1;return(async()=>{if(!r.isDesktop||!G?.path||!Qt||Jt){qt.current&&(URL.revokeObjectURL(qt.current),qt.current=""),Wt("");return}bt(null),qt.current&&(URL.revokeObjectURL(qt.current),qt.current=""),await(n.readFileBinary?n.readFileBinary(G.path,J).then(Ye=>Ye.dataUrl):(async()=>{const Ye=await Cs("/api/fs/raw",{query:{path:G.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:b||void 0}});if(!Ye.ok)throw new Error(e("filesView.error.readFileFailed"));const lt=await Ye.blob(),it=URL.createObjectURL(lt);return U?(URL.revokeObjectURL(it),""):(qt.current=it,it)})()).then(Ye=>{U||(Wt(Ye),Ut(G.path))}).catch(Ye=>{qt.current&&(URL.revokeObjectURL(qt.current),qt.current=""),U||(Wt(""),bt(Ye instanceof Error?Ye.message:e("filesView.error.readFileFailed")),Ut(null))}).finally(()=>{U||ot(!1)})})(),()=>{U=!0}},[n,Qt,Jt,b,r.isDesktop,G?.path,J,e]),i.useEffect(()=>()=>{qt.current&&(URL.revokeObjectURL(qt.current),qt.current="")},[]);const Lh=i.useCallback(()=>ws(null),[]),Oh=i.useMemo(()=>Im({drafts:sr,editingDraftId:yn,commentText:bn,onTextChange:Ln,selection:ds,isDragging:tt,fileLabel:G?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:U=>({start:U.startLine,end:U.endLine}),onSave:fi,onCancel:()=>{fn(null),Nr()},onEdit:U=>{kr(U),fn({start:U.startLine,end:U.endLine})},onDelete:Ri}),[Nr,bn,Ri,yn,sr,fi,tt,ds,G?.path,Ln,kr]),ld=i.useCallback((U,Ie)=>s.jsx("div",{className:"h-full",children:s.jsx(Kh,{file:{name:U.name,contents:Ie,lang:Ci(U.path)||void 0},options:{disableFileHeader:!0,overflow:N?"wrap":"scroll",theme:Jc,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,Jc,N]),nl=({exitFullscreenOnly:U=!1,layout:Ie="floating"}={})=>{if(!G)return null;const Ye=Ie==="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",lt=(it,ts)=>s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:ts})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:it})]});return s.jsxs("div",{className:Ye,children:[ht&&q==="edit"&&s.jsxs(s.Fragment,{children:[Yt?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):Kt&&Nt==="saved"&&!mn?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(I,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):mn?lt(e(Kt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${ll()}+S`}),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{cr()},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(Kt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${ll()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${ll()}+S`}),children:s.jsx(I,{name:"save-3",className:"size-4"})})):null,lt(e(Kt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Fs(it=>!it),className:Pe("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",Kt?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(Kt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(Kt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:Kt?s.jsx(I,{name:"file-check-fill",className:"size-4"}):s.jsx(I,{name:"file-check",className:"size-4"})}))]}),s.jsxs(nn,{onOpenChange:ne,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{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(I,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(sn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Nn.map(it=>s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{ui(it)},children:[s.jsx(y1,{label:it.label,iconDataUrl:it.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:it.label})]},it.id)),un?s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Fr(!0)},children:[s.jsx(I,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!Qt&&!vs&&s.jsxs(s.Fragment,{children:[lt(e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>B(!N),className:Pe("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",N?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(I,{name:"text-wrap",className:"size-4"})})),q==="edit"&&s.jsxs(s.Fragment,{children:[lt(e("filesView.editor.findInFile"),s.jsx($e,{variant:"ghost",size:"sm",onClick:it=>{R(!_),it.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.findInFile"),children:s.jsx(I,{name:"search",className:"size-4"})})),lt(e("filesView.editor.goToLine"),s.jsx($e,{variant:"ghost",size:"sm",onClick:it=>{Gn(ts=>!ts),it.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.goToLine"),children:s.jsx(I,{name:"menu-fold-2",className:"size-4"})})),s.jsx(p1,{open:Os,onOpenChange:Gn,view:ct.current,variant:"inline"})]})]}),kn&&ht&&!As&&!Zs&&s.jsx(aa,{currentMode:q==="view"?"preview":"edit",onToggle:()=>{Ah(q==="view"?"edit":"view")}}),($t||Xo(G?.path??""))&&s.jsx(aa,{currentMode:$t?mo():Yc(),onToggle:()=>{Xo(G?.path??"")?Ph(Yc()==="preview"?"edit":"preview"):Dh(mo()==="preview"?"edit":"preview")}}),$t&&mo()==="preview"&&Lr&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{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(ns?"filesView.tts.stopSpeaking":"filesView.tts.readAloud"),onClick:()=>{ns?Ve():Ze.trim()&&zt(Ze)},children:ns?s.jsx(I,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"volume-up",className:"size-4"})})}),s.jsx(Ft,{sideOffset:8,children:e(ns?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),hn&&s.jsxs(s.Fragment,{children:[s.jsx(aa,{currentMode:Y,onToggle:()=>Th(Y==="preview"?"edit":"preview")}),Y==="preview"&&s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{const it=Ke.current?.getXml();if(Dt.current&&(clearTimeout(Dt.current),Dt.current=null),G?.path&&it){if(!await tl(G.path,it))return;os(!0),setTimeout(()=>os(!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:ps?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"save-3",className:"size-4"})})]}),As&&lt(e(ue==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Ih(ue==="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(ue==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:ue==="tree"?s.jsx(I,{name:"code-sslash",className:"size-4"}):s.jsx(I,{name:"node-tree",className:"size-4"})})),at&&lt(e("filesView.editor.copyFileContents"),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await fr(Ze)).ok?(Ws(!0),we.current!==null&&window.clearTimeout(we.current),we.current=window.setTimeout(()=>{Ws(!1)},1200)):le.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:Ts?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"clipboard",className:"size-4"})})),rt&&lt(e("filesView.editor.copyFilePathTitle",{path:ie}),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await fr(ie)).ok?(Hs(!0),et.current!==null&&window.clearTimeout(et.current),et.current=window.setTimeout(()=>{Hs(!1)},1200)):le.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:ie}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:ie}),children:qs?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&&lt(e("filesView.editor.saveFile"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{const it=n.downloadFile;it&&it(G.path).catch(ts=>{console.error("Download failed:",ts),le.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(I,{name:"download",className:"size-4"})})),U?lt(e("filesView.editor.exitFullscreen"),s.jsx($e,{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(I,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&&lt(e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>E(!T),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:T?s.jsx(I,{name:"fullscreen-exit",className:"size-4"}):s.jsx(I,{name:"fullscreen",className:"size-4"})}))]})},rl=s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[s.jsx($s,{open:js,onOpenChange:U=>{U||rn(!0)},children:s.jsxs(Vs,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(Gs,{children:[s.jsx(Us,{children:e("filesView.unsaved.title")}),s.jsx(ln,{children:e("filesView.unsaved.description")})]}),s.jsxs(or,{children:[s.jsx($e,{variant:"outline",onClick:()=>{fo()},disabled:Yt,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($e,{variant:"destructive",onClick:uo,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:Pe("flex flex-col flex-shrink-0",x&&"border-b border-border/40"),children:[x?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&A&&s.jsx("button",{type:"button",onClick:()=>D(!1),"aria-label":e("filesView.editor.back"),className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(I,{name:"arrow-left-s",className:"size-5"})}),d?G?s.jsxs(nn,{children:[s.jsx(tn,{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(Gr,{filePath:G.path,extension:G.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(zu,{name:G.name}),s.jsx(I,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(sn,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:be.map(U=>{const Ie=G?.path===U.path;return s.jsxs(bs,{onSelect:We=>{if(We.target.closest("[data-close-open-file]")){We.preventDefault();return}Ie||an(U)},className:Pe("flex min-w-0 items-center justify-between gap-2 overflow-hidden",Ie&&"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(Gr,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(zu,{name:U.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:We=>{We.preventDefault(),We.stopPropagation()},onClick:We=>{We.preventDefault(),We.stopPropagation(),K(U.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:U.name}),children:s.jsx(I,{name:"close",className:"size-3.5"})})]},U.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):be.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[ae.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"}),ae.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:L,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:be.map(U=>{const Ie=G?.path===U.path;return s.jsxs("div",{title:sc(b,U.path),className:Pe("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",Ie?"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(Gr,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{Ie||an(U)},className:"max-w-[12rem] truncate text-left",children:U.name}),s.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),K(U.path)},className:Pe("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Ie&&!f&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:U.name}),children:s.jsx(I,{name:"close",className:"size-3.5"})})]},U.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,Bs&&!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:[ie?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:ie,children:ie}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:nl({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[G&&!_&&!(Bs&&!d)&&s.jsx("div",{ref:z,className:"absolute right-3 top-3 z-30",onMouseEnter:()=>V(!0),onMouseLeave:()=>{F.current>0||V(!1)},children:$?nl():s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>V(!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(I,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})}),s.jsx($n,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:G?At||nd||rd?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(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.loading")]}):vt?s.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:vt}):Qt?s.jsx("div",{className:"flex h-full items-center justify-center p-3",children:s.jsx("img",{src:id,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"},Zc)}):vs?ad(G):G&&hn&&Y==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(x1,{ref:Ke,xml:Eh,onChange:Rh},`${G.path}:${O}`)}):G&&As&&ue==="tree"?s.jsx(en,{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(wg,{jsonString:Ze,maxHeight:"100%",initiallyExpandedDepth:2})})}):G&&$t&&mo()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-3",children:[Ze.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(Ze.length/1024)})}),s.jsx(en,{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(Po,{content:Ze,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):G&&Zs&&Z==="preview"?Fh?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&&ed===$o?(()=>{const U=G.path.split("/").map(Ie=>encodeURIComponent(Ie)).join("/");return ki().authenticatedAsset(`/api/fs/serve${U.startsWith("/")?U:`/${U}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const U=G.path.substring(0,G.path.lastIndexOf("/")+1);return U?Ze.replace(/<head([^>]*)>/i,`<head$1><base href="${U}">`):Ze})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")},Mh)}):G&&kn&&q==="view"?ld(G,Bt):s.jsxs("div",{className:Pe("relative h-full",Ar&&"overflow-hidden"),ref:It,children:[s.jsx("div",{className:Pe("h-full",Ar&&"invisible"),children:s.jsx(ql,{value:Bt,onChange:_t,readOnly:!ht,vimMode:tr==="vim",extensions:Qc,className:"h-full",blockWidgets:Oh,onViewReady:U=>{ct.current=U,mt(Ie=>Ie+1),window.requestAnimationFrame(()=>{Oi(U)})},onViewDestroy:()=>{ct.current&&(ct.current=null),mt(U=>U+1)},enableSearch:!0,searchOpen:_,onSearchOpenChange:R,highlightLines:ds?{start:Math.min(ds.start,ds.end),end:Math.max(ds.start,ds.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(U,Ie,We)=>{if(!(We instanceof MouseEvent)||We.button!==0)return!1;We.preventDefault();const Ye=U.state.doc.lineAt(Ie.from).number;if(ds&&!We.shiftKey&&Math.min(ds.start,ds.end)===Ye&&Math.max(ds.start,ds.end)===Ye)return fn(null),Nr(),An.current=!1,Q.current=null,pt(!1),!0;if(d&&ds&&!We.shiftKey){const lt=Math.min(ds.start,ds.end,Ye),it=Math.max(ds.start,ds.end,Ye);return fn({start:lt,end:it}),An.current=!1,Q.current=null,pt(!1),!0}if(An.current=!0,Q.current=Ye,pt(!0),ds&&We.shiftKey){const lt=Math.min(ds.start,Ye),it=Math.max(ds.end,Ye);fn({start:lt,end:it})}else fn({start:Ye,end:Ye});return!0},mouseover:(U,Ie,We)=>{if(!(We instanceof MouseEvent)||We.buttons!==1||!An.current||Q.current===null)return!1;const Ye=U.state.doc.lineAt(Ie.from).number,lt=Math.min(Q.current,Ye),it=Math.max(Q.current,Ye);return fn({start:lt,end:it}),pt(!0),!1},mouseup:()=>(An.current=!1,Q.current=null,pt(!1),!1)}}})}),Ar&&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(I,{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")})})]})]}),Bh=!!(b&&Ge[b]),cd=b?nt[b]:null,dd=s.jsxs("section",{className:Pe("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:Pe("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(I,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(jn,{ref:j,value:v,onChange:U=>S(U.target.value),placeholder:e("filesView.tree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),v.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:()=>{S(""),j.current?.focus()},children:s.jsx(I,{name:"close",className:"size-4"})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>hr("createFile",{path:g,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(I,{name:"file-add",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>hr("createFolder",{path:g,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(I,{name:"folder-add",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{pr()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(I,{name:"refresh",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx($n,{outerClassName:"flex-1 min-h-0",className:Pe("py-2",d?"px-3":"px-2"),children:s.jsx("ul",{className:"flex flex-col",children:xt?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):wt.length>0?wt.map(U=>{const Ie=G?.path===U.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{an(U)},className:Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Ie?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[Jm(U.path,U.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:U.path,children:U.relativePath??U.path})]})},U.path)}):cd?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:cd}),s.jsxs($e,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{pr()},children:[s.jsx(I,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):Bh?Rt(b,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),_h=t==="full"&&T&&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:nl({exitFullscreenOnly:!0})}),s.jsx($n,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:At||nd||rd?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(I,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):vt?s.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:vt}):Qt?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("img",{src:id,alt:G.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},Zc)}):vs?ad(G):$t&&mo()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-4",children:[Ze.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(Ze.length/1024)})}),s.jsx(en,{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(Po,{content:Ze,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):kn&&q==="view"?ld(G,Bt):s.jsxs("div",{className:Pe("relative h-full",Ar&&"overflow-hidden"),children:[s.jsx("div",{className:Pe("h-full",Ar&&"invisible"),children:s.jsx(ql,{value:Bt,onChange:_t,readOnly:!ht,vimMode:tr==="vim",extensions:Qc,className:"h-full",onViewReady:U=>{ct.current=U,window.requestAnimationFrame(()=>{Oi(U)})},onViewDestroy:()=>{ct.current&&(ct.current=null)}})}),Ar&&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(I,{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(R1,{activeDialog:Ss,dialogData:Ds,dialogInputValue:zs,onDialogInputChange:Sn,isDialogSubmitting:Fn,onDialogSubmit:co,onClose:Lh,inputRef:Tt}),_h,d?A?rl:dd: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:rl})}):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:dd}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:rl})]})]})};function E1(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}`},M1=(t,e,n)=>Dl(Dl(Dl(t,".opencode"),"plans"),`${e}-${n}.md`),F1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,L1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},O1=(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},B1=(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},Zm=({targetPath:t=null})=>{const{t:e}=kt(),n=ut(re=>re.currentSessionId),r=ut(re=>re.createSession),o=ut(re=>re.initializeNewOpenChamberSession),a=ut(re=>re.sendMessage),c=ut(re=>re.setCurrentSession),l=Dc(),d=Xs(re=>re.homeDirectory),u=wc(re=>re.planModeEnabled),m=Ns(re=>re.projects),f=Ns(re=>re.activeProjectId),p=vn(re=>re.directories),y=di()??"",g=Ee(re=>re.setActiveMainTab),b=Ee(re=>re.setSessionSwitcherOpen),x=Xn(),{isMobile:h}=Mr(),{currentTheme:C}=qr(),w=i.useMemo(()=>n?l.find(re=>re.id===n)??null:null,[n,l]),v=i.useMemo(()=>{const re=typeof w?.directory=="string"?w.directory:"";return vr(re||"")},[w?.directory]),S=i.useMemo(()=>vr(y||v),[y,v]),k=i.useMemo(()=>B1(S,m,f),[f,S,m]),j=i.useMemo(()=>k?p.get(k.path)?.isGitRepo===!0:!1,[k,p]),[A,D]=i.useState(null),[N,B]=i.useState(!1),[T,E]=i.useState(null),_=i.useMemo(()=>!T||!v||!d?T:O1(T,{currentDirectory:v,homeDirectory:d}),[T,v,d]),[R,$]=i.useState(""),{isPlaying:V,play:z,stop:F}=sm(),ne=ss(re=>re.showMessageTTSButtons),[te,q]=i.useState(null),H=i.useMemo(()=>_&&_.split("/").pop()||e("planView.file.defaultName"),[_,e]),X=i.useMemo(()=>R.trim()&&vg(R).title||e("planView.title.default"),[R,e]),oe=i.useMemo(()=>X.trim()||e("planView.title.default"),[X,e]),[ue,Se]=i.useState(!1),[Z,ke]=i.useState(!1),[Y,ge]=i.useState("edit"),O=i.useRef(null),[se,ee]=i.useState(null),je=i.useRef(null),De=i.useRef(null),Be="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const re=localStorage.getItem(Be);if(!re)return;const Oe=JSON.parse(re);(Oe==="preview"||Oe==="edit")&&ge(Oe)}catch{}},[]);const Fe=i.useCallback(re=>{ge(re);try{localStorage.setItem(Be,JSON.stringify(re))}catch{}},[]),Me=i.useRef(!1),me=i.useRef(null),[Ae,pe]=i.useState(!1);i.useEffect(()=>{const re=()=>{Me.current=!1,me.current=null,pe(!1)};return document.addEventListener("mouseup",re),()=>document.removeEventListener("mouseup",re)},[]);const ce=i.useCallback((re,Oe)=>{const qe=re.split(`
34
- `),Ge=Math.max(1,Oe.start),Je=Math.min(qe.length,Oe.end);return Ge>Je?"":qe.slice(Ge-1,Je).join(`
35
- `)},[]),he=Nm({source:"plan",fileLabel:H,language:T&&Ci(T)||"markdown",getCodeForRange:re=>ce(R,km(re)),toStoreRange:re=>({startLine:re.start,endLine:re.end}),fromDraftRange:re=>({start:re.startLine,end:re.endLine})}),{drafts:Ne,commentText:fe,setCommentText:P,editingDraftId:M,setSelection:de,saveComment:xe,cancel:W,reset:be,startEdit:ve,deleteDraft:G}=he;i.useEffect(()=>{ee(null),be()},[R,be]),i.useEffect(()=>{de(se)},[se,de]);const ye=i.useCallback(()=>{ee(null),W()},[W]),Le=i.useCallback((re,Oe)=>{Oe&&ee(Oe),xe(re,Oe??se??void 0),ee(null)},[se,xe]);i.useEffect(()=>{if(!se)return;const re=qe=>{const Ge=qe.target;Ge.closest('[data-comment-card="true"]')||Ge.closest('[data-comment-input="true"]')||Ge.closest(".oc-block-widget")||Ge.closest(".cm-gutterElement")||Ge.closest("[data-sonner-toast]")||Ge.closest("[data-sonner-toaster]")||fe.trim()||(ee(null),W())},Oe=window.setTimeout(()=>{document.addEventListener("click",re)},100);return()=>{window.clearTimeout(Oe),document.removeEventListener("click",re)}},[W,fe,M,h,se]);const Re=i.useMemo(()=>{const re=T?Ci(T):null,Oe=!!re&&re!=="markdown",qe=[Kl(C,Oe?{syntaxColors:!1}:void 0)],Ge=nm(T||"plan.md");return Ge&&qe.push(Ge),Oe&&re&&qe.push(Cm({language:re,themeName:C.metadata.id,theme:rm(C)})),qe.push(ni.lineWrapping),qe},[C,T]);i.useEffect(()=>{if(!u&&!t){E(null),$(""),Se(!1);return}let re=!1;const Oe=async Ge=>{if(x.files?.readFile)return(await x.files.readFile(Ge))?.content??"";const Je=Lo()?.files;if(Je?.readFile)return(await Je.readFile(Ge,{optional:!0}))?.content??"";const nt=await Cs(`/api/fs/read?path=${encodeURIComponent(Ge)}&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),$(""),q(null),t){Se(!0);try{const Ge=await Oe(t);if(re)return;E(t),$(Ge)}catch{if(re)return;E(null),$("")}finally{re||Se(!1)}return}if(!w?.slug||!w?.time?.created||!v){E(null),$("");return}Se(!0);try{const Ge=M1(v,w.time.created,w.slug),Je=L1(F1(w.time.created,w.slug),d||null);let nt=null,gt=null;try{gt=await Oe(Ge),nt=Ge}catch{}if(!nt)try{gt=await Oe(Je),nt=Je}catch{}if(re)return;if(!nt||gt===null){E(null),$("");return}E(nt),$(gt)}catch{if(re)return;E(null),$("")}finally{re||Se(!1)}})(),()=>{re=!0}},[d,u,x.files,v,w?.slug,w?.time?.created,t]),i.useEffect(()=>{if(!T){q(null);return}const re=window.setTimeout(async()=>{q(null);try{if(x.files?.writeFile){if(!(await x.files.writeFile(T,R))?.success)throw new Error(e("planView.error.writeFailed"))}else{const Oe=await Cs("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:T,content:R})});if(!Oe.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:Oe.status}))}}catch(Oe){q(Oe instanceof Error?Oe.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(re)}},[R,T,x.files,e]),i.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const J=i.useCallback(()=>{g("chat"),b(!1)},[g,b]),L=i.useCallback(async re=>{if(!k||!A)return;const Oe=await En(A.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:oe}),Ge=[{synthetic:!0,text:await En(A.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:oe,plan_path:T??""})}];B(!0);try{J();let Je=null,nt=k.path;if(A.target==="worktree"){if(!j)return;const yt=await Xf(k.path,Zf());if(!yt?.id)return;Je=yt.id,nt=yt.path}else{const yt=await r(void 0,k.path,null);if(!yt?.id)return;Je=yt.id,nt=yt.directory??k.path,o(yt.id,ss.getState().agents??[])}if(!Je)return;const gt=Sc.getState();gt.saveSessionModelSelection(Je,re.providerID,re.modelID),re.agent.trim()&&(gt.saveSessionAgentSelection(Je,re.agent),gt.saveAgentModelForSession(Je,re.agent,re.providerID,re.modelID),gt.saveAgentModelVariantForSession(Je,re.agent,re.providerID,re.modelID,re.variant||void 0)),c(Je,nt),await a(Oe,re.providerID,re.modelID,re.agent.trim()||void 0,void 0,void 0,Ge,re.variant||void 0),D(null)}finally{B(!1)}},[j,r,k,o,A,T,J,a,oe,c]),ae=i.useMemo(()=>Im({drafts:Ne,editingDraftId:M,commentText:fe,onTextChange:P,selection:se,isDragging:Ae,fileLabel:H,newWidgetId:"plan-new-comment-input",mapDraftToRange:re=>({start:re.startLine,end:re.endLine}),onSave:Le,onCancel:ye,onEdit:re=>{ve(re),ee({start:re.startLine,end:re.endLine})},onDelete:G}),[fe,G,M,ye,Le,Ae,se,Ne,H,P,ve]);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:X}),te?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:te,children:e("planView.error.saveFailed")}):null]}),T?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(nn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.improvePlanAria"),disabled:!R.trim(),children:s.jsx(I,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(Ft,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(sn,{align:"end",children:[s.jsx(bs,{onClick:()=>D({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(bs,{onClick:()=>D({action:"improve",target:"worktree"}),disabled:!j,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(nn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.implementPlanAria"),disabled:!R.trim(),children:s.jsx(I,{name:"code-ai",className:"size-4"})})})}),s.jsx(Ft,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(sn,{align:"end",children:[s.jsx(bs,{onClick:()=>D({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(bs,{onClick:()=>D({action:"implement",target:"worktree"}),disabled:!j,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(aa,{currentMode:Y,onToggle:()=>Fe(Y==="preview"?"edit":"preview")}),Y==="preview"&&ne&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(V?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{V?F():R.trim()&&z(R)},children:V?s.jsx(I,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:8,children:e(V?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await fr(R)).ok&&(ke(!0),O.current!==null&&window.clearTimeout(O.current),O.current=window.setTimeout(()=>{ke(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:Z?s.jsx(I,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(Rm,{open:A!==null,onOpenChange:re=>{!re&&!N&&D(null)},target:A?.target??"session",projectDirectory:k?.path??null,submitting:N,onConfirm:L}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx($n,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:ue?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:Y==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(en,{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(Po,{content:R,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:De,children:s.jsx(ql,{value:R,onChange:$,readOnly:!1,className:"h-full",extensions:Re,onViewReady:re=>{je.current=re},onViewDestroy:()=>{je.current=null},blockWidgets:ae,highlightLines:se?{start:Math.min(se.start,se.end),end:Math.max(se.start,se.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(re,Oe,qe)=>{if(!(qe instanceof MouseEvent)||qe.button!==0)return!1;qe.preventDefault();const Ge=re.state.doc.lineAt(Oe.from).number;if(se&&!qe.shiftKey&&Math.min(se.start,se.end)===Ge&&Math.max(se.start,se.end)===Ge)return ee(null),W(),Me.current=!1,me.current=null,pe(!1),!0;if(h&&se&&!qe.shiftKey){const Je=Math.min(se.start,se.end,Ge),nt=Math.max(se.start,se.end,Ge);return ee({start:Je,end:nt}),Me.current=!1,me.current=null,pe(!1),!0}if(Me.current=!0,me.current=Ge,pe(!0),se&&qe.shiftKey){const Je=Math.min(se.start,Ge),nt=Math.max(se.end,Ge);ee({start:Je,end:nt})}else ee({start:Ge,end:Ge});return!0},mouseover:(re,Oe,qe)=>{if(!(qe instanceof MouseEvent)||qe.buttons!==1||!Me.current||me.current===null)return!1;const Ge=re.state.doc.lineAt(Oe.from).number,Je=Math.min(me.current,Ge),nt=Math.max(me.current,Ge);return ee({start:Je,end:nt}),pe(!0),!1},mouseup:()=>(Me.current=!1,me.current=null,pe(!1),!1)}}})})})})})})]})},_1=8,Wc=t=>t,nc=t=>{const e=Wc(t).type;return typeof e=="string"?e:""},V1=t=>{const e=Wc(t).tool;return typeof e=="string"?e:""},$1=t=>{const e=Wc(t).text;return typeof e=="string"?e:""},z1=t=>{const e=nc(t);return e==="tool"?V1(t).trim().toLowerCase()||"tool":e||"unknown"},W1=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=z1(n);e.includes(r)||e.push(r)}return e.join(" + ")},U1=(t,e=_1)=>typeof t!="string"?"":t.length<=e?t:t.slice(-e),H1=t=>t.replace(/\s+/g," ").trim(),G1=t=>{for(const n of t)if(nc(n)==="text"){const r=H1($1(n));if(r.length===0)continue;return r}const e=t.filter(n=>nc(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}})},rc={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},ca={user:0,assistant:0,tool:0,other:0},vi=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Il=t=>{const e=t.info.tokens,n=e!==void 0?e:t.parts.find(u=>u.tokens!==void 0)?.tokens;if(typeof n=="number")return{...rc,total:vi(n)};if(!n||typeof n!="object")return rc;const r=n,o=vi(r.input),a=vi(r.output),c=vi(r.reasoning),l=vi(r.cache?.read),d=vi(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""},rr=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+rr(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+rr(n),0):0,J1=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...ca,assistant:rr(n.text)+rr(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:rr(n.input)+rr(n.output)+rr(n.error)+rr(n.call?.input)+rr(n.call?.output)+rr(n.call?.error)+rr(n.raw)+Math.round(rr(n.metadata)*.25)+Math.round(rr(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}},Hu=(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=Oo(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},Z1=(t,e)=>{if(t.length===0)return{...ca};const n=t.reduce((r,o)=>{const a=X1(o);let c={...ca};for(const l of o.parts)c=Hu(c,J1(l,a));return Hu(r,c)},{...ca});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)}},ji=t=>t.toLocaleString(Xi()),e0=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(Xi(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(Xi(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),t0=(t,e)=>!t||!Number.isFinite(t)?"-":Nc(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=ft.c(202),{t:e}=kt(),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),u=ut(i0),m=Dc(),f=jg(u??""),p=ss(o0);let y;t[1]===Symbol.for("react.memo_cache_sentinel")?(y=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(a0),l(null)},t[1]=y):y=t[1];let g;t[2]!==u?(g=[u],t[2]=u,t[3]=g):g=t[3],i.useEffect(y,g);let b,x;t[4]===Symbol.for("react.memo_cache_sentinel")?(b=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},x=[],t[4]=b,t[5]=x):(b=t[4],x=t[5]),i.useEffect(b,x);let h;t[6]===Symbol.for("react.memo_cache_sentinel")?(h=async(vt,bt)=>{(await fr(bt)).ok?(l(vt),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(Wt=>Wt===vt?null:Wt),d.current=null},2e3)):l(null)},t[6]=h):h=t[6];const C=h;let w;t[7]!==u||t[8]!==m?(w=u?m.find(vt=>vt.id===u)??null:null,t[7]=u,t[8]=m,t[9]=w):w=t[9];const v=w;let S,k,j,A,D,N;if(t[10]!==p||t[11]!==f){S=f.filter(l0);let vt;t[18]!==f?(vt=f.filter(c0),t[18]=f,t[19]=vt):vt=t[19],N=vt;let bt=null;for(let Wt=S.length-1;Wt>=0;Wt=Wt-1,Wt){const qt=S[Wt];if(Il(qt).total>0){bt=qt;break}}A=bt?Il(bt):rc,k=Sg({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}),D=S.reduce(d0,0);const ls=bt?.info??null;j=s0(p,ls?.providerID||"",ls?.modelID||""),t[10]=p,t[11]=f,t[12]=S,t[13]=k,t[14]=j,t[15]=A,t[16]=D,t[17]=N}else S=t[12],k=t[13],j=t[14],A=t[15],D=t[16],N=t[17];const B=j,T=B.contextLimit,E=T&&T>0?Math.min(999,A.total/T*100):0;let _;if(t[20]!==f){const vt=[...f].reverse().find(u0)?.info?.system||"";_=Z1(f,vt),t[20]=f,t[21]=_}else _=t[21];const R=_,$=R.user,V=R.assistant,z=R.tool,F=Math.max(0,A.input-$-V-z),ne=$+V+z+F,te=f[0]?.info?.time?.created,q=f.length>0?f[f.length-1]?.info?.time?.created:null;let H;t[22]!==v?.title||t[23]!==e?(H=v?.title||e("contextSidebar.session.untitled"),t[22]=v?.title,t[23]=e,t[24]=H):H=t[24];const X=v?.time?.created??te??null,oe=q??v?.time?.created??null;let ue;t[25]!==V||t[26]!==F||t[27]!==z||t[28]!==$?(ue={user:$,assistant:V,tool:z,other:F},t[25]=V,t[26]=F,t[27]=z,t[28]=$,t[29]=ue):ue=t[29];let Se;t[30]!==S.length||t[31]!==ne||t[32]!==k||t[33]!==T||t[34]!==B||t[35]!==f.length||t[36]!==X||t[37]!==oe||t[38]!==ue||t[39]!==H||t[40]!==A||t[41]!==D||t[42]!==E||t[43]!==N.length?(Se={sessionTitle:H,messagesCount:f.length,userMessagesCount:N.length,assistantMessagesCount:S.length,createdAt:X,lastActivityAt:oe,providerModel:B,tokenBreakdown:A,usagePercent:E,cacheHitRate:k,totalAssistantCost:D,contextLimit:T,breakdown:ue,breakdownTotal:ne},t[30]=S.length,t[31]=ne,t[32]=k,t[33]=T,t[34]=B,t[35]=f.length,t[36]=X,t[37]=oe,t[38]=ue,t[39]=H,t[40]=A,t[41]=D,t[42]=E,t[43]=N.length,t[44]=Se):Se=t[44];const Z=Se;if(!u){let vt;t[45]!==e?(vt=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=vt):vt=t[46];let bt;return t[47]!==vt?(bt=s.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:vt}),t[47]=vt,t[48]=bt):bt=t[48],bt}let ke;t[49]!==e?(ke=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=ke):ke=t[50];let Y;t[51]!==ke||t[52]!==Z.breakdown.user?(Y={key:"user",label:ke,value:Z.breakdown.user,color:"var(--status-success)"},t[51]=ke,t[52]=Z.breakdown.user,t[53]=Y):Y=t[53];let ge;t[54]!==e?(ge=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=ge):ge=t[55];let O;t[56]!==ge||t[57]!==Z.breakdown.assistant?(O={key:"assistant",label:ge,value:Z.breakdown.assistant,color:"var(--primary-base)"},t[56]=ge,t[57]=Z.breakdown.assistant,t[58]=O):O=t[58];let se;t[59]!==e?(se=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=se):se=t[60];let ee;t[61]!==se||t[62]!==Z.breakdown.tool?(ee={key:"tool",label:se,value:Z.breakdown.tool,color:"var(--status-warning)"},t[61]=se,t[62]=Z.breakdown.tool,t[63]=ee):ee=t[63];let je;t[64]!==e?(je=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=je):je=t[65];let De;t[66]!==je||t[67]!==Z.breakdown.other?(De={key:"other",label:je,value:Z.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=je,t[67]=Z.breakdown.other,t[68]=De):De=t[68];let Be;t[69]!==Y||t[70]!==O||t[71]!==ee||t[72]!==De?(Be=[Y,O,ee,De],t[69]=Y,t[70]=O,t[71]=ee,t[72]=De,t[73]=Be):Be=t[73];const Fe=Be;let Me;t[74]!==Z.sessionTitle?(Me=s.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:Z.sessionTitle}),t[74]=Z.sessionTitle,t[75]=Me):Me=t[75];let me;t[76]!==Z.providerModel.modelName||t[77]!==Z.providerModel.providerName?(me=s.jsxs("span",{children:[Z.providerModel.providerName," / ",Z.providerModel.modelName]}),t[76]=Z.providerModel.modelName,t[77]=Z.providerModel.providerName,t[78]=me):me=t[78];let Ae;t[79]!==n||t[80]!==Z.createdAt?(Ae=Z.createdAt&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:t0(Z.createdAt,n)})]}),t[79]=n,t[80]=Z.createdAt,t[81]=Ae):Ae=t[81];let pe;t[82]!==me||t[83]!==Ae?(pe=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:[me,Ae]}),t[82]=me,t[83]=Ae,t[84]=pe):pe=t[84];let ce;t[85]!==Me||t[86]!==pe?(ce=s.jsxs("div",{className:"mb-6",children:[Me,pe]}),t[85]=Me,t[86]=pe,t[87]=ce):ce=t[87];let he;t[88]!==e?(he=e("contextSidebar.section.context"),t[88]=e,t[89]=he):he=t[89];let Ne;t[90]!==he?(Ne=s.jsx("span",{className:"typography-micro text-muted-foreground",children:he}),t[90]=he,t[91]=Ne):Ne=t[91];let fe;t[92]!==Z.tokenBreakdown.total?(fe=ji(Z.tokenBreakdown.total),t[92]=Z.tokenBreakdown.total,t[93]=fe):fe=t[93];let P;t[94]!==Z.contextLimit?(P=Z.contextLimit?` / ${ji(Z.contextLimit)}`:"",t[94]=Z.contextLimit,t[95]=P):P=t[95];let M;t[96]!==fe||t[97]!==P?(M=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[fe,P]}),t[96]=fe,t[97]=P,t[98]=M):M=t[98];let de;t[99]!==Ne||t[100]!==M?(de=s.jsxs("div",{className:"flex items-baseline justify-between",children:[Ne,M]}),t[99]=Ne,t[100]=M,t[101]=de):de=t[101];let xe;t[102]!==Z.usagePercent?(xe=Z.usagePercent>0&&s.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,Z.usagePercent)}%`,backgroundColor:Z.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}}),t[102]=Z.usagePercent,t[103]=xe):xe=t[103];let W;t[104]!==xe?(W=s.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:xe}),t[104]=xe,t[105]=W):W=t[105];let be;t[106]!==e||t[107]!==Z.usagePercent?(be=e("contextSidebar.context.percentUsed",{percent:Z.usagePercent.toFixed(1)}),t[106]=e,t[107]=Z.usagePercent,t[108]=be):be=t[108];let ve;t[109]!==be?(ve=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:be}),t[109]=be,t[110]=ve):ve=t[110];let G;t[111]!==de||t[112]!==W||t[113]!==ve?(G=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[de,W,ve]}),t[111]=de,t[112]=W,t[113]=ve,t[114]=G):G=t[114];let ye;t[115]!==e?(ye=e("contextSidebar.stats.messages"),t[115]=e,t[116]=ye):ye=t[116];let Le;t[117]!==Z.messagesCount?(Le=ji(Z.messagesCount),t[117]=Z.messagesCount,t[118]=Le):Le=t[118];let Re;t[119]!==ye||t[120]!==Le?(Re={label:ye,value:Le},t[119]=ye,t[120]=Le,t[121]=Re):Re=t[121];let J;t[122]!==e?(J=e("contextSidebar.stats.user"),t[122]=e,t[123]=J):J=t[123];let L;t[124]!==Z.userMessagesCount?(L=ji(Z.userMessagesCount),t[124]=Z.userMessagesCount,t[125]=L):L=t[125];let ae;t[126]!==J||t[127]!==L?(ae={label:J,value:L},t[126]=J,t[127]=L,t[128]=ae):ae=t[128];let re;t[129]!==e?(re=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=re):re=t[130];let Oe;t[131]!==Z.assistantMessagesCount?(Oe=ji(Z.assistantMessagesCount),t[131]=Z.assistantMessagesCount,t[132]=Oe):Oe=t[132];let qe;t[133]!==re||t[134]!==Oe?(qe={label:re,value:Oe},t[133]=re,t[134]=Oe,t[135]=qe):qe=t[135];let Ge;t[136]!==e?(Ge=e("contextSidebar.stats.cost"),t[136]=e,t[137]=Ge):Ge=t[137];let Je;t[138]!==Z.totalAssistantCost?(Je=e0(Z.totalAssistantCost),t[138]=Z.totalAssistantCost,t[139]=Je):Je=t[139];let nt;t[140]!==Ge||t[141]!==Je?(nt={label:Ge,value:Je},t[140]=Ge,t[141]=Je,t[142]=nt):nt=t[142];let gt;t[143]!==Re||t[144]!==ae||t[145]!==qe||t[146]!==nt?(gt=[Re,ae,qe,nt],t[143]=Re,t[144]=ae,t[145]=qe,t[146]=nt,t[147]=gt):gt=t[147];const yt=gt;let _e;t[148]!==yt?(_e=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:yt.map(f0)}),t[148]=yt,t[149]=_e):_e=t[149];let Qe;t[150]!==e?(Qe=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Qe):Qe=t[151];let st;t[152]!==Qe?(st=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Qe}),t[152]=Qe,t[153]=st):st=t[153];let wt;t[154]!==e||t[155]!==Z.cacheHitRate.hasInput||t[156]!==Z.cacheHitRate.percent||t[157]!==Z.tokenBreakdown.cacheRead||t[158]!==Z.tokenBreakdown.cacheWrite||t[159]!==Z.tokenBreakdown.input||t[160]!==Z.tokenBreakdown.output||t[161]!==Z.tokenBreakdown.reasoning?(wt=s.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:e("contextSidebar.tokens.input"),value:Z.tokenBreakdown.input,format:"count"},{label:e("contextSidebar.tokens.output"),value:Z.tokenBreakdown.output,format:"count"},{label:e("contextSidebar.tokens.reasoning"),value:Z.tokenBreakdown.reasoning,format:"count"},{label:e("contextSidebar.tokens.cacheRead"),value:Z.tokenBreakdown.cacheRead,format:"count"},{label:e("contextSidebar.tokens.cacheWrite"),value:Z.tokenBreakdown.cacheWrite,format:"count"},{label:e("contextSidebar.tokens.cacheHit"),value:Z.cacheHitRate.hasInput?Z.cacheHitRate.percent:null,format:"percent"}].map(m0)}),t[154]=e,t[155]=Z.cacheHitRate.hasInput,t[156]=Z.cacheHitRate.percent,t[157]=Z.tokenBreakdown.cacheRead,t[158]=Z.tokenBreakdown.cacheWrite,t[159]=Z.tokenBreakdown.input,t[160]=Z.tokenBreakdown.output,t[161]=Z.tokenBreakdown.reasoning,t[162]=wt):wt=t[162];let Ct;t[163]!==st||t[164]!==wt?(Ct=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[st,wt]}),t[163]=st,t[164]=wt,t[165]=Ct):Ct=t[165];let xt;t[166]!==Fe||t[167]!==Z.breakdownTotal?(xt=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:Fe.map(vt=>vt.value<=0||Z.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${vt.value/Z.breakdownTotal*100}%`,backgroundColor:vt.color}},vt.key))}),t[166]=Fe,t[167]=Z.breakdownTotal,t[168]=xt):xt=t[168];let St;t[169]!==Fe||t[170]!==Z.breakdownTotal?(St=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:Fe.map(vt=>{const bt=Z.breakdownTotal>0?vt.value/Z.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:vt.color}}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[vt.label," ",s.jsxs("span",{className:"tabular-nums",children:[bt.toFixed(0),"%"]})]})]},vt.key)})}),t[169]=Fe,t[170]=Z.breakdownTotal,t[171]=St):St=t[171];let Ze;t[172]!==xt||t[173]!==St?(Ze=s.jsxs("div",{className:"mb-6",children:[xt,St]}),t[172]=xt,t[173]=St,t[174]=Ze):Ze=t[174];let Ot;t[175]!==e?(Ot=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=Ot):Ot=t[176];let ns;t[177]!==Ot?(ns=s.jsx("div",{className:"typography-micro text-muted-foreground",children:Ot}),t[177]=Ot,t[178]=ns):ns=t[178];let zt;if(t[179]!==c||t[180]!==o||t[181]!==f||t[182]!==e||t[183]!==n){let vt;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(vt=bt=>{const Wt=Oo(bt.info).role,qt=Wt==="assistant",rs=Wt==="user",Ut=o[bt.info.id]===!0,Bt=c===bt.info.id,_t=bt.info.time?.created??null,Yt=W1(bt.parts),Ht=qt?Il({info:bt.info,parts:bt.parts}):null,Zt=rs?G1(bt.parts):"",ys=U1(bt.info.id),Tt=Y1(_t,n),Vt=Yt||"—",Dt=Ht?K1(Ht.input,Ht.output,ji):"",cs=Wt||"unknown",us=Yt,He=Ut?JSON.stringify({info:bt.info,parts:bt.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":Ut,onClick:()=>{a(Ke=>({...Ke,[bt.info.id]:Ke[bt.info.id]!==!0}))},children:s.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:"auto minmax(0, 1fr) 5rem 4.5rem"},children:[rs?s.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",style:{gridColumn:"span 2"},children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",Zt]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:qt?"min-w-0 truncate text-muted-foreground":"typography-ui-label text-foreground",children:qt?Vt:cs}),s.jsx("span",{className:qt?"text-right text-muted-foreground tabular-nums":"min-w-0 truncate text-muted-foreground",children:qt?Dt:us})]}),s.jsx("span",{className:"text-right font-mono text-muted-foreground",children:ys}),s.jsx("span",{className:"text-right text-muted-foreground",children:Tt})]})}),Ut&&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:Ke=>{Ke.stopPropagation(),C(bt.info.id,He)},"aria-label":e(Bt?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Bt?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Bt?s.jsx(I,{name:"check",className:"size-3.5"}):s.jsx(I,{name:"file-copy",className:"size-3.5"})})}),s.jsx(Ng,{language:"json",code:He,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},bt.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=vt):vt=t[189],zt=[...f].reverse().map(vt),t[179]=c,t[180]=o,t[181]=f,t[182]=e,t[183]=n,t[184]=zt}else zt=t[184];let Ve;t[190]!==zt?(Ve=s.jsx("div",{className:"mt-2.5 space-y-1",children:zt}),t[190]=zt,t[191]=Ve):Ve=t[191];let At;t[192]!==ns||t[193]!==Ve?(At=s.jsxs("div",{children:[ns,Ve]}),t[192]=ns,t[193]=Ve,t[194]=At):At=t[194];let ot;return t[195]!==ce||t[196]!==G||t[197]!==_e||t[198]!==Ct||t[199]!==Ze||t[200]!==At?(ot=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:[ce,G,_e,Ct,Ze,At]})}),t[195]=ce,t[196]=G,t[197]=_e,t[198]=Ct,t[199]=Ze,t[200]=At,t[201]=ot):ot=t[201],ot};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 Oo(t.info).role==="assistant"}function c0(t){return Oo(t.info).isUser}function d0(t,e){const n=vi(e.info.cost);return t+n}function u0(t){return Oo(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)}%`:ji(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"},Gu=t=>!t||typeof t!="object"?!1:Object.values(t).every(e=>typeof e=="string"),Ki=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)&&Gu(e.attributes)&&Gu(e.computedStyle)&&Array.isArray(e.ancestry)},Uc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([y,g])=>`${y}="${g}"`).join(" "),d=r.computedStyle,u=r.bounds,m=r.center,f=a.replace(/[.:]+$/g,""),p=r.ancestry.map(y=>y.selectorPart).join(" > ");return[`${f}:`,`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(u.x)}, y=${Math.round(u.y)}, width=${Math.round(u.width)}, height=${Math.round(u.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(y=>typeof y=="string").join(`
36
- `)},eh=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Hr("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((g,b)=>{o.onload=()=>g(),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),u=document.createElement("canvas");u.width=Math.floor(a*d),u.height=Math.floor(c*d);const m=u.getContext("2d");if(!m)return null;m.scale(d,d),m.drawImage(o,0,0,a,c);const f=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*f),m.fillRect(e.bounds.x*f,e.bounds.y*p,e.bounds.width*f,e.bounds.height*p),m.strokeRect(e.bounds.x*f,e.bounds.y*p,e.bounds.width*f,e.bounds.height*p);const y=await new Promise(g=>u.toBlob(g,"image/jpeg",.82));return y?new File([y],`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)},Hc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((x,h)=>{c.onload=()=>x(),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),f=document.createElement("canvas");f.width=Math.floor(l*m),f.height=Math.floor(d*m);const p=f.getContext("2d");if(!p)return null;p.scale(m,m),p.drawImage(c,0,0,l,d);const y=l/Math.max(1,r||l),g=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*y),p.fillRect(a.bounds.x*y,a.bounds.y*g,a.bounds.width*y,a.bounds.height*g),p.strokeRect(a.bounds.x*y,a.bounds.y*g,a.bounds.width*y,a.bounds.height*g);const b=await new Promise(x=>f.toBlob(x,"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,Gc=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 th(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 sh=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 sh(n)).split(",",2)[1]||""},v0=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},da=(...t)=>{v0()&&console.info("[preview-capture]",...t)},nh=(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}`:"",u=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(n.push({selector:`${l}${d}${u}`,scrollTop:a,scrollLeft:c,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),n.length>=e)break}}catch{}return n},ko="data-oc-fixed-pin",j0=(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(ko,JSON.stringify({top:l.top+n,left:l.left+e,width:l.width,height:l.height})),o.push(c);const d=c.tagName.toLowerCase(),u=typeof c.className=="string"&&c.className?`.${c.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";a.push({selector:`${d}${u}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return da("tagged fixed elements",a),()=>{for(const c of o)try{c.removeAttribute(ko)}catch{}}},S0={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${ko}]`)){let r;try{r=JSON.parse(n.getAttribute(ko)||"")}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(ko)}}},Ui="data-oc-scroll-pin",N0=t=>{const e=[],n=nh(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,u=l.scrollLeft||0;if(d<=0&&u<=0)continue;const m=l!==a&&l!==c;m&&l.setAttribute(Ui,JSON.stringify({top:d,left:u})),e.push({el:l,top:d,left:u,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(Ui)}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(`[${Ui}]`)){let o;try{o=JSON.parse(r.getAttribute(Ui)||"")}catch{r.removeAttribute(Ui);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(Ui)}}},Tl=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await sh(await n.blob()):null}catch{return null}},C0=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=Gc(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=Pl.get(e),o=r??(async()=>{try{const c=await Cs("/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:"",u=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Qn.delete(e),null;const m={proxyBasePath:d,expiresAt:u};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}`:""},rh=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 Tl(n.toString(),"include")??qi;const r=await C0(n),o=r?await Tl(r,"include"):null;return o||(await Tl(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 rh(a,e);r=r.replace(o[0],`url("${c}")`)}return r},Ku=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),ih=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},I0=(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 u=l.getBoundingClientRect();if(u.width<=0||u.height<=0||u.right<0||u.bottom<0||u.left>e||u.top>n)continue;const m=o.getComputedStyle(l);if(m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)continue;const f=m.getPropertyValue("text-wrap"),p=m.getPropertyValue("text-wrap-mode"),y=m.whiteSpace.includes("nowrap")||f==="nowrap"||p==="nowrap",g=u.height<=D0(m)*1.7;!y&&(!g||u.width>e*.72)||(r.push(ih(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(u=>{const m=a.getComputedStyle(u);if(m.position!=="fixed"||m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)return!1;const f=u.getBoundingClientRect();return f.width>0&&f.height>0&&f.right>=0&&f.bottom>=0&&f.left<=e&&f.top<=n}).filter((u,m,f)=>!f.some((p,y)=>y<m&&p.contains(u)));for(const u of d){const m=u.getBoundingClientRect(),f=a.getComputedStyle(u),p=Math.ceil(m.width)+8,y=Math.ceil(m.height)+2;r?.add(u),o.push(ih(u)),u.style.position="absolute",u.style.top=`${m.top+l}px`,u.style.left=`${m.left+c}px`,u.style.right="auto",u.style.bottom="auto",u.style.width=`${p}px`,u.style.minWidth=`${p}px`,u.style.height=`${y}px`,u.style.minHeight=`${y}px`,u.style.margin="0",u.style.boxSizing="border-box",u.style.transform="none",f.zIndex!=="auto"&&(u.style.zIndex=f.zIndex)}return()=>{for(let u=o.length-1;u>=0;u-=1)o[u]?.()}},oh=async(t,e,n,r={})=>{const o=[],a=t.defaultView??window,c=f=>{if(f===t.documentElement||f===t.body)return!0;try{const p=f.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 f=new WeakSet;o.push(P0(t,e,n,f)),o.push(I0(t,e,n))}const l=new Map;for(const f of Array.from(t.images))l.set(f,f.currentSrc||f.src||f.getAttribute("src")||"");const d=Array.from(t.querySelectorAll("picture"));for(const f of d){const p=Array.from(f.querySelectorAll("source"));if(p.length===0)continue;const y=p.map(g=>({source:g,srcset:g.getAttribute("srcset"),sizes:g.getAttribute("sizes")}));o.push(()=>{for(const g of y)g.srcset===null?g.source.removeAttribute("srcset"):g.source.setAttribute("srcset",g.srcset),g.sizes===null?g.source.removeAttribute("sizes"):g.source.setAttribute("sizes",g.sizes)});for(const g of p)g.removeAttribute("srcset"),g.removeAttribute("sizes")}const u=Array.from(t.images).filter(f=>c(f));await Promise.all(u.map(async f=>{const p=l.get(f)||f.currentSrc||f.src||f.getAttribute("src")||"";if(!p)return;await Ku(f);const y=await rh(p,t),g={src:f.getAttribute("src"),srcset:f.getAttribute("srcset"),sizes:f.getAttribute("sizes")};o.push(()=>{g.src===null?f.removeAttribute("src"):f.setAttribute("src",g.src),g.srcset===null?f.removeAttribute("srcset"):f.setAttribute("srcset",g.srcset),g.sizes===null?f.removeAttribute("sizes"):f.setAttribute("sizes",g.sizes)}),f.removeAttribute("srcset"),f.removeAttribute("sizes"),f.setAttribute("src",y||qi),await Ku(f)}));const m=Array.from(t.querySelectorAll("*")).filter(c);return await Promise.all(m.map(async f=>{const p=a.getComputedStyle(f).backgroundImage;if(!p||p==="none"||!p.includes("url("))return;const y=await A0(p,t);if(y===p)return;const g=f.style.backgroundImage;o.push(()=>{f.style.backgroundImage=g}),f.style.backgroundImage=y})),()=>{for(let f=o.length-1;f>=0;f-=1)try{o[f]?.()}catch{}}};async function T0(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,u=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,m=n.scrollX||0,f=n.scrollY||0,p=n.pageXOffset||0,y=n.pageYOffset||0,g=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,b=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,x=o.scrollLeft||0,h=o.scrollTop||0,C=d?.scrollLeft||0,w=d?.scrollTop||0,v=u?.scrollLeft||0,S=u?.scrollTop||0,k=Math.max(m,p,g,x,C,v),j=Math.max(f,y,b,h,w,S);da("scroll sources",{windowScrollX:m,windowScrollY:f,pageScrollX:p,pageScrollY:y,visualViewportScrollX:g,visualViewportScrollY:b,rootScrollX:x,rootScrollY:h,bodyScrollX:C,bodyScrollY:w,scrollingElementScrollX:v,scrollingElementScrollY:S,scrollingElementTag:u?.tagName?.toLowerCase()??null,resolvedScrollX:k,resolvedScrollY:j,nestedScrolledElements:nh(r)});const A=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),D=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),N=Math.min(2,Math.max(1,window.devicePixelRatio||1)),B=o.style.scrollBehavior,T=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const E=N0(r);da("nested scroll snapshot",E.snapshot);let _=()=>{},R=()=>{};try{await r.fonts?.ready.catch(()=>{}),_=await oh(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(k,j),R=j0(r,k,j),E.reapply();const $={backgroundColor:th(r),cache:"disabled",dpr:N,embedFonts:!0,fast:!1,height:D,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[S0,k0],quality:.82,width:A},z=await(await Qh(o,$)).toCanvas();if(!z.width||!z.height)return null;const F=z.width/Math.max(1,A),ne=z.height/Math.max(1,D),te=Math.min(z.width,Math.max(1,Math.round(c*F))),q=Math.min(z.height,Math.max(1,Math.round(l*ne))),H=Math.max(0,z.width-te),X=Math.max(0,z.height-q),oe=Math.min(H,Math.max(0,Math.round(k*F))),ue=Math.min(X,Math.max(0,Math.round(j*ne)));da("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:A,captureHeight:D,canvasWidth:z.width,canvasHeight:z.height,xScale:F,yScale:ne,sourceX:oe,sourceY:ue,sourceWidth:te,sourceHeight:q});const Se=r.createElement("canvas");Se.width=te,Se.height=q;const Z=Se.getContext("2d");if(!Z)return null;Z.drawImage(z,oe,ue,te,q,0,0,te,q);const ke=await w0(Se,.82);return ke?await Hc(ke,c,l,c,l,e):null}finally{R(),E.cleanup(),_(),n.scrollTo(k,j),E.reapply(),o.style.scrollBehavior=B,d&&(d.style.scrollBehavior=T)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function R0(t,e){const n=await T0(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)),u=r.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,m=r.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,f=o.body,p=Math.max(d,a.scrollHeight||0,f?.scrollHeight||0),y=Math.min(2,Math.max(1,window.devicePixelRatio||1)),g=a.style.scrollBehavior,b=f?.style.scrollBehavior??"";a.style.scrollBehavior="auto",f&&(f.style.scrollBehavior="auto");let x="",h=()=>{};try{await o.fonts?.ready.catch(()=>{}),h=await oh(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(u,m);const w=await qh(a).catch(()=>"");x=await Yh(a,{quality:.82,pixelRatio:y,width:l,height:d,backgroundColor:th(o),imagePlaceholder:qi,fontEmbedCSS:w||void 0,style:{transform:`translate(${-u}px, ${-m}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${p}px`},cacheBust:!0})}finally{h(),r.scrollTo(u,m),a.style.scrollBehavior=g,f&&(f.style.scrollBehavior=b)}const C=x.split(",",2)[1]||"";return C?await Hc(C,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const ah=380,E0=1400,lh=600,M0=24,Ea=new Map,qu=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",L0=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},ch=t=>Number.isFinite(t)?Math.min(E0,Math.max(ah,Math.round(t))):lh,O0=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},Rl=(t,e)=>{const n=ch(t),r=O0(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},_0=(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"),V0=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=ua(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 V0(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"):_0(t.mode,n)},z0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(Gr,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(I,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(I,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(I,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(I,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(I,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(I,{name:"global",className:"h-3.5 w-3.5"})},ua=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 Ea;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?Ea:r},H0=(t,e)=>{const n=im(t),r=i.useRef(Ea),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]),()=>Ea)},dh=`new Promise((resolve) => {
37
- const existing = document.getElementById('__openchamber_desktop_browser_overlay');
38
- if (existing) existing.remove();
39
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
40
- try { window.__openchamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
41
- }
42
- const overlay = document.createElement('div');
43
- overlay.id = '__openchamber_desktop_browser_overlay';
44
- overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
45
- document.documentElement.appendChild(overlay);
46
- const cssEscape = (value) => {
47
- try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
48
- };
49
- const selectorPart = (element) => {
50
- const tag = element.tagName.toLowerCase();
51
- if (element.id) return tag + '#' + cssEscape(element.id);
52
- const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
53
- return tag + className;
54
- };
55
- const metadata = (element) => {
56
- const rect = element.getBoundingClientRect();
57
- const style = getComputedStyle(element);
58
- const ancestry = [];
59
- let current = element;
60
- while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
61
- ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
62
- current = current.parentElement;
63
- }
64
- const attrs = {};
65
- for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
66
- const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
67
- return {
68
- frame: 'top',
69
- tag: element.tagName.toLowerCase(),
70
- text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
71
- selector: element.id ? '#' + cssEscape(element.id) : path,
72
- path,
73
- bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
74
- center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
75
- attributes: attrs,
76
- computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
77
- ancestry,
78
- };
79
- };
80
- const move = (event) => {
81
- const element = document.elementFromPoint(event.clientX, event.clientY);
82
- if (!element || element === overlay || element === document.documentElement || element === document.body) return;
83
- const rect = element.getBoundingClientRect();
84
- overlay.style.display = 'block';
85
- overlay.style.left = rect.left + 'px';
86
- overlay.style.top = rect.top + 'px';
87
- overlay.style.width = rect.width + 'px';
88
- overlay.style.height = rect.height + 'px';
89
- };
90
- const cleanup = () => {
91
- window.removeEventListener('mousemove', move, true);
92
- window.removeEventListener('click', click, true);
93
- window.removeEventListener('keydown', keydown, true);
94
- if (window.__openchamberDesktopBrowserCancelInspect === cancel) {
95
- delete window.__openchamberDesktopBrowserCancelInspect;
96
- }
97
- };
98
- const cancel = () => {
99
- cleanup();
100
- overlay.remove();
101
- resolve(null);
102
- };
103
- const click = (event) => {
104
- event.preventDefault();
105
- event.stopPropagation();
106
- const element = document.elementFromPoint(event.clientX, event.clientY);
107
- const result = element ? metadata(element) : null;
108
- cleanup();
109
- overlay.remove();
110
- resolve(result);
111
- };
112
- const keydown = (event) => {
113
- if (event.key !== 'Escape') return;
114
- cancel();
115
- };
116
- window.__openchamberDesktopBrowserCancelInspect = cancel;
117
- window.addEventListener('mousemove', move, true);
118
- window.addEventListener('click', click, true);
119
- window.addEventListener('keydown', keydown, true);
120
- });`,fa=`(() => {
121
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
122
- window.__openchamberDesktopBrowserCancelInspect();
123
- return;
124
- }
125
- const overlay = document.getElementById('__openchamber_desktop_browser_overlay');
126
- if (overlay) overlay.remove();
127
- })()`,G0=`(() => {
128
- if (window.__openchamberSameWebviewNavigationInstalled) return;
129
- window.__openchamberSameWebviewNavigationInstalled = true;
130
-
131
- const navigate = (rawUrl) => {
132
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
133
- try {
134
- const url = new URL(rawUrl, window.location.href);
135
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
136
- window.location.assign(url.href);
137
- return true;
138
- } catch (_error) {
139
- return false;
140
- }
141
- };
142
-
143
- const originalOpen = window.open.bind(window);
144
- window.open = (url, target, features) => {
145
- if (navigate(url)) return null;
146
- return originalOpen(url, target, features);
147
- };
148
-
149
- document.addEventListener('click', (event) => {
150
- if (event.defaultPrevented) return;
151
- const target = event.target;
152
- if (!(target instanceof Element)) return;
153
- const anchor = target.closest('a[target="_blank"][href]');
154
- if (!(anchor instanceof HTMLAnchorElement)) return;
155
- if (!navigate(anchor.href)) return;
156
- event.preventDefault();
157
- event.stopPropagation();
158
- }, true);
159
- })()`,Co=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"}},Yu=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)}...`,uh=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Qu=(t,e,n)=>{const r=uh(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}},Ju=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}=kt(),{currentTheme:r}=qr(),[o,a]=i.useReducer(me=>me+1,0),[c,l]=i.useReducer(me=>me+1,0),[d,u]=i.useState({status:"idle"}),[m,f]=i.useState(""),p=i.useRef(null),y=i.useRef(1),[g,b]=i.useState(!1),[x,h]=i.useState(!1),[C,w]=i.useState("all"),[v,S]=i.useState([]),[k,j]=i.useState(!1),[A,D]=i.useState(null),N=ut(me=>me.currentSessionId),B=ut(me=>me.newSessionDraft?.open),T=Ic(me=>me.addDraft),E=ci(me=>me.addAttachedFile);let _=null;try{_=t?new URL(t):null}catch{_=null}const R=_?_.hostname==="localhost"||_.hostname==="127.0.0.1"||_.hostname==="::1"||_.hostname==="[::1]"||_.hostname==="0.0.0.0":!1,$=_?_.hostname==="0.0.0.0"?new URL(_.toString().replace("0.0.0.0","127.0.0.1")):_:null,V=$?$.toString():"",z=V?`${Ur()||"same-origin"}|${V}`:"",F=r.metadata.variant;i.useEffect(()=>{if(!V||!R){u({status:"idle"});return}const me=Gc(z);if(me?.previewToken){u({status:"ready",proxyBasePath:me.proxyBasePath,previewToken:me.previewToken,expiresAt:me.expiresAt});return}me&&Qn.delete(z);let Ae=!1;return u({status:"loading"}),(async()=>{try{const pe=await Cs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:V})});if(!pe.ok){Qn.delete(z);const P=await pe.json().catch(()=>({})),M=typeof P?.error=="string"?P.error:`HTTP ${pe.status}`;Ae||u({status:"error",message:M});return}const ce=await pe.json(),he=typeof ce.proxyBasePath=="string"?ce.proxyBasePath:"",Ne=typeof ce.previewToken=="string"?ce.previewToken:"",fe=typeof ce.expiresAt=="number"?ce.expiresAt:0;if(!he||!Ne){Qn.delete(z),Ae||u({status:"error",message:n("contextPanel.preview.proxyError")});return}Qn.set(z,{proxyBasePath:he,previewToken:Ne,expiresAt:fe}),Ae||u({status:"ready",proxyBasePath:he,previewToken:Ne,expiresAt:fe})}catch(pe){if(Qn.delete(z),!Ae){const ce=pe instanceof Error?pe.message:String(pe);u({status:"error",message:ce})}}})(),()=>{Ae=!0}},[R,z,c,n,V]);const ne=$&&($.protocol==="http:"||$.protocol==="https:")?$.toString():"",te=R&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!te){f("");return}let me=!1;return f(""),gc(Ur()).then(Ae=>{!me&&Ae&&f(te)}).catch(()=>{}),()=>{me=!0}},[te]);const q=R&&d.status==="ready"&&$&&m===te?(()=>{const me=$.pathname||"/",Ae=new URLSearchParams($.search);Ae.delete("oc_url_token"),Ae.delete("oc_client_token"),Ae.set("ocPreview",String(o)),Ae.set("oc_preview_token",d.previewToken||"");const pe=Ae.toString(),ce=$.hash||"";return ki().authenticatedAsset(`${d.proxyBasePath}${me}${pe?`?${pe}`:""}${ce}`)})():"",H=R?q:ne,X=R?q0(q):ne,oe=R&&(d.status==="loading"||d.status==="idle"||m!==te),ue=R&&d.status==="error",Se=i.useCallback(me=>{const Ae=N??(B?"draft":null);if(!Ae){le.error(n("contextPanel.preview.inspect.attachNoSession"));return}const pe=t||H||"",ce=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},he=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let Ne=!1;try{const fe=p.current,P=fe?await eh(fe,me):null;P&&(await E(P),Ne=!0)}catch{Ne=!1}T({sessionKey:Ae,source:"preview-annotation",fileLabel:pe||"preview",startLine:1,endLine:1,code:Uc({pageUrl:pe,viewport:ce,devicePixelRatio:he,target:me,screenshotAttached:Ne,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),le.success(n("contextPanel.preview.inspect.attached"))})()},[E,T,N,H,B,t,n]);i.useEffect(()=>{b(!1),S([]),h(!1),w("all"),j(!1),D(null),y.current=1},[H]),i.useEffect(()=>{const me=p.current?.contentWindow;!g||!me||Qu(me,q,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[g,k,q]),i.useEffect(()=>{const me=p.current?.contentWindow;!g||!me||Qu(me,q,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:F})},[g,F,q]),i.useEffect(()=>{if(!k||typeof window>"u")return;const me=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopImmediatePropagation(),j(!1))};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[k]),i.useEffect(()=>{if(!R||typeof window>"u")return;const me=ce=>{if(typeof ce=="string")return ce;if(ce==null)return"";try{return JSON.stringify(ce)}catch{return String(ce)}},Ae=ce=>{const he=y.current;y.current+=1,S(Ne=>{const fe=[...Ne,{...ce,id:he}];return fe.length>qu?fe.slice(fe.length-qu):fe})},pe=ce=>{if(ce.source!==p.current?.contentWindow)return;const he=ce.data;if(!(!he||he.source!=="openchamber-preview-bridge"||he.version!==1)){if(he.type==="ready"){b(!0);return}if(he.type==="console"){const Ne=he.level==="error"||he.level==="warn"||he.level==="info"||he.level==="debug"?he.level:"log",fe=Array.isArray(he.args)?he.args.map(me).filter(Boolean):[];Ae({level:Ne,message:fe.join(" "),ts:typeof he.ts=="number"?he.ts:Date.now()});return}if(he.type==="runtime-error"){const Ne=me(he.filename),fe=typeof he.line=="number"?he.line:null,P=typeof he.column=="number"?he.column:null,M=Ne?`${Ne}${fe!==null?`:${fe}${P!==null?`:${P}`:""}`:""}`:"",de=me(he.stack);Ae({level:"runtime",message:me(he.message)||n("contextPanel.preview.console.runtimeError"),details:[M,de].filter(Boolean).join(`
160
- `),ts:typeof he.ts=="number"?he.ts:Date.now()});return}if(he.type==="resource-error"){const Ne=me(he.tag)||"resource",fe=me(he.url);Ae({level:"resource",message:fe?`${Ne}: ${fe}`:Ne,details:me(he.outerHTML),ts:typeof he.ts=="number"?he.ts:Date.now()});return}if(he.type==="hover"){D(Ki(he.target)?he.target:null);return}if(he.type==="select"&&Ki(he.target)){D(he.target),j(!1),Se(he.target);return}if(he.type==="navigate-preview"){const Ne=typeof he.url=="string"?he.url:"",fe=he.navigation==="external"?"external":"proxy";if(Ne&&fe==="external"){Di(Ne);return}Ne&&e(Ne)}}};return window.addEventListener("message",pe),()=>{window.removeEventListener("message",pe)}},[Se,R,e,n]);const Z=v.filter(me=>me.level==="error"||me.level==="runtime"||me.level==="resource").length,ke=v.filter(me=>F0(me,C)),Y=i.useCallback(()=>{const me=[`Preview URL: ${t||H||""}`,`Events: ${v.length}`,""].join(`
161
- `),Ae=v.map(pe=>{const ce=new Date(pe.ts).toISOString(),he=pe.details?`
162
- ${pe.details}`:"";return`[${ce}] [${pe.level}] ${pe.message}${he}`}).join(`
163
- `);fr(`${me}${Ae}`).then(pe=>{pe.ok?le.success(n("contextPanel.preview.console.copied")):le.error(n("contextPanel.preview.console.copyFailed"))})},[v,H,t,n]),ge=i.useCallback(()=>{const me=N??(B?"draft":null);if(!me){le.error(n("contextPanel.preview.console.attachNoSession"));return}const Ae=[`Preview URL: ${t||H||""}`,`Events: ${v.length}`,""].join(`
164
- `),pe=v.map(ce=>{const he=new Date(ce.ts).toISOString(),Ne=ce.details?`
165
- ${ce.details}`:"";return`[${he}] [${ce.level}] ${ce.message}${Ne}`}).join(`
166
- `);T({sessionKey:me,source:"preview-console",fileLabel:t||H||"preview",startLine:1,endLine:Math.max(1,v.length),code:`${Ae}${pe}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),le.success(n("contextPanel.preview.console.attached"))},[T,v,N,H,B,t,n]),[O,se]=i.useState("unknown"),ee=i.useRef(0),je=i.useRef(0),De=15e3;i.useEffect(()=>{if(!q){se("unknown"),ee.current=0,je.current=0;return}let me=!1;return ee.current||(ee.current=Date.now(),je.current=0),se("unknown"),(async()=>{const pe=await(async()=>{try{return await Cs(q,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(me)return;if(!pe){se("unreachable");return}if(pe.status===403||pe.status===404){Qn.delete(z),u({status:"loading"}),l();return}if(pe.status!==502){se("reachable");return}const ce=ee.current||Date.now();if(Date.now()-ce<De){se("starting"),je.current+=1;const Ne=je.current,fe=Math.min(2e3,250*Math.pow(2,Math.min(4,Ne)));setTimeout(()=>{me||a()},fe).unref?.();return}se("unreachable")})(),()=>{me=!0}},[z,q,o]);const Be=R&&d.status==="ready"&&(O==="unknown"||O==="starting"),Fe=R&&d.status==="ready"&&O==="unreachable",Me=i.useCallback(me=>{if(!R||d.status!=="ready"||typeof window>"u")return;const Ae=me.currentTarget.contentWindow;if(Ae)try{const pe=Ae.location,ce=uh(q);if(pe.origin!==ce||pe.pathname.startsWith(d.proxyBasePath))return;const he=`${d.proxyBasePath}${pe.pathname}${pe.search}${pe.hash}`;Ae.location.replace(he)}catch{}},[R,q,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:X||t,children:X||t||n("contextPanel.preview.empty")}),s.jsx($e,{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:!H,children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ne&&Di(ne)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!ne,children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})}),R?s.jsx($e,{type:"button",size:"sm",variant:k?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>j(me=>!me),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!g,children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}):null,R?s.jsxs($e,{type:"button",size:"sm",variant:x?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>h(me=>!me),title:n(g?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),"aria-label":n(g?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),disabled:!g&&v.length===0,children:[s.jsx(I,{name:"terminal-box",className:"h-3.5 w-3.5"}),Z>0?s.jsx("span",{className:"typography-micro text-status-error",children:Z}):null]}):null]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[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.startingServer")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.startingServerHint")})]}):Fe?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.upstreamUnreachable")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.upstreamUnreachableHint")}),s.jsx($e,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:n("contextPanel.preview.actions.retry")})]}):H&&(!R||O==="reachable")?s.jsxs("div",{className:"relative h-full w-full",children:[s.jsx("iframe",{ref:p,src:H,title:n("contextPanel.preview.iframeTitle"),className:"h-full w-full border-0",style:{colorScheme:F},onLoad:Me,sandbox:R?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${H}:${o}`),k&&A?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:A.bounds.x,top:A.bounds.y,width:A.bounds.width,height:A.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[A.tag,A.text?` · ${A.text}`:""]})}):null]}):oe?s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.loading")}):ue?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")}),x?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($e,{type:"button",size:"xs",variant:"ghost",onClick:ge,disabled:v.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:Y,disabled:v.length===0,children:n("contextPanel.preview.console.copy")}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:()=>S([]),disabled:v.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(me=>s.jsx($e,{type:"button",size:"xs",variant:C===me?"secondary":"ghost",onClick:()=>w(me),children:n(me==="all"?"contextPanel.preview.console.filter.all":me==="errors"?"contextPanel.preview.console.filter.errors":me==="warnings"?"contextPanel.preview.console.filter.warnings":"contextPanel.preview.console.filter.logs")},me))}),s.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:v.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.empty")}):ke.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):ke.map(me=>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:Pe("shrink-0 uppercase",me.level==="error"||me.level==="runtime"||me.level==="resource"?"text-status-error":me.level==="warn"?"text-status-warning":"text-muted-foreground"),children:me.level}),s.jsx("span",{className:"min-w-0 break-words text-foreground",children:me.message})]})},me.id))})]}):null]})]})},Q0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,J0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=kt(),o=i.useRef(null),a=Ee(Y=>Y.setContextPanelTabTargetPath),c=Co(t),l=c!=="about:blank"?c:"",[d,u]=i.useState(l),[m,f]=i.useState(l),[p,y]=i.useState(()=>l?[l]:[]),[g,b]=i.useState(()=>l?0:-1),[x,h]=i.useReducer(Y=>Y+1,0),[C,w]=i.useState(!!l),[v,S]=i.useState(!1),[k,j]=i.useState(null),[A,D]=i.useState({status:"idle"}),[N,B]=i.useState(""),T=ut(Y=>Y.currentSessionId),E=ut(Y=>Y.newSessionDraft?.open),_=Ic(Y=>Y.addDraft),R=ci(Y=>Y.addAttachedFile),$=i.useCallback(Y=>{!Y||Y==="about:blank"||!e||!n||a(e,n,Y)},[e,n,a]),V=i.useCallback((Y,ge)=>{const O=Co(Y),se=O!=="about:blank"?O:"";f(se),u(se),w(!!se),$(se),y(ee=>{if(!se)return b(-1),[];if(ge?.replaceHistory)return ee;const je=g>=0?ee.slice(0,g+1):[];if(je[je.length-1]===se)return b(je.length-1),je;const Be=[...je,se];return b(Be.length-1),Be})},[g,$]),z=i.useCallback(Y=>{const ge=p[Y];ge&&(b(Y),f(ge),u(ge),w(!0),$(ge))},[p,$]),F=i.useCallback(()=>{if(m){w(!0);try{o.current?.contentWindow?.location.reload()}catch{h()}}},[m]);i.useEffect(()=>{if(!m){D({status:"idle"});return}const Y=y0(m),ge=Gc(Y);if(ge?.previewToken){D({status:"ready",proxyBasePath:ge.proxyBasePath,previewToken:ge.previewToken,expiresAt:ge.expiresAt});return}ge&&Qn.delete(Y);let O=!1;return D({status:"loading"}),w(!0),(async()=>{try{const se=await Cs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:m,allowExternal:!0})});if(!se.ok){const Fe=await se.json().catch(()=>({})),Me=typeof Fe?.error=="string"?Fe.error:`HTTP ${se.status}`;O||D({status:"error",message:Me});return}const ee=await se.json(),je=typeof ee.proxyBasePath=="string"?ee.proxyBasePath:"",De=typeof ee.previewToken=="string"?ee.previewToken:"",Be=typeof ee.expiresAt=="number"?ee.expiresAt:0;if(!je||!De){O||D({status:"error",message:r("contextPanel.preview.proxyError")});return}Qn.set(Y,{proxyBasePath:je,previewToken:De,expiresAt:Be}),O||D({status:"ready",proxyBasePath:je,previewToken:De,expiresAt:Be})}catch(se){if(!O){const ee=se instanceof Error?se.message:String(se);D({status:"error",message:ee})}}})(),()=>{O=!0}},[m,r]);const ne=m&&A.status==="ready"?`${A.proxyBasePath}|${A.previewToken||""}|${x}`:"";i.useEffect(()=>{if(!ne){B("");return}let Y=!1;return B(""),gc(Ur()).then(ge=>{!Y&&ge&&B(ne)}).catch(()=>{}),()=>{Y=!0}},[ne]);const te=i.useMemo(()=>{if(N!==ne||!m||A.status!=="ready")return"";try{const Y=new URL(m),ge=Y.pathname||"/",O=new URLSearchParams(Y.search);O.delete("oc_url_token"),O.delete("oc_client_token"),O.set("ocPreview",String(x)),O.set("oc_preview_token",A.previewToken||"");const se=O.toString();return ki().authenticatedAsset(`${A.proxyBasePath}${ge}${se?`?${se}`:""}${Y.hash}`)}catch{return""}},[m,A,ne,x,N]),q=te||(A.status==="error"?m:""),H=i.useCallback(Y=>{if(!Y||!m||A.status!=="ready")return"";try{const ge=new URL(Y,window.location.origin),O=A.proxyBasePath.endsWith("/")?A.proxyBasePath.slice(0,-1):A.proxyBasePath;if(ge.origin!==window.location.origin||!ge.pathname.startsWith(O))return"";const se=ge.pathname.slice(O.length)||"/",ee=new URL(m).origin;return Ju(new URL(`${se}${ge.search}${ge.hash}`,ee).toString())}catch{return""}},[m,A]),X=i.useCallback(Y=>{if(!Y||!m||A.status!=="ready")return"";try{const ge=new URL(Y,window.location.origin),O=new URL(m).origin;if(ge.origin!==window.location.origin||O===window.location.origin)return"";const se=A.proxyBasePath.endsWith("/")?A.proxyBasePath.slice(0,-1):A.proxyBasePath;return ge.pathname.startsWith(se)?"":Ju(new URL(`${ge.pathname}${ge.search}${ge.hash}`,O).toString())}catch{return""}},[m,A]),oe=i.useCallback(Y=>{const ge=o.current?.contentWindow;ge&&ge.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:Y},window.location.origin)},[]),ue=i.useCallback(async Y=>{const ge=T??(E?"draft":null);if(!ge){le.error(r("contextPanel.preview.inspect.attachNoSession"));return}const O=o.current,se=O?.contentWindow,ee=O?.getBoundingClientRect(),je={width:Number.isFinite(se?.innerWidth)?se?.innerWidth??ee?.width??0:ee?.width??0,height:Number.isFinite(se?.innerHeight)?se?.innerHeight??ee?.height??0:ee?.height??0},De=O?await eh(O,Y):null,Be=!!De;De&&await R(De),_({sessionKey:ge,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Uc({pageUrl:m,viewport:je,devicePixelRatio:window.devicePixelRatio||1,target:Y,screenshotAttached:Be,intro:r(Be?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),le.success(r("contextPanel.preview.inspect.attached"))},[R,_,T,m,E,r]),Se=i.useCallback(()=>{const Y=o.current;j(null),oe(!1),Y&&Yu(Y,fa).catch(()=>{})},[oe]);i.useEffect(()=>{if(!v)return;const Y=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ge.stopImmediatePropagation(),S(!1),Se())};return window.addEventListener("keydown",Y,!0),()=>window.removeEventListener("keydown",Y,!0)},[Se,v]),i.useEffect(()=>()=>Se(),[Se]),i.useEffect(()=>{const Y=ge=>{if(ge.source!==o.current?.contentWindow)return;const O=ge.data;if(!(!O||O.source!=="openchamber-preview-bridge"||O.version!==1)){if(O.type==="ready"){const se=typeof O.url=="string"?O.url:"",ee=H(se);ee&&ee!==m&&V(ee);return}if(O.type==="hover"){j(Ki(O.target)?O.target:null);return}if(O.type==="select"&&Ki(O.target)){j(null),S(!1),oe(!1),ue(O.target);return}if(O.type==="navigate-preview"){const se=typeof O.url=="string"?O.url:"",ee=X(se);if(ee){V(ee);return}se&&V(se)}}};return window.addEventListener("message",Y),()=>window.removeEventListener("message",Y)},[V,ue,m,H,X,oe]);const Z=i.useCallback(()=>{const Y=o.current;if(!(!Y||!m)){if(v){S(!1),Se();return}if(te){j(null),S(!0),oe(!0);return}S(!0),(async()=>{try{const ge=await Yu(Y,dh);if(S(!1),!ge||!Ki(ge))return;await ue(ge)}catch{S(!1),le.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[ue,Se,m,v,oe,te,r]),ke=i.useCallback(()=>{try{const Y=o.current?.contentWindow?.location.href||"",ge=X(Y);if(ge){w(!0),V(ge);return}}catch{}w(!1),v&&te&&oe(!0)},[V,X,v,oe,te]);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($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:g<=0,onClick:()=>z(g-1),children:s.jsx(I,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:g<0||g>=p.length-1,onClick:()=>z(g+1),children:s.jsx(I,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:F,children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:Y=>{Y.preventDefault(),V(d)},children:s.jsx("input",{value:d,onChange:Y=>u(Y.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($e,{type:"button",variant:v?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:Z,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:()=>{Di(m)},children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[q?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:q,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:ke},`${q}:${x}`),v&&k?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:k.bounds.x,top:k.bounds.y,width:k.bounds.width,height:k.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:[k.tag,k.text?` · ${k.text}`:""]})}):null]}):s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(Pc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")}),s.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:r("contextPanel.browser.emptyHint")}),s.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:r("contextPanel.browser.trustNotice")})]}),C?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},X0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=kt(),o=i.useRef(null),a=Ee(D=>D.setContextPanelTabTargetPath),c=Co(t),l=c!=="about:blank"?c:"",[d,u]=i.useState(l),[m,f]=i.useState(l),[p,y]=i.useState(!1),[g,b]=i.useState(!0),x=i.useRef(null),h=g,C=i.useCallback(D=>{!D||D==="about:blank"||!e||!n||a(e,n,D)},[e,n,a]),w=ut(D=>D.currentSessionId),v=ut(D=>D.newSessionDraft?.open),S=Ic(D=>D.addDraft),k=ci(D=>D.addAttachedFile);i.useEffect(()=>{const D=o.current;if(!D)return;const N=()=>{try{const $=D.getURL();$&&$!=="about:blank"&&(f($),u($),C($))}catch{}},B=$=>{const V=$.detail;typeof V?.url=="string"&&V.url&&(f(V.url),u(V.url),C(V.url))},T=()=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>b(!0),200)},E=()=>{x.current&&clearTimeout(x.current),b(!1),N()},_=$=>{const V=$.detail;if(V?.disposition==="new-window"||V?.disposition==="foreground-tab"||V?.disposition==="background-tab"){$.preventDefault();const z=o.current;typeof z?.loadURL=="function"&&V.url&&z.loadURL(V.url)}},R=()=>{try{D.executeJavaScript?.(G0,!0).catch(()=>{})}catch{}};D.addEventListener("did-navigate",B),D.addEventListener("did-navigate-in-page",B),D.addEventListener("did-start-loading",T),D.addEventListener("did-stop-loading",E),D.addEventListener("new-window",_),D.addEventListener("dom-ready",R);try{D.isLoading()||(b(!1),N())}catch{}return R(),()=>{x.current&&clearTimeout(x.current),D.removeEventListener("did-navigate",B),D.removeEventListener("did-navigate-in-page",B),D.removeEventListener("did-start-loading",T),D.removeEventListener("did-stop-loading",E),D.removeEventListener("new-window",_),D.removeEventListener("dom-ready",R)}},[C]),i.useEffect(()=>{const D=setTimeout(()=>b(!1),3e4);return()=>clearTimeout(D)},[]),i.useEffect(()=>{if(!p)return;const D=N=>{if(N.key!=="Escape")return;N.preventDefault(),N.stopImmediatePropagation(),y(!1);const B=o.current;try{B?.executeJavaScript?.(fa).catch(()=>{})}catch{}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[p]),i.useEffect(()=>{const D=o.current;return()=>{try{const N=D?.getURL?.();N&&N!=="about:blank"&&a(e,n,N)}catch{}try{D?.executeJavaScript?.(fa).catch(()=>{})}catch{}}},[e,n,a]);const j=i.useCallback(D=>{const N=o.current;if(typeof N?.loadURL!="function")return;const B=Co(D);try{N.loadURL(B)}catch{}},[]),A=i.useCallback(()=>{const D=o.current;if(D){if(p){y(!1);try{D.executeJavaScript?.(fa).catch(()=>{})}catch{}return}y(!0),D.executeJavaScript?.(dh,!0).then(async N=>{if(y(!1),!N||!Ki(N))return;const B=w??(v?"draft":null);if(!B){le.error(r("contextPanel.preview.inspect.attachNoSession"));return}const T=typeof D.getWebContentsId=="function"?D.getWebContentsId():null;if(T==null)return;const E=await kg("desktop_browser_capture_page",{webContentsId:T}),_=await D.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),R=Number.isFinite(_?.width)?_.width:E.width,$=Number.isFinite(_?.height)?_.height:E.height,V=await Hc(E.base64,E.width,E.height,R,$,N),z=!!V;V&&await k(V),S({sessionKey:B,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Uc({pageUrl:m,viewport:{width:R,height:$},devicePixelRatio:window.devicePixelRatio||1,target:N,screenshotAttached:z,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),le.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>y(!1))}},[k,S,w,m,p,v,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($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:s.jsx(I,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:s.jsx(I,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:D=>{D.preventDefault(),j(d)},children:s.jsx("input",{value:d,onChange:D=>u(D.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx($e,{type:"button",variant:p?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:A,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{Di(m)},children:s.jsx(I,{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:Co(t),partition:"persist:openchamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!m||m==="about:blank")&&!g?s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(Pc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")})]}):null,h?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}=kt(),e=di()??"",n=i.useMemo(()=>L0(e),[e]),r=Ee(P=>n?P.contextPanelByDirectory[n]:void 0),o=Ee(P=>P.closeContextPanel),a=Ee(P=>P.closeContextPanelTab),c=Ee(P=>P.openContextPanelTab),l=Ee(P=>P.toggleContextPanelExpanded),d=Ee(P=>P.setContextPanelWidth),u=Ee(P=>P.setActiveContextPanelTab),m=Ee(P=>P.reorderContextPanelTabs),f=pn(P=>P.setSelectedPath),p=Ee(P=>P.openContextPreview),{themeMode:y,setThemeMode:g,lightThemeId:b,darkThemeId:x,currentTheme:h}=qr(),C=i.useMemo(()=>r?.tabs??[],[r?.tabs]),w=C.find(P=>P.id===r?.activeTabId)??C[C.length-1]??null,v=!!(r?.isOpen&&w),S=!!(v&&r?.expanded),k=ch(r?.width??lh),j=i.useMemo(()=>{const P=[];for(const M of C){if(M.mode!=="chat")continue;const de=ua(M.dedupeKey);de&&!P.includes(de)&&P.push(de)}return P},[C]),A=H0(n||void 0,j),[D,N]=i.useState(!1),[B,T]=i.useState(!1),E=i.useRef(0),_=i.useRef(k),R=i.useRef(null),$=i.useRef(null),V=i.useRef(null),z=i.useRef(new Map),F=i.useRef(new Map),ne=i.useRef(!1),te=i.useRef(v),q=i.useRef(null),H=i.useCallback(()=>{T(!0),q.current!==null&&window.cancelAnimationFrame(q.current),q.current=window.requestAnimationFrame(()=>{q.current=null,T(!1)})},[]);i.useEffect(()=>()=>{q.current!==null&&window.cancelAnimationFrame(q.current)},[]),i.useLayoutEffect(()=>{const P=te.current;if(te.current=v,!v){T(!1);return}P||H()},[v,H]),i.useEffect(()=>{if(!v||ne.current){ne.current=v;return}const P=window.requestAnimationFrame(()=>{V.current?.focus({preventScroll:!0})});return ne.current=!0,()=>window.cancelAnimationFrame(P)},[v]);const X=i.useCallback(P=>{const M=V.current;M&&M.style.setProperty("--oc-context-panel-width",`${Rl(P,M)}px`)},[]),oe=i.useCallback(P=>{if(!(!v||S||!n)){try{P.currentTarget.setPointerCapture(P.pointerId)}catch{}$.current=P.pointerId,N(!0),E.current=P.clientX,_.current=k,R.current=k,X(k),P.preventDefault()}},[X,n,S,v,k]),ue=i.useCallback(P=>{if(!D||$.current!==P.pointerId)return;const M=E.current-P.clientX,de=Rl(_.current+M,V.current);R.current!==de&&(R.current=de,X(de))},[X,D]),Se=i.useCallback(P=>{if($.current!==P.pointerId||!n)return;try{P.currentTarget.releasePointerCapture(P.pointerId)}catch{}const M=Rl(R.current??k,V.current);H(),X(M),R.current=M,d(n,M),N(!1),$.current=null},[X,n,d,H,k]);i.useEffect(()=>{D||(R.current=null)},[D]);const Z=i.useCallback(()=>{n&&o(n)},[o,n]),ke=i.useCallback(()=>{n&&l(n)},[n,l]),Y=i.useCallback(P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),Z())},[Z]);i.useEffect(()=>{if(!(!n||!w)&&w.mode==="file"&&w.targetPath){f(n,w.targetPath,{allowOutsideRoot:!0});return}},[w,n,f]);const ge=w?.mode==="chat"?w.id:null,O=w?.mode==="chat"?ua(w.dedupeKey):null;i.useEffect(()=>{if(!v||!n||!O||typeof window>"u")return;const P=()=>{if(document.visibilityState==="hidden"||!document.hasFocus()){cl(n,O,!1);return}om(O),cl(n,O,!0)};P();const M=window.setInterval(P,1e4);return window.addEventListener("focus",P),window.addEventListener("blur",P),document.addEventListener("visibilitychange",P),()=>{window.clearInterval(M),window.removeEventListener("focus",P),window.removeEventListener("blur",P),document.removeEventListener("visibilitychange",P),cl(n,O,!1)}},[O,n,v]);const se=i.useCallback((P,M,de)=>g0(F.current,P,M,n||null,de,{mode:y,lightThemeId:b,darkThemeId:x,currentTheme:h}),[h,x,n,b,y]);i.useEffect(()=>{const P=new Set(C.map(M=>M.id));for(const M of F.current.keys())P.has(M)||F.current.delete(M)},[C]);const ee=i.useCallback(P=>{!n||w?.mode!=="diff"||c(n,{mode:"diff",targetPath:w.targetPath,stagedDiff:P==="staged"})},[w,n,c]),je=i.useCallback(()=>{if(typeof window>"u")return;const P={themeMode:y,lightThemeId:b,darkThemeId:x,currentTheme:h};for(const M of z.current.values()){const de=M.contentWindow;if(!de)continue;const xe=de.__openchamberApplyThemeSync;if(typeof xe=="function")try{xe(P);continue}catch{}de.postMessage({type:"openchamber:theme-sync",payload:P},window.location.origin)}},[h,x,b,y]),De=i.useCallback(()=>{if(!(typeof window>"u"))for(const[P,M]of z.current.entries()){const de=M.contentWindow;if(!de)continue;const xe={visible:ge===P},W=de.__openchamberSetEmbeddedVisibility;if(typeof W=="function")try{W(xe);continue}catch{}de.postMessage({type:"openchamber:embedded-visibility",payload:xe},window.location.origin)}},[ge]);i.useEffect(()=>{if(typeof window>"u")return;const P=M=>{if(M.origin!==window.location.origin||!Array.from(z.current.values()).some(G=>G.contentWindow===M.source)||M.data?.type!=="openchamber:cycle-theme-request")return;const W=["light","dark","system"],ve=(W.indexOf(y)+1)%W.length;g(W[ve])};return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[g,y]),i.useLayoutEffect(()=>{C.some(M=>M.mode==="chat")&&(je(),De())},[x,b,De,je,C,y]);const Be=i.useMemo(()=>C.map(P=>{const M=$0(P,A,t),de=K0(M,M0),xe=B0(P.targetPath,e);return{id:P.id,label:de,icon:z0(P),title:xe?`${M}: ${xe}`:M,closeLabel:t("contextPanel.tab.closeTabAria",{label:de})}}),[e,A,t,C]),Fe=w?.mode==="context"?s.jsx(n0,{}):w?.mode==="plan"?s.jsx(Zm,{targetPath:w.targetPath}):w?.mode==="preview"?s.jsx(Y0,{rawUrl:w.targetPath??"",onNavigate:P=>p(e,P)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(I,{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")})]}),Me=i.useMemo(()=>C.filter(P=>P.mode==="chat"),[C]),me=i.useMemo(()=>C.filter(P=>P.mode==="browser"),[C]),Ae=i.useMemo(()=>C.filter(P=>P.mode==="diff"),[C]),pe=Q0()?X0:J0,ce=i.useMemo(()=>C.some(P=>P.mode==="file"),[C]),he=w?.mode==="file",Ne=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(To,{items:Be,activeId:w?.id??null,onSelect:P=>{n&&u(n,P)},onClose:P=>{n&&a(n,P)},onReorder:(P,M)=>{n&&m(n,P,M)},layoutMode:"scrollable",variant:"default"}),s.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:ke,className:"h-7 w-7 p-0",title:t(S?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),"aria-label":t(S?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),children:S?s.jsx(I,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:Z,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})})]})]}),fe=v?S?{"--oc-context-panel-width":"100%",width:"100%",minWidth:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",minWidth:`min(${ah}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${D?R.current??k:k}px`}:{"--oc-context-panel-width":`${D?R.current??k:k}px`,width:0,minWidth:0,maxWidth:0,opacity:0,overflow:"hidden",visibility:"hidden"};return s.jsxs("aside",{ref:V,"data-context-panel":"true",tabIndex:-1,inert:!v||void 0,className:Pe("flex min-h-0 flex-col overflow-hidden bg-background",!S&&"border-l border-border/40",S?"absolute inset-0 z-20 min-w-0":"relative h-full flex-shrink-0",!v&&"pointer-events-none",D||!v||B?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:Y,style:fe,children:[!S&&s.jsx("div",{className:Pe("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",D&&"bg-[var(--interactive-border)]"),onPointerDown:oe,onPointerMove:ue,onPointerUp:Se,onPointerCancel:Se,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),Ne,s.jsxs("div",{className:Pe("relative min-h-0 flex-1 overflow-hidden",D&&"pointer-events-none"),children:[ce?s.jsx("div",{className:Pe("absolute inset-0",he?"block":"hidden"),children:s.jsx(Xm,{mode:"editor-only"})}):null,Me.map(P=>{const M=ua(P.dedupeKey);if(!M)return null;const de=se(P.id,M,P.readOnly);return de?s.jsx("iframe",{ref:xe=>{if(!xe){z.current.delete(P.id);return}z.current.set(P.id,xe)},src:de,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:M}),className:Pe("absolute inset-0 h-full w-full border-0 bg-background",ge===P.id?"block":"hidden"),onLoad:()=>{je(),De()}},P.id):null}),me.map(P=>s.jsx("div",{className:Pe("absolute inset-0",w?.id!==P.id&&"hidden"),children:s.jsx(pe,{initialUrl:P.targetPath??"",directory:n,tabID:P.id})},P.id)),Ae.map(P=>s.jsx("div",{className:Pe("absolute inset-0",w?.id!==P.id&&"hidden"),children:s.jsx(qm,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:P.stagedDiff?"staged":"working",onDiffScopeChange:ee,targetFilePath:P.targetPath,flushContent:!0})},P.id)),w?.mode!=="chat"&&!he&&w?.mode!=="browser"&&w?.mode!=="diff"?Fe:null]})]})},ic=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},ej=()=>{const t=ft.c(171),{t:e}=kt(),n=Ee(tj),r=Ee(sj),o=Ee(nj),a=Ee(rj),c=Ee(ij),l=Ee(oj),d=Ee(aj),u=Ee(lj),m=Ee(cj),f=Ee(dj),p=Ee(uj),y=Ee(fj),g=ut(mj),b=ut(hj),x=jr(pj),h=Xs(gj),C=Ns(xj),w=di(),v=pc(bj),{files:S,git:k}=Xn(),j=vn(yj),{isMobile:A}=Mr();let D;t[0]!==w?(D=w?ic(w):null,t[0]=w,t[1]=D):D=t[1];const N=D,[B,T]=i.useState(""),E=qa(B,200);let _;t[2]!==E?(_=E.trim(),t[2]=E,t[3]=_):_=t[3];const R=_;let $;t[4]!==B?($=B.trim(),t[4]=B,t[5]=$):$=t[5];const V=$;let z,F;t[6]!==n?(z=()=>{n&&T("")},F=[n],t[6]=n,t[7]=z,t[8]=F):(z=t[7],F=t[8]),i.useEffect(z,F);let ne,te;t[9]!==x||t[10]!==j||t[11]!==k||t[12]!==n?(ne=()=>{if(!n||!k)return;const Ve=setTimeout(()=>{const At=new Set;for(const ot of x){const vt=Rr(ot);!vt||At.has(vt)||(At.add(vt),j(vt,k))}},0);return()=>clearTimeout(Ve)},te=[n,x,k,j],t[9]=x,t[10]=j,t[11]=k,t[12]=n,t[13]=ne,t[14]=te):(ne=t[13],te=t[14]),i.useEffect(ne,te);let q;t[15]!==r?(q=()=>r(!1),t[15]=r,t[16]=q):q=t[16];const H=q;let X;t[17]!==H?(X=Ve=>()=>{H(),Ve()},t[17]=H,t[18]=X):X=t[18];const oe=X;let ue;t[19]!==C?.id||t[20]!==C?.path||t[21]!==h||t[22]!==A||t[23]!==f||t[24]!==g||t[25]!==oe||t[26]!==o||t[27]!==l||t[28]!==a||t[29]!==e||t[30]!==m||t[31]!==u||t[32]!==d?(ue=()=>{const Ve=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(I,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:oe(()=>{o("chat"),l(!1),g()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(I,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:oe(wj)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(I,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:oe(vj)},{id:"toggle-sidebar",title:e(A?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(I,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(A?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:oe(()=>{if(A){const{isSessionSwitcherOpen:At}=Ee.getState();l(!At)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(I,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:oe(()=>u())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(I,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:oe(()=>m())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(I,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:oe(()=>{h&&f(h)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(I,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:oe(()=>a(!0))}];return Ba()&&Ve.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(I,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:oe(()=>{Hr("desktop_open_draft_mini_chat_window",{directory:ic(h||C?.path||""),projectId:C?.id??null}).catch(jj)})}),Ve},t[19]=C?.id,t[20]=C?.path,t[21]=h,t[22]=A,t[23]=f,t[24]=g,t[25]=oe,t[26]=o,t[27]=l,t[28]=a,t[29]=e,t[30]=m,t[31]=u,t[32]=d,t[33]=ue):ue=t[33],C?.id,C?.path;let Se;t[34]!==ue?(Se=ue(),t[34]=ue,t[35]=Se):Se=t[35];const Z=Se;let ke;t[36]===Symbol.for("react.memo_cache_sentinel")?(ke=ur(),t[36]=ke):ke=t[36];const Y=ke;let ge,O;t[37]===Symbol.for("react.memo_cache_sentinel")?(ge=Kr(),O=!Y&&xc(),t[37]=ge,t[38]=O):(ge=t[37],O=t[38]);let se;t[39]!==A?(se={isVSCode:ge,isWeb:O,isDesktop:Y,isMobile:A},t[39]=A,t[40]=se):se=t[40];const ee=se;let je;if(t[41]!==oe||t[42]!==a||t[43]!==c||t[44]!==ee){let Ve;t[46]!==ee?(Ve=ot=>ot.isAvailable?ot.isAvailable(ee):!0,t[46]=ee,t[47]=Ve):Ve=t[47];let At;t[48]!==oe||t[49]!==a||t[50]!==c?(At=ot=>{const vt=qx(ot.slug)??"settings-3",bt=(ot.keywords??[]).join(" ");return{id:`settings:${ot.slug}`,title:ot.title,icon:ot.slug==="mcp"?s.jsx(Gl,{className:"mr-2 h-4 w-4"}):s.jsx(I,{name:vt,className:"mr-2 h-4 w-4"}),searchText:`${ot.title} ${ot.group} ${bt}`,onSelect:oe(()=>{c(ot.slug),a(!0)})}},t[48]=oe,t[49]=a,t[50]=c,t[51]=At):At=t[51],je=Kx.filter(Sj).filter(Ve).map(At),t[41]=oe,t[42]=a,t[43]=c,t[44]=ee,t[45]=je}else je=t[45];const De=je,Be=Nj;let Fe;if(t[52]!==x){let Ve;t[54]===Symbol.for("react.memo_cache_sentinel")?(Ve=(At,ot)=>Be(ot)-Be(At),t[54]=Ve):Ve=t[54],Fe=[...x].sort(Ve),t[52]=x,t[53]=Fe}else Fe=t[53];const Me=Fe,me=am(),Ae=ut(kj);let pe;t[55]!==me||t[56]!==Ae?(pe=(Ve,At)=>{const ot=Ae.get(Ve);return ot?.branch?ot.branch.trim()||null:At&&me.get(At)?.trim()||null},t[55]=me,t[56]=Ae,t[57]=pe):pe=t[57];const ce=pe;let he;t[58]===Symbol.for("react.memo_cache_sentinel")?(he=[],t[58]=he):he=t[58];const[Ne,fe]=i.useState(he),[P,M]=i.useState(!1);let de,xe;t[59]!==N||t[60]!==n||t[61]!==v||t[62]!==R?(de=()=>{if(!n){fe([]),M(!1);return}if(!N||R.length===0){fe([]),M(!1);return}let Ve=!1;return M(!0),v(N,R,10,{type:"file"}).then(At=>{Ve||fe(At.map(Cj))}).catch(()=>{Ve||fe([])}).finally(()=>{Ve||M(!1)}),()=>{Ve=!0}},xe=[n,N,R,v],t[59]=N,t[60]=n,t[61]=v,t[62]=R,t[63]=de,t[64]=xe):(de=t[63],xe=t[64]),i.useEffect(de,xe);const W=V.length>0;let be;e:{if(!W){let At;t[65]!==Z?(At=Z.map(Aj),t[65]=Z,t[66]=At):At=t[66],be=At;break e}let Ve;t[67]!==Z||t[68]!==V?(Ve=Wo(Z,V,Dj,{limit:7,noFuzzy:!0}),t[67]=Z,t[68]=V,t[69]=Ve):Ve=t[69],be=Ve}const ve=be;let G;e:{if(!W){let At;t[70]===Symbol.for("react.memo_cache_sentinel")?(At=[],t[70]=At):At=t[70],G=At;break e}let Ve;t[71]!==V||t[72]!==De?(Ve=Wo(De,V,Ij,{limit:7,noFuzzy:!0}),t[71]=V,t[72]=De,t[73]=Ve):Ve=t[73],G=Ve}const ye=G;let Le;e:{if(!W){let At;t[74]!==Me?(At=Me.slice(0,5).map(Pj),t[74]=Me,t[75]=At):At=t[75],Le=At;break e}let Ve;t[76]!==V||t[77]!==Me?(Ve=Wo(Me,V,Tj,{limit:7,threshold:.2}),t[76]=V,t[77]=Me,t[78]=Ve):Ve=t[78],Le=Ve}const Re=Le;let J;e:{if(!W||Ne.length===0){let At;t[79]===Symbol.for("react.memo_cache_sentinel")?(At=[],t[79]=At):At=t[79],J=At;break e}let Ve;t[80]!==Ne||t[81]!==V?(Ve=Wo(Ne,V,Rj,{limit:10,threshold:.4}),t[80]=Ne,t[81]=V,t[82]=Ve):Ve=t[82],J=Ve}const L=J;let ae,re,Oe,qe,Ge,Je,nt,gt,yt,_e,Qe,st,wt,Ct,xt;if(t[83]!==ce||t[84]!==H||t[85]!==N||t[86]!==S||t[87]!==W||t[88]!==n||t[89]!==p||t[90]!==B||t[91]!==ve||t[92]!==L||t[93]!==Re||t[94]!==ye||t[95]!==r||t[96]!==b||t[97]!==y||t[98]!==e){const Ve=ve.map(Ej),At=ye.map(Mj),ot=Re.map(Fj);xt=W?L.map(Lj):[];let vt;e:{if(!W){vt=["commands","sessions"];break e}const Vt=Oj,Dt=[{key:"commands",score:Vt(ve)},{key:"settings",score:Vt(ye)},{key:"sessions",score:Vt(Re)},{key:"files",score:Vt(L)}];Dt.sort(Bj),vt=Dt.map(_j)}const bt=vt;let ls;t[114]!==H||t[115]!==b?(ls=Vt=>{H(),b(Vt.id,Rr(Vt))},t[114]=H,t[115]=b,t[116]=ls):ls=t[116];const Wt=ls;let qt;t[117]!==H||t[118]!==N||t[119]!==S||t[120]!==p?(qt=async Vt=>{if(!N)return;const Dt=await $c(S,Vt);if(!Dt.ok){le.error(zc(Dt.reason));return}p(N,Vt),H()},t[117]=H,t[118]=N,t[119]=S,t[120]=p,t[121]=qt):qt=t[121];const rs=qt;let Ut;t[122]!==y?(Ut=Vt=>_a(ii(Vt,y)),t[122]=y,t[123]=Ut):Ut=t[123];const Bt=Ut;qe=$s,st=n,wt=r;let _t;t[124]!==e?(_t=e("commandPalette.title"),t[124]=e,t[125]=_t):_t=t[125];let Yt;t[126]!==_t?(Yt=s.jsx(Us,{children:_t}),t[126]=_t,t[127]=Yt):Yt=t[127];let Ht;t[128]!==e?(Ht=e("commandPalette.description"),t[128]=e,t[129]=Ht):Ht=t[129];let Zt;t[130]!==Ht?(Zt=s.jsx(ln,{children:Ht}),t[130]=Ht,t[131]=Zt):Zt=t[131],t[132]!==Yt||t[133]!==Zt?(Ct=s.jsxs(Gs,{className:"sr-only",children:[Yt,Zt]}),t[132]=Yt,t[133]=Zt,t[134]=Ct):Ct=t[134],Oe=Vs,_e="overflow-hidden p-0",Qe=!0,re=Va,nt=!1,gt="[&_[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 ys;t[135]!==e?(ys=e("commandPalette.input.placeholder"),t[135]=e,t[136]=ys):ys=t[136],t[137]!==B||t[138]!==ys?(yt=s.jsx($a,{value:B,onValueChange:T,placeholder:ys}),t[137]=B,t[138]=ys,t[139]=yt):yt=t[139],ae=za;let Tt;t[140]!==e?(Tt=e("commandPalette.empty.noResults"),t[140]=e,t[141]=Tt):Tt=t[141],t[142]!==Tt?(Ge=s.jsx(Wa,{children:Tt}),t[142]=Tt,t[143]=Ge):Ge=t[143],Je=bt.map(Vt=>Vt==="commands"&&Ve.length>0?s.jsx(oi,{children:Ve.map(Dt=>s.jsxs(li,{value:Dt.id,onSelect:Dt.onSelect,children:[Dt.icon,s.jsx("span",{children:Dt.title}),Dt.shortcutId?s.jsx(Cg,{children:Bt(Dt.shortcutId)}):null]},Dt.id))},"commands"):Vt==="settings"&&At.length>0?s.jsx(oi,{children:At.map(Vj)},"settings"):Vt==="sessions"&&ot.length>0?s.jsx(oi,{children:ot.map(Dt=>{const cs=Dt.title||e("commandPalette.session.untitled"),us=Rr(Dt),He=ce(Dt.id,us);return s.jsxs(li,{value:`session:${Dt.id}`,onSelect:()=>Wt(Dt),children:[s.jsx(I,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:cs}),He?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:He})]}):null]},Dt.id)})},"sessions"):Vt==="files"&&xt.length>0?s.jsx(oi,{children:xt.map(Dt=>{const cs=Ag(Dt.relativePath||Dt.name,{maxLength:80});return s.jsxs(li,{value:`file:${Dt.path}`,onSelect:()=>{rs(Dt.path)},children:[s.jsx(Gr,{filePath:Dt.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":Dt.relativePath,children:cs})]},`file:${Dt.path}`)})},"files"):null),t[83]=ce,t[84]=H,t[85]=N,t[86]=S,t[87]=W,t[88]=n,t[89]=p,t[90]=B,t[91]=ve,t[92]=L,t[93]=Re,t[94]=ye,t[95]=r,t[96]=b,t[97]=y,t[98]=e,t[99]=ae,t[100]=re,t[101]=Oe,t[102]=qe,t[103]=Ge,t[104]=Je,t[105]=nt,t[106]=gt,t[107]=yt,t[108]=_e,t[109]=Qe,t[110]=st,t[111]=wt,t[112]=Ct,t[113]=xt}else ae=t[99],re=t[100],Oe=t[101],qe=t[102],Ge=t[103],Je=t[104],nt=t[105],gt=t[106],yt=t[107],_e=t[108],Qe=t[109],st=t[110],wt=t[111],Ct=t[112],xt=t[113];let St;t[144]!==W||t[145]!==P||t[146]!==e||t[147]!==xt?(St=W&&P&&xt.length===0?s.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:e("commandPalette.empty.searchingFiles")}):null,t[144]=W,t[145]=P,t[146]=e,t[147]=xt,t[148]=St):St=t[148];let Ze;t[149]!==ae||t[150]!==Ge||t[151]!==Je||t[152]!==St?(Ze=s.jsxs(ae,{children:[Ge,Je,St]}),t[149]=ae,t[150]=Ge,t[151]=Je,t[152]=St,t[153]=Ze):Ze=t[153];let Ot;t[154]!==re||t[155]!==nt||t[156]!==gt||t[157]!==yt||t[158]!==Ze?(Ot=s.jsxs(re,{shouldFilter:nt,className:gt,children:[yt,Ze]}),t[154]=re,t[155]=nt,t[156]=gt,t[157]=yt,t[158]=Ze,t[159]=Ot):Ot=t[159];let ns;t[160]!==Oe||t[161]!==_e||t[162]!==Qe||t[163]!==Ot?(ns=s.jsx(Oe,{className:_e,showCloseButton:Qe,children:Ot}),t[160]=Oe,t[161]=_e,t[162]=Qe,t[163]=Ot,t[164]=ns):ns=t[164];let zt;return t[165]!==qe||t[166]!==st||t[167]!==wt||t[168]!==Ct||t[169]!==ns?(zt=s.jsxs(qe,{open:st,onOpenChange:wt,children:[Ct,ns]}),t[165]=qe,t[166]=st,t[167]=wt,t[168]=Ct,t[169]=ns,t[170]=zt):zt=t[170],zt};function tj(t){return t.isCommandPaletteOpen}function sj(t){return t.setCommandPaletteOpen}function nj(t){return t.setActiveMainTab}function rj(t){return t.setSettingsDialogOpen}function ij(t){return t.setSettingsPage}function oj(t){return t.setSessionSwitcherOpen}function aj(t){return t.toggleSidebar}function lj(t){return t.toggleRightSidebar}function cj(t){return t.toggleBottomTerminal}function dj(t){return t.openContextOverview}function uj(t){return t.openContextFile}function fj(t){return t.shortcutOverrides}function mj(t){return t.openNewSessionDraft}function hj(t){return t.setCurrentSession}function pj(t){return t.activeSessions}function gj(t){return t.currentDirectory}function xj(t){return t.getActiveProject()}function bj(t){return t.searchFiles}function yj(t){return t.ensureStatus}function wj(){lm()}function vj(){Tr.requestDirectoryDialog()}function jj(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function Sj(t){return t.slug!=="home"}function Nj(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function kj(t){return t.worktreeMetadata}function Cj(t){return{path:ic(t.path),name:t.name,relativePath:t.relativePath}}function Aj(t){return{item:t,score:0}}function Dj(t){return t.searchText}function Ij(t){return t.searchText}function Pj(t){return{item:t,score:0}}function Tj(t){return t.title||""}function Rj(t){return t.name}function Ej(t){return t.item}function Mj(t){return t.item}function Fj(t){return t.item}function Lj(t){return t.item}function Oj(t){return t.length?t[0].score:1/0}function Bj(t,e){return t.score-e.score}function _j(t){return t.key}function Vj(t){return s.jsxs(li,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const Xu=(t,e,n)=>Ig(t)?_a(ii(t,n)):e,$j=()=>{const t=ft.c(68),{t:e}=kt(),n=Ee(zj),r=Ee(Wj),o=Ee(Uj);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=Dg(),t[0]=a):a=t[0];const c=a;let l,d,u,m,f,p,y,g,b;if(t[1]!==n||t[2]!==r||t[3]!==o||t[4]!==e){const R=[{categoryKey:"helpDialog.section.navigationCommands",items:[{id:"open_command_palette",descriptionKey:"helpDialog.item.openCommandPalette",icon:"command",keys:""},{id:"open_help",descriptionKey:"helpDialog.item.showKeyboardShortcuts",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"helpDialog.item.toggleSessionSidebar",icon:"layout-left",keys:""},{id:"cycle_agent",keys:"",descriptionKey:"helpDialog.item.cycleAgent",icon:"ai-agent"},{id:"open_model_selector",descriptionKey:"helpDialog.item.openModelSelector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"helpDialog.item.navigateModels",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"helpDialog.item.adjustThinkingMode",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"helpDialog.item.cycleThinkingVariant",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${c} + N`],descriptionKey:"helpDialog.item.newWindow",icon:"window"}]},{categoryKey:"helpDialog.section.sessionManagement",items:[{id:"new_chat",descriptionKey:"helpDialog.item.createNewSession",icon:"add",keys:""},{id:"new_chat_worktree",descriptionKey:"helpDialog.item.createNewWorktreeDraft",icon:"git-branch",keys:""},{id:"focus_input",descriptionKey:"helpDialog.item.focusChatInput",icon:"text",keys:""},{id:"abort_run",descriptionKey:"helpDialog.item.abortActiveRun",icon:"close-circle",keys:""}]},{categoryKey:"helpDialog.section.panels",items:[{id:"toggle_right_sidebar",descriptionKey:"helpDialog.item.toggleRightSidebar",icon:"layout-right",keys:""},{id:"open_right_sidebar_git",descriptionKey:"helpDialog.item.openRightSidebarGitTab",icon:"git-branch",keys:""},{id:"open_right_sidebar_files",descriptionKey:"helpDialog.item.openRightSidebarFilesTab",icon:"layout-right",keys:""},{id:"cycle_right_sidebar_tab",descriptionKey:"helpDialog.item.cycleRightSidebarTab",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{id:"toggle_terminal_expanded",descriptionKey:"helpDialog.item.toggleTerminalExpanded",icon:"window",keys:""},{id:"toggle_context_plan",descriptionKey:"helpDialog.item.togglePlanContextPanel",icon:"time",keys:""}]},{categoryKey:"helpDialog.section.interface",items:[{id:"cycle_theme",descriptionKey:"helpDialog.item.cycleTheme",icon:"palette",keys:""},{keys:[`${c} + 1...9`],descriptionKey:"helpDialog.item.switchProject",icon:"layout-left"},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"cycle_services_tab",descriptionKey:"helpDialog.item.cycleServicesTab",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"helpDialog.item.openSettings",icon:"settings-3",keys:""}]}];d=$s,g=n,b=r,l=Vs,p="max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden";let $;t[14]===Symbol.for("react.memo_cache_sentinel")?($=s.jsx(I,{name:"settings-3",className:"h-5 w-5"}),t[14]=$):$=t[14];let V;t[15]!==e?(V=e("helpDialog.title"),t[15]=e,t[16]=V):V=t[16];let z;t[17]!==V?(z=s.jsxs(Us,{className:"flex items-center gap-2",children:[$,V]}),t[17]=V,t[18]=z):z=t[18];let F;t[19]!==e?(F=e("helpDialog.description"),t[19]=e,t[20]=F):F=t[20];let ne;t[21]!==F?(ne=s.jsx(ln,{children:F}),t[21]=F,t[22]=ne):ne=t[22],t[23]!==z||t[24]!==ne?(y=s.jsxs(Gs,{children:[z,ne]}),t[23]=z,t[24]=ne,t[25]=y):y=t[25],f="flex-1 overflow-y-auto mt-3 pr-1",u="space-y-4",m=R.map(te=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(te.categoryKey)}),s.jsx("div",{className:"space-y-1",children:te.items.map(q=>{const H=q.id?Xu(q.id,Array.isArray(q.keys)?q.keys[0]:q.keys,o):Array.isArray(q.keys)?q.keys:q.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:[q.icon&&s.jsx(I,{name:q.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(q.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(H)?H:[H]).map((X,oe)=>s.jsxs(i.Fragment,{children:[oe>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:X})]},`${X}-${oe}`))})]},q.id||q.descriptionKey)})})]},te.categoryKey)),t[1]=n,t[2]=r,t[3]=o,t[4]=e,t[5]=l,t[6]=d,t[7]=u,t[8]=m,t[9]=f,t[10]=p,t[11]=y,t[12]=g,t[13]=b}else l=t[5],d=t[6],u=t[7],m=t[8],f=t[9],p=t[10],y=t[11],g=t[12],b=t[13];let x;t[26]!==u||t[27]!==m?(x=s.jsx("div",{className:u,children:m}),t[26]=u,t[27]=m,t[28]=x):x=t[28];let h;t[29]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(I,{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 v;t[34]!==o||t[35]!==e?(v=e("helpDialog.proTips.commandPalette",{shortcut:Xu("open_command_palette",`${c} P`,o)}),t[34]=o,t[35]=e,t[36]=v):v=t[36];let S;t[37]!==v?(S=s.jsxs("li",{children:["• ",v]}),t[37]=v,t[38]=S):S=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 A;t[43]!==e?(A=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=A):A=t[44];let D;t[45]!==A?(D=s.jsxs("li",{children:["• ",A]}),t[45]=A,t[46]=D):D=t[46];let N;t[47]!==S||t[48]!==j||t[49]!==D?(N=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[S,j,D]}),t[47]=S,t[48]=j,t[49]=D,t[50]=N):N=t[50];let B;t[51]!==w||t[52]!==N?(B=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,N]})]})}),t[51]=w,t[52]=N,t[53]=B):B=t[53];let T;t[54]!==B||t[55]!==f||t[56]!==x?(T=s.jsxs("div",{className:f,children:[x,B]}),t[54]=B,t[55]=f,t[56]=x,t[57]=T):T=t[57];let E;t[58]!==l||t[59]!==T||t[60]!==p||t[61]!==y?(E=s.jsxs(l,{className:p,children:[y,T]}),t[58]=l,t[59]=T,t[60]=p,t[61]=y,t[62]=E):E=t[62];let _;return t[63]!==d||t[64]!==E||t[65]!==g||t[66]!==b?(_=s.jsx(d,{open:g,onOpenChange:b,children:E}),t[63]=d,t[64]=E,t[65]=g,t[66]=b,t[67]=_):_=t[67],_};function zj(t){return t.isHelpDialogOpen}function Wj(t){return t.setHelpDialogOpen}function Uj(t){return t.shortcutOverrides}const Hj=()=>{const t=ft.c(32),{t:e}=kt(),n=Ee(Gj),r=Ee(Kj),o=Ee(qj);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await fr(o)).ok){le.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}le.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(Us,{children:l}),t[5]=l,t[6]=d):d=t[6];let u;t[7]!==e?(u=e("openCodeStatusDialog.description"),t[7]=e,t[8]=u):u=t[8];let m;t[9]!==u?(m=s.jsx(ln,{children:u}),t[9]=u,t[10]=m):m=t[10];let f;t[11]!==d||t[12]!==m?(f=s.jsxs(Gs,{children:[d,m]}),t[11]=d,t[12]=m,t[13]=f):f=t[13];let p;t[14]!==e?(p=e("openCodeStatusDialog.actions.copy"),t[14]=e,t[15]=p):p=t[15];let y;t[16]!==c||t[17]!==p?(y=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]=y):y=t[18];let g;t[19]!==o||t[20]!==e?(g=o||e("openCodeStatusDialog.empty.noData"),t[19]=o,t[20]=e,t[21]=g):g=t[21];let b;t[22]!==g?(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:g}),t[22]=g,t[23]=b):b=t[23];let x;t[24]!==f||t[25]!==y||t[26]!==b?(x=s.jsxs(Vs,{className:"max-w-2xl",children:[f,y,b]}),t[24]=f,t[25]=y,t[26]=b,t[27]=x):x=t[27];let h;return t[28]!==n||t[29]!==r||t[30]!==x?(h=s.jsx($s,{open:n,onOpenChange:r,children:x}),t[28]=n,t[29]=r,t[30]=x,t[31]=h):h=t[31],h};function Gj(t){return t.isOpenCodeStatusDialogOpen}function Kj(t){return t.setOpenCodeStatusDialogOpen}function qj(t){return t.openCodeStatusText}const Yj=180,Zu=600,Qj=1,Jj=6,Xj=({currentSessionId:t,sortedSessions:e,recentSessionIds:n=[],ensureSessionRenderable:r})=>{const o=i.useRef(new Map),a=i.useRef([]),c=i.useRef(new Set),l=i.useMemo(()=>Kr(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<Qj&&a.current.length>0;){const m=a.current.shift();if(!m)break;ut.getState().currentSessionId!==m&&(Od(m).renderable||(c.current.add(m),r(m).catch(()=>{}).finally(()=>{c.current.delete(m),d()})))}},[r,l]),u=i.useCallback(m=>{if(l||!m||m===t||typeof window>"u"||Od(m).renderable||c.current.has(m)||a.current.includes(m))return;a.current.length>=Jj&&a.current.shift();const f=o.current.get(m);f!==void 0&&window.clearTimeout(f);const p=window.setTimeout(()=>{o.current.delete(m),a.current.push(m),d()},Yj);o.current.set(m,p)},[t,l,d]);i.useEffect(()=>{if(l||!t||e.length===0)return;const m=window.setTimeout(()=>{const f=e.findIndex(p=>p.id===t);f<0||(u(e[f-1]?.id),u(e[f+1]?.id))},Zu);return()=>window.clearTimeout(m)},[t,l,u,e]),i.useEffect(()=>{if(l||!t||n.length===0)return;const m=window.setTimeout(()=>{const f=n.indexOf(t);f<0||(u(n[f-1]),u(n[f+1]))},Zu);return()=>window.clearTimeout(m)},[t,l,n,u]),i.useEffect(()=>{const m=o.current;return()=>{m.forEach(f=>{clearTimeout(f)}),m.clear(),a.current=[]}},[])};let Yi=null,Qi=null,ma=null,Eo=0,Ma=null;const Ai=new Set,Zj=3e4,eS=45e3,fh=()=>{ma&&(clearTimeout(ma),ma=null)},mh=()=>{if(Qi||Ai.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Eo,5)),Zj);Qi=setTimeout(()=>{Qi=null,Eo+=1,Kc()},t)},Mo=()=>{fh(),Yi&&Yi.close(),Yi=null},ef=()=>{fh(),Ai.size!==0&&(ma=setTimeout(()=>{Mo(),mh()},eS))},tS=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}},sS=t=>{if(t.type==="openchamber:event-stream-ready"){Eo=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 Ai)d(l)},Kc=()=>{if(typeof window>"u"||Ai.size===0||typeof EventSource!="function"||Yi&&Yi.readyState!==EventSource.CLOSED)return;Mo();const t=new EventSource(ki().sse("/api/openchamber/events"));t.onopen=()=>{ef()},t.onmessage=e=>{ef();const n=tS(e.data);n&&sS(n)},t.onerror=()=>{Mo(),mh()},Yi=t},nS=()=>{Ma||typeof window>"u"||(Ma=Vf(()=>{Mo(),Eo=0,Kc()}))},rS=()=>{Ma?.(),Ma=null},hh=t=>(Ai.add(t),nS(),Kc(),()=>{Ai.delete(t),Ai.size===0&&(Qi&&(clearTimeout(Qi),Qi=null),Eo=0,Mo(),rS())}),Xa=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},no=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},iS=async t=>{const e=no(t),n=await Cs(`/api/projects/${encodeURIComponent(e)}/scheduled-tasks`);if(!n.ok)throw new Error(await Xa(n,"Failed to load scheduled tasks"));const r=await n.json().catch(()=>null);return!r||!Array.isArray(r.tasks)?[]:r.tasks},tf=async(t,e)=>{const n=no(t),r=await Cs(`/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 Xa(r,"Failed to save scheduled task"));const o=await r.json().catch(()=>null);return!o||!Array.isArray(o.tasks)?[]:o.tasks},oS=async(t,e)=>{const n=no(t),r=no(e),o=await Cs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}`,{method:"DELETE",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Xa(o,"Failed to delete scheduled task"));const a=await o.json().catch(()=>null);return!a||!Array.isArray(a.tasks)?[]:a.tasks},aS=async(t,e)=>{const n=no(t),r=no(e),o=await Cs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}/run`,{method:"POST",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Xa(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 ph(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return Lf.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function lS(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=Lf.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 cS=[{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"}],gh=[0,1,2,3,4,5,6],oc=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"],sf=()=>{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}`},ha=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},nf=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},dS=(t,e,n)=>{const r=ha(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},rf=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),uS=(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(),u=[];for(let m=0;m<42;m+=1){const f=m-c+1;if(f<=0){const p=d+f;u.push({date:new Date(n,r-1,p),inCurrentMonth:!1});continue}if(f>l){u.push({date:new Date(n,r+1,f-l),inCurrentMonth:!1});continue}u.push({date:new Date(n,r,f),inCurrentMonth:!0})}return u},fS=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}},yi=(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")}`},lo=(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"},of=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:lo(t,{min:1,max:12}),Zo=t=>/^[0-5][0-9]$/.test(t)?t:lo(t,{max:59}),mS=(t,e)=>lo(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),af=(t,e)=>lo(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),hS=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}},pS=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}},gS=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return gh.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},xS=(t,e)=>[...t.slice(e),...t.slice(0,e)],Yn=t=>{const e=ft.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},lf=t=>{const e=ft.c(84),{value:n,onChange:r,use24Hour:o,hourAriaLabel:a,minuteAriaLabel:c,periodAriaLabel:l,amLabel:d,pmLabel:u}=t;let m;e[0]!==n?(m=fS(n),e[0]=n,e[1]=m):m=e[1];const f=m,p=Xe.useRef(null),y=Xe.useRef(null),[g,b]=Xe.useState(null),[x,h]=Xe.useState(null),C=Xe.useRef(null),w=Xe.useRef(null);let v;e[2]===Symbol.for("react.memo_cache_sentinel")?(v=pe=>{C.current=pe,b(pe)},e[2]=v):v=e[2];const S=v;let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=pe=>{w.current=pe,h(pe)},e[3]=k):k=e[3];const j=k,A=NS,D=kS,N=CS;let B;e[4]!==r||e[5]!==f.meridiem||e[6]!==f.minute||e[7]!==o?(B=pe=>{const ce=pe.replace(/\D/g,"").slice(0,2);S(ce),ce.length===2&&(r(o?N(A(ce),f.minute):yi(of(ce),f.minute,f.meridiem)),S(null),y.current?.focus())},e[4]=r,e[5]=f.meridiem,e[6]=f.minute,e[7]=o,e[8]=B):B=e[8];const T=B;let E;e[9]!==r||e[10]!==f.meridiem||e[11]!==f.minute||e[12]!==o?(E=()=>{const pe=C.current;if(pe!==null&&(S(null),pe.length!==0)){if(o){r(N(A(pe.padStart(2,"0")),f.minute));return}r(yi(of(pe.padStart(2,"0")),f.minute,f.meridiem))}},e[9]=r,e[10]=f.meridiem,e[11]=f.minute,e[12]=o,e[13]=E):E=e[13];const _=E;let R;e[14]!==r||e[15]!==f.hour12||e[16]!==f.hour24||e[17]!==f.meridiem||e[18]!==o?(R=pe=>{const ce=pe.replace(/\D/g,"").slice(0,2);j(ce),ce.length===2&&(r(o?N(f.hour24,Zo(ce)):yi(f.hour12,Zo(ce),f.meridiem)),j(null))},e[14]=r,e[15]=f.hour12,e[16]=f.hour24,e[17]=f.meridiem,e[18]=o,e[19]=R):R=e[19];const $=R;let V;e[20]!==r||e[21]!==f.hour12||e[22]!==f.hour24||e[23]!==f.meridiem||e[24]!==o?(V=()=>{const pe=w.current;pe!==null&&(j(null),pe.length!==0&&r(o?N(f.hour24,Zo(pe.padStart(2,"0"))):yi(f.hour12,Zo(pe.padStart(2,"0")),f.meridiem)))},e[20]=r,e[21]=f.hour12,e[22]=f.hour24,e[23]=f.meridiem,e[24]=o,e[25]=V):V=e[25];const z=V;let F;e[26]!==r||e[27]!==f.hour12||e[28]!==f.hour24||e[29]!==f.meridiem||e[30]!==f.minute||e[31]!==o?(F=pe=>r(o?N(D(f.hour24,pe),f.minute):yi(mS(f.hour12,pe),f.minute,f.meridiem)),e[26]=r,e[27]=f.hour12,e[28]=f.hour24,e[29]=f.meridiem,e[30]=f.minute,e[31]=o,e[32]=F):F=e[32];const ne=F;let te;e[33]!==r||e[34]!==f.hour12||e[35]!==f.hour24||e[36]!==f.meridiem||e[37]!==f.minute||e[38]!==o?(te=pe=>r(o?N(f.hour24,af(f.minute,pe)):yi(f.hour12,af(f.minute,pe),f.meridiem)),e[33]=r,e[34]=f.hour12,e[35]=f.hour24,e[36]=f.meridiem,e[37]=f.minute,e[38]=o,e[39]=te):te=e[39];const q=te;let H;e[40]!==r||e[41]!==f.hour12||e[42]!==f.meridiem||e[43]!==f.minute?(H=pe=>{pe!==f.meridiem&&r(yi(f.hour12,f.minute,pe))},e[40]=r,e[41]=f.hour12,e[42]=f.meridiem,e[43]=f.minute,e[44]=H):H=e[44];const X=H;let oe;e[45]!==_||e[46]!==ne?(oe=pe=>{if(pe.key==="ArrowRight"){pe.preventDefault(),_(),y.current?.focus();return}(pe.key==="ArrowUp"||pe.key==="ArrowDown")&&(pe.preventDefault(),S(null),ne(pe.key==="ArrowUp"?1:-1))},e[45]=_,e[46]=ne,e[47]=oe):oe=e[47];const ue=oe;let Se;e[48]!==z||e[49]!==q?(Se=pe=>{if(pe.key==="ArrowLeft"&&(pe.currentTarget.selectionStart??0)===0){pe.preventDefault(),z(),p.current?.focus();return}(pe.key==="ArrowUp"||pe.key==="ArrowDown")&&(pe.preventDefault(),j(null),q(pe.key==="ArrowUp"?1:-1))},e[48]=z,e[49]=q,e[50]=Se):Se=e[50];const Z=Se,ke=o?"px-2":"pl-2 pr-1";let Y;e[51]!==ke?(Y=Pe("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",ke),e[51]=ke,e[52]=Y):Y=e[52];const ge=g??(o?f.hour24:f.hour12);let O;e[53]!==T?(O=pe=>T(pe.target.value),e[53]=T,e[54]=O):O=e[54];let se;e[55]===Symbol.for("react.memo_cache_sentinel")?(se=()=>S(""),e[55]=se):se=e[55];let ee;e[56]!==_||e[57]!==a||e[58]!==ue||e[59]!==ge||e[60]!==O?(ee=s.jsx("input",{ref:p,inputMode:"numeric",value:ge,onChange:O,onKeyDown:ue,onFocus:se,onBlur:_,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]=_,e[57]=a,e[58]=ue,e[59]=ge,e[60]=O,e[61]=ee):ee=e[61];let je;e[62]===Symbol.for("react.memo_cache_sentinel")?(je=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=je):je=e[62];const De=x??f.minute;let Be;e[63]!==$?(Be=pe=>$(pe.target.value),e[63]=$,e[64]=Be):Be=e[64];let Fe;e[65]===Symbol.for("react.memo_cache_sentinel")?(Fe=()=>j(""),e[65]=Fe):Fe=e[65];let Me;e[66]!==z||e[67]!==c||e[68]!==Z||e[69]!==De||e[70]!==Be?(Me=s.jsx("input",{ref:y,inputMode:"numeric",value:De,onChange:Be,onKeyDown:Z,onFocus:Fe,onBlur:z,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]=z,e[67]=c,e[68]=Z,e[69]=De,e[70]=Be,e[71]=Me):Me=e[71];let me;e[72]!==d||e[73]!==f.meridiem||e[74]!==l||e[75]!==u||e[76]!==X||e[77]!==o?(me=o?null:s.jsxs(zn,{value:f.meridiem,onValueChange:pe=>X(pe),children:[s.jsx(Wn,{"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(Un,{children:[s.jsx(Ms,{value:"AM",children:d}),s.jsx(Ms,{value:"PM",children:u})]})]}),e[72]=d,e[73]=f.meridiem,e[74]=l,e[75]=u,e[76]=X,e[77]=o,e[78]=me):me=e[78];let Ae;return e[79]!==Y||e[80]!==ee||e[81]!==Me||e[82]!==me?(Ae=s.jsxs("div",{className:Y,children:[ee,je,Me,me]}),e[79]=Y,e[80]=ee,e[81]=Me,e[82]=me,e[83]=Ae):Ae=e[83],Ae},cf=t=>new Date(t.getFullYear(),t.getMonth(),1),bS=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},df=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),yS=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"]},uf=(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:yS(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:sf(),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:sf(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent}}},wS=(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(!ph(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")},vS=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))},jS=t=>{const e=ft.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?ph(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let u;e:{if(!d?.valid||!c.trim()){let F;e[2]===Symbol.for("react.memo_cache_sentinel")?(F=[],e[2]=F):F=e[2],u=F;break e}let z;e[3]!==c||e[4]!==n.schedule.timezone?(z=lS(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=z):z=e[5],u=z}const m=u;let f;e[6]!==n.schedule.timezone||e[7]!==o?(f=z=>new Intl.DateTimeFormat(o,{timeZone:n.schedule.timezone,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(z),e[6]=n.schedule.timezone,e[7]=o,e[8]=f):f=e[8];const p=f;let y;e[9]!==a?(y=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=y):y=e[10];let g;e[11]!==y?(g=s.jsx(Yn,{htmlFor:"sched-cron",required:!0,children:y}),e[11]=y,e[12]=g):g=e[12];let b;e[13]!==r?(b=z=>r(F=>({...F,schedule:{...F.schedule,cronExpression:z.target.value}})),e[13]=r,e[14]=b):b=e[14];let x;e[15]!==a?(x=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=x):x=e[16];let h;e[17]!==c||e[18]!==b||e[19]!==x?(h=s.jsx(jn,{id:"sched-cron",value:c,onChange:b,placeholder:x,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=b,e[19]=x,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]!==g||e[26]!==h||e[27]!==C?(w=s.jsxs("div",{className:"flex flex-col gap-1",children:[g,h,C]}),e[25]=g,e[26]=h,e[27]=C,e[28]=w):w=e[28];let v;e[29]!==p||e[30]!==m||e[31]!==a?(v=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]=v):v=e[32];let S;e[33]!==a?(S=a("sessions.scheduledTasks.editor.cronExpression.examples"),e[33]=a,e[34]=S):S=e[34];let k;e[35]!==S?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:S}),e[35]=S,e[36]=k):k=e[36];let j;e[37]!==r||e[38]!==a?(j=cS.map(z=>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(F=>({...F,schedule:{...F.schedule,cronExpression:z.expression}})),children:[s.jsx("span",{className:"font-mono",children:z.expression}),s.jsx("span",{className:"text-muted-foreground",children:a(z.labelKey)})]},z.expression)),e[37]=r,e[38]=a,e[39]=j):j=e[39];let A;e[40]!==j?(A=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:j}),e[40]=j,e[41]=A):A=e[41];let D;e[42]!==k||e[43]!==A?(D=s.jsxs("div",{className:"flex flex-col gap-1",children:[k,A]}),e[42]=k,e[43]=A,e[44]=D):D=e[44];let N;e[45]!==a?(N=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=N):N=e[46];let B;e[47]!==N?(B=s.jsx(Yn,{children:N}),e[47]=N,e[48]=B):B=e[48];let T;e[49]!==r?(T=z=>{r(F=>({...F,schedule:{...F.schedule,timezone:z}}))},e[49]=r,e[50]=T):T=e[50];let E;e[51]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Wn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),e[51]=E):E=e[51];let _;e[52]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx(Un,{children:oc.map(AS)}),e[52]=_):_=e[52];let R;e[53]!==n.schedule.timezone||e[54]!==T?(R=s.jsxs(zn,{value:n.schedule.timezone,onValueChange:T,children:[E,_]}),e[53]=n.schedule.timezone,e[54]=T,e[55]=R):R=e[55];let $;e[56]!==B||e[57]!==R?($=s.jsxs("div",{className:"flex flex-col gap-1",children:[B,R]}),e[56]=B,e[57]=R,e[58]=$):$=e[58];let V;return e[59]!==w||e[60]!==v||e[61]!==D||e[62]!==$?(V=s.jsxs("div",{className:"flex flex-col gap-3",children:[w,v,D,$]}),e[59]=w,e[60]=v,e[61]=D,e[62]=$,e[63]=V):V=e[63],V};function SS(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=kt(),l=ss(J=>J.loadProviders),d=ss(J=>J.loadAgents),u=ss(J=>J.providers),m=ss(J=>J.currentProviderId),f=ss(J=>J.currentModelId),p=ss(J=>J.currentVariant||""),y=ss(J=>J.currentAgentName||""),g=Ee(J=>J.timeFormatPreference),b=Ee(J=>J.weekStartPreference),x=Ee(J=>J.isMobile),[h,C]=Xe.useState(()=>uf(n,{providerID:m,modelID:f,variant:p,agent:y})),[w,v]=Xe.useState(!1),[S,k]=Xe.useState(!1),[j,A]=Xe.useState(!1),[D,N]=Xe.useState(""),[B,T]=Xe.useState(!1),[E,_]=Xe.useState(""),[R,$]=Xe.useState(!1),[V,z]=Xe.useState(""),[F,ne]=Xe.useState(()=>{const J=ha(n?.schedule?.date||"")||new Date;return new Date(J.getFullYear(),J.getMonth(),1)}),te=Xe.useRef(null),q=Xe.useRef(null),H=Xe.useRef(null),X=Xe.useRef(null),oe=Xe.useRef(null),ue=Xe.useMemo(()=>pS(c),[c]),Se=Xe.useMemo(()=>hS(c),[c]),Z=Xe.useMemo(()=>g==="24h"?!0:g==="12h"?!1:ue,[g,ue]),ke=Xe.useMemo(()=>b==="sunday"?0:b==="monday"?1:Se,[b,Se]),Y=Xe.useMemo(()=>{const J=gS(c);return xS(gh.map(L=>({value:L,label:J[L]||""})),ke)},[c,ke]);Xe.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),Xe.useEffect(()=>{if(!e)return;C(uf(n,{providerID:m,modelID:f,variant:p,agent:y}));const J=ha(n?.schedule?.date||"")||new Date;ne(new Date(J.getFullYear(),J.getMonth(),1)),k(!1),T(!1),A(!1),_(""),N("")},[e,n,m,f,p,y]),Xe.useEffect(()=>{if(!S)return;const J=L=>{te.current&&!te.current.contains(L.target)&&k(!1)};return document.addEventListener("mousedown",J),()=>{document.removeEventListener("mousedown",J)}},[S]);const ge=Xe.useMemo(()=>{const L=u.find(ae=>ae.id===h.execution.providerID)?.models?.find(ae=>ae.id===h.execution.modelID);return L?.variants?Object.keys(L.variants):[]},[u,h.execution.providerID,h.execution.modelID]),O=ge.length>0,se=Xe.useMemo(()=>!O||!h.execution.variant?"__default":ge.includes(h.execution.variant)?h.execution.variant:"__default",[h.execution.variant,O,ge]);Xe.useEffect(()=>{O||!h.execution.variant||C(J=>({...J,execution:{...J.execution,variant:""}}))},[O,h.execution.variant]);const ee=Xe.useCallback((J,L)=>{C(ae=>{const re=new Set(ae.schedule.weekdays);return L?re.add(J):re.delete(J),{...ae,schedule:{...ae.schedule,weekdays:Array.from(re).sort((Oe,qe)=>Oe-qe)}}})},[]),je=Xe.useCallback((J,L)=>{C(ae=>{const re=ae.schedule.times.slice();return re[J]=L,{...ae,schedule:{...ae.schedule,times:re}}})},[]),De=Xe.useCallback(J=>{C(L=>{const ae=L.schedule.times.filter((re,Oe)=>Oe!==J);return{...L,schedule:{...L.schedule,times:ae.length>0?ae:["09:00"]}}})},[]),Be=Xe.useCallback(()=>{C(J=>({...J,schedule:{...J.schedule,times:[...J.schedule.times,"12:00"]}}))},[]),Fe=Xe.useMemo(()=>bS(),[]),Me=Xe.useMemo(()=>cf(Fe),[Fe]),me=Xe.useMemo(()=>{const J=ha(h.schedule.onceDate);return J?df(J,Fe)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(J):null},[h.schedule.onceDate,c,a,Fe]),Ae=Xe.useMemo(()=>cf(F).getTime()<=Me.getTime(),[F,Me]),pe=Xe.useMemo(()=>Y.map(J=>J.label),[Y]),ce=Xe.useCallback(J=>{C(L=>({...L,schedule:{...L.schedule,onceDate:J}}))},[]),he=Xe.useCallback((J,L)=>{if(J.startsWith("/")){const qe=J.indexOf(" "),Ge=J.indexOf(`
167
- `),Je=Math.min(qe===-1?J.length:qe,Ge===-1?J.length:Ge);if(L<=Je&&qe===-1){_(J.substring(1,Je)),T(!0),A(!1),$(!1);return}}T(!1);const ae=J.substring(0,L),re=ae.lastIndexOf("#");if(re!==-1){const qe=re>0?ae[re-1]:null,Ge=ae.substring(re+1);if((!qe||/\s/.test(qe))&&!Ge.includes(" ")&&!Ge.includes(`
168
- `)){z(Ge),$(!0),A(!1);return}}$(!1);const Oe=ae.lastIndexOf("@");if(Oe!==-1){const qe=Oe>0?ae[Oe-1]:null,Ge=ae.substring(Oe+1);(!qe||/\s/.test(qe))&&!Ge.includes(" ")&&!Ge.includes(`
169
- `)?(N(Ge),A(!0)):A(!1);return}A(!1)},[]),Ne=Xe.useCallback(J=>{C(L=>({...L,execution:{...L.execution,prompt:J}}))},[]),fe=Xe.useCallback(J=>{const L=h.execution.prompt,re=q.current?.selectionStart??L.length,qe=L.substring(0,re).lastIndexOf("@"),Ge=J.relativePath&&J.relativePath.trim().length>0?J.relativePath.trim():J.path||J.name,Je=qe!==-1?qe:re,nt=`${L.substring(0,Je)}@${Ge} ${L.substring(re)}`,gt=Je+Ge.length+2;Ne(nt),A(!1),N(""),requestAnimationFrame(()=>{const yt=q.current;yt&&(yt.selectionStart=gt,yt.selectionEnd=gt,yt.focus()),he(nt,gt)})},[h.execution.prompt,Ne,he]),P=Xe.useCallback(J=>{const L=h.execution.prompt,re=q.current?.selectionStart??L.length,qe=L.substring(0,re).lastIndexOf("@"),Ge=qe!==-1?qe:re,Je=`${L.substring(0,Ge)}@${J} ${L.substring(re)}`,nt=Ge+J.length+2;Ne(Je),A(!1),N(""),requestAnimationFrame(()=>{const gt=q.current;gt&&(gt.selectionStart=nt,gt.selectionEnd=nt,gt.focus()),he(Je,nt)})},[h.execution.prompt,Ne,he]),M=Xe.useCallback(J=>{const L=`/${J.name} `;Ne(L),T(!1),_(""),$(!1),requestAnimationFrame(()=>{const ae=q.current;ae&&(ae.focus(),ae.selectionStart=ae.value.length,ae.selectionEnd=ae.value.length),he(L,L.length)})},[Ne,he]),de=Xe.useCallback((J,L)=>{const ae=h.execution.prompt,Oe=q.current?.selectionStart??ae.length,Ge=ae.substring(0,Oe).lastIndexOf("#"),Je=Ge!==-1?Ge:Oe,nt=`${ae.substring(0,Je)}#${L} ${ae.substring(Oe)}`,gt=Je+L.length+2;Ne(nt),$(!1),z(""),requestAnimationFrame(()=>{const yt=q.current;yt&&(yt.selectionStart=gt,yt.selectionEnd=gt,yt.focus()),he(nt,gt)})},[h.execution.prompt,Ne,he]),xe=Xe.useCallback(J=>{if(B&&X.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")){J.preventDefault(),X.current.handleKeyDown(J.key);return}j&&H.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")&&(J.preventDefault(),H.current.handleKeyDown(J.key)),R&&oe.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")&&(J.preventDefault(),oe.current.handleKeyDown(J.key))},[B,j,R]),W=Xe.useCallback(async()=>{const J=wS(h,a);if(J){le.error(J);return}const L={...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:vS(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}:{}};v(!0);try{await o(L),r(!1)}catch(ae){le.error(ae instanceof Error?ae.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{v(!1)}},[h,r,o,a]),be=Xe.useId(),ve=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"),ye=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(jn,{id:"sched-name",value:h.name,onChange:J=>C(L=>({...L,name:J.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(zn,{value:h.schedule.kind,onValueChange:J=>{C(L=>({...L,schedule:{...L.schedule,kind:J,...J==="cron"&&!L.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(Wn,{className:"w-fit max-w-full",children:s.jsx(Cn,{children:J=>a(J==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":J==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":J==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(Un,{children:[s.jsx(Ms,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(Ms,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(Ms,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(Ms,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),h.schedule.kind==="cron"?s.jsx(jS,{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:te,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(J=>!J),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(I,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:dS(h.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"})]}),S?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(J=>rf(J,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Ae,children:s.jsx(I,{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(F)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>ne(J=>rf(J,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4"})})]}),s.jsx("div",{className:"mb-1 grid grid-cols-7 gap-1 px-1",children:pe.map((J,L)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:J},`${J}-${L}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:uS(F,ke).map(({date:J,inCurrentMonth:L})=>{const ae=nf(J),re=ae===h.schedule.onceDate,Oe=df(J,Fe),qe=J.getTime()<Fe.getTime(),Ge=re?"bg-interactive-selection text-interactive-selection-foreground":qe?"text-muted-foreground/40":L?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{qe||(ce(ae),k(!1))},disabled:qe,className:["h-8 rounded-md typography-ui-label",Ge,Oe&&!re?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",qe?"cursor-not-allowed opacity-45":""].join(" "),children:J.getDate()},ae)})}),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:me||""}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:()=>{ce(nf(Fe)),ne(new Date(Fe.getFullYear(),Fe.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(lf,{value:h.schedule.onceTime,use24Hour:Z,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:J=>C(L=>({...L,schedule:{...L.schedule,onceTime:J}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(zn,{value:h.schedule.timezone,onValueChange:J=>{C(L=>({...L,schedule:{...L.schedule,timezone:J}}))},children:[s.jsx(Wn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),s.jsx(Un,{children:oc.map(J=>s.jsx(Ms,{value:J,children:J},J))})]})]})]})]}):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:Y.map(J=>{const L=h.schedule.weekdays.includes(J.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",L?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(Pi,{checked:L,onChange:ae=>ee(J.value,ae),ariaLabel:J.label}),s.jsx("button",{type:"button",onClick:()=>ee(J.value,!L),className:"group-hover:text-foreground",children:J.label})]},J.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((J,L)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(lf,{value:J,use24Hour:Z,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:ae=>je(L,ae)}),h.schedule.times.length>1?s.jsx($e,{type:"button",size:"icon",variant:"ghost",onClick:()=>De(L),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null]},L))}),s.jsx("div",{children:s.jsxs($e,{type:"button",size:"sm",variant:"outline",onClick:Be,children:[s.jsx(I,{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(zn,{value:h.schedule.timezone,onValueChange:J=>{C(L=>({...L,schedule:{...L.schedule,timezone:J}}))},children:[s.jsx(Wn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),s.jsx(Un,{children:oc.map(J=>s.jsx(Ms,{value:J,children:J},J))})]})]})]}),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(Qf,{providerId:h.execution.providerID,modelId:h.execution.modelID,onChange:(J,L)=>{C(ae=>({...ae,execution:{...ae.execution,providerID:J,modelID:L,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(zn,{value:se,disabled:!O,onValueChange:J=>{C(L=>({...L,execution:{...L.execution,variant:J==="__default"?"":J}}))},children:[s.jsx(Wn,{className:"w-fit max-w-full",children:s.jsx(Cn,{children:J=>J==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):J})}),s.jsxs(Un,{children:[s.jsx(Ms,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),ge.map(J=>s.jsx(Ms,{value:J,children:J},J))]})]})]})]}),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(Jf,{agentName:h.execution.agent,filter:J=>jc(J.mode),onChange:J=>C(L=>({...L,execution:{...L.execution,agent:J}}))})]}),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(Ni,{id:"sched-prompt",ref:q,value:h.execution.prompt,onChange:J=>{const L=J.target.value;Ne(L);const ae=J.target.selectionStart??L.length;he(L,ae)},onKeyDown:xe,rows:8,placeholder:a("sessions.scheduledTasks.editor.prompt.placeholder"),className:"typography-meta min-h-[120px] max-h-[300px] resize-none overflow-y-auto"}),B?s.jsx(cm,{ref:X,searchQuery:E,onCommandSelect:M,onClose:()=>T(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,j?s.jsx(dm,{ref:H,searchQuery:D,onFileSelect:fe,onAgentSelect:P,onClose:()=>A(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,R?s.jsx(um,{ref:oe,searchQuery:V,onSnippetSelect:de,onClose:()=>$(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]})]}),Re=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(Pi,{checked:h.enabled,onChange:J=>C(L=>({...L,enabled:J})),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($e,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(!1),disabled:w,children:a("sessions.scheduledTasks.editor.actions.cancel")}),s.jsx($e,{type:"button",size:"sm",onClick:W,disabled:w,children:a(w?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return x?s.jsx(Ua,{open:e,title:G,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:J=>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}),J]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:ye})]}),footer:Re,children:Le}):s.jsx($s,{open:e,onOpenChange:J=>{!J&&ve()||r(J)},children:s.jsxs(Vs,{"aria-describedby":be,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(ln,{id:be,className:"sr-only",children:ye}),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(Us,{className:"typography-ui-label font-medium text-foreground",children:G}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:ye})]})}),s.jsx(Ha,{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:Re})})]})})}function NS(t){return lo(t,{min:0,max:23})}function kS(t,e){return lo(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function CS(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 AS(t){return s.jsx(Ms,{value:t,children:t},t)}const DS=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))},IS=(t,e)=>{const n=DS(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||""})},PS=(t,e)=>!t||!Number.isFinite(t)?"":zf(t,e),ff=(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 f=Math.round(r/o);return l?e("sessions.scheduledTasks.dialog.relativeTime.inMinutes",{count:f}):e("sessions.scheduledTasks.dialog.relativeTime.minutesAgo",{count:f})}if(r<c){const f=Math.floor(r/a),p=Math.round(r%a/o),y=p>0?`${f}h ${p}m`:`${f}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:y}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:y})}const d=Math.floor(r/c),u=Math.round(r%c/a),m=u>0?`${d}d ${u}h`:`${d}d`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:m}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:m})},TS={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"}},RS=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function ES(){const{t}=kt(),e=Ee(R=>R.isScheduledTasksDialogOpen),n=Ee(R=>R.setScheduledTasksDialogOpen),r=Ee(R=>R.isMobile),o=Ee(R=>R.timeFormatPreference),a=Ns(R=>R.projects),c=Ns(R=>R.getActiveProject()),l=Xs(R=>R.homeDirectory),{currentTheme:d}=qr(),[u,m]=Xe.useState(""),[f,p]=Xe.useState([]),[y,g]=Xe.useState(!0),[b,x]=Xe.useState(!1),[h,C]=Xe.useState(null),[w,v]=Xe.useState(null),S=Xe.useMemo(()=>a.find(R=>R.id===u)||null,[a,u]),k=Xe.useCallback(R=>{const $=R.label?.trim()||Ti(R.path,l||void 0),V=R.icon?Tc[R.icon]:null,z=R.color?Ya[R.color]:void 0,F=V?s.jsx(I,{name:V,className:"h-3.5 w-3.5 shrink-0",style:z?{color:z}:void 0}):s.jsx(I,{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:[R.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:R.iconBackground?{backgroundColor:R.iconBackground}:void 0,children:s.jsx(Qa,{project:{id:R.id,iconImage:R.iconImage??null},options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:F})}):F,s.jsx("span",{className:"truncate",children:$})]})},[l,d.metadata.variant,d.colors.surface.foreground]),j=Xe.useCallback(async(R,$)=>{if(!R){p([]);return}$?.silent||g(!0);try{const V=await iS(R);V.sort((z,F)=>{if(z.enabled!==F.enabled)return z.enabled?-1:1;const ne=z.name.localeCompare(F.name);return ne!==0?ne:(z.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(F.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),p(V)}catch(V){le.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),$?.silent||p([])}finally{$?.silent||g(!1)}},[t]);Xe.useEffect(()=>{if(!e)return;const R=c?.id||a[0]?.id||"";m(R),R?j(R):(p([]),g(!1))},[e,c,a,j]),Xe.useEffect(()=>{if(!e)return;let R=null;const $=hh(V=>{V.type==="scheduled-task-ran"&&V.projectId===u&&(R&&clearTimeout(R),R=setTimeout(()=>{j(u,{silent:!0})},400))});return()=>{R&&clearTimeout(R),$()}},[e,u,j]);const A=Xe.useCallback(async R=>{if(!u)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await tf(u,R),await j(u),le.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[u,j,t]),D=Xe.useCallback(async(R,$)=>{if(u){v(R.id),p(V=>V.map(z=>z.id===R.id?{...z,enabled:$}:z));try{await tf(u,{...R,enabled:$}),await j(u,{silent:!0})}catch(V){le.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await j(u,{silent:!0})}finally{v(null)}}},[u,j,t]),N=Xe.useCallback(async R=>{if(!(!u||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:R.name})))){v(R.id);try{await oS(u,R.id),await j(u,{silent:!0}),le.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(V){le.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{v(null)}}},[u,j,t]),B=Xe.useCallback(async R=>{if(u){v(R.id);try{await aS(u,R.id),await Promise.all([j(u,{silent:!0}),Na()]),le.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch($){le.error($ instanceof Error?$.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{v(null)}}},[u,j,t]),T=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(zn,{value:u||"__none",onValueChange:R=>{const $=R==="__none"?"":R;m($),$?j($):p([])},children:[s.jsx(Wn,{className:r?"w-full":void 0,children:S?s.jsx(Cn,{children:k(S)}):s.jsx(Cn,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(Un,{children:[a.length===0?s.jsx(Ms,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(R=>s.jsx(Ms,{value:R.id,children:k(R)},R.id))]})]})]}),E=()=>{C(null),x(!0)},_=s.jsxs("div",{className:"space-y-4",children:[r?T:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[T,s.jsxs($e,{onClick:E,disabled:!u,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:y?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"})," ",t("sessions.scheduledTasks.dialog.loading")]}):f.length===0?s.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 typography-meta text-muted-foreground",children:t(u?"sessions.scheduledTasks.dialog.empty.noTasks":"sessions.scheduledTasks.dialog.empty.selectProject")}):s.jsx("div",{className:"space-y-2.5",children:f.map(R=>{const $=w===R.id,V=R.state?.lastStatus||"idle",z=TS[V],F=t(V==="success"?"sessions.scheduledTasks.dialog.status.success":V==="error"?"sessions.scheduledTasks.dialog.status.error":V==="running"?"sessions.scheduledTasks.dialog.status.running":"sessions.scheduledTasks.dialog.status.idle"),ne=R.state?.nextRunAt,te=R.state?.lastRunAt;return s.jsxs("div",{className:Pe("rounded-lg border border-border p-4 transition-opacity",!R.enabled&&"opacity-60"),children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-header truncate font-semibold text-foreground",children:R.name}),s.jsx("div",{className:"typography-micro truncate text-muted-foreground",children:IS(R,t)})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-5 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(I,{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:ff(ne,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:PS(ne,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(I,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),V==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(I,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):te?s.jsxs(s.Fragment,{children:[z.tone!=="muted"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:`var(--status-${z.tone})`},children:[s.jsx(I,{name:z.Icon,className:"h-3.5 w-3.5"}),F]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:ff(te,t)})]}):s.jsx("span",{children:t("sessions.scheduledTasks.dialog.lastRun.never")})]})]}),R.state?.lastError?s.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-md border p-2 typography-micro",style:RS("error"),children:[s.jsx(I,{name:"error-warning",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"min-w-0 break-words",children:R.state.lastError})]}):null,s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("label",{className:Pe("inline-flex cursor-pointer items-center gap-2 typography-micro font-medium",R.enabled?"text-foreground":"text-muted-foreground",$&&"cursor-not-allowed opacity-50"),children:[s.jsx(Pi,{checked:R.enabled,onChange:q=>{D(R,q)},ariaLabel:R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:R.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:R.name}),disabled:$}),R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.enabled"):t("sessions.scheduledTasks.dialog.taskToggle.paused")]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{B(R)},disabled:$,children:[s.jsx(I,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{C(R),x(!0)},disabled:$,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:R.name}),children:[s.jsx(I,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx($e,{variant:"destructive",size:"sm",onClick:()=>{N(R)},disabled:$,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:R.name}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})]})]})]},R.id)})})})]});return s.jsxs(s.Fragment,{children:[r?s.jsx(Ua,{open:e,title:t("sessions.scheduledTasks.dialog.title"),onClose:()=>n(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:R=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t("sessions.scheduledTasks.dialog.title")}),R]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:t("sessions.scheduledTasks.dialog.description")})]}),footer:s.jsxs($e,{className:"w-full",onClick:E,disabled:!u,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:_}):s.jsx($s,{open:e,onOpenChange:n,children:s.jsxs(Vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(Gs,{children:[s.jsx(Us,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(ln,{children:t("sessions.scheduledTasks.dialog.description")})]}),_]})}),s.jsx(SS,{open:b,task:h,onOpenChange:x,onSave:A})]})}const MS=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>as(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(d=>Ro(d,t.normalizedPath,r)))(e.archivedSessions),c=e.sessions.filter(l=>l.time?.archived||as(l.directory??null)?!1:Ro(l,t.normalizedPath,r));return so([...a,...c])},FS=t=>{const e=ft.c(12),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,isSessionsLoading:l,foldersMap:d,createFolder:u,addSessionToFolder:m,cleanupSessions:f}=t;let p,y;e[0]!==m||e[1]!==o||e[2]!==a||e[3]!==f||e[4]!==u||e[5]!==d||e[6]!==l||e[7]!==c||e[8]!==n||e[9]!==r?(p=()=>{l||n.forEach(g=>{const b=Oc(g.normalizedPath),x=MS(g,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c}),h=new Set(x.map(LS)),C=d[b]??[],w=new Map(C.map(OS));x.forEach(v=>{const S=ub(v,g.normalizedPath),k=S.toLowerCase();let j=w.get(k);j||(j=u(b,S),w.set(k,j)),j.sessionIds.includes(v.id)||m(b,j.id,v.id)}),f(b,h)})},y=[n,r,o,a,c,l,d,u,m,f],e[0]=m,e[1]=o,e[2]=a,e[3]=f,e[4]=u,e[5]=d,e[6]=l,e[7]=c,e[8]=n,e[9]=r,e[10]=p,e[11]=y):(p=e[10],y=e[11]),i.useEffect(p,y)};function LS(t){return t.id}function OS(t){return[t.name.toLowerCase(),t]}const BS=t=>{const e=ft.c(41),{normalizedProjects:n,getSessionsForProject:r,getArchivedSessionsForProject:o,availableWorktreesByProject:a,projectRepoStatus:c,projectRootBranches:l,lastRepoStatus:d,buildGroupedSessions:u,hasSessionSearchQuery:m,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:y,foldersMap:g}=t;let b;if(e[0]!==a||e[1]!==u||e[2]!==o||e[3]!==r||e[4]!==d||e[5]!==n||e[6]!==c||e[7]!==l){let N;e[9]!==a||e[10]!==u||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(N=B=>{const T=so([...r(B),...o(B)]),E=a.get(B.normalizedPath)??[],_=c.has(B.id)?!!c.get(B.id):d,R=u(T,B.normalizedPath,E,l.get(B.id)??null,_);return{project:B,groups:R}},e[9]=a,e[10]=u,e[11]=o,e[12]=r,e[13]=d,e[14]=c,e[15]=l,e[16]=N):N=e[16],b=n.map(N),e[0]=a,e[1]=u,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 x=b,h=x;let C;if(e[17]!==y||e[18]!==p||e[19]!==g||e[20]!==m||e[21]!==f||e[22]!==h){e:{const N=new WeakMap;if(!m){C=N;break e}const B=T=>T.reduce((E,_)=>E+1+B(_.children),0);h.forEach(T=>{T.groups.forEach(E=>{const _=p(E.sessions,f),R=B(_),$=y(E).includes(f),V=as(E.directory??null),F=(V?g[V]??[]:[]).filter(ne=>ne.name.toLowerCase().includes(f)).length;N.set(E,{filteredNodes:_,matchedSessionCount:R,folderNameMatchCount:F,groupMatches:$,hasMatch:$||R>0||F>0})})}),C=N}e[17]=y,e[18]=p,e[19]=g,e[20]=m,e[21]=f,e[22]=h,e[23]=C}else C=e[23];const w=C;let v;e:{if(!m){v=h;break e}let N;if(e[24]!==w||e[25]!==h){let B;e[27]!==w?(B=T=>({...T,groups:T.groups.filter(E=>w.get(E)?.hasMatch===!0)}),e[27]=w,e[28]=B):B=e[28],N=h.map(B).filter(_S),e[24]=w,e[25]=h,e[26]=N}else N=e[26];v=N}const S=v,k=m?S:h;let j;e:{if(!m){j=0;break e}let N;if(e[29]!==w||e[30]!==k){let B;e[32]!==w?(B=(T,E)=>T+E.groups.reduce((_,R)=>{const $=w.get(R);if(!$)return _;const V=$.folderNameMatchCount+($.groupMatches?1:0);return _+$.matchedSessionCount+V},0),e[32]=w,e[33]=B):B=e[33],N=k.reduce(B,0),e[29]=w,e[30]=k,e[31]=N}else N=e[31];j=N}const A=j;let D;return e[34]!==w||e[35]!==x||e[36]!==A||e[37]!==S||e[38]!==k||e[39]!==h?(D={projectSections:x,visibleProjectSections:h,groupSearchDataByGroup:w,searchableProjectSections:S,sectionsForRender:k,searchMatchCount:A},e[34]=w,e[35]=x,e[36]=A,e[37]=S,e[38]=k,e[39]=h,e[40]=D):D=e[40],D};function _S(t){return t.groups.length>0}const VS=t=>{const e=ft.c(26),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:c,handleSessionSelect:l,newSessionDraftOpen:d,mobileVariant:u,openNewSessionDraft:m,setActiveMainTab:f,setSessionSwitcherOpen:p}=t;let y,g;if(e[0]!==n){g=new Map,y=new Map;const k=(j,A,D,N)=>{g.has(j)||g.set(j,new Map);const B=g.get(j);N.forEach(T=>{const E=as(T.worktree?.path??T.session.directory??D??A);B.set(T.session.id,{directory:E}),y.has(j)||y.set(j,{id:T.session.id,directory:E}),T.children.length>0&&k(j,A,E,T.children)})};n.forEach(j=>{j.groups.forEach(A=>{k(j.project.id,j.project.normalizedPath,A.directory,A.sessions)})}),e[0]=n,e[1]=y,e[2]=g}else y=e[1],g=e[2];let b;e[3]!==y||e[4]!==g?(b={metaByProject:g,firstSessionByProject:y},e[3]=y,e[4]=g,e[5]=b):b=e[5];const x=b,h=i.useRef(null);let C,w;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==u||e[11]!==d||e[12]!==m||e[13]!==n||e[14]!==x||e[15]!==f||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=x.metaByProject.get(r);if(c&&j&&j.has(c)){a(E=>{if(E.get(r)===c)return E;const _=new Map(E);return _.set(r,c),_});return}if(c&&j)return;if(!j||j.size===0){f("chat"),u&&p(!1),m({directoryOverride:k.project.normalizedPath});return}const A=o.get(r),D=A&&j.has(A)?A:null,N=x.firstSessionByProject.get(r)?.id??null,B=D??N;if(!B||B===c)return;const T=j.get(B)?.directory??null;l(B,T,r)},w=[r,o,c,l,d,u,m,n,x,f,p,a],e[6]=r,e[7]=o,e[8]=c,e[9]=l,e[10]=u,e[11]=d,e[12]=m,e[13]=n,e[14]=x,e[15]=f,e[16]=a,e[17]=p,e[18]=C,e[19]=w):(C=e[18],w=e[19]),i.useLayoutEffect(C,w);let v,S;e[20]!==r||e[21]!==c||e[22]!==x||e[23]!==a?(v=()=>{if(!r||!c)return;const k=x.metaByProject.get(r);!k||!k.has(c)||a(j=>{if(j.get(r)===c)return j;const A=new Map(j);return A.set(r,c),A})},S=[r,c,x,a],e[20]=r,e[21]=c,e[22]=x,e[23]=a,e[24]=v,e[25]=S):(v=e[24],S=e[25]),i.useEffect(v,S)},$S=t=>{const e=ft.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(zS)),u=[];return l.forEach(m=>{const f=d.get(m);f&&(u.push(f),d.delete(m))}),c.forEach(m=>{d.has(m.id)&&u.push(m)}),u},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 zS(t){return[t.id,t]}const ea=t=>!!t.time?.archived,WS=t=>{const{t:e}=kt(),n=i.useCallback(c=>[c.label,c.branch??"",c.description??"",c.directory??""].join(" ").toLowerCase(),[]),r=i.useCallback(c=>{const l=as(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,u,m)=>{const f=as(l??null),p=so(c).sort((T,E)=>Gi(T,E,t.pinnedSessionIds)),y=new Map(p.map(T=>[T.id,T])),g=new Map;p.forEach(T=>{const E=T.parentID;if(!E)return;const _=y.get(E);if(!_||ea(_)!==ea(T))return;const R=g.get(E)??[];R.push(T),g.set(E,R)}),g.forEach(T=>T.sort((E,_)=>Gi(E,_,t.pinnedSessionIds)));const b=new Map;d.forEach(T=>{if(T.path){const E=as(T.path)??T.path;b.set(E,T)}});const x=T=>{const E=as(T.directory??null),_=t.worktreeMetadata.get(T.id)??null;if(_)return _;if(E){const R=b.get(E)??null;if(R&&E!==f)return R}return null},h=T=>{const E=g.get(T.id)??[];return{session:T,children:E.map(_=>h(_)),worktree:x(T)}},C=p.filter(T=>{const E=T.parentID;if(!E)return!0;const _=y.get(E);return _?ea(_)!==ea(T):!0}),w=new Map,v="__archived__",S=T=>{if(T.time?.archived)return v;if(t.isVSCode)return f??"__project_root__";const _=as(t.worktreeMetadata.get(T.id)?.path??null)??Rr(T);return _?_!==f&&b.has(_)?_:_===f?f??"__project_root__":v:v};C.forEach(T=>{const E=h(T),_=S(T);w.has(_)||w.set(_,[]),w.get(_)?.push(E)});const k=f??"__project_root__",j=[{id:"root",label:m&&u&&u!=="HEAD"?e("sessions.sidebar.grouping.projectRootWithBranch",{branch:u}):e("sessions.sidebar.grouping.projectRoot"),branch:u??null,description:f?ka(f,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:w.get(k)??[]}],A=new Map;d.forEach(T=>{const E=as(T.path)??T.path,_=w.get(E)??[],R=_.length>0,$=_.reduce((V,z)=>{const F=Number(z.session.time?.updated??z.session.time?.created??0);return Number.isFinite(F)?Math.max(V,F):V},0);A.set(E,{hasActiveSession:R,lastUpdatedAt:$})});const D=[...d].sort((T,E)=>{const _=as(T.path)??T.path,R=as(E.path)??E.path,$=A.get(_)??{hasActiveSession:!1,lastUpdatedAt:0},V=A.get(R)??{hasActiveSession:!1,lastUpdatedAt:0};if($.hasActiveSession!==V.hasActiveSession)return $.hasActiveSession?-1:1;if($.hasActiveSession&&V.hasActiveSession)return V.lastUpdatedAt-$.lastUpdatedAt;const z=(T.label||T.branch||T.name||T.path||"").toLowerCase(),F=(E.label||E.branch||E.name||E.path||"").toLowerCase();return z.localeCompare(F)});(t.isVSCode?[]:D).forEach(T=>{const E=as(T.path)??T.path,_=t.gitBranches.get(E)?.trim()||null,R=T.branch?.trim()||null,V=!!(_&&R&&T.label&&Jd(T.label)===Jd(R))?_:T.label||T.name||Ti(E,t.homeDirectory)||E;j.push({id:`worktree:${E}`,label:V,branch:_||R,description:ka(E,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:T,directory:E,folderScopeKey:E,sessions:w.get(E)??[]})});const B=w.get(v)??[];return B.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&&f?Oc(f):null,sessions:B}),j},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitBranches,t.isVSCode,e]);return{buildGroupSearchText:n,buildSessionSearchText:r,filterSessionNodesForSearch:o,buildGroupedSessions:a}},US=t=>{const e=ft.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,u;e[4]!==n||e[5]!==a||e[6]!==r?(d=()=>{if(!n||typeof document>"u")return;const m=f=>{a.current&&(a.current.contains(f.target)||r(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},u=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=d,e[8]=u):(d=e[7],u=e[8]),i.useEffect(d,u)},HS=t=>{const e=ft.c(42),{t:n}=kt(),[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=($,V,z)=>{const F=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(z&&z!==t.activeProjectId&&t.setActiveProjectIdOnly(z),V&&V!==t.currentDirectory&&t.setDirectory(V,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),$===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.($),F();return}t.setCurrentSession($,V??null),t.onSessionSelected?.($),F()},e[2]=t,e[3]=d):d=e[3];const u=d;let m;e[4]!==t?(m=($,V)=>{t.setEditingId($),t.setEditTitle(V)},e[4]=t,e[5]=m):m=e[5];const f=m;let p;e[6]!==t?(p=async $=>{if(!t.editingId)return;const V=($??t.editTitle).trim();V&&await t.updateSessionTitle(t.editingId,V),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=p):p=e[7];const y=p;let g;e[8]!==t?(g=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=g):g=e[9];const b=g;let x;e[10]!==t||e[11]!==n?(x=async $=>{const V=await t.shareSession($.id);V&&V.share?.url?le.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):le.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=x):x=e[12];const h=x;let C;e[13]!==n?(C=($,V)=>{fr($).then(z=>{if(!z.ok){le.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(V),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{le.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=C):C=e[14];const w=C;let v;e[15]!==t||e[16]!==n?(v=async $=>{await t.unshareSession($)?le.success(n("sessions.sidebar.session.unshare.success")):le.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=v):v=e[17];const S=v;let k;e[18]!==t.childrenMap?(k=$=>{const V=[],z=F=>{(t.childrenMap.get(F)??[]).forEach(te=>{V.push(te),z(te.id)})};return z($),V},e[18]=t.childrenMap,e[19]=k):k=e[19];const j=k,A=KS;let D;e[20]!==t||e[21]!==j||e[22]!==n?(D=async($,V,z)=>{const F=V?.archivedBucket===!0||V?.hardDelete===!0,ne=z?.descendantIds??A(j($.id),F).map(qS);if(ne.length===0){(F?await t.deleteSession($.id):await t.archiveSession($.id))?le.success(n(F?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):le.error(n(F?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const te=[$.id,...ne];if(F){const{deletedIds:X,failedIds:oe}=await t.deleteSessions(te);if(oe.length===0){const ue=X.length;le.success(ue===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:ue}):n("sessions.sidebar.bulkActions.deletedPlural",{count:ue}))}else le.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:q,failedIds:H}=await t.archiveSessions(te);q.length>0&&le.success(q.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:q.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:q.length})),H.length>0&&le.error(H.length===1?n("sessions.sidebar.bulkActions.failedArchiveSingle",{count:H.length}):n("sessions.sidebar.bulkActions.failedArchivePlural",{count:H.length}))},e[20]=t,e[21]=j,e[22]=n,e[23]=D):D=e[23];const N=D;let B;e[24]!==t||e[25]!==j||e[26]!==N?(B=($,V)=>{const z=V?.archivedBucket===!0||V?.hardDelete===!0,F=A(j($.id),z).map(YS);if(!t.showDeletionDialog||V?.skipConfirm===!0){N($,V,{descendantIds:F});return}t.setDeleteSessionConfirm({session:$,descendantCount:F.length,descendantIds:F,archivedBucket:z})},e[24]=t,e[25]=j,e[26]=N,e[27]=B):B=e[27];const T=B;let E;e[28]!==t||e[29]!==N?(E=async()=>{if(!t.deleteSessionConfirm)return;const{session:$,archivedBucket:V,descendantIds:z}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await N($,{archivedBucket:V},{descendantIds:z})},e[28]=t,e[29]=N,e[30]=E):E=e[30];const _=E;let R;return e[31]!==_||e[32]!==r||e[33]!==b||e[34]!==w||e[35]!==T||e[36]!==y||e[37]!==f||e[38]!==u||e[39]!==h||e[40]!==S?(R={copiedSessionId:r,handleSessionSelect:u,handleSessionDoubleClick:f,handleSaveEdit:y,handleCancelEdit:b,handleShareSession:h,handleCopyShareUrl:w,handleUnshareSession:S,handleDeleteSession:T,confirmDeleteSession:_},e[31]=_,e[32]=r,e[33]=b,e[34]=w,e[35]=T,e[36]=y,e[37]=f,e[38]=u,e[39]=h,e[40]=S,e[41]=R):R=e[41],R};function GS(t){return!t.time?.archived}function KS(t,e){return e?t:t.filter(GS)}function qS(t){return t.id}function YS(t){return t.id}const QS=["project:active:","project:archived:","recent:active:","recent:archived:"],JS=t=>{const{isVSCode:e,hasLoadedGlobalSessions:n,safeStorage:r,keys:o,sessions:a,setPinnedSessionIds:c,groupOrderByProject:l,activeSessionByProject:d,collapsedGroups:u,setExpandedParents:m,setCollapsedProjects:f}=t,p=i.useRef(null),y=i.useRef(null),g=i.useCallback(()=>{if(e)return;const x=y.current;if(y.current=null,p.current=null,!x)return;const{projects:h}=Ns.getState(),C=h.map(w=>({...w,sidebarCollapsed:x.has(w.id)}));hc({projects:C}).catch(()=>{})},[e]),b=i.useCallback(x=>{typeof window>"u"||e||(y.current=x,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{g()},700))},[e,g]);return i.useEffect(()=>()=>{typeof window<"u"&&p.current!==null&&window.clearTimeout(p.current),p.current=null,y.current=null},[]),i.useEffect(()=>{try{const x=r.getItem(o.sessionExpanded);if(x){const C=JSON.parse(x);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 v=new Set;if(w.forEach(S=>{typeof S!="string"||S.length===0||QS.forEach(k=>v.add(`${k}${S}`))}),v.size>0){m(v);try{r.setItem(o.sessionExpanded,JSON.stringify(Array.from(v)))}catch{}}}}catch{}try{r.removeItem?.(o.sessionExpandedLegacy)}catch{}}}const h=r.getItem(o.projectCollapse);if(h){const C=JSON.parse(h);Array.isArray(C)&&f(new Set(C.filter(w=>typeof w=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,f,m]),i.useEffect(()=>{if(!n||a.length===0)return;const x=new Set(a.map(h=>h.id));c(h=>{let C=!1;const w=new Set;return h.forEach(v=>{x.has(v)?w.add(v):C=!0}),C?w:h})},[n,a,c]),i.useEffect(()=>{try{const x=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(x))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const x=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(x))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(u)))}catch{}},[u,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:b}},XS=t=>{const{normalizedProjects:e,gitRepoStatus:n,setProjectRepoStatus:r,setProjectRootBranches:o}=t,{git:a}=Xn(),c=vn(f=>f.ensureStatus);i.useEffect(()=>{if(!a||e.length===0){r(new Map);return}e.forEach(f=>{c(f.normalizedPath,a)})},[e,a,c,r]),i.useEffect(()=>{const f=new Map;e.forEach(p=>{f.set(p.id,n.get(p.normalizedPath)?.isGitRepo??null)}),r(f)},[e,n,r]);const l=i.useMemo(()=>e.map(f=>{const p=n.get(f.normalizedPath)?.branch??"";return`${f.id}:${p}`}).join("|"),[e,n]),d=i.useRef(new Map),u=i.useRef(new Map),m=5*6e4;i.useEffect(()=>{let f=!1;const p=setTimeout(()=>{(async()=>{const g=new Set(e.map(v=>v.id));for(const v of d.current.keys())g.has(v)||(d.current.delete(v),u.current.delete(v));const b=Date.now(),x=e.filter(v=>{const S=n.get(v.normalizedPath);if(S?.isGitRepo===!1)return d.current.delete(v.id),u.current.delete(v.id),!1;if(S?.isGitRepo!==!0||S.branch===null)return!1;const k=S.branch.trim(),j=`${v.normalizedPath}\0${k}`,A=d.current.get(v.id);if(A===j){const D=u.current.get(v.id);return D&&(D.at=b),!1}return!(A!==void 0&&b-(u.current.get(v.id)?.at??0)<m)});if(x.length===0)return;const h=await _m(x,2,async v=>{const S=n.get(v.normalizedPath)?.branch?.trim()??"",k=`${v.normalizedPath}\0${S}`,j=await Ka(v.normalizedPath,S?{knownBranch:S}:void 0).catch(()=>null);return{id:v.id,inputKey:k,branch:j}});if(f)return;const C=h.filter(v=>v.branch);if(C.length===0)return;const w=Date.now();o(v=>{const S=new Map(v);return C.forEach(({id:k,branch:j})=>{j&&S.set(k,j)}),S}),C.forEach(({id:v,inputKey:S,branch:k})=>{d.current.set(v,S),k&&u.current.set(v,{branch:k,at:w})})})()},150);return()=>{f=!0,clearTimeout(p)}},[e,l,n,o])},ZS=t=>{const e=ft.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(x=>{x.normalizedPath&&l.add(x.normalizedPath)}),!n)for(const x of a.values())for(const h of x){const C=as(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 u;e[4]!==d||e[5]!==r?(u=new Map,r.forEach(x=>{const h=Rr(x);if(!h||!d.has(h))return;const C=u.get(h)??[];C.push(x),u.set(h,C)}),e[4]=d,e[5]=r,e[6]=u):u=e[6];const m=u;let f;e[7]!==a||e[8]!==n||e[9]!==m?(f=x=>{const h=n?[]:a.get(x.normalizedPath)??[],C=[x.normalizedPath,...h.map(eN).filter(tN)],w=new Set,v=[];return C.forEach(S=>{(m.get(S)??[]).forEach(j=>{w.has(j.id)||(w.add(j.id),v.push(j))})}),v},e[7]=a,e[8]=n,e[9]=m,e[10]=f):f=e[10];const p=f;let y;e[11]!==o||e[12]!==a||e[13]!==n||e[14]!==r?(y=x=>{if(n){const k=o.filter(A=>{const D=as(A.directory??null),N=as(A.project?.worktree??null);return D?D===x.normalizedPath:N===x.normalizedPath}),j=r.filter(A=>A.time?.archived||as(A.directory??null)?!1:as(A.project?.worktree??null)===x.normalizedPath);return so([...k,...j])}const h=n?[]:a.get(x.normalizedPath)??[],C=new Set([x.normalizedPath,...h.map(sN).filter(nN)]),v=(k=>k.filter(j=>Ro(j,x.normalizedPath,C)))(o),S=r.filter(k=>{if(k.time?.archived||as(k.directory??null))return!1;const A=as(k.project?.worktree??null);return A?A===x.normalizedPath||A.startsWith(`${x.normalizedPath}/`):!1});return so([...v,...S])},e[11]=o,e[12]=a,e[13]=n,e[14]=r,e[15]=y):y=e[15];const g=y;let b;return e[16]!==g||e[17]!==p?(b={getSessionsForProject:p,getArchivedSessionsForProject:g},e[16]=g,e[17]=p,e[18]=b):b=e[18],b};function eN(t){return as(t.path)??t.path}function tN(t){return!!t}function sN(t){return as(t.path)??t.path}function nN(t){return!!t}const rN=t=>{const e=ft.c(10),{isSessionsLoading:n,hasLoadedGlobalSessions:r,sessions:o,archivedSessions:a,normalizedProjects:c,isVSCode:l,availableWorktreesByProject:d,cleanupSessions:u}=t;let m,f;e[0]!==a||e[1]!==d||e[2]!==u||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 x=as(b.directory??null);if(!x)return;const h=p.get(x);if(h){h.add(b.id);return}p.set(x,new Set([b.id]))}),c.forEach(b=>{const x=Oc(b.normalizedPath),h=l?[]:d.get(b.normalizedPath)??[],C=new Set([b.normalizedPath,...h.map(iN).filter(oN)]),w=so([...a,...o.filter(v=>v.time?.archived||as(v.directory??null)?!1:Ro(v,b.normalizedPath,C))]).filter(v=>Ro(v,b.normalizedPath,C));p.set(x,new Set(w.map(aN)))});const y=Bn.getState().foldersMap;new Set([...Object.keys(y),...p.keys()]).forEach(b=>{u(b,p.get(b)??new Set)})},f=[a,d,u,r,n,l,c,o],e[0]=a,e[1]=d,e[2]=u,e[3]=r,e[4]=n,e[5]=l,e[6]=c,e[7]=o,e[8]=m,e[9]=f):(m=e[8],f=e[9]),i.useEffect(m,f)};function iN(t){return as(t.path)??t.path}function oN(t){return!!t}function aN(t){return t.id}const lN=t=>{const e=ft.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(f=>{f.forEach(p=>{const y=p.target.dataset.projectId;y&&l(g=>{const b=new Set(g);return p.isIntersecting?b.delete(y):b.add(y),b})})},{threshold:0});return o.current.forEach(f=>{f&&m.observe(f)}),()=>m.disconnect()},e[1]=n,e[2]=o,e[3]=d):d=e[3];let u;return e[4]!==n||e[5]!==o||e[6]!==r?(u=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=u):u=e[7],i.useEffect(d,u),c},cN=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,El=t=>{if(!t)return null;const e=t.trim();return e&&cN.test(e)?e.toLowerCase():null},dN=t=>{const e=ft.c(198),{open:n,onOpenChange:r,projectId:o,projectName:a,projectPath:c,initialIcon:l,initialColor:d,initialIconBackground:u,onSave:m}=t,f=l===void 0?null:l,p=d===void 0?null:d,y=u===void 0?null:u,{t:g}=kt(),b=Ns(uN),x=Ns(fN),h=Ns(mN);let C;e[0]!==o?(C=Ke=>Ke.projects.find(jt=>jt.id===o)?.iconImage??null,e[0]=o,e[1]=C):C=e[1];const w=Ns(C),{currentTheme:v}=qr(),[S,k]=i.useState(a),[j,A]=i.useState(f),[D,N]=i.useState(p);let B;e[2]!==y?(B=El(y),e[2]=y,e[3]=B):B=e[3];const[T,E]=i.useState(B),[_,R]=i.useState(!1),[$,V]=i.useState(!1),[z,F]=i.useState(!1),[ne,te]=i.useState(!1),[q,H]=i.useState(null),[X,oe]=i.useState(null),[ue,Se]=i.useState(!1),Z=i.useRef(null);let ke;e[4]===Symbol.for("react.memo_cache_sentinel")?(ke=()=>{H(null),oe(hN)},e[4]=ke):ke=e[4];const Y=ke;let ge,O;e[5]!==p||e[6]!==f||e[7]!==y||e[8]!==n||e[9]!==a?(ge=()=>{n&&(k(a),A(f),N(p),E(El(y)),te(!1),Y(),Se(!1))},O=[n,a,f,p,y,Y],e[5]=p,e[6]=f,e[7]=y,e[8]=n,e[9]=a,e[10]=ge,e[11]=O):(ge=e[10],O=e[11]),i.useEffect(ge,O);let se,ee;e[12]===Symbol.for("react.memo_cache_sentinel")?(ee=()=>()=>{Y()},se=[Y],e[12]=se,e[13]=ee):(se=e[12],ee=e[13]),i.useEffect(ee,se);let je,De,Be;if(e[14]!==D||e[15]!==w||e[16]!==j||e[17]!==T||e[18]!==S||e[19]!==r||e[20]!==m||e[21]!==ne||e[22]!==q||e[23]!==o||e[24]!==x||e[25]!==g||e[26]!==b){let Ke;e[30]!==D||e[31]!==j||e[32]!==T||e[33]!==S||e[34]!==r||e[35]!==m||e[36]!==ne||e[37]!==q||e[38]!==o||e[39]!==x||e[40]!==g||e[41]!==b?(Ke=async()=>{const jt=S.trim();if(!jt)return;if(q){R(!0);const Nt=await b(o,q);if(R(!1),!Nt.ok){le.error(Nt.error||g("projectEditDialog.toast.failedToUploadIcon"));return}le.success(g("projectEditDialog.toast.iconUpdated")),Y(),te(!1)}const Lt=ne&&Be;if(Lt){V(!0);const Nt=await x(o);if(V(!1),!Nt.ok){le.error(Nt.error||g("projectEditDialog.toast.failedToRemoveIcon"));return}le.success(g("projectEditDialog.toast.iconRemoved")),te(!1),E(null)}m({label:jt,icon:j,color:D,iconBackground:El(Lt?null:T)}),r(!1)},e[30]=D,e[31]=j,e[32]=T,e[33]=S,e[34]=r,e[35]=m,e[36]=ne,e[37]=q,e[38]=o,e[39]=x,e[40]=g,e[41]=b,e[42]=Ke):Ke=e[42],De=Ke,je=D?Ya[D]??null:null,Be=!!w,e[14]=D,e[15]=w,e[16]=j,e[17]=T,e[18]=S,e[19]=r,e[20]=m,e[21]=ne,e[22]=q,e[23]=o,e[24]=x,e[25]=g,e[26]=b,e[27]=je,e[28]=De,e[29]=Be}else je=e[27],De=e[28],Be=e[29];const Fe=!!(q&&X),Me=w?.source==="custom",me=Be&&!ne||Fe,Ae=me,ce=!ue&&(Fe||Be&&!ne);let he;e[43]===Symbol.for("react.memo_cache_sentinel")?(he=()=>{Se(!1)},e[43]=he):he=e[43];const Ne=w?.updatedAt;let fe;e[44]!==o||e[45]!==Ne?(fe=[o,Ne],e[44]=o,e[45]=Ne,e[46]=fe):fe=e[46],i.useEffect(he,fe);let P;e[47]!==_||e[48]!==o?(P=Ke=>{!o||!Ke||_||(te(!1),Se(!1),H(Ke),oe(jt=>(jt&&URL.revokeObjectURL(jt),URL.createObjectURL(Ke))))},e[47]=_,e[48]=o,e[49]=P):P=e[49];const M=P;let de;e[50]!==Fe||e[51]!==Ae||e[52]!==Be||e[53]!==$||e[54]!==o?(de=()=>{!o||!Ae||$||(Fe&&Y(),te(!!Be),Se(!1))},e[50]=Fe,e[51]=Ae,e[52]=Be,e[53]=$,e[54]=o,e[55]=de):de=e[55];const xe=de;let W;e[56]!==h||e[57]!==z||e[58]!==o||e[59]!==g?(W=async()=>{!o||z||(Y(),te(!1),Se(!1),F(!0),h(o).then(Ke=>{if(!Ke.ok){le.error(Ke.error||g("projectEditDialog.toast.failedToDiscoverIcon"));return}if(Ke.skipped){le.success(g("projectEditDialog.toast.customIconAlreadySet"));return}le.success(g("projectEditDialog.toast.iconDiscovered"))}).finally(()=>{F(!1)}))},e[56]=h,e[57]=z,e[58]=o,e[59]=g,e[60]=W):W=e[60];const be=W;let ve;e[61]!==g?(ve=g("projectEditDialog.title"),e[61]=g,e[62]=ve):ve=e[62];let G;e[63]!==ve?(G=s.jsx(Gs,{className:"min-w-0",children:s.jsx(Us,{children:ve})}),e[63]=ve,e[64]=G):G=e[64];let ye;e[65]!==g?(ye=g("projectEditDialog.field.name"),e[65]=g,e[66]=ye):ye=e[66];let Le;e[67]!==ye?(Le=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:ye}),e[67]=ye,e[68]=Le):Le=e[68];let Re;e[69]===Symbol.for("react.memo_cache_sentinel")?(Re=Ke=>k(Ke.target.value),e[69]=Re):Re=e[69];let J;e[70]!==g?(J=g("projectEditDialog.field.namePlaceholder"),e[70]=g,e[71]=J):J=e[71];let L;e[72]!==De?(L=Ke=>{Ke.key==="Enter"&&(Ke.preventDefault(),De())},e[72]=De,e[73]=L):L=e[73];let ae;e[74]!==S||e[75]!==J||e[76]!==L?(ae=s.jsx(jn,{value:S,onChange:Re,placeholder:J,onKeyDown:L,autoFocus:!0}),e[74]=S,e[75]=J,e[76]=L,e[77]=ae):ae=e[77];let re;e[78]!==c?(re=s.jsx("p",{className:"typography-meta text-muted-foreground truncate",title:c,children:c}),e[78]=c,e[79]=re):re=e[79];let Oe;e[80]!==Le||e[81]!==ae||e[82]!==re?(Oe=s.jsxs("div",{className:"min-w-0 space-y-1.5",children:[Le,ae,re]}),e[80]=Le,e[81]=ae,e[82]=re,e[83]=Oe):Oe=e[83];let qe;e[84]!==g?(qe=g("projectEditDialog.field.color"),e[84]=g,e[85]=qe):qe=e[85];let Ge;e[86]!==qe?(Ge=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:qe}),e[86]=qe,e[87]=Ge):Ge=e[87];let Je;e[88]===Symbol.for("react.memo_cache_sentinel")?(Je=()=>N(null),e[88]=Je):Je=e[88];const nt=D===null?"border-foreground scale-110":"border-border hover:border-border/80";let gt;e[89]!==nt?(gt=Pe("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",nt),e[89]=nt,e[90]=gt):gt=e[90];let yt;e[91]!==g?(yt=g("projectEditDialog.option.none"),e[91]=g,e[92]=yt):yt=e[92];let _e;e[93]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[93]=_e):_e=e[93];let Qe;e[94]!==gt||e[95]!==yt?(Qe=s.jsx("button",{type:"button",onClick:Je,className:gt,title:yt,children:_e}),e[94]=gt,e[95]=yt,e[96]=Qe):Qe=e[96];let st;e[97]!==D?(st=Pg.map(Ke=>s.jsx("button",{type:"button",onClick:()=>N(Ke.key),className:Pe("w-8 h-8 rounded-lg border-2 transition-all",D===Ke.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:Ke.cssVar},title:Ke.label},Ke.key)),e[97]=D,e[98]=st):st=e[98];let wt;e[99]!==Qe||e[100]!==st?(wt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Qe,st]}),e[99]=Qe,e[100]=st,e[101]=wt):wt=e[101];let Ct;e[102]!==Ge||e[103]!==wt?(Ct=s.jsxs("div",{className:"min-w-0 space-y-2",children:[Ge,wt]}),e[102]=Ge,e[103]=wt,e[104]=Ct):Ct=e[104];let xt;e[105]!==g?(xt=g("projectEditDialog.field.icon"),e[105]=g,e[106]=xt):xt=e[106];let St;e[107]!==xt?(St=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:xt}),e[107]=xt,e[108]=St):St=e[108];let Ze;e[109]!==M?(Ze=s.jsx("input",{ref:Z,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:Ke=>{const jt=Ke.target.files?.[0]??null;M(jt),Ke.currentTarget.value=""}}),e[109]=M,e[110]=Ze):Ze=e[110];let Ot;e[111]===Symbol.for("react.memo_cache_sentinel")?(Ot=()=>A(null),e[111]=Ot):Ot=e[111];const ns=j===null?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80";let zt;e[112]!==ns?(zt=Pe("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",ns),e[112]=ns,e[113]=zt):zt=e[113];let Ve;e[114]!==g?(Ve=g("projectEditDialog.option.none"),e[114]=g,e[115]=Ve):Ve=e[115];let At;e[116]===Symbol.for("react.memo_cache_sentinel")?(At=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[116]=At):At=e[116];let ot;e[117]!==zt||e[118]!==Ve?(ot=s.jsx("button",{type:"button",onClick:Ot,className:zt,title:Ve,children:At}),e[117]=zt,e[118]=Ve,e[119]=ot):ot=e[119];let vt;e[120]!==je||e[121]!==j?(vt=Tg.map(Ke=>{const jt=Ke.Icon;return s.jsx("button",{type:"button",onClick:()=>A(Ke.key),className:Pe("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",j===Ke.key?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80"),title:Ke.label,children:s.jsx(I,{name:jt,className:"w-4 h-4",style:je?{color:je}:void 0})},Ke.key)}),e[120]=je,e[121]=j,e[122]=vt):vt=e[122];let bt;e[123]!==ot||e[124]!==vt?(bt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[ot,vt]}),e[123]=ot,e[124]=vt,e[125]=bt):bt=e[125];let ls;e[126]!==w||e[127]!==v||e[128]!==me||e[129]!==Fe||e[130]!==T||e[131]!==X||e[132]!==o||e[133]!==ce||e[134]!==g?(ls=me&&ce&&s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:g("projectEditDialog.field.preview")}),s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-1",children:s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:T?{backgroundColor:T}:void 0,children:Fe&&X?s.jsx("img",{src:X,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>Se(!0)}):s.jsx(Qa,{project:{id:o,iconImage:w},options:{themeVariant:v.metadata.variant,iconColor:v.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>Se(!0)})})})]}),e[126]=w,e[127]=v,e[128]=me,e[129]=Fe,e[130]=T,e[131]=X,e[132]=o,e[133]=ce,e[134]=g,e[135]=ls):ls=e[135];let Wt;e[136]!==be||e[137]!==Me||e[138]!==z||e[139]!==_||e[140]!==g?(Wt=!Me&&s.jsxs(s.Fragment,{children:[s.jsx($e,{size:"sm",variant:"outline",onClick:()=>Z.current?.click(),disabled:_,children:g(_?"projectEditDialog.actions.uploading":"projectEditDialog.actions.uploadIcon")}),s.jsx($e,{size:"sm",variant:"outline",onClick:()=>{be()},disabled:z,children:g(z?"projectEditDialog.actions.discovering":"projectEditDialog.actions.discoverFavicon")})]}),e[136]=be,e[137]=Me,e[138]=z,e[139]=_,e[140]=g,e[141]=Wt):Wt=e[141];let qt;e[142]!==xe||e[143]!==Ae||e[144]!==$||e[145]!==g?(qt=Ae&&s.jsx($e,{size:"sm",variant:"outline",onClick:()=>{xe()},disabled:$,children:g($?"projectEditDialog.actions.removing":"projectEditDialog.actions.removeProjectIcon")}),e[142]=xe,e[143]=Ae,e[144]=$,e[145]=g,e[146]=qt):qt=e[146];let rs;e[147]!==$||e[148]!==ne||e[149]!==g?(rs=ne&&s.jsx($e,{size:"sm",variant:"outline",onClick:()=>te(!1),disabled:$,children:g("projectEditDialog.actions.undoRemove")}),e[147]=$,e[148]=ne,e[149]=g,e[150]=rs):rs=e[150];let Ut;e[151]!==Wt||e[152]!==qt||e[153]!==rs?(Ut=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[Wt,qt,rs]}),e[151]=Wt,e[152]=qt,e[153]=rs,e[154]=Ut):Ut=e[154];let Bt;e[155]!==St||e[156]!==Ze||e[157]!==bt||e[158]!==ls||e[159]!==Ut?(Bt=s.jsxs("div",{className:"min-w-0 space-y-2",children:[St,Ze,bt,ls,Ut]}),e[155]=St,e[156]=Ze,e[157]=bt,e[158]=ls,e[159]=Ut,e[160]=Bt):Bt=e[160];let _t;e[161]!==me||e[162]!==T||e[163]!==g?(_t=me&&s.jsxs("div",{className:"min-w-0 space-y-2",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:g("projectEditDialog.field.iconBackground")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:T??"#000000",onChange:Ke=>E(Ke.target.value),className:"h-8 w-10 cursor-pointer rounded border border-border bg-transparent p-1","aria-label":g("projectEditDialog.field.iconBackgroundAria")}),s.jsx(jn,{value:T??"",onChange:Ke=>E(Ke.target.value),placeholder:"#000000",className:"h-8 w-[8.5rem]"}),s.jsx($e,{size:"sm",variant:"outline",onClick:()=>E(null),children:g("projectEditDialog.actions.clear")})]})]}),e[161]=me,e[162]=T,e[163]=g,e[164]=_t):_t=e[164];let Yt;e[165]!==Oe||e[166]!==Ct||e[167]!==Bt||e[168]!==_t?(Yt=s.jsxs("div",{className:"min-w-0 space-y-5 py-1",children:[Oe,Ct,Bt,_t]}),e[165]=Oe,e[166]=Ct,e[167]=Bt,e[168]=_t,e[169]=Yt):Yt=e[169];let Ht;e[170]!==r?(Ht=()=>r(!1),e[170]=r,e[171]=Ht):Ht=e[171];let Zt;e[172]!==g?(Zt=g("projectEditDialog.actions.cancel"),e[172]=g,e[173]=Zt):Zt=e[173];let ys;e[174]!==Ht||e[175]!==Zt?(ys=s.jsx($e,{variant:"ghost",onClick:Ht,children:Zt}),e[174]=Ht,e[175]=Zt,e[176]=ys):ys=e[176];let Tt;e[177]!==$||e[178]!==_||e[179]!==S?(Tt=!S.trim()||_||$,e[177]=$,e[178]=_,e[179]=S,e[180]=Tt):Tt=e[180];let Vt;e[181]!==g?(Vt=g("projectEditDialog.actions.save"),e[181]=g,e[182]=Vt):Vt=e[182];let Dt;e[183]!==De||e[184]!==Tt||e[185]!==Vt?(Dt=s.jsx($e,{onClick:De,disabled:Tt,children:Vt}),e[183]=De,e[184]=Tt,e[185]=Vt,e[186]=Dt):Dt=e[186];let cs;e[187]!==ys||e[188]!==Dt?(cs=s.jsxs(or,{children:[ys,Dt]}),e[187]=ys,e[188]=Dt,e[189]=cs):cs=e[189];let us;e[190]!==G||e[191]!==Yt||e[192]!==cs?(us=s.jsxs(Vs,{className:"max-w-md",children:[G,Yt,cs]}),e[190]=G,e[191]=Yt,e[192]=cs,e[193]=us):us=e[193];let He;return e[194]!==r||e[195]!==n||e[196]!==us?(He=s.jsx($s,{open:n,onOpenChange:r,children:us}),e[194]=r,e[195]=n,e[196]=us,e[197]=He):He=e[197],He};function uN(t){return t.uploadProjectIcon}function fN(t){return t.removeProjectIcon}function mN(t){return t.discoverProjectIcon}function hN(t){return t&&URL.revokeObjectURL(t),null}const pN=t=>{const e=ft.c(86),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:c,onRename:l,onDelete:d,renderSessionNode:u,getRenderExtras:m,groupDirectory:f,projectId:p,mobileVariant:y,alwaysShowActions:g,isRenaming:b,renameDraft:x,onRenameDraftChange:h,onRenameSave:C,onRenameCancel:w,droppableRef:v,isDropTarget:S,onNewSession:k,onNewSubFolder:j,depth:A,hideActions:D,archivedBucket:N}=t,T=g===void 0?y===void 0?!1:y:g,E=b===void 0?!1:b,_=x===void 0?"":x,R=S===void 0?!1:S,$=A===void 0?0:A,V=D===void 0?!1:D,z=N===void 0?!1:N,{t:F}=kt(),[ne,te]=i.useState(!1),[q,H]=i.useState(""),X=i.useRef(null),oe=E||ne,ue=E?_:q;let Se;e[0]!==n.name?(Se=()=>{H(n.name),te(!0)},e[0]=n.name,e[1]=Se):Se=e[1];const Z=Se;let ke;e[2]!==ue||e[3]!==n.name||e[4]!==E||e[5]!==l||e[6]!==C?(ke=()=>{const L=ue.trim();L&&L!==n.name&&l(L),E&&C&&C(),te(!1),H("")},e[2]=ue,e[3]=n.name,e[4]=E,e[5]=l,e[6]=C,e[7]=ke):ke=e[7];const Y=ke;let ge;e[8]!==E||e[9]!==w?(ge=()=>{E&&w&&w(),te(!1),H("")},e[8]=E,e[9]=w,e[10]=ge):ge=e[10];const O=ge;let se;e[11]!==E||e[12]!==h?(se=L=>{E&&h?h(L):H(L)},e[11]=E,e[12]=h,e[13]=se):se=e[13];const ee=se;let je,De;e[14]!==E?(je=()=>{if(!E)return;const L=()=>{const Oe=X.current;Oe&&(Oe.focus(),Oe.select())},ae=requestAnimationFrame(L),re=window.setTimeout(L,0);return()=>{cancelAnimationFrame(ae),window.clearTimeout(re)}},De=[E],e[14]=E,e[15]=je,e[16]=De):(je=e[15],De=e[16]),i.useEffect(je,De);const Be=a?"folder":"folder-open",Me=$>0&&"ml-3";let me;e[17]!==Me?(me=Pe("oc-folder",Me),e[17]=Me,e[18]=me):me=e[18];const Ae=R&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let pe;e[19]!==Ae?(pe=Pe("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",Ae),e[19]=Ae,e[20]=pe):pe=e[20];const ce=oe?void 0:c,he=oe?void 0:"button",Ne=oe?void 0:0;let fe;e[21]!==c||e[22]!==oe?(fe=oe?void 0:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),c())},e[21]=c,e[22]=oe,e[23]=fe):fe=e[23];let P;e[24]!==n.name||e[25]!==a||e[26]!==F?(P=a?F("sessions.sidebar.folderItem.expandAria",{folderName:n.name}):F("sessions.sidebar.folderItem.collapseAria",{folderName:n.name}),e[24]=n.name,e[25]=a,e[26]=F,e[27]=P):P=e[27];const M=z?T?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let de;e[28]!==M?(de=Pe("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",M),e[28]=M,e[29]=de):de=e[29];const xe=R?"text-primary":"text-muted-foreground";let W;e[30]!==xe?(W=Pe("h-3.5 w-3.5 flex-shrink-0",xe),e[30]=xe,e[31]=W):W=e[31];let be;e[32]!==Be||e[33]!==W?(be=s.jsx(I,{name:Be,className:W}),e[32]=Be,e[33]=W,e[34]=be):be=e[34];let ve;e[35]!==ue||e[36]!==n.name||e[37]!==O||e[38]!==ee||e[39]!==Y||e[40]!==a||e[41]!==R||e[42]!==oe||e[43]!==r||e[44]!==F?(ve=oe?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:xN,onMouseDown:bN,onSubmit:L=>{L.preventDefault(),Y()},children:[s.jsx("input",{ref:X,value:ue,onChange:L=>ee(L.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:F("sessions.sidebar.folderItem.namePlaceholder"),onClick:yN,onPointerDown:wN,onMouseDown:vN,onKeyDown:L=>{if(L.key==="Escape"){L.stopPropagation(),O();return}(L.key===" "||L.key==="Enter")&&L.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:jN,onPointerDown:SN,onMouseDown:NN,children:s.jsx(I,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),O()},onPointerDown:kN,onMouseDown:CN,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{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:Pe("typography-ui-label font-semibold truncate",R?"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(I,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[35]=ue,e[36]=n.name,e[37]=O,e[38]=ee,e[39]=Y,e[40]=a,e[41]=R,e[42]=oe,e[43]=r,e[44]=F,e[45]=ve):ve=e[45];let G;e[46]!==de||e[47]!==be||e[48]!==ve?(G=s.jsxs("div",{className:de,children:[be,ve]}),e[46]=de,e[47]=be,e[48]=ve,e[49]=G):G=e[49];let ye;e[50]!==T||e[51]!==z||e[52]!==$||e[53]!==n.name||e[54]!==Z||e[55]!==V||e[56]!==d||e[57]!==k||e[58]!==j||e[59]!==oe||e[60]!==F?(ye=!oe&&(!V||z)?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:Pe("flex items-center gap-0.5 transition-opacity",T?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100",z&&"absolute right-0.5 top-1/2 z-10 -translate-y-1/2 px-0"),children:[!z&&k?s.jsx("button",{type:"button",onClick:L=>{L.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":F("sessions.sidebar.folderItem.newSessionAria",{folderName:n.name}),title:F("sessions.sidebar.project.actions.newSession"),children:s.jsx(I,{name:"add",className:"h-3.5 w-3.5"})}):null,!z&&j&&$===0?s.jsx("button",{type:"button",onClick:L=>{L.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":F("sessions.sidebar.folderItem.newSubfolderAria",{folderName:n.name}),title:F("sessions.sidebar.folderItem.newSubfolder"),children:s.jsx(I,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,z?null:s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),Z()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":F("sessions.sidebar.folderItem.renameAria",{folderName:n.name}),children:s.jsx(I,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:L=>{L.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":z?F("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):F("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=T,e[51]=z,e[52]=$,e[53]=n.name,e[54]=Z,e[55]=V,e[56]=d,e[57]=k,e[58]=j,e[59]=oe,e[60]=F,e[61]=ye):ye=e[61];let Le;e[62]!==v||e[63]!==pe||e[64]!==ce||e[65]!==he||e[66]!==Ne||e[67]!==fe||e[68]!==P||e[69]!==G||e[70]!==ye?(Le=s.jsxs("div",{ref:v,className:pe,onClick:ce,role:he,tabIndex:Ne,onKeyDown:fe,"aria-label":P,children:[G,ye]}),e[62]=v,e[63]=pe,e[64]=ce,e[65]=he,e[66]=Ne,e[67]=fe,e[68]=P,e[69]=G,e[70]=ye,e[71]=Le):Le=e[71];let Re;e[72]!==z||e[73]!==m||e[74]!==f||e[75]!==a||e[76]!==p||e[77]!==u||e[78]!==r||e[79]!==o||e[80]!==F?(Re=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(L=>u(L,0,f??null,p??null,z,void 0,"project",m?.(L))):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:F("sessions.sidebar.folderItem.emptyFolder")})]}),e[72]=z,e[73]=m,e[74]=f,e[75]=a,e[76]=p,e[77]=u,e[78]=r,e[79]=o,e[80]=F,e[81]=Re):Re=e[81];let J;return e[82]!==me||e[83]!==Le||e[84]!==Re?(J=s.jsxs("div",{className:me,children:[Le,Re]}),e[82]=me,e[83]=Le,e[84]=Re,e[85]=J):J=e[85],J},gN=i.memo(pN);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 jN(t){return t.stopPropagation()}function SN(t){return t.stopPropagation()}function NN(t){return t.stopPropagation()}function kN(t){return t.stopPropagation()}function CN(t){return t.stopPropagation()}const AN=t=>{const e=ft.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:u,listeners:m,setNodeRef:f,isDragging:p}=Xh(d);let y;e[7]!==m?(y=h=>{h.stopPropagation(),m?.onPointerDown&&m.onPointerDown(h)},e[7]=m,e[8]=y):y=e[8];const g=y,b=p?"opacity-30":void 0;let x;return e[9]!==u||e[10]!==a||e[11]!==g||e[12]!==f||e[13]!==b?(x=s.jsx("div",{ref:f,...u,onPointerDown:g,className:b,children:a}),e[9]=u,e[10]=a,e[11]=g,e[12]=f,e[13]=b,e[14]=x):x=e[14],x},DN=t=>{const e=ft.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}=Jh(c);let u;e[5]!==r||e[6]!==d||e[7]!==l?(u=r(l,d),e[5]=r,e[6]=d,e[7]=l,e[8]=u):u=e[8];let m;return e[9]!==u?(m=s.jsx(s.Fragment,{children:u}),e[9]=u,e[10]=m):m=e[10],m},IN=t=>{const e=ft.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=xa(yo(ba,c)),[d,u]=i.useState(null),[m,f]=i.useState("Session"),[p,y]=i.useState(null),[g,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 x;e[3]!==o?(x=j=>{u(null),y(null),b(null);const{active:A,over:D}=j;if(!D)return;const N=A.data.current,B=D.data.current;N?.type==="session"&&N.sessionId&&B?.type==="folder"&&B.folderId&&o(N.sessionId,B.folderId)},e[3]=o,e[4]=x):x=e[4];const h=x;let C,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(C=j=>{const A=j.active.data.current;if(A?.type==="session"&&A.sessionId){u(A.sessionId),f(A.sessionTitle??"Session");const D=j.active.rect.current.initial?.width,N=j.active.rect.current.initial?.height;y(typeof D=="number"?D:null),b(typeof N=="number"?N:null)}},w=()=>{u(null),y(null),b(null)},e[5]=C,e[6]=w):(C=e[5],w=e[6]);let v;e[7]!==g||e[8]!==d||e[9]!==m||e[10]!==p||e[11]!==r?(v=d&&r?s.jsxs("div",{style:{width:p?`${p}px`:"auto",height:g?`${g}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(I,{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]=g,e[8]=d,e[9]=m,e[10]=p,e[11]=r,e[12]=v):v=e[12];let S;e[13]!==v?(S=s.jsx(Wl,{children:v}),e[13]=v,e[14]=S):S=e[14];let k;return e[15]!==a||e[16]!==h||e[17]!==l||e[18]!==S?(k=s.jsxs(ya,{sensors:l,collisionDetection:wa,onDragStart:C,onDragCancel:w,onDragEnd:h,children:[a,S]}),e[15]=a,e[16]=h,e[17]=l,e[18]=S,e[19]=k):k=e[19],k},Hi=(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)},Wr=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if(Wr(n,e))return!0;return!1},Fa=t=>t.children.length===0?"":t.children.map(n=>n.children.length===0?n.session.id:`${n.session.id}:${Fa(n)}`).join("|"),Fo=(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 u of l.children)if(c(u))return!0;return!1};return t.forEach(l=>c(l)),a},Ir=ro()(uc(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}})),PN=50,TN=30,RN=28,_i=(t,e)=>e?t.sessions.some(n=>Wr(n,e)):!1,EN=(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)},MN=(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)},FN=(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)},LN=(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)},mf=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&&mf(t)!==mf(e)||t.pinnedSessionIds!==e.pinnedSessionIds&&EN(e.group,t.pinnedSessionIds,e.pinnedSessionIds)||t.expandedParents!==e.expandedParents&&FN(e.group,t.expandedParents,e.expandedParents)||t.sessionOrderIndex!==e.sessionOrderIndex&&MN(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=Fo(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket),r=Fo(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket);if(n||r)return!1}if(t.liveSessionById!==e.liveSessionById&&LN(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 BN(t){const{t:e}=kt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:u,collapsedGroups:m,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:y,renameFolder:g,deleteFolder:b,showDeletionDialog:x,setDeleteFolderConfirm:h,renderSessionNode:C,projectRepoStatus:w,lastRepoStatus:v,showMoreGroupSessions:S,resetGroupSessionLimit:k,mobileVariant:j,alwaysShowActions:A,activeProjectId:D,setActiveProjectIdOnly:N,setActiveMainTab:B,setSessionSwitcherOpen:T,openNewSessionDraft:E,addSessionToFolder:_,createFolderAndStartRename:R,renamingFolderId:$,renameFolderDraft:V,setRenameFolderDraft:z,setRenamingFolderId:F,pinnedSessionIds:ne,expandedParents:te,sessionOrderIndex:q,currentSessionId:H,editingId:X,openSidebarMenuKey:oe,prVisualStateByDirectoryBranch:ue,onToggleCollapsedGroup:Se,dragHandleProps:Z,compactBodyPadding:ke=!1,scrollContainerRef:Y}=t,ge=i.useCallback((He,Ke)=>{const jt=q.get(He.session.id),Lt=q.get(Ke.session.id);if(jt!==void 0||Lt!==void 0){if(jt===void 0)return 1;if(Lt===void 0)return-1;if(jt!==Lt)return jt-Lt}return Gi(He.session,Ke.session,ne)},[ne,q]),O=c?d.get(n):null,se=Ir(He=>He.displayMode),ee=Bn(He=>He.foldersMap),je=se==="minimal"&&!Kr(),De=c?!1:m.has(r),Be=f?10:5,Fe=Math.max(Be,u??Be),Me=c?O?.groupMatches===!0:!1,me=c,Ae=i.useMemo(()=>[...me?O?.filteredNodes??[]:n.sessions].sort(ge),[ge,n.sessions,O?.filteredNodes,me]),pe=n.folderScopeKey??as(n.directory??null),ce=i.useMemo(()=>pe?ee[pe]??[]:[],[pe,ee]),he=i.useMemo(()=>{const He=new Map,Ke=jt=>{jt.forEach(Lt=>{He.set(Lt.session.id,Lt),Lt.children.length>0&&Ke(Lt.children)})};return Ke(Ae),He},[Ae]),Ne=i.useMemo(()=>ce.map(He=>{const Ke=He.sessionIds.map(jt=>he.get(jt)).filter(jt=>!!jt).sort(ge);return{folder:He,nodes:Ke}}),[ce,he,ge]),fe=i.useMemo(()=>{const He=new Map(Ne.map(Nt=>[Nt.folder.id,Nt])),Ke=new Map;for(const{folder:Nt}of Ne){if(!Nt.parentId)continue;const xs=Ke.get(Nt.parentId);xs?xs.push(Nt.id):Ke.set(Nt.parentId,[Nt.id])}const jt=new Map,Lt=Nt=>{const xs=jt.get(Nt);if(xs!==void 0)return xs;const ps=He.get(Nt);if(!ps)return jt.set(Nt,!1),!1;const os=Ke.get(Nt)??[];if(n.isArchivedBucket&&ps.nodes.length===0){const js=os.some(rn=>Lt(rn));return jt.set(Nt,js),js}if(!c||ps.folder.name.toLowerCase().includes(l)||ps.nodes.length>0)return jt.set(Nt,!0),!0;const Fs=os.some(js=>Lt(js));return jt.set(Nt,Fs),Fs};return Ne.filter(({folder:Nt})=>Lt(Nt.id))},[Ne,n.isArchivedBucket,c,l]),P=i.useMemo(()=>new Set(fe.flatMap(He=>He.folder.sessionIds)),[fe]),M=i.useMemo(()=>Ae.filter(He=>!P.has(He.session.id)),[Ae,P]),de=i.useMemo(()=>fe.filter(({folder:He})=>!He.parentId),[fe]),xe="project",W=i.useMemo(()=>{const He=new Set;return Hi(Ae,H,He),fe.forEach(({nodes:Ke})=>{Hi(Ke,H,He)}),He},[Ae,fe,H]),be=i.useMemo(()=>{const He=new Set;return Hi(Ae,X,He),fe.forEach(({nodes:Ke})=>{Hi(Ke,X,He)}),He},[Ae,fe,X]),ve=i.useMemo(()=>{if(!oe)return null;const He=Fo(Ae,oe,xe,!!n.isArchivedBucket);if(He)return He;for(const{nodes:Ke}of fe){const jt=Fo(Ke,oe,xe,!!n.isArchivedBucket);if(jt)return jt}return null},[oe,Ae,fe,n.isArchivedBucket]),G=i.useCallback(He=>{const Ke=new WeakMap,jt=Lt=>{Ke.set(Lt,Fa(Lt));for(const Nt of Lt.children)jt(Nt)};return He.forEach(jt),Ke},[]),ye=i.useMemo(()=>G(Ae),[G,Ae]),Le=i.useMemo(()=>{const He=new WeakMap;return fe.forEach(({nodes:Ke})=>{Ke.forEach(jt=>He.set(jt,Fa(jt)))}),He},[fe]),Re=i.useCallback(He=>ye.get(He)??Le.get(He)??"",[ye,Le]),J=i.useCallback(He=>({subtreeContainsActive:W,subtreeContainsEditing:be,menuOpenSessionId:ve,nodeStructureKey:Re(He)}),[W,be,ve,Re]),L=M.length,ae=n.isArchivedBucket||c?M:M.slice(0,Fe),re=L-ae.length,Oe=!n.isArchivedBucket&&!c&&L>Be&&re===0,qe=n.isArchivedBucket===!0&&!c&&ae.length>=PN,Ge=n.isArchivedBucket!==!0&&!c&&ae.length>=TN,Je=qe||Ge,nt=n.isArchivedBucket?"archived":"active",gt=Je&&ae.some(He=>{if(He.children.length===0)return!1;const Ke=`project:${nt}:${He.session.id}`;return te.has(Ke)}),yt=i.useRef(null),[_e,Qe]=i.useState(null),[st,wt]=i.useState(0),[,Ct]=i.useState(0);i.useEffect(()=>{if(!Je)return;const He=yt.current;if(!He||typeof ResizeObserver>"u")return;const Ke=new ResizeObserver(()=>Ct(jt=>jt+1));return Ke.observe(He),()=>Ke.disconnect()},[Je]),i.useLayoutEffect(()=>{if(!Je){_e!==null&&Qe(null),st!==0&&wt(0);return}const He=yt.current;if(!He)return;let Ke=_e;const jt=Y?.current??null;if(jt&&jt.contains(He)){if(Ke=jt,Ke!==_e){Qe(Ke);return}}else if(!Ke||!Ke.contains(He)){let Nt=He.parentElement;for(;Nt;){const xs=window.getComputedStyle(Nt);if(xs.overflowY==="auto"||xs.overflowY==="scroll"){Ke=Nt;break}Nt=Nt.parentElement}if(Ke!==_e){Qe(Ke);return}}if(!Ke)return;const Lt=He.getBoundingClientRect().top-Ke.getBoundingClientRect().top+Ke.scrollTop;wt(Nt=>Math.abs(Nt-Lt)<1?Nt:Lt)});const xt=Je&&_e!==null,St=Zh({count:ae.length,enabled:xt,getScrollElement:()=>_e,initialOffset:()=>_e?.scrollTop??0,estimateSize:()=>RN,overscan:gt?20:8,scrollMargin:st,getItemKey:He=>ae[He]?.session.id??He}),Ze=i.useCallback(He=>{const Ke=[],jt=Lt=>{Lt.forEach(Nt=>{Ke.push(Nt.session),Nt.children.length>0&&jt(Nt.children)})};return jt(He),Ke},[]),Ot=i.useMemo(()=>Ze(Ae),[Ze,Ae]),ns=i.useMemo(()=>{if(!n.isArchivedBucket)return new Map;const He=new Map,Ke=new Map;for(const{folder:Lt}of fe){if(!Lt.parentId)continue;const Nt=Ke.get(Lt.parentId)??[];Nt.push(Lt.id),Ke.set(Lt.parentId,Nt)}const jt=(Lt,Nt)=>{if(Nt.has(Lt))return[];Nt.add(Lt);const xs=fe.find(({folder:Kt})=>Kt.id===Lt),ps=xs?Ze(xs.nodes):[],os=Ke.get(Lt)??[];for(const Kt of os)ps.push(...jt(Kt,Nt));return ps};for(const{folder:Lt}of fe)He.set(Lt.id,jt(Lt.id,new Set));return He},[fe,Ze,n.isArchivedBucket]);if(c&&!Me&&de.length===0&&M.length===0)return null;const zt=o&&w.has(o)?!!w.get(o):v,Ve=as(n.directory??null),At=n.branch?.trim()??null,ot=Ve&&At?ue.get(`${Ve}::${At}`)??null:null,vt=!!(ot&&n.branch),bt=!ot&&!n.isMain&&!!n.branch,ls=ot?.visualState??null,Wt=ot&&ot.state==="open"&&ot.checks?e("sessions.sidebar.group.pr.checksPassed",{success:ot.checks.success,total:ot.checks.total}):null,qt=ot&&ot.state==="open"&&ot.checks?[ot.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:ot.checks.failure}):null,ot.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:ot.checks.pending}):null].filter(He=>!!He).join(", "):null,rs=ot&&ot.state==="open"?ot.mergeableState==="blocked"||ot.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):ot.mergeableState==="clean"||ot.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,Ut=ot&&ot.state==="open"&&ot.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:ot.mergeableState}):null,Bt=ot?.base??null,_t=ot?.head??null,Yt=(()=>{if(!ot)return n.branch&&fb(n.branch,n.label)?{label:n.branch,color:null}:null;switch(ot.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return ot.canMerge===!0||ot.mergeableState==="clean"||ot.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:ot.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}})(),Ht=Yt?.color??(ls?`var(--pr-${ls})`:void 0),Zt=He=>{He.preventDefault(),He.stopPropagation();const Ke=ot?.url;Ke&&Di(Ke)},ys=(He,Ke,jt)=>{const Lt=fe.filter(({folder:ps})=>ps.parentId===He.id),Nt=Lt.length>0?s.jsx(s.Fragment,{children:Lt.map(({folder:ps,nodes:os})=>ys(ps,os,jt+1))}):void 0,xs=ns.get(He.id)??[];return s.jsx(DN,{folderId:He.id,children:(ps,os)=>s.jsx(gN,{folder:He,sessions:Ke,subFolderItems:Nt,isCollapsed:c?!1:p.has(He.id),onToggle:()=>y(He.id),onRename:Kt=>{pe&&g(pe,He.id,Kt)},onDelete:()=>{if(n.isArchivedBucket){Tr.requestDelete({sessions:xs,mode:"session"});return}if(!pe)return;if(!x){b(pe,He.id);return}const Kt=fe.filter(({folder:js})=>js.parentId===He.id).length,Fs=Ke.length;h({scopeKey:pe,folderId:He.id,folderName:He.name,subFolderCount:Kt,sessionCount:Fs})},renderSessionNode:C,getRenderExtras:Re?Kt=>({subtreeContainsActive:W,subtreeContainsEditing:be,menuOpenSessionId:ve,nodeStructureKey:Re(Kt),childRenderExtrasFor:J}):void 0,groupDirectory:n.directory,projectId:o,mobileVariant:j,alwaysShowActions:A,isRenaming:$===He.id,renameDraft:$===He.id?V:void 0,onRenameDraftChange:Kt=>z(Kt),onRenameSave:()=>{const Kt=V.trim();Kt&&pe&&g(pe,He.id,Kt),F(null),z("")},onRenameCancel:()=>{F(null),z("")},droppableRef:ps,isDropTarget:os,depth:jt,onNewSession:()=>{o&&o!==D&&N(o),B("chat"),j&&T(!1),E({directoryOverride:n.directory,targetFolderId:He.id})},onNewSubFolder:jt===0?()=>{pe&&R(pe,He.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},He.id)},Tt=()=>de.map(({folder:He,nodes:Ke})=>ys(He,Ke,0)),Vt=!!(!n.isMain&&n.worktree),Dt=A?Vt?"pr-14":"pr-7":je?Vt?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":Vt?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",cs=s.jsxs(IN,{scopeKey:pe,hasFolders:fe.length>0,onSessionDroppedOnFolder:(He,Ke)=>{pe&&_(pe,Ke,He)},children:[Tt(),Je?s.jsx("div",{ref:yt,children:xt?s.jsx("div",{style:{height:St.getTotalSize(),position:"relative"},children:St.getVirtualItems().map(He=>{const Ke=ae[He.index];return Ke?s.jsx("div",{"data-index":He.index,ref:St.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${He.start-st}px)`},children:C(Ke,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:W,subtreeContainsEditing:be,menuOpenSessionId:ve,nodeStructureKey:Re(Ke),childRenderExtrasFor:J})},Ke.session.id):null})}):ae.map(He=>C(He,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:W,subtreeContainsEditing:be,menuOpenSessionId:ve,nodeStructureKey:Re(He),childRenderExtrasFor:J}))}):ae.map(He=>C(He,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:W,subtreeContainsEditing:be,menuOpenSessionId:ve,nodeStructureKey:Re(He),childRenderExtrasFor:J})),L===0&&fe.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,re>0?s.jsx("button",{type:"button",onClick:()=>S(r,ae.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,Oe?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]}),us=ke?"pb-2 pl-1":"pb-3 pl-4";return a?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:Pe("oc-group-body",us),children:cs})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:Pe("group/gh relative flex items-start justify-between gap-1 py-1 min-w-0 rounded-md","cursor-pointer"),onClick:()=>Se(r),role:"button",tabIndex:0,onKeyDown:He=>{(He.key==="Enter"||He.key===" ")&&(He.preventDefault(),Se(r))},"aria-label":De?e("sessions.sidebar.group.expandAria",{label:n.label}):e("sessions.sidebar.group.collapseAria",{label:n.label}),"aria-expanded":!De,children:[s.jsx("div",{ref:Z?.setActivatorNodeRef,className:Pe("min-w-0 flex flex-1 items-start gap-1 overflow-hidden pl-0.5 transition-[padding] cursor-grab active:cursor-grabbing",Dt),...Z?.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:vt&&ot?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(Et,{children:[s.jsx(Mt,{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(I,{name:"git-branch",className:Pe("h-3.5 w-3.5 shrink-0",A?"hidden":"group-hover/gh:hidden"),style:Ht?{color:Ht}:void 0}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),ot.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:He=>He.stopPropagation(),onClick:Zt,children:["#",ot.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",ot.number]})]})}),s.jsx(Ft,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Bt||_t?s.jsx("div",{className:"text-muted-foreground truncate",children:Bt&&_t?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Bt}),s.jsx(I,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:_t})]}):s.jsx("span",{children:Bt??_t??""})}):null,Ut?s.jsx("div",{className:"text-muted-foreground truncate",children:Ut}):null,rs||Wt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[rs??"",rs&&Wt?" • ":"",Wt??"",qt?` (${qt})`:""]}):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(I,{name:"archive",className:Pe("h-3.5 w-3.5 shrink-0 text-muted-foreground",A?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:vo(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(I,{name:"git-branch",className:Pe("h-3.5 w-3.5 shrink-0 text-muted-foreground",A?"hidden":"group-hover/gh:hidden"),style:Ht?{color:Ht}:void 0}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:vo(n.label,l)})]}):vo(n.label,l)}),bt&&Yt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(I,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||zt?vt&&ot?s.jsxs(Et,{children:[s.jsx(Mt,{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(I,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:Ht?{color:Ht}:void 0})})}),s.jsx(Ft,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Bt||_t?s.jsx("div",{className:"text-muted-foreground truncate",children:Bt&&_t?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Bt}),s.jsx(I,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:_t})]}):s.jsx("span",{children:Bt??_t??""})}):null,Ut?s.jsx("div",{className:"text-muted-foreground truncate",children:Ut}):null,rs||Wt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[rs??"",rs&&Wt?" • ":"",Wt??"",qt?` (${qt})`:""]}):null]})})]}):s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:Ht?{color:Ht}:void 0}):null,s.jsx("span",{className:Pe("min-w-0 truncate text-[11px] font-medium",!Yt.color&&"text-muted-foreground/80"),style:Yt.color?{color:Yt.color}:void 0,children:Yt.label})]}):null]})}),n.isArchivedBucket&&Ot.length>0?s.jsx("div",{className:Pe("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",A?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),Tr.requestDelete({sessions:Ot,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(I,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ft,{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:Pe("absolute right-7 top-1/2 -translate-y-1/2 z-10 transition-opacity",A?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),Tr.requestDelete({sessions:Ot,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(I,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteWorktree")})})]})}):null,n.directory?s.jsx("div",{className:Pe("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",A?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),o&&o!==D&&N(o),B("chat"),j&&T(!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(I,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),De?null:s.jsx("div",{className:Pe("oc-group-body",us),children:cs})]})}const _N=i.memo(BN,ON);function VN(t){const e=ft.c(182),{t:n}=kt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:u,headerActionButtonClass:m,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:y,sessionSearchQuery:g,setSessionSearchQuery:b,hasSessionSearchQuery:x,searchMatchCount:h,collapseAllProjects:C,expandAllProjects:w,openScheduledTasksDialog:v,selectionModeEnabled:S,onToggleSelectionMode:k}=t,j=Ir(KN),A=Ir(GN),D=Ir(HN),N=Ir(UN),B=Ir(WN),T=Ir(zN);let E;e[0]===Symbol.for("react.memo_cache_sentinel")?(E=Kr(),e[0]=E):E=e[0];const _=!E;if(r)return null;let R;e[1]!==n?(R=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=R):R=e[2];let $;e[3]!==u?($=s.jsx(I,{name:"folder-add",className:u}),e[3]=u,e[4]=$):$=e[4];let V;e[5]!==a||e[6]!==m||e[7]!==R||e[8]!==$?(V=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:m,"aria-label":R,children:$})}),e[5]=a,e[6]=m,e[7]=R,e[8]=$,e[9]=V):V=e[9];let z;e[10]!==n?(z=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=z):z=e[11];let F;e[12]!==z?(F=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:z})}),e[12]=z,e[13]=F):F=e[13];let ne;e[14]!==V||e[15]!==F?(ne=s.jsxs(Et,{children:[V,F]}),e[14]=V,e[15]=F,e[16]=ne):ne=e[16];let te;e[17]!==n?(te=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=te):te=e[18];let q;e[19]!==u?(q=s.jsx(I,{name:"chat-new",className:u}),e[19]=u,e[20]=q):q=e[20];let H;e[21]!==m||e[22]!==c||e[23]!==te||e[24]!==q?(H=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:m,"aria-label":te,children:q})}),e[21]=m,e[22]=c,e[23]=te,e[24]=q,e[25]=H):H=e[25];let X;e[26]!==n?(X=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=X):X=e[27];let oe;e[28]!==X?(oe=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:X})}),e[28]=X,e[29]=oe):oe=e[29];let ue;e[30]!==oe||e[31]!==H?(ue=s.jsxs(Et,{children:[H,oe]}),e[30]=oe,e[31]=H,e[32]=ue):ue=e[32];let Se;e[33]!==n?(Se=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=Se):Se=e[34];const Z=!l;let ke;e[35]!==u?(ke=s.jsx(Rg,{className:u}),e[35]=u,e[36]=ke):ke=e[36];let Y;e[37]!==m||e[38]!==d||e[39]!==Se||e[40]!==Z||e[41]!==ke?(Y=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:m,"aria-label":Se,disabled:Z,children:ke})}),e[37]=m,e[38]=d,e[39]=Se,e[40]=Z,e[41]=ke,e[42]=Y):Y=e[42];let ge;e[43]!==n?(ge=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=ge):ge=e[44];let O;e[45]!==ge?(O=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ge})}),e[45]=ge,e[46]=O):O=e[46];let se;e[47]!==Y||e[48]!==O?(se=s.jsxs(Et,{children:[Y,O]}),e[47]=Y,e[48]=O,e[49]=se):se=e[49];let ee;e[50]!==n?(ee=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=ee):ee=e[51];let je;e[52]!==u?(je=s.jsx(I,{name:"calendar-schedule",className:u}),e[52]=u,e[53]=je):je=e[53];let De;e[54]!==m||e[55]!==v||e[56]!==ee||e[57]!==je?(De=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:v,className:m,"aria-label":ee,children:je})}),e[54]=m,e[55]=v,e[56]=ee,e[57]=je,e[58]=De):De=e[58];let Be;e[59]!==n?(Be=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=Be):Be=e[60];let Fe;e[61]!==Be?(Fe=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Be})}),e[61]=Be,e[62]=Fe):Fe=e[62];let Me;e[63]!==De||e[64]!==Fe?(Me=s.jsxs(Et,{children:[De,Fe]}),e[63]=De,e[64]=Fe,e[65]=Me):Me=e[65];let me;e[66]!==ue||e[67]!==se||e[68]!==Me||e[69]!==ne?(me=s.jsxs("div",{className:"flex items-center gap-1.5",children:[ne,ue,se,Me]}),e[66]=ue,e[67]=se,e[68]=Me,e[69]=ne,e[70]=me):me=e[70];let Ae;e[71]!==p?(Ae=()=>p($N),e[71]=p,e[72]=Ae):Ae=e[72];let pe;e[73]!==n?(pe=n("sessions.sidebar.header.actions.searchSessions"),e[73]=n,e[74]=pe):pe=e[74];let ce;e[75]!==u?(ce=s.jsx(I,{name:"search",className:u}),e[75]=u,e[76]=ce):ce=e[76];let he;e[77]!==m||e[78]!==f||e[79]!==Ae||e[80]!==pe||e[81]!==ce?(he=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Ae,className:m,"aria-label":pe,"aria-expanded":f,children:ce})}),e[77]=m,e[78]=f,e[79]=Ae,e[80]=pe,e[81]=ce,e[82]=he):he=e[82];let Ne;e[83]!==n?(Ne=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=Ne):Ne=e[84];let fe;e[85]!==Ne?(fe=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Ne})}),e[85]=Ne,e[86]=fe):fe=e[86];let P;e[87]!==he||e[88]!==fe?(P=s.jsxs(Et,{children:[he,fe]}),e[87]=he,e[88]=fe,e[89]=P):P=e[89];const M=S&&"bg-interactive-hover text-primary";let de;e[90]!==m||e[91]!==M?(de=Pe(m,M),e[90]=m,e[91]=M,e[92]=de):de=e[92];let xe;e[93]!==S||e[94]!==n?(xe=n(S?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=S,e[94]=n,e[95]=xe):xe=e[95];let W;e[96]!==u?(W=s.jsx(I,{name:"checkbox-multiple",className:u}),e[96]=u,e[97]=W):W=e[97];let be;e[98]!==k||e[99]!==S||e[100]!==de||e[101]!==xe||e[102]!==W?(be=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:de,"aria-label":xe,"aria-pressed":S,children:W})}),e[98]=k,e[99]=S,e[100]=de,e[101]=xe,e[102]=W,e[103]=be):be=e[103];let ve;e[104]!==S||e[105]!==n?(ve=n(S?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=S,e[105]=n,e[106]=ve):ve=e[106];let G;e[107]!==ve?(G=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ve})}),e[107]=ve,e[108]=G):G=e[108];let ye;e[109]!==be||e[110]!==G?(ye=s.jsxs(Et,{children:[be,G]}),e[109]=be,e[110]=G,e[111]=ye):ye=e[111];let Le;e[112]!==n?(Le=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[112]=n,e[113]=Le):Le=e[113];let Re;e[114]!==u?(Re=s.jsx(I,{name:"equalizer-2",className:u}),e[114]=u,e[115]=Re):Re=e[115];let J;e[116]!==m||e[117]!==Le||e[118]!==Re?(J=s.jsx(Mt,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":Le,children:Re})})}),e[116]=m,e[117]=Le,e[118]=Re,e[119]=J):J=e[119];let L;e[120]!==n?(L=n("sessions.sidebar.header.displayMode.label"),e[120]=n,e[121]=L):L=e[121];let ae;e[122]!==L?(ae=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:L})}),e[122]=L,e[123]=ae):ae=e[123];let re;e[124]!==J||e[125]!==ae?(re=s.jsxs(Et,{children:[J,ae]}),e[124]=J,e[125]=ae,e[126]=re):re=e[126];let Oe;e[127]!==j||e[128]!==N||e[129]!==n?(Oe=_?s.jsxs(s.Fragment,{children:[s.jsxs(bs,{onClick:()=>N("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),j==="default"?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(bs,{onClick:()=>N("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),j==="minimal"?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[127]=j,e[128]=N,e[129]=n,e[130]=Oe):Oe=e[130];let qe;e[131]!==D||e[132]!==o||e[133]!==A||e[134]!==n||e[135]!==T||e[136]!==B?(qe=o?s.jsxs(s.Fragment,{children:[_?s.jsx(Er,{}):null,s.jsxs(bs,{onClick:B,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showRecent")}),A?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(bs,{onClick:T,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),D?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[131]=D,e[132]=o,e[133]=A,e[134]=n,e[135]=T,e[136]=B,e[137]=qe):qe=e[137];let Ge;e[138]===Symbol.for("react.memo_cache_sentinel")?(Ge=s.jsx(Er,{}),e[138]=Ge):Ge=e[138];let Je;e[139]===Symbol.for("react.memo_cache_sentinel")?(Je=s.jsx(I,{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 gt;e[142]!==nt?(gt=s.jsx("span",{children:nt}),e[142]=nt,e[143]=gt):gt=e[143];let yt;e[144]!==C||e[145]!==gt?(yt=s.jsxs(bs,{onClick:C,className:"flex items-center gap-2",children:[Je,gt]}),e[144]=C,e[145]=gt,e[146]=yt):yt=e[146];let _e;e[147]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx(I,{name:"expand-up-down",className:"h-4 w-4"}),e[147]=_e):_e=e[147];let Qe;e[148]!==n?(Qe=n("sessions.sidebar.header.displayMode.expandAll"),e[148]=n,e[149]=Qe):Qe=e[149];let st;e[150]!==Qe?(st=s.jsx("span",{children:Qe}),e[150]=Qe,e[151]=st):st=e[151];let wt;e[152]!==w||e[153]!==st?(wt=s.jsxs(bs,{onClick:w,className:"flex items-center gap-2",children:[_e,st]}),e[152]=w,e[153]=st,e[154]=wt):wt=e[154];let Ct;e[155]!==Oe||e[156]!==qe||e[157]!==yt||e[158]!==wt?(Ct=s.jsxs(sn,{align:"end",className:"min-w-[160px]",children:[Oe,qe,Ge,yt,wt]}),e[155]=Oe,e[156]=qe,e[157]=yt,e[158]=wt,e[159]=Ct):Ct=e[159];let xt;e[160]!==re||e[161]!==Ct?(xt=s.jsxs(nn,{children:[re,Ct]}),e[160]=re,e[161]=Ct,e[162]=xt):xt=e[162];let St;e[163]!==P||e[164]!==ye||e[165]!==xt?(St=s.jsxs("div",{className:"flex items-center gap-1.5",children:[P,ye,xt]}),e[163]=P,e[164]=ye,e[165]=xt,e[166]=St):St=e[166];let Ze;e[167]!==me||e[168]!==St?(Ze=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[me,St]}),e[167]=me,e[168]=St,e[169]=Ze):Ze=e[169];let Ot;e[170]!==x||e[171]!==f||e[172]!==h||e[173]!==y||e[174]!==g||e[175]!==p||e[176]!==b||e[177]!==n?(Ot=f?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:[x?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(I,{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:y,value:g,onChange:zt=>b(zt.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:zt=>{zt.key==="Escape"&&(zt.stopPropagation(),x?b(""):p(!1))}}),g.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(I,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[170]=x,e[171]=f,e[172]=h,e[173]=y,e[174]=g,e[175]=p,e[176]=b,e[177]=n,e[178]=Ot):Ot=e[178];let ns;return e[179]!==Ze||e[180]!==Ot?(ns=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:[Ze,Ot]})}),e[179]=Ze,e[180]=Ot,e[181]=ns):ns=e[181],ns}function $N(t){return!t}function zN(t){return t.toggleArchivedSessions}function WN(t){return t.toggleRecentSection}function UN(t){return t.setDisplayMode}function HN(t){return t.showArchivedSessions}function GN(t){return t.showRecentSection}function KN(t){return t.displayMode}const hf=7;function qN({sections:t,renderSessionNode:e,currentSessionId:n,editingId:r,openSidebarMenuKey:o,variant:a="section",initialVisibleCount:c=hf,batchSize:l=hf}){const{t:d}=kt(),[u,m]=i.useState(new Set),[f,p]=i.useState(new Map),y=a==="flat",g=i.useCallback(w=>{p(v=>{if(!v.has(w))return v;const S=new Map(v);return S.delete(w),S})},[]),b=i.useCallback(w=>{g(w),m(v=>{const S=new Set(v);return S.has(w)?S.delete(w):S.add(w),S})},[g]),x=i.useCallback((w,v,S)=>{p(k=>{const j=Math.min(S,v+l),A=new Map(k);return A.set(w,j),A})},[l]),h=i.useCallback(w=>{const v=new Set;Hi(w,n,v);const S=new Set;Hi(w,r,S);const k=Fo(w,o,"recent",!1),j=new WeakMap,A=N=>{j.set(N,Fa(N)),N.children.forEach(A)};w.forEach(A);const D=N=>({subtreeContainsActive:v,subtreeContainsEditing:S,menuOpenSessionId:k,nodeStructureKey:j.get(N)??"",childRenderExtrasFor:D});return N=>({subtreeContainsActive:v,subtreeContainsEditing:S,menuOpenSessionId:k,nodeStructureKey:j.get(N)??"",childRenderExtrasFor:D})},[n,r,o]),C=t.filter(w=>w.items.length>0);return C.length===0?null:s.jsx("div",{className:Pe(y?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1"),children:C.map(w=>{const v=u.has(w.key),S=Math.max(c,f.get(w.key)??c),k=w.items.slice(0,S),j=w.items.length-k.length,A=!y&&w.items.length>c&&j===0,D=h(k.map(B=>B.node)),N=B=>e(B.node,0,B.groupDirectory,B.projectId,!1,B.secondaryMeta,"recent",D(B.node));return y?s.jsxs("div",{className:"space-y-0.5",children:[k.map(N),j>0?s.jsx("button",{type:"button",onClick:()=>x(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":!v,children:[s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground",children:v?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{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})]}),v?null:s.jsxs("div",{className:Pe("space-y-0.5 pl-7"),children:[k.map(N),j>0?s.jsx("button",{type:"button",onClick:()=>x(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,A?s.jsx("button",{type:"button",onClick:()=>g(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 Ml="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 YN(t){const e=ft.c(13),{onOpenSettings:n,onOpenShortcuts:r,onOpenAbout:o,onOpenUpdate:a,showRuntimeButtons:c,showUpdateButton:l}=t,d=c===void 0?!0:c,u=l===void 0?!0:l,{t:m}=kt();let f;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==d||e[4]!==m?(f=d?s.jsxs(s.Fragment,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Ml,"aria-label":m("sessions.sidebar.footer.actions.settings"),children:s.jsx(I,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:Ml,"aria-label":m("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(I,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:Ml,"aria-label":m("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(I,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=m,e[5]=f):f=e[5];let p;e[6]!==a||e[7]!==u||e[8]!==m?(p=u?s.jsx($e,{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:m("sessions.sidebar.footer.actions.update")}):null,e[6]=a,e[7]=u,e[8]=m,e[9]=p):p=e[9];let y;return e[10]!==f||e[11]!==p?(y=s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-2.5 py-2",children:[f,p]}),e[10]=f,e[11]=p,e[12]=y):y=e[12],y}const QN=t=>{const e=ft.c(58),{id:n,projectLabel:r,projectDescription:o,projectIcon:a,projectColor:c,projectIconImage:l,projectIconBackground:d,isCollapsed:u,isActiveProject:m,isRepo:f,isDesktopShell:p,isStuck:y,hideDirectoryControls:g,alwaysShowActions:b,onToggle:x,onNewSession:h,onNewWorktreeSession:C,onRenameStart:w,onClose:v,sentinelRef:S,children:k,showCreateButtons:j,hideHeader:A,openSidebarMenuKey:D,setOpenSidebarMenuKey:N}=t,B=j===void 0?!0:j,T=A===void 0?!1:A,{t:E}=kt(),{currentTheme:_}=qr();let R;e[0]!==n?(R={id:n},e[0]=n,e[1]=R):R=e[1];const{attributes:$,listeners:V,setNodeRef:z,transform:F,transition:ne,isDragging:te}=fc(R),q=i.useRef(!1),H=`project:${n}`,X=D===H,[oe,ue]=i.useState(!1),Se=a?Tc[a]:null,Z=c?Ya[c]??null:null;let ke;e[2]!==H||e[3]!==N?(ke=fe=>{fe&&ue(!1),N(fe?H:null)},e[2]=H,e[3]=N,e[4]=ke):ke=e[4];const Y=ke;let ge;e[5]!==g||e[6]!==f||e[7]!==v||e[8]!==h||e[9]!==w||e[10]!==B||e[11]!==E?(ge=fe=>s.jsxs(s.Fragment,{children:[B&&!f&&!g&&h&&s.jsxs(fe,{onClick:h,children:[s.jsx(I,{name:"add",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.newSession")]}),s.jsxs(fe,{onClick:w,children:[s.jsx(I,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.session.menu.rename")]}),s.jsxs(fe,{onClick:v,className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.closeProject")]})]}),e[5]=g,e[6]=f,e[7]=v,e[8]=h,e[9]=w,e[10]=B,e[11]=E,e[12]=ge):ge=e[12];const O=ge,se=ZN,ee=e2,je=t2;let De;e[13]===Symbol.for("react.memo_cache_sentinel")?(De=fe=>{(fe.button===2||fe.button===0&&fe.ctrlKey)&&(q.current=!0)},e[13]=De):De=e[13];const Be=De;let Fe;e[14]!==x?(Fe=()=>{if(q.current){q.current=!1;return}x()},e[14]=x,e[15]=Fe):Fe=e[15];const Me=Fe;let me;e[16]!==F?(me=mc.Transform.toString(F),e[16]=F,e[17]=me):me=e[17];let Ae;e[18]!==me||e[19]!==ne?(Ae={transform:me,transition:ne},e[18]=me,e[19]=ne,e[20]=Ae):Ae=e[20];const pe=te&&"opacity-30";let ce;e[21]!==pe?(ce=Pe("relative",pe),e[21]=pe,e[22]=ce):ce=e[22];let he;e[23]!==b||e[24]!==$||e[25]!==_||e[26]!==Y||e[27]!==Me||e[28]!==g||e[29]!==T||e[30]!==Z||e[31]!==n||e[32]!==m||e[33]!==u||e[34]!==oe||e[35]!==p||e[36]!==X||e[37]!==f||e[38]!==y||e[39]!==V||e[40]!==h||e[41]!==C||e[42]!==o||e[43]!==d||e[44]!==l||e[45]!==Se||e[46]!==r||e[47]!==O||e[48]!==S||e[49]!==B||e[50]!==E?(he=T?null:s.jsxs(s.Fragment,{children:[p&&s.jsx("div",{ref:S,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsxs(Lc,{open:oe,onOpenChange:ue,children:[s.jsx(Fc,{render:s.jsx("div",{className:Pe("w-full text-left group/project select-none"),style:{backgroundColor:p&&y?"transparent":void 0},onContextMenu:fe=>{g||(fe.preventDefault(),ue(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...$,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:Be,onClick:Me,...V,className:Pe("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]",f&&!g?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:Pe("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:u?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),l?s.jsx("span",{className:Pe("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(Qa,{project:{id:n,iconImage:l},options:{themeVariant:_.metadata.variant,iconColor:_.colors.surface.foreground},className:"h-full w-full object-contain",fallback:Se?s.jsx(I,{name:Se,className:"h-3.5 w-3.5",style:Z?{color:Z}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:Z?{color:Z}:void 0})})}):Se?s.jsx(I,{name:Se,className:Pe("h-3.5 w-3.5",b?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:Z?{color:Z}:void 0}):s.jsx(I,{name:"folder",className:Pe("h-3.5 w-3.5 text-muted-foreground/80",b?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:Z?{color:Z}:void 0})]}),s.jsx("span",{className:Pe("text-[14px] font-normal truncate lowercase",m?"text-foreground":"text-foreground group-hover/project:text-foreground"),children:r})]})}),s.jsx(Ft,{side:"right",sideOffset:8,children:o})]}),s.jsxs("div",{className:Pe("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",B?"right-7":"right-0.5"),children:[B&&f&&!g&&C?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:fe=>{fe.stopPropagation(),C()},className:Pe("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(I,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,g?null:s.jsxs(nn,{open:X,onOpenChange:Y,children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe("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",X?"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:ee,onMouseDown:je,onClick:se,children:s.jsx(I,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(sn,{align:"end",className:"min-w-[180px]",children:O(bs)})]})]}),B&&h?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:fe=>{fe.stopPropagation(),h()},className:Pe("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(f?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession"),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E(f?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(Ec,{className:"min-w-[180px]",children:O(Mc)})]})]}),e[23]=b,e[24]=$,e[25]=_,e[26]=Y,e[27]=Me,e[28]=g,e[29]=T,e[30]=Z,e[31]=n,e[32]=m,e[33]=u,e[34]=oe,e[35]=p,e[36]=X,e[37]=f,e[38]=y,e[39]=V,e[40]=h,e[41]=C,e[42]=o,e[43]=d,e[44]=l,e[45]=Se,e[46]=r,e[47]=O,e[48]=S,e[49]=B,e[50]=E,e[51]=he):he=e[51];let Ne;return e[52]!==k||e[53]!==z||e[54]!==ce||e[55]!==he||e[56]!==Ae?(Ne=s.jsxs("div",{ref:z,style:Ae,className:ce,children:[he,k]}),e[52]=k,e[53]=z,e[54]=ce,e[55]=he,e[56]=Ae,e[57]=Ne):Ne=e[57],Ne},JN=t=>{const e=ft.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:u,transform:m,transition:f,isDragging:p}=fc(c);let y;e[3]!==l||e[4]!==u?(y={listeners:l,setActivatorNodeRef:u},e[3]=l,e[4]=u,e[5]=y):y=e[5];const g=y;let b;e[6]!==m?(b=mc.Transform.toString(m),e[6]=m,e[7]=b):b=e[7];let x;e[8]!==b||e[9]!==f?(x={transform:b,transition:f},e[8]=b,e[9]=f,e[10]=x):x=e[10];const h=p&&"opacity-50";let C;e[11]!==h?(C=Pe("space-y-0.5 rounded-md",h),e[11]=h,e[12]=C):C=e[12];let w;e[13]!==o||e[14]!==g?(w=typeof o=="function"?o(g):o,e[13]=o,e[14]=g,e[15]=w):w=e[15];let v;return e[16]!==d||e[17]!==x||e[18]!==C||e[19]!==w?(v=s.jsx("div",{ref:d,style:x,className:C,children:w}),e[16]=d,e[17]=x,e[18]=C,e[19]=w,e[20]=v):v=e[20],v},XN=i.memo(JN);function ZN(t){t.stopPropagation()}function e2(t){t.stopPropagation()}function t2(t){t.stopPropagation()}function s2(t){const{t:e}=kt(),n=xa(yo(ba,{activationConstraint:{distance:8}}),yo(tp,{coordinateGetter:ep})),r=xa(yo(ba,{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,u)=>{const m=a.current,f=m.get(d);if(f&&f.groups===u)return f.ordered;const p=t.getOrderedGroups(d,u);if(m.set(d,{groups:u,ordered:p}),m.size>256){const y=m.keys().next().value;y!==void 0&&m.delete(y)}return p};return t.sharedSessionsOnly?s.jsxs($n,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("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($n,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.emptyState]}):t.sectionsForRender.length===0?s.jsx($n,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:t.searchEmptyState}):s.jsxs($n,{ref:o,useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("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 u=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(!u)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[u,...m&&m.id!==u.id?[m]:[]].map(p=>{const y=`${d.project.id}:${p.id}`,g=p.id===u.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(p,y,d.project.id,g,null,!0,o)},y)})})()}):s.jsx(s.Fragment,{children:s.jsxs(ya,{sensors:n,collisionDetection:wa,onDragEnd:d=>{if(t.isInlineEditing)return;const{active:u,over:m}=d;if(!m||u.id===m.id)return;const f=t.sectionsForRender.findIndex(y=>y.project.id===u.id),p=t.sectionsForRender.findIndex(y=>y.project.id===m.id);f===-1||p===-1||f===p||t.reorderProjects(f,p)},children:[s.jsx(Vl,{items:t.sectionsForRender.map(d=>d.project.id),strategy:$l,children:t.sectionsForRender.map(d=>{const u=d.project,m=u.id,f=Dm(u.label?.trim()||Ti(u.normalizedPath,t.homeDirectory)||u.normalizedPath),p=ka(u.normalizedPath,t.homeDirectory),y=t.collapsedProjects.has(m),g=m===t.activeProjectId,b=t.projectRepoStatus.get(m),x=l(m,d.groups),h=x.find(w=>w.isMain)??null,C=h?x.filter(w=>w.id!==h.id):x;return s.jsx(QN,{id:m,projectLabel:f,projectDescription:p,projectIcon:u.icon,projectColor:u.color,projectIconImage:u.iconImage,projectIconBackground:u.iconBackground,isCollapsed:y,isActiveProject:g,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:u.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:y?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:d.groups.length>0?s.jsxs(ya,{sensors:r,collisionDetection:wa,onDragEnd:w=>{if(t.isInlineEditing)return;const{active:v,over:S}=w;if(!S||v.id===S.id)return;const k=C.findIndex(N=>N.id===v.id),j=C.findIndex(N=>N.id===S.id);if(k===-1||j===-1||k===j)return;const A=Ff(C,k,j).map(N=>N.id),D=h?[h.id,...A]:A;t.setGroupOrderByProject(N=>{const B=new Map(N);return B.set(m,D),B})},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 v=`${m}:${w.id}`;return s.jsx(XN,{id:w.id,disabled:t.isInlineEditing,children:S=>t.renderGroupSessions(w,v,m,!1,S,void 0,o)},w.id)})}),s.jsx(Wl,{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(Wl,{dropAnimation:null})]})})]})}function n2(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(Xi(),{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 r2(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 i2(t){const e=t.info.role==="user"?"User":"Assistant",n=n2(t.info.time?.created),r=r2(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
170
-
171
- *${o}*`:`**${e}**`}function o2(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function xh(t){const e=i2(t),n=o2(t.parts).trim();return n?`${e}
172
-
173
- ${n}`:""}function bh(t,e){const n="#".repeat(Math.min(e+1,6)),r=t.agent?` — ${t.agent}`:"",o=`${n} Sub-agent: ${t.title}${r}
174
-
175
- ---
176
-
177
- `,a=t.records.map(xh).filter(Boolean).join(`
178
-
179
- ---
180
-
181
- `),c=[o+a];for(const l of t.children)c.push(bh(l,e+1));return c.join(`
182
-
183
- ---
184
-
185
- `)}function a2(t,e,n){const r=e?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
186
-
187
- *Exported on ${o}*
188
-
189
- ---
190
-
191
- `,c=t.map(xh).filter(Boolean).join(`
192
-
193
- ---
194
-
195
- `);let l=a+c;if(n&&n.length>0){const d=n.map(u=>bh(u,1)).join(`
196
-
197
- ---
198
-
199
- `);l+=`
200
-
201
- ---
202
-
203
- `+d}return l}function l2(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 c2(t,e){const n=await yp(e,t);if(n)return n;if(!Kr())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 d2(t){const e=Lo()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await wp(t)?!0:va(t)}function u2(){return Ac()}function f2(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 m2=(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},Vn=ro()((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],u=o.indexOf(d),m=o.indexOf(r);if(u<0||m<0)return;const[f,p]=u<=m?[u,m]:[m,u],y=o.slice(f,p+1),g=m2(y,c),x=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const h of g)x.add(h);t({selectedIds:x,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 ac=!1;const lc=new Set;let pf=!1;function h2(){for(const t of lc)t()}function qc(t){ac!==t&&(ac=t,h2())}function p2(t){t.key==="Shift"&&qc(!0)}function g2(t){t.key==="Shift"&&qc(!1)}function x2(){qc(!1)}function b2(){pf||typeof window>"u"||(pf=!0,window.addEventListener("keydown",p2),window.addEventListener("keyup",g2),window.addEventListener("blur",x2))}function y2(t){return b2(),lc.add(t),()=>{lc.delete(t)}}function w2(){return ac}function v2(){return!1}function j2(){return Xe.useSyncExternalStore(y2,w2,v2)}const S2=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,yh=/^g[1-9]\d*$/,xo=(t,e,n,r,o)=>{if(!S2.test(t)||e!==void 0&&!yh.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}},pa=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 xo(n,void 0,e[1],e[2],void 0);if(e.length===4){const[,l,d,u]=e;return yh.test(l)?xo(n,l,d,u,void 0):xo(n,void 0,l,d,u)}const[,r,o,a,c]=e;return r===""?xo(n,void 0,o,a,c):xo(n,r,o,a,c)},N2=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("/")},k2=(t,e,n,r)=>{const o=[t];return r&&o.push(r),o.push(e,n,"fusion"),o.join("/")},wh=t=>{const e=ft.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=kt(),u=ss(C2),m=ss(A2),f=ss(D2);let p;e[0]!==u?(p=u(),e[0]=u,e[1]=p):p=e[1];const y=p;let g;e[2]!==y?(g=y.filter(I2),e[2]=y,e[3]=g):g=e[3];const b=g;let x,h;e[4]!==y.length||e[5]!==m?(x=()=>{y.length===0&&m()},h=[y.length,m],e[4]=y.length,e[5]=m,e[6]=x,e[7]=h):(x=e[6],h=e[7]),i.useEffect(x,h);let C,w;e[8]!==f||e[9]!==a||e[10]!==r||e[11]!==b||e[12]!==n?(C=()=>{if(a)return;const T=n.trim();if(T.length>0&&b.some(R=>R.name===T))return;const E=typeof f=="string"&&f.trim().length>0?f.trim():null;if(E&&b.some(R=>R.name===E)){r(E);return}const _=b[0]?.name;_&&r(_)},w=[f,a,r,b,n],e[8]=f,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 v=n.trim().length>0?n:void 0;let S;e[15]!==o?(S=Pe("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]=S):S=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 A;e[21]!==c||e[22]!==S||e[23]!==j?(A=s.jsx(Wn,{id:c,size:"lg",className:S,children:j}),e[21]=c,e[22]=S,e[23]=j,e[24]=A):A=e[24];let D;e[25]!==b?(D=b.length>0&&s.jsx(Hl,{children:b.map(P2)}),e[25]=b,e[26]=D):D=e[26];let N;e[27]!==l||e[28]!==D?(N=s.jsx(Un,{fitContent:!0,portalToBody:l,children:D}),e[27]=l,e[28]=D,e[29]=N):N=e[29];let B;return e[30]!==a||e[31]!==r||e[32]!==v||e[33]!==A||e[34]!==N?(B=s.jsxs(zn,{value:v,onValueChange:r,disabled:a,children:[A,N]}),e[30]=a,e[31]=r,e[32]=v,e[33]=A,e[34]=N,e[35]=B):B=e[35],B};function C2(t){return t.getVisibleAgents}function A2(t){return t.loadAgents}function D2(t){return t.currentAgentName}function I2(t){return jc(t.mode)}function P2(t){return s.jsx(Ms,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const vh="h-7",Ao=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,T2=t=>{const e=ft.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=Pe("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",vh),e[0]=d):d=e[0];let u;e[1]!==n.providerID?(u=s.jsx(Do,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=u):u=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 f;e[5]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(I,{name:"close",className:"h-3.5 w-3.5"}),e[5]=f):f=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:f}),e[6]=a,e[7]=p):p=e[7];let y;return e[8]!==u||e[9]!==m||e[10]!==p?(y=s.jsxs("div",{className:d,children:[u,m,p]}),e[8]=u,e[9]=m,e[10]=p,e[11]=y):y=e[11],y},jh=t=>{const e=ft.c(119),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:u,addButtonClassName:m,dropdownSide:f,dropdownClassName:p,containerClassName:y,triggerIcon:g}=t,b=d===void 0?!0:d,x=f===void 0?"top":f,{t:h}=kt(),C=ss(R2),w=ss(E2),v=Ee(M2),S=Ee(F2),{favoriteModelsList:k,recentModelsList:j}=Eg(),A=Ee(L2),D=Ee(O2),[N,B]=i.useState(!1),[T,E]=i.useState(""),[_,R]=i.useState(null),$=i.useRef(null),V=i.useRef(null),z=u===1,F=u===void 0||n.length<u||z;let ne;if(e[0]!==n){ne=new Map;for(const ae of n){const re=`${ae.providerID}:${ae.modelID}`;ne.set(re,(ne.get(re)||0)+1)}e[0]=n,e[1]=ne}else ne=e[1];const te=ne;let q;e[2]!==n?(q=ae=>n.filter(Oe=>Oe.providerID===ae.providerID&&Oe.modelID===ae.modelID).findIndex(Oe=>Oe.instanceId===ae.instanceId)+1,e[2]=n,e[3]=q):q=e[3];const H=q;let X,oe;e[4]!==x||e[5]!==N?(X=()=>{if(!N||!V.current)return;const ae=V.current.getBoundingClientRect();if(x==="bottom"){const nt=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-ae.bottom-16-112;R(Math.max(160,Math.min(320,nt)));return}let re=V.current.parentElement;for(;re&&!(re.getAttribute("role")==="dialog"||re.hasAttribute("data-scroll-shadow"));){const Ge=getComputedStyle(re);if(Ge.overflow==="auto"||Ge.overflow==="hidden"||Ge.overflowY==="auto"||Ge.overflowY==="hidden")break;re=re.parentElement}const Oe=re?re.getBoundingClientRect().top:0,qe=ae.top-Oe-16;R(Math.max(150,Math.min(300,qe)))},oe=[x,N],e[4]=x,e[5]=N,e[6]=X,e[7]=oe):(X=e[6],oe=e[7]),i.useEffect(X,oe);let ue,Se;e[8]!==F||e[9]!==N?(ue=()=>{!F&&N&&(B(!1),E(""))},Se=[F,N],e[8]=F,e[9]=N,e[10]=ue,e[11]=Se):(ue=e[10],Se=e[11]),i.useEffect(ue,Se);let Z,ke;e[12]!==N?(Z=()=>{if(!N)return;const ae=re=>{$.current&&!$.current.contains(re.target)&&(B(!1),E(""))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},ke=[N],e[12]=N,e[13]=Z,e[14]=ke):(Z=e[13],ke=e[14]),i.useEffect(Z,ke);let Y;e[15]!==z||e[16]!==r||e[17]!==a||e[18]!==n.length?(Y=ae=>{const re={providerID:ae.providerID,modelID:ae.modelID,displayName:ae.model.name||ae.modelID,instanceId:Ao()};z&&n.length>0&&a?a(0,re):r(re),z&&(B(!1),E(""))},e[15]=z,e[16]=r,e[17]=a,e[18]=n.length,e[19]=Y):Y=e[19];const ge=Y;let O;e[20]!==h?(O=h("multirun.modelMultiSelect.search.placeholder"),e[20]=h,e[21]=O):O=e[21];let se;e[22]!==h?(se=h("multirun.modelMultiSelect.search.noResults"),e[22]=h,e[23]=se):se=e[23];let ee;e[24]!==h?(ee=h("multirun.modelMultiSelect.sections.favorites"),e[24]=h,e[25]=ee):ee=e[25];let je;e[26]!==h?(je=h("multirun.modelMultiSelect.sections.recent"),e[26]=h,e[27]=je):je=e[27];let De;e[28]!==h?(De=h("multirun.modelMultiSelect.keyboard.hint"),e[28]=h,e[29]=De):De=e[29];let Be;e[30]!==h?(Be=h("settings.agents.modelSelector.actions.favorite"),e[30]=h,e[31]=Be):Be=e[31];let Fe;e[32]!==h?(Fe=h("settings.agents.modelSelector.actions.unfavorite"),e[32]=h,e[33]=Fe):Fe=e[33];let Me;e[34]!==h?(Me=h("chat.modelControls.capabilities"),e[34]=h,e[35]=Me):Me=e[35];let me;e[36]!==h?(me=h("chat.modelControls.capability.toolCalling"),e[36]=h,e[37]=me):me=e[37];let Ae;e[38]!==h?(Ae=h("chat.modelControls.capability.reasoning"),e[38]=h,e[39]=Ae):Ae=e[39];let pe;e[40]!==h?(pe=h("chat.modelControls.input"),e[40]=h,e[41]=pe):pe=e[41];let ce;e[42]!==h?(ce=h("chat.modelControls.output"),e[42]=h,e[43]=ce):ce=e[43];let he;e[44]!==h?(he=h("chat.modelControls.costPerMillion"),e[44]=h,e[45]=he):he=e[45];let Ne;e[46]!==O||e[47]!==se||e[48]!==ee||e[49]!==je||e[50]!==De||e[51]!==Be||e[52]!==Fe||e[53]!==Me||e[54]!==me||e[55]!==Ae||e[56]!==pe||e[57]!==ce||e[58]!==he?(Ne={searchPlaceholder:O,noResults:se,favorites:ee,recent:je,keyboardHint:De,favorite:Be,unfavorite:Fe,capabilities:Me,capabilityToolCalling:me,capabilityReasoning:Ae,input:pe,output:ce,costPerMillion:he},e[46]=O,e[47]=se,e[48]=ee,e[49]=je,e[50]=De,e[51]=Be,e[52]=Fe,e[53]=Me,e[54]=me,e[55]=Ae,e[56]=pe,e[57]=ce,e[58]=he,e[59]=Ne):Ne=e[59];const fe=Ne;let P;e[60]!==y?(P=Pe("relative",y),e[60]=y,e[61]=P):P=e[61];let M;e[62]!==m?(M=Pe(vh,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",m),e[62]=m,e[63]=M):M=e[63];const de=!F;let xe;e[64]!==N?(xe=()=>{B(!N)},e[64]=N,e[65]=xe):xe=e[65];let W;e[66]!==g?(W=g??s.jsx(I,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=g,e[67]=W):W=e[67];let be;e[68]!==l||e[69]!==h?(be=l??h("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=h,e[70]=be):be=e[70];let ve;e[71]!==M||e[72]!==de||e[73]!==xe||e[74]!==W||e[75]!==be?(ve=s.jsxs($e,{ref:V,type:"button",variant:"outline",size:"sm",className:M,disabled:de,onClick:xe,children:[W,be]}),e[71]=M,e[72]=de,e[73]=xe,e[74]=W,e[75]=be,e[76]=ve):ve=e[76];let G;e[77]!==_||e[78]!==F||e[79]!==p||e[80]!==x||e[81]!==k||e[82]!==ge||e[83]!==A||e[84]!==S||e[85]!==N||e[86]!==fe||e[87]!==te||e[88]!==w||e[89]!==D||e[90]!==C||e[91]!==j||e[92]!==T||e[93]!==v?(G=N?s.jsx("div",{className:Pe("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",x==="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(Mg,{providers:C,providerOrder:D,favoriteModels:k,recentModels:j,modelsMetadata:w,hiddenModels:A,searchQuery:T,onSearchQueryChange:E,onSelect:ge,labels:fe,selectionCount:ae=>te.get(`${ae.providerID}:${ae.modelID}`)||0,disabled:!F,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:_?`${_}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:N,isFavorite:ae=>S(ae.providerID,ae.modelID),onToggleFavorite:ae=>v(ae.providerID,ae.modelID),onEscape:()=>{B(!1),E("")}})}):null,e[77]=_,e[78]=F,e[79]=p,e[80]=x,e[81]=k,e[82]=ge,e[83]=A,e[84]=S,e[85]=N,e[86]=fe,e[87]=te,e[88]=w,e[89]=D,e[90]=C,e[91]=j,e[92]=T,e[93]=v,e[94]=G):G=e[94];let ye;e[95]!==P||e[96]!==ve||e[97]!==G?(ye=s.jsxs("div",{className:P,ref:$,children:[ve,G]}),e[95]=P,e[96]=ve,e[97]=G,e[98]=ye):ye=e[98];let Le;e[99]!==H||e[100]!==te||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((ae,re)=>{const Oe=`${ae.providerID}:${ae.modelID}`,qe=te.get(Oe)||1,Ge=H(ae),nt=C.find(Qe=>Qe.id===ae.providerID)?.models?.find(Qe=>Qe.id===ae.modelID),gt=nt?.variants?Object.keys(nt.variants):[],yt=gt.length>0,_e=ae.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(T2,{model:ae,instanceIndex:Ge,totalSameModel:qe,onRemove:()=>o(re)}),yt&&s.jsxs(zn,{value:_e,onValueChange:Qe=>{if(!a)return;a(re,{...ae,variant:Qe==="__default__"?void 0:Qe})},children:[s.jsxs(Wn,{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(I,{name:"brain-ai-3",className:Pe("h-3.5 w-3.5 flex-shrink-0",_e==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(Cn,{placeholder:h("multirun.modelMultiSelect.variant.placeholder"),children:Qe=>Qe==="__default__"?h("multirun.modelMultiSelect.variant.default"):Qe})]}),s.jsxs(Un,{fitContent:!0,children:[s.jsx(Ms,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:h("multirun.modelMultiSelect.variant.default")}),gt.map(B2)]})]})]},ae.instanceId)})}),e[99]=H,e[100]=te,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 Re;e[108]!==ye||e[109]!==Le?(Re=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[ye,Le]}),e[108]=ye,e[109]=Le,e[110]=Re):Re=e[110];let J;e[111]!==u||e[112]!==c||e[113]!==n.length||e[114]!==h?(J=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:u!==void 0?h("multirun.modelMultiSelect.validation.minToMax",{min:c,max:u}):h("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[111]=u,e[112]=c,e[113]=n.length,e[114]=h,e[115]=J):J=e[115];let L;return e[116]!==Re||e[117]!==J?(L=s.jsxs("div",{className:"space-y-2",children:[Re,J]}),e[116]=Re,e[117]=J,e[118]=L):L=e[118],L};function R2(t){return t.providers}function E2(t){return t.modelsMetadata}function M2(t){return t.toggleFavoriteModel}function F2(t){return t.isFavoriteModel}function L2(t){return t.hiddenModels}function O2(t){return t.providerOrder}function B2(t){return s.jsx(Ms,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const _2=(t,e,n)=>{const r=t.session.title?.trim()||t.session.id;return`
204
-
205
- --- RESULT ${n+1}: ${r} ---
206
- ${e.trim()}
207
- --- END RESULT ${n+1} ---`},gf=(t,e)=>ut.getState().getWorktreeMetadata(t)?.projectDirectory??e,V2=async t=>{const e=t.directory??void 0,n=Fg(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 $2({session:t,open:e,onOpenChange:n}){const{t:r}=kt(),o=yc(),a=jr(z=>z.activeSessions),c=jr(z=>z.archivedSessions),l=ss(z=>z.providers),d=ss(z=>z.currentProviderId),u=ss(z=>z.currentModelId),m=ss(z=>z.currentAgentName),[f,p]=i.useState(d??""),[y,g]=i.useState(u??""),[b,x]=i.useState(()=>d&&u?[{providerID:d,modelID:u,instanceId:Ao()}]:[]),[h,C]=i.useState(""),[w,v]=i.useState(m??""),[S,k]=i.useState([]),[j,A]=i.useState(!1),D=i.useMemo(()=>pa(t.title),[t.title]),N=i.useMemo(()=>{const z=new Map;for(const F of o)z.set(F.id,F);for(const F of a)z.set(F.id,F);for(const F of c)z.set(F.id,F);return t.id&&z.set(t.id,t),Array.from(z.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!D)return;const z=ut.getState().getDirectoryForSession(t.id),F=gf(t.id,z),ne=N.map(te=>{const q=pa(te.title);if(!q||q.groupSlug!==D.groupSlug||q.fusion||(q.runGroup??null)!==(D.runGroup??null))return null;const H=ut.getState().getDirectoryForSession(te.id)??Rr(te),X=gf(te.id,H);return F&&X&&F!==X?null:{session:te,directory:H,projectDirectory:X}}).filter(te=>te!==null).sort((te,q)=>(te.session.time?.created??0)-(q.session.time?.created??0));k(ne)},[N,e,D,t.id]);const T=l.find(z=>z.id===f)?.models.find(z=>z.id===y),E=T?.variants?Object.keys(T.variants):[],_=!!(D&&f&&y&&S.length>0&&!j),R=i.useCallback(z=>{x([z]),p(z.providerID),g(z.modelID),C("")},[]),$=b[0]?.displayName||b[0]?.modelID||r("multirun.fusion.model.placeholder"),V=async()=>{if(!(!D||!f||!y)){A(!0);try{const z=await Promise.all(S.map(oe=>V2(oe))),F=S.map((oe,ue)=>({source:oe,text:z[ue]??""})).filter(oe=>oe.text.trim().length>0);if(F.length===0){le.error(r("multirun.fusion.toast.noOutputs"));return}const ne=S[0]?.projectDirectory??S[0]?.directory??null,te=k2(D.groupSlug,f,y,D.runGroup),[q,H]=await Promise.all([En("session.fusion.visible"),En("session.fusion.instructions")]),X=await ut.getState().createSession(te,ne,null);if(!X)throw new Error("Failed to create fusion session");ut.getState().setCurrentSession(X.id,ne),n(!1),await Jn.sendMessage({id:X.id,providerID:f,modelID:y,variant:h||void 0,agent:w||void 0,text:q,additionalParts:[{text:H,synthetic:!0},...F.map((oe,ue)=>({text:_2(oe.source,oe.text,ue),synthetic:!0})),{text:`
208
-
209
- --- FUSION INPUTS END ---
210
- Now write the final fused answer.`,synthetic:!0}],directory:ne??Jn.getDirectory()})}catch(z){console.error("[MultiRunFusion] Failed to start fusion",z),le.error(r("multirun.fusion.toast.failed"))}finally{A(!1)}}};return s.jsx($s,{open:e,onOpenChange:n,children:s.jsxs(Vs,{className:"max-w-xl overflow-visible",children:[s.jsxs(Gs,{children:[s.jsx(Us,{children:r("multirun.fusion.title")}),s.jsx(ln,{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(jh,{selectedModels:b,onAdd:R,onUpdate:(z,F)=>R(F),onRemove:()=>{x([]),p(""),g(""),C("")},maxModels:1,addButtonLabel:$,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:f?s.jsx(Do,{providerId:f,className:"h-3.5 w-3.5 mr-1"}):void 0})}),E.length>0?s.jsxs(zn,{value:h||"__default__",onValueChange:z=>C(z==="__default__"?"":z),children:[s.jsxs(Wn,{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(I,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(Cn,{children:z=>z==="__default__"?r("multirun.modelMultiSelect.variant.default"):z})]}),s.jsxs(Un,{fitContent:!0,portalToBody:!0,children:[s.jsx(Ms,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),E.map(z=>s.jsx(Ms,{value:z,children:z},z))]})]}):null,s.jsx(wh,{value:w,onChange:v,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:S.length})}),s.jsx("div",{className:"max-h-56 space-y-1 overflow-auto rounded-lg border border-[var(--interactive-border)] p-1",children:S.map(z=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(Do,{providerId:pa(z.session.title)?.providerID??"",className:"h-4 w-4"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:z.session.title||z.session.id}),s.jsx("button",{type:"button",onClick:()=>k(F=>F.filter(ne=>ne.session.id!==z.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"h-4 w-4"})})]},z.session.id))})]}),s.jsxs(or,{children:[s.jsx($e,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx($e,{onClick:V,disabled:!_,children:r(j?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function z2(t){const e=ft.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 W2=i.memo(function(e){const n=ft.c(22),{archiveLabel:r,deleteLabel:o,buttonSizeClass:a,iconSizeClass:c,onPointerDown:l,onMouseDown:d,onArchive:u,onDelete:m}=e,f=j2(),p=f?o:r;let y;n[0]!==u||n[1]!==m||n[2]!==f?(y=k=>{if(f||k.shiftKey){m(k);return}u(k)},n[0]=u,n[1]=m,n[2]=f,n[3]=y):y=n[3];const g=y,b=f?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground";let x;n[4]!==a||n[5]!==b?(x=Pe("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]=x):x=n[6];const h=f?"delete-bin":"archive";let C;n[7]!==c||n[8]!==h?(C=s.jsx(I,{name:h,className:c}),n[7]=c,n[8]=h,n[9]=C):C=n[9];let w;n[10]!==g||n[11]!==p||n[12]!==d||n[13]!==l||n[14]!==x||n[15]!==C?(w=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:x,"aria-label":p,onPointerDown:l,onMouseDown:d,onClick:g,onKeyDown:Q2,children:C})}),n[10]=g,n[11]=p,n[12]=d,n[13]=l,n[14]=x,n[15]=C,n[16]=w):w=n[16];let v;n[17]!==p?(v=s.jsx(Ft,{side:"left",sideOffset:8,children:p}),n[17]=p,n[18]=v):v=n[18];let S;return n[19]!==w||n[20]!==v?(S=s.jsxs(Et,{children:[w,v]}),n[19]=w,n[20]=v,n[21]=S):S=n[21],S});function U2(t){const{t:e}=kt(),{node:n,depth:r=0,groupDirectory:o,projectId:a,archivedBucket:c=!1,currentSessionId:l,pinnedSessionIds:d,expandedParents:u,hasSessionSearchQuery:m,normalizedSessionSearchQuery:f,notifyOnSubtasks:p,editingId:y,setEditingId:g,editTitle:b,setEditTitle:x,handleSaveEdit:h,handleCancelEdit:C,toggleParent:w,handleSessionSelect:v,handleSessionDoubleClick:S,togglePinnedSession:k,handleShareSession:j,copiedSessionId:A,handleCopyShareUrl:D,handleUnshareSession:N,openSidebarMenuKey:B,setOpenSidebarMenuKey:T,renamingFolderId:E,getFoldersForScope:_,getSessionFolderId:R,removeSessionFromFolder:$,addSessionToFolder:V,createFolderAndStartRename:z,openContextPanelTab:F,handleDeleteSession:ne,mobileVariant:te,alwaysShowActions:q,renderSessionNode:H,secondaryMeta:X,renderContext:oe="project",subtreeContainsActive:ue,subtreeContainsEditing:Se,menuOpenSessionId:Z,childRenderExtrasFor:ke,liveSessionById:Y}=t,ge=!!X?.projectLabel,O=!!X?.branchLabel,se=Ir(Ue=>Ue.displayMode),ee=i.useMemo(()=>Kr(),[]),je=se==="minimal"||ee,De=i.useMemo(()=>Ba(),[]),Be=i.useContext(Og),Fe=ee?"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",Me=ee?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",me=ee,Ae=!c&&!te,pe=je?ee?Ae&&me?"group-hover:pr-18":Ae||me?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":ee?Ae&&me?"group-hover:pr-18":Ae||me?"group-hover:pr-12":"group-hover:pr-5":Ae?"group-hover:pr-12 group-focus-within:pr-12":"group-hover:pr-5 group-focus-within:pr-5",ce=Ae?"pr-13":"pr-7",he=i.useRef(!1),[Ne,fe]=i.useState(!1),P=i.useRef(y);P.current=y;const M=i.useRef(null),de=i.useRef(h);de.current=h;const[xe,W]=i.useState(b),be=i.useRef(xe);be.current=xe;const ve=i.useRef(null),G=i.useRef(null),ye=n.session,Le=Y.get(ye.id)??ye,Re=as(ye.directory??null)??as(o??null),J=im(Re??void 0,{bootstrap:!c}),L=Rc(),ae=Vn(Ue=>Ue.enabled),re=Vn(i.useCallback(Ue=>Ue.selectedIds.has(ye.id),[ye.id])),Oe=Vn(Ue=>Ue.toggleSelected),qe=Vn(Ue=>Ue.setRange),Ge=i.useCallback(Ue=>{const Xt=[],Is=Ts=>{Ts.children.forEach(Ws=>{Xt.push(Ws.session.id),Is(Ws)})};return Is(Ue),Xt},[]),[Je,nt]=i.useState(!1),[gt,yt]=i.useState(!0),_e=`${oe}:${c?"archived":"active"}:${ye.id}`,Qe=fm(i.useCallback(Ue=>!!Ue.sessionMemoryState.get(Bg(ye.id))?.isZombie,[ye.id])),st=_g(ye.id),wt=Vg(ye.id,Re??void 0),Ct=l===ye.id,xt=Le.title||e("sessions.sidebar.session.untitled"),St=n.children.length>0,Ze=d.has(ye.id),Ot=_e,ns=m?!0:u.has(Ot),zt=!!Le.parentID,At=$g(ye.id)>0&&(!zt||p),ot=Le.time?.updated||Le.time?.created||Date.now(),vt=mb(ot),bt=hb(ot),ls=B===_e,[Wt,qt]=i.useState(!1),rs=ls||Wt,Ut=i.useMemo(()=>pa(Le.title)!==null,[Le.title]),[Bt,_t]=i.useState(!1),Yt=ee&&oe==="recent"&&!je,Ht=ee&&oe==="recent"&&je,Zt=i.useMemo(()=>Ge(n).length,[Ge,n]),ys=i.useCallback(async Ue=>{const Xt=[];let Is=0;for(const Ts of Ue)try{await L.ensureSessionRenderable(Ts.session.id);const Ws=_d(J.getState(),Ts.session.id).list,qs=Ts.session.title||e("sessions.sidebar.session.export.untitledSubagent"),Hs=Ts.session.agent,Os=await ys(Ts.children);Is+=Os.skipped,Xt.push({title:qs,agent:Hs,records:Ws,children:Os.children})}catch{Is+=Ge(Ts).length+1}return{children:Xt,skipped:Is}},[Ge,J,L,e]),Tt=i.useCallback(Ue=>{Ue<=0||le.warning(Ue===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:Ue}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:Ue}))},[e]),Vt=i.useCallback(async Ue=>{if(!Re){le.error(e("sessions.sidebar.session.export.nothingToExport"));return}await L.ensureSessionRenderable(ye.id);const Xt=_d(J.getState(),ye.id).list;if(Xt.length===0){le.error(e("sessions.sidebar.session.export.nothingToExport"));return}let Is,Ts=0;if(Ue&&n.children.length>0){const Os=await ys(n.children);Is=Os.children,Ts=Os.skipped}const Ws=a2(Xt,Le.title??null,Is),qs=f2(Le.title??null),Hs=await c2(Ws,qs);if(Hs){le.success(e("sessions.sidebar.session.export.success"),{action:{label:e(u2()),onClick:()=>{d2(Hs).then(Os=>{Os||le.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),Tt(Ts);return}l2(Ws,qs),le.success(e("sessions.sidebar.session.export.success")),Tt(Ts)},[ys,J,n.children,Le.title,ye.id,Re,Tt,L,e]),Dt=i.useCallback(async()=>{if(n.children.length>0){yt(!0),nt(!0);return}await Vt(!1)},[Vt,n.children.length]),cs=i.useCallback(()=>{Re&&Hr("desktop_open_session_mini_chat_window",{sessionId:ye.id,directory:Re,apiBaseUrl:Ur(),clientToken:Ul()}).catch(Ue=>{console.warn("[session-sidebar] failed to open mini chat window",Ue)})},[ye.id,Re]);if(i.useEffect(()=>{if(y!==ye.id)return;const Ue=Xt=>{G.current&&!G.current.contains(Xt.target)&&de.current(be.current)};return document.addEventListener("mousedown",Ue),()=>document.removeEventListener("mousedown",Ue)},[y,ye.id]),i.useLayoutEffect(()=>{if(y!==ye.id){ve.current===ye.id&&(ve.current=null);return}ve.current!==ye.id&&(ve.current=ye.id,W(b))},[y,b,ye.id]),y===ye.id)return s.jsx("div",{className:Pe("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(xe)},children:[s.jsx("input",{value:xe,onChange:Ue=>W(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(I,{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(I,{name:"close",className:"size-4"})})]}),je?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:[St?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:ns?s.jsx(I,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(I,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:vt}),ge?s.jsx("span",{className:"truncate",children:X?.projectLabel}):null,O?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:X?.branchLabel})]}):null]})})]})},ye.id);const us=st?.type??"idle",He=us==="busy"||us==="retry",Ke=wt.length,Lt=He||!He&&At&&!Ct,Nt=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")}),xs=!q&&St&&(Lt||Ze),ps=Ze&&!Lt,os=s.jsx(I,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}),Kt=Lt||ps?s.jsxs("span",{className:Pe("pointer-events-none absolute left-0.5 inline-flex h-3.5 w-3.5 items-center justify-center transition-opacity",je?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",xs?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[Lt?Nt:null,ps?os:null]}):null,Fs=St&&!q&&(Lt||Ze),js=St?s.jsx("span",{role:"button",tabIndex:0,onClick:Ue=>{Ue.stopPropagation(),w(Ot)},onKeyDown:Ue=>{(Ue.key==="Enter"||Ue.key===" ")&&(Ue.preventDefault(),Ue.stopPropagation(),w(Ot))},style:{minWidth:14,minHeight:14},className:Pe("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",Yt?"absolute left-1.5 bottom-1":Ht?"relative mr-0.5 shrink-0":Pe("absolute left-0.5",je?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!Yt&&!Ht&&Fs?"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(ns?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:ns?s.jsx(I,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(I,{name:"arrow-right-s",className:"h-3 w-3"})}):null,rn=Qe?s.jsx(I,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Ks=Ue=>{Ue&&qt(!1),T(Ue?_e:null)},cn=Ue=>{if(!Ue&&M.current){const{id:Xt,title:Is}=M.current;M.current=null,g(Xt),x(Is)}},Mn=Ue=>{qt(Ue)},Ls=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),T(ls?null:_e)},we=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},et=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},ct=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},It=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},Gt=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),T(null),ne(ye,{archivedBucket:c})},mt=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),T(null),ne(ye,{archivedBucket:c,hardDelete:!0,skipConfirm:!0})},ms=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},hs=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},Ss=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),Be?.vscode?.executeCommand("openchamber.openSessionInEditor",ye.id,xt)},ws=Ue=>{if(he.current){he.current=!1;return}if(ae){if(Ue?.preventDefault(),Ue?.stopPropagation(),Ue?.shiftKey){const Is=(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),Ts=Vn.getState().anchorId,Ws=new Map;Ws.set(ye.id,Ge(n)),qe(Ts,ye.id,Is,Re??null,Ws);return}Oe(ye.id,Re??null,Ge(n));return}v(ye.id,Re,a)},Ds=Ue=>{Ue.defaultPrevented||Ue.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||ws(Ue)},Hn=Ue=>{(Ue.button===2||Ue.button===0&&Ue.ctrlKey&&!ae)&&(he.current=!0)},zs=Ue=>{te&&Ue.pointerType==="touch"&&fe(!0)},Sn=Ue=>{te&&Ue.pointerType==="touch"&&fe(!1)},Fn=({Item:Ue,Separator:Xt,Sub:Is,SubTrigger:Ts,SubContent:Ws})=>s.jsxs(s.Fragment,{children:[s.jsxs(Ue,{onClick:()=>{M.current={id:ye.id,title:xt}},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(Ue,{onClick:()=>k(ye.id),className:"[&>svg]:mr-1",children:[Ze?s.jsx(I,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(I,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(Ze?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),Le.share?s.jsxs(s.Fragment,{children:[s.jsx(Ue,{onClick:()=>{Le.share?.url&&D(Le.share.url,ye.id)},className:"[&>svg]:mr-1",children:A===ye.id?s.jsxs(s.Fragment,{children:[s.jsx(I,{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(I,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(Ue,{onClick:()=>N(ye.id),className:"[&>svg]:mr-1",children:[s.jsx(I,{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(I,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(Ue,{onClick:()=>{Dt()},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),Ut?s.jsxs(Ue,{onClick:()=>_t(!0),className:"[&>svg]:mr-1",children:[s.jsx(z2,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,Re&&!c?(()=>{const qs=_(Re),Hs=R(Re,ye.id);return s.jsxs(s.Fragment,{children:[s.jsx(Xt,{}),s.jsxs(Is,{children:[s.jsxs(Ts,{className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs(Ws,{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:()=>{Hs===Os.id?$(Re,ye.id):V(Re,Os.id,ye.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:Os.name}),Hs===Os.id?s.jsx(I,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Os.id)),s.jsx(Xt,{}),s.jsxs(Ue,{onClick:()=>{const Os=z(Re);Os&&V(Re,Os.id,ye.id)},children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),Hs?s.jsxs(Ue,{onClick:()=>{$(Re,ye.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,ee?null:s.jsxs(Ue,{disabled:!Re,onClick:()=>{Re&&F(Re,{mode:"chat",dedupeKey:`session:${ye.id}`,label:xt,sessionTitleFallback:xt})},className:"[&>svg]:mr-1",children:[s.jsx(I,{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")})]}),De?s.jsxs(Ue,{disabled:!Re,onClick:cs,className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(Xt,{}),c?null:s.jsxs(Ue,{className:"[&>svg]:mr-1",onClick:()=>ne(ye,{archivedBucket:c}),children:[s.jsx(I,{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(ye,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(I,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),Zn=s.jsx(sn,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(E||P.current),children:Fn({Item:bs,Separator:Er,Sub:Hg,SubTrigger:Gg,SubContent:Kg})}),dn=s.jsx(fd,{children:s.jsx(md,{className:"app-region-no-drag z-50",children:s.jsx(hd,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(E||P.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Pe(Vd,"min-w-[180px]"),children:Fn({Item:({className:Ue,...Xt})=>s.jsx(rp,{className:Pe(zg,Ue),...Xt}),Separator:({className:Ue,...Xt})=>s.jsx(ip,{className:Pe(Wg,Ue),...Xt}),Sub:op,SubTrigger:({className:Ue,children:Xt,...Is})=>s.jsxs(ap,{className:Pe(Ug,Ue),...Is,children:[Xt,s.jsx(I,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:Ue,children:Xt,...Is})=>s.jsx(fd,{children:s.jsx(md,{className:"app-region-no-drag z-50",children:s.jsx(hd,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Pe(Vd,Ue),...Is,children:Xt})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(AN,{sessionId:ye.id,sessionDirectory:Re??null,sessionTitle:xt,children:s.jsxs(sp,{open:Wt,onOpenChange:Mn,onOpenChangeComplete:cn,children:[s.jsxs(np,{render:s.jsx("div",{"data-session-row":ye.id,"data-session-scope":Re??"","data-session-archived":c?"1":"0",onClick:Ds,className:Pe("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]",Ct&&!re&&"bg-primary/10",re&&"bg-interactive-selection")}),children:[Kt,js,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:je?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:zs,onPointerUp:Sn,onPointerCancel:Sn,onMouseDown:Hn,onClick:Ue=>ws(Ue),onDoubleClick:Ue=>{Ue.stopPropagation(),S(ye.id,xt)},className:Pe("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]",Ne&&"bg-interactive-hover/70",q?ee?pe:ce:pe),children:s.jsxs("div",{className:Pe("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Pe("block min-w-0 flex-1 truncate typography-ui-label font-normal",Ct?"text-primary":"text-foreground"),children:vo(xt,f)}),q?s.jsx("span",{className:"ml-2 flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:bt}):null,q?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:Pe("whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",rs?"opacity-0":Me),children:bt})}),Ke>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(I,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Ke})]}):null]})})}),ee?null:s.jsx(Ft,{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:Pe("flex items-center gap-3 text-left text-muted-foreground",X?.projectLabel?"justify-between":"justify-start"),children:[X?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:X.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:vt})]}),X?.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(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:X.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:zs,onPointerUp:Sn,onPointerCancel:Sn,onMouseDown:Hn,onClick:Ue=>ws(Ue),onDoubleClick:Ue=>{Ue.stopPropagation(),S(ye.id,xt)},className:Pe("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]",Ne&&"bg-interactive-hover/70",q?ee?pe:ce:pe),children:[s.jsxs("div",{className:Pe("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Pe("block min-w-0 flex-1 truncate typography-ui-label font-normal",Ct?"text-primary":"text-foreground"),children:vo(xt,f)}),Ke>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(I,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Ke})]}):null]}),je?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:Pe("flex min-w-0 items-center gap-1.5 overflow-hidden",Yt&&St?"pl-4":""),children:[s.jsx("span",{className:"flex-shrink-0",children:vt}),ge?s.jsx("span",{className:"truncate",children:X?.projectLabel}):null,O?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:X?.branchLabel})]}):null]})})]})}),rn&&!te?s.jsx("div",{className:Pe("absolute top-1/2 -translate-y-1/2 z-10",je?"right-0":"right-[30px]"),children:rn}):null,s.jsxs("div",{className:Pe("absolute right-0 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",rs||q&&!ee?"opacity-100":Pe("opacity-0",Fe)),children:[Ae?s.jsx(W2,{archiveLabel:e("sessions.sidebar.bulkActions.archive"),deleteLabel:e("sessions.sidebar.bulkActions.delete"),buttonSizeClass:je&&!q?"h-4 w-4":"h-6 w-6",iconSizeClass:je&&!q?"h-2.5 w-2.5":"h-3.5 w-3.5",onPointerDown:ct,onMouseDown:It,onArchive:Gt,onDelete:mt}):null,me?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe("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",je&&!q?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:ms,onMouseDown:hs,onClick:Ss,onKeyDown:Ue=>Ue.stopPropagation(),children:s.jsx(I,{name:"external-link",className:Pe(je&&!q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Ft,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(nn,{open:ls,onOpenChange:Ks,onOpenChangeComplete:cn,children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe("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",je&&!q?rs?"h-4 w-4 opacity-100":Pe("h-4 w-4 opacity-0",Fe):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:we,onMouseDown:et,onClick:Ls,onKeyDown:Ue=>Ue.stopPropagation(),children:s.jsx(I,{name:"more-2",className:Pe(je&&!q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),Zn]})]})]}),dn]})}),St&&ns?n.children.map(Ue=>{const Xt=ke?ke(Ue):{subtreeContainsActive:ue,subtreeContainsEditing:Se,menuOpenSessionId:Z,nodeStructureKey:""};return H(Ue,r+1,Re??o,a,c,void 0,oe,Xt)}):null,s.jsx($s,{open:Je,onOpenChange:nt,children:s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Gs,{children:[s.jsx(Us,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(ln,{children:Zt===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:Zt}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:Zt})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:gt,onChange:Ue=>yt(Ue.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(or,{children:[s.jsx($e,{type:"button",onClick:()=>nt(!1),variant:"outline",size:"sm",children:e("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{type:"button",onClick:()=>{nt(!1),Vt(gt)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),Ut?s.jsx($2,{session:Le,open:Bt,onOpenChange:_t}):null]},ye.id)}const xf=t=>as(t.session.directory??null),H2=(t,e)=>(t?.projectLabel??null)===(e?.projectLabel??null)&&(t?.branchLabel??null)===(e?.branchLabel??null),G2=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},ta=t=>t.menuOpenSessionId??G2(t),Vi=(t,e,n)=>e?n.has(t.node.session.id)?!0:Wr(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},Sh=(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(Sh(t.children[a],e.children[a],n,r))return!0;return!1},K2=(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}`)},q2=(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||xf(t.node)!==xf(e.node)||!H2(t.secondaryMeta,e.secondaryMeta)||t.liveSessionById!==e.liveSessionById&&Sh(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&&K2(t,e)||t.currentSessionId!==e.currentSessionId&&(Vi(t,t.currentSessionId,t.subtreeContainsActive)||Vi(e,e.currentSessionId,e.subtreeContainsActive))||t.editingId!==e.editingId&&(Vi(t,t.editingId,t.subtreeContainsEditing)||Vi(e,e.editingId,e.subtreeContainsEditing))||t.editTitle!==e.editTitle&&(Vi(t,t.editingId,t.subtreeContainsEditing)||Vi(e,e.editingId,e.subtreeContainsEditing))||t.copiedSessionId!==e.copiedSessionId&&(Wr(t.node,t.copiedSessionId)||Wr(e.node,e.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=ta(t),r=ta(e);if(Wr(t.node,n)||Wr(e.node,r))return!1}if(t.renamingFolderId!==e.renamingFolderId){const n=ta(t),r=ta(e);if(Wr(t.node,n)||Wr(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},Y2=i.memo(U2,q2);function Q2(t){return t.stopPropagation()}function J2(t){const e=ft.c(71),{t:n}=kt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,u,m,f,p,y,g,b,x,h;if(e[0]!==o||e[1]!==n||e[2]!==r){const F=n("sessions.sidebar.session.untitled");f=$s,x=!!r,e[13]!==o?(h=te=>{te||o(null)},e[13]=o,e[14]=h):h=e[14],m=Vs,g=!1,b="max-w-sm gap-5",u=Gs;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?(y=s.jsx(Us,{children:ne}),e[18]=ne,e[19]=y):y=e[19],d=ln,p=r&&r.descendantCount>0?r.archivedBucket?r.descendantCount===1?n("sessions.sidebar.dialogs.deleteSession.withOneSubtask",{sessionTitle:r.session.title||F,count:r.descendantCount}):n("sessions.sidebar.dialogs.deleteSession.withManySubtasks",{sessionTitle:r.session.title||F,count:r.descendantCount}):r.descendantCount===1?n("sessions.sidebar.dialogs.archiveSession.withOneSubtask",{sessionTitle:r.session.title||F,count:r.descendantCount}):n("sessions.sidebar.dialogs.archiveSession.withManySubtasks",{sessionTitle:r.session.title||F,count:r.descendantCount}):r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.single",{sessionTitle:r?.session.title||F}):n("sessions.sidebar.dialogs.archiveSession.single",{sessionTitle:r?.session.title||F}),e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=u,e[5]=m,e[6]=f,e[7]=p,e[8]=y,e[9]=g,e[10]=b,e[11]=x,e[12]=h}else d=e[3],u=e[4],m=e[5],f=e[6],p=e[7],y=e[8],g=e[9],b=e[10],x=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]!==u||e[24]!==y||e[25]!==C?(w=s.jsxs(u,{children:[y,C]}),e[23]=u,e[24]=y,e[25]=C,e[26]=w):w=e[26];let v;e[27]!==c||e[28]!==a?(v=()=>c(!a),e[27]=c,e[28]=a,e[29]=v):v=e[29];const S=!a;let k;e[30]!==a?(k=a?s.jsx(I,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(I,{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 A;e[34]!==k||e[35]!==j||e[36]!==v||e[37]!==S?(A=s.jsxs("button",{type:"button",onClick:v,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":S,children:[k,j]}),e[34]=k,e[35]=j,e[36]=v,e[37]=S,e[38]=A):A=e[38];let D;e[39]!==o?(D=()=>o(null),e[39]=o,e[40]=D):D=e[40];let N;e[41]!==n?(N=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=N):N=e[42];let B;e[43]!==D||e[44]!==N?(B=s.jsx("button",{type:"button",onClick:D,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:N}),e[43]=D,e[44]=N,e[45]=B):B=e[45];let T;e[46]!==l?(T=()=>{l()},e[46]=l,e[47]=T):T=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 _;e[51]!==T||e[52]!==E?(_=s.jsx("button",{type:"button",onClick:T,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]=T,e[52]=E,e[53]=_):_=e[53];let R;e[54]!==B||e[55]!==_?(R=s.jsxs("div",{className:"flex items-center gap-2",children:[B,_]}),e[54]=B,e[55]=_,e[56]=R):R=e[56];let $;e[57]!==A||e[58]!==R?($=s.jsxs(or,{className:"w-full sm:items-center sm:justify-between",children:[A,R]}),e[57]=A,e[58]=R,e[59]=$):$=e[59];let V;e[60]!==m||e[61]!==g||e[62]!==$||e[63]!==b||e[64]!==w?(V=s.jsxs(m,{showCloseButton:g,className:b,children:[w,$]}),e[60]=m,e[61]=g,e[62]=$,e[63]=b,e[64]=w,e[65]=V):V=e[65];let z;return e[66]!==f||e[67]!==V||e[68]!==x||e[69]!==h?(z=s.jsx(f,{open:x,onOpenChange:h,children:V}),e[66]=f,e[67]=V,e[68]=x,e[69]=h,e[70]=z):z=e[70],z}function X2(t){const e=ft.c(57),{t:n}=kt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t,d=r?.archivedBucket===!0,u=r?.sessionCount??0;let m;e[0]!==d||e[1]!==u||e[2]!==n?(m=n(d?u===1?"sessions.sidebar.dialogs.deleteSession.title":"sessions.sidebar.dialogs.deleteSessions.title":u===1?"sessions.sidebar.dialogs.archiveSession.title":"sessions.sidebar.dialogs.archiveSessions.title"),e[0]=d,e[1]=u,e[2]=n,e[3]=m):m=e[3];const f=m;let p;e[4]!==d||e[5]!==u||e[6]!==n?(p=d?u===1?n("sessions.sidebar.dialogs.deleteSessions.singleDescription",{count:u}):n("sessions.sidebar.dialogs.deleteSessions.pluralDescription",{count:u}):u===1?n("sessions.sidebar.dialogs.archiveSessions.singleDescription",{count:u}):n("sessions.sidebar.dialogs.archiveSessions.pluralDescription",{count:u}),e[4]=d,e[5]=u,e[6]=n,e[7]=p):p=e[7];const y=p,g=!!r;let b;e[8]!==o?(b=z=>{z||o(null)},e[8]=o,e[9]=b):b=e[9];let x;e[10]!==f?(x=s.jsx(Us,{children:f}),e[10]=f,e[11]=x):x=e[11];let h;e[12]!==y?(h=s.jsx(ln,{children:y}),e[12]=y,e[13]=h):h=e[13];let C;e[14]!==x||e[15]!==h?(C=s.jsxs(Gs,{children:[x,h]}),e[14]=x,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 v=!a;let S;e[20]!==a?(S=a?s.jsx(I,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(I,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[20]=a,e[21]=S):S=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]!==v||e[27]!==S?(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":v,children:[S,k]}),e[24]=k,e[25]=w,e[26]=v,e[27]=S,e[28]=j):j=e[28];let A;e[29]!==o?(A=()=>o(null),e[29]=o,e[30]=A):A=e[30];let D;e[31]!==n?(D=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=D):D=e[32];let N;e[33]!==A||e[34]!==D?(N=s.jsx("button",{type:"button",onClick:A,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:D}),e[33]=A,e[34]=D,e[35]=N):N=e[35];let B;e[36]!==l?(B=()=>{l()},e[36]=l,e[37]=B):B=e[37];let T;e[38]!==d||e[39]!==n?(T=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=T):T=e[40];let E;e[41]!==B||e[42]!==T?(E=s.jsx("button",{type:"button",onClick:B,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:T}),e[41]=B,e[42]=T,e[43]=E):E=e[43];let _;e[44]!==N||e[45]!==E?(_=s.jsxs("div",{className:"flex items-center gap-2",children:[N,E]}),e[44]=N,e[45]=E,e[46]=_):_=e[46];let R;e[47]!==j||e[48]!==_?(R=s.jsxs(or,{className:"w-full sm:items-center sm:justify-between",children:[j,_]}),e[47]=j,e[48]=_,e[49]=R):R=e[49];let $;e[50]!==R||e[51]!==C?($=s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[C,R]}),e[50]=R,e[51]=C,e[52]=$):$=e[52];let V;return e[53]!==g||e[54]!==$||e[55]!==b?(V=s.jsx($s,{open:g,onOpenChange:b,children:$}),e[53]=g,e[54]=$,e[55]=b,e[56]=V):V=e[56],V}function Z2(t){const e=ft.c(36),{t:n}=kt(),{value:r,setValue:o,onConfirm:a}=t,c=!!r;let l;e[0]!==o?(l=S=>{S||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 u;e[4]!==d?(u=s.jsx(Us,{children:d}),e[4]=d,e[5]=u):u=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 f;e[9]!==m?(f=s.jsx(ln,{children:m}),e[9]=m,e[10]=f):f=e[10];let p;e[11]!==u||e[12]!==f?(p=s.jsxs(Gs,{children:[u,f]}),e[11]=u,e[12]=f,e[13]=p):p=e[13];let y;e[14]!==o?(y=()=>o(null),e[14]=o,e[15]=y):y=e[15];let g;e[16]!==n?(g=n("sessions.sidebar.dialogs.cancel"),e[16]=n,e[17]=g):g=e[17];let b;e[18]!==y||e[19]!==g?(b=s.jsx("button",{type:"button",onClick:y,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:g}),e[18]=y,e[19]=g,e[20]=b):b=e[20];let x;e[21]!==n?(x=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=x):x=e[22];let h;e[23]!==a||e[24]!==x?(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:x}),e[23]=a,e[24]=x,e[25]=h):h=e[25];let C;e[26]!==h||e[27]!==b?(C=s.jsxs(or,{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(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[p,C]}),e[29]=C,e[30]=p,e[31]=w):w=e[31];let v;return e[32]!==c||e[33]!==l||e[34]!==w?(v=s.jsx($s,{open:c,onOpenChange:l,children:w}),e[32]=c,e[33]=l,e[34]=w,e[35]=v):v=e[35],v}const ek=t=>{const e=ft.c(46),{selectedCount:n,scopeKey:r,scopeFolders:o,archivedBucket:a,onMoveToFolder:c,onCreateFolderAndMove:l,onRemoveFromFolder:d,canRemoveFromFolder:u,onDelete:m,onDone:f}=t,{t:p}=kt(),y=!!r&&!a;let g;e[0]!==a||e[1]!==p?(g=p(a?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[0]=a,e[1]=p,e[2]=g):g=e[2];const b=g;let x;e[3]!==n||e[4]!==p?(x=p("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=p,e[5]=x):x=e[5];let h;e[6]!==x?(h=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:x}),e[6]=x,e[7]=h):h=e[7];let C;e[8]!==y||e[9]!==u||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==p?(C=y?s.jsxs(nn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(tn,{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(I,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:p("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(sn,{align:"end",className:"min-w-[180px]",children:[o.length===0?s.jsx(bs,{disabled:!0,className:"text-muted-foreground",children:p("sessions.sidebar.folders.none")}):o.map($=>s.jsx(bs,{onClick:()=>c($.id),children:s.jsx("span",{className:"flex-1 truncate",children:$.name})},$.id)),s.jsx(Er,{}),s.jsxs(bs,{onClick:l,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.newFolderEllipsis")]}),u?s.jsxs(bs,{onClick:d,className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=y,e[9]=u,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=Pe("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 v;e[17]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx(I,{name:"delete-bin",className:"h-4 w-4"}),e[17]=v):v=e[17];let S;e[18]!==b||e[19]!==m?(S=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,className:w,"aria-label":b,children:v})}),e[18]=b,e[19]=m,e[20]=S):S=e[20];let k;e[21]!==b?(k=s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:b})}),e[21]=b,e[22]=k):k=e[22];let j;e[23]!==S||e[24]!==k?(j=s.jsxs(Et,{children:[S,k]}),e[23]=S,e[24]=k,e[25]=j):j=e[25];let A;e[26]!==p?(A=p("sessions.sidebar.header.actions.exitSelection"),e[26]=p,e[27]=A):A=e[27];let D;e[28]===Symbol.for("react.memo_cache_sentinel")?(D=s.jsx(I,{name:"close",className:"h-4 w-4"}),e[28]=D):D=e[28];let N;e[29]!==f||e[30]!==A?(N=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:f,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":A,children:D})}),e[29]=f,e[30]=A,e[31]=N):N=e[31];let B;e[32]!==p?(B=p("sessions.sidebar.header.actions.exitSelection"),e[32]=p,e[33]=B):B=e[33];let T;e[34]!==B?(T=s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:B})}),e[34]=B,e[35]=T):T=e[35];let E;e[36]!==N||e[37]!==T?(E=s.jsxs(Et,{children:[N,T]}),e[36]=N,e[37]=T,e[38]=E):E=e[38];let _;e[39]!==E||e[40]!==C||e[41]!==j?(_=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]=_):_=e[42];let R;return e[43]!==_||e[44]!==h?(R=s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-2.5 py-1.5",children:[h,_]}),e[43]=_,e[44]=h,e[45]=R):R=e[45],R},tk=t=>{const{t:e}=kt(),{isInlineEditing:n,showDeletionDialog:r,foldersMap:o,addSessionsToFolder:a,removeSessionsFromFolders:c,createFolderAndStartRename:l,archiveSessions:d,deleteSessions:u,setBulkDeleteConfirm:m}=t,f=Vn(T=>T.enabled),p=Vn(T=>T.selectedIds.size),y=p>0,g=Vn(T=>T.selectedIds),b=Vn(T=>T.scopeKey),x=i.useCallback(()=>{Vn.getState().toggleMode()},[]),h=i.useCallback(()=>{Vn.getState().disable()},[]),C=i.useMemo(()=>{if(!y||typeof document>"u")return!1;let T=!1,E=!1;for(const _ of g){const R=document.querySelectorAll(`[data-session-row="${CSS.escape(_)}"]`);for(const $ of R)$.getAttribute("data-session-archived")==="1"?E=!0:T=!0}return E&&!T},[y,g]),w=i.useMemo(()=>{if(b)return b;if(!y||typeof document>"u")return null;for(const T of g){const _=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(_&&_.length>0)return _}return null},[y,g,b]),v=i.useMemo(()=>w?o[w]??[]:[],[o,w]),S=i.useMemo(()=>{if(!w||!y)return!1;const T=o[w]??[];for(const E of T)for(const _ of E.sessionIds)if(g.has(_))return!0;return!1},[o,w,y,g]),k=i.useCallback(T=>{!w||!y||a(w,T,Array.from(g))},[a,g,w,y]),j=i.useCallback(()=>{if(!w||!y)return;const T=l(w);T&&a(w,T.id,Array.from(g))},[a,l,g,w,y]),A=i.useCallback(()=>{!w||!y||c(w,Array.from(g))},[c,g,w,y]),D=i.useCallback(async()=>{const T=Array.from(g);if(T.length!==0){if(C){const{deletedIds:E,failedIds:_}=await u(T);E.length>0&&le.success(E.length===1?e("sessions.sidebar.bulkActions.deletedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.deletedPlural",{count:E.length})),_.length>0&&le.error(_.length===1?e("sessions.sidebar.bulkActions.failedDeleteSingle",{count:_.length}):e("sessions.sidebar.bulkActions.failedDeletePlural",{count:_.length}))}else{const{archivedIds:E,failedIds:_}=await d(T);E.length>0&&le.success(E.length===1?e("sessions.sidebar.bulkActions.archivedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.archivedPlural",{count:E.length})),_.length>0&&le.error(_.length===1?e("sessions.sidebar.bulkActions.failedArchiveSingle",{count:_.length}):e("sessions.sidebar.bulkActions.failedArchivePlural",{count:_.length}))}Vn.getState().clear()}},[d,C,u,g,e]),N=i.useCallback(()=>{if(!y)return;const T=g.size;if(!r){D();return}m({sessionCount:T,archivedBucket:C})},[C,D,g,r,m,y]),B=i.useCallback(async()=>{m(null),await D()},[D]);return i.useEffect(()=>{if(!f)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=_=>{if(n)return;const R=_.target;if(R&&(R.tagName==="INPUT"||R.tagName==="TEXTAREA"||R.isContentEditable))return;const $=T?_.metaKey:_.ctrlKey;if(_.key==="Escape"){_.preventDefault(),Vn.getState().disable();return}if($&&_.key==="Backspace"){_.preventDefault(),N();return}if($&&(_.key==="a"||_.key==="A")){const V=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(V.length===0)return;_.preventDefault();const F=Vn.getState().scopeKey??V[0]?.getAttribute("data-session-scope")??null,ne=q=>F?q.getAttribute("data-session-scope")===F:!0,te=V.filter(ne).map(q=>q.getAttribute("data-session-row")).filter(q=>typeof q=="string"&&q.length>0);if(te.length===0)return;Vn.getState().replaceAll(te,F||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[N,n,f]),{selectionModeEnabled:f,hasSelection:y,selectedIdsSize:p,bulkScopeIsArchived:C,derivedSelectionScope:w,bulkScopeFolders:v,bulkCanRemoveFromFolder:S,handleToggleSelectionMode:x,handleExitSelectionMode:h,handleBulkMoveToFolder:k,handleBulkCreateFolderAndMove:j,handleBulkRemoveFromFolder:A,handleBulkDelete:N,confirmBulkDelete:B}},sk=2880*60*1e3,nk=t=>!!t.parentID,rk=t=>!!t.time?.archived,cc=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},ik=t=>[...t].sort((e,n)=>cc(n)-cc(e)),ok=(t,e=Date.now())=>{const n=e-sk,r=t.filter(o=>rk(o)||nk(o)?!1:cc(o)>=n);return ik(r)},sa="oc.sessions.projectCollapse",bf="oc.sessions.groupOrder",yf="oc.sessions.groupCollapse",wf="oc.sessions.activeSessionByProject",Fl="oc.sessions.expandedParents.v2",ak="oc.sessions.expandedParents",lk="oc.sessions.pinned",ck=(t,e,n)=>{const r=new Set;for(const o of t){const a=as(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=as(a.path)?.toLowerCase();c&&r.add(c)}return r},dk=(t,e,n)=>{if(t.time?.archived)return!0;const r=as(Rr(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},uk=5*6e4,vf=new Set,Dr=t=>{const e=i.useRef(t);return e.current=t,i.useCallback((...n)=>e.current(...n),[])},jf=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=kt(),[c,l]=i.useState(!1),[d,u]=i.useState(""),m=i.useRef(null),f=i.useRef(null),p=i.useRef(new Set),[y,g]=i.useState(null),[b,x]=i.useState(""),[h,C]=i.useState(null),[w,v]=i.useState(new Set),S=i.useMemo(()=>zi(),[]),[k,j]=i.useState(new Set),[A,D]=i.useState(new Map),[N,B]=i.useState(new Map),T=Ee(ie=>ie.isNewWorktreeDialogOpen),E=Ee(ie=>ie.setNewWorktreeDialogOpen),[_,R]=i.useState(!1),[$,V]=i.useState(null),[z,F]=i.useState(null),[ne,te]=i.useState(""),[q,H]=i.useState(null),[X,oe]=i.useState(null),[ue,Se]=i.useState(null),Z=ul(ie=>ie.ids),ke=ul(ie=>ie.setIds),Y=ul(ie=>ie.toggle),[ge,O]=i.useState(()=>{try{const ie=zi().getItem(yf);if(!ie)return new Set;const at=JSON.parse(ie);return new Set(Array.isArray(at)?at.filter(rt=>typeof rt=="string"):[])}catch{return new Set}}),[se,ee]=i.useState(()=>{try{const ie=zi().getItem(bf);if(!ie)return new Map;const at=JSON.parse(ie),rt=new Map;return Object.entries(at).forEach(([ht,$t])=>{Array.isArray($t)&&rt.set(ht,$t.filter(As=>typeof As=="string"))}),rt}catch{return new Map}}),[je,De]=i.useState(()=>{try{const ie=zi().getItem(wf);if(!ie)return new Map;const at=JSON.parse(ie),rt=new Map;return Object.entries(at).forEach(([ht,$t])=>{typeof $t=="string"&&$t.length>0&&rt.set(ht,$t)}),rt}catch{return new Map}}),[Be,Fe]=i.useState(new Map),Me=i.useRef(new Map),me=i.useRef(0),Ae=Xs(ie=>ie.homeDirectory),pe=Xs(ie=>ie.currentDirectory),ce=Xs(ie=>ie.setDirectory),he=Ns(ie=>ie.projects),Ne=Ns(ie=>ie.activeProjectId),fe=Ns(ie=>ie.removeProject),P=Ns(ie=>ie.setActiveProjectIdOnly),M=Ns(ie=>ie.updateProjectMeta),de=Ns(ie=>ie.reorderProjects),xe=Ee(ie=>ie.setActiveMainTab),W=Ee(ie=>ie.openContextPanelTab),be=Ee(ie=>ie.setSettingsDialogOpen),ve=Ee(ie=>ie.toggleHelpDialog),G=Ee(ie=>ie.setAboutDialogOpen),ye=Ee(ie=>ie.setSessionSwitcherOpen),Le=Ee(ie=>ie.setScheduledTasksDialogOpen),Re=Ee(ie=>ie.openMultiRunLauncher),J=Ee(ie=>ie.notifyOnSubtasks),L=Ee(ie=>ie.showDeletionDialog),ae=Ee(ie=>ie.setShowDeletionDialog),re=qa(d,120),Oe=i.useMemo(()=>re.trim().toLowerCase(),[re]),qe=Oe.length>0,Ge=Bn(ie=>ie.collapsedFolderIds),Je=Bn(ie=>ie.foldersMap),nt=Bn(ie=>ie.getFoldersForScope),gt=Bn(ie=>ie.createFolder),yt=Bn(ie=>ie.renameFolder),_e=Bn(ie=>ie.deleteFolder),Qe=Bn(ie=>ie.addSessionToFolder),st=Bn(ie=>ie.addSessionsToFolder),wt=Bn(ie=>ie.removeSessionFromFolder),Ct=Bn(ie=>ie.removeSessionsFromFolders),xt=Bn(ie=>ie.toggleFolderCollapse),St=Bn(ie=>ie.cleanupSessions),Ze=Bn(ie=>ie.getSessionFolderId);US({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:f,sessionSearchContainerRef:m});const Ot=am(),ns=Rc(),zt=yc(),Ve=i.useMemo(()=>Kr(),[]),At=jr(ie=>ie.hasLoaded),ot=jr(ie=>ie.activeSessions),vt=jr(ie=>ie.archivedSessions),bt=ut(ie=>ie.currentSessionId),ls=ut(ie=>!!ie.newSessionDraft?.open),Wt=ut(ie=>ie.setCurrentSession),qt=ut(ie=>ie.updateSessionTitle),rs=ut(ie=>ie.shareSession),Ut=ut(ie=>ie.unshareSession),Bt=ut(ie=>ie.worktreeMetadata),_t=ut(ie=>ie.availableWorktreesByProject),Yt=ut(ie=>ie.openNewSessionDraft),Ht=i.useCallback(ie=>{Yt(ie),Ve&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[Ve,Yt]),Zt=wo(zl(ie=>({checkForUpdates:ie.checkForUpdates,available:ie.available,runtimeType:ie.runtimeType,info:ie.info,downloading:ie.downloading,downloaded:ie.downloaded,progress:ie.progress,error:ie.error,downloadUpdate:ie.downloadUpdate,restartToUpdate:ie.restartToUpdate}))),ys=i.useMemo(()=>ck(he,_t,{includeWorktrees:!Ve}),[_t,Ve,he]),Tt=i.useMemo(()=>{const ie=new Map(zt.map(ht=>[ht.id,ht])),at=ot.map(ht=>{const $t=ie.get(ht.id);return $t?qg($t,ht):ht}),rt=new Set(at.map(ht=>ht.id));return zt.forEach(ht=>{rt.has(ht.id)||at.push(ht)}),at.filter(ht=>dk(ht,ys,{allowUnknownDirectory:!Ve,allowEmptyDirectorySet:!Ve}))},[ot,Ve,ys,zt]),Vt=i.useMemo(()=>zt.map(ie=>{const at=as(ie.directory??null)??"";return`${ie.id}:${ie.title??""}:${ie.time?.archived?1:0}:${at}`}).join("|"),[zt]),Dt=i.useRef(zt);i.useEffect(()=>{Dt.current=zt},[Vt,zt]);const cs=i.useMemo(()=>new Map(zt.map(ie=>[ie.id,ie])),[zt]),us=i.useMemo(()=>he.map(ie=>`${ie.id}:${as(ie.path)??""}`).join("|"),[he]),He=i.useRef(!1);i.useEffect(()=>{He.current||(He.current=!0,Na(Dt.current))},[]);const Ke=i.useRef("");i.useEffect(()=>{let ie=!1;const at=async()=>{const rt=Ns.getState().projects;if(rt.length===0)return;const ht=new Map,$t=[],As=3;let Zs=0;const hn=Array.from({length:As},async()=>{for(;;){const On=Zs;if(Zs+=1,On>=rt.length)return;const kn=rt[On],In=as(kn.path);if(In)try{if(!(vn.getState().directories.get(In)?.isGitRepo??await mm(In)))continue;const gi=await Qg({id:kn.id,path:In});if(ie||gi.length===0)continue;ht.set(In,gi),$t.push(...gi)}catch{}}});await Promise.all(hn),!ie&&ut.setState({availableWorktrees:$t,availableWorktreesByProject:ht})};if(Ke.current!==us)return Ke.current=us,at(),()=>{ie=!0}},[us]),i.useEffect(()=>{let ie=null;const at=hh(rt=>{rt.type==="scheduled-task-ran"&&(ie&&clearTimeout(ie),ie=setTimeout(()=>{Na(Dt.current)},500))});return()=>{ie&&clearTimeout(ie),at()}},[]);const jt=i.useMemo(()=>ur(),[]),{isTablet:Lt}=Mr(),Nt=t||Lt,{buildGroupSearchText:xs,filterSessionNodesForSearch:ps,buildGroupedSessions:os}=WS({homeDirectory:Ae,worktreeMetadata:Bt,pinnedSessionIds:Z,gitBranches:Ot,isVSCode:Ve}),{scheduleCollapsedProjectsPersist:Kt}=JS({isVSCode:Ve,hasLoadedGlobalSessions:At,safeStorage:S,keys:{sessionExpanded:Fl,sessionExpandedLegacy:ak,projectCollapse:sa,sessionPinned:lk,groupOrder:bf,projectActiveSession:wf,groupCollapse:yf},sessions:Tt,setPinnedSessionIds:ke,groupOrderByProject:se,activeSessionByProject:je,collapsedGroups:ge,setExpandedParents:v,setCollapsedProjects:j}),Fs=i.useMemo(()=>[...Tt].sort((ie,at)=>Gi(ie,at,Z)),[Tt,Z]),js=i.useMemo(()=>Fs.map(ie=>`${ie.id}:${ie.time?.updated??0}`).join("|"),[Fs]),rn=i.useRef(null),Ks=i.useMemo(()=>{const ie=rn.current;if(ie&&ie.signature===js)return ie.map;const at=new Map(Fs.map((rt,ht)=>[rt.id,ht]));return rn.current={signature:js,map:at},at},[js,Fs]),cn=i.useMemo(()=>{const ie=new Map;return Fs.forEach(at=>{const rt=at.parentID;if(!rt)return;const ht=ie.get(rt)??[];ht.push(at),ie.set(rt,ht)}),ie.forEach(at=>at.sort((rt,ht)=>Gi(rt,ht,Z))),ie},[Fs,Z]),Mn=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")})]}),Ls=i.useMemo(()=>he.find(ie=>ie.id===h)??null,[he,h]),we=i.useCallback(ie=>{h&&(M(h,ie),C(null))},[h,M]),et=i.useCallback(()=>{E(!0)},[E]),ct=i.useCallback(()=>{const ie=wo.getState();if(ie.available&&ie.info){R(!0);return}Zt.checkForUpdates().then(()=>{const{available:at,error:rt}=wo.getState();if(rt){le.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:rt});return}if(!at){le.success(a("sessions.sidebar.updateCheck.latestVersion"));return}R(!0)})},[a,Zt]),It=i.useCallback(()=>{t&&ye(!1),be(!0)},[t,ye,be]),Gt=Zt.available&&(Zt.runtimeType==="desktop"||Zt.runtimeType==="web"),mt=ut(ie=>ie.deleteSession),ms=ut(ie=>ie.deleteSessions),hs=ut(ie=>ie.archiveSession),Ss=ut(ie=>ie.archiveSessions),{copiedSessionId:ws,handleSessionSelect:Ds,handleSessionDoubleClick:Hn,handleSaveEdit:zs,handleCancelEdit:Sn,handleShareSession:Fn,handleCopyShareUrl:Zn,handleUnshareSession:dn,handleDeleteSession:Ue,confirmDeleteSession:Xt}=HS({activeProjectId:Ne,currentDirectory:pe,currentSessionId:bt,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:u,setIsSessionSearchOpen:l,setActiveProjectIdOnly:P,setDirectory:ce,setActiveMainTab:xe,setSessionSwitcherOpen:ye,setCurrentSession:Wt,updateSessionTitle:qt,shareSession:rs,unshareSession:Ut,deleteSession:mt,deleteSessions:ms,archiveSession:hs,archiveSessions:Ss,childrenMap:cn,showDeletionDialog:L,setDeleteSessionConfirm:H,deleteSessionConfirm:q,setEditingId:g,setEditTitle:x,editingId:y,editTitle:b}),Is=i.useCallback(()=>{if(!X)return;const{scopeKey:ie,folderId:at}=X;oe(null),_e(ie,at)},[X,_e]),Ts=i.useCallback(()=>{Tr.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!bt)return;const at=Tt.find(ht=>ht.id===bt)?.parentID;if(!at)return;const rt=[`project:active:${at}`,`project:archived:${at}`,`recent:active:${at}`,`recent:archived:${at}`];v(ht=>{if(rt.every(As=>ht.has(As)))return ht;const $t=new Set(ht);rt.forEach(As=>$t.add(As));try{S.setItem(Fl,JSON.stringify(Array.from($t)))}catch{}return $t})},[bt,Tt,S]);const Ws=i.useCallback(ie=>{v(at=>{const rt=new Set(at);rt.has(ie)?rt.delete(ie):rt.add(ie);try{S.setItem(Fl,JSON.stringify(Array.from(rt)))}catch{}return rt})},[S]),qs=i.useCallback((ie,at)=>{if(!ie)return null;at&&Ge.has(at)&&xt(at);const rt=gt(ie,a("sessions.sidebar.folder.newFolderName"),at);return F(rt.id),te(rt.name),rt},[Ge,xt,gt,a]),Hs=Dr(Ds),Os=Dr(Hn),Gn=Dr(zs),mr=Dr(Sn),Kn=Dr(Fn),gs=Dr(Zn),Rs=Dr(dn),Sr=Dr(Ue),Nn=Dr(qs),un=i.useCallback((ie,at)=>{B(rt=>{const ht=new Map(rt);return ht.set(ie,at+7),ht})},[]),er=i.useCallback(ie=>{B(at=>{if(!at.has(ie))return at;const rt=new Map(at);return rt.delete(ie),rt})},[]),Fr=i.useCallback(ie=>{B(at=>{let rt=!1;const ht=new Map(at),$t=`${ie}:`;for(const As of ht.keys())As.startsWith($t)&&(ht.delete(As),rt=!0);return rt?ht:at})},[]),Yr=i.useCallback(()=>{me.current=Date.now()+150,B(new Map),j(()=>{const ie=new Set(he.map(at=>at.id));try{S.setItem(sa,JSON.stringify(Array.from(ie)))}catch{}return Ve||Kt(ie),ie})},[he,Ve,S,Kt]),ui=i.useCallback(()=>{me.current=Date.now()+150,B(new Map),j(()=>{const ie=new Set;try{S.setItem(sa,JSON.stringify([]))}catch{}return Ve||Kt(ie),ie})},[Ve,S,Kt]),hr=i.useCallback(ie=>{me.current=Date.now()+150,Fr(ie),j(at=>{const rt=new Set(at);rt.has(ie)?rt.delete(ie):rt.add(ie);try{S.setItem(sa,JSON.stringify(Array.from(rt)))}catch{}return Ve||Kt(rt),rt})},[Ve,Fr,S,Kt]),ds=i.useMemo(()=>he.map(ie=>({...ie,normalizedPath:as(ie.path)})).filter(ie=>!!ie.normalizedPath),[he]),fn=i.useMemo(()=>ds.map(ie=>ie.normalizedPath),[ds]),An=i.useMemo(()=>{const ie=new Set;return ds.forEach(at=>{if(at.normalizedPath&&ie.add(at.normalizedPath),Ve)return;(_t.get(at.normalizedPath)??[]).forEach(ht=>{const $t=as(ht.path);$t&&ie.add($t)})}),[...ie].sort()},[_t,Ve,ds]),Q=i.useRef(null);i.useEffect(()=>{const ie=new Set(An),at=Q.current;if(Q.current=ie,!at){Ve&&An.length>0&&$d(An,Dt.current);return}const rt=An.filter(ht=>!at.has(ht));rt.length!==0&&$d(rt,Dt.current)},[Ve,An]);const{github:tt}=Xn(),pt=Ii(ie=>ie.status),Pt=Ii(ie=>ie.hasChecked),es=Yg(fn),is=ir(ie=>ie.ensureEntry),fs=ir(ie=>ie.setParams),Es=ir(ie=>ie.refreshTargets);XS({normalizedProjects:ds,gitRepoStatus:es,setProjectRepoStatus:D,setProjectRootBranches:Fe});const Ys=ut(ie=>ie.isLoading);rN({isSessionsLoading:Ys,hasLoadedGlobalSessions:At,sessions:Tt,archivedSessions:vt,normalizedProjects:ds,isVSCode:Ve,availableWorktreesByProject:_t,cleanupSessions:St});const{getSessionsForProject:tr,getArchivedSessionsForProject:qn}=ZS({isVSCode:Ve,sessions:Tt,archivedSessions:vt,availableWorktreesByProject:_t,normalizedProjects:ds});FS({normalizedProjects:ds,sessions:Tt,archivedSessions:vt,availableWorktreesByProject:_t,isVSCode:Ve,isSessionsLoading:Ys,foldersMap:Je,createFolder:gt,addSessionToFolder:Qe,cleanupSessions:St});const Lr=i.useRef(!1);Ne&&A.has(Ne)&&(Lr.current=!!A.get(Ne));const{projectSections:Bs,groupSearchDataByGroup:Or,sectionsForRender:xn,searchMatchCount:sr}=BS({normalizedProjects:ds,getSessionsForProject:tr,getArchivedSessionsForProject:qn,availableWorktreesByProject:_t,projectRepoStatus:A,projectRootBranches:Be,lastRepoStatus:Lr.current,buildGroupedSessions:os,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:Oe,filterSessionNodesForSearch:ps,buildGroupSearchText:xs,foldersMap:Je}),bn=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")})]});VS({projectSections:Bs,activeProjectId:Ne,activeSessionByProject:je,setActiveSessionByProject:De,currentSessionId:bt,handleSessionSelect:Ds,newSessionDraftOpen:ls,mobileVariant:t,openNewSessionDraft:Yt,setActiveMainTab:xe,setSessionSwitcherOpen:ye});const{getOrderedGroups:Ln}=$S(se),yn=i.useRef(!1);i.useEffect(()=>{if(yn.current||Bs.length===0)return;const ie=Bs.flatMap(at=>at.groups.filter(rt=>rt.isArchivedBucket).map(rt=>`${at.project.id}:${rt.id}`));ie.length>0&&O(at=>new Set([...at,...ie])),yn.current=!0},[Bs]);const ar=i.useMemo(()=>{const ie=new Map,at=new Map;return Bs.forEach(rt=>{const ht=Dm(rt.project.label?.trim()||Ti(rt.project.normalizedPath,Ae)||rt.project.normalizedPath);rt.groups.forEach($t=>{const As=$t.branch&&$t.branch!=="HEAD"&&$t.branch!==ht?$t.branch:null,Zs={projectLabel:ht,branchLabel:As},hn=On=>{On.forEach(kn=>{const In=rt.project.normalizedPath.length,hi=at.get(kn.session.id)??-1;In<hi||(ie.set(kn.session.id,{node:kn,projectId:rt.project.id,groupDirectory:$t.directory,secondaryMeta:Zs}),at.set(kn.session.id,In),kn.children.length>0&&hn(kn.children))})};hn($t.sessions)})}),ie},[Bs,Ae]),Dn=Ir(ie=>ie.showRecentSection),Nr=Ir(ie=>ie.showArchivedSessions),Br=i.useMemo(()=>!Dn||Ve?[]:ok(Tt).sort((ie,at)=>Gi(ie,at,Z)),[Ve,Z,Tt,Dn]),kr=i.useMemo(()=>{if(Ve||!Dn)return[];const ie=Br,at=ht=>{const $t=ar.get(ht.id),As=as(ht.directory??null),Zs=$t?.node??{session:ht,children:[],worktree:null},On=(qe?ps([Zs],Oe):[Zs])[0];if(!On)return null;const kn=$t?.secondaryMeta?{projectLabel:$t.secondaryMeta.projectLabel,branchLabel:Ve?null:$t.secondaryMeta.branchLabel}:null;return{node:On,projectId:$t?.projectId??null,groupDirectory:$t?.groupDirectory??As,secondaryMeta:kn}},rt=ie.map(at).filter(ht=>ht!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:rt}]},[Br,ps,qe,Ve,Oe,ar,Dn,a]),Ri=i.useMemo(()=>kr.some(ie=>ie.items.length>0),[kr]),fi=i.useMemo(()=>new Set(Br.map(ie=>ie.id)),[Br]),Ei=i.useMemo(()=>[...fi],[fi]);Xj({currentSessionId:bt,sortedSessions:Fs,recentSessionIds:Ei,ensureSessionRenderable:ns.ensureSessionRenderable});const on=i.useMemo(()=>Nr?xn:xn.map(ie=>({...ie,groups:ie.groups.filter(at=>!at.isArchivedBucket)})),[xn,Nr]),pr=i.useMemo(()=>{const ie=new Set;return on.forEach(at=>{at.groups.forEach(rt=>{const ht=as(rt.directory??null),$t=rt.branch?.trim()||Ot.get(ht||"")?.trim();!ht||!$t||ie.add(No(ht,$t))})}),[...ie]},[Ot,on]),Qs=Mw(pr);i.useEffect(()=>{if(!Pt||!pt?.connected||!tt)return;const ie=[],at=Date.now();if(on.forEach(ht=>{k.has(ht.project.id)||ht.groups.forEach($t=>{const As=as($t.directory??null),Zs=$t.branch?.trim()||Ot.get(As||"")?.trim();if(!As||!Zs)return;const hn=No(As,Zs),On=ir.getState().entries[hn],kn=!!On?.status?.pr,In=`${As}::${Zs}`,hi=Math.max(On?.lastRefreshAt??0,On?.lastDiscoveryPollAt??0),pi=!!(On?.isInitialStatusResolved&&!kn&&(!p.current.has(In)||at-hi>=uk));(!On||!On.isInitialStatusResolved||pi)&&(pi&&p.current.add(In),ie.push({directory:As,branch:Zs}))})}),ie.length===0)return;const rt=new Map;ie.forEach(ht=>{const $t=No(ht.directory,ht.branch,ht.remoteName??null);rt.has($t)||rt.set($t,ht)}),rt.forEach((ht,$t)=>{is($t),fs($t,{directory:ht.directory,branch:ht.branch,remoteName:ht.remoteName??null,canShow:!0,github:tt,githubAuthChecked:Pt,githubConnected:pt.connected})}),Es([...rt.values()],{silent:!0,markInitialResolved:!0})},[k,is,tt,Pt,pt?.connected,Ot,Es,on,fs]);const co=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",_r="h-4.5 w-4.5",lr=lN({isDesktopShellRuntime:jt,projectSections:Bs,projectHeaderSentinelRefs:Me}),Cr=Dr((ie,at=0,rt,ht,$t=!1,As,Zs="project",hn)=>s.jsx(Y2,{node:ie,depth:at,groupDirectory:rt,projectId:ht,archivedBucket:$t,currentSessionId:bt,pinnedSessionIds:Z,expandedParents:w,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:Oe,notifyOnSubtasks:J,editingId:y,setEditingId:g,editTitle:b,setEditTitle:x,handleSaveEdit:Gn,handleCancelEdit:mr,toggleParent:Ws,handleSessionSelect:Hs,handleSessionDoubleClick:Os,togglePinnedSession:Y,handleShareSession:Kn,copiedSessionId:ws,handleCopyShareUrl:gs,handleUnshareSession:Rs,openSidebarMenuKey:$,setOpenSidebarMenuKey:V,renamingFolderId:z,getFoldersForScope:nt,getSessionFolderId:Ze,removeSessionFromFolder:wt,addSessionToFolder:Qe,createFolderAndStartRename:Nn,openContextPanelTab:W,handleDeleteSession:Sr,mobileVariant:t,alwaysShowActions:Nt,renderSessionNode:Cr,secondaryMeta:As,renderContext:Zs,subtreeContainsActive:hn?.subtreeContainsActive??vf,subtreeContainsEditing:hn?.subtreeContainsEditing??vf,menuOpenSessionId:hn?.menuOpenSessionId??null,nodeStructureKey:hn?.nodeStructureKey??"",childRenderExtrasFor:hn?.childRenderExtrasFor,liveSessionById:cs})),mn=i.useCallback(ie=>{er(ie),O(at=>{const rt=new Set(at);return rt.has(ie)?rt.delete(ie):rt.add(ie),rt})},[er]),cr=i.useMemo(()=>{const ie=new Map;for(const[at,rt]of Qs)ie.set(at,{visualState:rt.visualState,number:rt.number,url:rt.url,state:rt.prState,draft:rt.draft,title:rt.title,base:rt.base,head:rt.head,checks:rt.checks,canMerge:rt.canMerge,mergeableState:rt.mergeableState,repo:rt.repo});return ie},[Qs]),Mi=i.useCallback((ie,at,rt,ht,$t,As,Zs)=>s.jsx(_N,{group:ie,groupKey:at,projectId:rt,hideGroupLabel:ht,compactBodyPadding:As,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:Oe,groupSearchDataByGroup:Or,visibleSessionCount:N.get(at),collapsedGroups:ge,hideDirectoryControls:r,collapsedFolderIds:Ge,toggleFolderCollapse:xt,renameFolder:yt,deleteFolder:_e,showDeletionDialog:L,setDeleteFolderConfirm:oe,renderSessionNode:Cr,projectRepoStatus:A,lastRepoStatus:Lr.current,showMoreGroupSessions:un,resetGroupSessionLimit:er,mobileVariant:t,alwaysShowActions:Nt,activeProjectId:Ne,setActiveProjectIdOnly:P,setActiveMainTab:xe,setSessionSwitcherOpen:ye,openNewSessionDraft:Ht,addSessionToFolder:Qe,createFolderAndStartRename:Nn,renamingFolderId:z,renameFolderDraft:ne,setRenameFolderDraft:te,setRenamingFolderId:F,pinnedSessionIds:Z,expandedParents:w,sessionOrderIndex:Ks,currentSessionId:bt,editingId:y,editTitle:b,openSidebarMenuKey:$,liveSessionById:cs,prVisualStateByDirectoryBranch:cr,onToggleCollapsedGroup:mn,dragHandleProps:$t,scrollContainerRef:Zs}),[qe,Oe,Or,N,ge,r,Ge,xt,yt,_e,L,Cr,A,un,er,t,Nt,Ne,P,xe,ye,Ht,Qe,Nn,z,ne,Z,w,Ks,bt,y,b,$,cs,cr,mn]),Fi=!Ve&&Dn&&!qe?s.jsx(qN,{sections:kr,renderSessionNode:Cr,currentSessionId:bt,editingId:y,openSidebarMenuKey:$,variant:"section"}):null,Vr=!!(z||y||h),{selectionModeEnabled:mi,hasSelection:an,selectedIdsSize:Li,bulkScopeIsArchived:uo,derivedSelectionScope:fo,bulkScopeFolders:K,bulkCanRemoveFromFolder:Ce,handleToggleSelectionMode:Te,handleExitSelectionMode:ze,handleBulkMoveToFolder:dt,handleBulkCreateFolderAndMove:Rt,handleBulkRemoveFromFolder:Qt,handleBulkDelete:Jt,confirmBulkDelete:vs}=tk({isInlineEditing:Vr,showDeletionDialog:L,foldersMap:Je,addSessionsToFolder:st,removeSessionsFromFolders:Ct,createFolderAndStartRename:qs,archiveSessions:Ss,deleteSessions:ms,setBulkDeleteConfirm:Se}),gr=i.useCallback(()=>{xe("chat"),t&&ye(!1),Re()},[t,Re,xe,ye]),Ar=i.useCallback(()=>{xe("chat"),t&&ye(!1),Yt()},[t,Yt,xe,ye]);return s.jsxs("div",{ref:m,className:Pe("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(VN,{hideDirectoryControls:r,showRecentControls:!Ve,handleOpenDirectoryDialog:Ts,openNewSessionDraft:Ar,canOpenMultiRun:he.length>0,openMultiRunLauncher:gr,headerActionIconClass:_r,headerActionButtonClass:co,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:f,sessionSearchQuery:d,setSessionSearchQuery:u,hasSessionSearchQuery:qe,searchMatchCount:sr,collapseAllProjects:Yr,expandAllProjects:ui,openScheduledTasksDialog:()=>Le(!0),selectionModeEnabled:mi,onToggleSelectionMode:Te}),s.jsx(s2,{topContent:Fi,hasSharedSessions:Ri,sectionsForRender:on,projectSections:Bs,activeProjectId:Ne,showOnlyMainWorkspace:o,hasSessionSearchQuery:qe,emptyState:Mn,searchEmptyState:bn,renderGroupSessions:Mi,homeDirectory:Ae,collapsedProjects:k,hideDirectoryControls:r,projectRepoStatus:A,isDesktopShellRuntime:jt,stuckProjectHeaders:lr,mobileVariant:t,alwaysShowActions:Nt,toggleProject:hr,setActiveProjectIdOnly:P,setActiveMainTab:xe,setSessionSwitcherOpen:ye,openNewSessionDraft:Ht,openNewWorktreeDialog:et,openProjectEditDialog:C,removeProject:fe,projectHeaderSentinelRefs:Me,reorderProjects:de,getOrderedGroups:Ln,setGroupOrderByProject:ee,openSidebarMenuKey:$,setOpenSidebarMenuKey:V,isInlineEditing:Vr}),mi&&an?s.jsx(ek,{selectedCount:Li,scopeKey:fo,scopeFolders:K,archivedBucket:uo,onMoveToFolder:dt,onCreateFolderAndMove:Rt,onRemoveFromFolder:Qt,canRemoveFromFolder:Ce,onDelete:Jt,onDone:ze}):null,s.jsx(YN,{onOpenSettings:It,onOpenShortcuts:ve,onOpenAbout:()=>G(!0),onOpenUpdate:ct,showRuntimeButtons:!Ve,showUpdateButton:Gt}),s.jsx(vm,{open:_,onOpenChange:R,info:Zt.info,downloading:Zt.downloading,downloaded:Zt.downloaded,progress:Zt.progress,error:Zt.error,onDownload:Zt.downloadUpdate,onRestart:Zt.restartToUpdate,runtimeType:Zt.runtimeType}),Ls?s.jsx(dN,{open:!!Ls,onOpenChange:ie=>{ie||C(null)},projectId:Ls.id,projectName:Ls.label||Ti(Ls.path,Ae),projectPath:Ls.path,initialIcon:Ls.icon,initialColor:Ls.color,initialIconBackground:Ls.iconBackground,onSave:we}):null,s.jsx(Yx,{open:T,onOpenChange:E,onWorktreeCreated:(ie,at)=>{if(xe("chat"),t&&ye(!1),at?.sessionId){Wt(at.sessionId,ie);return}Yt({directoryOverride:ie,preserveDirectoryOverride:!0})}}),s.jsx(ES,{}),s.jsx(J2,{value:q,setValue:H,showDeletionDialog:L,setShowDeletionDialog:ae,onConfirm:Xt}),s.jsx(Z2,{value:X,setValue:oe,onConfirm:Is}),s.jsx(X2,{value:ue,setValue:Se,showDeletionDialog:L,setShowDeletionDialog:ae,onConfirm:vs})]})},wi=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(/\/+$/,"")},fk=()=>{const{t}=kt(),[e,n]=i.useState(!1),[r,o]=i.useState(!1),[a,c]=i.useState(null),[l,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(!1),[y,g]=i.useState(!1),[b,x]=i.useState(!1),[h,C]=i.useState(new Set),w=ut(ce=>ce.getWorktreeMetadata),v=ut(ce=>ce.newSessionDraft),S=ut(ce=>ce.setNewSessionDraftTarget),k=ut(ce=>ce.setDraftBootstrapPendingDirectory),j=Jg,A=ex,D=ut(ce=>ce.deleteSessions),N=ut(ce=>ce.archiveSessions),B=Ee(ce=>ce.showDeletionDialog),T=Ee(ce=>ce.setShowDeletionDialog),E=Xs(ce=>ce.currentDirectory),_=Xs(ce=>ce.homeDirectory),R=Xs(ce=>ce.isHomeReady),$=Ns(ce=>ce.projects),V=Ns(ce=>ce.activeProjectId),{isMobile:z,isTablet:F,hasTouchInput:ne}=Mr(),te=z||F||ne,q=i.useMemo(()=>{const he=(V?$.find(Ne=>Ne.id===V)??null:null)?.path??E;return yr(he)},[V,E,$]),H=i.useCallback(ce=>{const Ne=yr(ce.projectDirectory)||q;return{id:($.find(P=>yr(P.path)===Ne)??null)?.id??`path:${Ne}`,path:Ne}},[q,$]),X=b&&h.size>0,oe=i.useMemo(()=>{const ce=a?.worktree;return ce&&typeof ce.branch=="string"&&ce.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:he})=>typeof he.branch=="string"&&he.branch.trim().length>0)},[a?.worktree,l]),ue=a?.mode==="worktree",Se=ue,Z=y||!ue||!oe,ke=y||!ue;i.useEffect(()=>{r||!R||$.length>0||(o(!0),n(!0))},[r,R,$.length]);const Y=i.useCallback(ce=>{c({sessions:ce.sessions,dateLabel:ce.dateLabel,mode:ce.mode??"session",worktree:ce.worktree??null})},[]),ge=i.useCallback(()=>{c(null),d([]),m(!1),p(!1),g(!1),x(!1),C(new Set)},[]),O=i.useCallback(async ce=>{if(ce.sessions.length===0)return;if(ce.sessions.length===1){const P=ce.sessions[0];await j(P.id)?le.success(t("sessions.sidebar.session.delete.success")):le.error(t("sessions.sidebar.session.delete.error"));return}const he=ce.sessions.map(P=>P.id),{deletedIds:Ne,failedIds:fe}=await D(he);if(Ne.length>0){const P=fe.length>0?fe.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:fe.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:fe.length}):ce.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:ce.dateLabel}):void 0;le.success(Ne.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:Ne.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:Ne.length}),{description:wi(P)})}fe.length>0&&le.error(fe.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:fe.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:fe.length}),{description:wi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[j,D,t]);i.useEffect(()=>Tr.onDeleteRequest(ce=>{if(!B&&(ce.mode??"session")==="session"){O(ce);return}Y(ce)}),[Y,B,O]),i.useEffect(()=>Tr.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1),p(!1),x(!1),C(new Set);return}const ce=a.sessions.map(fe=>{const P=w(fe.id);return P?{session:fe,metadata:P}:null}).filter(fe=>!!fe);d(ce),m(!1),x(!1),C(new Set);const he=new Map;if(a.worktree?.path&&he.set(yr(a.worktree.path),a.worktree),ce.forEach(({metadata:fe})=>{fe.path&&he.set(yr(fe.path),fe)}),he.size===0){x(!0);return}let Ne=!1;return(async()=>{const fe=new Map,P=new Set;await Promise.all(Array.from(he.entries()).map(async([M,de])=>{try{const xe=await Xg(de.path);fe.set(M,xe),xe?.isDirty&&P.add(M)}catch{de.status&&(fe.set(M,de.status),de.status.isDirty&&P.add(M))}})).catch(M=>{console.warn("Failed to inspect worktree status before deletion:",M)}),!Ne&&(C(P),x(!0),c(M=>{if(!M?.worktree?.path)return M;const de=yr(M.worktree.path),xe=fe.get(de);if(!xe)return M;const W=M.worktree.status;return W?.isDirty===xe.isDirty&&W?.ahead===xe.ahead&&W?.behind===xe.behind&&W?.upstream===xe.upstream?M:{...M,worktree:{...M.worktree,status:xe}}}),d(M=>M.map(de=>{const xe=yr(de.metadata.path),W=fe.get(xe);return W?{session:de.session,metadata:{...de.metadata,status:W}}:de})))})(),()=>{Ne=!0}},[a,w]),i.useEffect(()=>{oe||m(!1)},[oe]);const se=i.useCallback(async(ce,he)=>{const Ne=u&&oe,fe=H(ce),P=yr(ce.path),M=yr(fe.path);try{await Zg(fe,ce,{deleteRemoteBranch:Ne,deleteLocalBranch:he});const de=yr(v?.directoryOverride);return v?.open&&P&&de===P&&M&&(k(null),S({projectId:fe.id,directoryOverride:M},{force:!0})),yr(E)===P&&M&&Xs.getState().setDirectory(M,{showOverlay:!1}),!0}catch(de){return le.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:wi(de instanceof Error?de.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[oe,E,u,H,v?.directoryOverride,v?.open,k,S,t]),ee=i.useCallback((ce,he)=>{const Ne=u&&oe;(async()=>{if(!await se(ce,he))return;const P=t(Ne?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");le.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:wi(P)})})()},[oe,u,se,t]),je=i.useCallback(async()=>{if(a){g(!0);try{const ce=Se,he=ce&&u,Ne=ce&&f;if(a.sessions.length===0&&ue&&a.worktree){ee(a.worktree,Ne),ge();return}if(a.sessions.length===1){const fe=a.sessions[0];if(!(ue?await A(fe.id):await j(fe.id,{archiveWorktree:!1,deleteRemoteBranch:he,deleteLocalBranch:Ne}))){le.error(t(ue?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),g(!1);return}const M=!ue&&ce?t(he?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;le.success(t(ue?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:wi(M),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const fe=a.sessions.map(de=>de.id);let P=[],M=[];if(ue){const de=await N(fe);P=de.archivedIds,M=de.failedIds}else{const de=await D(fe);P=de.deletedIds,M=de.failedIds}if(ue&&a.worktree&&M.length===0&&ee(a.worktree,Ne),P.length>0){const de=!ue&&ce?t(he?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,W=[M.length>0?ue?M.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:M.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:M.length}):M.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:M.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:M.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,de].filter(Boolean).join(" ");le.success(ue?P.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:P.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:P.length}):P.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:P.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:P.length}),{description:wi(W||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if(M.length>0&&(le.error(ue?M.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:M.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:M.length}):M.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:M.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:M.length}),{description:wi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),P.length===0)){g(!1);return}}ue&&a.sessions.length===1&&a.worktree&&ee(a.worktree,Ne),ge()}finally{g(!1)}}},[a,u,f,j,D,A,N,ge,Se,ue,ee,t]),De=a?.worktree??l[0]?.metadata??null,Be=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}):"",Fe=a?s.jsxs("div",{className:Pe(ue?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:Pe(ue?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[ue&&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:Pe(ue?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(ce=>s.jsxs("li",{className:Pe(ue?"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:Pe(!ue&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:ce.title||t("sessions.sidebar.session.untitled")})]},ce.id)),a.sessions.length>5&&s.jsx("li",{className:Pe(ue?"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})})]})]}),ue?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(I,{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")}),De?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:De.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:De?ka(De.path,_):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),X&&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,Me=ue?oe?s.jsxs("button",{type:"button",onClick:()=>{Z||m(ce=>!ce)},disabled:Z,className:Pe("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",Z?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(I,{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,me=ue?s.jsxs("button",{type:"button",onClick:()=>{ke||p(ce=>!ce)},disabled:ke,className:Pe("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ke?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[f?s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(I,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Ae=ue?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:[me,Me]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{variant:"ghost",onClick:ge,disabled:y,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{variant:"destructive",onClick:je,disabled:y,children:t(y?"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:()=>T(!B),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":!B,children:[B?s.jsx(I,{name:"checkbox-blank",className:"size-4"}):s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}),t("sessions.sidebar.dialogs.neverAsk")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{variant:"ghost",onClick:ge,disabled:y,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{variant:"destructive",onClick:je,disabled:y,children:y?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),pe=ue?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:[te?s.jsx(Ua,{open:!!a,onClose:()=>{y||ge()},title:pe,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Ae}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[Be&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Be}),Fe]})}):s.jsx($s,{open:!!a,onOpenChange:ce=>{if(!ce){if(y)return;ge()}},children:s.jsxs(Vs,{className:Pe(ue?"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(Gs,{children:[s.jsxs(Us,{className:Pe(ue&&"flex items-center gap-2"),children:[ue&&s.jsx(I,{name:"delete-bin",className:"h-5 w-5"}),pe]}),Be&&s.jsx(ln,{children:Be})]}),s.jsx("div",{className:Pe(ue&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:Fe}),s.jsx(or,{className:"mt-2 gap-2 pt-1 pb-1",children:Ae})]})}),s.jsx(Qx,{open:e,onOpenChange:n})]})},dc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),mk=(t,e)=>{const n=dc(t),r=dc(e);return`${n}-${r}`.substring(0,60)},Sf=(t,e)=>`${t}/${e}`,hk=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},Nf=(t,e)=>{const n=hk(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};lx(t.id,n),ut.getState().markSessionAsOpenChamberCreated(t.id),jr.getState().upsertSession(o);try{Ca().ensureChild(n,{bootstrap:!1}).setState(c=>{const l=c.session.findIndex(u=>u.id===t.id);if(l>=0&&c.session[l]===o)return c;const d=l>=0?c.session.map((u,m)=>m===l?o:u):[...c.session,o].sort((u,m)=>u.id.localeCompare(m.id));return{session:d,sessionTotal:Math.max(c.sessionTotal,d.length),limit:Math.max(c.limit,d.length)}})}catch{}return o},pk=()=>{const t=Ns.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=Xs.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},Ll=ro()(Mf(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=pk();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,m=await mm(d)&&e.isolateRuns!==!1,f=dc(n),p=m?await Ka(d):void 0,y=m?await tx(d):null,g=[],b=c?.filter(v=>v.trim().length>0)??[];for(let v=0;v<r.length;v++){const S=r[v],k=S.prompt,j=new Map;for(const D of S.models){const N=`${D.providerID}:${D.modelID}`;j.set(N,(j.get(N)||0)+1)}const A=new Map;for(const D of S.models){const N=`${D.providerID}:${D.modelID}`,B=j.get(N)||1,T=(A.get(N)||0)+1;A.set(N,T);const E=mk(D.providerID,D.modelID),_=r.length>1?`g${v+1}`:void 0,R=B>1?Sf(f,`${E}/${T}`):Sf(f,E),$=_?`${_}/${R}`:R,V=N2({groupSlug:f,runGroup:_,providerID:D.providerID,modelID:D.modelID,index:B>1?T:void 0});try{if(!m){const te=await Jn.withDirectory(d,()=>Jn.createSession({title:V}));Nf(te,d),g.push({sessionId:te.id,worktreePath:d,providerID:D.providerID,modelID:D.modelID,variant:D.variant,prompt:k});continue}const z=await sx(l,{preferredName:$,mode:"new",branchName:$,worktreeName:$,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:b,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:y}),F={...z,createdFromBranch:p,kind:"standard"};await nx(l)&&await rx(z.path);const ne=await Jn.withDirectory(z.path,()=>Jn.createSession({title:V}));Nf(ne,z.path),ut.getState().setWorktreeMetadata(ne.id,F),g.push({sessionId:ne.id,worktreePath:z.path,providerID:D.providerID,modelID:D.modelID,variant:D.variant,prompt:k})}catch(z){console.warn("[MultiRun] Failed to create session:",z)}}}const x=c?.filter(v=>v.trim().length>0)??[];x.length>0&&ix(l,x).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const h=g.map(v=>v.sessionId),C=g[0]?.sessionId??null;if(h.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const w=a?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));return(async()=>{try{const v=ox.getState().expandText;await Promise.allSettled(g.map(async S=>{try{const k=await v(S.prompt).catch(()=>S.prompt);await ax({sessionId:S.sessionId,directory:S.worktreePath,content:k,providerID:S.providerID,modelID:S.modelID,variant:S.variant,agent:o,files:w})}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),t({isLoading:!1}),{groupSlug:f,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"})),gk="oc:lastWorktreeSourceBranch";function Nh(t){const e=ft.c(30),{git:n}=Xn(),r=em(t),o=kc(t),a=Cc(t),c=cx(t),l=vn(vk),d=vn(wk);let u,m;e[0]!==t||e[1]!==d||e[2]!==n||e[3]!==o||e[4]!==a?(u=()=>{!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]=u,e[6]=m):(u=e[5],m=e[6]),i.useEffect(u,m);let f;e[7]!==r?.all||e[8]!==t||e[9]!==l||e[10]!==n||e[11]!==o?(f=()=>{!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]=f):f=e[12];const p=r?.all;let y;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==p?(y=[t,n,o,p,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=p,e[18]=y):y=e[18],i.useEffect(f,y);const g=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(yk).sort(),e[20]=r.all,e[21]=k):k=e[21],b=k}const x=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(bk).map(xk).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(g){w=null;break e}w=r?.all?!0:null}const v=w;let S;return e[25]!==v||e[26]!==g||e[27]!==x||e[28]!==C?(S={localBranches:x,remoteBranches:C,isLoading:g,isGitRepository:v},e[25]=v,e[26]=g,e[27]=x,e[28]=C,e[29]=S):S=e[29],S}function xk(t){return t.replace(/^remotes\//,"")}function bk(t){return t.startsWith("remotes/")}function yk(t){return!t.startsWith("remotes/")}function wk(t){return t.fetchStatus}function vk(t){return t.fetchBranches}const jk=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=kt(),{localBranches:l,remoteBranches:d,isLoading:u,isGitRepository:m}=Nh(t),f=i.useMemo(()=>[...l,...d.map(y=>`remotes/${y}`)],[l,d]);i.useEffect(()=>{if(o||u||f.length===0||e&&f.includes(e))return;(async()=>{try{const g=t?await Ka(t).catch(()=>null):null,b=localStorage.getItem(gk);b&&f.includes(b)?n(b):g&&f.includes(g)?n(g):f.includes("main")?n("main"):f.includes("master")?n("master"):f[0]&&n(f[0])}catch{}})()},[f,t,o,u,n,e]);const p=o||!m||u;return s.jsxs("div",{children:[s.jsxs(zn,{value:e,onValueChange:n,disabled:p,children:[s.jsx(Wn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(Cn,{placeholder:c(u?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(Un,{className:"max-h-[280px] max-w-[320px]",children:u?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(Hl,{children:[s.jsx(zd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(y=>s.jsx(Ms,{value:y,className:"whitespace-normal break-all",children:y},y))]}),l.length>0&&d.length>0&&s.jsx(dx,{}),d.length>0&&s.jsxs(Hl,{children:[s.jsx(zd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(y=>s.jsx(Ms,{value:`remotes/${y}`,className:"whitespace-normal break-all",children:y},`remotes/${y}`))]})]})})]}),m===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},Sk=10*1024*1024,Ol=5,ga=t=>{const e=ft.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(Mt,{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(I,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(Et,{children:[r,s.jsx(Ft,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},Si=t=>{const e=ft.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 u;return e[6]!==l||e[7]!==d?(u=s.jsxs("div",{className:"flex items-center gap-1.5",children:[l,d]}),e[6]=l,e[7]=d,e[8]=u):u=e[8],u},Nk=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=kt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:Ao(),prompt:"",models:[]}]),[u,m]=i.useState(""),[f,p]=i.useState([]),[y,g]=i.useState(!1),[b,x]=i.useState([]),[h,C]=i.useState(!1),[w,v]=i.useState(!1),[S,k]=i.useState(!0),j=i.useRef(null),A=Xs(M=>M.currentDirectory??null),D=Xs(M=>M.homeDirectory??null),N=i.useMemo(()=>{if(typeof window>"u")return null;const M=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof M=="string"&&M.trim().length>0?M.trim():null},[]),B=Ns(M=>M.activeProjectId),T=Ns(M=>M.setActiveProjectIdOnly),E=Ns(M=>M.projects),[_,R]=i.useState(()=>B??null);i.useEffect(()=>{if(B){R(B);return}!_&&E.length>0&&R(E[0].id)},[B,E,_]);const $=i.useMemo(()=>_?E.find(M=>M.id===_)??null:null,[E,_]),V=$?.path??A,z=i.useCallback(M=>{R(M),M!==B&&T(M)},[B,T]),{currentTheme:F}=qr(),ne=i.useCallback(M=>{const de=M.label?.trim()||Ti(M.path,D),xe=M.icon?Tc[M.icon]:null,W=M.color?Ya[M.color]:void 0,be=xe?s.jsx(I,{name:xe,className:"h-3.5 w-3.5 shrink-0",style:W?{color:W}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:W?{color:W}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[M.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:M.iconBackground?{backgroundColor:M.iconBackground}:void 0,children:s.jsx(Qa,{project:{id:M.id,iconImage:M.iconImage??null},options:{themeVariant:F.metadata.variant,iconColor:F.colors.surface.foreground},className:"h-full w-full object-contain",fallback:be})}):be,s.jsx("span",{className:"truncate",children:de})]})},[D,F.metadata.variant,F.colors.surface.foreground]),te=i.useMemo(()=>{if($?.path)return{id:$.id,path:$.path};const M=A??N;return M?{id:`path:${M}`,path:M}:null},[$,A,N]),[q]=i.useState(()=>typeof window<"u"?ur():!1),H=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),X=Uf(),oe=i.useMemo(()=>{if(typeof window>"u")return null;const M=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof M=="number"&&Number.isFinite(M)&&M>0)return M;if(typeof navigator>"u")return null;const de=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!de)return null;const xe=Number.parseInt(de[1],10),W=Number.parseInt(de[2],10);return Number.isNaN(xe)?null:xe===10?W:xe},[]),ue=i.useMemo(()=>q&&H||X?"pl-[5.5rem]":"pl-3",[q,H,X]),Se=i.useMemo(()=>!q||!H||oe===null?"":oe>=26?"h-12":oe<=15?"h-14":"",[q,H,oe]),Z=i.useCallback(async M=>{M.target.closest("button, a, input, select, textarea")||M.button===0&&q&&await ux()},[q]);i.useEffect(()=>{if(!n)return;const M=de=>{de.key==="Escape"&&(de.preventDefault(),de.stopPropagation(),n())};return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[n]);const[ke,Y]=i.useState(""),{isLoading:ge,isGitRepository:O}=Nh(V),se=i.useRef(!1),ee=O===!0,je=ee&&S;i.useEffect(()=>{if(O===!1){se.current=!0,k(!1);return}O===!0&&se.current&&(se.current=!1,k(!0))},[O]);const De=Ll(M=>M.createMultiRun),Be=Ll(M=>M.error),Fe=Ll(M=>M.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d(M=>{const de=[...M];return de.length>0&&!de[0].prompt.trim()&&(de[0]={...de[0],prompt:t}),de})},[t]),i.useEffect(()=>{if(!te)return;let M=!1;return v(!0),(async()=>{try{const de=await fx(te);M||x(de)}catch{}finally{M||v(!1)}})(),()=>{M=!0}},[te]);const Me=i.useCallback((M,de)=>{d(xe=>xe.map(W=>W.id===M?{...W,...de}:W))},[]),me=i.useCallback(M=>{d(de=>de.filter(xe=>xe.id!==M))},[]),Ae=i.useCallback(()=>{d(M=>[...M,{id:Ao(),prompt:"",models:[]}])},[]),pe=async M=>{const de=M.target.files;if(!de)return;let xe=0;for(let W=0;W<de.length;W++){const be=de[W];if(be.size>Sk){le.error(o("multirun.launcher.toast.fileTooLarge",{fileName:be.name}));continue}try{const ve=await new Promise((G,ye)=>{const Le=new FileReader;Le.onload=()=>G(Le.result),Le.onerror=ye,Le.readAsDataURL(be)});p(G=>[...G,{id:Ao(),filename:be.name,mimeType:be.type||"application/octet-stream",size:be.size,dataUrl:ve}]),xe++}catch(ve){console.error("File attach failed",ve),le.error(o("multirun.launcher.toast.attachFailed",{fileName:be.name}))}}xe>0&&le.success(xe===1?o("multirun.launcher.toast.attachedSingle",{count:xe}):o("multirun.launcher.toast.attachedPlural",{count:xe})),j.current&&(j.current.value="")},ce=M=>{p(de=>de.filter(xe=>xe.id!==M))},he=i.useMemo(()=>l.reduce((M,de)=>M+de.models.length,0),[l]),Ne=async M=>{M.preventDefault();const de=l.filter(xe=>xe.prompt.trim()&&xe.models.length>=1);if(de.length!==0&&!(he<1)){g(!0),Fe();try{_&&_!==B&&T(_);const xe=f.map(ye=>({mime:ye.mimeType,filename:ye.filename,url:ye.dataUrl})),W=b.filter(ye=>ye.trim().length>0),be=de.map(ye=>({prompt:ye.prompt.trim(),models:ye.models.map(Le=>({providerID:Le.providerID,modelID:Le.modelID,displayName:Le.displayName,variant:Le.variant}))})),ve={name:a.trim(),groups:be,agent:u||void 0,worktreeBaseBranch:je?ke:void 0,isolateRuns:je,files:xe.length>0?xe:void 0,setupCommands:W.length>0?W:void 0},G=await De(ve);G&&(G.firstSessionId&&ut.getState().setCurrentSession(G.firstSessionId),e?.())}finally{g(!1)}}},fe=!!(a.trim()&&l.some(M=>M.prompt.trim()&&M.models.length>=1)&&he>=1&&V&&!ge&&(O===!1||!je||ke)),P=b.filter(M=>M.trim()).length;return s.jsxs("form",{onSubmit:Ne,className:"flex flex-col h-full bg-background",children:[r?null:s.jsxs("header",{onMouseDown:Z,className:Pe("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",ue,Se),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(Et,{children:[s.jsx(Mt,{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(I,{name:"close",className:"h-5 w-5"})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("multirun.launcher.actions.closeEsc")})})]})})]}),s.jsx(Ha,{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(Si,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),E.length>0?s.jsxs(zn,{value:_??void 0,onValueChange:z,children:[s.jsx(Wn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:$?s.jsx(Cn,{children:ne($)}):s.jsx(Cn,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(Un,{fitContent:!0,children:E.map(M=>s.jsx(Ms,{value:M.id,className:"max-w-[24rem]",children:ne(M)},M.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(Si,{htmlFor:"group-name",required:!0,info:s.jsx(ga,{children:o("multirun.launcher.groupName.info")}),children:o("multirun.launcher.groupName.label")}),s.jsx(jn,{id:"group-name",value:a,onChange:M=>c(M.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(Si,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(ga,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(jk,{directory:V,value:ke,onChange:Y,disabled:!je,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(Pi,{checked:S,onChange:k,disabled:!ee,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(Si,{htmlFor:"multirun-agent",info:s.jsx(ga,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(wh,{value:u,onChange:m,id:"multirun-agent"})]})]}),s.jsxs(eo,{open:h,onOpenChange:C,children:[s.jsxs(Bo,{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(I,{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")}),P>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:P}),s.jsx(I,{name:"arrow-down-s",className:Pe("h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto",h&&"rotate-180")})]}),s.jsx(to,{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((M,de)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(jn,{value:M,onChange:xe=>{const W=[...b];W[de]=xe.target.value,x(W)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>x(b.filter((xe,W)=>W!==de)),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(I,{name:"close",className:"h-3.5 w-3.5"})})]},`${M}-${de}`)),s.jsxs("button",{type:"button",onClick:()=>x([...b,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(I,{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(Si,{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:pe,accept:"*/*"}),s.jsxs(Et,{children:[s.jsx(Mt,{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(I,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(Ft,{children:o("multirun.launcher.attachments.tooltip")})]}),f.map(M=>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:[M.mimeType.startsWith("image/")?s.jsx(I,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(I,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:M.filename,children:M.filename}),s.jsx("button",{type:"button",onClick:()=>ce(M.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(I,{name:"close",className:"h-3 w-3"})})]},M.id))]})]}),l.map((M,de)=>s.jsx(kk,{group:M,groupIndex:de,canRemove:l.length>1,onUpdate:Me,onRemove:me},M.id)),s.jsxs("button",{type:"button",onClick:Ae,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(I,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),Be&&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:Be})]})})}),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:[!je&&O!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(I,{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($e,{type:"button",variant:"ghost",size:"sm",onClick:n,children:o("multirun.launcher.actions.cancel")}),s.jsx($e,{type:"submit",size:"sm",disabled:!fe||y,children:y?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:he})})})]})})]})},kk=t=>{const e=ft.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=kt(),[d,u]=i.useState(!1),[m,f]=i.useState(""),[p,y]=i.useState(!1),[g,b]=i.useState(""),[x,h]=i.useState(!1),[C,w]=i.useState(""),v=i.useRef(null),S=i.useRef(null),k=i.useRef(null),j=i.useRef(null);let A;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(A=W=>{n.models.length>=Ol||a(n.id,{models:[...n.models,W]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=A):A=e[3];const D=A;let N;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(N=W=>{a(n.id,{models:n.models.filter((be,ve)=>ve!==W)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=N):N=e[7];const B=N;let T;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(T=(W,be)=>{a(n.id,{models:n.models.map((ve,G)=>G===W?be:ve)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=T):T=e[11];const E=T;let _;e[12]===Symbol.for("react.memo_cache_sentinel")?(_=(W,be)=>{if(W.startsWith("/")){const Le=W.indexOf(" "),Re=W.indexOf(`
211
- `),J=Math.min(Le===-1?W.length:Le,Re===-1?W.length:Re);if(be<=J&&Le===-1){b(W.substring(1,J)),y(!0),u(!1),h(!1);return}}y(!1);const ve=W.substring(0,be),G=ve.lastIndexOf("#");if(G!==-1){const Le=G>0?ve[G-1]:null,Re=ve.substring(G+1);if((!Le||/\s/.test(Le))&&!Re.includes(" ")&&!Re.includes(`
212
- `)){w(Re),h(!0),u(!1);return}}h(!1);const ye=ve.lastIndexOf("@");if(ye!==-1){const Le=ye>0?ve[ye-1]:null,Re=ve.substring(ye+1);(!Le||/\s/.test(Le))&&!Re.includes(" ")&&!Re.includes(`
213
- `)?(f(Re),u(!0)):u(!1);return}u(!1)},e[12]=_):_=e[12];const R=_;let $;e[13]!==n.id||e[14]!==a?($=W=>{a(n.id,{prompt:W})},e[13]=n.id,e[14]=a,e[15]=$):$=e[15];const V=$;let z;e[16]!==n.prompt||e[17]!==V?(z=W=>{const be=n.prompt,G=v.current?.selectionStart??be.length,Le=be.substring(0,G).lastIndexOf("@"),Re=W.relativePath&&W.relativePath.trim().length>0?W.relativePath.trim():W.path||W.name,J=Le!==-1?Le:G,L=`${be.substring(0,J)}@${Re} ${be.substring(G)}`,ae=J+Re.length+2;V(L),u(!1),f(""),requestAnimationFrame(()=>{const re=v.current;re&&(re.selectionStart=ae,re.selectionEnd=ae,re.focus()),R(L,ae)})},e[16]=n.prompt,e[17]=V,e[18]=z):z=e[18];const F=z;let ne;e[19]!==n.prompt||e[20]!==V?(ne=W=>{const be=n.prompt,G=v.current?.selectionStart??be.length,Le=be.substring(0,G).lastIndexOf("@"),Re=Le!==-1?Le:G,J=`${be.substring(0,Re)}@${W} ${be.substring(G)}`,L=Re+W.length+2;V(J),u(!1),f(""),requestAnimationFrame(()=>{const ae=v.current;ae&&(ae.selectionStart=L,ae.selectionEnd=L,ae.focus()),R(J,L)})},e[19]=n.prompt,e[20]=V,e[21]=ne):ne=e[21];const te=ne;let q;e[22]!==V?(q=W=>{const be=`/${W.name} `;V(be),y(!1),b(""),h(!1),requestAnimationFrame(()=>{const ve=v.current;ve&&(ve.focus(),ve.selectionStart=ve.value.length,ve.selectionEnd=ve.value.length),R(be,be.length)})},e[22]=V,e[23]=q):q=e[23];const H=q;let X;e[24]!==n.prompt||e[25]!==V?(X=(W,be)=>{const ve=n.prompt,ye=v.current?.selectionStart??ve.length,Re=ve.substring(0,ye).lastIndexOf("#"),J=Re!==-1?Re:ye,L=`${ve.substring(0,J)}#${be} ${ve.substring(ye)}`,ae=J+be.length+2;V(L),h(!1),w(""),requestAnimationFrame(()=>{const re=v.current;re&&(re.selectionStart=ae,re.selectionEnd=ae,re.focus()),R(L,ae)})},e[24]=n.prompt,e[25]=V,e[26]=X):X=e[26];const oe=X;let ue;e[27]!==p||e[28]!==d||e[29]!==x?(ue=W=>{if(p&&k.current&&(W.key==="Enter"||W.key==="ArrowUp"||W.key==="ArrowDown"||W.key==="Escape"||W.key==="Tab")){W.preventDefault(),k.current.handleKeyDown(W.key);return}d&&S.current&&(W.key==="Enter"||W.key==="ArrowUp"||W.key==="ArrowDown"||W.key==="Escape"||W.key==="Tab")&&(W.preventDefault(),S.current.handleKeyDown(W.key)),x&&j.current&&(W.key==="Enter"||W.key==="ArrowUp"||W.key==="ArrowDown"||W.key==="Escape"||W.key==="Tab")&&(W.preventDefault(),j.current.handleKeyDown(W.key))},e[27]=p,e[28]=d,e[29]=x,e[30]=ue):ue=e[30];const Se=ue,Z=r+1;let ke;e[31]!==l||e[32]!==Z?(ke=l("multirun.launcher.groups.groupLabel",{index:Z}),e[31]=l,e[32]=Z,e[33]=ke):ke=e[33];let Y;e[34]!==ke?(Y=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:ke}),e[34]=ke,e[35]=Y):Y=e[35];let ge;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(ge=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(I,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=ge):ge=e[40];let O;e[41]!==Y||e[42]!==ge?(O=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Y,ge]}),e[41]=Y,e[42]=ge,e[43]=O):O=e[43];let se;e[44]!==l?(se=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=se):se=e[45];let ee;e[46]!==se?(ee=s.jsx(Si,{required:!0,children:se}),e[46]=se,e[47]=ee):ee=e[47];const je=n.prompt;let De;e[48]!==V?(De=W=>{const be=W.target.value;V(be);const ve=W.target.selectionStart??be.length;R(be,ve)},e[48]=V,e[49]=De):De=e[49];let Be;e[50]!==l?(Be=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=Be):Be=e[51];let Fe;e[52]!==n.prompt||e[53]!==Se||e[54]!==De||e[55]!==Be?(Fe=s.jsx(Ni,{ref:v,value:je,onChange:De,onKeyDown:Se,placeholder:Be,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]=Se,e[54]=De,e[55]=Be,e[56]=Fe):Fe=e[56];let Me;e[57]!==g||e[58]!==H||e[59]!==p?(Me=p?s.jsx(cm,{ref:k,searchQuery:g,onCommandSelect:H,onClose:()=>y(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=g,e[58]=H,e[59]=p,e[60]=Me):Me=e[60];let me;e[61]!==te||e[62]!==F||e[63]!==m||e[64]!==d?(me=d?s.jsx(dm,{ref:S,searchQuery:m,onFileSelect:F,onAgentSelect:te,onClose:()=>u(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=te,e[62]=F,e[63]=m,e[64]=d,e[65]=me):me=e[65];let Ae;e[66]!==oe||e[67]!==x||e[68]!==C?(Ae=x?s.jsx(um,{ref:j,searchQuery:C,onSnippetSelect:oe,onClose:()=>h(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=oe,e[67]=x,e[68]=C,e[69]=Ae):Ae=e[69];let pe;e[70]!==Fe||e[71]!==Me||e[72]!==me||e[73]!==Ae?(pe=s.jsxs("div",{className:"relative",children:[Fe,Me,me,Ae]}),e[70]=Fe,e[71]=Me,e[72]=me,e[73]=Ae,e[74]=pe):pe=e[74];let ce;e[75]!==ee||e[76]!==pe?(ce=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[ee,pe]}),e[75]=ee,e[76]=pe,e[77]=ce):ce=e[77];let he;e[78]!==l?(he=l("multirun.launcher.models.info",{max:Ol}),e[78]=l,e[79]=he):he=e[79];let Ne;e[80]!==he?(Ne=s.jsx(ga,{children:he}),e[80]=he,e[81]=Ne):Ne=e[81];let fe;e[82]!==l?(fe=l("multirun.launcher.models.label"),e[82]=l,e[83]=fe):fe=e[83];let P;e[84]!==Ne||e[85]!==fe?(P=s.jsx(Si,{required:!0,info:Ne,children:fe}),e[84]=Ne,e[85]=fe,e[86]=P):P=e[86];let M;e[87]!==n.models||e[88]!==D||e[89]!==B||e[90]!==E?(M=s.jsx(jh,{selectedModels:n.models,onAdd:D,onRemove:B,onUpdate:E,minModels:1,maxModels:Ol}),e[87]=n.models,e[88]=D,e[89]=B,e[90]=E,e[91]=M):M=e[91];let de;e[92]!==P||e[93]!==M?(de=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[P,M]}),e[92]=P,e[93]=M,e[94]=de):de=e[94];let xe;return e[95]!==O||e[96]!==ce||e[97]!==de?(xe=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[O,ce,de]}),e[95]=O,e[96]=ce,e[97]=de,e[98]=xe):xe=e[98],xe},Ck=i.createContext(null),Ak=t=>{const e=ft.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(Ck.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},kf=oo(()=>io(()=>import("./TerminalView-DF7-jlam.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(t=>({default:t.TerminalView}))),Dk=oo(()=>io(()=>import("./DiagramView-CIaZCGUT.js"),__vite__mapDeps([8,1,3,4,2,5,6,7])).then(t=>({default:t.DiagramView}))),Ik=oo(()=>io(()=>import("./runtimeEndpointReset-BYLVW9e7.js").then(t=>t.a9),__vite__mapDeps([5,1,2,3,4,6])).then(t=>({default:t.SettingsView}))),Pk=oo(()=>io(()=>import("./SettingsWindow-K-ErjehP.js"),__vite__mapDeps([9,1,2,3,4,5,6])).then(t=>({default:t.SettingsWindow}))),Tk=oo(()=>io(()=>import("./MultiRunWindow-Bsbr3i8y.js"),__vite__mapDeps([10,1,2,3,4,5,6,7])).then(t=>({default:t.MultiRunWindow}))),Rk=()=>{const o=Ee(X=>X.isSidebarOpen),a=Ee(X=>X.isRightSidebarOpen),c=Ee(X=>X.isBottomTerminalOpen),l=Ee(X=>X.setRightSidebarOpen),d=Ee(X=>X.setBottomTerminalOpen),u=Ee(X=>X.activeMainTab),m=Ee(X=>X.setIsMobile),f=Ee(X=>X.isSessionSwitcherOpen),p=Ee(X=>X.isSettingsDialogOpen),y=Ee(X=>X.setSettingsDialogOpen),g=Ee(X=>X.isMultiRunLauncherOpen),b=Ee(X=>X.setMultiRunLauncherOpen),x=Ee(X=>X.multiRunLauncherPrefillPrompt),{isMobile:h,isTablet:C}=Mr(),w=i.useRef(!1),v=i.useRef(!1),S=i.useRef(!1),[k,j]=i.useState(!1),[A,D]=i.useState(!1),[N,B]=i.useState(!1),[T,E]=i.useState(!1),_=i.useCallback(X=>{j(X),Ee.getState().setSessionSwitcherOpen(X)},[]),R=i.useRef(!1),$=i.useRef(typeof window>"u"?0:window.innerWidth),V=pd(-$.current),z=Xe.useRef(0),F=pd($.current),ne=Xe.useRef(0);Xe.useEffect(()=>{h&&(z.current=window.innerWidth,ne.current=window.innerWidth)},[h]),Xe.useEffect(()=>{if(!h){B(!1);return}k&&B(!0),gd(V,k?0:-z.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[k,h,V]),Xe.useEffect(()=>{if(!h){E(!1);return}R.current=A,A&&E(!0),gd(F,A?0:ne.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[h,A,F]),Xe.useEffect(()=>{if(h)return V.on("change",X=>{const oe=z.current||$.current,ue=k||X>-oe+.5;B(Se=>Se===ue?Se:ue)})},[h,V,k]),Xe.useEffect(()=>{if(h)return F.on("change",X=>{const oe=ne.current||$.current,ue=A||X<oe-.5;E(Se=>Se===ue?Se:ue)})},[h,A,F]),Xe.useEffect(()=>{h&&!f&&k&&_(!1)},[f,h,k,_]),Xe.useEffect(()=>{if(!h){S.current=!1;return}S.current||(S.current=!0,_(!1),D(!1),Ee.getState().isRightSidebarOpen&&l(!1))},[h,_,l]),Xe.useEffect(()=>{if(!h||u!=="chat"||k||A||p)return;let X=!1,oe;const ue=Se=>{oe=window.setTimeout(()=>{if(X)return;const Z=ut.getState(),ke=Ee.getState();if(!(ke.activeMainTab!=="chat"||ke.isSettingsDialogOpen||Z.currentSessionId||Z.newSessionDraft?.open)){if(Z.isLoading){ue(250);return}Z.openNewSessionDraft()}},Se)};return ue(500),()=>{X=!0,oe!==void 0&&window.clearTimeout(oe)}},[u,h,p,k,A]),Xe.useEffect(()=>{!h||!p||(_(!1),D(!1),a&&l(!1))},[h,p,a,_,l]),Jx(),i.useEffect(()=>{Ee.getState().isMobile!==h&&m(h)},[h,m]),i.useEffect(()=>{if(typeof window>"u")return;let X;const oe=()=>{X===void 0&&(X=window.requestAnimationFrame(()=>{X=void 0,Ee.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",oe),()=>{window.removeEventListener("resize",oe),X!==void 0&&window.cancelAnimationFrame(X)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let X;const oe=()=>{const Se=Ee.getState(),Z=window.innerWidth,ke=window.innerHeight;if(!h&&!C){const Y=Z<1140,ge=Z>=1220;Y?Se.isRightSidebarOpen&&(l(!1),w.current=!0):ge&&w.current&&(l(!0),w.current=!1);const O=ke<640,se=ke>=700;O?Se.isBottomTerminalOpen&&(d(!1),v.current=!0):se&&v.current&&(d(!0),v.current=!1)}},ue=()=>{X===void 0&&(X=window.requestAnimationFrame(()=>{X=void 0,oe()}))};return oe(),window.addEventListener("resize",ue),()=>{window.removeEventListener("resize",ue),X!==void 0&&window.cancelAnimationFrame(X)}},[h,C,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const X=Ee.subscribe((oe,ue)=>{const Se=window.innerWidth,Z=window.innerHeight,ke=Se>=1220,Y=Z>=700;oe.isRightSidebarOpen!==ue.isRightSidebarOpen&&ke&&(w.current=!1),oe.isBottomTerminalOpen!==ue.isBottomTerminalOpen&&Y&&(v.current=!1)});return()=>{X()}},[h,C,d,l]);const te=i.useCallback(()=>{k&&_(!1),D(!A)},[k,A,_]),q=i.useMemo(()=>{switch(u){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Zm,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(ec,{isActive:!A})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(qm,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(kf,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Xm,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Um,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Dk,{})});default:return null}},[u,A]),H=u==="chat";return s.jsx(Xx,{children:s.jsxs("div",{"data-page-scroll-lock":"true",className:Pe("main-content-safe-area",h?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[s.jsx(ej,{}),s.jsx($j,{}),s.jsx(Hj,{}),s.jsx(fk,{}),h?s.jsxs(Ak,{value:{leftDrawerOpen:k,rightDrawerOpen:A,toggleLeftDrawer:()=>{const X=!k;A&&D(!1),_(X)},toggleRightDrawer:te,leftDrawerX:V,rightDrawerX:F,leftDrawerWidth:z,rightDrawerWidth:ne,setMobileLeftDrawerOpen:_,setRightSidebarOpen:D},children:[!p&&s.jsx(su,{onToggleLeftDrawer:()=>{const X=!k;A&&D(!1),_(X)},onToggleRightDrawer:()=>{te()},leftDrawerOpen:k,rightDrawerOpen:A}),s.jsx("div",{"data-page-scroll-lock":"true",className:Pe("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:Pe("absolute inset-0",!H&&"invisible"),children:s.jsx(en,{children:s.jsx(Yl,{})})}),q&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(en,{children:q})}),g&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(en,{children:s.jsx(Nk,{initialPrompt:x,onCreated:()=>b(!1),onCancel:()=>b(!1)})})}),N&&s.jsx(xd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:V},"aria-hidden":!k,children:s.jsx(en,{children:s.jsx(jf,{mobileVariant:!0})})}),T&&s.jsx(xd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:F},"aria-hidden":!A,children:s.jsx(en,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(ec,{isActive:A})})})})]})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(en,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Ik,{onClose:()=>y(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(ly,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(iy,{isOpen:o,isMobile:h,className:"border-border/50",topBar:s.jsx(oy,{}),children:s.jsx(jf,{})}),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:Pe("absolute inset-0",!H&&"invisible"),children:s.jsx(en,{children:s.jsx(Yl,{})})}),q&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(en,{children:q})})]}),s.jsx(Z0,{})]})}),s.jsx(ey,{isOpen:c,isMobile:h,children:c?s.jsx(en,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(kf,{})})}):null})]}),s.jsx(hy,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(en,{children:s.jsx(Fv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(Pk,{open:p,onOpenChange:y})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(Tk,{open:g,onOpenChange:b,initialPrompt:x})})]})]})})},Ek=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`},_n=t=>{const e=ft.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},Cf=t=>{const e=ft.c(43),{title:n,snapshot:r,emptyLabel:o}=t,{t:a}=kt();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(Lk,0),e[8]=r.entries,e[9]=d):d=e[9];const u=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 f;e[12]!==r.durationMs||e[13]!==r.startedAt||e[14]!==a?(f=r.startedAt?Ek(r.durationMs):a("memoryDebugPanel.common.idle"),e[12]=r.durationMs,e[13]=r.startedAt,e[14]=a,e[15]=f):f=e[15];let p;e[16]!==f?(p=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:f}),e[16]=f,e[17]=p):p=e[17];let y;e[18]!==m||e[19]!==p?(y=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m,p]}),e[18]=m,e[19]=p,e[20]=y):y=e[20];let g;e[21]!==a?(g=a("memoryDebugPanel.metric.metrics"),e[21]=a,e[22]=g):g=e[22];let b;e[23]!==r.entries.length||e[24]!==g?(b=s.jsx(_n,{label:g,value:r.entries.length}),e[23]=r.entries.length,e[24]=g,e[25]=b):b=e[25];let x;e[26]!==a?(x=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=x):x=e[27];let h;e[28]!==x||e[29]!==u?(h=s.jsx(_n,{label:x,value:u}),e[28]=x,e[29]=u,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 v;e[36]!==C||e[37]!==w?(v=s.jsx(_n,{label:C,value:w}),e[36]=C,e[37]=w,e[38]=v):v=e[38];let S;e[39]!==h||e[40]!==v||e[41]!==b?(S=s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[b,h,v]}),e[39]=h,e[40]=v,e[41]=b,e[42]=S):S=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:[y,S,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($n,{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},Mk=t=>{const e=ft.c(99),{onClose:n}=t,{t:r}=kt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=ut(Ok),u=fm(Bk),m=Dc(),f=mx(_k),p=ir(Vk),[y,g]=i.useState($k),[b,x]=i.useState(zk);let h;e[0]!==y.entries?(h=new Map,y.entries.forEach(fe=>{h.set(fe.metric,fe.count)}),e[0]=y.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 v;e[6]!==h?(v=h.get("ui.chat_message.render")??0,e[6]=h,e[7]=v):v=e[7];let S;e[8]!==h?(S=h.get("ui.chat_message.render.streaming")??0,e[8]=h,e[9]=S):S=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 A;e[14]!==C||e[15]!==w||e[16]!==v||e[17]!==S||e[18]!==k||e[19]!==j?(A={messageListRender:C,messageListRenderStreaming:w,chatMessageRender:v,chatMessageRenderStreaming:S,chatMessageRenderStaticDuringStream:k,chatMessageRenderStaticOutsideActiveTurnDuringStream:j},e[14]=C,e[15]=w,e[16]=v,e[17]=S,e[18]=k,e[19]=j,e[20]=A):A=e[20];const D=A;let N,B;e[21]===Symbol.for("react.memo_cache_sentinel")?(N=()=>{const fe=()=>{g(na()),x(ra())};fe();const P=window.setInterval(fe,500);return()=>window.clearInterval(P)},B=[],e[21]=N,e[22]=B):(N=e[21],B=e[22]),i.useEffect(N,B);let T,E;e[23]!==c?(T=()=>{if(c==="idle")return;const fe=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(fe)},E=[c],e[23]=c,e[24]=T,e[25]=E):(T=e[24],E=e[25]),i.useEffect(T,E);let _=0,R=0,$=0;for(const fe of Object.keys(f)){const P=f[fe]??[];R=R+P.length;for(const M of P)M.role==="user"?$=$+1:M.role==="assistant"&&(_=_+1)}let V;e[26]!==_||e[27]!==R||e[28]!==$?(V={assistant:_,total:R,user:$},e[26]=_,e[27]=R,e[28]=$,e[29]=V):V=e[29];const z=V;let F;if(e[30]!==d||e[31]!==f||e[32]!==u||e[33]!==m||e[34]!==r){let fe;e[36]!==d||e[37]!==f||e[38]!==u||e[39]!==r?(fe=P=>{const M=f[P.id]??[];let de=0,xe=0;for(const be of M)be.role==="user"?xe=xe+1:be.role==="assistant"&&(de=de+1);const W=u.get(P.id);return{id:P.id,title:P.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:de,messageCount:M.length,userMessageCount:xe,isStreaming:W?.isStreaming||!1,isZombie:W?.isZombie||!1,backgroundCount:W?.backgroundMessageCount||0,lastAccessed:W?.lastAccessedAt||0,isCurrent:P.id===d}},e[36]=d,e[37]=f,e[38]=u,e[39]=r,e[40]=fe):fe=e[40],F=m.map(fe).sort(Wk),e[30]=d,e[31]=f,e[32]=u,e[33]=m,e[34]=r,e[35]=F}else F=e[35];const ne=F;let te;e[41]!==f?(te=Object.keys(f),e[41]=f,e[42]=te):te=e[42];const q=te.length;let H;e[43]===Symbol.for("react.memo_cache_sentinel")?(H=async()=>{try{const fe={generatedAt:new Date().toISOString(),ui:na(),vscode:ra()};await navigator.clipboard.writeText(JSON.stringify(fe,null,2)),l("copied")}catch{l("error")}},e[43]=H):H=e[43];const X=H;let oe;e[44]===Symbol.for("react.memo_cache_sentinel")?(oe={backgroundColor:"color-mix(in srgb, var(--surface-background) 94%, transparent)"},e[44]=oe):oe=e[44];let ue;e[45]!==o?(ue=o==="memory"?s.jsx(I,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(I,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=ue):ue=e[46];let Se;e[47]!==r?(Se=r("memoryDebugPanel.title"),e[47]=r,e[48]=Se):Se=e[48];let Z;e[49]!==Se?(Z=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:Se}),e[49]=Se,e[50]=Z):Z=e[50];let ke;e[51]!==ue||e[52]!==Z?(ke=s.jsxs("div",{className:"flex items-center gap-2",children:[ue,Z]}),e[51]=ue,e[52]=Z,e[53]=ke):ke=e[53];let Y;e[54]!==o?(Y=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx($e,{size:"xs",variant:"ghost",onClick:X,children:s.jsx(I,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx($e,{size:"xs",variant:"ghost",onClick:()=>{vp(),g(na()),x(ra())},children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=Y):Y=e[55];let ge;e[56]!==n?(ge=n?s.jsx($e,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=ge):ge=e[57];let O;e[58]!==Y||e[59]!==ge?(O=s.jsxs("div",{className:"flex items-center gap-1",children:[Y,ge]}),e[58]=Y,e[59]=ge,e[60]=O):O=e[60];let se;e[61]!==ke||e[62]!==O?(se=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[ke,O]}),e[61]=ke,e[62]=O,e[63]=se):se=e[63];let ee;e[64]===Symbol.for("react.memo_cache_sentinel")?(ee={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=ee):ee=e[64];const je=o==="memory"?"secondary":"ghost";let De;e[65]===Symbol.for("react.memo_cache_sentinel")?(De=()=>a("memory"),e[65]=De):De=e[65];let Be;e[66]!==r?(Be=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=Be):Be=e[67];let Fe;e[68]!==je||e[69]!==Be?(Fe=s.jsx($e,{size:"sm",variant:je,className:"flex-1",onClick:De,children:Be}),e[68]=je,e[69]=Be,e[70]=Fe):Fe=e[70];const Me=o==="streaming"?"secondary":"ghost";let me;e[71]===Symbol.for("react.memo_cache_sentinel")?(me=()=>a("streaming"),e[71]=me):me=e[71];let Ae;e[72]!==r?(Ae=r("memoryDebugPanel.tabs.streaming"),e[72]=r,e[73]=Ae):Ae=e[73];let pe;e[74]!==Me||e[75]!==Ae?(pe=s.jsx($e,{size:"sm",variant:Me,className:"flex-1",onClick:me,children:Ae}),e[74]=Me,e[75]=Ae,e[76]=pe):pe=e[76];let ce;e[77]!==Fe||e[78]!==pe?(ce=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:ee,children:[Fe,pe]}),e[77]=Fe,e[78]=pe,e[79]=ce):ce=e[79];let he;e[80]!==o||e[81]!==q||e[82]!==c||e[83]!==d||e[84]!==f||e[85]!==z||e[86]!==u||e[87]!==ne||e[88]!==m||e[89]!==D||e[90]!==y||e[91]!==r||e[92]!==p||e[93]!==b?(he=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(_n,{label:r("memoryDebugPanel.metric.totalMessages"),value:z.total}),s.jsx(_n,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${q} / ${Wd.MAX_SESSIONS}`}),s.jsx(_n,{label:r("memoryDebugPanel.metric.userMessages"),value:z.user}),s.jsx(_n,{label:r("memoryDebugPanel.metric.assistantMessages"),value:z.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:hx()})})]}),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($n,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:ne.map(fe=>s.jsxs("div",{className:"typography-meta flex items-center justify-between rounded p-1.5",style:{backgroundColor:fe.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:fe.title}),fe.isStreaming?s.jsx(I,{name:"pulse",className:"h-3 w-3 animate-pulse text-[var(--status-info)]"}):null,fe.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:fe.assistantMessageCount,user:fe.userMessageCount})}),s.jsx("span",{className:"font-mono text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.msgsValue",{count:fe.messageCount})}),fe.backgroundCount>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["+",fe.backgroundCount]}):null]})]},fe.id))})]}),s.jsx("div",{className:"flex gap-2 border-t border-[var(--interactive-border)] pt-2",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:m.map(Uk),currentSessionId:d,cachedSessions:Object.keys(f),messageRoleCounts:z,sessionMessageRoleCounts:ne.map(Hk),memoryStates:Object.fromEntries(u)})},children:r("memoryDebugPanel.actions.logState")})}),s.jsx(Ft,{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($e,{size:"xs",variant:"outline",onClick:X,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(_n,{label:r("memoryDebugPanel.metric.uiMetrics"),value:y.entries.length}),s.jsx(_n,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:b.entries.length}),s.jsx(_n,{label:r("memoryDebugPanel.metric.messageListRenders"),value:D.messageListRender}),s.jsx(_n,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:D.messageListRenderStreaming}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:D.chatMessageRender}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:D.chatMessageRenderStreaming}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:D.chatMessageRenderStaticDuringStream}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:D.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(Cf,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:y,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),b.entries.length>0?s.jsx(Cf,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:b,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=q,e[82]=c,e[83]=d,e[84]=f,e[85]=z,e[86]=u,e[87]=ne,e[88]=m,e[89]=D,e[90]=y,e[91]=r,e[92]=p,e[93]=b,e[94]=he):he=e[94];let Ne;return e[95]!==se||e[96]!==ce||e[97]!==he?(Ne=s.jsxs(px,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:oe,children:[se,ce,he]}),e[95]=se,e[96]=ce,e[97]=he,e[98]=Ne):Ne=e[98],Ne},Fk=Mk;function Lk(t,e){return t+e.count}function Ok(t){return t.currentSessionId}function Bk(t){return t.sessionMemoryState}function _k(t){return t.message}function Vk(t){return t.totalRequestCount}function $k(){return na()}function zk(){return ra()}function Wk(t,e){return e.lastAccessed-t.lastAccessed}function Uk(t){return{id:t.id,title:t.title}}function Hk(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const Gk=()=>{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()??"":""},Kk=async()=>{const t=Gk()||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")},Af="openchamber:menu-action",Bl="openchamber:check-for-updates",qk=t=>{const e=ut(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),u=Ee(j=>j.setAboutDialogOpen),m=Ee(j=>j.toggleRightSidebar),f=Ee(j=>j.setRightSidebarOpen),p=Ee(j=>j.setRightSidebarTab),y=Ee(j=>j.toggleBottomTerminal),g=Ee(j=>j.setBottomTerminalExpanded),b=wo(j=>j.checkForUpdates),{setThemeMode:x}=qr(),h=i.useRef(!1),C=i.useCallback(()=>{h.current||(h.current=!0,b().then(()=>{const{available:j,error:A}=wo.getState();if(A){le.error("Failed to check for updates",{description:A});return}j||le.success("You are on the latest version")}).finally(()=>{h.current=!1}))},[b]),w=i.useCallback(()=>{Tr.requestDirectoryDialog()},[]),v=i.useCallback(j=>{const A=gx();if(A.length===0)return;const D=ut.getState().currentSessionId,N=A.findIndex(E=>E.id===D);let B=j>0?0:A.length-1;N>=0&&(B=(N+j+A.length)%A.length);const T=A[B];T&&(l("chat"),c(!1),ut.getState().setCurrentSession(T.id))},[l,c]),S=i.useCallback(j=>{const{activeProjectId:A,projects:D,setActiveProject:N}=Ns.getState();if(D.length===0)return;const B=D.findIndex(_=>_.id===A);let T=j>0?0:D.length-1;B>=0&&(T=(B+j+D.length)%D.length);const E=D[T];E&&N(E.id)},[]),k=i.useCallback(j=>{switch(j){case"about":u(!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),lm();break;case"change-workspace":w();break;case"toggle-right-sidebar":m();break;case"open-right-sidebar-git":f(!0),p("git");break;case"open-right-sidebar-files":f(!0),p("files");break;case"toggle-terminal":y();break;case"toggle-terminal-expanded":g(!Ee.getState().isBottomTerminalExpanded);break;case"copy":{const A=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(A)||Kk();break}case"theme-light":x("light");break;case"theme-dark":x("dark");break;case"theme-system":x("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":Xs.getState().goBack();break;case"go-forward":Xs.getState().goForward();break;case"previous-session":v(-1);break;case"next-session":v(1);break;case"previous-project":S(-1);break;case"next-project":S(1);break;case"help-dialog":o();break;case"download-logs":{xx().catch(()=>{le.error("Failed to collect OpenCode status")});break}}},[w,S,v,t,e,u,l,c,r,d,g,f,p,x,y,n,o,m,a]);i.useEffect(()=>{const j=D=>{const N=D.detail;N&&k(N)},A=()=>{C()};return window.addEventListener(Af,j),window.addEventListener(Bl,A),()=>{window.removeEventListener(Af,j),window.removeEventListener(Bl,A)}},[k,C]),i.useEffect(()=>{if(typeof window>"u")return;const A=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof A!="function")return;let D=null,N=null;return A("openchamber:menu-action",B=>{const T=B?.payload;typeof T=="string"&&k(T)}).then(B=>{D=B}).catch(()=>{}),A("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Bl))}).then(B=>{N=B}).catch(()=>{}),()=>{(async()=>{try{const T=D?.();T instanceof Promise&&await T}catch{}try{const T=N?.();T instanceof Promise&&await T}catch{}})()}},[k])},Yk="openchamber:tray-action",Df=5e3,Qk=120,Jk=45e3,kh=20,If=()=>typeof window>"u"?!1:window.__OPENCHAMBER_PLATFORM__==="darwin",Xk=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},Zk=t=>{const e=Array.isArray(t.questions)?t.questions[0]:void 0;return e?.header||e?.question||"Question"},Oa=t=>t.time?.updated??t.time?.created??0,eC=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},tC=(t,e,n,r,o)=>{if(!t)return"";const a=vx(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||eC(t),d=oa(t);let u=d&&o.get(d)||"";if(!u){for(const[m,f]of vn.getState().directories)if(oa(m)===d){u=f.status?.current??"";break}}if(!u)for(const m of r.values()){const f=m.find(p=>oa(p.path)===d);if(f?.branch){u=f.branch;break}}return u?`${l} · ${u}`:l},sC=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=gn.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 wm){if(!e.includes(c.id))continue;const l=o.get(c.id);if(!l||l.configured!==!0)continue;const d=[];for(const[m,f]of Object.entries(l.usage?.windows??{})){const p=r==="remaining"?f.remainingPercent:f.usedPercent;d.push({label:bc(m),value:Io(f.valueLabel,p)})}const u=!l.ok&&l.error?l.error:d.length===0?"No rate limits reported":null;a.push({provider:c.name,rows:d,status:u})}return{mode:r,groups:a}},nC=async()=>{try{if(Ji())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=Ur();if(e&&Sa(e,t))return"Local OpenChamber";const r=(await Hf()).hosts.find(o=>e?Sa(e,Gf(o)):!1);return r?.label?.trim()?Kf(r.label.trim()):"Instance"}catch{return""}},rC=()=>{const t=new Map,e=new Map,n=[],r=new Map;let o;try{o=Ca()}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(oa(a)??a,l.vcs.branch);for(const d of l.session)d?.id&&r.set(d.id,d.title);for(const[d,u]of Object.entries(l.session_status??{})){const m=u?.type,f=m==="busy"?"busy":m==="retry"?"retry":"idle",p=t.get(d);(!p||p==="idle")&&t.set(d,f)}for(const[d,u]of Object.entries(l.permission??{}))for(const m of u??[]){if(!m?.id)continue;const f=m.sessionID||d;n.push({kind:"permission",id:m.id,sessionId:f,sessionTitle:"",label:Xk(m),directory:a})}for(const[d,u]of Object.entries(l.question??{}))for(const m of u??[]){if(!m?.id)continue;const f=m.sessionID||d;n.push({kind:"question",id:m.id,sessionId:f,sessionTitle:"",label:Zk(m),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},iC=()=>{const t=jr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>Oa(o)-Oa(r)).slice(0,kh).forEach(r=>{const o=Rr(r);o&&e.add(o)});const n=new Map;for(const r of t){if(!r?.id)continue;const o=Rr(r);if(!o||!e.has(o))continue;const a=n.get(o)??[];a.push(r.id),n.set(o,a)}return n},oC=t=>{const e=rC(),n=hm.getState().index.session,r=jr.getState().activeSessions,o=new Map(e.titleById),a=new Map;for(const x of r)if(x?.id&&(x.title&&o.set(x.id,x.title),x.parentID)){const h=a.get(x.parentID)??[];h.push(x.id),a.set(x.parentID,h)}const c=x=>{const h=[],C=[...a.get(x)??[]],w=new Set;for(;C.length;){const v=C.pop();w.has(v)||(w.add(v),h.push(v),C.push(...a.get(v)??[]))}return h},l=pm.getState().statusById,d=x=>{const h=e.statusById.get(x);return h&&h!=="idle"?h:l.get(x)?.status??h??"idle"},u=x=>{const h=x.map(C=>d(C));return h.includes("busy")?"busy":h.includes("retry")?"retry":"idle"},m=Ns.getState().projects,f=ut.getState().availableWorktreesByProject,p=r.filter(x=>x?.id&&!x.parentID).slice().sort((x,h)=>Oa(h)-Oa(x)).slice(0,kh).map(x=>{const h=[x.id,...c(x.id)],C=Rr(x)??"";return{id:x.id,title:x.title||"Untitled session",status:u(h),branch:C?e.branchByDirectory.get(C)??"":"",unseen:h.reduce((w,v)=>w+(n.unseenCount[v]??0),0),hasError:h.some(w=>n.unseenHasError[w]??!1),directory:C,subtitle:tC(C,x,m,f,e.branchByDirectory)}}),y=e.approvals.map(x=>({...x,sessionTitle:o.get(x.sessionId)||""})),g=Ee.getState();let b=0;if(g.dockBadgeEnabled)for(const x of r){if(!x?.id||x.parentID)continue;let h=n.unseenCount[x.id]??0;h===0&&g.notifyOnSubtasks&&(h=c(x.id).reduce((C,w)=>C+(n.unseenCount[w]??0),0)),h>0&&(b+=1)}return{sessions:p,approvals:y,instanceName:t,usage:sC(),dockBadgeCount:b}},aC=()=>{i.useEffect(()=>{if(!If()||!Ba())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const k=oC(r),j=JSON.stringify(k);j!==e&&(e=j,Hr("desktop_tray_update",k))};nC().then(k=>{t||(r=k,o())});const a=async()=>{const k=iC();await Promise.all([...k.entries()].map(async([j,A])=>{const D=await Jn.getSessionStatusForDirectory(j).catch(()=>null);t||D===null||yx(j,D,A)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},Qk))},l=new Map,d=()=>{if(t)return;let k;try{k=Ca()}catch{return}const j=new Set;for(const[A,D]of k.children.entries())j.add(A),l.has(A)||l.set(A,D.subscribe(()=>c()));for(const[A,D]of l)j.has(A)||(D(),l.delete(A))};let u=null;try{u=Ca().subscribeRegistry(()=>{d(),c()})}catch{}d();const m=hm.subscribe(()=>c()),f=jr.subscribe(()=>c()),p=Ns.subscribe(()=>c()),y=ut.subscribe(()=>c()),g=vn.subscribe(()=>c()),b=Ee.subscribe(()=>c()),x=pm.subscribe(()=>c());bx(qf());const h=window.setInterval(()=>{Na()},Jk);a();const C=window.setInterval(()=>{a()},Df),w=gn.subscribe(()=>c());gn.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:k,results:j}=gn.getState();k.length>0&&k.some(D=>!j.some(N=>N.providerId===D))&&gn.getState().fetchAllQuotas()});const v=window.setInterval(()=>{const k=gn.getState();k.autoRefresh&&k.dropdownProviderIds.length>0&&k.fetchAllQuotas()},Math.max(3e4,gn.getState().refreshIntervalMs||6e4)),S=window.setInterval(()=>{d(),o()},Df);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(S),window.clearInterval(h),window.clearInterval(C),window.clearInterval(v),m(),f(),p(),y(),g(),b(),x(),w(),u?.();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"&&wx(o.sessionId,o.id,o.response).catch(()=>{le.error("Failed to respond to permission request")})};let r=null;return e(Yk,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{}}},[])},lC="/api/notifications/stream",cC=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),dC=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}},uC=t=>{const e=ft.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||ur()||!xc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(ki().sse(lC));return a.onmessage=fC,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function fC(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Ee.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&cC())return;const r=dC(e);if(!r)return;Lo()?.notifications?.notifyAgentCompletion(r)}const Pf="pwa-install-toast-shown",Tf="pwa-install-toast-dismissed",mC=()=>{const t=ft.c(6),{browserTab:e}=Zx(),{t:n}=kt(),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"||!xc()||!e)return;let d=null,u=null;const m=()=>{u!==null&&(le.dismiss(u),u=null)},f=async()=>{if(!d)return;const g=d;d=null,m(),await g.prompt();const{outcome:b}=await g.userChoice;b==="accepted"&&le.success(r.current("pwa.installPrompt.started"))},p=g=>{const b=g;if(typeof b.prompt!="function")return;b.preventDefault(),d=b;const x=zi(),h=Of();eb({dismissed:x.getItem(Tf),sessionShown:h.getItem(Pf),hasActiveToast:u!==null})&&(h.setItem(Pf,"true"),u=le.info(r.current("pwa.installPrompt.description"),{duration:1/0,action:{label:r.current("pwa.installPrompt.action"),onClick:()=>{f()}},cancel:{label:r.current("pwa.installPrompt.dismiss"),onClick:()=>{zi().setItem(Tf,"true"),m()}}}))},y=()=>{d=null,m(),le.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",p),window.addEventListener("appinstalled",y),()=>{m(),window.removeEventListener("beforeinstallprompt",p),window.removeEventListener("appinstalled",y)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},hC=({open:t,onOpenChange:e})=>{const{t:n}=kt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,u]=i.useState(!1),[m,f]=i.useState(!1),[p,y]=i.useState(null),[g,b]=i.useState(!1);i.useCallback(async()=>{},[p,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const C=await Cs("/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 Cs("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!w.ok)return;const v=await w.json().catch(()=>null),S=typeof v?.currentVersion=="string"?v.currentVersion.trim():"";!h&&S&&l(S)}catch{}})(),()=>{h=!0}},[t]),i.useEffect(()=>{{y(null),b(!1);return}},[t,r]);const x=o;return s.jsx($s,{open:t,onOpenChange:e,children:s.jsx(Vs,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(Pc,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),s.jsxs("div",{className:"space-y-0.5 typography-meta text-muted-foreground",children:[x&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:x})}),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(I,{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(I,{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(I,{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")})]})})})},_l=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},pC=(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},gC=()=>{const t=tb(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=_l(a,"code"),l=sb(a),d=nb(a),u=_l(a,"error"),m=_l(a,"error_description");if(u){d&&Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(m??u);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 f=l;if(!f&&d){const p=await Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`);if(p.ok){const y=await p.json().catch(()=>null);y?.name?.trim()&&(f={name:y.name.trim(),directory:typeof y.directory=="string"&&y.directory.trim()?y.directory.trim():null})}}if(!f?.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(f.name,c,f.directory),d&&await Cs(`/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(f){d&&await Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(pC(f,"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($e,{type:"button",onClick:()=>{typeof window>"u"||window.location.replace("/")},children:"Return to OpenChamber"})})]})})},Rf=oo(()=>io(()=>import("./OnboardingScreen-3IAKkM5k.js"),__vite__mapDeps([11,1,3,4,2])).then(t=>({default:t.OnboardingScreen}))),xC=()=>{const t=ft.c(3),e=Ee(SC),n=Ee(NC);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(hC,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},bC=t=>{const e=ft.c(21),{onRetry:n,isRetrying:r}=t,{t:o}=kt();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 u;e[8]!==c||e[9]!==d?(u=s.jsxs("div",{className:"flex flex-col gap-2",children:[c,d]}),e[8]=c,e[9]=d,e[10]=u):u=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 f;e[14]!==r||e[15]!==n||e[16]!==m?(f=s.jsx($e,{type:"button",onClick:n,disabled:r,children:m}),e[14]=r,e[15]=n,e[16]=m,e[17]=f):f=e[17];let p;return e[18]!==u||e[19]!==f?(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:[u,f]})}),e[18]=u,e[19]=f,e[20]=p):p=e[20],p},Ef=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",yC=()=>{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"}},wC=()=>typeof window>"u"?!1:window.location.pathname===ab,vC=t=>{const e=ft.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=Xs(kC),c=ut(CC),l=ut(AC),d=Rc(),u=i.useRef(null);let m;e[0]!==n.directory?(m=Ef(n.directory),e[0]=n.directory,e[1]=m):m=e[1];const f=m;let p;e[2]!==a?(p=Ef(a),e[2]=a,e[3]=p):p=e[3];const y=p;let g,b;if(e[4]!==y||e[5]!==c||e[6]!==n.directory||e[7]!==n.sessionId||e[8]!==f||e[9]!==r||e[10]!==l||e[11]!==d?(g=()=>{if(r||f&&y!==f)return;const S=`${f}
214
- ${n.sessionId}`;u.current===S&&c===n.sessionId||(u.current=S,l(n.sessionId,n.directory),d.ensureSessionRenderable(n.sessionId,!0))},b=[y,c,n.directory,n.sessionId,f,r,l,d],e[4]=y,e[5]=c,e[6]=n.directory,e[7]=n.sessionId,e[8]=f,e[9]=r,e[10]=l,e[11]=d,e[12]=g,e[13]=b):(g=e[12],b=e[13]),i.useEffect(g,b),f&&y!==f)return null;let x;e[14]!==o?(x=s.jsx(gm,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=x):x=e[15];let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(Am,{}),e[16]=h):h=e[16];let C;e[17]!==n.readOnly?(C=s.jsx(Yl,{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(xm,{}),e[19]=w):w=e[19];let v;return e[20]!==x||e[21]!==C?(v=s.jsxs(s.Fragment,{children:[x,h,C,w]}),e[20]=x,e[21]=C,e[22]=v):v=e[22],v};function jC({apis:t}){i.useEffect(()=>{jp("App:mounted"),Sp()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=ss(O=>O.initializeApp),n=ss(O=>O.isInitialized),r=ss(O=>O.isConnected),o=ss(O=>O.providers.length),a=ss(O=>O.agents.length),c=ss(O=>O.loadProviders),l=ss(O=>O.loadAgents),d=ut(O=>O.error),u=ut(O=>O.clearError),m=Xs(O=>O.currentDirectory),f=Xs(O=>O.setDirectory),p=Xs(O=>O.isSwitchingDirectory),[y,g]=i.useState(!1),b=Ii(O=>O.refreshStatus),[x,h]=i.useState(()=>t.runtime.isVSCode),[C,w]=i.useState(!0),[v,S]=i.useState(!1),[k,j]=i.useState(0),[A,D]=i.useState(0),[N,B]=i.useState(!1),T=Ee(O=>O.wideChatLayoutEnabled),E=Ee(O=>O.mobileKeyboardMode),_=i.useMemo(()=>ur(),[]),R=wc(O=>O.setPlanModeEnabled),[$,V]=i.useState(()=>vd()),[z,F]=i.useState(()=>{const O=jd();return O!==null?Sd({isDesktopShell:!0,bootOutcome:O}):null}),ne=i.useRef(!1),te=i.useMemo(()=>yC(),[]),q=!te||C,H=i.useMemo(()=>wC(),[]);i.useEffect(()=>(Nd(y),()=>{Nd(!1)}),[y]),i.useEffect(()=>{Np(E)},[E]),i.useEffect(()=>{h(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>Vf(O=>{rb(O),D(se=>se+1),S(!1),j(se=>se+1)}),[]);const X=Ud(O=>{const se=kd();return Object.values(O.runsByOriginalSessionID).filter(ee=>ee.status==="running"&&ee.runtimeKey===se).map(ee=>`${ee.originalSessionID}:${ee.phase}:${ee.lastForwardedMessageID??""}:${ee.expectedAssistantParentID??""}`).sort().join("|")});i.useEffect(()=>{if(te)return;const O=kd(),se=Object.values(Ud.getState().runsByOriginalSessionID).filter(ee=>ee.status==="running"&&ee.runtimeKey===O);for(const ee of se)Sx(ee.originalSessionID)},[X,te,A]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",T),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[T]),i.useEffect(()=>(Cd(t),()=>Cd(null)),[t]),i.useEffect(()=>{te||b(t.github,{force:!0})},[t.github,te,b]),Nx();const oe=$==="valid",ue=z?.screen==="main";i.useEffect(()=>{if(!kp({isDesktopShell:_,isInitialized:n,bootOutcomeKnown:oe,bootViewIsMain:ue}))return;const O=setTimeout(()=>{const se=document.getElementById("initial-loading");se&&(se.classList.add("fade-out"),setTimeout(()=>{se.remove()},300))},150);return()=>clearTimeout(O)},[_,n,oe,ue]),i.useEffect(()=>{if(!_||$!=="malformed")return;const O=document.getElementById("initial-loading");O&&(O.textContent="Desktop startup failed — please restart the app.")},[_,$]),i.useEffect(()=>{if(_)return;const O=setTimeout(()=>{const se=document.getElementById("initial-loading");se&&!n&&(se.classList.add("fade-out"),setTimeout(()=>{se.remove()},300))},5e3);return()=>clearTimeout(O)},[_,n]),i.useEffect(()=>{let O=!1;return(async()=>{const ee=await Cs("/health",{method:"GET"}).catch(()=>null);if(!ee||!ee.ok||O)return;const je=await ee.json().catch(()=>null);if(!je||O)return;const De=je.planModeExperimentalEnabled;R(De===!0||De===1||De==="1"||De==="true")})(),()=>{O=!0}},[R]),i.useEffect(()=>{x||e()},[e,x]),i.useEffect(()=>{if(x||n)return;let O=!0,se,ee=0;const je=10,De=1e3,Be=async()=>{if(!O)return;if(ee>=je){S(!0);return}const Fe=ss.getState();if(Fe.isInitialized){S(!1);return}ee+=1,await Fe.initializeApp();const Me=ss.getState();if(!O)return;if(Me.isInitialized){S(!1);return}if(ee>=je){S(!0);return}const me=Math.min(De*Math.pow(2,ee-1),16e3);se=setTimeout(Be,me)};return se=setTimeout(Be,De),()=>{O=!1,se&&clearTimeout(se)}},[k,n,x]),i.useEffect(()=>{n&&S(!1)},[n]),i.useEffect(()=>{if(!v)return;const O=document.getElementById("initial-loading");O&&(O.classList.add("fade-out"),setTimeout(()=>{O.remove()},300))},[v]),i.useEffect(()=>{if(x||!r||o>0&&a>0)return;let O=!0,se=0;const ee=15,je=async()=>{const Be=ss.getState();if(!(Be.providers.length>0&&Be.agents.length>0))try{Be.providers.length===0&&await c({source:"startupRecovery"}),ss.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};je();const De=setInterval(()=>{if(O){if(++se>=ee){clearInterval(De);return}je()}},2e3);return()=>{O=!1,clearInterval(De)}},[r,x,l,c,o,a]),i.useEffect(()=>{p||x||r&&Jn.setDirectory(m)},[m,p,r,x]),i.useEffect(()=>{if(!te||typeof window>"u")return;const O=je=>{const De=je?.visible===!0;w(De)},se=je=>{if(je.origin!==window.location.origin)return;const De=je.data;De?.type==="openchamber:embedded-visibility"&&O(De.payload)},ee=window;return ee.__openchamberSetEmbeddedVisibility=O,window.addEventListener("message",se),()=>{window.removeEventListener("message",se),ee.__openchamberSetEmbeddedVisibility===O&&delete ee.__openchamberSetEmbeddedVisibility}},[te]),i.useEffect(()=>{!te?.directory||x||m!==te.directory&&f(te.directory,{showOverlay:!1})},[m,te,x,f]),i.useEffect(()=>{if(!te||typeof window>"u")return;const O=se=>{se.storageArea===window.localStorage&&se.key==="ui-store"&&Ee.persist.rehydrate()};return window.addEventListener("storage",O),()=>{window.removeEventListener("storage",O)}},[te]),i.useEffect(()=>{if(typeof window>"u")return;const O=se=>{const ee=se.detail,je=typeof ee?.sessionId=="string"?ee.sessionId.trim():"";if(!je)return;const De=typeof ee?.directory=="string"&&ee.directory.trim().length>0?ee.directory.trim():null;Ee.getState().setActiveMainTab("chat"),ut.getState().setCurrentSession(je,De)};return window.addEventListener("openchamber:open-session",O),()=>window.removeEventListener("openchamber:open-session",O)},[]),i.useEffect(()=>{if(typeof window>"u")return;const O=()=>{const se=Xs.getState().currentDirectory,{activeProjectId:ee,projects:je}=Ns.getState(),De=je.find(Be=>Be.id===ee)??null;Hr("desktop_open_draft_mini_chat_window",{directory:se||De?.path||"",projectId:De?.id??null})};return window.addEventListener("openchamber:open-mini-chat",O),()=>window.removeEventListener("openchamber:open-mini-chat",O)},[]),i.useEffect(()=>{if(typeof window>"u")return;const O=()=>{const se=ut.getState().currentSessionId;se&&om(se)};return window.addEventListener("focus",O),()=>window.removeEventListener("focus",O)},[]),i.useEffect(()=>{if(typeof window>"u")return;const O=se=>{const ee=se.detail,je=typeof ee?.directory=="string"&&ee.directory.trim().length>0?ee.directory.trim():null,De=typeof ee?.projectId=="string"&&ee.projectId.trim().length>0?ee.projectId.trim():null;Ee.getState().setActiveMainTab("chat"),Ee.getState().setSessionSwitcherOpen(!1),ut.getState().openNewSessionDraft({selectedProjectId:De,directoryOverride:je,preserveDirectoryOverride:!!je})};return window.addEventListener("openchamber:open-draft-session",O),()=>window.removeEventListener("openchamber:open-draft-session",O)},[]),i.useEffect(()=>{if(typeof window>"u")return;const O=se=>{const ee=se.detail,je=typeof ee?.projectPath=="string"?ee.projectPath.trim():"";if(!je)return;const De=Ns.getState(),Be=De.projects.find(Fe=>Fe.path===je);Be?De.setActiveProject(Be.id):De.addProject(je)};return window.addEventListener("openchamber:open-project",O),()=>window.removeEventListener("openchamber:open-project",O)},[]),i.useEffect(()=>{typeof window>"u"||!n||p||ne.current||(ne.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,p]),kx({enabled:q}),uC({enabled:q}),mC(),Cx(),ib();const Se=i.useCallback(()=>{g(O=>!O)},[]);qk(Se),aC(),i.useEffect(()=>{if(te)return;const O=se=>{vc(se)&&se.shiftKey&&!se.altKey&&(se.code==="KeyD"||se.key.toLowerCase()==="d")&&(se.preventDefault(),g(je=>!je))};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[te]),i.useEffect(()=>{te||d&&setTimeout(()=>u(),5e3)},[u,te,d]),i.useEffect(()=>{if(!_||$!=="not-injected")return;let O=!1,se=0;const ee=200,je=2e3,De=50,Be=()=>{if(O)return;se++;const Fe=vd();if(Fe!=="not-injected"){if(O=!0,V(Fe),Fe==="valid"){const me=jd();me&&F(Sd({isDesktopShell:!0,bootOutcome:me}))}return}const Me=Math.min(ee*Math.pow(1.1,se),je);if(se>=De){const me=document.getElementById("initial-loading");me&&!me.textContent?.includes("taking longer")&&(me.textContent="Desktop startup is taking longer than expected...")}window.setTimeout(Be,Me)};return window.setTimeout(Be,ee),()=>{O=!0}},[_,$]);const Z=i.useCallback(async()=>{if(Cp({isDesktopShell:ur(),isDesktopLocalOriginActive:Ji()})){await Ap();return}window.location.reload()},[]),ke=i.useCallback(async()=>{if(!N){S(!1),B(!0);try{await ss.getState().initializeApp()}finally{B(!1)}ss.getState().isInitialized||j(O=>O+1)}},[N]),Y=O=>{if(O.screen==="recovery")return O.variant};if(_&&z&&z.screen!=="main"){if(z.screen==="chooser")return s.jsx(en,{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(Rf,{mode:"first-launch",onCliAvailable:Z,onChooseRemote:()=>{}})})})});const O=Y(z),se=z.screen==="recovery"&&"url"in z?z.url:void 0;return s.jsx(en,{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(Rf,{mode:"recovery",recoveryVariant:O,recoveryHostUrl:se,recoveryHostLabel:void 0,onCliAvailable:Z})})})})}if(te)return s.jsx(en,{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(vC,{embeddedSessionChat:te,isVSCodeRuntime:x,embeddedBackgroundWorkEnabled:q})})})})},A)});if(H)return s.jsx(en,{children:s.jsx(gC,{})});if(v&&!n&&!x&&!te)return s.jsx(en,{children:s.jsx(bC,{onRetry:()=>{ke()},isRetrying:N})});const ge=!n&&!_;return s.jsx(en,{children:s.jsx(Hd,{sdk:Jn.getSdkClient(),directory:m||"",children:s.jsx(Gd,{apis:t,children:s.jsx(Oy,{children:s.jsx(Kd,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:_?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(gm,{embeddedBackgroundWorkEnabled:q}),s.jsx(Am,{}),s.jsx(Rk,{}),s.jsx(xm,{}),!ge&&s.jsxs(s.Fragment,{children:[s.jsx(ob,{}),s.jsx(xC,{}),y&&s.jsx(Fk,{onClose:()=>g(!1)})]})]})})})})},A)})}function SC(t){return t.isAboutDialogOpen}function NC(t){return t.setAboutDialogOpen}function kC(t){return t.currentDirectory}function CC(t){return t.currentSessionId}function AC(t){return t.setCurrentSession}const DC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();Ax();Dp().then(()=>{Promise.all([Ip(),Dx()]).catch(t=>{console.error("[main] settings init failed:",t)}),Ix(),Px(),Tx()}).catch(t=>{console.error("[main] appearance init failed:",t)});const Ch=document.getElementById("root");if(!Ch)throw new Error("Root element not found");lp.createRoot(Ch).render(s.jsx(Xe.StrictMode,{children:s.jsx(Rx,{children:s.jsx(Ex,{children:s.jsx(Mx,{children:s.jsx(Fx,{children:s.jsx(jC,{apis:DC})})})})})}));const OC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{x1 as D,Nk as M,OC as m,_s as u};