@openchamber/web 1.14.1 → 1.16.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 (124) 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-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
  7. package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
  8. package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
  9. package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
  10. package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
  11. package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
  12. package/dist/assets/es-r0_jT91q.js +15 -0
  13. package/dist/assets/fr-Bo8rtAJ1.js +13 -0
  14. package/dist/assets/index-8J6waVO6.js +2 -0
  15. package/dist/assets/index-DEMqM4Lz.css +1 -0
  16. package/dist/assets/ja-BPWtkG-c.js +15 -0
  17. package/dist/assets/ko-Bv0k-0E3.js +15 -0
  18. package/dist/assets/main-B-GA5Tg5.js +237 -0
  19. package/dist/assets/main-Dfm-VKZ9.js +2 -0
  20. package/dist/assets/miniChat-CfmCFFfu.js +2 -0
  21. package/dist/assets/mobile-CXJqeDlm.js +2 -0
  22. package/dist/assets/pl-CiTP50bz.js +15 -0
  23. package/dist/assets/pt-BR-DadIjX5L.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
  25. package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
  27. package/dist/assets/uk-2RpsWGoZ.js +15 -0
  28. package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
  31. package/dist/assets/zh-TW--f_BqBpD.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 +236 -2
  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/DOCUMENTATION.md +1 -1
  41. package/server/lib/notifications/apns-runtime.js +11 -16
  42. package/server/lib/notifications/runtime.js +135 -33
  43. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  44. package/server/lib/opencode/agents.js +3 -0
  45. package/server/lib/opencode/bootstrap-runtime.js +15 -0
  46. package/server/lib/opencode/core-routes.js +321 -8
  47. package/server/lib/opencode/core-routes.test.js +329 -9
  48. package/server/lib/opencode/feature-routes-runtime.js +6 -0
  49. package/server/lib/opencode/network-runtime.js +14 -1
  50. package/server/lib/opencode/network-runtime.test.js +29 -9
  51. package/server/lib/opencode/proxy.js +47 -6
  52. package/server/lib/opencode/settings-helpers.js +24 -0
  53. package/server/lib/opencode/settings-helpers.test.js +25 -0
  54. package/server/lib/opencode/settings-normalization-runtime.js +21 -4
  55. package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
  56. package/server/lib/opencode/settings-runtime.js +25 -0
  57. package/server/lib/opencode/shutdown-runtime.js +2 -0
  58. package/server/lib/opencode/tunnel-auth.js +4 -9
  59. package/server/lib/package-manager.js +18 -5
  60. package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
  61. package/server/lib/permission-auto-accept/runtime.js +263 -0
  62. package/server/lib/permission-auto-accept/runtime.test.js +137 -0
  63. package/server/lib/projects/project-config.js +8 -0
  64. package/server/lib/quota/DOCUMENTATION.md +5 -2
  65. package/server/lib/quota/credentials/providers.js +43 -0
  66. package/server/lib/quota/credentials/store.js +48 -0
  67. package/server/lib/quota/credentials/store.test.js +26 -0
  68. package/server/lib/quota/opencode-go-credentials.js +11 -0
  69. package/server/lib/quota/opencode-go-credentials.test.js +32 -0
  70. package/server/lib/quota/providers/codex.js +7 -4
  71. package/server/lib/quota/providers/codex.test.js +48 -0
  72. package/server/lib/quota/providers/cursor.js +28 -39
  73. package/server/lib/quota/providers/index.js +7 -0
  74. package/server/lib/quota/providers/ollama-cloud.js +23 -42
  75. package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
  76. package/server/lib/quota/providers/opencode-go.js +70 -0
  77. package/server/lib/quota/providers/opencode-go.test.js +17 -0
  78. package/server/lib/quota/routes.js +78 -7
  79. package/server/lib/quota/routes.test.js +40 -0
  80. package/server/lib/relay/DOCUMENTATION.md +98 -0
  81. package/server/lib/relay/cross-compat.test.js +135 -0
  82. package/server/lib/relay/e2ee.js +341 -0
  83. package/server/lib/relay/e2ee.test.js +124 -0
  84. package/server/lib/relay/host-client.js +389 -0
  85. package/server/lib/relay/host-client.test.js +280 -0
  86. package/server/lib/relay/host-lock.js +101 -0
  87. package/server/lib/relay/host-lock.test.js +129 -0
  88. package/server/lib/relay/identity.js +93 -0
  89. package/server/lib/relay/identity.test.js +78 -0
  90. package/server/lib/relay/service.js +334 -0
  91. package/server/lib/relay/signing-key.js +73 -0
  92. package/server/lib/relay/tunnel-codec.js +373 -0
  93. package/server/lib/relay/tunnel-codec.test.js +58 -0
  94. package/server/lib/relay/tunnel-host.js +462 -0
  95. package/server/lib/scheduled-tasks/runtime.js +104 -0
  96. package/server/lib/session-goal/DOCUMENTATION.md +176 -0
  97. package/server/lib/session-goal/objectives.js +61 -0
  98. package/server/lib/session-goal/routes.js +36 -0
  99. package/server/lib/session-goal/runtime.js +764 -0
  100. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  101. package/server/lib/ui-auth/ui-auth.js +10 -0
  102. package/server/opencode-proxy.test.js +38 -0
  103. package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
  104. package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
  105. package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
  106. package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
  107. package/dist/assets/es-bWcuDy_2.js +0 -15
  108. package/dist/assets/fr-DzRs3OzV.js +0 -13
  109. package/dist/assets/index-KnWk9fmM.css +0 -1
  110. package/dist/assets/index-ZJTzZ0_U.js +0 -2
  111. package/dist/assets/ja-BqUX_UD3.js +0 -15
  112. package/dist/assets/ko-BQo10SNx.js +0 -15
  113. package/dist/assets/main-BDoqLlQB.js +0 -236
  114. package/dist/assets/main-DUGyTrDt.js +0 -2
  115. package/dist/assets/miniChat-DNDiX8GA.js +0 -2
  116. package/dist/assets/mobile-DnghtOCb.js +0 -2
  117. package/dist/assets/pl-Bgx_ATJT.js +0 -15
  118. package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
  119. package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
  120. package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
  121. package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
  122. package/dist/assets/uk-C9k8SP8q.js +0 -15
  123. package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
  124. package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
@@ -0,0 +1,237 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalView-DQcdegHp.js","assets/vendor-.bun-BE757pvp.js","assets/useAppFontEffects-DkPuAMXD.js","assets/index-8J6waVO6.js","assets/index-DEMqM4Lz.css","assets/runtimeEndpointReset-MTaPPm4F.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-CWWrCFzr.js","assets/DiagramView-he_RFVx5.js","assets/SettingsWindow-CjqLdpTE.js","assets/MultiRunWindow-B_C-tvVq.js","assets/OnboardingScreen-BBnTt-9w.js"])))=>i.map(i=>d[i]);
2
+ import{j as s,b as ht,a as co,R as i,d as Hf,p as gc,L as Kh,r as nt,N as Gf,u as ja,l as Ao,n as Sa,D as Na,q as ka,S as Hl,v as Gl,w as xc,C as bc,O as Kl,T as qh,W as Yh,X as Qh,Y as Jh,$ as hi,a0 as Xh,a1 as Zh,F as ep,a2 as tp,a3 as sp,a4 as np,a5 as Kf,a6 as rp,a7 as ip,a8 as ql,a9 as op,s as ap,m as lp,aa as vd,ab as jd,ac as Sd,ad as cp,ae as dp,af as up,ag as fp,ah as mp,ai as hp,_ as uo,aj as Nd,ak as kd,al as Cd,I as pp}from"./vendor-.bun-BE757pvp.js";import{t as wc,v as gr,w as to,x as Ad,y as gp,z as Ca,A as qf,B as xp,h as Ps,l as zo,u as Re,C as bp,D as Wa,E as _r,F as Yf,d as Xr,G as Aa,H as Qf,I as Jf,J as Zr,K as Yl,L as wp,M as yp,R as Dd,N as Td,e as Xs,O as vp,P as jp,Q as Xf,S as Zf,T as yc,o as Xn,U as Sp,b as Ii,V as Np,r as vc,W as kp,X as jc,n as em,Y as Cp,Z as Ap,a as Gi,_ as la,$ as ca,a0 as Dp,a1 as Tp,a2 as Pp,a3 as Pd,a4 as Id,a5 as Rd,a6 as Ed,a7 as Ip,f as Md,m as Fd,a8 as Rp,a9 as Ep,aa as Mp,p as Fp,q as Op}from"./index-8J6waVO6.js";import{c as yt,v as Pe,aC as ms,I as A,y as xr,t as ae,aD as Zs,aE as Vr,aF as en,aG as tn,d as Zn,aH as $r,o as ti,aI as Od,aJ as Ct,aK as At,aL as Dt,aM as Lp,ao as Oo,aN as Da,aO as pi,ap as Lo,aq as tm,al as Sc,aP as sm,aQ as Bp,Y as is,G as mt,aR as Vp,ae as nm,u as pr,E as Nc,b as Ds,Z as Fi,aS as rm,aT as im,aU as om,aV as _p,aW as $p,_ as kc,aX as Ua,aY as gi,aZ as Cc,a_ as da,a4 as on,a$ as zp,b0 as am,b1 as Wp,b2 as lm,b3 as Or,b4 as Ac,b5 as sn,b6 as Hs,B as ze,b7 as Vs,b8 as _s,b9 as bi,ba as Up,bb as Hp,bc as Yo,bd as Fn,be as cm,bf as dm,ai as Dc,bg as Gp,bh as Ld,bi as Bd,bj as Pi,w as Ln,bk as so,bl as Kp,bm as qp,bn as Yp,bo as Qp,bp as Ha,bq as Ga,br as Ka,bs as qa,bt as Qr,bu as Jr,bv as Jp,bw as Xp,bx as mn,by as Zp,bz as eg,bA as tg,bB as sg,bC as ng,p as Ri,bD as Tc,bE as rg,bF as ig,bG as og,bH as ag,bI as lg,bJ as cg,bK as dg,bL as On,bM as Gn,bN as Kn,bO as Dn,bP as qn,bQ as Bs,bR as ug,D as no,M as Ya,S as Qa,bS as fg,bT as br,bU as mg,e as wi,h as Pc,f as Ja,bV as hg,bW as um,bX as pg,bY as gg,i as Ic,bZ as xg,j as vn,b_ as Xa,aj as Lr,n as bg,b$ as wg,c0 as dl,c1 as yg,c2 as vg,F as ei,c3 as Rc,c4 as Za,c5 as fn,c6 as fo,q as Ei,c7 as fm,ah as jg,c8 as Sg,c9 as Ng,ca as kg,cb as ul,cc as Cg,z as yi,A as Vd,C as _d,cd as $d,ce as mm,cf as fl,cg as zd,ch as hm,ci as Ag,cj as pm,x as Wd,J as Dg,ck as ml,cl as Ec,cm as Tg,cn as Pg,co as Ig,cp as Rg,cq as Wo,cr as Eg,cs as hl,ct as gm,cu as xm,cv as Mc,cw as Mg,a2 as Fc,cx as ko,cy as bm,cz as Fg,r as Br,cA as Og,cB as wm,cC as Lg,cD as Bg,cE as Ud,cF as ym,cG as vm,cH as jm,cI as Vg,L as Oc,P as Lc,N as Bc,R as Ta,cJ as ds,cK as Pa,cL as Wn,cM as _g,cN as Ql,cO as $g,cP as zg,cQ as Wg,cR as Hd,cS as Ug,cT as Hg,cU as Vc,cV as Sm,cW as Gg,cX as Kg,cY as qg,cZ as Yg,c_ as Qg,c$ as Gd,d0 as Jg,d1 as Kd,d2 as qd,d3 as Xg,d4 as Zg,d5 as ex,d6 as tx,d7 as sx,d8 as nx,T as rx,d9 as Yd,da as ix,db as Nm,U as ox,aa as ax,dc as lx,H as cx,K as dx,dd as ux,de as fx,df as mx,dg as hx,dh as px,di as gx,dj as xx,dk as bx,dl as wx,dm as Ia,dn as yx,dp as Qd,dq as vx,dr as jx,ds as Sx,dt as mo,du as Nx,dv as Jd,dw as kx,dx as Cx,dy as Ax,dz as Dx,a as km,dA as Cm,dB as Tx,dC as Px,dD as Ix,dE as ua,ag as Rx,dF as Ex,dG as Xd,dH as Mx,$ as Fx,a0 as Ox,a1 as Lx,a5 as Zd,a6 as eu,a7 as tu,a8 as Am,a9 as Dm,ax as Bx,ay as Vx,az as _x,aA as $x,aB as zx,at as Wx,au as Ux,av as Hx,aw as Gx}from"./useAppFontEffects-DkPuAMXD.js";import{I as su,q as Kx,s as nu,t as qx,v as ru,w as li,x as Yx,y as pl,z as Bo,U as Ra,B as Ea,E as ro,F as Uo,G as io,n as Tm,j as Pm,l as xn,m as Qx,Q as Im,H as Jx,J as Xx,K as Zx,M as Jl,L as Rm,P as Em,R as eb,T as tb,C as sb,a as nb,V as _c,W as Mm,X as $c,Y as zc,Z as Wc,_ as Fm,$ as Om,a0 as Xl,a1 as Lm,a2 as Zl,a3 as fa,a4 as rb,a5 as ib,a6 as ob,u as Do,N as ab,D as lb,a7 as iu,a8 as cb,d as db,o as ub,i as ec,a9 as fb,aa as mb,h as hb,ab as pb,ac as gb,c as xb,e as bb,O as Bm,f as wb,ad as yb}from"./runtimeEndpointReset-MTaPPm4F.js";import{S as vb,C as jb,W as Sb,c as Uc,g as Hc,r as Nb,i as oo,d as ao,a as Qi,n as ou,b as kb,e as To,f as Vm,h as Cb,j as Ab,u as gl}from"./SessionSwitcherDropdown-CWWrCFzr.js";function _m(t){const{drafts:e,editingDraftId:n,commentText:r,onTextChange:o,selection:a,isDragging:c,fileLabel:l,newWidgetId:d,mapDraftToRange:f,onSave:m,onCancel:u,onEdit:p,onDelete:x}=t,b=[];for(const w of e){const g=f(w);if(w.id===n){b.push({afterLine:g.end,id:`edit-${w.id}`,content:s.jsx(su,{initialText:r,onTextChange:o,fileLabel:l,lineRange:g,isEditing:!0,onSave:m,onCancel:u},`edit-${w.id}`)});continue}b.push({afterLine:g.end,id:`card-${w.id}`,content:s.jsx(Kx,{draft:w,onEdit:()=>p(w),onDelete:()=>x(w)},`card-${w.id}`)})}if(a&&!n&&!c){const w={...a,start:Math.min(a.start,a.end),end:Math.max(a.start,a.end)};b.push({afterLine:w.end,id:d,content:s.jsx(su,{initialText:r,onTextChange:o,fileLabel:l,lineRange:w,isEditing:!1,onSave:m,onCancel:u},d)})}return b}function au(t){const e=ht.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const c=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let d;e[5]!==a||e[6]!==c||e[7]!==l?(d={width:c,height:l,...a},e[5]=a,e[6]=c,e[7]=l,e[8]=d):d=e[8];let f;e[9]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"}),e[9]=f):f=e[9];let m;return e[10]!==n||e[11]!==r||e[12]!==d?(m=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:d,...r,children:f}),e[10]=n,e[11]=r,e[12]=d,e[13]=m):m=e[13],m}const xi=[{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:"vscode-insiders",label:"VS Code Insiders",appName:"Visual Studio Code - Insiders"},{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"}],tc="finder",sc=new Set(["finder","terminal"]),Gc=t=>typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32"&&t.id==="finder"?{...t,label:"Explorer",appName:"File Explorer"}:t,nc=t=>{if(!t)return null;const e=xi.find(n=>n.id===t)??null;return e?Gc(e):null},xl=()=>xi.filter(t=>sc.has(t.id)).map(t=>({...Gc(t)})),Db=()=>{if(typeof window>"u")return tc;const t=window.localStorage.getItem("openInAppId");return t&&nc(t)?t:tc};let bl=!1,zi=!1,ci=!1,di=0,Po=null;const lu=()=>{Po&&(clearTimeout(Po),Po=null)},Cr=co()((t,e)=>({selectedAppId:Db(),availableApps:xl(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(bl||typeof window>"u")return;bl=!0;const n=(d,f=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:xl(),hasLoadedApps:f});return}const m=new Set(d.map(b=>b.name)),u=new Map(d.map(b=>[b.name,b.iconDataUrl??void 0])),x=xi.filter(b=>m.has(b.appName)||sc.has(b.id)).map(b=>({...Gc(b),iconDataUrl:u.get(b.appName)}));t({availableApps:x,hasLoadedApps:!0})},r=async d=>{if(!gr()||!to()||zi||e().hasLoadedApps&&!d)return;const m=xi.map(u=>u.appName);lu(),zi=!0,ci=!1,t({isScanning:!0});try{const{apps:u,success:p,hasCache:x,isCacheStale:b}=await Ad(m,d),w=p&&!x&&u.length===0&&di<3;if(t({isCacheStale:x?b:!1}),n(u,p?!w:!1),p){if(w){const h=[800,1600,3200][di]??3200;di+=1,ci=!0,Po=setTimeout(()=>{r()},h);return}di=0,ci=!1;return}if(di<3){const h=[1e3,3e3,7e3][di]??7e3;di+=1,ci=!0,Po=setTimeout(()=>{r()},h)}}finally{zi=!1,ci||t({isScanning:!1})}};r();const o=d=>{const f=d.detail,m=f&&typeof f.openInAppId=="string"&&f.openInAppId.length>0&&nc(f.openInAppId)?f.openInAppId:null;m&&(window.localStorage.setItem("openInAppId",m),t({selectedAppId:m}))},a=()=>{r()},c=d=>{const f=d.detail;Array.isArray(f)&&(di=3,ci=!1,t({isScanning:!1,isCacheStale:!1}),n(f))};window.addEventListener("openchamber:settings-synced",o),window.addEventListener("openchamber:app-ready",a),window.addEventListener("openchamber:installed-apps-updated",c),window.__openchamberAppReady&&r(),window.setTimeout(()=>{e().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(bl||e().initialize(),!gr()||!to()||zi||e().hasLoadedApps&&!n)return;const o=xi.map(a=>a.appName);lu(),n&&t({hasLoadedApps:!1}),zi=!0,ci=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await Ad(o,n),d=new Set(a.map(p=>p.name)),f=new Map(a.map(p=>[p.name,p.iconDataUrl??void 0])),u=xi.filter(p=>d.has(p.appName)||sc.has(p.id)).map(p=>({...p,iconDataUrl:f.get(p.appName)}));t({availableApps:u.length>0?u:xl(),hasLoadedApps:u.length>0,isCacheStale:c?l:!1})}finally{zi=!1,ci||t({isScanning:!1})}},selectApp:async n=>{nc(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await wc({openInAppId:n}))}})),Tb="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",Pb="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",wl=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__OPENCHAMBER_PLATFORM__!=="win32"?Tb:t.id==="terminal"?Pb:void 0}),cu=t=>{const e=ht.c(8),{label:n,iconDataUrl:r,fallbackIconDataUrl:o}=t,[a,c]=i.useState(!1);let l;e[0]!==n?(l=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=l):l=e[1];const d=l,f=r||o;if(f&&!a){let p;e[2]===Symbol.for("react.memo_cache_sentinel")?(p=()=>c(!0),e[2]=p):p=e[2];let x;return e[3]!==f?(x=s.jsx("img",{src:f,alt:"",className:"h-4 w-4 rounded-sm",onError:p}),e[3]=f,e[4]=x):x=e[4],x}let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=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 u;return e[6]!==d?(u=s.jsx("span",{className:m,children:d}),e[6]=d,e[7]=u):u=e[7],u},Ib=t=>{const e=ht.c(75),{directory:n,className:r}=t,{t:o}=yt(),a=Cr(Rb),c=Cr(Eb),l=Cr(Mb),d=Cr(Fb),f=Cr(Ob),m=Cr(Lb),u=Cr(Bb);let p,x;e[0]!==f?(p=()=>{f()},x=[f],e[0]=f,e[1]=p,e[2]=x):(p=e[1],x=e[2]),i.useEffect(p,x);const b=gr()&&to();let w;e:{let we;e[3]!==c||e[4]!==a?(we=c.find(z=>z.id===a)??c.find(Vb)??c[0]??xi[0],e[3]=c,e[4]=a,e[5]=we):we=e[5];const he=we;if(he){let z;e[6]!==he?(z=wl(he),e[6]=he,e[7]=z):z=e[7],w=z;break e}let Me;e[8]===Symbol.for("react.memo_cache_sentinel")?(Me=wl(xi[0]),e[8]=Me):Me=e[8],w=Me}const g=w;if(!b||!n||c.length===0)return null;let h;e[9]!==n?(h=async we=>{await gp(n,we.id,we.appName)||await Ca(n,we.appName)},e[9]=n,e[10]=h):h=e[10];const C=h;let j;e[11]!==C||e[12]!==u?(j=async we=>{await u(we.id),await C(we)},e[11]=C,e[12]=u,e[13]=j):j=e[13];const S=j;let N;e[14]!==n||e[15]!==o?(N=async()=>{(await xr(n)).ok&&ae.success(o("openInApp.toast.pathCopied"))},e[14]=n,e[15]=o,e[16]=N):N=e[16];const k=N;let y;e[17]!==r?(y=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]=y):y=e[18];let D;e[19]!==C||e[20]!==g?(D=()=>{C(g)},e[19]=C,e[20]=g,e[21]=D):D=e[21];const V=d&&"animate-pulse";let v;e[22]!==V?(v=Pe("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",V),e[22]=V,e[23]=v):v=e[23];let O;e[24]!==g.label||e[25]!==o?(O=o("openInApp.actions.openInAria",{app:g.label}),e[24]=g.label,e[25]=o,e[26]=O):O=e[26];let P;e[27]!==g.fallbackIconDataUrl||e[28]!==g.iconDataUrl||e[29]!==g.label?(P=s.jsx(cu,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:g.fallbackIconDataUrl}),e[27]=g.fallbackIconDataUrl,e[28]=g.iconDataUrl,e[29]=g.label,e[30]=P):P=e[30];let E;e[31]!==v||e[32]!==O||e[33]!==P||e[34]!==D?(E=s.jsx("button",{type:"button",onClick:D,className:v,"aria-label":O,children:P}),e[31]=v,e[32]=O,e[33]=P,e[34]=D,e[35]=E):E=e[35];let B;e[36]===Symbol.for("react.memo_cache_sentinel")?(B=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]=B):B=e[36];let T;e[37]!==o?(T=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=T):T=e[38];let W;e[39]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=W):W=e[39];let U;e[40]!==T?(U=s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:B,"aria-label":T,children:W})}),e[40]=T,e[41]=U):U=e[41];let L;e[42]!==k?(L=()=>{k()},e[42]=k,e[43]=L):L=e[43];let M;e[44]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(A,{name:"file-copy",className:"h-4 w-4"}),e[44]=M):M=e[44];let ee;e[45]!==o?(ee=o("openInApp.actions.copyPath"),e[45]=o,e[46]=ee):ee=e[46];let ie;e[47]!==ee?(ie=s.jsx("span",{className:"typography-ui-label text-foreground",children:ee}),e[47]=ee,e[48]=ie):ie=e[48];let X;e[49]!==L||e[50]!==ie?(X=s.jsxs(ms,{className:"flex items-center gap-2",onClick:L,children:[M,ie]}),e[49]=L,e[50]=ie,e[51]=X):X=e[51];let H;e[52]===Symbol.for("react.memo_cache_sentinel")?(H=s.jsx(Vr,{}),e[52]=H):H=e[52];let te;if(e[53]!==c||e[54]!==S||e[55]!==g.id){let we;e[57]!==S||e[58]!==g.id?(we=he=>{const Me=wl(he);return s.jsxs(ms,{className:"flex items-center gap-2",onClick:()=>{S(he)},children:[s.jsx(cu,{label:he.label,iconDataUrl:he.iconDataUrl,fallbackIconDataUrl:Me.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:he.label}),g.id===he.id?s.jsx(A,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},he.id)},e[57]=S,e[58]=g.id,e[59]=we):we=e[59],te=c.map(we),e[53]=c,e[54]=S,e[55]=g.id,e[56]=te}else te=e[56];let re;e[60]!==l||e[61]!==m||e[62]!==o?(re=l?s.jsxs(ms,{className:"flex items-center gap-2",onClick:()=>{m(!0)},children:[s.jsx(A,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:o("openInApp.actions.refreshApps")})]}):null,e[60]=l,e[61]=m,e[62]=o,e[63]=re):re=e[63];let le;e[64]!==X||e[65]!==te||e[66]!==re?(le=s.jsxs(en,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[X,H,te,re]}),e[64]=X,e[65]=te,e[66]=re,e[67]=le):le=e[67];let ve;e[68]!==U||e[69]!==le?(ve=s.jsxs(tn,{children:[U,le]}),e[68]=U,e[69]=le,e[70]=ve):ve=e[70];let ne;return e[71]!==E||e[72]!==ve||e[73]!==y?(ne=s.jsxs("div",{className:y,children:[E,ve]}),e[71]=E,e[72]=ve,e[73]=y,e[74]=ne):ne=e[74],ne};function Rb(t){return t.selectedAppId}function Eb(t){return t.availableApps}function Mb(t){return t.isCacheStale}function Fb(t){return t.isScanning}function Ob(t){return t.initialize}function Lb(t){return t.loadInstalledApps}function Bb(t){return t.selectApp}function Vb(t){return t.id===tc}const _b=1e6,$b="terminal-store";let du=!1;const yl=t=>typeof t=="object"&&t!==null,zb=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function En(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const vl=(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}),jl=t=>({tabs:[t],activeTabId:t.id}),Nr=(t,e)=>t.tabs.findIndex(n=>n.id===e),Us=co()(Hf(gc((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=En(n);r&&t(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),c=`tab-${o.nextTabId}`,l=vl(c,"Terminal");return a.set(r,jl(l)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=En(n);return e().sessions.get(r)},getActiveTab:n=>{const r=En(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=En(n);if(!r)return"tab-invalid";const o=`tab-${e().nextTabId}`;return t(a=>{const c=new Map(a.sessions),l=c.get(r),d=a.nextTabId+1,m=`Terminal ${(l?.tabs.length??0)+1}`,u=vl(o,m);return l?c.set(r,{...l,tabs:[...l.tabs,u]}):c.set(r,jl(u)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=En(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);return!l||l.activeTabId===r||Nr(l,r)<0?a:(c.set(o,{...l,activeTabId:r}),{sessions:c})})},setTabLabel:(n,r,o)=>{const a=En(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),f=d.get(a);if(!f)return l;const m=Nr(f,r);if(m<0||f.tabs[m]?.label===c)return l;const u=[...f.tabs];return u[m]={...u[m],label:c},d.set(a,{...f,tabs:u}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=En(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=Nr(d,r);if(f<0)return c;const m=o?.trim()||null;if(d.tabs[f]?.iconKey===m)return c;const u=[...d.tabs];return u[f]={...u[f],iconKey:m},l.set(a,{...d,tabs:u}),{sessions:l}})},closeTab:async(n,r)=>{const o=En(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await xp(l)}catch{}t(d=>{const f=new Map(d.sessions),m=f.get(o);if(!m)return d;const u=Nr(m,r);if(u<0)return d;const p=m.tabs.filter(g=>g.id!==r),x=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,g])=>!(g.directory===o&&g.tabId===r))),b=Object.keys(x).length!==Object.keys(d.projectActionRuns).length;if(p.length===0){const g=`tab-${d.nextTabId}`,h=vl(g,"Terminal");return f.set(o,jl(h)),{sessions:f,nextTabId:d.nextTabId+1,...b?{projectActionRuns:x}:{}}}let w=m.activeTabId;return m.activeTabId===r&&(w=p[Math.min(u,p.length-1)]?.id??p[0]?.id??null),f.set(o,{...m,tabs:p,activeTabId:w}),{sessions:f,...b?{projectActionRuns:x}:{}}})},setTabSessionId:(n,r,o)=>{const a=En(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=Nr(d,r);if(f<0)return c;const m=d.tabs[f],u=o!==null&&m.terminalSessionId!==o,p=o?"running":m.terminalSessionId?"exited":m.lifecycle,x={...m,terminalSessionId:o,lifecycle:p,isConnecting:!1,...u?{bufferChunks:[],bufferLength:0}:{}},b=[...d.tabs];return b[f]=x,l.set(a,{...d,tabs:b}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=En(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=Nr(d,r);if(f<0)return c;const m=[...d.tabs];return m[f]={...m[f],lifecycle:o,isConnecting:!1},l.set(a,{...d,tabs:m}),{sessions:l}})},setConnecting:(n,r,o)=>{const a=En(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=Nr(d,r);if(f<0)return c;const m=[...d.tabs];return m[f]={...m[f],isConnecting:o},l.set(a,{...d,tabs:m}),{sessions:l}})},appendToBuffer:(n,r,o)=>{if(!o)return;const a=En(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=Nr(d,r);if(f<0)return c;const m=d.tabs[f],u=c.nextChunkId,p={id:u,data:o},x=[...m.bufferChunks,p];let b=m.bufferLength+o.length;for(;b>_b&&x.length>1;){const g=x.shift();if(!g)break;b-=g.data.length}const w=[...d.tabs];return w[f]={...m,bufferChunks:x,bufferLength:b},l.set(a,{...d,tabs:w}),{sessions:l,nextChunkId:u+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=En(n);t(l=>{const d=new Map(l.sessions),f=d.get(c);if(!f)return l;const m=Nr(f,r);if(m<0)return l;const u=f.tabs[m],p=a.autoOpened??u.previewAutoOpened,x=a.locked??u.previewUrlLocked;if(u.previewUrl===o&&u.previewAutoOpened===p&&u.previewUrlLocked===x)return l;const b=[...f.tabs];return b[m]={...u,previewUrl:o,previewAutoOpened:p,previewUrlLocked:x},d.set(c,{...f,tabs:b}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=En(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=Nr(l,r);if(d<0)return a;const f=l.tabs[d];if(!f.previewUrl||f.previewAutoOpened)return a;const m=[...l.tabs];return m[d]={...f,previewAutoOpened:!0},c.set(o,{...l,tabs:m}),{sessions:c}})},setProjectActionRun:n=>{t(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{t(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{t(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},clearBuffer:(n,r)=>{const o=En(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=Nr(l,r);if(d<0)return a;const f=[...l.tabs];return f[d]={...f[d],bufferChunks:[],bufferLength:0},c.set(o,{...l,tabs:f}),{sessions:c}})},removeDirectory:n=>{const r=En(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:$b,storage:Kh(()=>qf()),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(!yl(t))return e;const n=Array.isArray(t.sessions)?t.sessions:[],r=new Map;let o=0;for(const l of n){if(!Array.isArray(l)||l.length!==2)continue;const[d,f]=l;if(typeof d!="string"||!yl(f))continue;const m=Array.isArray(f.tabs)?f.tabs:[],u=[];for(const b of m){if(!yl(b))continue;const w=typeof b.id=="string"?b.id:null;if(!w)continue;const g=zb(w);g!==null&&(o=Math.max(o,g));const h=typeof b.terminalSessionId=="string"||b.terminalSessionId===null?b.terminalSessionId:null,C=b.lifecycle,j=C==="idle"||C==="running"||C==="exited"?C:h?"running":"idle";u.push({id:w,label:typeof b.label=="string"?b.label:"Terminal",iconKey:typeof b.iconKey=="string"?b.iconKey:null,terminalSessionId:h,lifecycle:j,createdAt:typeof b.createdAt=="number"?b.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(u.length===0)continue;const p=typeof f.activeTabId=="string"?f.activeTabId:null,x=p?u.some(b=>b.id===p):!1;r.set(d,{tabs:u,activeTabId:x?p:u[0].id})}const a=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,c=Math.max(e.nextTabId,a,o+1);return{...e,sessions:r,nextChunkId:1,nextTabId:c,hasHydrated:!0}}})));if(typeof window<"u"&&!du){du=!0;const t=Us.persist,e=()=>{Us.getState().hasHydrated||Us.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const Wb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Ub=["dev","start","preview","serve"];async function Hb(t,e,n){if(!t)return null;const r=qb(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=Yb(n);if(o){const a=await Qb(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 Gb(t)){const o=await Kb(),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 Gb(t){const e=`${t}/index.html`,n=await Ma(e,t);return typeof n=="string"&&n.trim().length>0}async function Kb(){try{const t=await Ps("/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 qb(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(Ub.some(o=>n.includes(o)))return e}return null}function Yb(t){for(const{pattern:e}of Wb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function Qb(t){const e=await Ma(`${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 Ma(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Ma(t,e){if(e?.trim())try{const r=new URLSearchParams({path:t,directory:e,optional:"true"}),o=await Ps(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=zo()?.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 Ps(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Jb(t){try{const e=await Ma(`${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 Xb=t=>new Promise(e=>{window.setTimeout(e,t)}),Zb="\x1B",ew=new RegExp(`${Zb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),tw=/https?:\/\/[^\s<>'"`]+/gi,ir="__openchamber_auto_discover_preview__",sw=15e3,nw=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},rw=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}},iw=t=>{const n=t.replace(ew,"").match(tw);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const c=new URL(a);c.port&&c.port.length>0&&o.push({raw:a,parsed:c})}catch{}if(o.length>0){const a=c=>{const{parsed:l}=c,d=l.hostname.toLowerCase(),f=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",m=l.pathname||"/",u=m.split("/").filter(Boolean).length,p=m==="/"||m==="",x=!!(l.search||l.hash);let b=0;return f&&(b+=50),p&&(b+=30),b-=Math.min(u*5,20),x&&(b-=10),b};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},$m=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=yt(),{terminal:c,runtime:l}=Zn(),{isMobile:d}=$r(),f=i.useMemo(()=>gr(),[]),m=nu(R=>R.instances),u=nu(R=>R.load),p=Re(R=>R.setBottomTerminalOpen),x=Re(R=>R.setActiveMainTab),b=Re(R=>R.setSettingsPage),w=Re(R=>R.setSettingsDialogOpen),g=Re(R=>R.setSettingsProjectsSelectedId),h=Re(R=>R.openContextPreview),C=Us(R=>R.sessions),j=Us(R=>R.ensureDirectory),S=Us(R=>R.setTabLabel),N=Us(R=>R.setTabIconKey),k=Us(R=>R.setActiveTab),y=Us(R=>R.setConnecting),D=Us(R=>R.setTabSessionId),V=Us(R=>R.setTabPreviewUrl),v=Us(R=>R.projectActionRuns),O=Us(R=>R.setProjectActionRun),P=Us(R=>R.updateProjectActionRunStatus),E=Us(R=>R.removeProjectActionRun),[B,T]=i.useState([]),[W,U]=i.useState(null),[L,M]=i.useState(!1),ee=i.useRef({}),ie=i.useRef({}),X=i.useRef({}),H=i.useRef({}),te=i.useRef(0),re=t?.id??null,le=t?.path??"",ve=i.useMemo(()=>re?{id:re,path:le}:null,[re,le]);i.useEffect(()=>{f&&u().catch(()=>{})},[f,u]);const ne=i.useCallback(async R=>{await ti(R)},[]),we=i.useCallback(async()=>{if(!ve)return;const R=te.current+1;te.current=R,M(!0);try{const de=await Od(ve);if(te.current!==R)return;const fe=de.actions;T(fe),U($=>$===ir||$&&fe.some(Ae=>Ae.id===$)?$:null)}catch{if(te.current!==R)return}finally{te.current===R&&M(!1)}},[ve]),he=i.useMemo(()=>qx(e||ve?.path||""),[e,ve?.path]),Me=i.useMemo(()=>W?B.find(R=>R.id===W)??null:null,[B,W]),z=i.useMemo(()=>({id:ir,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),K=!d,q=i.useMemo(()=>K?[z,...B]:B,[B,z,K]);i.useEffect(()=>{we()},[we]),i.useEffect(()=>{if(typeof window>"u")return;const R=de=>{const fe=de.detail;re&&(fe?.projectId&&fe.projectId!==re||we())};return window.addEventListener(ru,R),()=>{window.removeEventListener(ru,R)}},[we,re]),i.useEffect(()=>{W&&(W===ir&&K||B.some(R=>R.id===W)||U(null))},[B,K,W]),i.useEffect(()=>{for(const[R,de]of Object.entries(v)){const $=C.get(de.directory)?.tabs.find(Ae=>Ae.id===de.tabId);(!$||$.terminalSessionId!==de.sessionId)&&E(R)}},[v,E,C]),i.useEffect(()=>{for(const[R,de]of Object.entries(v)){const fe=ie.current[R]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};ie.current[R]=fe;const $=q.find(ce=>ce.id===de.actionId);if(!$)continue;const Ve=C.get(de.directory)?.tabs.find(ce=>ce.id===de.tabId);if(!Ve||!Array.isArray(Ve.bufferChunks)||Ve.bufferChunks.length===0)continue;const Ne=Ve.bufferChunks.filter(ce=>fe.lastSeenChunkId===null?!0:ce.id>fe.lastSeenChunkId);if(Ne.length===0)continue;const Y=Ne.map(ce=>ce.data).join(""),F=`${fe.tail}${Y}`,se=!fe.openedUrl&&$.autoOpenUrl===!0?iw(F):null,Oe=Ne[Ne.length-1]?.id??fe.lastSeenChunkId;if(fe.lastSeenChunkId=Oe,fe.tail=F.slice(-512),se)if(fe.openedUrl=!0,fe.openInPreview){const ce=v[R];ce&&(V(ce.directory,ce.tabId,se,{locked:!1,autoOpened:!1}),ce.status==="waiting-for-preview"&&P(R,"running"),window.clearTimeout(H.current[R]),delete H.current[R],h(ce.directory,se))}else ne(se),ae.success(a("projectActions.toast.openedUrlFromOutput"));ie.current[R]=fe}for(const R of Object.keys(ie.current))v[R]||(delete ie.current[R],window.clearTimeout(H.current[R]),delete H.current[R])},[q,h,ne,v,V,a,C,P]);const me=i.useCallback(async(R,de={})=>{if(!he)throw new Error(a("projectActions.error.noActiveDirectory"));const fe=li(he,R.id);j(he);const $=Us.getState(),Ae=$.getDirectoryState(he);let Ve=ee.current[fe]||null;const Ne=Ve?!!Ae?.tabs.some(se=>se.id===Ve):!1;(!Ve||!Ne)&&(Ve=$.createTab(he),ee.current[fe]=Ve),S(he,Ve,`Action: ${R.name}`),N(he,Ve,R.icon||"play"),de.revealTerminal!==!1&&(k(he,Ve),p(!0),x("terminal"));const F=Us.getState().getDirectoryState(he)?.tabs.find(se=>se.id===Ve);return{key:fe,tabId:Ve,sessionId:F?.terminalSessionId??null}},[j,he,x,k,p,N,S,a]),Se=i.useCallback(async R=>{if(l.isVSCode||!o&&d)return;if(!he){ae.error(a("projectActions.error.noActiveDirectoryForAction"));return}const de=li(he,R.id),fe=v[de];if(!(fe&&fe.status==="running"))try{const $=R.id===ir?await(async()=>{const[Ye,tt]=await Promise.all([Od({id:ve?.id??"",path:he}),Jb(he)]),xt=await Hb(he,Ye.actions,tt);if(!xt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:ir,name:a("projectActions.actions.autoDiscover"),command:xt.command,icon:"search",autoOpenUrl:!0,openUrl:xt.previewUrlHint||""}})():R,Ae=$.autoOpenUrl===!0&&($.openUrl||"").trim().length>0,{key:Ve,tabId:Ne,sessionId:Y}=await me($,{revealTerminal:!Ae&&R.id!==ir});let F=Y,se=!1;if(!F){y(he,Ne,!0);try{F=(await c.createSession({cwd:he})).sessionId,se=!0,D(he,Ne,F)}finally{y(he,Ne,!1)}}if(!F)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));se&&await Xb(350),$.id===ir&&(X.current[Ve]?.(),y(he,Ne,!0),X.current[Ve]=bp(F,Ye=>{Ye.type==="data"&&typeof Ye.data=="string"&&Ye.data.length>0&&Us.getState().appendToBuffer(he,Ne,Ye.data),Ye.type==="exit"&&(Us.getState().setTabLifecycle(he,Ne,"exited"),Us.getState().setConnecting(he,Ne,!1),Us.getState().removeProjectActionRun(Ve),delete ie.current[Ve],X.current[Ve]?.(),delete X.current[Ve],window.clearTimeout(H.current[Ve]),delete H.current[Ve])},()=>{Us.getState().setConnecting(he,Ne,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const Oe=$.autoOpenUrl===!0&&f&&($.desktopOpenSshForward||"").trim().length>0,ce=$.autoOpenUrl?rw($.openUrl):null,Ue=$.autoOpenUrl&&f?Yx($.desktopOpenSshForward,m):null;O({key:Ve,directory:he,actionId:$.id,tabId:Ne,sessionId:F,status:$.id===ir&&!ce?"waiting-for-preview":"running"}),window.clearTimeout(H.current[Ve]),delete H.current[Ve],$.id===ir&&!ce&&(H.current[Ve]=window.setTimeout(()=>{Us.getState().updateProjectActionRunStatus(Ve,"running"),delete H.current[Ve]},sw)),Ue?(V(he,Ne,null,{locked:!0}),ne(Ue),ae.success(a("projectActions.toast.openedForwardedUrl"))):ce?(V(he,Ne,ce,{locked:!0,autoOpened:!0}),h(he,ce),ae.success(a("projectActions.toast.openedActionUrl"))):Ae?(V(he,Ne,null,{locked:!0}),ae.error(a("projectActions.error.invalidCustomUrlFormat"))):Oe?(V(he,Ne,null,{locked:!0}),ae.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):V(he,Ne,null,{locked:!1,autoOpened:!1}),ie.current[Ve]={lastSeenChunkId:null,openedUrl:!!Ue||!!ce||Ae,tail:"",openInPreview:$.id===ir};const qe=nw($.command.trim().replace(/\r\n|\r/g,`
3
+ `));await c.sendInput(F,`${qe}\r`)}catch($){E(de),delete ie.current[de],X.current[de]?.(),delete X.current[de],window.clearTimeout(H.current[de]),delete H.current[de],ae.error($ instanceof Error?$.message:a("projectActions.error.failedToRunAction"))}},[m,me,o,d,f,he,ne,h,v,l.isVSCode,E,y,O,V,D,ve?.id,a,c]),Be=i.useCallback(async R=>{const de=li(he,R.id),fe=v[de];if(!fe)return;P(de,"stopping");try{await c.sendInput(fe.sessionId,"")}catch{}if(await new Promise(Ve=>{window.setTimeout(Ve,1e3)}),Us.getState().getDirectoryState(fe.directory)?.tabs.find(Ve=>Ve.id===fe.tabId)?.terminalSessionId===fe.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:fe.sessionId})}catch{}else try{await c.close(fe.sessionId)}catch{}D(fe.directory,fe.tabId,null)}E(de),delete ie.current[de],X.current[de]?.(),delete X.current[de],window.clearTimeout(H.current[de]),delete H.current[de]},[he,v,E,D,c,P]),_e=i.useCallback(()=>{const R=Me??q[0];if(!R)return;const de=li(he,R.id),fe=v[de];if(fe?.status!=="stopping"){if(fe){Be(R);return}Se(R)}},[q,he,Se,v,Me,Be]),Le=i.useCallback((R,de=!1)=>{if(U(R.id),!de){Se(R);return}const fe=li(he,R.id),$=v[fe];if($?.status!=="stopping"){if($){Be(R);return}Se(R)}},[he,Se,v,Be]),pe=i.useCallback(()=>{ve?.id&&(g(ve.id),b("projects"),w(!0))},[w,b,g,ve?.id]);if(l.isVSCode||!o&&d||!ve||!he)return null;const Ee=Me??q[0]??null;if(!Ee)return null;const ge=Ee.icon||"play",oe=Ee.id===ir?"search":pl[ge]||"play",je=li(he,Ee.id),ye=v[je],ue=ye?.status==="stopping",De=ye?.status==="waiting-for-preview",I=ye?C.get(ye.directory)?.tabs.find(R=>R.id===ye.tabId)?.previewUrl??null:null,_=!!(ye&&I),be=()=>{!ye||!I||h(ye.directory,I)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:L||ue,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:_e,"aria-label":ye?a("projectActions.actions.stopNamedAria",{name:Ee.name}):a("projectActions.actions.runNamedAria",{name:Ee.name}),children:ue||De?s.jsx(A,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):ye?s.jsx(A,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(A,{name:oe,className:"h-5 w-5"})}),_?s.jsxs(Ct,{children:[s.jsx(At,{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:be,children:s.jsx(A,{name:"global",className:"h-4 w-4"})})}),s.jsx(Dt,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":a("projectActions.actions.chooseActionAria"),children:s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(en,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ms,{className:"flex items-center gap-2",onClick:pe,children:[s.jsx(A,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Vr,{}),q.map(R=>{const de=R.icon||"play",fe=R.id===ir?"search":pl[de]||"play",$=li(he,R.id),Ae=v[$],Ve=!!Ae,Ne=Ae?.status==="stopping";return s.jsxs(ms,{className:"flex items-center gap-2",onClick:()=>{Le(R,!0)},children:[s.jsx(A,{name:fe,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:R.name}),Ne||Ae?.status==="waiting-for-preview"?s.jsx(A,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Ve?s.jsx(A,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},R.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:_e,disabled:L||ue,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":ye?a("projectActions.actions.stopNamedAria",{name:Ee.name}):a("projectActions.actions.runNamedAria",{name:Ee.name}),children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:ue||De?s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):ye?s.jsx(A,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(A,{name:oe,className:"h-4 w-4"})})}),_?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:be,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(A,{name:"global",className:"h-4 w-4"})})}),s.jsx(Dt,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(tn,{children:[s.jsx(Zs,{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(A,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(en,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ms,{className:"flex items-center gap-2",onClick:pe,children:[s.jsx(A,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Vr,{}),q.map(R=>{const de=R.icon||"play",fe=R.id===ir?"search":pl[de]||"play",$=li(he,R.id),Ae=v[$],Ve=!!Ae,Ne=Ae?.status==="stopping";return s.jsxs(ms,{className:"flex items-center gap-2",onClick:()=>{Le(R,!0)},children:[s.jsx(A,{name:fe,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:R.name}),Ne||Ae?.status==="waiting-for-preview"?s.jsx(A,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Ve?s.jsx(A,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},R.id)})]})]})]})},el="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",ow="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",Qo=i.memo(function(e){const n=ht.c(17),{visible:r,title:o,ariaLabel:a,onClick:c,className:l,Icon:d,iconClassName:f,pressed:m}=e,u=r===void 0?!0:r,p=m===void 0?!1:m;if(!u)return null;const x=l??el,b=p&&"bg-interactive-selection text-interactive-selection-foreground";let w;n[0]!==x||n[1]!==b?(w=Pe(x,b),n[0]=x,n[1]=b,n[2]=w):w=n[2];const g=f??"h-[18px] w-[18px]";let h;n[3]!==d||n[4]!==g?(h=s.jsx(A,{name:d,className:g}),n[3]=d,n[4]=g,n[5]=h):h=n[5];let C;n[6]!==a||n[7]!==c||n[8]!==p||n[9]!==w||n[10]!==h?(C=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,"aria-label":a,"aria-pressed":p,className:w,children:h})}),n[6]=a,n[7]=c,n[8]=p,n[9]=w,n[10]=h,n[11]=C):C=n[11];let j;n[12]!==o?(j=s.jsx(Dt,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=j):j=n[13];let S;return n[14]!==C||n[15]!==j?(S=s.jsxs(Ct,{children:[C,j]}),n[14]=C,n[15]=j,n[16]=S):S=n[16],S}),aw=i.memo(function(e){const n=ht.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:f}=e,{t:m}=yt();if(!o?.connected||r)return null;if(a.length>1){let b;n[0]===Symbol.for("react.memo_cache_sentinel")?(b=Pe(el,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),n[0]=b):b=n[0];let w;n[1]!==l||n[2]!==m?(w=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[1]=l,n[2]=m,n[3]=w):w=n[3];let g;n[4]!==c||n[5]!==l||n[6]!==m?(g=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(A,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=m,n[7]=g):g=n[7];let h;n[8]!==d||n[9]!==w||n[10]!==g?(h=s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:b,title:w,disabled:d,children:g})}),n[8]=d,n[9]=w,n[10]=g,n[11]=h):h=n[11];let C;n[12]!==m?(C=m("header.github.accountsTitle"),n[12]=m,n[13]=C):C=n[13];let j;n[14]!==C?(j=s.jsx(Bp,{className:"typography-ui-header font-semibold text-foreground",children:C}),n[14]=C,n[15]=j):j=n[15];let S;n[16]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(Vr,{}),n[16]=S):S=n[16];let N;if(n[17]!==a||n[18]!==f||n[19]!==d||n[20]!==m){let D;n[22]!==f||n[23]!==d||n[24]!==m?(D=V=>{const v=V.user,O=!!V.current,P=V.source==="gh-cli"?m("header.github.accountSource.cli"):m("header.github.accountSource.oauth");return s.jsxs(ms,{className:"gap-2",disabled:d,onSelect:()=>{O||f(V.id)},children:[v?.avatarUrl?s.jsx("img",{src:v.avatarUrl,alt:v.login?m("header.github.avatarWithLogin",{login:v.login}):m("header.github.avatar"),className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:s.jsx(A,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:v?.name?.trim()||v?.login||"GitHub"}),v?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:v.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:P})]}):null]}),O?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]},V.id)},n[22]=f,n[23]=d,n[24]=m,n[25]=D):D=n[25],N=a.map(D),n[17]=a,n[18]=f,n[19]=d,n[20]=m,n[21]=N}else N=n[21];let k;n[26]!==j||n[27]!==N?(k=s.jsxs(en,{align:"end",className:"w-64",children:[j,S,N]}),n[26]=j,n[27]=N,n[28]=k):k=n[28];let y;return n[29]!==h||n[30]!==k?(y=s.jsxs(tn,{children:[h,k]}),n[29]=h,n[30]=k,n[31]=y):y=n[31],y}let u;n[32]!==l||n[33]!==m?(u=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[32]=l,n[33]=m,n[34]=u):u=n[34];let p;n[35]!==c||n[36]!==l||n[37]!==m?(p=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(A,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[35]=c,n[36]=l,n[37]=m,n[38]=p):p=n[38];let x;return n[39]!==u||n[40]!==p?(x=s.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:u,children:p}),n[39]=u,n[40]=p,n[41]=x):x=n[41],x}),lw=i.memo(function(e){const n=ht.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:f,desktopServicesTab:m,setDesktopServicesTab:u,quotaResultsLength:p,fetchAllQuotas:x,servicesTabItems:b,quotaLastUpdated:w,quotaDisplayMode:g,quotaDisplayTabItems:h,handleDisplayModeChange:C,handleUsageRefresh:j,isQuotaLoading:S,isUsageRefreshSpinning:N,hasRateLimits:k,rateLimitGroups:y,expandedFamilies:D,toggleFamilyExpanded:V,shortcutLabel:v,showDevShutdown:O,isDevShutdownInFlight:P,onDevShutdown:E,remoteUpdateInfo:B,remoteUpdateChecking:T,remoteUpdateError:W,onOpenRemoteUpdate:U,showPredValues:L,timeFormatPreference:M}=e,{t:ee}=yt();let ie;n[0]!==m||n[1]!==x||n[2]!==p||n[3]!==f||n[4]!==d?(ie=Le=>{d(Le),Le&&(f(),m==="usage"&&p===0&&x())},n[0]=m,n[1]=x,n[2]=p,n[3]=f,n[4]=d,n[5]=ie):ie=n[5];let X;n[6]!==o||n[7]!==r||n[8]!==ee?(X=r?ee("header.services.openWithCurrent",{current:o}):ee("header.services.open"),n[6]=o,n[7]=r,n[8]=ee,n[9]=X):X=n[9];const H=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let te;n[10]!==H?(te=Pe(el,H),n[10]=H,n[11]=te):te=n[11];let re;n[12]===Symbol.for("react.memo_cache_sentinel")?(re=s.jsx(A,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=re):re=n[12];let le;n[13]!==a||n[14]!==r?(le=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=le):le=n[15];let ve;n[16]!==X||n[17]!==te||n[18]!==le?(ve=s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":X,className:te,children:[re,le]})})}),n[16]=X,n[17]=te,n[18]=le,n[19]=ve):ve=n[19];let ne;n[20]!==o||n[21]!==r||n[22]!==v||n[23]!==ee?(ne=r?ee("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:v("toggle_services_menu"),nextTab:v("cycle_services_tab")}):ee("header.services.tooltip.servicesWithShortcuts",{toggle:v("toggle_services_menu"),nextTab:v("cycle_services_tab")}),n[20]=o,n[21]=r,n[22]=v,n[23]=ee,n[24]=ne):ne=n[24];let we;n[25]!==ne?(we=s.jsx(Dt,{children:s.jsx("p",{children:ne})}),n[25]=ne,n[26]=we):we=n[26];let he;n[27]!==ve||n[28]!==we?(he=s.jsxs(Ct,{children:[ve,we]}),n[27]=ve,n[28]=we,n[29]=he):he=n[29];let Me;n[30]!==x||n[31]!==p||n[32]!==u?(Me=Le=>{const pe=Le;u(pe),pe==="usage"&&p===0&&x()},n[30]=x,n[31]=p,n[32]=u,n[33]=Me):Me=n[33];let z;n[34]!==m||n[35]!==b||n[36]!==Me?(z=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(Bo,{items:b,activeId:m,onSelect:Me,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=m,n[35]=b,n[36]=Me,n[37]=z):z=n[37];let K;n[38]!==c||n[39]!==m||n[40]!==r||n[41]!==l||n[42]!==U||n[43]!==T||n[44]!==W||n[45]!==B||n[46]!==d||n[47]!==ee?(K=r&&m==="instance"?s.jsxs("div",{children:[c?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ee("header.services.remoteUpdate.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:B?.available?ee("header.services.remoteUpdate.available",{version:B.version||""}):T?ee("header.services.remoteUpdate.checking"):W||ee("header.services.remoteUpdate.upToDate")})]}),B?.available?s.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:U,children:ee("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(Lp,{embedded:!0,open:l&&m==="instance",onOpenChange:uw,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=m,n[40]=r,n[41]=l,n[42]=U,n[43]=T,n[44]=W,n[45]=B,n[46]=d,n[47]=ee,n[48]=K):K=n[48];let q;n[49]!==m||n[50]!==l?(q=m==="mcp"?s.jsx(Pm,{active:l&&m==="mcp"}):null,n[49]=m,n[50]=l,n[51]=q):q=n[51];let me;n[52]!==m||n[53]!==D||n[54]!==C||n[55]!==j||n[56]!==k||n[57]!==S||n[58]!==N||n[59]!==g||n[60]!==h||n[61]!==w||n[62]!==y||n[63]!==L||n[64]!==ee||n[65]!==M||n[66]!==V?(me=m==="usage"?s.jsxs("div",{className:"overflow-x-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--interactive-border)] px-4 py-2.5",children:[s.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:ee("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:zm(w,M)})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-[10.5rem]",children:s.jsx(Bo,{items:h,activeId:g,onSelect:Le=>{C(Le)},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:j,disabled:S||N,"aria-label":ee("header.services.refreshRateLimitsAria"),children:s.jsx(A,{name:"refresh",className:Pe("h-4 w-4",N&&"animate-spin")})})]})]}),k?null:s.jsx("div",{className:"px-4 py-5 text-center",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:ee("header.services.noRateLimits")})}),s.jsx("div",{className:"space-y-2 px-3 py-2.5",children:y.map(Le=>{const pe=D[Le.providerId]??[];return s.jsxs("div",{className:"min-w-0 rounded-xl bg-[var(--surface-muted)] p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[s.jsx(Oo,{providerId:Le.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Le.providerName})]}),Le.entries.length===0&&(!Le.modelFamilies||Le.modelFamilies.length===0)?s.jsx("div",{children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Le.error??ee("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3",children:[Le.entries.map(Ee=>{const[ge,oe]=Ee,je=g==="remaining"?oe.remainingPercent:oe.usedPercent,ye=Da(oe.usedPercent,oe.resetAt,oe.windowSeconds,ge),ue=ye?.dailyAllocationPercent!=null?g==="remaining"?100-pi(ye.elapsedRatio):pi(ye.elapsedRatio):null,De=Lo(oe.valueLabel,je),I=tm(oe.resetAt,oe.resetAfterFormatted??oe.resetAtFormatted,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.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:Sc(ge)}),I?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:I}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:De==="-"?"":De})]}),s.jsx(Ra,{percent:je,tonePercent:oe.usedPercent,className:"h-1.5",expectedMarkerPercent:ue}),ye&&L?s.jsx(Ea,{paceInfo:ye,compact:!0}):null]},`${Le.providerId}-${ge}`)}),Le.modelFamilies&&Le.modelFamilies.length>0?s.jsx("div",{className:"space-y-0.5",children:Le.modelFamilies.map(Ee=>{const ge=Ee.familyId??"other",oe=pe.includes(ge);return s.jsxs(ro,{open:oe,onOpenChange:()=>V(Le.providerId,ge),children:[s.jsxs(Uo,{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:Ee.familyLabel}),oe?s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(A,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(io,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:Ee.models.map(je=>{const[ye,ue]=je,De=g==="remaining"?ue.remainingPercent:ue.usedPercent,I=Da(ue.usedPercent,ue.resetAt,ue.windowSeconds),_=I?.dailyAllocationPercent!=null?g==="remaining"?100-pi(I.elapsedRatio):pi(I.elapsedRatio):null,be=Lo(ue.valueLabel,De);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:Tm(ye)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:be==="-"?"":be})]}),s.jsx(Ra,{percent:De,tonePercent:ue.usedPercent,className:"h-1.5",expectedMarkerPercent:_}),I&&L?s.jsx(Ea,{paceInfo:I,compact:!0}):null]},`${Le.providerId}-${ye}`)})})})]},ge)})}):null]})]},Le.providerId)})})]}):null,n[52]=m,n[53]=D,n[54]=C,n[55]=j,n[56]=k,n[57]=S,n[58]=N,n[59]=g,n[60]=h,n[61]=w,n[62]=y,n[63]=L,n[64]=ee,n[65]=M,n[66]=V,n[67]=me):me=n[67];let Se;n[68]!==P||n[69]!==E||n[70]!==O||n[71]!==ee?(Se=O?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(ms,{disabled:P,onSelect:()=>{E()},children:ee("header.services.shutdownDev")})})]}):null,n[68]=P,n[69]=E,n[70]=O,n[71]=ee,n[72]=Se):Se=n[72];let Be;n[73]!==z||n[74]!==K||n[75]!==q||n[76]!==me||n[77]!==Se?(Be=s.jsxs(en,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[z,K,q,me,Se]}),n[73]=z,n[74]=K,n[75]=q,n[76]=me,n[77]=Se,n[78]=Be):Be=n[78];let _e;return n[79]!==l||n[80]!==ie||n[81]!==he||n[82]!==Be?(_e=s.jsxs(tn,{open:l,onOpenChange:ie,children:[he,Be]}),n[79]=l,n[80]=ie,n[81]=he,n[82]=Be,n[83]=_e):_e=n[83],_e}),cw=(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??""),dw=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},zm=(t,e)=>{if(!t)return"-";try{return sm(t,e,{fallback:"-"})}catch{return"-"}},Mn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},ui=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,uu=({onToggleLeftDrawer:t,onToggleRightDrawer:e,leftDrawerOpen:n,rightDrawerOpen:r})=>{const{t:o}=yt(),a=Re(J=>J.setSessionSwitcherOpen),c=Re(J=>J.toggleSidebar),l=Re(J=>J.isSidebarOpen),d=Re(J=>J.toggleBottomTerminal),f=Re(J=>J.toggleRightSidebar),m=Re(J=>J.openContextOverview),u=Re(J=>J.openContextPlan),p=Re(J=>J.openContextBrowser),x=Re(J=>J.openContextPanelTab),b=Re(J=>J.closeContextPanel),w=Re(J=>J.contextPanelByDirectory),g=Re(J=>J.activeMainTab),h=Re(J=>J.setActiveMainTab),C=Re(J=>J.shortcutOverrides),j=Re(J=>J.timeFormatPreference),S=is(J=>J.getCurrentModel),N=Zn(),[k,y]=i.useState(!1),D=mt(J=>J.getContextUsage),V=mt(J=>!!J.newSessionDraft?.open),v=mt(J=>J.currentSessionId),O=Vp(v??""),P=nm(v??null),E=pr(J=>J.activeSessions),B=Nc(),T=Ds(J=>J.activeProjectId?J.projects.find(at=>at.id===J.activeProjectId)??null:null),W=i.useMemo(()=>{if(!T)return null;const J=T.label?.trim();if(J)return J;const at=T.path.split(/[\\/]/).filter(Boolean);return at[at.length-1]??null},[T]),U=xn(J=>J.results),L=xn(J=>J.fetchAllQuotas),M=xn(J=>J.isLoading),ee=xn(J=>J.lastUpdated),ie=xn(J=>J.displayMode),X=xn(J=>J.showPredValues),H=xn(J=>J.dropdownProviderIds),te=xn(J=>J.loadSettings),re=xn(J=>J.setDisplayMode),{isMobile:le}=$r(),ve=Fi(J=>J.status),ne=Fi(J=>J.setStatus),we=i.useRef(null),[he,Me]=i.useState(()=>typeof window>"u"?!1:gr()),z=i.useMemo(()=>Wa(),[]),K=rm(),[q,me]=i.useState(!1),Se=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",[]),_e=i.useMemo(()=>{if(typeof window>"u")return null;const J=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof J=="number"&&Number.isFinite(J)&&J>0)return J;if(typeof navigator>"u")return null;const at=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!at)return null;const ut=Number.parseInt(at[1],10),kt=Number.parseInt(at[2],10);return Number.isNaN(ut)?null:ut===10?kt:ut},[]);nt.useEffect(()=>{typeof window>"u"||Me(gr())},[]);const Le=S(),pe=Le&&typeof Le.limit=="object"&&Le.limit!==null?Le.limit:null,Ee=pe&&typeof pe.context=="number"?pe.context:0,ge=pe&&typeof pe.output=="number"?pe.output:0,oe=D(Ee,ge),[je,ye]=i.useState(null),ue=!v||O;nt.useEffect(()=>{if(!v){ye(J=>J===null?J:null);return}if(oe&&oe.totalTokens>0){ye(J=>cw(J,oe)?J:oe);return}ue&&ye(J=>J===null?J:null)},[oe,v,ue]);const De=Re(J=>J.isSessionSwitcherOpen),I=ve?.connected?ve.user?.avatarUrl??null:null,_=ve?.connected?ve.user?.login??null:null,be=ve?.accounts??[],[R,de]=i.useState(!1),[fe,$]=i.useState(!1),[Ae,Ve]=i.useState(!1),[Ne,Y]=i.useState(!1),[F,se]=i.useState("Local"),[Oe,ce]=i.useState(!0),[Ue,qe]=i.useState(!1),[Ye,tt]=i.useState(null),[xt,vt]=i.useState(!1),[Mt,Tt]=i.useState(null),Kt=i.useMemo(()=>dw(F),[F]),[Ut,Zt]=i.useState(he?"instance":"usage"),[ns,es]=i.useState("usage");nt.useEffect(()=>{!he&&Ut==="instance"&&Zt("usage")},[Ut,he]);const Ce=i.useMemo(()=>_r(),[]),Qe=!Ce&&g==="chat"&&!!je&&je.totalTokens>0,ot=je&&je.contextLimit>0?Math.min(999,je.totalTokens/je.contextLimit*100):0,bt=i.useCallback(async()=>{if(!(typeof window>"u"||!he))try{if(to()){se("Local"),ce(!0);return}ce(!1);const J=await Yf(),at=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,ut=Xr();if(ut&&Aa(ut,at)){se("Local"),ce(!0);return}const kt=J.hosts.find(Gt=>ut?Aa(ut,Qf(Gt)):!1);if(kt?.label?.trim()){se(Jf(kt.label.trim()));return}se("Instance")}catch{se("Local"),ce(!0)}},[he]);nt.useEffect(()=>{bt()},[bt]);const Je=i.useCallback(async()=>{if(Oe){tt(null),Tt(null);return}vt(!0),Tt(null);try{const J=new URLSearchParams({appType:"web",instanceMode:"remote"}),at=await Ps(`/api/openchamber/update-check?${J.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!at.ok)throw new Error(`Server responded with ${at.status}`);const ut=await at.json();tt({available:ut.available??!1,version:ut.version,currentVersion:ut.currentVersion??"unknown",body:ut.body,nextSuggestedCheckInSec:typeof ut.nextSuggestedCheckInSec=="number"?ut.nextSuggestedCheckInSec:void 0,packageManager:ut.packageManager,updateCommand:ut.updateCommand})}catch(J){tt(null),Tt(J instanceof Error?J.message:o("header.services.remoteUpdate.error"))}finally{vt(!1)}},[Oe,o]);i.useEffect(()=>{tt(null),Tt(null),qe(!1)},[Oe,F]),i.useEffect(()=>{if(!he||Oe)return;const J=3e3,at=3600*1e3;let ut=!1,kt=null;const Gt=os=>{kt=window.setTimeout(()=>{if(ut||typeof document<"u"&&document.visibilityState!=="visible"){Gt(at);return}Je().finally(()=>{ut||Gt(at)})},os)};return Gt(J),()=>{ut=!0,kt!==null&&window.clearTimeout(kt)}},[Je,Oe,F,he]);const Pt=i.useCallback(()=>{if(Ye?.available){qe(!0);return}Je()},[Je,Ye?.available]);Qx();const Xe=xn(J=>J.selectedModels),Ke=xn(J=>J.expandedFamilies),Ze=xn(J=>J.toggleFamilyExpanded),Bt=i.useMemo(()=>{const J=[];for(const at of Im){if(!H.includes(at.id))continue;const ut=U.find(Es=>Es.providerId===at.id),kt=ut?.usage?.windows??{},Gt=ut?.usage?.models,os=Object.entries(kt),fs={providerId:at.id,providerName:at.name,entries:os,error:ut&&!ut.ok&&ut.configured?ut.error:void 0};if(Gt&&Object.keys(Gt).length>0){const Es=Xe[at.id]??[],qs=Es.length>0,er=Jx(Gt,at.id),$n=Xx(at.id),ri=Zx($n);fs.modelFamilies=[];for(const In of ri){const tr=er.get(In.id)??[];if(tr.length===0)continue;const cn=qs?tr.filter(wn=>Es.includes(wn)):tr;if(cn.length===0)continue;const gn=[];for(const wn of cn){const sr=Gt[wn];if(sr?.windows){const nr=Object.entries(sr.windows);nr.length>0&&gn.push([wn,nr[0][1]])}}gn.length>0&&fs.modelFamilies.push({familyId:In.id,familyLabel:In.label,models:gn})}const pn=er.get(null)??[],Wr=qs?pn.filter(In=>Es.includes(In)):pn;if(Wr.length>0){const In=[];for(const tr of Wr){const cn=Gt[tr];if(cn?.windows){const gn=Object.entries(cn.windows);gn.length>0&&In.push([tr,gn[0][1]])}}In.length>0&&fs.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:In})}}(os.length>0||fs.modelFamilies&&fs.modelFamilies.length>0||fs.error)&&J.push(fs)}return J},[H,U,Xe,o]),Rt=Bt.length>0;i.useEffect(()=>{te()},[te]);const Ot=i.useCallback(async J=>{re(J);try{await wc({usageDisplayMode:J})}catch(at){console.warn("Failed to update usage display mode:",at)}},[re]),rs=i.useCallback(()=>{if(Ne)return;Y(!0);const J=new Promise(at=>setTimeout(at,500));Promise.all([L(),J]).finally(()=>{Y(!1)})},[L,Ne]),Wt=i.useMemo(()=>v?B.find(J=>J.id===v)??E.find(J=>J.id===v)??P??im().find(J=>J.id===v)??null:null,[v,P,E,B]),Et=i.useRef(null),[qt,hs]=i.useState(0);i.useEffect(()=>{if(!v){Et.current&&(Et.current=null,hs(kt=>kt+1));return}if(Wt){Et.current={sessionId:v,session:Wt,expiresAt:Date.now()+2e3};return}const J=Et.current;if(!J||J.sessionId!==v)return;const at=J.expiresAt-Date.now();if(at<=0){Et.current=null,hs(kt=>kt+1);return}const ut=window.setTimeout(()=>{Et.current?.sessionId===v&&(Et.current=null),hs(kt=>kt+1)},at);return()=>{window.clearTimeout(ut)}},[v,Wt]);const ts=(()=>{if(Wt)return Wt;if(!v)return null;const J=Et.current;return J&&J.sessionId===v&&J.expiresAt>Date.now()?J.session:null})(),as=mt(J=>v?J.worktreeMetadata.get(v)?.path??"":""),gs=mt(J=>v?J.worktreeMetadata.get(v)?.branch?.trim()??null:null),Ft=om(J=>v?J.getAttachment(v):void 0),Lt=i.useMemo(()=>Ft?_p(Ft,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,Ft]),Ht=i.useMemo(()=>Ft?Ft.legacy?"legacy":Ft.degraded?"degraded":Ft.worktreeStatus==="pending"?"pending":Ft.worktreeStatus==="missing"?"missing":Ft.worktreeStatus==="invalid"?"invalid":Ft.attentionReason?"attention":null:null,[Ft]),Yt=i.useMemo(()=>Mn(as||""),[as]),$t=i.useMemo(()=>{const J=typeof ts?.directory=="string"?ts.directory:"";return Mn(J||"")},[ts?.directory]),Fe=mt(J=>J.newSessionDraft?.open?Mn(J.newSessionDraft.bootstrapPendingDirectory??J.newSessionDraft.directoryOverride??""):""),st=i.useMemo(()=>Yt||$t||Fe,[Fe,$t,Yt]),wt=mt(J=>{const at=Mn(Yt||$t||"");if(!at)return null;for(const ut of J.availableWorktreesByProject.values()){const Gt=ut.find(os=>Mn(os.path)===at)?.branch?.trim();if(Gt)return Gt}return null}),Nt=$p(st||null)||gs||wt,ss=i.useMemo(()=>{if(!v)return W??"OpenChamber";const J=ts?.title?.trim();return J&&J.length>0?J:"Untitled Session"},[W,ts?.title,v]),cs=i.useMemo(()=>Mn(st||T?.path||""),[T?.path,st]),Xt=i.useMemo(()=>T?{id:T.id,path:T.path}:null,[T]),Vt=i.useRef(null);i.useEffect(()=>{!Xt||!cs||(Vt.current={projectRef:Xt,directory:cs})},[cs,Xt]);const Fs=i.useMemo(()=>Xt&&cs?{projectRef:Xt,directory:cs}:Vt.current,[cs,Xt]),us=kc(J=>J.planModeEnabled),$s=mt(J=>J.isSessionPlanAvailable),js=us&&v?$s(v):!1,Cs=js,jn=i.useRef("");i.useEffect(()=>{if(!us){Re.getState().activeMainTab==="plan"&&Re.getState().setActiveMainTab("chat");return}if(!v)return;const J=`${v||"none"}:${$t||"none"}:${ts?.time?.created||0}:${ts?.slug||"none"}`;jn.current!==J&&(jn.current=J),!js&&Re.getState().activeMainTab==="plan"&&Re.getState().setActiveMainTab("chat")},[us,js,ts?.slug,ts?.time?.created,v,$t]);const hn=i.useCallback(async J=>{if(!(!J||R)){de(!0);try{const at=N.github?await N.github.authActivate(J):await(async()=>{const ut=await Ps("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:J})}),kt=await ut.json().catch(()=>null);if(!ut.ok||!kt)throw new Error(kt?.error||ut.statusText);return kt})();ne(at)}catch(at){console.error("Failed to switch GitHub account:",at)}finally{de(!1)}}},[R,N.github,ne]),xe=i.useCallback(()=>{if(typeof document>"u")return;const J=document.activeElement;if(!J)return;const at=J.tagName;(at==="INPUT"||at==="TEXTAREA"||at==="SELECT"||J.isContentEditable)&&J.blur()},[]),rt=i.useCallback(()=>{if(le){xe(),a(!De);return}c()},[xe,le,De,a,c]),dt=i.useCallback(()=>{Zr("desktop_open_draft_mini_chat_window",{directory:Mn(st||T?.path||""),projectId:T?.id??null,apiBaseUrl:Xr(),clientToken:Yl()}).catch(J=>{console.warn("[header] failed to open draft mini chat window",J)})},[T?.id,T?.path,st]),jt=i.useCallback(()=>{if(V){dt();return}v&&Zr("desktop_open_session_mini_chat_window",{sessionId:v,directory:Mn(st||T?.path||""),apiBaseUrl:Xr(),clientToken:Yl()}).catch(J=>{console.warn("[header] failed to open session mini chat window",J)})},[T?.path,v,dt,V,st]),zt=i.useCallback(()=>{const J=Mn(st||"");if(!J)return;const at=w[J];if(ui(at)==="context"){b(J);return}m(J)},[b,w,m,st]),gt=i.useMemo(()=>{const J=Mn(st||"");if(!J)return!1;const at=w[J];return ui(at)==="context"},[w,st]),xs=i.useCallback(()=>{const J=Mn(st||"");if(!J)return;const at=w[J];if(ui(at)==="plan"){b(J);return}u(J)},[b,w,u,st]),bs=i.useCallback(()=>{const J=Mn(st||"");if(!J)return;const at=w[J];if(ui(at)==="diff"){b(J);return}x(J,{mode:"diff",stagedDiff:!1})},[b,w,x,st]),Ss=i.useCallback(()=>{const J=Mn(st||"");if(!J)return;const at=w[J];if(ui(at)==="browser"){b(J);return}p(J)},[b,w,p,st]),Ns=i.useMemo(()=>{const J=Mn(st||"");if(!J)return!1;const at=w[J];return ui(at)==="plan"},[w,st]),Os=i.useMemo(()=>{const J=Mn(st||"");if(!J)return!1;const at=w[J];return ui(at)==="diff"},[w,st]),Tn=i.useMemo(()=>{const J=Mn(st||"");if(!J)return!1;const at=w[J];return ui(at)==="browser"},[w,st]),Gs=el,Pn=ow,Bn=i.useMemo(()=>fe?"services":n?"sessions":r?"git":g,[g,fe,n,r]),Sn=i.useCallback(()=>{$(!1),n&&t&&t(),r&&e&&e(),!t&&De&&a(!1)},[De,n,t,e,r,a]),an=i.useCallback(()=>{n||$(!1),t?.()},[n,t]),Nn=i.useCallback(()=>{r||$(!1),e?.()},[e,r]),nn=i.useMemo(()=>he&&Se&&!q?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!he||Be)&&!Ce?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[he,q,Se,K,Ce,Be]);nt.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",nn)},[nn]);const Ge=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",ps=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";nt.useEffect(()=>{if(!he||!Se){me(!1);return}let J=!1;const at=async()=>{try{const kt=await Zr("desktop_is_window_fullscreen");J||me(kt===!0)}catch{J||me(!1)}},ut=()=>{at()};return at(),window.addEventListener("openchamber:window-resized",ut),()=>{J=!0,window.removeEventListener("openchamber:window-resized",ut)}},[he,Se]);const ks=i.useMemo(()=>!he||!Se||_e===null?"":_e>=26?"h-12":_e<=15?"h-14":"",[he,Se,_e]),zs=i.useMemo(()=>{if(!(he&&!Be||Ce))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[he,Ce,Be]),Rs=i.useCallback(()=>{if(typeof document>"u")return;const J=we.current?.getBoundingClientRect().height;J&&document.documentElement.style.setProperty("--oc-header-height",`${J}px`)},[]);nt.useEffect(()=>{if(typeof window>"u")return;Rs();const J=we.current;if(!J||typeof ResizeObserver>"u")return()=>{};let at=0;const ut=()=>{at||(at=requestAnimationFrame(()=>{at=0,Rs()}))},kt=new ResizeObserver(ut);return kt.observe(J),window.addEventListener("resize",ut),window.addEventListener("orientationchange",ut),()=>{at&&cancelAnimationFrame(at),kt.disconnect(),window.removeEventListener("resize",ut),window.removeEventListener("orientationchange",ut)}},[Rs]),nt.useEffect(()=>{Rs()},[Rs,le,ks]);const rn=i.useCallback(async J=>{const at=J.target;at.closest(".app-region-no-drag")||at.closest("button, a, input, select, textarea")||J.button===0&&he&&await wp()},[he]),Ks=i.useMemo(()=>{if(le){const J=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return Cs&&J.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),J.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"}),J}return[]},[le,Cs,o]),Is=i.useCallback(J=>Ua(gi(J,C)),[C]);nt.useEffect(()=>{!le&&(g==="git"||g==="terminal"||g==="diff"||g==="files"||g==="context")&&h("chat")},[g,le,h]);const Vn=i.useMemo(()=>{const J=[];return he&&J.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(A,{name:"server",className:"h-3.5 w-3.5"})}),J.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(A,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(Jl,{className:"h-3.5 w-3.5"})}),J},[he,o]),ws=i.useMemo(()=>Vn.map(J=>({id:J.value,label:J.label,icon:J.icon})),[Vn]),Ls=i.useMemo(()=>{if(typeof window>"u"||he||Ce)return!1;const J=window.location.hostname;return J==="localhost"||J==="127.0.0.1"||J==="::1"},[he,Ce]),Dr=i.useCallback(async()=>{if(k)return;y(!0),Ve(!1);const J=[];let at=!1;try{try{for(const[,ut]of Us.getState().sessions.entries())for(const kt of ut.tabs)kt.previewUrl&&J.push(kt.previewUrl)}catch{}try{await yp({})}catch{}try{(await Ps("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:J})})).ok?at=!0:at=(await Ps("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{at||y(!1)}},[k,Ve]),_n=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),bn=i.useMemo(()=>_n.map(J=>({id:J.value,label:J.label})),[_n]),Tr=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(A,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(Jl,{className:"h-3.5 w-3.5"})}],[o]);nt.useEffect(()=>{const J=at=>{if(Cc(at)&&!at.shiftKey&&!at.altKey){const ut=parseInt(at.key,10);ut>=1&&ut<=Ks.length&&(at.preventDefault(),le&&(xe(),Sn()),h(Ks[ut-1].id))}};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[xe,Sn,le,h,Ks]),nt.useEffect(()=>{const J=at=>{const ut=gi("toggle_services_menu",C);if(da(at,ut)){at.preventDefault(),Ae?Ve(!1):(Ve(!0),bt(),Ut==="usage"&&U.length===0&&L());return}const kt=gi("cycle_services_tab",C);if(da(at,kt)){at.preventDefault();const os=Vn.map(er=>er.value);if(os.length===0)return;const fs=os.indexOf(Ut),Es=fs===-1?0:(fs+1)%os.length,qs=os[Es];Zt(qs),Ve(!0),bt(),qs==="usage"&&U.length===0&&L();return}const Gt=gi("toggle_context_plan",C);da(at,Gt)&&(at.preventDefault(),xs())};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[C,Ae,Ut,Vn,U.length,L,bt,xs]);const si=J=>{const at=g===J.id,ut=J.icon==="diff",kt=ut?null:J.icon,Gt=J.id==="chat",os=Es=>ut?s.jsx(au,{size:Es}):kt?s.jsx(A,{name:kt,className:`h-${Es/4} w-${Es/4}`}):null,fs=s.jsxs("button",{type:"button",onClick:()=>h(J.id),className:Pe("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",at?"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",Gt&&!le&&"min-w-[100px] justify-center"),"aria-label":J.label,"aria-selected":at,role:"tab",children:[le?os(20):s.jsxs(s.Fragment,{children:[os(16),s.jsx("span",{className:"header-tab-label",children:J.label})]}),J.badge!==void 0&&J.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:J.badge})]});return s.jsx(i.Fragment,{children:fs},J.id)},ni=Ce?null:s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.toggleChangesPanelAria"),"aria-pressed":Os,onClick:bs,className:Gs,children:s.jsxs("span",{className:"relative h-5 w-5 overflow-hidden rounded-[2px]",children:[s.jsx("span",{className:"absolute left-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-success)]/25"}),s.jsx(A,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(Dt,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),zr=s.jsxs(s.Fragment,{children:[Cs&&s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:xs,className:Pe(Gs,Ns&&"bg-[var(--interactive-hover)]"),children:s.jsx(A,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(Dt,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:Is("toggle_context_plan")})})})]}),s.jsx(Ib,{directory:cs,className:"mr-1"}),s.jsx(lw,{isDesktopApp:he,currentInstanceLabel:F,compactCurrentInstanceLabel:Kt,currentInstanceIsLocal:Oe,isDesktopServicesOpen:Ae,setIsDesktopServicesOpen:Ve,refreshCurrentInstanceLabel:bt,desktopServicesTab:Ut,setDesktopServicesTab:Zt,quotaResultsLength:U.length,fetchAllQuotas:L,servicesTabItems:ws,quotaLastUpdated:ee,quotaDisplayMode:ie,showPredValues:X,quotaDisplayTabItems:bn,handleDisplayModeChange:Ot,handleUsageRefresh:rs,isQuotaLoading:M,isUsageRefreshSpinning:Ne,hasRateLimits:Rt,rateLimitGroups:Bt,expandedFamilies:Ke,toggleFamilyExpanded:Ze,shortcutLabel:Is,showDevShutdown:Ls,isDevShutdownInFlight:k,onDevShutdown:Dr,remoteUpdateInfo:Ye,remoteUpdateChecking:xt,remoteUpdateError:Mt,onOpenRemoteUpdate:Pt,timeFormatPreference:j}),s.jsx(Qo,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:Is("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),le?null:s.jsx(Qo,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:Ss,pressed:Tn,Icon:"global"}),s.jsx(Qo,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:Is("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:f,Icon:"layout-right"}),s.jsx(aw,{isMobile:le,githubAuthStatus:ve,githubAccounts:be,githubAvatarUrl:I,githubLogin:_,isSwitchingGitHubAccount:R,handleGitHubAccountSwitch:hn})]}),cr=z&&(V||!!v),ys=()=>s.jsxs("div",{onMouseDown:rn,className:Pe("app-region-drag relative flex h-12 select-none items-center pr-3",ks),style:zs,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:Ge}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:ps}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(vb,{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:V?o("sessions.switcher.draftTitle"):ss}),W||Nt||!V&&Ht?s.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[W?s.jsx("span",{className:"truncate",children:W}):null,Nt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:Nt})]}):null,!V&&Ht?s.jsxs("span",{className:Pe("inline-flex min-w-0 items-center gap-0.5",Ht==="attention"||Ht==="invalid"||Ht==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(A,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:Lt})]}):null]}):null]})}),Ks.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ks.map(J=>si(J))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Qe&&je?s.jsx(jb,{totalTokens:je.totalTokens,percentage:ot,colorPercentage:je.percentage,contextLimit:je.contextLimit,outputLimit:je.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:zt,pressed:gt,className:cr?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,ni,s.jsx(Qo,{visible:cr,title:o(V?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(V?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:jt,className:Pe(Gs,"mr-1"),Icon:"picture-in-picture-2"}),zr,s.jsx(Sb,{visible:Be})]})]})]}),ln=()=>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:an,className:Pe(Pn,Bn==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(A,{name:"layout-left",className:"h-5 w-5"})}):De?s.jsx("button",{type:"button",onClick:()=>a(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.backAria"),children:s.jsx(A,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:rt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.openSessionsAria"),children:s.jsx(A,{name:"play-list-add",className:"h-5 w-5"})}),!t&&De&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!De||!!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:Ks.map(J=>{const at=g===J.id,ut=J.icon==="diff",kt=ut?null:J.icon;return s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{le&&(xe(),Sn()),h(J.id)},"aria-label":J.label,"aria-selected":at,role:"tab",className:Pe(Pn,"relative rounded-lg",Bn===J.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ut?s.jsx(au,{className:"h-5 w-5"}):kt?s.jsx(A,{name:kt,className:"h-5 w-5"}):null,J.badge!==void 0&&J.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:J.badge}),J.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(Dt,{children:s.jsx("p",{children:J.label})})]},J.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[Fs&&s.jsx($m,{projectRef:Fs.projectRef,directory:Fs.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(tn,{open:fe,onOpenChange:J=>{J&&(n&&t&&t(),r&&e&&e()),$(J),J&&U.length===0&&L()},children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:Pe(Pn,Bn==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(A,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(Dt,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(en,{align:"end",sideOffset:0,positionerClassName:"!fixed !bottom-0 !left-0 !right-0 !top-[var(--oc-header-height,56px)] !transform-none",className:"h-full w-screen max-h-none rounded-none border-0 p-0 pt-1 overflow-hidden",children:s.jsxs("div",{className:"flex h-full flex-col bg-[var(--surface-elevated)]",children:[s.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)] px-2 py-px",children:s.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-0",children:[s.jsx("div",{className:"h-10 min-w-0 flex-1",children:s.jsx(Bo,{items:Tr,activeId:ns,onSelect:J=>{const at=J;es(at),at==="usage"&&U.length===0&&L()},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:()=>$(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover","aria-label":o("header.services.closeAria"),children:s.jsx(A,{name:"close",className:"h-5 w-5"})})]})}),ns==="mcp"&&s.jsx(Pm,{active:fe&&ns==="mcp"}),ns==="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:zm(ee,j)})]}),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:()=>Ot("usage"),className:Pe("typography-ui-label px-1 pb-0.5 transition-colors",ie==="usage"?"text-foreground border-b-2 border-[var(--primary-base)]":"text-muted-foreground hover:text-foreground"),children:o("header.services.used")}),s.jsx("span",{className:"text-muted-foreground typography-ui-label px-0.5",children:"·"}),s.jsx("button",{type:"button",onClick:()=>Ot("remaining"),className:Pe("typography-ui-label px-1 pb-0.5 transition-colors",ie==="remaining"?"text-foreground border-b-2 border-[var(--primary-base)]":"text-muted-foreground hover:text-foreground"),children:o("header.services.remaining")})]}),s.jsx("button",{type:"button",className: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:M||Ne,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(A,{name:"refresh",className:Pe("h-4 w-4",Ne&&"animate-spin")})})]})]})}),!Rt&&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:Bt.map((J,at)=>s.jsxs(i.Fragment,{children:[at>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(Oo,{providerId:J.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:J.providerName})]}),J.entries.length===0&&(!J.modelFamilies||J.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:J.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[J.entries.map(([ut,kt])=>{const Gt=ie==="remaining"?kt.remainingPercent:kt.usedPercent,os=Da(kt.usedPercent,kt.resetAt,kt.windowSeconds,ut),fs=os?.dailyAllocationPercent!=null?ie==="remaining"?100-pi(os.elapsedRatio):pi(os.elapsedRatio):null,Es=Lo(kt.valueLabel,Gt),qs=tm(kt.resetAt,kt.resetAfterFormatted??kt.resetAtFormatted,j);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:Sc(ut)}),qs?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:qs}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Es==="-"?"":Es})]}),s.jsx(Ra,{percent:Gt,tonePercent:kt.usedPercent,className:"h-1.5",expectedMarkerPercent:fs}),os&&X?s.jsx(Ea,{paceInfo:os,compact:!0}):null]},`${J.providerId}-${ut}`)}),J.modelFamilies&&J.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:J.modelFamilies.map(ut=>{const Gt=(Ke[J.providerId]??[]).includes(ut.familyId??"other");return s.jsxs(ro,{open:Gt,onOpenChange:()=>Ze(J.providerId,ut.familyId??"other"),children:[s.jsxs(Uo,{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:ut.familyLabel}),Gt?s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(A,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(io,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:ut.models.map(([os,fs])=>{const Es=ie==="remaining"?fs.remainingPercent:fs.usedPercent,qs=Da(fs.usedPercent,fs.resetAt,fs.windowSeconds),er=qs?.dailyAllocationPercent!=null?ie==="remaining"?100-pi(qs.elapsedRatio):pi(qs.elapsedRatio):null,$n=Lo(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:Tm(os)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:$n==="-"?"":$n})]}),s.jsx(Ra,{percent:Es,tonePercent:fs.usedPercent,className:"h-1.5",expectedMarkerPercent:er}),qs&&X?s.jsx(Ea,{paceInfo:qs,compact:!0}):null]},`${J.providerId}-${os}`)})})})]},ut.familyId??"other")})})]})]},J.providerId))})]})]})})]}),e?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Nn,className:Pe(Pn,"relative",Bn==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(A,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Dt,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),dr=Pe("header-safe-area relative z-10 bg-background",le&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:we,className:dr,style:{"--padding-scale":"1"},children:le?ln():ys()}),s.jsx(Rm,{open:Ue,onOpenChange:qe,info:Ye,downloading:!1,downloaded:!1,progress:null,error:Mt,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function uw(){}const fu=180,mu=640,fw=110,mw=t=>{const e=ht.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=yt(),c=Re(hw),l=Re(pw),d=Re(gw),f=Re(xw),[m,u]=i.useState(null),[p,x]=i.useState(!1),b=i.useRef(null),w=i.useRef(0),g=i.useRef(c||300),h=Math.min(mu,Math.max(fu,c||300));let C,j;e[0]!==n?(C=()=>{n||(u(null),x(!1))},j=[n],e[0]=n,e[1]=C,e[2]=j):(C=e[1],j=e[2]),i.useEffect(C,j);let S,N;e[3]!==l||e[4]!==r||e[5]!==n?(S=()=>{if(r||!n||!l)return;const te=()=>{const ve=b.current?.parentElement?.getBoundingClientRect().height;if(!ve||ve<=0)return;const ne=Math.max(0,Math.round(ve));u(we=>we===ne?we:ne)};te();const re=b.current?.parentElement;if(!re)return;const le=new ResizeObserver(te);return le.observe(re),()=>{le.disconnect()}},N=[l,r,n],e[3]=l,e[4]=r,e[5]=n,e[6]=S,e[7]=N):(S=e[6],N=e[7]),i.useEffect(S,N);let k,y;if(e[8]!==l||e[9]!==r||e[10]!==p||e[11]!==d||e[12]!==f?(k=()=>{if(r||!p||l)return;const te=le=>{const ve=w.current-le.clientY,ne=Math.min(mu,Math.max(fu,g.current+ve));d(ne)},re=()=>{x(!1),Re.getState().bottomTerminalHeight<=fw&&f(!1)};return window.addEventListener("pointermove",te),window.addEventListener("pointerup",re,{once:!0}),()=>{window.removeEventListener("pointermove",te),window.removeEventListener("pointerup",re)}},y=[l,r,p,d,f],e[8]=l,e[9]=r,e[10]=p,e[11]=d,e[12]=f,e[13]=k,e[14]=y):(k=e[13],y=e[14]),i.useEffect(k,y),r)return null;const D=n?l?Math.max(0,m??h):h:0,V=n&&l;let v;e[15]!==D||e[16]!==l||e[17]!==n?(v=te=>{!n||l||(x(!0),w.current=te.clientY,g.current=D,te.preventDefault())},e[15]=D,e[16]=l,e[17]=n,e[18]=v):v=e[18];const O=v,P=V?"absolute inset-x-0 bottom-0 z-40":"relative",E=p?"transition-none":"transition-[height] duration-300 ease-in-out",B=(!n||V)&&"border-t-0";let T;e[19]!==B||e[20]!==P||e[21]!==E?(T=Pe("flex overflow-hidden border-t border-border bg-sidebar",P,E,B),e[19]=B,e[20]=P,e[21]=E,e[22]=T):T=e[22];let W;e[23]!==D||e[24]!==V?(W=V?{top:0}:{height:`${D}px`,minHeight:`${D}px`,maxHeight:`${D}px`},e[23]=D,e[24]=V,e[25]=W):W=e[25];const U=!n||!l&&D===0;let L;e[26]!==O||e[27]!==l||e[28]!==n||e[29]!==p||e[30]!==a?(L=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:O,role:"separator","aria-orientation":"horizontal","aria-label":a("terminalView.bottomDock.resizeAria")}),e[26]=O,e[27]=l,e[28]=n,e[29]=p,e[30]=a,e[31]=L):L=e[31];const M=!n&&"pointer-events-none select-none opacity-0";let ee;e[32]!==M?(ee=Pe("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",M),e[32]=M,e[33]=ee):ee=e[33];const ie=!n;let X;e[34]!==o||e[35]!==ee||e[36]!==ie?(X=s.jsx("div",{className:ee,"aria-hidden":ie,children:o}),e[34]=o,e[35]=ee,e[36]=ie,e[37]=X):X=e[37];let H;return e[38]!==T||e[39]!==W||e[40]!==U||e[41]!==L||e[42]!==X?(H=s.jsxs("section",{ref:b,className:T,style:W,"aria-hidden":U,children:[L,X]}),e[38]=T,e[39]=W,e[40]=U,e[41]=L,e[42]=X,e[43]=H):H=e[43],H};function hw(t){return t.bottomTerminalHeight}function pw(t){return t.isBottomTerminalExpanded}function gw(t){return t.setBottomTerminalHeight}function xw(t){return t.setBottomTerminalOpen}const hu=280,pu=280,gu=500,bw=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=yt(),c=Re(y=>y.sidebarWidth),l=Re(y=>y.setSidebarWidth),[d,f]=i.useState(!1),m=i.useRef(0),u=i.useRef(c||hu),p=i.useRef(null),x=i.useRef(null),b=i.useRef(null),w=i.useCallback(y=>Math.min(gu,Math.max(pu,y)),[]),g=i.useCallback(y=>{const D=b.current;D&&(D.style.width=`${y}px`,D.style.minWidth=`${y}px`,D.style.maxWidth=`${y}px`,D.style.setProperty("--oc-left-sidebar-width",`${y}px`))},[]);if(i.useEffect(()=>{e&&d&&f(!1)},[e,d]),i.useEffect(()=>{d||(p.current=null,x.current=null)},[d]),e)return null;const h=Math.min(gu,Math.max(pu,c||hu)),C=t?h:0,j=y=>{if(t){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}x.current=y.pointerId,f(!0),m.current=y.clientX,u.current=C,p.current=C,g(C),y.preventDefault()}},S=y=>{if(e||!d||x.current!==y.pointerId)return;const D=y.clientX-m.current,V=w(u.current+D);p.current!==V&&(p.current=V,g(V))},N=y=>{if(x.current!==y.pointerId||e)return;try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}const D=w(p.current??C);x.current=null,p.current=null,f(!1),l(D)},k=d?p.current??C:C;return s.jsxs("aside",{ref:b,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:j,onPointerMove:S,onPointerUp:N,onPointerCancel:N,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(on,{children:n})})]})]})},ww=()=>{const t=ht.c(3);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e={height:"var(--oc-header-height, 3rem)"},t[0]=e):e=t[0];let n;t[1]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("div",{className:"app-region-drag shrink-0",style:{width:"var(--oc-titlebar-left-inset, 0.75rem)"}}),t[1]=n):n=t[1];let r;return t[2]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsxs("div",{"aria-hidden":!0,className:"flex shrink-0",style:e,children:[n,s.jsx("div",{className:"app-region-no-drag shrink-0",style:{width:"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)"}}),s.jsx("div",{className:"app-region-drag flex-1"})]}),t[2]=r):r=t[2],r},Jo=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function yw(){const t=Ds(u=>u.activeProjectId?u.projects.find(p=>p.id===u.activeProjectId)??null:null),e=mt(u=>u.currentSessionId),n=nm(e??null),r=mt(u=>e?u.worktreeMetadata.get(e)?.path??"":""),o=mt(u=>u.newSessionDraft?.open?Jo(u.newSessionDraft.bootstrapPendingDirectory??u.newSessionDraft.directoryOverride??""):""),a=i.useMemo(()=>Jo(r||""),[r]),c=i.useMemo(()=>{const u=typeof n?.directory=="string"?n.directory:"";return Jo(u||"")},[n?.directory]),l=a||c||o,d=i.useMemo(()=>Jo(l||t?.path||""),[t?.path,l]),f=i.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),m=i.useRef(null);return i.useEffect(()=>{f&&d&&(m.current={projectRef:f,directory:d})},[d,f]),i.useMemo(()=>f&&d?{projectRef:f,directory:d}:m.current,[f,d])}const xu="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",vw=()=>{const t=ht.c(31),{t:e}=yt(),n=Re(jw),r=Re(Sw),o=Re(Nw),a=yw(),c=i.useRef(null),l=Ua(gi("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const f=d,m=Cw;let u,p;t[0]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{if(typeof document>"u")return;const B=c.current;if(!B)return;const T=()=>{const U=B.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(U)}px`)};if(T(),typeof ResizeObserver>"u")return;const W=new ResizeObserver(T);return W.observe(B),()=>{W.disconnect()}},p=[],t[0]=u,t[1]=p):(u=t[0],p=t[1]),i.useEffect(u,p);const x="app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2";let b;t[2]===Symbol.for("react.memo_cache_sentinel")?(b={height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},t[2]=b):b=t[2];const w="flex items-center gap-2";let g;t[3]!==e?(g=f?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,"aria-label":e("header.actions.openAppMenuAria"),className:Pe(xu,"shrink-0"),children:s.jsx(A,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Dt,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=g):g=t[4];const h=Ct;let C;t[5]!==e?(C=e("header.actions.openSessionsAria"),t[5]=e,t[6]=C):C=t[6];let j,S;t[7]===Symbol.for("react.memo_cache_sentinel")?(j=Pe(xu,"shrink-0"),S=s.jsx(A,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=j,t[8]=S):(j=t[7],S=t[8]);let N;t[9]!==C||t[10]!==n?(N=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":C,className:j,children:S})}),t[9]=C,t[10]=n,t[11]=N):N=t[11];const k=Dt,y=e("header.actions.openSessionsWithShortcut",{shortcut:l});let D;t[12]!==y?(D=s.jsx("p",{children:y}),t[12]=y,t[13]=D):D=t[13];let V;t[14]!==k||t[15]!==D?(V=s.jsx(k,{children:D}),t[14]=k,t[15]=D,t[16]=V):V=t[16];let v;t[17]!==h||t[18]!==N||t[19]!==V?(v=s.jsxs(h,{children:[N,V]}),t[17]=h,t[18]=N,t[19]=V,t[20]=v):v=t[20];let O;t[21]!==r||t[22]!==a?(O=a?s.jsx($m,{projectRef:a.projectRef,directory:a.directory,className:r?"oc-vibrancy-pill":void 0}):null,t[21]=r,t[22]=a,t[23]=O):O=t[23];let P;t[24]!==v||t[25]!==O||t[26]!==g?(P=s.jsxs("div",{ref:c,className:w,children:[g,v,O]}),t[24]=v,t[25]=O,t[26]=g,t[27]=P):P=t[27];let E;return t[28]!==P||t[29]!==b?(E=s.jsx("div",{className:x,style:b,children:P}),t[28]=P,t[29]=b,t[30]=E):E=t[30],E};function jw(t){return t.toggleSidebar}function Sw(t){return t.isSidebarOpen}function Nw(t){return t.shortcutOverrides}function kw(t){console.warn("[titlebar] failed to open app menu",t)}function Cw(t){const e=t.currentTarget.getBoundingClientRect();Zr("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(kw)}const bu=420,Aw=({isOpen:t,children:e,className:n})=>{const{t:r}=yt(),o=Re(N=>N.rightSidebarWidth),a=Re(N=>N.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),f=i.useRef(o||bu),m=i.useRef(null),u=i.useRef(null),p=i.useRef(null),x=i.useCallback(N=>Math.min(Dd,Math.max(Td,N)),[]),b=i.useCallback(N=>{const k=p.current;k&&(k.style.width=`${N}px`,k.style.minWidth=`${N}px`,k.style.maxWidth=`${N}px`,k.style.setProperty("--oc-right-sidebar-width",`${N}px`))},[]),w=Math.min(Dd,Math.max(Td,o||bu)),g=t?w:0;i.useLayoutEffect(()=>{if(c)return;const N=p.current;N&&(N.style.minWidth="",N.style.maxWidth="")},[t,c,w]);const h=N=>{if(t){try{N.currentTarget.setPointerCapture(N.pointerId)}catch{}u.current=N.pointerId,l(!0),d.current=N.clientX,f.current=g,m.current=g,b(g),N.preventDefault()}},C=N=>{if(!c||u.current!==N.pointerId)return;const k=d.current-N.clientX,y=x(f.current+k);m.current!==y&&(m.current=y,b(y))},j=N=>{if(u.current!==N.pointerId)return;try{N.currentTarget.releasePointerCapture(N.pointerId)}catch{}const k=x(m.current??g);u.current=null,m.current=null,l(!1),a(k)},S=c?m.current??g:g;return s.jsxs("aside",{ref:p,className: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:`${S}px`,"--oc-right-sidebar-width":`${c?S:w}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||g===0,children:[t&&s.jsx("div",{className: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:j,onPointerCancel:j,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})]})},wu=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function Wm(t){const e=ht.c(131),{t:n}=yt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,allowRunAsGoal:d,onConfirm:f}=t,m=l===void 0?!1:l,u=d===void 0?!1:d;let p;e[0]!==u?(p=u&&!_r(),e[0]=u,e[1]=p):p=e[1];const x=p,b=is(Bw),w=is(Lw),g=zp(Ow),h=is(Fw),C=is(Mw),j=is(Ew),S=is(Rw),N=is(Iw);let k;e[2]!==N||e[3]!==j||e[4]!==C||e[5]!==S?(k=()=>wu({providerID:C,modelID:j,variant:S,agent:N}),e[2]=N,e[3]=j,e[4]=C,e[5]=S,e[6]=k):k=e[6];const[y,D]=i.useState(k);let V,v;e[7]!==g||e[8]!==w||e[9]!==b||e[10]!==r||e[11]!==c?(V=()=>{r&&(b({directory:c,source:"todoSendDialog"}),w({directory:c}),g())},v=[r,b,w,g,c],e[7]=g,e[8]=w,e[9]=b,e[10]=r,e[11]=c,e[12]=V,e[13]=v):(V=e[12],v=e[13]),i.useEffect(V,v);let O,P;e[14]!==N||e[15]!==j||e[16]!==C||e[17]!==S||e[18]!==r?(O=()=>{r&&D(wu({providerID:C,modelID:j,variant:S,agent:N}))},P=[r,C,j,S,N],e[14]=N,e[15]=j,e[16]=C,e[17]=S,e[18]=r,e[19]=O,e[20]=P):(O=e[19],P=e[20]),i.useEffect(O,P);let E,B;e[21]!==y.modelID||e[22]!==y.providerID||e[23]!==r||e[24]!==h?(E=()=>{if(!r||h.length===0)return;const ce=h.find(tt=>tt.id===y.providerID)??h[0],Ue=Array.isArray(ce?.models)?ce.models:[],qe=Ue.some(tt=>tt.id===y.modelID),Ye=Ue[0]?.id??"";ce?.id===y.providerID&&qe||D(tt=>({...tt,providerID:ce?.id??"",modelID:qe?tt.modelID:Ye,variant:""}))},B=[r,h,y.providerID,y.modelID],e[21]=y.modelID,e[22]=y.providerID,e[23]=r,e[24]=h,e[25]=E,e[26]=B):(E=e[25],B=e[26]),i.useEffect(E,B);const T=Pw;let W;if(e[27]!==y.modelID||e[28]!==y.providerID||e[29]!==h){let ce;e[31]!==y.providerID?(ce=qe=>qe.id===y.providerID,e[31]=y.providerID,e[32]=ce):ce=e[32],W=h.find(ce)?.models?.find(qe=>qe.id===y.modelID),e[27]=y.modelID,e[28]=y.providerID,e[29]=h,e[30]=W}else W=e[30];const U=W;let L;e[33]!==U?(L=U?.variants?Object.keys(U.variants):[],e[33]=U,e[34]=L):L=e[34];const M=L,ee=M.length>0;let ie,X;e[35]!==y.variant||e[36]!==ee?(ie=()=>{ee||!y.variant||D(Tw)},X=[ee,y.variant],e[35]=y.variant,e[36]=ee,e[37]=ie,e[38]=X):(ie=e[37],X=e[38]),i.useEffect(ie,X);let H;e[39]!==y.modelID||e[40]!==y.providerID?(H=y.providerID.trim().length>0&&y.modelID.trim().length>0,e[39]=y.modelID,e[40]=y.providerID,e[41]=H):H=e[41];const te=H;let re;e[42]!==te||e[43]!==y||e[44]!==f||e[45]!==m?(re=()=>{!te||m||f(y)},e[42]=te,e[43]=y,e[44]=f,e[45]=m,e[46]=re):re=e[46];const le=re;let ve,ne;e[47]!==le||e[48]!==r?(ve=()=>{if(!r)return;const ce=Ue=>{(Ue.metaKey||Ue.ctrlKey)&&Ue.key==="Enter"&&(Ue.preventDefault(),le())};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},ne=[r,le],e[47]=le,e[48]=r,e[49]=ve,e[50]=ne):(ve=e[49],ne=e[50]),i.useEffect(ve,ne);let we;e[51]!==n||e[52]!==a?(we=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[51]=n,e[52]=a,e[53]=we):we=e[53];const he=we;let Me;e[54]!==o||e[55]!==m?(Me=ce=>{m||o(ce)},e[54]=o,e[55]=m,e[56]=Me):Me=e[56];let z;e[57]!==he?(z=s.jsx(sn,{children:s.jsx(Hs,{children:he})}),e[57]=he,e[58]=z):z=e[58];let K;e[59]!==n?(K=n("chat.modelControls.model"),e[59]=n,e[60]=K):K=e[60];let q;e[61]!==K?(q=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:K}),e[61]=K,e[62]=q):q=e[62];let me;e[63]===Symbol.for("react.memo_cache_sentinel")?(me=(ce,Ue)=>{D(qe=>({...qe,providerID:ce,modelID:Ue,variant:""}))},e[63]=me):me=e[63];let Se;e[64]!==y.modelID||e[65]!==y.providerID?(Se=s.jsx(am,{providerId:y.providerID,modelId:y.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:me}),e[64]=y.modelID,e[65]=y.providerID,e[66]=Se):Se=e[66];let Be;e[67]!==q||e[68]!==Se?(Be=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[q,Se]}),e[67]=q,e[68]=Se,e[69]=Be):Be=e[69];let _e;e[70]!==n?(_e=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[70]=n,e[71]=_e):_e=e[71];let Le;e[72]!==_e?(Le=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:_e}),e[72]=_e,e[73]=Le):Le=e[73];const pe=!ee;let Ee;e[74]===Symbol.for("react.memo_cache_sentinel")?(Ee=ce=>D(Ue=>({...Ue,variant:ce})),e[74]=Ee):Ee=e[74];let ge;e[75]!==y.variant||e[76]!==pe||e[77]!==M?(ge=s.jsx(Wp,{value:y.variant,options:M,disabled:pe,onChange:Ee}),e[75]=y.variant,e[76]=pe,e[77]=M,e[78]=ge):ge=e[78];let oe;e[79]!==Le||e[80]!==ge?(oe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Le,ge]}),e[79]=Le,e[80]=ge,e[81]=oe):oe=e[81];let je;e[82]!==n?(je=n("sessions.scheduledTasks.editor.agent.label"),e[82]=n,e[83]=je):je=e[83];let ye;e[84]!==je?(ye=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:je}),e[84]=je,e[85]=ye):ye=e[85];let ue;e[86]===Symbol.for("react.memo_cache_sentinel")?(ue=ce=>D(Ue=>({...Ue,agent:ce})),e[86]=ue):ue=e[86];let De;e[87]!==y.agent?(De=s.jsx(lm,{agentName:y.agent,filter:T,dropdownPortalToBody:!0,onChange:ue}),e[87]=y.agent,e[88]=De):De=e[88];let I;e[89]!==ye||e[90]!==De?(I=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[ye,De]}),e[89]=ye,e[90]=De,e[91]=I):I=e[91];let _;e[92]!==Be||e[93]!==oe||e[94]!==I?(_=s.jsxs("div",{className:"flex flex-col gap-4",children:[Be,oe,I]}),e[92]=Be,e[93]=oe,e[94]=I,e[95]=_):_=e[95];const be=`flex items-center gap-3 ${x?"justify-between":"justify-end"}`;let R;e[96]!==y.runAsGoal||e[97]!==x||e[98]!==m||e[99]!==n?(R=x?s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(Or,{checked:y.runAsGoal===!0,onChange:ce=>D(Ue=>({...Ue,runAsGoal:ce})),disabled:m,ariaLabel:n("sessions.scheduledTasks.editor.goal.aria")}),s.jsx("button",{type:"button",className:"truncate typography-ui-label text-muted-foreground transition-colors hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:m,onClick:()=>D(Dw),children:n("sessions.scheduledTasks.editor.goal.label")})]}):null,e[96]=y.runAsGoal,e[97]=x,e[98]=m,e[99]=n,e[100]=R):R=e[100];let de;e[101]!==o?(de=()=>o(!1),e[101]=o,e[102]=de):de=e[102];let fe;e[103]!==n?(fe=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[103]=n,e[104]=fe):fe=e[104];let $;e[105]!==m||e[106]!==de||e[107]!==fe?($=s.jsx(ze,{variant:"ghost",size:"sm",onClick:de,disabled:m,children:fe}),e[105]=m,e[106]=de,e[107]=fe,e[108]=$):$=e[108];const Ae=!te||m;let Ve;e[109]!==m||e[110]!==n?(Ve=n(m?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[109]=m,e[110]=n,e[111]=Ve):Ve=e[111];let Ne;e[112]!==le||e[113]!==Ae||e[114]!==Ve?(Ne=s.jsx(ze,{size:"sm",onClick:le,disabled:Ae,children:Ve}),e[112]=le,e[113]=Ae,e[114]=Ve,e[115]=Ne):Ne=e[115];let Y;e[116]!==$||e[117]!==Ne?(Y=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[$,Ne]}),e[116]=$,e[117]=Ne,e[118]=Y):Y=e[118];let F;e[119]!==be||e[120]!==R||e[121]!==Y?(F=s.jsxs("div",{className:be,children:[R,Y]}),e[119]=be,e[120]=R,e[121]=Y,e[122]=F):F=e[122];let se;e[123]!==z||e[124]!==_||e[125]!==F?(se=s.jsxs(Vs,{className:"max-w-md overflow-visible",children:[z,_,F]}),e[123]=z,e[124]=_,e[125]=F,e[126]=se):se=e[126];let Oe;return e[127]!==r||e[128]!==Me||e[129]!==se?(Oe=s.jsx(_s,{open:r,onOpenChange:Me,children:se}),e[127]=r,e[128]=Me,e[129]=se,e[130]=Oe):Oe=e[130],Oe}function Dw(t){return{...t,runAsGoal:t.runAsGoal!==!0}}function Tw(t){return{...t,variant:""}}function Pw(t){return Ac(t.mode)}function Iw(t){return t.currentAgentName||""}function Rw(t){return t.currentVariant||""}function Ew(t){return t.currentModelId}function Mw(t){return t.currentProviderId}function Fw(t){return t.providers}function Ow(t){return t.loadAgents}function Lw(t){return t.loadAgents}function Bw(t){return t.loadProviders}const rc=5,Um=15,Xo=new Map,ma=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},Vw=(t,e)=>{const n=ma(e);return Math.max(n*rc,Math.min(n*Um,n*t))},_w=async(t,e)=>{const n=await Kp(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},$w=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,yu=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],vu=(t,e)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},zw=t=>{const e=ht.c(20),{id:n,children:r}=t;let o;e[0]!==n?(o={id:n},e[0]=n,e[1]=o):o=e[1];const{attributes:a,listeners:c,setNodeRef:l,setActivatorNodeRef:d,transform:f,transition:m,isDragging:u}=xc(o);let p;e[2]!==f?(p=bc.Transform.toString(f),e[2]=f,e[3]=p):p=e[3];let x;e[4]!==p||e[5]!==m?(x={transform:p,transition:m},e[4]=p,e[5]=m,e[6]=x):x=e[6];const b=u&&"opacity-60";let w;e[7]!==b?(w=Pe(b),e[7]=b,e[8]=w):w=e[8];let g;e[9]!==a||e[10]!==r||e[11]!==u||e[12]!==c||e[13]!==d?(g=r({attributes:a,listeners:c,setActivatorNodeRef:d,isDragging:u}),e[9]=a,e[10]=r,e[11]=u,e[12]=c,e[13]=d,e[14]=g):g=e[14];let h;return e[15]!==l||e[16]!==x||e[17]!==w||e[18]!==g?(h=s.jsx("li",{ref:l,style:x,className:w,children:g}),e[15]=l,e[16]=x,e[17]=w,e[18]=g,e[19]=h):h=e[19],h},Ww=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=yt(),[c,l]=i.useState(!1),[d,f]=i.useState(""),[m,u]=i.useState([]),[p,x]=i.useState(""),[b,w]=i.useState(null),[g,h]=i.useState(()=>new Set),[C,j]=i.useState([]),[S,N]=i.useState(null),[k,y]=i.useState(!1),[D,V]=i.useState(0),v=i.useRef(!1),O=i.useRef(""),P=i.useRef(null),E=Re(F=>F.todoPanelHeight),B=Re(F=>F.setTodoPanelHeight),T=Re(F=>F.notesPanelHeight),W=Re(F=>F.setNotesPanelHeight),[U,L]=i.useState(!1),M=i.useRef(0),ee=i.useRef(E),ie=mt(F=>F.currentSessionId),X=mt(F=>F.createSession),H=mt(F=>F.initializeNewOpenChamberSession),te=mt(F=>F.sendMessage),re=mt(F=>F.setCurrentSession),le=bi(F=>F.setPendingInputText),ve=Xs(F=>F.currentDirectory),ne=Re(F=>F.openContextPanelTab),we=Re(F=>F.setActiveMainTab),he=Re(F=>F.setSessionSwitcherOpen),Me=Re(F=>F.padding),z=i.useCallback(async(F,se)=>{if(!t)return!1;const Oe=t.id,Ue=(Xo.get(Oe)??Promise.resolve()).catch(()=>{}).then(()=>Up(t,{notes:F,todos:se}));Xo.set(Oe,Ue);try{const qe=await Ue;return qe||ae.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),qe}finally{Xo.get(Oe)===Ue&&Xo.delete(Oe)}},[t,a]);i.useEffect(()=>{if(!t){f(""),u([]),j([]),x(""),h(new Set);return}let F=!1;return l(!0),(async()=>{try{const se=await Hp(t),Oe=await Promise.all(se.plans.map(ce=>_w(ce,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(F)return;f(se.notes),u(yu(se.todos)),j(Oe),O.current=se.notes,v.current=!0,x(""),h(new Set)}catch{F||(ae.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),f(""),u([]),j([]),O.current="",v.current=!0)}finally{F||l(!1)}})(),()=>{F=!0}},[D,t,a]),i.useEffect(()=>{if(!t)return;const F=se=>{const Oe=se.detail;Oe?.projectId&&Oe.projectId!==t.id||V(ce=>ce+1)};return window.addEventListener("openchamber:project-plan-saved",F),window.addEventListener("openchamber:project-notes-updated",F),()=>{window.removeEventListener("openchamber:project-plan-saved",F),window.removeEventListener("openchamber:project-notes-updated",F)}},[t]),i.useEffect(()=>{if(m.length<7)return;const F=Vw(m.length,Me),se=ma(Me)*rc;E!==F&&(E<se||E>F)&&B(F)},[m.length,Me,E,B]),i.useEffect(()=>{if(!U)return;const F=Oe=>{const ce=Oe.clientY-M.current,Ue=Math.min(ma(Me)*Um,Math.max(ma(Me)*rc,ee.current+ce));B(Ue)},se=()=>{L(!1)};return window.addEventListener("pointermove",F),window.addEventListener("pointerup",se,{once:!0}),window.addEventListener("pointercancel",se,{once:!0}),()=>{window.removeEventListener("pointermove",F),window.removeEventListener("pointerup",se),window.removeEventListener("pointercancel",se)}},[U,Me,B]);const K=i.useCallback(F=>{L(!0),M.current=F.clientY,ee.current=E,F.preventDefault()},[E]),q=i.useCallback(()=>{P.current!==null&&(window.clearTimeout(P.current),P.current=null)},[]),me=i.useCallback(()=>{q(),O.current=d,z(d,m)},[q,d,z,m]);i.useEffect(()=>{if(!(!t||!v.current)&&d!==O.current)return P.current=window.setTimeout(()=>{P.current=null,O.current=d,z(d,m)},400),()=>{q()}},[q,d,z,t,m]),i.useEffect(()=>()=>q(),[q]);const Se=i.useCallback(()=>{const F=p.trim();if(!F)return;const se=vu(m,{id:$w(),text:F.slice(0,Yo),completed:!1,createdAt:Date.now()});u(se),x(""),z(d,se)},[p,d,z,m]),Be=i.useCallback(F=>{h(se=>{const Oe=new Set(se);return Oe.has(F)?Oe.delete(F):Oe.add(F),Oe})},[]),_e=i.useCallback((F,se)=>{const Oe=m.find(Ye=>Ye.id===F);if(!Oe||Oe.completed===se)return;const ce=m.filter(Ye=>Ye.id!==F),Ue={...Oe,completed:se},qe=se?[...ce,Ue]:vu(ce,Ue);u(qe),z(d,qe)},[d,z,m]),Le=i.useCallback(F=>{const se=m.filter(Oe=>Oe.id!==F);u(se),z(d,se)},[d,z,m]),pe=i.useCallback(()=>{const F=m.filter(se=>!se.completed);F.length!==m.length&&(u(F),z(d,F))},[d,z,m]),Ee=i.useCallback(F=>{const{active:se,over:Oe}=F;if(!Oe||se.id===Oe.id)return;const ce=m.findIndex(Ye=>Ye.id===se.id),Ue=m.findIndex(Ye=>Ye.id===Oe.id);if(ce===-1||Ue===-1)return;const qe=yu(Gf(m,ce,Ue));u(qe),z(d,qe)},[d,z,m]),ge=ja(Ao(Sa,{activationConstraint:{distance:8}})),oe=p.slice(0,Yo),je=m.reduce((F,se)=>F+(se.completed?1:0),0),ye=i.useCallback(()=>{we("chat"),he(!1)},[we,he]),ue=i.useCallback((F,se)=>{!t||b||N({kind:"session",todoId:F,todoText:se})},[t,b]),De=i.useCallback(F=>{if(!ie){ae.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}ye();const se=`\`\`\`md
4
+ ${F}
5
+ \`\`\``;le(se,"append"),ae.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[ie,r,ye,le,a]),I=i.useCallback((F,se)=>{if(!(!t||b)){if(!n){ae.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}N({kind:"worktree",todoId:F,todoText:se})}},[n,t,b,a]),_=i.useCallback(async F=>{if(!t||!S)return;const se=await Fn("plan.todo.visible",{todo_text:S.todoText}),ce=[{synthetic:!0,text:await Fn("plan.todo.instructions",{todo_text:S.todoText})}];y(!0),w(S.todoId);try{ye();let Ue=null,qe=t.path;if(S.kind==="worktree"){if(!n){ae.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const tt=await cm(t.path,dm());if(!tt?.id)return;Ue=tt.id,qe=tt.path}else{const tt=await X(void 0,t.path,null);if(!tt?.id){ae.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}Ue=tt.id,qe=tt.directory??t.path,H(tt.id,is.getState().agents??[])}if(!Ue)return;const Ye=Dc.getState();Ye.saveSessionModelSelection(Ue,F.providerID,F.modelID),F.agent.trim()&&(Ye.saveSessionAgentSelection(Ue,F.agent),Ye.saveAgentModelForSession(Ue,F.agent,F.providerID,F.modelID),Ye.saveAgentModelVariantForSession(Ue,F.agent,F.providerID,F.modelID,F.variant||void 0)),re(Ue,qe),await te(se,F.providerID,F.modelID,F.agent.trim()||void 0,void 0,void 0,ce,F.variant||void 0),ae.success(S.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),N(null),r?.()}catch(Ue){const qe=Ue instanceof Error?Ue.message:void 0;ae.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),qe?{description:qe}:void 0)}finally{y(!1),w(null)}},[n,X,H,r,S,t,ye,te,re,a]),be=i.useRef(null),[R,de]=i.useState(!1),[fe,$]=i.useState(null),Ae=i.useCallback(async F=>{if(!(!t||fe)){$(F);try{if(!await Gp(t,F)){ae.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}j(Oe=>Oe.filter(ce=>ce.id!==F)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{$(null)}}},[fe,t,a]),Ve=i.useCallback(async()=>{if(!t||R)return;const F=await vp({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(F.success&&F.path){de(!0);try{const se=new URLSearchParams({path:F.path,allowOutsideWorkspace:"true"});F.outsideFileGrant&&se.set("outsideFileGrant",F.outsideFileGrant);const Oe=await Ps(`/api/fs/read?${se.toString()}`,{cache:"no-store"});if(!Oe.ok){ae.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const ce=await Oe.text();if(!ce.trim()){ae.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Ue=F.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Ld(t,ce,Ue)){ae.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),ae.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(se){const Oe=se instanceof Error?se.message:void 0;ae.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),Oe?{description:Oe}:void 0)}finally{de(!1)}}else F.error==="Native file picker not available"&&be.current?.click()},[R,t,a]),Ne=i.useCallback(async F=>{if(!(!t||!F)){de(!0);try{const se=await F.text();if(!se.trim()){ae.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Oe=F.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Ld(t,se,Oe)){ae.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),ae.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(se){const Oe=se instanceof Error?se.message:void 0;ae.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),Oe?{description:Oe}:void 0)}finally{de(!1)}}},[t,a]),Y=i.useCallback(F=>{const se=t?.path?.trim(),Oe=ve?.trim()||se;Oe&&ne(Oe,{mode:"plan",targetPath:F.path,dedupeKey:F.path,label:F.title})},[ve,ne,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,"/",Bd]})]}),s.jsx(Pi,{value:d,onChange:F=>f(F.target.value.slice(0,Bd)),onBlur:me,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:T,onResizeHeightChange:W,useScrollShadow:!0,scrollShadowSize:56,disabled:c})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:a("rightSidebar.contextNotesTodo.todo.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:m.length===1?a("rightSidebar.contextNotesTodo.todo.itemsSingle",{count:m.length}):a("rightSidebar.contextNotesTodo.todo.itemsPlural",{count:m.length})}),s.jsx("button",{type:"button",onClick:pe,disabled:c||je===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:a("rightSidebar.contextNotesTodo.todo.clearCompleted")})]}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[oe.length,"/",Yo]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Ln,{value:oe,onChange:F=>x(F.target.value.slice(0,Yo)),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),Se())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:Se,disabled:c||oe.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.addAria"),title:a("rightSidebar.contextNotesTodo.todo.addAria"),children:s.jsx(A,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:Pe("overflow-y-auto rounded-lg border border-border/60 bg-background/40",U&&"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(Na,{sensors:ge,collisionDetection:ka,onDragEnd:Ee,children:s.jsx(Hl,{items:m.map(F=>F.id),strategy:Gl,children:s.jsx("ul",{className:"divide-y divide-border/50",children:m.map(F=>{const se=g.has(F.id);return s.jsx(zw,{id:F.id,children:Oe=>s.jsxs("div",{className:Pe("flex gap-1.5 px-2.5 py-1.5",se?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:Oe.setActivatorNodeRef,...Oe.attributes,...Oe.listeners,onClick:ce=>{ce.preventDefault(),ce.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:F.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:F.text}),children:s.jsx(A,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(Or,{checked:F.completed,onChange:ce=>_e(F.id,ce),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:F.text})})}),s.jsx("button",{type:"button",onClick:()=>Be(F.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",se?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",F.completed&&"text-muted-foreground line-through"),title:se?void 0:F.text,"aria-label":se?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:F.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:F.text}),children:F.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Le(F.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:F.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:F.text}),children:s.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",disabled:b===F.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.send",{text:F.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:F.text}),children:s.jsx(A,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(en,{align:"end",className:"w-56",children:[s.jsx(ms,{onClick:()=>De(F.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(ms,{onClick:()=>ue(F.id,F.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(ms,{onClick:()=>{I(F.id,F.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},F.id)})})})})}),m.length>=7&&s.jsx("div",{className:Pe("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",U&&"bg-[var(--interactive-border)]"),onPointerDown:K,role:"separator","aria-orientation":"horizontal","aria-label":a("rightSidebar.contextNotesTodo.todo.resizeAria")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:a("rightSidebar.contextNotesTodo.plans.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:C.length===1?a("rightSidebar.contextNotesTodo.plans.filesSingle",{count:C.length}):a("rightSidebar.contextNotesTodo.plans.filesPlural",{count:C.length})})]}),s.jsx("input",{ref:be,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:F=>{const se=F.target.files?.[0]??null;Ne(se),F.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Ve,disabled:!t||R,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.plans.importFromFile"),title:a("rightSidebar.contextNotesTodo.plans.importFromFile"),children:s.jsx(A,{name:"add",className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:C.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.plans.empty")}):s.jsx("ul",{className:"divide-y divide-border/50",children:C.map(F=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>Y(F),className:"flex min-w-0 flex-1 items-center justify-between gap-3 rounded-md px-1.5 py-1 text-left hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-foreground",children:F.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(F.createdAt).toLocaleDateString(so())})]}),s.jsx("button",{type:"button",onClick:()=>{Ae(F.id)},disabled:fe===F.id,className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",title:a("rightSidebar.contextNotesTodo.plans.deletePlan"),"aria-label":a("rightSidebar.contextNotesTodo.plans.deletePlanWithTitle",{title:F.title}),children:s.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},F.id))})})]}),s.jsx(Wm,{open:S!==null,onOpenChange:F=>{!F&&!k&&N(null)},target:S?.kind??"session",projectDirectory:t?.path??null,submitting:k,onConfirm:_})]}):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")})})},Hm=12,Uw=[{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"}],Hw=t=>{const e=ht.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,f=a===void 0?900:a,m=c===void 0?Uw:c,u=nt.useRef(!1);let p,x;e[0]!==n||e[1]!==l?(p=()=>{!n&&u.current&&l?.(),n&&(u.current=!0)},x=[n,l],e[0]=n,e[1]=l,e[2]=p,e[3]=x):(p=e[2],x=e[3]),nt.useEffect(p,x);let b;e[4]===Symbol.for("react.memo_cache_sentinel")?(b=Array.from({length:Hm},Gw),e[4]=b):b=e[4];const w=b;if(!n)return null;let g;e[5]!==o?(g=Pe("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=g):g=e[6];let h;if(e[7]!==d||e[8]!==m||e[9]!==f){let j;e[11]!==d||e[12]!==f?(j=S=>{const N={"--burst-delay":`${S.delay}ms`,"--burst-x":`${S.x}%`,"--burst-y":`${S.y}%`,"--firework-color":`var(${S.colorVar})`,"--firework-duration":`${f}ms`};return s.jsx("div",{className:"firework-burst",style:N,children:w.map((k,y)=>{const D=k.x*S.radius,V=k.y*S.radius,v={"--translate-x":`${D}px`,"--translate-y":`${V}px`,"--particle-delay":`${k.delay}ms`,color:`var(${S.colorVar})`};return s.jsx("span",{className:"firework-particle",style:v},`${S.id}-${y}-${d}`)})},`${S.id}-${d}`)},e[11]=d,e[12]=f,e[13]=j):j=e[13],h=m.map(j),e[7]=d,e[8]=m,e[9]=f,e[10]=h}else h=e[10];let C;return e[14]!==d||e[15]!==g||e[16]!==h?(C=s.jsx("div",{className:g,"aria-hidden":"true","data-burst-key":d,children:h}),e[14]=d,e[15]=g,e[16]=h,e[17]=C):C=e[17],C};function Gw(t,e){const n=Math.PI*2*e/Hm;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const Kw=t=>{const e=ht.c(13);let n;e[0]!==t?(n={},e[0]=t,e[1]=n):n=e[1];const{durationMs:r}=n,o=r===void 0?3400:r;let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a={isActive:!1,cycle:0},e[2]=a):a=e[2];const[c,l]=nt.useState(a),d=nt.useRef(null);let f;e[3]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{d.current&&(window.clearTimeout(d.current),d.current=null)},e[3]=f):f=e[3];const m=f;let u;e[4]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{m(),l(qw)},e[4]=u):u=e[4];const p=u;let x;e[5]!==o?(x=()=>{m(),l(Yw),d.current=window.setTimeout(()=>{l(Qw),d.current=null},o)},e[5]=o,e[6]=x):x=e[6];const b=x;let w,g;e[7]===Symbol.for("react.memo_cache_sentinel")?(w=()=>()=>m(),g=[m],e[7]=w,e[8]=g):(w=e[7],g=e[8]),nt.useEffect(w,g);let h;return e[9]!==c.cycle||e[10]!==c.isActive||e[11]!==b?(h={isActive:c.isActive,burstKey:c.cycle,triggerFireworks:b,dismissFireworks:p},e[9]=c.cycle,e[10]=c.isActive,e[11]=b,e[12]=h):h=e[12],h};function qw(t){return t.isActive?{...t,isActive:!1}:t}function Yw(t){return{isActive:!0,cycle:t.cycle+1}}function Qw(t){return t.isActive?{...t,isActive:!1}:t}const Gm=i.createContext(void 0),Jw=t=>{const e=ht.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=Kw();let l;e[0]!==c||e[1]!==a?(l={triggerFireworks:a,dismissFireworks:c},e[0]=c,e[1]=a,e[2]=l):l=e[2];const d=l;let f;e[3]!==o||e[4]!==r?(f=s.jsx(Hw,{isActive:r,burstKey:o}),e[3]=o,e[4]=r,e[5]=f):f=e[5];let m;return e[6]!==n||e[7]!==f||e[8]!==d?(m=s.jsxs(Gm.Provider,{value:d,children:[n,f]}),e[6]=n,e[7]=f,e[8]=d,e[9]=m):m=e[9],m},Xw=()=>{const t=i.useContext(Gm);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Km="gitmojiCache",Zw=1e3*60*60*24*7,qm="1",ey="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Ym=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},Sl=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Km);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==qm||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(Ym),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},ty=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:qm};window.localStorage.setItem(Km,JSON.stringify(e))}catch{return}},ju=t=>Date.now()-t.fetchedAt<Zw;let Zo=null;const Io=new Set,Su=async()=>{if(Zo)return Zo;const t=(async()=>{try{const e=await fetch(ey);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(Ym):[];return ty(r),Io.forEach(o=>o(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return Io.forEach(r=>r(n)),n}finally{Zo=null}})();return Zo=t,t},sy=t=>{const[e,n]=i.useState(()=>t?Sl()?.gitmojis??[]:[]),[r,o]=i.useState(!1),a=i.useRef(t);a.current=t,i.useEffect(()=>{if(!t){Io.delete(n),n([]),o(!1);return}const l=Sl();if(l&&(n(l.gitmojis),ju(l)))return;Io.add(n),o(!0);let d=!1;return Su().finally(()=>{!d&&a.current&&o(!1)}),()=>{d=!0,Io.delete(n)}},[t]);const c=i.useCallback(async()=>{if(!a.current)return[];if(e.length>0)return e;const l=Sl();return l&&ju(l)?l.gitmojis:Su()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:c}},Nu=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function ny(t,e,n){const r=ht.c(5),[o,a]=i.useState();let c,l;return r[0]!==n||r[1]!==t||r[2]!==e?(c=()=>{if(e){a(void 0);return}if(!t){a(void 0);return}a(void 0);let d=!1;return(async()=>{const[f,m]=await Promise.all([qp(t),Yp(t)]).catch(ry);if(d)return;const u=Nu(f),p=Nu(m);if(!u||!p||p===u)return;const x=n||"",b=p.split("/").filter(Boolean).pop()||p;a({source:"sdk",path:p,projectDirectory:u,branch:x,label:x||b,name:b,worktreeRoot:p,worktreeStatus:"ready",headState:x?"branch":"unborn",worktreeSource:"existing"})})(),()=>{d=!0}},l=[t,e,n],r[0]=n,r[1]=t,r[2]=e,r[3]=c,r[4]=l):(c=r[3],l=r[4]),i.useEffect(c,l),e??o}function ry(){return["",""]}const ho=async(t,e)=>{const n=await Ps(`/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 vo(t){return ho("plan",t)}async function iy(t){return ho("conflict-details",{tempWorktreePath:t})}async function oy(t){return(await ho("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function ay(t){return ho("run",{plan:t})}async function ly(t){await ho("abort",{state:t})}async function cy(t){return ho("continue",{state:t})}const dy=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=yt(),d=mt(M=>M.currentSessionId),f=Re(M=>M.setActiveMainTab),[m,u]=nt.useState(!1),p=nt.useRef(null),[x,b]=nt.useState(o);nt.useEffect(()=>{b(o)},[o]),nt.useEffect(()=>{if(m){const M=setTimeout(()=>{p.current?.focus()},0);return()=>clearTimeout(M)}},[m]);const w=!!(t&&e&&x&&x!=="HEAD"&&e!==x),[g,h]=nt.useState({kind:"idle"}),[C,j]=nt.useState(!1),[S,N]=nt.useState([]),k=nt.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);nt.useEffect(()=>{if(!k||typeof window>"u")return;const M=window.localStorage.getItem(k);if(!M)return;let ee=!1;try{const ie=JSON.parse(M);if(!ie?.tempWorktreePath||ie.repoRoot!==t){window.localStorage.removeItem(k);return}(async()=>{const X=await oy(ie.tempWorktreePath).catch(()=>!1);if(ee)return;if(!X){window.localStorage.removeItem(k);return}const H=await iy(ie.tempWorktreePath).catch(()=>null);ee||H&&h({kind:"conflict",state:ie,details:H})})()}catch{window.localStorage.removeItem(k)}return()=>{ee=!0}},[k,t]),nt.useEffect(()=>{if(!w){h({kind:"idle"});return}let M=!1;return h({kind:"loading"}),(async()=>{try{const ee=await vo({repoRoot:t,sourceBranch:e,targetBranch:x});if(M)return;if(h({kind:"ready",plan:ee}),ee.commits.length>0){const X=ee.commits.slice(-50).reverse(),H=await Qp(t,X);M||(N(H),j(!1))}else M||(N([]),j(!1))}catch{M||h({kind:"idle"})}})(),()=>{M=!0}},[w,t,e,x,a]);const y=nt.useCallback(M=>{d&&mt.getState().setWorktreeMetadata(d,{...n,createdFromBranch:M})},[d,n]),D=mt(M=>M.openNewSessionDraft),V=nt.useCallback(async M=>{const ee=await Fn("git.integrate.cherrypick.resolve.visible",{current_commit:M.state.currentCommit,target_branch:M.state.targetBranch}),ie=await Fn("git.integrate.cherrypick.resolve.instructions",{repo_root:M.state.repoRoot,temp_worktree_path:M.state.tempWorktreePath,source_branch:M.state.sourceBranch,target_branch:M.state.targetBranch,current_commit:M.state.currentCommit}),X=`Cherry-pick conflict context (JSON)
6
+ ${JSON.stringify({repoRoot:M.state.repoRoot,tempWorktreePath:M.state.tempWorktreePath,sourceBranch:M.state.sourceBranch,targetBranch:M.state.targetBranch,currentCommit:M.state.currentCommit,remainingCommits:M.state.remainingCommits,statusPorcelain:M.details.statusPorcelain,unmergedFiles:M.details.unmergedFiles,currentPatchMeta:M.details.currentPatchMeta,currentPatch:M.details.currentPatch,diff:M.details.diff},null,2)}`;return{visibleText:ee,instructionsText:ie,payloadText:X}},[]),v=bi(M=>M.setPendingInputText),O=bi(M=>M.setPendingSyntheticParts),P=nt.useCallback(async(M,ee)=>{const ie=await V(M);if(ee){D({directoryOverride:M.state.tempWorktreePath,initialPrompt:ie.visibleText,syntheticParts:[{text:ie.instructionsText,synthetic:!0},{text:ie.payloadText,synthetic:!0}]}),f("chat");return}if(!d){ae.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}v(ie.visibleText,"replace"),O([{text:ie.instructionsText,synthetic:!0},{text:ie.payloadText,synthetic:!0}]),f("chat")},[d,f,V,D,v,O,l]),E=nt.useCallback(async()=>{if(g.kind==="ready"){if(g.plan.commits.length===0){ae.message(l("gitView.integrate.noCommitsToMoveToast"));return}h({kind:"running",plan:g.plan});try{const M=await ay(g.plan);if(M.kind==="success"){ae.success(l("gitView.integrate.commitsMovedToast"),{description:M.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:M.moved,branch:g.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:M.moved,branch:g.plan.targetBranch})});const ee=await vo(g.plan);h({kind:"ready",plan:ee}),c?.();return}M.kind==="conflict"&&(ae.error(l("gitView.integrate.cherryPickConflictToast"),{description:l("gitView.integrate.cherryPickConflictDescription")}),h({kind:"conflict",state:M.state,details:M.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(M.state)))}catch(M){const ee=M instanceof Error?M.message:String(M);ae.error(l("gitView.integrate.failedToMoveToast"),{description:ee});const ie=await vo({repoRoot:t,sourceBranch:e,targetBranch:x}).catch(()=>null);h(ie?{kind:"ready",plan:ie}:{kind:"idle"})}}},[g,c,t,e,x,k,l]),B=nt.useCallback(async()=>{if(g.kind==="conflict")try{await ly(g.state),ae.message(l("gitView.integrate.cherryPickAbortedToast")),k&&typeof window<"u"&&window.localStorage.removeItem(k)}finally{const M=await vo({repoRoot:t,sourceBranch:e,targetBranch:x}).catch(()=>null);h(M?{kind:"ready",plan:M}:{kind:"idle"})}},[g,t,e,x,k,l]),T=nt.useCallback(async()=>{if(g.kind==="conflict")try{const M=await cy(g.state);if(M.kind==="success"){ae.success(l("gitView.integrate.cherryPickFinishedToast"));const ee=await vo({repoRoot:t,sourceBranch:e,targetBranch:x}).catch(()=>null);h(ee?{kind:"ready",plan:ee}:{kind:"idle"}),k&&typeof window<"u"&&window.localStorage.removeItem(k),c?.();return}M.kind==="conflict"&&(h({kind:"conflict",state:M.state,details:M.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(M.state)))}catch(M){const ee=M instanceof Error?M.message:String(M);ae.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:ee})}},[g,t,e,x,c,k,l]);return!t||!e?null:s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[s.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(A,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.integrate.title")}),g.kind==="ready"&&g.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:g.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:g.kind==="loading"||g.kind==="running"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.integrate.moveCommits")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",x]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(tn,{open:m,onOpenChange:u,children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"sm",className:"gap-1.5",children:[l("gitView.integrate.target"),s.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:x}),s.jsx(A,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(en,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:s.jsxs(Ha,{className:"h-full min-h-0",children:[s.jsx(Ga,{ref:p,placeholder:l("gitView.branch.searchPlaceholder"),onKeyDown:M=>M.stopPropagation()}),s.jsxs(Ka,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(qa,{children:l("gitView.branch.empty")}),s.jsx(Qr,{heading:l("gitView.branch.localBranches"),children:r.map(M=>s.jsx(Jr,{value:M,onSelect:()=>{b(M),y(M),u(!1)},children:M},M))})]})]})})]}),g.kind==="ready"?s.jsx(ze,{size:"sm",onClick:()=>{E()},disabled:!w||g.plan.commits.length===0,children:l("gitView.integrate.move")}):g.kind==="loading"?s.jsx(ze,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):g.kind==="running"?s.jsx(ze,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),g.kind==="ready"&&g.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),g.kind==="ready"&&g.plan.commits.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"typography-meta text-foreground",children:[l("gitView.integrate.commitsToMove"),s.jsxs("span",{className:"text-muted-foreground",children:[" (",g.plan.commits.length,")"]})]}),S.length>0&&g.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>j(M=>!M),className:"typography-micro text-muted-foreground hover:text-foreground",children:l(C?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),s.jsxs("div",{className:"space-y-1",children:[(C?S:S.slice(0,5)).map(M=>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:M.short}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:M.subject||M.sha})]},M.sha)),S.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.previewUnavailable")}),g.plan.commits.length>S.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:S.length})})]})]}),g.kind==="conflict"&&s.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[s.jsx("div",{className:"typography-meta text-foreground",children:l("gitView.integrate.conflictsInFiles",{count:g.details.unmergedFiles.length})}),s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[l("gitView.integrate.currentCommit"),": ",s.jsx("span",{className:"font-mono",children:g.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.details.unmergedFiles.slice(0,6).map(M=>s.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:M},M)),g.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:g.details.unmergedFiles.length-6})})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(ze,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{B()},children:l("gitView.operation.abort")}),s.jsxs(ze,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{P({state:g.state,details:g.details},!1)},children:[s.jsx(A,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs(ze,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{P({state:g.state,details:g.details},!0)},children:[s.jsx(A,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.newSession")]}),s.jsx(ze,{size:"sm",className:"typography-meta",onClick:()=>{T()},children:l("gitView.operation.continue")})]})]})]})]})},uy=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=yt(),[d,f]=i.useState([]),[m,u]=i.useState(!1),[p,x]=i.useState(""),[b,w]=i.useState(""),[g,h]=i.useState(null),[C,j]=i.useState({}),S=i.useCallback(async()=>{if(n){u(!0);try{const v=await Jp(n);f(v.stashes),j({})}catch(v){ae.error(v instanceof Error?v.message:l("gitView.stashes.toast.loadFailed"))}finally{u(!1)}}},[n,l]);i.useEffect(()=>{t&&S()},[S,t]),i.useEffect(()=>{if(!t||!n||d.length===0)return;let v=!1;const O=d.map(P=>P.ref);return Xp(n,O).then(P=>{v||j(P.counts)}).catch(()=>{}),()=>{v=!0}},[n,t,d]);const N=i.useMemo(()=>{const v=p.trim().toLowerCase();return v?d.filter(O=>`${O.ref} ${O.message} ${O.relativeTime}`.toLowerCase().includes(v)):d},[p,d]),k=i.useCallback(async v=>{await S(),await c?.(v)},[S,c]),y=async()=>{if(!(!n||g)){h("create");try{const v=await Zp(n,{message:b.trim()||void 0});v.created?(ae.success(l("gitView.stashes.toast.created")),w("")):ae.info(l("gitView.stashes.toast.noChanges")),await k({affectsIndex:!!(v.created&&o)})}catch(v){ae.error(v instanceof Error?v.message:l("gitView.stashes.toast.createFailed"))}finally{h(null)}}},D=async(v,O)=>{if(!(!n||g)&&!(O==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:v.ref})))){h(`${O}:${v.ref}`);try{O==="apply"&&await eg(n,{ref:v.ref}),O==="pop"&&await tg(n,{ref:v.ref}),O==="drop"&&await sg(n,{ref:v.ref});const P=O==="apply"?"gitView.stashes.toast.applySuccess":O==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";ae.success(l(P)),await k({affectsIndex:O!=="drop"})}catch(P){const E=O==="apply"?"gitView.stashes.toast.applyFailed":O==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";ae.error(P instanceof Error?P.message:l(E)),await k({affectsIndex:O!=="drop"})}finally{h(null)}}},V=g!==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(sn,{children:[s.jsxs(Hs,{className:"flex items-center gap-2",children:[s.jsx(A,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(mn,{children:l("gitView.stashes.description")})]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[s.jsx(Ln,{value:b,onChange:v=>w(v.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:V||!r,className:"flex-1"}),s.jsxs(ze,{onClick:y,disabled:!r||V||!n,children:[g==="create"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"inbox-archive",className:"size-4"}),l("gitView.stashes.actions.stashCurrentWithCount",{count:a})]})]}),s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:l("gitView.stashes.includeUntrackedHint")})]}),s.jsxs("div",{className:"relative mt-2",children:[s.jsx(A,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(Ln,{value:p,onChange:v=>x(v.target.value),placeholder:l("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto",children:m?s.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:s.jsx(A,{name:"loader-4",className:"size-5 animate-spin"})}):N.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:l(p?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):N.map((v,O)=>s.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[s.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[s.jsx("p",{className:"typography-small truncate text-foreground",children:v.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{children:O===0&&!p.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:O+1})})}),s.jsx(Dt,{sideOffset:6,children:v.ref})]})," · ",v.relativeTime," · ",typeof C[v.ref]=="number"?l("gitView.stashes.fileCount",{count:C[v.ref]}):l("gitView.stashes.fileCountLoading")]})]}),s.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[s.jsx(Nl,{label:l("gitView.stashes.actions.apply"),loading:g===`apply:${v.ref}`,onClick:()=>D(v,"apply"),disabled:V,children:s.jsx(A,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(Nl,{label:l("gitView.stashes.actions.pop"),loading:g===`pop:${v.ref}`,onClick:()=>D(v,"pop"),disabled:V,children:s.jsx(A,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(Nl,{label:l("gitView.stashes.actions.drop"),loading:g===`drop:${v.ref}`,onClick:()=>D(v,"drop"),disabled:V,destructive:!0,children:s.jsx(A,{name:"delete-bin",className:"size-4"})})]})]},v.ref))})]})})},Nl=t=>{const e=ht.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,f=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let m;e[0]!==f?(m=Pe("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",f),e[0]=f,e[1]=m):m=e[1];let u;e[2]!==l||e[3]!==r?(u=r?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):l,e[2]=l,e[3]=r,e[4]=u):u=e[4];let p;e[5]!==o||e[6]!==n||e[7]!==c||e[8]!==d||e[9]!==m||e[10]!==u?(p=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:m,onClick:c,disabled:o,children:u})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=m,e[10]=u,e[11]=p):p=e[11];let x;e[12]!==n?(x=s.jsx(Dt,{sideOffset:6,children:n}),e[12]=n,e[13]=x):x=e[13];let b;return e[14]!==p||e[15]!==x?(b=s.jsxs(Ct,{children:[p,x]}),e[14]=p,e[15]=x,e[16]=b):b=e[16],b},fy=t=>{const e=ht.c(16),{onOpenStashes:n}=t,{t:r}=yt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(A,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e[0]=o):o=e[0];let a;e[1]!==r?(a=r("gitView.empty.cleanTitle"),e[1]=r,e[2]=a):a=e[2];let c;e[3]!==a?(c=s.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:a}),e[3]=a,e[4]=c):c=e[4];let l;e[5]!==r?(l=r("gitView.empty.cleanDescription"),e[5]=r,e[6]=l):l=e[6];let d;e[7]!==l?(d=s.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:l}),e[7]=l,e[8]=d):d=e[8];let f;e[9]!==n||e[10]!==r?(f=n?s.jsxs(ze,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(A,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=f):f=e[11];let m;return e[12]!==c||e[13]!==d||e[14]!==f?(m=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,f]}),e[12]=c,e[13]=d,e[14]=f,e[15]=m):m=e[15],m},fi=8,my=t=>{const e=ht.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,f=Math.max(r,a+1)*fi+fi/2,m=i.useRef(null),u=i.useRef(null);let p;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==f?(p=()=>{const h=m.current,C=u.current;if(!h||!C)return;const j=h.offsetHeight;if(j===0)return;const S=window.devicePixelRatio||1;C.width=f*S,C.height=j*S;const N=C.getContext("2d");if(!N)return;N.scale(S,S),N.clearRect(0,0,f,j);const k=j/2,y=a*fi+fi/2,D=getComputedStyle(C),V=D.getPropertyValue("--surface-muted-foreground").trim()||D.color,v=E=>{if(!E.startsWith("var("))return E;const B=E.slice(4,-1).trim();return D.getPropertyValue(B).trim()||V},O=[...l].sort(py);for(const E of O){const B=E.fromLane*fi+fi/2,T=E.toLane*fi+fi/2,W=E.type==="passing"?.72:E.type==="branch-out"||E.type==="merge-in"?.95:1;N.beginPath(),N.strokeStyle=v(E.color),N.globalAlpha=W,N.lineWidth=1.25,N.lineCap="round";e:switch(E.type){case"passing":case"commit-lane":{N.moveTo(B,0),N.lineTo(B,j);break e}case"top-stub":{N.moveTo(B,0),N.lineTo(B,k);break e}case"bottom-stub":{N.moveTo(B,k),N.lineTo(B,j);break e}case"branch-out":{const U=(k+j)/2;N.moveTo(y,k),N.bezierCurveTo(y,U,T,U,T,j);break e}case"merge-in":{const U=k/2;N.moveTo(B,0),N.bezierCurveTo(B,U,y,U,y,k);break e}default:continue}N.stroke(),N.globalAlpha=1}const P=D.getPropertyValue("--background").trim()||D.getPropertyValue("--surface-background").trim();N.beginPath(),N.arc(y,k,4,0,Math.PI*2),N.fillStyle=v(c),N.fill(),N.beginPath(),N.arc(y,k,5,0,Math.PI*2),N.strokeStyle=P||V,N.lineWidth=2,N.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=f,e[4]=p):p=e[4];let x;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==f?(x=[n,a,c,l,r,o,f],e[5]=c,e[6]=l,e[7]=o,e[8]=a,e[9]=n,e[10]=r,e[11]=f,e[12]=x):x=e[12],i.useLayoutEffect(p,x);let b;e[13]!==f?(b={width:f,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=f,e[14]=b):b=e[14];let w;e[15]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx("canvas",{ref:u,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=w):w=e[15];let g;return e[16]!==b?(g=s.jsx("div",{ref:m,style:b,children:w}),e[16]=b,e[17]=g):g=e[17],g};function hy(t){return t==="branch-out"||t==="merge-in"}function py(t,e){const n=hy;return(n(t.type)?1:0)-(n(e.type)?1:0)}const ku=15e3,Cu=500,Au=12,Du=8*1024*1024,Tu=t=>typeof t=="string"?0:(t.original?.length??0)+(t.modified?.length??0),Pu=t=>{if(t.size<=Au){let o=0;for(const a of t.values())o+=Tu(a);if(o<=Du)return t}const e=Array.from(t.entries()).reverse(),n=new Map;let r=0;for(const[o,a]of e){if(n.size>=Au)continue;const c=Tu(a);r+c>Du&&n.size>0||(n.set(o,a),r+=c)}return new Map(Array.from(n.entries()).reverse())};function Iu(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:Tc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gy(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 xy(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 by=i.memo(({entry:t,mode:e="history",laned:n,totalLanes:r,isExpanded:o,onToggle:a,files:c,isLoadingFiles:l,onCopyHash:d,directory:f,onConflict:m,onActionSuccess:u})=>{const{t:p}=yt(),x=Re(H=>H.timeFormatPreference),b=e==="graph",[w,g]=i.useState(null),[h,C]=i.useState(!1),[j,S]=i.useState(""),[N,k]=i.useState(null),[y,D]=i.useState(new Set),[V,v]=i.useState(new Map),[O,P]=i.useState(new Set),E=async()=>{if(f){g("checkout");try{await dg(f,t.hash),ae.success(p("gitView.history.actions.detachedHead")),u?.()}catch(H){ae.error(String(H.message))}finally{g(null)}}},B=async()=>{if(!(!f||!j.trim())){g("createBranch");try{await rg(f,j.trim(),t.hash),C(!1),S(""),u?.()}catch(H){ae.error(String(H.message))}finally{g(null)}}},T=async()=>{if(f){g("cherryPick");try{const H=await cg(f,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"cherry-pick"}):u?.()}catch(H){ae.error(String(H.message))}finally{g(null)}}},W=async()=>{if(f){g("revert");try{const H=await lg(f,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"revert"}):u?.()}catch(H){ae.error(String(H.message))}finally{g(null)}}},U=async(H,te=!1)=>{if(!(!f||w!==null)){g("reset");try{await ig(f,t.hash,H,te),u?.()}catch(re){ae.error(String(re.message))}finally{g(null)}}},L=async()=>{if(!N)return;const H=N;switch(k(null),H){case"checkout":return E();case"cherryPick":return T();case"revert":return W();case"merge":return M();case"rebase":return ee();case"resetSoft":return U("soft");case"resetMixed":return U("mixed");case"resetHard":return U("hard",!0)}},M=async()=>{if(f){g("merge");try{const H=await ag(f,{branch:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"merge"}):u?.()}catch(H){ae.error(String(H.message))}finally{g(null)}}},ee=async()=>{if(f){g("rebase");try{const H=await og(f,{onto:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"rebase"}):u?.()}catch(H){ae.error(String(H.message))}finally{g(null)}}},ie=i.useCallback(async H=>{const te=H.path;if(!f){v(re=>new Map(re).set(te,"error"));return}v(re=>Pu(new Map(re).set(te,"loading")));try{const re=ng(f,t.hash,H.path,!1),le=new Promise((ne,we)=>{setTimeout(()=>we(new Error(`Timed out after ${ku}ms`)),ku)}),ve=await Promise.race([re,le]);v(ne=>Pu(new Map(ne).set(te,ve)))}catch{v(re=>new Map(re).set(te,"error"))}},[f,t.hash]),X=i.useCallback(async H=>{const te=H.path;if(H.changeType==="R"||H.isBinary){D(ne=>{const we=new Set(ne);return we.has(te)?we.delete(te):we.add(te),we});return}const re=V.get(te);if(y.has(te)&&re&&re!=="error"){D(ne=>{const we=new Set(ne);return we.delete(te),we});return}D(ne=>{const we=new Set(ne);return we.add(te),we}),!(re&&re!=="error"||H.insertions+H.deletions>Cu&&!O.has(te))&&await ie(H)},[V,O,ie,y]);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",b?"hover:bg-[var(--interactive-hover)]/40":o?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[b&&n&&r!==void 0?s.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:s.jsx(my,{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:[b?(()=>{const H=xy(t.refs);return H.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:H.map(te=>s.jsx("span",{className:Pe("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",te.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":te.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:te.label},te.label))}):null})():null,s.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:t.message}),s.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[s.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[s.jsx("span",{className:"truncate min-w-[3ch]",title:t.author_name,children:t.author_name}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("span",{className:"truncate min-w-0",title:Iu(t.date,x),children:Iu(t.date,x)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:H=>{H.stopPropagation(),d(t.hash)},children:s.jsx(A,{name:"file-copy",className:"size-3"})})}),s.jsx(Dt,{sideOffset:8,children:p("gitView.history.copySha")})]})]})]})]}),o&&s.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[b&&N?s.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:p(`gitView.history.actions.${N}Confirm`)}),s.jsxs(ze,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:w!==null,onClick:H=>{H.stopPropagation(),L()},children:[w!==null?s.jsx(A,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.confirmButton")]}),s.jsx(ze,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:w!==null,onClick:H=>{H.stopPropagation(),k(null)},children:p("gitView.history.actions.cancelButton")})]}):b?s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:w!==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:j,onChange:H=>S(H.target.value),onKeyDown:H=>{H.key==="Enter"&&B(),H.key==="Escape"&&(C(!1),S(""))},placeholder:p("gitView.history.actions.createBranchPlaceholder"),className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),s.jsxs(ze,{variant:"outline",size:"xs",className:"h-6",disabled:!j.trim()||w!==null,onClick:H=>{H.stopPropagation(),B()},children:[w==="createBranch"?s.jsx(A,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.createBranchConfirm")]})]}):s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",onClick:H=>{H.stopPropagation(),C(!0)},children:p("gitView.history.actions.createBranch")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:w!==null,onClick:H=>{H.stopPropagation(),k("cherryPick")},children:p("gitView.history.actions.cherryPick")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:w!==null,onClick:H=>{H.stopPropagation(),k("revert")},children:p("gitView.history.actions.revert")}),s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"xs",className:"h-6",disabled:w!==null,onClick:H=>H.stopPropagation(),children:[w==="reset"?s.jsx(A,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.reset")]})}),s.jsx(en,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(H=>s.jsx(ms,{disabled:w!==null,onSelect:te=>{te.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(ze,{variant:"outline",size:"xs",className:"h-6",disabled:w!==null,onClick:H=>{H.stopPropagation(),k("merge")},children:p("gitView.history.actions.merge")}),s.jsx(ze,{variant:"outline",size:"xs",className:"h-6",disabled:w!==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(A,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:p("gitView.history.loadingFiles")})]}):c.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:p("gitView.history.noFiles")}):s.jsx("ul",{className:"space-y-0.5 py-2",children:c.map(H=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>X(H),className:Pe("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",y.has(H.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:Pe("font-semibold w-3 text-center shrink-0",gy(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(A,{name:y.has(H.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),y.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 te=H.insertions+H.deletions;if(!O.has(H.path)&&te>Cu)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:te})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:p("gitView.history.largeDiffDescription")}),s.jsx(ze,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{P(le=>new Set(le).add(H.path)),ie(H)},children:p("gitView.history.renderDiffAnyway")})]});const re=V.get(H.path);return re==="loading"||re===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.loadingDiff")}):re==="error"?s.jsx("button",{type:"button",onClick:()=>X(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(Em,{original:re.original,modified:re.modified,language:Ri(H.path)||"",fileName:H.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},H.path))})]})]})}),Ru=["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 ea(t){return Ru[t%Ru.length]}function wy(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let x=0;x<e.length;x++)e[x]===o.hash&&a.push(x);let c=a.length>0?a[0]:-1;if(c===-1){const x=e.indexOf(null);x!==-1?c=x:(c=e.length,e.push(null))}const l=a.slice(1),d=ea(c),f=e[c]===o.hash,m=o.parents.length>0;m?e[c]=o.parents[0]:e[c]=null;const u=[];for(let x=1;x<o.parents.length;x++){const b=o.parents[x],w=e.indexOf(b);if(w!==-1)u.push(w);else{const g=e.indexOf(null),h=g!==-1?g:e.length;e[h]=b,h===e.length&&e.push(b),u.push(h)}}const p=[];f&&m?p.push({fromLane:c,toLane:c,color:d,type:"commit-lane"}):f&&!m?p.push({fromLane:c,toLane:c,color:d,type:"top-stub"}):!f&&m&&p.push({fromLane:c,toLane:c,color:d,type:"bottom-stub"});for(const x of l)p.push({fromLane:x,toLane:c,color:ea(x),type:"merge-in"}),e[x]=null;for(const x of u)p.push({fromLane:c,toLane:x,color:ea(x),type:"branch-out"});for(let x=0;x<e.length;x++)e[x]!==null&&x!==c&&(u.includes(x)||p.push({fromLane:x,toLane:x,color:ea(x),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:p})}return n}const yy=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],vy=t=>{const e=ht.c(84),{mode:n,log:r,isLogLoading:o,logMaxCount:a,onLogMaxCountChange:c,expandedCommitHashes:l,onToggleCommit:d,commitFilesMap:f,loadingCommitHashes:m,onCopyHash:u,directory:p,showHeader:x,contentMaxHeightClassName:b,branchDivider:w,onConflict:g,onActionSuccess:h}=t,C=n===void 0?"history":n,j=x===void 0?!0:x,S=b===void 0?"max-h-[50vh]":b,N=w===void 0?null:w,{t:k}=yt(),[y,D]=i.useState(!0),V=C==="graph";let v;e[0]!==V||e[1]!==r?(v=V&&r?wy(r.all):[],e[0]=V,e[1]=r,e[2]=v):v=e[2];const O=v;let P;e[3]!==O?(P=Math.max(1,...O.map(jy)),e[3]=O,e[4]=P):P=e[4];const E=P;let B;e[5]!==O?(B=new Map(O.map(Sy)),e[5]=O,e[6]=B):B=e[6];const T=B;if(!r)return null;const W=N!==null&&N.insertBeforeIndex>0&&N.insertBeforeIndex<r.all.length,U=N!==null&&N.insertBeforeIndex===r.all.length,L=W||U;let M;e[7]!==N||e[8]!==W||e[9]!==U||e[10]!==r.all?(M=W?r.all.slice(0,N.insertBeforeIndex):U?r.all:[],e[7]=N,e[8]=W,e[9]=U,e[10]=r.all,e[11]=M):M=e[11];const ee=M;let ie;if(e[12]!==N||e[13]!==f||e[14]!==S||e[15]!==p||e[16]!==l||e[17]!==W||e[18]!==L||e[19]!==V||e[20]!==o||e[21]!==T||e[22]!==m||e[23]!==r.all||e[24]!==a||e[25]!==E||e[26]!==C||e[27]!==h||e[28]!==g||e[29]!==u||e[30]!==c||e[31]!==d||e[32]!==k||e[33]!==ee){const Me=W?r.all.slice(N.insertBeforeIndex):[];let z;e[35]!==N?.direction?(z=N?.direction==="down"?s.jsx(A,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(A,{name:"arrow-up",className:"size-3.5"}),e[35]=N?.direction,e[36]=z):z=e[36];const K=z;let q;e[37]!==f||e[38]!==p||e[39]!==l||e[40]!==V||e[41]!==T||e[42]!==m||e[43]!==E||e[44]!==C||e[45]!==h||e[46]!==g||e[47]!==u||e[48]!==d?(q=_e=>s.jsx("ul",{className:"divide-y divide-border/60",children:_e.map(Le=>s.jsx(by,{entry:Le,mode:C,laned:V?T.get(Le.hash):void 0,totalLanes:V?E:void 0,isExpanded:l.has(Le.hash),onToggle:()=>d(Le.hash),files:f.get(Le.hash)??[],isLoadingFiles:m.has(Le.hash),onCopyHash:u,directory:p,onConflict:g,onActionSuccess:h},Le.hash))}),e[37]=f,e[38]=p,e[39]=l,e[40]=V,e[41]=T,e[42]=m,e[43]=E,e[44]=C,e[45]=h,e[46]=g,e[47]=u,e[48]=d,e[49]=q):q=e[49];const me=q;let Se;e[50]!==o||e[51]!==r.all.length||e[52]!==a||e[53]!==c||e[54]!==k?(Se=r.all.length>=a?s.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:s.jsx(ze,{type:"button",variant:"ghost",size:"xs",onClick:()=>c(a+25),disabled:o,className:"px-3 text-muted-foreground hover:text-foreground",children:o?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(A,{name:"loader-4",className:"size-3 animate-spin"}),k("gitView.history.loadingMore")]}):k("gitView.history.loadMore")})}):null,e[50]=o,e[51]=r.all.length,e[52]=a,e[53]=c,e[54]=k,e[55]=Se):Se=e[55];const Be=Se;ie=s.jsx(On,{outerClassName:`min-h-0 ${S}`,className:"h-full w-full",children:r.all.length===0?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:k("gitView.history.noCommits")})}):L&&N?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col gap-0",children:[ee.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:me(ee)}):null,s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5","aria-hidden":!0,children:[s.jsx("span",{className:"h-px flex-1 bg-border/60"}),s.jsxs("span",{className:"inline-flex max-w-[80%] items-center gap-1 typography-micro text-muted-foreground",children:[s.jsx("span",{className:"truncate",title:N.branchName,children:N.branchName}),K]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),Me.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:me(Me)}):null]}),Be]}):s.jsxs(s.Fragment,{children:[me(r.all),Be]})}),e[12]=N,e[13]=f,e[14]=S,e[15]=p,e[16]=l,e[17]=W,e[18]=L,e[19]=V,e[20]=o,e[21]=T,e[22]=m,e[23]=r.all,e[24]=a,e[25]=E,e[26]=C,e[27]=h,e[28]=g,e[29]=u,e[30]=c,e[31]=d,e[32]=k,e[33]=ee,e[34]=ie}else ie=e[34];const X=ie;if(!j){if(L){let z;return e[56]!==X?(z=s.jsx("section",{className:"h-full min-h-0",children:X}),e[56]=X,e[57]=z):z=e[57],z}let Me;return e[58]!==X?(Me=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:X}),e[58]=X,e[59]=Me):Me=e[59],Me}let H;e[60]!==k?(H=k("gitView.history.title"),e[60]=k,e[61]=H):H=e[61];let te;e[62]!==H?(te=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:H}),e[62]=H,e[63]=te):te=e[63];let re;e[64]!==o||e[65]!==y||e[66]!==a||e[67]!==c||e[68]!==k?(re=y&&s.jsx("div",{onClick:Ny,onPointerDown:ky,children:s.jsxs(Gn,{value:String(a),onValueChange:Me=>c(Number(Me)),disabled:o,children:[s.jsx(Kn,{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(Dn,{placeholder:k("gitView.history.commitsPlaceholder")})}),s.jsx(qn,{children:yy.map(Me=>s.jsx(Bs,{value:String(Me.value),children:k(Me.labelKey)},Me.value))})]})}),e[64]=o,e[65]=y,e[66]=a,e[67]=c,e[68]=k,e[69]=re):re=e[69];let le;e[70]!==y?(le=y?s.jsx(A,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(A,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=y,e[71]=le):le=e[71];let ve;e[72]!==re||e[73]!==le?(ve=s.jsxs("div",{className:"flex items-center gap-2",children:[re,le]}),e[72]=re,e[73]=le,e[74]=ve):ve=e[74];let ne;e[75]!==te||e[76]!==ve?(ne=s.jsxs(Uo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[te,ve]}),e[75]=te,e[76]=ve,e[77]=ne):ne=e[77];let we;e[78]!==X?(we=s.jsx(io,{children:X}),e[78]=X,e[79]=we):we=e[79];let he;return e[80]!==y||e[81]!==ne||e[82]!==we?(he=s.jsxs(ro,{open:y,onOpenChange:D,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[ne,we]}),e[80]=y,e[81]=ne,e[82]=we,e[83]=he):he=e[83],he};function jy(t){return t.lane+1}function Sy(t){return[t.commit.hash,t]}function Ny(t){return t.stopPropagation()}function ky(t){return t.stopPropagation()}const Qm=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},Cy=9e4,Ay=15e3,Dy=5*6e4,Ty=[2e3,5e3],Py=6e4,Iy=2*6e4,Ry=5*6e4,Ey=4,My=720*6e4,Fy="openchamber.github-pr-status",Oy=t=>t==="closed"||t==="merged",Ly=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},Ro=(t,e,n)=>`${t}::${e}`,ta=new Map,sa=new Map,jo=new Set,Eu=new Map,By=2;let Fa=0;const Jm=[],Vy=()=>Fa<By?(Fa+=1,Promise.resolve()):new Promise(t=>{Jm.push(t)}),_y=()=>{const t=Jm.shift();if(t){t();return}Fa=Math.max(0,Fa-1)},Co=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null}),Oa=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,Kc=t=>{const e=Oa(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},Xm=(t,e)=>Object.entries(t).filter(([,n])=>Kc(n)===e).map(([n])=>n),$y=(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}}},na=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},zy=(t,e,n)=>{const r=Xm(t,e),o=r.map(d=>na(t[d])).filter(d=>!!d);if(o.length===0)return null;const a=na(t[n]);if(a&&Kc(t[n])===e)return a;const c=r.map(d=>t[d]).find(d=>!!(d?.resolvedRemoteName&&na(d)));if(c)return na(c);const l=o.find(d=>!!d.remoteName);return l||(o[0]??null)},Wy=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:Oa(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Uy=t=>({...Co(),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}),lr=co()(gc((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,ensureEntry:n=>{t(r=>r.entries[n]?r:{entries:{...r.entries,[n]:Co()}})},setParams:(n,r)=>{t(o=>{const a=o.entries[n]??Co();return{entries:{...o.entries,[n]:$y(a,r)}}})},startWatching:n=>{if(t(a=>{const c=a.entries[n]??Co();return{entries:{...a.entries,[n]:{...c,watchers:c.watchers+1}}}}),ta.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=sa.get(n)??[];l.push(c),sa.set(n,l)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),Ty.forEach(a=>r(a));const o=window.setInterval(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const a=e().entries[n];if(!a||a.watchers<=0)return;if(!!!a.status?.pr){const f=Date.now();if(f-a.lastDiscoveryPollAt<Dy)return;t(m=>{const u=m.entries[n];return u?{entries:{...m.entries,[n]:{...u,lastDiscoveryPollAt:f}}}:m}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(Oy(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=Ly(a.status)?Py:a.status?.checks&&a.status.checks.state!=="pending"?Ry:Iy;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},Ay);ta.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=ta.get(n);typeof o=="number"&&window.clearInterval(o),ta.delete(n);const a=sa.get(n);a&&a.length>0&&a.forEach(c=>{window.clearTimeout(c)}),sa.delete(n)},refresh:async(n,r)=>{const o=e(),a=o.entries[n],c=Kc(a);if(!a||!c)return;const l=Xm(o.entries,c),d=l.some(u=>!!o.entries[u]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const f=Eu.get(c)??0;if(!r?.force&&Date.now()-f<Cy||jo.has(c))return;const m=zy(o.entries,c,n);if(m){if(jo.add(c),Eu.set(c,Date.now()),t(u=>{const p={...u.entries};return l.forEach(x=>{const b=p[x];b&&(p[x]={...b,lastRefreshAt:Date.now(),isLoading:r?.silent?b.isLoading:!0,error:null})}),{entries:p}}),m.githubAuthChecked&&m.githubConnected===!1){t(u=>{const p={...u.entries};return l.forEach(x=>{const b=p[x];b&&(p[x]={...b,status:{connected:!1},error:null,isLoading:r?.silent?b.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?b.isInitialStatusResolved:!0})}),{entries:p}}),jo.delete(c);return}if(!m.github?.prStatus){t(u=>{const p={...u.entries};return l.forEach(x=>{const b=p[x];b&&(p[x]={...b,status:null,error:"GitHub runtime API unavailable",isLoading:r?.silent?b.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?b.isInitialStatusResolved:!0})}),{entries:p}}),jo.delete(c);return}try{t(p=>({...p,activeRequestCount:p.activeRequestCount+1,totalRequestCount:p.totalRequestCount+1})),await Vy();let u;try{u=await m.github.prStatus(m.directory,m.branch,m.remoteName??void 0,{force:r?.force})}finally{_y()}t(p=>{const x={...p.entries};return l.forEach(b=>{const w=x[b];if(!w)return;const g=w.status?.pr,h=u.pr,j=!!(h&&g&&h.number===g.number&&(!h.body||!h.body.trim())&&typeof g.body=="string"&&g.body.trim().length>0)&&h&&g?.body?{...u,pr:{...h,body:g.body}}:u,S=j.resolvedRemoteName??w.resolvedRemoteName??m.remoteName??null,N=Oa(w)??{directory:m.directory,branch:m.branch,remoteName:m.remoteName??null};x[b]={...w,status:j,error:null,isLoading:r?.silent?w.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?w.isInitialStatusResolved:!0,resolvedRemoteName:S,identity:{...N,remoteName:S??N.remoteName??null}}}),{entries:x}})}catch(u){const p=u instanceof Error?u.message:String(u);t(x=>{const b={...x.entries};return l.forEach(w=>{const g=b[w];g&&(b[w]={...g,error:p||"Failed to load PR status",isLoading:r?.silent?g.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?g.isInitialStatusResolved:!0})}),{entries:b}})}finally{jo.delete(c),t(u=>({...u,activeRequestCount:Math.max(0,u.activeRequestCount-1)}))}}},refreshTargets:async(n,r)=>{const o=Array.from(new Set(n.map(a=>{const c=a.directory.trim(),l=a.branch.trim();return!c||!l?null:Ro(c,l,a.remoteName??null)}).filter(a=>!!a)));await Qm(o,Ey,a=>e().refresh(a,r))},updateStatus:(n,r)=>{t(o=>{const a=o.entries[n]??Co();return{entries:{...o.entries,[n]:{...a,status:r(a.status)}}}})}}),{name:Fy,storage:jp(),partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=Oa(e);if(!n?.directory||!n.branch)return!1;const r=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return r===0||Date.now()-r<My}).map(([e,n])=>[e,Wy(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).map(([o,a])=>[o,Uy(a)]))}}})),Hy=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"},Gy=t=>{const e=Hy(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}},Ky=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 kl=new Map,Mu=new Map;const qy=t=>{const e=ht.c(2);let n;return e[0]!==t?(n=r=>{const o=new Map,a=new Map;for(const c of t){const l=r.entries[c];if(!l)continue;const d=Gy(l);if(!d)continue;const f=Ky(d);o.set(c,f),a.set(c,d)}if(o.size===kl.size){let c=!0;for(const[l,d]of o)if(kl.get(l)!==d){c=!1;break}if(c)return Mu}return kl=o,Mu=a,a},e[0]=t,e[1]=n):n=e[1],lr(n)},Yy=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"}},Qy=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"},Jy=[2e3,5e3],Fu=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),mi=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):""},Xy=(t,e)=>{const n=mi(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},Zy=(t,e)=>`${t}::${e}`,qc=t=>{const e=String(t||"").trim();if(!e)return"";const n=e.indexOf("/");return n<=0?"":e.slice(0,n).trim()},Cl=(t,e)=>{if(t.length===0)return null;const n=String(e.selectedRemoteName||"").trim();if(n){const a=t.find(c=>c.name===n);if(a)return a}const r=qc(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)},ev=t=>t.startsWith("pr-"),tv=(t,e)=>{const n=qc(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=>!ev(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},Al=new Map,Dl=ti;function sv(t,e){const[n,r]=i.useState(null),[o,a]=i.useState([]),c=i.useRef(null);return i.useEffect(()=>{r(null),a([])},[t]),i.useEffect(()=>{if(!t||!e?.repoUpstream||c.current===t)return;c.current=t;let l=!1;return(async()=>{try{const d=await e.repoUpstream(t);if(l||!d?.isFork||!d.upstream||(r(d.upstream),!e.repoBranches))return;try{const f=await e.repoBranches(d.upstream.owner,d.upstream.repo);l||a(f)}catch{}}catch{}})(),()=>{l=!0}},[t,e]),{detectedUpstream:n,upstreamBranches:o}}const nv=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=yt(),d=Re(xe=>xe.timeFormatPreference),{github:f}=Zn(),m=Fi(xe=>xe.status),u=Fi(xe=>xe.hasChecked),p=Re(xe=>xe.setSettingsDialogOpen),x=Re(xe=>xe.setSettingsPage),b=Re(xe=>xe.setActiveMainTab),w=mt(xe=>xe.currentSessionId),{isMobile:g,hasTouchInput:h}=$r(),C=i.useCallback(()=>{x("github"),p(!0)},[p,x]),j=i.useMemo(()=>Zy(t,e),[t,e]),S=i.useMemo(()=>Al.get(j)??null,[j]),N=lr(xe=>xe.ensureEntry),k=lr(xe=>xe.setParams),y=lr(xe=>xe.startWatching),D=lr(xe=>xe.stopWatching),V=lr(xe=>xe.refresh),v=lr(xe=>xe.updateStatus),[O,P]=i.useState(()=>S?.title??Fu(e)),[E,B]=i.useState(()=>S?.body??""),[T,W]=i.useState(()=>S?.draft??!1),[U,L]=i.useState(()=>S?.additionalContext??""),[M,ee]=i.useState(()=>{const xe=typeof S?.targetBaseBranch=="string"?mi(S.targetBaseBranch):"";return xe||mi(n)}),[ie,X]=i.useState("squash"),[H,te]=i.useState(!1),[re,le]=i.useState(!1),[ve,ne]=i.useState(!1),[we,he]=i.useState(!1),[Me,z]=i.useState(!1),[K,q]=i.useState(!1),[me,Se]=i.useState(null),[Be,_e]=i.useState(""),[Le,pe]=i.useState(""),[Ee,ge]=i.useState(!1),[oe,je]=i.useState(!1),[ye,ue]=i.useState(()=>Cl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r})),[De,I]=i.useState(!1),{detectedUpstream:_,upstreamBranches:be}=sv(t,f);i.useEffect(()=>{I(!1)},[t]);const R=o.some(xe=>xe.name==="upstream"),fe=!!(t&&e&&n&&(e!==n||(R||_!==null))),$=i.useMemo(()=>Ro(t,e),[t,e]),Ae=lr(xe=>xe.entries[$]),Ve=Ae?.isLoading??!1,Ne=Ae?.status??null,Y=Ae?.error??null,F=Ae?.isInitialStatusResolved??!1,se=i.useMemo(()=>{const xe=De?null:ye?.name?.trim()||null,rt=new Set;for(const zt of a){const gt=Xy(zt,xe);!gt||gt==="HEAD"||rt.add(gt)}if(De)for(const zt of be)zt&&zt!=="HEAD"&&rt.add(zt);const dt=mi(n);dt&&dt!=="HEAD"&&rt.add(dt);const jt=mi(M);return jt&&jt!=="HEAD"&&rt.add(jt),Array.from(rt).sort((zt,gt)=>zt.localeCompare(gt))},[n,a,ye?.name,M,be,De]);i.useEffect(()=>{if(o.length===0){ye&&ue(null);return}(!ye||!o.some(xe=>xe.name===ye.name))&&ue(Cl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r}))},[S?.selectedRemoteName,o,ye,r]),i.useEffect(()=>{const xe=mi(n);if(!M&&xe){ee(xe);return}if(se.length!==0&&!se.includes(M)){const rt=se.includes(xe)?xe:se[0];rt&&ee(rt)}},[se,n,M]);const[Oe,ce]=i.useState(!1),[Ue,qe]=i.useState(null),[Ye,tt]=i.useState(!1),[xt,vt]=i.useState(new Set),[Mt,Tt]=i.useState(!1),[Kt,Ut]=i.useState(null),[Zt,ns]=i.useState(!1),es=i.useRef(new Set),Ce=i.useRef(null),Qe=i.useRef(!1),ot=i.useRef(new Set),bt=i.useRef([]);i.useEffect(()=>{_&&!R&&I(!0)},[_,R]),i.useEffect(()=>{De&&_?.defaultBranch&&ee(_.defaultBranch)},[De,_?.defaultBranch]);const Je=Ne?.pr??null,Pt=Je?`${t}#${Je.number}`:null,Xe=!!(Pt&&me===Pt);i.useEffect(()=>{if(!f?.prContext||!Je||typeof Je.body=="string"&&Je.body.length>0)return;const xe=`${t}#${Je.number}`;if(es.current.has(xe))return;es.current.add(xe),Se(xe);let rt=!1;return f.prContext(t,Je.number,{includeDiff:!1,includeCheckDetails:!1,sourceRepo:Ne?.repo??null}).then(dt=>{if(rt)return;const jt=dt?.pr;jt&&v($,zt=>!zt?.pr||zt.pr.number!==Je.number?zt:{...zt,pr:{...zt.pr,body:jt.body||""}})}).catch(()=>{}).finally(()=>{rt||Se(dt=>dt===xe?null:dt)}),()=>{rt=!0}},[t,f,Je,$,Ne?.repo,v]),i.useEffect(()=>{if(!Je){q(!1),_e(""),pe(""),Ce.current=null;return}const xe=Ce.current!==null&&Ce.current!==Je.number;xe&&q(!1),(!K||xe)&&(_e(Je.title||""),pe(Je.body||"")),Ce.current=Je.number},[K,Je]);const Ke=i.useCallback(async()=>{if(!f?.prContext){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Je){ce(!0),vt(new Set),tt(!0);try{const xe=await f.prContext(t,Je.number,{includeDiff:!1,includeCheckDetails:!0,sourceRepo:Ne?.repo??null});qe(xe)}catch(xe){const rt=xe instanceof Error?xe.message:String(xe);ae.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:rt})}finally{tt(!1)}}},[t,f,Je,Ne?.repo,l]),Ze=i.useCallback(async()=>{if(!f?.prContext){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Je){Tt(!0),ns(!0);try{const xe=await f.prContext(t,Je.number,{includeDiff:!1,includeCheckDetails:!1,sourceRepo:Ne?.repo??null});Ut(xe)}catch(xe){const rt=xe instanceof Error?xe.message:String(xe);ae.error(l("gitView.pr.toast.loadCommentsFailed"),{description:rt})}finally{ns(!1)}}},[t,f,Je,Ne?.repo,l]),Bt=i.useCallback(xe=>{if(!xe)return"";const rt=Date.parse(xe);return Number.isFinite(rt)?Tc(rt,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):xe},[d]),Rt=i.useMemo(()=>{const xe=m?.user?.login;return typeof xe=="string"?xe.trim():""},[m]),Ot=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(xe=>{const rt=Rt.toLowerCase(),dt=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return xe.replace(dt,(jt,zt,gt)=>{const xs=`@${gt}`,bs=gt.toLowerCase();return`${zt}[${xs}](https://github.com/${bs}${rt&&bs===rt?"?oc-self-mention=1":""})`})},[Rt]),Wt=i.useMemo(()=>{const xe=(Kt?.issueComments??[]).map(jt=>({id:`issue-${jt.id}`,body:jt.body||"",authorName:jt.author?.name||jt.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:jt.author?.login||null,avatarUrl:jt.author?.avatarUrl||null,createdAt:jt.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),rt=(Kt?.reviewComments??[]).map(jt=>({id:`review-${jt.id}`,body:jt.body||"",authorName:jt.author?.name||jt.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:jt.author?.login||null,avatarUrl:jt.author?.avatarUrl||null,createdAt:jt.createdAt,context:l("gitView.pr.comments.reviewContext"),path:jt.path||null,line:jt.line??null})),dt=[...xe,...rt];return dt.sort((jt,zt)=>{const gt=jt.createdAt?Date.parse(jt.createdAt):0,xs=zt.createdAt?Date.parse(zt.createdAt):0,bs=Number.isFinite(gt)?gt:0,Ss=Number.isFinite(xs)?xs:0;return bs-Ss}),dt},[Kt,l]),Et=i.useCallback(()=>{if(!w)return ae.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:xe,currentModelId:rt,currentAgentName:dt,currentVariant:jt}=is.getState(),zt=Dc.getState().lastUsedProvider,gt=xe||zt?.providerID,xs=rt||zt?.modelID;return!gt||!xs?(ae.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:w,providerID:gt,modelID:xs,currentAgentName:dt??null,currentVariant:jt??null}},[w,l]),qt=i.useCallback((xe,rt,dt,jt)=>{mt.getState().sendMessage(rt,xe.providerID,xe.modelID,xe.currentAgentName??void 0,void 0,void 0,[{text:dt,synthetic:!0},{text:jt,synthetic:!0}],xe.currentVariant??void 0).catch(zt=>{const gt=zt instanceof Error?zt.message:String(zt);ae.error(l("gitView.pr.toast.sendMessageFailed"),{description:gt})})},[l]),hs=i.useCallback(xe=>{const rt=xe.status||"unknown",dt=xe.conclusion??void 0,jt=dt?`${rt} / ${dt}`:rt,zt=xe.app?.name||xe.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:xe.name}),s.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:zt?`${zt} · ${jt}`:jt})]}),xe.detailsUrl?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:xe.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(A,{name:"external-link",className:"size-4"}),"Open"]})}):null]}),xe.output?.title?s.jsx("div",{className:"typography-micro text-foreground",children:xe.output.title}):null,xe.output?.summary?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:xe.output.summary}):null,xe.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:xe.output.text}):null,Array.isArray(xe.annotations)&&xe.annotations.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",xe.annotations.length>20?` (showing 20/${xe.annotations.length})`:""]}),s.jsx("div",{className:"space-y-1",children:xe.annotations.slice(0,20).map((gt,xs)=>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:[gt.title||gt.level||"Issue",gt.path?` · ${gt.path}`:"",typeof gt.startLine=="number"?`:${gt.startLine}`:"",typeof gt.endLine=="number"&&gt.endLine!==gt.startLine?`-${gt.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:gt.message}),gt.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:gt.rawDetails}):null]},`${gt.path||"file"}:${gt.startLine||xs}:${xs}`))})]}):null,xe.job?.steps&&xe.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:xe.job.steps.map((gt,xs)=>{const bs=(gt.conclusion||"").toLowerCase(),Ss=bs&&!["success","neutral","skipped"].includes(bs),Ns=`${xe.id??"run"}:${xe.job?.jobId??"job"}:${gt.number??xs}:${gt.name}`,Os=xt.has(Ns);return Ss?s.jsxs(ro,{open:Os,children:[s.jsxs("button",{type:"button",onClick:()=>{vt(Tn=>{const Gs=new Set(Tn);return Gs.has(Ns)?Gs.delete(Ns):Gs.add(Ns),Gs})},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:[Os?s.jsx(A,{name:"arrow-down-s",className:"size-4"}):s.jsx(A,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:gt.name}),gt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:gt.conclusion}):null]}),s.jsx(io,{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 gt.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",gt.number]}):null,gt.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",gt.status]}):null,gt.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",gt.conclusion]}):null,gt.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",Bt(gt.startedAt)]}):null,gt.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",Bt(gt.completedAt)]}):null]})})]},Ns):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:gt.name}),gt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:gt.conclusion}):null]},Ns)})})]}):null]})},[xt,Bt,l]),ts=i.useCallback(async()=>{if(b("chat"),!f?.prContext){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Je)return;const xe=Et();if(xe)try{const rt=await f.prContext(t,Je.number,{includeDiff:!1,includeCheckDetails:!0,sourceRepo:Ne?.repo??null}),jt=(rt.checkRuns??[]).filter(Ss=>{const Ns=typeof Ss.conclusion=="string"?Ss.conclusion.toLowerCase():"";return Ns?!["success","neutral","skipped"].includes(Ns):!1});if(jt.length===0){ae.message(l("gitView.pr.toast.noFailedChecks"));return}const zt=await Fn("github.pr.checks.review.visible"),gt=await Fn("github.pr.checks.review.instructions"),xs=jt.flatMap(Ss=>(Array.isArray(Ss.annotations)?Ss.annotations:[]).map(Os=>({run:Ss.name,level:Os.level,title:Os.title,path:Os.path,startLine:Os.startLine,endLine:Os.endLine,message:Os.message,rawDetails:Os.rawDetails}))),bs=`GitHub PR failed checks (JSON)
7
+ ${JSON.stringify({repo:rt.repo??null,pr:rt.pr??null,failedChecks:jt,failedAnnotations:xs},null,2)}`;qt(xe,zt,gt,bs)}catch(rt){const dt=rt instanceof Error?rt.message:String(rt);ae.error(l("gitView.pr.toast.loadChecksFailed"),{description:dt})}},[t,qt,f,Je,Et,b,Ne?.repo,l]),as=i.useCallback(async()=>{if(b("chat"),!f?.prContext){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Je)return;const xe=Et();if(xe)try{const rt=await f.prContext(t,Je.number,{includeDiff:!1,includeCheckDetails:!1,sourceRepo:Ne?.repo??null}),dt=rt.issueComments??[],jt=rt.reviewComments??[];if(dt.length+jt.length===0){ae.message(l("gitView.pr.toast.noPrComments"));return}const gt=await Fn("github.pr.comments.review.visible"),xs=await Fn("github.pr.comments.review.instructions"),bs=`GitHub PR comments (JSON)
8
+ ${JSON.stringify({repo:rt.repo??null,pr:rt.pr??null,issueComments:dt,reviewComments:jt},null,2)}`;qt(xe,gt,xs,bs)}catch(rt){const dt=rt instanceof Error?rt.message:String(rt);ae.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:dt})}},[t,qt,f,Je,Et,b,Ne?.repo,l]),gs=i.useCallback(async xe=>{Tt(!1),b("chat");const rt=Et();if(!rt)return;const dt=await Fn("github.pr.comment.single.visible"),jt=await Fn("github.pr.comment.single.instructions"),zt=`GitHub PR comment (JSON)
9
+ ${JSON.stringify({repo:Kt?.repo??null,pr:Kt?.pr??Je??null,comment:xe},null,2)}`;qt(rt,dt,jt,zt)},[Kt,qt,Je,Et,b]),Ft=i.useCallback(async xe=>{await V($,xe)},[$,V]),Lt=i.useCallback(()=>{bt.current.forEach(xe=>{window.clearTimeout(xe)}),bt.current=Jy.map(xe=>window.setTimeout(()=>{Ft({force:!0,silent:!0,markInitialResolved:!0})},xe))},[Ft]);i.useEffect(()=>{if(!f?.prStatus||!fe||o.length<=1||Qe.current||Ne?.pr)return;const xe=`${j}::${ye?.name??""}`;if(ot.current.has(xe))return;ot.current.add(xe);const rt=tv(o,r).filter(zt=>zt.name!==ye?.name);if(rt.length===0)return;let dt=!1;return(async()=>{for(const zt of rt){if(dt)return;try{if(!(await f.prStatus(t,e,zt.name))?.pr)continue;if(dt)return;ue(xs=>xs?.name===zt.name?xs:zt);return}catch{}}})(),()=>{dt=!0}},[e,fe,t,f,o,ye?.name,j,Ne?.pr,r]),i.useEffect(()=>{N($),k($,{directory:t,branch:e,remoteName:ye?.name??null,canShow:fe,github:f,githubAuthChecked:u,githubConnected:m?.connected??null})},[e,fe,t,N,f,u,m?.connected,$,ye?.name,k]),i.useEffect(()=>(y($),()=>{D($)}),[$,y,D]),i.useEffect(()=>{const xe=Al.get(j)??null;P(xe?.title??Fu(e)),B(xe?.body??""),W(xe?.draft??!1),ee(xe?.targetBaseBranch?mi(xe.targetBaseBranch):mi(n));const rt=Cl(o,{selectedRemoteName:xe?.selectedRemoteName,trackingBranch:r});ue(dt=>dt?.name===rt?.name?dt:rt)},[n,e,o,j,r]),i.useEffect(()=>{Ft({markInitialResolved:!0})},[$,Ft]),i.useEffect(()=>{!fe||!ye?.name||Ft({force:!0,silent:!0,markInitialResolved:!0})},[fe,Ft,ye?.name]),i.useEffect(()=>{const xe=Ne?.resolvedRemoteName?.trim();if(!xe||Qe.current)return;const rt=o.find(dt=>dt.name===xe);rt&&ue(dt=>dt?.name===rt.name?dt:rt)},[o,Ne?.resolvedRemoteName]),i.useEffect(()=>{const xe=Ne?.pr?.state==="closed"||Ne?.pr?.state==="merged",rt=Ae?.lastRefreshAt??0,dt=Date.now()-rt>6e4,jt=!xe&&dt,zt=()=>{jt&&Ft({force:!0,silent:!0})},gt=()=>{document.visibilityState==="visible"&&jt&&Ft({force:!0,silent:!0})};return window.addEventListener("focus",zt),document.addEventListener("visibilitychange",gt),()=>{window.removeEventListener("focus",zt),document.removeEventListener("visibilitychange",gt)}},[Ft,Ne?.pr?.state,Ae?.lastRefreshAt]),i.useEffect(()=>{u&&m?.connected===!1&&Ft({force:!0,silent:!0,markInitialResolved:!0})},[u,m,Ft]),i.useEffect(()=>{!t||!e||Al.set(j,{title:O,body:E,draft:T,additionalContext:U,targetBaseBranch:M,selectedRemoteName:ye?.name})},[j,O,E,T,U,M,ye?.name,t,e]),i.useEffect(()=>{const xe=bt.current;return()=>{xe.forEach(rt=>{window.clearTimeout(rt)}),bt.current=[]}},[]);const Ht=i.useCallback(async()=>{if(!H&&t){te(!0);try{const rt={base:De&&_?.defaultBranchSha?_.defaultBranchSha:M,head:e};U&&(rt.context=U);const dt=await ug(t,rt);dt.title?.trim()&&P(dt.title.trim()),dt.body?.trim()&&B(dt.body.trim()),c?.()}catch(xe){const rt=xe instanceof Error?xe.message:String(xe);ae.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:rt})}finally{te(!1)}}},[U,e,_?.defaultBranchSha,t,H,c,M,l,De]),Yt=i.useCallback(async()=>{if(!f?.prCreate){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}const xe=O.trim();if(!xe){ae.error(l("gitView.pr.toast.titleRequired"));return}const rt=M.trim();if(!rt){ae.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!De&&rt===e){ae.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}le(!0);try{const dt=qc(r),jt=De&&_,zt=await f.prCreate({directory:t,title:xe,head:e,base:rt,...E.trim()?{body:E}:{},draft:T,...jt?{targetRepo:{owner:_.owner,repo:_.repo},headRemote:"origin"}:{...ye?{remote:ye.name}:{},...dt&&dt!==ye?.name?{headRemote:dt}:{}}});ae.success(l("gitView.pr.toast.prCreated")),v($,gt=>gt&&{...gt,pr:zt}),await Ft({force:!0}),Lt()}catch(dt){const jt=dt instanceof Error?dt.message:String(dt);ae.error(l("gitView.pr.toast.createPrFailed"),{description:jt})}finally{le(!1)}},[E,e,_,t,T,f,$,Ft,Lt,ye,M,O,r,v,De,l]),$t=i.useCallback(async xe=>{if(!f?.prMerge){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}he(!0);try{const rt=await f.prMerge({directory:t,number:xe.number,method:ie});rt.merged?ae.success(l("gitView.pr.toast.prMerged")):ae.message(l("gitView.pr.toast.prNotMerged"),{description:rt.message||l("gitView.pr.notMergeable")}),await Ft({force:!0}),Lt()}catch(rt){const dt=rt instanceof Error?rt.message:String(rt);ae.error(l("gitView.pr.toast.mergeFailed"),{description:dt}),xe.url&&Dl(xe.url)}finally{he(!1)}},[t,f,ie,Ft,Lt,l]),Fe=i.useCallback(async xe=>{if(!f?.prReady){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}z(!0);try{await f.prReady({directory:t,number:xe.number}),ae.success(l("gitView.pr.toast.markedReady")),await Ft({force:!0}),Lt()}catch(rt){const dt=rt instanceof Error?rt.message:String(rt);ae.error(l("gitView.pr.toast.markReadyFailed"),{description:dt}),xe.url&&Dl(xe.url)}finally{z(!1)}},[t,f,Ft,Lt,l]),st=i.useCallback(async xe=>{if(!f?.prUpdate){ae.error(l("gitView.pr.toast.githubApiUnavailable"));return}const rt=Be.trim();if(!rt){ae.error(l("gitView.pr.toast.titleRequired"));return}ne(!0);try{const dt=await f.prUpdate({directory:t,number:xe.number,title:rt,body:Le});v($,jt=>jt&&{...jt,pr:{...jt.pr??xe,...dt}}),q(!1),ae.success(l("gitView.pr.toast.prUpdated")),await Ft({force:!0}),Lt()}catch(dt){const jt=dt instanceof Error?dt.message:String(dt);ae.error(l("gitView.pr.toast.updatePrFailed"),{description:jt})}finally{ne(!1)}},[t,Le,Be,f,$,Ft,Lt,v,l]);if(!fe)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 wt=Ne?.repo?.url||null,St=De&&_?.url?_.url:wt,Nt=Ne?.checks??null,ss=!!Ne?.canMerge,cs=!!Ne?.connected,Xt=u&&Ne?.connected===!1,Vt=Qy(Ne),Fs=Vt?`var(--pr-${Vt})`:"var(--status-info)",us=Vt==="draft"?"git-pr-draft":Vt==="merged"?"git-merge":Vt==="closed"?"git-close-pull-request":"git-pull-request",$s=Je?[`${Je.state}${Je.draft?" (draft)":""}`,Je.mergeable===!1?l("gitView.pr.notMergeable"):null,Je.state==="open"&&typeof Je.mergeableState=="string"&&Je.mergeableState&&Je.mergeableState!=="unknown"?Je.mergeableState:null].filter(Boolean).join(" · "):"",js=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:[Je?s.jsxs(Ct,{children:[s.jsx(At,{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:()=>{Dl(Je.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(A,{name:us,className:"size-4 shrink-0",style:{color:Fs}})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(A,{name:us,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")}),Je?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",Je.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ve?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex size-5 items-center justify-center rounded hover:bg-interactive-hover/60 disabled:opacity-40",disabled:Ve,onClick:()=>{Ft({force:!0})},"aria-label":l("gitView.pr.actions.refreshAria"),children:s.jsx(A,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),Je?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:$s}),Nt?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${Yy(Nt.state)}`}),js]}):null,r&&ye&&r.split("/")[0]!==ye.name?s.jsxs("span",{className:"min-w-0 truncate",children:[r.split("/")[0]," → ",ye.name]}):null]}):null]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[Xt?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.githubNotConnected")}),s.jsx(ze,{variant:"outline",size:"sm",onClick:C,className:"w-fit",children:l("gitView.pr.actions.openSettings")})]}):null,Y?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:Y}),St?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:s.jsxs("a",{href:St,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(A,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!Je&&!F&&!Y&&!Xt?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):Je?s.jsx("div",{className:"flex flex-col gap-2",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[K?s.jsxs("div",{className:"space-y-2",children:[s.jsx(Ln,{value:Be,onChange:xe=>_e(xe.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h}),s.jsx(Pi,{value:Le,onChange:xe=>pe(xe.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:Je.title}),Je.body?.trim()?s.jsx(no,{content:Je.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(Xe?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),ss&&Je.draft?s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.draftMustBeReady")}):null,ss?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:[Je.state==="open"?K?s.jsxs(s.Fragment,{children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{q(!1),_e(Je.title||""),pe(Je.body||"")},disabled:ve,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(A,{name:"close",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>st(Je),disabled:ve||!Be.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:ve?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"check",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>q(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(A,{name:"edit",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,Nt?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:Ke,disabled:Ye,"aria-label":l("gitView.pr.actions.openChecksAria"),children:Ye?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"information",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,Nt?.failure?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:ts,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(A,{name:"error-warning",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:Ze,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(A,{name:"chat-4",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:as,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(A,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),ss&&Je.draft&&Je.state==="open"?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>Fe(Je),disabled:Me||we||ve||K,"aria-label":l("gitView.pr.actions.markReadyAria"),children:Me?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.markReady")})})]}):null]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:ss?s.jsxs(s.Fragment,{children:[s.jsxs(Gn,{value:ie,onValueChange:xe=>X(xe),disabled:we||Je.state!=="open",children:[s.jsx(Kn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(Dn,{})}),s.jsxs(qn,{children:[s.jsx(Bs,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(Bs,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(Bs,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>$t(Je),disabled:we||Me||Je.state!=="open"||Je.draft||ve||K,"aria-label":l("gitView.pr.actions.mergePrAria"),children:we?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"git-merge",className:"size-4"})})}),s.jsx(Dt,{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)"})," → ",M," ",s.jsxs("span",{className:"opacity-60",children:["(",De&&_?"upstream":"remote",")"]})]})]}),St?s.jsx(ze,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:St,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(A,{name:"external-link",className:"size-4"}),l("gitView.pr.actions.repo")]})}):null]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.title")}),s.jsx(Ln,{value:O,onChange:xe=>P(xe.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")}),se.length>0?s.jsxs(Gn,{value:M,onValueChange:ee,children:[s.jsx(Kn,{className:"h-9",children:s.jsx(Dn,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(qn,{children:se.map(xe=>s.jsx(Bs,{value:xe,children:xe},xe))})]}):s.jsx(Ln,{value:M,onChange:xe=>ee(xe.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(Pi,{value:E,onChange:xe=>B(xe.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":T,onClick:()=>W(xe=>!xe),onKeyDown:xe=>{(xe.key===" "||xe.key==="Enter")&&(xe.preventDefault(),W(rt=>!rt))},children:[s.jsx(Or,{size:"sm",checked:T,onChange:xe=>W(xe),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),g?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx(ze,{variant:"outline",size:"sm",onClick:()=>je(!0),children:U.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),U.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(ro,{open:Ee,onOpenChange:ge,children:[s.jsxs(Uo,{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:Ee?l("gitView.pr.actions.hide"):U.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(io,{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(Pi,{value:U,onChange:xe=>L(xe.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(Ya,{open:oe,onClose:()=>je(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx(ze,{size:"sm",onClick:()=>je(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Pi,{value:U,onChange:xe=>L(xe.target.value),className:"min-h-[200px] bg-transparent",placeholder:l("gitView.pr.placeholder.additionalContext"),autoFocus:!0}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.hint")})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ze,{variant:"outline",size:"sm",onClick:Ht,disabled:H||re,children:[H?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"ai-generate-2",className:"size-4 text-primary"}),l("gitView.commit.generate")]}),s.jsx("div",{className:"flex-1"}),s.jsxs(ze,{size:"sm",className:"min-w-[7.5rem] justify-center gap-2",onClick:Yt,disabled:re||!cs||!M.trim()||!De&&M.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:re?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx(_s,{open:Oe,onOpenChange:ce,children:s.jsxs(Vs,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(sn,{children:[s.jsxs(Hs,{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(mn,{children:Je?l("gitView.pr.numberLabel",{number:Je.number}):l("gitView.pullRequest.title")})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[Ye?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Ye?null:s.jsx("div",{className:"space-y-3",children:Array.isArray(Ue?.checkRuns)&&Ue?.checkRuns.length>0?Ue.checkRuns.map((xe,rt)=>{const dt=`${xe.id??"run"}:${xe.job?.jobId??"job"}:${xe.name}:${rt}`;return s.jsx("div",{className:"p-1",children:hs(xe)},dt)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx(_s,{open:Mt,onOpenChange:Tt,children:s.jsxs(Vs,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(sn,{children:s.jsxs(Hs,{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),Je?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:Je.number})}):null]})}),s.jsxs(Qa,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[Zt?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Zt?null:s.jsx("div",{className:"space-y-4",children:Wt.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Wt.map((xe,rt)=>{const dt=(xe.authorName||"?").charAt(0).toUpperCase(),jt=rt===Wt.length-1;return s.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[jt?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:xe.avatarUrl?s.jsx("img",{src:xe.avatarUrl,alt:xe.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:dt})}),s.jsxs("div",{className:"rounded-lg bg-surface-elevated px-3 pt-0 pb-3 space-y-2",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1 typography-micro text-muted-foreground sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-1 sm:gap-y-1",children:[s.jsxs("span",{className:"text-foreground whitespace-nowrap",children:[xe.authorName,xe.authorLogin&&xe.authorLogin!==xe.authorName?` · @${xe.authorLogin}`:""]}),xe.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:Bt(xe.createdAt)}):null,s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsxs(ze,{variant:"ghost",size:"sm",className:"h-6 px-0 has-[>svg]:px-0 sm:px-2 sm:has-[>svg]:px-2.5 text-[var(--status-success)] hover:bg-[var(--status-success-background)] hover:text-[var(--status-success)] justify-start",onClick:()=>{gs(xe)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(A,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(Dt,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[xe.context,xe.path?` · ${xe.path}`:"",xe.line?`:${xe.line}`:""]}),s.jsx(no,{content:rs(xe.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",Ot].filter(Boolean).join(" "),enableFileReferences:!1})]})]},xe.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},rv=t=>{const e=ht.c(150),{open:n,onOpenChange:r,conflictFiles:o,directory:a,operation:c,onAbort:l,onClearState:d}=t;let f;e[0]!==o?(f=o===void 0?[]:o,e[0]=o,e[1]=f):f=e[1];const m=f,{t:u}=yt(),p=mt(iv),x=mt(ov),b=bi(av),w=bi(lv),g=Re(cv),[h,C]=i.useState(!1),[j,S]=i.useState(null),[N,k]=i.useState(null);let y,D;e[2]!==a||e[3]!==n||e[4]!==u?(y=()=>{!n||!a||(C(!0),k(null),S(null),fg(a).then(De=>{S(De)}).catch(De=>{const I=De instanceof Error?De.message:u("gitView.conflict.loadFailed");k(I)}).finally(()=>{C(!1)}))},D=[n,a,u],e[2]=a,e[3]=n,e[4]=u,e[5]=y,e[6]=D):(y=e[5],D=e[6]),i.useEffect(y,D);let V;e[7]!==j||e[8]!==a||e[9]!==c?(V=async()=>{if(!j)return null;const De=c==="merge"?"merge":"rebase",I=j.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),_=c==="merge"?"git commit --no-edit":"git rebase --continue",be=await Fn("git.conflict.resolve.visible",{operation_label:De,head_ref:I}),R=await Fn("git.conflict.resolve.instructions",{operation_label:De,directory:a,operation:c,head_info:j.headInfo||"N/A",continue_cmd:_}),de=`${De} conflict context (JSON)
10
+ ${JSON.stringify({directory:a,operation:j.operation,headInfo:j.headInfo,statusPorcelain:j.statusPorcelain,unmergedFiles:j.unmergedFiles,diff:j.diff},null,2)}`;return{visibleText:be,instructionsText:R,payloadText:de}},e[7]=j,e[8]=a,e[9]=c,e[10]=V):V=e[10];const v=V;let O;e[11]!==l||e[12]!==r?(O=()=>{l(),r(!1)},e[11]=l,e[12]=r,e[13]=O):O=e[13];const P=O;let E;e[14]!==d||e[15]!==r?(E=()=>{d?.(),r(!1)},e[14]=d,e[15]=r,e[16]=E):E=e[16];const B=E;let T;e[17]!==v||e[18]!==x||e[19]!==d||e[20]!==r||e[21]!==g||e[22]!==b||e[23]!==w||e[24]!==u?(T=async()=>{const De=await v();if(!De){ae.error(u("gitView.conflict.noDetailsAvailable"));return}if(!x){ae.error(u("gitView.conflict.noActiveSession"),{description:u("gitView.conflict.noActiveSessionDescription")});return}b(De.visibleText,"replace"),w([{text:De.instructionsText,synthetic:!0},{text:De.payloadText,synthetic:!0}]),g("chat"),d?.(),r(!1)},e[17]=v,e[18]=x,e[19]=d,e[20]=r,e[21]=g,e[22]=b,e[23]=w,e[24]=u,e[25]=T):T=e[25];const W=T;let U;e[26]!==v||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==p||e[31]!==g||e[32]!==u?(U=async()=>{const De=await v();if(!De){ae.error(u("gitView.conflict.noDetailsAvailable"));return}p({directoryOverride:a,initialPrompt:De.visibleText,syntheticParts:[{text:De.instructionsText,synthetic:!0},{text:De.payloadText,synthetic:!0}]}),g("chat"),d?.(),r(!1)},e[26]=v,e[27]=a,e[28]=d,e[29]=r,e[30]=p,e[31]=g,e[32]=u,e[33]=U):U=e[33];const L=U;let M,ee,ie,X,H,te,re,le,ve,ne,we,he,Me,z,K,q,me,Se,Be,_e,Le,pe;if(e[34]!==j||e[35]!==m||e[36]!==x||e[37]!==P||e[38]!==B||e[39]!==W||e[40]!==L||e[41]!==h||e[42]!==N||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==u){const De=u(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),I=j?.unmergedFiles||m;ie=_s,Le=n,pe=r,ee=Vs,_e="max-w-md w-[calc(100vw-2rem)]",z="flex flex-col gap-4 overflow-hidden";let _;e[69]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx(A,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=_):_=e[69];const be=s.jsxs("div",{className:"flex items-center gap-2",children:[_,s.jsx(Hs,{children:u("gitView.conflict.detectedTitle",{operation:De})})]});let R;e[70]!==c||e[71]!==u?(R=u("gitView.conflict.detectedDescription",{operation:c}),e[70]=c,e[71]=u,e[72]=R):R=e[72];let de;e[73]!==R?(de=s.jsx(mn,{children:R}),e[73]=R,e[74]=de):de=e[74],e[75]!==be||e[76]!==de?(K=s.jsxs(sn,{children:[be,de]}),e[75]=be,e[76]=de,e[77]=K):K=e[77],e[78]!==h||e[79]!==u?(q=h&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:u("gitView.conflict.loading")})]}),e[78]=h,e[79]=u,e[80]=q):q=e[80],e[81]!==N||e[82]!==u?(me=N&&s.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:u("gitView.conflict.errorLoadingDetails",{message:N})}),e[81]=N,e[82]=u,e[83]=me):me=e[83],e[84]!==I||e[85]!==u?(Se=I.length>0&&s.jsxs("div",{className:"space-y-2 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:u("gitView.conflict.conflictedFiles")}),s.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:I.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:I.map(dv)})})]}),e[84]=I,e[85]=u,e[86]=Se):Se=e[86],e[87]!==j||e[88]!==u?(Be=j?.headInfo&&s.jsxs("div",{className:"space-y-1 overflow-hidden",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:u("gitView.conflict.headInfo")}),s.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:j.headInfo})]}),e[87]=j,e[88]=u,e[89]=Be):Be=e[89],we="flex flex-col gap-2 pt-2";let fe;e[90]!==L?(fe=()=>{L()},e[90]=L,e[91]=fe):fe=e[91];const $=h||!j;let Ae;e[92]!==h?(Ae=h?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"add",className:"size-4"}),e[92]=h,e[93]=Ae):Ae=e[93];let Ve;e[94]!==u?(Ve=u("gitView.conflict.resolveNewSession"),e[94]=u,e[95]=Ve):Ve=e[95],e[96]!==fe||e[97]!==$||e[98]!==Ae||e[99]!==Ve?(he=s.jsxs(ze,{variant:"default",onClick:fe,disabled:$,className:"w-full gap-2",children:[Ae,Ve]}),e[96]=fe,e[97]=$,e[98]=Ae,e[99]=Ve,e[100]=he):he=e[100];let Ne;e[101]!==W?(Ne=()=>{W()},e[101]=W,e[102]=Ne):Ne=e[102];const Y=h||!j||!x;let F;e[103]!==h?(F=h?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"chat-1",className:"size-4"}),e[103]=h,e[104]=F):F=e[104];let se;e[105]!==u?(se=u("gitView.conflict.resolveCurrentSession"),e[105]=u,e[106]=se):se=e[106],e[107]!==Ne||e[108]!==Y||e[109]!==F||e[110]!==se?(Me=s.jsxs(ze,{variant:"outline",onClick:Ne,disabled:Y,className:"w-full gap-2",children:[F,se]}),e[107]=Ne,e[108]=Y,e[109]=F,e[110]=se,e[111]=Me):Me=e[111],ve="flex gap-2 pt-1";let Oe;e[112]!==u?(Oe=u("gitView.conflict.continueLater"),e[112]=u,e[113]=Oe):Oe=e[113],e[114]!==B||e[115]!==Oe?(ne=s.jsx(ze,{variant:"ghost",size:"sm",onClick:B,className:"flex-1",children:Oe}),e[114]=B,e[115]=Oe,e[116]=ne):ne=e[116],M=ze,X="destructive",H="sm",te=P,re="flex-1",le=u("gitView.conflict.abortOperation",{operation:De}),e[34]=j,e[35]=m,e[36]=x,e[37]=P,e[38]=B,e[39]=W,e[40]=L,e[41]=h,e[42]=N,e[43]=r,e[44]=n,e[45]=c,e[46]=u,e[47]=M,e[48]=ee,e[49]=ie,e[50]=X,e[51]=H,e[52]=te,e[53]=re,e[54]=le,e[55]=ve,e[56]=ne,e[57]=we,e[58]=he,e[59]=Me,e[60]=z,e[61]=K,e[62]=q,e[63]=me,e[64]=Se,e[65]=Be,e[66]=_e,e[67]=Le,e[68]=pe}else M=e[47],ee=e[48],ie=e[49],X=e[50],H=e[51],te=e[52],re=e[53],le=e[54],ve=e[55],ne=e[56],we=e[57],he=e[58],Me=e[59],z=e[60],K=e[61],q=e[62],me=e[63],Se=e[64],Be=e[65],_e=e[66],Le=e[67],pe=e[68];let Ee;e[117]!==M||e[118]!==X||e[119]!==H||e[120]!==te||e[121]!==re||e[122]!==le?(Ee=s.jsx(M,{variant:X,size:H,onClick:te,className:re,children:le}),e[117]=M,e[118]=X,e[119]=H,e[120]=te,e[121]=re,e[122]=le,e[123]=Ee):Ee=e[123];let ge;e[124]!==ve||e[125]!==ne||e[126]!==Ee?(ge=s.jsxs("div",{className:ve,children:[ne,Ee]}),e[124]=ve,e[125]=ne,e[126]=Ee,e[127]=ge):ge=e[127];let oe;e[128]!==we||e[129]!==he||e[130]!==Me||e[131]!==ge?(oe=s.jsxs("div",{className:we,children:[he,Me,ge]}),e[128]=we,e[129]=he,e[130]=Me,e[131]=ge,e[132]=oe):oe=e[132];let je;e[133]!==z||e[134]!==K||e[135]!==q||e[136]!==me||e[137]!==Se||e[138]!==Be||e[139]!==oe?(je=s.jsxs("div",{className:z,children:[K,q,me,Se,Be,oe]}),e[133]=z,e[134]=K,e[135]=q,e[136]=me,e[137]=Se,e[138]=Be,e[139]=oe,e[140]=je):je=e[140];let ye;e[141]!==ee||e[142]!==_e||e[143]!==je?(ye=s.jsx(ee,{className:_e,children:je}),e[141]=ee,e[142]=_e,e[143]=je,e[144]=ye):ye=e[144];let ue;return e[145]!==ie||e[146]!==Le||e[147]!==pe||e[148]!==ye?(ue=s.jsx(ie,{open:Le,onOpenChange:pe,children:ye}),e[145]=ie,e[146]=Le,e[147]=pe,e[148]=ye,e[149]=ue):ue=e[149],ue};function iv(t){return t.openNewSessionDraft}function ov(t){return t.currentSessionId}function av(t){return t.setPendingInputText}function lv(t){return t.setPendingSyntheticParts}function cv(t){return t.setActiveMainTab}function dv(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const uv=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=yt(),[c,l]=i.useState(!0),[d,f]=i.useState(!1),m=a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),u=async()=>{f(!0);try{await o(c),e(!1)}catch(x){const b=x instanceof Error?x.message:`Failed to ${n}`;ae.error(b)}finally{f(!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(sn,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(A,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(Hs,{children:a("gitView.stash.title")})]}),s.jsx(mn,{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(Or,{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(br,{className:"gap-2",children:[s.jsx(ze,{variant:"ghost",size:"sm",onClick:p,disabled:d,children:a("gitView.common.cancel")}),s.jsx(ze,{variant:"default",size:"sm",onClick:u,disabled:d,className:"gap-1.5",children:d?s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:m})})]})]})})},fv=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=yt(),[d,f]=i.useState(null),m=t&&t.head,u=e&&(e.headName||e.onto),p=m?"merge":u?"rebase":null;if(!p)return null;const x=async()=>{f("continue");try{await n()}finally{f(null)}},b=async()=>{f("abort");try{await r()}finally{f(null)}},w=d!==null,g=l(p==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),h=p==="merge"?"git-merge":"git-branch";let C="";return t?C=t.message?l("gitView.operation.mergingMessage",{message:t.message}):l("gitView.operation.mergeInProgressWithHead",{head:t.head}):e&&(C=e.headName?l("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):l("gitView.operation.rebaseInProgress")),s.jsx("div",{className:"bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[s.jsx(A,{name:h,className:"size-4 text-[var(--status-warning)] shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:l("gitView.operation.inProgressTitle",{operation:g})}),C&&s.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:C})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&o&&s.jsxs(ze,{variant:"outline",size:"sm",onClick:o,disabled:w||c,className:"gap-1.5",children:[s.jsx(A,{name:"sparkling",className:"size-4"}),l("gitView.operation.resolveWithAi")]}),d!=="continue"&&s.jsxs(ze,{variant:"ghost",size:"sm",onClick:b,disabled:w||c,className:"gap-1.5",children:[d==="abort"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs(ze,{variant:"default",size:"sm",onClick:x,disabled:w||c,className:"gap-1.5",children:[d==="continue"?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"check",className:"size-4"}),l("gitView.operation.continue")]})]}),a&&s.jsx("p",{className:"typography-micro text-[var(--status-warning)]",children:l("gitView.operation.resolveConflictsHint")})]})})},mv=t=>{const e=ht.c(104),{currentBranch:n,localBranches:r,remoteBranches:o,onMerge:a,onRebase:c,disabled:l,isOperating:d,operationLogs:f,onOperationComplete:m,mode:u,defaultTargetBranch:p}=t,x=l===void 0?!1:l,b=d===void 0?!1:d,w=f===void 0?[]:f,g=u===void 0?"dialog":u,{t:h}=yt(),[C,j]=i.useState(!1),[S,N]=i.useState("merge"),[k,y]=i.useState(null),[D,V]=i.useState(!1),[v,O]=i.useState(""),P=i.useRef(null),E=i.useRef(null),B=x||b,T=n||h("gitView.branch.currentBranchFallback"),W=w.length>0&&w.every(hv),U=w.some(pv);let L;e[0]===Symbol.for("react.memo_cache_sentinel")?(L=()=>{E.current&&(E.current.scrollTop=E.current.scrollHeight)},e[0]=L):L=e[0],i.useEffect(L,[w]);let M;if(e[1]!==v||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Ne=v.toLowerCase();let Y;e[6]!==o?(Y=new Set(o.map(gv).filter(Boolean)),e[6]=o,e[7]=Y):Y=e[7];const F=Y;let se;e[8]!==n||e[9]!==F?(se=ce=>ce!==n&&!F.has(ce),e[8]=n,e[9]=F,e[10]=se):se=e[10];const Oe=r.filter(se);if(!Ne){M=Oe;break e}M=Oe.filter(ce=>ce.toLowerCase().includes(Ne))}e[1]=v,e[2]=n,e[3]=r,e[4]=o,e[5]=M}else M=e[5];const ee=M;let ie;if(e[11]!==v||e[12]!==o){e:{const Ne=v.toLowerCase();if(!Ne){ie=o;break e}ie=o.filter(Y=>Y.toLowerCase().includes(Ne))}e[11]=v,e[12]=o,e[13]=ie}else ie=e[13];const X=ie;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 te=H;let re;e[18]!==te||e[19]!==j?(re=()=>{j(!0),y(te()),N("merge"),O("")},e[18]=te,e[19]=j,e[20]=re):re=e[20];const le=re;let ve;e[21]===Symbol.for("react.memo_cache_sentinel")?(ve=Ne=>{y(Ne),V(!1),O("")},e[21]=ve):ve=e[21];const ne=ve;let we;e[22]!==a||e[23]!==c||e[24]!==S||e[25]!==k?(we=()=>{k&&(S==="merge"?a(k):c(k))},e[22]=a,e[23]=c,e[24]=S,e[25]=k,e[26]=we):we=e[26];const he=we;let Me;e[27]!==b||e[28]!==j?(Me=()=>{b||(y(null),N("merge"),O(""),j(!1))},e[27]=b,e[28]=j,e[29]=Me):Me=e[29];const z=Me,K=()=>{b&&!W||(W&&m?.(),y(null),N("merge"),O(""),j(!1))};let q,me;e[30]!==D?(q=()=>{D||O("")},me=[D],e[30]=D,e[31]=q,e[32]=me):(q=e[31],me=e[32]),i.useEffect(q,me);let Se,Be;e[33]!==g||e[34]!==te||e[35]!==k?(Se=()=>{g!=="inline"||k||y(te())},Be=[g,te,k],e[33]=g,e[34]=te,e[35]=k,e[36]=Se,e[37]=Be):(Se=e[36],Be=e[37]),i.useEffect(Se,Be);const pe=b?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:w.map(xv)})}),W?g==="dialog"?s.jsx(br,{children:s.jsx(ze,{variant:"default",size:"sm",onClick:K,children:h(U?"gitView.common.close":"gitView.common.done")})}):s.jsx("div",{className:"flex justify-end",children:s.jsx(ze,{variant:"default",size:"sm",onClick:K,children:h(U?"gitView.common.close":"gitView.common.done")})}):null]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:h("gitView.branch.operation")}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>N("merge"),className:Pe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",S==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-merge",className:Pe("size-4",S==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Pe("typography-ui-label",S==="merge"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.merge")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.mergeDescription")})]}),s.jsxs("button",{type:"button",onClick:()=>N("rebase"),className:Pe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",S==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-branch",className:Pe("size-4",S==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Pe("typography-ui-label",S==="rebase"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.rebase")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.rebaseDescription")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:S==="merge"?h("gitView.branch.branchToMergeInto",{branch:T}):h("gitView.branch.branchToRebaseOnto")}),s.jsxs(tn,{open:D,onOpenChange:V,modal:!1,children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:Pe("truncate",!k&&"text-muted-foreground"),children:k||h("gitView.branch.selectBranch")}),s.jsx(A,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(en,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:s.jsxs(Ha,{className:"h-full min-h-0",children:[s.jsx(Ga,{ref:P,placeholder:h("gitView.branch.searchPlaceholder"),value:v,onValueChange:O,onKeyDown:bv}),s.jsxs(Ka,{className:"h-full min-h-0",disableHorizontal:!0,children:[s.jsx(qa,{children:h("gitView.branch.empty")}),ee.length>0&&s.jsx(Qr,{heading:h("gitView.branch.localBranches"),children:ee.map(Ne=>s.jsx(Jr,{onSelect:()=>ne(Ne),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ne})},`local-${Ne}`))}),ee.length>0&&X.length>0?s.jsx(mg,{}):null,X.length>0&&s.jsx(Qr,{heading:h("gitView.branch.remoteBranches"),children:X.map(Ne=>s.jsx(Jr,{onSelect:()=>ne(Ne),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ne})},`remote-${Ne}`))})]})]})})]})]}),k?s.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:S==="merge"?s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryMergePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})," ",h("gitView.branch.summaryMergeInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:T})]}):s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryRebasePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:T})," ",h("gitView.branch.summaryRebaseInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})]})})}):null,g==="dialog"?s.jsxs(br,{className:"gap-2 pt-1",children:[s.jsx(ze,{variant:"ghost",size:"sm",onClick:z,children:h("gitView.common.cancel")}),s.jsx(ze,{variant:"default",size:"sm",onClick:he,disabled:!k,className:"gap-1.5",children:S==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"git-merge",className:"size-4"}),h("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"git-branch",className:"size-4"}),h("gitView.operation.rebase")]})})]}):s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(ze,{variant:"destructive",size:"sm",onClick:z,disabled:B,children:h("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx(ze,{variant:"default",size:"sm",onClick:he,disabled:B||!k,children:h(S==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(g==="inline"){let Ne;e[38]!==h?(Ne=h("gitView.branch.updateTitle"),e[38]=h,e[39]=Ne):Ne=e[39];let Y;e[40]!==Ne?(Y=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Ne}),e[40]=Ne,e[41]=Y):Y=e[41];let F;e[42]!==h?(F=h("gitView.branch.updateDescriptionPrefix"),e[42]=h,e[43]=F):F=e[43];let se;e[44]!==T?(se=s.jsx("span",{className:"font-mono text-foreground",children:T}),e[44]=T,e[45]=se):se=e[45];let Oe;e[46]!==F||e[47]!==se?(Oe=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[F," ",se,"."]}),e[46]=F,e[47]=se,e[48]=Oe):Oe=e[48];let ce;e[49]!==Y||e[50]!==Oe?(ce=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[Y,Oe]})}),e[49]=Y,e[50]=Oe,e[51]=ce):ce=e[51];let Ue;e[52]!==pe?(Ue=s.jsx("div",{className:"pt-3",children:pe}),e[52]=pe,e[53]=Ue):Ue=e[53];let qe;return e[54]!==ce||e[55]!==Ue?(qe=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[ce,Ue]}),e[54]=ce,e[55]=Ue,e[56]=qe):qe=e[56],qe}let Ee;e[57]!==b?(Ee=b?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"git-merge",className:"size-4"}),e[57]=b,e[58]=Ee):Ee=e[58];let ge;e[59]!==h?(ge=h("gitView.branch.mergeRebase"),e[59]=h,e[60]=ge):ge=e[60];let oe;e[61]!==ge?(oe=s.jsx("span",{children:ge}),e[61]=ge,e[62]=oe):oe=e[62];let je;e[63]!==le||e[64]!==B||e[65]!==Ee||e[66]!==oe?(je=s.jsx(At,{asChild:!0,children:s.jsxs(ze,{variant:"outline",size:"sm",className:"gap-1.5",onClick:le,disabled:B,children:[Ee,oe]})}),e[63]=le,e[64]=B,e[65]=Ee,e[66]=oe,e[67]=je):je=e[67];let ye;e[68]!==h?(ye=h("gitView.branch.mergeRebaseTooltip"),e[68]=h,e[69]=ye):ye=e[69];let ue;e[70]!==ye?(ue=s.jsx(Dt,{sideOffset:8,children:ye}),e[70]=ye,e[71]=ue):ue=e[71];let De;e[72]!==je||e[73]!==ue?(De=s.jsxs(Ct,{children:[je,ue]}),e[72]=je,e[73]=ue,e[74]=De):De=e[74];let I;e[75]!==K||e[76]!==j?(I=Ne=>{Ne?j(!0):K()},e[75]=K,e[76]=j,e[77]=I):I=e[77];let _;e[78]!==h?(_=h("gitView.branch.updateTitle"),e[78]=h,e[79]=_):_=e[79];let be;e[80]!==_?(be=s.jsx(Hs,{children:_}),e[80]=_,e[81]=be):be=e[81];let R;e[82]!==U||e[83]!==b||e[84]!==S||e[85]!==W||e[86]!==h||e[87]!==T?(R=b?h(W?U?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":S==="merge"?"gitView.branch.mergingInProgress":"gitView.branch.rebasingInProgress"):s.jsxs(s.Fragment,{children:[h("gitView.branch.dialogDescriptionPrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:T}),"."]}),e[82]=U,e[83]=b,e[84]=S,e[85]=W,e[86]=h,e[87]=T,e[88]=R):R=e[88];let de;e[89]!==R?(de=s.jsx(mn,{children:R}),e[89]=R,e[90]=de):de=e[90];let fe;e[91]!==be||e[92]!==de?(fe=s.jsxs(sn,{children:[be,de]}),e[91]=be,e[92]=de,e[93]=fe):fe=e[93];let $;e[94]!==pe||e[95]!==fe?($=s.jsxs(Vs,{className:"max-w-md",children:[fe,pe]}),e[94]=pe,e[95]=fe,e[96]=$):$=e[96];let Ae;e[97]!==C||e[98]!==I||e[99]!==$?(Ae=s.jsx(_s,{open:C,onOpenChange:I,children:$}),e[97]=C,e[98]=I,e[99]=$,e[100]=Ae):Ae=e[100];let Ve;return e[101]!==De||e[102]!==Ae?(Ve=s.jsxs(s.Fragment,{children:[De,Ae]}),e[101]=De,e[102]=Ae,e[103]=Ve):Ve=e[103],Ve};function hv(t){return t.status==="done"||t.status==="error"}function pv(t){return t.status==="error"}function gv(t){return t.slice(t.indexOf("/")+1)}function xv(t,e){return s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"mt-0.5 shrink-0",children:[t.status==="running"&&s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(A,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(A,{name:"close",className:"size-3.5 text-destructive"}),t.status==="pending"&&s.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),s.jsx("span",{className: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 bv(t){return t.stopPropagation()}const wv=({runMutation:t,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:o})=>{const a=[];let c=!1;return{enqueue:d=>{const f=a[a.length-1];if(f?.directory===d.directory&&f.direction===d.direction){d.paths.forEach(m=>f.paths.add(m));return}a.push(d)},flush:()=>{if(c)return;const d=a.shift();if(!d)return;c=!0;const f={directory:d.directory,direction:d.direction,paths:Array.from(d.paths),rollback:d.rollback};(async()=>{try{await t(f),e(f)}catch(m){n(f,m)}finally{r(f.paths),c=!1,a.length>0&&o()}})()},clear:()=>{a.length=0},size:()=>a.length,isRunning:()=>c}},Ou="oc.git.actionTab",yv=15e3,vv=t=>t==="commit"||t==="branch"||t==="pr",jv=40,Sv=20,Lu={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:"},Nv=(t,e)=>{const n=t.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,o=n.match(r);if(o){const l=o[1],d=Lu[l];if(d)return e.find(f=>f.code===d)||null}const a=n.split(" ")[0],c=Lu[a];return c&&e.find(l=>l.code===c)||null},kv=20,Hi=new Map,Cv=(t,e)=>{if(Hi.delete(t),Hi.set(t,e),Hi.size>kv){const n=Hi.keys().next().value;n!==void 0&&Hi.delete(n)}},qr=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Bu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Av=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},ic=({isActive:t})=>{const{t:e}=yt(),{git:n}=Zn(),r=wi(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=mt(Q=>Q.currentSessionId),f=mt(Q=>Q.newSessionDraft),m=mt(Q=>Q.setDraftBootstrapPendingDirectory),u=mt(Q=>Q.worktreeMetadata),p=mt(Q=>Q.availableWorktrees),x=qr(r),b=i.useMemo(()=>{if(!x)return;const Q=p.find(ke=>qr(ke.path)===x);if(Q)return Q;for(const ke of u.values())if(qr(ke.path)===x)return ke},[p,x,u]),w=i.useMemo(()=>{if(d)return u.get(d)??b;if(f?.open)return b},[d,b,f?.open,u]),{profiles:g,globalIdentity:h,defaultGitIdentityId:C,loadProfiles:j,loadGlobalIdentity:S,loadDefaultGitIdentityId:N}=eb(Kl(Q=>({profiles:Q.profiles,globalIdentity:Q.globalIdentity,defaultGitIdentityId:Q.defaultGitIdentityId,loadProfiles:Q.loadProfiles,loadGlobalIdentity:Q.loadGlobalIdentity,loadDefaultGitIdentityId:Q.loadDefaultGitIdentityId}))),k=Pc(r??null),y=Ja(r??null),D=om(Q=>d?Q.getAttachment(d):void 0),V=D?hg(D):[],v=D&&!D.degraded&&!D.legacy?D.worktreeRoot??void 0:void 0,O=ny(r,w,y?.current??void 0),P=um(r??null),E=pg(r??null),B=gg(r??null),T=Ic(r??null),W=xg(r??null),{setActiveDirectory:U,fetchAll:L,ensureAll:M,fetchStatus:ee,fetchBranches:ie,fetchLog:X,setLogMaxCount:H,fetchIdentity:te,prefetchDiffs:re,moveStatusPathsOptimistically:le,restoreStatus:ve,bumpIndexRevision:ne}=vn(Kl(Q=>({setActiveDirectory:Q.setActiveDirectory,fetchAll:Q.fetchAll,ensureAll:Q.ensureAll,fetchStatus:Q.fetchStatus,fetchBranches:Q.fetchBranches,fetchLog:Q.fetchLog,setLogMaxCount:Q.setLogMaxCount,fetchIdentity:Q.fetchIdentity,prefetchDiffs:Q.prefetchDiffs,moveStatusPathsOptimistically:Q.moveStatusPathsOptimistically,restoreStatus:Q.restoreStatus,bumpIndexRevision:Q.bumpIndexRevision}))),we=Re(Q=>Q.isMobile),he=Re(Q=>Q.openContextDiff),Me=Re(Q=>Q.navigateToDiff),z=Re(Q=>Q.setRightSidebarOpen),K=i.useRef(null),q=i.useRef(null),me=i.useRef(null),Se=i.useRef(null),Be=i.useRef(!0);i.useEffect(()=>()=>{Be.current=!1},[]);const _e=i.useCallback(()=>{q.current!==null&&(window.clearTimeout(q.current),q.current=null)},[]),Le=i.useCallback(Q=>{_e(),q.current=window.setTimeout(()=>{q.current=null,qr(Q)===qr(r)&&ee(Q,n,{silent:!0})},yv)},[_e,r,ee,n]);i.useEffect(()=>_e,[_e]);const pe=i.useCallback(()=>{me.current!==null&&(window.clearTimeout(me.current),me.current=null)},[]),Ee=i.useCallback(()=>{me.current===null&&(me.current=window.setTimeout(()=>{me.current=null,Se.current?.()},0))},[]),ge=i.useCallback(async(Q,ke,Ie)=>{if(ke==="stage"){if(n.stageGitFiles){await n.stageGitFiles(Q,Ie);return}await Promise.all(Ie.map($e=>n.stageGitFile(Q,$e)));return}if(n.unstageGitFiles){await n.unstageGitFiles(Q,Ie);return}await Promise.all(Ie.map($e=>n.unstageGitFile(Q,$e)))},[n]),oe=i.useMemo(()=>wv({runMutation:({directory:Q,direction:ke,paths:Ie})=>ge(Q,ke,Ie),onMutationComplete:({directory:Q})=>{ne(Q),Le(Q)},onMutationError:({directory:Q,direction:ke,rollback:Ie},$e)=>{Ie?.(),ne(Q),Le(Q);const ft=e(ke==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");ae.error($e instanceof Error?$e.message:ft)},onPathsComplete:Q=>{ot(ke=>{const Ie=new Set(ke);return Q.forEach($e=>Ie.delete($e)),Ie})},scheduleFlush:Ee}),[ne,ge,Ee,Le,e]);i.useEffect(()=>(Se.current=oe.flush,()=>{Se.current=null}),[oe]),i.useEffect(()=>()=>oe.clear(),[oe]),i.useEffect(()=>pe,[pe]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let Q=!1,ke=null;const Ie=async()=>{try{const $e=await wg(r);if(Q)return;a($e.status),$e.status==="pending"&&(ke=window.setTimeout(()=>{Ie()},500))}catch{Q||a(null)}};return Ie(),()=>{Q=!0,ke!==null&&window.clearTimeout(ke)}},[t,r]),i.useEffect(()=>{const Q=K.current;K.current=o,!(!r||!n)&&(Q==="pending"&&o==="ready"&&(l(!0),L(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(m(null),l(!1)))},[r,L,n,m,o]);const je=qr(f?.bootstrapPendingDirectory??null),ye=!!(r&&je&&je===qr(r)),De=!!(r&&(o==="pending"||ye))||c,I=i.useMemo(()=>r?Hi.get(r)??null:null,[r]),_=is(Q=>Q.settingsGitmojiEnabled),[be,R]=i.useState(null),{gitmojis:de}=sy(_);i.useEffect(()=>{const Q=v||O?.projectDirectory;if(!Q){R(null);return}let ke=!1;return Xa(Q).then(Ie=>{if(ke)return;const $e=Ie.trim();R($e&&$e!=="HEAD"?$e:null)}).catch(()=>{ke||R(null)}),()=>{ke=!0}},[v,O?.projectDirectory]);const[fe,$]=i.useState(I?.commitMessage??""),[Ae,Ve]=i.useState([]),[Ne,Y]=i.useState(!1),F=i.useRef(null),[se,Oe]=i.useState(null),[ce,Ue]=i.useState(!1),[qe,Ye]=i.useState(null),[tt,xt]=i.useState(25),[vt,Mt]=i.useState(!1),{triggerFireworks:Tt}=Xw(),Kt=i.useRef(new Map),Ut=i.useRef(0),Zt=i.useCallback(()=>{Ut.current+=1,Be.current&&Mt(!0)},[]),ns=i.useCallback(()=>{Ut.current=Math.max(0,Ut.current-1),Be.current&&Ut.current===0&&Mt(!1)},[]),[es,Ce]=i.useState(new Set),[Qe,ot]=i.useState(new Set),[bt,Je]=i.useState(!1),[Pt,Xe]=i.useState(0),[Ke,Ze]=i.useState(!1),[Bt,Rt]=i.useState(I?.generatedHighlights??[]),Ot=Qe.size>0||oe.size()>0||oe.isRunning(),rs=i.useCallback(()=>{const Q=F.current;Q&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"})})})},[]),Wt=v||O?.projectDirectory||null,Et=y?.current||null,qt=i.useMemo(()=>{const Q=y?.tracking;return Q?Q.startsWith("origin/"):!0},[y?.tracking]),hs=i.useMemo(()=>{const Q=O?.createdFromBranch,ke=typeof Q=="string"?Q.trim():"",Ie=typeof y?.current=="string"?y.current.trim():"",$e=typeof be=="string"?be.trim():"";return ke?ke===Ie&&ke.startsWith("opencode/")&&$e.length>0&&$e!==ke?$e:ke:$e||Ie||"HEAD"},[O?.createdFromBranch,y,be]),ts=i.useCallback(()=>{Rt([])},[]),[as,gs]=i.useState(new Set),[Ft,Lt]=i.useState(new Map),[Ht,Yt]=i.useState(new Set),$t=i.useRef(Ft),Fe=i.useRef(Ht),[st,wt]=i.useState(null),[St,Nt]=i.useState(null),[ss,cs]=i.useState(""),[Xt,Vt]=i.useState(null),Fs=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(A,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(A,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(A,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[us,$s]=i.useState(()=>{if(typeof window>"u")return"commit";const Q=window.localStorage.getItem(Ou);return Q==="worktree"?"branch":vv(Q)?Q:"commit"}),[js,Cs]=i.useState([]),[jn,hn]=i.useState(null),[xe,rt]=i.useState(null),[dt,jt]=i.useState([]),[zt,gt]=i.useState(!1),[xs,bs]=i.useState([]),[Ss,Ns]=i.useState("merge"),[Os,Tn]=i.useState(null),[Gs,Pn]=i.useState(!1),[Bn,Sn]=i.useState(100),an=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),Nn=i.useCallback((Q,ke,Ie)=>{if(!an||typeof window>"u")return;const $e={directory:Q,conflictFiles:ke,operation:Ie};window.localStorage.setItem(an,JSON.stringify($e))},[an]),nn=i.useCallback(()=>{!an||typeof window>"u"||window.localStorage.removeItem(an)},[an]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Ou,us)},[us]),i.useEffect(()=>{if(!an||typeof window>"u"||!r)return;const Q=window.localStorage.getItem(an);if(Q)try{const ke=JSON.parse(Q);if(ke.directory!==r){window.localStorage.removeItem(an);return}bs(ke.conflictFiles??[]),Ns(ke.operation??"merge"),gt(!0)}catch{window.localStorage.removeItem(an)}},[an,r]);const[Ge,ps]=i.useState(!1),[ks,zs]=i.useState("merge"),[Rs,rn]=i.useState(""),Ks=i.useCallback(Q=>{xr(Q).then(ke=>{if(ke.ok){ae.success(e("gitView.toast.commitHashCopied"));return}ae.error(e("gitView.toast.copyFailed"))})},[e]),Is=i.useCallback(Q=>{gs(ke=>{const Ie=new Set(ke);return Ie.has(Q)?Ie.delete(Q):Ie.add(Q),Ie})},[]);i.useEffect(()=>{$t.current=Ft},[Ft]),i.useEffect(()=>{Fe.current=Ht},[Ht]),i.useEffect(()=>{if(!r||!n)return;const Q=Array.from(as).filter(Ie=>!$t.current.has(Ie)&&!Fe.current.has(Ie));if(Q.length===0)return;let ke=!1;return Yt(Ie=>{const $e=new Set(Ie);for(const ft of Q)$e.add(ft);return Fe.current=$e,$e}),Promise.all(Q.map(Ie=>n.getCommitFiles(r,Ie).then($e=>({hash:Ie,files:$e.files})).catch($e=>(console.error("Failed to fetch commit files:",$e),{hash:Ie,files:[]})))).then(Ie=>{ke||(Lt($e=>{const ft=new Map($e);for(const{hash:It,files:Qt}of Ie)ft.set(It,Qt);return $t.current=ft,ft}),Yt($e=>{const ft=new Set($e);for(const{hash:It}of Ie)ft.delete(It);return Fe.current=ft,ft}))}),()=>{ke=!0,Yt(Ie=>{let $e=!1;const ft=new Set(Ie);for(const It of Q)ft.delete(It)&&($e=!0);return $e?(Fe.current=ft,ft):Ie})}},[as,r,n]),i.useEffect(()=>{r&&Cv(r,{directory:r,commitMessage:fe,generatedHighlights:Bt})},[fe,r,Bt]),i.useEffect(()=>{t&&(j(),S(),N())},[t,j,S,N]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){Nt(null);return}let Q=!1;return n.getRemoteUrl(r).then(ke=>{Q||Nt(ke)}).catch(()=>{Q||Nt(null)}),()=>{Q=!0}},[t,r,n]);const Vn=i.useCallback(async()=>{if(!r||!n?.getRemotes){Cs([]);return}try{const Q=await n.getRemotes(r);Be.current&&Cs(Q)}catch{Be.current&&Cs([])}},[r,n]);i.useEffect(()=>{t&&Vn()},[t,Vn]),i.useEffect(()=>{t&&r&&(U(r),M(r,n))},[t,r,U,M,n]),i.useEffect(()=>{if(t&&r)return Lr.onGitRefreshHint(Q=>{qr(Q.directory)===qr(r)&&ee(r,n)})},[t,r,ee,n]);const ws=i.useCallback(async(Q=!0)=>{if(r)try{await Promise.all([ee(r,n),ie(r,n)])}catch(ke){if(Q){const Ie=ke instanceof Error?ke.message:e("gitView.toast.refreshRepositoryFailed");ae.error(Ie)}}},[r,n,ee,ie,e]),Ls=i.useCallback(async()=>{r&&await X(r,n,tt)},[r,n,X,tt]),Dr=i.useCallback(async()=>{r&&await te(r,n)},[r,n,te]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||k!==!0)return;const Q=typeof C=="string"?C.trim():"";if(!Q||Q==="global"||Kt.current.get(r)===Q)return;let Ie=!1;return(async()=>{try{const ft=await n.hasLocalIdentity?.(r);if(Ie||ft===!0)return;Zt(),await n.setGitIdentity(r,Q),Kt.current.set(r,Q),await Dr()}catch(ft){console.warn("Failed to auto-apply default git identity:",ft)}finally{Ie||ns()}})(),()=>{Ie=!0}},[t,Zt,r,C,ns,n,k,Dr]);const _n=i.useMemo(()=>y?[...y.files??[]].sort((ke,Ie)=>ke.path.localeCompare(Ie.path)):[],[y]),bn=i.useMemo(()=>_n.filter(Bu),[_n]),Tr=i.useMemo(()=>_n.filter(Av),[_n]);i.useEffect(()=>{if(!r||_n.length===0)return;const Q=[],ke=new Set,Ie=ft=>{!ft||ke.has(ft)||(ke.add(ft),Q.push(ft))};if(bn.forEach(ft=>Ie(ft.path)),Ae.forEach(Ie),_n.slice(0,Sv).forEach(ft=>Ie(ft.path)),Q.length===0)return;const $e=window.setTimeout(()=>{re(r,n,Q,{maxFiles:jv})},120);return()=>{window.clearTimeout($e)}},[_n,r,n,re,bn,Ae]);const si=Q=>Q?.pushed[0]?.remote||y?.tracking?.split("/")[0]||os.find(ke=>ke.name==="origin")?.name||os[0]?.name||"origin",ni=async(Q,ke)=>{if(r){Oe(Q);try{const Ie=$e=>{const ft=`${$e.name}/`,It=y?.tracking?.startsWith(ft)?y.tracking.slice(ft.length):void 0;return{remote:$e.name,branch:It,rebase:!0}};if(Q==="fetch"){if(!ke)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:ke.name}),ae.success(e("gitView.toast.fetchedFromRemote",{name:ke.name}))}else if(Q==="pull"){if(!ke)throw new Error("No remote available for pull");const $e=await n.gitPull(r,Ie(ke));ae.success($e.files.length===1?e("gitView.toast.pulledFilesSingle",{count:$e.files.length,name:ke.name}):e("gitView.toast.pulledFilesPlural",{count:$e.files.length,name:ke.name}))}else if(Q==="push"){const $e=await n.gitPush(r);ae.success(e("gitView.toast.pushedToUpstream",{name:si($e)}))}else if(Q==="sync"){if(!ke)throw new Error("No remote available for sync");let $e=0,ft=!1;await n.gitFetch(r,{remote:ke.name});const It=await n.getGitStatus(r);if((It.behind??0)>0){if((It.files?.length??0)>0){ae.error(e("gitView.toast.commitOrStashBeforeSync"));return}$e=(await n.gitPull(r,Ie(ke))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),ft=!0),$e>0&&ft?ae.success($e===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:$e,name:ke.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:$e,name:ke.name})):$e>0?ae.success($e===1?e("gitView.toast.pulledFilesSingle",{count:$e,name:ke.name}):e("gitView.toast.pulledFilesPlural",{count:$e,name:ke.name})):ft?ae.success(e("gitView.toast.pushedToUpstream",{name:ke.name})):ae.success(e("gitView.toast.alreadyUpToDate"))}await ws(!1),await Ls()}catch(Ie){const $e=Ie instanceof Error?Ie.message:e("gitView.toast.syncActionFailed",{action:Q==="sync"?e("gitView.sync.syncChanges"):Q==="pull"?e("gitView.sync.pull"):Q});ae.error($e)}finally{Oe(null)}}},zr=i.useCallback(async Q=>{if(!r)return;const ke=Q.name.trim();if(!ke){ae.error(e("gitView.toast.remoteNameRequired"));return}if(ke==="origin"){ae.error(e("gitView.toast.cannotRemoveOriginRemote"));return}hn(ke);try{await n.removeRemote(r,{remote:ke}),ae.success(e("gitView.toast.removedRemote",{name:ke})),await Promise.all([ws(!1),Vn()])}catch(Ie){const $e=Ie instanceof Error?Ie.message:`Failed to remove ${ke}`;ae.error($e)}finally{hn(null)}},[r,n,Vn,ws,e]),cr=async(Q={})=>{if(!r)return;if(!fe.trim()){ae.error(e("gitView.toast.enterCommitMessage"));return}const ke=bn.map($e=>$e.path).sort();if(ke.length===0){ae.error(e("gitView.toast.stageFileToCommit"));return}const Ie=Q.pushAfter?"commitAndPush":"commit";Ye(Ie);try{if(await n.createGitCommit(r,fe.trim(),{files:ke,stageFiles:[]}),ne(r),ae.success(e("gitView.toast.commitCreated")),$(""),ts(),await ws(),Q.pushAfter){const $e=y?.tracking?.split("/")[0],ft=os.find(Ir=>Ir.name===$e)??os[0];if(!ft)throw new Error(e("mobile.changes.noRemote"));Oe("sync");const It=`${ft.name}/`,Qt=y?.tracking?.startsWith(It)?y.tracking.slice(It.length):void 0;await n.gitFetch(r,{remote:ft.name});const Jt=await n.getGitStatus(r);if((Jt.behind??0)>0){if((Jt.files?.length??0)>0){ae.error(e("gitView.toast.commitOrStashBeforeSync")),await ws(!1);return}await n.gitPull(r,{remote:ft.name,branch:Qt,rebase:!0})}const vs=await n.getGitStatus(r);let vr;(vs.ahead??0)>0&&(vr=await n.gitPush(r)),ae.success(e("gitView.toast.pushedToUpstream",{name:si(vr)})),Tt(),await ws(!1)}else await ws(!1);await Ls(),Xe($e=>$e+1)}catch($e){const ft=$e instanceof Error?$e.message:e("gitView.toast.createCommitFailed");ae.error(ft)}finally{Ye(null),Q.pushAfter&&Oe(null)}},ys=i.useCallback(async()=>{if(!r)return;const Q=bn.map(ke=>ke.path).sort();if(Q.length===0){ae.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:Q.length}),Ze(!0);try{const{message:ke}=await bg(r,Q),Ie=ke.subject?.trim()??"",$e=Array.isArray(ke.highlights)?ke.highlights:[];if(Ie){let ft=Ie;if(_&&de.length>0){const It=Nv(Ie,de);if(It){const{code:Qt,emoji:Jt}=It;!Ie.startsWith(Qt)&&!Ie.startsWith(Jt)&&(ft=`${Qt} ${Ie}`)}}$(ft)}Rt($e),rs()}catch(ke){console.error("[git-generation][browser] GitView generate handler failed",{message:ke instanceof Error?ke.message:String(ke),error:ke});const Ie=ke instanceof Error?ke.message:e("gitView.toast.generateCommitMessageFailed");ae.error(Ie)}finally{Ze(!1)}},[r,bn,_,de,rs,e]),ln=Q=>Q.reason==="attention"?`${Q.attentionReason} in progress`:Q.reason==="missing"?"worktree is missing":"worktree is invalid",dr=async(Q,ke)=>{if(!r||!y)return;const Ie=dl(D);if(Ie.length>0){ae.error(e("gitView.toast.cannotCreateBranch",{reason:ln(Ie[0])}));return}const $e=y.current??null,ft=ke?.name??"origin";try{await n.createBranch(r,Q,$e??"HEAD"),ae.success(e("gitView.toast.createdBranch",{name:Q})),await n.checkoutBranch(r,Q);let It=!1;try{await n.gitPush(r,{remote:ft,branch:Q,options:["--set-upstream"]}),It=!0}catch(Qt){const Jt=Qt instanceof Error?Qt.message:`Unable to push new branch to ${ft}.`;ae.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Jt]})})}await ws(),await Ls(),It&&ae.success(e("gitView.toast.upstreamSet",{branch:Q,remote:ft}))}catch(It){const Qt=It instanceof Error?It.message:e("gitView.toast.createBranchFailed");throw ae.error(Qt),It}},J=async(Q,ke)=>{if(!r)return;const Ie=dl(D);if(Ie.length>0){ae.error(e("gitView.toast.cannotRenameBranch",{reason:ln(Ie[0])}));return}try{await n.renameBranch(r,Q,ke),ae.success(e("gitView.toast.renamedBranch",{oldName:Q,newName:ke})),await ws(),await Ls()}catch($e){const ft=$e instanceof Error?$e.message:e("gitView.toast.renameBranchFailed",{oldName:Q,newName:ke});ae.error(ft)}},at=async Q=>{if(!r)return;const ke=dl(D);if(ke.length>0){ae.error(e("gitView.toast.cannotCheckout",{reason:ln(ke[0])}));return}const Ie=Q.replace(/^remotes\//,"");if(y?.current!==Ie)try{await n.checkoutBranch(r,Ie),ae.success(e("gitView.toast.checkedOut",{name:Ie})),await ws(),await Ls()}catch($e){const ft=$e instanceof Error?$e.message:e("gitView.toast.checkoutFailed",{name:Ie});ae.error(ft)}},ut=async Q=>{if(r){Zt();try{await n.setGitIdentity(r,Q.id),ae.success(e("gitView.toast.appliedIdentity",{name:Q.name})),await Dr()}catch(ke){const Ie=ke instanceof Error?ke.message:e("gitView.toast.applyIdentityFailed");ae.error(Ie)}finally{ns()}}},kt=i.useMemo(()=>P?.all?P.all.filter(Q=>!Q.startsWith("remotes/")).sort():[],[P]),Gt=i.useMemo(()=>P?.all?P.all.filter(Q=>Q.startsWith("remotes/")).map(Q=>Q.replace(/^remotes\//,"")).sort():[],[P]),os=i.useMemo(()=>{if(js.length>0)return js;const Q=new Set,ke=y?.tracking?.trim();ke&&ke.includes("/")&&Q.add(ke.split("/")[0]);for(const Ie of Gt){const $e=Ie.indexOf("/");$e>0&&Q.add(Ie.slice(0,$e))}return Q.size===0&&St&&Q.add("origin"),Array.from(Q).map(Ie=>({name:Ie,fetchUrl:St??"",pushUrl:St??""}))},[js,Gt,St,y?.tracking]),fs=i.useMemo(()=>{const Q=new Set(os.map(ft=>ft.name)),ke=ft=>{if(!ft)return"";let It=ft.trim();if(!It||It==="HEAD")return"";if(kt.includes(It))return It;It.startsWith("refs/heads/")&&(It=It.slice(11)),It.startsWith("heads/")&&(It=It.slice(6)),It.startsWith("remotes/")&&(It=It.slice(8));const Qt=It.indexOf("/");if(Qt>0){const Jt=It.slice(0,Qt);if(Q.has(Jt)){const vs=It.slice(Qt+1).trim();vs&&(It=vs)}}return It},Ie=ke(typeof O?.createdFromBranch=="string"?O.createdFromBranch:"");if(Ie)return Ie;const $e=ke(typeof be=="string"?be:"");return $e||(kt.includes("main")?"main":kt.includes("master")?"master":kt.includes("develop")?"develop":"main")},[os,kt,be,O?.createdFromBranch]),Es=i.useMemo(()=>os.map(Ie=>Ie.name).map(Ie=>`${Ie}/${fs}`).find(Ie=>Gt.includes(Ie))??fs,[fs,os,Gt]),qs=i.useMemo(()=>{const Q=new Map;h&&Q.set(h.id,h);let ke=null;if(St)try{let Ie=St.trim();Ie.startsWith("git@")&&(Ie=`https://${Ie.slice(4).replace(":","/")}`),Ie.endsWith(".git")&&(Ie=Ie.slice(0,-4));const $e=new URL(Ie);ke=$e.hostname+$e.pathname}catch{}for(const Ie of g){if(Ie.authType!=="token"){Q.set(Ie.id,Ie);continue}const $e=Ie.host;if(!$e){Q.set(Ie.id,Ie);continue}if(!$e.includes("/")){Q.set(Ie.id,Ie);continue}ke&&ke===$e&&Q.set(Ie.id,Ie)}return Array.from(Q.values())},[g,h,St]),er=i.useMemo(()=>{if(B?.userName&&B?.userEmail){const Q=g.find(ke=>ke.userName===B.userName&&ke.userEmail===B.userEmail);return Q||(h&&h.userName===B.userName&&h.userEmail===B.userEmail?h:{id:"local-config",name:B.userName,userName:B.userName,userEmail:B.userEmail,sshKey:B.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return h??null},[B,g,h]),$n=bn.length,ri=T||se!==null||qe!==null,pn=y?.current??null,Wr=!!(O&&Wt&&Et&&qt),In=!!(r&&pn),tr=!!pn,cn=Wr&&Wt&&Et&&O?{repoRoot:Wt,sourceBranch:Et,worktreeMetadata:O}:null,gn=i.useMemo(()=>!In||!r||!pn?null:{directory:r,branch:pn},[In,pn,r]);i.useEffect(()=>{if(!r||!n||!E?.all?.length||!pn||!fs||pn===fs){wt(null);return}let Q=!1;return(async()=>{try{const Ie=await n.getGitLog(r,{from:fs,to:"HEAD",maxCount:tt});if(Q)return;const $e=new Set((Ie?.all??[]).map(It=>It.hash).filter(It=>typeof It=="string"&&It.length>0));if($e.size===0){wt(null);return}const ft=E.all.findIndex(It=>!$e.has(It.hash));if(ft===0){wt(null);return}if(ft===-1){wt({insertBeforeIndex:E.all.length,branchName:pn,direction:"up"});return}wt({insertBeforeIndex:ft,branchName:pn,direction:"up"})}catch{Q||wt(null)}})(),()=>{Q=!0}},[fs,pn,r,n,E,tt]),i.useEffect(()=>{Tn(null)},[r]),i.useEffect(()=>{if(Xt!=="graph"||!r){Xt!=="graph"&&Tn(null);return}let Q=!1;return Pn(!0),n.getGitLog(r,{maxCount:Bn,all:!0}).then(ke=>{Q||Tn(ke)}).catch(ke=>{console.error("Failed to fetch graph log:",ke)}).finally(()=>{Q||Pn(!1)}),()=>{Q=!0}},[Xt,r,Bn,n]);const wn=i.useCallback((Q,ke)=>{if(!r||Q.length===0)return;const Ie=Array.from(new Set(Q));ot(ft=>{const It=new Set(ft);return Ie.forEach(Qt=>It.add(Qt)),It});const $e=le(r,Ie,ke);oe.enqueue({directory:r,direction:ke,paths:new Set(Ie),rollback:()=>ve(r,$e)}),Ee()},[r,oe,le,ve,Ee]),sr=i.useCallback(async Q=>{if(r){Ce(ke=>{const Ie=new Set(ke);return Ie.add(Q),Ie});try{await n.revertGitFile(r,Q,{scope:"working"}),ae.success(e("gitView.toast.revertedFile",{path:Q})),await ws(!1)}catch(ke){const Ie=ke instanceof Error?ke.message:e("gitView.toast.revertFailed");ae.error(Ie)}finally{Ce(ke=>{const Ie=new Set(ke);return Ie.delete(Q),Ie})}}},[r,ws,n,e]),nr=i.useCallback(async(Q,ke,Ie="all")=>{if(!r||Q.length===0)return;const $e=Array.from(new Set(Q));if(bt||$e.some(Jt=>es.has(Jt)))return;const ft=new Set(bn.map(Jt=>Jt.path)),It=Ie==="all"&&$e.some(Jt=>ft.has(Jt));ke&&Je(!0),Ce(Jt=>{const vs=new Set(Jt);return $e.forEach(vr=>vs.add(vr)),vs});const Qt=[];try{if(await Promise.all($e.map(async Jt=>{try{await n.revertGitFile(r,Jt,{scope:Ie})}catch(vs){Qt.push({path:Jt,message:vs instanceof Error?vs.message:e("gitView.toast.revertFailed")})}})),It&&Qt.length<$e.length&&ne(r),await ws(!1),Qt.length===0)ae.success($e.length===1?e("gitView.toast.revertedFilesSingle",{count:$e.length}):e("gitView.toast.revertedFilesPlural",{count:$e.length}));else if(Qt.length===$e.length)ae.error(Qt[0]?.message||e("gitView.toast.revertFailed"));else{const Jt=$e.length-Qt.length;ae.warning(Jt===1?e("gitView.toast.revertedSomeSingle",{success:Jt,failed:Qt.length}):e("gitView.toast.revertedSomePlural",{success:Jt,failed:Qt.length}))}}finally{Ce(Jt=>{const vs=new Set(Jt);return $e.forEach(vr=>vs.delete(vr)),vs}),ke&&Je(!1)}},[ne,r,n,bt,ws,es,bn,e]),Ur=i.useCallback(async Q=>{await nr(Q,!0)},[nr]),rr=i.useCallback(async Q=>{await nr(Q,!1,"working")},[nr]),Hr=i.useCallback((Q,ke)=>{if(r&&!we){he(r,Q,ke);return}Me(Q,ke),we&&z(!1)},[r,we,Me,he,z]),ii=i.useCallback(()=>Ue(!0),[]),Oi=i.useMemo(()=>{const Q=[];return bn.length>0&&Q.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:bn,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:ke=>e("gitView.changes.unstageFileAria",{path:ke}),onActionFile:ke=>{wn([ke],"unstage")},onActionAll:ke=>{wn(ke,"unstage")},onViewDiff:ke=>Hr(ke,!0),onRevertFile:sr,showRevertActions:!1,accent:!0}),Tr.length>0&&Q.push({id:"unstaged",title:e("gitView.changes.title"),entries:Tr,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:ke=>e("gitView.changes.stageFileAria",{path:ke}),onActionFile:ke=>{wn([ke],"stage")},onActionAll:ke=>{wn(ke,"stage")},onViewDiff:ke=>Hr(ke,!1),onRevertFile:sr}),Q},[sr,Hr,wn,bn,e,Tr]),Li=i.useCallback(Q=>{if(Q.length===0)return;const ke=Q.map(Ie=>Ie.trim()).filter(Boolean);if(ke.length===0){ts();return}$(Ie=>{const $e=Ie.trim(),ft=$e.length>0?`
11
+
12
+ `:"";return`${$e}${ft}${ke.join(`
13
+ `)}`.trim()}),ts()},[ts]),Rn=i.useCallback((Q,ke)=>{const Ie=ke||Q;$($e=>{const ft=$e.trimStart();return ft.startsWith(Q)||ke&&ft.startsWith(ke)?$e:`${Ie.endsWith(" ")?Ie:`${Ie} `}${$e}`.trimStart()}),cs(""),Y(!1)},[]),ur=i.useCallback(Q=>{const ke=Q instanceof Error?Q.message.toLowerCase():"";return ke.includes("uncommitted changes")||ke.includes("local changes")||ke.includes("your local changes would be overwritten")||ke.includes("please commit your changes or stash them")||ke.includes("cannot rebase: you have unstaged changes")||ke.includes("error: cannot pull with rebase")},[]),Ys=i.useCallback((Q,ke)=>{jt(Ie=>[...Ie,{message:Q,status:ke,timestamp:Date.now()}])},[]),Qs=i.useCallback((Q,ke)=>{jt(Ie=>{if(Ie.length===0)return Ie;const $e=[...Ie];return $e[$e.length-1]={...$e[$e.length-1],status:Q,...ke?{message:ke}:{}},$e})},[]),wr=i.useCallback(()=>{jt([])},[]),go=i.useCallback(()=>{jt([]),rt(null)},[]),Pr=i.useCallback(Q=>{const ke=Q.trim(),Ie=new Set(os.map(ft=>ft.name)),$e=ke.indexOf("/");if($e>0){const ft=ke.slice(0,$e),It=ke.slice($e+1);if(Ie.has(ft)&&It)return{branch:ke,remote:ft,remoteBranch:It}}for(const ft of os){const It=`${ft.name}/${ke}`;if(Gt.includes(It))return{branch:It,remote:ft.name,remoteBranch:ke}}return{branch:ke,remote:null,remoteBranch:null}},[os,Gt]),fr=i.useCallback(async Q=>{if(!r)return;rt("merge"),wr();const ke=y?.current,Ie=Pr(Q);try{Ie.remote&&Ie.remoteBranch&&(Ys(`Fetching ${Ie.remote}/${Ie.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Ie.remote,branch:Ie.remoteBranch}),Qs("done",`Fetched ${Ie.remote}/${Ie.remoteBranch}`)),Ys(`Merging ${Ie.branch} into ${ke}...`,"running");const $e=await n.merge(r,{branch:Ie.branch});$e.conflict?(Qs("error","Merge conflicts detected"),bs($e.conflictFiles??[]),Ns("merge"),gt(!0),Nn(r,$e.conflictFiles??[],"merge")):(Qs("done",`Merged ${Ie.branch} into ${ke}`),nn(),Ys("Refreshing repository status...","running"),await ws(),await Ls(),Qs("done","Repository status updated"))}catch($e){if(ur($e))Qs("error","Uncommitted changes detected"),zs("merge"),rn(Ie.branch),ps(!0);else{const ft=$e instanceof Error?$e.message:`Failed to merge ${Ie.branch}`;Qs("error",ft)}}},[r,n,y,Pr,ws,Ls,ur,Nn,nn,Ys,Qs,wr]),yr=i.useCallback(async Q=>{if(!r)return;rt("rebase"),wr();const ke=y?.current,Ie=Pr(Q);try{Ie.remote&&Ie.remoteBranch&&(Ys(`Fetching ${Ie.remote}/${Ie.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Ie.remote,branch:Ie.remoteBranch}),Qs("done",`Fetched ${Ie.remote}/${Ie.remoteBranch}`)),Ys(`Rebasing ${ke} onto ${Ie.branch}...`,"running");const $e=await n.rebase(r,{onto:Ie.branch});$e.conflict?(Qs("error","Rebase conflicts detected"),bs($e.conflictFiles??[]),Ns("rebase"),gt(!0),Nn(r,$e.conflictFiles??[],"rebase")):(Qs("done",`Rebased ${ke} onto ${Ie.branch}`),nn(),Ys("Refreshing repository status...","running"),await ws(),await Ls(),Qs("done","Repository status updated"))}catch($e){if(ur($e))Qs("error","Uncommitted changes detected"),zs("rebase"),rn(Ie.branch),ps(!0);else{const ft=$e instanceof Error?$e.message:`Failed to rebase onto ${Ie.branch}`;Qs("error",ft)}}},[r,n,y,Pr,ws,Ls,ur,Nn,nn,Ys,Qs,wr]),yn=i.useCallback(async()=>{if(r)try{Ss==="merge"?(await n.abortMerge(r),ae.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),ae.success(e("gitView.toast.rebaseAborted"))),nn(),await ws(),await Ls()}catch(Q){const ke=Q instanceof Error?Q.message:`Failed to abort ${Ss}`;ae.error(ke)}},[r,n,Ss,ws,Ls,nn,e]),mr=i.useMemo(()=>y?.files?y.files.some(Q=>Q.index==="U"||Q.working_dir==="U"||Q.index==="A"&&Q.working_dir==="A"||Q.index==="D"&&Q.working_dir==="D"):!1,[y?.files]),xo=i.useCallback(async()=>{if(r)try{const Q=!!y?.mergeInProgress?.head,ke=!!(y?.rebaseInProgress?.headName||y?.rebaseInProgress?.onto);if(Q){const Ie=await n.continueMerge(r);Ie.conflict?(bs(Ie.conflictFiles??[]),Ns("merge"),gt(!0),Nn(r,Ie.conflictFiles??[],"merge"),ae.error(e("gitView.toast.mergeConflictsDetected"))):(nn(),ae.success(e("gitView.toast.mergeCompleted")),await ws(),await Ls())}else if(ke){const Ie=await n.continueRebase(r);Ie.conflict?(bs(Ie.conflictFiles??[]),Ns("rebase"),gt(!0),Nn(r,Ie.conflictFiles??[],"rebase"),ae.error(e("gitView.toast.rebaseConflictsDetected"))):(nn(),ae.success(e("gitView.toast.rebaseStepCompleted")),await ws(),await Ls())}}catch(Q){const ke=Q instanceof Error?Q.message:e("gitView.toast.continueOperationFailed");ae.error(ke)}},[r,n,y,ws,Ls,Nn,nn,e]),bo=i.useCallback(async()=>{if(r)try{!!y?.mergeInProgress?.head?(await n.abortMerge(r),ae.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),ae.success(e("gitView.toast.rebaseAborted"))),nn(),await ws(),await Ls()}catch(Q){const ke=Q instanceof Error?Q.message:e("gitView.toast.abortOperationFailed");ae.error(ke)}},[r,n,y,ws,Ls,nn,e]),oi=i.useCallback(()=>{if(!r)return;const ke=!!y?.mergeInProgress?.head?"merge":"rebase",Ie=y?.files?.filter($e=>$e.index==="U"||$e.working_dir==="U").map($e=>$e.path)??[];Ie.length>0&&bs(Ie),Ns(ke),gt(!0)},[r,y]),Bi=i.useCallback(async Q=>{if(!r)return;const ke=y?.current,Ie=ks,$e=Rs,ft=(y?.files??[]).some(Bu);try{await n.stash(r,{message:`Auto-stash before ${Ie} with ${$e}`,includeUntracked:!0}),ft&&ne(r)}catch(Jt){const vs=Jt instanceof Error?Jt.message:"Failed to stash changes";ae.error(vs);return}let It=!1,Qt=!1;try{if(Ie==="merge"){const Jt=await n.merge(r,{branch:$e});Jt.conflict?(Qt=!0,bs(Jt.conflictFiles??[]),Ns("merge"),gt(!0)):(It=!0,ae.success(e("gitView.toast.mergedIntoBranch",{branch:$e,currentBranch:ke||""})))}else{const Jt=await n.rebase(r,{onto:$e});Jt.conflict?(Qt=!0,bs(Jt.conflictFiles??[]),Ns("rebase"),gt(!0)):(It=!0,ae.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:ke||"",branch:$e})))}if(Q&&It)try{await n.stashPop(r),ne(r),ae.success(e("gitView.toast.stashedRestored"))}catch(Jt){const vs=Jt instanceof Error?Jt.message:e("gitView.toast.restoreStashFailed");ae.error(vs)}else Q&&Qt&&ae.info(e("gitView.toast.restoreStashManually"));await ws(),await Ls()}catch(Jt){if(Q)try{await n.stashPop(r),ne(r)}catch{}throw Jt}},[ne,r,n,y,ks,Rs,ws,Ls,e]),dn=i.useCallback(Q=>{xt(Q),r&&(H(r,Q),X(r,n,Q))},[r,X,n,H]),Gr=i.useCallback(Q=>{Sn(Q)},[]),Vi=i.useCallback(()=>{Vt(null),r&&(ee(r,n),ie(r,n),X(r,n,tt))},[r,ee,ie,X,tt,n]),_i=i.useCallback(Q=>{if(Q.conflict){if(Q.operation==="cherry-pick"||Q.operation==="revert"){ae.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:Q.conflictFiles?.join(", ")??"unknown files"})}),r&&(ee(r,n),ie(r,n),X(r,n,tt));return}bs(Q.conflictFiles??[]),Ns(Q.operation),gt(!0),r&&Nn(r,Q.conflictFiles??[],Q.operation)}},[e,bs,Ns,gt,Nn,r,ee,ie,X,tt,n]);return r?k===null||k===!0&&!y?s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):k===!1?De?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(A,{name:"loader-4",className:"mb-3 size-6 animate-spin text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.worktreeSetupInProgress")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.worktreeSetupDescription")})]}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(A,{name:"git-branch",className:"mb-3 size-6 text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.notGitRepository")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.notGitRepositoryDescription")}),V.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(tb,{status:y,localBranches:kt,remoteBranches:Gt,branchInfo:P?.branches,syncAction:se,remotes:os,onFetch:Q=>ni("fetch",Q),onSync:Q=>ni("sync",Q),onRemoveRemote:zr,removingRemoteName:jn,onCheckoutBranch:at,onCreateBranch:dr,onRenameBranch:J,activeIdentityProfile:er,availableIdentities:qs,onSelectIdentity:ut,isApplyingIdentity:vt,isWorktreeMode:!!O,onOpenHistory:()=>Vt("history"),onOpenGraph:()=>Vt("graph"),onOpenStashes:ii,actionTabItems:Fs,activeActionTab:us,onSelectActionTab:Q=>$s(Q)}),r&&(y?.mergeInProgress?.head||y?.rebaseInProgress?.headName||y?.rebaseInProgress?.onto)&&s.jsx(fv,{mergeInProgress:y?.mergeInProgress,rebaseInProgress:y?.rebaseInProgress,onContinue:xo,onAbort:bo,onResolveWithAI:oi,hasUnresolvedConflicts:mr,isLoading:T}),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(On,{as:Qa,ref:F,outerClassName:"flex-1 min-h-0",className:Pe("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[us==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(_n?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(sb,{groups:Oi,diffStats:y?.diffStats,revertingPaths:es,isRevertingAll:bt,onVisiblePathsChange:Ve,onRevertAll:Ur,onRevertDirectory:rr,headerBackgroundClassName:"bg-background"})}),s.jsx(nb,{stagedCount:$n,commitMessage:fe,onCommitMessageChange:$,generatedHighlights:Bt,onInsertHighlights:Li,onGenerateMessage:ys,isGeneratingMessage:Ke,onCommit:()=>cr({pushAfter:!1}),onCommitAndPush:()=>cr({pushAfter:!0}),commitAction:qe,hasPendingIndexMutation:Ot,gitmojiEnabled:_,onOpenGitmojiPicker:()=>Y(!0)})]}):s.jsx(fy,{onOpenStashes:()=>Ue(!0)})}):null,us==="branch"?s.jsx("div",{className:"space-y-4",children:tr?s.jsxs(s.Fragment,{children:[s.jsx(mv,{mode:"inline",currentBranch:y?.current,localBranches:kt,remoteBranches:Gt,defaultTargetBranch:Es,onMerge:fr,onRebase:yr,disabled:ri,isOperating:xe!==null,operationLogs:dt,onOperationComplete:go}),cn?s.jsx(dy,{repoRoot:cn.repoRoot,sourceBranch:cn.sourceBranch,worktreeMetadata:cn.worktreeMetadata,localBranches:kt,defaultTargetBranch:hs,refreshKey:Pt,onRefresh:()=>{r&&(ee(r,n),ie(r,n),X(r,n,tt))}},cn.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,us==="pr"?s.jsx("div",{className:"space-y-4",children:gn?s.jsx(nv,{directory:gn.directory,branch:gn.branch,baseBranch:fs,trackingBranch:y?.tracking??void 0,remotes:js,remoteBranches:Gt,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:Xt!==null,onOpenChange:Q=>{Q||Vt(null)},children:s.jsxs(Vs,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(sn,{children:[s.jsx(Hs,{children:e(Xt==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(mn,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(vy,{mode:Xt==="graph"?"graph":"history",log:Xt==="graph"?Os??E:E,isLogLoading:Xt==="graph"&&Gs||W,logMaxCount:Xt==="graph"?Bn:tt,onLogMaxCountChange:Xt==="graph"?Gr:dn,expandedCommitHashes:as,onToggleCommit:Is,commitFilesMap:Ft,loadingCommitHashes:Ht,onCopyHash:Ks,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:Xt==="graph"?null:st,onConflict:Xt==="graph"?_i:void 0,onActionSuccess:Xt==="graph"?Vi:void 0})})]})}),s.jsx(uy,{open:ce,onOpenChange:Ue,directory:r,hasUncommittedChanges:(y?.files?.length??0)>0,hasStagedChanges:bn.length>0,uncommittedFileCount:y?.files?.length??0,onChanged:async Q=>{r&&Q?.affectsIndex&&ne(r),await ws(!1),await Ls()}}),s.jsx(_s,{open:Ne,onOpenChange:Y,children:s.jsxs(Vs,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(sn,{className:"px-4 pt-4",children:s.jsx(Hs,{children:e("gitView.gitmoji.title")})}),s.jsxs(Ha,{className:"h-[420px]",children:[s.jsx(Ga,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:ss,onValueChange:cs}),s.jsxs(Ka,{children:[s.jsx(qa,{children:e("gitView.gitmoji.empty")}),s.jsx(Qr,{children:(de.length===0?[]:de.filter(Q=>{const ke=ss.trim().toLowerCase();return ke?Q.emoji.includes(ke)||Q.code.toLowerCase().includes(ke)||Q.description.toLowerCase().includes(ke):!0})).map(Q=>s.jsxs(Jr,{onSelect:()=>Rn(Q.emoji,Q.code),children:[s.jsx("span",{className:"text-lg",children:Q.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Q.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:Q.description})]},Q.code))})]})]})]})}),r&&s.jsx(rv,{open:zt,onOpenChange:gt,conflictFiles:xs,directory:r,operation:Ss,onAbort:yn,onClearState:nn}),s.jsx(uv,{open:Ge,onOpenChange:ps,operation:ks,targetBranch:Rs,onConfirm:Bi})]}):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")})})},oc=5e3,Dv=(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},Tl=(t,e)=>yg(vg.getState().dictionary,t,e),Tv=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"},Pv=async(t,e)=>{if(t.readFile)return(await t.readFile(e,{optional:!0})).content??"";const n=new URLSearchParams({path:e,optional:"true"}),r=await Ps(`/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()},Yc=async(t,e)=>{try{const n=await Pv(t,e);return Dv(n,oc)>oc?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:Tv(n)}}},Qc=t=>{if(t==="too-large"){const e=oc.toLocaleString(so());return Tl("contextFileOpen.failure.tooLarge",{count:e})}return Tl(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},Iv=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),An=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=An(e),r=An(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},Rv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Ev=new Set(["node_modules"]),Mv=t=>Ev.has(t),Fv=t=>{const e=An(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},Ov=8,Fr=new Map,Lv=t=>{const e=Fr.get(t);return e?(e.touchedAt=Date.now(),Fr.delete(t),Fr.set(t,e),e):null},Pl=t=>{const e=Fr.get(t);if(e)return e.touchedAt=Date.now(),e;if(Fr.size>=Ov){const r=Fr.keys().next().value;r!==void 0&&Fr.delete(r)}const n={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Fr.set(t,n),n},Bv=t=>{Fr.delete(t)},eh=(t,e)=>s.jsx(ei,{filePath:t,extension:e}),Vv=t=>{const e=ht.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},_v=t=>{const e=ht.c(73),{node:n,root:r,isExpanded:o,isActive:a,status:c,badge:l,permissions:d,downloadFile:f,onSelect:m,onToggle:u,onRevealPath:p,onOpenDialog:x}=t,{t:b}=yt(),w=n.type==="directory",{canRename:g,canCreateFile:h,canCreateFolder:C,canDelete:j,canReveal:S}=d,[N,k]=i.useState(!1),[y,D]=i.useState(!1);let V;e[0]!==h||e[1]!==C||e[2]!==j||e[3]!==g||e[4]!==S?(V=Me=>{!g&&!h&&!C&&!j&&!S||(Me?.preventDefault(),D(!0))},e[0]=h,e[1]=C,e[2]=j,e[3]=g,e[4]=S,e[5]=V):V=e[5];const v=V;let O;e[6]!==w||e[7]!==n||e[8]!==m||e[9]!==u?(O=()=>{w?u(n.path):m(n)},e[6]=w,e[7]=n,e[8]=m,e[9]=u,e[10]=O):O=e[10];const P=O;let E;e[11]===Symbol.for("react.memo_cache_sentinel")?(E=Me=>{Me.stopPropagation(),D(!1),k(!0)},e[11]=E):E=e[11];const B=E;let T;e[12]!==h||e[13]!==C||e[14]!==j||e[15]!==g||e[16]!==S||e[17]!==f||e[18]!==w||e[19]!==n||e[20]!==x||e[21]!==p||e[22]!==b?(T=Me=>{const{Item:z,Separator:K}=Me;return s.jsxs(s.Fragment,{children:[g&&s.jsxs(z,{onClick:q=>{q.stopPropagation(),x("rename",n)},children:[s.jsx(A,{name:"edit",className:"mr-2 h-4 w-4"})," ",b("sidebarFilesTree.menu.rename")]}),s.jsxs(z,{onClick:q=>{q.stopPropagation(),xr(n.path).then(me=>{if(me.ok){ae.success(b("sidebarFilesTree.toast.pathCopied"));return}ae.error(b("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(A,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",b("sidebarFilesTree.menu.copyPath")]}),!w&&f&&s.jsxs(z,{onClick:q=>{q.stopPropagation(),f(n.path).catch(me=>{console.error("Download failed:",me),ae.error(b("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(A,{name:"download",className:"mr-2 h-4 w-4"})," ",b("sidebarFilesTree.menu.save")]}),S&&s.jsxs(z,{onClick:q=>{q.stopPropagation(),p(n.path)},children:[s.jsx(A,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",b(Rc())]}),w&&(h||C)&&s.jsxs(s.Fragment,{children:[s.jsx(K,{}),h&&s.jsxs(z,{onClick:q=>{q.stopPropagation(),x("createFile",n)},children:[s.jsx(A,{name:"file-add",className:"mr-2 h-4 w-4"})," ",b("sidebarFilesTree.menu.newFile")]}),C&&s.jsxs(z,{onClick:q=>{q.stopPropagation(),x("createFolder",n)},children:[s.jsx(A,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",b("sidebarFilesTree.menu.newFolder")]})]}),j&&s.jsxs(s.Fragment,{children:[s.jsx(K,{}),s.jsxs(z,{onClick:q=>{q.stopPropagation(),x("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",b("sidebarFilesTree.menu.delete")]})]})]})},e[12]=h,e[13]=C,e[14]=j,e[15]=g,e[16]=S,e[17]=f,e[18]=w,e[19]=n,e[20]=x,e[21]=p,e[22]=b,e[23]=T):T=e[23];const W=T;let U;e[24]!==n.path||e[25]!==r?(U=Me=>{const z=Zm(r,n.path);!z||z==="."||(Me.dataTransfer.setData("application/x-openchamber-file-path",z),Me.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=U):U=e[26];const L=U;let M;e[27]!==v?(M=s.jsx("div",{className:"group relative flex items-center",onContextMenu:v}),e[27]=v,e[28]=M):M=e[28];const ee=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let ie;e[29]!==ee?(ie=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",ee,"cursor-grab active:cursor-grabbing"),e[29]=ee,e[30]=ie):ie=e[30];let X;e[31]!==w||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(X=w?o?s.jsx(A,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(A,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):eh(n.path,n.extension),e[31]=w,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=X):X=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 te;e[39]!==w||e[40]!==c?(te=!w&&c&&s.jsx(Vv,{status:c}),e[39]=w,e[40]=c,e[41]=te):te=e[41];let re;e[42]!==l||e[43]!==w?(re=w&&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]=w,e[44]=re):re=e[44];let le;e[45]!==v||e[46]!==L||e[47]!==P||e[48]!==H||e[49]!==te||e[50]!==re||e[51]!==ie||e[52]!==X?(le=s.jsxs("button",{type:"button",onClick:P,onContextMenu:v,draggable:!0,onDragStart:L,className:ie,children:[X,H,te,re]}),e[45]=v,e[46]=L,e[47]=P,e[48]=H,e[49]=te,e[50]=re,e[51]=ie,e[52]=X,e[53]=le):le=e[53];let ve;e[54]!==h||e[55]!==C||e[56]!==j||e[57]!==g||e[58]!==S||e[59]!==N||e[60]!==W||e[61]!==b?(ve=(g||h||C||j||S)&&s.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:s.jsxs(tn,{open:N,onOpenChange:k,children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:B,title:b("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":b("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(A,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:b("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(en,{align:"end",side:"bottom",onCloseAutoFocus:()=>k(!1),children:W({Item:ms,Separator:Vr})})]})}),e[54]=h,e[55]=C,e[56]=j,e[57]=g,e[58]=S,e[59]=N,e[60]=W,e[61]=b,e[62]=ve):ve=e[62];let ne;e[63]!==le||e[64]!==ve||e[65]!==M?(ne=s.jsxs(zc,{render:M,children:[le,ve]}),e[63]=le,e[64]=ve,e[65]=M,e[66]=ne):ne=e[66];let we;e[67]!==W?(we=s.jsx(_c,{className:"min-w-[180px]",children:W({Item:$c,Separator:Mm})}),e[67]=W,e[68]=we):we=e[68];let he;return e[69]!==y||e[70]!==ne||e[71]!==we?(he=s.jsxs(Wc,{open:y,onOpenChange:D,children:[ne,we]}),e[69]=y,e[70]=ne,e[71]=we,e[72]=he):he=e[72],he},$v=(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,zv=i.memo(_v,$v),Wv=()=>{const{t}=yt(),{files:e}=Zn(),n=wi()??"",r=An(n.trim()),o=Xf(),a=Zf(),c=yc(I=>I.searchFiles),l=Re(I=>I.openContextFile),d=Ja(n),[f,m]=i.useState(""),u=Za(f,200),p=i.useRef(null),[x,b]=i.useState([]),[w,g]=i.useState(!1),[h,C]=i.useState({}),[j,S]=i.useState({}),N=i.useRef(new Set),k=i.useRef(new Set),y=i.useRef(null);i.useEffect(()=>{if(!r){C({}),S({}),N.current=new Set;return}const I=Lv(r);I?(C({...I.childrenByDir}),S({...I.loadErrorsByDir}),N.current=new Set(I.loadedDirs)):(C({}),S({}),N.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const I=Pl(r);I.childrenByDir=h},[r,h]),i.useEffect(()=>{if(!r)return;const I=Pl(r);I.loadErrorsByDir=j},[r,j]),i.useEffect(()=>{if(!r)return;const I=Pl(r);I.loadedDirs=new Set(N.current)},[r,h,j]),i.useEffect(()=>()=>{if(!r)return;const I=Fr.get(r);I&&I.loadedDirs.size===0&&Object.keys(I.childrenByDir).length===0&&Bv(r)},[r]);const D=i.useMemo(()=>[],[]),V=i.useMemo(()=>[],[]),v=fn(I=>r?I.byRoot[r]?.expandedPaths??D:D),O=fn(I=>r?I.byRoot[r]?.selectedPath??null:null),P=fn(I=>I.setSelectedPath),E=fn(I=>I.addOpenPath),B=fn(I=>I.removeOpenPathsByPrefix),T=fn(I=>I.toggleExpandedPath),W=Re(I=>r?I.contextPanelByDirectory[r]?.tabs??V:V),U=i.useMemo(()=>new Set(W.map(I=>I.mode==="file"?I.targetPath:null).filter(I=>typeof I=="string"&&I.length>0).map(I=>An(I))),[W]),[L,M]=i.useState(null),[ee,ie]=i.useState(null),[X,H]=i.useState(""),[te,re]=i.useState(!1),le=!!e.writeFile,ve=!!e.createDirectory,ne=!!e.rename,we=!!e.delete,he=!!e.revealPath,Me=i.useMemo(()=>({canRename:ne,canCreateFile:le,canCreateFolder:ve,canDelete:we,canReveal:he}),[ne,le,ve,we,he]),z=i.useCallback(I=>{e.revealPath&&e.revealPath(I).catch(()=>{ae.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),K=i.useCallback((I,_)=>{M(I),ie(_),H(I==="rename"&&_.name||""),re(!1)},[]),q=i.useCallback((I,_)=>{const be=_.filter(R=>R&&typeof R.name=="string"&&R.name.length>0).filter(R=>o||!R.name.startsWith(".")).filter(R=>a||!Mv(R.name)).map(R=>{const de=R.name,fe=An(R.path||""),$=fe?Rv(fe)?fe:An(`${I}/${fe}`):An(`${I}/${de}`),Ae=R.isDirectory?"directory":"file",Ve=Ae==="file"&&de.includes(".")?de.split(".").pop()?.toLowerCase():void 0;return{name:de,path:$,type:Ae,extension:Ve}});return Iv(be)},[a,o]),me=i.useCallback(async(I,_)=>{const be=An(I.trim());if(!be||N.current.has(be)||k.current.has(be))return;k.current=new Set(k.current),k.current.add(be);const R=e.listDirectory?e.listDirectory(be).then(de=>de.entries.map(fe=>({name:fe.name,path:fe.path,isDirectory:fe.isDirectory}))):Xn.listLocalDirectory(be).then(de=>de.map(fe=>({name:fe.name,path:fe.path,isDirectory:fe.isDirectory})));try{const de=await R;if(_?.())return;const fe=q(be,de);N.current=new Set(N.current),N.current.add(be),S($=>{if(!$[be])return $;const Ae={...$};return delete Ae[be],Ae}),C($=>({...$,[be]:fe}))}catch(de){if(_?.())return;const fe=de instanceof Error?de.message:String(de??"");console.error("Failed to load sidebar directory:",de),S($=>({...$,[be]:fe}))}finally{k.current=new Set(k.current),k.current.delete(be)}},[e,q]),Se=i.useCallback(async()=>{if(!r)return;y.current?.abort();const I=new AbortController;y.current=I;try{const be=(fn.getState().byRoot[r]?.expandedPaths??[]).map(fe=>An(fe)).filter(fe=>!!fe&&fe!==r&&fe.startsWith(`${r}/`)),R=[r,...be];N.current=new Set(N.current);for(const fe of R)N.current.delete(fe);S(fe=>{if(Object.keys(fe).length===0)return fe;const $={...fe};let Ae=!1;for(const Ve of R)Ve in $&&(delete $[Ve],Ae=!0);return Ae?$:fe});const de=()=>I.signal.aborted;await me(r,de);for(let fe=0;fe<be.length&&!I.signal.aborted;fe+=3){const $=be.slice(fe,fe+3);await Promise.all($.map(Ae=>me(Ae,de)))}}catch(_){if(I.signal.aborted)return;console.error("Failed to refresh sidebar tree:",_)}finally{y.current===I&&(y.current=null)}},[me,r]),Be=i.useCallback(async I=>{if(!I){await Se();return}const _=An(I);N.current=new Set(N.current),N.current.delete(_),k.current=new Set(k.current),k.current.delete(_),await me(_)},[me,Se]);i.useEffect(()=>{r&&(y.current?.abort(),N.current=new Set,k.current=new Set,S({}),C(I=>Object.keys(I).length===0?I:{}),me(r))},[me,r,o,a]),i.useEffect(()=>{if(!r||v.length===0)return;const I=v.map(R=>An(R)).filter(R=>!!R&&R!==r&&R.startsWith(`${r}/`)&&!N.current.has(R)&&!k.current.has(R)).sort((R,de)=>R.split("/").length-de.split("/").length);if(I.length===0)return;let _=!1;const be=()=>_;return(async()=>{for(let R=0;R<I.length&&!_;R+=3){const de=I.slice(R,R+3);await Promise.all(de.map(fe=>me(fe,be)))}})(),()=>{_=!0}},[v,me,r]),i.useEffect(()=>{if(!n){b([]),g(!1);return}const I=u.trim();if(!I){b([]),g(!1);return}let _=!1;return g(!0),c(n,I,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(be=>{if(_)return;const de=be.filter(fe=>a||!Fv(fe.path)).map(fe=>({name:fe.name,path:An(fe.path),type:"file",extension:fe.extension,relativePath:fe.relativePath}));b(de)}).catch(()=>{_||b([])}).finally(()=>{_||g(!1)}),()=>{_=!0}},[n,u,c,o,a]);const _e=i.useMemo(()=>{const I=new Map;if(!d?.files)return I;for(const _ of d.files)_.index==="A"||_.working_dir==="?"?I.set(_.path,"git-added"):_.index==="D"?I.set(_.path,"git-deleted"):(_.index==="M"||_.working_dir==="M")&&I.set(_.path,"git-modified");return I},[d]),Le=i.useMemo(()=>{const I=new Map;if(!d?.files||!r)return I;for(const _ of d.files){const be=_.index==="M"||_.working_dir==="M",R=_.index==="A"||_.working_dir==="?";if(!be&&!R)continue;const de=_.path.split("/");if(de.length<=1)continue;let fe=r;for(let $=0;$<de.length-1;$++){fe=`${fe}/${de[$]}`;let Ae=I.get(fe);Ae||(Ae={modified:0,added:0},I.set(fe,Ae)),be&&Ae.modified++,R&&Ae.added++}}return I},[d,r]),pe=i.useCallback(I=>{if(U.has(I))return"open";if(_e.size===0)return null;const _=I.startsWith(r+"/")?I.slice(r.length+1):I;return _e.get(_)??null},[U,_e,r]),Ee=i.useCallback(I=>{if(Le.size===0)return null;const _=Le.get(I);return _&&_.modified+_.added>0?_:null},[Le]),ge=i.useCallback(async I=>{if(!r)return;const _=await Yc(e,I.path);if(!_.ok){ae.error(Qc(_.reason));return}P(r,I.path),E(r,I.path),l(r,I.path)},[E,e,l,r,P]),oe=i.useCallback(async I=>{const _=An(I);r&&(T(r,_),N.current.has(_)||await me(_))},[me,r,T]),je=i.useCallback(async I=>{if(I?.preventDefault(),!ee||!L)return;re(!0);const _=()=>re(!1),be=()=>M(null);if(L==="createFile"){if(!X.trim()){ae.error(t("sidebarFilesTree.toast.filenameRequired")),_();return}if(!e.writeFile){ae.error(t("sidebarFilesTree.toast.writeNotSupported")),_();return}const R=ee.path,de=R?`${R}/`:"",fe=An(`${de}${X.trim()}`);await e.writeFile(fe,"").then(async $=>{$.success&&(ae.success(t("sidebarFilesTree.toast.fileCreated")),await Be(R)),be()}).catch(()=>ae.error(t("sidebarFilesTree.toast.operationFailed"))).finally(_);return}if(L==="createFolder"){if(!X.trim()){ae.error(t("sidebarFilesTree.toast.folderNameRequired")),_();return}const R=ee.path,de=R?`${R}/`:"",fe=An(`${de}${X.trim()}`);await e.createDirectory(fe).then(async $=>{$.success&&(ae.success(t("sidebarFilesTree.toast.folderCreated")),await Be(R)),be()}).catch(()=>ae.error(t("sidebarFilesTree.toast.operationFailed"))).finally(_);return}if(L==="rename"){if(!X.trim()){ae.error(t("sidebarFilesTree.toast.nameRequired")),_();return}if(!e.rename){ae.error(t("sidebarFilesTree.toast.renameNotSupported")),_();return}const R=ee.path,de=R.split("/").slice(0,-1).join("/"),fe=de?`${de}/`:"",$=An(`${fe}${X.trim()}`);await e.rename(R,$).then(async Ae=>{Ae.success&&(ae.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await Be(de),r&&B(r,R),(O===R||O&&O.startsWith(`${R}/`))&&P(r,null)),be()}).catch(()=>ae.error(t("sidebarFilesTree.toast.operationFailed"))).finally(_);return}if(L==="delete"){if(!e.delete){ae.error(t("sidebarFilesTree.toast.deleteNotSupported")),_();return}const R=ee.path,de=R.split("/").slice(0,-1).join("/");await e.delete(R).then(async fe=>{fe.success&&(ae.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await Be(de),r&&B(r,R),(O===R||O&&O.startsWith(R+"/"))&&P(r,null)),be()}).catch(()=>ae.error(t("sidebarFilesTree.toast.operationFailed"))).finally(_);return}_()},[L,ee,X,e,Be,B,r,O,P,t]);function ye(I,_){const be=h[I]??[];return be.map((R,de)=>{const fe=R.type==="directory",$=fe&&v.includes(R.path),Ae=O===R.path,Ve=de===be.length-1;return s.jsxs("li",{className:"relative",children:[_>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ve&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),s.jsx(zv,{node:R,root:r,isExpanded:$,isActive:Ae,status:fe?void 0:pe(R.path),badge:fe?Ee(R.path):void 0,permissions:Me,downloadFile:e.downloadFile,onSelect:ge,onToggle:oe,onRevealPath:z,onOpenDialog:K}),fe&&$&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[j[R.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:j[R.path],children:j[R.path]}),s.jsxs(ze,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Be(R.path)},children:[s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,ye(R.path,_+1)]})]},R.path)})}const ue=!!(r&&h[r]),De=r?j[r]:null;return s.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(A,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(Ln,{ref:p,value:f,onChange:I=>m(I.target.value),placeholder:t("sidebarFilesTree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),f.trim().length>0?s.jsx("button",{type:"button","aria-label":t("sidebarFilesTree.search.clearAria"),className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{m(""),p.current?.focus()},children:s.jsx(A,{name:"close",className:"h-4 w-4"})}):null]}),le&&s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>K("createFile",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFileTitle"),"aria-label":t("sidebarFilesTree.actions.newFileTitle"),children:s.jsx(A,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),ve&&s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>K("createFolder",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFolderTitle"),"aria-label":t("sidebarFilesTree.actions.newFolderTitle"),children:s.jsx(A,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{Se()},className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.refreshTitle"),"aria-label":t("sidebarFilesTree.actions.refreshTitle"),children:s.jsx(A,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx(On,{outerClassName:"flex-1 min-h-0",className:"p-2",children:s.jsx("ul",{className:"flex flex-col",children:w?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):x.length>0?x.map(I=>{const _=O===I.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>ge(I),draggable:!0,onDragStart:be=>{const R=I.relativePath||Zm(r??"",I.path);!R||R==="."||(be.dataTransfer.setData("application/x-openchamber-file-path",R),be.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",_?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:I.path,children:[eh(I.path,I.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:I.relativePath??I.path})]})},I.path)}):De?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{children:De}),s.jsxs(ze,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{Se()},children:[s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):ue&&r?ye(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx(_s,{open:!!L,onOpenChange:I=>!I&&M(null),children:s.jsxs(Vs,{children:[s.jsxs(sn,{children:[s.jsxs(Hs,{children:[L==="createFile"&&t("sidebarFilesTree.dialog.createFile.title"),L==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.title"),L==="rename"&&t("sidebarFilesTree.dialog.rename.title"),L==="delete"&&t("sidebarFilesTree.dialog.delete.title")]}),s.jsxs(mn,{children:[L==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:ee?.path??t("sidebarFilesTree.dialog.rootFallback")}),L==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:ee?.path??t("sidebarFilesTree.dialog.rootFallback")}),L==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:ee?.name??""}),L==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:ee?.name??""})]})]}),L!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(Ln,{value:X,onChange:I=>H(I.target.value),placeholder:t(L==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:I=>{I.key==="Enter"&&je()},autoFocus:!0})}),s.jsxs(br,{children:[s.jsx(ze,{variant:"outline",onClick:()=>M(null),disabled:te,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx(ze,{variant:L==="delete"?"destructive":"default",onClick:()=>{je()},disabled:te||L!=="delete"&&!X.trim(),children:te?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):t(L==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},Uv=t=>t==="git"||t==="files"||t==="context",Hv="files",Gv=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function Kv(t,e,n,r){const o=ht.c(6),{git:a}=Zn(),c=vn(qv),l=!!(t&&a&&e&&n==="git"&&r!=="git");let d,f;o[0]!==t||o[1]!==c||o[2]!==a||o[3]!==l?(d=()=>{if(!l||!t||!a)return;c(t,a);const m=window.setInterval(()=>{Gv()&&c(t,a)},1e4);return()=>window.clearInterval(m)},f=[l,t,a,c],o[0]=t,o[1]=c,o[2]=a,o[3]=l,o[4]=d,o[5]=f):(d=o[4],f=o[5]),i.useEffect(d,f)}function qv(t){return t.ensureStatus}const th=()=>{const t=ht.c(17),e=Ds(Qv),n=Ds(Jv),r=Xs(Xv),o=vn(Zv);let a;e:{if(e){let b;t[0]!==e||t[1]!==n?(b=n.find(w=>w.id===e)??n[0]??null,t[0]=e,t[1]=n,t[2]=b):b=t[2],a=b;break e}a=n[0]??null}const c=a;let l;e:{if(!c){l=null;break e}let b;t[3]!==c.id||t[4]!==c.path?(b={id:c.id,path:c.path},t[3]=c.id,t[4]=c.path,t[5]=b):b=t[5],l=b}const d=l;let f;e:{if(!c){f=null;break e}let b;t[6]!==c.label||t[7]!==c.path||t[8]!==r?(b=c.label?.trim()||fo(c.path,r)||c.path,t[6]=c.label,t[7]=c.path,t[8]=r,t[9]=b):b=t[9],f=b}const m=f;let u;e:{if(!c){u=!1;break e}let b;t[10]!==c.path||t[11]!==o?(b=o.get(c.path)?.isGitRepo,t[10]=c.path,t[11]=o,t[12]=b):b=t[12],u=b===!0}const p=u;let x;return t[13]!==p||t[14]!==m||t[15]!==d?(x=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(Ww,{projectRef:d,projectLabel:m,canCreateWorktree:p})}),t[13]=p,t[14]=m,t[15]=d,t[16]=x):x=t[16],x},Yv=()=>{const t=ht.c(57),{t:e}=yt(),n=Re(e1),r=Re(t1),o=Re(s1),a=Re(n1),c=wi();Kv(c,o,n,a);const l=a==="git"?"git":a==="context"?"context":null;let d,f;t[0]!==l||t[1]!==n||t[2]!==r?(d=()=>{l&&n===l&&r(Hv)},f=[l,n,r],t[0]=l,t[1]=n,t[2]=r,t[3]=d,t[4]=f):(d=t[3],f=t[4]),i.useEffect(d,f);let m;t[5]!==e?(m=e("layout.rightSidebar.git"),t[5]=e,t[6]=m):m=t[6];let u;t[7]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(A,{name:"git-branch",className:"h-3.5 w-3.5"}),t[7]=u):u=t[7];let p;t[8]!==m?(p={id:"git",label:m,icon:u},t[8]=m,t[9]=p):p=t[9];let x;t[10]!==e?(x=e("layout.rightSidebar.files"),t[10]=e,t[11]=x):x=t[11];let b;t[12]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx(A,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=b):b=t[12];let w;t[13]!==x?(w={id:"files",label:x,icon:b},t[13]=x,t[14]=w):w=t[14];let g;t[15]!==e?(g=e("layout.rightSidebar.context"),t[15]=e,t[16]=g):g=t[16];let h;t[17]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(A,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=h):h=t[17];let C;t[18]!==g?(C={id:"context",label:g,icon:h},t[18]=g,t[19]=C):C=t[19];let j;t[20]!==C||t[21]!==p||t[22]!==w?(j=[p,w,C],t[20]=C,t[21]=p,t[22]=w,t[23]=j):j=t[23];const S=j;let N;t[24]!==l||t[25]!==S?(N=l?S.filter(re=>re.id!==l):S,t[24]=l,t[25]=S,t[26]=N):N=t[26];const k=N,y=o&&n==="git"&&l!=="git";let D;t[27]!==r?(D=re=>{Uv(re)&&r(re)},t[27]=r,t[28]=D):D=t[28];const V=D;let v;t[29]!==V||t[30]!==n||t[31]!==k?(v=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(Bo,{items:k,activeId:n,onSelect:V,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=V,t[30]=n,t[31]=k,t[32]=v):v=t[32];const O=n!=="git"&&"hidden";let P;t[33]!==O?(P=Pe("h-full",O),t[33]=O,t[34]=P):P=t[34];let E;t[35]!==y?(E=s.jsx(ic,{isActive:y}),t[35]=y,t[36]=E):E=t[36];let B;t[37]!==P||t[38]!==E?(B=s.jsx("div",{className:P,children:E}),t[37]=P,t[38]=E,t[39]=B):B=t[39];const T=n!=="files"&&"hidden";let W;t[40]!==T?(W=Pe("h-full",T),t[40]=T,t[41]=W):W=t[41];let U;t[42]===Symbol.for("react.memo_cache_sentinel")?(U=s.jsx(Wv,{}),t[42]=U):U=t[42];let L;t[43]!==W?(L=s.jsx("div",{className:W,children:U}),t[43]=W,t[44]=L):L=t[44];const M=n!=="context"&&"hidden";let ee;t[45]!==M?(ee=Pe("h-full",M),t[45]=M,t[46]=ee):ee=t[46];let ie;t[47]===Symbol.for("react.memo_cache_sentinel")?(ie=s.jsx(th,{}),t[47]=ie):ie=t[47];let X;t[48]!==ee?(X=s.jsx("div",{className:ee,children:ie}),t[48]=ee,t[49]=X):X=t[49];let H;t[50]!==B||t[51]!==L||t[52]!==X?(H=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[B,L,X]}),t[50]=B,t[51]=L,t[52]=X,t[53]=H):H=t[53];let te;return t[54]!==v||t[55]!==H?(te=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[v,H]}),t[54]=v,t[55]=H,t[56]=te):te=t[56],te};function Qv(t){return t.activeProjectId}function Jv(t){return t.projects}function Xv(t){return t.homeDirectory}function Zv(t){return t.directories}function e1(t){return t.rightSidebarTab}function t1(t){return t.setRightSidebarTab}function s1(t){return t.isRightSidebarOpen}function n1(t){return t.activeMainTab}const r1=64,i1=3,Ni=new Map,o1=(t,e,n=i1)=>{const r=`${t}\0${n}\0${e}`,o=Ni.get(r);if(o)return Ni.delete(r),Ni.set(r,o),o;const a=l1(e),c=a?qh(Yh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??_u(t):Qh(a1(t,e))[0]?.files[0]??_u(t);for(Ni.set(r,c);Ni.size>r1;){const l=Ni.keys().next().value;if(!l)break;Ni.delete(l)}return c},a1=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
14
+ ===================================================================
15
+ --- ${t}
16
+ +++ ${t}
17
+ ${e}`,l1=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(t))return;const e=[...t.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(e.length!==1)return;const n=e[0],r=Number.parseInt(n[1]??"",10),o=Number.parseInt(n[2]??"",10);if(r>1||o>1||!Number.isFinite(r)||!Number.isFinite(o))return;const a=(n.index??0)+n[0].length,c=t.slice(a),l=[],d=[];let f;for(const m of c.split(/\r?\n/)){if(m.startsWith("diff --git ")||m.startsWith("@@ "))break;if(m.startsWith("\\")){if(f==="-"||f===" "){const u=l.at(-1);u&&(u.newline=!1)}if(f==="+"||f===" "){const u=d.at(-1);u&&(u.newline=!1)}continue}if(m.startsWith("-")){l.push({text:m.slice(1),newline:!0}),f="-";continue}if(m.startsWith("+")){d.push({text:m.slice(1),newline:!0}),f="+";continue}m.startsWith(" ")&&(l.push({text:m.slice(1),newline:!0}),d.push({text:m.slice(1),newline:!0}),f=" ")}return{before:Vu(l),after:Vu(d)}},Vu=t=>t.map(e=>e.text+(e.newline?`
18
+ `:"")).join(""),_u=t=>Jh({name:t,contents:""},{name:t,contents:""}),$u=t=>{if(!t)return null;const e=t.split(`
19
+ `);let n=null;for(const r of e){const o=r.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(o){const a=Number.parseInt(o[1]??"",10);n=Number.isFinite(a)&&a>=1?a:null;continue}if(n!==null){if(r.startsWith(" ")){n+=1;continue}if(r.startsWith("+"))return n;if(r.startsWith("-"))return Math.max(1,n)}}return null},c1=1100,d1=15e3,zu=500,Wu=300,u1=1e6,f1=3,m1=t=>t<=6?t:t<=12?6:t<=25?4:2,h1=i.memo(()=>{const t=ht.c(4),{t:e}=yt();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}),sh={"?":{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"}},p1=sh.M,g1=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"},nh=t=>{const e=g1(t);return sh[e]??p1},x1=t=>{const{index:e,working_dir:n}=t;return e==="A"||n==="A"||e==="?"||n==="?"},Uu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Hu=t=>!!t.working_dir?.trim()||t.index==="?",b1=(t,e)=>kg(t,e),Gu=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Ku=(t,e)=>{const n=t.split(`
20
+ `),r=e.split(`
21
+ `),o=Math.min(n.length,r.length);for(let a=0;a<o;a+=1)if(n[a]!==r[a])return a+1;return r.length>n.length?n.length+1:n.length>r.length?Math.max(1,r.length):1},w1=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),y1=t=>Array.isArray(t)?t.filter(e=>!e||typeof e!="object"?!1:typeof e.file=="string"):[],v1=t=>t==="added"?"A":t==="deleted"?"D":"M",rh=(t,e,n)=>w1(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:o1(t,e),contextMode:n},ih=(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]})},j1=i.memo(t=>{const e=ht.c(53),{scope:n,workingCount:r,stagedCount:o,turnCount:a,onScopeChange:c}=t,{t:l}=yt(),[d,f]=i.useState(!1),m=n==="staged"?o:n==="turn"?a:r;let u;e[0]!==n||e[1]!==l?(u=l(n==="staged"?"diffView.scope.staged":n==="turn"?"diffView.scope.lastTurn":"diffView.scope.changed"),e[0]=n,e[1]=l,e[2]=u):u=e[2];const p=u;let x;e[3]!==l?(x=l("diffView.scope.selectorAria"),e[3]=l,e[4]=x):x=e[4];let b;e[5]!==m?(b=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",m]}),e[5]=m,e[6]=b):b=e[6];let w;e[7]!==p||e[8]!==b?(w=s.jsxs("span",{className:"whitespace-nowrap",children:[p,b]}),e[7]=p,e[8]=b,e[9]=w):w=e[9];let g;e[10]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(A,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=g):g=e[10];let h;e[11]!==x||e[12]!==w?(h=s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":x,children:[w,g]})}),e[11]=x,e[12]=w,e[13]=h):h=e[13];let C;e[14]!==c?(C=U=>{(U==="working"||U==="staged"||U==="turn")&&(c?.(U),f(!1))},e[14]=c,e[15]=C):C=e[15];let j;e[16]!==l?(j=l("diffView.scope.changed"),e[16]=l,e[17]=j):j=e[17];let S;e[18]!==j?(S=s.jsx("span",{children:j}),e[18]=j,e[19]=S):S=e[19];let N;e[20]!==r?(N=s.jsx("span",{className:"typography-meta text-muted-foreground",children:r}),e[20]=r,e[21]=N):N=e[21];let k;e[22]!==N||e[23]!==S?(k=s.jsx(ul,{value:"working",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[S,N]})}),e[22]=N,e[23]=S,e[24]=k):k=e[24];let y;e[25]!==l?(y=l("diffView.scope.staged"),e[25]=l,e[26]=y):y=e[26];let D;e[27]!==y?(D=s.jsx("span",{children:y}),e[27]=y,e[28]=D):D=e[28];let V;e[29]!==o?(V=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=V):V=e[30];let v;e[31]!==D||e[32]!==V?(v=s.jsx(ul,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[D,V]})}),e[31]=D,e[32]=V,e[33]=v):v=e[33];let O;e[34]!==l?(O=l("diffView.scope.lastTurn"),e[34]=l,e[35]=O):O=e[35];let P;e[36]!==O?(P=s.jsx("span",{children:O}),e[36]=O,e[37]=P):P=e[37];let E;e[38]!==a?(E=s.jsx("span",{className:"typography-meta text-muted-foreground",children:a}),e[38]=a,e[39]=E):E=e[39];let B;e[40]!==P||e[41]!==E?(B=s.jsx(ul,{value:"turn",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[P,E]})}),e[40]=P,e[41]=E,e[42]=B):B=e[42];let T;e[43]!==n||e[44]!==k||e[45]!==v||e[46]!==B||e[47]!==C?(T=s.jsx(en,{align:"start",className:"w-40",children:s.jsxs(Cg,{value:n,onValueChange:C,children:[k,v,B]})}),e[43]=n,e[44]=k,e[45]=v,e[46]=B,e[47]=C,e[48]=T):T=e[48];let W;return e[49]!==d||e[50]!==T||e[51]!==h?(W=s.jsxs(tn,{open:d,onOpenChange:f,children:[h,T]}),e[49]=d,e[50]=T,e[51]=h,e[52]=W):W=e[52],W}),S1=i.memo(t=>{const e=ht.c(11),{changedFiles:n,selectedFile:r,onSelectFile:o}=t,{t:a}=yt();if(n.length===0)return null;let c;if(e[0]!==n||e[1]!==o||e[2]!==r||e[3]!==a){let d;e[5]!==o||e[6]!==r||e[7]!==a?(d=f=>{const m=nh(f),u=r===f.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(f.path),className:Pe("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",u?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[s.jsx(ei,{filePath:f.path,className:"h-3.5 w-3.5 flex-shrink-0"}),s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:m.color},title:a(m.descriptionKey),"aria-label":a(m.descriptionKey),children:m.code}),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:f.path,children:f.path}),ih(f.insertions,f.deletions)]})},f.path)},e[5]=o,e[6]=r,e[7]=a,e[8]=d):d=e[8],c=n.map(d),e[0]=n,e[1]=o,e[2]=r,e[3]=a,e[4]=c}else c=e[4];let l;return e[9]!==c?(l=s.jsx(On,{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}),N1=i.memo(t=>{const e=ht.c(20),{filePath:n,diff:r,renderSideBySide:o}=t,{t:a}=yt(),c=r.original.length>0,l=r.modified.length>0,d=o?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",f=o?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m={contain:"layout"},e[0]=m):m=e[0];let u;e[1]!==r.original||e[2]!==n||e[3]!==c||e[4]!==f||e[5]!==o||e[6]!==a?(u=c&&s.jsxs("div",{className:f,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a("diffView.image.original")}),s.jsx("img",{src:r.original,alt:a("diffView.image.originalAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[1]=r.original,e[2]=n,e[3]=c,e[4]=f,e[5]=o,e[6]=a,e[7]=u):u=e[7];let p;e[8]!==r.modified||e[9]!==n||e[10]!==l||e[11]!==c||e[12]!==f||e[13]!==o||e[14]!==a?(p=l&&s.jsxs("div",{className:f,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a(c?"diffView.image.modified":"diffView.image.new")}),s.jsx("img",{src:r.modified,alt:a("diffView.image.modifiedAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[8]=r.modified,e[9]=n,e[10]=l,e[11]=c,e[12]=f,e[13]=o,e[14]=a,e[15]=p):p=e[15];let x;return e[16]!==d||e[17]!==u||e[18]!==p?(x=s.jsx("div",{className:"w-full overflow-auto p-4",style:m,children:s.jsxs("div",{className:d,children:[u,p]})}),e[16]=d,e[17]=u,e[18]=p,e[19]=x):x=e[19],x}),k1=i.memo(t=>{const e=ht.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=Ri(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(h1,{}),e[2]=m):m=e[2],m}if(Ei(n)){let m;return e[3]!==r||e[4]!==n||e[5]!==o?(m=s.jsx(N1,{filePath:n,diff:r,renderSideBySide:o}),e[3]=r,e[4]=n,e[5]=o,e[6]=m):m=e[6],m}let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={contain:"layout"},e[7]=d):d=e[7];let f;return e[8]!==r.fileDiff||e[9]!==r.modified||e[10]!==r.original||e[11]!==n||e[12]!==l||e[13]!==o||e[14]!==a?(f=s.jsx("div",{className:"w-full",style:d,children:s.jsx(Em,{original:r.original,modified:r.modified,fileDiff:r.fileDiff,language:l,fileName:n,renderSideBySide:o,wrapLines:a,layout:"inline"})}),e[8]=r.fileDiff,e[9]=r.modified,e[10]=r.original,e[11]=n,e[12]=l,e[13]=o,e[14]=a,e[15]=f):f=e[15],f}),C1=i.memo(t=>{const e=ht.c(7),{filePath:n,staged:r,busyAction:o,disabled:a,onAction:c}=t,{t:l}=yt();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(Il,{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(Il,{label:l("gitView.changes.revertFileAria",{path:n}),icon:"arrow-go-back",loading:o==="discard",disabled:a,tone:"failure",onClick:()=>c("discard")}),s.jsx(Il,{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}),Il=t=>{const e=ht.c(14),{label:n,icon:r,loading:o,disabled:a,tone:c,onClick:l}=t,d=c==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",f=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let m;e[0]!==d||e[1]!==f?(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,f),e[0]=d,e[1]=f,e[2]=m):m=e[2];let u;e[3]!==l?(u=b=>{b.stopPropagation(),l()},e[3]=l,e[4]=u):u=e[4];let p;e[5]!==r||e[6]!==o?(p=o?s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(A,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=p):p=e[7];let x;return e[8]!==a||e[9]!==n||e[10]!==m||e[11]!==u||e[12]!==p?(x=s.jsx(ze,{variant:"ghost",size:"sm",className:m,disabled:a,title:n,"aria-label":n,onClick:u,children:p}),e[8]=a,e[9]=n,e[10]=m,e[11]=u,e[12]=p,e[13]=x):x=e[13],x},A1=i.memo(({directory:t,file:e,layout:n,wrapLines:r,isSelected:o,isExpanded:a,isMounted:c,onSelect:l,onExpandedChange:d,registerSectionRef:f,showOpenInEditorAction:m=!1,isOpeningInEditor:u=!1,onOpenInEditor:p,staged:x=!1,loadFullFiles:b=!1,initialDiffData:w=null})=>{const{t:g}=yt(),{git:h}=Zn(),C=vn(i.useCallback(K=>K.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),j=vn(K=>K.setDiff),S=vn(K=>K.fetchStatus),N=Re(K=>K.setDiffFileLayout),[k,y]=i.useState(0),[D,V]=i.useState(null),[v,O]=i.useState(!1),[P,E]=i.useState(null),[B,T]=i.useState(!1),[W,U]=i.useState(null),[L,M]=i.useState(null),ee=i.useRef(null),ie=i.useRef(null),X=i.useMemo(()=>nh(e),[e]),H=n==="side-by-side",te=b?"full":"patch",re=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,le=i.useMemo(()=>w||(x?L:W||(C?{original:C.original,modified:C.modified,isBinary:C.isBinary,contextMode:"full"}:null)),[C,w,W,x,L]),ve=le?.contextMode===te,ne=i.useCallback(K=>{ie.current=K,f(e.path,K)},[e.path,f]),we=i.useCallback(K=>{d(e.path,K)},[e.path,d]),he=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{x?M(null):U(null),V(null),ee.current=null},[re,x]),i.useEffect(()=>{if(!a||!c)return;if(!t||w||le&&ve){ee.current=null,O(!1);return}const K=`${t}::${e.path}::${x?"staged":"unstaged"}::${re}::${te}::${k}`;if(ee.current===K)return;ee.current=K,V(null),O(!0);let q=!1;const me=b?u1:f1,Se=Ei(e.path)?h.getGitFileDiff(t,{path:e.path,staged:x}):h.getGitDiff(t,{path:e.path,staged:x,contextLines:me}),Be=d1,_e=new Promise((Le,pe)=>{setTimeout(()=>pe(new Error(`Timed out after ${Be}ms`)),Be)});return Promise.race([Se,_e]).then(Le=>{if(!q){if("diff"in Le){const pe=rh(e.path,Le.diff,te);x?M(pe):U(pe)}else{const pe={original:Le.original??"",modified:Le.modified??"",isBinary:Le.isBinary,contextMode:"full"};x?M(pe):j(t,e.path,pe)}O(!1)}}).catch(Le=>{if(q)return;const pe=Le instanceof Error?Le.message:String(Le);V(pe),O(!1)}),()=>{q=!0,ee.current===K&&(ee.current=null)}},[te,le,ve,k,t,e.path,re,h,w,a,c,b,j,x]);const Me=i.useCallback(()=>{we(!a),he()},[we,he,a]),z=i.useCallback(async K=>{if(!(!t||P!==null)){E(K);try{K==="stage"?await h.stageGitFile(t,e.path):K==="unstage"?await h.unstageGitFile(t,e.path):await h.revertGitFile(t,e.path,{scope:"working"}),y(q=>q+1),await S(t,h)}catch(q){const me=K==="unstage"?"gitView.toast.unstageFileFailed":K==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";ae.error(q instanceof Error?q.message:g(me))}finally{E(q=>q===K?null:q)}}},[t,S,e.path,P,h,g]);return s.jsxs("div",{ref:ne,className:"scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0",children:[s.jsx("div",{className:"sticky top-0 z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80",children:s.jsxs("div",{role:"button",tabIndex:0,onClick:Me,onKeyDown:K=>{K.target===K.currentTarget&&(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),Me())},className: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(A,{name:"arrow-down-s",className:"size-4"}):s.jsx(A,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:X.color},title:g(X.descriptionKey),"aria-label":g(X.descriptionKey),children:X.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(ei,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const K=e.path.lastIndexOf("/");if(K===-1)return s.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:e.path});const q=e.path.slice(0,K),me=e.path.slice(K+1);return s.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:q}),s.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[s.jsx("span",{className:"text-muted-foreground",children:"/"}),s.jsx("span",{className:"text-foreground",children:me})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[ih(e.insertions,e.deletions),m&&p?s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:g("diffView.actions.openFileInEditorAtChange"),onClick:K=>{K.stopPropagation(),p(e.path,le)},disabled:u,children:u?s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(A,{name:"edit",className:"size-3.5"})}):null,s.jsx(fm,{mode:H?"side-by-side":"unified",onModeChange:K=>{const q=K==="side-by-side"?"side-by-side":"inline";N(e.path,q)},className:"opacity-70"})]})]})}),a&&s.jsxs("div",{className:"relative bg-background overflow-hidden",children:[!c&&!D?s.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,D?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:g("diffView.state.failedToLoadDiff")}),s.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:D}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>y(K=>K+1),children:g("diffView.actions.retry")})]}):null,c&&v&&!le&&!D?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),g("diffView.state.loadingDiff")]}):null,c&&le&&!B&&e.insertions+e.deletions>zu?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:g("diffView.state.largeDiff",{count:e.insertions+e.deletions})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:g("diffView.state.largeDiffDescription")}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>T(!0),children:g("diffView.actions.renderAnyway")})]}):null,c&&le&&(B||e.insertions+e.deletions<=zu)?s.jsxs(s.Fragment,{children:[s.jsx(k1,{filePath:e.path,diff:le,renderSideBySide:H,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(C1,{filePath:e.path,staged:x,busyAction:P,disabled:P!==null,onAction:z})})})]}):null]})]})}),oh=({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}=yt(),{git:f,files:m}=Zn(),u=wi(),{screenWidth:p,isMobile:x}=$r(),b=Pc(u??null),w=Ja(u??null),g=Ic(u??null),h=vn(Ce=>Ce.setActiveDirectory),C=vn(Ce=>Ce.ensureStatus),j=vn(Ce=>Ce.fetchStatus),S=vn(Ce=>Ce.setDiff),[N,k]=i.useState(null),[y,D]=i.useState(!1),[V,v]=i.useState(null),[O,P]=i.useState(()=>new Set),[E,B]=i.useState(()=>new Set),[T,W]=i.useState(!1),[U,L]=i.useState(0),[M,ee]=i.useState(!1),[ie,X]=i.useState(!1),[H,te]=i.useState(o);i.useEffect(()=>{te(o)},[o]);const re=Re(Ce=>Ce.pendingDiffFile),le=Re(Ce=>Ce.pendingDiffStaged),ve=Re(Ce=>Ce.pendingDiffScope),ne=Re(Ce=>Ce.setPendingDiffFile),we=Re(Ce=>Ce.diffLayoutPreference),he=Re(Ce=>Ce.diffFileLayout),Me=Re(Ce=>Ce.setDiffFileLayout),z=Re(Ce=>Ce.diffWrapLines),K=Re(Ce=>Ce.setDiffWrapLines),q=Re(Ce=>Ce.openContextFileAtLine),me=mt(Ce=>Ce.currentSessionId),Se=jg(me??"",u??void 0),Be=z,_e=H==="staged"?!0:H==="working"?!1:null,Le=_e??y,pe=x||p<=768,Ee=!!me&&H!=="turn"&&!pe&&!_r(),ge=!t&&!pe&&p>=1024,oe=i.useRef(null),je=i.useRef(new Map),ye=i.useRef(null),ue=i.useRef(null),De=i.useRef(!1),I=i.useRef(null),_=i.useRef(null),be=i.useCallback(()=>{ye.current=null,De.current=!1,v(null),ue.current!==null&&(window.cancelAnimationFrame(ue.current),ue.current=null)},[]),R=i.useCallback(Ce=>{P(Qe=>{if(Qe.has(Ce))return Qe;const ot=new Set(Qe);return ot.add(Ce),ot})},[]),de=i.useMemo(()=>{for(let Ce=Se.length-1;Ce>=0;Ce-=1){const Qe=Se[Ce];if(Qe.role==="user")return y1(Qe.summary?.diffs)}return[]},[Se]),fe=i.useMemo(()=>{const Ce=new Map;for(const Qe of de)if(Qe.file){if(typeof Qe.patch=="string"){Ce.set(Qe.file,rh(Qe.file,Qe.patch,"patch"));continue}Ce.set(Qe.file,{original:Qe.before??"",modified:Qe.after??"",contextMode:"full"})}return Ce},[de]),$=i.useMemo(()=>{if(H==="turn")return de.map(ot=>({path:ot.file??"",index:"",working_dir:v1(ot.status),insertions:ot.additions??0,deletions:ot.deletions??0,isNew:ot.status==="added"})).filter(ot=>ot.path).sort((ot,bt)=>ot.path.localeCompare(bt.path));if(!w?.files)return[];const Ce=w.diffStats??{},Qe=H==="staged"?Uu:H==="working"?Hu:()=>!0;return w.files.filter(Qe).map(ot=>({...ot,insertions:Ce[ot.path]?.insertions??0,deletions:Ce[ot.path]?.deletions??0,isNew:x1(ot)})).sort((ot,bt)=>ot.path.localeCompare(bt.path))},[H,de,w]),Ae=i.useMemo(()=>w?.files?w.files.filter(Hu).length:0,[w]),Ve=i.useMemo(()=>w?.files?w.files.filter(Uu).length:0,[w]),Ne=de.length,Y=i.useMemo(()=>$.map(Ce=>Ce.path).join("\0"),[$]);i.useEffect(()=>{const Ce=Y?Y.split("\0"):[],Qe=new Set(Ce),ot=`${u??""}:${H}:${e?"collapsed":"default"}`,bt=_.current!==ot;_.current=ot,P(Je=>{if(bt){const Ke=e?0:m1(Ce.length);return new Set(Ce.slice(0,Ke))}let Pt=!1;const Xe=new Set;for(const Ke of Je){if(!Qe.has(Ke)){Pt=!0;continue}Xe.add(Ke)}return Pt?Xe:Je}),B(Je=>{if(bt)return new Set;let Pt=!1;const Xe=new Set;for(const Ke of Je){if(!Qe.has(Ke)){Pt=!0;continue}Xe.add(Ke)}return Pt?Xe:Je})},[H,Y,u,e]);const F=i.useCallback(()=>{I.current=null;const Ce=oe.current;if(!Ce)return;const Qe=Ce.getBoundingClientRect(),ot=Qe.top-Wu,bt=Qe.bottom+Wu,Je={};for(const[Pt,Xe]of je.current){if(!Xe||!O.has(Pt))continue;const Ke=Xe.getBoundingClientRect();Ke.bottom<ot||Ke.top>bt||(Je[Pt]=!0)}B(Pt=>{let Xe=!1;const Ke=new Set(Pt);for(const Ze of Object.keys(Je))Ke.has(Ze)||(Ke.add(Ze),Xe=!0);return Xe?Ke:Pt})},[O]),se=i.useCallback(()=>{typeof window>"u"||I.current===null&&(I.current=window.requestAnimationFrame(F))},[F]);i.useEffect(()=>{const Ce=oe.current;if(Ce)return se(),Ce.addEventListener("scroll",se,{passive:!0}),window.addEventListener("resize",se),()=>{Ce.removeEventListener("scroll",se),window.removeEventListener("resize",se),I.current!==null&&(window.cancelAnimationFrame(I.current),I.current=null)}},[$,O,se]);const Oe=i.useCallback(Ce=>{const Qe=he[Ce.path];if(Qe)return Qe;if(we==="inline")return"inline";if(we==="side-by-side")return"side-by-side";const ot=p<c1;return Ce.isNew||ot?"inline":"side-by-side"},[he,we,p]),ce=i.useMemo(()=>$.length===0?null:$.every(Ce=>Oe(Ce)==="side-by-side")?"side-by-side":"inline",[$,Oe]);i.useEffect(()=>{u&&(h(u),C(u,f))},[u,h,C,f]),i.useEffect(()=>{if(u)return Lr.onGitRefreshHint(Ce=>{Gu(Ce.directory)===Gu(u)&&j(u,f)})},[u,j,f]),i.useEffect(()=>{H!=="all"&&!ve||re&&(ve&&te(ve),k(re),D(ve==="staged"||!ve&&le),ne(null),De.current=!0,ye.current=re,R(re),L(Ce=>Ce+1))},[H,R,re,ve,le,ne]),i.useEffect(()=>{if(H==="all")return;const Ce=c?.trim();Ce&&(k(Ce),D(H==="staged"),De.current=!0,ye.current=Ce,R(Ce),L(Qe=>Qe+1))},[H,R,c]),i.useEffect(()=>{if(!N)return;$.some(Qe=>Qe.path===N)||(k(null),D(!1))},[$,N]);const Ue=i.useCallback((Ce,Qe)=>{const ot=je.current;Qe?ot.set(Ce,Qe):ot.delete(Ce),se()},[se]),qe=i.useCallback((Ce,Qe)=>{be(),P(ot=>{const bt=ot.has(Ce);if(Qe===bt)return ot;const Je=new Set(ot);return Qe?Je.add(Ce):Je.delete(Ce),Je}),Qe||B(ot=>{if(!ot.has(Ce))return ot;const bt=new Set(ot);return bt.delete(Ce),bt}),se()},[be,se]),Ye=i.useCallback(()=>{be(),P(Ce=>Ce.size>0?new Set:new Set($.map(Qe=>Qe.path))),B(new Set),se()},[be,$,se]),tt=i.useCallback(async Ce=>{if(!me)return;const Qe=mt.getState().getDirectoryForSession(me)||u||"";if(!Qe){ae.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}X(!0);try{await Sg({originalSessionID:me,directory:Qe,providerID:Ce.providerID,modelID:Ce.modelID,agent:Ce.agent||void 0,variant:Ce.variant||void 0,generateHandoff:Ce.generateHandoff,returnAfterHandoffRequest:Ce.generateHandoff,autoReview:Ce.autoReview}),ee(!1)}catch(ot){console.error("[review-flow] failed to start review flow",ot),ae.error(ot instanceof Error?ot.message:d("diffView.reviewDialog.toast.startFailed"))}finally{X(!1)}},[me,u,d]),xt=i.useCallback(Ce=>{const Qe=je.current.get(Ce),ot=oe.current;if(!Qe||!ot)return!1;const bt=ot.getBoundingClientRect(),Pt=Qe.getBoundingClientRect().top-bt.top,Xe=Math.max(0,ot.scrollHeight-ot.clientHeight);return ot.scrollTop=Math.min(Xe,Math.max(0,ot.scrollTop+Pt)),!0},[]);i.useEffect(()=>{if(!ye.current)return;let Qe=0;const ot=20;let bt=!1;const Je=()=>{bt||(bt=!0,ye.current=null,De.current=!1,v(null),ue.current!==null&&(window.cancelAnimationFrame(ue.current),ue.current=null))},Pt=()=>{if(bt){ue.current=null;return}const Xe=ye.current;if(!Xe){Je(),ue.current=null;return}if(!xt(Xe)){Qe+=1,Qe<ot?ue.current=window.requestAnimationFrame(Pt):(Je(),ue.current=null);return}n&&De.current&&v(Xe),Je()};return ue.current=window.requestAnimationFrame(Pt),()=>{bt=!0,ue.current!==null&&(window.cancelAnimationFrame(ue.current),ue.current=null)}},[n,U,xt]);const vt=i.useCallback(Ce=>{},[]),Mt=i.useCallback(Ce=>{be(),k(Ce),D(!1),De.current=!0,ye.current=Ce,R(Ce),L(Qe=>Qe+1),xt(Ce)},[be,R,xt]),Tt=i.useCallback(Ce=>{const Qe=Ce==="side-by-side"?"side-by-side":"inline";$.forEach(ot=>{Me(ot.path,Qe)})},[$,Me]),[Kt,Ut]=i.useState(null),Zt=i.useCallback(async(Ce,Qe)=>{if(!(!u||!Ce)){Ut(Ce);try{let ot=null;if(Qe?.patch&&!Qe.isBinary&&!Ei(Ce)?ot=$u(Qe.patch):Qe&&Qe.contextMode==="full"&&!Qe.isBinary&&!Ei(Ce)&&(ot=Ku(Qe.original,Qe.modified)),ot===null)try{const Ke=await f.getGitDiff(u,{path:Ce,staged:Le,contextLines:3});ot=$u(Ke.diff)}catch{ot=null}let bt=Qe;if(ot===null||!bt){const Ke=await f.getGitFileDiff(u,{path:Ce,staged:Le});bt={original:Ke.original??"",modified:Ke.modified??"",isBinary:Ke.isBinary},Le||S(u,Ce,bt)}const Je=ot??(bt.isBinary||Ei(Ce)?1:Ku(bt.original,bt.modified)),Pt=b1(u,Ce),Xe=await Yc(m,Pt);if(!Xe.ok){ae.error(Qc(Xe.reason));return}q(u,Pt,Je,1)}finally{Ut(ot=>ot===Ce?null:ot)}}},[Le,u,m,f,q,S]),ns=()=>{if(!u)return null;const Ce=Qe=>_e!==null?_e:y&&Qe===N;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:[ge&&s.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:d("diffView.section.files")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:$.length})]}),s.jsx(S1,{changedFiles:$,selectedFile:null,onSelectFile:Mt})]}),s.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:s.jsx(On,{ref:oe,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:s.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:$.map(Qe=>s.jsx(A1,{directory:u,file:Qe,layout:Oe(Qe),wrapLines:Be,isSelected:!1,isExpanded:O.has(Qe.path),isMounted:E.has(Qe.path)||Qe.path===V,onSelect:vt,onExpandedChange:qe,registerSectionRef:Ue,showOpenInEditorAction:r&&H!=="turn",isOpeningInEditor:Kt===Qe.path,onOpenInEditor:(ot,bt)=>{Zt(ot,bt)},staged:Ce(Qe.path),loadFullFiles:T,initialDiffData:H==="turn"?fe.get(Qe.path)??null:null},Qe.path))})})})]})},es=()=>u?H!=="turn"&&g&&!w?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),d("diffView.state.loadingRepositoryStatus")]}):H!=="turn"&&b===!1?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.notGitRepository")}):$.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d(H==="turn"?"diffView.state.noLastTurnChanges":"diffView.state.cleanWorkingTree")}):ns():s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.selectSessionDirectory")});return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[!x&&(H==="working"||H==="staged"||H==="turn"?s.jsx(j1,{scope:H,workingCount:Ae,stagedCount:Ve,turnCount:Ne,onScopeChange:Ce=>{te(Ce),a?.(Ce)}}):s.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:g&&!w?d("diffView.state.loadingChanges"):$.length===1?d("diffView.summary.changedFilesSingle",{count:$.length}):d("diffView.summary.changedFilesPlural",{count:$.length})})})),$.length>0&&s.jsxs(ze,{variant:"ghost",size:"sm",onClick:Ye,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:O.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll"),children:[s.jsx(A,{name:"expand-up-down",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:O.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll")})]}),$.length>0&&Ee&&s.jsxs(ze,{variant:"default",size:"sm",onClick:()=>ee(!0),disabled:ie,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[ie?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(A,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),$.length>0&&s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>W(Ce=>!Ce),"aria-pressed":T,"aria-label":d(T?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:Pe("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",T&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(A,{name:"file-download",className:"size-4"})})}),s.jsx(Dt,{children:s.jsx("p",{children:d(T?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),$.length>0&&s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>K(!z),className:Pe("h-5 w-5 p-0 transition-opacity",Be?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(Be?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(A,{name:"text-wrap",className:"size-4"})}),ce&&s.jsx(fm,{mode:ce==="side-by-side"?"side-by-side":"unified",onModeChange:Tt})]}),s.jsx(Ng,{open:M,onOpenChange:ee,projectDirectory:u??null,submitting:ie,onConfirm:tt}),es()]})},D1=(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)},qu=(t,e)=>{const n=t.state.doc.lineAt(e.main.head);return{lineNumber:n.number,character:e.main.head-n.from+1,selection:e}},Yu=(t,e,n)=>{const r=t.state.doc.line(e),o=Math.max(1,Math.min(n,r.length+1)),a=r.from+o-1;t.dispatch({selection:Xh.cursor(a),effects:hi.scrollIntoView(a,{y:"center"})})};function T1({open:t,onOpenChange:e,view:n,variant:r="overlay"}){const{t:o}=yt(),[a,c]=i.useState(""),l=i.useRef(null),d=i.useRef(!1),f=i.useRef(null),m=i.useRef(null),u=i.useMemo(()=>D1(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=qu(n,n.state.selection),c(""))},[t,n]),i.useEffect(()=>{t&&window.requestAnimationFrame(()=>{m.current?.focus(),m.current?.select()})},[t]),i.useEffect(()=>{if(!(!t||!n||!l.current)){if(u===null){const{selection:g}=l.current;n.dispatch({selection:g,effects:hi.scrollIntoView(g.main.from,{y:"center"})});return}Yu(n,u,l.current.character)}},[u,t,n]);const p=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:g}=l.current;n.dispatch({selection:g,effects:hi.scrollIntoView(g.main.from,{y:"center"})})},[n]),x=i.useCallback(g=>{g||p(),e(g)},[e,p]),b=i.useCallback(()=>{!n||u===null||!l.current||(d.current=!0,Yu(n,u,l.current.character),e(!1),n.focus())},[u,e,n]);i.useEffect(()=>{if(!t)return;const g=C=>{const j=f.current,S=C.target;!j||!(S instanceof Node)||j.contains(S)||x(!1)},h=C=>{C.key==="Escape"&&(C.preventDefault(),x(!1))};return document.addEventListener("pointerdown",g,!0),document.addEventListener("keydown",h,!0),()=>{document.removeEventListener("pointerdown",g,!0),document.removeEventListener("keydown",h,!0)}},[x,t,r]);const w=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(u===null){const g=l.current??qu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:g.lineNumber,max:n.state.doc.lines})}return o("goToLineDialog.helper.goToLine",{line:u})},[u,o,n]);return r==="inline"?t?s.jsxs("div",{ref:f,className:"ml-1 flex h-6 items-center gap-1",children:[s.jsx(Ln,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:g=>c(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),b())},placeholder:o("goToLineDialog.field.linePlaceholderShort"),className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),s.jsx(ze,{variant:"outline",size:"xs",onClick:b,disabled:!n||u===null,className:"h-6 px-2",children:o("goToLineDialog.actions.go")})]}):null:s.jsx("div",{ref:f,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(Ln,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:g=>c(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),b())},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:w})]})})}const P1='<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 Qu(){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 I1=i.forwardRef(function({xml:e,readOnly:n,className:r,onChange:o},a){const c=i.useRef(e),l=i.useRef(null),d=i.useRef(!1),[f,m]=i.useState(Qu),u=i.useRef(e),p=i.useRef(e);p.current!==e&&(p.current=e,u.current=e,c.current=e);const x=i.useRef(f);x.current!==f&&(x.current=f,u.current=c.current);const b=i.useRef(null);i.useEffect(()=>{const h=()=>m(Qu());h();const C=new MutationObserver(h);return C.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>C.disconnect()},[]),i.useEffect(()=>{const h=setTimeout(()=>{b.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(h)},[]),i.useImperativeHandle(a,()=>({getXml:()=>c.current}));const w=i.useCallback(()=>{!e&&!d.current&&(d.current=!0,setTimeout(()=>{l.current?.template({})},500))},[e]),g=i.useCallback(h=>{c.current=h.xml,o?.(h.xml)},[o]);return s.jsx("div",{ref:b,className:Pe("h-full w-full",r),children:s.jsx(Zh,{ref:l,xml:u.current||P1,autosave:!0,urlParameters:{ui:n?"simple":f?"dark":"kennedy",spin:!0,libraries:!n,chrome:n,nav:n,layers:n,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:w,onAutoSave:g},f?"dark":"light")})}),R1=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},E1=t=>{const e=ht.c(8),{label:n,iconDataUrl:r}=t,[o,a]=i.useState(!1);let c;e[0]!==n?(c=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=c):c=e[1];const l=c;if(r&&!o){let m;e[2]===Symbol.for("react.memo_cache_sentinel")?(m=()=>a(!0),e[2]=m):m=e[2];let u;return e[3]!==r?(u=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:m}),e[3]=r,e[4]=u):u=e[4],u}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=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 f;return e[6]!==l?(f=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=f):f=e[7],f},M1=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},F1=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Ki=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,La=(t,e)=>{const n=Js(e),r=Js(t);if(!n||!r)return!1;const o=Ki(n),a=Ki(r);return a===o||a.startsWith(`${o}/`)},Ju=(t,e)=>{const n=Js(e),r=Js(t);if(!La(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},ac=(t,e)=>{if(!e)return"";const n=Js(e);if(!t||!La(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},O1=new Set(["node_modules"]),L1=t=>{const e=ht.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},Xu=t=>{const e=ht.c(11),{name:n}=t,r=i.useRef(null),o=i.useRef(null),[a,c]=i.useState(!1);let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l=()=>{const p=r.current,x=o.current;if(!p||!x)return;const b=()=>{c(x.scrollWidth>p.clientWidth+1)};b();const w=new ResizeObserver(b);return w.observe(p),w.observe(x),()=>{w.disconnect()}},e[0]=l):l=e[0];let d;e[1]!==n?(d=[n],e[1]=n,e[2]=d):d=e[2],i.useLayoutEffect(l,d);let f;e[3]!==n?(f=s.jsx("span",{ref:o,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:n}),e[3]=n,e[4]=f):f=e[4];let m;e[5]!==n||e[6]!==a?(m=a?s.jsxs("span",{className:"open-file-name-marquee-track",children:[s.jsx("span",{className:"open-file-name-marquee-item",children:n}),s.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:n})]}):s.jsx("span",{className:"block min-w-0 truncate",children:n}),e[5]=n,e[6]=a,e[7]=m):m=e[7];let u;return e[8]!==f||e[9]!==m?(u=s.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[f,m]}),e[8]=f,e[9]=m,e[10]=u):u=e[10],u},B1=t=>O1.has(t),V1=t=>{const e=Js(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},_1=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},Zu=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")},So=2e5,ah="openchamber:files:auto-save-enabled",$1=t=>{let e=0,n=0;for(let r=0;r<t.length;r+=1)t.charCodeAt(r)===10&&(r>0&&t.charCodeAt(r-1)===13?e+=1:n+=1);return e>n?`\r
22
+ `:`
23
+ `},lh=t=>t.replace(/\r\n/g,`
24
+ `).replace(/\r/g,`
25
+ `),z1=(t,e)=>{const n=lh(t);return e===`\r
26
+ `?n.replace(/\n/g,`\r
27
+ `):n},W1=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(ah)!=="false"}catch{return!0}},ch=(t,e)=>s.jsx(ei,{filePath:t,extension:e}),ef=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},U1=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="json"||e==="jsonc"||e==="json5"||e==="geojson"},Rl=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="html"||e==="htm"},H1=t=>{const e=ht.c(83),{node:n,root:r,isExpanded:o,isActive:a,isMobile:c,alwaysShowActions:l,status:d,badge:f,permissions:m,downloadFile:u,contextMenuPath:p,setContextMenuPath:x,rightClickMenuPath:b,setRightClickMenuPath:w,onSelect:g,onToggle:h,onRevealPath:C,onOpenDialog:j}=t,{t:S}=yt(),N=n.type==="directory",{canRename:k,canCreateFile:y,canCreateFolder:D,canDelete:V,canReveal:v}=m;let O;e[0]!==y||e[1]!==D||e[2]!==V||e[3]!==k||e[4]!==v||e[5]!==n.path||e[6]!==w?(O=me=>{!k&&!y&&!D&&!V&&!v||(me?.preventDefault(),w(n.path))},e[0]=y,e[1]=D,e[2]=V,e[3]=k,e[4]=v,e[5]=n.path,e[6]=w,e[7]=O):O=e[7];const P=O;let E;e[8]!==N||e[9]!==n||e[10]!==g||e[11]!==h?(E=()=>{N?h(n.path):g(n)},e[8]=N,e[9]=n,e[10]=g,e[11]=h,e[12]=E):E=e[12];const B=E;let T;e[13]!==n.path||e[14]!==x||e[15]!==w?(T=me=>{me.stopPropagation(),w(null),x(n.path)},e[13]=n.path,e[14]=x,e[15]=w,e[16]=T):T=e[16];const W=T;let U;e[17]!==y||e[18]!==D||e[19]!==V||e[20]!==k||e[21]!==v||e[22]!==u||e[23]!==N||e[24]!==n||e[25]!==j||e[26]!==C||e[27]!==r||e[28]!==S?(U=me=>{const{Item:Se,Separator:Be}=me;return s.jsxs(s.Fragment,{children:[k&&s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),j("rename",n)},children:[s.jsx(A,{name:"edit",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.rename")]}),s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),xr(n.path).then(Le=>{if(Le.ok){ae.success(S("sidebarFilesTree.toast.pathCopied"));return}ae.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(A,{name:"file-copy",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.copyPath")]}),s.jsxs(Se,{onClick:_e=>{_e.stopPropagation();const Le=ac(r,n.path)||n.path;xr(Le).then(pe=>{if(pe.ok){ae.success(S("filesView.toast.relativePathCopied"));return}ae.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(A,{name:"file-copy-2",className:"mr-2 size-4"})," ",S("filesView.tree.menu.copyRelativePath")]}),!N&&u&&s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),u(n.path).catch(Le=>{console.error("Download failed:",Le),ae.error(S("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(A,{name:"download",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.save")]}),v&&s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),C(n.path)},children:[s.jsx(A,{name:"folder-received",className:"mr-2 size-4"})," ",S(Rc())]}),N&&(y||D)&&s.jsxs(s.Fragment,{children:[s.jsx(Be,{}),y&&s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),j("createFile",n)},children:[s.jsx(A,{name:"file-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFile")]}),D&&s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),j("createFolder",n)},children:[s.jsx(A,{name:"folder-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFolder")]})]}),V&&s.jsxs(s.Fragment,{children:[s.jsx(Be,{}),s.jsxs(Se,{onClick:_e=>{_e.stopPropagation(),j("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"delete-bin",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.delete")]})]})]})},e[17]=y,e[18]=D,e[19]=V,e[20]=k,e[21]=v,e[22]=u,e[23]=N,e[24]=n,e[25]=j,e[26]=C,e[27]=r,e[28]=S,e[29]=U):U=e[29];const L=U,M=b===n.path;let ee;e[30]!==n.path||e[31]!==w?(ee=me=>w(me?n.path:null),e[30]=n.path,e[31]=w,e[32]=ee):ee=e[32];const ie=c?void 0:P;let X;e[33]!==ie?(X=s.jsx("div",{className:"group relative flex items-center",onContextMenu:ie}),e[33]=ie,e[34]=X):X=e[34];const H=c?void 0:P,te=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let re;e[35]!==te?(re=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",te),e[35]=te,e[36]=re):re=e[36];let le;e[37]!==N||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(le=N?o?s.jsx(A,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(A,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):ch(n.path,n.extension),e[37]=N,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=le):le=e[41];let ve;e[42]!==n.name||e[43]!==n.path?(ve=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]=ve):ve=e[44];let ne;e[45]!==N||e[46]!==d?(ne=!N&&d&&s.jsx(L1,{status:d}),e[45]=N,e[46]=d,e[47]=ne):ne=e[47];let we;e[48]!==f||e[49]!==N?(we=N&&f&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[f.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",f.modified]}),f.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",f.added]})]}),e[48]=f,e[49]=N,e[50]=we):we=e[50];let he;e[51]!==B||e[52]!==re||e[53]!==le||e[54]!==ve||e[55]!==ne||e[56]!==we||e[57]!==H?(he=s.jsxs("button",{type:"button",onClick:B,onContextMenu:H,className:re,children:[le,ve,ne,we]}),e[51]=B,e[52]=re,e[53]=le,e[54]=ve,e[55]=ne,e[56]=we,e[57]=H,e[58]=he):he=e[58];let Me;e[59]!==l||e[60]!==y||e[61]!==D||e[62]!==V||e[63]!==k||e[64]!==v||e[65]!==p||e[66]!==W||e[67]!==c||e[68]!==n.path||e[69]!==L||e[70]!==x?(Me=(k||y||D||V||v)&&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(tn,{open:p===n.path,onOpenChange:me=>x(me?n.path:null),children:[s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"icon",className:"size-6",onClick:W,children:s.jsx(A,{name:"more-2-fill",className:"size-4"})})}),s.jsx(en,{align:"end",side:"bottom",onCloseAutoFocus:()=>x(null),children:L({Item:ms,Separator:Vr})})]})}),e[59]=l,e[60]=y,e[61]=D,e[62]=V,e[63]=k,e[64]=v,e[65]=p,e[66]=W,e[67]=c,e[68]=n.path,e[69]=L,e[70]=x,e[71]=Me):Me=e[71];let z;e[72]!==he||e[73]!==Me||e[74]!==X?(z=s.jsxs(zc,{render:X,children:[he,Me]}),e[72]=he,e[73]=Me,e[74]=X,e[75]=z):z=e[75];let K;e[76]!==L?(K=s.jsx(_c,{className:"min-w-[180px]",children:L({Item:$c,Separator:Mm})}),e[76]=L,e[77]=K):K=e[77];let q;return e[78]!==z||e[79]!==K||e[80]!==M||e[81]!==ee?(q=s.jsxs(Wc,{open:M,onOpenChange:ee,children:[z,K]}),e[78]=z,e[79]=K,e[80]=M,e[81]=ee,e[82]=q):q=e[82],q},G1=t=>{const e=ht.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:f}=t,{t:m}=yt(),u=!!n;let p;e[0]!==d?(p=M=>!M&&d(),e[0]=d,e[1]=p):p=e[1];let x;e[2]!==n||e[3]!==m?(x=n==="createFile"&&m("filesView.dialog.createFile.title"),e[2]=n,e[3]=m,e[4]=x):x=e[4];let b;e[5]!==n||e[6]!==m?(b=n==="createFolder"&&m("filesView.dialog.createFolder.title"),e[5]=n,e[6]=m,e[7]=b):b=e[7];let w;e[8]!==n||e[9]!==m?(w=n==="rename"&&m("filesView.dialog.rename.title"),e[8]=n,e[9]=m,e[10]=w):w=e[10];let g;e[11]!==n||e[12]!==m?(g=n==="delete"&&m("filesView.dialog.delete.title"),e[11]=n,e[12]=m,e[13]=g):g=e[13];let h;e[14]!==x||e[15]!==b||e[16]!==w||e[17]!==g?(h=s.jsxs(Hs,{children:[x,b,w,g]}),e[14]=x,e[15]=b,e[16]=w,e[17]=g,e[18]=h):h=e[18];let C;e[19]!==n||e[20]!==r?.path||e[21]!==m?(C=n==="createFile"&&m("filesView.dialog.createFile.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[19]=n,e[20]=r?.path,e[21]=m,e[22]=C):C=e[22];let j;e[23]!==n||e[24]!==r?.path||e[25]!==m?(j=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]=j):j=e[26];let S;e[27]!==n||e[28]!==r?.name||e[29]!==m?(S=n==="rename"&&m("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=m,e[30]=S):S=e[30];let N;e[31]!==n||e[32]!==r?.name||e[33]!==m?(N=n==="delete"&&m("filesView.dialog.delete.description",{name:r?.name??""}),e[31]=n,e[32]=r?.name,e[33]=m,e[34]=N):N=e[34];let k;e[35]!==S||e[36]!==N||e[37]!==C||e[38]!==j?(k=s.jsxs(mn,{children:[C,j,S,N]}),e[35]=S,e[36]=N,e[37]=C,e[38]=j,e[39]=k):k=e[39];let y;e[40]!==k||e[41]!==h?(y=s.jsxs(sn,{children:[h,k]}),e[40]=k,e[41]=h,e[42]=y):y=e[42];let D;e[43]!==n||e[44]!==o||e[45]!==f||e[46]!==a||e[47]!==l||e[48]!==m?(D=n!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(Ln,{value:o,onChange:M=>a(M.target.value),placeholder:m(n==="rename"?"filesView.dialog.rename.placeholder":"filesView.dialog.namePlaceholder"),onKeyDown:M=>{M.key==="Enter"&&l()},ref:f})}),e[43]=n,e[44]=o,e[45]=f,e[46]=a,e[47]=l,e[48]=m,e[49]=D):D=e[49];let V;e[50]!==m?(V=m("filesView.dialog.cancel"),e[50]=m,e[51]=V):V=e[51];let v;e[52]!==c||e[53]!==d||e[54]!==V?(v=s.jsx(ze,{variant:"outline",onClick:d,disabled:c,children:V}),e[52]=c,e[53]=d,e[54]=V,e[55]=v):v=e[55];const O=n==="delete"?"destructive":"default";let P;e[56]!==l?(P=()=>{l()},e[56]=l,e[57]=P):P=e[57];let E;e[58]!==n||e[59]!==o||e[60]!==c?(E=c||n!=="delete"&&!o.trim(),e[58]=n,e[59]=o,e[60]=c,e[61]=E):E=e[61];let B;e[62]!==n||e[63]!==c||e[64]!==m?(B=c?s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):m(n==="delete"?"filesView.dialog.delete.confirm":"filesView.dialog.confirm"),e[62]=n,e[63]=c,e[64]=m,e[65]=B):B=e[65];let T;e[66]!==O||e[67]!==P||e[68]!==E||e[69]!==B?(T=s.jsx(ze,{variant:O,onClick:P,disabled:E,children:B}),e[66]=O,e[67]=P,e[68]=E,e[69]=B,e[70]=T):T=e[70];let W;e[71]!==v||e[72]!==T?(W=s.jsxs(br,{children:[v,T]}),e[71]=v,e[72]=T,e[73]=W):W=e[73];let U;e[74]!==f||e[75]!==y||e[76]!==D||e[77]!==W?(U=s.jsxs(Vs,{initialFocus:f,children:[y,D,W]}),e[74]=f,e[75]=y,e[76]=D,e[77]=W,e[78]=U):U=e[78];let L;return e[79]!==u||e[80]!==p||e[81]!==U?(L=s.jsx(_s,{open:u,onOpenChange:p,children:U}),e[79]=u,e[80]=p,e[81]=U,e[82]=L):L=e[82],L},El=(t,e,n)=>{const r=ht.c(8),[o,a]=i.useState(""),[c,l]=i.useState(0);let d,f;r[0]!==t||r[1]!==n||r[2]!==e?(d=()=>{if(!t){a("");return}let u=!1;a("");const p=Xr(),x=Np(p);vc(p).then(w=>{u||!w||(a(t),e(null))}).catch(w=>{u||(e(w instanceof Error?w.message:n),a(t))});const b=kp(()=>{u||(a(t),l(K1),e(null))});return()=>{u=!0,x(),b()}},f=[t,e,n],r[0]=t,r[1]=n,r[2]=e,r[3]=d,r[4]=f):(d=r[3],f=r[4]),i.useEffect(d,f);let m;return r[5]!==c||r[6]!==o?(m={readyKey:o,nonce:c},r[5]=c,r[6]=o,r[7]=m):m=r[7],m},dh=({mode:t="full"})=>{const{t:e}=yt(),{files:n,runtime:r}=Zn(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=yi(),{isMobile:d,isTablet:f,screenWidth:m}=$r(),u=d||f,p=Xf(),x=Zf(),b=wi()??"",w=Js(b.trim()),g=d||t!=="editor-only",h=t==="editor-only"&&!d,C=yc(G=>G.searchFiles),j=Ja(b),[S,N]=i.useState(""),k=Za(S,200),y=i.useRef(null),[D,V]=i.useState(!1),[v,O]=i.useState(!0),[P,E]=i.useState(!1),[B,T]=i.useState(!1),[W,U]=i.useState(!1),L=i.useRef(null),M=i.useRef(0),ee=i.useCallback(G=>{M.current=Math.max(0,M.current+(G?1:-1))},[]),ie=i.useCallback(G=>G instanceof Element?G.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!W)return;const G=Te=>{M.current>0||ie(Te.target)||L.current&&!L.current.contains(Te.target)&&U(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[ie,W]);const[X,H]=i.useState("edit"),[te,re]=i.useState("edit"),[le,ve]=i.useState("tree"),[ne,we]=i.useState("edit"),[he,Me]=i.useState("preview"),[z,K]=i.useState(0),q=i.useRef({}),me=i.useRef({}),Se=i.useRef({}),Be=i.useRef({}),_e=i.useMemo(()=>a.find(G=>G.metadata.id===c)??Vd(!1),[a,c]),Le=i.useMemo(()=>a.find(G=>G.metadata.id===l)??Vd(!0),[a,l]);i.useEffect(()=>{_d(_e),_d(Le)},[_e,Le]);const pe=i.useMemo(()=>[],[]),Ee=fn(G=>w?G.byRoot[w]?.openPaths??pe:pe),ge=fn(G=>w?G.byRoot[w]?.selectedPath??null:null),oe=fn(G=>w?G.byRoot[w]?.expandedPaths??pe:pe),je=fn(G=>G.addOpenPath),ye=fn(G=>G.removeOpenPath),ue=fn(G=>G.removeOpenPathsByPrefix),De=fn(G=>G.removeExpandedPathsByPrefix),I=fn(G=>G.setSelectedPath),_=fn(G=>G.toggleExpandedPath),be=fn(G=>G.expandPaths),R=i.useCallback(G=>{const Te=Js(G),We=Te.split("/"),He=We[We.length-1]||Te,lt=He.includes(".")?He.split(".").pop()?.toLowerCase():void 0;return{name:He,path:Te,type:"file",extension:lt}},[]),de=i.useMemo(()=>Ee.map(R),[Ee,R]),fe=i.useMemo(()=>{if(ge){const G=Ki(ge);if(Ee.some(Te=>Ki(Te)===G))return ge}return Ee[0]??null},[Ee,ge]),$=i.useMemo(()=>fe?R(fe):null,[fe,R]),Ae=$?.path??"";i.useEffect(()=>{if(!w||!ge)return;const G=Ki(ge);Ee.some(We=>Ki(We)===G)||I(w,Ee[0]??null)},[Ee,w,ge,I]);const Ve=!!(w&&Ae&&!La(Ae,w)),Ne=Ve?$d(Ae):void 0,Y=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&Ve,outsideFileGrant:Ne,directory:w||void 0}),[t,Ve,Ne,w]),F=i.useRef(null),[se,Oe]=i.useState({left:!1,right:!1}),ce=i.useCallback(()=>{const G=F.current;G&&Oe({left:G.scrollLeft>2,right:G.scrollLeft+G.clientWidth<G.scrollWidth-2})},[]),Ue=i.useRef(ce);Ue.current=ce,i.useEffect(()=>{const G=F.current;if(!G)return;const Te=()=>Ue.current();Te(),G.addEventListener("scroll",Te,{passive:!0});const We=new ResizeObserver(Te);return We.observe(G),()=>{G.removeEventListener("scroll",Te),We.disconnect()}},[de.length]);const[qe,Ye]=i.useState({}),[tt,xt]=i.useState({}),vt=i.useRef(new Set),Mt=i.useRef(new Set),Tt=i.useRef(new Map),Kt=i.useRef(0),[Ut,Zt]=i.useState([]),[ns,es]=i.useState(!1),[Ce,Qe]=i.useState(""),{isPlaying:ot,play:bt,stop:Je}=mm(),[Pt,Xe]=i.useState(!1),[Ke,Ze]=i.useState(null),[Bt,Rt]=i.useState(""),Ot=i.useRef(""),[rs,Wt]=i.useState(null),[Et,qt]=i.useState(""),[hs,ts]=i.useState(!1),[as,gs]=i.useState(`
28
+ `),Ft=i.useRef(null),Lt=i.useRef(null),Ht=i.useRef(null),Yt=i.useRef(""),$t=i.useRef(""),Fe=i.useRef(null),st=i.useRef(null),wt=i.useRef(null),St=i.useRef(0),[Nt,ss]=i.useState("idle"),[cs,Xt]=i.useState(!1),[Vt,Fs]=i.useState(W1),[us,$s]=i.useState(!1),js=i.useRef(null),Cs=i.useRef(null),jn=i.useRef(null),hn=i.useRef(!1),xe=i.useRef(null),rt=i.useRef(null),dt=i.useRef(null),jt=i.useRef(null),[zt,gt]=i.useState(0),xs=i.useRef(null),bs=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{xs.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(xs.current),xs.current=null)},[]);const[Ss,Ns]=i.useState(null),[Os,Tn]=i.useState(null),[Gs,Pn]=i.useState(""),[Bn,Sn]=i.useState(!1),[an,Nn]=i.useState(null),[nn,Ge]=i.useState(null),[ps,ks]=i.useState(!1),[zs,Rs]=i.useState(!1),[rn,Ks]=i.useState(!1),Is=!!n.writeFile,Vn=!!n.createDirectory,ws=!!n.rename,Ls=!!n.delete,Dr=!!n.revealPath,_n=Cr(G=>G.availableApps),bn=Cr(G=>G.isCacheStale),Tr=Cr(G=>G.initialize),si=Cr(G=>G.loadInstalledApps);i.useEffect(()=>{Tr()},[Tr]);const ni=i.useCallback(G=>{n.revealPath&&n.revealPath(G).catch(()=>{ae.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),zr=i.useCallback(async G=>{if(!$?.path||await Sp($.path,G.id,G.appName)||await Ca($.path,G.appName))return;const He=R1($.path)||w;He&&await Ca(He,G.appName)||ae.error(e("filesView.toast.openInAppFailed",{app:G.appName}))},[w,$?.path,e]),cr=i.useCallback((G,Te)=>{Ns(G),Tn(Te),Pn(G==="rename"&&Te.name||""),Sn(!1)},[]),[ys,ln]=i.useState(null),dr=i.useRef(!1),J=i.useRef(null),[at,ut]=i.useState(!1),kt=Re(G=>G.setMainTabGuard),Gt=Re(G=>G.pendingFileNavigation),os=Re(G=>G.setPendingFileNavigation),fs=Re(G=>G.pendingFileFocusPath),Es=Re(G=>G.setPendingFileFocusPath),qs=Re(G=>G.shortcutOverrides),er=Re(G=>G.fileEditorKeymap),$n=is(G=>G.settingsDefaultFileViewerPreview),ri=is(G=>G.showMessageTTSButtons),pn=Re(G=>G.expandedEditorToolbar);i.useEffect(()=>{const G=()=>{dr.current=!1,J.current=null,ut(!1)};return document.addEventListener("mouseup",G),()=>document.removeEventListener("mouseup",G)},[]),i.useEffect(()=>()=>{xe.current!==null&&window.clearTimeout(xe.current),rt.current!==null&&window.clearTimeout(rt.current)},[]);const Wr=i.useCallback((G,Te)=>{const We=G.split(`
29
+ `),He=Math.max(1,Te.start),lt=Math.min(We.length,Te.end);return He>lt?"":We.slice(He-1,lt).join(`
30
+ `)},[]),In=Fm({source:"file",fileLabel:$?.path??null,language:$?.path&&Ri($.path)||"text",getCodeForRange:G=>Wr(Ce,Om(G)),toStoreRange:G=>({startLine:G.start,endLine:G.end}),fromDraftRange:G=>({start:G.startLine,end:G.endLine})}),{drafts:tr,commentText:cn,setCommentText:gn,editingDraftId:wn,setSelection:sr,saveComment:nr,cancel:Ur,reset:rr,startEdit:Hr,deleteDraft:ii}=In;i.useEffect(()=>{ln(null),rr(),kt(null),qt(""),ts(!1)},[$?.path,rr,kt]),i.useEffect(()=>{sr(ys)},[ys,sr]),i.useEffect(()=>{if(!ys&&!wn)return;const G=We=>{const He=We.target;He.closest('[data-comment-input="true"]')||He.closest('[data-comment-card="true"]')||He.closest(".cm-gutterElement")||He.closest("[data-sonner-toast]")||He.closest("[data-sonner-toaster]")||cn.trim()||(ln(null),Ur())},Te=setTimeout(()=>{document.addEventListener("click",G)},100);return()=>{clearTimeout(Te),document.removeEventListener("click",G)}},[Ur,cn,wn,ys]);const Oi=i.useCallback((G,Te)=>{const We=Te??ys??void 0;Te&&ln(Te),nr(G,We),ln(null)},[ys,nr]),Li=i.useCallback((G,Te)=>{const We=[];for(const He of Te){if(!(He&&typeof He.name=="string"&&He.name.length>0)||!p&&He.name.startsWith(".")||!x&&B1(He.name))continue;const lt=He.name,ct=Js(He.path||""),ls=ct?F1(ct)?ct:Js(`${G}/${ct}`):Js(`${G}/${lt}`),Ts=He.isDirectory?"directory":"file",Ms=Ts==="file"&&lt.includes(".")?lt.split(".").pop()?.toLowerCase():void 0;We.push({name:lt,path:ls,type:Ts,extension:Ms})}return M1(We)},[x,p]),Rn=i.useCallback(async G=>{const Te=Js(G.trim());if(!Te||vt.current.has(Te)||Mt.current.has(Te))return;Mt.current=new Set(Mt.current),Mt.current.add(Te);const We=Kt.current+1;Kt.current=We,Tt.current=new Map(Tt.current),Tt.current.set(Te,We);const He=()=>Tt.current.get(Te)===We;await(n.listDirectory?n.listDirectory(Te).then(ct=>ct.entries.map(ls=>({name:ls.name,path:ls.path,isDirectory:ls.isDirectory}))):Xn.listLocalDirectory(Te).then(ct=>ct.map(ls=>({name:ls.name,path:ls.path,isDirectory:ls.isDirectory})))).then(ct=>{if(!He())return;const ls=Li(Te,ct);vt.current=new Set(vt.current),vt.current.add(Te),xt(Ts=>{if(!Ts[Te])return Ts;const Ms={...Ts};return delete Ms[Te],Ms}),Ye(Ts=>({...Ts,[Te]:ls}))}).catch(ct=>{if(!He())return;const ls=ct instanceof Error?ct.message:String(ct??"");if(ls==="Directory not found"&&w&&Te!==w){De(w,Te),xt(Ts=>{if(!Ts[Te])return Ts;const Ms={...Ts};return delete Ms[Te],Ms});return}console.error("Failed to load files directory:",ct),xt(Ts=>({...Ts,[Te]:ls}))}).finally(()=>{He()&&(Tt.current=new Map(Tt.current),Tt.current.delete(Te),Mt.current=new Set(Mt.current),Mt.current.delete(Te))})},[n,Li,De,w]),ur=i.useCallback(async()=>{w&&(vt.current=new Set,Mt.current=new Set,Tt.current=new Map,xt({}),Ye(G=>Object.keys(G).length===0?G:{}),await Rn(w))},[Rn,w]),Ys=i.useCallback(async G=>{if(!G){await ur();return}const Te=Js(G);vt.current=new Set(vt.current),vt.current.delete(Te),Mt.current=new Set(Mt.current),Mt.current.delete(Te),await Rn(Te)},[Rn,ur]),Qs=i.useRef(""),wr=i.useRef("");i.useEffect(()=>{if(!w)return;const G=`${w}|h${p?"1":"0"}|g${x?"1":"0"}`,Te=Qs.current!==w,We=wr.current!==G;!Te&&!We||(Te&&(Qs.current=w,Qe(""),Ze(null),Rt(""),Wt(null),V(!1)),We&&(wr.current=G,vt.current=new Set,Mt.current=new Set,Tt.current=new Map,xt({}),Ye(He=>Object.keys(He).length===0?He:{}),Rn(w)))},[Rn,w,x,p]),i.useEffect(()=>{if(!n.listDirectory)return;const G=()=>{if(!document.hidden&&oe.length>0)for(const Te of oe)Ys(Te)};return document.addEventListener("visibilitychange",G),()=>document.removeEventListener("visibilitychange",G)},[oe,n.listDirectory,Ys]),i.useEffect(()=>{if(!n.listDirectory||oe.length===0)return;const G=setInterval(()=>{if(!document.hidden)for(const Te of oe)Ys(Te)},8e3);return()=>clearInterval(G)},[oe,n.listDirectory,Ys]);const go=i.useCallback(async G=>{if(G?.preventDefault(),!Os||!Ss)return;Sn(!0);const Te=()=>{Ns(null)},We=lt=>{ae.error(lt)},He=()=>{Sn(!1)};if(Ss==="createFile"){if(!Gs.trim()){We(e("sidebarFilesTree.toast.filenameRequired")),He();return}if(!n.writeFile){We(e("sidebarFilesTree.toast.writeNotSupported")),He();return}const lt=Os.path,ct=lt?`${lt}/`:"",ls=Js(`${ct}${Gs.trim()}`);await n.writeFile(ls,"").then(async Ts=>{Ts.success&&(ae.success(e("sidebarFilesTree.toast.fileCreated")),await Ys(lt)),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(He);return}if(Ss==="createFolder"){if(!Gs.trim()){We(e("sidebarFilesTree.toast.folderNameRequired")),He();return}const lt=Os.path,ct=lt?`${lt}/`:"",ls=Js(`${ct}${Gs.trim()}`);await n.createDirectory(ls).then(async Ts=>{Ts.success&&(ae.success(e("sidebarFilesTree.toast.folderCreated")),await Ys(lt)),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(He);return}if(Ss==="rename"){if(!Gs.trim()){We(e("sidebarFilesTree.toast.nameRequired")),He();return}if(!n.rename){We(e("sidebarFilesTree.toast.renameNotSupported")),He();return}const lt=Os.path,ct=lt.split("/").slice(0,-1).join("/"),ls=ct?`${ct}/`:"",Ts=Js(`${ls}${Gs.trim()}`);await n.rename(lt,Ts).then(async Ms=>{Ms.success&&(ae.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await Ys(ct),w&&ue(w,lt),($?.path===lt||$?.path.startsWith(`${lt}/`))&&(w&&I(w,null),Qe(""),Ze(null),Rt(""),Wt(null),d&&V(!1))),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(He);return}if(Ss==="delete"){if(!n.delete){We(e("sidebarFilesTree.toast.deleteNotSupported")),He();return}const lt=Os.path,ct=lt.split("/").slice(0,-1).join("/");await n.delete(lt).then(async ls=>{ls.success&&(ae.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await Ys(ct),w&&ue(w,lt),($?.path===lt||$?.path.startsWith(`${lt}/`))&&(w&&I(w,null),Qe(""),Ze(null),Rt(""),Wt(null),d&&V(!1))),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(He);return}He()},[Ss,Os,Gs,n,Ys,d,ue,w,$?.path,I,e]);i.useEffect(()=>{if(!b){Zt([]),es(!1);return}const G=k.trim();if(!G){Zt([]),es(!1);return}let Te=!1;return es(!0),C(b,G,150,{includeHidden:p,respectGitignore:!x,type:"file"}).then(We=>{if(Te)return;const lt=We.filter(ct=>x||!V1(ct.path)).map(ct=>({name:ct.name,path:Js(ct.path),type:"file",extension:ct.extension,relativePath:ct.relativePath}));Zt(lt)}).catch(()=>{Te||Zt([])}).finally(()=>{Te||es(!1)}),()=>{Te=!0}},[b,k,C,p,x]);const Pr=i.useCallback(async(G,Te)=>{if(n.readFile)return(await n.readFile(G,{...Te??{},directory:w||void 0})).content??"";const We=new URLSearchParams({path:G});Te?.allowOutsideWorkspace&&We.set("allowOutsideWorkspace","true"),Te?.outsideFileGrant&&We.set("outsideFileGrant",Te.outsideFileGrant),Te?.optional&&We.set("optional","true"),w&&We.set("directory",w);const He=await Ps(`/api/fs/read?${We.toString()}`,{cache:Te?.optional?"no-store":"default"});if(!He.ok){const lt=await He.json().catch(()=>({error:He.statusText}));throw new Error(lt.error||e("filesView.error.readFileFailed"))}return He.text()},[n,w,e]),fr=i.useCallback(async(G,Te)=>{if(n.statFile){const We=await n.statFile(G,{...Te??{},directory:w||void 0});return{path:We.path,size:We.size,mtimeMs:We.mtimeMs}}return null},[n,w]);i.useEffect(()=>{if(!w||!n.statFile||Ee.length===0)return;let G=!1;const Te=[...Ee];return Promise.all(Te.map(async We=>{try{const He=await n.statFile?.(We,{directory:w||void 0});!G&&He&&!He.isFile&&ue(w,We)}catch(He){!G&&Zu(He)&&ue(w,We)}})),()=>{G=!0}},[n,Ee,ue,w]);const yr=i.useMemo(()=>Ce.length>So?`${Ce.slice(0,So)}
31
+
32
+ … truncated …`:Ce,[Ce]),yn=Et!==yr,mr=i.useCallback(async()=>{if(!$||!n.writeFile)return ae.error(e("filesView.toast.savingNotSupported")),!1;if(!yn)return!0;if(Et===""&&Ce!==""&&rs!==$.path)return console.warn(`[saveDraft] refusing to save empty draft for "${$.path}" (${Ce.length} bytes were expected). The file may have been read during a concurrent write (O_TRUNC race). Try again after content finishes loading if the save was intentional.`),!1;ts(!0);try{const G=z1(Et,as);return(await n.writeFile($.path,G))?.success?(Qe(Et),$?.path&&fl($.path)&&(Yt.current=Et,$t.current=Et),fr($.path).then(We=>{We&&(wt.current=We)}).catch(()=>{}),!0):(ae.error(e("filesView.toast.writeFileFailed")),!1)}catch(G){return ae.error(G instanceof Error?G.message:e("filesView.toast.saveFailed")),!1}finally{ts(!1)}},[Et,Ce,n,yn,as,rs,fr,$,e]);i.useEffect(()=>{if(!yn){kt(null);return}const G=Te=>hn.current?(hn.current=!1,!0):($s(!0),Cs.current=Te,!1);return kt(G),()=>{Re.getState().mainTabGuard===G&&kt(null)}},[yn,kt]),i.useEffect(()=>{try{window.localStorage.setItem(ah,Vt?"true":"false")}catch{}},[Vt]),i.useEffect(()=>{Vt||(ss("idle"),Lt.current&&(clearTimeout(Lt.current),Lt.current=null))},[Vt]);const xo=1500;i.useEffect(()=>{const G=!!($&&n.writeFile);if(!(!Vt||!yn||!G||hs))return Lt.current=setTimeout(()=>{mr().then(Te=>{Te&&(ss("saved"),setTimeout(()=>ss("idle"),2e3))})},xo),()=>{Lt.current&&(clearTimeout(Lt.current),Lt.current=null)}},[Vt,Et,yn,$,n.writeFile,hs,mr]),i.useEffect(()=>{ss("idle")},[$?.path]),i.useEffect(()=>{const G=Te=>{Cc(Te)&&(Te.key.toLowerCase()==="s"?(Te.preventDefault(),Lt.current&&(clearTimeout(Lt.current),Lt.current=null),hs||mr().then(We=>{We&&(ss("saved"),setTimeout(()=>ss("idle"),2e3))})):Te.key.toLowerCase()==="f"&&(Te.preventDefault(),T(!0)))};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[hs,mr]);const bo=i.useCallback(async G=>{const Te=St.current+1;St.current=Te;const We=()=>{if(!w)return!1;const Ms=fn.getState().byRoot[w],Sr=Ms?.selectedPath??Ms?.openPaths[0]??null;return St.current===Te&&Sr===G.path};Ze(null),Rt(""),Wt(null);const He=Ei(G.path),lt=G.path.toLowerCase().endsWith(".svg"),ct=zd(G.path);if(d&&V(!0),r.isDesktop&&He&&!lt){Qe(""),qt(""),Xe(!0);return}if(!r.isDesktop&&He&&!lt){Qe(""),qt(""),Wt(G.path),Xe(!1);return}if(ct){Qe(""),qt(""),Wt(G.path),Xe(!1);return}Xe(!0);const ls=$d(G.path),Ts={allowOutsideWorkspace:t==="editor-only"&&!!w&&!La(G.path,w),outsideFileGrant:ls};await Pr(G.path,Ts).then(Ms=>{if(!We())return;const Sr=lh(Ms);gs($1(Ms)),Qe(Sr),Yt.current=Sr,$t.current=Sr,qt(Sr.length>So?`${Sr.slice(0,So)}
33
+
34
+ … truncated …`:Sr),Wt(G.path),fr(G.path,Ts).then(hr=>{hr&&We()&&(wt.current=hr)}).catch(()=>{})}).catch(Ms=>{if(We()){if(_1(Ms)){if(Xe(!1),w&&I(w,null),Ze(null),Qe(""),qt(""),Wt(null),wt.current=null,S.trim().length>0&&N(""),d&&V(!1),w){const hr=[...Ju(G.path,w),G.path];hr.length>0&&be(w,hr);for(const ll of hr)vt.current.has(ll)||Rn(ll)}return}if(Zu(Ms)){w&&ue(w,G.path),Qe(""),qt(""),Ze(null),wt.current=null,d&&V(!1);return}Qe(""),qt(""),Ze(Ms instanceof Error?Ms.message:e("filesView.error.readFileFailed")),wt.current=null}}).finally(()=>{We()&&Xe(!1)})},[be,d,Rn,t,Pr,fr,ue,w,r.isDesktop,S,I,e]),oi=i.useCallback(async(G,Te)=>{if(!w)return;const We=Ju(G,w),He=Te?[...We,G]:We;He.length>0&&be(w,He);const lt=He.map(ct=>{if(!vt.current.has(ct))return Rn(ct)}).filter(Boolean);await Promise.all(lt)},[be,Rn,w]),Bi=i.useCallback((G,Te)=>{const We=Te.findIndex(He=>He.path===G);return We===-1||Te.length<=1?null:Te[We+1]??Te[We-1]??null},[]),dn=i.useCallback(async G=>{if(hn.current)hn.current=!1;else if(yn){$s(!0),js.current=G;return}w&&(I(w,G.path),je(w,G.path),oi(G.path,!1)),Ze(null),Rt(""),Qe(""),Yt.current="",$t.current="",qt(""),Wt(null),d&&V(!0)},[je,oi,yn,d,w,I]);i.useEffect(()=>{$?.path&&oi($.path,!1)},[oi,$?.path]),i.useEffect(()=>{if(!$){St.current+=1,Xe(!1);return}rs!==$.path&&bo($)},[bo,rs,$]);const Gr=i.useRef(yn);Gr.current=yn,i.useEffect(()=>{if(!$?.path||rs!==$.path)return;let G=!1;const Te=window.setInterval(()=>{document.hidden||fr($.path,Y).then(We=>{if(G||!We)return;const He=wt.current;if(!He||He.path!==$.path){wt.current=We;return}const lt=We.mtimeMs!==void 0&&He.mtimeMs!==void 0&&We.mtimeMs!==He.mtimeMs,ct=We.size!==He.size;!lt&&!ct||Gr.current||(wt.current=We,Wt(null))}).catch(()=>{})},2e3);return()=>{G=!0,window.clearInterval(Te)}},[rs,fr,$?.path,Y]);const Vi=i.useCallback(()=>{const G=js.current,Te=Cs.current,We=jn.current;if(js.current=null,Cs.current=null,jn.current=null,hn.current=!0,$s(!1),qt(yr),We){w&&ye(w,We),$?.path===We&&(G?dn(G):(w&&I(w,null),Qe(""),Ze(null),Rt(""),Wt(null),d&&V(!1)));return}if(G){dn(G);return}Te&&(kt(null),Re.getState().setActiveMainTab(Te))},[yr,dn,d,ye,w,$?.path,kt,I]),_i=i.useCallback(async()=>{const G=js.current,Te=Cs.current,We=jn.current;if(!await mr()){hn.current=!1;return}if(js.current=null,Cs.current=null,jn.current=null,hn.current=!0,$s(!1),We){w&&ye(w,We),$?.path===We&&(G?await dn(G):(w&&I(w,null),Qe(""),Ze(null),Rt(""),Wt(null),d&&V(!1)));return}if(G){await dn(G);return}Te&&(kt(null),Re.getState().setActiveMainTab(Te))},[dn,d,ye,w,mr,$?.path,kt,I]),Q=i.useCallback(G=>{const Te=$?.path===G,We=Bi(G,de);if(Te&&yn){$s(!0),js.current=We,jn.current=G;return}if(w&&ye(w,G),!!Te){if(We){dn(We);return}w&&I(w,null),Qe(""),Ze(null),Rt(""),Wt(null),d&&V(!1)}},[Bi,dn,yn,d,de,ye,w,$?.path,I]),ke=i.useCallback(G=>{if(Ee.includes(G))return"open";if(j?.files){const Te=G.startsWith(w+"/")?G.slice(w.length+1):G,We=j.files.find(He=>He.path===Te);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},[Ee,j,w]),Ie=i.useCallback(G=>{if(!j?.files)return null;const Te=G.startsWith(w+"/")?G.slice(w.length+1):G,We=Te?`${Te}/`:"";let He=0,lt=0;for(const ct of j.files)ct.path.startsWith(We)&&((ct.index==="M"||ct.working_dir==="M")&&He++,(ct.index==="A"||ct.working_dir==="?")&&lt++);return He+lt>0?{modified:He,added:lt}:null},[j,w]),$e=i.useCallback(async G=>{const Te=Js(G);w&&(_(w,Te),vt.current.has(Te)||await Rn(Te))},[Rn,w,_]),ft=i.useMemo(()=>({canRename:ws,canCreateFile:Is,canCreateFolder:Vn,canDelete:Ls,canReveal:Dr}),[ws,Is,Vn,Ls,Dr]);function It(G,Te){const We=qe[G]??[];return We.map((He,lt)=>{const ct=He.type==="directory",ls=ct&&oe.includes(He.path),Ts=$?.path===He.path,Ms=lt===We.length-1;return s.jsxs("li",{className:"relative",children:[Te>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ms&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(H1,{node:He,root:w,isExpanded:ls,isActive:Ts,isMobile:d,alwaysShowActions:u,status:ct?void 0:ke(He.path),badge:ct?Ie(He.path):void 0,permissions:ft,downloadFile:n.downloadFile,contextMenuPath:an,setContextMenuPath:Nn,rightClickMenuPath:nn,setRightClickMenuPath:Ge,onSelect:dn,onToggle:$e,onRevealPath:ni,onOpenDialog:cr}),ct&&ls&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[tt[He.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:tt[He.path],children:tt[He.path]}),s.jsxs(ze,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Ys(He.path)},children:[s.jsx(A,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,It(He.path,Te+1)]})]},He.path)})}const Qt=!!($?.path&&Ei($.path)),Jt=!!($?.path&&$.path.toLowerCase().endsWith(".svg")),vs=!!($?.path&&zd($.path)),vr=i.useMemo(()=>Js(Gt?.path??""),[Gt?.path]),Ir=!!(Gt&&vr&&Ae&&Ae===vr&&!Pt&&!Ke&&!Qt&&!vs),Rr=i.useMemo(()=>ac(w,Ae),[Ae,w]),sl=!!($&&(!Qt||Jt)&&!vs&&Ce.length>0),nl=!!($&&Rr.length>0),Yn=!!($&&!Ve&&!Qt&&!vs&&n.writeFile&&Ce.length<=So),Er=!!($?.path&&ef($.path)),vi=!!($?.path&&U1($.path)),ai=!!($?.path&&Rl($.path)),ji=!!($?.path&&fl($.path)),it=!!($&&!Qt&&!vs)&&!Er&&!ji&&!(ai&&ne==="preview"),et=Er&&te==="edit"||ai&&ne==="edit"||vi&&le==="text"||!Er&&!ai&&!vi&&X==="edit",pt=i.useMemo(()=>Ae?hm(Ae):null,[Ae]),[_t,As]=i.useState(null);i.useEffect(()=>{let G=!1;const Te=$?.path;if(!Te||pt){As(null);return}return As(null),Ag(Te).then(We=>{G||As(We)}),()=>{G=!0}},[$?.path,pt]),i.useEffect(()=>{!Yn&&X==="edit"&&H("view")},[Yn,X]);const un="openchamber:files:md-viewer-mode",kn="openchamber:files:html-viewer-mode",Cn="openchamber:files:json-viewer-mode";i.useEffect(()=>{const G=$?.path;if(!G)return;H(q.current[G]??"edit");let Te=$n?"preview":"edit";try{const lt=localStorage.getItem(un);(lt==="preview"||lt==="edit")&&(Te=lt)}catch{}re(me.current[G]??Te);let We=$n?"preview":"edit";try{const lt=localStorage.getItem(kn);(lt==="preview"||lt==="edit")&&(We=lt)}catch{}we(Se.current[G]??We),Me(Be.current[G]??($n?"preview":"edit"));let He=$n?"tree":"text";try{const lt=localStorage.getItem(Cn);(lt==="tree"||lt==="text")&&(He=lt)}catch{}ve(He)},[$?.path,$n]);const zn=i.useCallback(G=>{const Te=$?.path;Te&&(q.current[Te]=G),H(G)},[$?.path]),jr=i.useCallback(G=>{const Te=$?.path;Te&&(me.current[Te]=G),re(G);try{localStorage.setItem(un,G)}catch{}},[$?.path]),Ws=i.useCallback(()=>te,[te]),wo=i.useCallback(G=>{ve(G);try{localStorage.setItem(Cn,G)}catch{}},[]),nd=i.useCallback(G=>{const Te=$?.path;Te&&(Se.current[Te]=G),we(G);try{localStorage.setItem(kn,G)}catch{}},[$?.path]),yo=i.useCallback(G=>{const Te=$?.path;if(Te&&(Be.current[Te]=G),Ht.current&&(clearTimeout(Ht.current),Ht.current=null),Fe.current!==null&&(cancelAnimationFrame(Fe.current),Fe.current=null),G==="edit")qt(Yt.current||Ce),Me(G);else{Yt.current=Et;const We=Te;Me("edit"),Fe.current=requestAnimationFrame(()=>{Fe.current=requestAnimationFrame(()=>{Fe.current=null,!(w&&We&&fn.getState().byRoot[w]?.selectedPath!==We)&&(K(He=>He+1),Me("preview"))})});return}},[Et,Ce,w,$?.path]),rl=i.useCallback(async(G,Te)=>{if(!n.writeFile||Te===$t.current)return!1;if(!(await n.writeFile(G,Te))?.success)return ae.error(e("filesView.toast.writeFileFailed")),!1;Yt.current=Te,$t.current=Te,qt(Te);const He=await fr(G,Y).catch(()=>null);return He&&(wt.current=He),!0},[n,fr,Y,e]);i.useEffect(()=>()=>{Ht.current&&(clearTimeout(Ht.current),Ht.current=null),Fe.current!==null&&(cancelAnimationFrame(Fe.current),Fe.current=null)},[he,$?.path]);const Vh=i.useCallback(G=>{if(Yt.current=G,!$?.path||he!=="preview"||!n.writeFile)return;Ht.current&&clearTimeout(Ht.current);const Te=$.path;Ht.current=setTimeout(()=>{Ht.current=null,rl(Te,G).then(We=>{We&&(Xt(!0),setTimeout(()=>Xt(!1),1500))}).catch(We=>{ae.error(We instanceof Error?We.message:e("filesView.toast.saveFailed"))})},xo)},[he,n.writeFile,rl,$?.path,e]),_h=i.useMemo(()=>ji&&(Yt.current||Et)||Ce,[Et,Ce,ji]),rd=i.useCallback(()=>ne,[ne]);i.useEffect(()=>{const G=We=>{const He=We?"preview":"edit",lt=We?"tree":"text";for(const ct of Ee)q.current[ct]="edit",ef(ct)&&(me.current[ct]=He),Rl(ct)&&(Se.current[ct]=He),fl(ct)&&(Be.current[ct]=He);H("edit"),re(He),we(He),Me(He),ve(lt);try{localStorage.setItem(un,He),localStorage.setItem(kn,He),localStorage.setItem(Cn,lt)}catch{}},Te=We=>{const He=!!We.detail?.enabled;G(He)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",Te),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",Te)}},[Ee]),i.useEffect(()=>{if(!Gt||!w)return;const G=()=>{typeof window>"u"||xs.current===null&&(xs.current=window.requestAnimationFrame(()=>{xs.current=null,gt(Kr=>Kr+1)}))},Te=(Kr,Si)=>{if(Kr.state.doc.length!==Si.length)return!1;if(Si.length===0)return!0;const cl=Math.min(128,Si.length);if(Kr.state.sliceDoc(0,cl)!==Si.slice(0,cl))return!1;const yd=Math.max(0,Si.length-cl);return Kr.state.sliceDoc(yd,Si.length)===Si.slice(yd)},We=Js(Gt.path);if(!We){os(null),bs.current={key:"",attempts:0};return}const He=`${We}:${Gt.line}:${Gt.column??1}`;if(bs.current.key!==He&&(bs.current={key:He,attempts:0}),$?.path!==We){if(us)return;dn(R(We));return}if(Pt||rs!==We)return;if(Ke||Qt||vs){os(null),bs.current={key:"",attempts:0};return}if(!Yn)return;if(X!=="edit"){H("edit");return}const lt=dt.current;if(!lt){G();return}if(!Te(lt,Et)){G();return}const ct=Math.max(1,Math.min(Gt.line,lt.state.doc.lines)),ls=lt.state.doc.line(ct),Ts=Math.max(1,Gt.column||1),Ms=Math.max(0,ls.to-ls.from),Sr=Math.min(Ms,Ts-1),hr=ls.from+Sr;if(!(lt.state.selection.main.head===hr)||bs.current.attempts===0){bs.current.attempts+=1,lt.dispatch({selection:{anchor:hr},effects:hi.scrollIntoView(hr,{y:"center"})}),lt.focus(),G();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const Kr=dt.current;Kr&&(Kr.dispatch({selection:{anchor:hr},effects:hi.scrollIntoView(hr,{y:"center"})}),Kr.focus())}),os(null),bs.current={key:"",attempts:0}},[Yn,us,Et,zt,Ke,Pt,Qt,vs,rs,dn,Gt,w,$?.path,os,X,R]),i.useEffect(()=>{if(!fs||!w)return;const G=Js(fs);if(!G){Es(null);return}if($?.path!==G){if(us)return;dn(R(G));return}if(!(Pt||rs!==G||Ke||Qt||vs)){if(Yn&&X==="edit"){const Te=dt.current;if(!Te)return;Te.focus()}Es(null)}},[Yn,us,Ke,Pt,dn,Qt,vs,rs,fs,w,$?.path,Es,X,R]);const $i=i.useCallback(G=>{if(!d||!G||!G.hasFocus||typeof window>"u")return;const Te=window.visualViewport;if(!Te)return;const We=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,We-(Te.offsetTop+Te.height))<=0)return;const lt=G.state.selection.main.head,ct=G.coordsAtPos(lt);if(!ct)return;const ls=Math.round(Te.offsetTop+Te.height),Ms=ct.bottom+20-ls;Ms<=0||(G.scrollDOM.scrollTop+=Ms)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const G=()=>{window.requestAnimationFrame(()=>{$i(dt.current)})},Te=window.visualViewport;return Te?.addEventListener("resize",G),Te?.addEventListener("scroll",G,{passive:!0}),document.addEventListener("selectionchange",G),()=>{Te?.removeEventListener("resize",G),Te?.removeEventListener("scroll",G),document.removeEventListener("selectionchange",G)}},[d,$i]),i.useEffect(()=>{if(!Yn||X!=="edit"||d)return;const G=gi("open_go_to_line",qs),Te=We=>{const He=We.target;if(He?.closest('[role="dialog"]'))return;const lt=!!He?.closest(".cm-editor");He?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!lt||!document.activeElement?.closest(".cm-editor")||da(We,G)&&(We.preventDefault(),Ks(!0))};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[Yn,d,qs,X]);const Ho=Re(G=>G.editorFontSize),id=i.useMemo(()=>{if(!$?.path)return[Xl(o,{fontSize:Ho})];const G=Ri($.path),Te=[Xl(o,G?{syntaxColors:!1,fontSize:Ho}:{fontSize:Ho})],We=pt??_t;return We&&Te.push(We),G&&Te.push(Lm({language:G,themeName:o.metadata.id,theme:pm(o)})),v&&Te.push(hi.lineWrapping),d&&Te.push(hi.updateListener.of(He=>{He.view.hasFocus&&(He.selectionSet||He.focusChanged||He.viewportChanged||He.geometryChanged)&&window.requestAnimationFrame(()=>{$i(He.view)})})),Te},[o,$?.path,pt,_t,v,d,$i,Ho]),od=i.useMemo(()=>({light:_e.metadata.id,dark:Le.metadata.id}),[_e.metadata.id,Le.metadata.id]),Go=$?.path&&Qt&&!r.isDesktop&&!Jt?`${$.path}|${Y.allowOutsideWorkspace?"outside":"workspace"}|${Y.outsideFileGrant??""}`:"",Ko=$?.path&&vs?`${$.path}|${Y.allowOutsideWorkspace?"outside":"workspace"}|${Y.outsideFileGrant??""}`:"",qo=$?.path&&ai&&ne==="preview"&&!r.isVSCode?$.path:"",il=e("filesView.error.readFileFailed"),{readyKey:ad,nonce:ld}=El(Go,Ze,il),{readyKey:cd,nonce:$h}=El(qo,Ze,il),{readyKey:dd,nonce:ud}=El(Ko,Ze,il),fd=!!(Go&&ad!==Go),zh=!!(qo&&cd!==qo),md=!!(Ko&&dd!==Ko),hd=$?.path&&Qt?r.isDesktop?Jt?`data:${Wd($.path)};utf8,${encodeURIComponent(Ce)}`:Bt:Jt?`data:${Wd($.path)};utf8,${encodeURIComponent(Ce)}`:ad===Go?Ii().authenticatedAsset("/api/fs/raw",{path:$.path,allowOutsideWorkspace:Y.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Y.outsideFileGrant,directory:w||void 0}):"":"",pd=$?.path&&vs&&dd===Ko?Ii().authenticatedAsset("/api/fs/raw",{path:$.path,allowOutsideWorkspace:Y.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Y.outsideFileGrant,directory:w||void 0}):"",gd=i.useCallback(G=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:pd,className:"h-full w-full border-0",title:G.name},ud)}),[pd,ud]);i.useEffect(()=>{let G=!1;return(async()=>{if(!r.isDesktop||!$?.path||!Qt||Jt){Ot.current&&(URL.revokeObjectURL(Ot.current),Ot.current=""),Rt("");return}Ze(null),Ot.current&&(URL.revokeObjectURL(Ot.current),Ot.current=""),await(n.readFileBinary?n.readFileBinary($.path,Y).then(He=>He.dataUrl):(async()=>{const He=await Ps("/api/fs/raw",{query:{path:$.path,allowOutsideWorkspace:Y.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Y.outsideFileGrant,directory:w||void 0}});if(!He.ok)throw new Error(e("filesView.error.readFileFailed"));const lt=await He.blob(),ct=URL.createObjectURL(lt);return G?(URL.revokeObjectURL(ct),""):(Ot.current=ct,ct)})()).then(He=>{G||(Rt(He),Wt($.path))}).catch(He=>{Ot.current&&(URL.revokeObjectURL(Ot.current),Ot.current=""),G||(Rt(""),Ze(He instanceof Error?He.message:e("filesView.error.readFileFailed")),Wt(null))}).finally(()=>{G||Xe(!1)})})(),()=>{G=!0}},[n,Qt,Jt,w,r.isDesktop,$?.path,Y,e]),i.useEffect(()=>()=>{Ot.current&&(URL.revokeObjectURL(Ot.current),Ot.current="")},[]);const Wh=i.useCallback(()=>Ns(null),[]),Uh=i.useMemo(()=>_m({drafts:tr,editingDraftId:wn,commentText:cn,onTextChange:gn,selection:ys,isDragging:at,fileLabel:$?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:G=>({start:G.startLine,end:G.endLine}),onSave:Oi,onCancel:()=>{ln(null),Ur()},onEdit:G=>{Hr(G),ln({start:G.startLine,end:G.endLine})},onDelete:ii}),[Ur,cn,ii,wn,tr,Oi,at,ys,$?.path,gn,Hr]),xd=i.useCallback((G,Te)=>s.jsx("div",{className:"h-full",children:s.jsx(ep,{file:{name:G.name,contents:Te,lang:Ri(G.path)||void 0},options:{disableFileHeader:!0,overflow:v?"wrap":"scroll",theme:od,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,od,v]),ol=({exitFullscreenOnly:G=!1,layout:Te="floating"}={})=>{if(!$)return null;const He=Te==="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=(ct,ls)=>s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:ls})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:ct})]});return s.jsxs("div",{className:He,children:[Yn&&et&&s.jsxs(s.Fragment,{children:[hs?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):Vt&&Nt==="saved"&&!yn?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(A,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):yn?lt(e(Vt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${ml()}+S`}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{mr()},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(Vt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${ml()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${ml()}+S`}),children:s.jsx(A,{name:"save-3",className:"size-4"})})):null,lt(e(Vt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>Fs(ct=>!ct),className:Pe("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",Vt?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(Vt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(Vt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:Vt?s.jsx(A,{name:"file-check-fill",className:"size-4"}):s.jsx(A,{name:"file-check",className:"size-4"})}))]}),s.jsxs(tn,{onOpenChange:ee,children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.openInDesktopApp"),"aria-label":e("filesView.editor.openInDesktopApp"),children:s.jsx(A,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(en,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[_n.map(ct=>s.jsxs(ms,{className:"flex items-center gap-2",onClick:()=>{zr(ct)},children:[s.jsx(E1,{label:ct.label,iconDataUrl:ct.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:ct.label})]},ct.id)),bn?s.jsxs(ms,{className:"flex items-center gap-2",onClick:()=>{si(!0)},children:[s.jsx(A,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!Qt&&!vs&&s.jsxs(s.Fragment,{children:[lt(e(v?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>O(!v),className:Pe("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",v?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(v?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(A,{name:"text-wrap",className:"size-4"})})),X==="edit"&&s.jsxs(s.Fragment,{children:[lt(e("filesView.editor.findInFile"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:ct=>{T(!B),ct.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.findInFile"),children:s.jsx(A,{name:"search",className:"size-4"})})),lt(e("filesView.editor.goToLine"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:ct=>{Ks(ls=>!ls),ct.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.goToLine"),children:s.jsx(A,{name:"menu-fold-2",className:"size-4"})})),s.jsx(T1,{open:rn,onOpenChange:Ks,view:dt.current,variant:"inline"})]})]}),it&&Yn&&!vi&&!ai&&s.jsx(fa,{currentMode:X==="view"?"preview":"edit",onToggle:()=>{zn(X==="view"?"edit":"view")}}),Er&&lt(e(Ws()==="preview"?"filesView.editor.switchToEditMode":"filesView.editor.switchToPreviewMode"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>jr(Ws()==="preview"?"edit":"preview"),className:Pe("size-6 p-0 transition-colors hover:bg-[var(--interactive-hover)] focus-visible:bg-[var(--interactive-hover)] active:bg-[var(--interactive-hover)]",Ws()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)] focus-visible:bg-[var(--interactive-selection)] active:bg-[var(--interactive-selection)]":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(Ws()==="preview"?"filesView.editor.switchToEditMode":"filesView.editor.switchToPreviewMode"),"aria-label":e(Ws()==="preview"?"filesView.editor.switchToEditMode":"filesView.editor.switchToPreviewMode"),children:s.jsx(A,{name:Ws()==="preview"?"eye":"eye-off",className:"size-4"})})),Rl($?.path??"")&&s.jsx(fa,{currentMode:rd(),onToggle:()=>{nd(rd()==="preview"?"edit":"preview")}}),Er&&Ws()==="preview"&&ri&&s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent","aria-label":e(ot?"filesView.tts.stopSpeaking":"filesView.tts.readAloud"),onClick:()=>{ot?Je():Ce.trim()&&bt(Ce)},children:ot?s.jsx(A,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"volume-up",className:"size-4"})})}),s.jsx(Dt,{sideOffset:8,children:e(ot?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),ji&&s.jsxs(s.Fragment,{children:[s.jsx(fa,{currentMode:he,onToggle:()=>yo(he==="preview"?"edit":"preview")}),he==="preview"&&s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{const ct=st.current?.getXml();if(Ht.current&&(clearTimeout(Ht.current),Ht.current=null),$?.path&&ct){if(!await rl($.path,ct))return;Xt(!0),setTimeout(()=>Xt(!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:cs?s.jsx(A,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"save-3",className:"size-4"})})]}),vi&&lt(e(le==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>wo(le==="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(le==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:le==="tree"?s.jsx(A,{name:"code-sslash",className:"size-4"}):s.jsx(A,{name:"node-tree",className:"size-4"})})),sl&&lt(e("filesView.editor.copyFileContents"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await xr(Ce)).ok?(ks(!0),xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{ks(!1)},1200)):ae.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFileContents"),"aria-label":e("filesView.editor.copyFileContents"),children:ps?s.jsx(A,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"clipboard",className:"size-4"})})),nl&&lt(e("filesView.editor.copyFilePathTitle",{path:Rr}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await xr(Rr)).ok?(Rs(!0),rt.current!==null&&window.clearTimeout(rt.current),rt.current=window.setTimeout(()=>{Rs(!1)},1200)):ae.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:Rr}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:Rr}),children:zs?s.jsx(A,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&&lt(e("filesView.editor.saveFile"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{const ct=n.downloadFile;ct&&ct($.path).catch(ls=>{console.error("Download failed:",ls),ae.error(e("sidebarFilesTree.toast.operationFailed"))})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.saveFile"),"aria-label":e("filesView.editor.saveFile"),children:s.jsx(A,{name:"download",className:"size-4"})})),G?lt(e("filesView.editor.exitFullscreen"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>E(!1),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.exitFullscreen"),"aria-label":e("filesView.editor.exitFullscreen"),children:s.jsx(A,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&&lt(e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>E(!P),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:P?s.jsx(A,{name:"fullscreen-exit",className:"size-4"}):s.jsx(A,{name:"fullscreen",className:"size-4"})}))]})},al=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:us,onOpenChange:G=>{G||$s(!0)},children:s.jsxs(Vs,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(sn,{children:[s.jsx(Hs,{children:e("filesView.unsaved.title")}),s.jsx(mn,{children:e("filesView.unsaved.description")})]}),s.jsxs(br,{children:[s.jsx(ze,{variant:"outline",onClick:()=>{_i()},disabled:hs,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:e("filesView.unsaved.saveChanges")}),s.jsx(ze,{variant:"destructive",onClick:Vi,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:Pe("flex flex-col flex-shrink-0",g&&"border-b border-border/40"),children:[g?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&D&&s.jsx("button",{type:"button",onClick:()=>V(!1),"aria-label":e("filesView.editor.back"),className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(A,{name:"arrow-left-s",className:"size-5"})}),d?$?s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":e("filesView.editor.openFilesAria"),children:[s.jsx(ei,{filePath:$.path,extension:$.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Xu,{name:$.name}),s.jsx(A,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(en,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:de.map(G=>{const Te=$?.path===G.path;return s.jsxs(ms,{onSelect:We=>{if(We.target.closest("[data-close-open-file]")){We.preventDefault();return}Te||dn(G)},className:Pe("flex min-w-0 items-center justify-between gap-2 overflow-hidden",Te&&"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(ei,{filePath:G.path,extension:G.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Xu,{name:G.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:We=>{We.preventDefault(),We.stopPropagation()},onClick:We=>{We.preventDefault(),We.stopPropagation(),Q(G.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:G.name}),children:s.jsx(A,{name:"close",className:"size-3.5"})})]},G.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):de.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[se.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"}),se.right&&s.jsx("div",{className:"pointer-events-none absolute right-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-l from-background to-transparent"}),s.jsx("div",{ref:F,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:de.map(G=>{const Te=$?.path===G.path;return s.jsxs("div",{title:ac(w,G.path),className:Pe("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",Te?"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(ei,{filePath:G.path,extension:G.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{Te||dn(G)},className:"max-w-[12rem] truncate text-left",children:G.name}),s.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),Q(G.path)},className:Pe("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Te&&!u&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:G.name}),children:s.jsx(A,{name:"close",className:"size-3.5"})})]},G.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,pn&&!d&&$?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:[Rr?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Rr,children:Rr}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:ol({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[$&&!B&&!(pn&&!d)&&s.jsx("div",{ref:L,className:"absolute right-3 top-3 z-30",onMouseLeave:()=>{M.current>0||U(!1)},children:W?ol():s.jsxs("div",{className:"flex items-center gap-1",children:[Er?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>jr(Ws()==="preview"?"edit":"preview"),className:Pe("size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 shadow-sm transition-colors",Ws()==="preview"?"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)] hover:bg-[var(--interactive-selection)]":"text-muted-foreground hover:text-foreground"),"aria-label":e(Ws()==="preview"?"filesView.editor.switchToEditMode":"filesView.editor.switchToPreviewMode"),title:e(Ws()==="preview"?"filesView.editor.switchToEditMode":"filesView.editor.switchToPreviewMode"),children:s.jsx(A,{name:Ws()==="preview"?"eye":"eye-off",className:"size-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:e(Ws()==="preview"?"filesView.editor.switchToEditMode":"filesView.editor.switchToPreviewMode")})]}):null,s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex",onMouseEnter:()=>U(!0),children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>U(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":e("filesView.editor.showControlsAria"),title:e("filesView.editor.controlsTitle"),children:s.jsx(A,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})]})}),s.jsx(On,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:$?Pt||fd||md?h?s.jsx("div",{className:"p-3"}):s.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.loading")]}):Ke?s.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:Ke}):Qt?s.jsx("div",{className:"flex h-full items-center justify-center p-3",children:s.jsx("img",{src:hd,alt:$?.name??e("filesView.editor.imageAltFallback"),className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},ld)}):vs?gd($):$&&ji&&he==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(I1,{ref:st,xml:_h,onChange:Vh},`${$.path}:${z}`)}):$&&vi&&le==="tree"?s.jsx(on,{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(Dg,{jsonString:Ce,maxHeight:"100%",initiallyExpandedDepth:2})})}):$&&Er&&Ws()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-3",children:[Ce.length>500*1024&&s.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:e("filesView.warning.largeFilePreviewLimited",{sizeKb:Math.round(Ce.length/1024)})}),s.jsx(on,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(no,{content:Ce,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):$&&ai&&ne==="preview"?zh?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&&cd===qo?(()=>{const G=$.path.split("/").map(Te=>encodeURIComponent(Te)).join("/");return Ii().authenticatedAsset(`/api/fs/serve${G.startsWith("/")?G:`/${G}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const G=$.path.substring(0,$.path.lastIndexOf("/")+1);return G?Ce.replace(/<head([^>]*)>/i,`<head$1><base href="${G}">`):Ce})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")},$h)}):$&&it&&X==="view"?xd($,Et):s.jsxs("div",{className:Pe("relative h-full",Ir&&"overflow-hidden"),ref:jt,children:[s.jsx("div",{className:Pe("h-full",Ir&&"invisible"),children:s.jsx(Zl,{value:Et,onChange:qt,readOnly:!Yn,vimMode:er==="vim",extensions:id,className:"h-full",blockWidgets:Uh,onViewReady:G=>{dt.current=G,gt(Te=>Te+1),window.requestAnimationFrame(()=>{$i(G)})},onViewDestroy:()=>{dt.current&&(dt.current=null),gt(G=>G+1)},enableSearch:!0,searchOpen:B,onSearchOpenChange:T,highlightLines:ys?{start:Math.min(ys.start,ys.end),end:Math.max(ys.start,ys.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(G,Te,We)=>{if(!(We instanceof MouseEvent)||We.button!==0)return!1;We.preventDefault();const He=G.state.doc.lineAt(Te.from).number;if(ys&&!We.shiftKey&&Math.min(ys.start,ys.end)===He&&Math.max(ys.start,ys.end)===He)return ln(null),Ur(),dr.current=!1,J.current=null,ut(!1),!0;if(d&&ys&&!We.shiftKey){const lt=Math.min(ys.start,ys.end,He),ct=Math.max(ys.start,ys.end,He);return ln({start:lt,end:ct}),dr.current=!1,J.current=null,ut(!1),!0}if(dr.current=!0,J.current=He,ut(!0),ys&&We.shiftKey){const lt=Math.min(ys.start,He),ct=Math.max(ys.end,He);ln({start:lt,end:ct})}else ln({start:He,end:He});return!0},mouseover:(G,Te,We)=>{if(!(We instanceof MouseEvent)||We.buttons!==1||!dr.current||J.current===null)return!1;const He=G.state.doc.lineAt(Te.from).number,lt=Math.min(J.current,He),ct=Math.max(J.current,He);return ln({start:lt,end:ct}),ut(!0),!1},mouseup:()=>(dr.current=!1,J.current=null,ut(!1),!1)}}})}),Ir&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]}):s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:e("filesView.editor.pickFileFromTree")})})]})]}),Hh=!!(w&&qe[w]),bd=w?tt[w]:null,wd=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(A,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(Ln,{ref:y,value:S,onChange:G=>N(G.target.value),placeholder:e("filesView.tree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),S.trim().length>0&&s.jsx("button",{type:"button","aria-label":e("filesView.tree.search.clearAria"),className:"absolute right-2 top-2 inline-flex size-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{N(""),y.current?.focus()},children:s.jsx(A,{name:"close",className:"size-4"})})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>cr("createFile",{path:b,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFileTitle"),"aria-label":e("filesView.tree.actions.newFileTitle"),children:s.jsx(A,{name:"file-add",className:"size-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>cr("createFolder",{path:b,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFolderTitle"),"aria-label":e("filesView.tree.actions.newFolderTitle"),children:s.jsx(A,{name:"folder-add",className:"size-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(ze,{variant:"ghost",size:"sm",onClick:()=>{ur()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(A,{name:"refresh",className:"size-4"})})})}),s.jsx(Dt,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx(On,{outerClassName:"flex-1 min-h-0",className:Pe("py-2",d?"px-3":"px-2"),children:s.jsx("ul",{className:"flex flex-col",children:ns?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):Ut.length>0?Ut.map(G=>{const Te=$?.path===G.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{dn(G)},className:Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Te?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[ch(G.path,G.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:G.path,children:G.relativePath??G.path})]})},G.path)}):bd?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:bd}),s.jsxs(ze,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ur()},children:[s.jsx(A,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):Hh?It(w,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),Gh=t==="full"&&P&&$&&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:ol({exitFullscreenOnly:!0})}),s.jsx(On,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:Pt||fd||md?h?s.jsx("div",{className:"p-4"}):s.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):Ke?s.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:Ke}):Qt?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("img",{src:hd,alt:$.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},ld)}):vs?gd($):Er&&Ws()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-4",children:[Ce.length>500*1024&&s.jsx("div",{className:"mb-3 rounded-md border border-status-warning/20 bg-status-warning/10 px-3 py-2 text-sm text-status-warning",children:e("filesView.warning.largeFilePreviewLimited",{sizeKb:Math.round(Ce.length/1024)})}),s.jsx(on,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(no,{content:Ce,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):it&&X==="view"?xd($,Et):s.jsxs("div",{className:Pe("relative h-full",Ir&&"overflow-hidden"),children:[s.jsx("div",{className:Pe("h-full",Ir&&"invisible"),children:s.jsx(Zl,{value:Et,onChange:qt,readOnly:!Yn,vimMode:er==="vim",extensions:id,className:"h-full",onViewReady:G=>{dt.current=G,window.requestAnimationFrame(()=>{$i(G)})},onViewDestroy:()=>{dt.current&&(dt.current=null)}})}),Ir&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]})})]})});return s.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[s.jsx(G1,{activeDialog:Ss,dialogData:Os,dialogInputValue:Gs,onDialogInputChange:Pn,isDialogSubmitting:Bn,onDialogSubmit:go,onClose:Wh,inputRef:Ft}),Gh,d?D?al:wd: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:al})}):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:wd}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:al})]})]})};function K1(t){return t+1}const Ar=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Ml=(t,e)=>{const n=Ar(t),r=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},q1=(t,e,n)=>Ml(Ml(Ml(t,".opencode"),"plans"),`${e}-${n}.md`),Y1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,Q1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},J1=(t,e)=>{const n=Ar(e.currentDirectory),r=Ar(e.homeDirectory),o=Ar(t);return n&&o.startsWith(n+"/")?o.slice(n.length+1):r&&o===r?"~":r&&o.startsWith(r+"/")?`~${o.slice(r.length)}`:o},X1=(t,e,n)=>{const r=Ar(t.trim());if(!r)return null;const o=n?e.find(c=>c.id===n)??null:null;if(o?.path){const c=Ar(o.path);if(r===c||r.startsWith(`${c}/`))return{id:o.id,path:o.path}}const a=e.filter(c=>{const l=Ar(c.path);return r===l||r.startsWith(`${l}/`)}).sort((c,l)=>Ar(l.path).length-Ar(c.path).length)[0];return a?{id:a.id,path:a.path}:null},uh=({targetPath:t=null})=>{const{t:e}=yt(),n=mt(ce=>ce.currentSessionId),r=mt(ce=>ce.createSession),o=mt(ce=>ce.initializeNewOpenChamberSession),a=mt(ce=>ce.sendMessage),c=mt(ce=>ce.setCurrentSession),l=Ec(),d=Xs(ce=>ce.homeDirectory),f=kc(ce=>ce.planModeEnabled),m=Ds(ce=>ce.projects),u=Ds(ce=>ce.activeProjectId),p=vn(ce=>ce.directories),x=wi()??"",b=Re(ce=>ce.setActiveMainTab),w=Re(ce=>ce.setSessionSwitcherOpen),g=Zn(),{isMobile:h}=$r(),{currentTheme:C}=yi(),j=i.useMemo(()=>n?l.find(ce=>ce.id===n)??null:null,[n,l]),S=i.useMemo(()=>{const ce=typeof j?.directory=="string"?j.directory:"";return Ar(ce||"")},[j?.directory]),N=i.useMemo(()=>Ar(x||S),[x,S]),k=i.useMemo(()=>X1(N,m,u),[u,N,m]),y=i.useMemo(()=>k?p.get(k.path)?.isGitRepo===!0:!1,[k,p]),[D,V]=i.useState(null),[v,O]=i.useState(!1),[P,E]=i.useState(null),B=i.useMemo(()=>!P||!S||!d?P:J1(P,{currentDirectory:S,homeDirectory:d}),[P,S,d]),[T,W]=i.useState(""),{isPlaying:U,play:L,stop:M}=mm(),ee=is(ce=>ce.showMessageTTSButtons),[ie,X]=i.useState(null),H=i.useMemo(()=>B&&B.split("/").pop()||e("planView.file.defaultName"),[B,e]),te=i.useMemo(()=>T.trim()&&Tg(T).title||e("planView.title.default"),[T,e]),re=i.useMemo(()=>te.trim()||e("planView.title.default"),[te,e]),[le,ve]=i.useState(!1),[ne,we]=i.useState(!1),[he,Me]=i.useState("edit"),z=i.useRef(null),[K,q]=i.useState(null),me=i.useRef(null),Se=i.useRef(null),Be="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const ce=localStorage.getItem(Be);if(!ce)return;const Ue=JSON.parse(ce);(Ue==="preview"||Ue==="edit")&&Me(Ue)}catch{}},[]);const _e=i.useCallback(ce=>{Me(ce);try{localStorage.setItem(Be,JSON.stringify(ce))}catch{}},[]),Le=i.useRef(!1),pe=i.useRef(null),[Ee,ge]=i.useState(!1);i.useEffect(()=>{const ce=()=>{Le.current=!1,pe.current=null,ge(!1)};return document.addEventListener("mouseup",ce),()=>document.removeEventListener("mouseup",ce)},[]);const oe=i.useCallback((ce,Ue)=>{const qe=ce.split(`
35
+ `),Ye=Math.max(1,Ue.start),tt=Math.min(qe.length,Ue.end);return Ye>tt?"":qe.slice(Ye-1,tt).join(`
36
+ `)},[]),je=Fm({source:"plan",fileLabel:H,language:P&&Ri(P)||"markdown",getCodeForRange:ce=>oe(T,Om(ce)),toStoreRange:ce=>({startLine:ce.start,endLine:ce.end}),fromDraftRange:ce=>({start:ce.startLine,end:ce.endLine})}),{drafts:ye,commentText:ue,setCommentText:De,editingDraftId:I,setSelection:_,saveComment:be,cancel:R,reset:de,startEdit:fe,deleteDraft:$}=je;i.useEffect(()=>{q(null),de()},[T,de]),i.useEffect(()=>{_(K)},[K,_]);const Ae=i.useCallback(()=>{q(null),R()},[R]),Ve=i.useCallback((ce,Ue)=>{Ue&&q(Ue),be(ce,Ue??K??void 0),q(null)},[K,be]);i.useEffect(()=>{if(!K)return;const ce=qe=>{const Ye=qe.target;Ye.closest('[data-comment-card="true"]')||Ye.closest('[data-comment-input="true"]')||Ye.closest(".oc-block-widget")||Ye.closest(".cm-gutterElement")||Ye.closest("[data-sonner-toast]")||Ye.closest("[data-sonner-toaster]")||ue.trim()||(q(null),R())},Ue=window.setTimeout(()=>{document.addEventListener("click",ce)},100);return()=>{window.clearTimeout(Ue),document.removeEventListener("click",ce)}},[R,ue,I,h,K]);const Ne=Re(ce=>ce.editorFontSize),Y=i.useMemo(()=>{const ce=P?Ri(P):null,Ue=!!ce&&ce!=="markdown",qe=[Xl(C,Ue?{syntaxColors:!1,fontSize:Ne}:{fontSize:Ne})],Ye=hm(P||"plan.md");return Ye&&qe.push(Ye),Ue&&ce&&qe.push(Lm({language:ce,themeName:C.metadata.id,theme:pm(C)})),qe.push(hi.lineWrapping),qe},[C,P,Ne]);i.useEffect(()=>{if(!f&&!t){E(null),W(""),ve(!1);return}let ce=!1;const Ue=async Ye=>{if(g.files?.readFile)return(await g.files.readFile(Ye))?.content??"";const tt=zo()?.files;if(tt?.readFile)return(await tt.readFile(Ye,{optional:!0}))?.content??"";const xt=await Ps(`/api/fs/read?path=${encodeURIComponent(Ye)}&optional=true`,{cache:"no-store"});if(!xt.ok)throw new Error(`Failed to read plan file (${xt.status})`);return xt.text()};return(async()=>{if(E(null),W(""),X(null),t){ve(!0);try{const Ye=await Ue(t);if(ce)return;E(t),W(Ye)}catch{if(ce)return;E(null),W("")}finally{ce||ve(!1)}return}if(!j?.slug||!j?.time?.created||!S){E(null),W("");return}ve(!0);try{const Ye=q1(S,j.time.created,j.slug),tt=Q1(Y1(j.time.created,j.slug),d||null);let xt=null,vt=null;try{vt=await Ue(Ye),xt=Ye}catch{}if(!xt)try{vt=await Ue(tt),xt=tt}catch{}if(ce)return;if(!xt||vt===null){E(null),W("");return}E(xt),W(vt)}catch{if(ce)return;E(null),W("")}finally{ce||ve(!1)}})(),()=>{ce=!0}},[d,f,g.files,S,j?.slug,j?.time?.created,t]),i.useEffect(()=>{if(!P){X(null);return}const ce=window.setTimeout(async()=>{X(null);try{if(g.files?.writeFile){if(!(await g.files.writeFile(P,T))?.success)throw new Error(e("planView.error.writeFailed"))}else{const Ue=await Ps("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:P,content:T})});if(!Ue.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:Ue.status}))}}catch(Ue){X(Ue instanceof Error?Ue.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(ce)}},[T,P,g.files,e]),i.useEffect(()=>()=>{z.current!==null&&window.clearTimeout(z.current)},[]);const F=i.useCallback(()=>{b("chat"),w(!1)},[b,w]),se=i.useCallback(async ce=>{if(!k||!D)return;const Ue=await Fn(D.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:re}),Ye=[{synthetic:!0,text:await Fn(D.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:re,plan_path:P??""})}];O(!0);try{F();let tt=null,xt=k.path;if(D.target==="worktree"){if(!y)return;const Tt=await cm(k.path,dm());if(!Tt?.id)return;tt=Tt.id,xt=Tt.path}else{const Tt=await r(void 0,k.path,null);if(!Tt?.id)return;tt=Tt.id,xt=Tt.directory??k.path,o(Tt.id,is.getState().agents??[])}if(!tt)return;const vt=Dc.getState();vt.saveSessionModelSelection(tt,ce.providerID,ce.modelID),ce.agent.trim()&&(vt.saveSessionAgentSelection(tt,ce.agent),vt.saveAgentModelForSession(tt,ce.agent,ce.providerID,ce.modelID),vt.saveAgentModelVariantForSession(tt,ce.agent,ce.providerID,ce.modelID,ce.variant||void 0)),c(tt,xt);const Mt=ce.runAsGoal===!0?[`Implement the plan "${re}" end-to-end${P?` (plan file: ${P})`:""}.`,"Re-read that file for full details — it is the source of truth.","",T].join(`
37
+ `):null;Pg.getState().setArmed(ce.runAsGoal===!0,Mt),await a(Ue,ce.providerID,ce.modelID,ce.agent.trim()||void 0,void 0,void 0,Ye,ce.variant||void 0),V(null)}finally{O(!1)}},[y,T,r,k,o,D,P,F,a,re,c]),Oe=i.useMemo(()=>_m({drafts:ye,editingDraftId:I,commentText:ue,onTextChange:De,selection:K,isDragging:Ee,fileLabel:H,newWidgetId:"plan-new-comment-input",mapDraftToRange:ce=>({start:ce.startLine,end:ce.endLine}),onSave:Ve,onCancel:Ae,onEdit:ce=>{fe(ce),q({start:ce.startLine,end:ce.endLine})},onDelete:$}),[ue,$,I,Ae,Ve,Ee,K,ye,H,De,fe]);return s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"typography-ui-label font-medium truncate",children:te}),ie?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:ie,children:e("planView.error.saveFailed")}):null]}),P?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(tn,{children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.improvePlanAria"),disabled:!T.trim(),children:s.jsx(A,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(Dt,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(en,{align:"end",children:[s.jsx(ms,{onClick:()=>V({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(ms,{onClick:()=>V({action:"improve",target:"worktree"}),disabled:!y,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(tn,{children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.implementPlanAria"),disabled:!T.trim(),children:s.jsx(A,{name:"code-ai",className:"size-4"})})})}),s.jsx(Dt,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(en,{align:"end",children:[s.jsx(ms,{onClick:()=>V({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(ms,{onClick:()=>V({action:"implement",target:"worktree"}),disabled:!y,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(fa,{currentMode:he,onToggle:()=>_e(he==="preview"?"edit":"preview")}),he==="preview"&&ee&&s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(U?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{U?M():T.trim()&&L(T)},children:U?s.jsx(A,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(Dt,{sideOffset:8,children:e(U?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx(ze,{variant:"ghost",size:"sm",onClick:async()=>{(await xr(T)).ok&&(we(!0),z.current!==null&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{we(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:ne?s.jsx(A,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(A,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(Wm,{open:D!==null,onOpenChange:ce=>{!ce&&!v&&V(null)},target:D?.target??"session",projectDirectory:k?.path??null,submitting:v,allowRunAsGoal:!0,onConfirm:se}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(On,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:le?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:he==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(on,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("planView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("planView.error.switchToEditMode")})]}),children:s.jsx(no,{content:T,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:Se,children:s.jsx(Zl,{value:T,onChange:W,readOnly:!1,className:"h-full",extensions:Y,onViewReady:ce=>{me.current=ce},onViewDestroy:()=>{me.current=null},blockWidgets:Oe,highlightLines:K?{start:Math.min(K.start,K.end),end:Math.max(K.start,K.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(ce,Ue,qe)=>{if(!(qe instanceof MouseEvent)||qe.button!==0)return!1;qe.preventDefault();const Ye=ce.state.doc.lineAt(Ue.from).number;if(K&&!qe.shiftKey&&Math.min(K.start,K.end)===Ye&&Math.max(K.start,K.end)===Ye)return q(null),R(),Le.current=!1,pe.current=null,ge(!1),!0;if(h&&K&&!qe.shiftKey){const tt=Math.min(K.start,K.end,Ye),xt=Math.max(K.start,K.end,Ye);return q({start:tt,end:xt}),Le.current=!1,pe.current=null,ge(!1),!0}if(Le.current=!0,pe.current=Ye,ge(!0),K&&qe.shiftKey){const tt=Math.min(K.start,Ye),xt=Math.max(K.end,Ye);q({start:tt,end:xt})}else q({start:Ye,end:Ye});return!0},mouseover:(ce,Ue,qe)=>{if(!(qe instanceof MouseEvent)||qe.buttons!==1||!Le.current||pe.current===null)return!1;const Ye=ce.state.doc.lineAt(Ue.from).number,tt=Math.min(pe.current,Ye),xt=Math.max(pe.current,Ye);return q({start:tt,end:xt}),ge(!0),!1},mouseup:()=>(Le.current=!1,pe.current=null,ge(!1),!1)}}})})})})})})]})},Jc=t=>t,lc=t=>{const e=Jc(t).type;return typeof e=="string"?e:""},Z1=t=>{const e=Jc(t).tool;return typeof e=="string"?e:""},ej=t=>{const e=Jc(t).text;return typeof e=="string"?e:""},tj=t=>{const e=lc(t);return e==="tool"?Z1(t).trim().toLowerCase()||"tool":e||"unknown"},sj=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=tj(n);e.includes(r)||e.push(r)}return e.join(" + ")},nj=t=>t.replace(/\s+/g," ").trim(),rj=t=>{for(const n of t)if(lc(n)==="text"){const r=nj(ej(n));if(r.length===0)continue;return r}const e=t.filter(n=>lc(n)!=="text").length;return e===0?"":`${e} attachment${e===1?"":"s"}`},ij=(t,e,n)=>`${n(t)} / ${n(e)}`,oj=t=>{if(t==="12h")return!0;if(t==="24h")return!1},aj=(t,e)=>{if(!t||!Number.isFinite(t))return"-";const n=oj(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}})},cc={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},ha={user:0,assistant:0,tool:0,other:0},Ai=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Fl=t=>{const e=t.info.tokens,n=e!==void 0?e:t.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof n=="number")return{...cc,total:Ai(n)};if(!n||typeof n!="object")return cc;const r=n,o=Ai(r.input),a=Ai(r.output),c=Ai(r.reasoning),l=Ai(r.cache?.read),d=Ai(r.cache?.write);return{input:o,output:a,reasoning:c,cacheRead:l,cacheWrite:d,total:o+a+c+l+d}},lj=(...t)=>{for(const e of t)if(typeof e=="string"&&e.trim().length>0)return e;return""},or=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+or(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+or(n),0):0,cj=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...ha,assistant:or(n.text)+or(n.content)};const o=lj(n.text,n.content,n.value,n.source?.value,n.source?.text?.value);return r==="tool"||e==="tool"?{user:0,assistant:0,tool:or(n.input)+or(n.output)+or(n.error)+or(n.call?.input)+or(n.call?.output)+or(n.call?.error)+or(n.raw)+Math.round(or(n.metadata)*.25)+Math.round(or(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}},tf=(t,e)=>({user:t.user+e.user,assistant:t.assistant+e.assistant,tool:t.tool+e.tool,other:t.other+e.other}),dj=t=>{const e=Wo(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},uj=(t,e)=>{if(t.length===0)return{...ha};const n=t.reduce((r,o)=>{const a=dj(o);let c={...ha};for(const l of o.parts)c=tf(c,cj(l,a));return tf(r,c)},{...ha});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)}},Di=t=>t.toLocaleString(so()),fj=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(so(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(so(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),mj=(t,e)=>!t||!Number.isFinite(t)?"-":Tc(t,e,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),hj=(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}},pj=()=>{const t=ht.c(202),{t:e}=yt(),n=Re(gj);let r;t[0]===Symbol.for("react.memo_cache_sentinel")?(r={},t[0]=r):r=t[0];const[o,a]=i.useState(r),[c,l]=i.useState(null),d=i.useRef(null),f=mt(xj),m=Ec(),u=Ig(f??""),p=is(bj);let x;t[1]===Symbol.for("react.memo_cache_sentinel")?(x=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(wj),l(null)},t[1]=x):x=t[1];let b;t[2]!==f?(b=[f],t[2]=f,t[3]=b):b=t[3],i.useEffect(x,b);let w,g;t[4]===Symbol.for("react.memo_cache_sentinel")?(w=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},g=[],t[4]=w,t[5]=g):(w=t[4],g=t[5]),i.useEffect(w,g);let h;t[6]===Symbol.for("react.memo_cache_sentinel")?(h=async(Ke,Ze)=>{(await xr(Ze)).ok?(l(Ke),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(Rt=>Rt===Ke?null:Rt),d.current=null},2e3)):l(null)},t[6]=h):h=t[6];const C=h;let j;t[7]!==f||t[8]!==m?(j=f?m.find(Ke=>Ke.id===f)??null:null,t[7]=f,t[8]=m,t[9]=j):j=t[9];const S=j;let N,k,y,D,V,v;if(t[10]!==p||t[11]!==u){N=u.filter(yj);let Ke;t[18]!==u?(Ke=u.filter(vj),t[18]=u,t[19]=Ke):Ke=t[19],v=Ke;let Ze=null;for(let Rt=N.length-1;Rt>=0;Rt=Rt-1,Rt){const Ot=N[Rt];if(Fl(Ot).total>0){Ze=Ot;break}}D=Ze?Fl(Ze):cc,k=Rg({input:D.input,cache:{read:D.cacheRead,write:D.cacheWrite}}),V=N.reduce(jj,0);const Bt=Ze?.info??null;y=hj(p,Bt?.providerID||"",Bt?.modelID||""),t[10]=p,t[11]=u,t[12]=N,t[13]=k,t[14]=y,t[15]=D,t[16]=V,t[17]=v}else N=t[12],k=t[13],y=t[14],D=t[15],V=t[16],v=t[17];const O=y,P=O.contextLimit,E=P&&P>0?Math.min(999,D.total/P*100):0;let B;if(t[20]!==u){const Ke=[...u].reverse().find(Sj)?.info?.system||"";B=uj(u,Ke),t[20]=u,t[21]=B}else B=t[21];const T=B,W=T.user,U=T.assistant,L=T.tool,M=Math.max(0,D.input-W-U-L),ee=W+U+L+M,ie=u[0]?.info?.time?.created,X=u.length>0?u[u.length-1]?.info?.time?.created:null;let H;t[22]!==S?.title||t[23]!==e?(H=S?.title||e("contextSidebar.session.untitled"),t[22]=S?.title,t[23]=e,t[24]=H):H=t[24];const te=S?.time?.created??ie??null,re=X??S?.time?.created??null;let le;t[25]!==U||t[26]!==M||t[27]!==L||t[28]!==W?(le={user:W,assistant:U,tool:L,other:M},t[25]=U,t[26]=M,t[27]=L,t[28]=W,t[29]=le):le=t[29];let ve;t[30]!==N.length||t[31]!==ee||t[32]!==k||t[33]!==P||t[34]!==O||t[35]!==u.length||t[36]!==te||t[37]!==re||t[38]!==le||t[39]!==H||t[40]!==D||t[41]!==V||t[42]!==E||t[43]!==v.length?(ve={sessionTitle:H,messagesCount:u.length,userMessagesCount:v.length,assistantMessagesCount:N.length,createdAt:te,lastActivityAt:re,providerModel:O,tokenBreakdown:D,usagePercent:E,cacheHitRate:k,totalAssistantCost:V,contextLimit:P,breakdown:le,breakdownTotal:ee},t[30]=N.length,t[31]=ee,t[32]=k,t[33]=P,t[34]=O,t[35]=u.length,t[36]=te,t[37]=re,t[38]=le,t[39]=H,t[40]=D,t[41]=V,t[42]=E,t[43]=v.length,t[44]=ve):ve=t[44];const ne=ve;if(!f){let Ke;t[45]!==e?(Ke=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=Ke):Ke=t[46];let Ze;return t[47]!==Ke?(Ze=s.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:Ke}),t[47]=Ke,t[48]=Ze):Ze=t[48],Ze}let we;t[49]!==e?(we=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=we):we=t[50];let he;t[51]!==we||t[52]!==ne.breakdown.user?(he={key:"user",label:we,value:ne.breakdown.user,color:"var(--status-success)"},t[51]=we,t[52]=ne.breakdown.user,t[53]=he):he=t[53];let Me;t[54]!==e?(Me=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=Me):Me=t[55];let z;t[56]!==Me||t[57]!==ne.breakdown.assistant?(z={key:"assistant",label:Me,value:ne.breakdown.assistant,color:"var(--primary-base)"},t[56]=Me,t[57]=ne.breakdown.assistant,t[58]=z):z=t[58];let K;t[59]!==e?(K=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=K):K=t[60];let q;t[61]!==K||t[62]!==ne.breakdown.tool?(q={key:"tool",label:K,value:ne.breakdown.tool,color:"var(--status-warning)"},t[61]=K,t[62]=ne.breakdown.tool,t[63]=q):q=t[63];let me;t[64]!==e?(me=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=me):me=t[65];let Se;t[66]!==me||t[67]!==ne.breakdown.other?(Se={key:"other",label:me,value:ne.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=me,t[67]=ne.breakdown.other,t[68]=Se):Se=t[68];let Be;t[69]!==he||t[70]!==z||t[71]!==q||t[72]!==Se?(Be=[he,z,q,Se],t[69]=he,t[70]=z,t[71]=q,t[72]=Se,t[73]=Be):Be=t[73];const _e=Be;let Le;t[74]!==ne.sessionTitle?(Le=s.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:ne.sessionTitle}),t[74]=ne.sessionTitle,t[75]=Le):Le=t[75];let pe;t[76]!==ne.providerModel.modelName||t[77]!==ne.providerModel.providerName?(pe=s.jsxs("span",{children:[ne.providerModel.providerName," / ",ne.providerModel.modelName]}),t[76]=ne.providerModel.modelName,t[77]=ne.providerModel.providerName,t[78]=pe):pe=t[78];let Ee;t[79]!==n||t[80]!==ne.createdAt?(Ee=ne.createdAt&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:mj(ne.createdAt,n)})]}),t[79]=n,t[80]=ne.createdAt,t[81]=Ee):Ee=t[81];let ge;t[82]!==pe||t[83]!==Ee?(ge=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:[pe,Ee]}),t[82]=pe,t[83]=Ee,t[84]=ge):ge=t[84];let oe;t[85]!==Le||t[86]!==ge?(oe=s.jsxs("div",{className:"mb-6",children:[Le,ge]}),t[85]=Le,t[86]=ge,t[87]=oe):oe=t[87];let je;t[88]!==e?(je=e("contextSidebar.section.context"),t[88]=e,t[89]=je):je=t[89];let ye;t[90]!==je?(ye=s.jsx("span",{className:"typography-micro text-muted-foreground",children:je}),t[90]=je,t[91]=ye):ye=t[91];let ue;t[92]!==ne.tokenBreakdown.total?(ue=Di(ne.tokenBreakdown.total),t[92]=ne.tokenBreakdown.total,t[93]=ue):ue=t[93];let De;t[94]!==ne.contextLimit?(De=ne.contextLimit?` / ${Di(ne.contextLimit)}`:"",t[94]=ne.contextLimit,t[95]=De):De=t[95];let I;t[96]!==ue||t[97]!==De?(I=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[ue,De]}),t[96]=ue,t[97]=De,t[98]=I):I=t[98];let _;t[99]!==ye||t[100]!==I?(_=s.jsxs("div",{className:"flex items-baseline justify-between",children:[ye,I]}),t[99]=ye,t[100]=I,t[101]=_):_=t[101];let be;t[102]!==ne.usagePercent?(be=ne.usagePercent>0&&s.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,ne.usagePercent)}%`,backgroundColor:ne.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}}),t[102]=ne.usagePercent,t[103]=be):be=t[103];let R;t[104]!==be?(R=s.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:be}),t[104]=be,t[105]=R):R=t[105];let de;t[106]!==e||t[107]!==ne.usagePercent?(de=e("contextSidebar.context.percentUsed",{percent:ne.usagePercent.toFixed(1)}),t[106]=e,t[107]=ne.usagePercent,t[108]=de):de=t[108];let fe;t[109]!==de?(fe=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:de}),t[109]=de,t[110]=fe):fe=t[110];let $;t[111]!==_||t[112]!==R||t[113]!==fe?($=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[_,R,fe]}),t[111]=_,t[112]=R,t[113]=fe,t[114]=$):$=t[114];let Ae;t[115]!==e?(Ae=e("contextSidebar.stats.messages"),t[115]=e,t[116]=Ae):Ae=t[116];let Ve;t[117]!==ne.messagesCount?(Ve=Di(ne.messagesCount),t[117]=ne.messagesCount,t[118]=Ve):Ve=t[118];let Ne;t[119]!==Ae||t[120]!==Ve?(Ne={label:Ae,value:Ve},t[119]=Ae,t[120]=Ve,t[121]=Ne):Ne=t[121];let Y;t[122]!==e?(Y=e("contextSidebar.stats.user"),t[122]=e,t[123]=Y):Y=t[123];let F;t[124]!==ne.userMessagesCount?(F=Di(ne.userMessagesCount),t[124]=ne.userMessagesCount,t[125]=F):F=t[125];let se;t[126]!==Y||t[127]!==F?(se={label:Y,value:F},t[126]=Y,t[127]=F,t[128]=se):se=t[128];let Oe;t[129]!==e?(Oe=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=Oe):Oe=t[130];let ce;t[131]!==ne.assistantMessagesCount?(ce=Di(ne.assistantMessagesCount),t[131]=ne.assistantMessagesCount,t[132]=ce):ce=t[132];let Ue;t[133]!==Oe||t[134]!==ce?(Ue={label:Oe,value:ce},t[133]=Oe,t[134]=ce,t[135]=Ue):Ue=t[135];let qe;t[136]!==e?(qe=e("contextSidebar.stats.cost"),t[136]=e,t[137]=qe):qe=t[137];let Ye;t[138]!==ne.totalAssistantCost?(Ye=fj(ne.totalAssistantCost),t[138]=ne.totalAssistantCost,t[139]=Ye):Ye=t[139];let tt;t[140]!==qe||t[141]!==Ye?(tt={label:qe,value:Ye},t[140]=qe,t[141]=Ye,t[142]=tt):tt=t[142];let xt;t[143]!==Ne||t[144]!==se||t[145]!==Ue||t[146]!==tt?(xt=[Ne,se,Ue,tt],t[143]=Ne,t[144]=se,t[145]=Ue,t[146]=tt,t[147]=xt):xt=t[147];const vt=xt;let Mt;t[148]!==vt?(Mt=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:vt.map(Nj)}),t[148]=vt,t[149]=Mt):Mt=t[149];let Tt;t[150]!==e?(Tt=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Tt):Tt=t[151];let Kt;t[152]!==Tt?(Kt=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Tt}),t[152]=Tt,t[153]=Kt):Kt=t[153];let Ut;t[154]!==e||t[155]!==ne.cacheHitRate.hasInput||t[156]!==ne.cacheHitRate.percent||t[157]!==ne.tokenBreakdown.cacheRead||t[158]!==ne.tokenBreakdown.cacheWrite||t[159]!==ne.tokenBreakdown.input||t[160]!==ne.tokenBreakdown.output||t[161]!==ne.tokenBreakdown.reasoning?(Ut=s.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:e("contextSidebar.tokens.input"),value:ne.tokenBreakdown.input,format:"count"},{label:e("contextSidebar.tokens.output"),value:ne.tokenBreakdown.output,format:"count"},{label:e("contextSidebar.tokens.reasoning"),value:ne.tokenBreakdown.reasoning,format:"count"},{label:e("contextSidebar.tokens.cacheRead"),value:ne.tokenBreakdown.cacheRead,format:"count"},{label:e("contextSidebar.tokens.cacheWrite"),value:ne.tokenBreakdown.cacheWrite,format:"count"},{label:e("contextSidebar.tokens.cacheHit"),value:ne.cacheHitRate.hasInput?ne.cacheHitRate.percent:null,format:"percent"}].map(kj)}),t[154]=e,t[155]=ne.cacheHitRate.hasInput,t[156]=ne.cacheHitRate.percent,t[157]=ne.tokenBreakdown.cacheRead,t[158]=ne.tokenBreakdown.cacheWrite,t[159]=ne.tokenBreakdown.input,t[160]=ne.tokenBreakdown.output,t[161]=ne.tokenBreakdown.reasoning,t[162]=Ut):Ut=t[162];let Zt;t[163]!==Kt||t[164]!==Ut?(Zt=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[Kt,Ut]}),t[163]=Kt,t[164]=Ut,t[165]=Zt):Zt=t[165];let ns;t[166]!==_e||t[167]!==ne.breakdownTotal?(ns=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:_e.map(Ke=>Ke.value<=0||ne.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${Ke.value/ne.breakdownTotal*100}%`,backgroundColor:Ke.color}},Ke.key))}),t[166]=_e,t[167]=ne.breakdownTotal,t[168]=ns):ns=t[168];let es;t[169]!==_e||t[170]!==ne.breakdownTotal?(es=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:_e.map(Ke=>{const Ze=ne.breakdownTotal>0?Ke.value/ne.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:Ke.color}}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[Ke.label," ",s.jsxs("span",{className:"tabular-nums",children:[Ze.toFixed(0),"%"]})]})]},Ke.key)})}),t[169]=_e,t[170]=ne.breakdownTotal,t[171]=es):es=t[171];let Ce;t[172]!==ns||t[173]!==es?(Ce=s.jsxs("div",{className:"mb-6",children:[ns,es]}),t[172]=ns,t[173]=es,t[174]=Ce):Ce=t[174];let Qe;t[175]!==e?(Qe=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=Qe):Qe=t[176];let ot;t[177]!==Qe?(ot=s.jsx("div",{className:"typography-micro text-muted-foreground",children:Qe}),t[177]=Qe,t[178]=ot):ot=t[178];let bt;if(t[179]!==c||t[180]!==o||t[181]!==u||t[182]!==e||t[183]!==n){let Ke;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(Ke=Ze=>{const Rt=Wo(Ze.info).role,Ot=Rt==="assistant",rs=Rt==="user",Wt=o[Ze.info.id]===!0,Et=c===Ze.info.id,qt=Ze.info.time?.created??null,hs=sj(Ze.parts),ts=Ot?Fl({info:Ze.info,parts:Ze.parts}):null,as=rs?rj(Ze.parts):"",gs=aj(qt,n),Ft=hs||"—",Lt=ts?ij(ts.input,ts.output,Di):"",Ht=Rt||"unknown",Yt=hs?`${Ht}: ${hs}`:Ht,$t=Wt?JSON.stringify({info:Ze.info,parts:Ze.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":Wt,onClick:()=>{a(Fe=>({...Fe,[Ze.info.id]:Fe[Ze.info.id]!==!0}))},children:s.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:Ot?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[rs?s.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",as]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:Ot?Ft:Yt}),Ot&&s.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:Lt})]}),s.jsx("span",{className:"text-right text-muted-foreground",children:gs})]})}),Wt&&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:Fe=>{Fe.stopPropagation(),C(Ze.info.id,$t)},"aria-label":e(Et?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Et?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Et?s.jsx(A,{name:"check",className:"size-3.5"}):s.jsx(A,{name:"file-copy",className:"size-3.5"})})}),s.jsx(Eg,{language:"json",code:$t,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},Ze.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=Ke):Ke=t[189],bt=[...u].reverse().map(Ke),t[179]=c,t[180]=o,t[181]=u,t[182]=e,t[183]=n,t[184]=bt}else bt=t[184];let Je;t[190]!==bt?(Je=s.jsx("div",{className:"mt-2.5 space-y-1",children:bt}),t[190]=bt,t[191]=Je):Je=t[191];let Pt;t[192]!==ot||t[193]!==Je?(Pt=s.jsxs("div",{children:[ot,Je]}),t[192]=ot,t[193]=Je,t[194]=Pt):Pt=t[194];let Xe;return t[195]!==oe||t[196]!==$||t[197]!==Mt||t[198]!==Zt||t[199]!==Ce||t[200]!==Pt?(Xe=s.jsx("div",{className:"h-full overflow-y-auto bg-background",children:s.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[oe,$,Mt,Zt,Ce,Pt]})}),t[195]=oe,t[196]=$,t[197]=Mt,t[198]=Zt,t[199]=Ce,t[200]=Pt,t[201]=Xe):Xe=t[201],Xe};function gj(t){return t.timeFormatPreference}function xj(t){return t.currentSessionId}function bj(t){return t.providers}function wj(t){return Object.keys(t).length>0?{}:t}function yj(t){return Wo(t.info).role==="assistant"}function vj(t){return Wo(t.info).isUser}function jj(t,e){const n=Ai(e.info.cost);return t+n}function Sj(t){return Wo(t.info).isUser&&typeof t.info.system=="string"}function Nj(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 kj(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)}%`:Di(t.value):"—"})]},t.label)}const Cj=(t,e,n)=>JSON.stringify({sessionID:t,directory:e||"",readOnly:n===!0}),Aj=(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("surface","desktop"),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()},Dj=(t,e,n,r,o,a)=>{const c=Cj(n,r,o),l=t.get(e);if(l?.signature===c)return l.src;const d=Aj(n,r,o,a);return t.set(e,{signature:c,src:d}),d},Tj=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.x=="number"&&typeof e.y=="number"},sf=t=>!t||typeof t!="object"?!1:Object.values(t).every(e=>typeof e=="string"),Ji=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"&&Tj(e.center)&&sf(e.attributes)&&sf(e.computedStyle)&&Array.isArray(e.ancestry)},Xc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([x,b])=>`${x}="${b}"`).join(" "),d=r.computedStyle,f=r.bounds,m=r.center,u=a.replace(/[.:]+$/g,""),p=r.ancestry.map(x=>x.selectorPart).join(" > ");return[`${u}:`,`Page: ${t||"preview"}`,`Viewport: ${e.width}x${e.height}, DPR ${n}`,`Screenshot: ${o?"attached":"not attached"}`,`Element: ${r.tag}`,c?`Text: ${c}`:null,`- Selector: ${r.selector}`,`- Path: ${r.path}`,p?`- Ancestry: ${p}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(f.x)}, y=${Math.round(f.y)}, width=${Math.round(f.width)}, height=${Math.round(f.height)}`,`- Center: x=${Math.round(m.x)}, y=${Math.round(m.y)}`,`Styles: display=${d.display}; position=${d.position}; font=${d.fontWeight} ${d.fontSize} / ${d.lineHeight} ${d.fontFamily}; color=${d.color}; background=${d.backgroundColor}; z-index=${d.zIndex}`].filter(x=>typeof x=="string").join(`
38
+ `)},fh=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Zr("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((b,w)=>{o.onload=()=>b(),o.onerror=()=>w(new Error("Failed to load desktop preview screenshot")),o.src=`data:${r.mime};base64,${r.base64}`});const a=Math.max(1,o.naturalWidth||r.width||Math.floor(n.width)),c=Math.max(1,o.naturalHeight||r.height||Math.floor(n.height)),d=Math.min(1,1200/a),f=document.createElement("canvas");f.width=Math.floor(a*d),f.height=Math.floor(c*d);const m=f.getContext("2d");if(!m)return null;m.scale(d,d),m.drawImage(o,0,0,a,c);const u=a/Math.max(1,n.width),p=c/Math.max(1,n.height);m.fillStyle="rgba(37, 99, 235, 0.28)",m.strokeStyle="rgb(37, 99, 235)",m.lineWidth=Math.max(2,2*u),m.fillRect(e.bounds.x*u,e.bounds.y*p,e.bounds.width*u,e.bounds.height*p),m.strokeRect(e.bounds.x*u,e.bounds.y*p,e.bounds.width*u,e.bounds.height*p);const x=await new Promise(b=>f.toBlob(b,"image/jpeg",.82));return x?new File([x],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(n){return console.warn("[preview] failed to capture annotation screenshot:",n),null}return await Uj(t,e)},Zc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((g,h)=>{c.onload=()=>g(),c.onerror=()=>h(new Error("Failed to load desktop browser screenshot")),c.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,c.naturalWidth||e),d=Math.max(1,c.naturalHeight||n),m=Math.min(1,1200/l),u=document.createElement("canvas");u.width=Math.floor(l*m),u.height=Math.floor(d*m);const p=u.getContext("2d");if(!p)return null;p.scale(m,m),p.drawImage(c,0,0,l,d);const x=l/Math.max(1,r||l),b=d/Math.max(1,o||d);p.fillStyle="rgba(37, 99, 235, 0.14)",p.strokeStyle="rgb(37, 99, 235)",p.lineWidth=Math.max(2,2*x),p.fillRect(a.bounds.x*x,a.bounds.y*b,a.bounds.width*x,a.bounds.height*b),p.strokeRect(a.bounds.x*x,a.bounds.y*b,a.bounds.width*x,a.bounds.height*b);const w=await new Promise(g=>u.toBlob(g,"image/jpeg",.82));return w?new File([w],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Xi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Jn=new Map,Ol=new Map,Pj=3e4,ed=t=>{const e=Jn.get(t);return e?e.expiresAt-Date.now()<=Pj?(Jn.delete(t),null):e:null},Ij=t=>{try{return new URL(t).origin}catch{return t}};function mh(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 hh=t=>new Promise((e,n)=>{const r=new FileReader;r.onloadend=()=>e(typeof r.result=="string"?r.result:Xi),r.onerror=()=>n(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),Rj=async(t,e=.82)=>{const n=await new Promise(r=>t.toBlob(r,"image/jpeg",e));return n&&(await hh(n)).split(",",2)[1]||""},Ej=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},pa=(...t)=>{Ej()&&console.info("[preview-capture]",...t)},ph=(t,e=8)=>{const n=[];try{const r=t.querySelectorAll("*");for(const o of r){const a=o.scrollTop||0,c=o.scrollLeft||0;if(a<=0&&c<=0)continue;const l=o.tagName.toLowerCase(),d=o.id?`#${o.id}`:"",f=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(n.push({selector:`${l}${d}${f}`,scrollTop:a,scrollLeft:c,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),n.length>=e)break}}catch{}return n},Eo="data-oc-fixed-pin",Mj=(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(Eo,JSON.stringify({top:l.top+n,left:l.left+e,width:l.width,height:l.height})),o.push(c);const d=c.tagName.toLowerCase(),f=typeof c.className=="string"&&c.className?`.${c.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";a.push({selector:`${d}${f}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return pa("tagged fixed elements",a),()=>{for(const c of o)try{c.removeAttribute(Eo)}catch{}}},Fj={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${Eo}]`)){let r;try{r=JSON.parse(n.getAttribute(Eo)||"")}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(Eo)}}},qi="data-oc-scroll-pin",Oj=t=>{const e=[],n=ph(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,f=l.scrollLeft||0;if(d<=0&&f<=0)continue;const m=l!==a&&l!==c;m&&l.setAttribute(qi,JSON.stringify({top:d,left:f})),e.push({el:l,top:d,left:f,tagged:m})}}catch{}return{reapply:()=>{for(const a of e)try{a.el.scrollHeight,a.el.scrollTop!==a.top&&(a.el.scrollTop=a.top),a.el.scrollLeft!==a.left&&(a.el.scrollLeft=a.left)}catch{}},cleanup:()=>{for(const a of e)if(a.tagged)try{a.el.removeAttribute(qi)}catch{}},snapshot:n}},Lj={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(`[${qi}]`)){let o;try{o=JSON.parse(r.getAttribute(qi)||"")}catch{r.removeAttribute(qi);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(qi)}}},Ll=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await hh(await n.blob()):null}catch{return null}},Bj=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=ed(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=Ol.get(e),o=r??(async()=>{try{const c=await Ps("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!c.ok)return Jn.delete(e),null;const l=await c.json(),d=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",f=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Jn.delete(e),null;const m={proxyBasePath:d,expiresAt:f};return Jn.set(e,m),m}catch{return Jn.delete(e),null}finally{Ol.delete(e)}})();r||Ol.set(e,o);const a=await o;return a?`${a.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},gh=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 Ll(n.toString(),"include")??Xi;const r=await Bj(n),o=r?await Ll(r,"include"):null;return o||(await Ll(n.toString(),"omit")??Xi)}catch{return Xi}},Vj=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 gh(a,e);r=r.replace(o[0],`url("${c}")`)}return r},nf=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),xh=t=>{const e=t.style.cssText;return()=>{t.style.cssText=e}},_j=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},$j=(t,e,n)=>{const r=[],o=t.defaultView??window,c=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of c){const d=l.textContent?.replace(/\s+/g," ").trim()??"";if(!d||!d.includes(" "))continue;const f=l.getBoundingClientRect();if(f.width<=0||f.height<=0||f.right<0||f.bottom<0||f.left>e||f.top>n)continue;const m=o.getComputedStyle(l);if(m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)continue;const u=m.getPropertyValue("text-wrap"),p=m.getPropertyValue("text-wrap-mode"),x=m.whiteSpace.includes("nowrap")||u==="nowrap"||p==="nowrap",b=f.height<=_j(m)*1.7;!x&&(!b||f.width>e*.72)||(r.push(xh(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]?.()}},zj=(t,e,n,r)=>{const o=[],a=t.defaultView??window,c=a.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=a.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,d=Array.from(t.querySelectorAll("*")).filter(f=>{const m=a.getComputedStyle(f);if(m.position!=="fixed"||m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)return!1;const u=f.getBoundingClientRect();return u.width>0&&u.height>0&&u.right>=0&&u.bottom>=0&&u.left<=e&&u.top<=n}).filter((f,m,u)=>!u.some((p,x)=>x<m&&p.contains(f)));for(const f of d){const m=f.getBoundingClientRect(),u=a.getComputedStyle(f),p=Math.ceil(m.width)+8,x=Math.ceil(m.height)+2;r?.add(f),o.push(xh(f)),f.style.position="absolute",f.style.top=`${m.top+l}px`,f.style.left=`${m.left+c}px`,f.style.right="auto",f.style.bottom="auto",f.style.width=`${p}px`,f.style.minWidth=`${p}px`,f.style.height=`${x}px`,f.style.minHeight=`${x}px`,f.style.margin="0",f.style.boxSizing="border-box",f.style.transform="none",u.zIndex!=="auto"&&(f.style.zIndex=u.zIndex)}return()=>{for(let f=o.length-1;f>=0;f-=1)o[f]?.()}},bh=async(t,e,n,r={})=>{const o=[],a=t.defaultView??window,c=u=>{if(u===t.documentElement||u===t.body)return!0;try{const p=u.getBoundingClientRect();return p.width>0&&p.height>0&&p.right>=0&&p.bottom>=0&&p.left<=e&&p.top<=n}catch{return!1}};if(r.applyLayoutWorkarounds){const u=new WeakSet;o.push(zj(t,e,n,u)),o.push($j(t,e,n))}const l=new Map;for(const u of Array.from(t.images))l.set(u,u.currentSrc||u.src||u.getAttribute("src")||"");const d=Array.from(t.querySelectorAll("picture"));for(const u of d){const p=Array.from(u.querySelectorAll("source"));if(p.length===0)continue;const x=p.map(b=>({source:b,srcset:b.getAttribute("srcset"),sizes:b.getAttribute("sizes")}));o.push(()=>{for(const b of x)b.srcset===null?b.source.removeAttribute("srcset"):b.source.setAttribute("srcset",b.srcset),b.sizes===null?b.source.removeAttribute("sizes"):b.source.setAttribute("sizes",b.sizes)});for(const b of p)b.removeAttribute("srcset"),b.removeAttribute("sizes")}const f=Array.from(t.images).filter(u=>c(u));await Promise.all(f.map(async u=>{const p=l.get(u)||u.currentSrc||u.src||u.getAttribute("src")||"";if(!p)return;await nf(u);const x=await gh(p,t),b={src:u.getAttribute("src"),srcset:u.getAttribute("srcset"),sizes:u.getAttribute("sizes")};o.push(()=>{b.src===null?u.removeAttribute("src"):u.setAttribute("src",b.src),b.srcset===null?u.removeAttribute("srcset"):u.setAttribute("srcset",b.srcset),b.sizes===null?u.removeAttribute("sizes"):u.setAttribute("sizes",b.sizes)}),u.removeAttribute("srcset"),u.removeAttribute("sizes"),u.setAttribute("src",x||Xi),await nf(u)}));const m=Array.from(t.querySelectorAll("*")).filter(c);return await Promise.all(m.map(async u=>{const p=a.getComputedStyle(u).backgroundImage;if(!p||p==="none"||!p.includes("url("))return;const x=await Vj(p,t);if(x===p)return;const b=u.style.backgroundImage;o.push(()=>{u.style.backgroundImage=b}),u.style.backgroundImage=x})),()=>{for(let u=o.length-1;u>=0;u-=1)try{o[u]?.()}catch{}}};async function Wj(t,e){try{const n=t.contentWindow,r=t.contentDocument??n?.document,o=r?.documentElement;if(!n||!r||!o)return null;const a=t.getBoundingClientRect(),c=Math.max(1,Math.ceil(n.innerWidth||t.clientWidth||a.width)),l=Math.max(1,Math.ceil(n.innerHeight||t.clientHeight||a.height)),d=r.body,f=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,m=n.scrollX||0,u=n.scrollY||0,p=n.pageXOffset||0,x=n.pageYOffset||0,b=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,w=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,g=o.scrollLeft||0,h=o.scrollTop||0,C=d?.scrollLeft||0,j=d?.scrollTop||0,S=f?.scrollLeft||0,N=f?.scrollTop||0,k=Math.max(m,p,b,g,C,S),y=Math.max(u,x,w,h,j,N);pa("scroll sources",{windowScrollX:m,windowScrollY:u,pageScrollX:p,pageScrollY:x,visualViewportScrollX:b,visualViewportScrollY:w,rootScrollX:g,rootScrollY:h,bodyScrollX:C,bodyScrollY:j,scrollingElementScrollX:S,scrollingElementScrollY:N,scrollingElementTag:f?.tagName?.toLowerCase()??null,resolvedScrollX:k,resolvedScrollY:y,nestedScrolledElements:ph(r)});const D=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),V=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),v=Math.min(2,Math.max(1,window.devicePixelRatio||1)),O=o.style.scrollBehavior,P=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const E=Oj(r);pa("nested scroll snapshot",E.snapshot);let B=()=>{},T=()=>{};try{await r.fonts?.ready.catch(()=>{}),B=await bh(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(k,y),T=Mj(r,k,y),E.reapply();const W={backgroundColor:mh(r),cache:"disabled",dpr:v,embedFonts:!0,fast:!1,height:V,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[Fj,Lj],quality:.82,width:D},L=await(await np(o,W)).toCanvas();if(!L.width||!L.height)return null;const M=L.width/Math.max(1,D),ee=L.height/Math.max(1,V),ie=Math.min(L.width,Math.max(1,Math.round(c*M))),X=Math.min(L.height,Math.max(1,Math.round(l*ee))),H=Math.max(0,L.width-ie),te=Math.max(0,L.height-X),re=Math.min(H,Math.max(0,Math.round(k*M))),le=Math.min(te,Math.max(0,Math.round(y*ee)));pa("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:D,captureHeight:V,canvasWidth:L.width,canvasHeight:L.height,xScale:M,yScale:ee,sourceX:re,sourceY:le,sourceWidth:ie,sourceHeight:X});const ve=r.createElement("canvas");ve.width=ie,ve.height=X;const ne=ve.getContext("2d");if(!ne)return null;ne.drawImage(L,re,le,ie,X,0,0,ie,X);const we=await Rj(ve,.82);return we?await Zc(we,c,l,c,l,e):null}finally{T(),E.cleanup(),B(),n.scrollTo(k,y),E.reapply(),o.style.scrollBehavior=O,d&&(d.style.scrollBehavior=P)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function Uj(t,e){const n=await Wj(t,e);if(n)return n;try{const r=t.contentWindow,o=t.contentDocument??r?.document,a=o?.documentElement;if(!r||!o||!a)return null;const c=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||c.width)),d=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||c.height)),f=r.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,m=r.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,u=o.body,p=Math.max(d,a.scrollHeight||0,u?.scrollHeight||0),x=Math.min(2,Math.max(1,window.devicePixelRatio||1)),b=a.style.scrollBehavior,w=u?.style.scrollBehavior??"";a.style.scrollBehavior="auto",u&&(u.style.scrollBehavior="auto");let g="",h=()=>{};try{await o.fonts?.ready.catch(()=>{}),h=await bh(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(f,m);const j=await tp(a).catch(()=>"");g=await sp(a,{quality:.82,pixelRatio:x,width:l,height:d,backgroundColor:mh(o),imagePlaceholder:Xi,fontEmbedCSS:j||void 0,style:{transform:`translate(${-f}px, ${-m}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${p}px`},cacheBust:!0})}finally{h(),r.scrollTo(f,m),a.style.scrollBehavior=b,u&&(u.style.scrollBehavior=w)}const C=g.split(",",2)[1]||"";return C?await Zc(C,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const wh=380,Hj=1400,yh=600,Gj=24,Ba=new Map,rf=200,Kj=(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",qj=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},vh=t=>Number.isFinite(t)?Math.min(Hj,Math.max(wh,Math.round(t))):yh,Yj=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},Bl=(t,e)=>{const n=vh(t),r=Yj(e);return r===null?n:Math.min(n,Math.max(1,r))},Qj=(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},Jj=(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"),Xj=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},Zj=(t,e,n)=>{if(t.mode==="chat"){const r=ga(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 Xj(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"):Jj(t.mode,n)},e0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(ei,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(A,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(A,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(A,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(A,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(A,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(A,{name:"global",className:"h-3.5 w-3.5"})},ga=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,t0=(t,e)=>{if(t.size!==e.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0},s0=(t,e)=>{if(e.length===0)return Ba;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?Ba:r},n0=(t,e)=>{const n=gm(t),r=i.useRef(Ba),o=i.useRef(e);return o.current=e,i.useSyncExternalStore(n.subscribe,i.useCallback(()=>{const a=s0(n.getState().session,o.current);return t0(r.current,a)?r.current:(r.current=a,a)},[n]),()=>Ba)},jh=`new Promise((resolve) => {
39
+ const existing = document.getElementById('__openchamber_desktop_browser_overlay');
40
+ if (existing) existing.remove();
41
+ if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
42
+ try { window.__openchamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
43
+ }
44
+ const overlay = document.createElement('div');
45
+ overlay.id = '__openchamber_desktop_browser_overlay';
46
+ 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;';
47
+ document.documentElement.appendChild(overlay);
48
+ const cssEscape = (value) => {
49
+ try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
50
+ };
51
+ const selectorPart = (element) => {
52
+ const tag = element.tagName.toLowerCase();
53
+ if (element.id) return tag + '#' + cssEscape(element.id);
54
+ const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
55
+ return tag + className;
56
+ };
57
+ const metadata = (element) => {
58
+ const rect = element.getBoundingClientRect();
59
+ const style = getComputedStyle(element);
60
+ const ancestry = [];
61
+ let current = element;
62
+ while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
63
+ ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
64
+ current = current.parentElement;
65
+ }
66
+ const attrs = {};
67
+ for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
68
+ const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
69
+ return {
70
+ frame: 'top',
71
+ tag: element.tagName.toLowerCase(),
72
+ text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
73
+ selector: element.id ? '#' + cssEscape(element.id) : path,
74
+ path,
75
+ bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
76
+ center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
77
+ attributes: attrs,
78
+ 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 },
79
+ ancestry,
80
+ };
81
+ };
82
+ const move = (event) => {
83
+ const element = document.elementFromPoint(event.clientX, event.clientY);
84
+ if (!element || element === overlay || element === document.documentElement || element === document.body) return;
85
+ const rect = element.getBoundingClientRect();
86
+ overlay.style.display = 'block';
87
+ overlay.style.left = rect.left + 'px';
88
+ overlay.style.top = rect.top + 'px';
89
+ overlay.style.width = rect.width + 'px';
90
+ overlay.style.height = rect.height + 'px';
91
+ };
92
+ const cleanup = () => {
93
+ window.removeEventListener('mousemove', move, true);
94
+ window.removeEventListener('click', click, true);
95
+ window.removeEventListener('keydown', keydown, true);
96
+ if (window.__openchamberDesktopBrowserCancelInspect === cancel) {
97
+ delete window.__openchamberDesktopBrowserCancelInspect;
98
+ }
99
+ };
100
+ const cancel = () => {
101
+ cleanup();
102
+ overlay.remove();
103
+ resolve(null);
104
+ };
105
+ const click = (event) => {
106
+ event.preventDefault();
107
+ event.stopPropagation();
108
+ const element = document.elementFromPoint(event.clientX, event.clientY);
109
+ const result = element ? metadata(element) : null;
110
+ cleanup();
111
+ overlay.remove();
112
+ resolve(result);
113
+ };
114
+ const keydown = (event) => {
115
+ if (event.key !== 'Escape') return;
116
+ cancel();
117
+ };
118
+ window.__openchamberDesktopBrowserCancelInspect = cancel;
119
+ window.addEventListener('mousemove', move, true);
120
+ window.addEventListener('click', click, true);
121
+ window.addEventListener('keydown', keydown, true);
122
+ });`,xa=`(() => {
123
+ if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
124
+ window.__openchamberDesktopBrowserCancelInspect();
125
+ return;
126
+ }
127
+ const overlay = document.getElementById('__openchamber_desktop_browser_overlay');
128
+ if (overlay) overlay.remove();
129
+ })()`,r0=`(() => {
130
+ if (window.__openchamberSameWebviewNavigationInstalled) return;
131
+ window.__openchamberSameWebviewNavigationInstalled = true;
132
+
133
+ const navigate = (rawUrl) => {
134
+ if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
135
+ try {
136
+ const url = new URL(rawUrl, window.location.href);
137
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
138
+ window.location.assign(url.href);
139
+ return true;
140
+ } catch (_error) {
141
+ return false;
142
+ }
143
+ };
144
+
145
+ const originalOpen = window.open.bind(window);
146
+ window.open = (url, target, features) => {
147
+ if (navigate(url)) return null;
148
+ return originalOpen(url, target, features);
149
+ };
150
+
151
+ document.addEventListener('click', (event) => {
152
+ if (event.defaultPrevented) return;
153
+ const target = event.target;
154
+ if (!(target instanceof Element)) return;
155
+ const anchor = target.closest('a[target="_blank"][href]');
156
+ if (!(anchor instanceof HTMLAnchorElement)) return;
157
+ if (!navigate(anchor.href)) return;
158
+ event.preventDefault();
159
+ event.stopPropagation();
160
+ }, true);
161
+ })()`,Mo=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"}},of=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)},i0=(t,e)=>t.length<=e?t:`${t.slice(0,e-3)}...`,Sh=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},af=(t,e,n)=>{const r=Sh(e);t.postMessage(n,r)},o0=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}},lf=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}},a0=({rawUrl:t,onNavigate:e})=>{const{t:n}=yt(),{currentTheme:r}=yi(),[o,a]=i.useReducer(pe=>pe+1,0),[c,l]=i.useReducer(pe=>pe+1,0),[d,f]=i.useState({status:"idle"}),[m,u]=i.useState(""),p=i.useRef(null),x=i.useRef(1),[b,w]=i.useState(!1),[g,h]=i.useState(!1),[C,j]=i.useState("all"),[S,N]=i.useState([]),[k,y]=i.useState(!1),[D,V]=i.useState(null),v=mt(pe=>pe.currentSessionId),O=mt(pe=>pe.newSessionDraft?.open),P=Mc(pe=>pe.addDraft),E=bi(pe=>pe.addAttachedFile);let B=null;try{B=t?new URL(t):null}catch{B=null}const T=B?B.hostname==="localhost"||B.hostname==="127.0.0.1"||B.hostname==="::1"||B.hostname==="[::1]"||B.hostname==="0.0.0.0":!1,W=B?B.hostname==="0.0.0.0"?new URL(B.toString().replace("0.0.0.0","127.0.0.1")):B:null,U=W?W.toString():"",L=U?`${Xr()||"same-origin"}|${U}`:"",M=r.metadata.variant;i.useEffect(()=>{if(!U||!T){f({status:"idle"});return}const pe=ed(L);if(pe?.previewToken){f({status:"ready",proxyBasePath:pe.proxyBasePath,previewToken:pe.previewToken,expiresAt:pe.expiresAt});return}pe&&Jn.delete(L);let Ee=!1;return f({status:"loading"}),(async()=>{try{const ge=await Ps("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:U})});if(!ge.ok){Jn.delete(L);const De=await ge.json().catch(()=>({})),I=typeof De?.error=="string"?De.error:`HTTP ${ge.status}`;Ee||f({status:"error",message:I});return}const oe=await ge.json(),je=typeof oe.proxyBasePath=="string"?oe.proxyBasePath:"",ye=typeof oe.previewToken=="string"?oe.previewToken:"",ue=typeof oe.expiresAt=="number"?oe.expiresAt:0;if(!je||!ye){Jn.delete(L),Ee||f({status:"error",message:n("contextPanel.preview.proxyError")});return}Jn.set(L,{proxyBasePath:je,previewToken:ye,expiresAt:ue}),Ee||f({status:"ready",proxyBasePath:je,previewToken:ye,expiresAt:ue})}catch(ge){if(Jn.delete(L),!Ee){const oe=ge instanceof Error?ge.message:String(ge);f({status:"error",message:oe})}}})(),()=>{Ee=!0}},[T,L,c,n,U]);const ee=W&&(W.protocol==="http:"||W.protocol==="https:")?W.toString():"",ie=T&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!ie){u("");return}let pe=!1;return u(""),vc(Xr()).then(Ee=>{!pe&&Ee&&u(ie)}).catch(()=>{}),()=>{pe=!0}},[ie]);const X=T&&d.status==="ready"&&W&&m===ie?(()=>{const pe=W.pathname||"/",Ee=new URLSearchParams(W.search);Ee.delete("oc_url_token"),Ee.delete("oc_client_token"),Ee.set("ocPreview",String(o)),Ee.set("oc_preview_token",d.previewToken||"");const ge=Ee.toString(),oe=W.hash||"";return Ii().authenticatedAsset(`${d.proxyBasePath}${pe}${ge?`?${ge}`:""}${oe}`)})():"",H=T?X:ee,te=T?o0(X):ee,re=T&&(d.status==="loading"||d.status==="idle"||m!==ie),le=T&&d.status==="error",ve=i.useCallback(pe=>{const Ee=v??(O?"draft":null);if(!Ee){ae.error(n("contextPanel.preview.inspect.attachNoSession"));return}const ge=t||H||"",oe=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},je=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let ye=!1;try{const ue=p.current,De=ue?await fh(ue,pe):null;De&&(await E(De),ye=!0)}catch{ye=!1}P({sessionKey:Ee,source:"preview-annotation",fileLabel:ge||"preview",startLine:1,endLine:1,code:Xc({pageUrl:ge,viewport:oe,devicePixelRatio:je,target:pe,screenshotAttached:ye,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),ae.success(n("contextPanel.preview.inspect.attached"))})()},[E,P,v,H,O,t,n]);i.useEffect(()=>{w(!1),N([]),h(!1),j("all"),y(!1),V(null),x.current=1},[H]),i.useEffect(()=>{const pe=p.current?.contentWindow;!b||!pe||af(pe,X,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[b,k,X]),i.useEffect(()=>{const pe=p.current?.contentWindow;!b||!pe||af(pe,X,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:M})},[b,M,X]),i.useEffect(()=>{if(!k||typeof window>"u")return;const pe=Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),Ee.stopImmediatePropagation(),y(!1))};return window.addEventListener("keydown",pe,!0),()=>window.removeEventListener("keydown",pe,!0)},[k]),i.useEffect(()=>{if(!T||typeof window>"u")return;const pe=oe=>{if(typeof oe=="string")return oe;if(oe==null)return"";try{return JSON.stringify(oe)}catch{return String(oe)}},Ee=oe=>{const je=x.current;x.current+=1,N(ye=>{const ue=[...ye,{...oe,id:je}];return ue.length>rf?ue.slice(ue.length-rf):ue})},ge=oe=>{if(oe.source!==p.current?.contentWindow)return;const je=oe.data;if(!(!je||je.source!=="openchamber-preview-bridge"||je.version!==1)){if(je.type==="ready"){w(!0);return}if(je.type==="console"){const ye=je.level==="error"||je.level==="warn"||je.level==="info"||je.level==="debug"?je.level:"log",ue=Array.isArray(je.args)?je.args.map(pe).filter(Boolean):[];Ee({level:ye,message:ue.join(" "),ts:typeof je.ts=="number"?je.ts:Date.now()});return}if(je.type==="runtime-error"){const ye=pe(je.filename),ue=typeof je.line=="number"?je.line:null,De=typeof je.column=="number"?je.column:null,I=ye?`${ye}${ue!==null?`:${ue}${De!==null?`:${De}`:""}`:""}`:"",_=pe(je.stack);Ee({level:"runtime",message:pe(je.message)||n("contextPanel.preview.console.runtimeError"),details:[I,_].filter(Boolean).join(`
162
+ `),ts:typeof je.ts=="number"?je.ts:Date.now()});return}if(je.type==="resource-error"){const ye=pe(je.tag)||"resource",ue=pe(je.url);Ee({level:"resource",message:ue?`${ye}: ${ue}`:ye,details:pe(je.outerHTML),ts:typeof je.ts=="number"?je.ts:Date.now()});return}if(je.type==="hover"){V(Ji(je.target)?je.target:null);return}if(je.type==="select"&&Ji(je.target)){V(je.target),y(!1),ve(je.target);return}if(je.type==="navigate-preview"){const ye=typeof je.url=="string"?je.url:"",ue=je.navigation==="external"?"external":"proxy";if(ye&&ue==="external"){ti(ye);return}ye&&e(ye)}}};return window.addEventListener("message",ge),()=>{window.removeEventListener("message",ge)}},[ve,T,e,n]);const ne=S.filter(pe=>pe.level==="error"||pe.level==="runtime"||pe.level==="resource").length,we=S.filter(pe=>Kj(pe,C)),he=i.useCallback(()=>{const pe=[`Preview URL: ${t||H||""}`,`Events: ${S.length}`,""].join(`
163
+ `),Ee=S.map(ge=>{const oe=new Date(ge.ts).toISOString(),je=ge.details?`
164
+ ${ge.details}`:"";return`[${oe}] [${ge.level}] ${ge.message}${je}`}).join(`
165
+ `);xr(`${pe}${Ee}`).then(ge=>{ge.ok?ae.success(n("contextPanel.preview.console.copied")):ae.error(n("contextPanel.preview.console.copyFailed"))})},[S,H,t,n]),Me=i.useCallback(()=>{const pe=v??(O?"draft":null);if(!pe){ae.error(n("contextPanel.preview.console.attachNoSession"));return}const Ee=[`Preview URL: ${t||H||""}`,`Events: ${S.length}`,""].join(`
166
+ `),ge=S.map(oe=>{const je=new Date(oe.ts).toISOString(),ye=oe.details?`
167
+ ${oe.details}`:"";return`[${je}] [${oe.level}] ${oe.message}${ye}`}).join(`
168
+ `);P({sessionKey:pe,source:"preview-console",fileLabel:t||H||"preview",startLine:1,endLine:Math.max(1,S.length),code:`${Ee}${ge}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),ae.success(n("contextPanel.preview.console.attached"))},[P,S,v,H,O,t,n]),[z,K]=i.useState("unknown"),q=i.useRef(0),me=i.useRef(0),Se=15e3;i.useEffect(()=>{if(!X){K("unknown"),q.current=0,me.current=0;return}let pe=!1;return q.current||(q.current=Date.now(),me.current=0),K("unknown"),(async()=>{const ge=await(async()=>{try{return await Ps(X,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(pe)return;if(!ge){K("unreachable");return}if(ge.status===403||ge.status===404){Jn.delete(L),f({status:"loading"}),l();return}if(ge.status!==502){K("reachable");return}const oe=q.current||Date.now();if(Date.now()-oe<Se){K("starting"),me.current+=1;const ye=me.current,ue=Math.min(2e3,250*Math.pow(2,Math.min(4,ye)));setTimeout(()=>{pe||a()},ue).unref?.();return}K("unreachable")})(),()=>{pe=!0}},[L,X,o]);const Be=T&&d.status==="ready"&&(z==="unknown"||z==="starting"),_e=T&&d.status==="ready"&&z==="unreachable",Le=i.useCallback(pe=>{if(!T||d.status!=="ready"||typeof window>"u")return;const Ee=pe.currentTarget.contentWindow;if(Ee)try{const ge=Ee.location,oe=Sh(X);if(ge.origin!==oe||ge.pathname.startsWith(d.proxyBasePath))return;const je=`${d.proxyBasePath}${ge.pathname}${ge.search}${ge.hash}`;Ee.location.replace(je)}catch{}},[T,X,d]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:te||t,children:te||t||n("contextPanel.preview.empty")}),s.jsx(ze,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:n("contextPanel.preview.actions.reload"),"aria-label":n("contextPanel.preview.actions.reload"),disabled:!H,children:s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ee&&ti(ee)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!ee,children:s.jsx(A,{name:"external-link",className:"h-3.5 w-3.5"})}),T?s.jsx(ze,{type:"button",size:"sm",variant:k?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>y(pe=>!pe),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!b,children:s.jsx(A,{name:"cursor",className:"h-3.5 w-3.5"})}):null,T?s.jsxs(ze,{type:"button",size:"sm",variant:g?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>h(pe=>!pe),title:n(b?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),"aria-label":n(b?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),disabled:!b&&S.length===0,children:[s.jsx(A,{name:"terminal-box",className:"h-3.5 w-3.5"}),ne>0?s.jsx("span",{className:"typography-micro text-status-error",children:ne}):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")})]}):_e?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.upstreamUnreachable")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.upstreamUnreachableHint")}),s.jsx(ze,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:n("contextPanel.preview.actions.retry")})]}):H&&(!T||z==="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:M},onLoad:Le,sandbox:T?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${H}:${o}`),k&&D?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:D.bounds.x,top:D.bounds.y,width:D.bounds.width,height:D.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[D.tag,D.text?` · ${D.text}`:""]})}):null]}):re?s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.loading")}):le?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.proxyError")}),d.status==="error"?s.jsx("div",{className:"text-center text-xs opacity-70",children:d.message}):null]}):s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.invalidUrl")}),g?s.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:n("contextPanel.preview.console.title")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:Me,disabled:S.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:he,disabled:S.length===0,children:n("contextPanel.preview.console.copy")}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:()=>N([]),disabled:S.length===0,children:n("contextPanel.preview.console.clear")})]})]}),s.jsx("div",{className:"flex items-center gap-1 border-b border-border/30 px-3 py-1.5",children:["all","errors","warnings","logs"].map(pe=>s.jsx(ze,{type:"button",size:"xs",variant:C===pe?"secondary":"ghost",onClick:()=>j(pe),children:n(pe==="all"?"contextPanel.preview.console.filter.all":pe==="errors"?"contextPanel.preview.console.filter.errors":pe==="warnings"?"contextPanel.preview.console.filter.warnings":"contextPanel.preview.console.filter.logs")},pe))}),s.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:S.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.empty")}):we.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):we.map(pe=>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",pe.level==="error"||pe.level==="runtime"||pe.level==="resource"?"text-status-error":pe.level==="warn"?"text-status-warning":"text-muted-foreground"),children:pe.level}),s.jsx("span",{className:"min-w-0 break-words text-foreground",children:pe.message})]})},pe.id))})]}):null]})]})},l0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,c0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=yt(),o=i.useRef(null),a=Re(z=>z.setContextPanelTabTargetPath),c=Mo(t),l=c!=="about:blank"?c:"",[d,f]=i.useState(l),[m,u]=i.useState(l),[p,x]=i.useState(l),[b,w]=i.useState(()=>l?[l]:[]),[g,h]=i.useState(()=>l?0:-1),[C,j]=i.useReducer(z=>z+1,0),[S,N]=i.useState(!!l),[k,y]=i.useState(!1),[D,V]=i.useState(null),[v,O]=i.useState({status:"idle"}),[P,E]=i.useState(""),B=mt(z=>z.currentSessionId),T=mt(z=>z.newSessionDraft?.open),W=Mc(z=>z.addDraft),U=bi(z=>z.addAttachedFile),L=i.useCallback(z=>{!z||z==="about:blank"||!e||!n||a(e,n,z)},[e,n,a]),M=i.useCallback((z,K)=>{const q=Mo(z),me=q!=="about:blank"?q:"";u(me),f(me),K?.inFrame?N(!1):(x(me),N(!!me)),L(me),w(Se=>{if(!me)return h(-1),[];if(K?.replaceHistory)return Se;const Be=g>=0?Se.slice(0,g+1):[];if(Be[Be.length-1]===me)return h(Be.length-1),Be;const Le=[...Be,me];return h(Le.length-1),Le})},[g,L]),ee=i.useCallback(z=>{const K=b[z];K&&(h(z),u(K),x(K),f(K),N(!0),L(K))},[b,L]),ie=i.useCallback(()=>{if(m){N(!0);try{o.current?.contentWindow?.location.reload()}catch{j()}}},[m]);i.useEffect(()=>{if(!p){O({status:"idle"});return}const z=Ij(p),K=ed(z);if(K?.previewToken){O({status:"ready",proxyBasePath:K.proxyBasePath,previewToken:K.previewToken,expiresAt:K.expiresAt});return}K&&Jn.delete(z);let q=!1;return O({status:"loading"}),N(!0),(async()=>{try{const me=await Ps("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:p,allowExternal:!0})});if(!me.ok){const pe=await me.json().catch(()=>({})),Ee=typeof pe?.error=="string"?pe.error:`HTTP ${me.status}`;q||O({status:"error",message:Ee});return}const Se=await me.json(),Be=typeof Se.proxyBasePath=="string"?Se.proxyBasePath:"",_e=typeof Se.previewToken=="string"?Se.previewToken:"",Le=typeof Se.expiresAt=="number"?Se.expiresAt:0;if(!Be||!_e){q||O({status:"error",message:r("contextPanel.preview.proxyError")});return}Jn.set(z,{proxyBasePath:Be,previewToken:_e,expiresAt:Le}),q||O({status:"ready",proxyBasePath:Be,previewToken:_e,expiresAt:Le})}catch(me){if(!q){const Se=me instanceof Error?me.message:String(me);O({status:"error",message:Se})}}})(),()=>{q=!0}},[p,r]);const X=p&&v.status==="ready"?`${v.proxyBasePath}|${v.previewToken||""}|${C}`:"";i.useEffect(()=>{if(!X){E("");return}let z=!1;return E(""),vc(Xr()).then(K=>{!z&&K&&E(X)}).catch(()=>{}),()=>{z=!0}},[X]);const H=i.useMemo(()=>{if(P!==X||!p||v.status!=="ready")return"";try{const z=new URL(p),K=z.pathname||"/",q=new URLSearchParams(z.search);q.delete("oc_url_token"),q.delete("oc_client_token"),q.set("ocPreview",String(C)),q.set("oc_preview_token",v.previewToken||"");const me=q.toString();return Ii().authenticatedAsset(`${v.proxyBasePath}${K}${me?`?${me}`:""}${z.hash}`)}catch{return""}},[p,v,X,C,P]),te=H||(v.status==="error"?p:""),re=i.useCallback(z=>{if(!z||!p||v.status!=="ready")return"";try{const K=new URL(z,window.location.origin),q=v.proxyBasePath.endsWith("/")?v.proxyBasePath.slice(0,-1):v.proxyBasePath;if(K.origin!==window.location.origin||!K.pathname.startsWith(q))return"";const me=K.pathname.slice(q.length)||"/",Se=new URL(p).origin;return lf(new URL(`${me}${K.search}${K.hash}`,Se).toString())}catch{return""}},[p,v]),le=i.useCallback(z=>{if(!z||!p||v.status!=="ready")return"";try{const K=new URL(z,window.location.origin),q=new URL(p).origin;if(K.origin!==window.location.origin||q===window.location.origin)return"";const me=v.proxyBasePath.endsWith("/")?v.proxyBasePath.slice(0,-1):v.proxyBasePath;return K.pathname.startsWith(me)?"":lf(new URL(`${K.pathname}${K.search}${K.hash}`,q).toString())}catch{return""}},[p,v]),ve=i.useCallback(z=>{const K=o.current?.contentWindow;K&&K.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:z},window.location.origin)},[]),ne=i.useCallback(async z=>{const K=B??(T?"draft":null);if(!K){ae.error(r("contextPanel.preview.inspect.attachNoSession"));return}const q=o.current,me=q?.contentWindow,Se=q?.getBoundingClientRect(),Be={width:Number.isFinite(me?.innerWidth)?me?.innerWidth??Se?.width??0:Se?.width??0,height:Number.isFinite(me?.innerHeight)?me?.innerHeight??Se?.height??0:Se?.height??0},_e=q?await fh(q,z):null,Le=!!_e;_e&&await U(_e),W({sessionKey:K,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Xc({pageUrl:m,viewport:Be,devicePixelRatio:window.devicePixelRatio||1,target:z,screenshotAttached:Le,intro:r(Le?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),ae.success(r("contextPanel.preview.inspect.attached"))},[U,W,B,m,T,r]),we=i.useCallback(()=>{const z=o.current;V(null),ve(!1),z&&of(z,xa).catch(()=>{})},[ve]);i.useEffect(()=>{if(!k)return;const z=K=>{K.key==="Escape"&&(K.preventDefault(),K.stopImmediatePropagation(),y(!1),we())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[we,k]),i.useEffect(()=>()=>we(),[we]),i.useEffect(()=>{const z=K=>{if(K.source!==o.current?.contentWindow)return;const q=K.data;if(!(!q||q.source!=="openchamber-preview-bridge"||q.version!==1)){if(q.type==="ready"){const me=typeof q.url=="string"?q.url:"",Se=re(me);Se&&Se!==m&&M(Se,{inFrame:!0});return}if(q.type==="hover"){V(Ji(q.target)?q.target:null);return}if(q.type==="select"&&Ji(q.target)){V(null),y(!1),ve(!1),ne(q.target);return}if(q.type==="navigate-preview"){const me=typeof q.url=="string"?q.url:"",Se=le(me);if(Se){M(Se);return}me&&M(me)}}};return window.addEventListener("message",z),()=>window.removeEventListener("message",z)},[M,ne,m,re,le,ve]);const he=i.useCallback(()=>{const z=o.current;if(!(!z||!m)){if(k){y(!1),we();return}if(H){V(null),y(!0),ve(!0);return}y(!0),(async()=>{try{const K=await of(z,jh);if(y(!1),!K||!Ji(K))return;await ne(K)}catch{y(!1),ae.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[ne,we,m,k,ve,H,r]),Me=i.useCallback(()=>{try{const z=o.current?.contentWindow?.location.href||"",K=le(z);if(K){M(K,{inFrame:!0});return}}catch{}N(!1),k&&H&&ve(!0)},[M,le,k,ve,H]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:g<=0,onClick:()=>ee(g-1),children:s.jsx(A,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:g<0||g>=b.length-1,onClick:()=>ee(g+1),children:s.jsx(A,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:ie,children:s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:z=>{z.preventDefault(),M(d)},children:s.jsx("input",{value:d,onChange:z=>f(z.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx(ze,{type:"button",variant:k?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:he,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(A,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:()=>{ti(m)},children:s.jsx(A,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[te?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:te,title:r("contextPanel.browser.empty"),className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:Me},`${n}:${C}`),k&&D?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:D.bounds.x,top:D.bounds.y,width:D.bounds.width,height:D.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[D.tag,D.text?` · ${D.text}`:""]})}):null]}):s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(Fc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")}),s.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:r("contextPanel.browser.emptyHint")}),s.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:r("contextPanel.browser.trustNotice")})]}),S?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},d0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=yt(),o=i.useRef(null),a=Re(v=>v.setContextPanelTabTargetPath),c=Mo(t),l=c!=="about:blank"?c:"",d=i.useRef(Mo(t)),[f,m]=i.useState(l),[u,p]=i.useState(l),[x,b]=i.useState(!1),[w,g]=i.useState(!0),h=i.useRef(null),C=w,j=i.useCallback(v=>{!v||v==="about:blank"||!e||!n||a(e,n,v)},[e,n,a]),S=mt(v=>v.currentSessionId),N=mt(v=>v.newSessionDraft?.open),k=Mc(v=>v.addDraft),y=bi(v=>v.addAttachedFile);i.useEffect(()=>{const v=o.current;if(!v)return;const O=()=>{try{const U=v.getURL();U&&U!=="about:blank"&&(p(U),m(U),j(U))}catch{}},P=U=>{const L=U.detail;typeof L?.url=="string"&&L.url&&(p(L.url),m(L.url),j(L.url))},E=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>g(!0),200)},B=()=>{h.current&&clearTimeout(h.current),g(!1),O()},T=U=>{const L=U.detail;if(L?.disposition==="new-window"||L?.disposition==="foreground-tab"||L?.disposition==="background-tab"){U.preventDefault();const M=o.current;typeof M?.loadURL=="function"&&L.url&&M.loadURL(L.url)}},W=()=>{try{v.executeJavaScript?.(r0,!0).catch(()=>{})}catch{}};v.addEventListener("did-navigate",P),v.addEventListener("did-navigate-in-page",P),v.addEventListener("did-start-loading",E),v.addEventListener("did-stop-loading",B),v.addEventListener("new-window",T),v.addEventListener("dom-ready",W);try{v.isLoading()||(g(!1),O())}catch{}return W(),()=>{h.current&&clearTimeout(h.current),v.removeEventListener("did-navigate",P),v.removeEventListener("did-navigate-in-page",P),v.removeEventListener("did-start-loading",E),v.removeEventListener("did-stop-loading",B),v.removeEventListener("new-window",T),v.removeEventListener("dom-ready",W)}},[j]),i.useEffect(()=>{const v=setTimeout(()=>g(!1),3e4);return()=>clearTimeout(v)},[]),i.useEffect(()=>{if(!x)return;const v=O=>{if(O.key!=="Escape")return;O.preventDefault(),O.stopImmediatePropagation(),b(!1);const P=o.current;try{P?.executeJavaScript?.(xa).catch(()=>{})}catch{}};return window.addEventListener("keydown",v,!0),()=>window.removeEventListener("keydown",v,!0)},[x]),i.useEffect(()=>{const v=o.current;return()=>{try{const O=v?.getURL?.();O&&O!=="about:blank"&&a(e,n,O)}catch{}try{v?.executeJavaScript?.(xa).catch(()=>{})}catch{}}},[e,n,a]);const D=i.useCallback(v=>{const O=o.current;if(typeof O?.loadURL!="function")return;const P=Mo(v);try{O.loadURL(P)}catch{}},[]),V=i.useCallback(()=>{const v=o.current;if(v){if(x){b(!1);try{v.executeJavaScript?.(xa).catch(()=>{})}catch{}return}b(!0),v.executeJavaScript?.(jh,!0).then(async O=>{if(b(!1),!O||!Ji(O))return;const P=S??(N?"draft":null);if(!P){ae.error(r("contextPanel.preview.inspect.attachNoSession"));return}const E=typeof v.getWebContentsId=="function"?v.getWebContentsId():null;if(E==null)return;const B=await Mg("desktop_browser_capture_page",{webContentsId:E}),T=await v.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),W=Number.isFinite(T?.width)?T.width:B.width,U=Number.isFinite(T?.height)?T.height:B.height,L=await Zc(B.base64,B.width,B.height,W,U,O),M=!!L;L&&await y(L),k({sessionKey:P,source:"preview-annotation",fileLabel:u||"browser",startLine:1,endLine:1,code:Xc({pageUrl:u,viewport:{width:W,height:U},devicePixelRatio:window.devicePixelRatio||1,target:O,screenshotAttached:M,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),ae.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>b(!1))}},[y,k,S,u,x,N,r]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:s.jsx(A,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:s.jsx(A,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:v=>{v.preventDefault(),D(f)},children:s.jsx("input",{value:f,onChange:v=>m(v.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx(ze,{type:"button",variant:x?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:V,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(A,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{ti(u)},children:s.jsx(A,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[s.jsx("webview",{ref:o,src:d.current,partition:"persist:openchamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!u||u==="about:blank")&&!w?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(Fc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")})]}):null,C?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},u0=()=>{const{t}=yt(),e=wi()??"",n=i.useMemo(()=>qj(e),[e]),r=Re(_=>n?_.contextPanelByDirectory[n]:void 0),o=Re(_=>_.closeContextPanel),a=Re(_=>_.closeContextPanelTab),c=Re(_=>_.openContextPanelTab),l=Re(_=>_.toggleContextPanelExpanded),d=Re(_=>_.setContextPanelWidth),f=Re(_=>_.setActiveContextPanelTab),m=Re(_=>_.reorderContextPanelTabs),u=fn(_=>_.setSelectedPath),p=Re(_=>_.openContextPreview),x=Re(_=>_.allowPromptingSubagentSessions),{themeMode:b,setThemeMode:w,lightThemeId:g,darkThemeId:h,currentTheme:C}=yi(),j=i.useMemo(()=>r?.tabs??[],[r?.tabs]),S=j.find(_=>_.id===r?.activeTabId)??j[j.length-1]??null,N=!!(r?.isOpen&&S),k=!!(N&&r?.expanded),y=vh(r?.width??yh),D=i.useMemo(()=>{const _=[];for(const be of j){if(be.mode!=="chat")continue;const R=ga(be.dedupeKey);R&&!_.includes(R)&&_.push(R)}return _},[j]),V=n0(n||void 0,D),[v,O]=i.useState(!1),[P,E]=i.useState(!1),B=i.useRef(0),T=i.useRef(y),W=i.useRef(null),U=i.useRef(null),L=i.useRef(null),M=i.useRef(new Map),ee=i.useRef(new Map),ie=i.useRef(!1),X=i.useRef(N),H=i.useRef(null),te=i.useCallback(()=>{E(!0),H.current!==null&&window.cancelAnimationFrame(H.current),H.current=window.requestAnimationFrame(()=>{H.current=null,E(!1)})},[]);i.useEffect(()=>()=>{H.current!==null&&window.cancelAnimationFrame(H.current)},[]),i.useLayoutEffect(()=>{const _=X.current;if(X.current=N,!N){E(!1);return}_||te()},[N,te]),i.useEffect(()=>{if(!N||ie.current){ie.current=N;return}const _=window.requestAnimationFrame(()=>{L.current?.focus({preventScroll:!0})});return ie.current=!0,()=>window.cancelAnimationFrame(_)},[N]);const re=i.useCallback(_=>{const be=L.current;be&&be.style.setProperty("--oc-context-panel-width",`${Bl(_,be)}px`)},[]),le=i.useCallback(_=>{if(!(!N||k||!n)){try{_.currentTarget.setPointerCapture(_.pointerId)}catch{}U.current=_.pointerId,O(!0),B.current=_.clientX,T.current=y,W.current=y,re(y),_.preventDefault()}},[re,n,k,N,y]),ve=i.useCallback(_=>{if(!v||U.current!==_.pointerId)return;const be=B.current-_.clientX,R=Bl(T.current+be,L.current);W.current!==R&&(W.current=R,re(R))},[re,v]),ne=i.useCallback(_=>{if(U.current!==_.pointerId||!n)return;try{_.currentTarget.releasePointerCapture(_.pointerId)}catch{}const be=Bl(W.current??y,L.current);te(),re(be),W.current=be,d(n,be),O(!1),U.current=null},[re,n,d,te,y]);i.useEffect(()=>{v||(W.current=null)},[v]);const we=i.useCallback(()=>{n&&o(n)},[o,n]),he=i.useCallback(()=>{n&&l(n)},[n,l]),Me=i.useCallback(_=>{_.key==="Escape"&&(_.preventDefault(),_.stopPropagation(),we())},[we]);i.useEffect(()=>{if(!(!n||!S)&&S.mode==="file"&&S.targetPath){u(n,S.targetPath,{allowOutsideRoot:!0});return}},[S,n,u]);const z=S?.mode==="chat"?S.id:null,K=S?.mode==="chat"?ga(S.dedupeKey):null;i.useEffect(()=>{if(!N||!n||!K||typeof window>"u")return;const _=()=>{if(document.visibilityState==="hidden"||!document.hasFocus()){hl(n,K,!1);return}xm(K),hl(n,K,!0)};_();const be=window.setInterval(_,1e4);return window.addEventListener("focus",_),window.addEventListener("blur",_),document.addEventListener("visibilitychange",_),()=>{window.clearInterval(be),window.removeEventListener("focus",_),window.removeEventListener("blur",_),document.removeEventListener("visibilitychange",_),hl(n,K,!1)}},[K,n,N]);const q=i.useCallback((_,be,R)=>Dj(ee.current,_,be,n||null,R,{mode:b,lightThemeId:g,darkThemeId:h,currentTheme:C}),[C,h,n,g,b]);i.useEffect(()=>{const _=new Set(j.map(be=>be.id));for(const be of ee.current.keys())_.has(be)||ee.current.delete(be)},[j]);const me=i.useCallback(_=>{!n||S?.mode!=="diff"||c(n,{mode:"diff",targetPath:S.targetPath,stagedDiff:_==="staged",diffScope:_})},[S,n,c]),Se=i.useCallback(()=>{if(typeof window>"u")return;const _={themeMode:b,lightThemeId:g,darkThemeId:h,currentTheme:C};for(const be of M.current.values()){const R=be.contentWindow;if(!R)continue;const de=R.__openchamberApplyThemeSync;if(typeof de=="function")try{de(_);continue}catch{}R.postMessage({type:"openchamber:theme-sync",payload:_},window.location.origin)}},[C,h,g,b]),Be=i.useCallback(()=>{if(typeof window>"u")return;const _={allowPromptingSubagentSessions:x};for(const be of M.current.values()){const R=be.contentWindow;if(!R)continue;const de=R.__openchamberApplyChatSettingsSync;if(typeof de=="function")try{de(_);continue}catch{}R.postMessage({type:"openchamber:chat-settings-sync",payload:_},window.location.origin)}},[x]),_e=i.useCallback(()=>{if(!(typeof window>"u"))for(const[_,be]of M.current.entries()){const R=be.contentWindow;if(!R)continue;const de={visible:z===_},fe=R.__openchamberSetEmbeddedVisibility;if(typeof fe=="function")try{fe(de);continue}catch{}R.postMessage({type:"openchamber:embedded-visibility",payload:de},window.location.origin)}},[z]);i.useEffect(()=>{if(typeof window>"u")return;const _=be=>{if(be.origin!==window.location.origin||!Array.from(M.current.values()).some(Ve=>Ve.contentWindow===be.source))return;const de=be.data;if(de?.type==="openchamber:chat-settings-request"){Be();return}if(de?.type!=="openchamber:cycle-theme-request")return;const fe=["light","dark","system"],Ae=(fe.indexOf(b)+1)%fe.length;w(fe[Ae])};return window.addEventListener("message",_),()=>window.removeEventListener("message",_)},[Be,w,b]),i.useLayoutEffect(()=>{j.some(be=>be.mode==="chat")&&(Se(),Be(),_e())},[h,g,Be,_e,Se,j,b]);const Le=i.useMemo(()=>j.map(_=>{const be=Zj(_,V,t),R=i0(be,Gj),de=Qj(_.targetPath,e);return{id:_.id,label:R,icon:e0(_),title:de?`${be}: ${de}`:be,closeLabel:t("contextPanel.tab.closeTabAria",{label:R})}}),[e,V,t,j]),pe=S?.mode==="context"?s.jsx(pj,{}):S?.mode==="plan"?s.jsx(uh,{targetPath:S.targetPath}):S?.mode==="preview"?s.jsx(a0,{rawUrl:S.targetPath??"",onNavigate:_=>p(e,_)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(A,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),s.jsx("div",{className:"typography-ui-header text-foreground",children:t("contextPanel.preview.title")}),s.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:t("contextPanel.preview.description")})]}),Ee=i.useMemo(()=>j.filter(_=>_.mode==="chat"),[j]),ge=i.useMemo(()=>j.filter(_=>_.mode==="browser"),[j]),oe=i.useMemo(()=>j.filter(_=>_.mode==="diff"),[j]),je=l0()?d0:c0,ye=i.useMemo(()=>j.some(_=>_.mode==="file"),[j]),ue=S?.mode==="file",De=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(Bo,{items:Le,activeId:S?.id??null,onSelect:_=>{n&&f(n,_)},onClose:_=>{n&&a(n,_)},onReorder:(_,be)=>{n&&m(n,_,be)},layoutMode:"scrollable",variant:"default"}),s.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:he,className:"h-7 w-7 p-0",title:t(k?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),"aria-label":t(k?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),children:k?s.jsx(A,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:we,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(A,{name:"close",className:"h-3.5 w-3.5"})})]})]}),I=N?k?{"--oc-context-panel-width":"100%",width:"100%",minWidth:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",minWidth:`min(${wh}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${v?W.current??y:y}px`}:{"--oc-context-panel-width":`${v?W.current??y:y}px`,width:0,minWidth:0,maxWidth:0,opacity:0,overflow:"hidden",visibility:"hidden"};return s.jsxs("aside",{ref:L,"data-context-panel":"true",tabIndex:-1,inert:!N||void 0,className:Pe("flex min-h-0 flex-col overflow-hidden bg-background",!k&&"border-l border-border/40",k?"absolute inset-0 z-20 min-w-0":"relative h-full flex-shrink-0",!N&&"pointer-events-none",v||!N||P?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:Me,style:I,children:[!k&&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",v&&"bg-[var(--interactive-border)]"),onPointerDown:le,onPointerMove:ve,onPointerUp:ne,onPointerCancel:ne,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),De,s.jsxs("div",{className:Pe("relative min-h-0 flex-1 overflow-hidden",v&&"pointer-events-none"),children:[ye?s.jsx("div",{className:Pe("absolute inset-0",ue?"block":"hidden"),children:s.jsx(dh,{mode:"editor-only"})}):null,Ee.map(_=>{const be=ga(_.dedupeKey);if(!be)return null;const R=q(_.id,be,_.readOnly);return R?s.jsx("iframe",{ref:de=>{if(!de){M.current.delete(_.id);return}M.current.set(_.id,de)},src:R,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:be}),className:Pe("absolute inset-0 h-full w-full border-0 bg-background",z===_.id?"block":"hidden"),onLoad:()=>{Se(),Be(),_e()}},_.id):null}),ge.map(_=>s.jsx("div",{className:Pe("absolute inset-0",S?.id!==_.id&&"hidden"),children:s.jsx(je,{initialUrl:_.targetPath??"",directory:n,tabID:_.id})},_.id)),oe.map(_=>s.jsx("div",{className:Pe("absolute inset-0",S?.id!==_.id&&"hidden"),children:s.jsx(oh,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:_.diffScope??(_.stagedDiff?"staged":"working"),onDiffScopeChange:me,targetFilePath:_.targetPath,flushContent:!0})},_.id)),S?.mode!=="chat"&&!ue&&S?.mode!=="browser"&&S?.mode!=="diff"?pe:null]})]})},f0=(t,e)=>!t||e.length===0?"":JSON.stringify([t,e]),m0=(t,e,n,r)=>!n||r!==n||t.length===0?[]:ko(t,e,o=>o.name,{limit:10,threshold:.4}),dc=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},h0=()=>{const t=ht.c(172),{t:e}=yt(),n=Re(p0),r=Re(g0),o=Re(x0),a=Re(b0),c=Re(w0),l=Re(y0),d=Re(v0),f=Re(j0),m=Re(S0),u=Re(N0),p=Re(k0),x=Re(C0),b=mt(A0),w=mt(D0),g=pr(T0),h=Xs(P0),C=Ds(I0),j=Ds(R0),S=wi(),N=yc(E0),{files:k,git:y}=Zn(),D=vn(M0),{isMobile:V}=$r();let v;t[0]!==S?(v=S?dc(S):null,t[0]=S,t[1]=v):v=t[1];const O=v,[P,E]=i.useState(""),T=Za(P,200).trim();let W;t[2]!==P?(W=P.trim(),t[2]=P,t[3]=W):W=t[3];const U=W;let L,M;t[4]!==n?(L=()=>{n&&E("")},M=[n],t[4]=n,t[5]=L,t[6]=M):(L=t[5],M=t[6]),i.useEffect(L,M);let ee,ie;t[7]!==g||t[8]!==D||t[9]!==y||t[10]!==n?(ee=()=>{if(!n||!y)return;const Ke=setTimeout(()=>{const Ze=new Set;for(const Bt of g){const Rt=Br(Bt);!Rt||Ze.has(Rt)||(Ze.add(Rt),D(Rt,y))}},0);return()=>clearTimeout(Ke)},ie=[n,g,y,D],t[7]=g,t[8]=D,t[9]=y,t[10]=n,t[11]=ee,t[12]=ie):(ee=t[11],ie=t[12]),i.useEffect(ee,ie);let X;t[13]!==r?(X=()=>r(!1),t[13]=r,t[14]=X):X=t[14];const H=X;let te;t[15]!==H?(te=Ke=>()=>{H(),Ke()},t[15]=H,t[16]=te):te=t[16];const re=te;let le;t[17]!==C?.id||t[18]!==C?.path||t[19]!==h||t[20]!==V||t[21]!==u||t[22]!==b||t[23]!==re||t[24]!==o||t[25]!==l||t[26]!==a||t[27]!==e||t[28]!==m||t[29]!==f||t[30]!==d?(le=()=>{const Ke=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(A,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:re(()=>{o("chat"),l(!1),b()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(A,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:re(F0)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(A,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:re(O0)},{id:"toggle-sidebar",title:e(V?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(A,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(V?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:re(()=>{if(V){const{isSessionSwitcherOpen:Ze}=Re.getState();l(!Ze)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(A,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:re(()=>f())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(A,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:re(()=>m())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(A,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:re(()=>{h&&u(h)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(A,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:re(()=>a(!0))}];return Wa()&&Ke.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(A,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:re(()=>{Zr("desktop_open_draft_mini_chat_window",{directory:dc(h||C?.path||""),projectId:C?.id??null}).catch(L0)})}),Ke},t[17]=C?.id,t[18]=C?.path,t[19]=h,t[20]=V,t[21]=u,t[22]=b,t[23]=re,t[24]=o,t[25]=l,t[26]=a,t[27]=e,t[28]=m,t[29]=f,t[30]=d,t[31]=le):le=t[31],C?.id,C?.path;let ve;t[32]!==le?(ve=le(),t[32]=le,t[33]=ve):ve=t[33];const ne=ve;let we;t[34]===Symbol.for("react.memo_cache_sentinel")?(we=gr(),t[34]=we):we=t[34];const he=we;let Me,z;t[35]===Symbol.for("react.memo_cache_sentinel")?(Me=_r(),z=!he&&jc(),t[35]=Me,t[36]=z):(Me=t[35],z=t[36]);let K;t[37]!==V?(K={isVSCode:Me,isWeb:z,isDesktop:he,isMobile:V},t[37]=V,t[38]=K):K=t[38];const q=K;let me;if(t[39]!==re||t[40]!==a||t[41]!==c||t[42]!==q){let Ke;t[44]!==q?(Ke=Bt=>Bt.isAvailable?Bt.isAvailable(q):!0,t[44]=q,t[45]=Ke):Ke=t[45];let Ze;t[46]!==re||t[47]!==a||t[48]!==c?(Ze=Bt=>{const Rt=ib(Bt.slug)??"settings-3",Ot=(Bt.keywords??[]).join(" ");return{id:`settings:${Bt.slug}`,title:Bt.title,icon:Bt.slug==="mcp"?s.jsx(Jl,{className:"mr-2 h-4 w-4"}):s.jsx(A,{name:Rt,className:"mr-2 h-4 w-4"}),searchText:`${Bt.title} ${Bt.group} ${Ot}`,onSelect:re(()=>{c(Bt.slug),a(!0)})}},t[46]=re,t[47]=a,t[48]=c,t[49]=Ze):Ze=t[49],me=rb.filter(B0).filter(Ke).map(Ze),t[39]=re,t[40]=a,t[41]=c,t[42]=q,t[43]=me}else me=t[43];const Se=me,Be=V0;let _e;if(t[50]!==g){let Ke;t[52]===Symbol.for("react.memo_cache_sentinel")?(Ke=(Ze,Bt)=>Be(Bt)-Be(Ze),t[52]=Ke):Ke=t[52],_e=[...g].sort(Ke),t[50]=g,t[51]=_e}else _e=t[51];const Le=_e,pe=bm(),Ee=mt(_0);let ge;t[53]!==pe||t[54]!==Ee?(ge=(Ke,Ze)=>{const Bt=Ee.get(Ke);return Bt?.branch?Bt.branch.trim()||null:Ze&&pe.get(Ze)?.trim()||null},t[53]=pe,t[54]=Ee,t[55]=ge):ge=t[55];const oe=ge;let je;t[56]===Symbol.for("react.memo_cache_sentinel")?(je=[],t[56]=je):je=t[56];const[ye,ue]=i.useState(je),[De,I]=i.useState(""),_=f0(O,T);let be;t[57]!==O||t[58]!==_||t[59]!==n||t[60]!==N||t[61]!==ue||t[62]!==I||t[63]!==T?(be=()=>{if(!n){ue([]),I("");return}if(!_){ue([]),I("");return}if(!O){ue([]),I("");return}let Ke=!1;return N(O,T,10,{type:"file"}).then(Ze=>{Ke||(ue(Ze.map($0)),I(_))}).catch(()=>{Ke||(ue([]),I(_))}),()=>{Ke=!0}},t[57]=O,t[58]=_,t[59]=n,t[60]=N,t[61]=ue,t[62]=I,t[63]=T,t[64]=be):be=t[64];let R;t[65]!==O||t[66]!==_||t[67]!==n||t[68]!==N||t[69]!==T?(R=[n,O,T,_,N],t[65]=O,t[66]=_,t[67]=n,t[68]=N,t[69]=T,t[70]=R):R=t[70],i.useEffect(be,R);const de=U.length>0;let fe;e:{if(!de){let Ze;t[71]!==ne?(Ze=ne.map(z0),t[71]=ne,t[72]=Ze):Ze=t[72],fe=Ze;break e}let Ke;t[73]!==ne||t[74]!==U?(Ke=ko(ne,U,W0,{limit:7,noFuzzy:!0}),t[73]=ne,t[74]=U,t[75]=Ke):Ke=t[75],fe=Ke}const $=fe;let Ae;e:{if(!de){let Ze;t[76]===Symbol.for("react.memo_cache_sentinel")?(Ze=[],t[76]=Ze):Ze=t[76],Ae=Ze;break e}let Ke;t[77]!==U||t[78]!==Se?(Ke=ko(Se,U,U0,{limit:7,noFuzzy:!0}),t[77]=U,t[78]=Se,t[79]=Ke):Ke=t[79],Ae=Ke}const Ve=Ae;let Ne;e:{if(!de){let Ze;t[80]!==Le?(Ze=Le.slice(0,5).map(H0),t[80]=Le,t[81]=Ze):Ze=t[81],Ne=Ze;break e}let Ke;t[82]!==U||t[83]!==Le?(Ke=ko(Le,U,G0,{limit:7,threshold:.2}),t[82]=U,t[83]=Le,t[84]=Ke):Ke=t[84],Ne=Ke}const Y=Ne;let F;e:{if(!n){let Ze;t[85]===Symbol.for("react.memo_cache_sentinel")?(Ze=[],t[85]=Ze):Ze=t[85],F=Ze;break e}let Ke;t[86]!==ye||t[87]!==De||t[88]!==_||t[89]!==T?(Ke=m0(ye,T,_,De),t[86]=ye,t[87]=De,t[88]=_,t[89]=T,t[90]=Ke):Ke=t[90],F=Ke}const se=F,Oe=n&&_.length>0&&De!==_;let ce;e:{if(!de){let Ze;t[91]===Symbol.for("react.memo_cache_sentinel")?(Ze=[],t[91]=Ze):Ze=t[91],ce=Ze;break e}let Ke;if(t[92]!==U||t[93]!==j){const Ze=j.map(K0);Ke=ko(Ze,U,q0,{limit:7,threshold:.4}),t[92]=U,t[93]=j,t[94]=Ke}else Ke=t[94];ce=Ke}const Ue=ce;let qe,Ye,tt,xt,vt,Mt,Tt,Kt,Ut,Zt,ns,es,Ce,Qe;if(t[95]!==oe||t[96]!==H||t[97]!==O||t[98]!==k||t[99]!==de||t[100]!==n||t[101]!==p||t[102]!==b||t[103]!==P||t[104]!==$||t[105]!==se||t[106]!==Ue||t[107]!==Y||t[108]!==Ve||t[109]!==r||t[110]!==w||t[111]!==x||t[112]!==e){const Ke=$.map(Y0),Ze=Ve.map(Q0),Bt=Y.map(J0),Rt=de?se.map(X0):[],Ot=de?Ue.map(Z0):[];let rs;e:{if(!de){rs=["commands","sessions"];break e}const $t=eS,Fe=[{key:"commands",score:$t($)},{key:"settings",score:$t(Ve)},{key:"sessions",score:$t(Y)},{key:"files",score:$t(se)},{key:"projects",score:$t(Ue)}];Fe.sort(tS),rs=Fe.map(sS)}const Wt=rs,Et=$t=>{H(),w($t.id,Br($t))},qt=async $t=>{if(!O)return;const Fe=await Yc(k,$t);if(!Fe.ok){ae.error(Qc(Fe.reason));return}p(O,$t),H()},hs=($t,Fe)=>{H(),b({selectedProjectId:$t,directoryOverride:Fe})},ts=$t=>Ua(gi($t,x));xt=_s,es=n,Ce=r;let as;t[127]!==e?(as=e("commandPalette.title"),t[127]=e,t[128]=as):as=t[128];let gs;t[129]!==as?(gs=s.jsx(Hs,{children:as}),t[129]=as,t[130]=gs):gs=t[130];let Ft;t[131]!==e?(Ft=e("commandPalette.description"),t[131]=e,t[132]=Ft):Ft=t[132];let Lt;t[133]!==Ft?(Lt=s.jsx(mn,{children:Ft}),t[133]=Ft,t[134]=Lt):Lt=t[134],t[135]!==gs||t[136]!==Lt?(Qe=s.jsxs(sn,{className:"sr-only",children:[gs,Lt]}),t[135]=gs,t[136]=Lt,t[137]=Qe):Qe=t[137],tt=Vs,Zt="overflow-hidden p-0",ns=!0,Ye=Ha,Tt=!1,Kt="[&_[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 Ht;t[138]!==e?(Ht=e("commandPalette.input.placeholder"),t[138]=e,t[139]=Ht):Ht=t[139],t[140]!==P||t[141]!==Ht?(Ut=s.jsx(Ga,{value:P,onValueChange:E,placeholder:Ht}),t[140]=P,t[141]=Ht,t[142]=Ut):Ut=t[142],qe=Ka;let Yt;t[143]!==e?(Yt=e("commandPalette.empty.noResults"),t[143]=e,t[144]=Yt):Yt=t[144],t[145]!==Yt?(vt=s.jsx(qa,{children:Yt}),t[145]=Yt,t[146]=vt):vt=t[146],Mt=Wt.map($t=>$t==="commands"&&Ke.length>0?s.jsx(Qr,{children:Ke.map(Fe=>s.jsxs(Jr,{value:Fe.id,onSelect:Fe.onSelect,children:[Fe.icon,s.jsx("span",{children:Fe.title}),Fe.shortcutId?s.jsx(Fg,{children:ts(Fe.shortcutId)}):null]},Fe.id))},"commands"):$t==="settings"&&Ze.length>0?s.jsx(Qr,{children:Ze.map(nS)},"settings"):$t==="sessions"&&Bt.length>0?s.jsx(Qr,{children:Bt.map(Fe=>{const st=Fe.title||e("commandPalette.session.untitled"),wt=Br(Fe),St=oe(Fe.id,wt);return s.jsxs(Jr,{value:`session:${Fe.id}`,onSelect:()=>Et(Fe),children:[s.jsx(A,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:st}),St?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:St})]}):null]},Fe.id)})},"sessions"):$t==="files"&&Rt.length>0?s.jsx(Qr,{children:Rt.map(Fe=>{const st=Og(Fe.relativePath||Fe.name,{maxLength:80});return s.jsxs(Jr,{value:`file:${Fe.path}`,onSelect:()=>{qt(Fe.path)},children:[s.jsx(ei,{filePath:Fe.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":Fe.relativePath,children:st})]},`file:${Fe.path}`)})},"files"):$t==="projects"&&Ot.length>0?s.jsx(Qr,{children:Ot.map(Fe=>{const st=Fe.displayName;return s.jsxs(Jr,{value:`project:${Fe.id}`,onSelect:()=>hs(Fe.id,Fe.path),children:[s.jsx(A,{name:"folder",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:st}),s.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:Fe.path})]},`project:${Fe.id}`)})},"projects"):null),t[95]=oe,t[96]=H,t[97]=O,t[98]=k,t[99]=de,t[100]=n,t[101]=p,t[102]=b,t[103]=P,t[104]=$,t[105]=se,t[106]=Ue,t[107]=Y,t[108]=Ve,t[109]=r,t[110]=w,t[111]=x,t[112]=e,t[113]=qe,t[114]=Ye,t[115]=tt,t[116]=xt,t[117]=vt,t[118]=Mt,t[119]=Tt,t[120]=Kt,t[121]=Ut,t[122]=Zt,t[123]=ns,t[124]=es,t[125]=Ce,t[126]=Qe}else qe=t[113],Ye=t[114],tt=t[115],xt=t[116],vt=t[117],Mt=t[118],Tt=t[119],Kt=t[120],Ut=t[121],Zt=t[122],ns=t[123],es=t[124],Ce=t[125],Qe=t[126];let ot;t[147]!==Oe||t[148]!==e?(ot=Oe?s.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:e("commandPalette.empty.searchingFiles")}):null,t[147]=Oe,t[148]=e,t[149]=ot):ot=t[149];let bt;t[150]!==qe||t[151]!==vt||t[152]!==Mt||t[153]!==ot?(bt=s.jsxs(qe,{children:[vt,Mt,ot]}),t[150]=qe,t[151]=vt,t[152]=Mt,t[153]=ot,t[154]=bt):bt=t[154];let Je;t[155]!==Ye||t[156]!==Tt||t[157]!==Kt||t[158]!==Ut||t[159]!==bt?(Je=s.jsxs(Ye,{shouldFilter:Tt,className:Kt,children:[Ut,bt]}),t[155]=Ye,t[156]=Tt,t[157]=Kt,t[158]=Ut,t[159]=bt,t[160]=Je):Je=t[160];let Pt;t[161]!==tt||t[162]!==Zt||t[163]!==ns||t[164]!==Je?(Pt=s.jsx(tt,{className:Zt,showCloseButton:ns,children:Je}),t[161]=tt,t[162]=Zt,t[163]=ns,t[164]=Je,t[165]=Pt):Pt=t[165];let Xe;return t[166]!==xt||t[167]!==es||t[168]!==Ce||t[169]!==Qe||t[170]!==Pt?(Xe=s.jsxs(xt,{open:es,onOpenChange:Ce,children:[Qe,Pt]}),t[166]=xt,t[167]=es,t[168]=Ce,t[169]=Qe,t[170]=Pt,t[171]=Xe):Xe=t[171],Xe};function p0(t){return t.isCommandPaletteOpen}function g0(t){return t.setCommandPaletteOpen}function x0(t){return t.setActiveMainTab}function b0(t){return t.setSettingsDialogOpen}function w0(t){return t.setSettingsPage}function y0(t){return t.setSessionSwitcherOpen}function v0(t){return t.toggleSidebar}function j0(t){return t.toggleRightSidebar}function S0(t){return t.toggleBottomTerminal}function N0(t){return t.openContextOverview}function k0(t){return t.openContextFile}function C0(t){return t.shortcutOverrides}function A0(t){return t.openNewSessionDraft}function D0(t){return t.setCurrentSession}function T0(t){return t.activeSessions}function P0(t){return t.currentDirectory}function I0(t){return t.getActiveProject()}function R0(t){return t.projects}function E0(t){return t.searchFiles}function M0(t){return t.ensureStatus}function F0(){wm()}function O0(){Lr.requestDirectoryDialog()}function L0(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function B0(t){return t.slug!=="home"}function V0(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function _0(t){return t.worktreeMetadata}function $0(t){return{path:dc(t.path),name:t.name,relativePath:t.relativePath}}function z0(t){return{item:t,score:0}}function W0(t){return t.searchText}function U0(t){return t.searchText}function H0(t){return{item:t,score:0}}function G0(t){return t.title||""}function K0(t){return{...t,displayName:t.label||t.path.split("/").pop()||t.path,searchText:`${t.label||""} ${t.path}`}}function q0(t){return t.searchText}function Y0(t){return t.item}function Q0(t){return t.item}function J0(t){return t.item}function X0(t){return t.item}function Z0(t){return t.item}function eS(t){return t.length?t[0].score:1/0}function tS(t,e){return t.score-e.score}function sS(t){return t.key}function nS(t){return s.jsxs(Jr,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const cf=(t,e,n)=>Bg(t)?Ua(gi(t,n)):e,rS=()=>{const t=ht.c(68),{t:e}=yt(),n=Re(iS),r=Re(oS),o=Re(aS);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=Lg(),t[0]=a):a=t[0];const c=a;let l,d,f,m,u,p,x,b,w;if(t[1]!==n||t[2]!==r||t[3]!==o||t[4]!==e){const T=[{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,b=n,w=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 W;t[14]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx(A,{name:"settings-3",className:"h-5 w-5"}),t[14]=W):W=t[14];let U;t[15]!==e?(U=e("helpDialog.title"),t[15]=e,t[16]=U):U=t[16];let L;t[17]!==U?(L=s.jsxs(Hs,{className:"flex items-center gap-2",children:[W,U]}),t[17]=U,t[18]=L):L=t[18];let M;t[19]!==e?(M=e("helpDialog.description"),t[19]=e,t[20]=M):M=t[20];let ee;t[21]!==M?(ee=s.jsx(mn,{children:M}),t[21]=M,t[22]=ee):ee=t[22],t[23]!==L||t[24]!==ee?(x=s.jsxs(sn,{children:[L,ee]}),t[23]=L,t[24]=ee,t[25]=x):x=t[25],u="flex-1 overflow-y-auto mt-3 pr-1",f="space-y-4",m=T.map(ie=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(ie.categoryKey)}),s.jsx("div",{className:"space-y-1",children:ie.items.map(X=>{const H=X.id?cf(X.id,Array.isArray(X.keys)?X.keys[0]:X.keys,o):Array.isArray(X.keys)?X.keys:X.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:[X.icon&&s.jsx(A,{name:X.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(X.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(H)?H:[H]).map((te,re)=>s.jsxs(i.Fragment,{children:[re>0&&s.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:e("helpDialog.keyCombiner.or")}),s.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:te})]},`${te}-${re}`))})]},X.id||X.descriptionKey)})})]},ie.categoryKey)),t[1]=n,t[2]=r,t[3]=o,t[4]=e,t[5]=l,t[6]=d,t[7]=f,t[8]=m,t[9]=u,t[10]=p,t[11]=x,t[12]=b,t[13]=w}else l=t[5],d=t[6],f=t[7],m=t[8],u=t[9],p=t[10],x=t[11],b=t[12],w=t[13];let g;t[26]!==f||t[27]!==m?(g=s.jsx("div",{className:f,children:m}),t[26]=f,t[27]=m,t[28]=g):g=t[28];let h;t[29]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(A,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),t[29]=h):h=t[29];let C;t[30]!==e?(C=e("helpDialog.proTips.title"),t[30]=e,t[31]=C):C=t[31];let j;t[32]!==C?(j=s.jsx("p",{className:"font-medium mb-1",children:C}),t[32]=C,t[33]=j):j=t[33];let S;t[34]!==o||t[35]!==e?(S=e("helpDialog.proTips.commandPalette",{shortcut:cf("open_command_palette",`${c} P`,o)}),t[34]=o,t[35]=e,t[36]=S):S=t[36];let N;t[37]!==S?(N=s.jsxs("li",{children:["• ",S]}),t[37]=S,t[38]=N):N=t[38];let k;t[39]!==e?(k=e("helpDialog.proTips.recentSessions"),t[39]=e,t[40]=k):k=t[40];let y;t[41]!==k?(y=s.jsxs("li",{children:["• ",k]}),t[41]=k,t[42]=y):y=t[42];let D;t[43]!==e?(D=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=D):D=t[44];let V;t[45]!==D?(V=s.jsxs("li",{children:["• ",D]}),t[45]=D,t[46]=V):V=t[46];let v;t[47]!==N||t[48]!==y||t[49]!==V?(v=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[N,y,V]}),t[47]=N,t[48]=y,t[49]=V,t[50]=v):v=t[50];let O;t[51]!==j||t[52]!==v?(O=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:[j,v]})]})}),t[51]=j,t[52]=v,t[53]=O):O=t[53];let P;t[54]!==O||t[55]!==u||t[56]!==g?(P=s.jsxs("div",{className:u,children:[g,O]}),t[54]=O,t[55]=u,t[56]=g,t[57]=P):P=t[57];let E;t[58]!==l||t[59]!==P||t[60]!==p||t[61]!==x?(E=s.jsxs(l,{className:p,children:[x,P]}),t[58]=l,t[59]=P,t[60]=p,t[61]=x,t[62]=E):E=t[62];let B;return t[63]!==d||t[64]!==E||t[65]!==b||t[66]!==w?(B=s.jsx(d,{open:b,onOpenChange:w,children:E}),t[63]=d,t[64]=E,t[65]=b,t[66]=w,t[67]=B):B=t[67],B};function iS(t){return t.isHelpDialogOpen}function oS(t){return t.setHelpDialogOpen}function aS(t){return t.shortcutOverrides}const lS=()=>{const t=ht.c(32),{t:e}=yt(),n=Re(cS),r=Re(dS),o=Re(uS);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await xr(o)).ok){ae.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}ae.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(Hs,{children:l}),t[5]=l,t[6]=d):d=t[6];let f;t[7]!==e?(f=e("openCodeStatusDialog.description"),t[7]=e,t[8]=f):f=t[8];let m;t[9]!==f?(m=s.jsx(mn,{children:f}),t[9]=f,t[10]=m):m=t[10];let u;t[11]!==d||t[12]!==m?(u=s.jsxs(sn,{children:[d,m]}),t[11]=d,t[12]=m,t[13]=u):u=t[13];let p;t[14]!==e?(p=e("openCodeStatusDialog.actions.copy"),t[14]=e,t[15]=p):p=t[15];let x;t[16]!==c||t[17]!==p?(x=s.jsx("div",{className:"flex items-center justify-end",children:s.jsx("button",{type:"button",onClick:c,className:"app-region-no-drag inline-flex h-9 items-center justify-center rounded-md px-3 typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:p})}),t[16]=c,t[17]=p,t[18]=x):x=t[18];let b;t[19]!==o||t[20]!==e?(b=o||e("openCodeStatusDialog.empty.noData"),t[19]=o,t[20]=e,t[21]=b):b=t[21];let w;t[22]!==b?(w=s.jsx("pre",{className:"max-h-[60vh] overflow-auto rounded-lg bg-surface-muted p-4 typography-code text-foreground whitespace-pre-wrap",children:b}),t[22]=b,t[23]=w):w=t[23];let g;t[24]!==u||t[25]!==x||t[26]!==w?(g=s.jsxs(Vs,{className:"max-w-2xl",children:[u,x,w]}),t[24]=u,t[25]=x,t[26]=w,t[27]=g):g=t[27];let h;return t[28]!==n||t[29]!==r||t[30]!==g?(h=s.jsx(_s,{open:n,onOpenChange:r,children:g}),t[28]=n,t[29]=r,t[30]=g,t[31]=h):h=t[31],h};function cS(t){return t.isOpenCodeStatusDialogOpen}function dS(t){return t.setOpenCodeStatusDialogOpen}function uS(t){return t.openCodeStatusText}const fS=180,df=600,mS=1,hS=6,pS=({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(()=>_r(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<mS&&a.current.length>0;){const m=a.current.shift();if(!m)break;mt.getState().currentSessionId!==m&&(Ud(m).renderable||(c.current.add(m),r(m).catch(()=>{}).finally(()=>{c.current.delete(m),d()})))}},[r,l]),f=i.useCallback(m=>{if(l||!m||m===t||typeof window>"u"||Ud(m).renderable||c.current.has(m)||a.current.includes(m))return;a.current.length>=hS&&a.current.shift();const u=o.current.get(m);u!==void 0&&window.clearTimeout(u);const p=window.setTimeout(()=>{o.current.delete(m),a.current.push(m),d()},fS);o.current.set(m,p)},[t,l,d]);i.useEffect(()=>{if(l||!t||e.length===0)return;const m=window.setTimeout(()=>{const u=e.findIndex(p=>p.id===t);u<0||(f(e[u-1]?.id),f(e[u+1]?.id))},df);return()=>window.clearTimeout(m)},[t,l,f,e]),i.useEffect(()=>{if(l||!t||n.length===0)return;const m=window.setTimeout(()=>{const u=n.indexOf(t);u<0||(f(n[u-1]),f(n[u+1]))},df);return()=>window.clearTimeout(m)},[t,l,n,f]),i.useEffect(()=>{const m=o.current;return()=>{m.forEach(u=>{clearTimeout(u)}),m.clear(),a.current=[]}},[])};let Zi=null,eo=null,ba=null,Vo=0,Va=null;const Mi=new Set,gS=3e4,xS=45e3,Nh=()=>{ba&&(clearTimeout(ba),ba=null)},kh=()=>{if(eo||Mi.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Vo,5)),gS);eo=setTimeout(()=>{eo=null,Vo+=1,td()},t)},_o=()=>{Nh(),Zi&&Zi.close(),Zi=null},uf=()=>{Nh(),Mi.size!==0&&(ba=setTimeout(()=>{_o(),kh()},xS))},bS=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}},wS=t=>{if(t.type==="openchamber:event-stream-ready"){Vo=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 Mi)d(l)},td=()=>{if(typeof window>"u"||Mi.size===0||typeof EventSource!="function"||Zi&&Zi.readyState!==EventSource.CLOSED)return;_o();const t=new EventSource(Ii().sse("/api/openchamber/events"));t.onopen=()=>{uf()},t.onmessage=e=>{uf();const n=bS(e.data);n&&wS(n)},t.onerror=()=>{_o(),kh()},Zi=t},yS=()=>{Va||typeof window>"u"||(Va=em(()=>{_o(),Vo=0,td()}))},vS=()=>{Va?.(),Va=null},Ch=t=>(Mi.add(t),yS(),td(),()=>{Mi.delete(t),Mi.size===0&&(eo&&(clearTimeout(eo),eo=null),Vo=0,_o(),vS())}),tl=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},lo=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},jS=async t=>{const e=lo(t),n=await Ps(`/api/projects/${encodeURIComponent(e)}/scheduled-tasks`);if(!n.ok)throw new Error(await tl(n,"Failed to load scheduled tasks"));const r=await n.json().catch(()=>null);return!r||!Array.isArray(r.tasks)?[]:r.tasks},ff=async(t,e)=>{const n=lo(t),r=await Ps(`/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 tl(r,"Failed to save scheduled task"));const o=await r.json().catch(()=>null);return!o||!Array.isArray(o.tasks)?[]:o.tasks},SS=async(t,e)=>{const n=lo(t),r=lo(e),o=await Ps(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}`,{method:"DELETE",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await tl(o,"Failed to delete scheduled task"));const a=await o.json().catch(()=>null);return!a||!Array.isArray(a.tasks)?[]:a.tasks},NS=async(t,e)=>{const n=lo(t),r=lo(e),o=await Ps(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}/run`,{method:"POST",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await tl(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 Ah(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return Kf.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function kS(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=Kf.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"}],Dh=[0,1,2,3,4,5,6],uc=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"],mf=()=>{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}`},wa=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},hf=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},AS=(t,e,n)=>{const r=wa(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},pf=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),DS=(t,e)=>{const n=t.getFullYear(),r=t.getMonth(),c=(new Date(n,r,1).getDay()-e+7)%7,l=new Date(n,r+1,0).getDate(),d=new Date(n,r,0).getDate(),f=[];for(let m=0;m<42;m+=1){const u=m-c+1;if(u<=0){const p=d+u;f.push({date:new Date(n,r-1,p),inCurrentMonth:!1});continue}if(u>l){f.push({date:new Date(n,r+1,u-l),inCurrentMonth:!1});continue}f.push({date:new Date(n,r,u),inCurrentMonth:!0})}return f},TS=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}},ki=(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")}`},po=(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"},gf=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:po(t,{min:1,max:12}),ra=t=>/^[0-5][0-9]$/.test(t)?t:po(t,{max:59}),PS=(t,e)=>po(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),xf=(t,e)=>po(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),IS=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}},RS=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}},ES=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return Dh.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},MS=(t,e)=>[...t.slice(e),...t.slice(0,e)],Qn=t=>{const e=ht.c(6),{htmlFor:n,required:r,children:o}=t;let a;e[0]!==r?(a=r&&s.jsx("span",{className:"ml-0.5 text-destructive",children:"*"}),e[0]=r,e[1]=a):a=e[1];let c;return e[2]!==o||e[3]!==n||e[4]!==a?(c=s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,a]})}),e[2]=o,e[3]=n,e[4]=a,e[5]=c):c=e[5],c},bf=t=>{const e=ht.c(84),{value:n,onChange:r,use24Hour:o,hourAriaLabel:a,minuteAriaLabel:c,periodAriaLabel:l,amLabel:d,pmLabel:f}=t;let m;e[0]!==n?(m=TS(n),e[0]=n,e[1]=m):m=e[1];const u=m,p=nt.useRef(null),x=nt.useRef(null),[b,w]=nt.useState(null),[g,h]=nt.useState(null),C=nt.useRef(null),j=nt.useRef(null);let S;e[2]===Symbol.for("react.memo_cache_sentinel")?(S=ge=>{C.current=ge,w(ge)},e[2]=S):S=e[2];const N=S;let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=ge=>{j.current=ge,h(ge)},e[3]=k):k=e[3];const y=k,D=$S,V=zS,v=WS;let O;e[4]!==r||e[5]!==u.meridiem||e[6]!==u.minute||e[7]!==o?(O=ge=>{const oe=ge.replace(/\D/g,"").slice(0,2);N(oe),oe.length===2&&(r(o?v(D(oe),u.minute):ki(gf(oe),u.minute,u.meridiem)),N(null),x.current?.focus())},e[4]=r,e[5]=u.meridiem,e[6]=u.minute,e[7]=o,e[8]=O):O=e[8];const P=O;let E;e[9]!==r||e[10]!==u.meridiem||e[11]!==u.minute||e[12]!==o?(E=()=>{const ge=C.current;if(ge!==null&&(N(null),ge.length!==0)){if(o){r(v(D(ge.padStart(2,"0")),u.minute));return}r(ki(gf(ge.padStart(2,"0")),u.minute,u.meridiem))}},e[9]=r,e[10]=u.meridiem,e[11]=u.minute,e[12]=o,e[13]=E):E=e[13];const B=E;let T;e[14]!==r||e[15]!==u.hour12||e[16]!==u.hour24||e[17]!==u.meridiem||e[18]!==o?(T=ge=>{const oe=ge.replace(/\D/g,"").slice(0,2);y(oe),oe.length===2&&(r(o?v(u.hour24,ra(oe)):ki(u.hour12,ra(oe),u.meridiem)),y(null))},e[14]=r,e[15]=u.hour12,e[16]=u.hour24,e[17]=u.meridiem,e[18]=o,e[19]=T):T=e[19];const W=T;let U;e[20]!==r||e[21]!==u.hour12||e[22]!==u.hour24||e[23]!==u.meridiem||e[24]!==o?(U=()=>{const ge=j.current;ge!==null&&(y(null),ge.length!==0&&r(o?v(u.hour24,ra(ge.padStart(2,"0"))):ki(u.hour12,ra(ge.padStart(2,"0")),u.meridiem)))},e[20]=r,e[21]=u.hour12,e[22]=u.hour24,e[23]=u.meridiem,e[24]=o,e[25]=U):U=e[25];const L=U;let M;e[26]!==r||e[27]!==u.hour12||e[28]!==u.hour24||e[29]!==u.meridiem||e[30]!==u.minute||e[31]!==o?(M=ge=>r(o?v(V(u.hour24,ge),u.minute):ki(PS(u.hour12,ge),u.minute,u.meridiem)),e[26]=r,e[27]=u.hour12,e[28]=u.hour24,e[29]=u.meridiem,e[30]=u.minute,e[31]=o,e[32]=M):M=e[32];const ee=M;let ie;e[33]!==r||e[34]!==u.hour12||e[35]!==u.hour24||e[36]!==u.meridiem||e[37]!==u.minute||e[38]!==o?(ie=ge=>r(o?v(u.hour24,xf(u.minute,ge)):ki(u.hour12,xf(u.minute,ge),u.meridiem)),e[33]=r,e[34]=u.hour12,e[35]=u.hour24,e[36]=u.meridiem,e[37]=u.minute,e[38]=o,e[39]=ie):ie=e[39];const X=ie;let H;e[40]!==r||e[41]!==u.hour12||e[42]!==u.meridiem||e[43]!==u.minute?(H=ge=>{ge!==u.meridiem&&r(ki(u.hour12,u.minute,ge))},e[40]=r,e[41]=u.hour12,e[42]=u.meridiem,e[43]=u.minute,e[44]=H):H=e[44];const te=H;let re;e[45]!==B||e[46]!==ee?(re=ge=>{if(ge.key==="ArrowRight"){ge.preventDefault(),B(),x.current?.focus();return}(ge.key==="ArrowUp"||ge.key==="ArrowDown")&&(ge.preventDefault(),N(null),ee(ge.key==="ArrowUp"?1:-1))},e[45]=B,e[46]=ee,e[47]=re):re=e[47];const le=re;let ve;e[48]!==L||e[49]!==X?(ve=ge=>{if(ge.key==="ArrowLeft"&&(ge.currentTarget.selectionStart??0)===0){ge.preventDefault(),L(),p.current?.focus();return}(ge.key==="ArrowUp"||ge.key==="ArrowDown")&&(ge.preventDefault(),y(null),X(ge.key==="ArrowUp"?1:-1))},e[48]=L,e[49]=X,e[50]=ve):ve=e[50];const ne=ve,we=o?"px-2":"pl-2 pr-1";let he;e[51]!==we?(he=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",we),e[51]=we,e[52]=he):he=e[52];const Me=b??(o?u.hour24:u.hour12);let z;e[53]!==P?(z=ge=>P(ge.target.value),e[53]=P,e[54]=z):z=e[54];let K;e[55]===Symbol.for("react.memo_cache_sentinel")?(K=()=>N(""),e[55]=K):K=e[55];let q;e[56]!==B||e[57]!==a||e[58]!==le||e[59]!==Me||e[60]!==z?(q=s.jsx("input",{ref:p,inputMode:"numeric",value:Me,onChange:z,onKeyDown:le,onFocus:K,onBlur:B,maxLength:2,"aria-label":a,className:"h-7 w-7 shrink-0 rounded-sm bg-transparent text-center font-mono text-sm tabular-nums text-foreground outline-none caret-transparent focus:bg-interactive-hover"}),e[56]=B,e[57]=a,e[58]=le,e[59]=Me,e[60]=z,e[61]=q):q=e[61];let me;e[62]===Symbol.for("react.memo_cache_sentinel")?(me=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=me):me=e[62];const Se=g??u.minute;let Be;e[63]!==W?(Be=ge=>W(ge.target.value),e[63]=W,e[64]=Be):Be=e[64];let _e;e[65]===Symbol.for("react.memo_cache_sentinel")?(_e=()=>y(""),e[65]=_e):_e=e[65];let Le;e[66]!==L||e[67]!==c||e[68]!==ne||e[69]!==Se||e[70]!==Be?(Le=s.jsx("input",{ref:x,inputMode:"numeric",value:Se,onChange:Be,onKeyDown:ne,onFocus:_e,onBlur:L,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]=L,e[67]=c,e[68]=ne,e[69]=Se,e[70]=Be,e[71]=Le):Le=e[71];let pe;e[72]!==d||e[73]!==u.meridiem||e[74]!==l||e[75]!==f||e[76]!==te||e[77]!==o?(pe=o?null:s.jsxs(Gn,{value:u.meridiem,onValueChange:ge=>te(ge),children:[s.jsx(Kn,{"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(Dn,{})}),s.jsxs(qn,{children:[s.jsx(Bs,{value:"AM",children:d}),s.jsx(Bs,{value:"PM",children:f})]})]}),e[72]=d,e[73]=u.meridiem,e[74]=l,e[75]=f,e[76]=te,e[77]=o,e[78]=pe):pe=e[78];let Ee;return e[79]!==he||e[80]!==q||e[81]!==Le||e[82]!==pe?(Ee=s.jsxs("div",{className:he,children:[q,me,Le,pe]}),e[79]=he,e[80]=q,e[81]=Le,e[82]=pe,e[83]=Ee):Ee=e[83],Ee},wf=t=>new Date(t.getFullYear(),t.getMonth(),1),FS=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},yf=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),OS=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"]},vf=(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:OS(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:mf(),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||"",goalEnabled:t.execution.goalEnabled===!0,goalTokenBudget:typeof t.execution.goalTokenBudget=="number"&&t.execution.goalTokenBudget>0?t.execution.goalTokenBudget:null},state:t.state}:{name:"",enabled:!0,schedule:{kind:"daily",times:["09:00"],onceDate:mf(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent,goalEnabled:!1,goalTokenBudget:null}}},LS=(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(!Ah(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")},BS=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))},VS=t=>{const e=ht.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?Ah(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let f;e:{if(!d?.valid||!c.trim()){let M;e[2]===Symbol.for("react.memo_cache_sentinel")?(M=[],e[2]=M):M=e[2],f=M;break e}let L;e[3]!==c||e[4]!==n.schedule.timezone?(L=kS(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=L):L=e[5],f=L}const m=f;let u;e[6]!==n.schedule.timezone||e[7]!==o?(u=L=>new Intl.DateTimeFormat(o,{timeZone:n.schedule.timezone,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(L),e[6]=n.schedule.timezone,e[7]=o,e[8]=u):u=e[8];const p=u;let x;e[9]!==a?(x=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=x):x=e[10];let b;e[11]!==x?(b=s.jsx(Qn,{htmlFor:"sched-cron",required:!0,children:x}),e[11]=x,e[12]=b):b=e[12];let w;e[13]!==r?(w=L=>r(M=>({...M,schedule:{...M.schedule,cronExpression:L.target.value}})),e[13]=r,e[14]=w):w=e[14];let g;e[15]!==a?(g=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=g):g=e[16];let h;e[17]!==c||e[18]!==w||e[19]!==g?(h=s.jsx(Ln,{id:"sched-cron",value:c,onChange:w,placeholder:g,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=w,e[19]=g,e[20]=h):h=e[20];let C;e[21]!==c||e[22]!==d||e[23]!==a?(C=d&&!d.valid&&c.trim()?s.jsx("span",{className:"typography-micro text-destructive",children:a("sessions.scheduledTasks.editor.validation.cronInvalid")}):null,e[21]=c,e[22]=d,e[23]=a,e[24]=C):C=e[24];let j;e[25]!==b||e[26]!==h||e[27]!==C?(j=s.jsxs("div",{className:"flex flex-col gap-1",children:[b,h,C]}),e[25]=b,e[26]=h,e[27]=C,e[28]=j):j=e[28];let S;e[29]!==p||e[30]!==m||e[31]!==a?(S=m.length>0?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:a("sessions.scheduledTasks.editor.cronExpression.nextRuns")}),s.jsx("span",{className:"typography-micro text-foreground",children:m.map(p).join(", ")})]}):null,e[29]=p,e[30]=m,e[31]=a,e[32]=S):S=e[32];let N;e[33]!==a?(N=a("sessions.scheduledTasks.editor.cronExpression.examples"),e[33]=a,e[34]=N):N=e[34];let k;e[35]!==N?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:N}),e[35]=N,e[36]=k):k=e[36];let y;e[37]!==r||e[38]!==a?(y=CS.map(L=>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(M=>({...M,schedule:{...M.schedule,cronExpression:L.expression}})),children:[s.jsx("span",{className:"font-mono",children:L.expression}),s.jsx("span",{className:"text-muted-foreground",children:a(L.labelKey)})]},L.expression)),e[37]=r,e[38]=a,e[39]=y):y=e[39];let D;e[40]!==y?(D=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:y}),e[40]=y,e[41]=D):D=e[41];let V;e[42]!==k||e[43]!==D?(V=s.jsxs("div",{className:"flex flex-col gap-1",children:[k,D]}),e[42]=k,e[43]=D,e[44]=V):V=e[44];let v;e[45]!==a?(v=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=v):v=e[46];let O;e[47]!==v?(O=s.jsx(Qn,{children:v}),e[47]=v,e[48]=O):O=e[48];let P;e[49]!==r?(P=L=>{r(M=>({...M,schedule:{...M.schedule,timezone:L}}))},e[49]=r,e[50]=P):P=e[50];let E;e[51]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Kn,{className:"w-fit max-w-full",children:s.jsx(Dn,{})}),e[51]=E):E=e[51];let B;e[52]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(qn,{children:uc.map(US)}),e[52]=B):B=e[52];let T;e[53]!==n.schedule.timezone||e[54]!==P?(T=s.jsxs(Gn,{value:n.schedule.timezone,onValueChange:P,children:[E,B]}),e[53]=n.schedule.timezone,e[54]=P,e[55]=T):T=e[55];let W;e[56]!==O||e[57]!==T?(W=s.jsxs("div",{className:"flex flex-col gap-1",children:[O,T]}),e[56]=O,e[57]=T,e[58]=W):W=e[58];let U;return e[59]!==j||e[60]!==S||e[61]!==V||e[62]!==W?(U=s.jsxs("div",{className:"flex flex-col gap-3",children:[j,S,V,W]}),e[59]=j,e[60]=S,e[61]=V,e[62]=W,e[63]=U):U=e[63],U};function _S(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=yt(),l=is(Y=>Y.loadProviders),d=is(Y=>Y.loadAgents),f=is(Y=>Y.providers),m=is(Y=>Y.currentProviderId),u=is(Y=>Y.currentModelId),p=is(Y=>Y.currentVariant||""),x=is(Y=>Y.currentAgentName||""),b=Re(Y=>Y.timeFormatPreference),w=Re(Y=>Y.weekStartPreference),g=Re(Y=>Y.isMobile),[h,C]=nt.useState(()=>vf(n,{providerID:m,modelID:u,variant:p,agent:x})),[j,S]=nt.useState(!1),[N,k]=nt.useState(!1),[y,D]=nt.useState(!1),[V,v]=nt.useState(""),[O,P]=nt.useState(!1),[E,B]=nt.useState(""),[T,W]=nt.useState(!1),[U,L]=nt.useState(""),[M,ee]=nt.useState(()=>{const Y=wa(n?.schedule?.date||"")||new Date;return new Date(Y.getFullYear(),Y.getMonth(),1)}),ie=nt.useRef(null),X=nt.useRef(null),H=nt.useRef(null),te=nt.useRef(null),re=nt.useRef(null),le=nt.useMemo(()=>RS(c),[c]),ve=nt.useMemo(()=>IS(c),[c]),ne=nt.useMemo(()=>b==="24h"?!0:b==="12h"?!1:le,[b,le]),we=nt.useMemo(()=>w==="sunday"?0:w==="monday"?1:ve,[w,ve]),he=nt.useMemo(()=>{const Y=ES(c);return MS(Dh.map(F=>({value:F,label:Y[F]||""})),we)},[c,we]);nt.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),nt.useEffect(()=>{if(!e)return;C(vf(n,{providerID:m,modelID:u,variant:p,agent:x}));const Y=wa(n?.schedule?.date||"")||new Date;ee(new Date(Y.getFullYear(),Y.getMonth(),1)),k(!1),P(!1),D(!1),B(""),v("")},[e,n,m,u,p,x]),nt.useEffect(()=>{if(!N)return;const Y=F=>{ie.current&&!ie.current.contains(F.target)&&k(!1)};return document.addEventListener("mousedown",Y),()=>{document.removeEventListener("mousedown",Y)}},[N]);const Me=nt.useMemo(()=>{const F=f.find(se=>se.id===h.execution.providerID)?.models?.find(se=>se.id===h.execution.modelID);return F?.variants?Object.keys(F.variants):[]},[f,h.execution.providerID,h.execution.modelID]),z=Me.length>0,K=nt.useMemo(()=>!z||!h.execution.variant?"__default":Me.includes(h.execution.variant)?h.execution.variant:"__default",[h.execution.variant,z,Me]);nt.useEffect(()=>{z||!h.execution.variant||C(Y=>({...Y,execution:{...Y.execution,variant:""}}))},[z,h.execution.variant]);const q=nt.useCallback((Y,F)=>{C(se=>{const Oe=new Set(se.schedule.weekdays);return F?Oe.add(Y):Oe.delete(Y),{...se,schedule:{...se.schedule,weekdays:Array.from(Oe).sort((ce,Ue)=>ce-Ue)}}})},[]),me=nt.useCallback((Y,F)=>{C(se=>{const Oe=se.schedule.times.slice();return Oe[Y]=F,{...se,schedule:{...se.schedule,times:Oe}}})},[]),Se=nt.useCallback(Y=>{C(F=>{const se=F.schedule.times.filter((Oe,ce)=>ce!==Y);return{...F,schedule:{...F.schedule,times:se.length>0?se:["09:00"]}}})},[]),Be=nt.useCallback(()=>{C(Y=>({...Y,schedule:{...Y.schedule,times:[...Y.schedule.times,"12:00"]}}))},[]),_e=nt.useMemo(()=>FS(),[]),Le=nt.useMemo(()=>wf(_e),[_e]),pe=nt.useMemo(()=>{const Y=wa(h.schedule.onceDate);return Y?yf(Y,_e)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(Y):null},[h.schedule.onceDate,c,a,_e]),Ee=nt.useMemo(()=>wf(M).getTime()<=Le.getTime(),[M,Le]),ge=nt.useMemo(()=>he.map(Y=>Y.label),[he]),oe=nt.useCallback(Y=>{C(F=>({...F,schedule:{...F.schedule,onceDate:Y}}))},[]),je=nt.useCallback((Y,F)=>{if(Y.startsWith("/")){const Ue=Y.indexOf(" "),qe=Y.indexOf(`
169
+ `),Ye=Math.min(Ue===-1?Y.length:Ue,qe===-1?Y.length:qe);if(F<=Ye&&Ue===-1){B(Y.substring(1,Ye)),P(!0),D(!1),W(!1);return}}P(!1);const se=Y.substring(0,F),Oe=se.lastIndexOf("#");if(Oe!==-1){const Ue=Oe>0?se[Oe-1]:null,qe=se.substring(Oe+1);if((!Ue||/\s/.test(Ue))&&!qe.includes(" ")&&!qe.includes(`
170
+ `)){L(qe),W(!0),D(!1);return}}W(!1);const ce=se.lastIndexOf("@");if(ce!==-1){const Ue=ce>0?se[ce-1]:null,qe=se.substring(ce+1);(!Ue||/\s/.test(Ue))&&!qe.includes(" ")&&!qe.includes(`
171
+ `)?(v(qe),D(!0)):D(!1);return}D(!1)},[]),ye=nt.useCallback(Y=>{C(F=>({...F,execution:{...F.execution,prompt:Y}}))},[]),ue=nt.useCallback(Y=>{const F=h.execution.prompt,Oe=X.current?.selectionStart??F.length,Ue=F.substring(0,Oe).lastIndexOf("@"),qe=Y.relativePath&&Y.relativePath.trim().length>0?Y.relativePath.trim():Y.path||Y.name,Ye=Ue!==-1?Ue:Oe,tt=`${F.substring(0,Ye)}@${qe} ${F.substring(Oe)}`,xt=Ye+qe.length+2;ye(tt),D(!1),v(""),requestAnimationFrame(()=>{const vt=X.current;vt&&(vt.selectionStart=xt,vt.selectionEnd=xt,vt.focus()),je(tt,xt)})},[h.execution.prompt,ye,je]),De=nt.useCallback(Y=>{const F=h.execution.prompt,Oe=X.current?.selectionStart??F.length,Ue=F.substring(0,Oe).lastIndexOf("@"),qe=Ue!==-1?Ue:Oe,Ye=`${F.substring(0,qe)}@${Y} ${F.substring(Oe)}`,tt=qe+Y.length+2;ye(Ye),D(!1),v(""),requestAnimationFrame(()=>{const xt=X.current;xt&&(xt.selectionStart=tt,xt.selectionEnd=tt,xt.focus()),je(Ye,tt)})},[h.execution.prompt,ye,je]),I=nt.useCallback(Y=>{const F=`/${Y.name} `;ye(F),P(!1),B(""),W(!1),requestAnimationFrame(()=>{const se=X.current;se&&(se.focus(),se.selectionStart=se.value.length,se.selectionEnd=se.value.length),je(F,F.length)})},[ye,je]),_=nt.useCallback((Y,F)=>{const se=h.execution.prompt,ce=X.current?.selectionStart??se.length,qe=se.substring(0,ce).lastIndexOf("#"),Ye=qe!==-1?qe:ce,tt=`${se.substring(0,Ye)}#${F} ${se.substring(ce)}`,xt=Ye+F.length+2;ye(tt),W(!1),L(""),requestAnimationFrame(()=>{const vt=X.current;vt&&(vt.selectionStart=xt,vt.selectionEnd=xt,vt.focus()),je(tt,xt)})},[h.execution.prompt,ye,je]),be=nt.useCallback(Y=>{if(O&&te.current&&(Y.key==="Enter"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="Escape"||Y.key==="Tab")){Y.preventDefault(),te.current.handleKeyDown(Y.key);return}y&&H.current&&(Y.key==="Enter"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="Escape"||Y.key==="Tab")&&(Y.preventDefault(),H.current.handleKeyDown(Y.key)),T&&re.current&&(Y.key==="Enter"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="Escape"||Y.key==="Tab")&&(Y.preventDefault(),re.current.handleKeyDown(Y.key))},[O,y,T]),R=nt.useCallback(async()=>{const Y=LS(h,a);if(Y){ae.error(Y);return}const F={...h.id?{id:h.id}:{},name:h.name.trim(),enabled:h.enabled,schedule:{kind:h.schedule.kind,timezone:h.schedule.timezone.trim(),...h.schedule.kind==="cron"?{cron:h.schedule.cronExpression.trim()}:h.schedule.kind==="once"?{date:h.schedule.onceDate,time:h.schedule.onceTime}:{times:BS(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.execution.goalEnabled?{goalEnabled:!0}:{},...h.execution.goalEnabled&&h.execution.goalTokenBudget?{goalTokenBudget:h.execution.goalTokenBudget}:{}},...h.state?{state:h.state}:{}};S(!0);try{await o(F),r(!1)}catch(se){ae.error(se instanceof Error?se.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{S(!1)}},[h,r,o,a]),de=nt.useId(),fe=nt.useCallback(()=>typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"], [data-slot="select-content"]'),[]),$=a(n?"sessions.scheduledTasks.editor.title.edit":"sessions.scheduledTasks.editor.title.new"),Ae=a("sessions.scheduledTasks.editor.description"),Ve=s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Qn,{htmlFor:"sched-name",required:!0,children:a("sessions.scheduledTasks.editor.taskName.label")}),s.jsx(Ln,{id:"sched-name",value:h.name,onChange:Y=>C(F=>({...F,name:Y.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(Qn,{children:a("sessions.scheduledTasks.editor.scheduleType.label")}),s.jsxs(Gn,{value:h.schedule.kind,onValueChange:Y=>{C(F=>({...F,schedule:{...F.schedule,kind:Y,...Y==="cron"&&!F.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(Kn,{className:"w-fit max-w-full",children:s.jsx(Dn,{children:Y=>a(Y==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":Y==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":Y==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(qn,{children:[s.jsx(Bs,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(Bs,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(Bs,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(Bs,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),h.schedule.kind==="cron"?s.jsx(VS,{draft:h,setDraft:C,locale:c,t:a}):h.schedule.kind==="once"?s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex flex-col gap-1",ref:ie,children:[s.jsx(Qn,{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(Y=>!Y),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(A,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:AS(h.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(A,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"})]}),N?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+6px)] z-50 w-[288px] rounded-xl border border-border bg-background p-3 shadow-sm",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover disabled:cursor-not-allowed disabled:opacity-40",onClick:()=>ee(Y=>pf(Y,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Ee,children:s.jsx(A,{name:"arrow-left-s",className:"h-4 w-4"})}),s.jsx("div",{className:"typography-ui-label text-foreground",children:new Intl.DateTimeFormat(c,{month:"long",year:"numeric"}).format(M)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>ee(Y=>pf(Y,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(A,{name:"arrow-right-s",className:"h-4 w-4"})})]}),s.jsx("div",{className:"mb-1 grid grid-cols-7 gap-1 px-1",children:ge.map((Y,F)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:Y},`${Y}-${F}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:DS(M,we).map(({date:Y,inCurrentMonth:F})=>{const se=hf(Y),Oe=se===h.schedule.onceDate,ce=yf(Y,_e),Ue=Y.getTime()<_e.getTime(),qe=Oe?"bg-interactive-selection text-interactive-selection-foreground":Ue?"text-muted-foreground/40":F?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{Ue||(oe(se),k(!1))},disabled:Ue,className:["h-8 rounded-md typography-ui-label",qe,ce&&!Oe?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",Ue?"cursor-not-allowed opacity-45":""].join(" "),children:Y.getDate()},se)})}),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:pe||""}),s.jsx(ze,{type:"button",size:"xs",variant:"ghost",onClick:()=>{oe(hf(_e)),ee(new Date(_e.getFullYear(),_e.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(Qn,{children:a("sessions.scheduledTasks.editor.time.label")}),s.jsx(bf,{value:h.schedule.onceTime,use24Hour:ne,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:Y=>C(F=>({...F,schedule:{...F.schedule,onceTime:Y}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(Qn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Gn,{value:h.schedule.timezone,onValueChange:Y=>{C(F=>({...F,schedule:{...F.schedule,timezone:Y}}))},children:[s.jsx(Kn,{className:"w-fit max-w-full",children:s.jsx(Dn,{})}),s.jsx(qn,{children:uc.map(Y=>s.jsx(Bs,{value:Y,children:Y},Y))})]})]})]})]}):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(Qn,{children:a("sessions.scheduledTasks.editor.weekdays.label")}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-2",children:he.map(Y=>{const F=h.schedule.weekdays.includes(Y.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",F?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(Or,{checked:F,onChange:se=>q(Y.value,se),ariaLabel:Y.label}),s.jsx("button",{type:"button",onClick:()=>q(Y.value,!F),className:"group-hover:text-foreground",children:Y.label})]},Y.value)})})]}):null,s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qn,{children:a("sessions.scheduledTasks.editor.times.label")}),s.jsx("div",{className:"flex flex-col gap-2",children:h.schedule.times.map((Y,F)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(bf,{value:Y,use24Hour:ne,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:se=>me(F,se)}),h.schedule.times.length>1?s.jsx(ze,{type:"button",size:"icon",variant:"ghost",onClick:()=>Se(F),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(A,{name:"close",className:"h-4 w-4"})}):null]},F))}),s.jsx("div",{children:s.jsxs(ze,{type:"button",size:"sm",variant:"outline",onClick:Be,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"})," ",a("sessions.scheduledTasks.editor.times.add")]})})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Qn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Gn,{value:h.schedule.timezone,onValueChange:Y=>{C(F=>({...F,schedule:{...F.schedule,timezone:Y}}))},children:[s.jsx(Kn,{className:"w-fit max-w-full",children:s.jsx(Dn,{})}),s.jsx(qn,{children:uc.map(Y=>s.jsx(Bs,{value:Y,children:Y},Y))})]})]})]}),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(Qn,{required:!0,children:a("sessions.scheduledTasks.editor.model.label")}),s.jsx(am,{providerId:h.execution.providerID,modelId:h.execution.modelID,onChange:(Y,F)=>{C(se=>({...se,execution:{...se.execution,providerID:Y,modelID:F,variant:""}}))}})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Qn,{children:a("sessions.scheduledTasks.editor.thinkingLevel.label")}),s.jsxs(Gn,{value:K,disabled:!z,onValueChange:Y=>{C(F=>({...F,execution:{...F.execution,variant:Y==="__default"?"":Y}}))},children:[s.jsx(Kn,{className:"w-fit max-w-full",children:s.jsx(Dn,{children:Y=>Y==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):Y})}),s.jsxs(qn,{children:[s.jsx(Bs,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),Me.map(Y=>s.jsx(Bs,{value:Y,children:Y},Y))]})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Qn,{children:a("sessions.scheduledTasks.editor.agent.label")}),s.jsx(lm,{agentName:h.execution.agent,filter:Y=>Ac(Y.mode),onChange:Y=>C(F=>({...F,execution:{...F.execution,agent:Y}}))})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Qn,{htmlFor:"sched-prompt",required:!0,children:a("sessions.scheduledTasks.editor.prompt.label")}),s.jsxs("div",{className:"relative",children:[s.jsx(Pi,{id:"sched-prompt",ref:X,value:h.execution.prompt,onChange:Y=>{const F=Y.target.value;ye(F);const se=Y.target.selectionStart??F.length;je(F,se)},onKeyDown:be,rows:8,placeholder:a("sessions.scheduledTasks.editor.prompt.placeholder"),className:"typography-meta min-h-[120px] max-h-[300px] resize-none overflow-y-auto"}),O?s.jsx(ym,{ref:te,searchQuery:E,onCommandSelect:I,onClose:()=>P(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,y?s.jsx(vm,{ref:H,searchQuery:V,onFileSelect:ue,onAgentSelect:De,onClose:()=>D(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,T?s.jsx(jm,{ref:re,searchQuery:U,onSnippetSelect:_,onClose:()=>W(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-8 gap-y-2",children:[s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-2",children:[s.jsx(Or,{checked:h.execution.goalEnabled,onChange:Y=>C(F=>({...F,execution:{...F.execution,goalEnabled:Y}})),ariaLabel:a("sessions.scheduledTasks.editor.goal.aria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.goal.label")})]}),h.execution.goalEnabled?s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-2",children:[s.jsx(Or,{checked:h.execution.goalTokenBudget!==null,onChange:Y=>C(F=>({...F,execution:{...F.execution,goalTokenBudget:Y?2e5:null}})),ariaLabel:a("sessions.scheduledTasks.editor.goal.budgetAria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.goal.budgetLabel")})]}):null,h.execution.goalEnabled&&h.execution.goalTokenBudget!==null?s.jsx(Vg,{value:h.execution.goalTokenBudget,onValueChange:Y=>{typeof Y=="number"&&Number.isFinite(Y)&&Y>0&&C(F=>({...F,execution:{...F.execution,goalTokenBudget:Math.floor(Y)}}))},min:1e3,max:1e8,step:5e4}):null]})]}),Ne=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(Or,{checked:h.enabled,onChange:Y=>C(F=>({...F,enabled:Y})),ariaLabel:a("sessions.scheduledTasks.editor.enabled.aria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.enabled.label")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(!1),disabled:j,children:a("sessions.scheduledTasks.editor.actions.cancel")}),s.jsx(ze,{type:"button",size:"sm",onClick:R,disabled:j,children:a(j?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return g?s.jsx(Ya,{open:e,title:$,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:Y=>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:$}),Y]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:Ae})]}),footer:Ne,children:Ve}):s.jsx(_s,{open:e,onOpenChange:Y=>{!Y&&fe()||r(Y)},children:s.jsxs(Vs,{"aria-describedby":de,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(mn,{id:de,className:"sr-only",children:Ae}),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(Hs,{className:"typography-ui-label font-medium text-foreground",children:$}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:Ae})]})}),s.jsx(Qa,{className:"flex-1 min-h-0 overflow-auto [scrollbar-gutter:stable_both-edges]",size:64,hideTopShadow:!0,children:s.jsx("div",{className:"mx-auto w-full max-w-2xl px-4 sm:px-6 pb-5",children:Ve})}),s.jsx("div",{className:"shrink-0 px-4 sm:px-6 py-3",children:s.jsx("div",{className:"mx-auto w-full max-w-2xl",children:Ne})})]})})}function $S(t){return po(t,{min:0,max:23})}function zS(t,e){return po(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function WS(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 US(t){return s.jsx(Bs,{value:t,children:t},t)}const HS=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))},GS=(t,e)=>{const n=HS(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||""})},KS=(t,e)=>!t||!Number.isFinite(t)?"":sm(t,e),jf=(t,e)=>{if(!t||!Number.isFinite(t))return"";const n=t-Date.now(),r=Math.abs(n),o=6e4,a=60*o,c=24*a,l=n>=0;if(r<o)return e(l?"sessions.scheduledTasks.dialog.relativeTime.inLessThanOneMinute":"sessions.scheduledTasks.dialog.relativeTime.justNow");if(r<a){const u=Math.round(r/o);return l?e("sessions.scheduledTasks.dialog.relativeTime.inMinutes",{count:u}):e("sessions.scheduledTasks.dialog.relativeTime.minutesAgo",{count:u})}if(r<c){const u=Math.floor(r/a),p=Math.round(r%a/o),x=p>0?`${u}h ${p}m`:`${u}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:x}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:x})}const d=Math.floor(r/c),f=Math.round(r%c/a),m=f>0?`${d}d ${f}h`:`${d}d`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:m}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:m})},qS={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"}},YS=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function QS(){const{t}=yt(),e=Re(T=>T.isScheduledTasksDialogOpen),n=Re(T=>T.setScheduledTasksDialogOpen),r=Re(T=>T.isMobile),o=Re(T=>T.timeFormatPreference),a=Ds(T=>T.projects),c=Ds(T=>T.getActiveProject()),l=Xs(T=>T.homeDirectory),{currentTheme:d}=yi(),[f,m]=nt.useState(""),[u,p]=nt.useState([]),[x,b]=nt.useState(!0),[w,g]=nt.useState(!1),[h,C]=nt.useState(null),[j,S]=nt.useState(null),N=nt.useMemo(()=>a.find(T=>T.id===f)||null,[a,f]),k=nt.useCallback(T=>{const W=T.label?.trim()||fo(T.path,l||void 0),U=T.icon?Oc[T.icon]:null,L=T.color?Lc[T.color]:void 0,M=U?s.jsx(A,{name:U,className:"h-3.5 w-3.5 shrink-0",style:L?{color:L}:void 0}):s.jsx(A,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:L?{color:L}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[T.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:T.iconBackground?{backgroundColor:T.iconBackground}:void 0,children:s.jsx(Bc,{project:{id:T.id,iconImage:T.iconImage??null},options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:M})}):M,s.jsx("span",{className:"truncate",children:W})]})},[l,d.metadata.variant,d.colors.surface.foreground]),y=nt.useCallback(async(T,W)=>{if(!T){p([]);return}W?.silent||b(!0);try{const U=await jS(T);U.sort((L,M)=>{if(L.enabled!==M.enabled)return L.enabled?-1:1;const ee=L.name.localeCompare(M.name);return ee!==0?ee:(L.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(M.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),p(U)}catch(U){ae.error(U instanceof Error?U.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),W?.silent||p([])}finally{W?.silent||b(!1)}},[t]);nt.useEffect(()=>{if(!e)return;const T=c?.id||a[0]?.id||"";m(T),T?y(T):(p([]),b(!1))},[e,c,a,y]),nt.useEffect(()=>{if(!e)return;let T=null;const W=Ch(U=>{U.type==="scheduled-task-ran"&&U.projectId===f&&(T&&clearTimeout(T),T=setTimeout(()=>{y(f,{silent:!0})},400))});return()=>{T&&clearTimeout(T),W()}},[e,f,y]);const D=nt.useCallback(async T=>{if(!f)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await ff(f,T),await y(f),ae.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[f,y,t]),V=nt.useCallback(async(T,W)=>{if(f){S(T.id),p(U=>U.map(L=>L.id===T.id?{...L,enabled:W}:L));try{await ff(f,{...T,enabled:W}),await y(f,{silent:!0})}catch(U){ae.error(U instanceof Error?U.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await y(f,{silent:!0})}finally{S(null)}}},[f,y,t]),v=nt.useCallback(async T=>{if(!(!f||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:T.name})))){S(T.id);try{await SS(f,T.id),await y(f,{silent:!0}),ae.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(U){ae.error(U instanceof Error?U.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{S(null)}}},[f,y,t]),O=nt.useCallback(async T=>{if(f){S(T.id);try{await NS(f,T.id),await Promise.all([y(f,{silent:!0}),Ta()]),ae.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch(W){ae.error(W instanceof Error?W.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{S(null)}}},[f,y,t]),P=s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("sessions.scheduledTasks.dialog.project.label")}),s.jsxs(Gn,{value:f||"__none",onValueChange:T=>{const W=T==="__none"?"":T;m(W),W?y(W):p([])},children:[s.jsx(Kn,{className:r?"w-full":void 0,children:N?s.jsx(Dn,{children:k(N)}):s.jsx(Dn,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(qn,{children:[a.length===0?s.jsx(Bs,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(T=>s.jsx(Bs,{value:T.id,children:k(T)},T.id))]})]})]}),E=()=>{C(null),g(!0)},B=s.jsxs("div",{className:"space-y-4",children:[r?P:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[P,s.jsxs(ze,{onClick:E,disabled:!f,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:x?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin"})," ",t("sessions.scheduledTasks.dialog.loading")]}):u.length===0?s.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 typography-meta text-muted-foreground",children:t(f?"sessions.scheduledTasks.dialog.empty.noTasks":"sessions.scheduledTasks.dialog.empty.selectProject")}):s.jsx("div",{className:"space-y-2.5",children:u.map(T=>{const W=j===T.id,U=T.state?.lastStatus||"idle",L=qS[U],M=t(U==="success"?"sessions.scheduledTasks.dialog.status.success":U==="error"?"sessions.scheduledTasks.dialog.status.error":U==="running"?"sessions.scheduledTasks.dialog.status.running":"sessions.scheduledTasks.dialog.status.idle"),ee=T.state?.nextRunAt,ie=T.state?.lastRunAt;return s.jsxs("div",{className:Pe("rounded-lg border border-border p-4 transition-opacity",!T.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:T.name}),s.jsx("div",{className:"typography-micro truncate text-muted-foreground",children:GS(T,t)})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-5 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(A,{name:"timer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.nextRun.label")}),ee?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-foreground",children:jf(ee,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:KS(ee,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(A,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),U==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(A,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):ie?s.jsxs(s.Fragment,{children:[L.tone!=="muted"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:`var(--status-${L.tone})`},children:[s.jsx(A,{name:L.Icon,className:"h-3.5 w-3.5"}),M]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:jf(ie,t)})]}):s.jsx("span",{children:t("sessions.scheduledTasks.dialog.lastRun.never")})]})]}),T.state?.lastError?s.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-md border p-2 typography-micro",style:YS("error"),children:[s.jsx(A,{name:"error-warning",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"min-w-0 break-words",children:T.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",T.enabled?"text-foreground":"text-muted-foreground",W&&"cursor-not-allowed opacity-50"),children:[s.jsx(Or,{checked:T.enabled,onChange:X=>{V(T,X)},ariaLabel:T.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:T.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:T.name}),disabled:W}),T.enabled?t("sessions.scheduledTasks.dialog.taskToggle.enabled"):t("sessions.scheduledTasks.dialog.taskToggle.paused")]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsxs(ze,{variant:"outline",size:"sm",onClick:()=>{O(T)},disabled:W,children:[s.jsx(A,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs(ze,{variant:"outline",size:"sm",onClick:()=>{C(T),g(!0)},disabled:W,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:T.name}),children:[s.jsx(A,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx(ze,{variant:"destructive",size:"sm",onClick:()=>{v(T)},disabled:W,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:T.name}),children:s.jsx(A,{name:"delete-bin",className:"h-4 w-4"})})]})]})]},T.id)})})})]});return s.jsxs(s.Fragment,{children:[r?s.jsx(Ya,{open:e,title:t("sessions.scheduledTasks.dialog.title"),onClose:()=>n(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:T=>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")}),T]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:t("sessions.scheduledTasks.dialog.description")})]}),footer:s.jsxs(ze,{className:"w-full",onClick:E,disabled:!f,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:B}):s.jsx(_s,{open:e,onOpenChange:n,children:s.jsxs(Vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(sn,{children:[s.jsx(Hs,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(mn,{children:t("sessions.scheduledTasks.dialog.description")})]}),B]})}),s.jsx(_S,{open:w,task:h,onOpenChange:g,onSave:D})]})}const JS=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>ds(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(d=>oo(d,t.normalizedPath,r,e.knownProjectDirectories)))(e.archivedSessions),c=e.sessions.filter(l=>l.time?.archived||ds(l.directory??null)?!1:oo(l,t.normalizedPath,r,e.knownProjectDirectories));return ao([...a,...c])},XS=t=>{const e=ht.c(17),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,isSessionsLoading:l,foldersMap:d,createFolder:f,addSessionToFolder:m,cleanupSessions:u}=t;let p;e[0]!==a||e[1]!==c||e[2]!==n?(p=Uc(n,a,c),e[0]=a,e[1]=c,e[2]=n,e[3]=p):p=e[3];const x=p;let b,w;e[4]!==m||e[5]!==o||e[6]!==a||e[7]!==u||e[8]!==f||e[9]!==d||e[10]!==l||e[11]!==c||e[12]!==x||e[13]!==n||e[14]!==r?(b=()=>{l||n.forEach(g=>{const h=Hc(g.normalizedPath),C=JS(g,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,knownProjectDirectories:x}),j=new Set(C.map(ZS)),S=d[h]??[],N=new Map(S.map(e2));C.forEach(k=>{const y=Nb(k,g.normalizedPath),D=y.toLowerCase();let V=N.get(D);V||(V=f(h,y),N.set(D,V)),V.sessionIds.includes(k.id)||m(h,V.id,k.id)}),u(h,j)})},w=[n,r,o,a,x,c,l,d,f,m,u],e[4]=m,e[5]=o,e[6]=a,e[7]=u,e[8]=f,e[9]=d,e[10]=l,e[11]=c,e[12]=x,e[13]=n,e[14]=r,e[15]=b,e[16]=w):(b=e[15],w=e[16]),i.useEffect(b,w)};function ZS(t){return t.id}function e2(t){return[t.name.toLowerCase(),t]}const t2=t=>{const e=ht.c(41),{normalizedProjects:n,getSessionsForProject:r,getArchivedSessionsForProject:o,availableWorktreesByProject:a,projectRepoStatus:c,projectRootBranches:l,lastRepoStatus:d,buildGroupedSessions:f,hasSessionSearchQuery:m,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:p,buildGroupSearchText:x,foldersMap:b}=t;let w;if(e[0]!==a||e[1]!==f||e[2]!==o||e[3]!==r||e[4]!==d||e[5]!==n||e[6]!==c||e[7]!==l){let v;e[9]!==a||e[10]!==f||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(v=O=>{const P=ao([...r(O),...o(O)]),E=a.get(O.normalizedPath)??[],B=c.has(O.id)?!!c.get(O.id):d,T=f(P,O.normalizedPath,E,l.get(O.id)??null,B);return{project:O,groups:T}},e[9]=a,e[10]=f,e[11]=o,e[12]=r,e[13]=d,e[14]=c,e[15]=l,e[16]=v):v=e[16],w=n.map(v),e[0]=a,e[1]=f,e[2]=o,e[3]=r,e[4]=d,e[5]=n,e[6]=c,e[7]=l,e[8]=w}else w=e[8];const g=w,h=g;let C;if(e[17]!==x||e[18]!==p||e[19]!==b||e[20]!==m||e[21]!==u||e[22]!==h){e:{const v=new WeakMap;if(!m){C=v;break e}const O=P=>P.reduce((E,B)=>E+1+O(B.children),0);h.forEach(P=>{P.groups.forEach(E=>{const B=p(E.sessions,u),T=O(B),W=x(E).includes(u),U=ds(E.directory??null),M=(U?b[U]??[]:[]).filter(ee=>ee.name.toLowerCase().includes(u)).length;v.set(E,{filteredNodes:B,matchedSessionCount:T,folderNameMatchCount:M,groupMatches:W,hasMatch:W||T>0||M>0})})}),C=v}e[17]=x,e[18]=p,e[19]=b,e[20]=m,e[21]=u,e[22]=h,e[23]=C}else C=e[23];const j=C;let S;e:{if(!m){S=h;break e}let v;if(e[24]!==j||e[25]!==h){let O;e[27]!==j?(O=P=>({...P,groups:P.groups.filter(E=>j.get(E)?.hasMatch===!0)}),e[27]=j,e[28]=O):O=e[28],v=h.map(O).filter(s2),e[24]=j,e[25]=h,e[26]=v}else v=e[26];S=v}const N=S,k=m?N:h;let y;e:{if(!m){y=0;break e}let v;if(e[29]!==j||e[30]!==k){let O;e[32]!==j?(O=(P,E)=>P+E.groups.reduce((B,T)=>{const W=j.get(T);if(!W)return B;const U=W.folderNameMatchCount+(W.groupMatches?1:0);return B+W.matchedSessionCount+U},0),e[32]=j,e[33]=O):O=e[33],v=k.reduce(O,0),e[29]=j,e[30]=k,e[31]=v}else v=e[31];y=v}const D=y;let V;return e[34]!==j||e[35]!==g||e[36]!==D||e[37]!==N||e[38]!==k||e[39]!==h?(V={projectSections:g,visibleProjectSections:h,groupSearchDataByGroup:j,searchableProjectSections:N,sectionsForRender:k,searchMatchCount:D},e[34]=j,e[35]=g,e[36]=D,e[37]=N,e[38]=k,e[39]=h,e[40]=V):V=e[40],V};function s2(t){return t.groups.length>0}const n2=t=>{const e=ht.c(26),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:c,handleSessionSelect:l,newSessionDraftOpen:d,mobileVariant:f,openNewSessionDraft:m,setActiveMainTab:u,setSessionSwitcherOpen:p}=t;let x,b;if(e[0]!==n){b=new Map,x=new Map;const k=(y,D,V,v)=>{b.has(y)||b.set(y,new Map);const O=b.get(y);v.forEach(P=>{const E=ds(P.worktree?.path??P.session.directory??V??D);O.set(P.session.id,{directory:E}),x.has(y)||x.set(y,{id:P.session.id,directory:E}),P.children.length>0&&k(y,D,E,P.children)})};n.forEach(y=>{y.groups.forEach(D=>{k(y.project.id,y.project.normalizedPath,D.directory,D.sessions)})}),e[0]=n,e[1]=x,e[2]=b}else x=e[1],b=e[2];let w;e[3]!==x||e[4]!==b?(w={metaByProject:b,firstSessionByProject:x},e[3]=x,e[4]=b,e[5]=w):w=e[5];const g=w,h=i.useRef(null);let C,j;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==f||e[11]!==d||e[12]!==m||e[13]!==n||e[14]!==g||e[15]!==u||e[16]!==a||e[17]!==p?(C=()=>{if(!r||d||Re.getState().isNewWorktreeDialogOpen||h.current===r)return;const k=n.find(E=>E.project.id===r);if(!k)return;h.current=r;const y=g.metaByProject.get(r);if(c&&y&&y.has(c)){a(E=>{if(E.get(r)===c)return E;const B=new Map(E);return B.set(r,c),B});return}if(c&&y)return;if(!y||y.size===0){u("chat"),f&&p(!1),m({directoryOverride:k.project.normalizedPath});return}const D=o.get(r),V=D&&y.has(D)?D:null,v=g.firstSessionByProject.get(r)?.id??null,O=V??v;if(!O||O===c)return;const P=y.get(O)?.directory??null;l(O,P,r)},j=[r,o,c,l,d,f,m,n,g,u,p,a],e[6]=r,e[7]=o,e[8]=c,e[9]=l,e[10]=f,e[11]=d,e[12]=m,e[13]=n,e[14]=g,e[15]=u,e[16]=a,e[17]=p,e[18]=C,e[19]=j):(C=e[18],j=e[19]),i.useLayoutEffect(C,j);let S,N;e[20]!==r||e[21]!==c||e[22]!==g||e[23]!==a?(S=()=>{if(!r||!c)return;const k=g.metaByProject.get(r);!k||!k.has(c)||a(y=>{if(y.get(r)===c)return y;const D=new Map(y);return D.set(r,c),D})},N=[r,c,g,a],e[20]=r,e[21]=c,e[22]=g,e[23]=a,e[24]=S,e[25]=N):(S=e[24],N=e[25]),i.useEffect(S,N)},r2=t=>{const e=ht.c(4);let n;e[0]!==t?(n=(a,c)=>{const l=t.get(a);if(!l||l.length===0)return c;const d=new Map(c.map(i2)),f=[];return l.forEach(m=>{const u=d.get(m);u&&(f.push(u),d.delete(m))}),c.forEach(m=>{d.has(m.id)&&f.push(m)}),f},e[0]=t,e[1]=n):n=e[1];const r=n;let o;return e[2]!==r?(o={getOrderedGroups:r},e[2]=r,e[3]=o):o=e[3],o};function i2(t){return[t.id,t]}const ia=t=>!!t.time?.archived,o2=t=>{const{t:e}=yt(),n=i.useCallback(c=>[c.label,c.branch??"",c.description??"",c.directory??""].join(" ").toLowerCase(),[]),r=i.useCallback(c=>{const l=ds(c.directory??null)??"";return`${(c.title||e("sessions.sidebar.session.untitled")).trim()} ${l}`.toLowerCase()},[e]),o=i.useCallback((c,l)=>l?c.flatMap(d=>{if(r(d.session).includes(l))return[d];const m=o(d.children,l);return m.length===0?[]:[{...d,children:m}]}):c,[r]),a=i.useCallback((c,l,d,f,m)=>{const u=ds(l??null),p=ao(c).sort((P,E)=>Qi(P,E,t.pinnedSessionIds)),x=new Map(p.map(P=>[P.id,P])),b=new Map;p.forEach(P=>{const E=P.parentID;if(!E)return;const B=x.get(E);if(!B||ia(B)!==ia(P))return;const T=b.get(E)??[];T.push(P),b.set(E,T)}),b.forEach(P=>P.sort((E,B)=>Qi(E,B,t.pinnedSessionIds)));const w=new Map;d.forEach(P=>{if(P.path){const E=ds(P.path)??P.path;w.set(E,P)}});const g=P=>{const E=ds(P.directory??null),B=t.worktreeMetadata.get(P.id)??null;if(B)return B;if(E){const T=w.get(E)??null;if(T&&E!==u)return T}return null},h=P=>{const E=b.get(P.id)??[];return{session:P,children:E.map(B=>h(B)),worktree:g(P)}},C=p.filter(P=>{const E=P.parentID;if(!E)return!0;const B=x.get(E);return B?ia(B)!==ia(P):!0}),j=new Map,S="__archived__",N=P=>{if(P.time?.archived)return S;if(t.isVSCode)return u??"__project_root__";const B=ds(t.worktreeMetadata.get(P.id)?.path??null)??Br(P);return B?B!==u&&w.has(B)?B:B===u?u??"__project_root__":S:S};C.forEach(P=>{const E=h(P),B=N(P);j.has(B)||j.set(B,[]),j.get(B)?.push(E)});const k=u??"__project_root__",y=[{id:"root",label:m&&f&&f!=="HEAD"?e("sessions.sidebar.grouping.projectRootWithBranch",{branch:f}):e("sessions.sidebar.grouping.projectRoot"),branch:f??null,description:u?Pa(u,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:u,folderScopeKey:u,sessions:j.get(k)??[]}],D=new Map;d.forEach(P=>{const E=ds(P.path)??P.path,B=j.get(E)??[],T=B.length>0,W=B.reduce((U,L)=>{const M=Number(L.session.time?.updated??L.session.time?.created??0);return Number.isFinite(M)?Math.max(U,M):U},0);D.set(E,{hasActiveSession:T,lastUpdatedAt:W})});const V=[...d].sort((P,E)=>{const B=ds(P.path)??P.path,T=ds(E.path)??E.path,W=D.get(B)??{hasActiveSession:!1,lastUpdatedAt:0},U=D.get(T)??{hasActiveSession:!1,lastUpdatedAt:0};if(W.hasActiveSession!==U.hasActiveSession)return W.hasActiveSession?-1:1;if(W.hasActiveSession&&U.hasActiveSession)return U.lastUpdatedAt-W.lastUpdatedAt;const L=(P.label||P.branch||P.name||P.path||"").toLowerCase(),M=(E.label||E.branch||E.name||E.path||"").toLowerCase();return L.localeCompare(M)});(t.isVSCode?[]:V).forEach(P=>{const E=ds(P.path)??P.path,B=t.gitBranches.get(E)?.trim()||null,T=P.branch?.trim()||null,U=!!(B&&T&&P.label&&ou(P.label)===ou(T))?B:P.label||P.name||fo(E,t.homeDirectory)||E;y.push({id:`worktree:${E}`,label:U,branch:B||T,description:Pa(E,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:P,directory:E,folderScopeKey:E,sessions:j.get(E)??[]})});const O=j.get(S)??[];return O.length>0&&y.push({id:"archived",label:e("sessions.sidebar.grouping.archived"),branch:null,description:e("sessions.sidebar.grouping.archivedDescription"),isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:!t.isVSCode&&u?Hc(u):null,sessions:O}),y},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitBranches,t.isVSCode,e]);return{buildGroupSearchText:n,buildSessionSearchText:r,filterSessionNodesForSearch:o,buildGroupedSessions:a}},a2=t=>{const e=ht.c(9),{isSessionSearchOpen:n,setIsSessionSearchOpen:r,sessionSearchInputRef:o,sessionSearchContainerRef:a}=t;let c,l;e[0]!==n||e[1]!==o?(c=()=>{if(!n||typeof window>"u")return;const m=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(m)},l=[n,o],e[0]=n,e[1]=o,e[2]=c,e[3]=l):(c=e[2],l=e[3]),i.useEffect(c,l);let d,f;e[4]!==n||e[5]!==a||e[6]!==r?(d=()=>{if(!n||typeof document>"u")return;const m=u=>{a.current&&(a.current.contains(u.target)||r(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},f=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=d,e[8]=f):(d=e[7],f=e[8]),i.useEffect(d,f)},l2=t=>{const e=ht.c(42),{t:n}=yt(),[r,o]=i.useState(null),a=i.useRef(null);let c,l;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=()=>()=>{a.current&&clearTimeout(a.current)},l=[],e[0]=c,e[1]=l):(c=e[0],l=e[1]),i.useEffect(c,l);let d;e[2]!==t?(d=(W,U,L)=>{const M=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(L&&L!==t.activeProjectId&&t.setActiveProjectIdOnly(L),U&&U!==t.currentDirectory&&t.setDirectory(U,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),W===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(W),M();return}t.setCurrentSession(W,U??null),t.onSessionSelected?.(W),M()},e[2]=t,e[3]=d):d=e[3];const f=d;let m;e[4]!==t?(m=(W,U)=>{t.setEditingId(W),t.setEditTitle(U)},e[4]=t,e[5]=m):m=e[5];const u=m;let p;e[6]!==t?(p=async W=>{if(!t.editingId)return;const U=(W??t.editTitle).trim();U&&await t.updateSessionTitle(t.editingId,U),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=p):p=e[7];const x=p;let b;e[8]!==t?(b=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=b):b=e[9];const w=b;let g;e[10]!==t||e[11]!==n?(g=async W=>{const U=await t.shareSession(W.id);U&&U.share?.url?ae.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):ae.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=g):g=e[12];const h=g;let C;e[13]!==n?(C=(W,U)=>{xr(W).then(L=>{if(!L.ok){ae.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(U),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{ae.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=C):C=e[14];const j=C;let S;e[15]!==t||e[16]!==n?(S=async W=>{await t.unshareSession(W)?ae.success(n("sessions.sidebar.session.unshare.success")):ae.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=S):S=e[17];const N=S;let k;e[18]!==t.childrenMap?(k=W=>{const U=[],L=M=>{(t.childrenMap.get(M)??[]).forEach(ie=>{U.push(ie),L(ie.id)})};return L(W),U},e[18]=t.childrenMap,e[19]=k):k=e[19];const y=k,D=d2;let V;e[20]!==t||e[21]!==y||e[22]!==n?(V=async(W,U,L)=>{const M=U?.archivedBucket===!0||U?.hardDelete===!0,ee=L?.descendantIds??D(y(W.id),M).map(u2);if(ee.length===0){(M?await t.deleteSession(W.id):await t.archiveSession(W.id))?ae.success(n(M?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):ae.error(n(M?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const ie=[W.id,...ee];if(M){const{deletedIds:te,failedIds:re}=await t.deleteSessions(ie);if(re.length===0){const le=te.length;ae.success(le===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:le}):n("sessions.sidebar.bulkActions.deletedPlural",{count:le}))}else ae.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:X,failedIds:H}=await t.archiveSessions(ie);X.length>0&&ae.success(X.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:X.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:X.length})),H.length>0&&ae.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]=y,e[22]=n,e[23]=V):V=e[23];const v=V;let O;e[24]!==t||e[25]!==y||e[26]!==v?(O=(W,U)=>{const L=U?.archivedBucket===!0||U?.hardDelete===!0,M=D(y(W.id),L).map(f2);if(!t.showDeletionDialog||U?.skipConfirm===!0){v(W,U,{descendantIds:M});return}t.setDeleteSessionConfirm({session:W,descendantCount:M.length,descendantIds:M,archivedBucket:L})},e[24]=t,e[25]=y,e[26]=v,e[27]=O):O=e[27];const P=O;let E;e[28]!==t||e[29]!==v?(E=async()=>{if(!t.deleteSessionConfirm)return;const{session:W,archivedBucket:U,descendantIds:L}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await v(W,{archivedBucket:U},{descendantIds:L})},e[28]=t,e[29]=v,e[30]=E):E=e[30];const B=E;let T;return e[31]!==B||e[32]!==r||e[33]!==w||e[34]!==j||e[35]!==P||e[36]!==x||e[37]!==u||e[38]!==f||e[39]!==h||e[40]!==N?(T={copiedSessionId:r,handleSessionSelect:f,handleSessionDoubleClick:u,handleSaveEdit:x,handleCancelEdit:w,handleShareSession:h,handleCopyShareUrl:j,handleUnshareSession:N,handleDeleteSession:P,confirmDeleteSession:B},e[31]=B,e[32]=r,e[33]=w,e[34]=j,e[35]=P,e[36]=x,e[37]=u,e[38]=f,e[39]=h,e[40]=N,e[41]=T):T=e[41],T};function c2(t){return!t.time?.archived}function d2(t,e){return e?t:t.filter(c2)}function u2(t){return t.id}function f2(t){return t.id}const m2=(t,e)=>{const n=new Set(t.map(a=>a.id));let r=!1;const o=new Set;return e.forEach(a=>{if(n.has(a)){o.add(a);return}r=!0}),r?o:e},h2=["project:active:","project:archived:","recent:active:","recent:archived:"],p2=t=>{const{isVSCode:e,hasAuthoritativeGlobalSessions:n,safeStorage:r,keys:o,sessions:a,setPinnedSessionIds:c,groupOrderByProject:l,activeSessionByProject:d,collapsedGroups:f,setExpandedParents:m,setCollapsedProjects:u}=t,p=i.useRef(null),x=i.useRef(null),b=i.useCallback(()=>{if(e)return;const g=x.current;if(x.current=null,p.current=null,!g)return;const{projects:h}=Ds.getState(),C=h.map(j=>({...j,sidebarCollapsed:g.has(j.id)}));wc({projects:C}).catch(()=>{})},[e]),w=i.useCallback(g=>{typeof window>"u"||e||(x.current=g,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{b()},700))},[e,b]);return i.useEffect(()=>()=>{typeof window<"u"&&p.current!==null&&window.clearTimeout(p.current),p.current=null,x.current=null},[]),i.useEffect(()=>{try{const g=r.getItem(o.sessionExpanded);if(g){const C=JSON.parse(g);Array.isArray(C)&&m(new Set(C.filter(j=>typeof j=="string")))}else{const C=r.getItem(o.sessionExpandedLegacy);if(C){try{const j=JSON.parse(C);if(Array.isArray(j)){const S=new Set;if(j.forEach(N=>{typeof N!="string"||N.length===0||h2.forEach(k=>S.add(`${k}${N}`))}),S.size>0){m(S);try{r.setItem(o.sessionExpanded,JSON.stringify(Array.from(S)))}catch{}}}}catch{}try{r.removeItem?.(o.sessionExpandedLegacy)}catch{}}}const h=r.getItem(o.projectCollapse);if(h){const C=JSON.parse(h);Array.isArray(C)&&u(new Set(C.filter(j=>typeof j=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,u,m]),i.useEffect(()=>{n&&c(g=>m2(a,g))},[n,a,c]),i.useEffect(()=>{try{const g=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(g))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const g=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(g))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(f)))}catch{}},[f,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:w}},g2=t=>{const{normalizedProjects:e,gitRepoStatus:n,setProjectRepoStatus:r,setProjectRootBranches:o}=t,{git:a}=Zn(),c=vn(u=>u.ensureStatus);i.useEffect(()=>{if(!a||e.length===0){r(new Map);return}e.forEach(u=>{c(u.normalizedPath,a)})},[e,a,c,r]),i.useEffect(()=>{const u=new Map;e.forEach(p=>{u.set(p.id,n.get(p.normalizedPath)?.isGitRepo??null)}),r(u)},[e,n,r]);const l=i.useMemo(()=>e.map(u=>{const p=n.get(u.normalizedPath)?.branch??"";return`${u.id}:${p}`}).join("|"),[e,n]),d=i.useRef(new Map),f=i.useRef(new Map),m=5*6e4;i.useEffect(()=>{let u=!1;const p=setTimeout(()=>{(async()=>{const b=new Set(e.map(S=>S.id));for(const S of d.current.keys())b.has(S)||(d.current.delete(S),f.current.delete(S));const w=Date.now(),g=e.filter(S=>{const N=n.get(S.normalizedPath);if(N?.isGitRepo===!1)return d.current.delete(S.id),f.current.delete(S.id),!1;if(N?.isGitRepo!==!0||N.branch===null)return!1;const k=N.branch.trim(),y=`${S.normalizedPath}\0${k}`,D=d.current.get(S.id);if(D===y){const V=f.current.get(S.id);return V&&(V.at=w),!1}return!(D!==void 0&&w-(f.current.get(S.id)?.at??0)<m)});if(g.length===0)return;const h=await Qm(g,2,async S=>{const N=n.get(S.normalizedPath)?.branch?.trim()??"",k=`${S.normalizedPath}\0${N}`,y=await Xa(S.normalizedPath,N?{knownBranch:N}:void 0).catch(()=>null);return{id:S.id,inputKey:k,branch:y}});if(u)return;const C=h.filter(S=>S.branch);if(C.length===0)return;const j=Date.now();o(S=>{const N=new Map(S);return C.forEach(({id:k,branch:y})=>{y&&N.set(k,y)}),N}),C.forEach(({id:S,inputKey:N,branch:k})=>{d.current.set(S,N),k&&f.current.set(S,{branch:k,at:j})})})()},150);return()=>{u=!0,clearTimeout(p)}},[e,l,n,o])},x2=t=>{const e=ht.c(20),{isVSCode:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,normalizedProjects:c}=t;let l;e[0]!==a||e[1]!==n||e[2]!==c?(l=Uc(c,a,n),e[0]=a,e[1]=n,e[2]=c,e[3]=l):l=e[3];const d=l;let f;e[4]!==d||e[5]!==r?(f=new Map,r.forEach(g=>{const h=Br(g);if(!h||!d.has(h))return;const C=f.get(h)??[];C.push(g),f.set(h,C)}),e[4]=d,e[5]=r,e[6]=f):f=e[6];const m=f;let u;e[7]!==a||e[8]!==n||e[9]!==m?(u=g=>{const h=n?[]:a.get(g.normalizedPath)??[],C=[g.normalizedPath,...h.map(b2).filter(w2)],j=new Set,S=[];return C.forEach(N=>{(m.get(N)??[]).forEach(y=>{j.has(y.id)||(j.add(y.id),S.push(y))})}),S},e[7]=a,e[8]=n,e[9]=m,e[10]=u):u=e[10];const p=u;let x;e[11]!==o||e[12]!==a||e[13]!==n||e[14]!==d||e[15]!==r?(x=g=>{if(n){const k=o.filter(D=>{const V=ds(D.directory??null),v=ds(D.project?.worktree??null);return V?V===g.normalizedPath:v===g.normalizedPath}),y=r.filter(D=>D.time?.archived||ds(D.directory??null)?!1:ds(D.project?.worktree??null)===g.normalizedPath);return ao([...k,...y])}const h=n?[]:a.get(g.normalizedPath)??[],C=new Set([g.normalizedPath,...h.map(y2).filter(v2)]),S=(k=>k.filter(y=>oo(y,g.normalizedPath,C,d)))(o),N=r.filter(k=>k.time?.archived||ds(k.directory??null)||!ds(k.project?.worktree??null)?!1:oo(k,g.normalizedPath,C,d));return ao([...S,...N])},e[11]=o,e[12]=a,e[13]=n,e[14]=d,e[15]=r,e[16]=x):x=e[16];const b=x;let w;return e[17]!==b||e[18]!==p?(w={getSessionsForProject:p,getArchivedSessionsForProject:b},e[17]=b,e[18]=p,e[19]=w):w=e[19],w};function b2(t){return ds(t.path)??t.path}function w2(t){return!!t}function y2(t){return ds(t.path)??t.path}function v2(t){return!!t}const j2=t=>{const e=ht.c(15),{isSessionsLoading:n,hasLoadedGlobalSessions:r,sessions:o,archivedSessions:a,normalizedProjects:c,isVSCode:l,availableWorktreesByProject:d,cleanupSessions:f}=t;let m;e[0]!==d||e[1]!==l||e[2]!==c?(m=Uc(c,d,l),e[0]=d,e[1]=l,e[2]=c,e[3]=m):m=e[3];const u=m;let p,x;e[4]!==a||e[5]!==d||e[6]!==f||e[7]!==r||e[8]!==n||e[9]!==l||e[10]!==u||e[11]!==c||e[12]!==o?(p=()=>{if(n||!r||o.length===0&&a.length===0)return;const b=new Map;o.forEach(h=>{const C=ds(h.directory??null);if(!C)return;const j=b.get(C);if(j){j.add(h.id);return}b.set(C,new Set([h.id]))}),c.forEach(h=>{const C=Hc(h.normalizedPath),j=l?[]:d.get(h.normalizedPath)??[],S=new Set([h.normalizedPath,...j.map(S2).filter(N2)]),N=ao([...a,...o.filter(k=>k.time?.archived||ds(k.directory??null)?!1:oo(k,h.normalizedPath,S,u))]).filter(k=>oo(k,h.normalizedPath,S,u));b.set(C,new Set(N.map(k2)))});const w=Wn.getState().foldersMap;new Set([...Object.keys(w),...b.keys()]).forEach(h=>{f(h,b.get(h)??new Set)})},x=[a,d,f,r,n,l,u,c,o],e[4]=a,e[5]=d,e[6]=f,e[7]=r,e[8]=n,e[9]=l,e[10]=u,e[11]=c,e[12]=o,e[13]=p,e[14]=x):(p=e[13],x=e[14]),i.useEffect(p,x)};function S2(t){return ds(t.path)??t.path}function N2(t){return!!t}function k2(t){return t.id}const C2=t=>{const e=ht.c(8),{isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=t;let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=new Set,e[0]=a):a=e[0];const[c,l]=i.useState(a);let d;e[1]!==n||e[2]!==o?(d=()=>{if(!n)return;const m=new IntersectionObserver(u=>{u.forEach(p=>{const x=p.target.dataset.projectId;x&&l(b=>{const w=new Set(b);return p.isIntersecting?w.delete(x):w.add(x),w})})},{threshold:0});return o.current.forEach(u=>{u&&m.observe(u)}),()=>m.disconnect()},e[1]=n,e[2]=o,e[3]=d):d=e[3];let f;return e[4]!==n||e[5]!==o||e[6]!==r?(f=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=f):f=e[7],i.useEffect(d,f),c},A2=t=>{const e=ht.c(10),{open:n,onOpenChange:r,project:o,onSave:a}=t;let c;e[0]!==a||e[1]!==n||e[2]!==o?(c=n&&o?s.jsx(ob,{project:o,onIdentitySave:a}):null,e[0]=a,e[1]=n,e[2]=o,e[3]=c):c=e[3];let l;e[4]!==c?(l=s.jsx(Vs,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(On,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:s.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:c})})}),e[4]=c,e[5]=l):l=e[5];let d;return e[6]!==r||e[7]!==n||e[8]!==l?(d=s.jsx(_s,{open:n,onOpenChange:r,children:l}),e[6]=r,e[7]=n,e[8]=l,e[9]=d):d=e[9],d},D2=`**Help shape what OpenChamber becomes next!**
172
+
173
+ Hey 👋,
174
+
175
+ OpenChamber has grown mostly through word of mouth, GitHub issues, Discord feedback, and people telling me what is broken, confusing, or surprisingly useful.
176
+
177
+ I'm planning the next chapter now - mobile, better remote access, a tighter VS Code ↔ desktop/web/mobile flow, and more, but before building too much, I want to hear from the people actually using it.
178
+
179
+ I'm doing a round of short 1-on-1 calls. No sales pitch, no formal script - just a real conversation about how you use OpenChamber, what you love, what frustrates you, and what would make it much more valuable.
180
+
181
+ You can book a call or use the short survey below.
182
+
183
+ What you get:
184
+
185
+ - A direct chance to influence the roadmap
186
+ - Your pain points and feature requests prioritized with more context
187
+ - A Power User role in Discord for people helping shape the product
188
+ - My genuine thanks for helping make OpenChamber better
189
+
190
+ **This project is what it is because of your feedback. Thank you, genuinely.**
191
+
192
+ I'll remove this button in 10 days 🙂`;function T2(t){const e=ht.c(25),{open:n,onOpenChange:r}=t,{t:o}=yt();let a;e[0]!==o?(a=o("shareOpinion.dialog.title"),e[0]=o,e[1]=a):a=e[1];let c;e[2]!==a?(c=s.jsx(Hs,{className:"sr-only",children:a}),e[2]=a,e[3]=c):c=e[3];let l;e[4]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(no,{content:D2,className:"typography-markdown-body",enableFileReferences:!1}),e[4]=l):l=e[4];let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(A,{name:"video-chat",className:"size-5 text-[var(--status-warning)]"}),e[5]=d):d=e[5];let f;e[6]!==o?(f=o("shareOpinion.actions.bookCall"),e[6]=o,e[7]=f):f=e[7];let m;e[8]!==f?(m=s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-2.5 typography-ui-label text-foreground hover:bg-[var(--interactive-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",onClick:I2,children:[d,f]}),e[8]=f,e[9]=m):m=e[9];let u;e[10]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(A,{name:"survey",className:"size-5 text-[var(--pr-merged)]"}),e[10]=u):u=e[10];let p;e[11]!==o?(p=o("shareOpinion.actions.shortSurvey"),e[11]=o,e[12]=p):p=e[12];let x;e[13]!==p?(x=s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-2.5 typography-ui-label text-foreground hover:bg-[var(--interactive-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",onClick:P2,children:[u,p]}),e[13]=p,e[14]=x):x=e[14];let b;e[15]!==m||e[16]!==x?(b=s.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[m,x]}),e[15]=m,e[16]=x,e[17]=b):b=e[17];let w;e[18]!==b||e[19]!==c?(w=s.jsxs(Vs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[c,l,b]}),e[18]=b,e[19]=c,e[20]=w):w=e[20];let g;return e[21]!==r||e[22]!==n||e[23]!==w?(g=s.jsx(_s,{open:n,onOpenChange:r,children:w}),e[21]=r,e[22]=n,e[23]=w,e[24]=g):g=e[24],g}function P2(){ti("https://forms.gle/cdMVKUGs5QuLWkA86")}function I2(){ti("https://calendly.com/artmore/30min")}const R2=t=>{const e=ht.c(86),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:c,onRename:l,onDelete:d,renderSessionNode:f,getRenderExtras:m,groupDirectory:u,projectId:p,mobileVariant:x,alwaysShowActions:b,isRenaming:w,renameDraft:g,onRenameDraftChange:h,onRenameSave:C,onRenameCancel:j,droppableRef:S,isDropTarget:N,onNewSession:k,onNewSubFolder:y,depth:D,hideActions:V,archivedBucket:v}=t,P=b===void 0?x===void 0?!1:x:b,E=w===void 0?!1:w,B=g===void 0?"":g,T=N===void 0?!1:N,W=D===void 0?0:D,U=V===void 0?!1:V,L=v===void 0?!1:v,{t:M}=yt(),[ee,ie]=i.useState(!1),[X,H]=i.useState(""),te=i.useRef(null),re=E||ee,le=E?B:X;let ve;e[0]!==n.name?(ve=()=>{H(n.name),ie(!0)},e[0]=n.name,e[1]=ve):ve=e[1];const ne=ve;let we;e[2]!==le||e[3]!==n.name||e[4]!==E||e[5]!==l||e[6]!==C?(we=()=>{const F=le.trim();F&&F!==n.name&&l(F),E&&C&&C(),ie(!1),H("")},e[2]=le,e[3]=n.name,e[4]=E,e[5]=l,e[6]=C,e[7]=we):we=e[7];const he=we;let Me;e[8]!==E||e[9]!==j?(Me=()=>{E&&j&&j(),ie(!1),H("")},e[8]=E,e[9]=j,e[10]=Me):Me=e[10];const z=Me;let K;e[11]!==E||e[12]!==h?(K=F=>{E&&h?h(F):H(F)},e[11]=E,e[12]=h,e[13]=K):K=e[13];const q=K;let me,Se;e[14]!==E?(me=()=>{if(!E)return;const F=()=>{const ce=te.current;ce&&(ce.focus(),ce.select())},se=requestAnimationFrame(F),Oe=window.setTimeout(F,0);return()=>{cancelAnimationFrame(se),window.clearTimeout(Oe)}},Se=[E],e[14]=E,e[15]=me,e[16]=Se):(me=e[15],Se=e[16]),i.useEffect(me,Se);const Be=a?"folder":"folder-open",Le=W>0&&"ml-3";let pe;e[17]!==Le?(pe=Pe("oc-folder",Le),e[17]=Le,e[18]=pe):pe=e[18];const Ee=T&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let ge;e[19]!==Ee?(ge=Pe("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",Ee),e[19]=Ee,e[20]=ge):ge=e[20];const oe=re?void 0:c,je=re?void 0:"button",ye=re?void 0:0;let ue;e[21]!==c||e[22]!==re?(ue=re?void 0:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),c())},e[21]=c,e[22]=re,e[23]=ue):ue=e[23];let De;e[24]!==n.name||e[25]!==a||e[26]!==M?(De=a?M("sessions.sidebar.folderItem.expandAria",{folderName:n.name}):M("sessions.sidebar.folderItem.collapseAria",{folderName:n.name}),e[24]=n.name,e[25]=a,e[26]=M,e[27]=De):De=e[27];const I=L?P?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let _;e[28]!==I?(_=Pe("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",I),e[28]=I,e[29]=_):_=e[29];const be=T?"text-primary":"text-muted-foreground";let R;e[30]!==be?(R=Pe("h-3.5 w-3.5 flex-shrink-0",be),e[30]=be,e[31]=R):R=e[31];let de;e[32]!==Be||e[33]!==R?(de=s.jsx(A,{name:Be,className:R}),e[32]=Be,e[33]=R,e[34]=de):de=e[34];let fe;e[35]!==le||e[36]!==n.name||e[37]!==z||e[38]!==q||e[39]!==he||e[40]!==a||e[41]!==T||e[42]!==re||e[43]!==r||e[44]!==M?(fe=re?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:M2,onMouseDown:F2,onSubmit:F=>{F.preventDefault(),he()},children:[s.jsx("input",{ref:te,value:le,onChange:F=>q(F.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:M("sessions.sidebar.folderItem.namePlaceholder"),onClick:O2,onPointerDown:L2,onMouseDown:B2,onKeyDown:F=>{if(F.key==="Escape"){F.stopPropagation(),z();return}(F.key===" "||F.key==="Enter")&&F.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:V2,onPointerDown:_2,onMouseDown:$2,children:s.jsx(A,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),z()},onPointerDown:z2,onMouseDown:W2,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(A,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:Pe("typography-ui-label font-semibold truncate",T?"text-primary":"text-muted-foreground"),children:n.name}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",r.length]}),a?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[35]=le,e[36]=n.name,e[37]=z,e[38]=q,e[39]=he,e[40]=a,e[41]=T,e[42]=re,e[43]=r,e[44]=M,e[45]=fe):fe=e[45];let $;e[46]!==_||e[47]!==de||e[48]!==fe?($=s.jsxs("div",{className:_,children:[de,fe]}),e[46]=_,e[47]=de,e[48]=fe,e[49]=$):$=e[49];let Ae;e[50]!==P||e[51]!==L||e[52]!==W||e[53]!==n.name||e[54]!==ne||e[55]!==U||e[56]!==d||e[57]!==k||e[58]!==y||e[59]!==re||e[60]!==M?(Ae=!re&&(!U||L)?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",P?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100",L&&"absolute right-0.5 top-1/2 z-10 -translate-y-1/2 px-0"),children:[!L&&k?s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),k()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":M("sessions.sidebar.folderItem.newSessionAria",{folderName:n.name}),title:M("sessions.sidebar.project.actions.newSession"),children:s.jsx(A,{name:"add",className:"h-3.5 w-3.5"})}):null,!L&&y&&W===0?s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),y()},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":M("sessions.sidebar.folderItem.newSubfolderAria",{folderName:n.name}),title:M("sessions.sidebar.folderItem.newSubfolder"),children:s.jsx(A,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,L?null:s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),ne()},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":M("sessions.sidebar.folderItem.renameAria",{folderName:n.name}),children:s.jsx(A,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":L?M("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):M("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=P,e[51]=L,e[52]=W,e[53]=n.name,e[54]=ne,e[55]=U,e[56]=d,e[57]=k,e[58]=y,e[59]=re,e[60]=M,e[61]=Ae):Ae=e[61];let Ve;e[62]!==S||e[63]!==ge||e[64]!==oe||e[65]!==je||e[66]!==ye||e[67]!==ue||e[68]!==De||e[69]!==$||e[70]!==Ae?(Ve=s.jsxs("div",{ref:S,className:ge,onClick:oe,role:je,tabIndex:ye,onKeyDown:ue,"aria-label":De,children:[$,Ae]}),e[62]=S,e[63]=ge,e[64]=oe,e[65]=je,e[66]=ye,e[67]=ue,e[68]=De,e[69]=$,e[70]=Ae,e[71]=Ve):Ve=e[71];let Ne;e[72]!==L||e[73]!==m||e[74]!==u||e[75]!==a||e[76]!==p||e[77]!==f||e[78]!==r||e[79]!==o||e[80]!==M?(Ne=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(F=>f(F,0,u??null,p??null,L,void 0,"project",m?.(F))):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:M("sessions.sidebar.folderItem.emptyFolder")})]}),e[72]=L,e[73]=m,e[74]=u,e[75]=a,e[76]=p,e[77]=f,e[78]=r,e[79]=o,e[80]=M,e[81]=Ne):Ne=e[81];let Y;return e[82]!==pe||e[83]!==Ve||e[84]!==Ne?(Y=s.jsxs("div",{className:pe,children:[Ve,Ne]}),e[82]=pe,e[83]=Ve,e[84]=Ne,e[85]=Y):Y=e[85],Y},E2=i.memo(R2);function M2(t){return t.stopPropagation()}function F2(t){return t.stopPropagation()}function O2(t){return t.stopPropagation()}function L2(t){return t.stopPropagation()}function B2(t){return t.stopPropagation()}function V2(t){return t.stopPropagation()}function _2(t){return t.stopPropagation()}function $2(t){return t.stopPropagation()}function z2(t){return t.stopPropagation()}function W2(t){return t.stopPropagation()}const U2=t=>{const e=ht.c(15),{sessionId:n,sessionDirectory:r,sessionTitle:o,children:a}=t,c=`session-drag:${n}`;let l;e[0]!==r||e[1]!==n||e[2]!==o?(l={type:"session",sessionId:n,sessionDirectory:r,sessionTitle:o},e[0]=r,e[1]=n,e[2]=o,e[3]=l):l=e[3];let d;e[4]!==c||e[5]!==l?(d={id:c,data:l},e[4]=c,e[5]=l,e[6]=d):d=e[6];const{attributes:f,listeners:m,setNodeRef:u,isDragging:p}=ip(d);let x;e[7]!==m?(x=h=>{h.stopPropagation(),m?.onPointerDown&&m.onPointerDown(h)},e[7]=m,e[8]=x):x=e[8];const b=x,w=p?"opacity-30":void 0;let g;return e[9]!==f||e[10]!==a||e[11]!==b||e[12]!==u||e[13]!==w?(g=s.jsx("div",{ref:u,...f,onPointerDown:b,className:w,children:a}),e[9]=f,e[10]=a,e[11]=b,e[12]=u,e[13]=w,e[14]=g):g=e[14],g},H2=t=>{const e=ht.c(11),{folderId:n,children:r}=t,o=`folder-drop:${n}`;let a;e[0]!==n?(a={type:"folder",folderId:n},e[0]=n,e[1]=a):a=e[1];let c;e[2]!==o||e[3]!==a?(c={id:o,data:a},e[2]=o,e[3]=a,e[4]=c):c=e[4];const{setNodeRef:l,isOver:d}=rp(c);let f;e[5]!==r||e[6]!==d||e[7]!==l?(f=r(l,d),e[5]=r,e[6]=d,e[7]=l,e[8]=f):f=e[8];let m;return e[9]!==f?(m=s.jsx(s.Fragment,{children:f}),e[9]=f,e[10]=m):m=e[10],m},G2=t=>{const e=ht.c(20),{scopeKey:n,hasFolders:r,onSessionDroppedOnFolder:o,children:a}=t;let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c={activationConstraint:{distance:8}},e[0]=c):c=e[0];const l=ja(Ao(Sa,c)),[d,f]=i.useState(null),[m,u]=i.useState("Session"),[p,x]=i.useState(null),[b,w]=i.useState(null);if(!n){let y;return e[1]!==a?(y=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=y):y=e[2],y}let g;e[3]!==o?(g=y=>{f(null),x(null),w(null);const{active:D,over:V}=y;if(!V)return;const v=D.data.current,O=V.data.current;v?.type==="session"&&v.sessionId&&O?.type==="folder"&&O.folderId&&o(v.sessionId,O.folderId)},e[3]=o,e[4]=g):g=e[4];const h=g;let C,j;e[5]===Symbol.for("react.memo_cache_sentinel")?(C=y=>{const D=y.active.data.current;if(D?.type==="session"&&D.sessionId){f(D.sessionId),u(D.sessionTitle??"Session");const V=y.active.rect.current.initial?.width,v=y.active.rect.current.initial?.height;x(typeof V=="number"?V:null),w(typeof v=="number"?v:null)}},j=()=>{f(null),x(null),w(null)},e[5]=C,e[6]=j):(C=e[5],j=e[6]);let S;e[7]!==b||e[8]!==d||e[9]!==m||e[10]!==p||e[11]!==r?(S=d&&r?s.jsxs("div",{style:{width:p?`${p}px`:"auto",height:b?`${b}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2.5 py-1 shadow-none pointer-events-none",children:[s.jsx(A,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:m})]}):null,e[7]=b,e[8]=d,e[9]=m,e[10]=p,e[11]=r,e[12]=S):S=e[12];let N;e[13]!==S?(N=s.jsx(ql,{children:S}),e[13]=S,e[14]=N):N=e[14];let k;return e[15]!==a||e[16]!==h||e[17]!==l||e[18]!==N?(k=s.jsxs(Na,{sensors:l,collisionDetection:ka,onDragStart:C,onDragCancel:j,onDragEnd:h,children:[a,N]}),e[15]=a,e[16]=h,e[17]=l,e[18]=N,e[19]=k):k=e[19],k},Yi=(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)},Yr=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if(Yr(n,e))return!0;return!1},_a=t=>t.children.length===0?"":t.children.map(n=>n.children.length===0?n.session.id:`${n.session.id}:${_a(n)}`).join("|"),$o=(t,e,n,r)=>{if(!e)return null;const o=r?"archived":"active";let a=null;const c=l=>{if(`${n}:${o}:${l.session.id}`===e)return a=l.session.id,!0;for(const f of l.children)if(c(f))return!0;return!1};return t.forEach(l=>c(l)),a},ar=co()(gc(t=>({displayMode:"minimal",showRecentSection:!0,showArchivedSessions:!1,projectSortOrder:"recent",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})),setProjectSortOrder:e=>t({projectSortOrder:e})}),{name:"session-display-mode",version:2,migrate:(t,e)=>{const n=t??{};return e<1?{...n,displayMode:"minimal",projectSortOrder:"recent"}:e<2?{...n,projectSortOrder:"recent"}:n}})),K2=50,q2=30,Y2=28,Wi=(t,e)=>e?t.sessions.some(n=>Yr(n,e)):!1,Q2=(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)},J2=(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)},X2=(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)},Z2=(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)},Sf=t=>{if(t.projectId)return t.projectRepoStatus.has(t.projectId)?t.projectRepoStatus.get(t.projectId):void 0},eN=(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&&Sf(t)!==Sf(e)||t.pinnedSessionIds!==e.pinnedSessionIds&&Q2(e.group,t.pinnedSessionIds,e.pinnedSessionIds)||t.expandedParents!==e.expandedParents&&X2(e.group,t.expandedParents,e.expandedParents)||t.sessionOrderIndex!==e.sessionOrderIndex&&J2(e.group,t.sessionOrderIndex,e.sessionOrderIndex)||t.currentSessionId!==e.currentSessionId&&(Wi(t.group,t.currentSessionId)||Wi(e.group,e.currentSessionId))||t.editingId!==e.editingId&&(Wi(t.group,t.editingId)||Wi(e.group,e.editingId))||t.editTitle!==e.editTitle&&(Wi(t.group,t.editingId)||Wi(e.group,e.editingId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=$o(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket),r=$o(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket);if(n||r)return!1}if(t.liveSessionById!==e.liveSessionById&&Z2(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 tN(t){const{t:e}=yt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:f,collapsedGroups:m,hideDirectoryControls:u,collapsedFolderIds:p,toggleFolderCollapse:x,renameFolder:b,deleteFolder:w,showDeletionDialog:g,setDeleteFolderConfirm:h,renderSessionNode:C,projectRepoStatus:j,lastRepoStatus:S,showMoreGroupSessions:N,resetGroupSessionLimit:k,mobileVariant:y,alwaysShowActions:D,activeProjectId:V,setActiveProjectIdOnly:v,setActiveMainTab:O,setSessionSwitcherOpen:P,openNewSessionDraft:E,addSessionToFolder:B,createFolderAndStartRename:T,renamingFolderId:W,renameFolderDraft:U,setRenameFolderDraft:L,setRenamingFolderId:M,pinnedSessionIds:ee,expandedParents:ie,sessionOrderIndex:X,currentSessionId:H,editingId:te,openSidebarMenuKey:re,prVisualStateByDirectoryBranch:le,onToggleCollapsedGroup:ve,dragHandleProps:ne,compactBodyPadding:we=!1,scrollContainerRef:he}=t,Me=i.useCallback((Fe,st)=>{const wt=X.get(Fe.session.id),St=X.get(st.session.id);if(wt!==void 0||St!==void 0){if(wt===void 0)return 1;if(St===void 0)return-1;if(wt!==St)return wt-St}return Qi(Fe.session,st.session,ee)},[ee,X]),z=c?d.get(n):null,K=ar(Fe=>Fe.displayMode),q=Wn(Fe=>Fe.foldersMap),me=K==="minimal"&&!_r(),Se=c?!1:m.has(r),Be=u?10:5,_e=Math.max(Be,f??Be),Le=c?z?.groupMatches===!0:!1,pe=c,Ee=i.useMemo(()=>[...pe?z?.filteredNodes??[]:n.sessions].sort(Me),[Me,n.sessions,z?.filteredNodes,pe]),ge=n.folderScopeKey??ds(n.directory??null),oe=i.useMemo(()=>ge?q[ge]??[]:[],[ge,q]),je=i.useMemo(()=>{const Fe=new Map,st=wt=>{wt.forEach(St=>{Fe.set(St.session.id,St),St.children.length>0&&st(St.children)})};return st(Ee),Fe},[Ee]),ye=i.useMemo(()=>oe.map(Fe=>{const st=Fe.sessionIds.map(wt=>je.get(wt)).filter(wt=>!!wt).sort(Me);return{folder:Fe,nodes:st}}),[oe,je,Me]),ue=i.useMemo(()=>{const Fe=new Map(ye.map(Nt=>[Nt.folder.id,Nt])),st=new Map;for(const{folder:Nt}of ye){if(!Nt.parentId)continue;const ss=st.get(Nt.parentId);ss?ss.push(Nt.id):st.set(Nt.parentId,[Nt.id])}const wt=new Map,St=Nt=>{const ss=wt.get(Nt);if(ss!==void 0)return ss;const cs=Fe.get(Nt);if(!cs)return wt.set(Nt,!1),!1;const Xt=st.get(Nt)??[];if(n.isArchivedBucket&&cs.nodes.length===0){const us=Xt.some($s=>St($s));return wt.set(Nt,us),us}if(!c||cs.folder.name.toLowerCase().includes(l)||cs.nodes.length>0)return wt.set(Nt,!0),!0;const Fs=Xt.some(us=>St(us));return wt.set(Nt,Fs),Fs};return ye.filter(({folder:Nt})=>St(Nt.id))},[ye,n.isArchivedBucket,c,l]),De=i.useMemo(()=>new Set(ue.flatMap(Fe=>Fe.folder.sessionIds)),[ue]),I=i.useMemo(()=>Ee.filter(Fe=>!De.has(Fe.session.id)),[Ee,De]),_=i.useMemo(()=>ue.filter(({folder:Fe})=>!Fe.parentId),[ue]),be="project",R=i.useMemo(()=>{const Fe=new Set;return Yi(Ee,H,Fe),ue.forEach(({nodes:st})=>{Yi(st,H,Fe)}),Fe},[Ee,ue,H]),de=i.useMemo(()=>{const Fe=new Set;return Yi(Ee,te,Fe),ue.forEach(({nodes:st})=>{Yi(st,te,Fe)}),Fe},[Ee,ue,te]),fe=i.useMemo(()=>{if(!re)return null;const Fe=$o(Ee,re,be,!!n.isArchivedBucket);if(Fe)return Fe;for(const{nodes:st}of ue){const wt=$o(st,re,be,!!n.isArchivedBucket);if(wt)return wt}return null},[re,Ee,ue,n.isArchivedBucket]),$=i.useCallback(Fe=>{const st=new WeakMap,wt=St=>{st.set(St,_a(St));for(const Nt of St.children)wt(Nt)};return Fe.forEach(wt),st},[]),Ae=i.useMemo(()=>$(Ee),[$,Ee]),Ve=i.useMemo(()=>{const Fe=new WeakMap;return ue.forEach(({nodes:st})=>{st.forEach(wt=>Fe.set(wt,_a(wt)))}),Fe},[ue]),Ne=i.useCallback(Fe=>Ae.get(Fe)??Ve.get(Fe)??"",[Ae,Ve]),Y=i.useCallback(Fe=>({subtreeContainsActive:R,subtreeContainsEditing:de,menuOpenSessionId:fe,nodeStructureKey:Ne(Fe)}),[R,de,fe,Ne]),F=I.length,se=n.isArchivedBucket||c?I:I.slice(0,_e),Oe=F-se.length,ce=!n.isArchivedBucket&&!c&&F>Be&&Oe===0,Ue=n.isArchivedBucket===!0&&!c&&se.length>=K2,qe=n.isArchivedBucket!==!0&&!c&&se.length>=q2,Ye=Ue||qe,tt=n.isArchivedBucket?"archived":"active",xt=Ye&&se.some(Fe=>{if(Fe.children.length===0)return!1;const st=`project:${tt}:${Fe.session.id}`;return ie.has(st)}),vt=i.useRef(null),[Mt,Tt]=i.useState(null),[Kt,Ut]=i.useState(0),[,Zt]=i.useState(0);i.useEffect(()=>{if(!Ye)return;const Fe=vt.current;if(!Fe||typeof ResizeObserver>"u")return;const st=new ResizeObserver(()=>Zt(wt=>wt+1));return st.observe(Fe),()=>st.disconnect()},[Ye]),i.useLayoutEffect(()=>{if(!Ye){Mt!==null&&Tt(null),Kt!==0&&Ut(0);return}const Fe=vt.current;if(!Fe)return;let st=Mt;const wt=he?.current??null;if(wt&&wt.contains(Fe)){if(st=wt,st!==Mt){Tt(st);return}}else if(!st||!st.contains(Fe)){let Nt=Fe.parentElement;for(;Nt;){const ss=window.getComputedStyle(Nt);if(ss.overflowY==="auto"||ss.overflowY==="scroll"){st=Nt;break}Nt=Nt.parentElement}if(st!==Mt){Tt(st);return}}if(!st)return;const St=Fe.getBoundingClientRect().top-st.getBoundingClientRect().top+st.scrollTop;Ut(Nt=>Math.abs(Nt-St)<1?Nt:St)});const ns=Ye&&Mt!==null,es=op({count:se.length,enabled:ns,getScrollElement:()=>Mt,initialOffset:()=>Mt?.scrollTop??0,estimateSize:()=>Y2,overscan:xt?20:8,scrollMargin:Kt,getItemKey:Fe=>se[Fe]?.session.id??Fe}),Ce=i.useCallback(Fe=>{const st=[],wt=St=>{St.forEach(Nt=>{st.push(Nt.session),Nt.children.length>0&&wt(Nt.children)})};return wt(Fe),st},[]),Qe=i.useMemo(()=>Ce(Ee),[Ce,Ee]),ot=i.useMemo(()=>{if(!n.isArchivedBucket)return new Map;const Fe=new Map,st=new Map;for(const{folder:St}of ue){if(!St.parentId)continue;const Nt=st.get(St.parentId)??[];Nt.push(St.id),st.set(St.parentId,Nt)}const wt=(St,Nt)=>{if(Nt.has(St))return[];Nt.add(St);const ss=ue.find(({folder:Vt})=>Vt.id===St),cs=ss?Ce(ss.nodes):[],Xt=st.get(St)??[];for(const Vt of Xt)cs.push(...wt(Vt,Nt));return cs};for(const{folder:St}of ue)Fe.set(St.id,wt(St.id,new Set));return Fe},[ue,Ce,n.isArchivedBucket]);if(c&&!Le&&_.length===0&&I.length===0)return null;const bt=o&&j.has(o)?!!j.get(o):S,Je=ds(n.directory??null),Pt=n.branch?.trim()??null,Xe=Je&&Pt?le.get(`${Je}::${Pt}`)??null:null,Ke=!!(Xe&&n.branch),Ze=!Xe&&!n.isMain&&!!n.branch,Bt=Xe?.visualState??null,Rt=Xe&&Xe.state==="open"&&Xe.checks?e("sessions.sidebar.group.pr.checksPassed",{success:Xe.checks.success,total:Xe.checks.total}):null,Ot=Xe&&Xe.state==="open"&&Xe.checks?[Xe.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:Xe.checks.failure}):null,Xe.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:Xe.checks.pending}):null].filter(Fe=>!!Fe).join(", "):null,rs=Xe&&Xe.state==="open"?Xe.mergeableState==="blocked"||Xe.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):Xe.mergeableState==="clean"||Xe.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,Wt=Xe&&Xe.state==="open"&&Xe.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:Xe.mergeableState}):null,Et=Xe?.base??null,qt=Xe?.head??null,hs=(()=>{if(!Xe)return n.branch&&kb(n.branch,n.label)?{label:n.branch,color:null}:null;switch(Xe.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return Xe.canMerge===!0||Xe.mergeableState==="clean"||Xe.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:Xe.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}})(),ts=hs?.color??(Bt?`var(--pr-${Bt})`:void 0),as=Fe=>{Fe.preventDefault(),Fe.stopPropagation();const st=Xe?.url;st&&ti(st)},gs=(Fe,st,wt)=>{const St=ue.filter(({folder:cs})=>cs.parentId===Fe.id),Nt=St.length>0?s.jsx(s.Fragment,{children:St.map(({folder:cs,nodes:Xt})=>gs(cs,Xt,wt+1))}):void 0,ss=ot.get(Fe.id)??[];return s.jsx(H2,{folderId:Fe.id,children:(cs,Xt)=>s.jsx(E2,{folder:Fe,sessions:st,subFolderItems:Nt,isCollapsed:c?!1:p.has(Fe.id),onToggle:()=>x(Fe.id),onRename:Vt=>{ge&&b(ge,Fe.id,Vt)},onDelete:()=>{if(n.isArchivedBucket){Lr.requestDelete({sessions:ss,mode:"session"});return}if(!ge)return;if(!g){w(ge,Fe.id);return}const Vt=ue.filter(({folder:us})=>us.parentId===Fe.id).length,Fs=st.length;h({scopeKey:ge,folderId:Fe.id,folderName:Fe.name,subFolderCount:Vt,sessionCount:Fs})},renderSessionNode:C,getRenderExtras:Ne?Vt=>({subtreeContainsActive:R,subtreeContainsEditing:de,menuOpenSessionId:fe,nodeStructureKey:Ne(Vt),childRenderExtrasFor:Y}):void 0,groupDirectory:n.directory,projectId:o,mobileVariant:y,alwaysShowActions:D,isRenaming:W===Fe.id,renameDraft:W===Fe.id?U:void 0,onRenameDraftChange:Vt=>L(Vt),onRenameSave:()=>{const Vt=U.trim();Vt&&ge&&b(ge,Fe.id,Vt),M(null),L("")},onRenameCancel:()=>{M(null),L("")},droppableRef:cs,isDropTarget:Xt,depth:wt,onNewSession:()=>{o&&o!==V&&v(o),O("chat"),y&&P(!1),E({directoryOverride:n.directory,targetFolderId:Fe.id})},onNewSubFolder:wt===0?()=>{ge&&T(ge,Fe.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},Fe.id)},Ft=()=>_.map(({folder:Fe,nodes:st})=>gs(Fe,st,0)),Lt=!!(!n.isMain&&n.worktree),Ht=D?Lt?"pr-14":"pr-7":me?Lt?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":Lt?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",Yt=s.jsxs(G2,{scopeKey:ge,hasFolders:ue.length>0,onSessionDroppedOnFolder:(Fe,st)=>{ge&&B(ge,st,Fe)},children:[Ft(),Ye?s.jsx("div",{ref:vt,children:ns?s.jsx("div",{style:{height:es.getTotalSize(),position:"relative"},children:es.getVirtualItems().map(Fe=>{const st=se[Fe.index];return st?s.jsx("div",{"data-index":Fe.index,ref:es.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${Fe.start-Kt}px)`},children:C(st,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:R,subtreeContainsEditing:de,menuOpenSessionId:fe,nodeStructureKey:Ne(st),childRenderExtrasFor:Y})},st.session.id):null})}):se.map(Fe=>C(Fe,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:R,subtreeContainsEditing:de,menuOpenSessionId:fe,nodeStructureKey:Ne(Fe),childRenderExtrasFor:Y}))}):se.map(Fe=>C(Fe,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:R,subtreeContainsEditing:de,menuOpenSessionId:fe,nodeStructureKey:Ne(Fe),childRenderExtrasFor:Y})),F===0&&ue.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,Oe>0?s.jsx("button",{type:"button",onClick:()=>N(r,se.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showMore")}):null,ce?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]}),$t=we?"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",$t),children:Yt})}):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:()=>ve(r),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),ve(r))},"aria-label":Se?e("sessions.sidebar.group.expandAria",{label:n.label}):e("sessions.sidebar.group.collapseAria",{label:n.label}),"aria-expanded":!Se,children:[s.jsx("div",{ref:ne?.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",Ht),...ne?.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:Ke&&Xe?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 leading-none align-middle",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(A,{name:"git-branch",className:Pe("h-3.5 w-3.5 shrink-0",D?"hidden":"group-hover/gh:hidden"),style:ts?{color:ts}:void 0}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Se?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),Xe.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:Fe=>Fe.stopPropagation(),onClick:as,children:["#",Xe.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",Xe.number]})]})}),s.jsx(Dt,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Et||qt?s.jsx("div",{className:"text-muted-foreground truncate",children:Et&&qt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Et}),s.jsx(A,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:qt})]}):s.jsx("span",{children:Et??qt??""})}):null,Wt?s.jsx("div",{className:"text-muted-foreground truncate",children:Wt}):null,rs||Rt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[rs??"",rs&&Rt?" • ":"",Rt??"",Ot?` (${Ot})`:""]}):null]})})]}),s.jsx("span",{className:"ml-1 min-w-0 flex-1 truncate leading-none align-middle",children:n.branch})]}):n.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(A,{name:"archive",className:Pe("h-3.5 w-3.5 shrink-0 text-muted-foreground",D?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Se?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:To(n.label,l)})]}):!n.isMain||n.worktree?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(A,{name:"git-branch",className:Pe("h-3.5 w-3.5 shrink-0 text-muted-foreground",D?"hidden":"group-hover/gh:hidden"),style:ts?{color:ts}:void 0}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Se?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:To(n.label,l)})]}):To(n.label,l)}),Ze&&hs?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(A,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||bt?Ke&&Xe?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:s.jsx(A,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:ts?{color:ts}:void 0})})}),s.jsx(Dt,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Et||qt?s.jsx("div",{className:"text-muted-foreground truncate",children:Et&&qt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Et}),s.jsx(A,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:qt})]}):s.jsx("span",{children:Et??qt??""})}):null,Wt?s.jsx("div",{className:"text-muted-foreground truncate",children:Wt}):null,rs||Rt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[rs??"",rs&&Rt?" • ":"",Rt??"",Ot?` (${Ot})`:""]}):null]})})]}):s.jsx(A,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:ts?{color:ts}:void 0}):null,s.jsx("span",{className:Pe("min-w-0 truncate text-[11px] font-medium",!hs.color&&"text-muted-foreground/80"),style:hs.color?{color:hs.color}:void 0,children:hs.label})]}):null]})}),n.isArchivedBucket&&Qe.length>0?s.jsx("div",{className:Pe("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",D?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Fe=>{Fe.stopPropagation(),Lr.requestDelete({sessions:Qe,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.deleteArchivedInGroupAria",{label:n.label}),children:s.jsx(A,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Dt,{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",D?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Fe=>{Fe.stopPropagation(),Lr.requestDelete({sessions:Qe,mode:"worktree",worktree:n.worktree})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.deleteGroupAria",{label:n.label}),children:s.jsx(A,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Dt,{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",D?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Fe=>{Fe.stopPropagation(),o&&o!==V&&v(o),O("chat"),y&&P(!1),E({directoryOverride:n.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.newDraftInGroupAria",{label:n.label}),children:s.jsx(A,{name:"add",className:"h-4 w-4"})})}),s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),Se?null:s.jsx("div",{className:Pe("oc-group-body",$t),children:Yt})]})}const sN=i.memo(tN,eN);function nN(t){const e=ht.c(267),{t:n}=yt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:f,headerActionButtonClass:m,isSessionSearchOpen:u,setIsSessionSearchOpen:p,sessionSearchInputRef:x,sessionSearchQuery:b,setSessionSearchQuery:w,hasSessionSearchQuery:g,searchMatchCount:h,collapseAllProjects:C,expandAllProjects:j,openScheduledTasksDialog:S,selectionModeEnabled:N,onToggleSelectionMode:k}=t,y=ar(fN),D=ar(uN),V=ar(dN),v=ar(cN),O=ar(lN),P=ar(aN),E=ar(oN),B=ar(iN);let T;e[0]===Symbol.for("react.memo_cache_sentinel")?(T=_r(),e[0]=T):T=e[0];const W=!T;if(r)return null;let U;e[1]!==n?(U=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=U):U=e[2];let L;e[3]!==f?(L=s.jsx(A,{name:"folder-add",className:f}),e[3]=f,e[4]=L):L=e[4];let M;e[5]!==a||e[6]!==m||e[7]!==U||e[8]!==L?(M=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:m,"aria-label":U,children:L})}),e[5]=a,e[6]=m,e[7]=U,e[8]=L,e[9]=M):M=e[9];let ee;e[10]!==n?(ee=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=ee):ee=e[11];let ie;e[12]!==ee?(ie=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ee})}),e[12]=ee,e[13]=ie):ie=e[13];let X;e[14]!==M||e[15]!==ie?(X=s.jsxs(Ct,{children:[M,ie]}),e[14]=M,e[15]=ie,e[16]=X):X=e[16];let H;e[17]!==n?(H=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=H):H=e[18];let te;e[19]!==f?(te=s.jsx(A,{name:"chat-new",className:f}),e[19]=f,e[20]=te):te=e[20];let re;e[21]!==m||e[22]!==c||e[23]!==H||e[24]!==te?(re=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:m,"aria-label":H,children:te})}),e[21]=m,e[22]=c,e[23]=H,e[24]=te,e[25]=re):re=e[25];let le;e[26]!==n?(le=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=le):le=e[27];let ve;e[28]!==le?(ve=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:le})}),e[28]=le,e[29]=ve):ve=e[29];let ne;e[30]!==ve||e[31]!==re?(ne=s.jsxs(Ct,{children:[re,ve]}),e[30]=ve,e[31]=re,e[32]=ne):ne=e[32];let we;e[33]!==n?(we=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=we):we=e[34];const he=!l;let Me;e[35]!==f?(Me=s.jsx(_g,{className:f}),e[35]=f,e[36]=Me):Me=e[36];let z;e[37]!==m||e[38]!==d||e[39]!==we||e[40]!==he||e[41]!==Me?(z=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:m,"aria-label":we,disabled:he,children:Me})}),e[37]=m,e[38]=d,e[39]=we,e[40]=he,e[41]=Me,e[42]=z):z=e[42];let K;e[43]!==n?(K=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=K):K=e[44];let q;e[45]!==K?(q=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:K})}),e[45]=K,e[46]=q):q=e[46];let me;e[47]!==z||e[48]!==q?(me=s.jsxs(Ct,{children:[z,q]}),e[47]=z,e[48]=q,e[49]=me):me=e[49];let Se;e[50]!==n?(Se=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=Se):Se=e[51];let Be;e[52]!==f?(Be=s.jsx(A,{name:"calendar-schedule",className:f}),e[52]=f,e[53]=Be):Be=e[53];let _e;e[54]!==m||e[55]!==S||e[56]!==Se||e[57]!==Be?(_e=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:m,"aria-label":Se,children:Be})}),e[54]=m,e[55]=S,e[56]=Se,e[57]=Be,e[58]=_e):_e=e[58];let Le;e[59]!==n?(Le=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=Le):Le=e[60];let pe;e[61]!==Le?(pe=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Le})}),e[61]=Le,e[62]=pe):pe=e[62];let Ee;e[63]!==_e||e[64]!==pe?(Ee=s.jsxs(Ct,{children:[_e,pe]}),e[63]=_e,e[64]=pe,e[65]=Ee):Ee=e[65];let ge;e[66]!==ne||e[67]!==me||e[68]!==Ee||e[69]!==X?(ge=s.jsxs("div",{className:"flex items-center gap-1.5",children:[X,ne,me,Ee]}),e[66]=ne,e[67]=me,e[68]=Ee,e[69]=X,e[70]=ge):ge=e[70];let oe;e[71]!==p?(oe=()=>p(rN),e[71]=p,e[72]=oe):oe=e[72];let je;e[73]!==n?(je=n("sessions.sidebar.header.actions.searchSessions"),e[73]=n,e[74]=je):je=e[74];let ye;e[75]!==f?(ye=s.jsx(A,{name:"search",className:f}),e[75]=f,e[76]=ye):ye=e[76];let ue;e[77]!==m||e[78]!==u||e[79]!==oe||e[80]!==je||e[81]!==ye?(ue=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:oe,className:m,"aria-label":je,"aria-expanded":u,children:ye})}),e[77]=m,e[78]=u,e[79]=oe,e[80]=je,e[81]=ye,e[82]=ue):ue=e[82];let De;e[83]!==n?(De=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=De):De=e[84];let I;e[85]!==De?(I=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:De})}),e[85]=De,e[86]=I):I=e[86];let _;e[87]!==ue||e[88]!==I?(_=s.jsxs(Ct,{children:[ue,I]}),e[87]=ue,e[88]=I,e[89]=_):_=e[89];const be=N&&"bg-interactive-hover text-primary";let R;e[90]!==m||e[91]!==be?(R=Pe(m,be),e[90]=m,e[91]=be,e[92]=R):R=e[92];let de;e[93]!==N||e[94]!==n?(de=n(N?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=N,e[94]=n,e[95]=de):de=e[95];let fe;e[96]!==f?(fe=s.jsx(A,{name:"checkbox-multiple",className:f}),e[96]=f,e[97]=fe):fe=e[97];let $;e[98]!==k||e[99]!==N||e[100]!==R||e[101]!==de||e[102]!==fe?($=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:R,"aria-label":de,"aria-pressed":N,children:fe})}),e[98]=k,e[99]=N,e[100]=R,e[101]=de,e[102]=fe,e[103]=$):$=e[103];let Ae;e[104]!==N||e[105]!==n?(Ae=n(N?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=N,e[105]=n,e[106]=Ae):Ae=e[106];let Ve;e[107]!==Ae?(Ve=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Ae})}),e[107]=Ae,e[108]=Ve):Ve=e[108];let Ne;e[109]!==$||e[110]!==Ve?(Ne=s.jsxs(Ct,{children:[$,Ve]}),e[109]=$,e[110]=Ve,e[111]=Ne):Ne=e[111];let Y;e[112]!==n?(Y=n("sessions.sidebar.header.actions.sortProjects"),e[112]=n,e[113]=Y):Y=e[113];let F;e[114]!==f?(F=s.jsx(A,{name:"sort-desc",className:f}),e[114]=f,e[115]=F):F=e[115];let se;e[116]!==m||e[117]!==Y||e[118]!==F?(se=s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":Y,children:F})})}),e[116]=m,e[117]=Y,e[118]=F,e[119]=se):se=e[119];let Oe;e[120]!==n?(Oe=n("sessions.sidebar.header.actions.sortProjects"),e[120]=n,e[121]=Oe):Oe=e[121];let ce;e[122]!==Oe?(ce=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Oe})}),e[122]=Oe,e[123]=ce):ce=e[123];let Ue;e[124]!==se||e[125]!==ce?(Ue=s.jsxs(Ct,{children:[se,ce]}),e[124]=se,e[125]=ce,e[126]=Ue):Ue=e[126];let qe;e[127]!==B?(qe=()=>B("manual"),e[127]=B,e[128]=qe):qe=e[128];let Ye;e[129]!==n?(Ye=n("sessions.sidebar.header.projectSort.manual"),e[129]=n,e[130]=Ye):Ye=e[130];let tt;e[131]!==Ye?(tt=s.jsx("span",{children:Ye}),e[131]=Ye,e[132]=tt):tt=e[132];let xt;e[133]!==E?(xt=E==="manual"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null,e[133]=E,e[134]=xt):xt=e[134];let vt;e[135]!==qe||e[136]!==tt||e[137]!==xt?(vt=s.jsxs(ms,{onClick:qe,className:"flex items-center justify-between",children:[tt,xt]}),e[135]=qe,e[136]=tt,e[137]=xt,e[138]=vt):vt=e[138];let Mt;e[139]!==B?(Mt=()=>B("a-z"),e[139]=B,e[140]=Mt):Mt=e[140];let Tt;e[141]!==n?(Tt=n("sessions.sidebar.header.projectSort.aToZ"),e[141]=n,e[142]=Tt):Tt=e[142];let Kt;e[143]!==Tt?(Kt=s.jsx("span",{children:Tt}),e[143]=Tt,e[144]=Kt):Kt=e[144];let Ut;e[145]!==E?(Ut=E==="a-z"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null,e[145]=E,e[146]=Ut):Ut=e[146];let Zt;e[147]!==Mt||e[148]!==Kt||e[149]!==Ut?(Zt=s.jsxs(ms,{onClick:Mt,className:"flex items-center justify-between",children:[Kt,Ut]}),e[147]=Mt,e[148]=Kt,e[149]=Ut,e[150]=Zt):Zt=e[150];let ns;e[151]!==B?(ns=()=>B("z-a"),e[151]=B,e[152]=ns):ns=e[152];let es;e[153]!==n?(es=n("sessions.sidebar.header.projectSort.zToA"),e[153]=n,e[154]=es):es=e[154];let Ce;e[155]!==es?(Ce=s.jsx("span",{children:es}),e[155]=es,e[156]=Ce):Ce=e[156];let Qe;e[157]!==E?(Qe=E==="z-a"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null,e[157]=E,e[158]=Qe):Qe=e[158];let ot;e[159]!==ns||e[160]!==Ce||e[161]!==Qe?(ot=s.jsxs(ms,{onClick:ns,className:"flex items-center justify-between",children:[Ce,Qe]}),e[159]=ns,e[160]=Ce,e[161]=Qe,e[162]=ot):ot=e[162];let bt;e[163]!==B?(bt=()=>B("date-added"),e[163]=B,e[164]=bt):bt=e[164];let Je;e[165]!==n?(Je=n("sessions.sidebar.header.projectSort.dateAdded"),e[165]=n,e[166]=Je):Je=e[166];let Pt;e[167]!==Je?(Pt=s.jsx("span",{children:Je}),e[167]=Je,e[168]=Pt):Pt=e[168];let Xe;e[169]!==E?(Xe=E==="date-added"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null,e[169]=E,e[170]=Xe):Xe=e[170];let Ke;e[171]!==bt||e[172]!==Pt||e[173]!==Xe?(Ke=s.jsxs(ms,{onClick:bt,className:"flex items-center justify-between",children:[Pt,Xe]}),e[171]=bt,e[172]=Pt,e[173]=Xe,e[174]=Ke):Ke=e[174];let Ze;e[175]!==B?(Ze=()=>B("recent"),e[175]=B,e[176]=Ze):Ze=e[176];let Bt;e[177]!==n?(Bt=n("sessions.sidebar.header.projectSort.recent"),e[177]=n,e[178]=Bt):Bt=e[178];let Rt;e[179]!==Bt?(Rt=s.jsx("span",{children:Bt}),e[179]=Bt,e[180]=Rt):Rt=e[180];let Ot;e[181]!==E?(Ot=E==="recent"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null,e[181]=E,e[182]=Ot):Ot=e[182];let rs;e[183]!==Ze||e[184]!==Rt||e[185]!==Ot?(rs=s.jsxs(ms,{onClick:Ze,className:"flex items-center justify-between",children:[Rt,Ot]}),e[183]=Ze,e[184]=Rt,e[185]=Ot,e[186]=rs):rs=e[186];let Wt;e[187]!==vt||e[188]!==Zt||e[189]!==ot||e[190]!==Ke||e[191]!==rs?(Wt=s.jsxs(en,{align:"end",className:"min-w-[160px]",children:[vt,Zt,ot,Ke,rs]}),e[187]=vt,e[188]=Zt,e[189]=ot,e[190]=Ke,e[191]=rs,e[192]=Wt):Wt=e[192];let Et;e[193]!==Ue||e[194]!==Wt?(Et=s.jsxs(tn,{children:[Ue,Wt]}),e[193]=Ue,e[194]=Wt,e[195]=Et):Et=e[195];let qt;e[196]!==n?(qt=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[196]=n,e[197]=qt):qt=e[197];let hs;e[198]!==f?(hs=s.jsx(A,{name:"equalizer-2",className:f}),e[198]=f,e[199]=hs):hs=e[199];let ts;e[200]!==m||e[201]!==qt||e[202]!==hs?(ts=s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":qt,children:hs})})}),e[200]=m,e[201]=qt,e[202]=hs,e[203]=ts):ts=e[203];let as;e[204]!==n?(as=n("sessions.sidebar.header.displayMode.label"),e[204]=n,e[205]=as):as=e[205];let gs;e[206]!==as?(gs=s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:as})}),e[206]=as,e[207]=gs):gs=e[207];let Ft;e[208]!==ts||e[209]!==gs?(Ft=s.jsxs(Ct,{children:[ts,gs]}),e[208]=ts,e[209]=gs,e[210]=Ft):Ft=e[210];let Lt;e[211]!==y||e[212]!==v||e[213]!==n?(Lt=W?s.jsxs(s.Fragment,{children:[s.jsxs(ms,{onClick:()=>v("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),y==="default"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(ms,{onClick:()=>v("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),y==="minimal"?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[211]=y,e[212]=v,e[213]=n,e[214]=Lt):Lt=e[214];let Ht;e[215]!==V||e[216]!==o||e[217]!==D||e[218]!==n||e[219]!==P||e[220]!==O?(Ht=o?s.jsxs(s.Fragment,{children:[W?s.jsx(Vr,{}):null,s.jsxs(ms,{onClick:O,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showRecent")}),D?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(ms,{onClick:P,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),V?s.jsx(A,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[215]=V,e[216]=o,e[217]=D,e[218]=n,e[219]=P,e[220]=O,e[221]=Ht):Ht=e[221];let Yt;e[222]===Symbol.for("react.memo_cache_sentinel")?(Yt=s.jsx(Vr,{}),e[222]=Yt):Yt=e[222];let $t;e[223]===Symbol.for("react.memo_cache_sentinel")?($t=s.jsx(A,{name:"contract-up-down",className:"h-4 w-4"}),e[223]=$t):$t=e[223];let Fe;e[224]!==n?(Fe=n("sessions.sidebar.header.displayMode.collapseAll"),e[224]=n,e[225]=Fe):Fe=e[225];let st;e[226]!==Fe?(st=s.jsx("span",{children:Fe}),e[226]=Fe,e[227]=st):st=e[227];let wt;e[228]!==C||e[229]!==st?(wt=s.jsxs(ms,{onClick:C,className:"flex items-center gap-2",children:[$t,st]}),e[228]=C,e[229]=st,e[230]=wt):wt=e[230];let St;e[231]===Symbol.for("react.memo_cache_sentinel")?(St=s.jsx(A,{name:"expand-up-down",className:"h-4 w-4"}),e[231]=St):St=e[231];let Nt;e[232]!==n?(Nt=n("sessions.sidebar.header.displayMode.expandAll"),e[232]=n,e[233]=Nt):Nt=e[233];let ss;e[234]!==Nt?(ss=s.jsx("span",{children:Nt}),e[234]=Nt,e[235]=ss):ss=e[235];let cs;e[236]!==j||e[237]!==ss?(cs=s.jsxs(ms,{onClick:j,className:"flex items-center gap-2",children:[St,ss]}),e[236]=j,e[237]=ss,e[238]=cs):cs=e[238];let Xt;e[239]!==Lt||e[240]!==Ht||e[241]!==wt||e[242]!==cs?(Xt=s.jsxs(en,{align:"end",className:"min-w-[160px]",children:[Lt,Ht,Yt,wt,cs]}),e[239]=Lt,e[240]=Ht,e[241]=wt,e[242]=cs,e[243]=Xt):Xt=e[243];let Vt;e[244]!==Ft||e[245]!==Xt?(Vt=s.jsxs(tn,{children:[Ft,Xt]}),e[244]=Ft,e[245]=Xt,e[246]=Vt):Vt=e[246];let Fs;e[247]!==_||e[248]!==Ne||e[249]!==Et||e[250]!==Vt?(Fs=s.jsxs("div",{className:"flex items-center gap-1.5",children:[_,Ne,Et,Vt]}),e[247]=_,e[248]=Ne,e[249]=Et,e[250]=Vt,e[251]=Fs):Fs=e[251];let us;e[252]!==ge||e[253]!==Fs?(us=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[ge,Fs]}),e[252]=ge,e[253]=Fs,e[254]=us):us=e[254];let $s;e[255]!==g||e[256]!==u||e[257]!==h||e[258]!==x||e[259]!==b||e[260]!==p||e[261]!==w||e[262]!==n?($s=u?s.jsxs("div",{className:"pb-1",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:[g?s.jsx("span",{children:h===1?n("sessions.sidebar.header.search.matchCountSingle",{count:h}):n("sessions.sidebar.header.search.matchCountPlural",{count:h})}):s.jsx("span",{}),s.jsx("span",{children:n("sessions.sidebar.header.search.escapeHint")})]}),s.jsxs("div",{className:"relative",children:[s.jsx(A,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:x,value:b,onChange:Cs=>w(Cs.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:Cs=>{Cs.key==="Escape"&&(Cs.stopPropagation(),g?w(""):p(!1))}}),b.length>0?s.jsx("button",{type:"button",onClick:()=>w(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":n("sessions.sidebar.header.search.clear"),children:s.jsx(A,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[255]=g,e[256]=u,e[257]=h,e[258]=x,e[259]=b,e[260]=p,e[261]=w,e[262]=n,e[263]=$s):$s=e[263];let js;return e[264]!==us||e[265]!==$s?(js=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:[us,$s]})}),e[264]=us,e[265]=$s,e[266]=js):js=e[266],js}function rN(t){return!t}function iN(t){return t.setProjectSortOrder}function oN(t){return t.projectSortOrder}function aN(t){return t.toggleArchivedSessions}function lN(t){return t.toggleRecentSection}function cN(t){return t.setDisplayMode}function dN(t){return t.showArchivedSessions}function uN(t){return t.showRecentSection}function fN(t){return t.displayMode}const Nf=7;function mN({sections:t,renderSessionNode:e,currentSessionId:n,editingId:r,openSidebarMenuKey:o,variant:a="section",initialVisibleCount:c=Nf,batchSize:l=Nf}){const{t:d}=yt(),[f,m]=i.useState(new Set),[u,p]=i.useState(new Map),x=a==="flat",b=i.useCallback(j=>{p(S=>{if(!S.has(j))return S;const N=new Map(S);return N.delete(j),N})},[]),w=i.useCallback(j=>{b(j),m(S=>{const N=new Set(S);return N.has(j)?N.delete(j):N.add(j),N})},[b]),g=i.useCallback((j,S,N)=>{p(k=>{const y=Math.min(N,S+l),D=new Map(k);return D.set(j,y),D})},[l]),h=i.useCallback(j=>{const S=new Set;Yi(j,n,S);const N=new Set;Yi(j,r,N);const k=$o(j,o,"recent",!1),y=new WeakMap,D=v=>{y.set(v,_a(v)),v.children.forEach(D)};j.forEach(D);const V=v=>({subtreeContainsActive:S,subtreeContainsEditing:N,menuOpenSessionId:k,nodeStructureKey:y.get(v)??"",childRenderExtrasFor:V});return v=>({subtreeContainsActive:S,subtreeContainsEditing:N,menuOpenSessionId:k,nodeStructureKey:y.get(v)??"",childRenderExtrasFor:V})},[n,r,o]),C=t.filter(j=>j.items.length>0);return C.length===0?null:s.jsx("div",{className:Pe(x?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1"),children:C.map(j=>{const S=f.has(j.key),N=Math.max(c,u.get(j.key)??c),k=j.items.slice(0,N),y=j.items.length-k.length,D=!x&&j.items.length>c&&y===0,V=h(k.map(O=>O.node)),v=O=>e(O.node,0,O.groupDirectory,O.projectId,!1,O.secondaryMeta,"recent",V(O.node));return x?s.jsxs("div",{className:"space-y-0.5",children:[k.map(v),y>0?s.jsx("button",{type:"button",onClick:()=>g(j.key,k.length,j.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]},j.key):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("button",{type:"button",onClick:()=>w(j.key),className:"group flex w-full items-center gap-1 rounded-md px-0.5 py-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-expanded":!S,children:[s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground",children:S?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"text-[14px] font-normal text-foreground/95",children:j.title})]}),S?null:s.jsxs("div",{className:Pe("space-y-0.5 pl-7"),children:[k.map(v),y>0?s.jsx("button",{type:"button",onClick:()=>g(j.key,k.length,j.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showMore")}):null,D?s.jsx("button",{type:"button",onClick:()=>b(j.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]})]},j.key)})})}const Vl="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function hN(t){const e=ht.c(14),{onOpenSettings:n,onOpenShortcuts:r,onOpenAbout:o,onOpenUpdate:a,onOpenShareOpinion:c,showRuntimeButtons:l,showUpdateButton:d}=t,f=l===void 0?!0:l,m=d===void 0?!0:d,{t:u}=yt();let p;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==f||e[4]!==u?(p=f?s.jsxs(s.Fragment,{children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Vl,"aria-label":u("sessions.sidebar.footer.actions.settings"),children:s.jsx(A,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(Dt,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:Vl,"aria-label":u("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(A,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(Dt,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:Vl,"aria-label":u("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(A,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(Dt,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=f,e[4]=u,e[5]=p):p=e[5];let x;e[6]!==c||e[7]!==a||e[8]!==m||e[9]!==u?(x=m?s.jsx(ze,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:a,children:u("sessions.sidebar.footer.actions.update")}):s.jsx(ze,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--primary-base)]/15 bg-[var(--primary-base)]/5 text-[var(--primary-base)]/60 hover:bg-[var(--primary-base)]/10 hover:text-[var(--primary-base)]/75",onClick:c,children:u("sessions.sidebar.footer.actions.shareOpinion")}),e[6]=c,e[7]=a,e[8]=m,e[9]=u,e[10]=x):x=e[10];let b;return e[11]!==p||e[12]!==x?(b=s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-2.5 py-2",children:[p,x]}),e[11]=p,e[12]=x,e[13]=b):b=e[13],b}const pN=t=>{const e=ht.c(59),{id:n,disabled:r,projectLabel:o,projectDescription:a,projectIcon:c,projectColor:l,projectIconImage:d,projectIconBackground:f,isCollapsed:m,isActiveProject:u,isRepo:p,isDesktopShell:x,isStuck:b,hideDirectoryControls:w,alwaysShowActions:g,onToggle:h,onNewSession:C,onNewWorktreeSession:j,onRenameStart:S,onClose:N,sentinelRef:k,children:y,showCreateButtons:D,hideHeader:V,openSidebarMenuKey:v,setOpenSidebarMenuKey:O}=t,P=r===void 0?!1:r,E=D===void 0?!0:D,B=V===void 0?!1:V,{t:T}=yt(),{currentTheme:W}=yi();let U;e[0]!==P||e[1]!==n?(U={id:n,disabled:P},e[0]=P,e[1]=n,e[2]=U):U=e[2];const{attributes:L,listeners:M,setNodeRef:ee,transform:ie,transition:X,isDragging:H}=xc(U),te=i.useRef(!1),re=`project:${n}`,le=v===re,[ve,ne]=i.useState(!1),we=c?Oc[c]:null,he=l?Lc[l]??null:null;let Me;e[3]!==re||e[4]!==O?(Me=I=>{I&&ne(!1),O(I?re:null)},e[3]=re,e[4]=O,e[5]=Me):Me=e[5];const z=Me;let K;e[6]!==w||e[7]!==p||e[8]!==N||e[9]!==C||e[10]!==S||e[11]!==E||e[12]!==T?(K=I=>s.jsxs(s.Fragment,{children:[E&&!p&&!w&&C&&s.jsxs(I,{onClick:C,children:[s.jsx(A,{name:"add",className:"mr-1.5 h-4 w-4"}),T("sessions.sidebar.project.actions.newSession")]}),s.jsxs(I,{onClick:S,children:[s.jsx(A,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),T("sessions.sidebar.project.actions.edit")]}),s.jsxs(I,{onClick:N,className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"close",className:"mr-1.5 h-4 w-4"}),T("sessions.sidebar.project.actions.closeProject")]})]}),e[6]=w,e[7]=p,e[8]=N,e[9]=C,e[10]=S,e[11]=E,e[12]=T,e[13]=K):K=e[13];const q=K,me=bN,Se=wN,Be=yN;let _e;e[14]===Symbol.for("react.memo_cache_sentinel")?(_e=I=>{(I.button===2||I.button===0&&I.ctrlKey)&&(te.current=!0)},e[14]=_e):_e=e[14];const Le=_e;let pe;e[15]!==h?(pe=()=>{if(te.current){te.current=!1;return}h()},e[15]=h,e[16]=pe):pe=e[16];const Ee=pe;let ge;e[17]!==ie?(ge=bc.Transform.toString(ie),e[17]=ie,e[18]=ge):ge=e[18];let oe;e[19]!==ge||e[20]!==X?(oe={transform:ge,transition:X},e[19]=ge,e[20]=X,e[21]=oe):oe=e[21];const je=H&&"opacity-30";let ye;e[22]!==je?(ye=Pe("relative",je),e[22]=je,e[23]=ye):ye=e[23];let ue;e[24]!==g||e[25]!==L||e[26]!==W||e[27]!==z||e[28]!==Ee||e[29]!==w||e[30]!==B||e[31]!==he||e[32]!==n||e[33]!==u||e[34]!==m||e[35]!==ve||e[36]!==x||e[37]!==le||e[38]!==p||e[39]!==b||e[40]!==M||e[41]!==C||e[42]!==j||e[43]!==a||e[44]!==f||e[45]!==d||e[46]!==we||e[47]!==o||e[48]!==q||e[49]!==k||e[50]!==E||e[51]!==T?(ue=B?null:s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{ref:k,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsxs(Wc,{open:ve,onOpenChange:ne,children:[s.jsx(zc,{render:s.jsx("div",{className:Pe("w-full text-left group/project select-none"),style:{backgroundColor:x&&b?"transparent":void 0},onContextMenu:I=>{w||(I.preventDefault(),ne(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...L,children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:Le,onClick:Ee,...M,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]",p&&!w?g?"pr-20":"pr-7 group-hover/project:pr-20 group-focus-within/project:pr-20":g?"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",g?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:m?s.jsx(A,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),d?s.jsx("span",{className:Pe("h-3.5 w-3.5 items-center justify-center overflow-hidden rounded-[3px]",g?"hidden":"inline-flex group-hover/project:hidden group-focus-within/project:hidden"),style:f?{backgroundColor:f}:void 0,children:s.jsx(Bc,{project:{id:n,iconImage:d},options:{themeVariant:W.metadata.variant,iconColor:W.colors.surface.foreground},className:"h-full w-full object-contain",fallback:we?s.jsx(A,{name:we,className:"h-3.5 w-3.5",style:he?{color:he}:void 0}):s.jsx(A,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:he?{color:he}:void 0})})}):we?s.jsx(A,{name:we,className:Pe("h-3.5 w-3.5",g?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:he?{color:he}:void 0}):s.jsx(A,{name:"folder",className:Pe("h-3.5 w-3.5 text-muted-foreground/80",g?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:he?{color:he}:void 0})]}),s.jsx("span",{className:Pe("text-[14px] font-normal truncate lowercase",u?"text-foreground":"text-foreground group-hover/project:text-foreground"),children:o})]})}),s.jsx(Dt,{side:"right",sideOffset:8,children:a})]}),s.jsxs("div",{className:Pe("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",E?"right-7":"right-0.5"),children:[E&&p&&!w&&j?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),j()},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",g?"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":T("sessions.sidebar.project.actions.newWorktree"),children:s.jsx(A,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:T("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,w?null:s.jsxs(tn,{open:le,onOpenChange:z,children:[s.jsx(Zs,{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",le?"opacity-100 pointer-events-auto":g?"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":T("sessions.sidebar.project.actions.projectMenu"),onPointerDown:Se,onMouseDown:Be,onClick:me,children:s.jsx(A,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(en,{align:"end",className:"min-w-[180px]",children:q(ms)})]})]}),E&&C?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),C()},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",g?"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":T(p?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession"),children:s.jsx(A,{name:"add",className:"h-4 w-4"})})}),s.jsx(Dt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:T(p?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(_c,{className:"min-w-[180px]",children:q($c)})]})]}),e[24]=g,e[25]=L,e[26]=W,e[27]=z,e[28]=Ee,e[29]=w,e[30]=B,e[31]=he,e[32]=n,e[33]=u,e[34]=m,e[35]=ve,e[36]=x,e[37]=le,e[38]=p,e[39]=b,e[40]=M,e[41]=C,e[42]=j,e[43]=a,e[44]=f,e[45]=d,e[46]=we,e[47]=o,e[48]=q,e[49]=k,e[50]=E,e[51]=T,e[52]=ue):ue=e[52];let De;return e[53]!==y||e[54]!==ee||e[55]!==oe||e[56]!==ye||e[57]!==ue?(De=s.jsxs("div",{ref:ee,style:oe,className:ye,children:[ue,y]}),e[53]=y,e[54]=ee,e[55]=oe,e[56]=ye,e[57]=ue,e[58]=De):De=e[58],De},gN=t=>{const e=ht.c(21),{id:n,disabled:r,children:o}=t,a=r===void 0?!1:r;let c;e[0]!==a||e[1]!==n?(c={id:n,disabled:a},e[0]=a,e[1]=n,e[2]=c):c=e[2];const{listeners:l,setNodeRef:d,setActivatorNodeRef:f,transform:m,transition:u,isDragging:p}=xc(c);let x;e[3]!==l||e[4]!==f?(x={listeners:l,setActivatorNodeRef:f},e[3]=l,e[4]=f,e[5]=x):x=e[5];const b=x;let w;e[6]!==m?(w=bc.Transform.toString(m),e[6]=m,e[7]=w):w=e[7];let g;e[8]!==w||e[9]!==u?(g={transform:w,transition:u},e[8]=w,e[9]=u,e[10]=g):g=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 j;e[13]!==o||e[14]!==b?(j=typeof o=="function"?o(b):o,e[13]=o,e[14]=b,e[15]=j):j=e[15];let S;return e[16]!==d||e[17]!==g||e[18]!==C||e[19]!==j?(S=s.jsx("div",{ref:d,style:g,className:C,children:j}),e[16]=d,e[17]=g,e[18]=C,e[19]=j,e[20]=S):S=e[20],S},xN=i.memo(gN);function bN(t){t.stopPropagation()}function wN(t){t.stopPropagation()}function yN(t){t.stopPropagation()}function vN(t){const{t:e}=yt(),n=ja(Ao(Sa,{activationConstraint:{distance:8}}),Ao(lp,{coordinateGetter:ap})),r=ja(Ao(Sa,{activationConstraint:{distance:8}})),o=i.useRef(null),a=i.useRef(new Map),c=i.useRef(t.getOrderedGroups);c.current!==t.getOrderedGroups&&(c.current=t.getOrderedGroups,a.current.clear());const l=(d,f)=>{const m=a.current,u=m.get(d);if(u&&u.groups===f)return u.ordered;const p=t.getOrderedGroups(d,f);if(m.set(d,{groups:f,ordered:p}),m.size>256){const x=m.keys().next().value;x!==void 0&&m.delete(x)}return p};return t.sharedSessionsOnly?s.jsxs(On,{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(On,{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(On,{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(On,{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 f=d.groups.find(p=>p.isMain&&p.sessions.length>0)??d.groups.find(p=>p.sessions.length>0)??d.groups.find(p=>p.isMain)??d.groups[0];if(!f)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")});const m=d.groups.find(p=>p.isArchivedBucket);return[f,...m&&m.id!==f.id?[m]:[]].map(p=>{const x=`${d.project.id}:${p.id}`,b=p.id===f.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(p,x,d.project.id,b,null,!0,o)},x)})})()}):s.jsx(s.Fragment,{children:s.jsxs(Na,{sensors:n,collisionDetection:ka,onDragEnd:d=>{if(t.isInlineEditing||t.projectSortOrder!=="manual")return;const{active:f,over:m}=d;if(!m||f.id===m.id)return;const u=t.sectionsForRender.findIndex(x=>x.project.id===f.id),p=t.sectionsForRender.findIndex(x=>x.project.id===m.id);u===-1||p===-1||u===p||t.reorderProjects(u,p)},children:[s.jsx(Hl,{items:t.sectionsForRender.map(d=>d.project.id),strategy:Gl,children:t.sectionsForRender.map(d=>{const f=d.project,m=f.id,u=Vm(f.label?.trim()||fo(f.normalizedPath,t.homeDirectory)||f.normalizedPath),p=Pa(f.normalizedPath,t.homeDirectory),x=t.collapsedProjects.has(m),b=m===t.activeProjectId,w=t.projectRepoStatus.get(m),g=l(m,d.groups),h=g.find(j=>j.isMain)??null,C=h?g.filter(j=>j.id!==h.id):g;return s.jsx(pN,{id:m,disabled:t.projectSortOrder!=="manual",projectLabel:u,projectDescription:p,projectIcon:f.icon,projectColor:f.color,projectIconImage:f.iconImage,projectIconBackground:f.iconBackground,isCollapsed:x,isActiveProject:b,isRepo:!!w,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(m),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,alwaysShowActions:t.alwaysShowActions,onToggle:()=>t.toggleProject(m),onNewSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:f.normalizedPath})},onNewWorktreeSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.openNewWorktreeDialog()},onRenameStart:()=>t.openProjectEditDialog(m),onClose:()=>t.removeProject(m),sentinelRef:j=>{t.projectHeaderSentinelRefs.current.set(m,j)},showCreateButtons:!0,openSidebarMenuKey:t.openSidebarMenuKey,setOpenSidebarMenuKey:t.setOpenSidebarMenuKey,children:x?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:d.groups.length>0?s.jsxs(Na,{sensors:r,collisionDetection:ka,onDragEnd:j=>{if(t.isInlineEditing)return;const{active:S,over:N}=j;if(!N||S.id===N.id)return;const k=C.findIndex(v=>v.id===S.id),y=C.findIndex(v=>v.id===N.id);if(k===-1||y===-1||k===y)return;const D=Gf(C,k,y).map(v=>v.id),V=h?[h.id,...D]:D;t.setGroupOrderByProject(v=>{const O=new Map(v);return O.set(m,V),O})},children:[h?t.renderGroupSessions(h,`${m}:${h.id}`,m,!0,null,void 0,o):null,s.jsx(Hl,{items:C.map(j=>j.id),strategy:Gl,children:C.map(j=>{const S=`${m}:${j.id}`;return s.jsx(xN,{id:j.id,disabled:t.isInlineEditing,children:N=>t.renderGroupSessions(j,S,m,!1,N,void 0,o)},j.id)})}),s.jsx(ql,{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(ql,{dropAnimation:null})]})})]})}function jN(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(so(),{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 SN(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 NN(t){const e=t.info.role==="user"?"User":"Assistant",n=jN(t.info.time?.created),r=SN(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
193
+
194
+ *${o}*`:`**${e}**`}function kN(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function Th(t){const e=NN(t),n=kN(t.parts).trim();return n?`${e}
195
+
196
+ ${n}`:""}function Ph(t,e){const n="#".repeat(Math.min(e+1,6)),r=t.agent?` — ${t.agent}`:"",o=`${n} Sub-agent: ${t.title}${r}
197
+
198
+ ---
199
+
200
+ `,a=t.records.map(Th).filter(Boolean).join(`
201
+
202
+ ---
203
+
204
+ `),c=[o+a];for(const l of t.children)c.push(Ph(l,e+1));return c.join(`
205
+
206
+ ---
207
+
208
+ `)}function CN(t,e,n){const r=e?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
209
+
210
+ *Exported on ${o}*
211
+
212
+ ---
213
+
214
+ `,c=t.map(Th).filter(Boolean).join(`
215
+
216
+ ---
217
+
218
+ `);let l=a+c;if(n&&n.length>0){const d=n.map(f=>Ph(f,1)).join(`
219
+
220
+ ---
221
+
222
+ `);l+=`
223
+
224
+ ---
225
+
226
+ `+d}return l}function AN(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 DN(t,e){const n=await Cp(e,t);if(n)return n;if(!_r())return null;try{const r=await zo()?.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 TN(t){const e=zo()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await Ap(t)?!0:Ca(t)}function PN(){return Rc()}function IN(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 RN=(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},Hn=co()((t,e)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{e().enabled||t({enabled:!0})},disable:()=>{t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{e().enabled?t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):t({enabled:!0})},toggleSelected:(n,r,o)=>{const a=e(),c=new Set(a.selectedIds);let l=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(c.clear(),l=r,d=null):l===null&&r!==null&&(l=r);const m=o&&o.length>0?[n,...o]:[n];if(c.has(n)){for(const p of m)c.delete(p);d===n&&(d=null)}else{for(const p of m)c.add(p);d=n}c.size===0?t({selectedIds:c,scopeKey:null,anchorId:null}):t({selectedIds:c,scopeKey:l,anchorId:d})},setRange:(n,r,o,a,c)=>{const l=e();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],f=o.indexOf(d),m=o.indexOf(r);if(f<0||m<0)return;const[u,p]=f<=m?[f,m]:[m,f],x=o.slice(u,p+1),b=RN(x,c),g=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const h of b)g.add(h);t({selectedIds:g,scopeKey:a??l.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){t({selectedIds:new Set,scopeKey:null,anchorId:null});return}t({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{t({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=e();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?t({selectedIds:o,scopeKey:null,anchorId:null}):t({selectedIds:o}))}}));let fc=!1;const mc=new Set;let kf=!1;function EN(){for(const t of mc)t()}function sd(t){fc!==t&&(fc=t,EN())}function MN(t){t.key==="Shift"&&sd(!0)}function FN(t){t.key==="Shift"&&sd(!1)}function ON(){sd(!1)}function LN(){kf||typeof window>"u"||(kf=!0,window.addEventListener("keydown",MN),window.addEventListener("keyup",FN),window.addEventListener("blur",ON))}function BN(t){return LN(),mc.add(t),()=>{mc.delete(t)}}function VN(){return fc}function _N(){return!1}function $N(){return nt.useSyncExternalStore(BN,VN,_N)}const zN=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,Ih=/^g[1-9]\d*$/,No=(t,e,n,r,o)=>{if(!zN.test(t)||e!==void 0&&!Ih.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}},ya=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 No(n,void 0,e[1],e[2],void 0);if(e.length===4){const[,l,d,f]=e;return Ih.test(l)?No(n,l,d,f,void 0):No(n,void 0,l,d,f)}const[,r,o,a,c]=e;return r===""?No(n,void 0,o,a,c):No(n,r,o,a,c)},WN=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("/")},UN=(t,e,n,r)=>{const o=[t];return r&&o.push(r),o.push(e,n,"fusion"),o.join("/")},Rh=t=>{const e=ht.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=yt(),f=is(HN),m=is(GN),u=is(KN);let p;e[0]!==f?(p=f(),e[0]=f,e[1]=p):p=e[1];const x=p;let b;e[2]!==x?(b=x.filter(qN),e[2]=x,e[3]=b):b=e[3];const w=b;let g,h;e[4]!==x.length||e[5]!==m?(g=()=>{x.length===0&&m()},h=[x.length,m],e[4]=x.length,e[5]=m,e[6]=g,e[7]=h):(g=e[6],h=e[7]),i.useEffect(g,h);let C,j;e[8]!==u||e[9]!==a||e[10]!==r||e[11]!==w||e[12]!==n?(C=()=>{if(a)return;const P=n.trim();if(P.length>0&&w.some(T=>T.name===P))return;const E=typeof u=="string"&&u.trim().length>0?u.trim():null;if(E&&w.some(T=>T.name===E)){r(E);return}const B=w[0]?.name;B&&r(B)},j=[u,a,r,w,n],e[8]=u,e[9]=a,e[10]=r,e[11]=w,e[12]=n,e[13]=C,e[14]=j):(C=e[13],j=e[14]),i.useEffect(C,j);const S=n.trim().length>0?n:void 0;let N;e[15]!==o?(N=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]=N):N=e[16];let k;e[17]!==d?(k=d("multirun.agentSelector.placeholder"),e[17]=d,e[18]=k):k=e[18];let y;e[19]!==k?(y=s.jsx(Dn,{placeholder:k}),e[19]=k,e[20]=y):y=e[20];let D;e[21]!==c||e[22]!==N||e[23]!==y?(D=s.jsx(Kn,{id:c,size:"lg",className:N,children:y}),e[21]=c,e[22]=N,e[23]=y,e[24]=D):D=e[24];let V;e[25]!==w?(V=w.length>0&&s.jsx(Ql,{children:w.map(YN)}),e[25]=w,e[26]=V):V=e[26];let v;e[27]!==l||e[28]!==V?(v=s.jsx(qn,{fitContent:!0,portalToBody:l,children:V}),e[27]=l,e[28]=V,e[29]=v):v=e[29];let O;return e[30]!==a||e[31]!==r||e[32]!==S||e[33]!==D||e[34]!==v?(O=s.jsxs(Gn,{value:S,onValueChange:r,disabled:a,children:[D,v]}),e[30]=a,e[31]=r,e[32]=S,e[33]=D,e[34]=v,e[35]=O):O=e[35],O};function HN(t){return t.getVisibleAgents}function GN(t){return t.loadAgents}function KN(t){return t.currentAgentName}function qN(t){return Ac(t.mode)}function YN(t){return s.jsx(Bs,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const Eh="h-7",Fo=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,QN=t=>{const e=ht.c(12),{model:n,instanceIndex:r,totalSameModel:o,onRemove:a}=t,c=n.displayName||`${n.providerID}/${n.modelID}`,l=o>1?`${c} (${r})`:c;let d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=Pe("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",Eh),e[0]=d):d=e[0];let f;e[1]!==n.providerID?(f=s.jsx(Oo,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=f):f=e[2];let m;e[3]!==l?(m=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=m):m=e[4];let u;e[5]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(A,{name:"close",className:"h-3.5 w-3.5"}),e[5]=u):u=e[5];let p;e[6]!==a?(p=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:u}),e[6]=a,e[7]=p):p=e[7];let x;return e[8]!==f||e[9]!==m||e[10]!==p?(x=s.jsxs("div",{className:d,children:[f,m,p]}),e[8]=f,e[9]=m,e[10]=p,e[11]=x):x=e[11],x},Mh=t=>{const e=ht.c(119),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:f,addButtonClassName:m,dropdownSide:u,dropdownClassName:p,containerClassName:x,triggerIcon:b}=t,w=d===void 0?!0:d,g=u===void 0?"top":u,{t:h}=yt(),C=is(JN),j=is(XN),S=Re(ZN),N=Re(ek),{favoriteModelsList:k,recentModelsList:y}=$g(),D=Re(tk),V=Re(sk),[v,O]=i.useState(!1),[P,E]=i.useState(""),[B,T]=i.useState(null),W=i.useRef(null),U=i.useRef(null),L=f===1,M=f===void 0||n.length<f||L;let ee;if(e[0]!==n){ee=new Map;for(const se of n){const Oe=`${se.providerID}:${se.modelID}`;ee.set(Oe,(ee.get(Oe)||0)+1)}e[0]=n,e[1]=ee}else ee=e[1];const ie=ee;let X;e[2]!==n?(X=se=>n.filter(ce=>ce.providerID===se.providerID&&ce.modelID===se.modelID).findIndex(ce=>ce.instanceId===se.instanceId)+1,e[2]=n,e[3]=X):X=e[3];const H=X;let te,re;e[4]!==g||e[5]!==v?(te=()=>{if(!v||!U.current)return;const se=U.current.getBoundingClientRect();if(g==="bottom"){const tt=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-se.bottom-16-112;T(Math.max(160,Math.min(320,tt)));return}let Oe=U.current.parentElement;for(;Oe&&!(Oe.getAttribute("role")==="dialog"||Oe.hasAttribute("data-scroll-shadow"));){const qe=getComputedStyle(Oe);if(qe.overflow==="auto"||qe.overflow==="hidden"||qe.overflowY==="auto"||qe.overflowY==="hidden")break;Oe=Oe.parentElement}const ce=Oe?Oe.getBoundingClientRect().top:0,Ue=se.top-ce-16;T(Math.max(150,Math.min(300,Ue)))},re=[g,v],e[4]=g,e[5]=v,e[6]=te,e[7]=re):(te=e[6],re=e[7]),i.useEffect(te,re);let le,ve;e[8]!==M||e[9]!==v?(le=()=>{!M&&v&&(O(!1),E(""))},ve=[M,v],e[8]=M,e[9]=v,e[10]=le,e[11]=ve):(le=e[10],ve=e[11]),i.useEffect(le,ve);let ne,we;e[12]!==v?(ne=()=>{if(!v)return;const se=Oe=>{W.current&&!W.current.contains(Oe.target)&&(O(!1),E(""))};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},we=[v],e[12]=v,e[13]=ne,e[14]=we):(ne=e[13],we=e[14]),i.useEffect(ne,we);let he;e[15]!==L||e[16]!==r||e[17]!==a||e[18]!==n.length?(he=se=>{const Oe={providerID:se.providerID,modelID:se.modelID,displayName:se.model.name||se.modelID,instanceId:Fo()};L&&n.length>0&&a?a(0,Oe):r(Oe),L&&(O(!1),E(""))},e[15]=L,e[16]=r,e[17]=a,e[18]=n.length,e[19]=he):he=e[19];const Me=he;let z;e[20]!==h?(z=h("multirun.modelMultiSelect.search.placeholder"),e[20]=h,e[21]=z):z=e[21];let K;e[22]!==h?(K=h("multirun.modelMultiSelect.search.noResults"),e[22]=h,e[23]=K):K=e[23];let q;e[24]!==h?(q=h("multirun.modelMultiSelect.sections.favorites"),e[24]=h,e[25]=q):q=e[25];let me;e[26]!==h?(me=h("multirun.modelMultiSelect.sections.recent"),e[26]=h,e[27]=me):me=e[27];let Se;e[28]!==h?(Se=h("multirun.modelMultiSelect.keyboard.hint"),e[28]=h,e[29]=Se):Se=e[29];let Be;e[30]!==h?(Be=h("settings.agents.modelSelector.actions.favorite"),e[30]=h,e[31]=Be):Be=e[31];let _e;e[32]!==h?(_e=h("settings.agents.modelSelector.actions.unfavorite"),e[32]=h,e[33]=_e):_e=e[33];let Le;e[34]!==h?(Le=h("chat.modelControls.capabilities"),e[34]=h,e[35]=Le):Le=e[35];let pe;e[36]!==h?(pe=h("chat.modelControls.capability.toolCalling"),e[36]=h,e[37]=pe):pe=e[37];let Ee;e[38]!==h?(Ee=h("chat.modelControls.capability.reasoning"),e[38]=h,e[39]=Ee):Ee=e[39];let ge;e[40]!==h?(ge=h("chat.modelControls.input"),e[40]=h,e[41]=ge):ge=e[41];let oe;e[42]!==h?(oe=h("chat.modelControls.output"),e[42]=h,e[43]=oe):oe=e[43];let je;e[44]!==h?(je=h("chat.modelControls.costPerMillion"),e[44]=h,e[45]=je):je=e[45];let ye;e[46]!==z||e[47]!==K||e[48]!==q||e[49]!==me||e[50]!==Se||e[51]!==Be||e[52]!==_e||e[53]!==Le||e[54]!==pe||e[55]!==Ee||e[56]!==ge||e[57]!==oe||e[58]!==je?(ye={searchPlaceholder:z,noResults:K,favorites:q,recent:me,keyboardHint:Se,favorite:Be,unfavorite:_e,capabilities:Le,capabilityToolCalling:pe,capabilityReasoning:Ee,input:ge,output:oe,costPerMillion:je},e[46]=z,e[47]=K,e[48]=q,e[49]=me,e[50]=Se,e[51]=Be,e[52]=_e,e[53]=Le,e[54]=pe,e[55]=Ee,e[56]=ge,e[57]=oe,e[58]=je,e[59]=ye):ye=e[59];const ue=ye;let De;e[60]!==x?(De=Pe("relative",x),e[60]=x,e[61]=De):De=e[61];let I;e[62]!==m?(I=Pe(Eh,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",m),e[62]=m,e[63]=I):I=e[63];const _=!M;let be;e[64]!==v?(be=()=>{O(!v)},e[64]=v,e[65]=be):be=e[65];let R;e[66]!==b?(R=b??s.jsx(A,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=b,e[67]=R):R=e[67];let de;e[68]!==l||e[69]!==h?(de=l??h("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=h,e[70]=de):de=e[70];let fe;e[71]!==I||e[72]!==_||e[73]!==be||e[74]!==R||e[75]!==de?(fe=s.jsxs(ze,{ref:U,type:"button",variant:"outline",size:"sm",className:I,disabled:_,onClick:be,children:[R,de]}),e[71]=I,e[72]=_,e[73]=be,e[74]=R,e[75]=de,e[76]=fe):fe=e[76];let $;e[77]!==B||e[78]!==M||e[79]!==p||e[80]!==g||e[81]!==k||e[82]!==Me||e[83]!==D||e[84]!==N||e[85]!==v||e[86]!==ue||e[87]!==ie||e[88]!==j||e[89]!==V||e[90]!==C||e[91]!==y||e[92]!==P||e[93]!==S?($=v?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",g==="top"?"bottom-full mb-1":"top-full mt-1",p),style:{background:"linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))"},children:s.jsx(zg,{providers:C,providerOrder:V,favoriteModels:k,recentModels:y,modelsMetadata:j,hiddenModels:D,searchQuery:P,onSearchQueryChange:E,onSelect:Me,labels:ue,selectionCount:se=>ie.get(`${se.providerID}:${se.modelID}`)||0,disabled:!M,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:B?`${B}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:v,isFavorite:se=>N(se.providerID,se.modelID),onToggleFavorite:se=>S(se.providerID,se.modelID),onEscape:()=>{O(!1),E("")}})}):null,e[77]=B,e[78]=M,e[79]=p,e[80]=g,e[81]=k,e[82]=Me,e[83]=D,e[84]=N,e[85]=v,e[86]=ue,e[87]=ie,e[88]=j,e[89]=V,e[90]=C,e[91]=y,e[92]=P,e[93]=S,e[94]=$):$=e[94];let Ae;e[95]!==De||e[96]!==fe||e[97]!==$?(Ae=s.jsxs("div",{className:De,ref:W,children:[fe,$]}),e[95]=De,e[96]=fe,e[97]=$,e[98]=Ae):Ae=e[98];let Ve;e[99]!==H||e[100]!==ie||e[101]!==o||e[102]!==a||e[103]!==C||e[104]!==n||e[105]!==w||e[106]!==h?(Ve=w&&n.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:n.map((se,Oe)=>{const ce=`${se.providerID}:${se.modelID}`,Ue=ie.get(ce)||1,qe=H(se),tt=C.find(Tt=>Tt.id===se.providerID)?.models?.find(Tt=>Tt.id===se.modelID),xt=tt?.variants?Object.keys(tt.variants):[],vt=xt.length>0,Mt=se.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(QN,{model:se,instanceIndex:qe,totalSameModel:Ue,onRemove:()=>o(Oe)}),vt&&s.jsxs(Gn,{value:Mt,onValueChange:Tt=>{if(!a)return;a(Oe,{...se,variant:Tt==="__default__"?void 0:Tt})},children:[s.jsxs(Kn,{size:"chip",className:"px-2 gap-1.5 rounded-md !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground",children:[s.jsx(A,{name:"brain-ai-3",className:Pe("h-3.5 w-3.5 flex-shrink-0",Mt==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(Dn,{placeholder:h("multirun.modelMultiSelect.variant.placeholder"),children:Tt=>Tt==="__default__"?h("multirun.modelMultiSelect.variant.default"):Tt})]}),s.jsxs(qn,{fitContent:!0,children:[s.jsx(Bs,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:h("multirun.modelMultiSelect.variant.default")}),xt.map(nk)]})]})]},se.instanceId)})}),e[99]=H,e[100]=ie,e[101]=o,e[102]=a,e[103]=C,e[104]=n,e[105]=w,e[106]=h,e[107]=Ve):Ve=e[107];let Ne;e[108]!==Ae||e[109]!==Ve?(Ne=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[Ae,Ve]}),e[108]=Ae,e[109]=Ve,e[110]=Ne):Ne=e[110];let Y;e[111]!==f||e[112]!==c||e[113]!==n.length||e[114]!==h?(Y=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:f!==void 0?h("multirun.modelMultiSelect.validation.minToMax",{min:c,max:f}):h("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[111]=f,e[112]=c,e[113]=n.length,e[114]=h,e[115]=Y):Y=e[115];let F;return e[116]!==Ne||e[117]!==Y?(F=s.jsxs("div",{className:"space-y-2",children:[Ne,Y]}),e[116]=Ne,e[117]=Y,e[118]=F):F=e[118],F};function JN(t){return t.providers}function XN(t){return t.modelsMetadata}function ZN(t){return t.toggleFavoriteModel}function ek(t){return t.isFavoriteModel}function tk(t){return t.hiddenModels}function sk(t){return t.providerOrder}function nk(t){return s.jsx(Bs,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const rk=(t,e,n)=>{const r=t.session.title?.trim()||t.session.id;return`
227
+
228
+ --- RESULT ${n+1}: ${r} ---
229
+ ${e.trim()}
230
+ --- END RESULT ${n+1} ---`},Cf=(t,e)=>mt.getState().getWorktreeMetadata(t)?.projectDirectory??e,ik=async t=>{const e=t.directory??void 0,n=Wg(t.session.id,e);if(n.length===0&&t.directory){const o=(await Xn.withDirectory(t.directory,()=>Xn.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 Hd(c.parts??[]).trim()}return""}for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o.role==="assistant")return Hd(Ug(o.id,e)).trim()}return""};function ok({session:t,open:e,onOpenChange:n}){const{t:r}=yt(),o=Nc(),a=pr(L=>L.activeSessions),c=pr(L=>L.archivedSessions),l=is(L=>L.providers),d=is(L=>L.currentProviderId),f=is(L=>L.currentModelId),m=is(L=>L.currentAgentName),[u,p]=i.useState(d??""),[x,b]=i.useState(f??""),[w,g]=i.useState(()=>d&&f?[{providerID:d,modelID:f,instanceId:Fo()}]:[]),[h,C]=i.useState(""),[j,S]=i.useState(m??""),[N,k]=i.useState([]),[y,D]=i.useState(!1),V=i.useMemo(()=>ya(t.title),[t.title]),v=i.useMemo(()=>{const L=new Map;for(const M of o)L.set(M.id,M);for(const M of a)L.set(M.id,M);for(const M of c)L.set(M.id,M);return t.id&&L.set(t.id,t),Array.from(L.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!V)return;const L=mt.getState().getDirectoryForSession(t.id),M=Cf(t.id,L),ee=v.map(ie=>{const X=ya(ie.title);if(!X||X.groupSlug!==V.groupSlug||X.fusion||(X.runGroup??null)!==(V.runGroup??null))return null;const H=mt.getState().getDirectoryForSession(ie.id)??Br(ie),te=Cf(ie.id,H);return M&&te&&M!==te?null:{session:ie,directory:H,projectDirectory:te}}).filter(ie=>ie!==null).sort((ie,X)=>(ie.session.time?.created??0)-(X.session.time?.created??0));k(ee)},[v,e,V,t.id]);const P=l.find(L=>L.id===u)?.models.find(L=>L.id===x),E=P?.variants?Object.keys(P.variants):[],B=!!(V&&u&&x&&N.length>0&&!y),T=i.useCallback(L=>{g([L]),p(L.providerID),b(L.modelID),C("")},[]),W=w[0]?.displayName||w[0]?.modelID||r("multirun.fusion.model.placeholder"),U=async()=>{if(!(!V||!u||!x)){D(!0);try{const L=await Promise.all(N.map(re=>ik(re))),M=N.map((re,le)=>({source:re,text:L[le]??""})).filter(re=>re.text.trim().length>0);if(M.length===0){ae.error(r("multirun.fusion.toast.noOutputs"));return}const ee=N[0]?.projectDirectory??N[0]?.directory??null,ie=UN(V.groupSlug,u,x,V.runGroup),[X,H]=await Promise.all([Fn("session.fusion.visible"),Fn("session.fusion.instructions")]),te=await mt.getState().createSession(ie,ee,null);if(!te)throw new Error("Failed to create fusion session");mt.getState().setCurrentSession(te.id,ee),n(!1),await Xn.sendMessage({id:te.id,providerID:u,modelID:x,variant:h||void 0,agent:j||void 0,text:X,additionalParts:[{text:H,synthetic:!0},...M.map((re,le)=>({text:rk(re.source,re.text,le),synthetic:!0})),{text:`
231
+
232
+ --- FUSION INPUTS END ---
233
+ Now write the final fused answer.`,synthetic:!0}],directory:ee??Xn.getDirectory()})}catch(L){console.error("[MultiRunFusion] Failed to start fusion",L),ae.error(r("multirun.fusion.toast.failed"))}finally{D(!1)}}};return s.jsx(_s,{open:e,onOpenChange:n,children:s.jsxs(Vs,{className:"max-w-xl overflow-visible",children:[s.jsxs(sn,{children:[s.jsx(Hs,{children:r("multirun.fusion.title")}),s.jsx(mn,{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(Mh,{selectedModels:w,onAdd:T,onUpdate:(L,M)=>T(M),onRemove:()=>{g([]),p(""),b(""),C("")},maxModels:1,addButtonLabel:W,showChips:!1,addButtonClassName:"h-8 w-fit max-w-[min(28rem,calc(100vw-8rem))] justify-start rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5",dropdownSide:"bottom",dropdownClassName:"w-[min(28rem,calc(100vw-8rem))]",triggerIcon:u?s.jsx(Oo,{providerId:u,className:"h-3.5 w-3.5 mr-1"}):void 0})}),E.length>0?s.jsxs(Gn,{value:h||"__default__",onValueChange:L=>C(L==="__default__"?"":L),children:[s.jsxs(Kn,{size:"lg",className:"h-8 w-fit rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground px-3 py-1.5",children:[s.jsx(A,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(Dn,{children:L=>L==="__default__"?r("multirun.modelMultiSelect.variant.default"):L})]}),s.jsxs(qn,{fitContent:!0,portalToBody:!0,children:[s.jsx(Bs,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),E.map(L=>s.jsx(Bs,{value:L,children:L},L))]})]}):null,s.jsx(Rh,{value:j,onChange:S,portalToBody:!0,className:"h-8 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta font-medium text-foreground",children:r("multirun.fusion.sources.label",{count:N.length})}),s.jsx("div",{className:"max-h-56 space-y-1 overflow-auto rounded-lg border border-[var(--interactive-border)] p-1",children:N.map(L=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(Oo,{providerId:ya(L.session.title)?.providerID??"",className:"h-4 w-4"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:L.session.title||L.session.id}),s.jsx("button",{type:"button",onClick:()=>k(M=>M.filter(ee=>ee.session.id!==L.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(A,{name:"close",className:"h-4 w-4"})})]},L.session.id))})]}),s.jsxs(br,{children:[s.jsx(ze,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx(ze,{onClick:U,disabled:!B,children:r(y?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function ak(t){const e=ht.c(7);let n,r,o,a,c;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("path",{d:"M12 4.5v6.25M12 10.75v3.5M12 10.75H7.25A3.25 3.25 0 0 0 4 14v1.25M12 10.75h4.75A3.25 3.25 0 0 1 20 14v1.25",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),r=s.jsx("path",{d:"M9.25 7.25 12 4.5l2.75 2.75",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),o=s.jsx("circle",{cx:"4",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),a=s.jsx("circle",{cx:"12",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),c=s.jsx("circle",{cx:"20",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),e[0]=n,e[1]=r,e[2]=o,e[3]=a,e[4]=c):(n=e[0],r=e[1],o=e[2],a=e[3],c=e[4]);let l;return e[5]!==t?(l=s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",...t,children:[n,r,o,a,c]}),e[5]=t,e[6]=l):l=e[6],l}const lk=i.memo(function(e){const n=ht.c(22),{archiveLabel:r,deleteLabel:o,buttonSizeClass:a,iconSizeClass:c,onPointerDown:l,onMouseDown:d,onArchive:f,onDelete:m}=e,u=$N(),p=u?o:r;let x;n[0]!==f||n[1]!==m||n[2]!==u?(x=k=>{if(u||k.shiftKey){m(k);return}f(k)},n[0]=f,n[1]=m,n[2]=u,n[3]=x):x=n[3];const b=x,w=u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground";let g;n[4]!==a||n[5]!==w?(g=Pe("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",w,a),n[4]=a,n[5]=w,n[6]=g):g=n[6];const h=u?"delete-bin":"archive";let C;n[7]!==c||n[8]!==h?(C=s.jsx(A,{name:h,className:c}),n[7]=c,n[8]=h,n[9]=C):C=n[9];let j;n[10]!==b||n[11]!==p||n[12]!==d||n[13]!==l||n[14]!==g||n[15]!==C?(j=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",className:g,"aria-label":p,onPointerDown:l,onMouseDown:d,onClick:b,onKeyDown:pk,children:C})}),n[10]=b,n[11]=p,n[12]=d,n[13]=l,n[14]=g,n[15]=C,n[16]=j):j=n[16];let S;n[17]!==p?(S=s.jsx(Dt,{side:"left",sideOffset:8,children:p}),n[17]=p,n[18]=S):S=n[18];let N;return n[19]!==j||n[20]!==S?(N=s.jsxs(Ct,{children:[j,S]}),n[19]=j,n[20]=S,n[21]=N):N=n[21],N});function ck(t){const{t:e}=yt(),{node:n,depth:r=0,groupDirectory:o,projectId:a,archivedBucket:c=!1,currentSessionId:l,pinnedSessionIds:d,expandedParents:f,hasSessionSearchQuery:m,normalizedSessionSearchQuery:u,notifyOnSubtasks:p,editingId:x,setEditingId:b,editTitle:w,setEditTitle:g,handleSaveEdit:h,handleCancelEdit:C,toggleParent:j,handleSessionSelect:S,handleSessionDoubleClick:N,togglePinnedSession:k,handleShareSession:y,copiedSessionId:D,handleCopyShareUrl:V,handleUnshareSession:v,openSidebarMenuKey:O,setOpenSidebarMenuKey:P,renamingFolderId:E,getFoldersForScope:B,getSessionFolderId:T,removeSessionFromFolder:W,addSessionToFolder:U,createFolderAndStartRename:L,openContextPanelTab:M,handleDeleteSession:ee,mobileVariant:ie,alwaysShowActions:X,renderSessionNode:H,secondaryMeta:te,renderContext:re="project",subtreeContainsActive:le,subtreeContainsEditing:ve,menuOpenSessionId:ne,childRenderExtrasFor:we,liveSessionById:he}=t,Me=!!te?.projectLabel,z=!!te?.branchLabel,K=ar(Ge=>Ge.displayMode),q=i.useMemo(()=>_r(),[]),me=K==="minimal"||q,Se=i.useMemo(()=>Wa(),[]),Be=i.useContext(Hg),_e=q?"group-hover:opacity-100 group-hover:pointer-events-auto":"group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto",Le=q?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",pe=q,Ee=!c&&!ie,ge=me?q?Ee&&pe?"group-hover:pr-18":Ee||pe?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":q?Ee&&pe?"group-hover:pr-18":Ee||pe?"group-hover:pr-12":"group-hover:pr-5":Ee?"group-hover:pr-12 group-focus-within:pr-12":"group-hover:pr-5 group-focus-within:pr-5",oe=Ee?"pr-13":"pr-7",je=i.useRef(!1),[ye,ue]=i.useState(!1),De=i.useRef(x);De.current=x;const I=i.useRef(null),_=i.useRef(h);_.current=h;const[be,R]=i.useState(w),de=i.useRef(be);de.current=be;const fe=i.useRef(null),$=i.useRef(null),Ae=n.session,Ve=he.get(Ae.id)??Ae,Ne=ds(Ae.directory??null)??ds(o??null),Y=gm(Ne??void 0,{bootstrap:!c}),F=Vc(),se=Hn(Ge=>Ge.enabled),Oe=Hn(i.useCallback(Ge=>Ge.selectedIds.has(Ae.id),[Ae.id])),ce=Hn(Ge=>Ge.toggleSelected),Ue=Hn(Ge=>Ge.setRange),qe=i.useCallback(Ge=>{const ps=[],ks=zs=>{zs.children.forEach(Rs=>{ps.push(Rs.session.id),ks(Rs)})};return ks(Ge),ps},[]),[Ye,tt]=i.useState(!1),[xt,vt]=i.useState(!0),Mt=`${re}:${c?"archived":"active"}:${Ae.id}`,Tt=Sm(i.useCallback(Ge=>!!Ge.sessionMemoryState.get(Gg(Ae.id))?.isZombie,[Ae.id])),Kt=Kg(Ae.id),Ut=qg(Ae.id,Ne??void 0),Zt=Yg(Ve),ns=Zt?s.jsx("span",{className:"inline-flex flex-shrink-0 items-center",title:e(Gd[Zt.status]),"aria-label":e(Gd[Zt.status]),children:s.jsx(A,{name:"target",className:"h-3 w-3",style:{color:Qg[Zt.status]}})}):null,es=l===Ae.id,Ce=Ve.title||e("sessions.sidebar.session.untitled"),Qe=n.children.length>0,ot=d.has(Ae.id),bt=Mt,Je=m?!0:f.has(bt),Pt=!!Ve.parentID,Ke=Jg(Ae.id)>0&&(!Pt||p),Ze=Ve.time?.updated||Ve.time?.created||Date.now(),Bt=Cb(Ze),Rt=Ab(Ze),Ot=O===Mt,[rs,Wt]=i.useState(!1),Et=Ot||rs,qt=i.useMemo(()=>ya(Ve.title)!==null,[Ve.title]),[hs,ts]=i.useState(!1),as=q&&re==="recent"&&!me,gs=q&&re==="recent"&&me,Ft=i.useMemo(()=>qe(n).length,[qe,n]),Lt=i.useCallback(async Ge=>{const ps=[];let ks=0;for(const zs of Ge)try{await F.ensureSessionRenderable(zs.session.id);const Rs=Kd(Y.getState(),zs.session.id).list,rn=zs.session.title||e("sessions.sidebar.session.export.untitledSubagent"),Ks=zs.session.agent,Is=await Lt(zs.children);ks+=Is.skipped,ps.push({title:rn,agent:Ks,records:Rs,children:Is.children})}catch{ks+=qe(zs).length+1}return{children:ps,skipped:ks}},[qe,Y,F,e]),Ht=i.useCallback(Ge=>{Ge<=0||ae.warning(Ge===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:Ge}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:Ge}))},[e]),Yt=i.useCallback(async Ge=>{if(!Ne){ae.error(e("sessions.sidebar.session.export.nothingToExport"));return}await F.ensureSessionRenderable(Ae.id);const ps=Kd(Y.getState(),Ae.id).list;if(ps.length===0){ae.error(e("sessions.sidebar.session.export.nothingToExport"));return}let ks,zs=0;if(Ge&&n.children.length>0){const Is=await Lt(n.children);ks=Is.children,zs=Is.skipped}const Rs=CN(ps,Ve.title??null,ks),rn=IN(Ve.title??null),Ks=await DN(Rs,rn);if(Ks){ae.success(e("sessions.sidebar.session.export.success"),{action:{label:e(PN()),onClick:()=>{TN(Ks).then(Is=>{Is||ae.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),Ht(zs);return}AN(Rs,rn),ae.success(e("sessions.sidebar.session.export.success")),Ht(zs)},[Lt,Y,n.children,Ve.title,Ae.id,Ne,Ht,F,e]),$t=i.useCallback(async()=>{if(n.children.length>0){vt(!0),tt(!0);return}await Yt(!1)},[Yt,n.children.length]),Fe=i.useCallback(()=>{Ne&&Zr("desktop_open_session_mini_chat_window",{sessionId:Ae.id,directory:Ne,apiBaseUrl:Xr(),clientToken:Yl()}).catch(Ge=>{console.warn("[session-sidebar] failed to open mini chat window",Ge)})},[Ae.id,Ne]);if(i.useEffect(()=>{if(x!==Ae.id)return;const Ge=ps=>{$.current&&!$.current.contains(ps.target)&&_.current(de.current)};return document.addEventListener("mousedown",Ge),()=>document.removeEventListener("mousedown",Ge)},[x,Ae.id]),i.useLayoutEffect(()=>{if(x!==Ae.id){fe.current===Ae.id&&(fe.current=null);return}fe.current!==Ae.id&&(fe.current=Ae.id,R(w))},[x,w,Ae.id]),x===Ae.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:$,className:"flex w-full items-center gap-2",onSubmit:Ge=>{Ge.preventDefault(),h(be)},children:[s.jsx("input",{value:be,onChange:Ge=>R(Ge.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:Ge=>{if(Ge.stopPropagation(),Ge.key==="Escape"){C();return}}}),s.jsx("button",{type:"submit","aria-label":e("sessions.sidebar.session.rename.save"),title:e("sessions.sidebar.session.rename.save"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(A,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:C,"aria-label":e("sessions.sidebar.session.rename.cancel"),title:e("sessions.sidebar.session.rename.cancel"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(A,{name:"close",className:"size-4"})})]}),me?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[Qe?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Je?s.jsx(A,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(A,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:Bt}),Me?s.jsx("span",{className:"truncate",children:te?.projectLabel}):null,z?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:te?.branchLabel})]}):null]})})]})},Ae.id);const st=Kt?.type??"idle",wt=st==="busy"||st==="retry",St=Ut.length,ss=wt||!wt&&Ke&&!es,cs=wt?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")}),Xt=!X&&Qe&&(ss||ot),Vt=ot&&!ss,Fs=s.jsx(A,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}),us=ss||Vt?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",me?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",Xt?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[ss?cs:null,Vt?Fs:null]}):null,$s=Qe&&!X&&(ss||ot),js=Qe?s.jsx("span",{role:"button",tabIndex:0,onClick:Ge=>{Ge.stopPropagation(),j(bt)},onKeyDown:Ge=>{(Ge.key==="Enter"||Ge.key===" ")&&(Ge.preventDefault(),Ge.stopPropagation(),j(bt))},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",as?"absolute left-1.5 bottom-1":gs?"relative mr-0.5 shrink-0":Pe("absolute left-0.5",me?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!as&&!gs&&$s?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto":""),"aria-label":e(Je?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:Je?s.jsx(A,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(A,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Cs=Tt?s.jsx(A,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,jn=Ge=>{Ge&&Wt(!1),P(Ge?Mt:null)},hn=Ge=>{if(!Ge&&I.current){const{id:ps,title:ks}=I.current;I.current=null,b(ps),g(ks)}},xe=Ge=>{Wt(Ge)},rt=Ge=>{Ge.preventDefault(),Ge.stopPropagation(),P(Ot?null:Mt)},dt=Ge=>{Ge.preventDefault(),Ge.stopPropagation()},jt=Ge=>{Ge.preventDefault(),Ge.stopPropagation()},zt=Ge=>{Ge.preventDefault(),Ge.stopPropagation()},gt=Ge=>{Ge.preventDefault(),Ge.stopPropagation()},xs=Ge=>{Ge.preventDefault(),Ge.stopPropagation(),P(null),ee(Ae,{archivedBucket:c})},bs=Ge=>{Ge.preventDefault(),Ge.stopPropagation(),P(null),ee(Ae,{archivedBucket:c,hardDelete:!0,skipConfirm:!0})},Ss=Ge=>{Ge.preventDefault(),Ge.stopPropagation()},Ns=Ge=>{Ge.preventDefault(),Ge.stopPropagation()},Os=Ge=>{Ge.preventDefault(),Ge.stopPropagation(),Be?.vscode?.executeCommand("openchamber.openSessionInEditor",Ae.id,Ce)},Tn=Ge=>{if(je.current){je.current=!1;return}if(se){if(Ge?.preventDefault(),Ge?.stopPropagation(),Ge?.shiftKey){const ks=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(rn=>rn.getAttribute("data-session-row")).filter(rn=>typeof rn=="string"&&rn.length>0),zs=Hn.getState().anchorId,Rs=new Map;Rs.set(Ae.id,qe(n)),Ue(zs,Ae.id,ks,Ne??null,Rs);return}ce(Ae.id,Ne??null,qe(n));return}S(Ae.id,Ne,a)},Gs=Ge=>{Ge.defaultPrevented||Ge.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Tn(Ge)},Pn=Ge=>{(Ge.button===2||Ge.button===0&&Ge.ctrlKey&&!se)&&(je.current=!0)},Bn=Ge=>{ie&&Ge.pointerType==="touch"&&ue(!0)},Sn=Ge=>{ie&&Ge.pointerType==="touch"&&ue(!1)},an=({Item:Ge,Separator:ps,Sub:ks,SubTrigger:zs,SubContent:Rs})=>s.jsxs(s.Fragment,{children:[s.jsxs(Ge,{onClick:()=>{I.current={id:Ae.id,title:Ce}},className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(Ge,{onClick:()=>k(Ae.id),className:"[&>svg]:mr-1",children:[ot?s.jsx(A,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(A,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(ot?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),Ve.share?s.jsxs(s.Fragment,{children:[s.jsx(Ge,{onClick:()=>{Ve.share?.url&&V(Ve.share.url,Ae.id)},className:"[&>svg]:mr-1",children:D===Ae.id?s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),e("sessions.sidebar.session.menu.copied")]}):s.jsxs(s.Fragment,{children:[s.jsx(A,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(Ge,{onClick:()=>v(Ae.id),className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.unshare")]})]}):s.jsxs(Ge,{onClick:()=>y(Ve),className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(Ge,{onClick:()=>{$t()},className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),qt?s.jsxs(Ge,{onClick:()=>ts(!0),className:"[&>svg]:mr-1",children:[s.jsx(ak,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,Ne&&!c?(()=>{const rn=B(Ne),Ks=T(Ne,Ae.id);return s.jsxs(s.Fragment,{children:[s.jsx(ps,{}),s.jsxs(ks,{children:[s.jsxs(zs,{className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs(Rs,{className:"min-w-[180px]",children:[rn.length===0?s.jsx(Ge,{disabled:!0,className:"text-muted-foreground",children:e("sessions.sidebar.folders.none")}):rn.map(Is=>s.jsxs(Ge,{onClick:()=>{Ks===Is.id?W(Ne,Ae.id):U(Ne,Is.id,Ae.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:Is.name}),Ks===Is.id?s.jsx(A,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Is.id)),s.jsx(ps,{}),s.jsxs(Ge,{onClick:()=>{const Is=L(Ne);Is&&U(Ne,Is.id,Ae.id)},children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),Ks?s.jsxs(Ge,{onClick:()=>{W(Ne,Ae.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,q?null:s.jsxs(Ge,{disabled:!Ne,onClick:()=>{Ne&&M(Ne,{mode:"chat",dedupeKey:`session:${Ae.id}`,label:Ce,sessionTitleFallback:Ce})},className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"chat-4",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openInSidePanel")}),s.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:e("sessions.sidebar.session.menu.betaBadge")})]}),Se?s.jsxs(Ge,{disabled:!Ne,onClick:Fe,className:"[&>svg]:mr-1",children:[s.jsx(A,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(ps,{}),c?null:s.jsxs(Ge,{className:"[&>svg]:mr-1",onClick:()=>ee(Ae,{archivedBucket:c}),children:[s.jsx(A,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.archive")]}),s.jsxs(Ge,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ee(Ae,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(A,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),Nn=s.jsx(en,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(E||De.current),children:an({Item:ms,Separator:Vr,Sub:tx,SubTrigger:sx,SubContent:nx})}),nn=s.jsx(vd,{children:s.jsx(jd,{className:"app-region-no-drag z-50",children:s.jsx(Sd,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(E||De.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Pe(qd,"min-w-[180px]"),children:an({Item:({className:Ge,...ps})=>s.jsx(up,{className:Pe(Xg,Ge),...ps}),Separator:({className:Ge,...ps})=>s.jsx(fp,{className:Pe(Zg,Ge),...ps}),Sub:mp,SubTrigger:({className:Ge,children:ps,...ks})=>s.jsxs(hp,{className:Pe(ex,Ge),...ks,children:[ps,s.jsx(A,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:Ge,children:ps,...ks})=>s.jsx(vd,{children:s.jsx(jd,{className:"app-region-no-drag z-50",children:s.jsx(Sd,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Pe(qd,Ge),...ks,children:ps})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(U2,{sessionId:Ae.id,sessionDirectory:Ne??null,sessionTitle:Ce,children:s.jsxs(cp,{open:rs,onOpenChange:xe,onOpenChangeComplete:hn,children:[s.jsxs(dp,{render:s.jsx("div",{"data-session-row":Ae.id,"data-session-scope":Ne??"","data-session-archived":c?"1":"0",onClick:Gs,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]",es&&!Oe&&"bg-primary/10",Oe&&"bg-interactive-selection")}),children:[us,js,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:me?s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:Bn,onPointerUp:Sn,onPointerCancel:Sn,onMouseDown:Pn,onClick:Ge=>Tn(Ge),onDoubleClick:Ge=>{Ge.stopPropagation(),N(Ae.id,Ce)},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]",ye&&"bg-interactive-hover/70",X?q?ge:oe:ge),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",es?"text-primary":"text-foreground"),children:To(Ce,u)}),X?s.jsxs("span",{className:"ml-2 inline-flex flex-shrink-0 items-center gap-1 text-[0.72rem] text-muted-foreground/75",children:[ns,Rt]}):null,X?null:s.jsx("div",{className:"relative ml-1 flex h-4 min-w-4 flex-shrink-0 items-center justify-end",children:s.jsxs("span",{className:Pe("inline-flex items-center gap-1 whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",Et?"opacity-0":Le),children:[ns,Rt]})}),St>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(A,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:St})]}):null]})})}),q?null:s.jsx(Dt,{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",te?.projectLabel?"justify-between":"justify-start"),children:[te?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:te.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:Bt})]}),te?.branchLabel?s.jsx("div",{className:"flex items-center gap-3 text-left text-muted-foreground justify-start",children:s.jsx("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:te.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:Bn,onPointerUp:Sn,onPointerCancel:Sn,onMouseDown:Pn,onClick:Ge=>Tn(Ge),onDoubleClick:Ge=>{Ge.stopPropagation(),N(Ae.id,Ce)},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]",ye&&"bg-interactive-hover/70",X?q?ge:oe:ge),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",es?"text-primary":"text-foreground"),children:To(Ce,u)}),St>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(A,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:St})]}):null]}),me?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:Pe("flex min-w-0 items-center gap-1.5 overflow-hidden",as&&Qe?"pl-4":""),children:[ns,s.jsx("span",{className:"flex-shrink-0",children:Bt}),Me?s.jsx("span",{className:"truncate",children:te?.projectLabel}):null,z?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:te?.branchLabel})]}):null]})})]})}),Cs&&!ie?s.jsx("div",{className:Pe("absolute top-1/2 -translate-y-1/2 z-10",me?"right-0":"right-[30px]"),children:Cs}):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",Et||X&&!q?"opacity-100":Pe("opacity-0",_e)),children:[Ee?s.jsx(lk,{archiveLabel:e("sessions.sidebar.bulkActions.archive"),deleteLabel:e("sessions.sidebar.bulkActions.delete"),buttonSizeClass:me&&!X?"h-4 w-4":"h-6 w-6",iconSizeClass:me&&!X?"h-2.5 w-2.5":"h-3.5 w-3.5",onPointerDown:zt,onMouseDown:gt,onArchive:xs,onDelete:bs}):null,pe?s.jsxs(Ct,{children:[s.jsx(At,{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",me&&!X?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:Ss,onMouseDown:Ns,onClick:Os,onKeyDown:Ge=>Ge.stopPropagation(),children:s.jsx(A,{name:"external-link",className:Pe(me&&!X?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Dt,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(tn,{open:Ot,onOpenChange:jn,onOpenChangeComplete:hn,children:[s.jsx(Zs,{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",me&&!X?Et?"h-4 w-4 opacity-100":Pe("h-4 w-4 opacity-0",_e):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:dt,onMouseDown:jt,onClick:rt,onKeyDown:Ge=>Ge.stopPropagation(),children:s.jsx(A,{name:"more-2",className:Pe(me&&!X?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),Nn]})]})]}),nn]})}),Qe&&Je?n.children.map(Ge=>{const ps=we?we(Ge):{subtreeContainsActive:le,subtreeContainsEditing:ve,menuOpenSessionId:ne,nodeStructureKey:""};return H(Ge,r+1,Ne??o,a,c,void 0,re,ps)}):null,s.jsx(_s,{open:Ye,onOpenChange:tt,children:s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(sn,{children:[s.jsx(Hs,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(mn,{children:Ft===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:Ft}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:Ft})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:xt,onChange:Ge=>vt(Ge.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(br,{children:[s.jsx(ze,{type:"button",onClick:()=>tt(!1),variant:"outline",size:"sm",children:e("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{type:"button",onClick:()=>{tt(!1),Yt(xt)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),qt?s.jsx(ok,{session:Ve,open:hs,onOpenChange:ts}):null]},Ae.id)}const Af=t=>ds(t.session.directory??null),dk=(t,e)=>(t?.projectLabel??null)===(e?.projectLabel??null)&&(t?.branchLabel??null)===(e?.branchLabel??null),uk=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},oa=t=>t.menuOpenSessionId??uk(t),Ui=(t,e,n)=>e?n.has(t.node.session.id)?!0:Yr(t.node,e):!1,$a=(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($a(t.children[c],e.children[c],n,r,o))return!0;return!1},Fh=(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(Fh(t.children[a],e.children[a],n,r))return!0;return!1},fk=(t,e)=>{if(t.hasSessionSearchQuery||e.hasSessionSearchQuery)return!1;const n=t.archivedBucket?"archived":"active",r=e.archivedBucket?"archived":"active";return $a(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${t.renderContext??"project"}:${n}:${o.session.id}`)||$a(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${e.renderContext??"project"}:${r}:${o.session.id}`)},mk=(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||Af(t.node)!==Af(e.node)||!dk(t.secondaryMeta,e.secondaryMeta)||t.liveSessionById!==e.liveSessionById&&Fh(t.node,e.node,t.liveSessionById,e.liveSessionById)||t.pinnedSessionIds!==e.pinnedSessionIds&&$a(t.node,e.node,t.pinnedSessionIds,e.pinnedSessionIds,n=>n.session.id)||t.expandedParents!==e.expandedParents&&fk(t,e)||t.currentSessionId!==e.currentSessionId&&(Ui(t,t.currentSessionId,t.subtreeContainsActive)||Ui(e,e.currentSessionId,e.subtreeContainsActive))||t.editingId!==e.editingId&&(Ui(t,t.editingId,t.subtreeContainsEditing)||Ui(e,e.editingId,e.subtreeContainsEditing))||t.editTitle!==e.editTitle&&(Ui(t,t.editingId,t.subtreeContainsEditing)||Ui(e,e.editingId,e.subtreeContainsEditing))||t.copiedSessionId!==e.copiedSessionId&&(Yr(t.node,t.copiedSessionId)||Yr(e.node,e.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=oa(t),r=oa(e);if(Yr(t.node,n)||Yr(e.node,r))return!1}if(t.renamingFolderId!==e.renamingFolderId){const n=oa(t),r=oa(e);if(Yr(t.node,n)||Yr(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},hk=i.memo(ck,mk);function pk(t){return t.stopPropagation()}function gk(t){const e=ht.c(71),{t:n}=yt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,f,m,u,p,x,b,w,g,h;if(e[0]!==o||e[1]!==n||e[2]!==r){const M=n("sessions.sidebar.session.untitled");u=_s,g=!!r,e[13]!==o?(h=ie=>{ie||o(null)},e[13]=o,e[14]=h):h=e[14],m=Vs,b=!1,w="max-w-sm gap-5",f=sn;let ee;e[15]!==n||e[16]!==r?.archivedBucket?(ee=r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.title"):n("sessions.sidebar.dialogs.archiveSession.title"),e[15]=n,e[16]=r?.archivedBucket,e[17]=ee):ee=e[17],e[18]!==ee?(x=s.jsx(Hs,{children:ee}),e[18]=ee,e[19]=x):x=e[19],d=mn,p=r&&r.descendantCount>0?r.archivedBucket?r.descendantCount===1?n("sessions.sidebar.dialogs.deleteSession.withOneSubtask",{sessionTitle:r.session.title||M,count:r.descendantCount}):n("sessions.sidebar.dialogs.deleteSession.withManySubtasks",{sessionTitle:r.session.title||M,count:r.descendantCount}):r.descendantCount===1?n("sessions.sidebar.dialogs.archiveSession.withOneSubtask",{sessionTitle:r.session.title||M,count:r.descendantCount}):n("sessions.sidebar.dialogs.archiveSession.withManySubtasks",{sessionTitle:r.session.title||M,count:r.descendantCount}):r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.single",{sessionTitle:r?.session.title||M}):n("sessions.sidebar.dialogs.archiveSession.single",{sessionTitle:r?.session.title||M}),e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=f,e[5]=m,e[6]=u,e[7]=p,e[8]=x,e[9]=b,e[10]=w,e[11]=g,e[12]=h}else d=e[3],f=e[4],m=e[5],u=e[6],p=e[7],x=e[8],b=e[9],w=e[10],g=e[11],h=e[12];let C;e[20]!==d||e[21]!==p?(C=s.jsx(d,{children:p}),e[20]=d,e[21]=p,e[22]=C):C=e[22];let j;e[23]!==f||e[24]!==x||e[25]!==C?(j=s.jsxs(f,{children:[x,C]}),e[23]=f,e[24]=x,e[25]=C,e[26]=j):j=e[26];let S;e[27]!==c||e[28]!==a?(S=()=>c(!a),e[27]=c,e[28]=a,e[29]=S):S=e[29];const N=!a;let k;e[30]!==a?(k=a?s.jsx(A,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(A,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[30]=a,e[31]=k):k=e[31];let y;e[32]!==n?(y=n("sessions.sidebar.dialogs.neverAsk"),e[32]=n,e[33]=y):y=e[33];let D;e[34]!==k||e[35]!==y||e[36]!==S||e[37]!==N?(D=s.jsxs("button",{type:"button",onClick:S,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":N,children:[k,y]}),e[34]=k,e[35]=y,e[36]=S,e[37]=N,e[38]=D):D=e[38];let V;e[39]!==o?(V=()=>o(null),e[39]=o,e[40]=V):V=e[40];let v;e[41]!==n?(v=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=v):v=e[42];let O;e[43]!==V||e[44]!==v?(O=s.jsx("button",{type:"button",onClick:V,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:v}),e[43]=V,e[44]=v,e[45]=O):O=e[45];let P;e[46]!==l?(P=()=>{l()},e[46]=l,e[47]=P):P=e[47];let E;e[48]!==n||e[49]!==r?.archivedBucket?(E=r?.archivedBucket?n("sessions.sidebar.bulkActions.delete"):n("sessions.sidebar.bulkActions.archive"),e[48]=n,e[49]=r?.archivedBucket,e[50]=E):E=e[50];let B;e[51]!==P||e[52]!==E?(B=s.jsx("button",{type:"button",onClick:P,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:E}),e[51]=P,e[52]=E,e[53]=B):B=e[53];let T;e[54]!==O||e[55]!==B?(T=s.jsxs("div",{className:"flex items-center gap-2",children:[O,B]}),e[54]=O,e[55]=B,e[56]=T):T=e[56];let W;e[57]!==D||e[58]!==T?(W=s.jsxs(br,{className:"w-full sm:items-center sm:justify-between",children:[D,T]}),e[57]=D,e[58]=T,e[59]=W):W=e[59];let U;e[60]!==m||e[61]!==b||e[62]!==W||e[63]!==w||e[64]!==j?(U=s.jsxs(m,{showCloseButton:b,className:w,children:[j,W]}),e[60]=m,e[61]=b,e[62]=W,e[63]=w,e[64]=j,e[65]=U):U=e[65];let L;return e[66]!==u||e[67]!==U||e[68]!==g||e[69]!==h?(L=s.jsx(u,{open:g,onOpenChange:h,children:U}),e[66]=u,e[67]=U,e[68]=g,e[69]=h,e[70]=L):L=e[70],L}function xk(t){const e=ht.c(57),{t:n}=yt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t,d=r?.archivedBucket===!0,f=r?.sessionCount??0;let m;e[0]!==d||e[1]!==f||e[2]!==n?(m=n(d?f===1?"sessions.sidebar.dialogs.deleteSession.title":"sessions.sidebar.dialogs.deleteSessions.title":f===1?"sessions.sidebar.dialogs.archiveSession.title":"sessions.sidebar.dialogs.archiveSessions.title"),e[0]=d,e[1]=f,e[2]=n,e[3]=m):m=e[3];const u=m;let p;e[4]!==d||e[5]!==f||e[6]!==n?(p=d?f===1?n("sessions.sidebar.dialogs.deleteSessions.singleDescription",{count:f}):n("sessions.sidebar.dialogs.deleteSessions.pluralDescription",{count:f}):f===1?n("sessions.sidebar.dialogs.archiveSessions.singleDescription",{count:f}):n("sessions.sidebar.dialogs.archiveSessions.pluralDescription",{count:f}),e[4]=d,e[5]=f,e[6]=n,e[7]=p):p=e[7];const x=p,b=!!r;let w;e[8]!==o?(w=L=>{L||o(null)},e[8]=o,e[9]=w):w=e[9];let g;e[10]!==u?(g=s.jsx(Hs,{children:u}),e[10]=u,e[11]=g):g=e[11];let h;e[12]!==x?(h=s.jsx(mn,{children:x}),e[12]=x,e[13]=h):h=e[13];let C;e[14]!==g||e[15]!==h?(C=s.jsxs(sn,{children:[g,h]}),e[14]=g,e[15]=h,e[16]=C):C=e[16];let j;e[17]!==c||e[18]!==a?(j=()=>c(!a),e[17]=c,e[18]=a,e[19]=j):j=e[19];const S=!a;let N;e[20]!==a?(N=a?s.jsx(A,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(A,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[20]=a,e[21]=N):N=e[21];let k;e[22]!==n?(k=n("sessions.sidebar.dialogs.neverAsk"),e[22]=n,e[23]=k):k=e[23];let y;e[24]!==k||e[25]!==j||e[26]!==S||e[27]!==N?(y=s.jsxs("button",{type:"button",onClick:j,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":S,children:[N,k]}),e[24]=k,e[25]=j,e[26]=S,e[27]=N,e[28]=y):y=e[28];let D;e[29]!==o?(D=()=>o(null),e[29]=o,e[30]=D):D=e[30];let V;e[31]!==n?(V=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=V):V=e[32];let v;e[33]!==D||e[34]!==V?(v=s.jsx("button",{type:"button",onClick:D,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:V}),e[33]=D,e[34]=V,e[35]=v):v=e[35];let O;e[36]!==l?(O=()=>{l()},e[36]=l,e[37]=O):O=e[37];let P;e[38]!==d||e[39]!==n?(P=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=P):P=e[40];let E;e[41]!==O||e[42]!==P?(E=s.jsx("button",{type:"button",onClick:O,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:P}),e[41]=O,e[42]=P,e[43]=E):E=e[43];let B;e[44]!==v||e[45]!==E?(B=s.jsxs("div",{className:"flex items-center gap-2",children:[v,E]}),e[44]=v,e[45]=E,e[46]=B):B=e[46];let T;e[47]!==y||e[48]!==B?(T=s.jsxs(br,{className:"w-full sm:items-center sm:justify-between",children:[y,B]}),e[47]=y,e[48]=B,e[49]=T):T=e[49];let W;e[50]!==T||e[51]!==C?(W=s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[C,T]}),e[50]=T,e[51]=C,e[52]=W):W=e[52];let U;return e[53]!==b||e[54]!==W||e[55]!==w?(U=s.jsx(_s,{open:b,onOpenChange:w,children:W}),e[53]=b,e[54]=W,e[55]=w,e[56]=U):U=e[56],U}function bk(t){const e=ht.c(36),{t:n}=yt(),{value:r,setValue:o,onConfirm:a}=t,c=!!r;let l;e[0]!==o?(l=N=>{N||o(null)},e[0]=o,e[1]=l):l=e[1];let d;e[2]!==n?(d=n("sessions.sidebar.dialogs.deleteFolder.title"),e[2]=n,e[3]=d):d=e[3];let f;e[4]!==d?(f=s.jsx(Hs,{children:d}),e[4]=d,e[5]=f):f=e[5];let m;e[6]!==n||e[7]!==r?(m=r&&(r.subFolderCount>0||r.sessionCount>0)?r.subFolderCount>0?r.subFolderCount===1?n("sessions.sidebar.dialogs.deleteFolder.withOneSubfolder",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withManySubfolders",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withContentsNoSubfolders",{folderName:r.folderName}):n("sessions.sidebar.dialogs.deleteFolder.single",{folderName:r?.folderName??""}),e[6]=n,e[7]=r,e[8]=m):m=e[8];let u;e[9]!==m?(u=s.jsx(mn,{children:m}),e[9]=m,e[10]=u):u=e[10];let p;e[11]!==f||e[12]!==u?(p=s.jsxs(sn,{children:[f,u]}),e[11]=f,e[12]=u,e[13]=p):p=e[13];let x;e[14]!==o?(x=()=>o(null),e[14]=o,e[15]=x):x=e[15];let b;e[16]!==n?(b=n("sessions.sidebar.dialogs.cancel"),e[16]=n,e[17]=b):b=e[17];let w;e[18]!==x||e[19]!==b?(w=s.jsx("button",{type:"button",onClick:x,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:b}),e[18]=x,e[19]=b,e[20]=w):w=e[20];let g;e[21]!==n?(g=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=g):g=e[22];let h;e[23]!==a||e[24]!==g?(h=s.jsx("button",{type:"button",onClick:a,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:g}),e[23]=a,e[24]=g,e[25]=h):h=e[25];let C;e[26]!==h||e[27]!==w?(C=s.jsxs(br,{children:[w,h]}),e[26]=h,e[27]=w,e[28]=C):C=e[28];let j;e[29]!==C||e[30]!==p?(j=s.jsxs(Vs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[p,C]}),e[29]=C,e[30]=p,e[31]=j):j=e[31];let S;return e[32]!==c||e[33]!==l||e[34]!==j?(S=s.jsx(_s,{open:c,onOpenChange:l,children:j}),e[32]=c,e[33]=l,e[34]=j,e[35]=S):S=e[35],S}const wk=t=>{const e=ht.c(46),{selectedCount:n,scopeKey:r,scopeFolders:o,archivedBucket:a,onMoveToFolder:c,onCreateFolderAndMove:l,onRemoveFromFolder:d,canRemoveFromFolder:f,onDelete:m,onDone:u}=t,{t:p}=yt(),x=!!r&&!a;let b;e[0]!==a||e[1]!==p?(b=p(a?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[0]=a,e[1]=p,e[2]=b):b=e[2];const w=b;let g;e[3]!==n||e[4]!==p?(g=p("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=p,e[5]=g):g=e[5];let h;e[6]!==g?(h=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:g}),e[6]=g,e[7]=h):h=e[7];let C;e[8]!==x||e[9]!==f||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==p?(C=x?s.jsxs(tn,{children:[s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":p("sessions.sidebar.bulkActions.moveToFolder"),children:s.jsx(A,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(Dt,{side:"top",sideOffset:4,children:s.jsx("p",{children:p("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(en,{align:"end",className:"min-w-[180px]",children:[o.length===0?s.jsx(ms,{disabled:!0,className:"text-muted-foreground",children:p("sessions.sidebar.folders.none")}):o.map(W=>s.jsx(ms,{onClick:()=>c(W.id),children:s.jsx("span",{className:"flex-1 truncate",children:W.name})},W.id)),s.jsx(Vr,{}),s.jsxs(ms,{onClick:l,children:[s.jsx(A,{name:"add",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.newFolderEllipsis")]}),f?s.jsxs(ms,{onClick:d,className:"text-destructive focus:text-destructive",children:[s.jsx(A,{name:"close",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=x,e[9]=f,e[10]=l,e[11]=c,e[12]=d,e[13]=o,e[14]=p,e[15]=C):C=e[15];let j;e[16]===Symbol.for("react.memo_cache_sentinel")?(j=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]=j):j=e[16];let S;e[17]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(A,{name:"delete-bin",className:"h-4 w-4"}),e[17]=S):S=e[17];let N;e[18]!==w||e[19]!==m?(N=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,className:j,"aria-label":w,children:S})}),e[18]=w,e[19]=m,e[20]=N):N=e[20];let k;e[21]!==w?(k=s.jsx(Dt,{side:"top",sideOffset:4,children:s.jsx("p",{children:w})}),e[21]=w,e[22]=k):k=e[22];let y;e[23]!==N||e[24]!==k?(y=s.jsxs(Ct,{children:[N,k]}),e[23]=N,e[24]=k,e[25]=y):y=e[25];let D;e[26]!==p?(D=p("sessions.sidebar.header.actions.exitSelection"),e[26]=p,e[27]=D):D=e[27];let V;e[28]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsx(A,{name:"close",className:"h-4 w-4"}),e[28]=V):V=e[28];let v;e[29]!==u||e[30]!==D?(v=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:u,className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":D,children:V})}),e[29]=u,e[30]=D,e[31]=v):v=e[31];let O;e[32]!==p?(O=p("sessions.sidebar.header.actions.exitSelection"),e[32]=p,e[33]=O):O=e[33];let P;e[34]!==O?(P=s.jsx(Dt,{side:"top",sideOffset:4,children:s.jsx("p",{children:O})}),e[34]=O,e[35]=P):P=e[35];let E;e[36]!==v||e[37]!==P?(E=s.jsxs(Ct,{children:[v,P]}),e[36]=v,e[37]=P,e[38]=E):E=e[38];let B;e[39]!==E||e[40]!==C||e[41]!==y?(B=s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[C,y,E]}),e[39]=E,e[40]=C,e[41]=y,e[42]=B):B=e[42];let T;return e[43]!==B||e[44]!==h?(T=s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-2.5 py-1.5",children:[h,B]}),e[43]=B,e[44]=h,e[45]=T):T=e[45],T},yk=t=>{const{t:e}=yt(),{isInlineEditing:n,showDeletionDialog:r,foldersMap:o,addSessionsToFolder:a,removeSessionsFromFolders:c,createFolderAndStartRename:l,archiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:m}=t,u=Hn(P=>P.enabled),p=Hn(P=>P.selectedIds.size),x=p>0,b=Hn(P=>P.selectedIds),w=Hn(P=>P.scopeKey),g=i.useCallback(()=>{Hn.getState().toggleMode()},[]),h=i.useCallback(()=>{Hn.getState().disable()},[]),C=i.useMemo(()=>{if(!x||typeof document>"u")return!1;let P=!1,E=!1;for(const B of b){const T=document.querySelectorAll(`[data-session-row="${CSS.escape(B)}"]`);for(const W of T)W.getAttribute("data-session-archived")==="1"?E=!0:P=!0}return E&&!P},[x,b]),j=i.useMemo(()=>{if(w)return w;if(!x||typeof document>"u")return null;for(const P of b){const B=document.querySelector(`[data-session-row="${CSS.escape(P)}"]`)?.getAttribute("data-session-scope");if(B&&B.length>0)return B}return null},[x,b,w]),S=i.useMemo(()=>j?o[j]??[]:[],[o,j]),N=i.useMemo(()=>{if(!j||!x)return!1;const P=o[j]??[];for(const E of P)for(const B of E.sessionIds)if(b.has(B))return!0;return!1},[o,j,x,b]),k=i.useCallback(P=>{!j||!x||a(j,P,Array.from(b))},[a,b,j,x]),y=i.useCallback(()=>{if(!j||!x)return;const P=l(j);P&&a(j,P.id,Array.from(b))},[a,l,b,j,x]),D=i.useCallback(()=>{!j||!x||c(j,Array.from(b))},[c,b,j,x]),V=i.useCallback(async()=>{const P=Array.from(b);if(P.length!==0){if(C){const{deletedIds:E,failedIds:B}=await f(P);E.length>0&&ae.success(E.length===1?e("sessions.sidebar.bulkActions.deletedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.deletedPlural",{count:E.length})),B.length>0&&ae.error(B.length===1?e("sessions.sidebar.bulkActions.failedDeleteSingle",{count:B.length}):e("sessions.sidebar.bulkActions.failedDeletePlural",{count:B.length}))}else{const{archivedIds:E,failedIds:B}=await d(P);E.length>0&&ae.success(E.length===1?e("sessions.sidebar.bulkActions.archivedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.archivedPlural",{count:E.length})),B.length>0&&ae.error(B.length===1?e("sessions.sidebar.bulkActions.failedArchiveSingle",{count:B.length}):e("sessions.sidebar.bulkActions.failedArchivePlural",{count:B.length}))}Hn.getState().clear()}},[d,C,f,b,e]),v=i.useCallback(()=>{if(!x)return;const P=b.size;if(!r){V();return}m({sessionCount:P,archivedBucket:C})},[C,V,b,r,m,x]),O=i.useCallback(async()=>{m(null),await V()},[V]);return i.useEffect(()=>{if(!u)return;const P=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=B=>{if(n)return;const T=B.target;if(T&&(T.tagName==="INPUT"||T.tagName==="TEXTAREA"||T.isContentEditable))return;const W=P?B.metaKey:B.ctrlKey;if(B.key==="Escape"){B.preventDefault(),Hn.getState().disable();return}if(W&&B.key==="Backspace"){B.preventDefault(),v();return}if(W&&(B.key==="a"||B.key==="A")){const U=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(U.length===0)return;B.preventDefault();const M=Hn.getState().scopeKey??U[0]?.getAttribute("data-session-scope")??null,ee=X=>M?X.getAttribute("data-session-scope")===M:!0,ie=U.filter(ee).map(X=>X.getAttribute("data-session-row")).filter(X=>typeof X=="string"&&X.length>0);if(ie.length===0)return;Hn.getState().replaceAll(ie,M||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[v,n,u]),{selectionModeEnabled:u,hasSelection:x,selectedIdsSize:p,bulkScopeIsArchived:C,derivedSelectionScope:j,bulkScopeFolders:S,bulkCanRemoveFromFolder:N,handleToggleSelectionMode:g,handleExitSelectionMode:h,handleBulkMoveToFolder:k,handleBulkCreateFolderAndMove:y,handleBulkRemoveFromFolder:D,handleBulkDelete:v,confirmBulkDelete:O}},vk=2880*60*1e3,jk=t=>!!t.parentID,Sk=t=>!!t.time?.archived,hc=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},Nk=t=>[...t].sort((e,n)=>hc(n)-hc(e)),kk=(t,e=Date.now())=>{const n=e-vk,r=t.filter(o=>Sk(o)||jk(o)?!1:hc(o)>=n);return Nk(r)},Df="openchamber.shareOpinionToast.dismissed.v2",aa="oc.sessions.projectCollapse",Tf="oc.sessions.groupOrder",Pf="oc.sessions.groupCollapse",If="oc.sessions.activeSessionByProject",_l="oc.sessions.expandedParents.v2",Ck="oc.sessions.expandedParents",Ak="oc.sessions.pinned",Dk=(t,e,n)=>{const r=new Set;for(const o of t){const a=ds(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=ds(a.path)?.toLowerCase();c&&r.add(c)}return r},Tk=(t,e,n)=>{if(t.time?.archived)return!0;const r=ds(Br(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},Pk=5*6e4,Rf=new Set,Mr=t=>{const e=i.useRef(t);return e.current=t,i.useCallback((...n)=>e.current(...n),[])},Ef=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=yt(),[c,l]=i.useState(!1),[d,f]=i.useState(""),m=i.useRef(null),u=i.useRef(null),p=i.useRef(new Set),[x,b]=i.useState(null),[w,g]=i.useState(""),[h,C]=i.useState(null),[j,S]=i.useState(new Set),N=i.useMemo(()=>Gi(),[]),[k,y]=i.useState(new Set),[D,V]=i.useState(new Map),[v,O]=i.useState(new Map),P=Re(Z=>Z.isNewWorktreeDialogOpen),E=Re(Z=>Z.setNewWorktreeDialogOpen),[B,T]=i.useState(!1),[W,U]=i.useState(!1),[L,M]=i.useState(null),[ee,ie]=i.useState(null),[X,H]=i.useState(""),[te,re]=i.useState(null),[le,ve]=i.useState(null),[ne,we]=i.useState(null),he=gl(Z=>Z.ids),Me=gl(Z=>Z.setIds),z=gl(Z=>Z.toggle),[K,q]=i.useState(()=>{try{const Z=Gi().getItem(Pf);if(!Z)return new Set;const it=JSON.parse(Z);return new Set(Array.isArray(it)?it.filter(et=>typeof et=="string"):[])}catch{return new Set}}),[me,Se]=i.useState(()=>{try{const Z=Gi().getItem(Tf);if(!Z)return new Map;const it=JSON.parse(Z),et=new Map;return Object.entries(it).forEach(([pt,_t])=>{Array.isArray(_t)&&et.set(pt,_t.filter(As=>typeof As=="string"))}),et}catch{return new Map}}),[Be,_e]=i.useState(()=>{try{const Z=Gi().getItem(If);if(!Z)return new Map;const it=JSON.parse(Z),et=new Map;return Object.entries(it).forEach(([pt,_t])=>{typeof _t=="string"&&_t.length>0&&et.set(pt,_t)}),et}catch{return new Map}}),[Le,pe]=i.useState(new Map),Ee=i.useRef(new Map),ge=i.useRef(0),oe=Xs(Z=>Z.homeDirectory),je=Xs(Z=>Z.currentDirectory),ye=Xs(Z=>Z.setDirectory),ue=Ds(Z=>Z.projects),De=Ds(Z=>Z.activeProjectId),I=Ds(Z=>Z.removeProject),_=Ds(Z=>Z.setActiveProjectIdOnly),be=Ds(Z=>Z.updateProjectMeta),R=Ds(Z=>Z.reorderProjects),de=Re(Z=>Z.setActiveMainTab),fe=Re(Z=>Z.openContextPanelTab),$=Re(Z=>Z.setSettingsDialogOpen),Ae=Re(Z=>Z.toggleHelpDialog),Ve=Re(Z=>Z.setAboutDialogOpen),Ne=Re(Z=>Z.setSessionSwitcherOpen),Y=Re(Z=>Z.setScheduledTasksDialogOpen),F=Re(Z=>Z.openMultiRunLauncher),se=Re(Z=>Z.notifyOnSubtasks),Oe=Re(Z=>Z.showDeletionDialog),ce=Re(Z=>Z.setShowDeletionDialog),Ue=Za(d,120),qe=i.useMemo(()=>Ue.trim().toLowerCase(),[Ue]),Ye=qe.length>0,tt=Wn(Z=>Z.collapsedFolderIds),xt=Wn(Z=>Z.foldersMap),vt=Wn(Z=>Z.getFoldersForScope),Mt=Wn(Z=>Z.createFolder),Tt=Wn(Z=>Z.renameFolder),Kt=Wn(Z=>Z.deleteFolder),Ut=Wn(Z=>Z.addSessionToFolder),Zt=Wn(Z=>Z.addSessionsToFolder),ns=Wn(Z=>Z.removeSessionFromFolder),es=Wn(Z=>Z.removeSessionsFromFolders),Ce=Wn(Z=>Z.toggleFolderCollapse),Qe=Wn(Z=>Z.cleanupSessions),ot=Wn(Z=>Z.getSessionFolderId);a2({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchContainerRef:m});const bt=bm(),Je=Vc(),Pt=Nc(),Xe=i.useMemo(()=>_r(),[]),Ke=pr(Z=>Z.hasLoaded),Ze=pr(Z=>Z.status==="ready"),Bt=pr(Z=>Z.activeSessions),Rt=pr(Z=>Z.archivedSessions),Ot=mt(Z=>Z.currentSessionId),rs=mt(Z=>!!Z.newSessionDraft?.open),Wt=mt(Z=>Z.setCurrentSession),Et=mt(Z=>Z.updateSessionTitle),qt=mt(Z=>Z.shareSession),hs=mt(Z=>Z.unshareSession),ts=mt(Z=>Z.worktreeMetadata),as=mt(Z=>Z.availableWorktreesByProject),gs=mt(Z=>Z.openNewSessionDraft),Ft=i.useCallback(Z=>{gs(Z),Xe&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[Xe,gs]),Lt=Do(Kl(Z=>({checkForUpdates:Z.checkForUpdates,available:Z.available,runtimeType:Z.runtimeType,info:Z.info,downloading:Z.downloading,downloaded:Z.downloaded,progress:Z.progress,error:Z.error,downloadUpdate:Z.downloadUpdate,restartToUpdate:Z.restartToUpdate}))),Ht=i.useMemo(()=>Dk(ue,as,{includeWorktrees:!Xe}),[as,Xe,ue]),Yt=i.useMemo(()=>{const Z=new Map(Pt.map(pt=>[pt.id,pt])),it=Bt.map(pt=>{const _t=Z.get(pt.id);return _t?rx(_t,pt):pt}),et=new Set(it.map(pt=>pt.id));return Pt.forEach(pt=>{et.has(pt.id)||it.push(pt)}),it.filter(pt=>Tk(pt,Ht,{allowUnknownDirectory:!Xe,allowEmptyDirectorySet:!Xe}))},[Bt,Xe,Ht,Pt]),$t=i.useMemo(()=>[...Bt,...Rt],[Rt,Bt]),Fe=i.useMemo(()=>Pt.map(Z=>{const it=ds(Z.directory??null)??"";return`${Z.id}:${Z.title??""}:${Z.time?.archived?1:0}:${it}`}).join("|"),[Pt]),st=i.useRef(Pt);i.useEffect(()=>{st.current=Pt},[Fe,Pt]);const wt=i.useMemo(()=>new Map(Pt.map(Z=>[Z.id,Z])),[Pt]),St=i.useMemo(()=>ue.map(Z=>`${Z.id}:${ds(Z.path)??""}`).join("|"),[ue]),Nt=i.useRef(!1);i.useEffect(()=>{Nt.current||(Nt.current=!0,Ta(st.current))},[]);const ss=i.useRef("");i.useEffect(()=>{let Z=!1;const it=async()=>{const et=Ds.getState().projects;if(et.length===0)return;const pt=new Map,_t=[],As=3;let un=0;const kn=Array.from({length:As},async()=>{for(;;){const zn=un;if(un+=1,zn>=et.length)return;const jr=et[zn],Ws=ds(jr.path);if(Ws)try{if(!(vn.getState().directories.get(Ws)?.isGitRepo??await Nm(Ws)))continue;const yo=await ox({id:jr.id,path:Ws});if(Z||yo.length===0)continue;pt.set(Ws,yo),_t.push(...yo)}catch{}}});if(await Promise.all(kn),Z)return;const Cn=mt.getState().availableWorktreesByProject;ax(pt,Cn)||mt.setState({availableWorktrees:_t,availableWorktreesByProject:pt})};if(ss.current!==St)return ss.current=St,it(),()=>{Z=!0}},[St]),i.useEffect(()=>{let Z=null;const it=Ch(et=>{et.type==="scheduled-task-ran"&&(Z&&clearTimeout(Z),Z=setTimeout(()=>{Ta(st.current)},500))});return()=>{Z&&clearTimeout(Z),it()}},[]);const cs=i.useMemo(()=>gr(),[]),{isTablet:Xt}=$r(),Vt=t||Xt,{buildGroupSearchText:Fs,filterSessionNodesForSearch:us,buildGroupedSessions:$s}=o2({homeDirectory:oe,worktreeMetadata:ts,pinnedSessionIds:he,gitBranches:bt,isVSCode:Xe}),{scheduleCollapsedProjectsPersist:js}=p2({isVSCode:Xe,hasAuthoritativeGlobalSessions:Ze,safeStorage:N,keys:{sessionExpanded:_l,sessionExpandedLegacy:Ck,projectCollapse:aa,sessionPinned:Ak,groupOrder:Tf,projectActiveSession:If,groupCollapse:Pf},sessions:$t,setPinnedSessionIds:Me,groupOrderByProject:me,activeSessionByProject:Be,collapsedGroups:K,setExpandedParents:S,setCollapsedProjects:y}),Cs=i.useMemo(()=>[...Yt].sort((Z,it)=>Qi(Z,it,he)),[Yt,he]),jn=i.useMemo(()=>Cs.map(Z=>`${Z.id}:${Z.time?.updated??0}`).join("|"),[Cs]),hn=i.useRef(null),xe=i.useMemo(()=>{const Z=hn.current;if(Z&&Z.signature===jn)return Z.map;const it=new Map(Cs.map((et,pt)=>[et.id,pt]));return hn.current={signature:jn,map:it},it},[jn,Cs]),rt=i.useMemo(()=>{const Z=new Map;return Cs.forEach(it=>{const et=it.parentID;if(!et)return;const pt=Z.get(et)??[];pt.push(it),Z.set(et,pt)}),Z.forEach(it=>it.sort((et,pt)=>Qi(et,pt,he))),Z},[Cs,he]),dt=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")})]}),jt=i.useMemo(()=>ue.find(Z=>Z.id===h)??null,[ue,h]),zt=i.useCallback(Z=>{h&&be(h,{label:Z.label,icon:Z.icon,color:Z.color,iconBackground:Z.iconBackground,defaultModel:Z.defaultModel??null})},[h,be]),gt=i.useCallback(()=>{E(!0)},[E]),xs=i.useCallback(()=>{const Z=Do.getState();if(Z.available&&Z.info){T(!0);return}Lt.checkForUpdates().then(()=>{const{available:it,error:et}=Do.getState();if(et){ae.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:et});return}if(!it){ae.success(a("sessions.sidebar.updateCheck.latestVersion"));return}T(!0)})},[a,Lt]),bs=i.useCallback(()=>{U(!0)},[]);i.useEffect(()=>{if(typeof window>"u")return;try{if(window.localStorage.getItem(Df)==="true")return;window.localStorage.setItem(Df,"true")}catch{}const Z=window.setTimeout(()=>{ae.info(a("shareOpinion.toast.title"),{description:a("shareOpinion.toast.description"),action:{label:a("shareOpinion.actions.shareOpinion"),onClick:()=>U(!0)},duration:12e3})},1e3);return()=>window.clearTimeout(Z)},[a]);const Ss=i.useCallback(()=>{t&&Ne(!1),$(!0)},[t,Ne,$]),Ns=Lt.available&&(Lt.runtimeType==="desktop"||Lt.runtimeType==="web"),Os=mt(Z=>Z.deleteSession),Tn=mt(Z=>Z.deleteSessions),Gs=mt(Z=>Z.archiveSession),Pn=mt(Z=>Z.archiveSessions),{copiedSessionId:Bn,handleSessionSelect:Sn,handleSessionDoubleClick:an,handleSaveEdit:Nn,handleCancelEdit:nn,handleShareSession:Ge,handleCopyShareUrl:ps,handleUnshareSession:ks,handleDeleteSession:zs,confirmDeleteSession:Rs}=l2({activeProjectId:De,currentDirectory:je,currentSessionId:Ot,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:l,setActiveProjectIdOnly:_,setDirectory:ye,setActiveMainTab:de,setSessionSwitcherOpen:Ne,setCurrentSession:Wt,updateSessionTitle:Et,shareSession:qt,unshareSession:hs,deleteSession:Os,deleteSessions:Tn,archiveSession:Gs,archiveSessions:Pn,childrenMap:rt,showDeletionDialog:Oe,setDeleteSessionConfirm:re,deleteSessionConfirm:te,setEditingId:b,setEditTitle:g,editingId:x,editTitle:w}),rn=i.useCallback(()=>{if(!le)return;const{scopeKey:Z,folderId:it}=le;ve(null),Kt(Z,it)},[le,Kt]),Ks=i.useCallback(()=>{Lr.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!Ot)return;const it=Yt.find(pt=>pt.id===Ot)?.parentID;if(!it)return;const et=[`project:active:${it}`,`project:archived:${it}`,`recent:active:${it}`,`recent:archived:${it}`];S(pt=>{if(et.every(As=>pt.has(As)))return pt;const _t=new Set(pt);et.forEach(As=>_t.add(As));try{N.setItem(_l,JSON.stringify(Array.from(_t)))}catch{}return _t})},[Ot,Yt,N]);const Is=i.useCallback(Z=>{S(it=>{const et=new Set(it);et.has(Z)?et.delete(Z):et.add(Z);try{N.setItem(_l,JSON.stringify(Array.from(et)))}catch{}return et})},[N]),Vn=i.useCallback((Z,it)=>{if(!Z)return null;it&&tt.has(it)&&Ce(it);const et=Mt(Z,a("sessions.sidebar.folder.newFolderName"),it);return ie(et.id),H(et.name),et},[tt,Ce,Mt,a]),ws=Mr(Sn),Ls=Mr(an),Dr=Mr(Nn),_n=Mr(nn),bn=Mr(Ge),Tr=Mr(ps),si=Mr(ks),ni=Mr(zs),zr=Mr(Vn),cr=i.useCallback((Z,it)=>{O(et=>{const pt=new Map(et);return pt.set(Z,it+7),pt})},[]),ys=i.useCallback(Z=>{O(it=>{if(!it.has(Z))return it;const et=new Map(it);return et.delete(Z),et})},[]),ln=i.useCallback(Z=>{O(it=>{let et=!1;const pt=new Map(it),_t=`${Z}:`;for(const As of pt.keys())As.startsWith(_t)&&(pt.delete(As),et=!0);return et?pt:it})},[]),dr=i.useCallback(()=>{ge.current=Date.now()+150,O(new Map),y(()=>{const Z=new Set(ue.map(it=>it.id));try{N.setItem(aa,JSON.stringify(Array.from(Z)))}catch{}return Xe||js(Z),Z})},[ue,Xe,N,js]),J=i.useCallback(()=>{ge.current=Date.now()+150,O(new Map),y(()=>{const Z=new Set;try{N.setItem(aa,JSON.stringify([]))}catch{}return Xe||js(Z),Z})},[Xe,N,js]),at=i.useCallback(Z=>{ge.current=Date.now()+150,ln(Z),y(it=>{const et=new Set(it);et.has(Z)?et.delete(Z):et.add(Z);try{N.setItem(aa,JSON.stringify(Array.from(et)))}catch{}return Xe||js(et),et})},[Xe,ln,N,js]),ut=i.useMemo(()=>ue.map(Z=>({...Z,normalizedPath:ds(Z.path)})).filter(Z=>!!Z.normalizedPath),[ue]),kt=i.useMemo(()=>ut.map(Z=>Z.normalizedPath),[ut]),Gt=i.useMemo(()=>{const Z=new Set;return ut.forEach(it=>{if(it.normalizedPath&&Z.add(it.normalizedPath),Xe)return;(as.get(it.normalizedPath)??[]).forEach(pt=>{const _t=ds(pt.path);_t&&Z.add(_t)})}),[...Z].sort()},[as,Xe,ut]),os=i.useRef(null);i.useEffect(()=>{const Z=new Set(Gt),it=os.current;if(os.current=Z,!it){Xe&&Gt.length>0&&Yd(Gt,st.current);return}const et=Gt.filter(pt=>!it.has(pt));et.length!==0&&Yd(et,st.current)},[Xe,Gt]);const{github:fs}=Zn(),Es=Fi(Z=>Z.status),qs=Fi(Z=>Z.hasChecked),er=ix(kt),$n=lr(Z=>Z.ensureEntry),ri=lr(Z=>Z.setParams),pn=lr(Z=>Z.refreshTargets);g2({normalizedProjects:ut,gitRepoStatus:er,setProjectRepoStatus:V,setProjectRootBranches:pe});const Wr=mt(Z=>Z.isLoading);j2({isSessionsLoading:Wr,hasLoadedGlobalSessions:Ke,sessions:Yt,archivedSessions:Rt,normalizedProjects:ut,isVSCode:Xe,availableWorktreesByProject:as,cleanupSessions:Qe});const{getSessionsForProject:In,getArchivedSessionsForProject:tr}=x2({isVSCode:Xe,sessions:Yt,archivedSessions:Rt,availableWorktreesByProject:as,normalizedProjects:ut});XS({normalizedProjects:ut,sessions:Yt,archivedSessions:Rt,availableWorktreesByProject:as,isVSCode:Xe,isSessionsLoading:Wr,foldersMap:xt,createFolder:Mt,addSessionToFolder:Ut,cleanupSessions:Qe});const cn=i.useRef(!1);De&&D.has(De)&&(cn.current=!!D.get(De));const gn=ar(Z=>Z.showRecentSection),wn=ar(Z=>Z.showArchivedSessions),sr=ar(Z=>Z.projectSortOrder),nr=Ds(Z=>Z.manualProjectOrder),Ur=i.useMemo(()=>{const Z=[...ut];switch(sr){case"a-z":Z.sort((it,et)=>{const pt=(it.label||it.path).toLowerCase(),_t=(et.label||et.path).toLowerCase();return pt.localeCompare(_t)});break;case"z-a":Z.sort((it,et)=>{const pt=(it.label||it.path).toLowerCase();return(et.label||et.path).toLowerCase().localeCompare(pt)});break;case"date-added":Z.sort((it,et)=>(et.addedAt??0)-(it.addedAt??0));break;case"recent":Z.sort((it,et)=>(et.lastOpenedAt??0)-(it.lastOpenedAt??0));break;case"manual":{const it=new Map(nr.map((et,pt)=>[et,pt]));Z.sort((et,pt)=>{const _t=it.get(et.id)??1/0,As=it.get(pt.id)??1/0;return _t-As});break}}return Z},[ut,sr,nr]),{projectSections:rr,groupSearchDataByGroup:Hr,sectionsForRender:ii,searchMatchCount:Oi}=t2({normalizedProjects:Ur,getSessionsForProject:In,getArchivedSessionsForProject:tr,availableWorktreesByProject:as,projectRepoStatus:D,projectRootBranches:Le,lastRepoStatus:cn.current,buildGroupedSessions:$s,hasSessionSearchQuery:Ye,normalizedSessionSearchQuery:qe,filterSessionNodesForSearch:us,buildGroupSearchText:Fs,foldersMap:xt}),Li=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")})]});n2({projectSections:rr,activeProjectId:De,activeSessionByProject:Be,setActiveSessionByProject:_e,currentSessionId:Ot,handleSessionSelect:Sn,newSessionDraftOpen:rs,mobileVariant:t,openNewSessionDraft:gs,setActiveMainTab:de,setSessionSwitcherOpen:Ne});const{getOrderedGroups:Rn}=r2(me),ur=i.useRef(!1);i.useEffect(()=>{if(ur.current||rr.length===0)return;const Z=rr.flatMap(it=>it.groups.filter(et=>et.isArchivedBucket).map(et=>`${it.project.id}:${et.id}`));Z.length>0&&q(it=>new Set([...it,...Z])),ur.current=!0},[rr]);const Ys=i.useMemo(()=>{const Z=new Map,it=new Map;return rr.forEach(et=>{const pt=Vm(et.project.label?.trim()||fo(et.project.normalizedPath,oe)||et.project.normalizedPath);et.groups.forEach(_t=>{const As=_t.branch&&_t.branch!=="HEAD"&&_t.branch!==pt?_t.branch:null,un={projectLabel:pt,branchLabel:As},kn=Cn=>{Cn.forEach(zn=>{const jr=et.project.normalizedPath.length,Ws=it.get(zn.session.id)??-1;jr<Ws||(Z.set(zn.session.id,{node:zn,projectId:et.project.id,groupDirectory:_t.directory,secondaryMeta:un}),it.set(zn.session.id,jr),zn.children.length>0&&kn(zn.children))})};kn(_t.sessions)})}),Z},[rr,oe]),Qs=i.useMemo(()=>!gn||Xe?[]:kk(Yt).sort((Z,it)=>Qi(Z,it,he)),[Xe,he,Yt,gn]),wr=i.useMemo(()=>{if(Xe||!gn)return[];const Z=Qs,it=pt=>{const _t=Ys.get(pt.id),As=ds(pt.directory??null),un=_t?.node??{session:pt,children:[],worktree:null},Cn=(Ye?us([un],qe):[un])[0];if(!Cn)return null;const zn=_t?.secondaryMeta?{projectLabel:_t.secondaryMeta.projectLabel,branchLabel:Xe?null:_t.secondaryMeta.branchLabel}:null;return{node:Cn,projectId:_t?.projectId??null,groupDirectory:_t?.groupDirectory??As,secondaryMeta:zn}},et=Z.map(it).filter(pt=>pt!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:et}]},[Qs,us,Ye,Xe,qe,Ys,gn,a]),go=i.useMemo(()=>wr.some(Z=>Z.items.length>0),[wr]),Pr=i.useMemo(()=>new Set(Qs.map(Z=>Z.id)),[Qs]),fr=i.useMemo(()=>[...Pr],[Pr]);pS({currentSessionId:Ot,sortedSessions:Cs,recentSessionIds:fr,ensureSessionRenderable:Je.ensureSessionRenderable});const yr=i.useMemo(()=>wn?ii:ii.map(Z=>({...Z,groups:Z.groups.filter(it=>!it.isArchivedBucket)})),[ii,wn]),yn=i.useMemo(()=>{const Z=new Set;return yr.forEach(it=>{it.groups.forEach(et=>{const pt=ds(et.directory??null),_t=et.branch?.trim()||bt.get(pt||"")?.trim();!pt||!_t||Z.add(Ro(pt,_t))})}),[...Z]},[bt,yr]),mr=qy(yn);i.useEffect(()=>{if(!qs||!Es?.connected||!fs)return;const Z=[],it=Date.now();if(yr.forEach(pt=>{k.has(pt.project.id)||pt.groups.forEach(_t=>{const As=ds(_t.directory??null),un=_t.branch?.trim()||bt.get(As||"")?.trim();if(!As||!un)return;const kn=Ro(As,un),Cn=lr.getState().entries[kn],zn=!!Cn?.status?.pr,jr=`${As}::${un}`,Ws=Math.max(Cn?.lastRefreshAt??0,Cn?.lastDiscoveryPollAt??0),wo=!!(Cn?.isInitialStatusResolved&&!zn&&(!p.current.has(jr)||it-Ws>=Pk));(!Cn||!Cn.isInitialStatusResolved||wo)&&(wo&&p.current.add(jr),Z.push({directory:As,branch:un}))})}),Z.length===0)return;const et=new Map;Z.forEach(pt=>{const _t=Ro(pt.directory,pt.branch,pt.remoteName??null);et.has(_t)||et.set(_t,pt)}),et.forEach((pt,_t)=>{$n(_t),ri(_t,{directory:pt.directory,branch:pt.branch,remoteName:pt.remoteName??null,canShow:!0,github:fs,githubAuthChecked:qs,githubConnected:Es.connected})}),pn([...et.values()],{silent:!0,markInitialResolved:!0})},[k,$n,fs,qs,Es?.connected,bt,pn,yr,ri]);const oi=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",Bi="h-4.5 w-4.5",dn=C2({isDesktopShellRuntime:cs,projectSections:rr,projectHeaderSentinelRefs:Ee}),Gr=Mr((Z,it=0,et,pt,_t=!1,As,un="project",kn)=>s.jsx(hk,{node:Z,depth:it,groupDirectory:et,projectId:pt,archivedBucket:_t,currentSessionId:Ot,pinnedSessionIds:he,expandedParents:j,hasSessionSearchQuery:Ye,normalizedSessionSearchQuery:qe,notifyOnSubtasks:se,editingId:x,setEditingId:b,editTitle:w,setEditTitle:g,handleSaveEdit:Dr,handleCancelEdit:_n,toggleParent:Is,handleSessionSelect:ws,handleSessionDoubleClick:Ls,togglePinnedSession:z,handleShareSession:bn,copiedSessionId:Bn,handleCopyShareUrl:Tr,handleUnshareSession:si,openSidebarMenuKey:L,setOpenSidebarMenuKey:M,renamingFolderId:ee,getFoldersForScope:vt,getSessionFolderId:ot,removeSessionFromFolder:ns,addSessionToFolder:Ut,createFolderAndStartRename:zr,openContextPanelTab:fe,handleDeleteSession:ni,mobileVariant:t,alwaysShowActions:Vt,renderSessionNode:Gr,secondaryMeta:As,renderContext:un,subtreeContainsActive:kn?.subtreeContainsActive??Rf,subtreeContainsEditing:kn?.subtreeContainsEditing??Rf,menuOpenSessionId:kn?.menuOpenSessionId??null,nodeStructureKey:kn?.nodeStructureKey??"",childRenderExtrasFor:kn?.childRenderExtrasFor,liveSessionById:wt})),Vi=i.useCallback(Z=>{ys(Z),q(it=>{const et=new Set(it);return et.has(Z)?et.delete(Z):et.add(Z),et})},[ys]),_i=i.useMemo(()=>{const Z=new Map;for(const[it,et]of mr)Z.set(it,{visualState:et.visualState,number:et.number,url:et.url,state:et.prState,draft:et.draft,title:et.title,base:et.base,head:et.head,checks:et.checks,canMerge:et.canMerge,mergeableState:et.mergeableState,repo:et.repo});return Z},[mr]),Q=i.useCallback((Z,it,et,pt,_t,As,un)=>s.jsx(sN,{group:Z,groupKey:it,projectId:et,hideGroupLabel:pt,compactBodyPadding:As,hasSessionSearchQuery:Ye,normalizedSessionSearchQuery:qe,groupSearchDataByGroup:Hr,visibleSessionCount:v.get(it),collapsedGroups:K,hideDirectoryControls:r,collapsedFolderIds:tt,toggleFolderCollapse:Ce,renameFolder:Tt,deleteFolder:Kt,showDeletionDialog:Oe,setDeleteFolderConfirm:ve,renderSessionNode:Gr,projectRepoStatus:D,lastRepoStatus:cn.current,showMoreGroupSessions:cr,resetGroupSessionLimit:ys,mobileVariant:t,alwaysShowActions:Vt,activeProjectId:De,setActiveProjectIdOnly:_,setActiveMainTab:de,setSessionSwitcherOpen:Ne,openNewSessionDraft:Ft,addSessionToFolder:Ut,createFolderAndStartRename:zr,renamingFolderId:ee,renameFolderDraft:X,setRenameFolderDraft:H,setRenamingFolderId:ie,pinnedSessionIds:he,expandedParents:j,sessionOrderIndex:xe,currentSessionId:Ot,editingId:x,editTitle:w,openSidebarMenuKey:L,liveSessionById:wt,prVisualStateByDirectoryBranch:_i,onToggleCollapsedGroup:Vi,dragHandleProps:_t,scrollContainerRef:un}),[Ye,qe,Hr,v,K,r,tt,Ce,Tt,Kt,Oe,Gr,D,cr,ys,t,Vt,De,_,de,Ne,Ft,Ut,zr,ee,X,he,j,xe,Ot,x,w,L,wt,_i,Vi]),ke=!Xe&&gn&&!Ye?s.jsx(mN,{sections:wr,renderSessionNode:Gr,currentSessionId:Ot,editingId:x,openSidebarMenuKey:L,variant:"section"}):null,Ie=!!(ee||x||h),{selectionModeEnabled:$e,hasSelection:ft,selectedIdsSize:It,bulkScopeIsArchived:Qt,derivedSelectionScope:Jt,bulkScopeFolders:vs,bulkCanRemoveFromFolder:vr,handleToggleSelectionMode:Ir,handleExitSelectionMode:Rr,handleBulkMoveToFolder:sl,handleBulkCreateFolderAndMove:nl,handleBulkRemoveFromFolder:Yn,handleBulkDelete:Er,confirmBulkDelete:vi}=yk({isInlineEditing:Ie,showDeletionDialog:Oe,foldersMap:xt,addSessionsToFolder:Zt,removeSessionsFromFolders:es,createFolderAndStartRename:Vn,archiveSessions:Pn,deleteSessions:Tn,setBulkDeleteConfirm:we}),ai=i.useCallback(()=>{de("chat"),t&&Ne(!1),F()},[t,F,de,Ne]),ji=i.useCallback(()=>{de("chat"),t&&Ne(!1),gs()},[t,gs,de,Ne]);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(nN,{hideDirectoryControls:r,showRecentControls:!Xe,handleOpenDirectoryDialog:Ks,openNewSessionDraft:ji,canOpenMultiRun:ue.length>0,openMultiRunLauncher:ai,headerActionIconClass:Bi,headerActionButtonClass:oi,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:Ye,searchMatchCount:Oi,collapseAllProjects:dr,expandAllProjects:J,openScheduledTasksDialog:()=>Y(!0),selectionModeEnabled:$e,onToggleSelectionMode:Ir}),s.jsx(vN,{topContent:ke,hasSharedSessions:go,sectionsForRender:yr,projectSections:rr,activeProjectId:De,showOnlyMainWorkspace:o,hasSessionSearchQuery:Ye,emptyState:dt,searchEmptyState:Li,renderGroupSessions:Q,homeDirectory:oe,collapsedProjects:k,hideDirectoryControls:r,projectRepoStatus:D,isDesktopShellRuntime:cs,stuckProjectHeaders:dn,mobileVariant:t,alwaysShowActions:Vt,toggleProject:at,setActiveProjectIdOnly:_,setActiveMainTab:de,setSessionSwitcherOpen:Ne,openNewSessionDraft:Ft,openNewWorktreeDialog:gt,openProjectEditDialog:C,removeProject:I,projectHeaderSentinelRefs:Ee,reorderProjects:R,projectSortOrder:sr,getOrderedGroups:Rn,setGroupOrderByProject:Se,openSidebarMenuKey:L,setOpenSidebarMenuKey:M,isInlineEditing:Ie}),$e&&ft?s.jsx(wk,{selectedCount:It,scopeKey:Jt,scopeFolders:vs,archivedBucket:Qt,onMoveToFolder:sl,onCreateFolderAndMove:nl,onRemoveFromFolder:Yn,canRemoveFromFolder:vr,onDelete:Er,onDone:Rr}):null,s.jsx(hN,{onOpenSettings:Ss,onOpenShortcuts:Ae,onOpenAbout:()=>Ve(!0),onOpenUpdate:xs,onOpenShareOpinion:bs,showRuntimeButtons:!Xe,showUpdateButton:Ns}),s.jsx(T2,{open:W,onOpenChange:U}),s.jsx(Rm,{open:B,onOpenChange:T,info:Lt.info,downloading:Lt.downloading,downloaded:Lt.downloaded,progress:Lt.progress,error:Lt.error,onDownload:Lt.downloadUpdate,onRestart:Lt.restartToUpdate,runtimeType:Lt.runtimeType}),s.jsx(A2,{open:!!jt,onOpenChange:Z=>{Z||C(null)},project:jt,onSave:zt}),s.jsx(ab,{open:P,onOpenChange:E,onWorktreeCreated:(Z,it)=>{if(de("chat"),t&&Ne(!1),it?.sessionId){Wt(it.sessionId,Z);return}gs({directoryOverride:Z,preserveDirectoryOverride:!0})}}),s.jsx(QS,{}),s.jsx(gk,{value:te,setValue:re,showDeletionDialog:Oe,setShowDeletionDialog:ce,onConfirm:Rs}),s.jsx(bk,{value:le,setValue:ve,onConfirm:rn}),s.jsx(xk,{value:ne,setValue:we,showDeletionDialog:Oe,setShowDeletionDialog:ce,onConfirm:vi})]})},Ci=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,kr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Ik=()=>{const{t}=yt(),[e,n]=i.useState(!1),[r,o]=i.useState(!1),[a,c]=i.useState(null),[l,d]=i.useState([]),[f,m]=i.useState(!1),[u,p]=i.useState(!1),[x,b]=i.useState(!1),[w,g]=i.useState(!1),[h,C]=i.useState(new Set),j=mt(oe=>oe.getWorktreeMetadata),S=mt(oe=>oe.newSessionDraft),N=mt(oe=>oe.setNewSessionDraftTarget),k=mt(oe=>oe.setDraftBootstrapPendingDirectory),y=lx,D=ux,V=mt(oe=>oe.deleteSessions),v=mt(oe=>oe.archiveSessions),O=Re(oe=>oe.showDeletionDialog),P=Re(oe=>oe.setShowDeletionDialog),E=Xs(oe=>oe.currentDirectory),B=Xs(oe=>oe.homeDirectory),T=Xs(oe=>oe.isHomeReady),W=Ds(oe=>oe.projects),U=Ds(oe=>oe.activeProjectId),{isMobile:L,isTablet:M,hasTouchInput:ee}=$r(),ie=L||M||ee,X=i.useMemo(()=>{const je=(U?W.find(ye=>ye.id===U)??null:null)?.path??E;return kr(je)},[U,E,W]),H=i.useCallback(oe=>{const ye=kr(oe.projectDirectory)||X;return{id:(W.find(De=>kr(De.path)===ye)??null)?.id??`path:${ye}`,path:ye}},[X,W]),te=w&&h.size>0,re=i.useMemo(()=>{const oe=a?.worktree;return oe&&typeof oe.branch=="string"&&oe.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:je})=>typeof je.branch=="string"&&je.branch.trim().length>0)},[a?.worktree,l]),le=a?.mode==="worktree",ve=le,ne=x||!le||!re,we=x||!le;i.useEffect(()=>{r||!T||W.length>0||(o(!0),n(!0))},[r,T,W.length]);const he=i.useCallback(oe=>{c({sessions:oe.sessions,dateLabel:oe.dateLabel,mode:oe.mode??"session",worktree:oe.worktree??null})},[]),Me=i.useCallback(()=>{c(null),d([]),m(!1),p(!1),b(!1),g(!1),C(new Set)},[]),z=i.useCallback(async oe=>{if(oe.sessions.length===0)return;if(oe.sessions.length===1){const De=oe.sessions[0];await y(De.id)?ae.success(t("sessions.sidebar.session.delete.success")):ae.error(t("sessions.sidebar.session.delete.error"));return}const je=oe.sessions.map(De=>De.id),{deletedIds:ye,failedIds:ue}=await V(je);if(ye.length>0){const De=ue.length>0?ue.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:ue.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:ue.length}):oe.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:oe.dateLabel}):void 0;ae.success(ye.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:ye.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:ye.length}),{description:Ci(De)})}ue.length>0&&ae.error(ue.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:ue.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:ue.length}),{description:Ci(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[y,V,t]);i.useEffect(()=>Lr.onDeleteRequest(oe=>{if(!O&&(oe.mode??"session")==="session"){z(oe);return}he(oe)}),[he,O,z]),i.useEffect(()=>Lr.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1),p(!1),g(!1),C(new Set);return}const oe=a.sessions.map(ue=>{const De=j(ue.id);return De?{session:ue,metadata:De}:null}).filter(ue=>!!ue);d(oe),m(!1),g(!1),C(new Set);const je=new Map;if(a.worktree?.path&&je.set(kr(a.worktree.path),a.worktree),oe.forEach(({metadata:ue})=>{ue.path&&je.set(kr(ue.path),ue)}),je.size===0){g(!0);return}let ye=!1;return(async()=>{const ue=new Map,De=new Set;await Promise.all(Array.from(je.entries()).map(async([I,_])=>{try{const be=await cx(_.path);ue.set(I,be),be?.isDirty&&De.add(I)}catch{_.status&&(ue.set(I,_.status),_.status.isDirty&&De.add(I))}})).catch(I=>{console.warn("Failed to inspect worktree status before deletion:",I)}),!ye&&(C(De),g(!0),c(I=>{if(!I?.worktree?.path)return I;const _=kr(I.worktree.path),be=ue.get(_);if(!be)return I;const R=I.worktree.status;return R?.isDirty===be.isDirty&&R?.ahead===be.ahead&&R?.behind===be.behind&&R?.upstream===be.upstream?I:{...I,worktree:{...I.worktree,status:be}}}),d(I=>I.map(_=>{const be=kr(_.metadata.path),R=ue.get(be);return R?{session:_.session,metadata:{..._.metadata,status:R}}:_})))})(),()=>{ye=!0}},[a,j]),i.useEffect(()=>{re||m(!1)},[re]);const K=i.useCallback(async(oe,je)=>{const ye=f&&re,ue=H(oe),De=kr(oe.path),I=kr(ue.path);try{await dx(ue,oe,{deleteRemoteBranch:ye,deleteLocalBranch:je});const _=kr(S?.directoryOverride);return S?.open&&De&&_===De&&I&&(k(null),N({projectId:ue.id,directoryOverride:I},{force:!0})),kr(E)===De&&I&&Xs.getState().setDirectory(I,{showOverlay:!1}),!0}catch(_){return ae.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:Ci(_ instanceof Error?_.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[re,E,f,H,S?.directoryOverride,S?.open,k,N,t]),q=i.useCallback((oe,je)=>{const ye=f&&re;(async()=>{if(!await K(oe,je))return;const De=t(ye?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");ae.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:Ci(De)})})()},[re,f,K,t]),me=i.useCallback(async()=>{if(a){b(!0);try{const oe=ve,je=oe&&f,ye=oe&&u;if(a.sessions.length===0&&le&&a.worktree){q(a.worktree,ye),Me();return}if(a.sessions.length===1){const ue=a.sessions[0];if(!(le?await D(ue.id):await y(ue.id,{archiveWorktree:!1,deleteRemoteBranch:je,deleteLocalBranch:ye}))){ae.error(t(le?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),b(!1);return}const I=!le&&oe?t(je?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;ae.success(t(le?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:Ci(I),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const ue=a.sessions.map(_=>_.id);let De=[],I=[];if(le){const _=await v(ue);De=_.archivedIds,I=_.failedIds}else{const _=await V(ue);De=_.deletedIds,I=_.failedIds}if(le&&a.worktree&&I.length===0&&q(a.worktree,ye),De.length>0){const _=!le&&oe?t(je?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,R=[I.length>0?le?I.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:I.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:I.length}):I.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:I.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:I.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,_].filter(Boolean).join(" ");ae.success(le?De.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:De.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:De.length}):De.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:De.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:De.length}),{description:Ci(R||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if(I.length>0&&(ae.error(le?I.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:I.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:I.length}):I.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:I.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:I.length}),{description:Ci(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),De.length===0)){b(!1);return}}le&&a.sessions.length===1&&a.worktree&&q(a.worktree,ye),Me()}finally{b(!1)}}},[a,f,u,y,V,D,v,Me,ve,le,q,t]),Se=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}):"",_e=a?s.jsxs("div",{className:Pe(le?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:Pe(le?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[le&&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(le?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(oe=>s.jsxs("li",{className:Pe(le?"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(!le&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:oe.title||t("sessions.sidebar.session.untitled")})]},oe.id)),a.sessions.length>5&&s.jsx("li",{className:Pe(le?"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})})]})]}),le?s.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(A,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:t("sessions.sidebar.sessionDialogs.worktree.label")}),Se?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Se.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Se?Pa(Se.path,B):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),te&&s.jsx("p",{className:"typography-micro text-status-warning",children:t("sessions.sidebar.sessionDialogs.worktree.uncommittedWarning")})]}):s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:t("sessions.sidebar.sessionDialogs.delete.note")})})]}):null,Le=le?re?s.jsxs("button",{type:"button",onClick:()=>{ne||m(oe=>!oe)},disabled:ne,className:Pe("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ne?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[f?s.jsx(A,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(A,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteRemoteBranch")]}):s.jsx("span",{className:"text-xs text-muted-foreground/70",children:t("sessions.sidebar.sessionDialogs.actions.remoteBranchInfoUnavailable")}):null,pe=le?s.jsxs("button",{type:"button",onClick:()=>{we||p(oe=>!oe)},disabled:we,className:Pe("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",we?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(A,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(A,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Ee=le?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:[pe,Le]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{variant:"ghost",onClick:Me,disabled:x,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{variant:"destructive",onClick:me,disabled:x,children:t(x?"sessions.sidebar.sessionDialogs.actions.deleting":"sessions.sidebar.sessionDialogs.actions.deleteWorktree")})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>P(!O),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":!O,children:[O?s.jsx(A,{name:"checkbox-blank",className:"size-4"}):s.jsx(A,{name:"checkbox",className:"size-4 text-primary"}),t("sessions.sidebar.dialogs.neverAsk")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ze,{variant:"ghost",onClick:Me,disabled:x,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(ze,{variant:"destructive",onClick:me,disabled:x,children:x?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),ge=le?t("sessions.sidebar.sessionDialogs.actions.deleteWorktree"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction");return s.jsxs(s.Fragment,{children:[ie?s.jsx(Ya,{open:!!a,onClose:()=>{x||Me()},title:ge,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Ee}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[Be&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Be}),_e]})}):s.jsx(_s,{open:!!a,onOpenChange:oe=>{if(!oe){if(x)return;Me()}},children:s.jsxs(Vs,{className:Pe(le?"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(sn,{children:[s.jsxs(Hs,{className:Pe(le&&"flex items-center gap-2"),children:[le&&s.jsx(A,{name:"delete-bin",className:"h-5 w-5"}),ge]}),Be&&s.jsx(mn,{children:Be})]}),s.jsx("div",{className:Pe(le&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:_e}),s.jsx(br,{className:"mt-2 gap-2 pt-1 pb-1",children:Ee})]})}),s.jsx(lb,{open:e,onOpenChange:n})]})},pc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),Rk=(t,e)=>{const n=pc(t),r=pc(e);return`${n}-${r}`.substring(0,60)},Mf=(t,e)=>`${t}/${e}`,Ek=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},Ff=(t,e)=>{const n=Ek(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};wx(t.id,n),mt.getState().markSessionAsOpenChamberCreated(t.id),pr.getState().upsertSession(o);try{Ia().ensureChild(n,{bootstrap:!1}).setState(c=>{const l=c.session.findIndex(f=>f.id===t.id);if(l>=0&&c.session[l]===o)return c;const d=l>=0?c.session.map((f,m)=>m===l?o:f):[...c.session,o].sort((f,m)=>f.id.localeCompare(m.id));return{session:d,sessionTotal:Math.max(c.sessionTotal,d.length),limit:Math.max(c.limit,d.length)}})}catch{}return o},Mk=()=>{const t=Ds.getState(),e=t.activeProjectId;if(!e)return null;const n=t.projects.find(o=>o.id===e);if(n?.path)return{id:n.id,path:n.path};const r=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},$l=co()(Hf(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=Mk();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,m=await Nm(d)&&e.isolateRuns!==!1,u=pc(n),p=m?await Xa(d):void 0,x=m?await fx(d):null,b=[],w=c?.filter(S=>S.trim().length>0)??[];for(let S=0;S<r.length;S++){const N=r[S],k=N.prompt,y=new Map;for(const V of N.models){const v=`${V.providerID}:${V.modelID}`;y.set(v,(y.get(v)||0)+1)}const D=new Map;for(const V of N.models){const v=`${V.providerID}:${V.modelID}`,O=y.get(v)||1,P=(D.get(v)||0)+1;D.set(v,P);const E=Rk(V.providerID,V.modelID),B=r.length>1?`g${S+1}`:void 0,T=O>1?Mf(u,`${E}/${P}`):Mf(u,E),W=B?`${B}/${T}`:T,U=WN({groupSlug:u,runGroup:B,providerID:V.providerID,modelID:V.modelID,index:O>1?P:void 0});try{if(!m){const ie=await Xn.withDirectory(d,()=>Xn.createSession({title:U}));Ff(ie,d),b.push({sessionId:ie.id,worktreePath:d,providerID:V.providerID,modelID:V.modelID,variant:V.variant,prompt:k});continue}const L=await mx(l,{preferredName:W,mode:"new",branchName:W,worktreeName:W,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:w,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:x}),M={...L,createdFromBranch:p,kind:"standard"};await hx(l)&&await px(L.path);const ee=await Xn.withDirectory(L.path,()=>Xn.createSession({title:U}));Ff(ee,L.path),mt.getState().setWorktreeMetadata(ee.id,M),b.push({sessionId:ee.id,worktreePath:L.path,providerID:V.providerID,modelID:V.modelID,variant:V.variant,prompt:k})}catch(L){console.warn("[MultiRun] Failed to create session:",L)}}}const g=c?.filter(S=>S.trim().length>0)??[];g.length>0&&gx(l,g).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const h=b.map(S=>S.sessionId),C=b[0]?.sessionId??null;if(h.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const j=a?.map(S=>({type:"file",mime:S.mime,filename:S.filename,url:S.url}));return(async()=>{try{const S=xx.getState().expandText;await Promise.allSettled(b.map(async N=>{try{const k=await S(N.prompt).catch(()=>N.prompt);await bx({sessionId:N.sessionId,directory:N.worktreePath,content:k,providerID:N.providerID,modelID:N.modelID,variant:N.variant,agent:o,files:j})}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(S){console.warn("[MultiRun] Failed to start runs:",S)}})(),t({isLoading:!1}),{groupSlug:u,sessionIds:h,firstSessionId:C}}catch(l){return t({error:l instanceof Error?l.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"}));function Oh(t){const e=ht.c(30),{git:n}=Zn(),r=um(t),o=Pc(t),a=Ic(t),c=yx(t),l=vn(Vk),d=vn(Bk);let f,m;e[0]!==t||e[1]!==d||e[2]!==n||e[3]!==o||e[4]!==a?(f=()=>{!t||!n||o!==null||a||d(t,n,{silent:!0})},m=[t,n,d,o,a],e[0]=t,e[1]=d,e[2]=n,e[3]=o,e[4]=a,e[5]=f,e[6]=m):(f=e[5],m=e[6]),i.useEffect(f,m);let u;e[7]!==r?.all||e[8]!==t||e[9]!==l||e[10]!==n||e[11]!==o?(u=()=>{!t||!n||o===!0&&(r?.all||l(t,n))},e[7]=r?.all,e[8]=t,e[9]=l,e[10]=n,e[11]=o,e[12]=u):u=e[12];const p=r?.all;let x;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==p?(x=[t,n,o,p,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=p,e[18]=x):x=e[18],i.useEffect(u,x);const b=a||o===!0&&c;let w;e:{if(!r?.all){let y;e[19]===Symbol.for("react.memo_cache_sentinel")?(y=[],e[19]=y):y=e[19],w=y;break e}let k;e[20]!==r.all?(k=r.all.filter(Lk).sort(),e[20]=r.all,e[21]=k):k=e[21],w=k}const g=w;let h;e:{if(!r?.all){let y;e[22]===Symbol.for("react.memo_cache_sentinel")?(y=[],e[22]=y):y=e[22],h=y;break e}let k;e[23]!==r.all?(k=r.all.filter(Ok).map(Fk).sort(),e[23]=r.all,e[24]=k):k=e[24],h=k}const C=h;let j;e:{if(!t){j=null;break e}if(o!==null){j=o;break e}if(b){j=null;break e}j=r?.all?!0:null}const S=j;let N;return e[25]!==S||e[26]!==b||e[27]!==g||e[28]!==C?(N={localBranches:g,remoteBranches:C,isLoading:b,isGitRepository:S},e[25]=S,e[26]=b,e[27]=g,e[28]=C,e[29]=N):N=e[29],N}function Fk(t){return t.replace(/^remotes\//,"")}function Ok(t){return t.startsWith("remotes/")}function Lk(t){return!t.startsWith("remotes/")}function Bk(t){return t.fetchStatus}function Vk(t){return t.fetchBranches}const _k=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=yt(),{localBranches:l,remoteBranches:d,isLoading:f,isGitRepository:m}=Oh(t),u=i.useMemo(()=>[...l,...d.map(x=>`remotes/${x}`)],[l,d]);i.useEffect(()=>{if(o||f||u.length===0||e&&u.includes(e))return;const x=e;let b=!1;return(async()=>{try{const g=t?await Xa(t).catch(()=>null):null;if(b)return;const h=localStorage.getItem(iu),{sourceBranch:C,shouldClearSavedSourceBranch:j}=cb({branches:u,savedSourceBranch:h,rootBranch:g});if(j&&localStorage.removeItem(iu),b||x&&u.includes(x))return;C&&n(C)}catch{}})(),()=>{b=!0}},[u,t,o,f,n,e]);const p=o||!m||f;return s.jsxs("div",{children:[s.jsxs(Gn,{value:e,onValueChange:n,disabled:p,children:[s.jsx(Kn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(Dn,{placeholder:c(f?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(qn,{className:"max-h-[280px] max-w-[320px]",children:f?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.loadingBranches")}):l.length===0&&d.length===0?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.noBranchesFound")}):s.jsxs(s.Fragment,{children:[l.length>0&&s.jsxs(Ql,{children:[s.jsx(Qd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(x=>s.jsx(Bs,{value:x,className:"whitespace-normal break-all",children:x},x))]}),l.length>0&&d.length>0&&s.jsx(vx,{}),d.length>0&&s.jsxs(Ql,{children:[s.jsx(Qd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(x=>s.jsx(Bs,{value:`remotes/${x}`,className:"whitespace-normal break-all",children:x},`remotes/${x}`))]})]})})]}),m===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},$k=10*1024*1024,zl=5,va=t=>{const e=ht.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",tabIndex:-1,className:"inline-flex items-center justify-center text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:s.jsx(A,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(Ct,{children:[r,s.jsx(Dt,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},Ti=t=>{const e=ht.c(9),{htmlFor:n,required:r,children:o,info:a}=t;let c;e[0]!==r?(c=r&&s.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),e[0]=r,e[1]=c):c=e[1];let l;e[2]!==o||e[3]!==n||e[4]!==c?(l=s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,c]}),e[2]=o,e[3]=n,e[4]=c,e[5]=l):l=e[5];const d=a&&a;let f;return e[6]!==l||e[7]!==d?(f=s.jsxs("div",{className:"flex items-center gap-1.5",children:[l,d]}),e[6]=l,e[7]=d,e[8]=f):f=e[8],f},zk=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=yt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:Fo(),prompt:"",models:[]}]),[f,m]=i.useState(""),[u,p]=i.useState([]),[x,b]=i.useState(!1),[w,g]=i.useState([]),[h,C]=i.useState(!1),[j,S]=i.useState(!1),[N,k]=i.useState(!0),y=i.useRef(null),D=Xs(I=>I.currentDirectory??null),V=Xs(I=>I.homeDirectory??null),v=i.useMemo(()=>{if(typeof window>"u")return null;const I=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof I=="string"&&I.trim().length>0?I.trim():null},[]),O=Ds(I=>I.activeProjectId),P=Ds(I=>I.setActiveProjectIdOnly),E=Ds(I=>I.projects),[B,T]=i.useState(()=>O??null);i.useEffect(()=>{if(O){T(O);return}!B&&E.length>0&&T(E[0].id)},[O,E,B]);const W=i.useMemo(()=>B?E.find(I=>I.id===B)??null:null,[E,B]),U=W?.path??D,L=i.useCallback(I=>{T(I),I!==O&&P(I)},[O,P]),{currentTheme:M}=yi(),ee=i.useCallback(I=>{const _=I.label?.trim()||fo(I.path,V),be=I.icon?Oc[I.icon]:null,R=I.color?Lc[I.color]:void 0,de=be?s.jsx(A,{name:be,className:"h-3.5 w-3.5 shrink-0",style:R?{color:R}:void 0}):s.jsx(A,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:R?{color:R}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[I.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:I.iconBackground?{backgroundColor:I.iconBackground}:void 0,children:s.jsx(Bc,{project:{id:I.id,iconImage:I.iconImage??null},options:{themeVariant:M.metadata.variant,iconColor:M.colors.surface.foreground},className:"h-full w-full object-contain",fallback:de})}):de,s.jsx("span",{className:"truncate",children:_})]})},[V,M.metadata.variant,M.colors.surface.foreground]),ie=i.useMemo(()=>{if(W?.path)return{id:W.id,path:W.path};const I=D??v;return I?{id:`path:${I}`,path:I}:null},[W,D,v]),[X]=i.useState(()=>typeof window<"u"?gr():!1),H=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),te=rm(),re=i.useMemo(()=>{if(typeof window>"u")return null;const I=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof I=="number"&&Number.isFinite(I)&&I>0)return I;if(typeof navigator>"u")return null;const _=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!_)return null;const be=Number.parseInt(_[1],10),R=Number.parseInt(_[2],10);return Number.isNaN(be)?null:be===10?R:be},[]),le=i.useMemo(()=>X&&H||te?"pl-[5.5rem]":"pl-3",[X,H,te]),ve=i.useMemo(()=>!X||!H||re===null?"":re>=26?"h-12":re<=15?"h-14":"",[X,H,re]),ne=i.useCallback(async I=>{I.target.closest("button, a, input, select, textarea")||I.button===0&&X&&await jx()},[X]);i.useEffect(()=>{if(!n)return;const I=_=>{_.key==="Escape"&&(_.preventDefault(),_.stopPropagation(),n())};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[n]);const[we,he]=i.useState(""),{isLoading:Me,isGitRepository:z}=Oh(U),K=i.useRef(!1),q=z===!0,me=q&&N;i.useEffect(()=>{if(z===!1){K.current=!0,k(!1);return}z===!0&&K.current&&(K.current=!1,k(!0))},[z]);const Se=$l(I=>I.createMultiRun),Be=$l(I=>I.error),_e=$l(I=>I.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d(I=>{const _=[...I];return _.length>0&&!_[0].prompt.trim()&&(_[0]={..._[0],prompt:t}),_})},[t]),i.useEffect(()=>{if(!ie)return;let I=!1;return S(!0),(async()=>{try{const _=await Sx(ie);I||g(_)}catch{}finally{I||S(!1)}})(),()=>{I=!0}},[ie]);const Le=i.useCallback((I,_)=>{d(be=>be.map(R=>R.id===I?{...R,..._}:R))},[]),pe=i.useCallback(I=>{d(_=>_.filter(be=>be.id!==I))},[]),Ee=i.useCallback(()=>{d(I=>[...I,{id:Fo(),prompt:"",models:[]}])},[]),ge=async I=>{const _=I.target.files;if(!_)return;let be=0;for(let R=0;R<_.length;R++){const de=_[R];if(de.size>$k){ae.error(o("multirun.launcher.toast.fileTooLarge",{fileName:de.name}));continue}try{const fe=await new Promise(($,Ae)=>{const Ve=new FileReader;Ve.onload=()=>$(Ve.result),Ve.onerror=Ae,Ve.readAsDataURL(de)});p($=>[...$,{id:Fo(),filename:de.name,mimeType:de.type||"application/octet-stream",size:de.size,dataUrl:fe}]),be++}catch(fe){console.error("File attach failed",fe),ae.error(o("multirun.launcher.toast.attachFailed",{fileName:de.name}))}}be>0&&ae.success(be===1?o("multirun.launcher.toast.attachedSingle",{count:be}):o("multirun.launcher.toast.attachedPlural",{count:be})),y.current&&(y.current.value="")},oe=I=>{p(_=>_.filter(be=>be.id!==I))},je=i.useMemo(()=>l.reduce((I,_)=>I+_.models.length,0),[l]),ye=async I=>{I.preventDefault();const _=l.filter(be=>be.prompt.trim()&&be.models.length>=1);if(_.length!==0&&!(je<1)){b(!0),_e();try{B&&B!==O&&P(B);const be=u.map(Ae=>({mime:Ae.mimeType,filename:Ae.filename,url:Ae.dataUrl})),R=w.filter(Ae=>Ae.trim().length>0),de=_.map(Ae=>({prompt:Ae.prompt.trim(),models:Ae.models.map(Ve=>({providerID:Ve.providerID,modelID:Ve.modelID,displayName:Ve.displayName,variant:Ve.variant}))})),fe={name:a.trim(),groups:de,agent:f||void 0,worktreeBaseBranch:me?we:void 0,isolateRuns:me,files:be.length>0?be:void 0,setupCommands:R.length>0?R:void 0},$=await Se(fe);$&&($.firstSessionId&&mt.getState().setCurrentSession($.firstSessionId),e?.())}finally{b(!1)}}},ue=!!(a.trim()&&l.some(I=>I.prompt.trim()&&I.models.length>=1)&&je>=1&&U&&!Me&&(z===!1||!me||we)),De=w.filter(I=>I.trim()).length;return s.jsxs("form",{onSubmit:ye,className:"flex flex-col h-full bg-background",children:[r?null:s.jsxs("header",{onMouseDown:ne,className:Pe("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",le,ve),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(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":o("multirun.launcher.actions.closeEsc"),className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:s.jsx(A,{name:"close",className:"h-5 w-5"})})}),s.jsx(Dt,{children:s.jsx("p",{children:o("multirun.launcher.actions.closeEsc")})})]})})]}),s.jsx(Qa,{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(Ti,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),E.length>0?s.jsxs(Gn,{value:B??void 0,onValueChange:L,children:[s.jsx(Kn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:W?s.jsx(Dn,{children:ee(W)}):s.jsx(Dn,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(qn,{fitContent:!0,children:E.map(I=>s.jsx(Bs,{value:I.id,className:"max-w-[24rem]",children:ee(I)},I.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(Ti,{htmlFor:"group-name",required:!0,info:s.jsx(va,{children:o("multirun.launcher.groupName.info")}),children:o("multirun.launcher.groupName.label")}),s.jsx(Ln,{id:"group-name",value:a,onChange:I=>c(I.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(Ti,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(va,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(_k,{directory:U,value:we,onChange:he,disabled:!me,id:"multirun-worktree-base-branch"}),s.jsxs("label",{className:"mt-1.5 flex w-fit items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(Or,{checked:N,onChange:k,disabled:!q,ariaLabel:o("multirun.launcher.isolateRuns.label")}),s.jsx("span",{children:o("multirun.launcher.isolateRuns.label")})]})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Ti,{htmlFor:"multirun-agent",info:s.jsx(va,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(Rh,{value:f,onChange:m,id:"multirun-agent"})]})]}),s.jsxs(ro,{open:h,onOpenChange:C,children:[s.jsxs(Uo,{className:"w-full flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-lg hover:bg-[var(--interactive-hover)]/50 transition-colors group",children:[s.jsx(A,{name:"terminal",className:"h-3.5 w-3.5 text-muted-foreground/70"}),s.jsx("span",{className:"typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors",children:o("multirun.launcher.setupCommands.label")}),De>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:De}),s.jsx(A,{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(io,{children:s.jsx("div",{className:"pt-2 space-y-1.5",children:j?s.jsx("p",{className:"typography-meta text-muted-foreground/70 px-2",children:o("multirun.launcher.setupCommands.loading")}):s.jsxs(s.Fragment,{children:[w.map((I,_)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(Ln,{value:I,onChange:be=>{const R=[...w];R[_]=be.target.value,g(R)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>g(w.filter((be,R)=>R!==_)),className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":o("multirun.launcher.setupCommands.removeCommandAria"),children:s.jsx(A,{name:"close",className:"h-3.5 w-3.5"})})]},`${I}-${_}`)),s.jsxs("button",{type:"button",onClick:()=>g([...w,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(A,{name:"add",className:"h-3 w-3"}),o("multirun.launcher.setupCommands.addCommand")]})]})})})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Ti,{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:y,type:"file",multiple:!0,className:"hidden",onChange:ge,accept:"*/*"}),s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>y.current?.click(),className:"inline-flex items-center gap-1 h-6 px-2 rounded-md typography-micro text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(A,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(Dt,{children:o("multirun.launcher.attachments.tooltip")})]}),u.map(I=>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:[I.mimeType.startsWith("image/")?s.jsx(A,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(A,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:I.filename,children:I.filename}),s.jsx("button",{type:"button",onClick:()=>oe(I.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(A,{name:"close",className:"h-3 w-3"})})]},I.id))]})]}),l.map((I,_)=>s.jsx(Wk,{group:I,groupIndex:_,canRemove:l.length>1,onUpdate:Le,onRemove:pe},I.id)),s.jsxs("button",{type:"button",onClick:Ee,className:"flex items-center gap-1.5 py-2 px-3 -mx-3 rounded-lg typography-meta font-medium text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(A,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),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:[!me&&z!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(A,{name:"information",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:o("multirun.launcher.project.gitRequired")})]}):null,s.jsx(ze,{type:"button",variant:"ghost",size:"sm",onClick:n,children:o("multirun.launcher.actions.cancel")}),s.jsx(ze,{type:"submit",size:"sm",disabled:!ue||x,children:x?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:je})})})]})})]})},Wk=t=>{const e=ht.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=yt(),[d,f]=i.useState(!1),[m,u]=i.useState(""),[p,x]=i.useState(!1),[b,w]=i.useState(""),[g,h]=i.useState(!1),[C,j]=i.useState(""),S=i.useRef(null),N=i.useRef(null),k=i.useRef(null),y=i.useRef(null);let D;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(D=R=>{n.models.length>=zl||a(n.id,{models:[...n.models,R]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=D):D=e[3];const V=D;let v;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(v=R=>{a(n.id,{models:n.models.filter((de,fe)=>fe!==R)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=v):v=e[7];const O=v;let P;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(P=(R,de)=>{a(n.id,{models:n.models.map((fe,$)=>$===R?de:fe)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=P):P=e[11];const E=P;let B;e[12]===Symbol.for("react.memo_cache_sentinel")?(B=(R,de)=>{if(R.startsWith("/")){const Ve=R.indexOf(" "),Ne=R.indexOf(`
234
+ `),Y=Math.min(Ve===-1?R.length:Ve,Ne===-1?R.length:Ne);if(de<=Y&&Ve===-1){w(R.substring(1,Y)),x(!0),f(!1),h(!1);return}}x(!1);const fe=R.substring(0,de),$=fe.lastIndexOf("#");if($!==-1){const Ve=$>0?fe[$-1]:null,Ne=fe.substring($+1);if((!Ve||/\s/.test(Ve))&&!Ne.includes(" ")&&!Ne.includes(`
235
+ `)){j(Ne),h(!0),f(!1);return}}h(!1);const Ae=fe.lastIndexOf("@");if(Ae!==-1){const Ve=Ae>0?fe[Ae-1]:null,Ne=fe.substring(Ae+1);(!Ve||/\s/.test(Ve))&&!Ne.includes(" ")&&!Ne.includes(`
236
+ `)?(u(Ne),f(!0)):f(!1);return}f(!1)},e[12]=B):B=e[12];const T=B;let W;e[13]!==n.id||e[14]!==a?(W=R=>{a(n.id,{prompt:R})},e[13]=n.id,e[14]=a,e[15]=W):W=e[15];const U=W;let L;e[16]!==n.prompt||e[17]!==U?(L=R=>{const de=n.prompt,$=S.current?.selectionStart??de.length,Ve=de.substring(0,$).lastIndexOf("@"),Ne=R.relativePath&&R.relativePath.trim().length>0?R.relativePath.trim():R.path||R.name,Y=Ve!==-1?Ve:$,F=`${de.substring(0,Y)}@${Ne} ${de.substring($)}`,se=Y+Ne.length+2;U(F),f(!1),u(""),requestAnimationFrame(()=>{const Oe=S.current;Oe&&(Oe.selectionStart=se,Oe.selectionEnd=se,Oe.focus()),T(F,se)})},e[16]=n.prompt,e[17]=U,e[18]=L):L=e[18];const M=L;let ee;e[19]!==n.prompt||e[20]!==U?(ee=R=>{const de=n.prompt,$=S.current?.selectionStart??de.length,Ve=de.substring(0,$).lastIndexOf("@"),Ne=Ve!==-1?Ve:$,Y=`${de.substring(0,Ne)}@${R} ${de.substring($)}`,F=Ne+R.length+2;U(Y),f(!1),u(""),requestAnimationFrame(()=>{const se=S.current;se&&(se.selectionStart=F,se.selectionEnd=F,se.focus()),T(Y,F)})},e[19]=n.prompt,e[20]=U,e[21]=ee):ee=e[21];const ie=ee;let X;e[22]!==U?(X=R=>{const de=`/${R.name} `;U(de),x(!1),w(""),h(!1),requestAnimationFrame(()=>{const fe=S.current;fe&&(fe.focus(),fe.selectionStart=fe.value.length,fe.selectionEnd=fe.value.length),T(de,de.length)})},e[22]=U,e[23]=X):X=e[23];const H=X;let te;e[24]!==n.prompt||e[25]!==U?(te=(R,de)=>{const fe=n.prompt,Ae=S.current?.selectionStart??fe.length,Ne=fe.substring(0,Ae).lastIndexOf("#"),Y=Ne!==-1?Ne:Ae,F=`${fe.substring(0,Y)}#${de} ${fe.substring(Ae)}`,se=Y+de.length+2;U(F),h(!1),j(""),requestAnimationFrame(()=>{const Oe=S.current;Oe&&(Oe.selectionStart=se,Oe.selectionEnd=se,Oe.focus()),T(F,se)})},e[24]=n.prompt,e[25]=U,e[26]=te):te=e[26];const re=te;let le;e[27]!==p||e[28]!==d||e[29]!==g?(le=R=>{if(p&&k.current&&(R.key==="Enter"||R.key==="ArrowUp"||R.key==="ArrowDown"||R.key==="Escape"||R.key==="Tab")){R.preventDefault(),k.current.handleKeyDown(R.key);return}d&&N.current&&(R.key==="Enter"||R.key==="ArrowUp"||R.key==="ArrowDown"||R.key==="Escape"||R.key==="Tab")&&(R.preventDefault(),N.current.handleKeyDown(R.key)),g&&y.current&&(R.key==="Enter"||R.key==="ArrowUp"||R.key==="ArrowDown"||R.key==="Escape"||R.key==="Tab")&&(R.preventDefault(),y.current.handleKeyDown(R.key))},e[27]=p,e[28]=d,e[29]=g,e[30]=le):le=e[30];const ve=le,ne=r+1;let we;e[31]!==l||e[32]!==ne?(we=l("multirun.launcher.groups.groupLabel",{index:ne}),e[31]=l,e[32]=ne,e[33]=we):we=e[33];let he;e[34]!==we?(he=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:we}),e[34]=we,e[35]=he):he=e[35];let Me;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(Me=o&&s.jsx("button",{type:"button",onClick:()=>c(n.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":l("multirun.launcher.groups.removeGroup"),children:s.jsx(A,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=Me):Me=e[40];let z;e[41]!==he||e[42]!==Me?(z=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[he,Me]}),e[41]=he,e[42]=Me,e[43]=z):z=e[43];let K;e[44]!==l?(K=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=K):K=e[45];let q;e[46]!==K?(q=s.jsx(Ti,{required:!0,children:K}),e[46]=K,e[47]=q):q=e[47];const me=n.prompt;let Se;e[48]!==U?(Se=R=>{const de=R.target.value;U(de);const fe=R.target.selectionStart??de.length;T(de,fe)},e[48]=U,e[49]=Se):Se=e[49];let Be;e[50]!==l?(Be=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=Be):Be=e[51];let _e;e[52]!==n.prompt||e[53]!==ve||e[54]!==Se||e[55]!==Be?(_e=s.jsx(Pi,{ref:S,value:me,onChange:Se,onKeyDown:ve,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]=ve,e[54]=Se,e[55]=Be,e[56]=_e):_e=e[56];let Le;e[57]!==b||e[58]!==H||e[59]!==p?(Le=p?s.jsx(ym,{ref:k,searchQuery:b,onCommandSelect:H,onClose:()=>x(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=b,e[58]=H,e[59]=p,e[60]=Le):Le=e[60];let pe;e[61]!==ie||e[62]!==M||e[63]!==m||e[64]!==d?(pe=d?s.jsx(vm,{ref:N,searchQuery:m,onFileSelect:M,onAgentSelect:ie,onClose:()=>f(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=ie,e[62]=M,e[63]=m,e[64]=d,e[65]=pe):pe=e[65];let Ee;e[66]!==re||e[67]!==g||e[68]!==C?(Ee=g?s.jsx(jm,{ref:y,searchQuery:C,onSnippetSelect:re,onClose:()=>h(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=re,e[67]=g,e[68]=C,e[69]=Ee):Ee=e[69];let ge;e[70]!==_e||e[71]!==Le||e[72]!==pe||e[73]!==Ee?(ge=s.jsxs("div",{className:"relative",children:[_e,Le,pe,Ee]}),e[70]=_e,e[71]=Le,e[72]=pe,e[73]=Ee,e[74]=ge):ge=e[74];let oe;e[75]!==q||e[76]!==ge?(oe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[q,ge]}),e[75]=q,e[76]=ge,e[77]=oe):oe=e[77];let je;e[78]!==l?(je=l("multirun.launcher.models.info",{max:zl}),e[78]=l,e[79]=je):je=e[79];let ye;e[80]!==je?(ye=s.jsx(va,{children:je}),e[80]=je,e[81]=ye):ye=e[81];let ue;e[82]!==l?(ue=l("multirun.launcher.models.label"),e[82]=l,e[83]=ue):ue=e[83];let De;e[84]!==ye||e[85]!==ue?(De=s.jsx(Ti,{required:!0,info:ye,children:ue}),e[84]=ye,e[85]=ue,e[86]=De):De=e[86];let I;e[87]!==n.models||e[88]!==V||e[89]!==O||e[90]!==E?(I=s.jsx(Mh,{selectedModels:n.models,onAdd:V,onRemove:O,onUpdate:E,minModels:1,maxModels:zl}),e[87]=n.models,e[88]=V,e[89]=O,e[90]=E,e[91]=I):I=e[91];let _;e[92]!==De||e[93]!==I?(_=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[De,I]}),e[92]=De,e[93]=I,e[94]=_):_=e[94];let be;return e[95]!==z||e[96]!==oe||e[97]!==_?(be=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[z,oe,_]}),e[95]=z,e[96]=oe,e[97]=_,e[98]=be):be=e[98],be},Uk=i.createContext(null),Hk=t=>{const e=ht.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(Uk.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},Of=mo(()=>uo(()=>import("./TerminalView-DQcdegHp.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(t=>({default:t.TerminalView}))),Gk=mo(()=>uo(()=>import("./DiagramView-he_RFVx5.js"),__vite__mapDeps([8,1,3,4,2,5,6,7])).then(t=>({default:t.DiagramView}))),Kk=mo(()=>uo(()=>import("./runtimeEndpointReset-MTaPPm4F.js").then(t=>t.ae),__vite__mapDeps([5,1,2,3,4,6])).then(t=>({default:t.SettingsView}))),qk=mo(()=>uo(()=>import("./SettingsWindow-CjqLdpTE.js"),__vite__mapDeps([9,1,2,3,4,5,6])).then(t=>({default:t.SettingsWindow}))),Yk=mo(()=>uo(()=>import("./MultiRunWindow-B_C-tvVq.js"),__vite__mapDeps([10,1,2,3,4,5,6,7])).then(t=>({default:t.MultiRunWindow}))),Qk=()=>{const o=Re(te=>te.isSidebarOpen),a=Re(te=>te.isRightSidebarOpen),c=Re(te=>te.isBottomTerminalOpen),l=Re(te=>te.setRightSidebarOpen),d=Re(te=>te.setBottomTerminalOpen),f=Re(te=>te.activeMainTab),m=Re(te=>te.setIsMobile),u=Re(te=>te.isSessionSwitcherOpen),p=Re(te=>te.isSettingsDialogOpen),x=Re(te=>te.setSettingsDialogOpen),b=Re(te=>te.isMultiRunLauncherOpen),w=Re(te=>te.setMultiRunLauncherOpen),g=Re(te=>te.multiRunLauncherPrefillPrompt),{isMobile:h,isTablet:C}=$r(),j=i.useRef(!1),S=i.useRef(!1),N=i.useRef(!1),[k,y]=i.useState(!1),[D,V]=i.useState(!1),[v,O]=i.useState(!1),[P,E]=i.useState(!1),B=i.useCallback(te=>{y(te),Re.getState().setSessionSwitcherOpen(te)},[]),T=i.useRef(!1),W=i.useRef(typeof window>"u"?0:window.innerWidth),U=Nd(-W.current),L=nt.useRef(0),M=Nd(W.current),ee=nt.useRef(0);nt.useEffect(()=>{h&&(L.current=window.innerWidth,ee.current=window.innerWidth)},[h]),nt.useEffect(()=>{if(!h){O(!1);return}k&&O(!0),kd(U,k?0:-L.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[k,h,U]),nt.useEffect(()=>{if(!h){E(!1);return}T.current=D,D&&E(!0),kd(M,D?0:ee.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[h,D,M]),nt.useEffect(()=>{if(h)return U.on("change",te=>{const re=L.current||W.current,le=k||te>-re+.5;O(ve=>ve===le?ve:le)})},[h,U,k]),nt.useEffect(()=>{if(h)return M.on("change",te=>{const re=ee.current||W.current,le=D||te<re-.5;E(ve=>ve===le?ve:le)})},[h,D,M]),nt.useEffect(()=>{h&&!u&&k&&B(!1)},[u,h,k,B]),nt.useEffect(()=>{if(!h){N.current=!1;return}N.current||(N.current=!0,B(!1),V(!1),Re.getState().isRightSidebarOpen&&l(!1))},[h,B,l]),nt.useEffect(()=>{if(!h||f!=="chat"||k||D||p)return;let te=!1,re;const le=ve=>{re=window.setTimeout(()=>{if(te)return;const ne=mt.getState(),we=Re.getState();if(!(we.activeMainTab!=="chat"||we.isSettingsDialogOpen||ne.currentSessionId||ne.newSessionDraft?.open)){if(ne.isLoading){le(250);return}ne.openNewSessionDraft()}},ve)};return le(500),()=>{te=!0,re!==void 0&&window.clearTimeout(re)}},[f,h,p,k,D]),nt.useEffect(()=>{!h||!p||(B(!1),V(!1),a&&l(!1))},[h,p,a,B,l]),db(),i.useEffect(()=>{Re.getState().isMobile!==h&&m(h)},[h,m]),i.useEffect(()=>{if(typeof window>"u")return;let te;const re=()=>{te===void 0&&(te=window.requestAnimationFrame(()=>{te=void 0,Re.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",re),()=>{window.removeEventListener("resize",re),te!==void 0&&window.cancelAnimationFrame(te)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let te;const re=()=>{const ve=Re.getState(),ne=window.innerWidth,we=window.innerHeight;if(!h&&!C){const he=ne<1140,Me=ne>=1220;he?ve.isRightSidebarOpen&&(l(!1),j.current=!0):Me&&j.current&&(l(!0),j.current=!1);const z=we<640,K=we>=700;z?ve.isBottomTerminalOpen&&(d(!1),S.current=!0):K&&S.current&&(d(!0),S.current=!1)}},le=()=>{te===void 0&&(te=window.requestAnimationFrame(()=>{te=void 0,re()}))};return re(),window.addEventListener("resize",le),()=>{window.removeEventListener("resize",le),te!==void 0&&window.cancelAnimationFrame(te)}},[h,C,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const te=Re.subscribe((re,le)=>{const ve=window.innerWidth,ne=window.innerHeight,we=ve>=1220,he=ne>=700;re.isRightSidebarOpen!==le.isRightSidebarOpen&&we&&(j.current=!1),re.isBottomTerminalOpen!==le.isBottomTerminalOpen&&he&&(S.current=!1)});return()=>{te()}},[h,C,d,l]);const ie=i.useCallback(()=>{k&&B(!1),V(!D)},[k,D,B]),X=i.useMemo(()=>{switch(f){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(uh,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(ic,{isActive:!D})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(oh,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Of,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(dh,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(th,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Gk,{})});default:return null}},[f,D]),H=f==="chat";return s.jsx(ub,{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(h0,{}),s.jsx(rS,{}),s.jsx(lS,{}),s.jsx(Ik,{}),h?s.jsxs(Hk,{value:{leftDrawerOpen:k,rightDrawerOpen:D,toggleLeftDrawer:()=>{const te=!k;D&&V(!1),B(te)},toggleRightDrawer:ie,leftDrawerX:U,rightDrawerX:M,leftDrawerWidth:L,rightDrawerWidth:ee,setMobileLeftDrawerOpen:B,setRightSidebarOpen:V},children:[!p&&s.jsx(uu,{onToggleLeftDrawer:()=>{const te=!k;D&&V(!1),B(te)},onToggleRightDrawer:()=>{ie()},leftDrawerOpen:k,rightDrawerOpen:D}),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(on,{children:s.jsx(ec,{})})}),X&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(on,{children:X})}),b&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(on,{children:s.jsx(zk,{initialPrompt:g,onCreated:()=>w(!1),onCancel:()=>w(!1)})})}),s.jsx(Cd.div,{className:Pe("absolute inset-0 z-20 bg-sidebar",!v&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:U},"aria-hidden":!k,children:s.jsx(on,{children:s.jsx(Ef,{mobileVariant:!0})})}),P&&s.jsx(Cd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:M},"aria-hidden":!D,children:s.jsx(on,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(ic,{isActive:D})})})})]})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(on,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Kk,{onClose:()=>x(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(vw,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(bw,{isOpen:o,isMobile:h,className:"border-border/50",topBar:s.jsx(ww,{}),children:s.jsx(Ef,{})}),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(uu,{}),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(on,{children:s.jsx(ec,{})})}),X&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(on,{children:X})})]}),s.jsx(u0,{})]})}),s.jsx(mw,{isOpen:c,isMobile:h,children:c?s.jsx(on,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Of,{})})}):null})]}),s.jsx(Aw,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(on,{children:s.jsx(Yv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(qk,{open:p,onOpenChange:x})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(Yk,{open:b,onOpenChange:w,initialPrompt:g})})]})]})})},Jk=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`},Un=t=>{const e=ht.c(8),{label:n,value:r}=t;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[0]=o):o=e[0];let a;e[1]!==n?(a=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:n}),e[1]=n,e[2]=a):a=e[2];let c;e[3]!==r?(c=s.jsx("div",{className:"typography-markdown font-semibold text-[var(--surface-foreground)]",children:r}),e[3]=r,e[4]=c):c=e[4];let l;return e[5]!==a||e[6]!==c?(l=s.jsxs("div",{className:"rounded-md p-2",style:o,children:[a,c]}),e[5]=a,e[6]=c,e[7]=l):l=e[7],l},Lf=t=>{const e=ht.c(43),{title:n,snapshot:r,emptyLabel:o}=t,{t:a}=yt();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(eC,0),e[8]=r.entries,e[9]=d):d=e[9];const f=d;let m;e[10]!==n?(m=s.jsx("div",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:n}),e[10]=n,e[11]=m):m=e[11];let u;e[12]!==r.durationMs||e[13]!==r.startedAt||e[14]!==a?(u=r.startedAt?Jk(r.durationMs):a("memoryDebugPanel.common.idle"),e[12]=r.durationMs,e[13]=r.startedAt,e[14]=a,e[15]=u):u=e[15];let p;e[16]!==u?(p=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:u}),e[16]=u,e[17]=p):p=e[17];let x;e[18]!==m||e[19]!==p?(x=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m,p]}),e[18]=m,e[19]=p,e[20]=x):x=e[20];let b;e[21]!==a?(b=a("memoryDebugPanel.metric.metrics"),e[21]=a,e[22]=b):b=e[22];let w;e[23]!==r.entries.length||e[24]!==b?(w=s.jsx(Un,{label:b,value:r.entries.length}),e[23]=r.entries.length,e[24]=b,e[25]=w):w=e[25];let g;e[26]!==a?(g=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=g):g=e[27];let h;e[28]!==g||e[29]!==f?(h=s.jsx(Un,{label:g,value:f}),e[28]=g,e[29]=f,e[30]=h):h=e[30];let C;e[31]!==a?(C=a("memoryDebugPanel.metric.lastUpdate"),e[31]=a,e[32]=C):C=e[32];let j;e[33]!==r.lastUpdatedAt||e[34]!==a?(j=r.lastUpdatedAt?a("memoryDebugPanel.common.live"):a("memoryDebugPanel.common.notAvailable"),e[33]=r.lastUpdatedAt,e[34]=a,e[35]=j):j=e[35];let S;e[36]!==C||e[37]!==j?(S=s.jsx(Un,{label:C,value:j}),e[36]=C,e[37]=j,e[38]=S):S=e[38];let N;e[39]!==h||e[40]!==S||e[41]!==w?(N=s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[w,h,S]}),e[39]=h,e[40]=S,e[41]=w,e[42]=N):N=e[42],c=s.jsxs("div",{className:"space-y-2 border-t border-[var(--interactive-border)] pt-2 first:border-t-0 first:pt-0",children:[x,N,l.length===0?s.jsx("div",{className:"rounded-md p-3 typography-meta text-[var(--surface-muted-foreground)]",style:{backgroundColor:"color-mix(in srgb, var(--surface-muted) 45%, transparent)"},children:o}):s.jsx(On,{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},Xk=t=>{const e=ht.c(99),{onClose:n}=t,{t:r}=yt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=mt(tC),f=Sm(sC),m=Ec(),u=Nx(nC),p=lr(rC),[x,b]=i.useState(iC),[w,g]=i.useState(oC);let h;e[0]!==x.entries?(h=new Map,x.entries.forEach(ue=>{h.set(ue.metric,ue.count)}),e[0]=x.entries,e[1]=h):h=e[1];let C;e[2]!==h?(C=h.get("ui.message_list.render")??0,e[2]=h,e[3]=C):C=e[3];let j;e[4]!==h?(j=h.get("ui.message_list.render.streaming")??0,e[4]=h,e[5]=j):j=e[5];let S;e[6]!==h?(S=h.get("ui.chat_message.render")??0,e[6]=h,e[7]=S):S=e[7];let N;e[8]!==h?(N=h.get("ui.chat_message.render.streaming")??0,e[8]=h,e[9]=N):N=e[9];let k;e[10]!==h?(k=h.get("ui.chat_message.render.static_during_stream")??0,e[10]=h,e[11]=k):k=e[11];let y;e[12]!==h?(y=h.get("ui.chat_message.render.static_outside_active_turn_during_stream")??0,e[12]=h,e[13]=y):y=e[13];let D;e[14]!==C||e[15]!==j||e[16]!==S||e[17]!==N||e[18]!==k||e[19]!==y?(D={messageListRender:C,messageListRenderStreaming:j,chatMessageRender:S,chatMessageRenderStreaming:N,chatMessageRenderStaticDuringStream:k,chatMessageRenderStaticOutsideActiveTurnDuringStream:y},e[14]=C,e[15]=j,e[16]=S,e[17]=N,e[18]=k,e[19]=y,e[20]=D):D=e[20];const V=D;let v,O;e[21]===Symbol.for("react.memo_cache_sentinel")?(v=()=>{const ue=()=>{b(la()),g(ca())};ue();const De=window.setInterval(ue,500);return()=>window.clearInterval(De)},O=[],e[21]=v,e[22]=O):(v=e[21],O=e[22]),i.useEffect(v,O);let P,E;e[23]!==c?(P=()=>{if(c==="idle")return;const ue=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(ue)},E=[c],e[23]=c,e[24]=P,e[25]=E):(P=e[24],E=e[25]),i.useEffect(P,E);let B=0,T=0,W=0;for(const ue of Object.keys(u)){const De=u[ue]??[];T=T+De.length;for(const I of De)I.role==="user"?W=W+1:I.role==="assistant"&&(B=B+1)}let U;e[26]!==B||e[27]!==T||e[28]!==W?(U={assistant:B,total:T,user:W},e[26]=B,e[27]=T,e[28]=W,e[29]=U):U=e[29];const L=U;let M;if(e[30]!==d||e[31]!==u||e[32]!==f||e[33]!==m||e[34]!==r){let ue;e[36]!==d||e[37]!==u||e[38]!==f||e[39]!==r?(ue=De=>{const I=u[De.id]??[];let _=0,be=0;for(const de of I)de.role==="user"?be=be+1:de.role==="assistant"&&(_=_+1);const R=f.get(De.id);return{id:De.id,title:De.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:_,messageCount:I.length,userMessageCount:be,isStreaming:R?.isStreaming||!1,isZombie:R?.isZombie||!1,backgroundCount:R?.backgroundMessageCount||0,lastAccessed:R?.lastAccessedAt||0,isCurrent:De.id===d}},e[36]=d,e[37]=u,e[38]=f,e[39]=r,e[40]=ue):ue=e[40],M=m.map(ue).sort(aC),e[30]=d,e[31]=u,e[32]=f,e[33]=m,e[34]=r,e[35]=M}else M=e[35];const ee=M;let ie;e[41]!==u?(ie=Object.keys(u),e[41]=u,e[42]=ie):ie=e[42];const X=ie.length;let H;e[43]===Symbol.for("react.memo_cache_sentinel")?(H=async()=>{try{const ue={generatedAt:new Date().toISOString(),ui:la(),vscode:ca()};await navigator.clipboard.writeText(JSON.stringify(ue,null,2)),l("copied")}catch{l("error")}},e[43]=H):H=e[43];const te=H;let re;e[44]===Symbol.for("react.memo_cache_sentinel")?(re={backgroundColor:"color-mix(in srgb, var(--surface-background) 94%, transparent)"},e[44]=re):re=e[44];let le;e[45]!==o?(le=o==="memory"?s.jsx(A,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(A,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=le):le=e[46];let ve;e[47]!==r?(ve=r("memoryDebugPanel.title"),e[47]=r,e[48]=ve):ve=e[48];let ne;e[49]!==ve?(ne=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:ve}),e[49]=ve,e[50]=ne):ne=e[50];let we;e[51]!==le||e[52]!==ne?(we=s.jsxs("div",{className:"flex items-center gap-2",children:[le,ne]}),e[51]=le,e[52]=ne,e[53]=we):we=e[53];let he;e[54]!==o?(he=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx(ze,{size:"xs",variant:"ghost",onClick:te,children:s.jsx(A,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx(ze,{size:"xs",variant:"ghost",onClick:()=>{Dp(),b(la()),g(ca())},children:s.jsx(A,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=he):he=e[55];let Me;e[56]!==n?(Me=n?s.jsx(ze,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(A,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=Me):Me=e[57];let z;e[58]!==he||e[59]!==Me?(z=s.jsxs("div",{className:"flex items-center gap-1",children:[he,Me]}),e[58]=he,e[59]=Me,e[60]=z):z=e[60];let K;e[61]!==we||e[62]!==z?(K=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[we,z]}),e[61]=we,e[62]=z,e[63]=K):K=e[63];let q;e[64]===Symbol.for("react.memo_cache_sentinel")?(q={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=q):q=e[64];const me=o==="memory"?"secondary":"ghost";let Se;e[65]===Symbol.for("react.memo_cache_sentinel")?(Se=()=>a("memory"),e[65]=Se):Se=e[65];let Be;e[66]!==r?(Be=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=Be):Be=e[67];let _e;e[68]!==me||e[69]!==Be?(_e=s.jsx(ze,{size:"sm",variant:me,className:"flex-1",onClick:Se,children:Be}),e[68]=me,e[69]=Be,e[70]=_e):_e=e[70];const Le=o==="streaming"?"secondary":"ghost";let pe;e[71]===Symbol.for("react.memo_cache_sentinel")?(pe=()=>a("streaming"),e[71]=pe):pe=e[71];let Ee;e[72]!==r?(Ee=r("memoryDebugPanel.tabs.streaming"),e[72]=r,e[73]=Ee):Ee=e[73];let ge;e[74]!==Le||e[75]!==Ee?(ge=s.jsx(ze,{size:"sm",variant:Le,className:"flex-1",onClick:pe,children:Ee}),e[74]=Le,e[75]=Ee,e[76]=ge):ge=e[76];let oe;e[77]!==_e||e[78]!==ge?(oe=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:q,children:[_e,ge]}),e[77]=_e,e[78]=ge,e[79]=oe):oe=e[79];let je;e[80]!==o||e[81]!==X||e[82]!==c||e[83]!==d||e[84]!==u||e[85]!==L||e[86]!==f||e[87]!==ee||e[88]!==m||e[89]!==V||e[90]!==x||e[91]!==r||e[92]!==p||e[93]!==w?(je=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(Un,{label:r("memoryDebugPanel.metric.totalMessages"),value:L.total}),s.jsx(Un,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${X} / ${Jd.MAX_SESSIONS}`}),s.jsx(Un,{label:r("memoryDebugPanel.metric.userMessages"),value:L.user}),s.jsx(Un,{label:r("memoryDebugPanel.metric.assistantMessages"),value:L.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:kx()})})]}),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:Jd.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(On,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:ee.map(ue=>s.jsxs("div",{className:"typography-meta flex items-center justify-between rounded p-1.5",style:{backgroundColor:ue.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:ue.title}),ue.isStreaming?s.jsx(A,{name:"pulse",className:"h-3 w-3 animate-pulse text-[var(--status-info)]"}):null,ue.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:ue.assistantMessageCount,user:ue.userMessageCount})}),s.jsx("span",{className:"font-mono text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.msgsValue",{count:ue.messageCount})}),ue.backgroundCount>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["+",ue.backgroundCount]}):null]})]},ue.id))})]}),s.jsx("div",{className:"flex gap-2 border-t border-[var(--interactive-border)] pt-2",children:s.jsxs(Ct,{children:[s.jsx(At,{asChild:!0,children:s.jsx(ze,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:m.map(lC),currentSessionId:d,cachedSessions:Object.keys(u),messageRoleCounts:L,sessionMessageRoleCounts:ee.map(cC),memoryStates:Object.fromEntries(f)})},children:r("memoryDebugPanel.actions.logState")})}),s.jsx(Dt,{side:"top",children:r("memoryDebugPanel.tooltip.logCurrentState")})]})})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-[var(--interactive-border)] px-3 py-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:r(c==="copied"?"memoryDebugPanel.streaming.copy.copied":c==="error"?"memoryDebugPanel.streaming.copy.failed":"memoryDebugPanel.streaming.copy.hint")}),s.jsx(ze,{size:"xs",variant:"outline",onClick:te,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(Un,{label:r("memoryDebugPanel.metric.uiMetrics"),value:x.entries.length}),s.jsx(Un,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:w.entries.length}),s.jsx(Un,{label:r("memoryDebugPanel.metric.messageListRenders"),value:V.messageListRender}),s.jsx(Un,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:V.messageListRenderStreaming}),s.jsx(Un,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:V.chatMessageRender}),s.jsx(Un,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:V.chatMessageRenderStreaming}),s.jsx(Un,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:V.chatMessageRenderStaticDuringStream}),s.jsx(Un,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:V.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(Lf,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:x,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),w.entries.length>0?s.jsx(Lf,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:w,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=X,e[82]=c,e[83]=d,e[84]=u,e[85]=L,e[86]=f,e[87]=ee,e[88]=m,e[89]=V,e[90]=x,e[91]=r,e[92]=p,e[93]=w,e[94]=je):je=e[94];let ye;return e[95]!==K||e[96]!==oe||e[97]!==je?(ye=s.jsxs(Cx,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:re,children:[K,oe,je]}),e[95]=K,e[96]=oe,e[97]=je,e[98]=ye):ye=e[98],ye},Zk=Xk;function eC(t,e){return t+e.count}function tC(t){return t.currentSessionId}function sC(t){return t.sessionMemoryState}function nC(t){return t.message}function rC(t){return t.totalRequestCount}function iC(){return la()}function oC(){return ca()}function aC(t,e){return e.lastAccessed-t.lastAccessed}function lC(t){return{id:t.id,title:t.title}}function cC(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const dC=()=>{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()??"":""},uC=async()=>{const t=dC()||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")},Bf="openchamber:menu-action",Wl="openchamber:check-for-updates",fC=t=>{const e=mt(y=>y.openNewSessionDraft),n=Re(y=>y.toggleCommandPalette),r=Re(y=>y.setCommandPaletteOpen),o=Re(y=>y.toggleHelpDialog),a=Re(y=>y.toggleSidebar),c=Re(y=>y.setSessionSwitcherOpen),l=Re(y=>y.setActiveMainTab),d=Re(y=>y.setSettingsDialogOpen),f=Re(y=>y.setAboutDialogOpen),m=Re(y=>y.toggleRightSidebar),u=Re(y=>y.setRightSidebarOpen),p=Re(y=>y.setRightSidebarTab),x=Re(y=>y.toggleBottomTerminal),b=Re(y=>y.setBottomTerminalExpanded),w=Do(y=>y.checkForUpdates),{setThemeMode:g}=yi(),h=i.useRef(!1),C=i.useCallback(()=>{h.current||(h.current=!0,w().then(()=>{const{available:y,error:D}=Do.getState();if(D){ae.error("Failed to check for updates",{description:D});return}y||ae.success("You are on the latest version")}).finally(()=>{h.current=!1}))},[w]),j=i.useCallback(()=>{Lr.requestDirectoryDialog()},[]),S=i.useCallback(y=>{const D=Ax();if(D.length===0)return;const V=mt.getState().currentSessionId,v=D.findIndex(E=>E.id===V);let O=y>0?0:D.length-1;v>=0&&(O=(v+y+D.length)%D.length);const P=D[O];P&&(l("chat"),c(!1),mt.getState().setCurrentSession(P.id))},[l,c]),N=i.useCallback(y=>{const{activeProjectId:D,projects:V,setActiveProject:v}=Ds.getState();if(V.length===0)return;const O=V.findIndex(B=>B.id===D);let P=y>0?0:V.length-1;O>=0&&(P=(O+y+V.length)%V.length);const E=V[P];E&&v(E.id)},[]),k=i.useCallback(y=>{switch(y){case"about":f(!0);break;case"settings":d(!0);break;case"command-palette":n();break;case"quick-open":r(!0);break;case"new-session":l("chat"),c(!1),e();break;case"new-worktree-session":l("chat"),c(!1),wm();break;case"change-workspace":j();break;case"toggle-right-sidebar":m();break;case"open-right-sidebar-git":u(!0),p("git");break;case"open-right-sidebar-files":u(!0),p("files");break;case"toggle-terminal":x();break;case"toggle-terminal-expanded":b(!Re.getState().isBottomTerminalExpanded);break;case"copy":{const D=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(D)||uC();break}case"theme-light":g("light");break;case"theme-dark":g("dark");break;case"theme-system":g("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":Xs.getState().goBack();break;case"go-forward":Xs.getState().goForward();break;case"previous-session":S(-1);break;case"next-session":S(1);break;case"previous-project":N(-1);break;case"next-project":N(1);break;case"help-dialog":o();break;case"download-logs":{Dx().catch(()=>{ae.error("Failed to collect OpenCode status")});break}}},[j,N,S,t,e,f,l,c,r,d,b,u,p,g,x,n,o,m,a]);i.useEffect(()=>{const y=V=>{const v=V.detail;v&&k(v)},D=()=>{C()};return window.addEventListener(Bf,y),window.addEventListener(Wl,D),()=>{window.removeEventListener(Bf,y),window.removeEventListener(Wl,D)}},[k,C]),i.useEffect(()=>{if(typeof window>"u")return;const D=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof D!="function")return;let V=null,v=null;return D("openchamber:menu-action",O=>{const P=O?.payload;typeof P=="string"&&k(P)}).then(O=>{V=O}).catch(()=>{}),D("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Wl))}).then(O=>{v=O}).catch(()=>{}),()=>{(async()=>{try{const P=V?.();P instanceof Promise&&await P}catch{}try{const P=v?.();P instanceof Promise&&await P}catch{}})()}},[k])},mC="openchamber:tray-action",Vf=5e3,hC=120,pC=45e3,Lh=20,_f=()=>{if(typeof window>"u")return!1;const t=window.__OPENCHAMBER_PLATFORM__;return t==="darwin"||t==="win32"},gC=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},xC=t=>{const e=Array.isArray(t.questions)?t.questions[0]:void 0;return e?.header||e?.question||"Question"},za=t=>t.time?.updated??t.time?.created??0,bC=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},wC=(t,e,n,r,o)=>{if(!t)return"";const a=Rx(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||bC(t),d=ua(t);let f=d&&o.get(d)||"";if(!f){for(const[m,u]of vn.getState().directories)if(ua(m)===d){f=u.status?.current??"";break}}if(!f)for(const m of r.values()){const u=m.find(p=>ua(p.path)===d);if(u?.branch){f=u.branch;break}}return f?`${l} · ${f}`:l},yC=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=xn.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 Im){if(!e.includes(c.id))continue;const l=o.get(c.id);if(!l||l.configured!==!0)continue;const d=[];for(const[m,u]of Object.entries(l.usage?.windows??{})){const p=r==="remaining"?u.remainingPercent:u.usedPercent;d.push({label:Sc(m),value:Lo(u.valueLabel,p)})}const f=!l.ok&&l.error?l.error:d.length===0?"No rate limits reported":null;a.push({provider:c.name,rows:d,status:f})}return{mode:r,groups:a}},vC=async()=>{try{if(to())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=Xr();if(e&&Aa(e,t))return"Local OpenChamber";const r=(await Yf()).hosts.find(o=>e?Aa(e,Qf(o)):!1);return r?.label?.trim()?Jf(r.label.trim()):"Instance"}catch{return""}},jC=()=>{const t=new Map,e=new Map,n=[],r=new Map;let o;try{o=Ia()}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(ua(a)??a,l.vcs.branch);for(const d of l.session)d?.id&&r.set(d.id,d.title);for(const[d,f]of Object.entries(l.session_status??{})){const m=f?.type,u=m==="busy"?"busy":m==="retry"?"retry":"idle",p=t.get(d);(!p||p==="idle")&&t.set(d,u)}for(const[d,f]of Object.entries(l.permission??{}))for(const m of f??[]){if(!m?.id)continue;const u=m.sessionID||d;n.push({kind:"permission",id:m.id,sessionId:u,sessionTitle:"",label:gC(m),directory:a})}for(const[d,f]of Object.entries(l.question??{}))for(const m of f??[]){if(!m?.id)continue;const u=m.sessionID||d;n.push({kind:"question",id:m.id,sessionId:u,sessionTitle:"",label:xC(m),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},SC=()=>{const t=pr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>za(o)-za(r)).slice(0,Lh).forEach(r=>{const o=Br(r);o&&e.add(o)});const n=new Map;for(const r of t){if(!r?.id)continue;const o=Br(r);if(!o||!e.has(o))continue;const a=n.get(o)??[];a.push(r.id),n.set(o,a)}return n},NC=t=>{const e=jC(),n=km.getState().index.session,r=pr.getState().activeSessions,o=new Map(e.titleById),a=new Map;for(const g of r)if(g?.id&&(g.title&&o.set(g.id,g.title),g.parentID)){const h=a.get(g.parentID)??[];h.push(g.id),a.set(g.parentID,h)}const c=g=>{const h=[],C=[...a.get(g)??[]],j=new Set;for(;C.length;){const S=C.pop();j.has(S)||(j.add(S),h.push(S),C.push(...a.get(S)??[]))}return h},l=Cm.getState().statusById,d=g=>{const h=e.statusById.get(g);return h&&h!=="idle"?h:l.get(g)?.status??h??"idle"},f=g=>{const h=g.map(C=>d(C));return h.includes("busy")?"busy":h.includes("retry")?"retry":"idle"},m=Ds.getState().projects,u=mt.getState().availableWorktreesByProject,p=r.filter(g=>g?.id&&!g.parentID).slice().sort((g,h)=>za(h)-za(g)).slice(0,Lh).map(g=>{const h=[g.id,...c(g.id)],C=Br(g)??"";return{id:g.id,title:g.title||"Untitled session",status:f(h),branch:C?e.branchByDirectory.get(C)??"":"",unseen:h.reduce((j,S)=>j+(n.unseenCount[S]??0),0),hasError:h.some(j=>n.unseenHasError[j]??!1),directory:C,subtitle:wC(C,g,m,u,e.branchByDirectory)}}),x=e.approvals.map(g=>({...g,sessionTitle:o.get(g.sessionId)||""})),b=Re.getState();let w=0;if(b.dockBadgeEnabled)for(const g of r){if(!g?.id||g.parentID)continue;let h=n.unseenCount[g.id]??0;h===0&&b.notifyOnSubtasks&&(h=c(g.id).reduce((C,j)=>C+(n.unseenCount[j]??0),0)),h>0&&(w+=1)}return{sessions:p,approvals:x,instanceName:t,usage:yC(),dockBadgeCount:w}},kC=()=>{i.useEffect(()=>{if(!_f()||!Wa())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const k=NC(r),y=JSON.stringify(k);y!==e&&(e=y,Zr("desktop_tray_update",k))};vC().then(k=>{t||(r=k,o())});const a=async()=>{const k=SC();await Promise.all([...k.entries()].map(async([y,D])=>{const V=await Xn.getSessionStatusForDirectory(y).catch(()=>null);t||V===null||Px(y,V,D)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},hC))},l=new Map,d=()=>{if(t)return;let k;try{k=Ia()}catch{return}const y=new Set;for(const[D,V]of k.children.entries())y.add(D),l.has(D)||l.set(D,V.subscribe(()=>c()));for(const[D,V]of l)y.has(D)||(V(),l.delete(D))};let f=null;try{f=Ia().subscribeRegistry(()=>{d(),c()})}catch{}d();const m=km.subscribe(()=>c()),u=pr.subscribe(()=>c()),p=Ds.subscribe(()=>c()),x=mt.subscribe(()=>c()),b=vn.subscribe(()=>c()),w=Re.subscribe(()=>c()),g=Cm.subscribe(()=>c());Tx(im());const h=window.setInterval(()=>{Ta()},pC);a();const C=window.setInterval(()=>{a()},Vf),j=xn.subscribe(()=>c());xn.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:k,results:y}=xn.getState();k.length>0&&k.some(V=>!y.some(v=>v.providerId===V))&&xn.getState().fetchAllQuotas()});const S=window.setInterval(()=>{const k=xn.getState();k.autoRefresh&&k.dropdownProviderIds.length>0&&k.fetchAllQuotas()},Math.max(3e4,xn.getState().refreshIntervalMs||6e4)),N=window.setInterval(()=>{d(),o()},Vf);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(N),window.clearInterval(h),window.clearInterval(C),window.clearInterval(S),m(),u(),p(),x(),b(),w(),g(),j(),f?.();for(const k of l.values())k();l.clear()}},[]),i.useEffect(()=>{if(!_f()||typeof window>"u")return;const e=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof e!="function")return;const n=o=>{o.type==="respond-permission"&&Ix(o.sessionId,o.id,o.response).catch(()=>{ae.error("Failed to respond to permission request")})};let r=null;return e(mC,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{}}},[])},CC="/api/notifications/stream",AC=()=>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}},TC=t=>{const e=ht.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||gr()||!jc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(Ii().sse(CC));return a.onmessage=PC,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function PC(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Re.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&AC())return;const r=DC(e);if(!r)return;zo()?.notifications?.notifyAgentCompletion(r)}const $f="pwa-install-toast-shown",zf="pwa-install-toast-dismissed",IC=()=>{const t=ht.c(6),{browserTab:e}=fb(),{t:n}=yt(),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"||!jc()||!e)return;let d=null,f=null;const m=()=>{f!==null&&(ae.dismiss(f),f=null)},u=async()=>{if(!d)return;const b=d;d=null,m(),await b.prompt();const{outcome:w}=await b.userChoice;w==="accepted"&&ae.success(r.current("pwa.installPrompt.started"))},p=b=>{const w=b;if(typeof w.prompt!="function")return;w.preventDefault(),d=w;const g=Gi(),h=qf();mb({dismissed:g.getItem(zf),sessionShown:h.getItem($f),hasActiveToast:f!==null})&&(h.setItem($f,"true"),f=ae.info(r.current("pwa.installPrompt.description"),{duration:1/0,action:{label:r.current("pwa.installPrompt.action"),onClick:()=>{u()}},cancel:{label:r.current("pwa.installPrompt.dismiss"),onClick:()=>{Gi().setItem(zf,"true"),m()}}}))},x=()=>{d=null,m(),ae.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",p),window.addEventListener("appinstalled",x),()=>{m(),window.removeEventListener("beforeinstallprompt",p),window.removeEventListener("appinstalled",x)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},RC=({open:t,onOpenChange:e})=>{const{t:n}=yt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,f]=i.useState(!1),[m,u]=i.useState(!1),[p,x]=i.useState(null),[b,w]=i.useState(!1);i.useCallback(async()=>{},[p,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const C=await Ps("/api/system/info");if(C.ok){const j=await C.json();if(typeof j.openchamberVersion=="string"&&j.openchamberVersion.trim()){a(j.openchamberVersion);return}}}catch{}a(await Ex())})()},[t]),i.useEffect(()=>{if(!t)return;let h=!1;return(async()=>{try{const j=await Ps("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!j.ok)return;const S=await j.json().catch(()=>null),N=typeof S?.currentVersion=="string"?S.currentVersion.trim():"";!h&&N&&l(N)}catch{}})(),()=>{h=!0}},[t]),i.useEffect(()=>{{x(null),w(!1);return}},[t,r]);const g=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(Fc,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),s.jsxs("div",{className:"space-y-0.5 typography-meta text-muted-foreground",children:[g&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:g})}),c&&s.jsx("p",{children:n("aboutDialog.openCodeVersionLabel",{version:c})})]})]}),r,s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-center gap-4",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(A,{name:"github-fill",className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(A,{name:"discord-fill",className:"h-4 w-4"}),s.jsx("span",{children:"Discord"})]})]}),s.jsxs("a",{href:"https://x.com/openchamber_dev",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(A,{name:"twitter-xfill",className:"h-4 w-4"}),s.jsx("span",{children:"@openchamber_dev"})]})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:n("aboutDialog.footerNote")})]})})})},Ul=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},EC=(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},MC=()=>{const t=hb(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=Ul(a,"code"),l=pb(a),d=gb(a),f=Ul(a,"error"),m=Ul(a,"error_description");if(f){d&&Ps(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(m??f);return}(async()=>{try{if(!c)throw new Error("Missing OAuth authorization code. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");let u=l;if(!u&&d){const p=await Ps(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`);if(p.ok){const x=await p.json().catch(()=>null);x?.name?.trim()&&(u={name:x.name.trim(),directory:typeof x.directory=="string"&&x.directory.trim()?x.directory.trim():null})}}if(!u?.name)throw new Error("Authorization session details were not available. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");await t(u.name,c,u.directory),d&&await Ps(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("success"),o("Authorization completed. You can close this tab and return to OpenChamber.")}catch(u){d&&await Ps(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(EC(u,"Failed to complete MCP authorization."))}})()},[t]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-6 py-12 text-foreground",children:s.jsxs("div",{className:"w-full max-w-xl rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-8 shadow-sm",children:[s.jsxs("div",{className:"space-y-3 text-center",children:[s.jsx("div",{className:e==="error"?"text-[var(--status-error)]":e==="success"?"text-[var(--status-success)]":"text-[var(--status-info)]",children:s.jsx("h1",{className:"typography-hero font-semibold",children:e==="working"?"Completing Authorization":e==="success"?"Authorization Complete":"Authorization Failed"})}),s.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}),e!=="working"&&s.jsx("div",{className:"mt-8 flex justify-center",children:s.jsx(ze,{type:"button",onClick:()=>{typeof window>"u"||window.location.replace("/")},children:"Return to OpenChamber"})})]})})},Wf=mo(()=>uo(()=>import("./OnboardingScreen-BBnTt-9w.js"),__vite__mapDeps([11,1,3,4,2])).then(t=>({default:t.OnboardingScreen}))),FC=()=>{const t=ht.c(3),e=Re($C),n=Re(zC);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(RC,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},OC=t=>{const e=ht.c(21),{onRetry:n,isRetrying:r}=t,{t:o}=yt();let a;e[0]!==o?(a=o("startup.initRecovery.title"),e[0]=o,e[1]=a):a=e[1];let c;e[2]!==a?(c=s.jsx("h1",{className:"typography-title text-foreground",children:a}),e[2]=a,e[3]=c):c=e[3];let l;e[4]!==o?(l=o("startup.initRecovery.description"),e[4]=o,e[5]=l):l=e[5];let d;e[6]!==l?(d=s.jsx("p",{className:"typography-body text-muted-foreground",children:l}),e[6]=l,e[7]=d):d=e[7];let f;e[8]!==c||e[9]!==d?(f=s.jsxs("div",{className:"flex flex-col gap-2",children:[c,d]}),e[8]=c,e[9]=d,e[10]=f):f=e[10];let m;e[11]!==r||e[12]!==o?(m=o(r?"startup.initRecovery.retrying":"startup.initRecovery.retry"),e[11]=r,e[12]=o,e[13]=m):m=e[13];let u;e[14]!==r||e[15]!==n||e[16]!==m?(u=s.jsx(ze,{type:"button",onClick:n,disabled:r,children:m}),e[14]=r,e[15]=n,e[16]=m,e[17]=u):u=e[17];let p;return e[18]!==f||e[19]!==u?(p=s.jsx("div",{className:"flex h-full items-center justify-center bg-background px-6 text-foreground",children:s.jsxs("div",{className:"flex max-w-md flex-col items-center gap-4 text-center",children:[f,u]})}),e[18]=f,e[19]=u,e[20]=p):p=e[20],p},Uf=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",LC=()=>{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"}},BC=()=>typeof window>"u"?!1:window.location.pathname===yb,VC=t=>{const e=ht.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=Xs(WC),c=mt(UC),l=mt(HC),d=Vc(),f=i.useRef(null);let m;e[0]!==n.directory?(m=Uf(n.directory),e[0]=n.directory,e[1]=m):m=e[1];const u=m;let p;e[2]!==a?(p=Uf(a),e[2]=a,e[3]=p):p=e[3];const x=p;let b,w;if(e[4]!==x||e[5]!==c||e[6]!==n.directory||e[7]!==n.sessionId||e[8]!==u||e[9]!==r||e[10]!==l||e[11]!==d?(b=()=>{if(r||u&&x!==u)return;const N=`${u}
237
+ ${n.sessionId}`;f.current===N&&c===n.sessionId||(f.current=N,l(n.sessionId,n.directory),d.ensureSessionRenderable(n.sessionId,!0))},w=[x,c,n.directory,n.sessionId,u,r,l,d],e[4]=x,e[5]=c,e[6]=n.directory,e[7]=n.sessionId,e[8]=u,e[9]=r,e[10]=l,e[11]=d,e[12]=b,e[13]=w):(b=e[12],w=e[13]),i.useEffect(b,w),u&&x!==u)return null;let g;e[14]!==o?(g=s.jsx(Am,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=g):g=e[15];let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(Bm,{}),e[16]=h):h=e[16];let C;e[17]!==n.readOnly?(C=s.jsx(ec,{readOnly:n.readOnly}),e[17]=n.readOnly,e[18]=C):C=e[18];let j;e[19]===Symbol.for("react.memo_cache_sentinel")?(j=s.jsx(Dm,{}),e[19]=j):j=e[19];let S;return e[20]!==g||e[21]!==C?(S=s.jsxs(s.Fragment,{children:[g,h,C,j]}),e[20]=g,e[21]=C,e[22]=S):S=e[22],S};function _C({apis:t}){i.useEffect(()=>{Tp("App:mounted"),Pp()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=is(z=>z.initializeApp),n=is(z=>z.isInitialized),r=is(z=>z.isConnected),o=is(z=>z.providers.length),a=is(z=>z.agents.length),c=is(z=>z.loadProviders),l=is(z=>z.loadAgents),d=mt(z=>z.error),f=mt(z=>z.clearError),m=Xs(z=>z.currentDirectory),u=Xs(z=>z.setDirectory),p=Xs(z=>z.isSwitchingDirectory),[x,b]=i.useState(!1),w=Fi(z=>z.refreshStatus),[g,h]=i.useState(()=>t.runtime.isVSCode),[C,j]=i.useState(!0),[S,N]=i.useState(!1),[k,y]=i.useState(0),[D,V]=i.useState(0),[v,O]=i.useState(!1),P=Re(z=>z.wideChatLayoutEnabled),E=Re(z=>z.mobileKeyboardMode),B=i.useMemo(()=>gr(),[]),T=kc(z=>z.setPlanModeEnabled),[W,U]=i.useState(()=>Pd()),[L,M]=i.useState(()=>{const z=Id();return z!==null?Rd({isDesktopShell:!0,bootOutcome:z}):null}),ee=i.useRef(!1),ie=i.useMemo(()=>LC(),[]),X=!ie||C,H=i.useMemo(()=>BC(),[]);i.useEffect(()=>(Ed(x),()=>{Ed(!1)}),[x]),i.useEffect(()=>{Ip(E)},[E]),i.useEffect(()=>{h(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>em(z=>{xb(z),V(K=>K+1),N(!1),y(K=>K+1)}),[]);const te=Xd(z=>{const K=Md();return Object.values(z.runsByOriginalSessionID).filter(q=>q.status==="running"&&q.runtimeKey===K).map(q=>`${q.originalSessionID}:${q.phase}:${q.lastForwardedMessageID??""}:${q.expectedAssistantParentID??""}`).sort().join("|")});i.useEffect(()=>{if(ie)return;const z=Md(),K=Object.values(Xd.getState().runsByOriginalSessionID).filter(q=>q.status==="running"&&q.runtimeKey===z);for(const q of K)Mx(q.originalSessionID)},[te,ie,D]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",P),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[P]),i.useEffect(()=>(Fd(t),()=>Fd(null)),[t]),i.useEffect(()=>{ie||w(t.github,{force:!0})},[t.github,ie,w]),Fx();const re=W==="valid",le=L?.screen==="main";i.useEffect(()=>{if(!Rp({isDesktopShell:B,isInitialized:n,bootOutcomeKnown:re,bootViewIsMain:le}))return;const z=setTimeout(()=>{const K=document.getElementById("initial-loading");K&&(K.classList.add("fade-out"),setTimeout(()=>{K.remove()},300))},150);return()=>clearTimeout(z)},[B,n,re,le]),i.useEffect(()=>{if(!B||W!=="malformed")return;const z=document.getElementById("initial-loading");z&&(z.textContent="Desktop startup failed — please restart the app.")},[B,W]),i.useEffect(()=>{if(B)return;const z=setTimeout(()=>{const K=document.getElementById("initial-loading");K&&!n&&(K.classList.add("fade-out"),setTimeout(()=>{K.remove()},300))},5e3);return()=>clearTimeout(z)},[B,n]),i.useEffect(()=>{let z=!1;return(async()=>{const q=await Ps("/health",{method:"GET"}).catch(()=>null);if(!q||!q.ok||z)return;const me=await q.json().catch(()=>null);if(!me||z)return;const Se=me.planModeExperimentalEnabled;T(Se===!0||Se===1||Se==="1"||Se==="true")})(),()=>{z=!0}},[T]),i.useEffect(()=>{g||e()},[e,g]),i.useEffect(()=>{if(g||n)return;let z=!0,K,q=0;const me=10,Se=1e3,Be=async()=>{if(!z)return;if(q>=me){N(!0);return}const _e=is.getState();if(_e.isInitialized){N(!1);return}q+=1,await _e.initializeApp();const Le=is.getState();if(!z)return;if(Le.isInitialized){N(!1);return}if(q>=me){N(!0);return}const pe=Math.min(Se*Math.pow(2,q-1),16e3);K=setTimeout(Be,pe)};return K=setTimeout(Be,Se),()=>{z=!1,K&&clearTimeout(K)}},[k,n,g]),i.useEffect(()=>{n&&N(!1)},[n]),i.useEffect(()=>{if(!S)return;const z=document.getElementById("initial-loading");z&&(z.classList.add("fade-out"),setTimeout(()=>{z.remove()},300))},[S]),i.useEffect(()=>{if(g||!r||o>0&&a>0)return;let z=!0,K=0;const q=15,me=async()=>{const Be=is.getState();if(!(Be.providers.length>0&&Be.agents.length>0))try{Be.providers.length===0&&await c({source:"startupRecovery"}),is.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};me();const Se=setInterval(()=>{if(z){if(++K>=q){clearInterval(Se);return}me()}},2e3);return()=>{z=!1,clearInterval(Se)}},[r,g,l,c,o,a]),i.useEffect(()=>{p||g||r&&Xn.setDirectory(m)},[m,p,r,g]),i.useEffect(()=>{if(!ie||typeof window>"u")return;const z=me=>{const Se=me?.visible===!0;j(Se)},K=me=>{if(me.origin!==window.location.origin)return;const Se=me.data;Se?.type==="openchamber:embedded-visibility"&&z(Se.payload)},q=window;return q.__openchamberSetEmbeddedVisibility=z,window.addEventListener("message",K),()=>{window.removeEventListener("message",K),q.__openchamberSetEmbeddedVisibility===z&&delete q.__openchamberSetEmbeddedVisibility}},[ie]),i.useEffect(()=>{!ie?.directory||g||m!==ie.directory&&u(ie.directory,{showOverlay:!1})},[m,ie,g,u]),i.useEffect(()=>{if(!ie||typeof window>"u")return;const z=K=>{K.storageArea===window.localStorage&&K.key==="ui-store"&&Re.persist.rehydrate()};return window.addEventListener("storage",z),()=>{window.removeEventListener("storage",z)}},[ie]),i.useEffect(()=>{if(typeof window>"u")return;const z=K=>{const q=K.detail,me=typeof q?.sessionId=="string"?q.sessionId.trim():"";if(!me)return;const Se=typeof q?.directory=="string"&&q.directory.trim().length>0?q.directory.trim():null;Re.getState().setActiveMainTab("chat"),mt.getState().setCurrentSession(me,Se)};return window.addEventListener("openchamber:open-session",z),()=>window.removeEventListener("openchamber:open-session",z)},[]),i.useEffect(()=>{if(typeof window>"u")return;const z=()=>{const K=Xs.getState().currentDirectory,{activeProjectId:q,projects:me}=Ds.getState(),Se=me.find(Be=>Be.id===q)??null;Zr("desktop_open_draft_mini_chat_window",{directory:K||Se?.path||"",projectId:Se?.id??null})};return window.addEventListener("openchamber:open-mini-chat",z),()=>window.removeEventListener("openchamber:open-mini-chat",z)},[]),i.useEffect(()=>{if(typeof window>"u")return;const z=()=>{const K=mt.getState().currentSessionId;K&&xm(K)};return window.addEventListener("focus",z),()=>window.removeEventListener("focus",z)},[]),i.useEffect(()=>{if(typeof window>"u")return;const z=K=>{const q=K.detail,me=typeof q?.directory=="string"&&q.directory.trim().length>0?q.directory.trim():null,Se=typeof q?.projectId=="string"&&q.projectId.trim().length>0?q.projectId.trim():null;Re.getState().setActiveMainTab("chat"),Re.getState().setSessionSwitcherOpen(!1),mt.getState().openNewSessionDraft({selectedProjectId:Se,directoryOverride:me,preserveDirectoryOverride:!!me})};return window.addEventListener("openchamber:open-draft-session",z),()=>window.removeEventListener("openchamber:open-draft-session",z)},[]),i.useEffect(()=>{if(typeof window>"u")return;const z=K=>{const q=K.detail,me=typeof q?.projectPath=="string"?q.projectPath.trim():"";if(!me)return;const Se=Ds.getState(),Be=Se.projects.find(_e=>_e.path===me);Be?Se.setActiveProject(Be.id):Se.addProject(me)};return window.addEventListener("openchamber:open-project",z),()=>window.removeEventListener("openchamber:open-project",z)},[]),i.useEffect(()=>{typeof window>"u"||!n||p||ee.current||(ee.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,p]),Ox({enabled:X}),TC({enabled:X}),IC(),Lx(),bb();const ve=i.useCallback(()=>{b(z=>!z)},[]);fC(ve),kC(),i.useEffect(()=>{if(ie)return;const z=K=>{Cc(K)&&K.shiftKey&&!K.altKey&&(K.code==="KeyD"||K.key.toLowerCase()==="d")&&(K.preventDefault(),b(me=>!me))};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[ie]),i.useEffect(()=>{ie||d&&setTimeout(()=>f(),5e3)},[f,ie,d]),i.useEffect(()=>{if(!B||W!=="not-injected")return;let z=!1,K=0;const q=200,me=2e3,Se=50,Be=()=>{if(z)return;K++;const _e=Pd();if(_e!=="not-injected"){if(z=!0,U(_e),_e==="valid"){const pe=Id();pe&&M(Rd({isDesktopShell:!0,bootOutcome:pe}))}return}const Le=Math.min(q*Math.pow(1.1,K),me);if(K>=Se){const pe=document.getElementById("initial-loading");pe&&!pe.textContent?.includes("taking longer")&&(pe.textContent="Desktop startup is taking longer than expected...")}window.setTimeout(Be,Le)};return window.setTimeout(Be,q),()=>{z=!0}},[B,W]);const ne=i.useCallback(async()=>{if(Ep({isDesktopShell:gr(),isDesktopLocalOriginActive:to()})){await Mp();return}window.location.reload()},[]),we=i.useCallback(async()=>{if(!v){N(!1),O(!0);try{await is.getState().initializeApp()}finally{O(!1)}is.getState().isInitialized||y(z=>z+1)}},[v]),he=z=>{if(z.screen==="recovery")return z.variant};if(B&&L&&L.screen!=="main"){if(L.screen==="chooser")return s.jsx(on,{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(Wf,{mode:"first-launch",onCliAvailable:ne,onChooseRemote:()=>{}})})})});const z=he(L),K=L.screen==="recovery"&&"url"in L?L.url:void 0;return s.jsx(on,{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(Wf,{mode:"recovery",recoveryVariant:z,recoveryHostUrl:K,recoveryHostLabel:void 0,onCliAvailable:ne})})})})}if(ie)return s.jsx(on,{children:s.jsx(Zd,{sdk:Xn.getSdkClient(),directory:m||"",children:s.jsx(eu,{apis:t,children:s.jsx(tu,{delayDuration:300,skipDelayDuration:150,children:s.jsx("div",{className:"h-full text-foreground bg-background",children:s.jsx(VC,{embeddedSessionChat:ie,isVSCodeRuntime:g,embeddedBackgroundWorkEnabled:X})})})})},D)});if(H)return s.jsx(on,{children:s.jsx(MC,{})});if(S&&!n&&!g&&!ie)return s.jsx(on,{children:s.jsx(OC,{onRetry:()=>{we()},isRetrying:v})});const Me=!n&&!B;return s.jsx(on,{children:s.jsx(Zd,{sdk:Xn.getSdkClient(),directory:m||"",children:s.jsx(eu,{apis:t,children:s.jsx(Jw,{children:s.jsx(tu,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:B?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(Am,{embeddedBackgroundWorkEnabled:X}),s.jsx(Bm,{}),s.jsx(Qk,{}),s.jsx(Dm,{}),!Me&&s.jsxs(s.Fragment,{children:[s.jsx(wb,{}),s.jsx(FC,{}),x&&s.jsx(Zk,{onClose:()=>b(!1)})]})]})})})})},D)})}function $C(t){return t.isAboutDialogOpen}function zC(t){return t.setAboutDialogOpen}function WC(t){return t.currentDirectory}function UC(t){return t.currentSessionId}function HC(t){return t.setCurrentSession}const GC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();Bx();Fp().then(()=>{Promise.all([Op(),Vx()]).catch(t=>{console.error("[main] settings init failed:",t)}),_x(),$x(),zx()}).catch(t=>{console.error("[main] appearance init failed:",t)});const Bh=document.getElementById("root");if(!Bh)throw new Error("Root element not found");pp.createRoot(Bh).render(s.jsx(nt.StrictMode,{children:s.jsx(Wx,{children:s.jsx(Ux,{children:s.jsx(Hx,{children:s.jsx(Gx,{children:s.jsx(_C,{apis:GC})})})})})}));const t3=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{I1 as D,zk as M,t3 as m,Us as u};