@openchamber/web 1.13.3 → 1.13.5

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 (129) hide show
  1. package/bin/cli-output.js +2 -7
  2. package/bin/cli-output.test.js +36 -0
  3. package/bin/cli.js +132 -5548
  4. package/bin/cli.test.js +686 -0
  5. package/bin/lib/DOCUMENTATION.md +121 -0
  6. package/bin/lib/cli-args.js +726 -0
  7. package/bin/lib/cli-errors.js +18 -0
  8. package/bin/lib/cli-executables.js +54 -0
  9. package/bin/lib/cli-http.js +216 -0
  10. package/bin/lib/cli-lifecycle.js +421 -0
  11. package/bin/lib/cli-log-files.js +93 -0
  12. package/bin/lib/cli-network.js +154 -0
  13. package/bin/lib/cli-paths.js +113 -0
  14. package/bin/lib/cli-ports.js +51 -0
  15. package/bin/lib/cli-process.js +292 -0
  16. package/bin/lib/cli-startup.js +370 -0
  17. package/bin/lib/cli-tunnel-capabilities.js +9 -0
  18. package/bin/lib/cli-tunnel-profiles.js +366 -0
  19. package/bin/lib/cli-tunnel-utils.js +300 -0
  20. package/bin/lib/commands-connect-url.js +173 -0
  21. package/bin/lib/commands-lifecycle.js +396 -0
  22. package/bin/lib/commands-logs.js +110 -0
  23. package/bin/lib/commands-serve.js +396 -0
  24. package/bin/lib/commands-startup.js +64 -0
  25. package/bin/lib/commands-status.js +114 -0
  26. package/bin/lib/commands-tunnel.js +1761 -0
  27. package/bin/lib/commands-update.js +141 -0
  28. package/dist/assets/{DiagramView-BmHROYsX.js → DiagramView-Bbj-QI7h.js} +1 -1
  29. package/dist/assets/{MarkdownRendererImpl-DiJE-v5Q.js → MarkdownRendererImpl-BNr_9Jsb.js} +3 -3
  30. package/dist/assets/MultiRunWindow-DMMu53kw.js +1 -0
  31. package/dist/assets/NewWorktreeDialog-5TYBoMMA.js +167 -0
  32. package/dist/assets/{OnboardingScreen-DpBF8dKJ.js → OnboardingScreen-BucKVBD7.js} +1 -1
  33. package/dist/assets/{SessionSwitcherDropdown-1xaHUxPK.js → SessionSwitcherDropdown-B6kvduse.js} +1 -1
  34. package/dist/assets/{SettingsWindow-ChwLyQAe.js → SettingsWindow-BEfDro9b.js} +1 -1
  35. package/dist/assets/{TerminalView-DGEBNuAp.js → TerminalView-CMdqMpTy.js} +1 -1
  36. package/dist/assets/es-Bk-yR0w-.js +15 -0
  37. package/dist/assets/fr-f1ibV7QU.js +13 -0
  38. package/dist/assets/index-B82A6jBD.css +1 -0
  39. package/dist/assets/index-BsXkdBYx.js +3 -0
  40. package/dist/assets/ja-D9mS3zWP.js +15 -0
  41. package/dist/assets/ko-Cpl1IA3D.js +15 -0
  42. package/dist/assets/main-DOdUrt3s.js +214 -0
  43. package/dist/assets/{main-fm_8J7Lk.js → main-KEVf2Yak.js} +2 -2
  44. package/dist/assets/miniChat-Nlzqr3Df.js +2 -0
  45. package/dist/assets/mobile-BIhOFhia.js +2 -0
  46. package/dist/assets/pl-CYke_fxL.js +15 -0
  47. package/dist/assets/pt-BR-Clb6Z8up.js +15 -0
  48. package/dist/assets/renderElectronMiniChatApp-Cb1iUq8M.js +2 -0
  49. package/dist/assets/{renderMobileApp-6s0G1iIJ.js → renderMobileApp-7chEBHPK.js} +5 -5
  50. package/dist/assets/uk-CXn8cxXa.js +15 -0
  51. package/dist/assets/{useAppFontEffects-CV5C5O0r.js → useAppFontEffects-Bd0ks39c.js} +124 -119
  52. package/dist/assets/{vendor-.bun-CC_Xso_s.js → vendor-.bun-By2L9XvG.js} +1 -1
  53. package/dist/assets/zh-CN-BRwwlEdG.js +15 -0
  54. package/dist/assets/zh-TW-D5pg5Z8l.js +15 -0
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +4 -4
  57. package/dist/mobile.html +4 -4
  58. package/package.json +1 -1
  59. package/server/lib/cloudflare-tunnel.js +2 -2
  60. package/server/lib/event-stream/global-hub.js +1 -1
  61. package/server/lib/event-stream/index.js +0 -12
  62. package/server/lib/event-stream/runtime.js +1 -1
  63. package/server/lib/git/routes.test.js +4 -4
  64. package/server/lib/git/service.js +18 -0
  65. package/server/lib/git/service.test.js +48 -0
  66. package/server/lib/github/routes.js +1 -0
  67. package/server/lib/notifications/index.js +1 -4
  68. package/server/lib/opencode/agents.js +0 -6
  69. package/server/lib/opencode/commands.js +0 -5
  70. package/server/lib/opencode/config-entity-routes.js +39 -21
  71. package/server/lib/opencode/feature-routes-runtime.js +27 -62
  72. package/server/lib/opencode/lifecycle.js +13 -1
  73. package/server/lib/opencode/npm-registry.js +3 -3
  74. package/server/lib/opencode/proxy.js +3 -3
  75. package/server/lib/opencode/shared.js +0 -6
  76. package/server/lib/opencode/skills.js +0 -2
  77. package/server/lib/opencode/snippets.js +0 -2
  78. package/server/lib/package-manager.js +4 -4
  79. package/server/lib/package-manager.test.js +8 -1
  80. package/server/lib/projects/project-config.js +0 -8
  81. package/server/lib/quota/DOCUMENTATION.md +3 -1
  82. package/server/lib/quota/providers/claude.js +1 -1
  83. package/server/lib/quota/providers/codex.js +1 -1
  84. package/server/lib/quota/providers/copilot.js +1 -1
  85. package/server/lib/quota/providers/cursor.js +1 -1
  86. package/server/lib/quota/providers/google/auth.js +2 -2
  87. package/server/lib/quota/providers/google/index.js +14 -33
  88. package/server/lib/quota/providers/google/transforms.js +1 -1
  89. package/server/lib/quota/providers/index.js +4 -4
  90. package/server/lib/quota/providers/index.test.js +17 -0
  91. package/server/lib/quota/providers/kimi.js +1 -1
  92. package/server/lib/quota/providers/minimax-cn-coding-plan.js +1 -1
  93. package/server/lib/quota/providers/minimax-coding-plan.js +1 -1
  94. package/server/lib/quota/providers/nanogpt.js +1 -1
  95. package/server/lib/quota/providers/ollama-cloud.js +1 -1
  96. package/server/lib/quota/providers/openai.js +4 -4
  97. package/server/lib/quota/providers/openrouter.js +1 -1
  98. package/server/lib/quota/providers/wafer.js +1 -1
  99. package/server/lib/quota/providers/zai.js +1 -1
  100. package/server/lib/quota/providers/zhipuai-coding-plan.js +1 -1
  101. package/server/lib/skills-catalog/cache.js +0 -4
  102. package/server/lib/skills-catalog/clawdhub/api.js +0 -32
  103. package/server/lib/skills-catalog/clawdhub/scan.js +0 -52
  104. package/server/lib/skills-catalog/curated-sources.js +1 -1
  105. package/server/lib/skills-catalog/source.js +5 -0
  106. package/server/lib/terminal/runtime.js +11 -9
  107. package/server/lib/text/summarization.js +1 -1
  108. package/server/lib/tunnels/types.js +2 -2
  109. package/dist/assets/MultiRunWindow-yZoCT7F7.js +0 -1
  110. package/dist/assets/NewWorktreeDialog-CTMiE7Xd.js +0 -167
  111. package/dist/assets/es-CTE-E8we.js +0 -15
  112. package/dist/assets/fr-TVkZpyEo.js +0 -13
  113. package/dist/assets/index-B4pCDMbq.css +0 -1
  114. package/dist/assets/index-D9uMvTQF.js +0 -3
  115. package/dist/assets/ko-D_UCJIIL.js +0 -15
  116. package/dist/assets/main-eAd3a6tx.js +0 -214
  117. package/dist/assets/miniChat-Bbjg31IC.js +0 -2
  118. package/dist/assets/mobile-B3_j_DsB.js +0 -2
  119. package/dist/assets/pl-nDEkk-GZ.js +0 -15
  120. package/dist/assets/pt-BR-B_g2RcgU.js +0 -15
  121. package/dist/assets/renderElectronMiniChatApp-CB13zs6N.js +0 -2
  122. package/dist/assets/uk-CWLhnPGW.js +0 -15
  123. package/dist/assets/zh-CN-BFxe1b5m.js +0 -15
  124. package/dist/assets/zh-TW-n-d-xbGV.js +0 -15
  125. package/server/lib/opencode/index.js +0 -95
  126. package/server/lib/quota/providers/interface.js +0 -55
  127. package/server/lib/skills-catalog/clawdhub/index.js +0 -30
  128. package/server/lib/skills-catalog/index.js +0 -42
  129. package/server/lib/terminal/index.js +0 -31
@@ -1,214 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalView-DGEBNuAp.js","assets/vendor-.bun-CC_Xso_s.js","assets/vendor--Dwc_TRgJ.css","assets/useAppFontEffects-CV5C5O0r.js","assets/index-D9uMvTQF.js","assets/index-B4pCDMbq.css","assets/NewWorktreeDialog-CTMiE7Xd.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-1xaHUxPK.js","assets/DiagramView-BmHROYsX.js","assets/SettingsWindow-ChwLyQAe.js","assets/MultiRunWindow-yZoCT7F7.js","assets/OnboardingScreen-DpBF8dKJ.js"])))=>i.map(i=>d[i]);
2
- import{j as s,e as gt,a as io,R as i,d as Sf,p as ic,b as Nf,H as tt,I as kf,u as ga,l as yo,n as xa,D as ba,q as ya,S as Ll,v as Ol,w as oc,C as ac,L as Bl,N as Ah,O as Dh,T as Ih,W as Ph,X as si,Y as Th,$ as Rh,F as Eh,a0 as Mh,a1 as Fh,a2 as Lh,a3 as Cf,a4 as Oh,a5 as Bh,a6 as Vl,a7 as Vh,s as _h,m as $h,a8 as id,a9 as od,aa as ad,ab as zh,ac as Wh,ad as Uh,ae as Hh,af as Gh,ag as Kh,_ as oo,ah as ld,ai as cd,aj as dd,G as qh}from"./vendor-.bun-CC_Xso_s.js";import{f as lc,h as hr,j as Xi,k as ud,l as Yh,m as wa,n as Af,p as Qh,e as As,q as Lo,b as Ee,t as Jh,v as Fa,w as Hr,a as zr,x as Wr,y as _l,z as Xh,A as Zh,R as fd,B as md,u as Qs,C as ep,D as ki,E as Df,F as If,G as cc,o as zn,H as tp,g as Ai,I as sp,r as dc,J as np,K as uc,L as Pf,M as rp,N as ip,O as na,P as ra,Q as op,S as ap,T as lp,U as hd,V as pd,W as gd,X as xd,Y as cp,Z as dp,d as bd,_ as up,$ as fp,a0 as mp,i as hp,s as pp}from"./index-D9uMvTQF.js";import{u as kt,m as De,ap as bs,I,p as pr,t as de,aq as tn,ar as Rr,as as sn,at as nn,a as er,au as Er,av as Pi,aw as yd,ax as Rt,ay as Et,az as Mt,aA as gp,ad as Do,aB as va,aC as ni,ae as Io,af as Tf,a6 as fc,aD as Rf,aE as xp,Q as ss,z as ut,aF as bp,a8 as Ef,y as jr,x as mc,D as ws,R as Ti,aG as Mf,aH as Ff,aI as ja,aJ as Lf,aK as Of,a5 as Bf,aL as Vf,aM as _f,aN as yp,aO as wp,T as hc,aP as La,aQ as ri,aR as pc,aS as ia,X as en,aT as vp,aU as $f,aV as jp,aW as zf,aX as gc,aY as Us,aZ as _s,B as $e,a_ as Ls,a$ as Os,b0 as li,b1 as Sp,b2 as Np,b3 as zo,b4 as Fn,b5 as Wf,b6 as Uf,a2 as xc,b7 as kp,b8 as wd,b9 as vd,ba as Ci,n as vn,bb as Ri,bc as Zi,bd as Cp,be as Ap,bf as Dp,bg as Ip,bh as Oa,bi as Ba,bj as Va,bk as _a,bl as ii,bm as ai,bn as Pp,bo as Tp,bp as an,bq as Rp,br as Ep,bs as Mp,bt as Fp,bu as Lp,k as Di,bv as bc,bw as Op,bx as Bp,by as Vp,bz as _p,bA as $p,bB as zp,bC as Wp,bD as Wn,bE as Un,bF as Hn,bG as Cn,bH as Gn,bI as Ts,bJ as Up,w as Po,M as $a,S as za,bK as Hp,bL as ar,bM as Gp,b as ci,d as yc,c as Wa,bN as Kp,bO as Hf,bP as qp,bQ as Yp,e as wc,bR as Qp,f as wn,bS as Ua,a3 as Pr,j as Jp,bT as Xp,bU as nl,bV as Zp,bW as eg,F as Ur,bX as vc,bY as Ha,bZ as yn,b_ as Ei,l as eo,b$ as Gf,c0 as tg,c1 as sg,c2 as ng,c3 as jd,c4 as rg,q as Gr,r as Sd,v as Nd,c5 as kd,c6 as Kf,c7 as Cd,c8 as Ad,c9 as qf,ca as ig,cb as Yf,o as Dd,J as og,cc as rl,cd as jc,ce as ag,cf as lg,cg,ch as Oo,ci as dg,cj as Sc,ck as ug,cl as Nc,cm as Qf,cn as Wo,co as fg,cp as Tr,cq as mg,cr as Jf,cs as hg,ct as pg,cu as Id,cv as Xf,cw as Zf,cx as em,E as kc,P as Ga,G as Ka,L as Sa,cy as Na,cz as Vn,H as gg,K as xg,cA as bg,cB as $l,cC as yg,cD as wg,cE as vg,cF as Pd,cG as jg,cH as Sg,cI as Ng,cJ as Cc,cK as tm,cL as kg,cM as Cg,cN as Ag,cO as Dg,cP as Td,cQ as Rd,cR as Ig,cS as Pg,cT as Tg,cU as Rg,cV as Eg,cW as Mg,N as Fg,cX as Ed,cY as Lg,cZ as sm,O as Og,c_ as Bg,A as Vg,C as _g,c$ as $g,d0 as zg,d1 as Wg,d2 as Ug,d3 as Hg,d4 as Gg,d5 as Kg,d6 as ka,d7 as qg,d8 as Md,d9 as Yg,da as Qg,db as Jg,dc as ao,dd as Xg,de as Fd,df as Zg,dg as ex,dh as tx,di as sx,dj as nm,dk as rm,dl as nx,dm as rx,dn as ix,dp as oa,aa as ox,dq as ax,dr as lx,U as cx,V as dx,W as ux,Y as Ld,Z as Od,_ as Bd,ds as fx,$ as im,a0 as om,dt as mx,ak as hx,al as px,am as gx,an as xx,ao as bx,ag as yx,ah as wx,ai as vx,aj as jx}from"./useAppFontEffects-CV5C5O0r.js";import{I as Vd,o as Sx,p as _d,q as Nx,r as $d,t as Qr,s as kx,v as il,w as To,U as Ca,x as Aa,y as to,z as Bo,B as so,k as am,M as lm,i as fn,j as Cx,E as Ax,F as Dx,G as Ix,l as zl,H as cm,P as dm,J as Px,K as Tx,C as Rx,a as Ex,L as Ac,Q as um,R as Dc,T as Ic,V as Pc,W as fm,X as mm,Y as Wl,Z as hm,_ as Ul,$ as aa,a0 as Mx,a1 as Fx,e as wo,N as Lx,D as Ox,u as Bx,n as Vx,m as Hl,a2 as _x,a3 as $x,g as zx,a4 as Wx,a5 as Ux,c as Hx,O as pm,d as Gx,a6 as Kx}from"./NewWorktreeDialog-CTMiE7Xd.js";import{S as qx,C as Yx,W as Qx,g as Tc,r as Jx,n as as,i as Ro,d as no,c as Ki,a as zd,b as Xx,e as vo,f as gm,h as Zx,j as eb,u as ol}from"./SessionSwitcherDropdown-1xaHUxPK.js";function xm(t){const{drafts:e,editingDraftId:n,commentText:r,onTextChange:o,selection:a,isDragging:c,fileLabel:l,newWidgetId:d,mapDraftToRange:u,onSave:m,onCancel:f,onEdit:g,onDelete:y}=t,p=[];for(const x of e){const b=u(x);if(x.id===n){p.push({afterLine:b.end,id:`edit-${x.id}`,content:s.jsx(Vd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:b,isEditing:!0,onSave:m,onCancel:f},`edit-${x.id}`)});continue}p.push({afterLine:b.end,id:`card-${x.id}`,content:s.jsx(Sx,{draft:x,onEdit:()=>g(x),onDelete:()=>y(x)},`card-${x.id}`)})}if(a&&!n&&!c){const x={...a,start:Math.min(a.start,a.end),end:Math.max(a.start,a.end)};p.push({afterLine:x.end,id:d,content:s.jsx(Vd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:x,isEditing:!1,onSave:m,onCancel:f},d)})}return p}function Wd(t){const e=gt.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const c=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let d;e[5]!==a||e[6]!==c||e[7]!==l?(d={width:c,height:l,...a},e[5]=a,e[6]=c,e[7]=l,e[8]=d):d=e[8];let u;e[9]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"}),e[9]=u):u=e[9];let m;return e[10]!==n||e[11]!==r||e[12]!==d?(m=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:d,...r,children:u}),e[10]=n,e[11]=r,e[12]=d,e[13]=m):m=e[13],m}const oi=[{id:"finder",label:"Finder",appName:"Finder"},{id:"terminal",label:"Terminal",appName:"Terminal"},{id:"iterm2",label:"iTerm2",appName:"iTerm"},{id:"ghostty",label:"Ghostty",appName:"Ghostty"},{id:"vscode",label:"VS Code",appName:"Visual Studio Code"},{id:"intellij",label:"IntelliJ",appName:"IntelliJ IDEA"},{id:"visual-studio",label:"Visual Studio",appName:"Visual Studio"},{id:"cursor",label:"Cursor",appName:"Cursor"},{id:"android-studio",label:"Android Studio",appName:"Android Studio"},{id:"pycharm",label:"PyCharm",appName:"PyCharm"},{id:"xcode",label:"Xcode",appName:"Xcode"},{id:"sublime-text",label:"Sublime",appName:"Sublime Text"},{id:"webstorm",label:"WebStorm",appName:"WebStorm"},{id:"rider",label:"Rider",appName:"Rider"},{id:"zed",label:"Zed",appName:"Zed"},{id:"phpstorm",label:"PhpStorm",appName:"PhpStorm"},{id:"eclipse",label:"Eclipse",appName:"Eclipse"},{id:"windsurf",label:"Windsurf",appName:"Windsurf"},{id:"vscodium",label:"VSCodium",appName:"VSCodium"},{id:"rustrover",label:"RustRover",appName:"RustRover"},{id:"kiro",label:"Kiro",appName:"Kiro"},{id:"antigravity",label:"Antigravity",appName:"Antigravity"},{id:"trae",label:"Trae",appName:"Trae"}],Gl="finder",Kl=new Set(["finder","terminal"]),Rc=t=>typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32"&&t.id==="finder"?{...t,label:"Explorer",appName:"File Explorer"}:t,ql=t=>{if(!t)return null;const e=oi.find(n=>n.id===t)??null;return e?Rc(e):null},al=()=>oi.filter(t=>Kl.has(t.id)).map(t=>({...Rc(t)})),tb=()=>{if(typeof window>"u")return Gl;const t=window.localStorage.getItem("openInAppId");return t&&ql(t)?t:Gl};let ll=!1,_i=!1,Jr=!1,Xr=0,jo=null;const Ud=()=>{jo&&(clearTimeout(jo),jo=null)},wr=io()((t,e)=>({selectedAppId:tb(),availableApps:al(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(ll||typeof window>"u")return;ll=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:al(),hasLoadedApps:u});return}const m=new Set(d.map(p=>p.name)),f=new Map(d.map(p=>[p.name,p.iconDataUrl??void 0])),y=oi.filter(p=>m.has(p.appName)||Kl.has(p.id)).map(p=>({...Rc(p),iconDataUrl:f.get(p.appName)}));t({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!hr()||!Xi()||_i||e().hasLoadedApps&&!d)return;const m=oi.map(f=>f.appName);Ud(),_i=!0,Jr=!1,t({isScanning:!0});try{const{apps:f,success:g,hasCache:y,isCacheStale:p}=await ud(m,d),x=g&&!y&&f.length===0&&Xr<3;if(t({isCacheStale:y?p:!1}),n(f,g?!x:!1),g){if(x){const h=[800,1600,3200][Xr]??3200;Xr+=1,Jr=!0,jo=setTimeout(()=>{r()},h);return}Xr=0,Jr=!1;return}if(Xr<3){const h=[1e3,3e3,7e3][Xr]??7e3;Xr+=1,Jr=!0,jo=setTimeout(()=>{r()},h)}}finally{_i=!1,Jr||t({isScanning:!1})}};r();const o=d=>{const u=d.detail,m=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&ql(u.openInAppId)?u.openInAppId:null;m&&(window.localStorage.setItem("openInAppId",m),t({selectedAppId:m}))},a=()=>{r()},c=d=>{const u=d.detail;Array.isArray(u)&&(Xr=3,Jr=!1,t({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("openchamber:settings-synced",o),window.addEventListener("openchamber:app-ready",a),window.addEventListener("openchamber:installed-apps-updated",c),window.__openchamberAppReady&&r(),window.setTimeout(()=>{e().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(ll||e().initialize(),!hr()||!Xi()||_i||e().hasLoadedApps&&!n)return;const o=oi.map(a=>a.appName);Ud(),n&&t({hasLoadedApps:!1}),_i=!0,Jr=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await ud(o,n),d=new Set(a.map(g=>g.name)),u=new Map(a.map(g=>[g.name,g.iconDataUrl??void 0])),f=oi.filter(g=>d.has(g.appName)||Kl.has(g.id)).map(g=>({...g,iconDataUrl:u.get(g.appName)}));t({availableApps:f.length>0?f:al(),hasLoadedApps:f.length>0,isCacheStale:c?l:!1})}finally{_i=!1,Jr||t({isScanning:!1})}},selectApp:async n=>{ql(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await lc({openInAppId:n}))}})),sb="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",nb="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",cl=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__OPENCHAMBER_PLATFORM__!=="win32"?sb:t.id==="terminal"?nb:void 0}),Hd=t=>{const e=gt.c(8),{label:n,iconDataUrl:r,fallbackIconDataUrl:o}=t,[a,c]=i.useState(!1);let l;e[0]!==n?(l=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=l):l=e[1];const d=l,u=r||o;if(u&&!a){let g;e[2]===Symbol.for("react.memo_cache_sentinel")?(g=()=>c(!0),e[2]=g):g=e[2];let y;return e[3]!==u?(y=s.jsx("img",{src:u,alt:"",className:"h-4 w-4 rounded-sm",onError:g}),e[3]=u,e[4]=y):y=e[4],y}let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=De("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=m):m=e[5];let f;return e[6]!==d?(f=s.jsx("span",{className:m,children:d}),e[6]=d,e[7]=f):f=e[7],f},rb=t=>{const e=gt.c(75),{directory:n,className:r}=t,{t:o}=kt(),a=wr(ib),c=wr(ob),l=wr(ab),d=wr(lb),u=wr(cb),m=wr(db),f=wr(ub);let g,y;e[0]!==u?(g=()=>{u()},y=[u],e[0]=u,e[1]=g,e[2]=y):(g=e[1],y=e[2]),i.useEffect(g,y);const p=hr()&&Xi();let x;e:{let Ne;e[3]!==c||e[4]!==a?(Ne=c.find(q=>q.id===a)??c.find(fb)??c[0]??oi[0],e[3]=c,e[4]=a,e[5]=Ne):Ne=e[5];const J=Ne;if(J){let q;e[6]!==J?(q=cl(J),e[6]=J,e[7]=q):q=e[7],x=q;break e}let H;e[8]===Symbol.for("react.memo_cache_sentinel")?(H=cl(oi[0]),e[8]=H):H=e[8],x=H}const b=x;if(!p||!n||c.length===0)return null;let h;e[9]!==n?(h=async Ne=>{await Yh(n,Ne.id,Ne.appName)||await wa(n,Ne.appName)},e[9]=n,e[10]=h):h=e[10];const N=h;let w;e[11]!==N||e[12]!==f?(w=async Ne=>{await f(Ne.id),await N(Ne)},e[11]=N,e[12]=f,e[13]=w):w=e[13];const S=w;let j;e[14]!==n||e[15]!==o?(j=async()=>{(await pr(n)).ok&&de.success(o("openInApp.toast.pathCopied"))},e[14]=n,e[15]=o,e[16]=j):j=e[16];const k=j;let v;e[17]!==r?(v=De("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]=v):v=e[18];let D;e[19]!==N||e[20]!==b?(D=()=>{N(b)},e[19]=N,e[20]=b,e[21]=D):D=e[21];const A=d&&"animate-pulse";let C;e[22]!==A?(C=De("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",A),e[22]=A,e[23]=C):C=e[23];let O;e[24]!==b.label||e[25]!==o?(O=o("openInApp.actions.openInAria",{app:b.label}),e[24]=b.label,e[25]=o,e[26]=O):O=e[26];let T;e[27]!==b.fallbackIconDataUrl||e[28]!==b.iconDataUrl||e[29]!==b.label?(T=s.jsx(Hd,{label:b.label,iconDataUrl:b.iconDataUrl,fallbackIconDataUrl:b.fallbackIconDataUrl}),e[27]=b.fallbackIconDataUrl,e[28]=b.iconDataUrl,e[29]=b.label,e[30]=T):T=e[30];let E;e[31]!==C||e[32]!==O||e[33]!==T||e[34]!==D?(E=s.jsx("button",{type:"button",onClick:D,className:C,"aria-label":O,children:T}),e[31]=C,e[32]=O,e[33]=T,e[34]=D,e[35]=E):E=e[35];let F;e[36]===Symbol.for("react.memo_cache_sentinel")?(F=De("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]=F):F=e[36];let R;e[37]!==o?(R=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=R):R=e[38];let L;e[39]===Symbol.for("react.memo_cache_sentinel")?(L=s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=L):L=e[39];let B;e[40]!==R?(B=s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:F,"aria-label":R,children:L})}),e[40]=R,e[41]=B):B=e[41];let V;e[42]!==k?(V=()=>{k()},e[42]=k,e[43]=V):V=e[43];let M;e[44]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(I,{name:"file-copy",className:"h-4 w-4"}),e[44]=M):M=e[44];let Z;e[45]!==o?(Z=o("openInApp.actions.copyPath"),e[45]=o,e[46]=Z):Z=e[46];let se;e[47]!==Z?(se=s.jsx("span",{className:"typography-ui-label text-foreground",children:Z}),e[47]=Z,e[48]=se):se=e[48];let Q;e[49]!==V||e[50]!==se?(Q=s.jsxs(bs,{className:"flex items-center gap-2",onClick:V,children:[M,se]}),e[49]=V,e[50]=se,e[51]=Q):Q=e[51];let K;e[52]===Symbol.for("react.memo_cache_sentinel")?(K=s.jsx(Rr,{}),e[52]=K):K=e[52];let ee;if(e[53]!==c||e[54]!==S||e[55]!==b.id){let Ne;e[57]!==S||e[58]!==b.id?(Ne=J=>{const H=cl(J);return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{S(J)},children:[s.jsx(Hd,{label:J.label,iconDataUrl:J.iconDataUrl,fallbackIconDataUrl:H.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:J.label}),b.id===J.id?s.jsx(I,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},J.id)},e[57]=S,e[58]=b.id,e[59]=Ne):Ne=e[59],ee=c.map(Ne),e[53]=c,e[54]=S,e[55]=b.id,e[56]=ee}else ee=e[56];let re;e[60]!==l||e[61]!==m||e[62]!==o?(re=l?s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{m(!0)},children:[s.jsx(I,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:o("openInApp.actions.refreshApps")})]}):null,e[60]=l,e[61]=m,e[62]=o,e[63]=re):re=e[63];let he;e[64]!==Q||e[65]!==ee||e[66]!==re?(he=s.jsxs(sn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Q,K,ee,re]}),e[64]=Q,e[65]=ee,e[66]=re,e[67]=he):he=e[67];let je;e[68]!==B||e[69]!==he?(je=s.jsxs(nn,{children:[B,he]}),e[68]=B,e[69]=he,e[70]=je):je=e[70];let te;return e[71]!==E||e[72]!==je||e[73]!==v?(te=s.jsxs("div",{className:v,children:[E,je]}),e[71]=E,e[72]=je,e[73]=v,e[74]=te):te=e[74],te};function ib(t){return t.selectedAppId}function ob(t){return t.availableApps}function ab(t){return t.isCacheStale}function lb(t){return t.isScanning}function cb(t){return t.initialize}function db(t){return t.loadInstalledApps}function ub(t){return t.selectApp}function fb(t){return t.id===Gl}const mb=1e6,hb="terminal-store";let Gd=!1;const dl=t=>typeof t=="object"&&t!==null,pb=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function Rn(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const ul=(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}),fl=t=>({tabs:[t],activeTabId:t.id}),br=(t,e)=>t.tabs.findIndex(n=>n.id===e),Fs=io()(Sf(ic((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Rn(n);r&&t(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),c=`tab-${o.nextTabId}`,l=ul(c,"Terminal");return a.set(r,fl(l)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=Rn(n);return e().sessions.get(r)},getActiveTab:n=>{const r=Rn(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=Rn(n);if(!r)return"tab-invalid";const o=`tab-${e().nextTabId}`;return t(a=>{const c=new Map(a.sessions),l=c.get(r),d=a.nextTabId+1,m=`Terminal ${(l?.tabs.length??0)+1}`,f=ul(o,m);return l?c.set(r,{...l,tabs:[...l.tabs,f]}):c.set(r,fl(f)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Rn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);return!l||l.activeTabId===r||br(l,r)<0?a:(c.set(o,{...l,activeTabId:r}),{sessions:c})})},setTabLabel:(n,r,o)=>{const a=Rn(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),u=d.get(a);if(!u)return l;const m=br(u,r);if(m<0||u.tabs[m]?.label===c)return l;const f=[...u.tabs];return f[m]={...f[m],label:c},d.set(a,{...u,tabs:f}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=Rn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=o?.trim()||null;if(d.tabs[u]?.iconKey===m)return c;const f=[...d.tabs];return f[u]={...f[u],iconKey:m},l.set(a,{...d,tabs:f}),{sessions:l}})},closeTab:async(n,r)=>{const o=Rn(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await Qh(l)}catch{}t(d=>{const u=new Map(d.sessions),m=u.get(o);if(!m)return d;const f=br(m,r);if(f<0)return d;const g=m.tabs.filter(b=>b.id!==r),y=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,b])=>!(b.directory===o&&b.tabId===r))),p=Object.keys(y).length!==Object.keys(d.projectActionRuns).length;if(g.length===0){const b=`tab-${d.nextTabId}`,h=ul(b,"Terminal");return u.set(o,fl(h)),{sessions:u,nextTabId:d.nextTabId+1,...p?{projectActionRuns:y}:{}}}let x=m.activeTabId;return m.activeTabId===r&&(x=g[Math.min(f,g.length-1)]?.id??g[0]?.id??null),u.set(o,{...m,tabs:g,activeTabId:x}),{sessions:u,...p?{projectActionRuns:y}:{}}})},setTabSessionId:(n,r,o)=>{const a=Rn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=d.tabs[u],f=o!==null&&m.terminalSessionId!==o,g=o?"running":m.terminalSessionId?"exited":m.lifecycle,y={...m,terminalSessionId:o,lifecycle:g,isConnecting:!1,...f?{bufferChunks:[],bufferLength:0}:{}},p=[...d.tabs];return p[u]=y,l.set(a,{...d,tabs:p}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=Rn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=[...d.tabs];return m[u]={...m[u],lifecycle:o,isConnecting:!1},l.set(a,{...d,tabs:m}),{sessions:l}})},setConnecting:(n,r,o)=>{const a=Rn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=[...d.tabs];return m[u]={...m[u],isConnecting:o},l.set(a,{...d,tabs:m}),{sessions:l}})},appendToBuffer:(n,r,o)=>{if(!o)return;const a=Rn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=br(d,r);if(u<0)return c;const m=d.tabs[u],f=c.nextChunkId,g={id:f,data:o},y=[...m.bufferChunks,g];let p=m.bufferLength+o.length;for(;p>mb&&y.length>1;){const b=y.shift();if(!b)break;p-=b.data.length}const x=[...d.tabs];return x[u]={...m,bufferChunks:y,bufferLength:p},l.set(a,{...d,tabs:x}),{sessions:l,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=Rn(n);t(l=>{const d=new Map(l.sessions),u=d.get(c);if(!u)return l;const m=br(u,r);if(m<0)return l;const f=u.tabs[m],g=a.autoOpened??f.previewAutoOpened,y=a.locked??f.previewUrlLocked;if(f.previewUrl===o&&f.previewAutoOpened===g&&f.previewUrlLocked===y)return l;const p=[...u.tabs];return p[m]={...f,previewUrl:o,previewAutoOpened:g,previewUrlLocked:y},d.set(c,{...u,tabs:p}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Rn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=br(l,r);if(d<0)return a;const u=l.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const m=[...l.tabs];return m[d]={...u,previewAutoOpened:!0},c.set(o,{...l,tabs:m}),{sessions:c}})},setProjectActionRun:n=>{t(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{t(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{t(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},clearBuffer:(n,r)=>{const o=Rn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=br(l,r);if(d<0)return a;const u=[...l.tabs];return u[d]={...u[d],bufferChunks:[],bufferLength:0},c.set(o,{...l,tabs:u}),{sessions:c}})},removeDirectory:n=>{const r=Rn(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:hb,storage:Nf(()=>Af()),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(!dl(t))return e;const n=Array.isArray(t.sessions)?t.sessions:[],r=new Map;let o=0;for(const l of n){if(!Array.isArray(l)||l.length!==2)continue;const[d,u]=l;if(typeof d!="string"||!dl(u))continue;const m=Array.isArray(u.tabs)?u.tabs:[],f=[];for(const p of m){if(!dl(p))continue;const x=typeof p.id=="string"?p.id:null;if(!x)continue;const b=pb(x);b!==null&&(o=Math.max(o,b));const h=typeof p.terminalSessionId=="string"||p.terminalSessionId===null?p.terminalSessionId:null,N=p.lifecycle,w=N==="idle"||N==="running"||N==="exited"?N:h?"running":"idle";f.push({id:x,label:typeof p.label=="string"?p.label:"Terminal",iconKey:typeof p.iconKey=="string"?p.iconKey:null,terminalSessionId:h,lifecycle:w,createdAt:typeof p.createdAt=="number"?p.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(f.length===0)continue;const g=typeof u.activeTabId=="string"?u.activeTabId:null,y=g?f.some(p=>p.id===g):!1;r.set(d,{tabs:f,activeTabId:y?g:f[0].id})}const a=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,c=Math.max(e.nextTabId,a,o+1);return{...e,sessions:r,nextChunkId:1,nextTabId:c,hasHydrated:!0}}})));if(typeof window<"u"&&!Gd){Gd=!0;const t=Fs.persist,e=()=>{Fs.getState().hasHydrated||Fs.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const gb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],xb=["dev","start","preview","serve"];async function bb(t,e,n){if(!t)return null;const r=vb(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=jb(n);if(o){const a=await Sb(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 yb(t)){const o=await wb(),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 yb(t){const e=`${t}/index.html`,n=await Da(e,t);return typeof n=="string"&&n.trim().length>0}async function wb(){try{const t=await As("/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 vb(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(xb.some(o=>n.includes(o)))return e}return null}function jb(t){for(const{pattern:e}of gb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function Sb(t){const e=await Da(`${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 Da(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Da(t,e){if(e?.trim())try{const r=new URLSearchParams({path:t,directory:e,optional:"true"}),o=await As(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Lo()?.files;if(n?.readFile)try{const r=await n.readFile(t,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await As(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Nb(t){try{const e=await Da(`${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 kb=t=>new Promise(e=>{window.setTimeout(e,t)}),Cb="\x1B",Ab=new RegExp(`${Cb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Db=/https?:\/\/[^\s<>'"`]+/gi,rr="__openchamber_auto_discover_preview__",Ib=15e3,Pb=t=>{let e="";for(let n=0;n<t.length;n+=1){const r=t.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(e+=t[n])}return e},Tb=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}},Rb=t=>{const n=t.replace(Ab,"").match(Db);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const c=new URL(a);c.port&&c.port.length>0&&o.push({raw:a,parsed:c})}catch{}if(o.length>0){const a=c=>{const{parsed:l}=c,d=l.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",m=l.pathname||"/",f=m.split("/").filter(Boolean).length,g=m==="/"||m==="",y=!!(l.search||l.hash);let p=0;return u&&(p+=50),g&&(p+=30),p-=Math.min(f*5,20),y&&(p-=10),p};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},bm=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=kt(),{terminal:c,runtime:l}=er(),{isMobile:d}=Er(),u=i.useMemo(()=>hr(),[]),m=_d(_=>_.instances),f=_d(_=>_.load),g=Ee(_=>_.setBottomTerminalOpen),y=Ee(_=>_.setActiveMainTab),p=Ee(_=>_.setSettingsPage),x=Ee(_=>_.setSettingsDialogOpen),b=Ee(_=>_.setSettingsProjectsSelectedId),h=Ee(_=>_.openContextPreview),N=Fs(_=>_.sessions),w=Fs(_=>_.ensureDirectory),S=Fs(_=>_.setTabLabel),j=Fs(_=>_.setTabIconKey),k=Fs(_=>_.setActiveTab),v=Fs(_=>_.setConnecting),D=Fs(_=>_.setTabSessionId),A=Fs(_=>_.setTabPreviewUrl),C=Fs(_=>_.projectActionRuns),O=Fs(_=>_.setProjectActionRun),T=Fs(_=>_.updateProjectActionRunStatus),E=Fs(_=>_.removeProjectActionRun),[F,R]=i.useState([]),[L,B]=i.useState(null),[V,M]=i.useState(!1),Z=i.useRef({}),se=i.useRef({}),Q=i.useRef({}),K=i.useRef({}),ee=i.useRef(0),re=t?.id??null,he=t?.path??"",je=i.useMemo(()=>re?{id:re,path:he}:null,[re,he]);i.useEffect(()=>{u&&f().catch(()=>{})},[u,f]);const te=i.useCallback(async _=>{await Pi(_)},[]),Ne=i.useCallback(async()=>{if(!je)return;const _=ee.current+1;ee.current=_,M(!0);try{const ye=await yd(je);if(ee.current!==_)return;const $=ye.actions;R($),B(Ie=>Ie===rr||Ie&&$.some(ve=>ve.id===Ie)?Ie:null)}catch{if(ee.current!==_)return}finally{ee.current===_&&M(!1)}},[je]),J=i.useMemo(()=>Nx(e||je?.path||""),[e,je?.path]),H=i.useMemo(()=>L?F.find(_=>_.id===L)??null:null,[F,L]),q=i.useMemo(()=>({id:rr,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),ae=!d,le=i.useMemo(()=>ae?[q,...F]:F,[F,q,ae]);i.useEffect(()=>{Ne()},[Ne]),i.useEffect(()=>{if(typeof window>"u")return;const _=ye=>{const $=ye.detail;re&&($?.projectId&&$.projectId!==re||Ne())};return window.addEventListener($d,_),()=>{window.removeEventListener($d,_)}},[Ne,re]),i.useEffect(()=>{L&&(L===rr&&ae||F.some(_=>_.id===L)||B(null))},[F,ae,L]),i.useEffect(()=>{for(const[_,ye]of Object.entries(C)){const Ie=N.get(ye.directory)?.tabs.find(ve=>ve.id===ye.tabId);(!Ie||Ie.terminalSessionId!==ye.sessionId)&&E(_)}},[C,E,N]),i.useEffect(()=>{for(const[_,ye]of Object.entries(C)){const $=se.current[_]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};se.current[_]=$;const Ie=le.find(Be=>Be.id===ye.actionId);if(!Ie)continue;const Fe=N.get(ye.directory)?.tabs.find(Be=>Be.id===ye.tabId);if(!Fe||!Array.isArray(Fe.bufferChunks)||Fe.bufferChunks.length===0)continue;const Ce=Fe.bufferChunks.filter(Be=>$.lastSeenChunkId===null?!0:Be.id>$.lastSeenChunkId);if(Ce.length===0)continue;const ne=Ce.map(Be=>Be.data).join(""),P=`${$.tail}${ne}`,me=!$.openedUrl&&Ie.autoOpenUrl===!0?Rb(P):null,oe=Ce[Ce.length-1]?.id??$.lastSeenChunkId;if($.lastSeenChunkId=oe,$.tail=P.slice(-512),me)if($.openedUrl=!0,$.openInPreview){const Be=C[_];Be&&(A(Be.directory,Be.tabId,me,{locked:!1,autoOpened:!1}),Be.status==="waiting-for-preview"&&T(_,"running"),window.clearTimeout(K.current[_]),delete K.current[_],h(Be.directory,me))}else te(me),de.success(a("projectActions.toast.openedUrlFromOutput"));se.current[_]=$}for(const _ of Object.keys(se.current))C[_]||(delete se.current[_],window.clearTimeout(K.current[_]),delete K.current[_])},[le,h,te,C,A,a,N,T]);const Se=i.useCallback(async(_,ye={})=>{if(!J)throw new Error(a("projectActions.error.noActiveDirectory"));const $=Qr(J,_.id);w(J);const Ie=Fs.getState(),ve=Ie.getDirectoryState(J);let Fe=Z.current[$]||null;const Ce=Fe?!!ve?.tabs.some(me=>me.id===Fe):!1;(!Fe||!Ce)&&(Fe=Ie.createTab(J),Z.current[$]=Fe),S(J,Fe,`Action: ${_.name}`),j(J,Fe,_.icon||"play"),ye.revealTerminal!==!1&&(k(J,Fe),g(!0),y("terminal"));const P=Fs.getState().getDirectoryState(J)?.tabs.find(me=>me.id===Fe);return{key:$,tabId:Fe,sessionId:P?.terminalSessionId??null}},[w,J,y,k,g,j,S,a]),Re=i.useCallback(async _=>{if(l.isVSCode||!o&&d)return;if(!J){de.error(a("projectActions.error.noActiveDirectoryForAction"));return}const ye=Qr(J,_.id),$=C[ye];if(!($&&$.status==="running"))try{const Ie=_.id===rr?await(async()=>{const[Qe,rt]=await Promise.all([yd({id:je?.id??"",path:J}),Nb(J)]),pt=await bb(J,Qe.actions,rt);if(!pt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:rr,name:a("projectActions.actions.autoDiscover"),command:pt.command,icon:"search",autoOpenUrl:!0,openUrl:pt.previewUrlHint||""}})():_,ve=Ie.autoOpenUrl===!0&&(Ie.openUrl||"").trim().length>0,{key:Fe,tabId:Ce,sessionId:ne}=await Se(Ie,{revealTerminal:!ve&&_.id!==rr});let P=ne,me=!1;if(!P){v(J,Ce,!0);try{P=(await c.createSession({cwd:J})).sessionId,me=!0,D(J,Ce,P)}finally{v(J,Ce,!1)}}if(!P)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));me&&await kb(350),Ie.id===rr&&(Q.current[Fe]?.(),v(J,Ce,!0),Q.current[Fe]=Jh(P,Qe=>{Qe.type==="data"&&typeof Qe.data=="string"&&Qe.data.length>0&&Fs.getState().appendToBuffer(J,Ce,Qe.data),Qe.type==="exit"&&(Fs.getState().setTabLifecycle(J,Ce,"exited"),Fs.getState().setConnecting(J,Ce,!1),Fs.getState().removeProjectActionRun(Fe),delete se.current[Fe],Q.current[Fe]?.(),delete Q.current[Fe],window.clearTimeout(K.current[Fe]),delete K.current[Fe])},()=>{Fs.getState().setConnecting(J,Ce,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const oe=Ie.autoOpenUrl===!0&&u&&(Ie.desktopOpenSshForward||"").trim().length>0,Be=Ie.autoOpenUrl?Tb(Ie.openUrl):null,Ue=Ie.autoOpenUrl&&u?kx(Ie.desktopOpenSshForward,m):null;O({key:Fe,directory:J,actionId:Ie.id,tabId:Ce,sessionId:P,status:Ie.id===rr&&!Be?"waiting-for-preview":"running"}),window.clearTimeout(K.current[Fe]),delete K.current[Fe],Ie.id===rr&&!Be&&(K.current[Fe]=window.setTimeout(()=>{Fs.getState().updateProjectActionRunStatus(Fe,"running"),delete K.current[Fe]},Ib)),Ue?(A(J,Ce,null,{locked:!0}),te(Ue),de.success(a("projectActions.toast.openedForwardedUrl"))):Be?(A(J,Ce,Be,{locked:!0,autoOpened:!0}),h(J,Be),de.success(a("projectActions.toast.openedActionUrl"))):ve?(A(J,Ce,null,{locked:!0}),de.error(a("projectActions.error.invalidCustomUrlFormat"))):oe?(A(J,Ce,null,{locked:!0}),de.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):A(J,Ce,null,{locked:!1,autoOpened:!1}),se.current[Fe]={lastSeenChunkId:null,openedUrl:!!Ue||!!Be||ve,tail:"",openInPreview:Ie.id===rr};const Ke=Pb(Ie.command.trim().replace(/\r\n|\r/g,`
3
- `));await c.sendInput(P,`${Ke}\r`)}catch(Ie){E(ye),delete se.current[ye],Q.current[ye]?.(),delete Q.current[ye],window.clearTimeout(K.current[ye]),delete K.current[ye],de.error(Ie instanceof Error?Ie.message:a("projectActions.error.failedToRunAction"))}},[m,Se,o,d,u,J,te,h,C,l.isVSCode,E,v,O,A,D,je?.id,a,c]),_e=i.useCallback(async _=>{const ye=Qr(J,_.id),$=C[ye];if(!$)return;T(ye,"stopping");try{await c.sendInput($.sessionId,"")}catch{}if(await new Promise(Fe=>{window.setTimeout(Fe,1e3)}),Fs.getState().getDirectoryState($.directory)?.tabs.find(Fe=>Fe.id===$.tabId)?.terminalSessionId===$.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:$.sessionId})}catch{}else try{await c.close($.sessionId)}catch{}D($.directory,$.tabId,null)}E(ye),delete se.current[ye],Q.current[ye]?.(),delete Q.current[ye],window.clearTimeout(K.current[ye]),delete K.current[ye]},[J,C,E,D,c,T]),Oe=i.useCallback(()=>{const _=H??le[0];if(!_)return;const ye=Qr(J,_.id),$=C[ye];if($?.status!=="stopping"){if($){_e(_);return}Re(_)}},[le,J,Re,C,H,_e]),Me=i.useCallback((_,ye=!1)=>{if(B(_.id),!ye){Re(_);return}const $=Qr(J,_.id),Ie=C[$];if(Ie?.status!=="stopping"){if(Ie){_e(_);return}Re(_)}},[J,Re,C,_e]),ge=i.useCallback(()=>{je?.id&&(b(je.id),p("projects"),x(!0))},[x,p,b,je?.id]);if(l.isVSCode||!o&&d||!je||!J)return null;const Ae=H??le[0]??null;if(!Ae)return null;const pe=Ae.icon||"play",ue=Ae.id===rr?"search":il[pe]||"play",G=Qr(J,Ae.id),fe=C[G],ce=fe?.status==="stopping",W=fe?.status==="waiting-for-preview",z=fe?N.get(fe.directory)?.tabs.find(_=>_.id===fe.tabId)?.previewUrl??null:null,be=!!(fe&&z),xe=()=>{!fe||!z||h(fe.directory,z)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:V||ce,className:De("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:Oe,"aria-label":fe?a("projectActions.actions.stopNamedAria",{name:Ae.name}):a("projectActions.actions.runNamedAria",{name:Ae.name}),children:ce||W?s.jsx(I,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):fe?s.jsx(I,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(I,{name:ue,className:"h-5 w-5"})}),be?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":a("projectActions.actions.openPreview"),onClick:xe,children:s.jsx(I,{name:"global",className:"h-4 w-4"})})}),s.jsx(Mt,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":a("projectActions.actions.chooseActionAria"),children:s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(sn,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(bs,{className:"flex items-center gap-2",onClick:ge,children:[s.jsx(I,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Rr,{}),le.map(_=>{const ye=_.icon||"play",$=_.id===rr?"search":il[ye]||"play",Ie=Qr(J,_.id),ve=C[Ie],Fe=!!ve,Ce=ve?.status==="stopping";return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Me(_,!0)},children:[s.jsx(I,{name:$,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.name}),Ce||ve?.status==="waiting-for-preview"?s.jsx(I,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Fe?s.jsx(I,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]}):s.jsxs("div",{className:De("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[s.jsx("button",{type:"button",onClick:Oe,disabled:V||ce,className:De("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":fe?a("projectActions.actions.stopNamedAria",{name:Ae.name}):a("projectActions.actions.runNamedAria",{name:Ae.name}),children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:ce||W?s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):fe?s.jsx(I,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(I,{name:ue,className:"h-4 w-4"})})}),be?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:xe,className:De(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":a("projectActions.actions.openPreview"),children:s.jsx(I,{name:"global",className:"h-4 w-4"})})}),s.jsx(Mt,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:De(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":a("projectActions.actions.chooseActionAria"),children:s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(sn,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(bs,{className:"flex items-center gap-2",onClick:ge,children:[s.jsx(I,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Rr,{}),le.map(_=>{const ye=_.icon||"play",$=_.id===rr?"search":il[ye]||"play",Ie=Qr(J,_.id),ve=C[Ie],Fe=!!ve,Ce=ve?.status==="stopping";return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Me(_,!0)},children:[s.jsx(I,{name:$,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.name}),Ce||ve?.status==="waiting-for-preview"?s.jsx(I,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Fe?s.jsx(I,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]})},qa="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Eb="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Uo=i.memo(function(e){const n=gt.c(17),{visible:r,title:o,ariaLabel:a,onClick:c,className:l,Icon:d,iconClassName:u,pressed:m}=e,f=r===void 0?!0:r,g=m===void 0?!1:m;if(!f)return null;const y=l??qa,p=g&&"bg-interactive-selection text-interactive-selection-foreground";let x;n[0]!==y||n[1]!==p?(x=De(y,p),n[0]=y,n[1]=p,n[2]=x):x=n[2];const b=u??"h-[18px] w-[18px]";let h;n[3]!==d||n[4]!==b?(h=s.jsx(I,{name:d,className:b}),n[3]=d,n[4]=b,n[5]=h):h=n[5];let N;n[6]!==a||n[7]!==c||n[8]!==g||n[9]!==x||n[10]!==h?(N=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,"aria-label":a,"aria-pressed":g,className:x,children:h})}),n[6]=a,n[7]=c,n[8]=g,n[9]=x,n[10]=h,n[11]=N):N=n[11];let w;n[12]!==o?(w=s.jsx(Mt,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=w):w=n[13];let S;return n[14]!==N||n[15]!==w?(S=s.jsxs(Rt,{children:[N,w]}),n[14]=N,n[15]=w,n[16]=S):S=n[16],S}),Mb=i.memo(function(e){const n=gt.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:u}=e,{t:m}=kt();if(!o?.connected||r)return null;if(a.length>1){let p;n[0]===Symbol.for("react.memo_cache_sentinel")?(p=De(qa,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),n[0]=p):p=n[0];let x;n[1]!==l||n[2]!==m?(x=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[1]=l,n[2]=m,n[3]=x):x=n[3];let b;n[4]!==c||n[5]!==l||n[6]!==m?(b=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(I,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=m,n[7]=b):b=n[7];let h;n[8]!==d||n[9]!==x||n[10]!==b?(h=s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:p,title:x,disabled:d,children:b})}),n[8]=d,n[9]=x,n[10]=b,n[11]=h):h=n[11];let N;n[12]!==m?(N=m("header.github.accountsTitle"),n[12]=m,n[13]=N):N=n[13];let w;n[14]!==N?(w=s.jsx(xp,{className:"typography-ui-header font-semibold text-foreground",children:N}),n[14]=N,n[15]=w):w=n[15];let S;n[16]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(Rr,{}),n[16]=S):S=n[16];let j;if(n[17]!==a||n[18]!==u||n[19]!==d||n[20]!==m){let D;n[22]!==u||n[23]!==d||n[24]!==m?(D=A=>{const C=A.user,O=!!A.current,T=A.source==="gh-cli"?m("header.github.accountSource.cli"):m("header.github.accountSource.oauth");return s.jsxs(bs,{className:"gap-2",disabled:d,onSelect:()=>{O||u(A.id)},children:[C?.avatarUrl?s.jsx("img",{src:C.avatarUrl,alt:C.login?m("header.github.avatarWithLogin",{login:C.login}):m("header.github.avatar"),className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:s.jsx(I,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:C?.name?.trim()||C?.login||"GitHub"}),C?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:C.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:T})]}):null]}),O?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]},A.id)},n[22]=u,n[23]=d,n[24]=m,n[25]=D):D=n[25],j=a.map(D),n[17]=a,n[18]=u,n[19]=d,n[20]=m,n[21]=j}else j=n[21];let k;n[26]!==w||n[27]!==j?(k=s.jsxs(sn,{align:"end",className:"w-64",children:[w,S,j]}),n[26]=w,n[27]=j,n[28]=k):k=n[28];let v;return n[29]!==h||n[30]!==k?(v=s.jsxs(nn,{children:[h,k]}),n[29]=h,n[30]=k,n[31]=v):v=n[31],v}let f;n[32]!==l||n[33]!==m?(f=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[32]=l,n[33]=m,n[34]=f):f=n[34];let g;n[35]!==c||n[36]!==l||n[37]!==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(I,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[35]=c,n[36]=l,n[37]=m,n[38]=g):g=n[38];let y;return n[39]!==f||n[40]!==g?(y=s.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:f,children:g}),n[39]=f,n[40]=g,n[41]=y):y=n[41],y}),Fb=i.memo(function(e){const n=gt.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:u,desktopServicesTab:m,setDesktopServicesTab:f,quotaResultsLength:g,fetchAllQuotas:y,servicesTabItems:p,quotaLastUpdated:x,quotaDisplayMode:b,quotaDisplayTabItems:h,handleDisplayModeChange:N,handleUsageRefresh:w,isQuotaLoading:S,isUsageRefreshSpinning:j,hasRateLimits:k,rateLimitGroups:v,expandedFamilies:D,toggleFamilyExpanded:A,shortcutLabel:C,showDevShutdown:O,isDevShutdownInFlight:T,onDevShutdown:E,remoteUpdateInfo:F,remoteUpdateChecking:R,remoteUpdateError:L,onOpenRemoteUpdate:B,showPredValues:V,timeFormatPreference:M}=e,{t:Z}=kt();let se;n[0]!==m||n[1]!==y||n[2]!==g||n[3]!==u||n[4]!==d?(se=Me=>{d(Me),Me&&(u(),m==="usage"&&g===0&&y())},n[0]=m,n[1]=y,n[2]=g,n[3]=u,n[4]=d,n[5]=se):se=n[5];let Q;n[6]!==o||n[7]!==r||n[8]!==Z?(Q=r?Z("header.services.openWithCurrent",{current:o}):Z("header.services.open"),n[6]=o,n[7]=r,n[8]=Z,n[9]=Q):Q=n[9];const K=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let ee;n[10]!==K?(ee=De(qa,K),n[10]=K,n[11]=ee):ee=n[11];let re;n[12]===Symbol.for("react.memo_cache_sentinel")?(re=s.jsx(I,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=re):re=n[12];let he;n[13]!==a||n[14]!==r?(he=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=he):he=n[15];let je;n[16]!==Q||n[17]!==ee||n[18]!==he?(je=s.jsx(Et,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":Q,className:ee,children:[re,he]})})}),n[16]=Q,n[17]=ee,n[18]=he,n[19]=je):je=n[19];let te;n[20]!==o||n[21]!==r||n[22]!==C||n[23]!==Z?(te=r?Z("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:C("toggle_services_menu"),nextTab:C("cycle_services_tab")}):Z("header.services.tooltip.servicesWithShortcuts",{toggle:C("toggle_services_menu"),nextTab:C("cycle_services_tab")}),n[20]=o,n[21]=r,n[22]=C,n[23]=Z,n[24]=te):te=n[24];let Ne;n[25]!==te?(Ne=s.jsx(Mt,{children:s.jsx("p",{children:te})}),n[25]=te,n[26]=Ne):Ne=n[26];let J;n[27]!==je||n[28]!==Ne?(J=s.jsxs(Rt,{children:[je,Ne]}),n[27]=je,n[28]=Ne,n[29]=J):J=n[29];let H;n[30]!==y||n[31]!==g||n[32]!==f?(H=Me=>{const ge=Me;f(ge),ge==="usage"&&g===0&&y()},n[30]=y,n[31]=g,n[32]=f,n[33]=H):H=n[33];let q;n[34]!==m||n[35]!==p||n[36]!==H?(q=s.jsx("div",{className:"sticky top-0 z-20 px-2 pt-1.5 pb-px",children:s.jsx("div",{className:"h-9",children:s.jsx(To,{items:p,activeId:m,onSelect:H,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=m,n[35]=p,n[36]=H,n[37]=q):q=n[37];let ae;n[38]!==c||n[39]!==m||n[40]!==r||n[41]!==l||n[42]!==B||n[43]!==R||n[44]!==L||n[45]!==F||n[46]!==d||n[47]!==Z?(ae=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:Z("header.services.remoteUpdate.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:F?.available?Z("header.services.remoteUpdate.available",{version:F.version||""}):R?Z("header.services.remoteUpdate.checking"):L||Z("header.services.remoteUpdate.upToDate")})]}),F?.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:B,children:Z("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(gp,{embedded:!0,open:l&&m==="instance",onOpenChange:Bb,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=m,n[40]=r,n[41]=l,n[42]=B,n[43]=R,n[44]=L,n[45]=F,n[46]=d,n[47]=Z,n[48]=ae):ae=n[48];let le;n[49]!==m||n[50]!==l?(le=m==="mcp"?s.jsx(lm,{active:l&&m==="mcp"}):null,n[49]=m,n[50]=l,n[51]=le):le=n[51];let Se;n[52]!==m||n[53]!==D||n[54]!==N||n[55]!==w||n[56]!==k||n[57]!==S||n[58]!==j||n[59]!==b||n[60]!==h||n[61]!==x||n[62]!==v||n[63]!==V||n[64]!==Z||n[65]!==M||n[66]!==A?(Se=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:Z("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:ym(x,M)})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-[10.5rem]",children:s.jsx(To,{items:h,activeId:b,onSelect:Me=>{N(Me)},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",className:"h-full"})}),s.jsx("button",{type:"button",className:De("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:w,disabled:S||j,"aria-label":Z("header.services.refreshRateLimitsAria"),children:s.jsx(I,{name:"refresh",className:De("h-4 w-4",j&&"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:Z("header.services.noRateLimits")})}),s.jsx("div",{className:"py-2",children:v.map((Me,ge)=>{const Ae=D[Me.providerId]??[];return s.jsxs(i.Fragment,{children:[ge>0?s.jsx("div",{className:"mx-4 my-2 border-t border-[var(--interactive-border)]"}):null,s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2",children:[s.jsx(Do,{providerId:Me.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Me.providerName})]}),Me.entries.length===0&&(!Me.modelFamilies||Me.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Me.error??Z("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[Me.entries.map(pe=>{const[ue,G]=pe,fe=b==="remaining"?G.remainingPercent:G.usedPercent,ce=va(G.usedPercent,G.resetAt,G.windowSeconds,ue),W=ce?.dailyAllocationPercent!=null?b==="remaining"?100-ni(ce.elapsedRatio):ni(ce.elapsedRatio):null,z=Io(G.valueLabel,fe),be=Tf(G.resetAt,G.resetAfterFormatted??G.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:fc(ue)}),be?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:be}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:z==="-"?"":z})]}),s.jsx(Ca,{percent:fe,tonePercent:G.usedPercent,className:"h-1.5",expectedMarkerPercent:W}),ce&&V?s.jsx(Aa,{paceInfo:ce,compact:!0}):null]},`${Me.providerId}-${ue}`)}),Me.modelFamilies&&Me.modelFamilies.length>0?s.jsx("div",{className:"space-y-0.5",children:Me.modelFamilies.map(pe=>{const ue=pe.familyId??"other",G=Ae.includes(ue);return s.jsxs(to,{open:G,onOpenChange:()=>A(Me.providerId,ue),children:[s.jsxs(Bo,{className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:pe.familyLabel}),G?s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(so,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:pe.models.map(fe=>{const[ce,W]=fe,z=b==="remaining"?W.remainingPercent:W.usedPercent,be=va(W.usedPercent,W.resetAt,W.windowSeconds),xe=be?.dailyAllocationPercent!=null?b==="remaining"?100-ni(be.elapsedRatio):ni(be.elapsedRatio):null,_=Io(W.valueLabel,z);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:am(ce)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:_==="-"?"":_})]}),s.jsx(Ca,{percent:z,tonePercent:W.usedPercent,className:"h-1.5",expectedMarkerPercent:xe}),be&&V?s.jsx(Aa,{paceInfo:be,compact:!0}):null]},`${Me.providerId}-${ce}`)})})})]},ue)})}):null]})]},Me.providerId)})})]}):null,n[52]=m,n[53]=D,n[54]=N,n[55]=w,n[56]=k,n[57]=S,n[58]=j,n[59]=b,n[60]=h,n[61]=x,n[62]=v,n[63]=V,n[64]=Z,n[65]=M,n[66]=A,n[67]=Se):Se=n[67];let Re;n[68]!==T||n[69]!==E||n[70]!==O||n[71]!==Z?(Re=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(bs,{disabled:T,onSelect:()=>{E()},children:Z("header.services.shutdownDev")})})]}):null,n[68]=T,n[69]=E,n[70]=O,n[71]=Z,n[72]=Re):Re=n[72];let _e;n[73]!==q||n[74]!==ae||n[75]!==le||n[76]!==Se||n[77]!==Re?(_e=s.jsxs(sn,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[q,ae,le,Se,Re]}),n[73]=q,n[74]=ae,n[75]=le,n[76]=Se,n[77]=Re,n[78]=_e):_e=n[78];let Oe;return n[79]!==l||n[80]!==se||n[81]!==J||n[82]!==_e?(Oe=s.jsxs(nn,{open:l,onOpenChange:se,children:[J,_e]}),n[79]=l,n[80]=se,n[81]=J,n[82]=_e,n[83]=Oe):Oe=n[83],Oe}),Lb=(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??""),Ob=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},ym=(t,e)=>{if(!t)return"-";try{return Rf(t,e,{fallback:"-"})}catch{return"-"}},En=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Zr=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,Kd=({onToggleLeftDrawer:t,onToggleRightDrawer:e,leftDrawerOpen:n,rightDrawerOpen:r})=>{const{t:o}=kt(),a=Ee(X=>X.setSessionSwitcherOpen),c=Ee(X=>X.toggleSidebar),l=Ee(X=>X.isSidebarOpen),d=Ee(X=>X.toggleBottomTerminal),u=Ee(X=>X.toggleRightSidebar),m=Ee(X=>X.openContextOverview),f=Ee(X=>X.openContextPlan),g=Ee(X=>X.openContextBrowser),y=Ee(X=>X.openContextPanelTab),p=Ee(X=>X.closeContextPanel),x=Ee(X=>X.contextPanelByDirectory),b=Ee(X=>X.activeMainTab),h=Ee(X=>X.setActiveMainTab),N=Ee(X=>X.shortcutOverrides),w=Ee(X=>X.timeFormatPreference),S=ss(X=>X.getCurrentModel),j=er(),[k,v]=i.useState(!1),D=ut(X=>X.getContextUsage),A=ut(X=>!!X.newSessionDraft?.open),C=ut(X=>X.currentSessionId),O=bp(C??""),T=Ef(C??null),E=jr(X=>X.activeSessions),F=mc(),R=ws(X=>X.activeProjectId?X.projects.find(st=>st.id===X.activeProjectId)??null:null),L=i.useMemo(()=>{if(!R)return null;const X=R.label?.trim();if(X)return X;const st=R.path.split(/[\\/]/).filter(Boolean);return st[st.length-1]??null},[R]),B=fn(X=>X.results),V=fn(X=>X.fetchAllQuotas),M=fn(X=>X.isLoading),Z=fn(X=>X.lastUpdated),se=fn(X=>X.displayMode),Q=fn(X=>X.showPredValues),K=fn(X=>X.dropdownProviderIds),ee=fn(X=>X.loadSettings),re=fn(X=>X.setDisplayMode),{isMobile:he}=Er(),je=Ti(X=>X.status),te=Ti(X=>X.setStatus),Ne=i.useRef(null),[J,H]=i.useState(()=>typeof window>"u"?!1:hr()),q=i.useMemo(()=>Fa(),[]),ae=Mf(),[le,Se]=i.useState(!1),Re=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),_e=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32",[]),Oe=i.useMemo(()=>{if(typeof window>"u")return null;const X=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof X=="number"&&Number.isFinite(X)&&X>0)return X;if(typeof navigator>"u")return null;const st=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!st)return null;const ht=Number.parseInt(st[1],10),At=Number.parseInt(st[2],10);return Number.isNaN(ht)?null:ht===10?At:ht},[]);tt.useEffect(()=>{typeof window>"u"||H(hr())},[]);const Me=S(),ge=Me&&typeof Me.limit=="object"&&Me.limit!==null?Me.limit:null,Ae=ge&&typeof ge.context=="number"?ge.context:0,pe=ge&&typeof ge.output=="number"?ge.output:0,ue=D(Ae,pe),[G,fe]=i.useState(null),ce=!C||O;tt.useEffect(()=>{if(!C){fe(X=>X===null?X:null);return}if(ue&&ue.totalTokens>0){fe(X=>Lb(X,ue)?X:ue);return}ce&&fe(X=>X===null?X:null)},[ue,C,ce]);const W=Ee(X=>X.isSessionSwitcherOpen),z=je?.connected?je.user?.avatarUrl??null:null,be=je?.connected?je.user?.login??null:null,xe=je?.accounts??[],[_,ye]=i.useState(!1),[$,Ie]=i.useState(!1),[ve,Fe]=i.useState(!1),[Ce,ne]=i.useState(!1),[P,me]=i.useState("Local"),[oe,Be]=i.useState(!0),[Ue,Ke]=i.useState(!1),[Qe,rt]=i.useState(null),[pt,jt]=i.useState(!1),[Ve,Ze]=i.useState(null),nt=i.useMemo(()=>Ob(P),[P]),[St,Dt]=i.useState(J?"instance":"usage"),[wt,ot]=i.useState("usage");tt.useEffect(()=>{!J&&St==="instance"&&Dt("usage")},[St,J]);const at=i.useMemo(()=>Hr(),[]),Kt=!at&&b==="chat"&&!!G&&G.totalTokens>0,is=G&&G.contextLimit>0?Math.min(999,G.totalTokens/G.contextLimit*100):0,$t=i.useCallback(async()=>{if(!(typeof window>"u"||!J))try{if(Xi()){me("Local"),Be(!0);return}Be(!1);const X=await Ff(),st=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,ht=zr();if(ht&&ja(ht,st)){me("Local"),Be(!0);return}const At=X.hosts.find(os=>ht?ja(ht,Lf(os)):!1);if(At?.label?.trim()){me(Of(At.label.trim()));return}me("Instance")}catch{me("Local"),Be(!0)}},[J]);tt.useEffect(()=>{$t()},[$t]);const Le=i.useCallback(async()=>{if(oe){rt(null),Ze(null);return}jt(!0),Ze(null);try{const X=new URLSearchParams({appType:"web",instanceMode:"remote"}),st=await As(`/api/openchamber/update-check?${X.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!st.ok)throw new Error(`Server responded with ${st.status}`);const ht=await st.json();rt({available:ht.available??!1,version:ht.version,currentVersion:ht.currentVersion??"unknown",body:ht.body,nextSuggestedCheckInSec:typeof ht.nextSuggestedCheckInSec=="number"?ht.nextSuggestedCheckInSec:void 0,packageManager:ht.packageManager,updateCommand:ht.updateCommand})}catch(X){rt(null),Ze(X instanceof Error?X.message:o("header.services.remoteUpdate.error"))}finally{jt(!1)}},[oe,o]);i.useEffect(()=>{rt(null),Ze(null),Ke(!1)},[oe,P]),i.useEffect(()=>{if(!J||oe)return;const X=3e3,st=3600*1e3;let ht=!1,At=null;const os=rs=>{At=window.setTimeout(()=>{if(ht||typeof document<"u"&&document.visibilityState!=="visible"){os(st);return}Le().finally(()=>{ht||os(st)})},rs)};return os(X),()=>{ht=!0,At!==null&&window.clearTimeout(At)}},[Le,oe,P,J]);const et=i.useCallback(()=>{if(Qe?.available){Ke(!0);return}Le()},[Le,Qe?.available]);Cx();const Vt=fn(X=>X.selectedModels),xt=fn(X=>X.expandedFamilies),Ft=fn(X=>X.toggleFamilyExpanded),Gt=i.useMemo(()=>{const X=[];for(const st of Bf){if(!K.includes(st.id))continue;const ht=B.find(Es=>Es.providerId===st.id),At=ht?.usage?.windows??{},os=ht?.usage?.models,rs=Object.entries(At),ds={providerId:st.id,providerName:st.name,entries:rs,error:ht&&!ht.ok&&ht.configured?ht.error:void 0};if(os&&Object.keys(os).length>0){const Es=Vt[st.id]??[],Gs=Es.length>0,Dn=Ax(os,st.id),Nr=Dx(st.id),kr=Ix(Nr);ds.modelFamilies=[];for(const dn of kr){const Ln=Dn.get(dn.id)??[];if(Ln.length===0)continue;const In=Gs?Ln.filter(Pn=>Es.includes(Pn)):Ln;if(In.length===0)continue;const Nn=[];for(const Pn of In){const cr=os[Pn];if(cr?.windows){const un=Object.entries(cr.windows);un.length>0&&Nn.push([Pn,un[0][1]])}}Nn.length>0&&ds.modelFamilies.push({familyId:dn.id,familyLabel:dn.label,models:Nn})}const Bs=Dn.get(null)??[],Or=Gs?Bs.filter(dn=>Es.includes(dn)):Bs;if(Or.length>0){const dn=[];for(const Ln of Or){const In=os[Ln];if(In?.windows){const Nn=Object.entries(In.windows);Nn.length>0&&dn.push([Ln,Nn[0][1]])}}dn.length>0&&ds.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:dn})}}(rs.length>0||ds.modelFamilies&&ds.modelFamilies.length>0||ds.error)&&X.push(ds)}return X},[K,B,Vt,o]),Ut=Gt.length>0;i.useEffect(()=>{ee()},[ee]);const qt=i.useCallback(async X=>{re(X);try{await lc({usageDisplayMode:X})}catch(st){console.warn("Failed to update usage display mode:",st)}},[re]),Xt=i.useCallback(()=>{if(Ce)return;ne(!0);const X=new Promise(st=>setTimeout(st,500));Promise.all([V(),X]).finally(()=>{ne(!1)})},[V,Ce]),Lt=i.useMemo(()=>C?F.find(X=>X.id===C)??E.find(X=>X.id===C)??T??Vf().find(X=>X.id===C)??null:null,[C,T,E,F]),Bt=i.useRef(null),[Yt,Jt]=i.useState(0);i.useEffect(()=>{if(!C){Bt.current&&(Bt.current=null,Jt(At=>At+1));return}if(Lt){Bt.current={sessionId:C,session:Lt,expiresAt:Date.now()+2e3};return}const X=Bt.current;if(!X||X.sessionId!==C)return;const st=X.expiresAt-Date.now();if(st<=0){Bt.current=null,Jt(At=>At+1);return}const ht=window.setTimeout(()=>{Bt.current?.sessionId===C&&(Bt.current=null),Jt(At=>At+1)},st);return()=>{window.clearTimeout(ht)}},[C,Lt]);const es=(()=>{if(Lt)return Lt;if(!C)return null;const X=Bt.current;return X&&X.sessionId===C&&X.expiresAt>Date.now()?X.session:null})(),Zt=ut(X=>C?X.worktreeMetadata.get(C)?.path??"":""),vs=ut(X=>C?X.worktreeMetadata.get(C)?.branch?.trim()??null:null),bt=_f(X=>C?X.getAttachment(C):void 0),Ot=i.useMemo(()=>bt?yp(bt,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,bt]),It=i.useMemo(()=>bt?bt.legacy?"legacy":bt.degraded?"degraded":bt.worktreeStatus==="pending"?"pending":bt.worktreeStatus==="missing"?"missing":bt.worktreeStatus==="invalid"?"invalid":bt.attentionReason?"attention":null:null,[bt]),us=i.useMemo(()=>En(Zt||""),[Zt]),He=i.useMemo(()=>{const X=typeof es?.directory=="string"?es.directory:"";return En(X||"")},[es?.directory]),ft=ut(X=>X.newSessionDraft?.open?En(X.newSessionDraft.bootstrapPendingDirectory??X.newSessionDraft.directoryOverride??""):""),Ye=i.useMemo(()=>us||He||ft,[ft,He,us]),Pt=ut(X=>{const st=En(us||He||"");if(!st)return null;for(const ht of X.availableWorktreesByProject.values()){const os=ht.find(rs=>En(rs.path)===st)?.branch?.trim();if(os)return os}return null}),Qt=wp(Ye||null)||vs||Pt,Ss=i.useMemo(()=>{if(!C)return L??"OpenChamber";const X=es?.title?.trim();return X&&X.length>0?X:"Untitled Session"},[L,es?.title,C]),ys=i.useMemo(()=>En(Ye||R?.path||""),[R?.path,Ye]),_t=i.useMemo(()=>R?{id:R.id,path:R.path}:null,[R]),Ns=i.useRef(null);i.useEffect(()=>{!_t||!ys||(Ns.current={projectRef:_t,directory:ys})},[ys,_t]);const js=i.useMemo(()=>_t&&ys?{projectRef:_t,directory:ys}:Ns.current,[ys,_t]),Ds=hc(X=>X.planModeEnabled),mn=ut(X=>X.isSessionPlanAvailable),Js=Ds&&C?mn(C):!1,ln=Js,jn=i.useRef("");i.useEffect(()=>{if(!Ds){Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat");return}if(!C)return;const X=`${C||"none"}:${He||"none"}:${es?.time?.created||0}:${es?.slug||"none"}`;jn.current!==X&&(jn.current=X),!Js&&Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat")},[Ds,Js,es?.slug,es?.time?.created,C,He]);const $s=i.useCallback(async X=>{if(!(!X||_)){ye(!0);try{const st=j.github?await j.github.authActivate(X):await(async()=>{const ht=await As("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:X})}),At=await ht.json().catch(()=>null);if(!ht.ok||!At)throw new Error(At?.error||ht.statusText);return At})();te(st)}catch(st){console.error("Failed to switch GitHub account:",st)}finally{ye(!1)}}},[_,j.github,te]),we=i.useCallback(()=>{if(typeof document>"u")return;const X=document.activeElement;if(!X)return;const st=X.tagName;(st==="INPUT"||st==="TEXTAREA"||st==="SELECT"||X.isContentEditable)&&X.blur()},[]),Je=i.useCallback(()=>{if(he){we(),a(!W);return}c()},[we,he,W,a,c]),vt=i.useCallback(()=>{Wr("desktop_open_draft_mini_chat_window",{directory:En(Ye||R?.path||""),projectId:R?.id??null,apiBaseUrl:zr(),clientToken:_l()}).catch(X=>{console.warn("[header] failed to open draft mini chat window",X)})},[R?.id,R?.path,Ye]),Ct=i.useCallback(()=>{if(A){vt();return}C&&Wr("desktop_open_session_mini_chat_window",{sessionId:C,directory:En(Ye||R?.path||""),apiBaseUrl:zr(),clientToken:_l()}).catch(X=>{console.warn("[header] failed to open session mini chat window",X)})},[R?.path,C,vt,A,Ye]),zt=i.useCallback(()=>{const X=En(Ye||"");if(!X)return;const st=x[X];if(Zr(st)==="context"){p(X);return}m(X)},[p,x,m,Ye]),mt=i.useMemo(()=>{const X=En(Ye||"");if(!X)return!1;const st=x[X];return Zr(st)==="context"},[x,Ye]),cs=i.useCallback(()=>{const X=En(Ye||"");if(!X)return;const st=x[X];if(Zr(st)==="plan"){p(X);return}f(X)},[p,x,f,Ye]),fs=i.useCallback(()=>{const X=En(Ye||"");if(!X)return;const st=x[X];if(Zr(st)==="diff"){p(X);return}y(X,{mode:"diff",stagedDiff:!1})},[p,x,y,Ye]),ks=i.useCallback(()=>{const X=En(Ye||"");if(!X)return;const st=x[X];if(Zr(st)==="browser"){p(X);return}g(X)},[p,x,g,Ye]),ms=i.useMemo(()=>{const X=En(Ye||"");if(!X)return!1;const st=x[X];return Zr(st)==="plan"},[x,Ye]),Hs=i.useMemo(()=>{const X=En(Ye||"");if(!X)return!1;const st=x[X];return Zr(st)==="diff"},[x,Ye]),zs=i.useMemo(()=>{const X=En(Ye||"");if(!X)return!1;const st=x[X];return Zr(st)==="browser"},[x,Ye]),hn=qa,tr=Eb,An=i.useMemo(()=>$?"services":n?"sessions":r?"git":b,[b,$,n,r]),qe=i.useCallback(()=>{Ie(!1),n&&t&&t(),r&&e&&e(),!t&&W&&a(!1)},[W,n,t,e,r,a]),ns=i.useCallback(()=>{n||Ie(!1),t?.()},[n,t]),ps=i.useCallback(()=>{r||Ie(!1),e?.()},[e,r]),hs=i.useMemo(()=>J&&Re&&!le?"5.5rem":ae?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!J||_e)&&!at?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[J,le,Re,ae,at,_e]);tt.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",hs)},[hs]);const rn=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ws=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";tt.useEffect(()=>{if(!J||!Re){Se(!1);return}let X=!1;const st=async()=>{try{const At=await Wr("desktop_is_window_fullscreen");X||Se(At===!0)}catch{X||Se(!1)}},ht=()=>{st()};return st(),window.addEventListener("openchamber:window-resized",ht),()=>{X=!0,window.removeEventListener("openchamber:window-resized",ht)}},[J,Re]);const cn=i.useMemo(()=>!J||!Re||Oe===null?"":Oe>=26?"h-12":Oe<=15?"h-14":"",[J,Re,Oe]),Is=i.useMemo(()=>{if(!(J&&!_e||at))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[J,at,_e]),sr=i.useCallback(()=>{if(typeof document>"u")return;const X=Ne.current?.getBoundingClientRect().height;X&&document.documentElement.style.setProperty("--oc-header-height",`${X}px`)},[]);tt.useEffect(()=>{if(typeof window>"u")return;sr();const X=Ne.current;if(!X||typeof ResizeObserver>"u")return()=>{};let st=0;const ht=()=>{st||(st=requestAnimationFrame(()=>{st=0,sr()}))},At=new ResizeObserver(ht);return At.observe(X),window.addEventListener("resize",ht),window.addEventListener("orientationchange",ht),()=>{st&&cancelAnimationFrame(st),At.disconnect(),window.removeEventListener("resize",ht),window.removeEventListener("orientationchange",ht)}},[sr]),tt.useEffect(()=>{sr()},[sr,he,cn]);const Sr=i.useCallback(async X=>{const st=X.target;st.closest(".app-region-no-drag")||st.closest("button, a, input, select, textarea")||X.button===0&&J&&await Xh()},[J]),nr=i.useMemo(()=>{if(he){const X=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return ln&&X.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),X.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"}),X}return[]},[he,ln,o]),gr=i.useCallback(X=>La(ri(X,N)),[N]);tt.useEffect(()=>{!he&&(b==="git"||b==="terminal"||b==="diff"||b==="files"||b==="context")&&h("chat")},[b,he,h]);const Kn=i.useMemo(()=>{const X=[];return J&&X.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(I,{name:"server",className:"h-3.5 w-3.5"})}),X.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(zl,{className:"h-3.5 w-3.5"})}),X},[J,o]),gs=i.useMemo(()=>Kn.map(X=>({id:X.value,label:X.label,icon:X.icon})),[Kn]),Ps=i.useMemo(()=>{if(typeof window>"u"||J||at)return!1;const X=window.location.hostname;return X==="localhost"||X==="127.0.0.1"||X==="::1"},[J,at]),Mr=i.useCallback(async()=>{if(k)return;v(!0),Fe(!1);const X=[];let st=!1;try{try{for(const[,ht]of Fs.getState().sessions.entries())for(const At of ht.tabs)At.previewUrl&&X.push(At.previewUrl)}catch{}try{await Zh({})}catch{}try{(await As("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:X})})).ok?st=!0:st=(await As("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{st||v(!1)}},[k,Fe]),Sn=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),on=i.useMemo(()=>Sn.map(X=>({id:X.value,label:X.label})),[Sn]),lr=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(zl,{className:"h-3.5 w-3.5"})}],[o]);tt.useEffect(()=>{const X=st=>{if(pc(st)&&!st.shiftKey&&!st.altKey){const ht=parseInt(st.key,10);ht>=1&&ht<=nr.length&&(st.preventDefault(),he&&(we(),qe()),h(nr[ht-1].id))}};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[we,qe,he,h,nr]),tt.useEffect(()=>{const X=st=>{const ht=ri("toggle_services_menu",N);if(ia(st,ht)){st.preventDefault(),ve?Fe(!1):(Fe(!0),$t(),St==="usage"&&B.length===0&&V());return}const At=ri("cycle_services_tab",N);if(ia(st,At)){st.preventDefault();const rs=Kn.map(Dn=>Dn.value);if(rs.length===0)return;const ds=rs.indexOf(St),Es=ds===-1?0:(ds+1)%rs.length,Gs=rs[Es];Dt(Gs),Fe(!0),$t(),Gs==="usage"&&B.length===0&&V();return}const os=ri("toggle_context_plan",N);ia(st,os)&&(st.preventDefault(),cs())};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[N,ve,St,Kn,B.length,V,$t,cs]);const Fr=X=>{const st=b===X.id,ht=X.icon==="diff",At=ht?null:X.icon,os=X.id==="chat",rs=Es=>ht?s.jsx(Wd,{size:Es}):At?s.jsx(I,{name:At,className:`h-${Es/4} w-${Es/4}`}):null,ds=s.jsxs("button",{type:"button",onClick:()=>h(X.id),className:De("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",st?"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",os&&!he&&"min-w-[100px] justify-center"),"aria-label":X.label,"aria-selected":st,role:"tab",children:[he?rs(20):s.jsxs(s.Fragment,{children:[rs(16),s.jsx("span",{className:"header-tab-label",children:X.label})]}),X.badge!==void 0&&X.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:X.badge})]});return s.jsx(i.Fragment,{children:ds},X.id)},Kr=at?null:s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.toggleChangesPanelAria"),"aria-pressed":Hs,onClick:fs,className:hn,children:s.jsxs("span",{className:"relative h-5 w-5 overflow-hidden rounded-[2px]",children:[s.jsx("span",{className:"absolute left-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-success)]/25"}),s.jsx(I,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(Mt,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),Lr=s.jsxs(s.Fragment,{children:[ln&&s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:cs,className:De(hn,ms&&"bg-[var(--interactive-hover)]"),children:s.jsx(I,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(Mt,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:gr("toggle_context_plan")})})})]}),s.jsx(rb,{directory:ys,className:"mr-1"}),s.jsx(Fb,{isDesktopApp:J,currentInstanceLabel:P,compactCurrentInstanceLabel:nt,currentInstanceIsLocal:oe,isDesktopServicesOpen:ve,setIsDesktopServicesOpen:Fe,refreshCurrentInstanceLabel:$t,desktopServicesTab:St,setDesktopServicesTab:Dt,quotaResultsLength:B.length,fetchAllQuotas:V,servicesTabItems:gs,quotaLastUpdated:Z,quotaDisplayMode:se,showPredValues:Q,quotaDisplayTabItems:on,handleDisplayModeChange:qt,handleUsageRefresh:Xt,isQuotaLoading:M,isUsageRefreshSpinning:Ce,hasRateLimits:Ut,rateLimitGroups:Gt,expandedFamilies:xt,toggleFamilyExpanded:Ft,shortcutLabel:gr,showDevShutdown:Ps,isDevShutdownInFlight:k,onDevShutdown:Mr,remoteUpdateInfo:Qe,remoteUpdateChecking:pt,remoteUpdateError:Ve,onOpenRemoteUpdate:et,timeFormatPreference:w}),s.jsx(Uo,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:gr("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),he?null:s.jsx(Uo,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:ks,pressed:zs,Icon:"global"}),s.jsx(Uo,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:gr("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:u,Icon:"layout-right"}),s.jsx(Mb,{isMobile:he,githubAuthStatus:je,githubAccounts:xe,githubAvatarUrl:z,githubLogin:be,isSwitchingGitHubAccount:_,handleGitHubAccountSwitch:$s})]}),xs=q&&(A||!!C),Rs=()=>s.jsxs("div",{onMouseDown:Sr,className:De("app-region-drag relative flex h-12 select-none items-center pr-3",cn),style:Is,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:rn}}),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:Ws}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(qx,{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:A?o("sessions.switcher.draftTitle"):Ss}),L||Qt||!A&&It?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:[L?s.jsx("span",{className:"truncate",children:L}):null,Qt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:Qt})]}):null,!A&&It?s.jsxs("span",{className:De("inline-flex min-w-0 items-center gap-0.5",It==="attention"||It==="invalid"||It==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(I,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:Ot})]}):null]}):null]})}),nr.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:nr.map(X=>Fr(X))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Kt&&G?s.jsx(Yx,{totalTokens:G.totalTokens,percentage:is,colorPercentage:G.percentage,contextLimit:G.contextLimit,outputLimit:G.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:zt,pressed:mt,className:xs?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,Kr,s.jsx(Uo,{visible:xs,title:o(A?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(A?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:Ct,className:De(hn,"mr-1"),Icon:"picture-in-picture-2"}),Lr,s.jsx(Qx,{visible:_e})]})]})]}),qn=()=>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:ns,className:De(tr,An==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(I,{name:"layout-left",className:"h-5 w-5"})}):W?s.jsx("button",{type:"button",onClick:()=>a(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.backAria"),children:s.jsx(I,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Je,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.openSessionsAria"),children:s.jsx(I,{name:"play-list-add",className:"h-5 w-5"})}),!t&&W&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!W||!!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:nr.map(X=>{const st=b===X.id,ht=X.icon==="diff",At=ht?null:X.icon;return s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{he&&(we(),qe()),h(X.id)},"aria-label":X.label,"aria-selected":st,role:"tab",className:De(tr,"relative rounded-lg",An===X.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ht?s.jsx(Wd,{className:"h-5 w-5"}):At?s.jsx(I,{name:At,className:"h-5 w-5"}):null,X.badge!==void 0&&X.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:X.badge}),X.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(Mt,{children:s.jsx("p",{children:X.label})})]},X.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[js&&s.jsx(bm,{projectRef:js.projectRef,directory:js.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(nn,{open:$,onOpenChange:X=>{X&&(n&&t&&t(),r&&e&&e()),Ie(X),X&&B.length===0&&V()},children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:De(tr,An==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(I,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(Mt,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(sn,{align:"end",sideOffset:0,positionerClassName:"!fixed !bottom-0 !left-0 !right-0 !top-[var(--oc-header-height,56px)] !transform-none",className:"h-full w-screen max-h-none rounded-none border-0 p-0 pt-1 overflow-hidden",children:s.jsxs("div",{className:"flex h-full flex-col bg-[var(--surface-elevated)]",children:[s.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)] px-2 py-px",children:s.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-0",children:[s.jsx("div",{className:"h-10 min-w-0 flex-1",children:s.jsx(To,{items:lr,activeId:wt,onSelect:X=>{const st=X;ot(st),st==="usage"&&B.length===0&&V()},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})}),s.jsx("button",{type:"button",onClick:()=>Ie(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover","aria-label":o("header.services.closeAria"),children:s.jsx(I,{name:"close",className:"h-5 w-5"})})]})}),wt==="mcp"&&s.jsx(lm,{active:$&&wt==="mcp"}),wt==="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:ym(Z,w)})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"flex items-center h-6",children:[s.jsx("button",{type:"button",onClick:()=>qt("usage"),className:De("typography-ui-label px-1 pb-0.5 transition-colors",se==="usage"?"text-foreground border-b-2 border-[var(--primary-base)]":"text-muted-foreground hover:text-foreground"),children:o("header.services.used")}),s.jsx("span",{className:"text-muted-foreground typography-ui-label px-0.5",children:"·"}),s.jsx("button",{type:"button",onClick:()=>qt("remaining"),className:De("typography-ui-label px-1 pb-0.5 transition-colors",se==="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:De("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:Xt,disabled:M||Ce,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(I,{name:"refresh",className:De("h-4 w-4",Ce&&"animate-spin")})})]})]})}),!Ut&&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:Gt.map((X,st)=>s.jsxs(i.Fragment,{children:[st>0?s.jsx("div",{className:"mx-4 my-1 border-t border-[var(--interactive-border)]"}):null,s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2",children:[s.jsx(Do,{providerId:X.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:X.providerName})]}),X.entries.length===0&&(!X.modelFamilies||X.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:X.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[X.entries.map(([ht,At])=>{const os=se==="remaining"?At.remainingPercent:At.usedPercent,rs=va(At.usedPercent,At.resetAt,At.windowSeconds,ht),ds=rs?.dailyAllocationPercent!=null?se==="remaining"?100-ni(rs.elapsedRatio):ni(rs.elapsedRatio):null,Es=Io(At.valueLabel,os),Gs=Tf(At.resetAt,At.resetAfterFormatted??At.resetAtFormatted,w);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:fc(ht)}),Gs?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Gs}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Es==="-"?"":Es})]}),s.jsx(Ca,{percent:os,tonePercent:At.usedPercent,className:"h-1.5",expectedMarkerPercent:ds}),rs&&Q?s.jsx(Aa,{paceInfo:rs,compact:!0}):null]},`${X.providerId}-${ht}`)}),X.modelFamilies&&X.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:X.modelFamilies.map(ht=>{const os=(xt[X.providerId]??[]).includes(ht.familyId??"other");return s.jsxs(to,{open:os,onOpenChange:()=>Ft(X.providerId,ht.familyId??"other"),children:[s.jsxs(Bo,{className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:ht.familyLabel}),os?s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(so,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:ht.models.map(([rs,ds])=>{const Es=se==="remaining"?ds.remainingPercent:ds.usedPercent,Gs=va(ds.usedPercent,ds.resetAt,ds.windowSeconds),Dn=Gs?.dailyAllocationPercent!=null?se==="remaining"?100-ni(Gs.elapsedRatio):ni(Gs.elapsedRatio):null,Nr=Io(ds.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:am(rs)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Nr==="-"?"":Nr})]}),s.jsx(Ca,{percent:Es,tonePercent:ds.usedPercent,className:"h-1.5",expectedMarkerPercent:Dn}),Gs&&Q?s.jsx(Aa,{paceInfo:Gs,compact:!0}):null]},`${X.providerId}-${rs}`)})})})]},ht.familyId??"other")})})]})]},X.providerId))})]})]})})]}),e?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ps,className:De(tr,"relative",An==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(I,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Mt,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),pn=De("header-safe-area relative z-10 bg-background",he&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:Ne,className:pn,style:{"--padding-scale":"1"},children:he?qn():Rs()}),s.jsx(cm,{open:Ue,onOpenChange:Ke,info:Qe,downloading:!1,downloaded:!1,progress:null,error:Ve,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function Bb(){}const qd=180,Yd=640,Vb=110,_b=t=>{const e=gt.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=kt(),c=Ee($b),l=Ee(zb),d=Ee(Wb),u=Ee(Ub),[m,f]=i.useState(null),[g,y]=i.useState(!1),p=i.useRef(null),x=i.useRef(0),b=i.useRef(c||300),h=Math.min(Yd,Math.max(qd,c||300));let N,w;e[0]!==n?(N=()=>{n||(f(null),y(!1))},w=[n],e[0]=n,e[1]=N,e[2]=w):(N=e[1],w=e[2]),i.useEffect(N,w);let S,j;e[3]!==l||e[4]!==r||e[5]!==n?(S=()=>{if(r||!n||!l)return;const ee=()=>{const je=p.current?.parentElement?.getBoundingClientRect().height;if(!je||je<=0)return;const te=Math.max(0,Math.round(je));f(Ne=>Ne===te?Ne:te)};ee();const re=p.current?.parentElement;if(!re)return;const he=new ResizeObserver(ee);return he.observe(re),()=>{he.disconnect()}},j=[l,r,n],e[3]=l,e[4]=r,e[5]=n,e[6]=S,e[7]=j):(S=e[6],j=e[7]),i.useEffect(S,j);let k,v;if(e[8]!==l||e[9]!==r||e[10]!==g||e[11]!==d||e[12]!==u?(k=()=>{if(r||!g||l)return;const ee=he=>{const je=x.current-he.clientY,te=Math.min(Yd,Math.max(qd,b.current+je));d(te)},re=()=>{y(!1),Ee.getState().bottomTerminalHeight<=Vb&&u(!1)};return window.addEventListener("pointermove",ee),window.addEventListener("pointerup",re,{once:!0}),()=>{window.removeEventListener("pointermove",ee),window.removeEventListener("pointerup",re)}},v=[l,r,g,d,u],e[8]=l,e[9]=r,e[10]=g,e[11]=d,e[12]=u,e[13]=k,e[14]=v):(k=e[13],v=e[14]),i.useEffect(k,v),r)return null;const D=n?l?Math.max(0,m??h):h:0,A=n&&l;let C;e[15]!==D||e[16]!==l||e[17]!==n?(C=ee=>{!n||l||(y(!0),x.current=ee.clientY,b.current=D,ee.preventDefault())},e[15]=D,e[16]=l,e[17]=n,e[18]=C):C=e[18];const O=C,T=A?"absolute inset-x-0 bottom-0 z-40":"relative",E=g?"transition-none":"transition-[height] duration-300 ease-in-out",F=(!n||A)&&"border-t-0";let R;e[19]!==F||e[20]!==T||e[21]!==E?(R=De("flex overflow-hidden border-t border-border bg-sidebar",T,E,F),e[19]=F,e[20]=T,e[21]=E,e[22]=R):R=e[22];let L;e[23]!==D||e[24]!==A?(L=A?{top:0}:{height:`${D}px`,minHeight:`${D}px`,maxHeight:`${D}px`},e[23]=D,e[24]=A,e[25]=L):L=e[25];const B=!n||!l&&D===0;let V;e[26]!==O||e[27]!==l||e[28]!==n||e[29]!==g||e[30]!==a?(V=n&&!l&&s.jsx("div",{className:De("absolute left-0 top-0 z-20 h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",g&&"bg-[var(--interactive-border)]"),onPointerDown:O,role:"separator","aria-orientation":"horizontal","aria-label":a("terminalView.bottomDock.resizeAria")}),e[26]=O,e[27]=l,e[28]=n,e[29]=g,e[30]=a,e[31]=V):V=e[31];const M=!n&&"pointer-events-none select-none opacity-0";let Z;e[32]!==M?(Z=De("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]=Z):Z=e[33];const se=!n;let Q;e[34]!==o||e[35]!==Z||e[36]!==se?(Q=s.jsx("div",{className:Z,"aria-hidden":se,children:o}),e[34]=o,e[35]=Z,e[36]=se,e[37]=Q):Q=e[37];let K;return e[38]!==R||e[39]!==L||e[40]!==B||e[41]!==V||e[42]!==Q?(K=s.jsxs("section",{ref:p,className:R,style:L,"aria-hidden":B,children:[V,Q]}),e[38]=R,e[39]=L,e[40]=B,e[41]=V,e[42]=Q,e[43]=K):K=e[43],K};function $b(t){return t.bottomTerminalHeight}function zb(t){return t.isBottomTerminalExpanded}function Wb(t){return t.setBottomTerminalHeight}function Ub(t){return t.setBottomTerminalOpen}const Qd=280,Jd=280,Xd=500,Hb=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=kt(),c=Ee(v=>v.sidebarWidth),l=Ee(v=>v.setSidebarWidth),[d,u]=i.useState(!1),m=i.useRef(0),f=i.useRef(c||Qd),g=i.useRef(null),y=i.useRef(null),p=i.useRef(null),x=i.useCallback(v=>Math.min(Xd,Math.max(Jd,v)),[]),b=i.useCallback(v=>{const D=p.current;D&&(D.style.width=`${v}px`,D.style.minWidth=`${v}px`,D.style.maxWidth=`${v}px`,D.style.setProperty("--oc-left-sidebar-width",`${v}px`))},[]);if(i.useEffect(()=>{e&&d&&u(!1)},[e,d]),i.useEffect(()=>{d||(g.current=null,y.current=null)},[d]),e)return null;const h=Math.min(Xd,Math.max(Jd,c||Qd)),N=t?h:0,w=v=>{if(t){try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}y.current=v.pointerId,u(!0),m.current=v.clientX,f.current=N,g.current=N,b(N),v.preventDefault()}},S=v=>{if(e||!d||y.current!==v.pointerId)return;const D=v.clientX-m.current,A=x(f.current+D);g.current!==A&&(g.current=A,b(A))},j=v=>{if(y.current!==v.pointerId||e)return;try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}const D=x(g.current??N);y.current=null,g.current=null,u(!1),l(D)},k=d?g.current??N:N;return s.jsxs("aside",{ref:p,className:De("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||N===0,children:[t&&s.jsx("div",{className:De("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",d&&"bg-[var(--interactive-border)]"),onPointerDown:w,onPointerMove:S,onPointerUp:j,onPointerCancel:j,role:"separator","aria-orientation":"vertical","aria-label":a("sidebar.resize.leftPanelAria")}),s.jsxs("div",{className:De("relative z-10 flex h-full shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",d&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[o,s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:s.jsx(en,{children:n})})]})]})},Gb=()=>{const t=gt.c(3);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e={height:"var(--oc-header-height, 3rem)"},t[0]=e):e=t[0];let n;t[1]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("div",{className:"app-region-drag shrink-0",style:{width:"var(--oc-titlebar-left-inset, 0.75rem)"}}),t[1]=n):n=t[1];let r;return t[2]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsxs("div",{"aria-hidden":!0,className:"flex shrink-0",style:e,children:[n,s.jsx("div",{className:"app-region-no-drag shrink-0",style:{width:"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)"}}),s.jsx("div",{className:"app-region-drag flex-1"})]}),t[2]=r):r=t[2],r},Ho=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function Kb(){const t=ws(f=>f.activeProjectId?f.projects.find(g=>g.id===f.activeProjectId)??null:null),e=ut(f=>f.currentSessionId),n=Ef(e??null),r=ut(f=>e?f.worktreeMetadata.get(e)?.path??"":""),o=ut(f=>f.newSessionDraft?.open?Ho(f.newSessionDraft.bootstrapPendingDirectory??f.newSessionDraft.directoryOverride??""):""),a=i.useMemo(()=>Ho(r||""),[r]),c=i.useMemo(()=>{const f=typeof n?.directory=="string"?n.directory:"";return Ho(f||"")},[n?.directory]),l=a||c||o,d=i.useMemo(()=>Ho(l||t?.path||""),[t?.path,l]),u=i.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),m=i.useRef(null);return i.useEffect(()=>{u&&d&&(m.current={projectRef:u,directory:d})},[d,u]),i.useMemo(()=>u&&d?{projectRef:u,directory:d}:m.current,[u,d])}const Zd="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",qb=()=>{const t=gt.c(31),{t:e}=kt(),n=Ee(Yb),r=Ee(Qb),o=Ee(Jb),a=Kb(),c=i.useRef(null),l=La(ri("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const u=d,m=Zb;let f,g;t[0]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{if(typeof document>"u")return;const F=c.current;if(!F)return;const R=()=>{const B=F.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(B)}px`)};if(R(),typeof ResizeObserver>"u")return;const L=new ResizeObserver(R);return L.observe(F),()=>{L.disconnect()}},g=[],t[0]=f,t[1]=g):(f=t[0],g=t[1]),i.useEffect(f,g);const y="app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2";let p;t[2]===Symbol.for("react.memo_cache_sentinel")?(p={height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},t[2]=p):p=t[2];const x="flex items-center gap-2";let b;t[3]!==e?(b=u?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,"aria-label":e("header.actions.openAppMenuAria"),className:De(Zd,"shrink-0"),children:s.jsx(I,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Mt,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=b):b=t[4];const h=Rt;let N;t[5]!==e?(N=e("header.actions.openSessionsAria"),t[5]=e,t[6]=N):N=t[6];let w,S;t[7]===Symbol.for("react.memo_cache_sentinel")?(w=De(Zd,"shrink-0"),S=s.jsx(I,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=w,t[8]=S):(w=t[7],S=t[8]);let j;t[9]!==N||t[10]!==n?(j=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":N,className:w,children:S})}),t[9]=N,t[10]=n,t[11]=j):j=t[11];const k=Mt,v=e("header.actions.openSessionsWithShortcut",{shortcut:l});let D;t[12]!==v?(D=s.jsx("p",{children:v}),t[12]=v,t[13]=D):D=t[13];let A;t[14]!==k||t[15]!==D?(A=s.jsx(k,{children:D}),t[14]=k,t[15]=D,t[16]=A):A=t[16];let C;t[17]!==h||t[18]!==j||t[19]!==A?(C=s.jsxs(h,{children:[j,A]}),t[17]=h,t[18]=j,t[19]=A,t[20]=C):C=t[20];let O;t[21]!==r||t[22]!==a?(O=a?s.jsx(bm,{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 T;t[24]!==C||t[25]!==O||t[26]!==b?(T=s.jsxs("div",{ref:c,className:x,children:[b,C,O]}),t[24]=C,t[25]=O,t[26]=b,t[27]=T):T=t[27];let E;return t[28]!==T||t[29]!==p?(E=s.jsx("div",{className:y,style:p,children:T}),t[28]=T,t[29]=p,t[30]=E):E=t[30],E};function Yb(t){return t.toggleSidebar}function Qb(t){return t.isSidebarOpen}function Jb(t){return t.shortcutOverrides}function Xb(t){console.warn("[titlebar] failed to open app menu",t)}function Zb(t){const e=t.currentTarget.getBoundingClientRect();Wr("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(Xb)}const eu=420,ey=({isOpen:t,children:e,className:n})=>{const{t:r}=kt(),o=Ee(j=>j.rightSidebarWidth),a=Ee(j=>j.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),u=i.useRef(o||eu),m=i.useRef(null),f=i.useRef(null),g=i.useRef(null),y=i.useCallback(j=>Math.min(fd,Math.max(md,j)),[]),p=i.useCallback(j=>{const k=g.current;k&&(k.style.width=`${j}px`,k.style.minWidth=`${j}px`,k.style.maxWidth=`${j}px`,k.style.setProperty("--oc-right-sidebar-width",`${j}px`))},[]),x=Math.min(fd,Math.max(md,o||eu)),b=t?x:0,h=j=>{if(t){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}f.current=j.pointerId,l(!0),d.current=j.clientX,u.current=b,m.current=b,p(b),j.preventDefault()}},N=j=>{if(!c||f.current!==j.pointerId)return;const k=d.current-j.clientX,v=y(u.current+k);m.current!==v&&(m.current=v,p(v))},w=j=>{if(f.current!==j.pointerId)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const k=y(m.current??b);f.current=null,m.current=null,l(!1),a(k)},S=c?m.current??b:b;return s.jsxs("aside",{ref:g,className:De("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:x}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||b===0,children:[t&&s.jsx("div",{className:De("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:N,onPointerUp:w,onPointerCancel:w,role:"separator","aria-orientation":"vertical","aria-label":r("sidebar.resize.rightPanelAria")}),s.jsx("div",{className:De("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})]})},tu=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function wm(t){const e=gt.c(120),{t:n}=kt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,onConfirm:d}=t,u=l===void 0?!1:l,m=ss(dy),f=ss(cy),g=vp(ly),y=ss(ay),p=ss(oy),x=ss(iy),b=ss(ry),h=ss(ny);let N;e[0]!==h||e[1]!==x||e[2]!==p||e[3]!==b?(N=()=>tu({providerID:p,modelID:x,variant:b,agent:h}),e[0]=h,e[1]=x,e[2]=p,e[3]=b,e[4]=N):N=e[4];const[w,S]=i.useState(N);let j,k;e[5]!==g||e[6]!==f||e[7]!==m||e[8]!==r||e[9]!==c?(j=()=>{r&&(m({directory:c,source:"todoSendDialog"}),f({directory:c}),g())},k=[r,m,f,g,c],e[5]=g,e[6]=f,e[7]=m,e[8]=r,e[9]=c,e[10]=j,e[11]=k):(j=e[10],k=e[11]),i.useEffect(j,k);let v,D;e[12]!==h||e[13]!==x||e[14]!==p||e[15]!==b||e[16]!==r?(v=()=>{r&&S(tu({providerID:p,modelID:x,variant:b,agent:h}))},D=[r,p,x,b,h],e[12]=h,e[13]=x,e[14]=p,e[15]=b,e[16]=r,e[17]=v,e[18]=D):(v=e[17],D=e[18]),i.useEffect(v,D);let A,C;e[19]!==w.modelID||e[20]!==w.providerID||e[21]!==r||e[22]!==y?(A=()=>{if(!r||y.length===0)return;const ve=y.find(P=>P.id===w.providerID)??y[0],Fe=Array.isArray(ve?.models)?ve.models:[],Ce=Fe.some(P=>P.id===w.modelID),ne=Fe[0]?.id??"";ve?.id===w.providerID&&Ce||S(P=>({...P,providerID:ve?.id??"",modelID:Ce?P.modelID:ne,variant:""}))},C=[r,y,w.providerID,w.modelID],e[19]=w.modelID,e[20]=w.providerID,e[21]=r,e[22]=y,e[23]=A,e[24]=C):(A=e[23],C=e[24]),i.useEffect(A,C);const O=sy;let T;if(e[25]!==w.modelID||e[26]!==w.providerID||e[27]!==y){let ve;e[29]!==w.providerID?(ve=Ce=>Ce.id===w.providerID,e[29]=w.providerID,e[30]=ve):ve=e[30],T=y.find(ve)?.models?.find(Ce=>Ce.id===w.modelID),e[25]=w.modelID,e[26]=w.providerID,e[27]=y,e[28]=T}else T=e[28];const E=T;let F;e[31]!==E?(F=E?.variants?Object.keys(E.variants):[],e[31]=E,e[32]=F):F=e[32];const R=F,L=R.length>0;let B,V;e[33]!==w.variant||e[34]!==L?(B=()=>{L||!w.variant||S(ty)},V=[L,w.variant],e[33]=w.variant,e[34]=L,e[35]=B,e[36]=V):(B=e[35],V=e[36]),i.useEffect(B,V);let M;e[37]!==w.modelID||e[38]!==w.providerID?(M=w.providerID.trim().length>0&&w.modelID.trim().length>0,e[37]=w.modelID,e[38]=w.providerID,e[39]=M):M=e[39];const Z=M;let se;e[40]!==Z||e[41]!==w||e[42]!==d||e[43]!==u?(se=()=>{!Z||u||d(w)},e[40]=Z,e[41]=w,e[42]=d,e[43]=u,e[44]=se):se=e[44];const Q=se;let K,ee;e[45]!==Q||e[46]!==r?(K=()=>{if(!r)return;const ve=Fe=>{(Fe.metaKey||Fe.ctrlKey)&&Fe.key==="Enter"&&(Fe.preventDefault(),Q())};return window.addEventListener("keydown",ve),()=>window.removeEventListener("keydown",ve)},ee=[r,Q],e[45]=Q,e[46]=r,e[47]=K,e[48]=ee):(K=e[47],ee=e[48]),i.useEffect(K,ee);let re;e[49]!==n||e[50]!==a?(re=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[49]=n,e[50]=a,e[51]=re):re=e[51];const he=re;let je;e[52]!==o||e[53]!==u?(je=ve=>{u||o(ve)},e[52]=o,e[53]=u,e[54]=je):je=e[54];let te;e[55]!==he?(te=s.jsx(Us,{children:s.jsx(_s,{children:he})}),e[55]=he,e[56]=te):te=e[56];let Ne;e[57]!==n?(Ne=n("chat.modelControls.model"),e[57]=n,e[58]=Ne):Ne=e[58];let J;e[59]!==Ne?(J=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:Ne}),e[59]=Ne,e[60]=J):J=e[60];let H;e[61]===Symbol.for("react.memo_cache_sentinel")?(H=(ve,Fe)=>{S(Ce=>({...Ce,providerID:ve,modelID:Fe,variant:""}))},e[61]=H):H=e[61];let q;e[62]!==w.modelID||e[63]!==w.providerID?(q=s.jsx($f,{providerId:w.providerID,modelId:w.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:H}),e[62]=w.modelID,e[63]=w.providerID,e[64]=q):q=e[64];let ae;e[65]!==J||e[66]!==q?(ae=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[J,q]}),e[65]=J,e[66]=q,e[67]=ae):ae=e[67];let le;e[68]!==n?(le=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[68]=n,e[69]=le):le=e[69];let Se;e[70]!==le?(Se=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:le}),e[70]=le,e[71]=Se):Se=e[71];const Re=!L;let _e;e[72]===Symbol.for("react.memo_cache_sentinel")?(_e=ve=>S(Fe=>({...Fe,variant:ve})),e[72]=_e):_e=e[72];let Oe;e[73]!==w.variant||e[74]!==Re||e[75]!==R?(Oe=s.jsx(jp,{value:w.variant,options:R,disabled:Re,onChange:_e}),e[73]=w.variant,e[74]=Re,e[75]=R,e[76]=Oe):Oe=e[76];let Me;e[77]!==Se||e[78]!==Oe?(Me=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Se,Oe]}),e[77]=Se,e[78]=Oe,e[79]=Me):Me=e[79];let ge;e[80]!==n?(ge=n("sessions.scheduledTasks.editor.agent.label"),e[80]=n,e[81]=ge):ge=e[81];let Ae;e[82]!==ge?(Ae=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ge}),e[82]=ge,e[83]=Ae):Ae=e[83];let pe;e[84]===Symbol.for("react.memo_cache_sentinel")?(pe=ve=>S(Fe=>({...Fe,agent:ve})),e[84]=pe):pe=e[84];let ue;e[85]!==w.agent?(ue=s.jsx(zf,{agentName:w.agent,filter:O,dropdownPortalToBody:!0,onChange:pe}),e[85]=w.agent,e[86]=ue):ue=e[86];let G;e[87]!==Ae||e[88]!==ue?(G=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Ae,ue]}),e[87]=Ae,e[88]=ue,e[89]=G):G=e[89];let fe;e[90]!==ae||e[91]!==Me||e[92]!==G?(fe=s.jsxs("div",{className:"flex flex-col gap-4",children:[ae,Me,G]}),e[90]=ae,e[91]=Me,e[92]=G,e[93]=fe):fe=e[93];let ce;e[94]!==o?(ce=()=>o(!1),e[94]=o,e[95]=ce):ce=e[95];let W;e[96]!==n?(W=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[96]=n,e[97]=W):W=e[97];let z;e[98]!==u||e[99]!==ce||e[100]!==W?(z=s.jsx($e,{variant:"ghost",size:"sm",onClick:ce,disabled:u,children:W}),e[98]=u,e[99]=ce,e[100]=W,e[101]=z):z=e[101];const be=!Z||u;let xe;e[102]!==u||e[103]!==n?(xe=n(u?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[102]=u,e[103]=n,e[104]=xe):xe=e[104];let _;e[105]!==Q||e[106]!==be||e[107]!==xe?(_=s.jsx($e,{size:"sm",onClick:Q,disabled:be,children:xe}),e[105]=Q,e[106]=be,e[107]=xe,e[108]=_):_=e[108];let ye;e[109]!==z||e[110]!==_?(ye=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[z,_]}),e[109]=z,e[110]=_,e[111]=ye):ye=e[111];let $;e[112]!==te||e[113]!==fe||e[114]!==ye?($=s.jsxs(Ls,{className:"max-w-md overflow-visible",children:[te,fe,ye]}),e[112]=te,e[113]=fe,e[114]=ye,e[115]=$):$=e[115];let Ie;return e[116]!==r||e[117]!==je||e[118]!==$?(Ie=s.jsx(Os,{open:r,onOpenChange:je,children:$}),e[116]=r,e[117]=je,e[118]=$,e[119]=Ie):Ie=e[119],Ie}function ty(t){return{...t,variant:""}}function sy(t){return gc(t.mode)}function ny(t){return t.currentAgentName||""}function ry(t){return t.currentVariant||""}function iy(t){return t.currentModelId}function oy(t){return t.currentProviderId}function ay(t){return t.providers}function ly(t){return t.loadAgents}function cy(t){return t.loadAgents}function dy(t){return t.loadProviders}const Yl=5,vm=15,Go=new Map,la=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},uy=(t,e)=>{const n=la(e);return Math.max(n*Yl,Math.min(n*vm,n*t))},fy=async(t,e)=>{const n=await Cp(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},my=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,su=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],nu=(t,e)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},hy=t=>{const e=gt.c(20),{id:n,children:r}=t;let o;e[0]!==n?(o={id:n},e[0]=n,e[1]=o):o=e[1];const{attributes:a,listeners:c,setNodeRef:l,setActivatorNodeRef:d,transform:u,transition:m,isDragging:f}=oc(o);let g;e[2]!==u?(g=ac.Transform.toString(u),e[2]=u,e[3]=g):g=e[3];let y;e[4]!==g||e[5]!==m?(y={transform:g,transition:m},e[4]=g,e[5]=m,e[6]=y):y=e[6];const p=f&&"opacity-60";let x;e[7]!==p?(x=De(p),e[7]=p,e[8]=x):x=e[8];let b;e[9]!==a||e[10]!==r||e[11]!==f||e[12]!==c||e[13]!==d?(b=r({attributes:a,listeners:c,setActivatorNodeRef:d,isDragging:f}),e[9]=a,e[10]=r,e[11]=f,e[12]=c,e[13]=d,e[14]=b):b=e[14];let h;return e[15]!==l||e[16]!==y||e[17]!==x||e[18]!==b?(h=s.jsx("li",{ref:l,style:y,className:x,children:b}),e[15]=l,e[16]=y,e[17]=x,e[18]=b,e[19]=h):h=e[19],h},py=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=kt(),[c,l]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState([]),[g,y]=i.useState(""),[p,x]=i.useState(null),[b,h]=i.useState(()=>new Set),[N,w]=i.useState([]),[S,j]=i.useState(null),[k,v]=i.useState(!1),[D,A]=i.useState(0),C=i.useRef(!1),O=i.useRef(""),T=i.useRef(null),E=Ee(P=>P.todoPanelHeight),F=Ee(P=>P.setTodoPanelHeight),R=Ee(P=>P.notesPanelHeight),L=Ee(P=>P.setNotesPanelHeight),[B,V]=i.useState(!1),M=i.useRef(0),Z=i.useRef(E),se=ut(P=>P.currentSessionId),Q=ut(P=>P.createSession),K=ut(P=>P.initializeNewOpenChamberSession),ee=ut(P=>P.sendMessage),re=ut(P=>P.setCurrentSession),he=li(P=>P.setPendingInputText),je=Qs(P=>P.currentDirectory),te=Ee(P=>P.openContextPanelTab),Ne=Ee(P=>P.setActiveMainTab),J=Ee(P=>P.setSessionSwitcherOpen),H=Ee(P=>P.padding),q=i.useCallback(async(P,me)=>{if(!t)return!1;const oe=t.id,Ue=(Go.get(oe)??Promise.resolve()).catch(()=>{}).then(()=>Sp(t,{notes:P,todos:me}));Go.set(oe,Ue);try{const Ke=await Ue;return Ke||de.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),Ke}finally{Go.get(oe)===Ue&&Go.delete(oe)}},[t,a]);i.useEffect(()=>{if(!t){u(""),f([]),w([]),y(""),h(new Set);return}let P=!1;return l(!0),(async()=>{try{const me=await Np(t),oe=await Promise.all(me.plans.map(Be=>fy(Be,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(P)return;u(me.notes),f(su(me.todos)),w(oe),O.current=me.notes,C.current=!0,y(""),h(new Set)}catch{P||(de.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),u(""),f([]),w([]),O.current="",C.current=!0)}finally{P||l(!1)}})(),()=>{P=!0}},[D,t,a]),i.useEffect(()=>{if(!t)return;const P=me=>{const oe=me.detail;oe?.projectId&&oe.projectId!==t.id||A(Be=>Be+1)};return window.addEventListener("openchamber:project-plan-saved",P),window.addEventListener("openchamber:project-notes-updated",P),()=>{window.removeEventListener("openchamber:project-plan-saved",P),window.removeEventListener("openchamber:project-notes-updated",P)}},[t]),i.useEffect(()=>{if(m.length<7)return;const P=uy(m.length,H),me=la(H)*Yl;E!==P&&(E<me||E>P)&&F(P)},[m.length,H,E,F]),i.useEffect(()=>{if(!B)return;const P=oe=>{const Be=oe.clientY-M.current,Ue=Math.min(la(H)*vm,Math.max(la(H)*Yl,Z.current+Be));F(Ue)},me=()=>{V(!1)};return window.addEventListener("pointermove",P),window.addEventListener("pointerup",me,{once:!0}),window.addEventListener("pointercancel",me,{once:!0}),()=>{window.removeEventListener("pointermove",P),window.removeEventListener("pointerup",me),window.removeEventListener("pointercancel",me)}},[B,H,F]);const ae=i.useCallback(P=>{V(!0),M.current=P.clientY,Z.current=E,P.preventDefault()},[E]),le=i.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),Se=i.useCallback(()=>{le(),O.current=d,q(d,m)},[le,d,q,m]);i.useEffect(()=>{if(!(!t||!C.current)&&d!==O.current)return T.current=window.setTimeout(()=>{T.current=null,O.current=d,q(d,m)},400),()=>{le()}},[le,d,q,t,m]),i.useEffect(()=>()=>le(),[le]);const Re=i.useCallback(()=>{const P=g.trim();if(!P)return;const me=nu(m,{id:my(),text:P.slice(0,zo),completed:!1,createdAt:Date.now()});f(me),y(""),q(d,me)},[g,d,q,m]),_e=i.useCallback(P=>{h(me=>{const oe=new Set(me);return oe.has(P)?oe.delete(P):oe.add(P),oe})},[]),Oe=i.useCallback((P,me)=>{const oe=m.find(Qe=>Qe.id===P);if(!oe||oe.completed===me)return;const Be=m.filter(Qe=>Qe.id!==P),Ue={...oe,completed:me},Ke=me?[...Be,Ue]:nu(Be,Ue);f(Ke),q(d,Ke)},[d,q,m]),Me=i.useCallback(P=>{const me=m.filter(oe=>oe.id!==P);f(me),q(d,me)},[d,q,m]),ge=i.useCallback(()=>{const P=m.filter(me=>!me.completed);P.length!==m.length&&(f(P),q(d,P))},[d,q,m]),Ae=i.useCallback(P=>{const{active:me,over:oe}=P;if(!oe||me.id===oe.id)return;const Be=m.findIndex(Qe=>Qe.id===me.id),Ue=m.findIndex(Qe=>Qe.id===oe.id);if(Be===-1||Ue===-1)return;const Ke=su(kf(m,Be,Ue));f(Ke),q(d,Ke)},[d,q,m]),pe=ga(yo(xa,{activationConstraint:{distance:8}})),ue=g.slice(0,zo),G=m.reduce((P,me)=>P+(me.completed?1:0),0),fe=i.useCallback(()=>{Ne("chat"),J(!1)},[Ne,J]),ce=i.useCallback((P,me)=>{!t||p||j({kind:"session",todoId:P,todoText:me})},[t,p]),W=i.useCallback(P=>{if(!se){de.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}fe();const me=`\`\`\`md
4
- ${P}
5
- \`\`\``;he(me,"append"),de.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[se,r,fe,he,a]),z=i.useCallback((P,me)=>{if(!(!t||p)){if(!n){de.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}j({kind:"worktree",todoId:P,todoText:me})}},[n,t,p,a]),be=i.useCallback(async P=>{if(!t||!S)return;const me=await Fn("plan.todo.visible",{todo_text:S.todoText}),Be=[{synthetic:!0,text:await Fn("plan.todo.instructions",{todo_text:S.todoText})}];v(!0),x(S.todoId);try{fe();let Ue=null,Ke=t.path;if(S.kind==="worktree"){if(!n){de.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const rt=await Wf(t.path,Uf());if(!rt?.id)return;Ue=rt.id,Ke=rt.path}else{const rt=await Q(void 0,t.path,null);if(!rt?.id){de.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}Ue=rt.id,Ke=rt.directory??t.path,K(rt.id,ss.getState().agents??[])}if(!Ue)return;const Qe=xc.getState();Qe.saveSessionModelSelection(Ue,P.providerID,P.modelID),P.agent.trim()&&(Qe.saveSessionAgentSelection(Ue,P.agent),Qe.saveAgentModelForSession(Ue,P.agent,P.providerID,P.modelID),Qe.saveAgentModelVariantForSession(Ue,P.agent,P.providerID,P.modelID,P.variant||void 0)),re(Ue,Ke),await ee(me,P.providerID,P.modelID,P.agent.trim()||void 0,void 0,void 0,Be,P.variant||void 0),de.success(S.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),j(null),r?.()}catch(Ue){const Ke=Ue instanceof Error?Ue.message:void 0;de.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),Ke?{description:Ke}:void 0)}finally{v(!1),x(null)}},[n,Q,K,r,S,t,fe,ee,re,a]),xe=i.useRef(null),[_,ye]=i.useState(!1),[$,Ie]=i.useState(null),ve=i.useCallback(async P=>{if(!(!t||$)){Ie(P);try{if(!await kp(t,P)){de.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}w(oe=>oe.filter(Be=>Be.id!==P)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{Ie(null)}}},[$,t,a]),Fe=i.useCallback(async()=>{if(!t||_)return;const P=await ep({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(P.success&&P.path){ye(!0);try{const me=new URLSearchParams({path:P.path,allowOutsideWorkspace:"true"});P.outsideFileGrant&&me.set("outsideFileGrant",P.outsideFileGrant);const oe=await As(`/api/fs/read?${me.toString()}`,{cache:"no-store"});if(!oe.ok){de.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const Be=await oe.text();if(!Be.trim()){de.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Ue=P.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await wd(t,Be,Ue)){de.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),de.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(me){const oe=me instanceof Error?me.message:void 0;de.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),oe?{description:oe}:void 0)}finally{ye(!1)}}else P.error==="Native file picker not available"&&xe.current?.click()},[_,t,a]),Ce=i.useCallback(async P=>{if(!(!t||!P)){ye(!0);try{const me=await P.text();if(!me.trim()){de.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const oe=P.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await wd(t,me,oe)){de.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),de.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(me){const oe=me instanceof Error?me.message:void 0;de.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),oe?{description:oe}:void 0)}finally{ye(!1)}}},[t,a]),ne=i.useCallback(P=>{const me=t?.path?.trim(),oe=je?.trim()||me;oe&&te(oe,{mode:"plan",targetPath:P.path,dedupeKey:P.path,label:P.title})},[je,te,t]);return t?s.jsxs("div",{className:De("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,"/",vd]})]}),s.jsx(Ci,{value:d,onChange:P=>u(P.target.value.slice(0,vd)),onBlur:Se,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:R,onResizeHeightChange:L,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:ge,disabled:c||G===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:a("rightSidebar.contextNotesTodo.todo.clearCompleted")})]}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue.length,"/",zo]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(vn,{value:ue,onChange:P=>y(P.target.value.slice(0,zo)),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),Re())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:Re,disabled:c||ue.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.addAria"),title:a("rightSidebar.contextNotesTodo.todo.addAria"),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:De("overflow-y-auto rounded-lg border border-border/60 bg-background/40",B&&"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(ba,{sensors:pe,collisionDetection:ya,onDragEnd:Ae,children:s.jsx(Ll,{items:m.map(P=>P.id),strategy:Ol,children:s.jsx("ul",{className:"divide-y divide-border/50",children:m.map(P=>{const me=b.has(P.id);return s.jsx(hy,{id:P.id,children:oe=>s.jsxs("div",{className:De("flex gap-1.5 px-2.5 py-1.5",me?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:oe.setActivatorNodeRef,...oe.attributes,...oe.listeners,onClick:Be=>{Be.preventDefault(),Be.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:P.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:P.text}),children:s.jsx(I,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(Ri,{checked:P.completed,onChange:Be=>Oe(P.id,Be),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:P.text})})}),s.jsx("button",{type:"button",onClick:()=>_e(P.id),className:De("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",me?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",P.completed&&"text-muted-foreground line-through"),title:me?void 0:P.text,"aria-label":me?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:P.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:P.text}),children:P.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Me(P.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:P.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:P.text}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",disabled:p===P.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:P.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:P.text}),children:s.jsx(I,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(sn,{align:"end",className:"w-56",children:[s.jsx(bs,{onClick:()=>W(P.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(bs,{onClick:()=>ce(P.id,P.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(bs,{onClick:()=>{z(P.id,P.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},P.id)})})})})}),m.length>=7&&s.jsx("div",{className:De("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",B&&"bg-[var(--interactive-border)]"),onPointerDown:ae,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:N.length===1?a("rightSidebar.contextNotesTodo.plans.filesSingle",{count:N.length}):a("rightSidebar.contextNotesTodo.plans.filesPlural",{count:N.length})})]}),s.jsx("input",{ref:xe,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:P=>{const me=P.target.files?.[0]??null;Ce(me),P.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Fe,disabled:!t||_,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.plans.importFromFile"),title:a("rightSidebar.contextNotesTodo.plans.importFromFile"),children:s.jsx(I,{name:"add",className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:N.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:N.map(P=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>ne(P),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:P.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(P.createdAt).toLocaleDateString(Zi())})]}),s.jsx("button",{type:"button",onClick:()=>{ve(P.id)},disabled:$===P.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:P.title}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},P.id))})})]}),s.jsx(wm,{open:S!==null,onOpenChange:P=>{!P&&!k&&j(null)},target:S?.kind??"session",projectDirectory:t?.path??null,submitting:k,onConfirm:be})]}):s.jsx("div",{className:De("w-full min-w-0 p-3",o),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.empty.selectProject")})})},jm=12,gy=[{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"}],xy=t=>{const e=gt.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,u=a===void 0?900:a,m=c===void 0?gy:c,f=tt.useRef(!1);let g,y;e[0]!==n||e[1]!==l?(g=()=>{!n&&f.current&&l?.(),n&&(f.current=!0)},y=[n,l],e[0]=n,e[1]=l,e[2]=g,e[3]=y):(g=e[2],y=e[3]),tt.useEffect(g,y);let p;e[4]===Symbol.for("react.memo_cache_sentinel")?(p=Array.from({length:jm},by),e[4]=p):p=e[4];const x=p;if(!n)return null;let b;e[5]!==o?(b=De("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=b):b=e[6];let h;if(e[7]!==d||e[8]!==m||e[9]!==u){let w;e[11]!==d||e[12]!==u?(w=S=>{const j={"--burst-delay":`${S.delay}ms`,"--burst-x":`${S.x}%`,"--burst-y":`${S.y}%`,"--firework-color":`var(${S.colorVar})`,"--firework-duration":`${u}ms`};return s.jsx("div",{className:"firework-burst",style:j,children:x.map((k,v)=>{const D=k.x*S.radius,A=k.y*S.radius,C={"--translate-x":`${D}px`,"--translate-y":`${A}px`,"--particle-delay":`${k.delay}ms`,color:`var(${S.colorVar})`};return s.jsx("span",{className:"firework-particle",style:C},`${S.id}-${v}-${d}`)})},`${S.id}-${d}`)},e[11]=d,e[12]=u,e[13]=w):w=e[13],h=m.map(w),e[7]=d,e[8]=m,e[9]=u,e[10]=h}else h=e[10];let N;return e[14]!==d||e[15]!==b||e[16]!==h?(N=s.jsx("div",{className:b,"aria-hidden":"true","data-burst-key":d,children:h}),e[14]=d,e[15]=b,e[16]=h,e[17]=N):N=e[17],N};function by(t,e){const n=Math.PI*2*e/jm;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const yy=t=>{const e=gt.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]=tt.useState(a),d=tt.useRef(null);let u;e[3]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{d.current&&(window.clearTimeout(d.current),d.current=null)},e[3]=u):u=e[3];const m=u;let f;e[4]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{m(),l(wy)},e[4]=f):f=e[4];const g=f;let y;e[5]!==o?(y=()=>{m(),l(vy),d.current=window.setTimeout(()=>{l(jy),d.current=null},o)},e[5]=o,e[6]=y):y=e[6];const p=y;let x,b;e[7]===Symbol.for("react.memo_cache_sentinel")?(x=()=>()=>m(),b=[m],e[7]=x,e[8]=b):(x=e[7],b=e[8]),tt.useEffect(x,b);let h;return e[9]!==c.cycle||e[10]!==c.isActive||e[11]!==p?(h={isActive:c.isActive,burstKey:c.cycle,triggerFireworks:p,dismissFireworks:g},e[9]=c.cycle,e[10]=c.isActive,e[11]=p,e[12]=h):h=e[12],h};function wy(t){return t.isActive?{...t,isActive:!1}:t}function vy(t){return{isActive:!0,cycle:t.cycle+1}}function jy(t){return t.isActive?{...t,isActive:!1}:t}const Sm=i.createContext(void 0),Sy=t=>{const e=gt.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=yy();let l;e[0]!==c||e[1]!==a?(l={triggerFireworks:a,dismissFireworks:c},e[0]=c,e[1]=a,e[2]=l):l=e[2];const d=l;let u;e[3]!==o||e[4]!==r?(u=s.jsx(xy,{isActive:r,burstKey:o}),e[3]=o,e[4]=r,e[5]=u):u=e[5];let m;return e[6]!==n||e[7]!==u||e[8]!==d?(m=s.jsxs(Sm.Provider,{value:d,children:[n,u]}),e[6]=n,e[7]=u,e[8]=d,e[9]=m):m=e[9],m},Ny=()=>{const t=i.useContext(Sm);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Nm="gitmojiCache",ky=1e3*60*60*24*7,km="1",Cy="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Cm=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},ml=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Nm);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==km||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(Cm),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},Ay=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:km};window.localStorage.setItem(Nm,JSON.stringify(e))}catch{return}},ru=t=>Date.now()-t.fetchedAt<ky;let Ko=null;const So=new Set,iu=async()=>{if(Ko)return Ko;const t=(async()=>{try{const e=await fetch(Cy);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(Cm):[];return Ay(r),So.forEach(o=>o(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return So.forEach(r=>r(n)),n}finally{Ko=null}})();return Ko=t,t},Dy=t=>{const[e,n]=i.useState(()=>t?ml()?.gitmojis??[]:[]),[r,o]=i.useState(!1),a=i.useRef(t);a.current=t,i.useEffect(()=>{if(!t){So.delete(n),n([]),o(!1);return}const l=ml();if(l&&(n(l.gitmojis),ru(l)))return;So.add(n),o(!0);let d=!1;return iu().finally(()=>{!d&&a.current&&o(!1)}),()=>{d=!0,So.delete(n)}},[t]);const c=i.useCallback(async()=>{if(!a.current)return[];if(e.length>0)return e;const l=ml();return l&&ru(l)?l.gitmojis:iu()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:c}},ou=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function Iy(t,e,n){const r=gt.c(5),[o,a]=i.useState();let c,l;return r[0]!==n||r[1]!==t||r[2]!==e?(c=()=>{if(e){a(void 0);return}if(!t){a(void 0);return}a(void 0);let d=!1;return(async()=>{const[u,m]=await Promise.all([Ap(t),Dp(t)]).catch(Py);if(d)return;const f=ou(u),g=ou(m);if(!f||!g||g===f)return;const y=n||"",p=g.split("/").filter(Boolean).pop()||g;a({source:"sdk",path:g,projectDirectory:f,branch:y,label:y||p,name:p,worktreeRoot:g,worktreeStatus:"ready",headState:y?"branch":"unborn",worktreeSource:"existing"})})(),()=>{d=!0}},l=[t,e,n],r[0]=n,r[1]=t,r[2]=e,r[3]=c,r[4]=l):(c=r[3],l=r[4]),i.useEffect(c,l),e??o}function Py(){return["",""]}const lo=async(t,e)=>{const n=await As(`/api/git/integrate/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>null);throw new Error(r?.error||`Git integrate request failed: ${n.statusText}`)}return n.json()};async function ho(t){return lo("plan",t)}async function Ty(t){return lo("conflict-details",{tempWorktreePath:t})}async function Ry(t){return(await lo("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function Ey(t){return lo("run",{plan:t})}async function My(t){await lo("abort",{state:t})}async function Fy(t){return lo("continue",{state:t})}const Ly=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=kt(),d=ut(M=>M.currentSessionId),u=Ee(M=>M.setActiveMainTab),[m,f]=tt.useState(!1),g=tt.useRef(null),[y,p]=tt.useState(o);tt.useEffect(()=>{p(o)},[o]),tt.useEffect(()=>{if(m){const M=setTimeout(()=>{g.current?.focus()},0);return()=>clearTimeout(M)}},[m]);const x=!!(t&&e&&y&&y!=="HEAD"&&e!==y),[b,h]=tt.useState({kind:"idle"}),[N,w]=tt.useState(!1),[S,j]=tt.useState([]),k=tt.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);tt.useEffect(()=>{if(!k||typeof window>"u")return;const M=window.localStorage.getItem(k);if(!M)return;let Z=!1;try{const se=JSON.parse(M);if(!se?.tempWorktreePath||se.repoRoot!==t){window.localStorage.removeItem(k);return}(async()=>{const Q=await Ry(se.tempWorktreePath).catch(()=>!1);if(Z)return;if(!Q){window.localStorage.removeItem(k);return}const K=await Ty(se.tempWorktreePath).catch(()=>null);Z||K&&h({kind:"conflict",state:se,details:K})})()}catch{window.localStorage.removeItem(k)}return()=>{Z=!0}},[k,t]),tt.useEffect(()=>{if(!x){h({kind:"idle"});return}let M=!1;return h({kind:"loading"}),(async()=>{try{const Z=await ho({repoRoot:t,sourceBranch:e,targetBranch:y});if(M)return;if(h({kind:"ready",plan:Z}),Z.commits.length>0){const Q=Z.commits.slice(-50).reverse(),K=await Ip(t,Q);M||(j(K),w(!1))}else M||(j([]),w(!1))}catch{M||h({kind:"idle"})}})(),()=>{M=!0}},[x,t,e,y,a]);const v=tt.useCallback(M=>{d&&ut.getState().setWorktreeMetadata(d,{...n,createdFromBranch:M})},[d,n]),D=ut(M=>M.openNewSessionDraft),A=tt.useCallback(async M=>{const Z=await Fn("git.integrate.cherrypick.resolve.visible",{current_commit:M.state.currentCommit,target_branch:M.state.targetBranch}),se=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}),Q=`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:Z,instructionsText:se,payloadText:Q}},[]),C=li(M=>M.setPendingInputText),O=li(M=>M.setPendingSyntheticParts),T=tt.useCallback(async(M,Z)=>{const se=await A(M);if(Z){D({directoryOverride:M.state.tempWorktreePath,initialPrompt:se.visibleText,syntheticParts:[{text:se.instructionsText,synthetic:!0},{text:se.payloadText,synthetic:!0}]}),u("chat");return}if(!d){de.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}C(se.visibleText,"replace"),O([{text:se.instructionsText,synthetic:!0},{text:se.payloadText,synthetic:!0}]),u("chat")},[d,u,A,D,C,O,l]),E=tt.useCallback(async()=>{if(b.kind==="ready"){if(b.plan.commits.length===0){de.message(l("gitView.integrate.noCommitsToMoveToast"));return}h({kind:"running",plan:b.plan});try{const M=await Ey(b.plan);if(M.kind==="success"){de.success(l("gitView.integrate.commitsMovedToast"),{description:M.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:M.moved,branch:b.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:M.moved,branch:b.plan.targetBranch})});const Z=await ho(b.plan);h({kind:"ready",plan:Z}),c?.();return}M.kind==="conflict"&&(de.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 Z=M instanceof Error?M.message:String(M);de.error(l("gitView.integrate.failedToMoveToast"),{description:Z});const se=await ho({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(se?{kind:"ready",plan:se}:{kind:"idle"})}}},[b,c,t,e,y,k,l]),F=tt.useCallback(async()=>{if(b.kind==="conflict")try{await My(b.state),de.message(l("gitView.integrate.cherryPickAbortedToast")),k&&typeof window<"u"&&window.localStorage.removeItem(k)}finally{const M=await ho({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(M?{kind:"ready",plan:M}:{kind:"idle"})}},[b,t,e,y,k,l]),R=tt.useCallback(async()=>{if(b.kind==="conflict")try{const M=await Fy(b.state);if(M.kind==="success"){de.success(l("gitView.integrate.cherryPickFinishedToast"));const Z=await ho({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(Z?{kind:"ready",plan:Z}:{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 Z=M instanceof Error?M.message:String(M);de.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:Z})}},[b,t,e,y,c,k,l]);return!t||!e?null:s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[s.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(I,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.integrate.title")}),b.kind==="ready"&&b.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:b.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:b.kind==="loading"||b.kind==="running"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.integrate.moveCommits")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",y]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(nn,{open:m,onOpenChange:f,children:[s.jsx(tn,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"sm",className:"gap-1.5",children:[l("gitView.integrate.target"),s.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:y}),s.jsx(I,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(sn,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:s.jsxs(Oa,{className:"h-full min-h-0",children:[s.jsx(Ba,{ref:g,placeholder:l("gitView.branch.searchPlaceholder"),onKeyDown:M=>M.stopPropagation()}),s.jsxs(Va,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(_a,{children:l("gitView.branch.empty")}),s.jsx(ii,{heading:l("gitView.branch.localBranches"),children:r.map(M=>s.jsx(ai,{value:M,onSelect:()=>{p(M),v(M),f(!1)},children:M},M))})]})]})})]}),b.kind==="ready"?s.jsx($e,{size:"sm",onClick:()=>{E()},disabled:!x||b.plan.commits.length===0,children:l("gitView.integrate.move")}):b.kind==="loading"?s.jsx($e,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):b.kind==="running"?s.jsx($e,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),b.kind==="ready"&&b.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),b.kind==="ready"&&b.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:[" (",b.plan.commits.length,")"]})]}),S.length>0&&b.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>w(M=>!M),className:"typography-micro text-muted-foreground hover:text-foreground",children:l(N?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),s.jsxs("div",{className:"space-y-1",children:[(N?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")}),b.plan.commits.length>S.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:S.length})})]})]}),b.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:b.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:b.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.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)),b.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:b.details.unmergedFiles.length-6})})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx($e,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{F()},children:l("gitView.operation.abort")}),s.jsxs($e,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{T({state:b.state,details:b.details},!1)},children:[s.jsx(I,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs($e,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{T({state:b.state,details:b.details},!0)},children:[s.jsx(I,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.newSession")]}),s.jsx($e,{size:"sm",className:"typography-meta",onClick:()=>{R()},children:l("gitView.operation.continue")})]})]})]})]})},Oy=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=kt(),[d,u]=i.useState([]),[m,f]=i.useState(!1),[g,y]=i.useState(""),[p,x]=i.useState(""),[b,h]=i.useState(null),[N,w]=i.useState({}),S=i.useCallback(async()=>{if(n){f(!0);try{const C=await Pp(n);u(C.stashes),w({})}catch(C){de.error(C instanceof Error?C.message:l("gitView.stashes.toast.loadFailed"))}finally{f(!1)}}},[n,l]);i.useEffect(()=>{t&&S()},[S,t]),i.useEffect(()=>{if(!t||!n||d.length===0)return;let C=!1;const O=d.map(T=>T.ref);return Tp(n,O).then(T=>{C||w(T.counts)}).catch(()=>{}),()=>{C=!0}},[n,t,d]);const j=i.useMemo(()=>{const C=g.trim().toLowerCase();return C?d.filter(O=>`${O.ref} ${O.message} ${O.relativeTime}`.toLowerCase().includes(C)):d},[g,d]),k=i.useCallback(async C=>{await S(),await c?.(C)},[S,c]),v=async()=>{if(!(!n||b)){h("create");try{const C=await Rp(n,{message:p.trim()||void 0});C.created?(de.success(l("gitView.stashes.toast.created")),x("")):de.info(l("gitView.stashes.toast.noChanges")),await k({affectsIndex:!!(C.created&&o)})}catch(C){de.error(C instanceof Error?C.message:l("gitView.stashes.toast.createFailed"))}finally{h(null)}}},D=async(C,O)=>{if(!(!n||b)&&!(O==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:C.ref})))){h(`${O}:${C.ref}`);try{O==="apply"&&await Ep(n,{ref:C.ref}),O==="pop"&&await Mp(n,{ref:C.ref}),O==="drop"&&await Fp(n,{ref:C.ref});const T=O==="apply"?"gitView.stashes.toast.applySuccess":O==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";de.success(l(T)),await k({affectsIndex:O!=="drop"})}catch(T){const E=O==="apply"?"gitView.stashes.toast.applyFailed":O==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";de.error(T instanceof Error?T.message:l(E)),await k({affectsIndex:O!=="drop"})}finally{h(null)}}},A=b!==null;return s.jsx(Os,{open:t,onOpenChange:e,children:s.jsxs(Ls,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(Us,{children:[s.jsxs(_s,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(an,{children:l("gitView.stashes.description")})]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[s.jsx(vn,{value:p,onChange:C=>x(C.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:A||!r,className:"flex-1"}),s.jsxs($e,{onClick:v,disabled:!r||A||!n,children:[b==="create"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"inbox-archive",className:"size-4"}),l("gitView.stashes.actions.stashCurrentWithCount",{count:a})]})]}),s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:l("gitView.stashes.includeUntrackedHint")})]}),s.jsxs("div",{className:"relative mt-2",children:[s.jsx(I,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(vn,{value:g,onChange:C=>y(C.target.value),placeholder:l("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto",children:m?s.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:s.jsx(I,{name:"loader-4",className:"size-5 animate-spin"})}):j.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:l(g?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):j.map((C,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:C.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{children:O===0&&!g.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:O+1})})}),s.jsx(Mt,{sideOffset:6,children:C.ref})]})," · ",C.relativeTime," · ",typeof N[C.ref]=="number"?l("gitView.stashes.fileCount",{count:N[C.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(hl,{label:l("gitView.stashes.actions.apply"),loading:b===`apply:${C.ref}`,onClick:()=>D(C,"apply"),disabled:A,children:s.jsx(I,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(hl,{label:l("gitView.stashes.actions.pop"),loading:b===`pop:${C.ref}`,onClick:()=>D(C,"pop"),disabled:A,children:s.jsx(I,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(hl,{label:l("gitView.stashes.actions.drop"),loading:b===`drop:${C.ref}`,onClick:()=>D(C,"drop"),disabled:A,destructive:!0,children:s.jsx(I,{name:"delete-bin",className:"size-4"})})]})]},C.ref))})]})})},hl=t=>{const e=gt.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,u=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let m;e[0]!==u?(m=De("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",u),e[0]=u,e[1]=m):m=e[1];let f;e[2]!==l||e[3]!==r?(f=r?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):l,e[2]=l,e[3]=r,e[4]=f):f=e[4];let g;e[5]!==o||e[6]!==n||e[7]!==c||e[8]!==d||e[9]!==m||e[10]!==f?(g=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:m,onClick:c,disabled:o,children:f})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=m,e[10]=f,e[11]=g):g=e[11];let y;e[12]!==n?(y=s.jsx(Mt,{sideOffset:6,children:n}),e[12]=n,e[13]=y):y=e[13];let p;return e[14]!==g||e[15]!==y?(p=s.jsxs(Rt,{children:[g,y]}),e[14]=g,e[15]=y,e[16]=p):p=e[16],p},By=t=>{const e=gt.c(16),{onOpenStashes:n}=t,{t:r}=kt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(I,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e[0]=o):o=e[0];let a;e[1]!==r?(a=r("gitView.empty.cleanTitle"),e[1]=r,e[2]=a):a=e[2];let c;e[3]!==a?(c=s.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:a}),e[3]=a,e[4]=c):c=e[4];let l;e[5]!==r?(l=r("gitView.empty.cleanDescription"),e[5]=r,e[6]=l):l=e[6];let d;e[7]!==l?(d=s.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:l}),e[7]=l,e[8]=d):d=e[8];let u;e[9]!==n||e[10]!==r?(u=n?s.jsxs($e,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(I,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=u):u=e[11];let m;return e[12]!==c||e[13]!==d||e[14]!==u?(m=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,u]}),e[12]=c,e[13]=d,e[14]=u,e[15]=m):m=e[15],m},ei=8,Vy=t=>{const e=gt.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,u=Math.max(r,a+1)*ei+ei/2,m=i.useRef(null),f=i.useRef(null);let g;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==u?(g=()=>{const h=m.current,N=f.current;if(!h||!N)return;const w=h.offsetHeight;if(w===0)return;const S=window.devicePixelRatio||1;N.width=u*S,N.height=w*S;const j=N.getContext("2d");if(!j)return;j.scale(S,S),j.clearRect(0,0,u,w);const k=w/2,v=a*ei+ei/2,D=getComputedStyle(N),A=D.getPropertyValue("--surface-muted-foreground").trim()||D.color,C=E=>{if(!E.startsWith("var("))return E;const F=E.slice(4,-1).trim();return D.getPropertyValue(F).trim()||A},O=[...l].sort($y);for(const E of O){const F=E.fromLane*ei+ei/2,R=E.toLane*ei+ei/2,L=E.type==="passing"?.72:E.type==="branch-out"||E.type==="merge-in"?.95:1;j.beginPath(),j.strokeStyle=C(E.color),j.globalAlpha=L,j.lineWidth=1.25,j.lineCap="round";e:switch(E.type){case"passing":case"commit-lane":{j.moveTo(F,0),j.lineTo(F,w);break e}case"top-stub":{j.moveTo(F,0),j.lineTo(F,k);break e}case"bottom-stub":{j.moveTo(F,k),j.lineTo(F,w);break e}case"branch-out":{const B=(k+w)/2;j.moveTo(v,k),j.bezierCurveTo(v,B,R,B,R,w);break e}case"merge-in":{const B=k/2;j.moveTo(F,0),j.bezierCurveTo(F,B,v,B,v,k);break e}default:continue}j.stroke(),j.globalAlpha=1}const T=D.getPropertyValue("--background").trim()||D.getPropertyValue("--surface-background").trim();j.beginPath(),j.arc(v,k,4,0,Math.PI*2),j.fillStyle=C(c),j.fill(),j.beginPath(),j.arc(v,k,5,0,Math.PI*2),j.strokeStyle=T||A,j.lineWidth=2,j.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=u,e[4]=g):g=e[4];let y;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==u?(y=[n,a,c,l,r,o,u],e[5]=c,e[6]=l,e[7]=o,e[8]=a,e[9]=n,e[10]=r,e[11]=u,e[12]=y):y=e[12],i.useLayoutEffect(g,y);let p;e[13]!==u?(p={width:u,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=u,e[14]=p):p=e[14];let x;e[15]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx("canvas",{ref:f,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=x):x=e[15];let b;return e[16]!==p?(b=s.jsx("div",{ref:m,style:p,children:x}),e[16]=p,e[17]=b):b=e[17],b};function _y(t){return t==="branch-out"||t==="merge-in"}function $y(t,e){const n=_y;return(n(t.type)?1:0)-(n(e.type)?1:0)}const au=15e3,lu=500,cu=12,du=8*1024*1024,uu=t=>typeof t=="string"?0:(t.original?.length??0)+(t.modified?.length??0),fu=t=>{if(t.size<=cu){let o=0;for(const a of t.values())o+=uu(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>=cu)continue;const c=uu(a);r+c>du&&n.size>0||(n.set(o,a),r+=c)}return new Map(Array.from(n.entries()).reverse())};function mu(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:bc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function zy(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 Wy(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 Uy=i.memo(({entry:t,mode:e="history",laned:n,totalLanes:r,isExpanded:o,onToggle:a,files:c,isLoadingFiles:l,onCopyHash:d,directory:u,onConflict:m,onActionSuccess:f})=>{const{t:g}=kt(),y=Ee(K=>K.timeFormatPreference),p=e==="graph",[x,b]=i.useState(null),[h,N]=i.useState(!1),[w,S]=i.useState(""),[j,k]=i.useState(null),[v,D]=i.useState(new Set),[A,C]=i.useState(new Map),[O,T]=i.useState(new Set),E=async()=>{if(u){b("checkout");try{await Wp(u,t.hash),de.success(g("gitView.history.actions.detachedHead")),f?.()}catch(K){de.error(String(K.message))}finally{b(null)}}},F=async()=>{if(!(!u||!w.trim())){b("createBranch");try{await Op(u,w.trim(),t.hash),N(!1),S(""),f?.()}catch(K){de.error(String(K.message))}finally{b(null)}}},R=async()=>{if(u){b("cherryPick");try{const K=await zp(u,t.hash);K.conflict?m?.({conflict:!0,conflictFiles:K.conflictFiles,operation:"cherry-pick"}):f?.()}catch(K){de.error(String(K.message))}finally{b(null)}}},L=async()=>{if(u){b("revert");try{const K=await $p(u,t.hash);K.conflict?m?.({conflict:!0,conflictFiles:K.conflictFiles,operation:"revert"}):f?.()}catch(K){de.error(String(K.message))}finally{b(null)}}},B=async(K,ee=!1)=>{if(!(!u||x!==null)){b("reset");try{await Bp(u,t.hash,K,ee),f?.()}catch(re){de.error(String(re.message))}finally{b(null)}}},V=async()=>{if(!j)return;const K=j;switch(k(null),K){case"checkout":return E();case"cherryPick":return R();case"revert":return L();case"merge":return M();case"rebase":return Z();case"resetSoft":return B("soft");case"resetMixed":return B("mixed");case"resetHard":return B("hard",!0)}},M=async()=>{if(u){b("merge");try{const K=await _p(u,{branch:t.hash});K.conflict?m?.({conflict:!0,conflictFiles:K.conflictFiles,operation:"merge"}):f?.()}catch(K){de.error(String(K.message))}finally{b(null)}}},Z=async()=>{if(u){b("rebase");try{const K=await Vp(u,{onto:t.hash});K.conflict?m?.({conflict:!0,conflictFiles:K.conflictFiles,operation:"rebase"}):f?.()}catch(K){de.error(String(K.message))}finally{b(null)}}},se=i.useCallback(async K=>{const ee=K.path;if(!u){C(re=>new Map(re).set(ee,"error"));return}C(re=>fu(new Map(re).set(ee,"loading")));try{const re=Lp(u,t.hash,K.path,!1),he=new Promise((te,Ne)=>{setTimeout(()=>Ne(new Error(`Timed out after ${au}ms`)),au)}),je=await Promise.race([re,he]);C(te=>fu(new Map(te).set(ee,je)))}catch{C(re=>new Map(re).set(ee,"error"))}},[u,t.hash]),Q=i.useCallback(async K=>{const ee=K.path;if(K.changeType==="R"||K.isBinary){D(te=>{const Ne=new Set(te);return Ne.has(ee)?Ne.delete(ee):Ne.add(ee),Ne});return}const re=A.get(ee);if(v.has(ee)&&re&&re!=="error"){D(te=>{const Ne=new Set(te);return Ne.delete(ee),Ne});return}D(te=>{const Ne=new Set(te);return Ne.add(ee),Ne}),!(re&&re!=="error"||K.insertions+K.deletions>lu&&!O.has(ee))&&await se(K)},[A,O,se,v]);return s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:a,className:De("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",p?"hover:bg-[var(--interactive-hover)]/40":o?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[p&&n&&r!==void 0?s.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:s.jsx(Vy,{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:[p?(()=>{const K=Wy(t.refs);return K.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:K.map(ee=>s.jsx("span",{className:De("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",ee.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":ee.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:ee.label},ee.label))}):null})():null,s.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:t.message}),s.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[s.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[s.jsx("span",{className:"truncate min-w-[3ch]",title:t.author_name,children:t.author_name}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("span",{className:"truncate min-w-0",title:mu(t.date,y),children:mu(t.date,y)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:K=>{K.stopPropagation(),d(t.hash)},children:s.jsx(I,{name:"file-copy",className:"size-3"})})}),s.jsx(Mt,{sideOffset:8,children:g("gitView.history.copySha")})]})]})]})]}),o&&s.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[p&&j?s.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:g(`gitView.history.actions.${j}Confirm`)}),s.jsxs($e,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:x!==null,onClick:K=>{K.stopPropagation(),V()},children:[x!==null?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.confirmButton")]}),s.jsx($e,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:x!==null,onClick:K=>{K.stopPropagation(),k(null)},children:g("gitView.history.actions.cancelButton")})]}):p?s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:K=>{K.stopPropagation(),k("checkout")},children:g("gitView.history.actions.checkout")}),h?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("input",{autoFocus:!0,value:w,onChange:K=>S(K.target.value),onKeyDown:K=>{K.key==="Enter"&&F(),K.key==="Escape"&&(N(!1),S(""))},placeholder:g("gitView.history.actions.createBranchPlaceholder"),className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),s.jsxs($e,{variant:"outline",size:"xs",className:"h-6",disabled:!w.trim()||x!==null,onClick:K=>{K.stopPropagation(),F()},children:[x==="createBranch"?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.createBranchConfirm")]})]}):s.jsx($e,{variant:"outline",size:"xs",className:"h-6",onClick:K=>{K.stopPropagation(),N(!0)},children:g("gitView.history.actions.createBranch")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:K=>{K.stopPropagation(),k("cherryPick")},children:g("gitView.history.actions.cherryPick")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:K=>{K.stopPropagation(),k("revert")},children:g("gitView.history.actions.revert")}),s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:K=>K.stopPropagation(),children:[x==="reset"?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.reset")]})}),s.jsx(sn,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(K=>s.jsx(bs,{disabled:x!==null,onSelect:ee=>{ee.stopPropagation(),k(`reset${K.charAt(0).toUpperCase()+K.slice(1)}`)},children:g(`gitView.history.actions.reset${K.charAt(0).toUpperCase()+K.slice(1)}`)},K))})]}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:K=>{K.stopPropagation(),k("merge")},children:g("gitView.history.actions.merge")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:K=>{K.stopPropagation(),k("rebase")},children:g("gitView.history.actions.rebase")})]}):null,l?s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:g("gitView.history.loadingFiles")})]}):c.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:g("gitView.history.noFiles")}):s.jsx("ul",{className:"space-y-0.5 py-2",children:c.map(K=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>Q(K),className:De("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",v.has(K.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:De("font-semibold w-3 text-center shrink-0",zy(K.changeType)),children:K.changeType}),s.jsx("span",{className:"truncate text-foreground min-w-0",title:K.path,children:K.path}),!K.isBinary&&s.jsxs("span",{className:"shrink-0",children:[s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",K.insertions]}),s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",K.deletions]})]}),K.isBinary&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:g("gitView.history.binary")}),s.jsx(I,{name:v.has(K.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),v.has(K.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:K.changeType==="R"?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.renamedNoDiff")}):K.isBinary?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.binaryNoDiff")}):(()=>{const ee=K.insertions+K.deletions;if(!O.has(K.path)&&ee>lu)return s.jsxs("div",{className:"flex flex-col items-start gap-1 px-3 py-2 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:g("gitView.history.largeDiffTitle",{count:ee})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:g("gitView.history.largeDiffDescription")}),s.jsx($e,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{T(he=>new Set(he).add(K.path)),se(K)},children:g("gitView.history.renderDiffAnyway")})]});const re=A.get(K.path);return re==="loading"||re===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.loadingDiff")}):re==="error"?s.jsx("button",{type:"button",onClick:()=>Q(K),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:g("gitView.history.diffError")}):s.jsx(dm,{original:re.original,modified:re.modified,language:Di(K.path)||"",fileName:K.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},K.path))})]})]})}),hu=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)","var(--syntax-keyword)","var(--syntax-string)","var(--status-info)"];function qo(t){return hu[t%hu.length]}function Hy(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let y=0;y<e.length;y++)e[y]===o.hash&&a.push(y);let c=a.length>0?a[0]:-1;if(c===-1){const y=e.indexOf(null);y!==-1?c=y:(c=e.length,e.push(null))}const l=a.slice(1),d=qo(c),u=e[c]===o.hash,m=o.parents.length>0;m?e[c]=o.parents[0]:e[c]=null;const f=[];for(let y=1;y<o.parents.length;y++){const p=o.parents[y],x=e.indexOf(p);if(x!==-1)f.push(x);else{const b=e.indexOf(null),h=b!==-1?b:e.length;e[h]=p,h===e.length&&e.push(p),f.push(h)}}const g=[];u&&m?g.push({fromLane:c,toLane:c,color:d,type:"commit-lane"}):u&&!m?g.push({fromLane:c,toLane:c,color:d,type:"top-stub"}):!u&&m&&g.push({fromLane:c,toLane:c,color:d,type:"bottom-stub"});for(const y of l)g.push({fromLane:y,toLane:c,color:qo(y),type:"merge-in"}),e[y]=null;for(const y of f)g.push({fromLane:c,toLane:y,color:qo(y),type:"branch-out"});for(let y=0;y<e.length;y++)e[y]!==null&&y!==c&&(f.includes(y)||g.push({fromLane:y,toLane:y,color:qo(y),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:g})}return n}const Gy=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],Ky=t=>{const e=gt.c(84),{mode:n,log:r,isLogLoading:o,logMaxCount:a,onLogMaxCountChange:c,expandedCommitHashes:l,onToggleCommit:d,commitFilesMap:u,loadingCommitHashes:m,onCopyHash:f,directory:g,showHeader:y,contentMaxHeightClassName:p,branchDivider:x,onConflict:b,onActionSuccess:h}=t,N=n===void 0?"history":n,w=y===void 0?!0:y,S=p===void 0?"max-h-[50vh]":p,j=x===void 0?null:x,{t:k}=kt(),[v,D]=i.useState(!0),A=N==="graph";let C;e[0]!==A||e[1]!==r?(C=A&&r?Hy(r.all):[],e[0]=A,e[1]=r,e[2]=C):C=e[2];const O=C;let T;e[3]!==O?(T=Math.max(1,...O.map(qy)),e[3]=O,e[4]=T):T=e[4];const E=T;let F;e[5]!==O?(F=new Map(O.map(Yy)),e[5]=O,e[6]=F):F=e[6];const R=F;if(!r)return null;const L=j!==null&&j.insertBeforeIndex>0&&j.insertBeforeIndex<r.all.length,B=j!==null&&j.insertBeforeIndex===r.all.length,V=L||B;let M;e[7]!==j||e[8]!==L||e[9]!==B||e[10]!==r.all?(M=L?r.all.slice(0,j.insertBeforeIndex):B?r.all:[],e[7]=j,e[8]=L,e[9]=B,e[10]=r.all,e[11]=M):M=e[11];const Z=M;let se;if(e[12]!==j||e[13]!==u||e[14]!==S||e[15]!==g||e[16]!==l||e[17]!==L||e[18]!==V||e[19]!==A||e[20]!==o||e[21]!==R||e[22]!==m||e[23]!==r.all||e[24]!==a||e[25]!==E||e[26]!==N||e[27]!==h||e[28]!==b||e[29]!==f||e[30]!==c||e[31]!==d||e[32]!==k||e[33]!==Z){const H=L?r.all.slice(j.insertBeforeIndex):[];let q;e[35]!==j?.direction?(q=j?.direction==="down"?s.jsx(I,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(I,{name:"arrow-up",className:"size-3.5"}),e[35]=j?.direction,e[36]=q):q=e[36];const ae=q;let le;e[37]!==u||e[38]!==g||e[39]!==l||e[40]!==A||e[41]!==R||e[42]!==m||e[43]!==E||e[44]!==N||e[45]!==h||e[46]!==b||e[47]!==f||e[48]!==d?(le=Oe=>s.jsx("ul",{className:"divide-y divide-border/60",children:Oe.map(Me=>s.jsx(Uy,{entry:Me,mode:N,laned:A?R.get(Me.hash):void 0,totalLanes:A?E:void 0,isExpanded:l.has(Me.hash),onToggle:()=>d(Me.hash),files:u.get(Me.hash)??[],isLoadingFiles:m.has(Me.hash),onCopyHash:f,directory:g,onConflict:b,onActionSuccess:h},Me.hash))}),e[37]=u,e[38]=g,e[39]=l,e[40]=A,e[41]=R,e[42]=m,e[43]=E,e[44]=N,e[45]=h,e[46]=b,e[47]=f,e[48]=d,e[49]=le):le=e[49];const Se=le;let Re;e[50]!==o||e[51]!==r.all.length||e[52]!==a||e[53]!==c||e[54]!==k?(Re=r.all.length>=a?s.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:s.jsx($e,{type:"button",variant:"ghost",size:"xs",onClick:()=>c(a+25),disabled:o,className:"px-3 text-muted-foreground hover:text-foreground",children:o?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(I,{name:"loader-4",className:"size-3 animate-spin"}),k("gitView.history.loadingMore")]}):k("gitView.history.loadMore")})}):null,e[50]=o,e[51]=r.all.length,e[52]=a,e[53]=c,e[54]=k,e[55]=Re):Re=e[55];const _e=Re;se=s.jsx(Wn,{outerClassName:`min-h-0 ${S}`,className:"h-full w-full",children:r.all.length===0?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:k("gitView.history.noCommits")})}):V&&j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col gap-0",children:[Z.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:Se(Z)}):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:j.branchName,children:j.branchName}),ae]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),H.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:Se(H)}):null]}),_e]}):s.jsxs(s.Fragment,{children:[Se(r.all),_e]})}),e[12]=j,e[13]=u,e[14]=S,e[15]=g,e[16]=l,e[17]=L,e[18]=V,e[19]=A,e[20]=o,e[21]=R,e[22]=m,e[23]=r.all,e[24]=a,e[25]=E,e[26]=N,e[27]=h,e[28]=b,e[29]=f,e[30]=c,e[31]=d,e[32]=k,e[33]=Z,e[34]=se}else se=e[34];const Q=se;if(!w){if(V){let q;return e[56]!==Q?(q=s.jsx("section",{className:"h-full min-h-0",children:Q}),e[56]=Q,e[57]=q):q=e[57],q}let H;return e[58]!==Q?(H=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:Q}),e[58]=Q,e[59]=H):H=e[59],H}let K;e[60]!==k?(K=k("gitView.history.title"),e[60]=k,e[61]=K):K=e[61];let ee;e[62]!==K?(ee=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:K}),e[62]=K,e[63]=ee):ee=e[63];let re;e[64]!==o||e[65]!==v||e[66]!==a||e[67]!==c||e[68]!==k?(re=v&&s.jsx("div",{onClick:Qy,onPointerDown:Jy,children:s.jsxs(Un,{value:String(a),onValueChange:H=>c(Number(H)),disabled:o,children:[s.jsx(Hn,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:o,children:s.jsx(Cn,{placeholder:k("gitView.history.commitsPlaceholder")})}),s.jsx(Gn,{children:Gy.map(H=>s.jsx(Ts,{value:String(H.value),children:k(H.labelKey)},H.value))})]})}),e[64]=o,e[65]=v,e[66]=a,e[67]=c,e[68]=k,e[69]=re):re=e[69];let he;e[70]!==v?(he=v?s.jsx(I,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=v,e[71]=he):he=e[71];let je;e[72]!==re||e[73]!==he?(je=s.jsxs("div",{className:"flex items-center gap-2",children:[re,he]}),e[72]=re,e[73]=he,e[74]=je):je=e[74];let te;e[75]!==ee||e[76]!==je?(te=s.jsxs(Bo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[ee,je]}),e[75]=ee,e[76]=je,e[77]=te):te=e[77];let Ne;e[78]!==Q?(Ne=s.jsx(so,{children:Q}),e[78]=Q,e[79]=Ne):Ne=e[79];let J;return e[80]!==v||e[81]!==te||e[82]!==Ne?(J=s.jsxs(to,{open:v,onOpenChange:D,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[te,Ne]}),e[80]=v,e[81]=te,e[82]=Ne,e[83]=J):J=e[83],J};function qy(t){return t.lane+1}function Yy(t){return[t.commit.hash,t]}function Qy(t){return t.stopPropagation()}function Jy(t){return t.stopPropagation()}const Am=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},Xy=9e4,Zy=15e3,ew=5*6e4,tw=[2e3,5e3],sw=6e4,nw=2*6e4,rw=5*6e4,iw=4,ow=720*6e4,aw="openchamber.github-pr-status",lw=t=>t==="closed"||t==="merged",cw=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},No=(t,e,n)=>`${t}::${e}`,Yo=new Map,Qo=new Map,po=new Set,pu=new Map,bo=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null}),Ia=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,Ec=t=>{const e=Ia(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},Dm=(t,e)=>Object.entries(t).filter(([,n])=>Ec(n)===e).map(([n])=>n),dw=(t,e)=>{const n=e.remoteName??t.params?.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null;return{...t,params:t.params?{...t.params,...e,remoteName:n}:{...e,remoteName:n},identity:{directory:e.directory,branch:e.branch,remoteName:n}}},Jo=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},uw=(t,e,n)=>{const r=Dm(t,e),o=r.map(d=>Jo(t[d])).filter(d=>!!d);if(o.length===0)return null;const a=Jo(t[n]);if(a&&Ec(t[n])===e)return a;const c=r.map(d=>t[d]).find(d=>!!(d?.resolvedRemoteName&&Jo(d)));if(c)return Jo(c);const l=o.find(d=>!!d.remoteName);return l||(o[0]??null)},fw=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:Ia(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),mw=t=>({...bo(),status:t?.status??null,isInitialStatusResolved:t?.isInitialStatusResolved??!1,lastRefreshAt:t?.lastRefreshAt??0,lastDiscoveryPollAt:t?.lastDiscoveryPollAt??0,identity:t?.identity??null,resolvedRemoteName:t?.resolvedRemoteName??t?.status?.resolvedRemoteName??null}),or=io()(ic((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,ensureEntry:n=>{t(r=>r.entries[n]?r:{entries:{...r.entries,[n]:bo()}})},setParams:(n,r)=>{t(o=>{const a=o.entries[n]??bo();return{entries:{...o.entries,[n]:dw(a,r)}}})},startWatching:n=>{if(t(a=>{const c=a.entries[n]??bo();return{entries:{...a.entries,[n]:{...c,watchers:c.watchers+1}}}}),Yo.has(n))return;const r=a=>{const c=window.setTimeout(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const d=e().entries[n];!d||d.watchers<=0||d.status?.pr||e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0})},a),l=Qo.get(n)??[];l.push(c),Qo.set(n,l)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),tw.forEach(a=>r(a));const o=window.setInterval(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const a=e().entries[n];if(!a||a.watchers<=0)return;if(!!!a.status?.pr){const u=Date.now();if(u-a.lastDiscoveryPollAt<ew)return;t(m=>{const f=m.entries[n];return f?{entries:{...m.entries,[n]:{...f,lastDiscoveryPollAt:u}}}:m}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(lw(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=cw(a.status)?sw:a.status?.checks&&a.status.checks.state!=="pending"?rw:nw;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},Zy);Yo.set(n,o)},stopWatching:n=>{t(c=>{const l=c.entries[n];if(!l)return c;const d=Math.max(0,l.watchers-1);return{entries:{...c.entries,[n]:{...l,watchers:d}}}});const r=e().entries[n];if(r&&r.watchers>0)return;const o=Yo.get(n);typeof o=="number"&&window.clearInterval(o),Yo.delete(n);const a=Qo.get(n);a&&a.length>0&&a.forEach(c=>{window.clearTimeout(c)}),Qo.delete(n)},refresh:async(n,r)=>{const o=e(),a=o.entries[n],c=Ec(a);if(!a||!c)return;const l=Dm(o.entries,c),d=l.some(f=>!!o.entries[f]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const u=pu.get(c)??0;if(!r?.force&&Date.now()-u<Xy||po.has(c))return;const m=uw(o.entries,c,n);if(m){if(po.add(c),pu.set(c,Date.now()),t(f=>{const g={...f.entries};return l.forEach(y=>{const p=g[y];p&&(g[y]={...p,lastRefreshAt:Date.now(),isLoading:r?.silent?p.isLoading:!0,error:null})}),{entries:g}}),m.githubAuthChecked&&m.githubConnected===!1){t(f=>{const g={...f.entries};return l.forEach(y=>{const p=g[y];p&&(g[y]={...p,status:{connected:!1},error:null,isLoading:r?.silent?p.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?p.isInitialStatusResolved:!0})}),{entries:g}}),po.delete(c);return}if(!m.github?.prStatus){t(f=>{const g={...f.entries};return l.forEach(y=>{const p=g[y];p&&(g[y]={...p,status:null,error:"GitHub runtime API unavailable",isLoading:r?.silent?p.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?p.isInitialStatusResolved:!0})}),{entries:g}}),po.delete(c);return}try{t(g=>({...g,activeRequestCount:g.activeRequestCount+1,totalRequestCount:g.totalRequestCount+1}));const f=await m.github.prStatus(m.directory,m.branch,m.remoteName??void 0,{force:r?.force});t(g=>{const y={...g.entries};return l.forEach(p=>{const x=y[p];if(!x)return;const b=x.status?.pr,h=f.pr,w=!!(h&&b&&h.number===b.number&&(!h.body||!h.body.trim())&&typeof b.body=="string"&&b.body.trim().length>0)&&h&&b?.body?{...f,pr:{...h,body:b.body}}:f,S=w.resolvedRemoteName??x.resolvedRemoteName??m.remoteName??null,j=Ia(x)??{directory:m.directory,branch:m.branch,remoteName:m.remoteName??null};y[p]={...x,status:w,error:null,isLoading:r?.silent?x.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?x.isInitialStatusResolved:!0,resolvedRemoteName:S,identity:{...j,remoteName:S??j.remoteName??null}}}),{entries:y}})}catch(f){const g=f instanceof Error?f.message:String(f);t(y=>{const p={...y.entries};return l.forEach(x=>{const b=p[x];b&&(p[x]={...b,error:g||"Failed to load PR status",isLoading:r?.silent?b.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?b.isInitialStatusResolved:!0})}),{entries:p}})}finally{po.delete(c),t(f=>({...f,activeRequestCount:Math.max(0,f.activeRequestCount-1)}))}}},refreshTargets:async(n,r)=>{const o=Array.from(new Set(n.map(a=>{const c=a.directory.trim(),l=a.branch.trim();return!c||!l?null:No(c,l,a.remoteName??null)}).filter(a=>!!a)));await Am(o,iw,a=>e().refresh(a,r))},updateStatus:(n,r)=>{t(o=>{const a=o.entries[n]??bo();return{entries:{...o.entries,[n]:{...a,status:r(a.status)}}}})}}),{name:aw,storage:Nf(()=>ki()),partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=Ia(e);if(!n?.directory||!n.branch)return!1;const r=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return r===0||Date.now()-r<ow}).map(([e,n])=>[e,fw(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).map(([o,a])=>[o,mw(a)]))}}})),hw=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"},pw=t=>{const e=hw(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}},gw=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 pl=new Map,gu=new Map;const xw=t=>{const e=gt.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=pw(l);if(!d)continue;const u=gw(d);o.set(c,u),a.set(c,d)}if(o.size===pl.size){let c=!0;for(const[l,d]of o)if(pl.get(l)!==d){c=!1;break}if(c)return gu}return pl=o,gu=a,a},e[0]=t,e[1]=n):n=e[1],or(n)},bw=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"}},yw=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"},ww=[2e3,5e3],xu=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),ti=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):""},vw=(t,e)=>{const n=ti(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},jw=(t,e)=>`${t}::${e}`,Mc=t=>{const e=String(t||"").trim();if(!e)return"";const n=e.indexOf("/");return n<=0?"":e.slice(0,n).trim()},gl=(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=Mc(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)},Sw=t=>t.startsWith("pr-"),Nw=(t,e)=>{const n=Mc(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=>!Sw(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},xl=new Map,bl=Pi;function kw(t,e){const[n,r]=i.useState(null),[o,a]=i.useState([]),c=i.useRef(null);return i.useEffect(()=>{r(null),a([])},[t]),i.useEffect(()=>{if(!t||!e?.repoUpstream||c.current===t)return;c.current=t;let l=!1;return(async()=>{try{const d=await e.repoUpstream(t);if(l||!d?.isFork||!d.upstream||(r(d.upstream),!e.repoBranches))return;try{const u=await e.repoBranches(d.upstream.owner,d.upstream.repo);l||a(u)}catch{}}catch{}})(),()=>{l=!0}},[t,e]),{detectedUpstream:n,upstreamBranches:o}}const Cw=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=kt(),d=Ee(we=>we.timeFormatPreference),{github:u}=er(),m=Ti(we=>we.status),f=Ti(we=>we.hasChecked),g=Ee(we=>we.setSettingsDialogOpen),y=Ee(we=>we.setSettingsPage),p=Ee(we=>we.setActiveMainTab),x=ut(we=>we.currentSessionId),{isMobile:b,hasTouchInput:h}=Er(),N=i.useCallback(()=>{y("github"),g(!0)},[g,y]),w=i.useMemo(()=>jw(t,e),[t,e]),S=i.useMemo(()=>xl.get(w)??null,[w]),j=or(we=>we.ensureEntry),k=or(we=>we.setParams),v=or(we=>we.startWatching),D=or(we=>we.stopWatching),A=or(we=>we.refresh),C=or(we=>we.updateStatus),[O,T]=i.useState(()=>S?.title??xu(e)),[E,F]=i.useState(()=>S?.body??""),[R,L]=i.useState(()=>S?.draft??!1),[B,V]=i.useState(()=>S?.additionalContext??""),[M,Z]=i.useState(()=>{const we=typeof S?.targetBaseBranch=="string"?ti(S.targetBaseBranch):"";return we||ti(n)}),[se,Q]=i.useState("squash"),[K,ee]=i.useState(!1),[re,he]=i.useState(!1),[je,te]=i.useState(!1),[Ne,J]=i.useState(!1),[H,q]=i.useState(!1),[ae,le]=i.useState(!1),[Se,Re]=i.useState(null),[_e,Oe]=i.useState(""),[Me,ge]=i.useState(""),[Ae,pe]=i.useState(!1),[ue,G]=i.useState(!1),[fe,ce]=i.useState(()=>gl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r})),[W,z]=i.useState(!1),{detectedUpstream:be,upstreamBranches:xe}=kw(t,u);i.useEffect(()=>{z(!1)},[t]);const _=o.some(we=>we.name==="upstream"),$=!!(t&&e&&n&&(e!==n||(_||be!==null))),Ie=i.useMemo(()=>No(t,e),[t,e]),ve=or(we=>we.entries[Ie]),Fe=ve?.isLoading??!1,Ce=ve?.status??null,ne=ve?.error??null,P=ve?.isInitialStatusResolved??!1,me=i.useMemo(()=>{const we=W?null:fe?.name?.trim()||null,Je=new Set;for(const zt of a){const mt=vw(zt,we);!mt||mt==="HEAD"||Je.add(mt)}if(W)for(const zt of xe)zt&&zt!=="HEAD"&&Je.add(zt);const vt=ti(n);vt&&vt!=="HEAD"&&Je.add(vt);const Ct=ti(M);return Ct&&Ct!=="HEAD"&&Je.add(Ct),Array.from(Je).sort((zt,mt)=>zt.localeCompare(mt))},[n,a,fe?.name,M,xe,W]);i.useEffect(()=>{if(o.length===0){fe&&ce(null);return}(!fe||!o.some(we=>we.name===fe.name))&&ce(gl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r}))},[S?.selectedRemoteName,o,fe,r]),i.useEffect(()=>{const we=ti(n);if(!M&&we){Z(we);return}if(me.length!==0&&!me.includes(M)){const Je=me.includes(we)?we:me[0];Je&&Z(Je)}},[me,n,M]);const[oe,Be]=i.useState(!1),[Ue,Ke]=i.useState(null),[Qe,rt]=i.useState(!1),[pt,jt]=i.useState(new Set),[Ve,Ze]=i.useState(!1),[nt,St]=i.useState(null),[Dt,wt]=i.useState(!1),ot=i.useRef(new Set),at=i.useRef(null),Kt=i.useRef(!1),is=i.useRef(new Set),$t=i.useRef([]);i.useEffect(()=>{be&&!_&&z(!0)},[be,_]),i.useEffect(()=>{W&&be?.defaultBranch&&Z(be.defaultBranch)},[W,be?.defaultBranch]);const Le=Ce?.pr??null,et=Le?`${t}#${Le.number}`:null,Vt=!!(et&&Se===et);i.useEffect(()=>{if(!u?.prContext||!Le||typeof Le.body=="string"&&Le.body.length>0)return;const we=`${t}#${Le.number}`;if(ot.current.has(we))return;ot.current.add(we),Re(we);let Je=!1;return u.prContext(t,Le.number,{includeDiff:!1,includeCheckDetails:!1}).then(vt=>{if(Je)return;const Ct=vt?.pr;Ct&&C(Ie,zt=>!zt?.pr||zt.pr.number!==Le.number?zt:{...zt,pr:{...zt.pr,body:Ct.body||""}})}).catch(()=>{}).finally(()=>{Je||Re(vt=>vt===we?null:vt)}),()=>{Je=!0}},[t,u,Le,Ie,C]),i.useEffect(()=>{if(!Le){le(!1),Oe(""),ge(""),at.current=null;return}const we=at.current!==null&&at.current!==Le.number;we&&le(!1),(!ae||we)&&(Oe(Le.title||""),ge(Le.body||"")),at.current=Le.number},[ae,Le]);const xt=i.useCallback(async()=>{if(!u?.prContext){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Le){Be(!0),jt(new Set),rt(!0);try{const we=await u.prContext(t,Le.number,{includeDiff:!1,includeCheckDetails:!0});Ke(we)}catch(we){const Je=we instanceof Error?we.message:String(we);de.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:Je})}finally{rt(!1)}}},[t,u,Le,l]),Ft=i.useCallback(async()=>{if(!u?.prContext){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Le){Ze(!0),wt(!0);try{const we=await u.prContext(t,Le.number,{includeDiff:!1,includeCheckDetails:!1});St(we)}catch(we){const Je=we instanceof Error?we.message:String(we);de.error(l("gitView.pr.toast.loadCommentsFailed"),{description:Je})}finally{wt(!1)}}},[t,u,Le,l]),Gt=i.useCallback(we=>{if(!we)return"";const Je=Date.parse(we);return Number.isFinite(Je)?bc(Je,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):we},[d]),Ut=i.useMemo(()=>{const we=m?.user?.login;return typeof we=="string"?we.trim():""},[m]),qt=i.useMemo(()=>"[&_a[href*='oc-self-mention=1']]:!text-[var(--primary-base)] [&_a[href*='oc-self-mention=1']]:font-semibold [&_a[href*='oc-self-mention=1']]:!no-underline [&_a[href*='oc-self-mention=1']:hover]:!text-[var(--primary-hover)]",[]),Xt=i.useCallback(we=>{const Je=Ut.toLowerCase(),vt=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return we.replace(vt,(Ct,zt,mt)=>{const cs=`@${mt}`,fs=mt.toLowerCase();return`${zt}[${cs}](https://github.com/${fs}${Je&&fs===Je?"?oc-self-mention=1":""})`})},[Ut]),Lt=i.useMemo(()=>{const we=(nt?.issueComments??[]).map(Ct=>({id:`issue-${Ct.id}`,body:Ct.body||"",authorName:Ct.author?.name||Ct.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:Ct.author?.login||null,avatarUrl:Ct.author?.avatarUrl||null,createdAt:Ct.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),Je=(nt?.reviewComments??[]).map(Ct=>({id:`review-${Ct.id}`,body:Ct.body||"",authorName:Ct.author?.name||Ct.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:Ct.author?.login||null,avatarUrl:Ct.author?.avatarUrl||null,createdAt:Ct.createdAt,context:l("gitView.pr.comments.reviewContext"),path:Ct.path||null,line:Ct.line??null})),vt=[...we,...Je];return vt.sort((Ct,zt)=>{const mt=Ct.createdAt?Date.parse(Ct.createdAt):0,cs=zt.createdAt?Date.parse(zt.createdAt):0,fs=Number.isFinite(mt)?mt:0,ks=Number.isFinite(cs)?cs:0;return fs-ks}),vt},[nt,l]),Bt=i.useCallback(()=>{if(!x)return de.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:we,currentModelId:Je,currentAgentName:vt,currentVariant:Ct}=ss.getState(),zt=xc.getState().lastUsedProvider,mt=we||zt?.providerID,cs=Je||zt?.modelID;return!mt||!cs?(de.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:x,providerID:mt,modelID:cs,currentAgentName:vt??null,currentVariant:Ct??null}},[x,l]),Yt=i.useCallback((we,Je,vt,Ct)=>{ut.getState().sendMessage(Je,we.providerID,we.modelID,we.currentAgentName??void 0,void 0,void 0,[{text:vt,synthetic:!0},{text:Ct,synthetic:!0}],we.currentVariant??void 0).catch(zt=>{const mt=zt instanceof Error?zt.message:String(zt);de.error(l("gitView.pr.toast.sendMessageFailed"),{description:mt})})},[l]),Jt=i.useCallback(we=>{const Je=we.status||"unknown",vt=we.conclusion??void 0,Ct=vt?`${Je} / ${vt}`:Je,zt=we.app?.name||we.app?.slug;return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground truncate",children:we.name}),s.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:zt?`${zt} · ${Ct}`:Ct})]}),we.detailsUrl?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:we.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),"Open"]})}):null]}),we.output?.title?s.jsx("div",{className:"typography-micro text-foreground",children:we.output.title}):null,we.output?.summary?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:we.output.summary}):null,we.output?.text?s.jsx("div",{className:"rounded border border-border/40 bg-transparent px-2 py-2 typography-micro text-muted-foreground whitespace-pre-wrap max-h-48 overflow-y-auto",children:we.output.text}):null,Array.isArray(we.annotations)&&we.annotations.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",we.annotations.length>20?` (showing 20/${we.annotations.length})`:""]}),s.jsx("div",{className:"space-y-1",children:we.annotations.slice(0,20).map((mt,cs)=>s.jsxs("div",{className:"rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)]/40 px-2 py-2",children:[s.jsxs("div",{className:"typography-micro text-[var(--status-error)]",children:[mt.title||mt.level||"Issue",mt.path?` · ${mt.path}`:"",typeof mt.startLine=="number"?`:${mt.startLine}`:"",typeof mt.endLine=="number"&&mt.endLine!==mt.startLine?`-${mt.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:mt.message}),mt.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:mt.rawDetails}):null]},`${mt.path||"file"}:${mt.startLine||cs}:${cs}`))})]}):null,we.job?.steps&&we.job.steps.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.checks.steps")}),s.jsx("div",{className:"space-y-1",children:we.job.steps.map((mt,cs)=>{const fs=(mt.conclusion||"").toLowerCase(),ks=fs&&!["success","neutral","skipped"].includes(fs),ms=`${we.id??"run"}:${we.job?.jobId??"job"}:${mt.number??cs}:${mt.name}`,Hs=pt.has(ms);return ks?s.jsxs(to,{open:Hs,children:[s.jsxs("button",{type:"button",onClick:()=>{jt(zs=>{const hn=new Set(zs);return hn.has(ms)?hn.delete(ms):hn.add(ms),hn})},className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-left "+(ks?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[Hs?s.jsx(I,{name:"arrow-down-s",className:"size-4"}):s.jsx(I,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:mt.name}),mt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:mt.conclusion}):null]}),s.jsx(so,{children:s.jsxs("div",{className:"ml-6 mt-1 rounded border border-border/40 bg-transparent px-2 py-2 typography-micro text-muted-foreground space-y-1",children:[typeof mt.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",mt.number]}):null,mt.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",mt.status]}):null,mt.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",mt.conclusion]}):null,mt.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",Gt(mt.startedAt)]}):null,mt.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",Gt(mt.completedAt)]}):null]})})]},ms):s.jsxs("div",{className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-muted-foreground",children:[s.jsx("span",{className:"truncate",children:mt.name}),mt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:mt.conclusion}):null]},ms)})})]}):null]})},[pt,Gt,l]),es=i.useCallback(async()=>{if(p("chat"),!u?.prContext){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Le)return;const we=Bt();if(we)try{const Je=await u.prContext(t,Le.number,{includeDiff:!1,includeCheckDetails:!0}),Ct=(Je.checkRuns??[]).filter(ks=>{const ms=typeof ks.conclusion=="string"?ks.conclusion.toLowerCase():"";return ms?!["success","neutral","skipped"].includes(ms):!1});if(Ct.length===0){de.message(l("gitView.pr.toast.noFailedChecks"));return}const zt=await Fn("github.pr.checks.review.visible"),mt=await Fn("github.pr.checks.review.instructions"),cs=Ct.flatMap(ks=>(Array.isArray(ks.annotations)?ks.annotations:[]).map(Hs=>({run:ks.name,level:Hs.level,title:Hs.title,path:Hs.path,startLine:Hs.startLine,endLine:Hs.endLine,message:Hs.message,rawDetails:Hs.rawDetails}))),fs=`GitHub PR failed checks (JSON)
7
- ${JSON.stringify({repo:Je.repo??null,pr:Je.pr??null,failedChecks:Ct,failedAnnotations:cs},null,2)}`;Yt(we,zt,mt,fs)}catch(Je){const vt=Je instanceof Error?Je.message:String(Je);de.error(l("gitView.pr.toast.loadChecksFailed"),{description:vt})}},[t,Yt,u,Le,Bt,p,l]),Zt=i.useCallback(async()=>{if(p("chat"),!u?.prContext){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Le)return;const we=Bt();if(we)try{const Je=await u.prContext(t,Le.number,{includeDiff:!1,includeCheckDetails:!1}),vt=Je.issueComments??[],Ct=Je.reviewComments??[];if(vt.length+Ct.length===0){de.message(l("gitView.pr.toast.noPrComments"));return}const mt=await Fn("github.pr.comments.review.visible"),cs=await Fn("github.pr.comments.review.instructions"),fs=`GitHub PR comments (JSON)
8
- ${JSON.stringify({repo:Je.repo??null,pr:Je.pr??null,issueComments:vt,reviewComments:Ct},null,2)}`;Yt(we,mt,cs,fs)}catch(Je){const vt=Je instanceof Error?Je.message:String(Je);de.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:vt})}},[t,Yt,u,Le,Bt,p,l]),vs=i.useCallback(async we=>{Ze(!1),p("chat");const Je=Bt();if(!Je)return;const vt=await Fn("github.pr.comment.single.visible"),Ct=await Fn("github.pr.comment.single.instructions"),zt=`GitHub PR comment (JSON)
9
- ${JSON.stringify({repo:nt?.repo??null,pr:nt?.pr??Le??null,comment:we},null,2)}`;Yt(Je,vt,Ct,zt)},[nt,Yt,Le,Bt,p]),bt=i.useCallback(async we=>{await A(Ie,we)},[Ie,A]),Ot=i.useCallback(()=>{$t.current.forEach(we=>{window.clearTimeout(we)}),$t.current=ww.map(we=>window.setTimeout(()=>{bt({force:!0,silent:!0,markInitialResolved:!0})},we))},[bt]);i.useEffect(()=>{if(!u?.prStatus||!$||o.length<=1||Kt.current||Ce?.pr)return;const we=`${w}::${fe?.name??""}`;if(is.current.has(we))return;is.current.add(we);const Je=Nw(o,r).filter(zt=>zt.name!==fe?.name);if(Je.length===0)return;let vt=!1;return(async()=>{for(const zt of Je){if(vt)return;try{if(!(await u.prStatus(t,e,zt.name))?.pr)continue;if(vt)return;ce(cs=>cs?.name===zt.name?cs:zt);return}catch{}}})(),()=>{vt=!0}},[e,$,t,u,o,fe?.name,w,Ce?.pr,r]),i.useEffect(()=>{j(Ie),k(Ie,{directory:t,branch:e,remoteName:fe?.name??null,canShow:$,github:u,githubAuthChecked:f,githubConnected:m?.connected??null})},[e,$,t,j,u,f,m?.connected,Ie,fe?.name,k]),i.useEffect(()=>(v(Ie),()=>{D(Ie)}),[Ie,v,D]),i.useEffect(()=>{const we=xl.get(w)??null;T(we?.title??xu(e)),F(we?.body??""),L(we?.draft??!1),Z(we?.targetBaseBranch?ti(we.targetBaseBranch):ti(n));const Je=gl(o,{selectedRemoteName:we?.selectedRemoteName,trackingBranch:r});ce(vt=>vt?.name===Je?.name?vt:Je)},[n,e,o,w,r]),i.useEffect(()=>{bt({markInitialResolved:!0})},[Ie,bt]),i.useEffect(()=>{!$||!fe?.name||bt({force:!0,silent:!0,markInitialResolved:!0})},[$,bt,fe?.name]),i.useEffect(()=>{const we=Ce?.resolvedRemoteName?.trim();if(!we||Kt.current)return;const Je=o.find(vt=>vt.name===we);Je&&ce(vt=>vt?.name===Je.name?vt:Je)},[o,Ce?.resolvedRemoteName]),i.useEffect(()=>{const we=Ce?.pr?.state==="closed"||Ce?.pr?.state==="merged",Je=ve?.lastRefreshAt??0,vt=Date.now()-Je>6e4,Ct=!we&&vt,zt=()=>{Ct&&bt({force:!0,silent:!0})},mt=()=>{document.visibilityState==="visible"&&Ct&&bt({force:!0,silent:!0})};return window.addEventListener("focus",zt),document.addEventListener("visibilitychange",mt),()=>{window.removeEventListener("focus",zt),document.removeEventListener("visibilitychange",mt)}},[bt,Ce?.pr?.state,ve?.lastRefreshAt]),i.useEffect(()=>{f&&m?.connected===!1&&bt({force:!0,silent:!0,markInitialResolved:!0})},[f,m,bt]),i.useEffect(()=>{!t||!e||xl.set(w,{title:O,body:E,draft:R,additionalContext:B,targetBaseBranch:M,selectedRemoteName:fe?.name})},[w,O,E,R,B,M,fe?.name,t,e]),i.useEffect(()=>{const we=$t.current;return()=>{we.forEach(Je=>{window.clearTimeout(Je)}),$t.current=[]}},[]);const It=i.useCallback(async()=>{if(!K&&t){ee(!0);try{const Je={base:W&&be?.defaultBranchSha?be.defaultBranchSha:M,head:e};B&&(Je.context=B);const vt=await Up(t,Je);vt.title?.trim()&&T(vt.title.trim()),vt.body?.trim()&&F(vt.body.trim()),c?.()}catch(we){const Je=we instanceof Error?we.message:String(we);de.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:Je})}finally{ee(!1)}}},[B,e,be?.defaultBranchSha,t,K,c,M,l,W]),us=i.useCallback(async()=>{if(!u?.prCreate){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}const we=O.trim();if(!we){de.error(l("gitView.pr.toast.titleRequired"));return}const Je=M.trim();if(!Je){de.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!W&&Je===e){de.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}he(!0);try{const vt=Mc(r),Ct=W&&be,zt=await u.prCreate({directory:t,title:we,head:e,base:Je,...E.trim()?{body:E}:{},draft:R,...Ct?{targetRepo:{owner:be.owner,repo:be.repo},headRemote:"origin"}:{...fe?{remote:fe.name}:{},...vt&&vt!==fe?.name?{headRemote:vt}:{}}});de.success(l("gitView.pr.toast.prCreated")),C(Ie,mt=>mt&&{...mt,pr:zt}),await bt({force:!0}),Ot()}catch(vt){const Ct=vt instanceof Error?vt.message:String(vt);de.error(l("gitView.pr.toast.createPrFailed"),{description:Ct})}finally{he(!1)}},[E,e,be,t,R,u,Ie,bt,Ot,fe,M,O,r,C,W,l]),He=i.useCallback(async we=>{if(!u?.prMerge){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}J(!0);try{const Je=await u.prMerge({directory:t,number:we.number,method:se});Je.merged?de.success(l("gitView.pr.toast.prMerged")):de.message(l("gitView.pr.toast.prNotMerged"),{description:Je.message||l("gitView.pr.notMergeable")}),await bt({force:!0}),Ot()}catch(Je){const vt=Je instanceof Error?Je.message:String(Je);de.error(l("gitView.pr.toast.mergeFailed"),{description:vt}),we.url&&bl(we.url)}finally{J(!1)}},[t,u,se,bt,Ot,l]),ft=i.useCallback(async we=>{if(!u?.prReady){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}q(!0);try{await u.prReady({directory:t,number:we.number}),de.success(l("gitView.pr.toast.markedReady")),await bt({force:!0}),Ot()}catch(Je){const vt=Je instanceof Error?Je.message:String(Je);de.error(l("gitView.pr.toast.markReadyFailed"),{description:vt}),we.url&&bl(we.url)}finally{q(!1)}},[t,u,bt,Ot,l]),Ye=i.useCallback(async we=>{if(!u?.prUpdate){de.error(l("gitView.pr.toast.githubApiUnavailable"));return}const Je=_e.trim();if(!Je){de.error(l("gitView.pr.toast.titleRequired"));return}te(!0);try{const vt=await u.prUpdate({directory:t,number:we.number,title:Je,body:Me});C(Ie,Ct=>Ct&&{...Ct,pr:{...Ct.pr??we,...vt}}),le(!1),de.success(l("gitView.pr.toast.prUpdated")),await bt({force:!0}),Ot()}catch(vt){const Ct=vt instanceof Error?vt.message:String(vt);de.error(l("gitView.pr.toast.updatePrFailed"),{description:Ct})}finally{te(!1)}},[t,Me,_e,u,Ie,bt,Ot,C,l]);if(!$)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 Pt=Ce?.repo?.url||null,Tt=W&&be?.url?be.url:Pt,Qt=Ce?.checks??null,Ss=!!Ce?.canMerge,ys=!!Ce?.connected,_t=f&&Ce?.connected===!1,Ns=yw(Ce),js=Ns?`var(--pr-${Ns})`:"var(--status-info)",Ds=Ns==="draft"?"git-pr-draft":Ns==="merged"?"git-merge":Ns==="closed"?"git-close-pull-request":"git-pull-request",mn=Le?[`${Le.state}${Le.draft?" (draft)":""}`,Le.mergeable===!1?l("gitView.pr.notMergeable"):null,Le.state==="open"&&typeof Le.mergeableState=="string"&&Le.mergeableState&&Le.mergeableState!=="unknown"?Le.mergeableState:null].filter(Boolean).join(" · "):"",Js=Qt?Qt.total>0?`${Qt.success}/${Qt.total} ${l("gitView.pr.checks.label")}`:`${Qt.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:[Le?s.jsxs(Rt,{children:[s.jsx(Et,{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:()=>{bl(Le.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(I,{name:Ds,className:"size-4 shrink-0",style:{color:js}})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(I,{name:Ds,className:"size-4 shrink-0",style:{color:"var(--surface-muted-foreground)"}}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.pullRequest.title")}),Le?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",Le.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Fe?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(Rt,{children:[s.jsx(Et,{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:Fe,onClick:()=>{bt({force:!0})},"aria-label":l("gitView.pr.actions.refreshAria"),children:s.jsx(I,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),Le?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:js},children:mn}),Qt?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${bw(Qt.state)}`}),Js]}):null,r&&fe&&r.split("/")[0]!==fe.name?s.jsxs("span",{className:"min-w-0 truncate",children:[r.split("/")[0]," → ",fe.name]}):null]}):null]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[_t?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.githubNotConnected")}),s.jsx($e,{variant:"outline",size:"sm",onClick:N,className:"w-fit",children:l("gitView.pr.actions.openSettings")})]}):null,ne?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:ne}),Tt?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:s.jsxs("a",{href:Tt,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!Le&&!P&&!ne&&!_t?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):Le?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:[ae?s.jsxs("div",{className:"space-y-2",children:[s.jsx(vn,{value:_e,onChange:we=>Oe(we.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h}),s.jsx(Ci,{value:Me,onChange:we=>ge(we.target.value),className:"min-h-[120px] bg-background/80",placeholder:l("gitView.pr.placeholder.description"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"typography-markdown text-xl font-semibold text-foreground break-words leading-snug",children:Le.title}),Le.body?.trim()?s.jsx(Po,{content:Le.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(Vt?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),Ss&&Le.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:[Le.state==="open"?ae?s.jsxs(s.Fragment,{children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{le(!1),Oe(Le.title||""),ge(Le.body||"")},disabled:je,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(I,{name:"close",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>Ye(Le),disabled:je||!_e.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:je?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"check",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>le(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(I,{name:"edit",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,Qt?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:xt,disabled:Qe,"aria-label":l("gitView.pr.actions.openChecksAria"),children:Qe?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"information",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,Qt?.failure?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:es,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(I,{name:"error-warning",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:Ft,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(I,{name:"chat-4",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Zt,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(I,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),Ss&&Le.draft&&Le.state==="open"?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>ft(Le),disabled:H||Ne||je||ae,"aria-label":l("gitView.pr.actions.markReadyAria"),children:H?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(Mt,{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(Un,{value:se,onValueChange:we=>Q(we),disabled:Ne||Le.state!=="open",children:[s.jsx(Hn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(Cn,{})}),s.jsxs(Gn,{children:[s.jsx(Ts,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(Ts,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(Ts,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>He(Le),disabled:Ne||H||Le.state!=="open"||Le.draft||je||ae,"aria-label":l("gitView.pr.actions.mergePrAria"),children:Ne?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-merge",className:"size-4"})})}),s.jsx(Mt,{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:["(",W&&be?"upstream":"remote",")"]})]})]}),Tt?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:Tt,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),l("gitView.pr.actions.repo")]})}):null]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.title")}),s.jsx(vn,{value:O,onChange:we=>T(we.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.baseBranch")}),me.length>0?s.jsxs(Un,{value:M,onValueChange:Z,children:[s.jsx(Hn,{className:"h-9",children:s.jsx(Cn,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(Gn,{children:me.map(we=>s.jsx(Ts,{value:we,children:we},we))})]}):s.jsx(vn,{value:M,onChange:we=>Z(we.target.value),placeholder:l("gitView.pr.placeholder.main")})]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.description")}),s.jsx(Ci,{value:E,onChange:we=>F(we.target.value),className:"min-h-[110px]",placeholder:l("gitView.pr.placeholder.whatChanged"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}),s.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":R,onClick:()=>L(we=>!we),onKeyDown:we=>{(we.key===" "||we.key==="Enter")&&(we.preventDefault(),L(Je=>!Je))},children:[s.jsx(Ri,{size:"sm",checked:R,onChange:we=>L(we),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),b?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx($e,{variant:"outline",size:"sm",onClick:()=>G(!0),children:B.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),B.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(to,{open:Ae,onOpenChange:pe,children:[s.jsxs(Bo,{className:"flex w-full items-center justify-between rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2 hover:bg-[var(--interactive-hover)]",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx("span",{className:"typography-micro text-[var(--primary-base)]",children:Ae?l("gitView.pr.actions.hide"):B.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(so,{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(Ci,{value:B,onChange:we=>V(we.target.value),className:"min-h-[100px] bg-transparent",placeholder:l("gitView.pr.placeholder.additionalContext")}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.hint")})]})})]}),s.jsx($a,{open:ue,onClose:()=>G(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx($e,{size:"sm",onClick:()=>G(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ci,{value:B,onChange:we=>V(we.target.value),className:"min-h-[200px] bg-transparent",placeholder:l("gitView.pr.placeholder.additionalContext"),autoFocus:!0}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.hint")})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs($e,{variant:"outline",size:"sm",onClick:It,disabled:K||re,children:[K?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"ai-generate-2",className:"size-4 text-primary"}),l("gitView.commit.generate")]}),s.jsx("div",{className:"flex-1"}),s.jsxs($e,{size:"sm",className:"min-w-[7.5rem] justify-center gap-2",onClick:us,disabled:re||!ys||!M.trim()||!W&&M.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:re?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx(Os,{open:oe,onOpenChange:Be,children:s.jsxs(Ls,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(Us,{children:[s.jsxs(_s,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(an,{children:Le?l("gitView.pr.numberLabel",{number:Le.number}):l("gitView.pullRequest.title")})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[Qe?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Qe?null:s.jsx("div",{className:"space-y-3",children:Array.isArray(Ue?.checkRuns)&&Ue?.checkRuns.length>0?Ue.checkRuns.map((we,Je)=>{const vt=`${we.id??"run"}:${we.job?.jobId??"job"}:${we.name}:${Je}`;return s.jsx("div",{className:"p-1",children:Jt(we)},vt)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx(Os,{open:Ve,onOpenChange:Ze,children:s.jsxs(Ls,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(Us,{children:s.jsxs(_s,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),Le?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:Le.number})}):null]})}),s.jsxs(za,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[Dt?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Dt?null:s.jsx("div",{className:"space-y-4",children:Lt.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Lt.map((we,Je)=>{const vt=(we.authorName||"?").charAt(0).toUpperCase(),Ct=Je===Lt.length-1;return s.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[Ct?null:s.jsx("div",{className:"absolute left-4 top-[2.375rem] bottom-[0.375rem] w-px bg-border/60"}),s.jsx("div",{className:"absolute left-0 top-0 z-10 flex size-8 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-surface-elevated text-xs text-muted-foreground",children:we.avatarUrl?s.jsx("img",{src:we.avatarUrl,alt:we.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:vt})}),s.jsxs("div",{className:"rounded-lg bg-surface-elevated px-3 pt-0 pb-3 space-y-2",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1 typography-micro text-muted-foreground sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-1 sm:gap-y-1",children:[s.jsxs("span",{className:"text-foreground whitespace-nowrap",children:[we.authorName,we.authorLogin&&we.authorLogin!==we.authorName?` · @${we.authorLogin}`:""]}),we.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:Gt(we.createdAt)}):null,s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsxs($e,{variant:"ghost",size:"sm",className:"h-6 px-0 has-[>svg]:px-0 sm:px-2 sm:has-[>svg]:px-2.5 text-[var(--status-success)] hover:bg-[var(--status-success-background)] hover:text-[var(--status-success)] justify-start",onClick:()=>{vs(we)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(I,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(Mt,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[we.context,we.path?` · ${we.path}`:"",we.line?`:${we.line}`:""]}),s.jsx(Po,{content:Xt(we.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",qt].filter(Boolean).join(" "),enableFileReferences:!1})]})]},we.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},Aw=t=>{const e=gt.c(150),{open:n,onOpenChange:r,conflictFiles:o,directory:a,operation:c,onAbort:l,onClearState:d}=t;let u;e[0]!==o?(u=o===void 0?[]:o,e[0]=o,e[1]=u):u=e[1];const m=u,{t:f}=kt(),g=ut(Dw),y=ut(Iw),p=li(Pw),x=li(Tw),b=Ee(Rw),[h,N]=i.useState(!1),[w,S]=i.useState(null),[j,k]=i.useState(null);let v,D;e[2]!==a||e[3]!==n||e[4]!==f?(v=()=>{!n||!a||(N(!0),k(null),S(null),Hp(a).then(W=>{S(W)}).catch(W=>{const z=W instanceof Error?W.message:f("gitView.conflict.loadFailed");k(z)}).finally(()=>{N(!1)}))},D=[n,a,f],e[2]=a,e[3]=n,e[4]=f,e[5]=v,e[6]=D):(v=e[5],D=e[6]),i.useEffect(v,D);let A;e[7]!==w||e[8]!==a||e[9]!==c?(A=async()=>{if(!w)return null;const W=c==="merge"?"merge":"rebase",z=w.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),be=c==="merge"?"git commit --no-edit":"git rebase --continue",xe=await Fn("git.conflict.resolve.visible",{operation_label:W,head_ref:z}),_=await Fn("git.conflict.resolve.instructions",{operation_label:W,directory:a,operation:c,head_info:w.headInfo||"N/A",continue_cmd:be}),ye=`${W} conflict context (JSON)
10
- ${JSON.stringify({directory:a,operation:w.operation,headInfo:w.headInfo,statusPorcelain:w.statusPorcelain,unmergedFiles:w.unmergedFiles,diff:w.diff},null,2)}`;return{visibleText:xe,instructionsText:_,payloadText:ye}},e[7]=w,e[8]=a,e[9]=c,e[10]=A):A=e[10];const C=A;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 T=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 F=E;let R;e[17]!==C||e[18]!==y||e[19]!==d||e[20]!==r||e[21]!==b||e[22]!==p||e[23]!==x||e[24]!==f?(R=async()=>{const W=await C();if(!W){de.error(f("gitView.conflict.noDetailsAvailable"));return}if(!y){de.error(f("gitView.conflict.noActiveSession"),{description:f("gitView.conflict.noActiveSessionDescription")});return}p(W.visibleText,"replace"),x([{text:W.instructionsText,synthetic:!0},{text:W.payloadText,synthetic:!0}]),b("chat"),d?.(),r(!1)},e[17]=C,e[18]=y,e[19]=d,e[20]=r,e[21]=b,e[22]=p,e[23]=x,e[24]=f,e[25]=R):R=e[25];const L=R;let B;e[26]!==C||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==g||e[31]!==b||e[32]!==f?(B=async()=>{const W=await C();if(!W){de.error(f("gitView.conflict.noDetailsAvailable"));return}g({directoryOverride:a,initialPrompt:W.visibleText,syntheticParts:[{text:W.instructionsText,synthetic:!0},{text:W.payloadText,synthetic:!0}]}),b("chat"),d?.(),r(!1)},e[26]=C,e[27]=a,e[28]=d,e[29]=r,e[30]=g,e[31]=b,e[32]=f,e[33]=B):B=e[33];const V=B;let M,Z,se,Q,K,ee,re,he,je,te,Ne,J,H,q,ae,le,Se,Re,_e,Oe,Me,ge;if(e[34]!==w||e[35]!==m||e[36]!==y||e[37]!==T||e[38]!==F||e[39]!==L||e[40]!==V||e[41]!==h||e[42]!==j||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==f){const W=f(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),z=w?.unmergedFiles||m;se=Os,Me=n,ge=r,Z=Ls,Oe="max-w-md w-[calc(100vw-2rem)]",q="flex flex-col gap-4 overflow-hidden";let be;e[69]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx(I,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=be):be=e[69];const xe=s.jsxs("div",{className:"flex items-center gap-2",children:[be,s.jsx(_s,{children:f("gitView.conflict.detectedTitle",{operation:W})})]});let _;e[70]!==c||e[71]!==f?(_=f("gitView.conflict.detectedDescription",{operation:c}),e[70]=c,e[71]=f,e[72]=_):_=e[72];let ye;e[73]!==_?(ye=s.jsx(an,{children:_}),e[73]=_,e[74]=ye):ye=e[74],e[75]!==xe||e[76]!==ye?(ae=s.jsxs(Us,{children:[xe,ye]}),e[75]=xe,e[76]=ye,e[77]=ae):ae=e[77],e[78]!==h||e[79]!==f?(le=h&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:f("gitView.conflict.loading")})]}),e[78]=h,e[79]=f,e[80]=le):le=e[80],e[81]!==j||e[82]!==f?(Se=j&&s.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:f("gitView.conflict.errorLoadingDetails",{message:j})}),e[81]=j,e[82]=f,e[83]=Se):Se=e[83],e[84]!==z||e[85]!==f?(Re=z.length>0&&s.jsxs("div",{className:"space-y-2 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:f("gitView.conflict.conflictedFiles")}),s.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:z.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:z.map(Ew)})})]}),e[84]=z,e[85]=f,e[86]=Re):Re=e[86],e[87]!==w||e[88]!==f?(_e=w?.headInfo&&s.jsxs("div",{className:"space-y-1 overflow-hidden",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:f("gitView.conflict.headInfo")}),s.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:w.headInfo})]}),e[87]=w,e[88]=f,e[89]=_e):_e=e[89],Ne="flex flex-col gap-2 pt-2";let $;e[90]!==V?($=()=>{V()},e[90]=V,e[91]=$):$=e[91];const Ie=h||!w;let ve;e[92]!==h?(ve=h?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"add",className:"size-4"}),e[92]=h,e[93]=ve):ve=e[93];let Fe;e[94]!==f?(Fe=f("gitView.conflict.resolveNewSession"),e[94]=f,e[95]=Fe):Fe=e[95],e[96]!==$||e[97]!==Ie||e[98]!==ve||e[99]!==Fe?(J=s.jsxs($e,{variant:"default",onClick:$,disabled:Ie,className:"w-full gap-2",children:[ve,Fe]}),e[96]=$,e[97]=Ie,e[98]=ve,e[99]=Fe,e[100]=J):J=e[100];let Ce;e[101]!==L?(Ce=()=>{L()},e[101]=L,e[102]=Ce):Ce=e[102];const ne=h||!w||!y;let P;e[103]!==h?(P=h?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"chat-1",className:"size-4"}),e[103]=h,e[104]=P):P=e[104];let me;e[105]!==f?(me=f("gitView.conflict.resolveCurrentSession"),e[105]=f,e[106]=me):me=e[106],e[107]!==Ce||e[108]!==ne||e[109]!==P||e[110]!==me?(H=s.jsxs($e,{variant:"outline",onClick:Ce,disabled:ne,className:"w-full gap-2",children:[P,me]}),e[107]=Ce,e[108]=ne,e[109]=P,e[110]=me,e[111]=H):H=e[111],je="flex gap-2 pt-1";let oe;e[112]!==f?(oe=f("gitView.conflict.continueLater"),e[112]=f,e[113]=oe):oe=e[113],e[114]!==F||e[115]!==oe?(te=s.jsx($e,{variant:"ghost",size:"sm",onClick:F,className:"flex-1",children:oe}),e[114]=F,e[115]=oe,e[116]=te):te=e[116],M=$e,Q="destructive",K="sm",ee=T,re="flex-1",he=f("gitView.conflict.abortOperation",{operation:W}),e[34]=w,e[35]=m,e[36]=y,e[37]=T,e[38]=F,e[39]=L,e[40]=V,e[41]=h,e[42]=j,e[43]=r,e[44]=n,e[45]=c,e[46]=f,e[47]=M,e[48]=Z,e[49]=se,e[50]=Q,e[51]=K,e[52]=ee,e[53]=re,e[54]=he,e[55]=je,e[56]=te,e[57]=Ne,e[58]=J,e[59]=H,e[60]=q,e[61]=ae,e[62]=le,e[63]=Se,e[64]=Re,e[65]=_e,e[66]=Oe,e[67]=Me,e[68]=ge}else M=e[47],Z=e[48],se=e[49],Q=e[50],K=e[51],ee=e[52],re=e[53],he=e[54],je=e[55],te=e[56],Ne=e[57],J=e[58],H=e[59],q=e[60],ae=e[61],le=e[62],Se=e[63],Re=e[64],_e=e[65],Oe=e[66],Me=e[67],ge=e[68];let Ae;e[117]!==M||e[118]!==Q||e[119]!==K||e[120]!==ee||e[121]!==re||e[122]!==he?(Ae=s.jsx(M,{variant:Q,size:K,onClick:ee,className:re,children:he}),e[117]=M,e[118]=Q,e[119]=K,e[120]=ee,e[121]=re,e[122]=he,e[123]=Ae):Ae=e[123];let pe;e[124]!==je||e[125]!==te||e[126]!==Ae?(pe=s.jsxs("div",{className:je,children:[te,Ae]}),e[124]=je,e[125]=te,e[126]=Ae,e[127]=pe):pe=e[127];let ue;e[128]!==Ne||e[129]!==J||e[130]!==H||e[131]!==pe?(ue=s.jsxs("div",{className:Ne,children:[J,H,pe]}),e[128]=Ne,e[129]=J,e[130]=H,e[131]=pe,e[132]=ue):ue=e[132];let G;e[133]!==q||e[134]!==ae||e[135]!==le||e[136]!==Se||e[137]!==Re||e[138]!==_e||e[139]!==ue?(G=s.jsxs("div",{className:q,children:[ae,le,Se,Re,_e,ue]}),e[133]=q,e[134]=ae,e[135]=le,e[136]=Se,e[137]=Re,e[138]=_e,e[139]=ue,e[140]=G):G=e[140];let fe;e[141]!==Z||e[142]!==Oe||e[143]!==G?(fe=s.jsx(Z,{className:Oe,children:G}),e[141]=Z,e[142]=Oe,e[143]=G,e[144]=fe):fe=e[144];let ce;return e[145]!==se||e[146]!==Me||e[147]!==ge||e[148]!==fe?(ce=s.jsx(se,{open:Me,onOpenChange:ge,children:fe}),e[145]=se,e[146]=Me,e[147]=ge,e[148]=fe,e[149]=ce):ce=e[149],ce};function Dw(t){return t.openNewSessionDraft}function Iw(t){return t.currentSessionId}function Pw(t){return t.setPendingInputText}function Tw(t){return t.setPendingSyntheticParts}function Rw(t){return t.setActiveMainTab}function Ew(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const Mw=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=kt(),[c,l]=i.useState(!0),[d,u]=i.useState(!1),m=a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),f=async()=>{u(!0);try{await o(c),e(!1)}catch(y){const p=y instanceof Error?y.message:`Failed to ${n}`;de.error(p)}finally{u(!1)}},g=()=>{d||e(!1)};return s.jsx(Os,{open:t,onOpenChange:d?void 0:e,children:s.jsxs(Ls,{className:"max-w-md",children:[s.jsxs(Us,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(_s,{children:a("gitView.stash.title")})]}),s.jsx(an,{children:a("gitView.stash.description",{operation:n})})]}),s.jsxs("div",{className:"py-2",children:[s.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:a("gitView.stash.thisWill")}),s.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[s.jsx("li",{children:a("gitView.stash.stepStash")}),s.jsxs("li",{children:[a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase")," ",a(n==="merge"?"gitView.stash.mergeWith":"gitView.stash.rebaseOnto")," ",s.jsx("span",{className:"font-mono text-primary",children:r})]}),c&&s.jsx("li",{children:a("gitView.stash.stepRestore")})]})]}),s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(Ri,{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(ar,{className:"gap-2",children:[s.jsx($e,{variant:"ghost",size:"sm",onClick:g,disabled:d,children:a("gitView.common.cancel")}),s.jsx($e,{variant:"default",size:"sm",onClick:f,disabled:d,className:"gap-1.5",children:d?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:m})})]})]})})},Fw=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=kt(),[d,u]=i.useState(null),m=t&&t.head,f=e&&(e.headName||e.onto),g=m?"merge":f?"rebase":null;if(!g)return null;const y=async()=>{u("continue");try{await n()}finally{u(null)}},p=async()=>{u("abort");try{await r()}finally{u(null)}},x=d!==null,b=l(g==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),h=g==="merge"?"git-merge":"git-branch";let N="";return t?N=t.message?l("gitView.operation.mergingMessage",{message:t.message}):l("gitView.operation.mergeInProgressWithHead",{head:t.head}):e&&(N=e.headName?l("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):l("gitView.operation.rebaseInProgress")),s.jsx("div",{className:"bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[s.jsx(I,{name:h,className:"size-4 text-[var(--status-warning)] shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:l("gitView.operation.inProgressTitle",{operation:b})}),N&&s.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:N})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&o&&s.jsxs($e,{variant:"outline",size:"sm",onClick:o,disabled:x||c,className:"gap-1.5",children:[s.jsx(I,{name:"sparkling",className:"size-4"}),l("gitView.operation.resolveWithAi")]}),d!=="continue"&&s.jsxs($e,{variant:"ghost",size:"sm",onClick:p,disabled:x||c,className:"gap-1.5",children:[d==="abort"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs($e,{variant:"default",size:"sm",onClick:y,disabled:x||c,className:"gap-1.5",children:[d==="continue"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"check",className:"size-4"}),l("gitView.operation.continue")]})]}),a&&s.jsx("p",{className:"typography-micro text-[var(--status-warning)]",children:l("gitView.operation.resolveConflictsHint")})]})})},Lw=t=>{const e=gt.c(104),{currentBranch:n,localBranches:r,remoteBranches:o,onMerge:a,onRebase:c,disabled:l,isOperating:d,operationLogs:u,onOperationComplete:m,mode:f,defaultTargetBranch:g}=t,y=l===void 0?!1:l,p=d===void 0?!1:d,x=u===void 0?[]:u,b=f===void 0?"dialog":f,{t:h}=kt(),[N,w]=i.useState(!1),[S,j]=i.useState("merge"),[k,v]=i.useState(null),[D,A]=i.useState(!1),[C,O]=i.useState(""),T=i.useRef(null),E=i.useRef(null),F=y||p,R=n||h("gitView.branch.currentBranchFallback"),L=x.length>0&&x.every(Ow),B=x.some(Bw);let V;e[0]===Symbol.for("react.memo_cache_sentinel")?(V=()=>{E.current&&(E.current.scrollTop=E.current.scrollHeight)},e[0]=V):V=e[0],i.useEffect(V,[x]);let M;if(e[1]!==C||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Ce=C.toLowerCase();let ne;e[6]!==o?(ne=new Set(o.map(Vw).filter(Boolean)),e[6]=o,e[7]=ne):ne=e[7];const P=ne;let me;e[8]!==n||e[9]!==P?(me=Be=>Be!==n&&!P.has(Be),e[8]=n,e[9]=P,e[10]=me):me=e[10];const oe=r.filter(me);if(!Ce){M=oe;break e}M=oe.filter(Be=>Be.toLowerCase().includes(Ce))}e[1]=C,e[2]=n,e[3]=r,e[4]=o,e[5]=M}else M=e[5];const Z=M;let se;if(e[11]!==C||e[12]!==o){e:{const Ce=C.toLowerCase();if(!Ce){se=o;break e}se=o.filter(ne=>ne.toLowerCase().includes(Ce))}e[11]=C,e[12]=o,e[13]=se}else se=e[13];const Q=se;let K;e[14]!==g||e[15]!==r||e[16]!==o?(K=()=>g&&(o.includes(g)||r.includes(g))?g:null,e[14]=g,e[15]=r,e[16]=o,e[17]=K):K=e[17];const ee=K;let re;e[18]!==ee||e[19]!==w?(re=()=>{w(!0),v(ee()),j("merge"),O("")},e[18]=ee,e[19]=w,e[20]=re):re=e[20];const he=re;let je;e[21]===Symbol.for("react.memo_cache_sentinel")?(je=Ce=>{v(Ce),A(!1),O("")},e[21]=je):je=e[21];const te=je;let Ne;e[22]!==a||e[23]!==c||e[24]!==S||e[25]!==k?(Ne=()=>{k&&(S==="merge"?a(k):c(k))},e[22]=a,e[23]=c,e[24]=S,e[25]=k,e[26]=Ne):Ne=e[26];const J=Ne;let H;e[27]!==p||e[28]!==w?(H=()=>{p||(v(null),j("merge"),O(""),w(!1))},e[27]=p,e[28]=w,e[29]=H):H=e[29];const q=H,ae=()=>{p&&!L||(L&&m?.(),v(null),j("merge"),O(""),w(!1))};let le,Se;e[30]!==D?(le=()=>{D||O("")},Se=[D],e[30]=D,e[31]=le,e[32]=Se):(le=e[31],Se=e[32]),i.useEffect(le,Se);let Re,_e;e[33]!==b||e[34]!==ee||e[35]!==k?(Re=()=>{b!=="inline"||k||v(ee())},_e=[b,ee,k],e[33]=b,e[34]=ee,e[35]=k,e[36]=Re,e[37]=_e):(Re=e[36],_e=e[37]),i.useEffect(Re,_e);const ge=p?s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{ref:E,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:s.jsx("div",{className:"space-y-2",children:x.map(_w)})}),L?b==="dialog"?s.jsx(ar,{children:s.jsx($e,{variant:"default",size:"sm",onClick:ae,children:h(B?"gitView.common.close":"gitView.common.done")})}):s.jsx("div",{className:"flex justify-end",children:s.jsx($e,{variant:"default",size:"sm",onClick:ae,children:h(B?"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:()=>j("merge"),className:De("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(I,{name:"git-merge",className:De("size-4",S==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:De("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:()=>j("rebase"),className:De("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(I,{name:"git-branch",className:De("size-4",S==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:De("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:R}):h("gitView.branch.branchToRebaseOnto")}),s.jsxs(nn,{open:D,onOpenChange:A,modal:!1,children:[s.jsx(tn,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:De("truncate",!k&&"text-muted-foreground"),children:k||h("gitView.branch.selectBranch")}),s.jsx(I,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(sn,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:s.jsxs(Oa,{className:"h-full min-h-0",children:[s.jsx(Ba,{ref:T,placeholder:h("gitView.branch.searchPlaceholder"),value:C,onValueChange:O,onKeyDown:$w}),s.jsxs(Va,{className:"h-full min-h-0",disableHorizontal:!0,children:[s.jsx(_a,{children:h("gitView.branch.empty")}),Z.length>0&&s.jsx(ii,{heading:h("gitView.branch.localBranches"),children:Z.map(Ce=>s.jsx(ai,{onSelect:()=>te(Ce),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ce})},`local-${Ce}`))}),Z.length>0&&Q.length>0?s.jsx(Gp,{}):null,Q.length>0&&s.jsx(ii,{heading:h("gitView.branch.remoteBranches"),children:Q.map(Ce=>s.jsx(ai,{onSelect:()=>te(Ce),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ce})},`remote-${Ce}`))})]})]})})]})]}),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:R})]}):s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryRebasePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R})," ",h("gitView.branch.summaryRebaseInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})]})})}):null,b==="dialog"?s.jsxs(ar,{className:"gap-2 pt-1",children:[s.jsx($e,{variant:"ghost",size:"sm",onClick:q,children:h("gitView.common.cancel")}),s.jsx($e,{variant:"default",size:"sm",onClick:J,disabled:!k,className:"gap-1.5",children:S==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"git-merge",className:"size-4"}),h("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"git-branch",className:"size-4"}),h("gitView.operation.rebase")]})})]}):s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx($e,{variant:"destructive",size:"sm",onClick:q,disabled:F,children:h("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx($e,{variant:"default",size:"sm",onClick:J,disabled:F||!k,children:h(S==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(b==="inline"){let Ce;e[38]!==h?(Ce=h("gitView.branch.updateTitle"),e[38]=h,e[39]=Ce):Ce=e[39];let ne;e[40]!==Ce?(ne=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Ce}),e[40]=Ce,e[41]=ne):ne=e[41];let P;e[42]!==h?(P=h("gitView.branch.updateDescriptionPrefix"),e[42]=h,e[43]=P):P=e[43];let me;e[44]!==R?(me=s.jsx("span",{className:"font-mono text-foreground",children:R}),e[44]=R,e[45]=me):me=e[45];let oe;e[46]!==P||e[47]!==me?(oe=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[P," ",me,"."]}),e[46]=P,e[47]=me,e[48]=oe):oe=e[48];let Be;e[49]!==ne||e[50]!==oe?(Be=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[ne,oe]})}),e[49]=ne,e[50]=oe,e[51]=Be):Be=e[51];let Ue;e[52]!==ge?(Ue=s.jsx("div",{className:"pt-3",children:ge}),e[52]=ge,e[53]=Ue):Ue=e[53];let Ke;return e[54]!==Be||e[55]!==Ue?(Ke=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Be,Ue]}),e[54]=Be,e[55]=Ue,e[56]=Ke):Ke=e[56],Ke}let Ae;e[57]!==p?(Ae=p?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-merge",className:"size-4"}),e[57]=p,e[58]=Ae):Ae=e[58];let pe;e[59]!==h?(pe=h("gitView.branch.mergeRebase"),e[59]=h,e[60]=pe):pe=e[60];let ue;e[61]!==pe?(ue=s.jsx("span",{children:pe}),e[61]=pe,e[62]=ue):ue=e[62];let G;e[63]!==he||e[64]!==F||e[65]!==Ae||e[66]!==ue?(G=s.jsx(Et,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"sm",className:"gap-1.5",onClick:he,disabled:F,children:[Ae,ue]})}),e[63]=he,e[64]=F,e[65]=Ae,e[66]=ue,e[67]=G):G=e[67];let fe;e[68]!==h?(fe=h("gitView.branch.mergeRebaseTooltip"),e[68]=h,e[69]=fe):fe=e[69];let ce;e[70]!==fe?(ce=s.jsx(Mt,{sideOffset:8,children:fe}),e[70]=fe,e[71]=ce):ce=e[71];let W;e[72]!==G||e[73]!==ce?(W=s.jsxs(Rt,{children:[G,ce]}),e[72]=G,e[73]=ce,e[74]=W):W=e[74];let z;e[75]!==ae||e[76]!==w?(z=Ce=>{Ce?w(!0):ae()},e[75]=ae,e[76]=w,e[77]=z):z=e[77];let be;e[78]!==h?(be=h("gitView.branch.updateTitle"),e[78]=h,e[79]=be):be=e[79];let xe;e[80]!==be?(xe=s.jsx(_s,{children:be}),e[80]=be,e[81]=xe):xe=e[81];let _;e[82]!==B||e[83]!==p||e[84]!==S||e[85]!==L||e[86]!==h||e[87]!==R?(_=p?h(L?B?"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:R}),"."]}),e[82]=B,e[83]=p,e[84]=S,e[85]=L,e[86]=h,e[87]=R,e[88]=_):_=e[88];let ye;e[89]!==_?(ye=s.jsx(an,{children:_}),e[89]=_,e[90]=ye):ye=e[90];let $;e[91]!==xe||e[92]!==ye?($=s.jsxs(Us,{children:[xe,ye]}),e[91]=xe,e[92]=ye,e[93]=$):$=e[93];let Ie;e[94]!==ge||e[95]!==$?(Ie=s.jsxs(Ls,{className:"max-w-md",children:[$,ge]}),e[94]=ge,e[95]=$,e[96]=Ie):Ie=e[96];let ve;e[97]!==N||e[98]!==z||e[99]!==Ie?(ve=s.jsx(Os,{open:N,onOpenChange:z,children:Ie}),e[97]=N,e[98]=z,e[99]=Ie,e[100]=ve):ve=e[100];let Fe;return e[101]!==W||e[102]!==ve?(Fe=s.jsxs(s.Fragment,{children:[W,ve]}),e[101]=W,e[102]=ve,e[103]=Fe):Fe=e[103],Fe};function Ow(t){return t.status==="done"||t.status==="error"}function Bw(t){return t.status==="error"}function Vw(t){return t.slice(t.indexOf("/")+1)}function _w(t,e){return s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"mt-0.5 shrink-0",children:[t.status==="running"&&s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(I,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(I,{name:"close",className:"size-3.5 text-destructive"}),t.status==="pending"&&s.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),s.jsx("span",{className:De("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 $w(t){return t.stopPropagation()}const zw=({runMutation:t,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:o})=>{const a=[];let c=!1;return{enqueue:d=>{const u=a[a.length-1];if(u?.directory===d.directory&&u.direction===d.direction){d.paths.forEach(m=>u.paths.add(m));return}a.push(d)},flush:()=>{if(c)return;const d=a.shift();if(!d)return;c=!0;const u={directory:d.directory,direction:d.direction,paths:Array.from(d.paths),rollback:d.rollback};(async()=>{try{await t(u),e(u)}catch(m){n(u,m)}finally{r(u.paths),c=!1,a.length>0&&o()}})()},clear:()=>{a.length=0},size:()=>a.length,isRunning:()=>c}},bu="oc.git.actionTab",Ww=15e3,Uw=t=>t==="commit"||t==="branch"||t==="pr",Hw=40,Gw=20,yu={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:"},Kw=(t,e)=>{const n=t.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,o=n.match(r);if(o){const l=o[1],d=yu[l];if(d)return e.find(u=>u.code===d)||null}const a=n.split(" ")[0],c=yu[a];return c&&e.find(l=>l.code===c)||null},qw=20,Wi=new Map,Yw=(t,e)=>{if(Wi.delete(t),Wi.set(t,e),Wi.size>qw){const n=Wi.keys().next().value;n!==void 0&&Wi.delete(n)}},_r=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),wu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Qw=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},Ql=({isActive:t})=>{const{t:e}=kt(),{git:n}=er(),r=ci(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=ut(Y=>Y.currentSessionId),u=ut(Y=>Y.newSessionDraft),m=ut(Y=>Y.setDraftBootstrapPendingDirectory),f=ut(Y=>Y.worktreeMetadata),g=ut(Y=>Y.availableWorktrees),y=_r(r),p=i.useMemo(()=>{if(!y)return;const Y=g.find(ke=>_r(ke.path)===y);if(Y)return Y;for(const ke of f.values())if(_r(ke.path)===y)return ke},[g,y,f]),x=i.useMemo(()=>{if(d)return f.get(d)??p;if(u?.open)return p},[d,p,u?.open,f]),{profiles:b,globalIdentity:h,defaultGitIdentityId:N,loadProfiles:w,loadGlobalIdentity:S,loadDefaultGitIdentityId:j}=Px(Bl(Y=>({profiles:Y.profiles,globalIdentity:Y.globalIdentity,defaultGitIdentityId:Y.defaultGitIdentityId,loadProfiles:Y.loadProfiles,loadGlobalIdentity:Y.loadGlobalIdentity,loadDefaultGitIdentityId:Y.loadDefaultGitIdentityId}))),k=yc(r??null),v=Wa(r??null),D=_f(Y=>d?Y.getAttachment(d):void 0),A=D?Kp(D):[],C=D&&!D.degraded&&!D.legacy?D.worktreeRoot??void 0:void 0,O=Iy(r,x,v?.current??void 0),T=Hf(r??null),E=qp(r??null),F=Yp(r??null),R=wc(r??null),L=Qp(r??null),{setActiveDirectory:B,fetchAll:V,ensureAll:M,fetchStatus:Z,fetchBranches:se,fetchLog:Q,setLogMaxCount:K,fetchIdentity:ee,prefetchDiffs:re,moveStatusPathsOptimistically:he,restoreStatus:je,bumpIndexRevision:te}=wn(Bl(Y=>({setActiveDirectory:Y.setActiveDirectory,fetchAll:Y.fetchAll,ensureAll:Y.ensureAll,fetchStatus:Y.fetchStatus,fetchBranches:Y.fetchBranches,fetchLog:Y.fetchLog,setLogMaxCount:Y.setLogMaxCount,fetchIdentity:Y.fetchIdentity,prefetchDiffs:Y.prefetchDiffs,moveStatusPathsOptimistically:Y.moveStatusPathsOptimistically,restoreStatus:Y.restoreStatus,bumpIndexRevision:Y.bumpIndexRevision}))),Ne=Ee(Y=>Y.isMobile),J=Ee(Y=>Y.openContextDiff),H=Ee(Y=>Y.navigateToDiff),q=Ee(Y=>Y.setRightSidebarOpen),ae=i.useRef(null),le=i.useRef(null),Se=i.useRef(null),Re=i.useRef(null),_e=i.useRef(!0);i.useEffect(()=>()=>{_e.current=!1},[]);const Oe=i.useCallback(()=>{le.current!==null&&(window.clearTimeout(le.current),le.current=null)},[]),Me=i.useCallback(Y=>{Oe(),le.current=window.setTimeout(()=>{le.current=null,_r(Y)===_r(r)&&Z(Y,n,{silent:!0})},Ww)},[Oe,r,Z,n]);i.useEffect(()=>Oe,[Oe]);const ge=i.useCallback(()=>{Se.current!==null&&(window.clearTimeout(Se.current),Se.current=null)},[]),Ae=i.useCallback(()=>{Se.current===null&&(Se.current=window.setTimeout(()=>{Se.current=null,Re.current?.()},0))},[]),pe=i.useCallback(async(Y,ke,Pe)=>{if(ke==="stage"){if(n.stageGitFiles){await n.stageGitFiles(Y,Pe);return}await Promise.all(Pe.map(ze=>n.stageGitFile(Y,ze)));return}if(n.unstageGitFiles){await n.unstageGitFiles(Y,Pe);return}await Promise.all(Pe.map(ze=>n.unstageGitFile(Y,ze)))},[n]),ue=i.useMemo(()=>zw({runMutation:({directory:Y,direction:ke,paths:Pe})=>pe(Y,ke,Pe),onMutationComplete:({directory:Y})=>{te(Y),Me(Y)},onMutationError:({directory:Y,direction:ke,rollback:Pe},ze)=>{Pe?.(),te(Y),Me(Y);const dt=e(ke==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");de.error(ze instanceof Error?ze.message:dt)},onPathsComplete:Y=>{is(ke=>{const Pe=new Set(ke);return Y.forEach(ze=>Pe.delete(ze)),Pe})},scheduleFlush:Ae}),[te,pe,Ae,Me,e]);i.useEffect(()=>(Re.current=ue.flush,()=>{Re.current=null}),[ue]),i.useEffect(()=>()=>ue.clear(),[ue]),i.useEffect(()=>ge,[ge]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let Y=!1,ke=null;const Pe=async()=>{try{const ze=await Xp(r);if(Y)return;a(ze.status),ze.status==="pending"&&(ke=window.setTimeout(()=>{Pe()},500))}catch{Y||a(null)}};return Pe(),()=>{Y=!0,ke!==null&&window.clearTimeout(ke)}},[t,r]),i.useEffect(()=>{const Y=ae.current;ae.current=o,!(!r||!n)&&(Y==="pending"&&o==="ready"&&(l(!0),V(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(m(null),l(!1)))},[r,V,n,m,o]);const G=_r(u?.bootstrapPendingDirectory??null),fe=!!(r&&G&&G===_r(r)),W=!!(r&&(o==="pending"||fe))||c,z=i.useMemo(()=>r?Wi.get(r)??null:null,[r]),be=ss(Y=>Y.settingsGitmojiEnabled),[xe,_]=i.useState(null),{gitmojis:ye}=Dy(be);i.useEffect(()=>{const Y=C||O?.projectDirectory;if(!Y){_(null);return}let ke=!1;return Ua(Y).then(Pe=>{if(ke)return;const ze=Pe.trim();_(ze&&ze!=="HEAD"?ze:null)}).catch(()=>{ke||_(null)}),()=>{ke=!0}},[C,O?.projectDirectory]);const[$,Ie]=i.useState(z?.commitMessage??""),[ve,Fe]=i.useState([]),[Ce,ne]=i.useState(!1),P=i.useRef(null),[me,oe]=i.useState(null),[Be,Ue]=i.useState(!1),[Ke,Qe]=i.useState(null),[rt,pt]=i.useState(25),[jt,Ve]=i.useState(!1),{triggerFireworks:Ze}=Ny(),nt=i.useRef(new Map),St=i.useRef(0),Dt=i.useCallback(()=>{St.current+=1,_e.current&&Ve(!0)},[]),wt=i.useCallback(()=>{St.current=Math.max(0,St.current-1),_e.current&&St.current===0&&Ve(!1)},[]),[ot,at]=i.useState(new Set),[Kt,is]=i.useState(new Set),[$t,Le]=i.useState(!1),[et,Vt]=i.useState(0),[xt,Ft]=i.useState(!1),[Gt,Ut]=i.useState(z?.generatedHighlights??[]),qt=Kt.size>0||ue.size()>0||ue.isRunning(),Xt=i.useCallback(()=>{const Y=P.current;Y&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Y.scrollTo({top:Y.scrollHeight,behavior:"smooth"})})})},[]),Lt=C||O?.projectDirectory||null,Bt=v?.current||null,Yt=i.useMemo(()=>{const Y=v?.tracking;return Y?Y.startsWith("origin/"):!0},[v?.tracking]),Jt=i.useMemo(()=>{const Y=O?.createdFromBranch,ke=typeof Y=="string"?Y.trim():"",Pe=typeof v?.current=="string"?v.current.trim():"",ze=typeof xe=="string"?xe.trim():"";return ke?ke===Pe&&ke.startsWith("opencode/")&&ze.length>0&&ze!==ke?ze:ke:ze||Pe||"HEAD"},[O?.createdFromBranch,v,xe]),es=i.useCallback(()=>{Ut([])},[]),[Zt,vs]=i.useState(new Set),[bt,Ot]=i.useState(new Map),[It,us]=i.useState(new Set),He=i.useRef(bt),ft=i.useRef(It),[Ye,Pt]=i.useState(null),[Tt,Qt]=i.useState(null),[Ss,ys]=i.useState(""),[_t,Ns]=i.useState(null),js=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(I,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(I,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(I,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[Ds,mn]=i.useState(()=>{if(typeof window>"u")return"commit";const Y=window.localStorage.getItem(bu);return Y==="worktree"?"branch":Uw(Y)?Y:"commit"}),[Js,ln]=i.useState([]),[jn,$s]=i.useState(null),[we,Je]=i.useState(null),[vt,Ct]=i.useState([]),[zt,mt]=i.useState(!1),[cs,fs]=i.useState([]),[ks,ms]=i.useState("merge"),[Hs,zs]=i.useState(null),[hn,tr]=i.useState(!1),[An,qe]=i.useState(100),ns=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),ps=i.useCallback((Y,ke,Pe)=>{if(!ns||typeof window>"u")return;const ze={directory:Y,conflictFiles:ke,operation:Pe};window.localStorage.setItem(ns,JSON.stringify(ze))},[ns]),hs=i.useCallback(()=>{!ns||typeof window>"u"||window.localStorage.removeItem(ns)},[ns]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(bu,Ds)},[Ds]),i.useEffect(()=>{if(!ns||typeof window>"u"||!r)return;const Y=window.localStorage.getItem(ns);if(Y)try{const ke=JSON.parse(Y);if(ke.directory!==r){window.localStorage.removeItem(ns);return}fs(ke.conflictFiles??[]),ms(ke.operation??"merge"),mt(!0)}catch{window.localStorage.removeItem(ns)}},[ns,r]);const[rn,Ws]=i.useState(!1),[cn,Is]=i.useState("merge"),[sr,Sr]=i.useState(""),nr=i.useCallback(Y=>{pr(Y).then(ke=>{if(ke.ok){de.success(e("gitView.toast.commitHashCopied"));return}de.error(e("gitView.toast.copyFailed"))})},[e]),gr=i.useCallback(Y=>{vs(ke=>{const Pe=new Set(ke);return Pe.has(Y)?Pe.delete(Y):Pe.add(Y),Pe})},[]);i.useEffect(()=>{He.current=bt},[bt]),i.useEffect(()=>{ft.current=It},[It]),i.useEffect(()=>{if(!r||!n)return;const Y=Array.from(Zt).filter(Pe=>!He.current.has(Pe)&&!ft.current.has(Pe));if(Y.length===0)return;let ke=!1;return us(Pe=>{const ze=new Set(Pe);for(const dt of Y)ze.add(dt);return ft.current=ze,ze}),Promise.all(Y.map(Pe=>n.getCommitFiles(r,Pe).then(ze=>({hash:Pe,files:ze.files})).catch(ze=>(console.error("Failed to fetch commit files:",ze),{hash:Pe,files:[]})))).then(Pe=>{ke||(Ot(ze=>{const dt=new Map(ze);for(const{hash:yt,files:ls}of Pe)dt.set(yt,ls);return He.current=dt,dt}),us(ze=>{const dt=new Set(ze);for(const{hash:yt}of Pe)dt.delete(yt);return ft.current=dt,dt}))}),()=>{ke=!0,us(Pe=>{let ze=!1;const dt=new Set(Pe);for(const yt of Y)dt.delete(yt)&&(ze=!0);return ze?(ft.current=dt,dt):Pe})}},[Zt,r,n]),i.useEffect(()=>{r&&Yw(r,{directory:r,commitMessage:$,generatedHighlights:Gt})},[$,r,Gt]),i.useEffect(()=>{t&&(w(),S(),j())},[t,w,S,j]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){Qt(null);return}let Y=!1;return n.getRemoteUrl(r).then(ke=>{Y||Qt(ke)}).catch(()=>{Y||Qt(null)}),()=>{Y=!0}},[t,r,n]);const Kn=i.useCallback(async()=>{if(!r||!n?.getRemotes){ln([]);return}try{const Y=await n.getRemotes(r);_e.current&&ln(Y)}catch{_e.current&&ln([])}},[r,n]);i.useEffect(()=>{t&&Kn()},[t,Kn]),i.useEffect(()=>{t&&r&&(B(r),M(r,n))},[t,r,B,M,n]),i.useEffect(()=>{if(t&&r)return Pr.onGitRefreshHint(Y=>{_r(Y.directory)===_r(r)&&Z(r,n)})},[t,r,Z,n]);const gs=i.useCallback(async(Y=!0)=>{if(r)try{await Promise.all([Z(r,n),se(r,n)])}catch(ke){if(Y){const Pe=ke instanceof Error?ke.message:e("gitView.toast.refreshRepositoryFailed");de.error(Pe)}}},[r,n,Z,se,e]),Ps=i.useCallback(async()=>{r&&await Q(r,n,rt)},[r,n,Q,rt]),Mr=i.useCallback(async()=>{r&&await ee(r,n)},[r,n,ee]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||k!==!0)return;const Y=typeof N=="string"?N.trim():"";if(!Y||Y==="global"||nt.current.get(r)===Y)return;let Pe=!1;return(async()=>{try{const dt=await n.hasLocalIdentity?.(r);if(Pe||dt===!0)return;Dt(),await n.setGitIdentity(r,Y),nt.current.set(r,Y),await Mr()}catch(dt){console.warn("Failed to auto-apply default git identity:",dt)}finally{Pe||wt()}})(),()=>{Pe=!0}},[t,Dt,r,N,wt,n,k,Mr]);const Sn=i.useMemo(()=>v?[...v.files??[]].sort((ke,Pe)=>ke.path.localeCompare(Pe.path)):[],[v]),on=i.useMemo(()=>Sn.filter(wu),[Sn]),lr=i.useMemo(()=>Sn.filter(Qw),[Sn]);i.useEffect(()=>{if(!r||Sn.length===0)return;const Y=[],ke=new Set,Pe=dt=>{!dt||ke.has(dt)||(ke.add(dt),Y.push(dt))};if(on.forEach(dt=>Pe(dt.path)),ve.forEach(Pe),Sn.slice(0,Gw).forEach(dt=>Pe(dt.path)),Y.length===0)return;const ze=window.setTimeout(()=>{re(r,n,Y,{maxFiles:Hw})},120);return()=>{window.clearTimeout(ze)}},[Sn,r,n,re,on,ve]);const Fr=Y=>Y?.pushed[0]?.remote||v?.tracking?.split("/")[0]||rs.find(ke=>ke.name==="origin")?.name||rs[0]?.name||"origin",Kr=async(Y,ke)=>{if(r){oe(Y);try{const Pe=ze=>{const dt=`${ze.name}/`,yt=v?.tracking?.startsWith(dt)?v.tracking.slice(dt.length):void 0;return{remote:ze.name,branch:yt,rebase:!0}};if(Y==="fetch"){if(!ke)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:ke.name}),de.success(e("gitView.toast.fetchedFromRemote",{name:ke.name}))}else if(Y==="pull"){if(!ke)throw new Error("No remote available for pull");const ze=await n.gitPull(r,Pe(ke));de.success(ze.files.length===1?e("gitView.toast.pulledFilesSingle",{count:ze.files.length,name:ke.name}):e("gitView.toast.pulledFilesPlural",{count:ze.files.length,name:ke.name}))}else if(Y==="push"){const ze=await n.gitPush(r);de.success(e("gitView.toast.pushedToUpstream",{name:Fr(ze)}))}else if(Y==="sync"){if(!ke)throw new Error("No remote available for sync");let ze=0,dt=!1;await n.gitFetch(r,{remote:ke.name});const yt=await n.getGitStatus(r);if((yt.behind??0)>0){if((yt.files?.length??0)>0){de.error(e("gitView.toast.commitOrStashBeforeSync"));return}ze=(await n.gitPull(r,Pe(ke))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),dt=!0),ze>0&&dt?de.success(ze===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:ze,name:ke.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:ze,name:ke.name})):ze>0?de.success(ze===1?e("gitView.toast.pulledFilesSingle",{count:ze,name:ke.name}):e("gitView.toast.pulledFilesPlural",{count:ze,name:ke.name})):dt?de.success(e("gitView.toast.pushedToUpstream",{name:ke.name})):de.success(e("gitView.toast.alreadyUpToDate"))}await gs(!1),await Ps()}catch(Pe){const ze=Pe instanceof Error?Pe.message:e("gitView.toast.syncActionFailed",{action:Y==="sync"?e("gitView.sync.syncChanges"):Y==="pull"?e("gitView.sync.pull"):Y});de.error(ze)}finally{oe(null)}}},Lr=i.useCallback(async Y=>{if(!r)return;const ke=Y.name.trim();if(!ke){de.error(e("gitView.toast.remoteNameRequired"));return}if(ke==="origin"){de.error(e("gitView.toast.cannotRemoveOriginRemote"));return}$s(ke);try{await n.removeRemote(r,{remote:ke}),de.success(e("gitView.toast.removedRemote",{name:ke})),await Promise.all([gs(!1),Kn()])}catch(Pe){const ze=Pe instanceof Error?Pe.message:`Failed to remove ${ke}`;de.error(ze)}finally{$s(null)}},[r,n,Kn,gs,e]),xs=async(Y={})=>{if(!r)return;if(!$.trim()){de.error(e("gitView.toast.enterCommitMessage"));return}const ke=on.map(ze=>ze.path).sort();if(ke.length===0){de.error(e("gitView.toast.stageFileToCommit"));return}const Pe=Y.pushAfter?"commitAndPush":"commit";Qe(Pe);try{if(await n.createGitCommit(r,$.trim(),{files:ke,stageFiles:[]}),te(r),de.success(e("gitView.toast.commitCreated")),Ie(""),es(),await gs(),Y.pushAfter){const ze=v?.tracking?.split("/")[0],dt=rs.find(fr=>fr.name===ze)??rs[0];if(!dt)throw new Error(e("mobile.changes.noRemote"));oe("sync");const yt=`${dt.name}/`,ls=v?.tracking?.startsWith(yt)?v.tracking.slice(yt.length):void 0;await n.gitFetch(r,{remote:dt.name});const Wt=await n.getGitStatus(r);if((Wt.behind??0)>0){if((Wt.files?.length??0)>0){de.error(e("gitView.toast.commitOrStashBeforeSync")),await gs(!1);return}await n.gitPull(r,{remote:dt.name,branch:ls,rebase:!0})}const Ks=await n.getGitStatus(r);let Bn;(Ks.ahead??0)>0&&(Bn=await n.gitPush(r)),de.success(e("gitView.toast.pushedToUpstream",{name:Fr(Bn)})),Ze(),await gs(!1)}else await gs(!1);await Ps(),Vt(ze=>ze+1)}catch(ze){const dt=ze instanceof Error?ze.message:e("gitView.toast.createCommitFailed");de.error(dt)}finally{Qe(null),Y.pushAfter&&oe(null)}},Rs=i.useCallback(async()=>{if(!r)return;const Y=on.map(ke=>ke.path).sort();if(Y.length===0){de.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:Y.length}),Ft(!0);try{const{message:ke}=await Jp(r,Y),Pe=ke.subject?.trim()??"",ze=Array.isArray(ke.highlights)?ke.highlights:[];if(Pe){let dt=Pe;if(be&&ye.length>0){const yt=Kw(Pe,ye);if(yt){const{code:ls,emoji:Wt}=yt;!Pe.startsWith(ls)&&!Pe.startsWith(Wt)&&(dt=`${ls} ${Pe}`)}}Ie(dt)}Ut(ze),Xt()}catch(ke){console.error("[git-generation][browser] GitView generate handler failed",{message:ke instanceof Error?ke.message:String(ke),error:ke});const Pe=ke instanceof Error?ke.message:e("gitView.toast.generateCommitMessageFailed");de.error(Pe)}finally{Ft(!1)}},[r,on,be,ye,Xt,e]),qn=Y=>Y.reason==="attention"?`${Y.attentionReason} in progress`:Y.reason==="missing"?"worktree is missing":"worktree is invalid",pn=async(Y,ke)=>{if(!r||!v)return;const Pe=nl(D);if(Pe.length>0){de.error(e("gitView.toast.cannotCreateBranch",{reason:qn(Pe[0])}));return}const ze=v.current??null,dt=ke?.name??"origin";try{await n.createBranch(r,Y,ze??"HEAD"),de.success(e("gitView.toast.createdBranch",{name:Y})),await n.checkoutBranch(r,Y);let yt=!1;try{await n.gitPush(r,{remote:dt,branch:Y,options:["--set-upstream"]}),yt=!0}catch(ls){const Wt=ls instanceof Error?ls.message:`Unable to push new branch to ${dt}.`;de.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Wt]})})}await gs(),await Ps(),yt&&de.success(e("gitView.toast.upstreamSet",{branch:Y,remote:dt}))}catch(yt){const ls=yt instanceof Error?yt.message:e("gitView.toast.createBranchFailed");throw de.error(ls),yt}},X=async(Y,ke)=>{if(!r)return;const Pe=nl(D);if(Pe.length>0){de.error(e("gitView.toast.cannotRenameBranch",{reason:qn(Pe[0])}));return}try{await n.renameBranch(r,Y,ke),de.success(e("gitView.toast.renamedBranch",{oldName:Y,newName:ke})),await gs(),await Ps()}catch(ze){const dt=ze instanceof Error?ze.message:e("gitView.toast.renameBranchFailed",{oldName:Y,newName:ke});de.error(dt)}},st=async Y=>{if(!r)return;const ke=nl(D);if(ke.length>0){de.error(e("gitView.toast.cannotCheckout",{reason:qn(ke[0])}));return}const Pe=Y.replace(/^remotes\//,"");if(v?.current!==Pe)try{await n.checkoutBranch(r,Pe),de.success(e("gitView.toast.checkedOut",{name:Pe})),await gs(),await Ps()}catch(ze){const dt=ze instanceof Error?ze.message:e("gitView.toast.checkoutFailed",{name:Pe});de.error(dt)}},ht=async Y=>{if(r){Dt();try{await n.setGitIdentity(r,Y.id),de.success(e("gitView.toast.appliedIdentity",{name:Y.name})),await Mr()}catch(ke){const Pe=ke instanceof Error?ke.message:e("gitView.toast.applyIdentityFailed");de.error(Pe)}finally{wt()}}},At=i.useMemo(()=>T?.all?T.all.filter(Y=>!Y.startsWith("remotes/")).sort():[],[T]),os=i.useMemo(()=>T?.all?T.all.filter(Y=>Y.startsWith("remotes/")).map(Y=>Y.replace(/^remotes\//,"")).sort():[],[T]),rs=i.useMemo(()=>{if(Js.length>0)return Js;const Y=new Set,ke=v?.tracking?.trim();ke&&ke.includes("/")&&Y.add(ke.split("/")[0]);for(const Pe of os){const ze=Pe.indexOf("/");ze>0&&Y.add(Pe.slice(0,ze))}return Y.size===0&&Tt&&Y.add("origin"),Array.from(Y).map(Pe=>({name:Pe,fetchUrl:Tt??"",pushUrl:Tt??""}))},[Js,os,Tt,v?.tracking]),ds=i.useMemo(()=>{const Y=new Set(rs.map(dt=>dt.name)),ke=dt=>{if(!dt)return"";let yt=dt.trim();if(!yt||yt==="HEAD")return"";if(At.includes(yt))return yt;yt.startsWith("refs/heads/")&&(yt=yt.slice(11)),yt.startsWith("heads/")&&(yt=yt.slice(6)),yt.startsWith("remotes/")&&(yt=yt.slice(8));const ls=yt.indexOf("/");if(ls>0){const Wt=yt.slice(0,ls);if(Y.has(Wt)){const Ks=yt.slice(ls+1).trim();Ks&&(yt=Ks)}}return yt},Pe=ke(typeof O?.createdFromBranch=="string"?O.createdFromBranch:"");if(Pe)return Pe;const ze=ke(typeof xe=="string"?xe:"");return ze||(At.includes("main")?"main":At.includes("master")?"master":At.includes("develop")?"develop":"main")},[rs,At,xe,O?.createdFromBranch]),Es=i.useMemo(()=>rs.map(Pe=>Pe.name).map(Pe=>`${Pe}/${ds}`).find(Pe=>os.includes(Pe))??ds,[ds,rs,os]),Gs=i.useMemo(()=>{const Y=new Map;h&&Y.set(h.id,h);let ke=null;if(Tt)try{let Pe=Tt.trim();Pe.startsWith("git@")&&(Pe=`https://${Pe.slice(4).replace(":","/")}`),Pe.endsWith(".git")&&(Pe=Pe.slice(0,-4));const ze=new URL(Pe);ke=ze.hostname+ze.pathname}catch{}for(const Pe of b){if(Pe.authType!=="token"){Y.set(Pe.id,Pe);continue}const ze=Pe.host;if(!ze){Y.set(Pe.id,Pe);continue}if(!ze.includes("/")){Y.set(Pe.id,Pe);continue}ke&&ke===ze&&Y.set(Pe.id,Pe)}return Array.from(Y.values())},[b,h,Tt]),Dn=i.useMemo(()=>{if(F?.userName&&F?.userEmail){const Y=b.find(ke=>ke.userName===F.userName&&ke.userEmail===F.userEmail);return Y||(h&&h.userName===F.userName&&h.userEmail===F.userEmail?h:{id:"local-config",name:F.userName,userName:F.userName,userEmail:F.userEmail,sshKey:F.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return h??null},[F,b,h]),Nr=on.length,kr=R||me!==null||Ke!==null,Bs=v?.current??null,Or=!!(O&&Lt&&Bt&&Yt),dn=!!(r&&Bs),Ln=!!Bs,In=Or&&Lt&&Bt&&O?{repoRoot:Lt,sourceBranch:Bt,worktreeMetadata:O}:null,Nn=i.useMemo(()=>!dn||!r||!Bs?null:{directory:r,branch:Bs},[dn,Bs,r]);i.useEffect(()=>{if(!r||!n||!E?.all?.length||!Bs||!ds||Bs===ds){Pt(null);return}let Y=!1;return(async()=>{try{const Pe=await n.getGitLog(r,{from:ds,to:"HEAD",maxCount:rt});if(Y)return;const ze=new Set((Pe?.all??[]).map(yt=>yt.hash).filter(yt=>typeof yt=="string"&&yt.length>0));if(ze.size===0){Pt(null);return}const dt=E.all.findIndex(yt=>!ze.has(yt.hash));if(dt===0){Pt(null);return}if(dt===-1){Pt({insertBeforeIndex:E.all.length,branchName:Bs,direction:"up"});return}Pt({insertBeforeIndex:dt,branchName:Bs,direction:"up"})}catch{Y||Pt(null)}})(),()=>{Y=!0}},[ds,Bs,r,n,E,rt]),i.useEffect(()=>{zs(null)},[r]),i.useEffect(()=>{if(_t!=="graph"||!r){_t!=="graph"&&zs(null);return}let Y=!1;return tr(!0),n.getGitLog(r,{maxCount:An,all:!0}).then(ke=>{Y||zs(ke)}).catch(ke=>{console.error("Failed to fetch graph log:",ke)}).finally(()=>{Y||tr(!1)}),()=>{Y=!0}},[_t,r,An,n]);const Pn=i.useCallback((Y,ke)=>{if(!r||Y.length===0)return;const Pe=Array.from(new Set(Y));is(dt=>{const yt=new Set(dt);return Pe.forEach(ls=>yt.add(ls)),yt});const ze=he(r,Pe,ke);ue.enqueue({directory:r,direction:ke,paths:new Set(Pe),rollback:()=>je(r,ze)}),Ae()},[r,ue,he,je,Ae]),cr=i.useCallback(async Y=>{if(r){at(ke=>{const Pe=new Set(ke);return Pe.add(Y),Pe});try{await n.revertGitFile(r,Y,{scope:"working"}),de.success(e("gitView.toast.revertedFile",{path:Y})),await gs(!1)}catch(ke){const Pe=ke instanceof Error?ke.message:e("gitView.toast.revertFailed");de.error(Pe)}finally{at(ke=>{const Pe=new Set(ke);return Pe.delete(Y),Pe})}}},[r,gs,n,e]),un=i.useCallback(async(Y,ke,Pe="all")=>{if(!r||Y.length===0)return;const ze=Array.from(new Set(Y));if($t||ze.some(Wt=>ot.has(Wt)))return;const dt=new Set(on.map(Wt=>Wt.path)),yt=Pe==="all"&&ze.some(Wt=>dt.has(Wt));ke&&Le(!0),at(Wt=>{const Ks=new Set(Wt);return ze.forEach(Bn=>Ks.add(Bn)),Ks});const ls=[];try{if(await Promise.all(ze.map(async Wt=>{try{await n.revertGitFile(r,Wt,{scope:Pe})}catch(Ks){ls.push({path:Wt,message:Ks instanceof Error?Ks.message:e("gitView.toast.revertFailed")})}})),yt&&ls.length<ze.length&&te(r),await gs(!1),ls.length===0)de.success(ze.length===1?e("gitView.toast.revertedFilesSingle",{count:ze.length}):e("gitView.toast.revertedFilesPlural",{count:ze.length}));else if(ls.length===ze.length)de.error(ls[0]?.message||e("gitView.toast.revertFailed"));else{const Wt=ze.length-ls.length;de.warning(Wt===1?e("gitView.toast.revertedSomeSingle",{success:Wt,failed:ls.length}):e("gitView.toast.revertedSomePlural",{success:Wt,failed:ls.length}))}}finally{at(Wt=>{const Ks=new Set(Wt);return ze.forEach(Bn=>Ks.delete(Bn)),Ks}),ke&&Le(!1)}},[te,r,n,$t,gs,ot,on,e]),di=i.useCallback(async Y=>{await un(Y,!0)},[un]),Br=i.useCallback(async Y=>{await un(Y,!1,"working")},[un]),Cr=i.useCallback((Y,ke)=>{if(r&&!Ne){J(r,Y,ke);return}H(Y,ke),Ne&&q(!1)},[r,Ne,H,J,q]),Mi=i.useCallback(()=>Ue(!0),[]),ui=i.useMemo(()=>{const Y=[];return on.length>0&&Y.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:on,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:ke=>e("gitView.changes.unstageFileAria",{path:ke}),onActionFile:ke=>{Pn([ke],"unstage")},onActionAll:ke=>{Pn(ke,"unstage")},onViewDiff:ke=>Cr(ke,!0),onRevertFile:cr,showRevertActions:!1,accent:!0}),lr.length>0&&Y.push({id:"unstaged",title:e("gitView.changes.title"),entries:lr,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:ke=>e("gitView.changes.stageFileAria",{path:ke}),onActionFile:ke=>{Pn([ke],"stage")},onActionAll:ke=>{Pn(ke,"stage")},onViewDiff:ke=>Cr(ke,!1),onRevertFile:cr}),Y},[cr,Cr,Pn,on,e,lr]),Tn=i.useCallback(Y=>{if(Y.length===0)return;const ke=Y.map(Pe=>Pe.trim()).filter(Boolean);if(ke.length===0){es();return}Ie(Pe=>{const ze=Pe.trim(),dt=ze.length>0?`
11
-
12
- `:"";return`${ze}${dt}${ke.join(`
13
- `)}`.trim()}),es()},[es]),dr=i.useCallback((Y,ke)=>{const Pe=ke||Y;Ie(ze=>{const dt=ze.trimStart();return dt.startsWith(Y)||ke&&dt.startsWith(ke)?ze:`${Pe.endsWith(" ")?Pe:`${Pe} `}${ze}`.trimStart()}),ys(""),ne(!1)},[]),kn=i.useCallback(Y=>{const ke=Y instanceof Error?Y.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")},[]),Yn=i.useCallback((Y,ke)=>{Ct(Pe=>[...Pe,{message:Y,status:ke,timestamp:Date.now()}])},[]),gn=i.useCallback((Y,ke)=>{Ct(Pe=>{if(Pe.length===0)return Pe;const ze=[...Pe];return ze[ze.length-1]={...ze[ze.length-1],status:Y,...ke?{message:ke}:{}},ze})},[]),fi=i.useCallback(()=>{Ct([])},[]),Fi=i.useCallback(()=>{Ct([]),Je(null)},[]),On=i.useCallback(Y=>{const ke=Y.trim(),Pe=new Set(rs.map(dt=>dt.name)),ze=ke.indexOf("/");if(ze>0){const dt=ke.slice(0,ze),yt=ke.slice(ze+1);if(Pe.has(dt)&&yt)return{branch:ke,remote:dt,remoteBranch:yt}}for(const dt of rs){const yt=`${dt.name}/${ke}`;if(os.includes(yt))return{branch:yt,remote:dt.name,remoteBranch:ke}}return{branch:ke,remote:null,remoteBranch:null}},[rs,os]),mi=i.useCallback(async Y=>{if(!r)return;Je("merge"),fi();const ke=v?.current,Pe=On(Y);try{Pe.remote&&Pe.remoteBranch&&(Yn(`Fetching ${Pe.remote}/${Pe.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Pe.remote,branch:Pe.remoteBranch}),gn("done",`Fetched ${Pe.remote}/${Pe.remoteBranch}`)),Yn(`Merging ${Pe.branch} into ${ke}...`,"running");const ze=await n.merge(r,{branch:Pe.branch});ze.conflict?(gn("error","Merge conflicts detected"),fs(ze.conflictFiles??[]),ms("merge"),mt(!0),ps(r,ze.conflictFiles??[],"merge")):(gn("done",`Merged ${Pe.branch} into ${ke}`),hs(),Yn("Refreshing repository status...","running"),await gs(),await Ps(),gn("done","Repository status updated"))}catch(ze){if(kn(ze))gn("error","Uncommitted changes detected"),Is("merge"),Sr(Pe.branch),Ws(!0);else{const dt=ze instanceof Error?ze.message:`Failed to merge ${Pe.branch}`;gn("error",dt)}}},[r,n,v,On,gs,Ps,kn,ps,hs,Yn,gn,fi]),Xs=i.useCallback(async Y=>{if(!r)return;Je("rebase"),fi();const ke=v?.current,Pe=On(Y);try{Pe.remote&&Pe.remoteBranch&&(Yn(`Fetching ${Pe.remote}/${Pe.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Pe.remote,branch:Pe.remoteBranch}),gn("done",`Fetched ${Pe.remote}/${Pe.remoteBranch}`)),Yn(`Rebasing ${ke} onto ${Pe.branch}...`,"running");const ze=await n.rebase(r,{onto:Pe.branch});ze.conflict?(gn("error","Rebase conflicts detected"),fs(ze.conflictFiles??[]),ms("rebase"),mt(!0),ps(r,ze.conflictFiles??[],"rebase")):(gn("done",`Rebased ${ke} onto ${Pe.branch}`),hs(),Yn("Refreshing repository status...","running"),await gs(),await Ps(),gn("done","Repository status updated"))}catch(ze){if(kn(ze))gn("error","Uncommitted changes detected"),Is("rebase"),Sr(Pe.branch),Ws(!0);else{const dt=ze instanceof Error?ze.message:`Failed to rebase onto ${Pe.branch}`;gn("error",dt)}}},[r,n,v,On,gs,Ps,kn,ps,hs,Yn,gn,fi]),ur=i.useCallback(async()=>{if(r)try{ks==="merge"?(await n.abortMerge(r),de.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),de.success(e("gitView.toast.rebaseAborted"))),hs(),await gs(),await Ps()}catch(Y){const ke=Y instanceof Error?Y.message:`Failed to abort ${ks}`;de.error(ke)}},[r,n,ks,gs,Ps,hs,e]),hi=i.useMemo(()=>v?.files?v.files.some(Y=>Y.index==="U"||Y.working_dir==="U"||Y.index==="A"&&Y.working_dir==="A"||Y.index==="D"&&Y.working_dir==="D"):!1,[v?.files]),Li=i.useCallback(async()=>{if(r)try{const Y=!!v?.mergeInProgress?.head,ke=!!(v?.rebaseInProgress?.headName||v?.rebaseInProgress?.onto);if(Y){const Pe=await n.continueMerge(r);Pe.conflict?(fs(Pe.conflictFiles??[]),ms("merge"),mt(!0),ps(r,Pe.conflictFiles??[],"merge"),de.error(e("gitView.toast.mergeConflictsDetected"))):(hs(),de.success(e("gitView.toast.mergeCompleted")),await gs(),await Ps())}else if(ke){const Pe=await n.continueRebase(r);Pe.conflict?(fs(Pe.conflictFiles??[]),ms("rebase"),mt(!0),ps(r,Pe.conflictFiles??[],"rebase"),de.error(e("gitView.toast.rebaseConflictsDetected"))):(hs(),de.success(e("gitView.toast.rebaseStepCompleted")),await gs(),await Ps())}}catch(Y){const ke=Y instanceof Error?Y.message:e("gitView.toast.continueOperationFailed");de.error(ke)}},[r,n,v,gs,Ps,ps,hs,e]),qr=i.useCallback(async()=>{if(r)try{!!v?.mergeInProgress?.head?(await n.abortMerge(r),de.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),de.success(e("gitView.toast.rebaseAborted"))),hs(),await gs(),await Ps()}catch(Y){const ke=Y instanceof Error?Y.message:e("gitView.toast.abortOperationFailed");de.error(ke)}},[r,n,v,gs,Ps,hs,e]),pi=i.useCallback(()=>{if(!r)return;const ke=!!v?.mergeInProgress?.head?"merge":"rebase",Pe=v?.files?.filter(ze=>ze.index==="U"||ze.working_dir==="U").map(ze=>ze.path)??[];Pe.length>0&&fs(Pe),ms(ke),mt(!0)},[r,v]),Zs=i.useCallback(async Y=>{if(!r)return;const ke=v?.current,Pe=cn,ze=sr,dt=(v?.files??[]).some(wu);try{await n.stash(r,{message:`Auto-stash before ${Pe} with ${ze}`,includeUntracked:!0}),dt&&te(r)}catch(Wt){const Ks=Wt instanceof Error?Wt.message:"Failed to stash changes";de.error(Ks);return}let yt=!1,ls=!1;try{if(Pe==="merge"){const Wt=await n.merge(r,{branch:ze});Wt.conflict?(ls=!0,fs(Wt.conflictFiles??[]),ms("merge"),mt(!0)):(yt=!0,de.success(e("gitView.toast.mergedIntoBranch",{branch:ze,currentBranch:ke||""})))}else{const Wt=await n.rebase(r,{onto:ze});Wt.conflict?(ls=!0,fs(Wt.conflictFiles??[]),ms("rebase"),mt(!0)):(yt=!0,de.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:ke||"",branch:ze})))}if(Y&&yt)try{await n.stashPop(r),te(r),de.success(e("gitView.toast.stashedRestored"))}catch(Wt){const Ks=Wt instanceof Error?Wt.message:e("gitView.toast.restoreStashFailed");de.error(Ks)}else Y&&ls&&de.info(e("gitView.toast.restoreStashManually"));await gs(),await Ps()}catch(Wt){if(Y)try{await n.stashPop(r),te(r)}catch{}throw Wt}},[te,r,n,v,cn,sr,gs,Ps,e]),Oi=i.useCallback(Y=>{pt(Y),r&&(K(r,Y),Q(r,n,Y))},[r,Q,n,K]),uo=i.useCallback(Y=>{qe(Y)},[]),fo=i.useCallback(()=>{Ns(null),r&&(Z(r,n),se(r,n),Q(r,n,rt))},[r,Z,se,Q,rt,n]),Bi=i.useCallback(Y=>{if(Y.conflict){if(Y.operation==="cherry-pick"||Y.operation==="revert"){de.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:Y.conflictFiles?.join(", ")??"unknown files"})}),r&&(Z(r,n),se(r,n),Q(r,n,rt));return}fs(Y.conflictFiles??[]),ms(Y.operation),mt(!0),r&&ps(r,Y.conflictFiles??[],Y.operation)}},[e,fs,ms,mt,ps,r,Z,se,Q,rt,n]);return r?k===null||k===!0&&!v?s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):k===!1?W?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(I,{name:"loader-4",className:"mb-3 size-6 animate-spin text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.worktreeSetupInProgress")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.worktreeSetupDescription")})]}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(I,{name:"git-branch",className:"mb-3 size-6 text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.notGitRepository")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.notGitRepositoryDescription")}),A.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:De("flex h-full flex-col overflow-hidden"),children:[s.jsx(Tx,{status:v,localBranches:At,remoteBranches:os,branchInfo:T?.branches,syncAction:me,remotes:rs,onFetch:Y=>Kr("fetch",Y),onSync:Y=>Kr("sync",Y),onRemoveRemote:Lr,removingRemoteName:jn,onCheckoutBranch:st,onCreateBranch:pn,onRenameBranch:X,activeIdentityProfile:Dn,availableIdentities:Gs,onSelectIdentity:ht,isApplyingIdentity:jt,isWorktreeMode:!!O,onOpenHistory:()=>Ns("history"),onOpenGraph:()=>Ns("graph"),onOpenStashes:Mi,actionTabItems:js,activeActionTab:Ds,onSelectActionTab:Y=>mn(Y)}),r&&(v?.mergeInProgress?.head||v?.rebaseInProgress?.headName||v?.rebaseInProgress?.onto)&&s.jsx(Fw,{mergeInProgress:v?.mergeInProgress,rebaseInProgress:v?.rebaseInProgress,onContinue:Li,onAbort:qr,onResolveWithAI:pi,hasUnresolvedConflicts:hi,isLoading:R}),s.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:s.jsx("div",{className:"h-full min-h-0 flex flex-col",children:s.jsx("div",{className:De("min-w-0 min-h-0 h-full flex flex-col"),children:s.jsxs(Wn,{as:za,ref:P,outerClassName:"flex-1 min-h-0",className:De("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[Ds==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(Sn?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(Rx,{groups:ui,diffStats:v?.diffStats,revertingPaths:ot,isRevertingAll:$t,onVisiblePathsChange:Fe,onRevertAll:di,onRevertDirectory:Br,headerBackgroundClassName:"bg-background"})}),s.jsx(Ex,{stagedCount:Nr,commitMessage:$,onCommitMessageChange:Ie,generatedHighlights:Gt,onInsertHighlights:Tn,onGenerateMessage:Rs,isGeneratingMessage:xt,onCommit:()=>xs({pushAfter:!1}),onCommitAndPush:()=>xs({pushAfter:!0}),commitAction:Ke,hasPendingIndexMutation:qt,gitmojiEnabled:be,onOpenGitmojiPicker:()=>ne(!0)})]}):s.jsx(By,{onOpenStashes:()=>Ue(!0)})}):null,Ds==="branch"?s.jsx("div",{className:"space-y-4",children:Ln?s.jsxs(s.Fragment,{children:[s.jsx(Lw,{mode:"inline",currentBranch:v?.current,localBranches:At,remoteBranches:os,defaultTargetBranch:Es,onMerge:mi,onRebase:Xs,disabled:kr,isOperating:we!==null,operationLogs:vt,onOperationComplete:Fi}),In?s.jsx(Ly,{repoRoot:In.repoRoot,sourceBranch:In.sourceBranch,worktreeMetadata:In.worktreeMetadata,localBranches:At,defaultTargetBranch:Jt,refreshKey:et,onRefresh:()=>{r&&(Z(r,n),se(r,n),Q(r,n,rt))}},In.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,Ds==="pr"?s.jsx("div",{className:"space-y-4",children:Nn?s.jsx(Cw,{directory:Nn.directory,branch:Nn.branch,baseBranch:ds,trackingBranch:v?.tracking??void 0,remotes:Js,remoteBranches:os,onGeneratedDescription:Xt}):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(Os,{open:_t!==null,onOpenChange:Y=>{Y||Ns(null)},children:s.jsxs(Ls,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(Us,{children:[s.jsx(_s,{children:e(_t==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(an,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(Ky,{mode:_t==="graph"?"graph":"history",log:_t==="graph"?Hs??E:E,isLogLoading:_t==="graph"&&hn||L,logMaxCount:_t==="graph"?An:rt,onLogMaxCountChange:_t==="graph"?uo:Oi,expandedCommitHashes:Zt,onToggleCommit:gr,commitFilesMap:bt,loadingCommitHashes:It,onCopyHash:nr,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:_t==="graph"?null:Ye,onConflict:_t==="graph"?Bi:void 0,onActionSuccess:_t==="graph"?fo:void 0})})]})}),s.jsx(Oy,{open:Be,onOpenChange:Ue,directory:r,hasUncommittedChanges:(v?.files?.length??0)>0,hasStagedChanges:on.length>0,uncommittedFileCount:v?.files?.length??0,onChanged:async Y=>{r&&Y?.affectsIndex&&te(r),await gs(!1),await Ps()}}),s.jsx(Os,{open:Ce,onOpenChange:ne,children:s.jsxs(Ls,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(Us,{className:"px-4 pt-4",children:s.jsx(_s,{children:e("gitView.gitmoji.title")})}),s.jsxs(Oa,{className:"h-[420px]",children:[s.jsx(Ba,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:Ss,onValueChange:ys}),s.jsxs(Va,{children:[s.jsx(_a,{children:e("gitView.gitmoji.empty")}),s.jsx(ii,{children:(ye.length===0?[]:ye.filter(Y=>{const ke=Ss.trim().toLowerCase();return ke?Y.emoji.includes(ke)||Y.code.toLowerCase().includes(ke)||Y.description.toLowerCase().includes(ke):!0})).map(Y=>s.jsxs(ai,{onSelect:()=>dr(Y.emoji,Y.code),children:[s.jsx("span",{className:"text-lg",children:Y.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Y.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:Y.description})]},Y.code))})]})]})]})}),r&&s.jsx(Aw,{open:zt,onOpenChange:mt,conflictFiles:cs,directory:r,operation:ks,onAbort:ur,onClearState:hs}),s.jsx(Mw,{open:rn,onOpenChange:Ws,operation:cn,targetBranch:sr,onConfirm:Zs})]}):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")})})},Jl=5e3,Jw=(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},yl=(t,e)=>Zp(eg.getState().dictionary,t,e),Xw=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"},Zw=async(t,e)=>{if(t.readFile)return(await t.readFile(e,{optional:!0})).content??"";const n=new URLSearchParams({path:e,optional:"true"}),r=await As(`/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()},Fc=async(t,e)=>{try{const n=await Zw(t,e);return Jw(n,Jl)>Jl?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:Xw(n)}}},Lc=t=>{if(t==="too-large"){const e=Jl.toLocaleString(Zi());return yl("contextFileOpen.failure.tooLarge",{count:e})}return yl(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},ev=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Mn=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},Im=(t,e)=>{const n=Mn(e),r=Mn(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},tv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),sv=new Set(["node_modules"]),nv=t=>sv.has(t),rv=t=>{const e=Mn(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},iv=8,Ir=new Map,ov=t=>{const e=Ir.get(t);return e?(e.touchedAt=Date.now(),Ir.delete(t),Ir.set(t,e),e):null},wl=t=>{const e=Ir.get(t);if(e)return e.touchedAt=Date.now(),e;if(Ir.size>=iv){const r=Ir.keys().next().value;r!==void 0&&Ir.delete(r)}const n={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Ir.set(t,n),n},av=t=>{Ir.delete(t)},Pm=(t,e)=>s.jsx(Ur,{filePath:t,extension:e}),lv=t=>{const e=gt.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},cv=t=>{const e=gt.c(73),{node:n,root:r,isExpanded:o,isActive:a,status:c,badge:l,permissions:d,downloadFile:u,onSelect:m,onToggle:f,onRevealPath:g,onOpenDialog:y}=t,{t:p}=kt(),x=n.type==="directory",{canRename:b,canCreateFile:h,canCreateFolder:N,canDelete:w,canReveal:S}=d,[j,k]=i.useState(!1),[v,D]=i.useState(!1);let A;e[0]!==h||e[1]!==N||e[2]!==w||e[3]!==b||e[4]!==S?(A=H=>{!b&&!h&&!N&&!w&&!S||(H?.preventDefault(),D(!0))},e[0]=h,e[1]=N,e[2]=w,e[3]=b,e[4]=S,e[5]=A):A=e[5];const C=A;let O;e[6]!==x||e[7]!==n||e[8]!==m||e[9]!==f?(O=()=>{x?f(n.path):m(n)},e[6]=x,e[7]=n,e[8]=m,e[9]=f,e[10]=O):O=e[10];const T=O;let E;e[11]===Symbol.for("react.memo_cache_sentinel")?(E=H=>{H.stopPropagation(),D(!1),k(!0)},e[11]=E):E=e[11];const F=E;let R;e[12]!==h||e[13]!==N||e[14]!==w||e[15]!==b||e[16]!==S||e[17]!==u||e[18]!==x||e[19]!==n||e[20]!==y||e[21]!==g||e[22]!==p?(R=H=>{const{Item:q,Separator:ae}=H;return s.jsxs(s.Fragment,{children:[b&&s.jsxs(q,{onClick:le=>{le.stopPropagation(),y("rename",n)},children:[s.jsx(I,{name:"edit",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.rename")]}),s.jsxs(q,{onClick:le=>{le.stopPropagation(),pr(n.path).then(Se=>{if(Se.ok){de.success(p("sidebarFilesTree.toast.pathCopied"));return}de.error(p("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.copyPath")]}),!x&&u&&s.jsxs(q,{onClick:le=>{le.stopPropagation(),u(n.path).catch(Se=>{console.error("Download failed:",Se),de.error(p("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(I,{name:"download",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.save")]}),S&&s.jsxs(q,{onClick:le=>{le.stopPropagation(),g(n.path)},children:[s.jsx(I,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",p(vc())]}),x&&(h||N)&&s.jsxs(s.Fragment,{children:[s.jsx(ae,{}),h&&s.jsxs(q,{onClick:le=>{le.stopPropagation(),y("createFile",n)},children:[s.jsx(I,{name:"file-add",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.newFile")]}),N&&s.jsxs(q,{onClick:le=>{le.stopPropagation(),y("createFolder",n)},children:[s.jsx(I,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.newFolder")]})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx(ae,{}),s.jsxs(q,{onClick:le=>{le.stopPropagation(),y("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.delete")]})]})]})},e[12]=h,e[13]=N,e[14]=w,e[15]=b,e[16]=S,e[17]=u,e[18]=x,e[19]=n,e[20]=y,e[21]=g,e[22]=p,e[23]=R):R=e[23];const L=R;let B;e[24]!==n.path||e[25]!==r?(B=H=>{const q=Im(r,n.path);!q||q==="."||(H.dataTransfer.setData("application/x-openchamber-file-path",q),H.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=B):B=e[26];const V=B;let M;e[27]!==C?(M=s.jsx("div",{className:"group relative flex items-center",onContextMenu:C}),e[27]=C,e[28]=M):M=e[28];const Z=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let se;e[29]!==Z?(se=De("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",Z,"cursor-grab active:cursor-grabbing"),e[29]=Z,e[30]=se):se=e[30];let Q;e[31]!==x||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(Q=x?o?s.jsx(I,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(I,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Pm(n.path,n.extension),e[31]=x,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=Q):Q=e[35];let K;e[36]!==n.name||e[37]!==n.path?(K=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]=K):K=e[38];let ee;e[39]!==x||e[40]!==c?(ee=!x&&c&&s.jsx(lv,{status:c}),e[39]=x,e[40]=c,e[41]=ee):ee=e[41];let re;e[42]!==l||e[43]!==x?(re=x&&l&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[l.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",l.modified]}),l.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",l.added]})]}),e[42]=l,e[43]=x,e[44]=re):re=e[44];let he;e[45]!==C||e[46]!==V||e[47]!==T||e[48]!==K||e[49]!==ee||e[50]!==re||e[51]!==se||e[52]!==Q?(he=s.jsxs("button",{type:"button",onClick:T,onContextMenu:C,draggable:!0,onDragStart:V,className:se,children:[Q,K,ee,re]}),e[45]=C,e[46]=V,e[47]=T,e[48]=K,e[49]=ee,e[50]=re,e[51]=se,e[52]=Q,e[53]=he):he=e[53];let je;e[54]!==h||e[55]!==N||e[56]!==w||e[57]!==b||e[58]!==S||e[59]!==j||e[60]!==L||e[61]!==p?(je=(b||h||N||w||S)&&s.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:s.jsxs(nn,{open:j,onOpenChange:k,children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:F,title:p("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":p("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(I,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:p("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(sn,{align:"end",side:"bottom",onCloseAutoFocus:()=>k(!1),children:L({Item:bs,Separator:Rr})})]})}),e[54]=h,e[55]=N,e[56]=w,e[57]=b,e[58]=S,e[59]=j,e[60]=L,e[61]=p,e[62]=je):je=e[62];let te;e[63]!==he||e[64]!==je||e[65]!==M?(te=s.jsxs(Ic,{render:M,children:[he,je]}),e[63]=he,e[64]=je,e[65]=M,e[66]=te):te=e[66];let Ne;e[67]!==L?(Ne=s.jsx(Ac,{className:"min-w-[180px]",children:L({Item:Dc,Separator:um})}),e[67]=L,e[68]=Ne):Ne=e[68];let J;return e[69]!==v||e[70]!==te||e[71]!==Ne?(J=s.jsxs(Pc,{open:v,onOpenChange:D,children:[te,Ne]}),e[69]=v,e[70]=te,e[71]=Ne,e[72]=J):J=e[72],J},dv=(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,uv=i.memo(cv,dv),fv=()=>{const{t}=kt(),{files:e}=er(),n=ci()??"",r=Mn(n.trim()),o=Df(),a=If(),c=cc(W=>W.searchFiles),l=Ee(W=>W.openContextFile),d=Wa(n),[u,m]=i.useState(""),f=Ha(u,200),g=i.useRef(null),[y,p]=i.useState([]),[x,b]=i.useState(!1),[h,N]=i.useState({}),[w,S]=i.useState({}),j=i.useRef(new Set),k=i.useRef(new Set);i.useEffect(()=>{if(!r){N({}),S({}),j.current=new Set;return}const W=ov(r);W?(N({...W.childrenByDir}),S({...W.loadErrorsByDir}),j.current=new Set(W.loadedDirs)):(N({}),S({}),j.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const W=wl(r);W.childrenByDir=h},[r,h]),i.useEffect(()=>{if(!r)return;const W=wl(r);W.loadErrorsByDir=w},[r,w]),i.useEffect(()=>{if(!r)return;const W=wl(r);W.loadedDirs=new Set(j.current)},[r,h,w]),i.useEffect(()=>()=>{if(!r)return;const W=Ir.get(r);W&&W.loadedDirs.size===0&&Object.keys(W.childrenByDir).length===0&&av(r)},[r]);const v=i.useMemo(()=>[],[]),D=i.useMemo(()=>[],[]),A=yn(W=>r?W.byRoot[r]?.expandedPaths??v:v),C=yn(W=>r?W.byRoot[r]?.selectedPath??null:null),O=yn(W=>W.setSelectedPath),T=yn(W=>W.addOpenPath),E=yn(W=>W.removeOpenPathsByPrefix),F=yn(W=>W.toggleExpandedPath),R=Ee(W=>r?W.contextPanelByDirectory[r]?.tabs??D:D),L=i.useMemo(()=>new Set(R.map(W=>W.mode==="file"?W.targetPath:null).filter(W=>typeof W=="string"&&W.length>0).map(W=>Mn(W))),[R]),[B,V]=i.useState(null),[M,Z]=i.useState(null),[se,Q]=i.useState(""),[K,ee]=i.useState(!1),re=!!e.writeFile,he=!!e.createDirectory,je=!!e.rename,te=!!e.delete,Ne=!!e.revealPath,J=i.useMemo(()=>({canRename:je,canCreateFile:re,canCreateFolder:he,canDelete:te,canReveal:Ne}),[je,re,he,te,Ne]),H=i.useCallback(W=>{e.revealPath&&e.revealPath(W).catch(()=>{de.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),q=i.useCallback((W,z)=>{V(W),Z(z),Q(W==="rename"&&z.name||""),ee(!1)},[]),ae=i.useCallback((W,z)=>{const be=z.filter(xe=>xe&&typeof xe.name=="string"&&xe.name.length>0).filter(xe=>o||!xe.name.startsWith(".")).filter(xe=>a||!nv(xe.name)).map(xe=>{const _=xe.name,ye=Mn(xe.path||""),$=ye?tv(ye)?ye:Mn(`${W}/${ye}`):Mn(`${W}/${_}`),Ie=xe.isDirectory?"directory":"file",ve=Ie==="file"&&_.includes(".")?_.split(".").pop()?.toLowerCase():void 0;return{name:_,path:$,type:Ie,extension:ve}});return ev(be)},[a,o]),le=i.useCallback(async(W,z)=>{const be=Mn(W.trim());if(!be||j.current.has(be)||k.current.has(be))return;k.current=new Set(k.current),k.current.add(be);const xe=e.listDirectory?e.listDirectory(be).then(_=>_.entries.map(ye=>({name:ye.name,path:ye.path,isDirectory:ye.isDirectory}))):zn.listLocalDirectory(be).then(_=>_.map(ye=>({name:ye.name,path:ye.path,isDirectory:ye.isDirectory})));try{const _=await xe;if(z?.())return;const ye=ae(be,_);j.current=new Set(j.current),j.current.add(be),S($=>{if(!$[be])return $;const Ie={...$};return delete Ie[be],Ie}),N($=>({...$,[be]:ye}))}catch(_){if(z?.())return;const ye=_ instanceof Error?_.message:String(_??"");console.error("Failed to load sidebar directory:",_),S($=>({...$,[be]:ye}))}finally{k.current=new Set(k.current),k.current.delete(be)}},[e,ae]),Se=i.useCallback(async()=>{r&&(j.current=new Set,k.current=new Set,S({}),N(W=>Object.keys(W).length===0?W:{}),await le(r))},[le,r]),Re=i.useCallback(async W=>{if(!W){await Se();return}const z=Mn(W);j.current=new Set(j.current),j.current.delete(z),k.current=new Set(k.current),k.current.delete(z),await le(z)},[le,Se]);i.useEffect(()=>{r&&(j.current=new Set,k.current=new Set,S({}),N(W=>Object.keys(W).length===0?W:{}),le(r))},[le,r,o,a]),i.useEffect(()=>{if(!r||A.length===0)return;const W=A.map(xe=>Mn(xe)).filter(xe=>!!xe&&xe!==r&&xe.startsWith(`${r}/`)&&!j.current.has(xe)&&!k.current.has(xe)).sort((xe,_)=>xe.split("/").length-_.split("/").length);if(W.length===0)return;let z=!1;const be=()=>z;return(async()=>{for(let xe=0;xe<W.length&&!z;xe+=3){const _=W.slice(xe,xe+3);await Promise.all(_.map(ye=>le(ye,be)))}})(),()=>{z=!0}},[A,le,r]),i.useEffect(()=>{if(!n){p([]),b(!1);return}const W=f.trim();if(!W){p([]),b(!1);return}let z=!1;return b(!0),c(n,W,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(be=>{if(z)return;const _=be.filter(ye=>a||!rv(ye.path)).map(ye=>({name:ye.name,path:Mn(ye.path),type:"file",extension:ye.extension,relativePath:ye.relativePath}));p(_)}).catch(()=>{z||p([])}).finally(()=>{z||b(!1)}),()=>{z=!0}},[n,f,c,o,a]);const _e=i.useMemo(()=>{const W=new Map;if(!d?.files)return W;for(const z of d.files)z.index==="A"||z.working_dir==="?"?W.set(z.path,"git-added"):z.index==="D"?W.set(z.path,"git-deleted"):(z.index==="M"||z.working_dir==="M")&&W.set(z.path,"git-modified");return W},[d]),Oe=i.useMemo(()=>{const W=new Map;if(!d?.files||!r)return W;for(const z of d.files){const be=z.index==="M"||z.working_dir==="M",xe=z.index==="A"||z.working_dir==="?";if(!be&&!xe)continue;const _=z.path.split("/");if(_.length<=1)continue;let ye=r;for(let $=0;$<_.length-1;$++){ye=`${ye}/${_[$]}`;let Ie=W.get(ye);Ie||(Ie={modified:0,added:0},W.set(ye,Ie)),be&&Ie.modified++,xe&&Ie.added++}}return W},[d,r]),Me=i.useCallback(W=>{if(L.has(W))return"open";if(_e.size===0)return null;const z=W.startsWith(r+"/")?W.slice(r.length+1):W;return _e.get(z)??null},[L,_e,r]),ge=i.useCallback(W=>{if(Oe.size===0)return null;const z=Oe.get(W);return z&&z.modified+z.added>0?z:null},[Oe]),Ae=i.useCallback(async W=>{if(!r)return;const z=await Fc(e,W.path);if(!z.ok){de.error(Lc(z.reason));return}O(r,W.path),T(r,W.path),l(r,W.path)},[T,e,l,r,O]),pe=i.useCallback(async W=>{const z=Mn(W);r&&(F(r,z),j.current.has(z)||await le(z))},[le,r,F]),ue=i.useCallback(async W=>{if(W?.preventDefault(),!M||!B)return;ee(!0);const z=()=>ee(!1),be=()=>V(null);if(B==="createFile"){if(!se.trim()){de.error(t("sidebarFilesTree.toast.filenameRequired")),z();return}if(!e.writeFile){de.error(t("sidebarFilesTree.toast.writeNotSupported")),z();return}const xe=M.path,_=xe?`${xe}/`:"",ye=Mn(`${_}${se.trim()}`);await e.writeFile(ye,"").then(async $=>{$.success&&(de.success(t("sidebarFilesTree.toast.fileCreated")),await Re(xe)),be()}).catch(()=>de.error(t("sidebarFilesTree.toast.operationFailed"))).finally(z);return}if(B==="createFolder"){if(!se.trim()){de.error(t("sidebarFilesTree.toast.folderNameRequired")),z();return}const xe=M.path,_=xe?`${xe}/`:"",ye=Mn(`${_}${se.trim()}`);await e.createDirectory(ye).then(async $=>{$.success&&(de.success(t("sidebarFilesTree.toast.folderCreated")),await Re(xe)),be()}).catch(()=>de.error(t("sidebarFilesTree.toast.operationFailed"))).finally(z);return}if(B==="rename"){if(!se.trim()){de.error(t("sidebarFilesTree.toast.nameRequired")),z();return}if(!e.rename){de.error(t("sidebarFilesTree.toast.renameNotSupported")),z();return}const xe=M.path,_=xe.split("/").slice(0,-1).join("/"),ye=_?`${_}/`:"",$=Mn(`${ye}${se.trim()}`);await e.rename(xe,$).then(async Ie=>{Ie.success&&(de.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await Re(_),r&&E(r,xe),(C===xe||C&&C.startsWith(`${xe}/`))&&O(r,null)),be()}).catch(()=>de.error(t("sidebarFilesTree.toast.operationFailed"))).finally(z);return}if(B==="delete"){if(!e.delete){de.error(t("sidebarFilesTree.toast.deleteNotSupported")),z();return}const xe=M.path,_=xe.split("/").slice(0,-1).join("/");await e.delete(xe).then(async ye=>{ye.success&&(de.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await Re(_),r&&E(r,xe),(C===xe||C&&C.startsWith(xe+"/"))&&O(r,null)),be()}).catch(()=>de.error(t("sidebarFilesTree.toast.operationFailed"))).finally(z);return}z()},[B,M,se,e,Re,E,r,C,O,t]);function G(W,z){const be=h[W]??[];return be.map((xe,_)=>{const ye=xe.type==="directory",$=ye&&A.includes(xe.path),Ie=C===xe.path,ve=_===be.length-1;return s.jsxs("li",{className:"relative",children:[z>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(uv,{node:xe,root:r,isExpanded:$,isActive:Ie,status:ye?void 0:Me(xe.path),badge:ye?ge(xe.path):void 0,permissions:J,downloadFile:e.downloadFile,onSelect:Ae,onToggle:pe,onRevealPath:H,onOpenDialog:q}),ye&&$&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[w[xe.path]?s.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:w[xe.path],children:w[xe.path]}),s.jsxs($e,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Re(xe.path)},children:[s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,G(xe.path,z+1)]})]},xe.path)})}const fe=!!(r&&h[r]),ce=r?w[r]:null;return s.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(I,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(vn,{ref:g,value:u,onChange:W=>m(W.target.value),placeholder:t("sidebarFilesTree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),u.trim().length>0?s.jsx("button",{type:"button","aria-label":t("sidebarFilesTree.search.clearAria"),className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{m(""),g.current?.focus()},children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null]}),re&&s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>q("createFile",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFileTitle"),"aria-label":t("sidebarFilesTree.actions.newFileTitle"),children:s.jsx(I,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),he&&s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>q("createFolder",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFolderTitle"),"aria-label":t("sidebarFilesTree.actions.newFolderTitle"),children:s.jsx(I,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{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(I,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx(Wn,{outerClassName:"flex-1 min-h-0",className:"p-2",children:s.jsx("ul",{className:"flex flex-col",children:x?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):y.length>0?y.map(W=>{const z=C===W.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>Ae(W),draggable:!0,onDragStart:be=>{const xe=W.relativePath||Im(r??"",W.path);!xe||xe==="."||(be.dataTransfer.setData("application/x-openchamber-file-path",xe),be.dataTransfer.effectAllowed="copy")},className:De("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",z?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:W.path,children:[Pm(W.path,W.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:W.relativePath??W.path})]})},W.path)}):ce?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{children:ce}),s.jsxs($e,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{Se()},children:[s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):fe&&r?G(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx(Os,{open:!!B,onOpenChange:W=>!W&&V(null),children:s.jsxs(Ls,{children:[s.jsxs(Us,{children:[s.jsxs(_s,{children:[B==="createFile"&&t("sidebarFilesTree.dialog.createFile.title"),B==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.title"),B==="rename"&&t("sidebarFilesTree.dialog.rename.title"),B==="delete"&&t("sidebarFilesTree.dialog.delete.title")]}),s.jsxs(an,{children:[B==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:M?.path??t("sidebarFilesTree.dialog.rootFallback")}),B==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:M?.path??t("sidebarFilesTree.dialog.rootFallback")}),B==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:M?.name??""}),B==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:M?.name??""})]})]}),B!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(vn,{value:se,onChange:W=>Q(W.target.value),placeholder:t(B==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:W=>{W.key==="Enter"&&ue()},autoFocus:!0})}),s.jsxs(ar,{children:[s.jsx($e,{variant:"outline",onClick:()=>V(null),disabled:K,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx($e,{variant:B==="delete"?"destructive":"default",onClick:()=>{ue()},disabled:K||B!=="delete"&&!se.trim(),children:K?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):t(B==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},mv=t=>t==="git"||t==="files"||t==="context",hv="files",pv=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function gv(t,e,n,r){const o=gt.c(6),{git:a}=er(),c=wn(xv),l=!!(t&&a&&e&&n==="git"&&r!=="git");let d,u;o[0]!==t||o[1]!==c||o[2]!==a||o[3]!==l?(d=()=>{if(!l||!t||!a)return;c(t,a);const m=window.setInterval(()=>{pv()&&c(t,a)},1e4);return()=>window.clearInterval(m)},u=[l,t,a,c],o[0]=t,o[1]=c,o[2]=a,o[3]=l,o[4]=d,o[5]=u):(d=o[4],u=o[5]),i.useEffect(d,u)}function xv(t){return t.ensureStatus}const Tm=()=>{const t=gt.c(17),e=ws(yv),n=ws(wv),r=Qs(vv),o=wn(jv);let a;e:{if(e){let p;t[0]!==e||t[1]!==n?(p=n.find(x=>x.id===e)??n[0]??null,t[0]=e,t[1]=n,t[2]=p):p=t[2],a=p;break e}a=n[0]??null}const c=a;let l;e:{if(!c){l=null;break e}let p;t[3]!==c.id||t[4]!==c.path?(p={id:c.id,path:c.path},t[3]=c.id,t[4]=c.path,t[5]=p):p=t[5],l=p}const d=l;let u;e:{if(!c){u=null;break e}let p;t[6]!==c.label||t[7]!==c.path||t[8]!==r?(p=c.label?.trim()||Ei(c.path,r)||c.path,t[6]=c.label,t[7]=c.path,t[8]=r,t[9]=p):p=t[9],u=p}const m=u;let f;e:{if(!c){f=!1;break e}let p;t[10]!==c.path||t[11]!==o?(p=o.get(c.path)?.isGitRepo,t[10]=c.path,t[11]=o,t[12]=p):p=t[12],f=p===!0}const g=f;let y;return t[13]!==g||t[14]!==m||t[15]!==d?(y=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(py,{projectRef:d,projectLabel:m,canCreateWorktree:g})}),t[13]=g,t[14]=m,t[15]=d,t[16]=y):y=t[16],y},bv=()=>{const t=gt.c(57),{t:e}=kt(),n=Ee(Sv),r=Ee(Nv),o=Ee(kv),a=Ee(Cv),c=ci();gv(c,o,n,a);const l=a==="git"?"git":a==="context"?"context":null;let d,u;t[0]!==l||t[1]!==n||t[2]!==r?(d=()=>{l&&n===l&&r(hv)},u=[l,n,r],t[0]=l,t[1]=n,t[2]=r,t[3]=d,t[4]=u):(d=t[3],u=t[4]),i.useEffect(d,u);let m;t[5]!==e?(m=e("layout.rightSidebar.git"),t[5]=e,t[6]=m):m=t[6];let f;t[7]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5"}),t[7]=f):f=t[7];let g;t[8]!==m?(g={id:"git",label:m,icon:f},t[8]=m,t[9]=g):g=t[9];let y;t[10]!==e?(y=e("layout.rightSidebar.files"),t[10]=e,t[11]=y):y=t[11];let p;t[12]===Symbol.for("react.memo_cache_sentinel")?(p=s.jsx(I,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=p):p=t[12];let x;t[13]!==y?(x={id:"files",label:y,icon:p},t[13]=y,t[14]=x):x=t[14];let b;t[15]!==e?(b=e("layout.rightSidebar.context"),t[15]=e,t[16]=b):b=t[16];let h;t[17]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(I,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=h):h=t[17];let N;t[18]!==b?(N={id:"context",label:b,icon:h},t[18]=b,t[19]=N):N=t[19];let w;t[20]!==N||t[21]!==g||t[22]!==x?(w=[g,x,N],t[20]=N,t[21]=g,t[22]=x,t[23]=w):w=t[23];const S=w;let j;t[24]!==l||t[25]!==S?(j=l?S.filter(re=>re.id!==l):S,t[24]=l,t[25]=S,t[26]=j):j=t[26];const k=j,v=o&&n==="git"&&l!=="git";let D;t[27]!==r?(D=re=>{mv(re)&&r(re)},t[27]=r,t[28]=D):D=t[28];const A=D;let C;t[29]!==A||t[30]!==n||t[31]!==k?(C=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(To,{items:k,activeId:n,onSelect:A,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=A,t[30]=n,t[31]=k,t[32]=C):C=t[32];const O=n!=="git"&&"hidden";let T;t[33]!==O?(T=De("h-full",O),t[33]=O,t[34]=T):T=t[34];let E;t[35]!==v?(E=s.jsx(Ql,{isActive:v}),t[35]=v,t[36]=E):E=t[36];let F;t[37]!==T||t[38]!==E?(F=s.jsx("div",{className:T,children:E}),t[37]=T,t[38]=E,t[39]=F):F=t[39];const R=n!=="files"&&"hidden";let L;t[40]!==R?(L=De("h-full",R),t[40]=R,t[41]=L):L=t[41];let B;t[42]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(fv,{}),t[42]=B):B=t[42];let V;t[43]!==L?(V=s.jsx("div",{className:L,children:B}),t[43]=L,t[44]=V):V=t[44];const M=n!=="context"&&"hidden";let Z;t[45]!==M?(Z=De("h-full",M),t[45]=M,t[46]=Z):Z=t[46];let se;t[47]===Symbol.for("react.memo_cache_sentinel")?(se=s.jsx(Tm,{}),t[47]=se):se=t[47];let Q;t[48]!==Z?(Q=s.jsx("div",{className:Z,children:se}),t[48]=Z,t[49]=Q):Q=t[49];let K;t[50]!==F||t[51]!==V||t[52]!==Q?(K=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[F,V,Q]}),t[50]=F,t[51]=V,t[52]=Q,t[53]=K):K=t[53];let ee;return t[54]!==C||t[55]!==K?(ee=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[C,K]}),t[54]=C,t[55]=K,t[56]=ee):ee=t[56],ee};function yv(t){return t.activeProjectId}function wv(t){return t.projects}function vv(t){return t.homeDirectory}function jv(t){return t.directories}function Sv(t){return t.rightSidebarTab}function Nv(t){return t.setRightSidebarTab}function kv(t){return t.isRightSidebarOpen}function Cv(t){return t.activeMainTab}const Av=64,Dv=3,yi=new Map,Iv=(t,e,n=Dv)=>{const r=`${t}\0${n}\0${e}`,o=yi.get(r);if(o)return yi.delete(r),yi.set(r,o),o;const a=Tv(e),c=a?Ah(Dh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??ju(t):Ih(Pv(t,e))[0]?.files[0]??ju(t);for(yi.set(r,c);yi.size>Av;){const l=yi.keys().next().value;if(!l)break;yi.delete(l)}return c},Pv=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
14
- ===================================================================
15
- --- ${t}
16
- +++ ${t}
17
- ${e}`,Tv=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(t))return;const e=[...t.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(e.length!==1)return;const n=e[0],r=Number.parseInt(n[1]??"",10),o=Number.parseInt(n[2]??"",10);if(r>1||o>1||!Number.isFinite(r)||!Number.isFinite(o))return;const a=(n.index??0)+n[0].length,c=t.slice(a),l=[],d=[];let u;for(const m of c.split(/\r?\n/)){if(m.startsWith("diff --git ")||m.startsWith("@@ "))break;if(m.startsWith("\\")){if(u==="-"||u===" "){const f=l.at(-1);f&&(f.newline=!1)}if(u==="+"||u===" "){const f=d.at(-1);f&&(f.newline=!1)}continue}if(m.startsWith("-")){l.push({text:m.slice(1),newline:!0}),u="-";continue}if(m.startsWith("+")){d.push({text:m.slice(1),newline:!0}),u="+";continue}m.startsWith(" ")&&(l.push({text:m.slice(1),newline:!0}),d.push({text:m.slice(1),newline:!0}),u=" ")}return{before:vu(l),after:vu(d)}},vu=t=>t.map(e=>e.text+(e.newline?`
18
- `:"")).join(""),ju=t=>Ph({name:t,contents:""},{name:t,contents:""}),Rv=1100,Ev=15e3,Su=500,Nu=300,Mv=1e6,Fv=3,Lv=t=>t<=6?t:t<=12?6:t<=25?4:2,Ov=i.memo(()=>{const t=gt.c(4),{t:e}=kt();let n;t[0]!==e?(n=e("diffView.binary.unavailable"),t[0]=e,t[1]=n):n=t[1];let r;return t[2]!==n?(r=s.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:s.jsx("div",{className:"typography-meta text-muted-foreground",children:n})}),t[2]=n,t[3]=r):r=t[3],r}),Rm={"?":{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"}},Bv=Rm.M,Vv=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"},Em=t=>{const e=Vv(t);return Rm[e]??Bv},_v=t=>{const{index:e,working_dir:n}=t;return e==="A"||n==="A"||e==="?"||n==="?"},ku=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Cu=t=>!!t.working_dir?.trim()||t.index==="?",$v=(t,e)=>ng(t,e),Au=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Du=(t,e)=>{const n=t.split(`
19
- `),r=e.split(`
20
- `),o=Math.min(n.length,r.length);for(let a=0;a<o;a+=1)if(n[a]!==r[a])return a+1;return r.length>n.length?n.length+1:n.length>r.length?Math.max(1,r.length):1},zv=t=>{if(!t)return null;const e=t.match(/@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/m);if(!e)return null;const n=Number.parseInt(e[1],10);return!Number.isFinite(n)||n<1?null:n},Wv=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),Uv=(t,e,n)=>Wv(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:Iv(t,e),contextMode:n},Mm=(t,e,n)=>{const r=t??0,o=e??0;return!r&&!o?null:s.jsxs("span",{className:De("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]})},Hv=i.memo(t=>{const e=gt.c(43),{scope:n,workingCount:r,stagedCount:o,onScopeChange:a}=t,{t:c}=kt(),[l,d]=i.useState(!1),u=n==="staged"?o:r;let m;e[0]!==n||e[1]!==c?(m=c(n==="staged"?"diffView.scope.staged":"diffView.scope.changed"),e[0]=n,e[1]=c,e[2]=m):m=e[2];const f=m;let g;e[3]!==c?(g=c("diffView.scope.selectorAria"),e[3]=c,e[4]=g):g=e[4];let y;e[5]!==u?(y=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",u]}),e[5]=u,e[6]=y):y=e[6];let p;e[7]!==f||e[8]!==y?(p=s.jsxs("span",{className:"whitespace-nowrap",children:[f,y]}),e[7]=f,e[8]=y,e[9]=p):p=e[9];let x;e[10]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx(I,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=x):x=e[10];let b;e[11]!==g||e[12]!==p?(b=s.jsx(tn,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":g,children:[p,x]})}),e[11]=g,e[12]=p,e[13]=b):b=e[13];let h;e[14]!==a?(h=T=>{(T==="working"||T==="staged")&&(a?.(T),d(!1))},e[14]=a,e[15]=h):h=e[15];let N;e[16]!==c?(N=c("diffView.scope.changed"),e[16]=c,e[17]=N):N=e[17];let w;e[18]!==N?(w=s.jsx("span",{children:N}),e[18]=N,e[19]=w):w=e[19];let S;e[20]!==r?(S=s.jsx("span",{className:"typography-meta text-muted-foreground",children:r}),e[20]=r,e[21]=S):S=e[21];let j;e[22]!==S||e[23]!==w?(j=s.jsx(jd,{value:"working",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[w,S]})}),e[22]=S,e[23]=w,e[24]=j):j=e[24];let k;e[25]!==c?(k=c("diffView.scope.staged"),e[25]=c,e[26]=k):k=e[26];let v;e[27]!==k?(v=s.jsx("span",{children:k}),e[27]=k,e[28]=v):v=e[28];let D;e[29]!==o?(D=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=D):D=e[30];let A;e[31]!==v||e[32]!==D?(A=s.jsx(jd,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[v,D]})}),e[31]=v,e[32]=D,e[33]=A):A=e[33];let C;e[34]!==n||e[35]!==j||e[36]!==A||e[37]!==h?(C=s.jsx(sn,{align:"start",className:"w-40",children:s.jsxs(rg,{value:n,onValueChange:h,children:[j,A]})}),e[34]=n,e[35]=j,e[36]=A,e[37]=h,e[38]=C):C=e[38];let O;return e[39]!==l||e[40]!==C||e[41]!==b?(O=s.jsxs(nn,{open:l,onOpenChange:d,children:[b,C]}),e[39]=l,e[40]=C,e[41]=b,e[42]=O):O=e[42],O}),Gv=i.memo(t=>{const e=gt.c(11),{changedFiles:n,selectedFile:r,onSelectFile:o}=t,{t:a}=kt();if(n.length===0)return null;let c;if(e[0]!==n||e[1]!==o||e[2]!==r||e[3]!==a){let d;e[5]!==o||e[6]!==r||e[7]!==a?(d=u=>{const m=Em(u),f=r===u.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(u.path),className:De("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",f?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[s.jsx(Ur,{filePath:u.path,className:"h-3.5 w-3.5 flex-shrink-0"}),s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:m.color},title:a(m.descriptionKey),"aria-label":a(m.descriptionKey),children:m.code}),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:u.path,children:u.path}),Mm(u.insertions,u.deletions)]})},u.path)},e[5]=o,e[6]=r,e[7]=a,e[8]=d):d=e[8],c=n.map(d),e[0]=n,e[1]=o,e[2]=r,e[3]=a,e[4]=c}else c=e[4];let l;return e[9]!==c?(l=s.jsx(Wn,{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}),Kv=i.memo(t=>{const e=gt.c(20),{filePath:n,diff:r,renderSideBySide:o}=t,{t:a}=kt(),c=r.original.length>0,l=r.modified.length>0,d=o?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",u=o?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m={contain:"layout"},e[0]=m):m=e[0];let f;e[1]!==r.original||e[2]!==n||e[3]!==c||e[4]!==u||e[5]!==o||e[6]!==a?(f=c&&s.jsxs("div",{className:u,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a("diffView.image.original")}),s.jsx("img",{src:r.original,alt:a("diffView.image.originalAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[1]=r.original,e[2]=n,e[3]=c,e[4]=u,e[5]=o,e[6]=a,e[7]=f):f=e[7];let g;e[8]!==r.modified||e[9]!==n||e[10]!==l||e[11]!==c||e[12]!==u||e[13]!==o||e[14]!==a?(g=l&&s.jsxs("div",{className:u,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a(c?"diffView.image.modified":"diffView.image.new")}),s.jsx("img",{src:r.modified,alt:a("diffView.image.modifiedAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[8]=r.modified,e[9]=n,e[10]=l,e[11]=c,e[12]=u,e[13]=o,e[14]=a,e[15]=g):g=e[15];let y;return e[16]!==d||e[17]!==f||e[18]!==g?(y=s.jsx("div",{className:"w-full overflow-auto p-4",style:m,children:s.jsxs("div",{className:d,children:[f,g]})}),e[16]=d,e[17]=f,e[18]=g,e[19]=y):y=e[19],y}),qv=i.memo(t=>{const e=gt.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=Di(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(Ov,{}),e[2]=m):m=e[2],m}if(eo(n)){let m;return e[3]!==r||e[4]!==n||e[5]!==o?(m=s.jsx(Kv,{filePath:n,diff:r,renderSideBySide:o}),e[3]=r,e[4]=n,e[5]=o,e[6]=m):m=e[6],m}let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={contain:"layout"},e[7]=d):d=e[7];let u;return e[8]!==r.fileDiff||e[9]!==r.modified||e[10]!==r.original||e[11]!==n||e[12]!==l||e[13]!==o||e[14]!==a?(u=s.jsx("div",{className:"w-full",style:d,children:s.jsx(dm,{original:r.original,modified:r.modified,fileDiff:r.fileDiff,language:l,fileName:n,renderSideBySide:o,wrapLines:a,layout:"inline"})}),e[8]=r.fileDiff,e[9]=r.modified,e[10]=r.original,e[11]=n,e[12]=l,e[13]=o,e[14]=a,e[15]=u):u=e[15],u}),Yv=i.memo(t=>{const e=gt.c(7),{filePath:n,staged:r,busyAction:o,disabled:a,onAction:c}=t,{t:l}=kt();let d;return e[0]!==o||e[1]!==a||e[2]!==n||e[3]!==c||e[4]!==r||e[5]!==l?(d=s.jsx("div",{className:"flex items-center gap-0.5 rounded-full border border-[var(--interactive-border)]/45 bg-[var(--surface-background)]/95 px-1 py-0.5 shadow-lg backdrop-blur-md",children:r?s.jsx(vl,{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(vl,{label:l("gitView.changes.revertFileAria",{path:n}),icon:"arrow-go-back",loading:o==="discard",disabled:a,tone:"failure",onClick:()=>c("discard")}),s.jsx(vl,{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}),vl=t=>{const e=gt.c(14),{label:n,icon:r,loading:o,disabled:a,tone:c,onClick:l}=t,d=c==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",u=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let m;e[0]!==d||e[1]!==u?(m=De("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",d,u),e[0]=d,e[1]=u,e[2]=m):m=e[2];let f;e[3]!==l?(f=p=>{p.stopPropagation(),l()},e[3]=l,e[4]=f):f=e[4];let g;e[5]!==r||e[6]!==o?(g=o?s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(I,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=g):g=e[7];let y;return e[8]!==a||e[9]!==n||e[10]!==m||e[11]!==f||e[12]!==g?(y=s.jsx($e,{variant:"ghost",size:"sm",className:m,disabled:a,title:n,"aria-label":n,onClick:f,children:g}),e[8]=a,e[9]=n,e[10]=m,e[11]=f,e[12]=g,e[13]=y):y=e[13],y},Qv=i.memo(({directory:t,file:e,layout:n,wrapLines:r,isSelected:o,isExpanded:a,isMounted:c,onSelect:l,onExpandedChange:d,registerSectionRef:u,showOpenInEditorAction:m=!1,isOpeningInEditor:f=!1,onOpenInEditor:g,staged:y=!1,loadFullFiles:p=!1})=>{const{t:x}=kt(),{git:b}=er(),h=wn(i.useCallback(q=>q.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),N=wn(q=>q.setDiff),w=wn(q=>q.fetchStatus),S=Ee(q=>q.setDiffFileLayout),[j,k]=i.useState(0),[v,D]=i.useState(null),[A,C]=i.useState(!1),[O,T]=i.useState(null),[E,F]=i.useState(!1),[R,L]=i.useState(null),[B,V]=i.useState(null),M=i.useRef(null),Z=i.useRef(null),se=i.useMemo(()=>Em(e),[e]),Q=n==="side-by-side",K=p?"full":"patch",ee=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,re=i.useMemo(()=>y?B:R||(h?{original:h.original,modified:h.modified,isBinary:h.isBinary,contextMode:"full"}:null),[h,R,y,B]),he=re?.contextMode===K,je=i.useCallback(q=>{Z.current=q,u(e.path,q)},[e.path,u]),te=i.useCallback(q=>{d(e.path,q)},[e.path,d]),Ne=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{y?V(null):L(null),D(null),M.current=null},[ee,y]),i.useEffect(()=>{if(!a||!c)return;if(!t||re&&he){M.current=null,C(!1);return}const q=`${t}::${e.path}::${y?"staged":"unstaged"}::${ee}::${K}::${j}`;if(M.current===q)return;M.current=q,D(null),C(!0);let ae=!1;const le=p?Mv:Fv,Se=eo(e.path)?b.getGitFileDiff(t,{path:e.path,staged:y}):b.getGitDiff(t,{path:e.path,staged:y,contextLines:le}),Re=Ev,_e=new Promise((Oe,Me)=>{setTimeout(()=>Me(new Error(`Timed out after ${Re}ms`)),Re)});return Promise.race([Se,_e]).then(Oe=>{if(!ae){if("diff"in Oe){const Me=Uv(e.path,Oe.diff,K);y?V(Me):L(Me)}else{const Me={original:Oe.original??"",modified:Oe.modified??"",isBinary:Oe.isBinary,contextMode:"full"};y?V(Me):N(t,e.path,Me)}C(!1)}}).catch(Oe=>{if(ae)return;const Me=Oe instanceof Error?Oe.message:String(Oe);D(Me),C(!1)}),()=>{ae=!0,M.current===q&&(M.current=null)}},[K,re,he,j,t,e.path,ee,b,a,c,p,N,y]);const J=i.useCallback(()=>{te(!a),Ne()},[te,Ne,a]),H=i.useCallback(async q=>{if(!(!t||O!==null)){T(q);try{q==="stage"?await b.stageGitFile(t,e.path):q==="unstage"?await b.unstageGitFile(t,e.path):await b.revertGitFile(t,e.path,{scope:"working"}),k(ae=>ae+1),await w(t,b)}catch(ae){const le=q==="unstage"?"gitView.toast.unstageFileFailed":q==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";de.error(ae instanceof Error?ae.message:x(le))}finally{T(ae=>ae===q?null:ae)}}},[t,w,e.path,O,b,x]);return s.jsxs("div",{ref:je,className:"scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0",children:[s.jsx("div",{className:"sticky top-0 z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80",children:s.jsxs("div",{role:"button",tabIndex:0,onClick:J,onKeyDown:q=>{q.target===q.currentTarget&&(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),J())},className:De("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",o?"bg-[var(--interactive-selection)]/35":null),children:[s.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),s.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[s.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:a?s.jsx(I,{name:"arrow-down-s",className:"size-4"}):s.jsx(I,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:se.color},title:x(se.descriptionKey),"aria-label":x(se.descriptionKey),children:se.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(Ur,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const q=e.path.lastIndexOf("/");if(q===-1)return s.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:e.path});const ae=e.path.slice(0,q),le=e.path.slice(q+1);return s.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:ae}),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:le})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[Mm(e.insertions,e.deletions),m&&g?s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:x("diffView.actions.openFileInEditorAtChange"),onClick:q=>{q.stopPropagation(),g(e.path,re)},disabled:f,children:f?s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(I,{name:"edit",className:"size-3.5"})}):null,s.jsx(Gf,{mode:Q?"side-by-side":"unified",onModeChange:q=>{const ae=q==="side-by-side"?"side-by-side":"inline";S(e.path,ae)},className:"opacity-70"})]})]})}),a&&s.jsxs("div",{className:"relative bg-background overflow-hidden",children:[!c&&!v?s.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,v?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:x("diffView.state.failedToLoadDiff")}),s.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:v}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>k(q=>q+1),children:x("diffView.actions.retry")})]}):null,c&&A&&!re&&!v?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),x("diffView.state.loadingDiff")]}):null,c&&re&&!E&&e.insertions+e.deletions>Su?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:x("diffView.state.largeDiff",{count:e.insertions+e.deletions})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:x("diffView.state.largeDiffDescription")}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>F(!0),children:x("diffView.actions.renderAnyway")})]}):null,c&&re&&(E||e.insertions+e.deletions<=Su)?s.jsxs(s.Fragment,{children:[s.jsx(qv,{filePath:e.path,diff:re,renderSideBySide:Q,wrapLines:r}),s.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:s.jsx("div",{className:"pointer-events-auto",children:s.jsx(Yv,{filePath:e.path,staged:y,busyAction:O,disabled:O!==null,onAction:H})})})]}):null]})]})}),Fm=({hideStackedFileSidebar:t=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:n=!1,showOpenInEditorAction:r=!1,diffScope:o="all",onDiffScopeChange:a,targetFilePath:c=null,flushContent:l=!1})=>{const{t:d}=kt(),{git:u,files:m}=er(),f=ci(),{screenWidth:g,isMobile:y}=Er(),p=yc(f??null),x=Wa(f??null),b=wc(f??null),h=wn(Ve=>Ve.setActiveDirectory),N=wn(Ve=>Ve.ensureStatus),w=wn(Ve=>Ve.fetchStatus),S=wn(Ve=>Ve.setDiff),[j,k]=i.useState(null),[v,D]=i.useState(!1),[A,C]=i.useState(null),[O,T]=i.useState(()=>new Set),[E,F]=i.useState(()=>new Set),[R,L]=i.useState(!1),[B,V]=i.useState(0),[M,Z]=i.useState(!1),[se,Q]=i.useState(!1),K=Ee(Ve=>Ve.pendingDiffFile),ee=Ee(Ve=>Ve.pendingDiffStaged),re=Ee(Ve=>Ve.setPendingDiffFile),he=Ee(Ve=>Ve.diffLayoutPreference),je=Ee(Ve=>Ve.diffFileLayout),te=Ee(Ve=>Ve.setDiffFileLayout),Ne=Ee(Ve=>Ve.diffWrapLines),J=Ee(Ve=>Ve.setDiffWrapLines),H=Ee(Ve=>Ve.openContextFileAtLine),q=ut(Ve=>Ve.currentSessionId),ae=Ne,le=o==="staged"?!0:o==="working"?!1:null,Se=le??v,Re=y||g<=768,_e=!!q&&!Re&&!Hr(),Oe=!t&&!Re&&g>=1024,Me=i.useRef(null),ge=i.useRef(new Map),Ae=i.useRef(null),pe=i.useRef(null),ue=i.useRef(!1),G=i.useRef(null),fe=i.useRef(null),ce=i.useCallback(()=>{Ae.current=null,ue.current=!1,C(null),pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null)},[]),W=i.useCallback(Ve=>{T(Ze=>{if(Ze.has(Ve))return Ze;const nt=new Set(Ze);return nt.add(Ve),nt})},[]),z=i.useMemo(()=>{if(!x?.files)return[];const Ve=x.diffStats??{},Ze=o==="staged"?ku:o==="working"?Cu:()=>!0;return x.files.filter(Ze).map(nt=>({...nt,insertions:Ve[nt.path]?.insertions??0,deletions:Ve[nt.path]?.deletions??0,isNew:_v(nt)})).sort((nt,St)=>nt.path.localeCompare(St.path))},[o,x]),be=i.useMemo(()=>x?.files?x.files.filter(Cu).length:0,[x]),xe=i.useMemo(()=>x?.files?x.files.filter(ku).length:0,[x]),_=i.useMemo(()=>z.map(Ve=>Ve.path).join("\0"),[z]);i.useEffect(()=>{const Ve=_?_.split("\0"):[],Ze=new Set(Ve),nt=`${f??""}:${o}:${e?"collapsed":"default"}`,St=fe.current!==nt;fe.current=nt,T(Dt=>{if(St){const at=e?0:Lv(Ve.length);return new Set(Ve.slice(0,at))}let wt=!1;const ot=new Set;for(const at of Dt){if(!Ze.has(at)){wt=!0;continue}ot.add(at)}return wt?ot:Dt}),F(Dt=>{if(St)return new Set;let wt=!1;const ot=new Set;for(const at of Dt){if(!Ze.has(at)){wt=!0;continue}ot.add(at)}return wt?ot:Dt})},[_,o,f,e]);const ye=i.useCallback(()=>{G.current=null;const Ve=Me.current;if(!Ve)return;const Ze=Ve.getBoundingClientRect(),nt=Ze.top-Nu,St=Ze.bottom+Nu,Dt={};for(const[wt,ot]of ge.current){if(!ot||!O.has(wt))continue;const at=ot.getBoundingClientRect();at.bottom<nt||at.top>St||(Dt[wt]=!0)}F(wt=>{let ot=!1;const at=new Set(wt);for(const Kt of Object.keys(Dt))at.has(Kt)||(at.add(Kt),ot=!0);return ot?at:wt})},[O]),$=i.useCallback(()=>{typeof window>"u"||G.current===null&&(G.current=window.requestAnimationFrame(ye))},[ye]);i.useEffect(()=>{const Ve=Me.current;if(Ve)return $(),Ve.addEventListener("scroll",$,{passive:!0}),window.addEventListener("resize",$),()=>{Ve.removeEventListener("scroll",$),window.removeEventListener("resize",$),G.current!==null&&(window.cancelAnimationFrame(G.current),G.current=null)}},[z,O,$]);const Ie=i.useCallback(Ve=>{const Ze=je[Ve.path];if(Ze)return Ze;if(he==="inline")return"inline";if(he==="side-by-side")return"side-by-side";const nt=g<Rv;return Ve.isNew||nt?"inline":"side-by-side"},[je,he,g]),ve=i.useMemo(()=>z.length===0?null:z.every(Ve=>Ie(Ve)==="side-by-side")?"side-by-side":"inline",[z,Ie]);i.useEffect(()=>{f&&(h(f),N(f,u))},[f,h,N,u]),i.useEffect(()=>{if(f)return Pr.onGitRefreshHint(Ve=>{Au(Ve.directory)===Au(f)&&w(f,u)})},[f,w,u]),i.useEffect(()=>{o==="all"&&K&&(k(K),D(ee),re(null),ue.current=!0,Ae.current=K,W(K),V(Ve=>Ve+1))},[o,W,K,ee,re]),i.useEffect(()=>{if(o==="all")return;const Ve=c?.trim();Ve&&(k(Ve),D(o==="staged"),ue.current=!0,Ae.current=Ve,W(Ve),V(Ze=>Ze+1))},[o,W,c]),i.useEffect(()=>{if(!j)return;z.some(Ze=>Ze.path===j)||(k(null),D(!1))},[z,j]);const Fe=i.useCallback((Ve,Ze)=>{const nt=ge.current;Ze?nt.set(Ve,Ze):nt.delete(Ve),$()},[$]),Ce=i.useCallback((Ve,Ze)=>{ce(),T(nt=>{const St=nt.has(Ve);if(Ze===St)return nt;const Dt=new Set(nt);return Ze?Dt.add(Ve):Dt.delete(Ve),Dt}),Ze||F(nt=>{if(!nt.has(Ve))return nt;const St=new Set(nt);return St.delete(Ve),St}),$()},[ce,$]),ne=i.useCallback(()=>{ce(),T(Ve=>Ve.size>0?new Set:new Set(z.map(Ze=>Ze.path))),F(new Set),$()},[ce,z,$]),P=i.useCallback(async Ve=>{if(!q)return;const Ze=ut.getState().getDirectoryForSession(q)||f||"";if(!Ze){de.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}Q(!0);try{await tg({originalSessionID:q,directory:Ze,providerID:Ve.providerID,modelID:Ve.modelID,agent:Ve.agent||void 0,variant:Ve.variant||void 0,generateHandoff:Ve.generateHandoff,returnAfterHandoffRequest:Ve.generateHandoff}),Z(!1)}catch(nt){console.error("[review-flow] failed to start review flow",nt),de.error(nt instanceof Error?nt.message:d("diffView.reviewDialog.toast.startFailed"))}finally{Q(!1)}},[q,f,d]),me=i.useCallback(Ve=>{const Ze=ge.current.get(Ve),nt=Me.current;if(!Ze||!nt)return!1;const St=nt.getBoundingClientRect(),wt=Ze.getBoundingClientRect().top-St.top,ot=Math.max(0,nt.scrollHeight-nt.clientHeight);return nt.scrollTop=Math.min(ot,Math.max(0,nt.scrollTop+wt)),!0},[]);i.useEffect(()=>{if(!Ae.current)return;let Ze=0;const nt=20;let St=!1;const Dt=()=>{St||(St=!0,Ae.current=null,ue.current=!1,C(null),pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null))},wt=()=>{if(St){pe.current=null;return}const ot=Ae.current;if(!ot){Dt(),pe.current=null;return}if(!me(ot)){Ze+=1,Ze<nt?pe.current=window.requestAnimationFrame(wt):(Dt(),pe.current=null);return}n&&ue.current&&C(ot),Dt()};return pe.current=window.requestAnimationFrame(wt),()=>{St=!0,pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null)}},[n,B,me]);const oe=i.useCallback(Ve=>{},[]),Be=i.useCallback(Ve=>{ce(),k(Ve),D(!1),ue.current=!0,Ae.current=Ve,W(Ve),V(Ze=>Ze+1),me(Ve)},[ce,W,me]),Ue=i.useCallback(Ve=>{const Ze=Ve==="side-by-side"?"side-by-side":"inline";z.forEach(nt=>{te(nt.path,Ze)})},[z,te]),[Ke,Qe]=i.useState(null),rt=i.useCallback(async(Ve,Ze)=>{if(!(!f||!Ve)){Qe(Ve);try{let nt=null;if(Ze&&!Ze.isBinary&&!eo(Ve)&&(nt=Du(Ze.original,Ze.modified)),nt===null)try{const at=await u.getGitDiff(f,{path:Ve,staged:Se,contextLines:3});nt=zv(at.diff)}catch{nt=null}let St=Ze;if(nt===null||!St){const at=await u.getGitFileDiff(f,{path:Ve,staged:Se});St={original:at.original??"",modified:at.modified??"",isBinary:at.isBinary},Se||S(f,Ve,St)}const Dt=nt??(St.isBinary||eo(Ve)?1:Du(St.original,St.modified)),wt=$v(f,Ve),ot=await Fc(m,wt);if(!ot.ok){de.error(Lc(ot.reason));return}H(f,wt,Dt,1)}finally{Qe(nt=>nt===Ve?null:nt)}}},[Se,f,m,u,H,S]),pt=()=>{if(!f)return null;const Ve=Ze=>le!==null?le:v&&Ze===j;return s.jsxs("div",{className:De("flex min-w-0 flex-1 min-h-0 h-full",l?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[Oe&&s.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:d("diffView.section.files")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:z.length})]}),s.jsx(Gv,{changedFiles:z,selectedFile:null,onSelectFile:Be})]}),s.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:s.jsx(Wn,{ref:Me,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:s.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:z.map(Ze=>s.jsx(Qv,{directory:f,file:Ze,layout:Ie(Ze),wrapLines:ae,isSelected:!1,isExpanded:O.has(Ze.path),isMounted:E.has(Ze.path)||Ze.path===A,onSelect:oe,onExpandedChange:Ce,registerSectionRef:Fe,showOpenInEditorAction:r,isOpeningInEditor:Ke===Ze.path,onOpenInEditor:(nt,St)=>{rt(nt,St)},staged:Ve(Ze.path),loadFullFiles:R},Ze.path))})})})]})},jt=()=>f?b&&!x?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),d("diffView.state.loadingRepositoryStatus")]}):p===!1?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.notGitRepository")}):z.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.cleanWorkingTree")}):pt():s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.selectSessionDirectory")});return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[!y&&(o==="working"||o==="staged"?s.jsx(Hv,{scope:o,workingCount:be,stagedCount:xe,onScopeChange:a}):s.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:b&&!x?d("diffView.state.loadingChanges"):z.length===1?d("diffView.summary.changedFilesSingle",{count:z.length}):d("diffView.summary.changedFilesPlural",{count:z.length})})})),z.length>0&&s.jsxs($e,{variant:"ghost",size:"sm",onClick:ne,className:De("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(I,{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")})]}),z.length>0&&_e&&s.jsxs($e,{variant:"default",size:"sm",onClick:()=>Z(!0),disabled:se,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[se?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),z.length>0&&s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>L(Ve=>!Ve),"aria-pressed":R,"aria-label":d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:De("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",R&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(I,{name:"file-download",className:"size-4"})})}),s.jsx(Mt,{children:s.jsx("p",{children:d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),z.length>0&&s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>J(!Ne),className:De("h-5 w-5 p-0 transition-opacity",ae?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(ae?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(I,{name:"text-wrap",className:"size-4"})}),ve&&s.jsx(Gf,{mode:ve==="side-by-side"?"side-by-side":"unified",onModeChange:Ue})]}),s.jsx(sg,{open:M,onOpenChange:Z,projectDirectory:f??null,submitting:se,onConfirm:P}),jt()]})},Jv=(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)},Iu=(t,e)=>{const n=t.state.doc.lineAt(e.main.head);return{lineNumber:n.number,character:e.main.head-n.from+1,selection:e}},Pu=(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:Th.cursor(a),effects:si.scrollIntoView(a,{y:"center"})})};function Xv({open:t,onOpenChange:e,view:n,variant:r="overlay"}){const{t:o}=kt(),[a,c]=i.useState(""),l=i.useRef(null),d=i.useRef(!1),u=i.useRef(null),m=i.useRef(null),f=i.useMemo(()=>Jv(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=Iu(n,n.state.selection),c(""))},[t,n]),i.useEffect(()=>{t&&window.requestAnimationFrame(()=>{m.current?.focus(),m.current?.select()})},[t]),i.useEffect(()=>{if(!(!t||!n||!l.current)){if(f===null){const{selection:b}=l.current;n.dispatch({selection:b,effects:si.scrollIntoView(b.main.from,{y:"center"})});return}Pu(n,f,l.current.character)}},[f,t,n]);const g=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:b}=l.current;n.dispatch({selection:b,effects:si.scrollIntoView(b.main.from,{y:"center"})})},[n]),y=i.useCallback(b=>{b||g(),e(b)},[e,g]),p=i.useCallback(()=>{!n||f===null||!l.current||(d.current=!0,Pu(n,f,l.current.character),e(!1),n.focus())},[f,e,n]);i.useEffect(()=>{if(!t)return;const b=N=>{const w=u.current,S=N.target;!w||!(S instanceof Node)||w.contains(S)||y(!1)},h=N=>{N.key==="Escape"&&(N.preventDefault(),y(!1))};return document.addEventListener("pointerdown",b,!0),document.addEventListener("keydown",h,!0),()=>{document.removeEventListener("pointerdown",b,!0),document.removeEventListener("keydown",h,!0)}},[y,t,r]);const x=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(f===null){const b=l.current??Iu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:b.lineNumber,max:n.state.doc.lines})}return o("goToLineDialog.helper.goToLine",{line:f})},[f,o,n]);return r==="inline"?t?s.jsxs("div",{ref:u,className:"ml-1 flex h-6 items-center gap-1",children:[s.jsx(vn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:b=>c(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())},placeholder:o("goToLineDialog.field.linePlaceholderShort"),className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),s.jsx($e,{variant:"outline",size:"xs",onClick:p,disabled:!n||f===null,className:"h-6 px-2",children:o("goToLineDialog.actions.go")})]}):null:s.jsx("div",{ref:u,className:De("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(vn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:b=>c(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())},placeholder:o("goToLineDialog.field.linePlaceholder"),className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),s.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:x})]})})}const Zv='<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 Tu(){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 e1=i.forwardRef(function({xml:e,readOnly:n,className:r,onChange:o},a){const c=i.useRef(e),l=i.useRef(null),d=i.useRef(!1),[u,m]=i.useState(Tu),f=i.useRef(e),g=i.useRef(e);g.current!==e&&(g.current=e,f.current=e,c.current=e);const y=i.useRef(u);y.current!==u&&(y.current=u,f.current=c.current);const p=i.useRef(null);i.useEffect(()=>{const h=()=>m(Tu());h();const N=new MutationObserver(h);return N.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>N.disconnect()},[]),i.useEffect(()=>{const h=setTimeout(()=>{p.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(h)},[]),i.useImperativeHandle(a,()=>({getXml:()=>c.current}));const x=i.useCallback(()=>{!e&&!d.current&&(d.current=!0,setTimeout(()=>{l.current?.template({})},500))},[e]),b=i.useCallback(h=>{c.current=h.xml,o?.(h.xml)},[o]);return s.jsx("div",{ref:p,className:De("h-full w-full",r),children:s.jsx(Rh,{ref:l,xml:f.current||Zv,autosave:!0,urlParameters:{ui:n?"simple":u?"dark":"kennedy",spin:!0,libraries:!n,chrome:n,nav:n,layers:n,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:x,onAutoSave:b},u?"dark":"light")})}),t1=t=>{const e=Ys(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},s1=t=>{const e=gt.c(8),{label:n,iconDataUrl:r}=t,[o,a]=i.useState(!1);let c;e[0]!==n?(c=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=c):c=e[1];const l=c;if(r&&!o){let m;e[2]===Symbol.for("react.memo_cache_sentinel")?(m=()=>a(!0),e[2]=m):m=e[2];let f;return e[3]!==r?(f=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:m}),e[3]=r,e[4]=f):f=e[4],f}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=De("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=d):d=e[5];let u;return e[6]!==l?(u=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=u):u=e[7],u},n1=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Ys=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},r1=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Ui=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,Pa=(t,e)=>{const n=Ys(e),r=Ys(t);if(!n||!r)return!1;const o=Ui(n),a=Ui(r);return a===o||a.startsWith(`${o}/`)},Ru=(t,e)=>{const n=Ys(e),r=Ys(t);if(!Pa(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},Xl=(t,e)=>{if(!e)return"";const n=Ys(e);if(!t||!Pa(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},i1=new Set(["node_modules"]),o1=t=>{const e=gt.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},Eu=t=>{const e=gt.c(11),{name:n}=t,r=i.useRef(null),o=i.useRef(null),[a,c]=i.useState(!1);let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l=()=>{const g=r.current,y=o.current;if(!g||!y)return;const p=()=>{c(y.scrollWidth>g.clientWidth+1)};p();const x=new ResizeObserver(p);return x.observe(g),x.observe(y),()=>{x.disconnect()}},e[0]=l):l=e[0];let d;e[1]!==n?(d=[n],e[1]=n,e[2]=d):d=e[2],i.useLayoutEffect(l,d);let u;e[3]!==n?(u=s.jsx("span",{ref:o,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:n}),e[3]=n,e[4]=u):u=e[4];let m;e[5]!==n||e[6]!==a?(m=a?s.jsxs("span",{className:"open-file-name-marquee-track",children:[s.jsx("span",{className:"open-file-name-marquee-item",children:n}),s.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:n})]}):s.jsx("span",{className:"block min-w-0 truncate",children:n}),e[5]=n,e[6]=a,e[7]=m):m=e[7];let f;return e[8]!==u||e[9]!==m?(f=s.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[u,m]}),e[8]=u,e[9]=m,e[10]=f):f=e[10],f},a1=t=>i1.has(t),l1=t=>{const e=Ys(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},c1=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},Mu=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},go=2e5,Lm="openchamber:files:auto-save-enabled",d1=t=>{let e=0,n=0;for(let r=0;r<t.length;r+=1)t.charCodeAt(r)===10&&(r>0&&t.charCodeAt(r-1)===13?e+=1:n+=1);return e>n?`\r
21
- `:`
22
- `},Om=t=>t.replace(/\r\n/g,`
23
- `).replace(/\r/g,`
24
- `),u1=(t,e)=>{const n=Om(t);return e===`\r
25
- `?n.replace(/\n/g,`\r
26
- `):n},f1=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(Lm)!=="false"}catch{return!0}},Bm=(t,e)=>s.jsx(Ur,{filePath:t,extension:e}),Fu=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},m1=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="json"||e==="jsonc"||e==="json5"||e==="geojson"},Xo=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="html"||e==="htm"},h1=t=>{const e=gt.c(83),{node:n,root:r,isExpanded:o,isActive:a,isMobile:c,alwaysShowActions:l,status:d,badge:u,permissions:m,downloadFile:f,contextMenuPath:g,setContextMenuPath:y,rightClickMenuPath:p,setRightClickMenuPath:x,onSelect:b,onToggle:h,onRevealPath:N,onOpenDialog:w}=t,{t:S}=kt(),j=n.type==="directory",{canRename:k,canCreateFile:v,canCreateFolder:D,canDelete:A,canReveal:C}=m;let O;e[0]!==v||e[1]!==D||e[2]!==A||e[3]!==k||e[4]!==C||e[5]!==n.path||e[6]!==x?(O=Se=>{!k&&!v&&!D&&!A&&!C||(Se?.preventDefault(),x(n.path))},e[0]=v,e[1]=D,e[2]=A,e[3]=k,e[4]=C,e[5]=n.path,e[6]=x,e[7]=O):O=e[7];const T=O;let E;e[8]!==j||e[9]!==n||e[10]!==b||e[11]!==h?(E=()=>{j?h(n.path):b(n)},e[8]=j,e[9]=n,e[10]=b,e[11]=h,e[12]=E):E=e[12];const F=E;let R;e[13]!==n.path||e[14]!==y||e[15]!==x?(R=Se=>{Se.stopPropagation(),x(null),y(n.path)},e[13]=n.path,e[14]=y,e[15]=x,e[16]=R):R=e[16];const L=R;let B;e[17]!==v||e[18]!==D||e[19]!==A||e[20]!==k||e[21]!==C||e[22]!==f||e[23]!==j||e[24]!==n||e[25]!==w||e[26]!==N||e[27]!==r||e[28]!==S?(B=Se=>{const{Item:Re,Separator:_e}=Se;return s.jsxs(s.Fragment,{children:[k&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),w("rename",n)},children:[s.jsx(I,{name:"edit",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.rename")]}),s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),pr(n.path).then(Me=>{if(Me.ok){de.success(S("sidebarFilesTree.toast.pathCopied"));return}de.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.copyPath")]}),s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation();const Me=Xl(r,n.path)||n.path;pr(Me).then(ge=>{if(ge.ok){de.success(S("filesView.toast.relativePathCopied"));return}de.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy-2",className:"mr-2 size-4"})," ",S("filesView.tree.menu.copyRelativePath")]}),!j&&f&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),f(n.path).catch(Me=>{console.error("Download failed:",Me),de.error(S("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(I,{name:"download",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.save")]}),C&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),N(n.path)},children:[s.jsx(I,{name:"folder-received",className:"mr-2 size-4"})," ",S(vc())]}),j&&(v||D)&&s.jsxs(s.Fragment,{children:[s.jsx(_e,{}),v&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),w("createFile",n)},children:[s.jsx(I,{name:"file-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFile")]}),D&&s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),w("createFolder",n)},children:[s.jsx(I,{name:"folder-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFolder")]})]}),A&&s.jsxs(s.Fragment,{children:[s.jsx(_e,{}),s.jsxs(Re,{onClick:Oe=>{Oe.stopPropagation(),w("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"delete-bin",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.delete")]})]})]})},e[17]=v,e[18]=D,e[19]=A,e[20]=k,e[21]=C,e[22]=f,e[23]=j,e[24]=n,e[25]=w,e[26]=N,e[27]=r,e[28]=S,e[29]=B):B=e[29];const V=B,M=p===n.path;let Z;e[30]!==n.path||e[31]!==x?(Z=Se=>x(Se?n.path:null),e[30]=n.path,e[31]=x,e[32]=Z):Z=e[32];const se=c?void 0:T;let Q;e[33]!==se?(Q=s.jsx("div",{className:"group relative flex items-center",onContextMenu:se}),e[33]=se,e[34]=Q):Q=e[34];const K=c?void 0:T,ee=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let re;e[35]!==ee?(re=De("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",ee),e[35]=ee,e[36]=re):re=e[36];let he;e[37]!==j||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(he=j?o?s.jsx(I,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(I,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):Bm(n.path,n.extension),e[37]=j,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=he):he=e[41];let je;e[42]!==n.name||e[43]!==n.path?(je=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]=je):je=e[44];let te;e[45]!==j||e[46]!==d?(te=!j&&d&&s.jsx(o1,{status:d}),e[45]=j,e[46]=d,e[47]=te):te=e[47];let Ne;e[48]!==u||e[49]!==j?(Ne=j&&u&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[u.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",u.modified]}),u.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",u.added]})]}),e[48]=u,e[49]=j,e[50]=Ne):Ne=e[50];let J;e[51]!==F||e[52]!==re||e[53]!==he||e[54]!==je||e[55]!==te||e[56]!==Ne||e[57]!==K?(J=s.jsxs("button",{type:"button",onClick:F,onContextMenu:K,className:re,children:[he,je,te,Ne]}),e[51]=F,e[52]=re,e[53]=he,e[54]=je,e[55]=te,e[56]=Ne,e[57]=K,e[58]=J):J=e[58];let H;e[59]!==l||e[60]!==v||e[61]!==D||e[62]!==A||e[63]!==k||e[64]!==C||e[65]!==g||e[66]!==L||e[67]!==c||e[68]!==n.path||e[69]!==V||e[70]!==y?(H=(k||v||D||A||C)&&s.jsx("div",{className:De("absolute right-1 top-1/2 -translate-y-1/2",l?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:s.jsxs(nn,{open:g===n.path,onOpenChange:Se=>y(Se?n.path:null),children:[s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"icon",className:"size-6",onClick:L,children:s.jsx(I,{name:"more-2-fill",className:"size-4"})})}),s.jsx(sn,{align:"end",side:"bottom",onCloseAutoFocus:()=>y(null),children:V({Item:bs,Separator:Rr})})]})}),e[59]=l,e[60]=v,e[61]=D,e[62]=A,e[63]=k,e[64]=C,e[65]=g,e[66]=L,e[67]=c,e[68]=n.path,e[69]=V,e[70]=y,e[71]=H):H=e[71];let q;e[72]!==J||e[73]!==H||e[74]!==Q?(q=s.jsxs(Ic,{render:Q,children:[J,H]}),e[72]=J,e[73]=H,e[74]=Q,e[75]=q):q=e[75];let ae;e[76]!==V?(ae=s.jsx(Ac,{className:"min-w-[180px]",children:V({Item:Dc,Separator:um})}),e[76]=V,e[77]=ae):ae=e[77];let le;return e[78]!==q||e[79]!==ae||e[80]!==M||e[81]!==Z?(le=s.jsxs(Pc,{open:M,onOpenChange:Z,children:[q,ae]}),e[78]=q,e[79]=ae,e[80]=M,e[81]=Z,e[82]=le):le=e[82],le},p1=t=>{const e=gt.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:u}=t,{t:m}=kt(),f=!!n;let g;e[0]!==d?(g=M=>!M&&d(),e[0]=d,e[1]=g):g=e[1];let y;e[2]!==n||e[3]!==m?(y=n==="createFile"&&m("filesView.dialog.createFile.title"),e[2]=n,e[3]=m,e[4]=y):y=e[4];let p;e[5]!==n||e[6]!==m?(p=n==="createFolder"&&m("filesView.dialog.createFolder.title"),e[5]=n,e[6]=m,e[7]=p):p=e[7];let x;e[8]!==n||e[9]!==m?(x=n==="rename"&&m("filesView.dialog.rename.title"),e[8]=n,e[9]=m,e[10]=x):x=e[10];let b;e[11]!==n||e[12]!==m?(b=n==="delete"&&m("filesView.dialog.delete.title"),e[11]=n,e[12]=m,e[13]=b):b=e[13];let h;e[14]!==y||e[15]!==p||e[16]!==x||e[17]!==b?(h=s.jsxs(_s,{children:[y,p,x,b]}),e[14]=y,e[15]=p,e[16]=x,e[17]=b,e[18]=h):h=e[18];let N;e[19]!==n||e[20]!==r?.path||e[21]!==m?(N=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]=N):N=e[22];let w;e[23]!==n||e[24]!==r?.path||e[25]!==m?(w=n==="createFolder"&&m("filesView.dialog.createFolder.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[23]=n,e[24]=r?.path,e[25]=m,e[26]=w):w=e[26];let S;e[27]!==n||e[28]!==r?.name||e[29]!==m?(S=n==="rename"&&m("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=m,e[30]=S):S=e[30];let j;e[31]!==n||e[32]!==r?.name||e[33]!==m?(j=n==="delete"&&m("filesView.dialog.delete.description",{name:r?.name??""}),e[31]=n,e[32]=r?.name,e[33]=m,e[34]=j):j=e[34];let k;e[35]!==S||e[36]!==j||e[37]!==N||e[38]!==w?(k=s.jsxs(an,{children:[N,w,S,j]}),e[35]=S,e[36]=j,e[37]=N,e[38]=w,e[39]=k):k=e[39];let v;e[40]!==k||e[41]!==h?(v=s.jsxs(Us,{children:[h,k]}),e[40]=k,e[41]=h,e[42]=v):v=e[42];let D;e[43]!==n||e[44]!==o||e[45]!==u||e[46]!==a||e[47]!==l||e[48]!==m?(D=n!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(vn,{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:u})}),e[43]=n,e[44]=o,e[45]=u,e[46]=a,e[47]=l,e[48]=m,e[49]=D):D=e[49];let A;e[50]!==m?(A=m("filesView.dialog.cancel"),e[50]=m,e[51]=A):A=e[51];let C;e[52]!==c||e[53]!==d||e[54]!==A?(C=s.jsx($e,{variant:"outline",onClick:d,disabled:c,children:A}),e[52]=c,e[53]=d,e[54]=A,e[55]=C):C=e[55];const O=n==="delete"?"destructive":"default";let T;e[56]!==l?(T=()=>{l()},e[56]=l,e[57]=T):T=e[57];let E;e[58]!==n||e[59]!==o||e[60]!==c?(E=c||n!=="delete"&&!o.trim(),e[58]=n,e[59]=o,e[60]=c,e[61]=E):E=e[61];let F;e[62]!==n||e[63]!==c||e[64]!==m?(F=c?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):m(n==="delete"?"filesView.dialog.delete.confirm":"filesView.dialog.confirm"),e[62]=n,e[63]=c,e[64]=m,e[65]=F):F=e[65];let R;e[66]!==O||e[67]!==T||e[68]!==E||e[69]!==F?(R=s.jsx($e,{variant:O,onClick:T,disabled:E,children:F}),e[66]=O,e[67]=T,e[68]=E,e[69]=F,e[70]=R):R=e[70];let L;e[71]!==C||e[72]!==R?(L=s.jsxs(ar,{children:[C,R]}),e[71]=C,e[72]=R,e[73]=L):L=e[73];let B;e[74]!==u||e[75]!==v||e[76]!==D||e[77]!==L?(B=s.jsxs(Ls,{initialFocus:u,children:[v,D,L]}),e[74]=u,e[75]=v,e[76]=D,e[77]=L,e[78]=B):B=e[78];let V;return e[79]!==f||e[80]!==g||e[81]!==B?(V=s.jsx(Os,{open:f,onOpenChange:g,children:B}),e[79]=f,e[80]=g,e[81]=B,e[82]=V):V=e[82],V},jl=(t,e,n)=>{const r=gt.c(8),[o,a]=i.useState(""),[c,l]=i.useState(0);let d,u;r[0]!==t||r[1]!==n||r[2]!==e?(d=()=>{if(!t){a("");return}let f=!1;a("");const g=zr(),y=sp(g);dc(g).then(x=>{f||!x||(a(t),e(null))}).catch(x=>{f||(e(x instanceof Error?x.message:n),a(t))});const p=np(()=>{f||(a(t),l(g1),e(null))});return()=>{f=!0,y(),p()}},u=[t,e,n],r[0]=t,r[1]=n,r[2]=e,r[3]=d,r[4]=u):(d=r[3],u=r[4]),i.useEffect(d,u);let m;return r[5]!==c||r[6]!==o?(m={readyKey:o,nonce:c},r[5]=c,r[6]=o,r[7]=m):m=r[7],m},Vm=({mode:t="full"})=>{const{t:e}=kt(),{files:n,runtime:r}=er(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=Gr(),{isMobile:d,isTablet:u,screenWidth:m}=Er(),f=d||u,g=Df(),y=If(),p=ci()??"",x=Ys(p.trim()),b=d||t!=="editor-only",h=t==="editor-only"&&!d,N=cc(U=>U.searchFiles),w=Wa(p),[S,j]=i.useState(""),k=Ha(S,200),v=i.useRef(null),[D,A]=i.useState(!1),[C,O]=i.useState(!0),[T,E]=i.useState(!1),[F,R]=i.useState(!1),[L,B]=i.useState(!1),V=i.useRef(null),M=i.useRef(0),Z=i.useCallback(U=>{M.current=Math.max(0,M.current+(U?1:-1))},[]),se=i.useCallback(U=>U instanceof Element?U.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!L)return;const U=Te=>{M.current>0||se(Te.target)||V.current&&!V.current.contains(Te.target)&&B(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[se,L]);const[Q,K]=i.useState("edit"),[ee,re]=i.useState("edit"),[he,je]=i.useState("tree"),[te,Ne]=i.useState("edit"),[J,H]=i.useState("preview"),[q,ae]=i.useState(0),le=i.useRef({}),Se=i.useRef({}),Re=i.useRef({}),_e=i.useRef({}),Oe=i.useMemo(()=>a.find(U=>U.metadata.id===c)??Sd(!1),[a,c]),Me=i.useMemo(()=>a.find(U=>U.metadata.id===l)??Sd(!0),[a,l]);i.useEffect(()=>{Nd(Oe),Nd(Me)},[Oe,Me]);const ge=i.useMemo(()=>[],[]),Ae=yn(U=>x?U.byRoot[x]?.openPaths??ge:ge),pe=yn(U=>x?U.byRoot[x]?.selectedPath??null:null),ue=yn(U=>x?U.byRoot[x]?.expandedPaths??ge:ge),G=yn(U=>U.addOpenPath),fe=yn(U=>U.removeOpenPath),ce=yn(U=>U.removeOpenPathsByPrefix),W=yn(U=>U.setSelectedPath),z=yn(U=>U.toggleExpandedPath),be=yn(U=>U.expandPaths),xe=i.useCallback(U=>{const Te=Ys(U),We=Te.split("/"),Ge=We[We.length-1]||Te,ct=Ge.includes(".")?Ge.split(".").pop()?.toLowerCase():void 0;return{name:Ge,path:Te,type:"file",extension:ct}},[]),_=i.useMemo(()=>Ae.map(xe),[Ae,xe]),ye=i.useMemo(()=>{if(pe){const U=Ui(pe);if(Ae.some(Te=>Ui(Te)===U))return pe}return Ae[0]??null},[Ae,pe]),$=i.useMemo(()=>ye?xe(ye):null,[ye,xe]),Ie=$?.path??"";i.useEffect(()=>{if(!x||!pe)return;const U=Ui(pe);Ae.some(We=>Ui(We)===U)||W(x,Ae[0]??null)},[Ae,x,pe,W]);const ve=!!(x&&Ie&&!Pa(Ie,x)),Fe=ve?kd(Ie):void 0,Ce=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&ve,outsideFileGrant:Fe,directory:x||void 0}),[t,ve,Fe,x]),ne=i.useRef(null),[P,me]=i.useState({left:!1,right:!1}),oe=i.useCallback(()=>{const U=ne.current;U&&me({left:U.scrollLeft>2,right:U.scrollLeft+U.clientWidth<U.scrollWidth-2})},[]),Be=i.useRef(oe);Be.current=oe,i.useEffect(()=>{const U=ne.current;if(!U)return;const Te=()=>Be.current();Te(),U.addEventListener("scroll",Te,{passive:!0});const We=new ResizeObserver(Te);return We.observe(U),()=>{U.removeEventListener("scroll",Te),We.disconnect()}},[_.length]);const[Ue,Ke]=i.useState({}),[Qe,rt]=i.useState({}),pt=i.useRef(new Set),jt=i.useRef(new Set),Ve=i.useRef(new Map),Ze=i.useRef(0),[nt,St]=i.useState([]),[Dt,wt]=i.useState(!1),[ot,at]=i.useState(""),{isPlaying:Kt,play:is,stop:$t}=Kf(),[Le,et]=i.useState(!1),[Vt,xt]=i.useState(null),[Ft,Gt]=i.useState(""),Ut=i.useRef(""),[qt,Xt]=i.useState(null),[Lt,Bt]=i.useState(""),[Yt,Jt]=i.useState(!1),[es,Zt]=i.useState(`
27
- `),vs=i.useRef(null),bt=i.useRef(null),Ot=i.useRef(null),It=i.useRef(""),us=i.useRef(""),He=i.useRef(null),ft=i.useRef(null),Ye=i.useRef(null),Pt=i.useRef(0),[Tt,Qt]=i.useState("idle"),[Ss,ys]=i.useState(!1),[_t,Ns]=i.useState(f1),[js,Ds]=i.useState(!1),mn=i.useRef(null),Js=i.useRef(null),ln=i.useRef(null),jn=i.useRef(!1),$s=i.useRef(null),we=i.useRef(null),Je=i.useRef(null),vt=i.useRef(null),[Ct,zt]=i.useState(0),mt=i.useRef(null),cs=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{mt.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(mt.current),mt.current=null)},[]);const[fs,ks]=i.useState(null),[ms,Hs]=i.useState(null),[zs,hn]=i.useState(""),[tr,An]=i.useState(!1),[qe,ns]=i.useState(null),[ps,hs]=i.useState(null),[rn,Ws]=i.useState(!1),[cn,Is]=i.useState(!1),[sr,Sr]=i.useState(!1),nr=!!n.writeFile,gr=!!n.createDirectory,Kn=!!n.rename,gs=!!n.delete,Ps=!!n.revealPath,Mr=wr(U=>U.availableApps),Sn=wr(U=>U.isCacheStale),on=wr(U=>U.initialize),lr=wr(U=>U.loadInstalledApps);i.useEffect(()=>{on()},[on]);const Fr=i.useCallback(U=>{n.revealPath&&n.revealPath(U).catch(()=>{de.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),Kr=i.useCallback(async U=>{if(!$?.path||await tp($.path,U.id,U.appName)||await wa($.path,U.appName))return;const Ge=t1($.path)||x;Ge&&await wa(Ge,U.appName)||de.error(e("filesView.toast.openInAppFailed",{app:U.appName}))},[x,$?.path,e]),Lr=i.useCallback((U,Te)=>{ks(U),Hs(Te),hn(U==="rename"&&Te.name||""),An(!1)},[]),[xs,Rs]=i.useState(null),qn=i.useRef(!1),pn=i.useRef(null),[X,st]=i.useState(!1),ht=Ee(U=>U.setMainTabGuard),At=Ee(U=>U.pendingFileNavigation),os=Ee(U=>U.setPendingFileNavigation),rs=Ee(U=>U.pendingFileFocusPath),ds=Ee(U=>U.setPendingFileFocusPath),Es=Ee(U=>U.shortcutOverrides),Gs=Ee(U=>U.fileEditorKeymap),Dn=ss(U=>U.settingsDefaultFileViewerPreview),Nr=ss(U=>U.showMessageTTSButtons),kr=Ee(U=>U.expandedEditorToolbar);i.useEffect(()=>{const U=()=>{qn.current=!1,pn.current=null,st(!1)};return document.addEventListener("mouseup",U),()=>document.removeEventListener("mouseup",U)},[]),i.useEffect(()=>()=>{$s.current!==null&&window.clearTimeout($s.current),we.current!==null&&window.clearTimeout(we.current)},[]);const Bs=i.useCallback((U,Te)=>{const We=U.split(`
28
- `),Ge=Math.max(1,Te.start),ct=Math.min(We.length,Te.end);return Ge>ct?"":We.slice(Ge-1,ct).join(`
29
- `)},[]),Or=fm({source:"file",fileLabel:$?.path??null,language:$?.path&&Di($.path)||"text",getCodeForRange:U=>Bs(ot,mm(U)),toStoreRange:U=>({startLine:U.start,endLine:U.end}),fromDraftRange:U=>({start:U.startLine,end:U.endLine})}),{drafts:dn,commentText:Ln,setCommentText:In,editingDraftId:Nn,setSelection:Pn,saveComment:cr,cancel:un,reset:di,startEdit:Br,deleteDraft:Cr}=Or;i.useEffect(()=>{Rs(null),di(),ht(null),Bt(""),Jt(!1)},[$?.path,di,ht]),i.useEffect(()=>{Pn(xs)},[xs,Pn]),i.useEffect(()=>{if(!xs&&!Nn)return;const U=We=>{const Ge=We.target;Ge.closest('[data-comment-input="true"]')||Ge.closest('[data-comment-card="true"]')||Ge.closest(".cm-gutterElement")||Ge.closest("[data-sonner-toast]")||Ge.closest("[data-sonner-toaster]")||Ln.trim()||(Rs(null),un())},Te=setTimeout(()=>{document.addEventListener("click",U)},100);return()=>{clearTimeout(Te),document.removeEventListener("click",U)}},[un,Ln,Nn,xs]);const Mi=i.useCallback((U,Te)=>{const We=Te??xs??void 0;Te&&Rs(Te),cr(U,We),Rs(null)},[xs,cr]),ui=i.useCallback((U,Te)=>{const We=[];for(const Ge of Te){if(!(Ge&&typeof Ge.name=="string"&&Ge.name.length>0)||!g&&Ge.name.startsWith(".")||!y&&a1(Ge.name))continue;const ct=Ge.name,it=Ys(Ge.path||""),ts=it?r1(it)?it:Ys(`${U}/${it}`):Ys(`${U}/${ct}`),Ms=Ge.isDirectory?"directory":"file",Vs=Ms==="file"&&ct.includes(".")?ct.split(".").pop()?.toLowerCase():void 0;We.push({name:ct,path:ts,type:Ms,extension:Vs})}return n1(We)},[y,g]),Tn=i.useCallback(async U=>{const Te=Ys(U.trim());if(!Te||pt.current.has(Te)||jt.current.has(Te))return;jt.current=new Set(jt.current),jt.current.add(Te);const We=Ze.current+1;Ze.current=We,Ve.current=new Map(Ve.current),Ve.current.set(Te,We);const Ge=()=>Ve.current.get(Te)===We;await(n.listDirectory?n.listDirectory(Te).then(it=>it.entries.map(ts=>({name:ts.name,path:ts.path,isDirectory:ts.isDirectory}))):zn.listLocalDirectory(Te).then(it=>it.map(ts=>({name:ts.name,path:ts.path,isDirectory:ts.isDirectory})))).then(it=>{if(!Ge())return;const ts=ui(Te,it);pt.current=new Set(pt.current),pt.current.add(Te),rt(Ms=>{if(!Ms[Te])return Ms;const Vs={...Ms};return delete Vs[Te],Vs}),Ke(Ms=>({...Ms,[Te]:ts}))}).catch(it=>{if(!Ge())return;const ts=it instanceof Error?it.message:String(it??"");console.error("Failed to load files directory:",it),rt(Ms=>({...Ms,[Te]:ts}))}).finally(()=>{Ge()&&(Ve.current=new Map(Ve.current),Ve.current.delete(Te),jt.current=new Set(jt.current),jt.current.delete(Te))})},[n,ui]),dr=i.useCallback(async()=>{x&&(pt.current=new Set,jt.current=new Set,Ve.current=new Map,rt({}),Ke(U=>Object.keys(U).length===0?U:{}),await Tn(x))},[Tn,x]),kn=i.useCallback(async U=>{if(!U){await dr();return}const Te=Ys(U);pt.current=new Set(pt.current),pt.current.delete(Te),jt.current=new Set(jt.current),jt.current.delete(Te),await Tn(Te)},[Tn,dr]),Yn=i.useRef(""),gn=i.useRef("");i.useEffect(()=>{if(!x)return;const U=`${x}|h${g?"1":"0"}|g${y?"1":"0"}`,Te=Yn.current!==x,We=gn.current!==U;!Te&&!We||(Te&&(Yn.current=x,at(""),xt(null),Gt(""),Xt(null),A(!1)),We&&(gn.current=U,pt.current=new Set,jt.current=new Set,Ve.current=new Map,rt({}),Ke(Ge=>Object.keys(Ge).length===0?Ge:{}),Tn(x)))},[Tn,x,y,g]),i.useEffect(()=>{if(!n.listDirectory)return;const U=()=>{if(!document.hidden&&ue.length>0)for(const Te of ue)kn(Te)};return document.addEventListener("visibilitychange",U),()=>document.removeEventListener("visibilitychange",U)},[ue,n.listDirectory,kn]),i.useEffect(()=>{if(!n.listDirectory||ue.length===0)return;const U=setInterval(()=>{if(!document.hidden)for(const Te of ue)kn(Te)},8e3);return()=>clearInterval(U)},[ue,n.listDirectory,kn]);const fi=i.useCallback(async U=>{if(U?.preventDefault(),!ms||!fs)return;An(!0);const Te=()=>{ks(null)},We=ct=>{de.error(ct)},Ge=()=>{An(!1)};if(fs==="createFile"){if(!zs.trim()){We(e("sidebarFilesTree.toast.filenameRequired")),Ge();return}if(!n.writeFile){We(e("sidebarFilesTree.toast.writeNotSupported")),Ge();return}const ct=ms.path,it=ct?`${ct}/`:"",ts=Ys(`${it}${zs.trim()}`);await n.writeFile(ts,"").then(async Ms=>{Ms.success&&(de.success(e("sidebarFilesTree.toast.fileCreated")),await kn(ct)),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(fs==="createFolder"){if(!zs.trim()){We(e("sidebarFilesTree.toast.folderNameRequired")),Ge();return}const ct=ms.path,it=ct?`${ct}/`:"",ts=Ys(`${it}${zs.trim()}`);await n.createDirectory(ts).then(async Ms=>{Ms.success&&(de.success(e("sidebarFilesTree.toast.folderCreated")),await kn(ct)),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(fs==="rename"){if(!zs.trim()){We(e("sidebarFilesTree.toast.nameRequired")),Ge();return}if(!n.rename){We(e("sidebarFilesTree.toast.renameNotSupported")),Ge();return}const ct=ms.path,it=ct.split("/").slice(0,-1).join("/"),ts=it?`${it}/`:"",Ms=Ys(`${ts}${zs.trim()}`);await n.rename(ct,Ms).then(async Vs=>{Vs.success&&(de.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await kn(it),x&&ce(x,ct),($?.path===ct||$?.path.startsWith(`${ct}/`))&&(x&&W(x,null),at(""),xt(null),Gt(""),Xt(null),d&&A(!1))),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}if(fs==="delete"){if(!n.delete){We(e("sidebarFilesTree.toast.deleteNotSupported")),Ge();return}const ct=ms.path,it=ct.split("/").slice(0,-1).join("/");await n.delete(ct).then(async ts=>{ts.success&&(de.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await kn(it),x&&ce(x,ct),($?.path===ct||$?.path.startsWith(`${ct}/`))&&(x&&W(x,null),at(""),xt(null),Gt(""),Xt(null),d&&A(!1))),Te()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ge);return}Ge()},[fs,ms,zs,n,kn,d,ce,x,$?.path,W,e]);i.useEffect(()=>{if(!p){St([]),wt(!1);return}const U=k.trim();if(!U){St([]),wt(!1);return}let Te=!1;return wt(!0),N(p,U,150,{includeHidden:g,respectGitignore:!y,type:"file"}).then(We=>{if(Te)return;const ct=We.filter(it=>y||!l1(it.path)).map(it=>({name:it.name,path:Ys(it.path),type:"file",extension:it.extension,relativePath:it.relativePath}));St(ct)}).catch(()=>{Te||St([])}).finally(()=>{Te||wt(!1)}),()=>{Te=!0}},[p,k,N,g,y]);const Fi=i.useCallback(async(U,Te)=>{if(n.readFile)return(await n.readFile(U,{...Te??{},directory:x||void 0})).content??"";const We=new URLSearchParams({path:U});Te?.allowOutsideWorkspace&&We.set("allowOutsideWorkspace","true"),Te?.outsideFileGrant&&We.set("outsideFileGrant",Te.outsideFileGrant),Te?.optional&&We.set("optional","true"),x&&We.set("directory",x);const Ge=await As(`/api/fs/read?${We.toString()}`,{cache:Te?.optional?"no-store":"default"});if(!Ge.ok){const ct=await Ge.json().catch(()=>({error:Ge.statusText}));throw new Error(ct.error||e("filesView.error.readFileFailed"))}return Ge.text()},[n,x,e]),On=i.useCallback(async(U,Te)=>{if(n.statFile){const We=await n.statFile(U,{...Te??{},directory:x||void 0});return{path:We.path,size:We.size,mtimeMs:We.mtimeMs}}return null},[n,x]);i.useEffect(()=>{if(!x||!n.statFile||Ae.length===0)return;let U=!1;const Te=[...Ae];return Promise.all(Te.map(async We=>{try{const Ge=await n.statFile?.(We,{directory:x||void 0});!U&&Ge&&!Ge.isFile&&ce(x,We)}catch(Ge){!U&&Mu(Ge)&&ce(x,We)}})),()=>{U=!0}},[n,Ae,ce,x]);const mi=i.useMemo(()=>ot.length>go?`${ot.slice(0,go)}
30
-
31
- … truncated …`:ot,[ot]),Xs=Lt!==mi,ur=i.useCallback(async()=>{if(!$||!n.writeFile)return de.error(e("filesView.toast.savingNotSupported")),!1;if(!Xs)return!0;if(Lt===""&&ot!==""&&qt!==$.path)return console.warn(`[saveDraft] refusing to save empty draft for "${$.path}" (${ot.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;Jt(!0);try{const U=u1(Lt,es);return(await n.writeFile($.path,U))?.success?(at(Lt),$?.path&&Cd($.path)&&(It.current=Lt,us.current=Lt),On($.path).then(We=>{We&&(Ye.current=We)}).catch(()=>{}),!0):(de.error(e("filesView.toast.writeFileFailed")),!1)}catch(U){return de.error(U instanceof Error?U.message:e("filesView.toast.saveFailed")),!1}finally{Jt(!1)}},[Lt,ot,n,Xs,es,qt,On,$,e]);i.useEffect(()=>{if(!Xs){ht(null);return}const U=Te=>jn.current?(jn.current=!1,!0):(Ds(!0),Js.current=Te,!1);return ht(U),()=>{Ee.getState().mainTabGuard===U&&ht(null)}},[Xs,ht]),i.useEffect(()=>{try{window.localStorage.setItem(Lm,_t?"true":"false")}catch{}},[_t]),i.useEffect(()=>{_t||(Qt("idle"),bt.current&&(clearTimeout(bt.current),bt.current=null))},[_t]);const hi=1500;i.useEffect(()=>{const U=!!($&&n.writeFile);if(!(!_t||!Xs||!U||Yt))return bt.current=setTimeout(()=>{ur().then(Te=>{Te&&(Qt("saved"),setTimeout(()=>Qt("idle"),2e3))})},hi),()=>{bt.current&&(clearTimeout(bt.current),bt.current=null)}},[_t,Lt,Xs,$,n.writeFile,Yt,ur]),i.useEffect(()=>{Qt("idle")},[$?.path]),i.useEffect(()=>{const U=Te=>{pc(Te)&&(Te.key.toLowerCase()==="s"?(Te.preventDefault(),bt.current&&(clearTimeout(bt.current),bt.current=null),Yt||ur().then(We=>{We&&(Qt("saved"),setTimeout(()=>Qt("idle"),2e3))})):Te.key.toLowerCase()==="f"&&(Te.preventDefault(),R(!0)))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[Yt,ur]);const Li=i.useCallback(async U=>{const Te=Pt.current+1;Pt.current=Te;const We=()=>{if(!x)return!1;const Vs=yn.getState().byRoot[x],xr=Vs?.selectedPath??Vs?.openPaths[0]??null;return Pt.current===Te&&xr===U.path};xt(null),Gt(""),Xt(null);const Ge=eo(U.path),ct=U.path.toLowerCase().endsWith(".svg"),it=Ad(U.path);if(d&&A(!0),r.isDesktop&&Ge&&!ct){at(""),Bt(""),et(!0);return}if(!r.isDesktop&&Ge&&!ct){at(""),Bt(""),Xt(U.path),et(!1);return}if(it){at(""),Bt(""),Xt(U.path),et(!1);return}et(!0);const ts=kd(U.path),Ms={allowOutsideWorkspace:t==="editor-only"&&!!x&&!Pa(U.path,x),outsideFileGrant:ts};await Fi(U.path,Ms).then(Vs=>{if(!We())return;const xr=Om(Vs);Zt(d1(Vs)),at(xr),It.current=xr,us.current=xr,Bt(xr.length>go?`${xr.slice(0,go)}
32
-
33
- … truncated …`:xr),Xt(U.path),On(U.path,Ms).then(mr=>{mr&&We()&&(Ye.current=mr)}).catch(()=>{})}).catch(Vs=>{if(We()){if(c1(Vs)){if(et(!1),x&&W(x,null),xt(null),at(""),Bt(""),Xt(null),Ye.current=null,S.trim().length>0&&j(""),d&&A(!1),x){const mr=[...Ru(U.path,x),U.path];mr.length>0&&be(x,mr);for(const tl of mr)pt.current.has(tl)||Tn(tl)}return}if(Mu(Vs)){x&&ce(x,U.path),at(""),Bt(""),xt(null),Ye.current=null,d&&A(!1);return}at(""),Bt(""),xt(Vs instanceof Error?Vs.message:e("filesView.error.readFileFailed")),Ye.current=null}}).finally(()=>{We()&&et(!1)})},[be,d,Tn,t,Fi,On,ce,x,r.isDesktop,S,W,e]),qr=i.useCallback(async(U,Te)=>{if(!x)return;const We=Ru(U,x),Ge=Te?[...We,U]:We;Ge.length>0&&be(x,Ge);const ct=Ge.map(it=>{if(!pt.current.has(it))return Tn(it)}).filter(Boolean);await Promise.all(ct)},[be,Tn,x]),pi=i.useCallback((U,Te)=>{const We=Te.findIndex(Ge=>Ge.path===U);return We===-1||Te.length<=1?null:Te[We+1]??Te[We-1]??null},[]),Zs=i.useCallback(async U=>{if(jn.current)jn.current=!1;else if(Xs){Ds(!0),mn.current=U;return}x&&(W(x,U.path),G(x,U.path),qr(U.path,!1)),xt(null),Gt(""),at(""),It.current="",us.current="",Bt(""),Xt(null),d&&A(!0)},[G,qr,Xs,d,x,W]);i.useEffect(()=>{$?.path&&qr($.path,!1)},[qr,$?.path]),i.useEffect(()=>{if(!$){Pt.current+=1,et(!1);return}qt!==$.path&&Li($)},[Li,qt,$]);const Oi=i.useRef(Xs);Oi.current=Xs,i.useEffect(()=>{if(!$?.path||qt!==$.path)return;let U=!1;const Te=window.setInterval(()=>{document.hidden||On($.path,Ce).then(We=>{if(U||!We)return;const Ge=Ye.current;if(!Ge||Ge.path!==$.path){Ye.current=We;return}const ct=We.mtimeMs!==void 0&&Ge.mtimeMs!==void 0&&We.mtimeMs!==Ge.mtimeMs,it=We.size!==Ge.size;!ct&&!it||Oi.current||(Ye.current=We,Xt(null))}).catch(()=>{})},2e3);return()=>{U=!0,window.clearInterval(Te)}},[qt,On,$?.path,Ce]);const uo=i.useCallback(()=>{const U=mn.current,Te=Js.current,We=ln.current;if(mn.current=null,Js.current=null,ln.current=null,jn.current=!0,Ds(!1),Bt(mi),We){x&&fe(x,We),$?.path===We&&(U?Zs(U):(x&&W(x,null),at(""),xt(null),Gt(""),Xt(null),d&&A(!1)));return}if(U){Zs(U);return}Te&&(ht(null),Ee.getState().setActiveMainTab(Te))},[mi,Zs,d,fe,x,$?.path,ht,W]),fo=i.useCallback(async()=>{const U=mn.current,Te=Js.current,We=ln.current;if(!await ur()){jn.current=!1;return}if(mn.current=null,Js.current=null,ln.current=null,jn.current=!0,Ds(!1),We){x&&fe(x,We),$?.path===We&&(U?await Zs(U):(x&&W(x,null),at(""),xt(null),Gt(""),Xt(null),d&&A(!1)));return}if(U){await Zs(U);return}Te&&(ht(null),Ee.getState().setActiveMainTab(Te))},[Zs,d,fe,x,ur,$?.path,ht,W]),Bi=i.useCallback(U=>{const Te=$?.path===U,We=pi(U,_);if(Te&&Xs){Ds(!0),mn.current=We,ln.current=U;return}if(x&&fe(x,U),!!Te){if(We){Zs(We);return}x&&W(x,null),at(""),xt(null),Gt(""),Xt(null),d&&A(!1)}},[pi,Zs,Xs,d,_,fe,x,$?.path,W]),Y=i.useCallback(U=>{if(Ae.includes(U))return"open";if(w?.files){const Te=U.startsWith(x+"/")?U.slice(x.length+1):U,We=w.files.find(Ge=>Ge.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},[Ae,w,x]),ke=i.useCallback(U=>{if(!w?.files)return null;const Te=U.startsWith(x+"/")?U.slice(x.length+1):U,We=Te?`${Te}/`:"";let Ge=0,ct=0;for(const it of w.files)it.path.startsWith(We)&&((it.index==="M"||it.working_dir==="M")&&Ge++,(it.index==="A"||it.working_dir==="?")&&ct++);return Ge+ct>0?{modified:Ge,added:ct}:null},[w,x]),Pe=i.useCallback(async U=>{const Te=Ys(U);x&&(z(x,Te),pt.current.has(Te)||await Tn(Te))},[Tn,x,z]),ze=i.useMemo(()=>({canRename:Kn,canCreateFile:nr,canCreateFolder:gr,canDelete:gs,canReveal:Ps}),[Kn,nr,gr,gs,Ps]);function dt(U,Te){const We=Ue[U]??[];return We.map((Ge,ct)=>{const it=Ge.type==="directory",ts=it&&ue.includes(Ge.path),Ms=$?.path===Ge.path,Vs=ct===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"}),Vs&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(h1,{node:Ge,root:x,isExpanded:ts,isActive:Ms,isMobile:d,alwaysShowActions:f,status:it?void 0:Y(Ge.path),badge:it?ke(Ge.path):void 0,permissions:ze,downloadFile:n.downloadFile,contextMenuPath:qe,setContextMenuPath:ns,rightClickMenuPath:ps,setRightClickMenuPath:hs,onSelect:Zs,onToggle:Pe,onRevealPath:Fr,onOpenDialog:Lr}),it&&ts&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[Qe[Ge.path]?s.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:Qe[Ge.path],children:Qe[Ge.path]}),s.jsxs($e,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{kn(Ge.path)},children:[s.jsx(I,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,dt(Ge.path,Te+1)]})]},Ge.path)})}const yt=!!($?.path&&eo($.path)),ls=!!($?.path&&$.path.toLowerCase().endsWith(".svg")),Wt=!!($?.path&&Ad($.path)),Ks=i.useMemo(()=>Ys(At?.path??""),[At?.path]),Bn=!!(At&&Ks&&Ie&&Ie===Ks&&!Le&&!Vt&&!yt&&!Wt),fr=i.useMemo(()=>Xl(x,Ie),[Ie,x]),ie=!!($&&(!yt||ls)&&!Wt&&ot.length>0),lt=!!($&&fr.length>0),Xe=!!($&&!ve&&!yt&&!Wt&&n.writeFile&&ot.length<=go),Nt=!!($?.path&&Fu($.path)),Ht=!!($?.path&&m1($.path)),Cs=!!($?.path&&Xo($.path)),qs=!!($?.path&&Cd($.path)),xn=!!($&&!yt&&!Wt)&&!Nt&&!qs&&!(Cs&&te==="preview"),bn=i.useMemo(()=>Ie?qf(Ie):null,[Ie]),[Jn,Yr]=i.useState(null);i.useEffect(()=>{let U=!1;const Te=$?.path;if(!Te||bn){Yr(null);return}return Yr(null),ig(Te).then(We=>{U||Yr(We)}),()=>{U=!0}},[$?.path,bn]),i.useEffect(()=>{!Xe&&Q==="edit"&&K("view")},[Xe,Q]);const gi="openchamber:files:md-viewer-mode",xi="openchamber:files:html-viewer-mode",Qa="openchamber:files:json-viewer-mode";i.useEffect(()=>{const U=$?.path;if(!U)return;const Te=Dn?"view":"edit";K(le.current[U]??Te);let We=Dn?"preview":"edit";try{const it=localStorage.getItem(gi);(it==="preview"||it==="edit")&&(We=it)}catch{}re(Se.current[U]??We);let Ge=Dn?"preview":"edit";try{const it=localStorage.getItem(xi);(it==="preview"||it==="edit")&&(Ge=it)}catch{}Ne(Re.current[U]??Ge),H(_e.current[U]??"preview");let ct=Dn?"tree":"text";try{const it=localStorage.getItem(Qa);(it==="tree"||it==="text")&&(ct=it)}catch{}je(ct)},[$?.path,Dn]);const hh=i.useCallback(U=>{const Te=$?.path;Te&&(le.current[Te]=U),K(U)},[$?.path]),ph=i.useCallback(U=>{const Te=$?.path;Te&&(Se.current[Te]=U),re(U);try{localStorage.setItem(gi,U)}catch{}},[$?.path]),mo=i.useCallback(()=>ee,[ee]),gh=i.useCallback(U=>{je(U);try{localStorage.setItem(Qa,U)}catch{}},[]),xh=i.useCallback(U=>{const Te=$?.path;Te&&(Re.current[Te]=U),Ne(U);try{localStorage.setItem(xi,U)}catch{}},[$?.path]),bh=i.useCallback(U=>{const Te=$?.path;if(Te&&(_e.current[Te]=U),Ot.current&&(clearTimeout(Ot.current),Ot.current=null),He.current!==null&&(cancelAnimationFrame(He.current),He.current=null),U==="edit")Bt(It.current||ot),H(U);else{It.current=Lt;const We=Te;H("edit"),He.current=requestAnimationFrame(()=>{He.current=requestAnimationFrame(()=>{He.current=null,!(x&&We&&yn.getState().byRoot[x]?.selectedPath!==We)&&(ae(Ge=>Ge+1),H("preview"))})});return}},[Lt,ot,x,$?.path]),Ja=i.useCallback(async(U,Te)=>{if(!n.writeFile||Te===us.current)return!1;if(!(await n.writeFile(U,Te))?.success)return de.error(e("filesView.toast.writeFileFailed")),!1;It.current=Te,us.current=Te,Bt(Te);const Ge=await On(U,Ce).catch(()=>null);return Ge&&(Ye.current=Ge),!0},[n,On,Ce,e]);i.useEffect(()=>()=>{Ot.current&&(clearTimeout(Ot.current),Ot.current=null),He.current!==null&&(cancelAnimationFrame(He.current),He.current=null)},[J,$?.path]);const yh=i.useCallback(U=>{if(It.current=U,!$?.path||J!=="preview"||!n.writeFile)return;Ot.current&&clearTimeout(Ot.current);const Te=$.path;Ot.current=setTimeout(()=>{Ot.current=null,Ja(Te,U).then(We=>{We&&(ys(!0),setTimeout(()=>ys(!1),1500))}).catch(We=>{de.error(We instanceof Error?We.message:e("filesView.toast.saveFailed"))})},hi)},[J,n.writeFile,Ja,$?.path,e]),wh=i.useMemo(()=>qs&&(It.current||Lt)||ot,[Lt,ot,qs]),zc=i.useCallback(()=>te,[te]);i.useEffect(()=>{const U=We=>{const Ge=We?"view":"edit",ct=We?"preview":"edit",it=We?"tree":"text";for(const ts of Ae)le.current[ts]=Ge,Fu(ts)&&(Se.current[ts]=ct),Xo(ts)&&(Re.current[ts]=ct);K(Ge),re(ct),Ne(ct),je(it);try{localStorage.setItem(gi,ct),localStorage.setItem(xi,ct),localStorage.setItem(Qa,it)}catch{}},Te=We=>{const Ge=!!We.detail?.enabled;U(Ge)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",Te),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",Te)}},[Ae]),i.useEffect(()=>{if(!At||!x)return;const U=()=>{typeof window>"u"||mt.current===null&&(mt.current=window.requestAnimationFrame(()=>{mt.current=null,zt(Vr=>Vr+1)}))},Te=(Vr,bi)=>{if(Vr.state.doc.length!==bi.length)return!1;if(bi.length===0)return!0;const sl=Math.min(128,bi.length);if(Vr.state.sliceDoc(0,sl)!==bi.slice(0,sl))return!1;const rd=Math.max(0,bi.length-sl);return Vr.state.sliceDoc(rd,bi.length)===bi.slice(rd)},We=Ys(At.path);if(!We){os(null),cs.current={key:"",attempts:0};return}const Ge=`${We}:${At.line}:${At.column??1}`;if(cs.current.key!==Ge&&(cs.current={key:Ge,attempts:0}),$?.path!==We){if(js)return;Zs(xe(We));return}if(Le||qt!==We)return;if(Vt||yt||Wt){os(null),cs.current={key:"",attempts:0};return}if(!Xe)return;if(Q!=="edit"){K("edit");return}const ct=Je.current;if(!ct){U();return}if(!Te(ct,Lt)){U();return}const it=Math.max(1,Math.min(At.line,ct.state.doc.lines)),ts=ct.state.doc.line(it),Ms=Math.max(1,At.column||1),Vs=Math.max(0,ts.to-ts.from),xr=Math.min(Vs,Ms-1),mr=ts.from+xr;if(!(ct.state.selection.main.head===mr)||cs.current.attempts===0){cs.current.attempts+=1,ct.dispatch({selection:{anchor:mr},effects:si.scrollIntoView(mr,{y:"center"})}),ct.focus(),U();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const Vr=Je.current;Vr&&(Vr.dispatch({selection:{anchor:mr},effects:si.scrollIntoView(mr,{y:"center"})}),Vr.focus())}),os(null),cs.current={key:"",attempts:0}},[Xe,js,Lt,Ct,Vt,Le,yt,Wt,qt,Zs,At,x,$?.path,os,Q,xe]),i.useEffect(()=>{if(!rs||!x)return;const U=Ys(rs);if(!U){ds(null);return}if($?.path!==U){if(js)return;Zs(xe(U));return}if(!(Le||qt!==U||Vt||yt||Wt)){if(Xe&&Q==="edit"){const Te=Je.current;if(!Te)return;Te.focus()}ds(null)}},[Xe,js,Vt,Le,Zs,yt,Wt,qt,rs,x,$?.path,ds,Q,xe]);const Vi=i.useCallback(U=>{if(!d||!U||!U.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 ct=U.state.selection.main.head,it=U.coordsAtPos(ct);if(!it)return;const ts=Math.round(Te.offsetTop+Te.height),Vs=it.bottom+20-ts;Vs<=0||(U.scrollDOM.scrollTop+=Vs)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const U=()=>{window.requestAnimationFrame(()=>{Vi(Je.current)})},Te=window.visualViewport;return Te?.addEventListener("resize",U),Te?.addEventListener("scroll",U,{passive:!0}),document.addEventListener("selectionchange",U),()=>{Te?.removeEventListener("resize",U),Te?.removeEventListener("scroll",U),document.removeEventListener("selectionchange",U)}},[d,Vi]),i.useEffect(()=>{if(!Xe||Q!=="edit"||d)return;const U=ri("open_go_to_line",Es),Te=We=>{const Ge=We.target;if(Ge?.closest('[role="dialog"]'))return;const ct=!!Ge?.closest(".cm-editor");Ge?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!ct||!document.activeElement?.closest(".cm-editor")||ia(We,U)&&(We.preventDefault(),Sr(!0))};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[Xe,d,Es,Q]);const Wc=i.useMemo(()=>{if(!$?.path)return[Wl(o)];const U=Di($.path),Te=[Wl(o,U?{syntaxColors:!1}:void 0)],We=bn??Jn;return We&&Te.push(We),U&&Te.push(hm({language:U,themeName:o.metadata.id,theme:Yf(o)})),C&&Te.push(si.lineWrapping),d&&Te.push(si.updateListener.of(Ge=>{Ge.view.hasFocus&&(Ge.selectionSet||Ge.focusChanged||Ge.viewportChanged||Ge.geometryChanged)&&window.requestAnimationFrame(()=>{Vi(Ge.view)})})),Te},[o,$?.path,bn,Jn,C,d,Vi]),Uc=i.useMemo(()=>({light:Oe.metadata.id,dark:Me.metadata.id}),[Oe.metadata.id,Me.metadata.id]),Vo=$?.path&&yt&&!r.isDesktop&&!ls?`${$.path}|${Ce.allowOutsideWorkspace?"outside":"workspace"}|${Ce.outsideFileGrant??""}`:"",_o=$?.path&&Wt?`${$.path}|${Ce.allowOutsideWorkspace?"outside":"workspace"}|${Ce.outsideFileGrant??""}`:"",$o=$?.path&&Cs&&te==="preview"&&!r.isVSCode?$.path:"",Xa=e("filesView.error.readFileFailed"),{readyKey:Hc,nonce:Gc}=jl(Vo,xt,Xa),{readyKey:Kc,nonce:vh}=jl($o,xt,Xa),{readyKey:qc,nonce:Yc}=jl(_o,xt,Xa),Qc=!!(Vo&&Hc!==Vo),jh=!!($o&&Kc!==$o),Jc=!!(_o&&qc!==_o),Xc=$?.path&&yt?r.isDesktop?ls?`data:${Dd($.path)};utf8,${encodeURIComponent(ot)}`:Ft:ls?`data:${Dd($.path)};utf8,${encodeURIComponent(ot)}`:Hc===Vo?Ai().authenticatedAsset("/api/fs/raw",{path:$.path,allowOutsideWorkspace:Ce.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Ce.outsideFileGrant,directory:x||void 0}):"":"",Zc=$?.path&&Wt&&qc===_o?Ai().authenticatedAsset("/api/fs/raw",{path:$.path,allowOutsideWorkspace:Ce.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Ce.outsideFileGrant,directory:x||void 0}):"",ed=i.useCallback(U=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:Zc,className:"h-full w-full border-0",title:U.name},Yc)}),[Zc,Yc]);i.useEffect(()=>{let U=!1;return(async()=>{if(!r.isDesktop||!$?.path||!yt||ls){Ut.current&&(URL.revokeObjectURL(Ut.current),Ut.current=""),Gt("");return}xt(null),Ut.current&&(URL.revokeObjectURL(Ut.current),Ut.current=""),await(n.readFileBinary?n.readFileBinary($.path,Ce).then(Ge=>Ge.dataUrl):(async()=>{const Ge=await As("/api/fs/raw",{query:{path:$.path,allowOutsideWorkspace:Ce.allowOutsideWorkspace?"true":void 0,outsideFileGrant:Ce.outsideFileGrant,directory:x||void 0}});if(!Ge.ok)throw new Error(e("filesView.error.readFileFailed"));const ct=await Ge.blob(),it=URL.createObjectURL(ct);return U?(URL.revokeObjectURL(it),""):(Ut.current=it,it)})()).then(Ge=>{U||(Gt(Ge),Xt($.path))}).catch(Ge=>{Ut.current&&(URL.revokeObjectURL(Ut.current),Ut.current=""),U||(Gt(""),xt(Ge instanceof Error?Ge.message:e("filesView.error.readFileFailed")),Xt(null))}).finally(()=>{U||et(!1)})})(),()=>{U=!0}},[n,yt,ls,x,r.isDesktop,$?.path,Ce,e]),i.useEffect(()=>()=>{Ut.current&&(URL.revokeObjectURL(Ut.current),Ut.current="")},[]);const Sh=i.useCallback(()=>ks(null),[]),Nh=i.useMemo(()=>xm({drafts:dn,editingDraftId:Nn,commentText:Ln,onTextChange:In,selection:xs,isDragging:X,fileLabel:$?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:U=>({start:U.startLine,end:U.endLine}),onSave:Mi,onCancel:()=>{Rs(null),un()},onEdit:U=>{Br(U),Rs({start:U.startLine,end:U.endLine})},onDelete:Cr}),[un,Ln,Cr,Nn,dn,Mi,X,xs,$?.path,In,Br]),td=i.useCallback((U,Te)=>s.jsx("div",{className:"h-full",children:s.jsx(Eh,{file:{name:U.name,contents:Te,lang:Di(U.path)||void 0},options:{disableFileHeader:!0,overflow:C?"wrap":"scroll",theme:Uc,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,Uc,C]),Za=({exitFullscreenOnly:U=!1,layout:Te="floating"}={})=>{if(!$)return null;const Ge=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",ct=(it,ts)=>s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:ts})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:it})]});return s.jsxs("div",{className:Ge,children:[Xe&&Q==="edit"&&s.jsxs(s.Fragment,{children:[Yt?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):_t&&Tt==="saved"&&!Xs?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(I,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):Xs?ct(e(_t?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${rl()}+S`}),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{ur()},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(_t?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${rl()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${rl()}+S`}),children:s.jsx(I,{name:"save-3",className:"size-4"})})):null,ct(e(_t?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Ns(it=>!it),className:De("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",_t?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(_t?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(_t?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:_t?s.jsx(I,{name:"file-check-fill",className:"size-4"}):s.jsx(I,{name:"file-check",className:"size-4"})}))]}),s.jsxs(nn,{onOpenChange:Z,children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.openInDesktopApp"),"aria-label":e("filesView.editor.openInDesktopApp"),children:s.jsx(I,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(sn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Mr.map(it=>s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Kr(it)},children:[s.jsx(s1,{label:it.label,iconDataUrl:it.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:it.label})]},it.id)),Sn?s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{lr(!0)},children:[s.jsx(I,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!yt&&!Wt&&s.jsxs(s.Fragment,{children:[ct(e(C?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>O(!C),className:De("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",C?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(C?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(I,{name:"text-wrap",className:"size-4"})})),Q==="edit"&&s.jsxs(s.Fragment,{children:[ct(e("filesView.editor.findInFile"),s.jsx($e,{variant:"ghost",size:"sm",onClick:it=>{R(!F),it.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.findInFile"),children:s.jsx(I,{name:"search",className:"size-4"})})),ct(e("filesView.editor.goToLine"),s.jsx($e,{variant:"ghost",size:"sm",onClick:it=>{Sr(ts=>!ts),it.currentTarget.blur()},className:"size-6 p-0 text-foreground opacity-100 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.goToLine"),children:s.jsx(I,{name:"menu-fold-2",className:"size-4"})})),s.jsx(Xv,{open:sr,onOpenChange:Sr,view:Je.current,variant:"inline"})]})]}),xn&&Xe&&!Ht&&!Cs&&s.jsx(aa,{currentMode:Q==="view"?"preview":"edit",onToggle:()=>{hh(Q==="view"?"edit":"view")}}),(Nt||Xo($?.path??""))&&s.jsx(aa,{currentMode:Nt?mo():zc(),onToggle:()=>{Xo($?.path??"")?xh(zc()==="preview"?"edit":"preview"):ph(mo()==="preview"?"edit":"preview")}}),Nt&&mo()==="preview"&&Nr&&s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent","aria-label":e(Kt?"filesView.tts.stopSpeaking":"filesView.tts.readAloud"),onClick:()=>{Kt?$t():ot.trim()&&is(ot)},children:Kt?s.jsx(I,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"volume-up",className:"size-4"})})}),s.jsx(Mt,{sideOffset:8,children:e(Kt?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),qs&&s.jsxs(s.Fragment,{children:[s.jsx(aa,{currentMode:J,onToggle:()=>bh(J==="preview"?"edit":"preview")}),J==="preview"&&s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{const it=ft.current?.getXml();if(Ot.current&&(clearTimeout(Ot.current),Ot.current=null),$?.path&&it){if(!await Ja($.path,it))return;ys(!0),setTimeout(()=>ys(!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:Ss?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"save-3",className:"size-4"})})]}),Ht&&ct(e(he==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>gh(he==="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(he==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:he==="tree"?s.jsx(I,{name:"code-sslash",className:"size-4"}):s.jsx(I,{name:"node-tree",className:"size-4"})})),ie&&ct(e("filesView.editor.copyFileContents"),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await pr(ot)).ok?(Ws(!0),$s.current!==null&&window.clearTimeout($s.current),$s.current=window.setTimeout(()=>{Ws(!1)},1200)):de.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:rn?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"clipboard",className:"size-4"})})),lt&&ct(e("filesView.editor.copyFilePathTitle",{path:fr}),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await pr(fr)).ok?(Is(!0),we.current!==null&&window.clearTimeout(we.current),we.current=window.setTimeout(()=>{Is(!1)},1200)):de.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:fr}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:fr}),children:cn?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&&ct(e("filesView.editor.saveFile"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{const it=n.downloadFile;it&&it($.path).catch(ts=>{console.error("Download failed:",ts),de.error(e("sidebarFilesTree.toast.operationFailed"))})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.saveFile"),"aria-label":e("filesView.editor.saveFile"),children:s.jsx(I,{name:"download",className:"size-4"})})),U?ct(e("filesView.editor.exitFullscreen"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>E(!1),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.exitFullscreen"),"aria-label":e("filesView.editor.exitFullscreen"),children:s.jsx(I,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&&ct(e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>E(!T),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:T?s.jsx(I,{name:"fullscreen-exit",className:"size-4"}):s.jsx(I,{name:"fullscreen",className:"size-4"})}))]})},el=s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[s.jsx(Os,{open:js,onOpenChange:U=>{U||Ds(!0)},children:s.jsxs(Ls,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(Us,{children:[s.jsx(_s,{children:e("filesView.unsaved.title")}),s.jsx(an,{children:e("filesView.unsaved.description")})]}),s.jsxs(ar,{children:[s.jsx($e,{variant:"outline",onClick:()=>{fo()},disabled:Yt,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:e("filesView.unsaved.saveChanges")}),s.jsx($e,{variant:"destructive",onClick:uo,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:De("flex flex-col flex-shrink-0",b&&"border-b border-border/40"),children:[b?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&D&&s.jsx("button",{type:"button",onClick:()=>A(!1),"aria-label":e("filesView.editor.back"),className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(I,{name:"arrow-left-s",className:"size-5"})}),d?$?s.jsxs(nn,{children:[s.jsx(tn,{asChild:!0,children:s.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":e("filesView.editor.openFilesAria"),children:[s.jsx(Ur,{filePath:$.path,extension:$.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Eu,{name:$.name}),s.jsx(I,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(sn,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:_.map(U=>{const Te=$?.path===U.path;return s.jsxs(bs,{onSelect:We=>{if(We.target.closest("[data-close-open-file]")){We.preventDefault();return}Te||Zs(U)},className:De("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(Ur,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Eu,{name:U.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:We=>{We.preventDefault(),We.stopPropagation()},onClick:We=>{We.preventDefault(),We.stopPropagation(),Bi(U.path)},className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":e("filesView.editor.closeFileAria",{name:U.name}),children:s.jsx(I,{name:"close",className:"size-3.5"})})]},U.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):_.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[P.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"}),P.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:ne,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:_.map(U=>{const Te=$?.path===U.path;return s.jsxs("div",{title:Xl(x,U.path),className:De("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(Ur,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{Te||Zs(U)},className:"max-w-[12rem] truncate text-left",children:U.name}),s.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),Bi(U.path)},className:De("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Te&&!f&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:U.name}),children:s.jsx(I,{name:"close",className:"size-3.5"})})]},U.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,kr&&!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:[fr?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:fr,children:fr}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:Za({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[$&&!F&&!(kr&&!d)&&s.jsx("div",{ref:V,className:"absolute right-3 top-3 z-30",onMouseEnter:()=>B(!0),onMouseLeave:()=>{M.current>0||B(!1)},children:L?Za():s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>B(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":e("filesView.editor.showControlsAria"),title:e("filesView.editor.controlsTitle"),children:s.jsx(I,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})}),s.jsx(Wn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:$?Le||Qc||Jc?h?s.jsx("div",{className:"p-3"}):s.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.loading")]}):Vt?s.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:Vt}):yt?s.jsx("div",{className:"flex h-full items-center justify-center p-3",children:s.jsx("img",{src:Xc,alt:$?.name??e("filesView.editor.imageAltFallback"),className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},Gc)}):Wt?ed($):$&&qs&&J==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(e1,{ref:ft,xml:wh,onChange:yh},`${$.path}:${q}`)}):$&&Ht&&he==="tree"?s.jsx(en,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.jsonViewerUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToTextMode")})]}),children:s.jsx("div",{className:"h-full overflow-auto",children:s.jsx(og,{jsonString:ot,maxHeight:"100%",initiallyExpandedDepth:2})})}):$&&Nt&&mo()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-3",children:[ot.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(ot.length/1024)})}),s.jsx(en,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(Po,{content:ot,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):$&&Cs&&te==="preview"?jh?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&&Kc===$o?(()=>{const U=$.path.split("/").map(Te=>encodeURIComponent(Te)).join("/");return Ai().authenticatedAsset(`/api/fs/serve${U.startsWith("/")?U:`/${U}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const U=$.path.substring(0,$.path.lastIndexOf("/")+1);return U?ot.replace(/<head([^>]*)>/i,`<head$1><base href="${U}">`):ot})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")},vh)}):$&&xn&&Q==="view"?td($,Lt):s.jsxs("div",{className:De("relative h-full",Bn&&"overflow-hidden"),ref:vt,children:[s.jsx("div",{className:De("h-full",Bn&&"invisible"),children:s.jsx(Ul,{value:Lt,onChange:Bt,readOnly:!Xe,vimMode:Gs==="vim",extensions:Wc,className:"h-full",blockWidgets:Nh,onViewReady:U=>{Je.current=U,zt(Te=>Te+1),window.requestAnimationFrame(()=>{Vi(U)})},onViewDestroy:()=>{Je.current&&(Je.current=null),zt(U=>U+1)},enableSearch:!0,searchOpen:F,onSearchOpenChange:R,highlightLines:xs?{start:Math.min(xs.start,xs.end),end:Math.max(xs.start,xs.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(U,Te,We)=>{if(!(We instanceof MouseEvent)||We.button!==0)return!1;We.preventDefault();const Ge=U.state.doc.lineAt(Te.from).number;if(xs&&!We.shiftKey&&Math.min(xs.start,xs.end)===Ge&&Math.max(xs.start,xs.end)===Ge)return Rs(null),un(),qn.current=!1,pn.current=null,st(!1),!0;if(d&&xs&&!We.shiftKey){const ct=Math.min(xs.start,xs.end,Ge),it=Math.max(xs.start,xs.end,Ge);return Rs({start:ct,end:it}),qn.current=!1,pn.current=null,st(!1),!0}if(qn.current=!0,pn.current=Ge,st(!0),xs&&We.shiftKey){const ct=Math.min(xs.start,Ge),it=Math.max(xs.end,Ge);Rs({start:ct,end:it})}else Rs({start:Ge,end:Ge});return!0},mouseover:(U,Te,We)=>{if(!(We instanceof MouseEvent)||We.buttons!==1||!qn.current||pn.current===null)return!1;const Ge=U.state.doc.lineAt(Te.from).number,ct=Math.min(pn.current,Ge),it=Math.max(pn.current,Ge);return Rs({start:ct,end:it}),st(!0),!1},mouseup:()=>(qn.current=!1,pn.current=null,st(!1),!1)}}})}),Bn&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]}):s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:e("filesView.editor.pickFileFromTree")})})]})]}),kh=!!(x&&Ue[x]),sd=x?Qe[x]:null,nd=s.jsxs("section",{className:De("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:De("flex flex-col gap-2 py-2",d?"px-3":"px-2"),children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx(I,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(vn,{ref:v,value:S,onChange:U=>j(U.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:()=>{j(""),v.current?.focus()},children:s.jsx(I,{name:"close",className:"size-4"})})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Lr("createFile",{path:p,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFileTitle"),"aria-label":e("filesView.tree.actions.newFileTitle"),children:s.jsx(I,{name:"file-add",className:"size-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Lr("createFolder",{path:p,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFolderTitle"),"aria-label":e("filesView.tree.actions.newFolderTitle"),children:s.jsx(I,{name:"folder-add",className:"size-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{dr()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(I,{name:"refresh",className:"size-4"})})})}),s.jsx(Mt,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx(Wn,{outerClassName:"flex-1 min-h-0",className:De("py-2",d?"px-3":"px-2"),children:s.jsx("ul",{className:"flex flex-col",children:Dt?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):nt.length>0?nt.map(U=>{const Te=$?.path===U.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{Zs(U)},className:De("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:[Bm(U.path,U.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:U.path,children:U.relativePath??U.path})]})},U.path)}):sd?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:sd}),s.jsxs($e,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{dr()},children:[s.jsx(I,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):kh?dt(x,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),Ch=t==="full"&&T&&$&&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:Za({exitFullscreenOnly:!0})}),s.jsx(Wn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:Le||Qc||Jc?h?s.jsx("div",{className:"p-4"}):s.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):Vt?s.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:Vt}):yt?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("img",{src:Xc,alt:$.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},Gc)}):Wt?ed($):Nt&&mo()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-4",children:[ot.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(ot.length/1024)})}),s.jsx(en,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(Po,{content:ot,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):xn&&Q==="view"?td($,Lt):s.jsxs("div",{className:De("relative h-full",Bn&&"overflow-hidden"),children:[s.jsx("div",{className:De("h-full",Bn&&"invisible"),children:s.jsx(Ul,{value:Lt,onChange:Bt,readOnly:!Xe,vimMode:Gs==="vim",extensions:Wc,className:"h-full",onViewReady:U=>{Je.current=U,window.requestAnimationFrame(()=>{Vi(U)})},onViewDestroy:()=>{Je.current&&(Je.current=null)}})}),Bn&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]})})]})});return s.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[s.jsx(p1,{activeDialog:fs,dialogData:ms,dialogInputValue:zs,onDialogInputChange:hn,isDialogSubmitting:tr,onDialogSubmit:fi,onClose:Sh,inputRef:vs}),Ch,d?D?el:nd: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:el})}):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:nd}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:el})]})]})};function g1(t){return t+1}const vr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Sl=(t,e)=>{const n=vr(t),r=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},x1=(t,e,n)=>Sl(Sl(Sl(t,".opencode"),"plans"),`${e}-${n}.md`),b1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,y1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},w1=(t,e)=>{const n=vr(e.currentDirectory),r=vr(e.homeDirectory),o=vr(t);return n&&o.startsWith(n+"/")?o.slice(n.length+1):r&&o===r?"~":r&&o.startsWith(r+"/")?`~${o.slice(r.length)}`:o},v1=(t,e,n)=>{const r=vr(t.trim());if(!r)return null;const o=n?e.find(c=>c.id===n)??null:null;if(o?.path){const c=vr(o.path);if(r===c||r.startsWith(`${c}/`))return{id:o.id,path:o.path}}const a=e.filter(c=>{const l=vr(c.path);return r===l||r.startsWith(`${l}/`)}).sort((c,l)=>vr(l.path).length-vr(c.path).length)[0];return a?{id:a.id,path:a.path}:null},_m=({targetPath:t=null})=>{const{t:e}=kt(),n=ut(oe=>oe.currentSessionId),r=ut(oe=>oe.createSession),o=ut(oe=>oe.initializeNewOpenChamberSession),a=ut(oe=>oe.sendMessage),c=ut(oe=>oe.setCurrentSession),l=jc(),d=Qs(oe=>oe.homeDirectory),u=hc(oe=>oe.planModeEnabled),m=ws(oe=>oe.projects),f=ws(oe=>oe.activeProjectId),g=wn(oe=>oe.directories),y=ci()??"",p=Ee(oe=>oe.setActiveMainTab),x=Ee(oe=>oe.setSessionSwitcherOpen),b=er(),{isMobile:h}=Er(),{currentTheme:N}=Gr(),w=i.useMemo(()=>n?l.find(oe=>oe.id===n)??null:null,[n,l]),S=i.useMemo(()=>{const oe=typeof w?.directory=="string"?w.directory:"";return vr(oe||"")},[w?.directory]),j=i.useMemo(()=>vr(y||S),[y,S]),k=i.useMemo(()=>v1(j,m,f),[f,j,m]),v=i.useMemo(()=>k?g.get(k.path)?.isGitRepo===!0:!1,[k,g]),[D,A]=i.useState(null),[C,O]=i.useState(!1),[T,E]=i.useState(null),F=i.useMemo(()=>!T||!S||!d?T:w1(T,{currentDirectory:S,homeDirectory:d}),[T,S,d]),[R,L]=i.useState(""),{isPlaying:B,play:V,stop:M}=Kf(),Z=ss(oe=>oe.showMessageTTSButtons),[se,Q]=i.useState(null),K=i.useMemo(()=>F&&F.split("/").pop()||e("planView.file.defaultName"),[F,e]),ee=i.useMemo(()=>R.trim()&&ag(R).title||e("planView.title.default"),[R,e]),re=i.useMemo(()=>ee.trim()||e("planView.title.default"),[ee,e]),[he,je]=i.useState(!1),[te,Ne]=i.useState(!1),[J,H]=i.useState("edit"),q=i.useRef(null),[ae,le]=i.useState(null),Se=i.useRef(null),Re=i.useRef(null),_e="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const oe=localStorage.getItem(_e);if(!oe)return;const Be=JSON.parse(oe);(Be==="preview"||Be==="edit")&&H(Be)}catch{}},[]);const Oe=i.useCallback(oe=>{H(oe);try{localStorage.setItem(_e,JSON.stringify(oe))}catch{}},[]),Me=i.useRef(!1),ge=i.useRef(null),[Ae,pe]=i.useState(!1);i.useEffect(()=>{const oe=()=>{Me.current=!1,ge.current=null,pe(!1)};return document.addEventListener("mouseup",oe),()=>document.removeEventListener("mouseup",oe)},[]);const ue=i.useCallback((oe,Be)=>{const Ue=oe.split(`
34
- `),Ke=Math.max(1,Be.start),Qe=Math.min(Ue.length,Be.end);return Ke>Qe?"":Ue.slice(Ke-1,Qe).join(`
35
- `)},[]),G=fm({source:"plan",fileLabel:K,language:T&&Di(T)||"markdown",getCodeForRange:oe=>ue(R,mm(oe)),toStoreRange:oe=>({startLine:oe.start,endLine:oe.end}),fromDraftRange:oe=>({start:oe.startLine,end:oe.endLine})}),{drafts:fe,commentText:ce,setCommentText:W,editingDraftId:z,setSelection:be,saveComment:xe,cancel:_,reset:ye,startEdit:$,deleteDraft:Ie}=G;i.useEffect(()=>{le(null),ye()},[R,ye]),i.useEffect(()=>{be(ae)},[ae,be]);const ve=i.useCallback(()=>{le(null),_()},[_]),Fe=i.useCallback((oe,Be)=>{Be&&le(Be),xe(oe,Be??ae??void 0),le(null)},[ae,xe]);i.useEffect(()=>{if(!ae)return;const oe=Ue=>{const Ke=Ue.target;Ke.closest('[data-comment-card="true"]')||Ke.closest('[data-comment-input="true"]')||Ke.closest(".oc-block-widget")||Ke.closest(".cm-gutterElement")||Ke.closest("[data-sonner-toast]")||Ke.closest("[data-sonner-toaster]")||ce.trim()||(le(null),_())},Be=window.setTimeout(()=>{document.addEventListener("click",oe)},100);return()=>{window.clearTimeout(Be),document.removeEventListener("click",oe)}},[_,ce,z,h,ae]);const Ce=i.useMemo(()=>{const oe=T?Di(T):null,Be=!!oe&&oe!=="markdown",Ue=[Wl(N,Be?{syntaxColors:!1}:void 0)],Ke=qf(T||"plan.md");return Ke&&Ue.push(Ke),Be&&oe&&Ue.push(hm({language:oe,themeName:N.metadata.id,theme:Yf(N)})),Ue.push(si.lineWrapping),Ue},[N,T]);i.useEffect(()=>{if(!u&&!t){E(null),L(""),je(!1);return}let oe=!1;const Be=async Ke=>{if(b.files?.readFile)return(await b.files.readFile(Ke))?.content??"";const Qe=Lo()?.files;if(Qe?.readFile)return(await Qe.readFile(Ke,{optional:!0}))?.content??"";const rt=await As(`/api/fs/read?path=${encodeURIComponent(Ke)}&optional=true`,{cache:"no-store"});if(!rt.ok)throw new Error(`Failed to read plan file (${rt.status})`);return rt.text()};return(async()=>{if(E(null),L(""),Q(null),t){je(!0);try{const Ke=await Be(t);if(oe)return;E(t),L(Ke)}catch{if(oe)return;E(null),L("")}finally{oe||je(!1)}return}if(!w?.slug||!w?.time?.created||!S){E(null),L("");return}je(!0);try{const Ke=x1(S,w.time.created,w.slug),Qe=y1(b1(w.time.created,w.slug),d||null);let rt=null,pt=null;try{pt=await Be(Ke),rt=Ke}catch{}if(!rt)try{pt=await Be(Qe),rt=Qe}catch{}if(oe)return;if(!rt||pt===null){E(null),L("");return}E(rt),L(pt)}catch{if(oe)return;E(null),L("")}finally{oe||je(!1)}})(),()=>{oe=!0}},[d,u,b.files,S,w?.slug,w?.time?.created,t]),i.useEffect(()=>{if(!T){Q(null);return}const oe=window.setTimeout(async()=>{Q(null);try{if(b.files?.writeFile){if(!(await b.files.writeFile(T,R))?.success)throw new Error(e("planView.error.writeFailed"))}else{const Be=await As("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:T,content:R})});if(!Be.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:Be.status}))}}catch(Be){Q(Be instanceof Error?Be.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(oe)}},[R,T,b.files,e]),i.useEffect(()=>()=>{q.current!==null&&window.clearTimeout(q.current)},[]);const ne=i.useCallback(()=>{p("chat"),x(!1)},[p,x]),P=i.useCallback(async oe=>{if(!k||!D)return;const Be=await Fn(D.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:re}),Ke=[{synthetic:!0,text:await Fn(D.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:re,plan_path:T??""})}];O(!0);try{ne();let Qe=null,rt=k.path;if(D.target==="worktree"){if(!v)return;const jt=await Wf(k.path,Uf());if(!jt?.id)return;Qe=jt.id,rt=jt.path}else{const jt=await r(void 0,k.path,null);if(!jt?.id)return;Qe=jt.id,rt=jt.directory??k.path,o(jt.id,ss.getState().agents??[])}if(!Qe)return;const pt=xc.getState();pt.saveSessionModelSelection(Qe,oe.providerID,oe.modelID),oe.agent.trim()&&(pt.saveSessionAgentSelection(Qe,oe.agent),pt.saveAgentModelForSession(Qe,oe.agent,oe.providerID,oe.modelID),pt.saveAgentModelVariantForSession(Qe,oe.agent,oe.providerID,oe.modelID,oe.variant||void 0)),c(Qe,rt),await a(Be,oe.providerID,oe.modelID,oe.agent.trim()||void 0,void 0,void 0,Ke,oe.variant||void 0),A(null)}finally{O(!1)}},[v,r,k,o,D,T,ne,a,re,c]),me=i.useMemo(()=>xm({drafts:fe,editingDraftId:z,commentText:ce,onTextChange:W,selection:ae,isDragging:Ae,fileLabel:K,newWidgetId:"plan-new-comment-input",mapDraftToRange:oe=>({start:oe.startLine,end:oe.endLine}),onSave:Fe,onCancel:ve,onEdit:oe=>{$(oe),le({start:oe.startLine,end:oe.endLine})},onDelete:Ie}),[ce,Ie,z,ve,Fe,Ae,ae,fe,K,W,$]);return s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"typography-ui-label font-medium truncate",children:ee}),se?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:se,children:e("planView.error.saveFailed")}):null]}),T?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(nn,{children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.improvePlanAria"),disabled:!R.trim(),children:s.jsx(I,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(Mt,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(sn,{align:"end",children:[s.jsx(bs,{onClick:()=>A({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(bs,{onClick:()=>A({action:"improve",target:"worktree"}),disabled:!v,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(nn,{children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.implementPlanAria"),disabled:!R.trim(),children:s.jsx(I,{name:"code-ai",className:"size-4"})})})}),s.jsx(Mt,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(sn,{align:"end",children:[s.jsx(bs,{onClick:()=>A({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(bs,{onClick:()=>A({action:"implement",target:"worktree"}),disabled:!v,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(aa,{currentMode:J,onToggle:()=>Oe(J==="preview"?"edit":"preview")}),J==="preview"&&Z&&s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(B?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{B?M():R.trim()&&V(R)},children:B?s.jsx(I,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(Mt,{sideOffset:8,children:e(B?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await pr(R)).ok&&(Ne(!0),q.current!==null&&window.clearTimeout(q.current),q.current=window.setTimeout(()=>{Ne(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:te?s.jsx(I,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(wm,{open:D!==null,onOpenChange:oe=>{!oe&&!C&&A(null)},target:D?.target??"session",projectDirectory:k?.path??null,submitting:C,onConfirm:P}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(Wn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:he?s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:e("planView.state.loading")}):s.jsx("div",{className:"relative h-full",children:s.jsx("div",{className:"h-full",children:J==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(en,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("planView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("planView.error.switchToEditMode")})]}),children:s.jsx(Po,{content:R,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:Re,children:s.jsx(Ul,{value:R,onChange:L,readOnly:!1,className:"h-full",extensions:Ce,onViewReady:oe=>{Se.current=oe},onViewDestroy:()=>{Se.current=null},blockWidgets:me,highlightLines:ae?{start:Math.min(ae.start,ae.end),end:Math.max(ae.start,ae.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(oe,Be,Ue)=>{if(!(Ue instanceof MouseEvent)||Ue.button!==0)return!1;Ue.preventDefault();const Ke=oe.state.doc.lineAt(Be.from).number;if(ae&&!Ue.shiftKey&&Math.min(ae.start,ae.end)===Ke&&Math.max(ae.start,ae.end)===Ke)return le(null),_(),Me.current=!1,ge.current=null,pe(!1),!0;if(h&&ae&&!Ue.shiftKey){const Qe=Math.min(ae.start,ae.end,Ke),rt=Math.max(ae.start,ae.end,Ke);return le({start:Qe,end:rt}),Me.current=!1,ge.current=null,pe(!1),!0}if(Me.current=!0,ge.current=Ke,pe(!0),ae&&Ue.shiftKey){const Qe=Math.min(ae.start,Ke),rt=Math.max(ae.end,Ke);le({start:Qe,end:rt})}else le({start:Ke,end:Ke});return!0},mouseover:(oe,Be,Ue)=>{if(!(Ue instanceof MouseEvent)||Ue.buttons!==1||!Me.current||ge.current===null)return!1;const Ke=oe.state.doc.lineAt(Be.from).number,Qe=Math.min(ge.current,Ke),rt=Math.max(ge.current,Ke);return le({start:Qe,end:rt}),pe(!0),!1},mouseup:()=>(Me.current=!1,ge.current=null,pe(!1),!1)}}})})})})})})]})},j1=8,Oc=t=>t,Zl=t=>{const e=Oc(t).type;return typeof e=="string"?e:""},S1=t=>{const e=Oc(t).tool;return typeof e=="string"?e:""},N1=t=>{const e=Oc(t).text;return typeof e=="string"?e:""},k1=t=>{const e=Zl(t);return e==="tool"?S1(t).trim().toLowerCase()||"tool":e||"unknown"},C1=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=k1(n);e.includes(r)||e.push(r)}return e.join(" + ")},A1=(t,e=j1)=>typeof t!="string"?"":t.length<=e?t:t.slice(-e),D1=t=>t.replace(/\s+/g," ").trim(),I1=t=>{for(const n of t)if(Zl(n)==="text"){const r=D1(N1(n));if(r.length===0)continue;return r}const e=t.filter(n=>Zl(n)!=="text").length;return e===0?"":`${e} attachment${e===1?"":"s"}`},P1=(t,e,n)=>`${n(t)} / ${n(e)}`,T1=t=>{if(t==="12h")return!0;if(t==="24h")return!1},R1=(t,e)=>{if(!t||!Number.isFinite(t))return"-";const n=T1(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}})},ec={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},ca={user:0,assistant:0,tool:0,other:0},ji=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Nl=t=>{const e=t.info.tokens,n=e!==void 0?e:t.parts.find(u=>u.tokens!==void 0)?.tokens;if(typeof n=="number")return{...ec,total:ji(n)};if(!n||typeof n!="object")return ec;const r=n,o=ji(r.input),a=ji(r.output),c=ji(r.reasoning),l=ji(r.cache?.read),d=ji(r.cache?.write);return{input:o,output:a,reasoning:c,cacheRead:l,cacheWrite:d,total:o+a+c+l+d}},E1=(...t)=>{for(const e of t)if(typeof e=="string"&&e.trim().length>0)return e;return""},ir=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+ir(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+ir(n),0):0,M1=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...ca,assistant:ir(n.text)+ir(n.content)};const o=E1(n.text,n.content,n.value,n.source?.value,n.source?.text?.value);return r==="tool"||e==="tool"?{user:0,assistant:0,tool:ir(n.input)+ir(n.output)+ir(n.error)+ir(n.call?.input)+ir(n.call?.output)+ir(n.call?.error)+ir(n.raw)+Math.round(ir(n.metadata)*.25)+Math.round(ir(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}},Lu=(t,e)=>({user:t.user+e.user,assistant:t.assistant+e.assistant,tool:t.tool+e.tool,other:t.other+e.other}),F1=t=>{const e=Oo(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},L1=(t,e)=>{if(t.length===0)return{...ca};const n=t.reduce((r,o)=>{const a=F1(o);let c={...ca};for(const l of o.parts)c=Lu(c,M1(l,a));return Lu(r,c)},{...ca});return n.user+=e.length,{user:Math.ceil(n.user/4),assistant:Math.ceil(n.assistant/4),tool:Math.ceil(n.tool/4),other:Math.ceil(n.other/4)}},Si=t=>t.toLocaleString(Zi()),O1=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(Zi(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(Zi(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),B1=(t,e)=>!t||!Number.isFinite(t)?"-":bc(t,e,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),V1=(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}},_1=()=>{const t=gt.c(202),{t:e}=kt(),n=Ee($1);let r;t[0]===Symbol.for("react.memo_cache_sentinel")?(r={},t[0]=r):r=t[0];const[o,a]=i.useState(r),[c,l]=i.useState(null),d=i.useRef(null),u=ut(z1),m=jc(),f=lg(u??""),g=ss(W1);let y;t[1]===Symbol.for("react.memo_cache_sentinel")?(y=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(U1),l(null)},t[1]=y):y=t[1];let p;t[2]!==u?(p=[u],t[2]=u,t[3]=p):p=t[3],i.useEffect(y,p);let x,b;t[4]===Symbol.for("react.memo_cache_sentinel")?(x=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},b=[],t[4]=x,t[5]=b):(x=t[4],b=t[5]),i.useEffect(x,b);let h;t[6]===Symbol.for("react.memo_cache_sentinel")?(h=async(xt,Ft)=>{(await pr(Ft)).ok?(l(xt),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(Ut=>Ut===xt?null:Ut),d.current=null},2e3)):l(null)},t[6]=h):h=t[6];const N=h;let w;t[7]!==u||t[8]!==m?(w=u?m.find(xt=>xt.id===u)??null:null,t[7]=u,t[8]=m,t[9]=w):w=t[9];const S=w;let j,k,v,D,A,C;if(t[10]!==g||t[11]!==f){j=f.filter(H1);let xt;t[18]!==f?(xt=f.filter(G1),t[18]=f,t[19]=xt):xt=t[19],C=xt;let Ft=null;for(let Ut=j.length-1;Ut>=0;Ut=Ut-1,Ut){const qt=j[Ut];if(Nl(qt).total>0){Ft=qt;break}}D=Ft?Nl(Ft):ec,k=cg({input:D.input,cache:{read:D.cacheRead,write:D.cacheWrite}}),A=j.reduce(K1,0);const Gt=Ft?.info??null;v=V1(g,Gt?.providerID||"",Gt?.modelID||""),t[10]=g,t[11]=f,t[12]=j,t[13]=k,t[14]=v,t[15]=D,t[16]=A,t[17]=C}else j=t[12],k=t[13],v=t[14],D=t[15],A=t[16],C=t[17];const O=v,T=O.contextLimit,E=T&&T>0?Math.min(999,D.total/T*100):0;let F;if(t[20]!==f){const xt=[...f].reverse().find(q1)?.info?.system||"";F=L1(f,xt),t[20]=f,t[21]=F}else F=t[21];const R=F,L=R.user,B=R.assistant,V=R.tool,M=Math.max(0,D.input-L-B-V),Z=L+B+V+M,se=f[0]?.info?.time?.created,Q=f.length>0?f[f.length-1]?.info?.time?.created:null;let K;t[22]!==S?.title||t[23]!==e?(K=S?.title||e("contextSidebar.session.untitled"),t[22]=S?.title,t[23]=e,t[24]=K):K=t[24];const ee=S?.time?.created??se??null,re=Q??S?.time?.created??null;let he;t[25]!==B||t[26]!==M||t[27]!==V||t[28]!==L?(he={user:L,assistant:B,tool:V,other:M},t[25]=B,t[26]=M,t[27]=V,t[28]=L,t[29]=he):he=t[29];let je;t[30]!==j.length||t[31]!==Z||t[32]!==k||t[33]!==T||t[34]!==O||t[35]!==f.length||t[36]!==ee||t[37]!==re||t[38]!==he||t[39]!==K||t[40]!==D||t[41]!==A||t[42]!==E||t[43]!==C.length?(je={sessionTitle:K,messagesCount:f.length,userMessagesCount:C.length,assistantMessagesCount:j.length,createdAt:ee,lastActivityAt:re,providerModel:O,tokenBreakdown:D,usagePercent:E,cacheHitRate:k,totalAssistantCost:A,contextLimit:T,breakdown:he,breakdownTotal:Z},t[30]=j.length,t[31]=Z,t[32]=k,t[33]=T,t[34]=O,t[35]=f.length,t[36]=ee,t[37]=re,t[38]=he,t[39]=K,t[40]=D,t[41]=A,t[42]=E,t[43]=C.length,t[44]=je):je=t[44];const te=je;if(!u){let xt;t[45]!==e?(xt=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=xt):xt=t[46];let Ft;return t[47]!==xt?(Ft=s.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:xt}),t[47]=xt,t[48]=Ft):Ft=t[48],Ft}let Ne;t[49]!==e?(Ne=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=Ne):Ne=t[50];let J;t[51]!==Ne||t[52]!==te.breakdown.user?(J={key:"user",label:Ne,value:te.breakdown.user,color:"var(--status-success)"},t[51]=Ne,t[52]=te.breakdown.user,t[53]=J):J=t[53];let H;t[54]!==e?(H=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=H):H=t[55];let q;t[56]!==H||t[57]!==te.breakdown.assistant?(q={key:"assistant",label:H,value:te.breakdown.assistant,color:"var(--primary-base)"},t[56]=H,t[57]=te.breakdown.assistant,t[58]=q):q=t[58];let ae;t[59]!==e?(ae=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=ae):ae=t[60];let le;t[61]!==ae||t[62]!==te.breakdown.tool?(le={key:"tool",label:ae,value:te.breakdown.tool,color:"var(--status-warning)"},t[61]=ae,t[62]=te.breakdown.tool,t[63]=le):le=t[63];let Se;t[64]!==e?(Se=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=Se):Se=t[65];let Re;t[66]!==Se||t[67]!==te.breakdown.other?(Re={key:"other",label:Se,value:te.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=Se,t[67]=te.breakdown.other,t[68]=Re):Re=t[68];let _e;t[69]!==J||t[70]!==q||t[71]!==le||t[72]!==Re?(_e=[J,q,le,Re],t[69]=J,t[70]=q,t[71]=le,t[72]=Re,t[73]=_e):_e=t[73];const Oe=_e;let Me;t[74]!==te.sessionTitle?(Me=s.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:te.sessionTitle}),t[74]=te.sessionTitle,t[75]=Me):Me=t[75];let ge;t[76]!==te.providerModel.modelName||t[77]!==te.providerModel.providerName?(ge=s.jsxs("span",{children:[te.providerModel.providerName," / ",te.providerModel.modelName]}),t[76]=te.providerModel.modelName,t[77]=te.providerModel.providerName,t[78]=ge):ge=t[78];let Ae;t[79]!==n||t[80]!==te.createdAt?(Ae=te.createdAt&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:B1(te.createdAt,n)})]}),t[79]=n,t[80]=te.createdAt,t[81]=Ae):Ae=t[81];let pe;t[82]!==ge||t[83]!==Ae?(pe=s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 typography-micro text-muted-foreground/70",children:[ge,Ae]}),t[82]=ge,t[83]=Ae,t[84]=pe):pe=t[84];let ue;t[85]!==Me||t[86]!==pe?(ue=s.jsxs("div",{className:"mb-6",children:[Me,pe]}),t[85]=Me,t[86]=pe,t[87]=ue):ue=t[87];let G;t[88]!==e?(G=e("contextSidebar.section.context"),t[88]=e,t[89]=G):G=t[89];let fe;t[90]!==G?(fe=s.jsx("span",{className:"typography-micro text-muted-foreground",children:G}),t[90]=G,t[91]=fe):fe=t[91];let ce;t[92]!==te.tokenBreakdown.total?(ce=Si(te.tokenBreakdown.total),t[92]=te.tokenBreakdown.total,t[93]=ce):ce=t[93];let W;t[94]!==te.contextLimit?(W=te.contextLimit?` / ${Si(te.contextLimit)}`:"",t[94]=te.contextLimit,t[95]=W):W=t[95];let z;t[96]!==ce||t[97]!==W?(z=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[ce,W]}),t[96]=ce,t[97]=W,t[98]=z):z=t[98];let be;t[99]!==fe||t[100]!==z?(be=s.jsxs("div",{className:"flex items-baseline justify-between",children:[fe,z]}),t[99]=fe,t[100]=z,t[101]=be):be=t[101];let xe;t[102]!==te.usagePercent?(xe=te.usagePercent>0&&s.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,te.usagePercent)}%`,backgroundColor:te.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}}),t[102]=te.usagePercent,t[103]=xe):xe=t[103];let _;t[104]!==xe?(_=s.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:xe}),t[104]=xe,t[105]=_):_=t[105];let ye;t[106]!==e||t[107]!==te.usagePercent?(ye=e("contextSidebar.context.percentUsed",{percent:te.usagePercent.toFixed(1)}),t[106]=e,t[107]=te.usagePercent,t[108]=ye):ye=t[108];let $;t[109]!==ye?($=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:ye}),t[109]=ye,t[110]=$):$=t[110];let Ie;t[111]!==be||t[112]!==_||t[113]!==$?(Ie=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[be,_,$]}),t[111]=be,t[112]=_,t[113]=$,t[114]=Ie):Ie=t[114];let ve;t[115]!==e?(ve=e("contextSidebar.stats.messages"),t[115]=e,t[116]=ve):ve=t[116];let Fe;t[117]!==te.messagesCount?(Fe=Si(te.messagesCount),t[117]=te.messagesCount,t[118]=Fe):Fe=t[118];let Ce;t[119]!==ve||t[120]!==Fe?(Ce={label:ve,value:Fe},t[119]=ve,t[120]=Fe,t[121]=Ce):Ce=t[121];let ne;t[122]!==e?(ne=e("contextSidebar.stats.user"),t[122]=e,t[123]=ne):ne=t[123];let P;t[124]!==te.userMessagesCount?(P=Si(te.userMessagesCount),t[124]=te.userMessagesCount,t[125]=P):P=t[125];let me;t[126]!==ne||t[127]!==P?(me={label:ne,value:P},t[126]=ne,t[127]=P,t[128]=me):me=t[128];let oe;t[129]!==e?(oe=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=oe):oe=t[130];let Be;t[131]!==te.assistantMessagesCount?(Be=Si(te.assistantMessagesCount),t[131]=te.assistantMessagesCount,t[132]=Be):Be=t[132];let Ue;t[133]!==oe||t[134]!==Be?(Ue={label:oe,value:Be},t[133]=oe,t[134]=Be,t[135]=Ue):Ue=t[135];let Ke;t[136]!==e?(Ke=e("contextSidebar.stats.cost"),t[136]=e,t[137]=Ke):Ke=t[137];let Qe;t[138]!==te.totalAssistantCost?(Qe=O1(te.totalAssistantCost),t[138]=te.totalAssistantCost,t[139]=Qe):Qe=t[139];let rt;t[140]!==Ke||t[141]!==Qe?(rt={label:Ke,value:Qe},t[140]=Ke,t[141]=Qe,t[142]=rt):rt=t[142];let pt;t[143]!==Ce||t[144]!==me||t[145]!==Ue||t[146]!==rt?(pt=[Ce,me,Ue,rt],t[143]=Ce,t[144]=me,t[145]=Ue,t[146]=rt,t[147]=pt):pt=t[147];const jt=pt;let Ve;t[148]!==jt?(Ve=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:jt.map(Y1)}),t[148]=jt,t[149]=Ve):Ve=t[149];let Ze;t[150]!==e?(Ze=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Ze):Ze=t[151];let nt;t[152]!==Ze?(nt=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Ze}),t[152]=Ze,t[153]=nt):nt=t[153];let St;t[154]!==e||t[155]!==te.cacheHitRate.hasInput||t[156]!==te.cacheHitRate.percent||t[157]!==te.tokenBreakdown.cacheRead||t[158]!==te.tokenBreakdown.cacheWrite||t[159]!==te.tokenBreakdown.input||t[160]!==te.tokenBreakdown.output||t[161]!==te.tokenBreakdown.reasoning?(St=s.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:e("contextSidebar.tokens.input"),value:te.tokenBreakdown.input,format:"count"},{label:e("contextSidebar.tokens.output"),value:te.tokenBreakdown.output,format:"count"},{label:e("contextSidebar.tokens.reasoning"),value:te.tokenBreakdown.reasoning,format:"count"},{label:e("contextSidebar.tokens.cacheRead"),value:te.tokenBreakdown.cacheRead,format:"count"},{label:e("contextSidebar.tokens.cacheWrite"),value:te.tokenBreakdown.cacheWrite,format:"count"},{label:e("contextSidebar.tokens.cacheHit"),value:te.cacheHitRate.hasInput?te.cacheHitRate.percent:null,format:"percent"}].map(Q1)}),t[154]=e,t[155]=te.cacheHitRate.hasInput,t[156]=te.cacheHitRate.percent,t[157]=te.tokenBreakdown.cacheRead,t[158]=te.tokenBreakdown.cacheWrite,t[159]=te.tokenBreakdown.input,t[160]=te.tokenBreakdown.output,t[161]=te.tokenBreakdown.reasoning,t[162]=St):St=t[162];let Dt;t[163]!==nt||t[164]!==St?(Dt=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[nt,St]}),t[163]=nt,t[164]=St,t[165]=Dt):Dt=t[165];let wt;t[166]!==Oe||t[167]!==te.breakdownTotal?(wt=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:Oe.map(xt=>xt.value<=0||te.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${xt.value/te.breakdownTotal*100}%`,backgroundColor:xt.color}},xt.key))}),t[166]=Oe,t[167]=te.breakdownTotal,t[168]=wt):wt=t[168];let ot;t[169]!==Oe||t[170]!==te.breakdownTotal?(ot=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:Oe.map(xt=>{const Ft=te.breakdownTotal>0?xt.value/te.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:xt.color}}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[xt.label," ",s.jsxs("span",{className:"tabular-nums",children:[Ft.toFixed(0),"%"]})]})]},xt.key)})}),t[169]=Oe,t[170]=te.breakdownTotal,t[171]=ot):ot=t[171];let at;t[172]!==wt||t[173]!==ot?(at=s.jsxs("div",{className:"mb-6",children:[wt,ot]}),t[172]=wt,t[173]=ot,t[174]=at):at=t[174];let Kt;t[175]!==e?(Kt=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=Kt):Kt=t[176];let is;t[177]!==Kt?(is=s.jsx("div",{className:"typography-micro text-muted-foreground",children:Kt}),t[177]=Kt,t[178]=is):is=t[178];let $t;if(t[179]!==c||t[180]!==o||t[181]!==f||t[182]!==e||t[183]!==n){let xt;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(xt=Ft=>{const Ut=Oo(Ft.info).role,qt=Ut==="assistant",Xt=Ut==="user",Lt=o[Ft.info.id]===!0,Bt=c===Ft.info.id,Yt=Ft.info.time?.created??null,Jt=C1(Ft.parts),es=qt?Nl({info:Ft.info,parts:Ft.parts}):null,Zt=Xt?I1(Ft.parts):"",vs=A1(Ft.info.id),bt=R1(Yt,n),Ot=Jt||"—",It=es?P1(es.input,es.output,Si):"",us=Ut||"unknown",He=Jt,ft=Lt?JSON.stringify({info:Ft.info,parts:Ft.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":Lt,onClick:()=>{a(Ye=>({...Ye,[Ft.info.id]:Ye[Ft.info.id]!==!0}))},children:s.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:"auto minmax(0, 1fr) 5rem 4.5rem"},children:[Xt?s.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",style:{gridColumn:"span 2"},children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",Zt]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:qt?"min-w-0 truncate text-muted-foreground":"typography-ui-label text-foreground",children:qt?Ot:us}),s.jsx("span",{className:qt?"text-right text-muted-foreground tabular-nums":"min-w-0 truncate text-muted-foreground",children:qt?It:He})]}),s.jsx("span",{className:"text-right font-mono text-muted-foreground",children:vs}),s.jsx("span",{className:"text-right text-muted-foreground",children:bt})]})}),Lt&&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:Ye=>{Ye.stopPropagation(),N(Ft.info.id,ft)},"aria-label":e(Bt?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Bt?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Bt?s.jsx(I,{name:"check",className:"size-3.5"}):s.jsx(I,{name:"file-copy",className:"size-3.5"})})}),s.jsx(dg,{language:"json",code:ft,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},Ft.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=xt):xt=t[189],$t=[...f].reverse().map(xt),t[179]=c,t[180]=o,t[181]=f,t[182]=e,t[183]=n,t[184]=$t}else $t=t[184];let Le;t[190]!==$t?(Le=s.jsx("div",{className:"mt-2.5 space-y-1",children:$t}),t[190]=$t,t[191]=Le):Le=t[191];let et;t[192]!==is||t[193]!==Le?(et=s.jsxs("div",{children:[is,Le]}),t[192]=is,t[193]=Le,t[194]=et):et=t[194];let Vt;return t[195]!==ue||t[196]!==Ie||t[197]!==Ve||t[198]!==Dt||t[199]!==at||t[200]!==et?(Vt=s.jsx("div",{className:"h-full overflow-y-auto bg-background",children:s.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[ue,Ie,Ve,Dt,at,et]})}),t[195]=ue,t[196]=Ie,t[197]=Ve,t[198]=Dt,t[199]=at,t[200]=et,t[201]=Vt):Vt=t[201],Vt};function $1(t){return t.timeFormatPreference}function z1(t){return t.currentSessionId}function W1(t){return t.providers}function U1(t){return Object.keys(t).length>0?{}:t}function H1(t){return Oo(t.info).role==="assistant"}function G1(t){return Oo(t.info).isUser}function K1(t,e){const n=ji(e.info.cost);return t+n}function q1(t){return Oo(t.info).isUser&&typeof t.info.system=="string"}function Y1(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 Q1(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)}%`:Si(t.value):"—"})]},t.label)}const J1=(t,e,n)=>JSON.stringify({sessionID:t,directory:e||"",readOnly:n===!0}),X1=(t,e,n,r)=>{if(typeof window>"u")return"";const o=new URL(window.location.pathname,window.location.origin);return o.searchParams.set("ocPanel","session-chat"),o.searchParams.set("sessionId",t),n?o.searchParams.set("readOnly","1"):o.searchParams.delete("readOnly"),e&&e.trim().length>0?o.searchParams.set("directory",e):o.searchParams.delete("directory"),o.searchParams.set("themeMode",r.mode),o.searchParams.set("lightThemeId",r.lightThemeId),o.searchParams.set("darkThemeId",r.darkThemeId),o.searchParams.set("themeVariant",r.currentTheme.metadata.variant==="dark"?"dark":"light"),o.searchParams.set("currentTheme",JSON.stringify(r.currentTheme)),o.hash="",o.toString()},Z1=(t,e,n,r,o,a)=>{const c=J1(n,r,o),l=t.get(e);if(l?.signature===c)return l.src;const d=X1(n,r,o,a);return t.set(e,{signature:c,src:d}),d},e0=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.x=="number"&&typeof e.y=="number"},Ou=t=>!t||typeof t!="object"?!1:Object.values(t).every(e=>typeof e=="string"),qi=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"&&e0(e.center)&&Ou(e.attributes)&&Ou(e.computedStyle)&&Array.isArray(e.ancestry)},Bc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([y,p])=>`${y}="${p}"`).join(" "),d=r.computedStyle,u=r.bounds,m=r.center,f=a.replace(/[.:]+$/g,""),g=r.ancestry.map(y=>y.selectorPart).join(" > ");return[`${f}:`,`Page: ${t||"preview"}`,`Viewport: ${e.width}x${e.height}, DPR ${n}`,`Screenshot: ${o?"attached":"not attached"}`,`Element: ${r.tag}`,c?`Text: ${c}`:null,`- Selector: ${r.selector}`,`- Path: ${r.path}`,g?`- Ancestry: ${g}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(u.x)}, y=${Math.round(u.y)}, width=${Math.round(u.width)}, height=${Math.round(u.height)}`,`- Center: x=${Math.round(m.x)}, y=${Math.round(m.y)}`,`Styles: display=${d.display}; position=${d.position}; font=${d.fontWeight} ${d.fontSize} / ${d.lineHeight} ${d.fontFamily}; color=${d.color}; background=${d.backgroundColor}; z-index=${d.zIndex}`].filter(y=>typeof y=="string").join(`
36
- `)},$m=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Wr("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((p,x)=>{o.onload=()=>p(),o.onerror=()=>x(new Error("Failed to load desktop preview screenshot")),o.src=`data:${r.mime};base64,${r.base64}`});const a=Math.max(1,o.naturalWidth||r.width||Math.floor(n.width)),c=Math.max(1,o.naturalHeight||r.height||Math.floor(n.height)),d=Math.min(1,1200/a),u=document.createElement("canvas");u.width=Math.floor(a*d),u.height=Math.floor(c*d);const m=u.getContext("2d");if(!m)return null;m.scale(d,d),m.drawImage(o,0,0,a,c);const f=a/Math.max(1,n.width),g=c/Math.max(1,n.height);m.fillStyle="rgba(37, 99, 235, 0.28)",m.strokeStyle="rgb(37, 99, 235)",m.lineWidth=Math.max(2,2*f),m.fillRect(e.bounds.x*f,e.bounds.y*g,e.bounds.width*f,e.bounds.height*g),m.strokeRect(e.bounds.x*f,e.bounds.y*g,e.bounds.width*f,e.bounds.height*g);const y=await new Promise(p=>u.toBlob(p,"image/jpeg",.82));return y?new File([y],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(n){return console.warn("[preview] failed to capture annotation screenshot:",n),null}return await p0(t,e)},Vc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((b,h)=>{c.onload=()=>b(),c.onerror=()=>h(new Error("Failed to load desktop browser screenshot")),c.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,c.naturalWidth||e),d=Math.max(1,c.naturalHeight||n),m=Math.min(1,1200/l),f=document.createElement("canvas");f.width=Math.floor(l*m),f.height=Math.floor(d*m);const g=f.getContext("2d");if(!g)return null;g.scale(m,m),g.drawImage(c,0,0,l,d);const y=l/Math.max(1,r||l),p=d/Math.max(1,o||d);g.fillStyle="rgba(37, 99, 235, 0.14)",g.strokeStyle="rgb(37, 99, 235)",g.lineWidth=Math.max(2,2*y),g.fillRect(a.bounds.x*y,a.bounds.y*p,a.bounds.width*y,a.bounds.height*p),g.strokeRect(a.bounds.x*y,a.bounds.y*p,a.bounds.width*y,a.bounds.height*p);const x=await new Promise(b=>f.toBlob(b,"image/jpeg",.82));return x?new File([x],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Yi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Zn=new Map,kl=new Map,t0=3e4,_c=t=>{const e=Zn.get(t);return e?e.expiresAt-Date.now()<=t0?(Zn.delete(t),null):e:null},s0=t=>{try{return new URL(t).origin}catch{return t}};function zm(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 Wm=t=>new Promise((e,n)=>{const r=new FileReader;r.onloadend=()=>e(typeof r.result=="string"?r.result:Yi),r.onerror=()=>n(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),n0=async(t,e=.82)=>{const n=await new Promise(r=>t.toBlob(r,"image/jpeg",e));return n&&(await Wm(n)).split(",",2)[1]||""},r0=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},da=(...t)=>{r0()&&console.info("[preview-capture]",...t)},Um=(t,e=8)=>{const n=[];try{const r=t.querySelectorAll("*");for(const o of r){const a=o.scrollTop||0,c=o.scrollLeft||0;if(a<=0&&c<=0)continue;const l=o.tagName.toLowerCase(),d=o.id?`#${o.id}`:"",u=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(n.push({selector:`${l}${d}${u}`,scrollTop:a,scrollLeft:c,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),n.length>=e)break}}catch{}return n},ko="data-oc-fixed-pin",i0=(t,e,n)=>{if(e<=0&&n<=0)return()=>{};const r=t.defaultView;if(!r)return()=>{};const o=[],a=[];try{for(const c of t.querySelectorAll("*")){if(r.getComputedStyle(c).position!=="fixed")continue;const l=c.getBoundingClientRect();if(!(l.width>0&&l.height>0))continue;c.setAttribute(ko,JSON.stringify({top:l.top+n,left:l.left+e,width:l.width,height:l.height})),o.push(c);const d=c.tagName.toLowerCase(),u=typeof c.className=="string"&&c.className?`.${c.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";a.push({selector:`${d}${u}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return da("tagged fixed elements",a),()=>{for(const c of o)try{c.removeAttribute(ko)}catch{}}},o0={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${ko}]`)){let r;try{r=JSON.parse(n.getAttribute(ko)||"")}catch{continue}n.style.setProperty("position","absolute","important"),n.style.setProperty("top",`${r.top}px`,"important"),n.style.setProperty("left",`${r.left}px`,"important"),n.style.setProperty("right","auto","important"),n.style.setProperty("bottom","auto","important"),n.style.setProperty("width",`${r.width}px`,"important"),n.style.setProperty("height",`${r.height}px`,"important"),n.removeAttribute(ko)}}},Hi="data-oc-scroll-pin",a0=t=>{const e=[],n=Um(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,u=l.scrollLeft||0;if(d<=0&&u<=0)continue;const m=l!==a&&l!==c;m&&l.setAttribute(Hi,JSON.stringify({top:d,left:u})),e.push({el:l,top:d,left:u,tagged:m})}}catch{}return{reapply:()=>{for(const a of e)try{a.el.scrollHeight,a.el.scrollTop!==a.top&&(a.el.scrollTop=a.top),a.el.scrollLeft!==a.left&&(a.el.scrollLeft=a.left)}catch{}},cleanup:()=>{for(const a of e)if(a.tagged)try{a.el.removeAttribute(Hi)}catch{}},snapshot:n}},l0={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(`[${Hi}]`)){let o;try{o=JSON.parse(r.getAttribute(Hi)||"")}catch{r.removeAttribute(Hi);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(Hi)}}},Cl=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await Wm(await n.blob()):null}catch{return null}},c0=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=_c(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=kl.get(e),o=r??(async()=>{try{const c=await As("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!c.ok)return Zn.delete(e),null;const l=await c.json(),d=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",u=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Zn.delete(e),null;const m={proxyBasePath:d,expiresAt:u};return Zn.set(e,m),m}catch{return Zn.delete(e),null}finally{kl.delete(e)}})();r||kl.set(e,o);const a=await o;return a?`${a.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},Hm=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 Cl(n.toString(),"include")??Yi;const r=await c0(n),o=r?await Cl(r,"include"):null;return o||(await Cl(n.toString(),"omit")??Yi)}catch{return Yi}},d0=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 Hm(a,e);r=r.replace(o[0],`url("${c}")`)}return r},Bu=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),Gm=t=>{const e=t.style.cssText;return()=>{t.style.cssText=e}},u0=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},f0=(t,e,n)=>{const r=[],o=t.defaultView??window,c=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of c){const d=l.textContent?.replace(/\s+/g," ").trim()??"";if(!d||!d.includes(" "))continue;const u=l.getBoundingClientRect();if(u.width<=0||u.height<=0||u.right<0||u.bottom<0||u.left>e||u.top>n)continue;const m=o.getComputedStyle(l);if(m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)continue;const f=m.getPropertyValue("text-wrap"),g=m.getPropertyValue("text-wrap-mode"),y=m.whiteSpace.includes("nowrap")||f==="nowrap"||g==="nowrap",p=u.height<=u0(m)*1.7;!y&&(!p||u.width>e*.72)||(r.push(Gm(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]?.()}},m0=(t,e,n,r)=>{const o=[],a=t.defaultView??window,c=a.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=a.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,d=Array.from(t.querySelectorAll("*")).filter(u=>{const m=a.getComputedStyle(u);if(m.position!=="fixed"||m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)return!1;const f=u.getBoundingClientRect();return f.width>0&&f.height>0&&f.right>=0&&f.bottom>=0&&f.left<=e&&f.top<=n}).filter((u,m,f)=>!f.some((g,y)=>y<m&&g.contains(u)));for(const u of d){const m=u.getBoundingClientRect(),f=a.getComputedStyle(u),g=Math.ceil(m.width)+8,y=Math.ceil(m.height)+2;r?.add(u),o.push(Gm(u)),u.style.position="absolute",u.style.top=`${m.top+l}px`,u.style.left=`${m.left+c}px`,u.style.right="auto",u.style.bottom="auto",u.style.width=`${g}px`,u.style.minWidth=`${g}px`,u.style.height=`${y}px`,u.style.minHeight=`${y}px`,u.style.margin="0",u.style.boxSizing="border-box",u.style.transform="none",f.zIndex!=="auto"&&(u.style.zIndex=f.zIndex)}return()=>{for(let u=o.length-1;u>=0;u-=1)o[u]?.()}},Km=async(t,e,n,r={})=>{const o=[],a=t.defaultView??window,c=f=>{if(f===t.documentElement||f===t.body)return!0;try{const g=f.getBoundingClientRect();return g.width>0&&g.height>0&&g.right>=0&&g.bottom>=0&&g.left<=e&&g.top<=n}catch{return!1}};if(r.applyLayoutWorkarounds){const f=new WeakSet;o.push(m0(t,e,n,f)),o.push(f0(t,e,n))}const l=new Map;for(const f of Array.from(t.images))l.set(f,f.currentSrc||f.src||f.getAttribute("src")||"");const d=Array.from(t.querySelectorAll("picture"));for(const f of d){const g=Array.from(f.querySelectorAll("source"));if(g.length===0)continue;const y=g.map(p=>({source:p,srcset:p.getAttribute("srcset"),sizes:p.getAttribute("sizes")}));o.push(()=>{for(const p of y)p.srcset===null?p.source.removeAttribute("srcset"):p.source.setAttribute("srcset",p.srcset),p.sizes===null?p.source.removeAttribute("sizes"):p.source.setAttribute("sizes",p.sizes)});for(const p of g)p.removeAttribute("srcset"),p.removeAttribute("sizes")}const u=Array.from(t.images).filter(f=>c(f));await Promise.all(u.map(async f=>{const g=l.get(f)||f.currentSrc||f.src||f.getAttribute("src")||"";if(!g)return;await Bu(f);const y=await Hm(g,t),p={src:f.getAttribute("src"),srcset:f.getAttribute("srcset"),sizes:f.getAttribute("sizes")};o.push(()=>{p.src===null?f.removeAttribute("src"):f.setAttribute("src",p.src),p.srcset===null?f.removeAttribute("srcset"):f.setAttribute("srcset",p.srcset),p.sizes===null?f.removeAttribute("sizes"):f.setAttribute("sizes",p.sizes)}),f.removeAttribute("srcset"),f.removeAttribute("sizes"),f.setAttribute("src",y||Yi),await Bu(f)}));const m=Array.from(t.querySelectorAll("*")).filter(c);return await Promise.all(m.map(async f=>{const g=a.getComputedStyle(f).backgroundImage;if(!g||g==="none"||!g.includes("url("))return;const y=await d0(g,t);if(y===g)return;const p=f.style.backgroundImage;o.push(()=>{f.style.backgroundImage=p}),f.style.backgroundImage=y})),()=>{for(let f=o.length-1;f>=0;f-=1)try{o[f]?.()}catch{}}};async function h0(t,e){try{const n=t.contentWindow,r=t.contentDocument??n?.document,o=r?.documentElement;if(!n||!r||!o)return null;const a=t.getBoundingClientRect(),c=Math.max(1,Math.ceil(n.innerWidth||t.clientWidth||a.width)),l=Math.max(1,Math.ceil(n.innerHeight||t.clientHeight||a.height)),d=r.body,u=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,m=n.scrollX||0,f=n.scrollY||0,g=n.pageXOffset||0,y=n.pageYOffset||0,p=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,x=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,b=o.scrollLeft||0,h=o.scrollTop||0,N=d?.scrollLeft||0,w=d?.scrollTop||0,S=u?.scrollLeft||0,j=u?.scrollTop||0,k=Math.max(m,g,p,b,N,S),v=Math.max(f,y,x,h,w,j);da("scroll sources",{windowScrollX:m,windowScrollY:f,pageScrollX:g,pageScrollY:y,visualViewportScrollX:p,visualViewportScrollY:x,rootScrollX:b,rootScrollY:h,bodyScrollX:N,bodyScrollY:w,scrollingElementScrollX:S,scrollingElementScrollY:j,scrollingElementTag:u?.tagName?.toLowerCase()??null,resolvedScrollX:k,resolvedScrollY:v,nestedScrolledElements:Um(r)});const D=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),A=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),C=Math.min(2,Math.max(1,window.devicePixelRatio||1)),O=o.style.scrollBehavior,T=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const E=a0(r);da("nested scroll snapshot",E.snapshot);let F=()=>{},R=()=>{};try{await r.fonts?.ready.catch(()=>{}),F=await Km(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(k,v),R=i0(r,k,v),E.reapply();const L={backgroundColor:zm(r),cache:"disabled",dpr:C,embedFonts:!0,fast:!1,height:A,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[o0,l0],quality:.82,width:D},V=await(await Lh(o,L)).toCanvas();if(!V.width||!V.height)return null;const M=V.width/Math.max(1,D),Z=V.height/Math.max(1,A),se=Math.min(V.width,Math.max(1,Math.round(c*M))),Q=Math.min(V.height,Math.max(1,Math.round(l*Z))),K=Math.max(0,V.width-se),ee=Math.max(0,V.height-Q),re=Math.min(K,Math.max(0,Math.round(k*M))),he=Math.min(ee,Math.max(0,Math.round(v*Z)));da("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:D,captureHeight:A,canvasWidth:V.width,canvasHeight:V.height,xScale:M,yScale:Z,sourceX:re,sourceY:he,sourceWidth:se,sourceHeight:Q});const je=r.createElement("canvas");je.width=se,je.height=Q;const te=je.getContext("2d");if(!te)return null;te.drawImage(V,re,he,se,Q,0,0,se,Q);const Ne=await n0(je,.82);return Ne?await Vc(Ne,c,l,c,l,e):null}finally{R(),E.cleanup(),F(),n.scrollTo(k,v),E.reapply(),o.style.scrollBehavior=O,d&&(d.style.scrollBehavior=T)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function p0(t,e){const n=await h0(t,e);if(n)return n;try{const r=t.contentWindow,o=t.contentDocument??r?.document,a=o?.documentElement;if(!r||!o||!a)return null;const c=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||c.width)),d=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||c.height)),u=r.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,m=r.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,f=o.body,g=Math.max(d,a.scrollHeight||0,f?.scrollHeight||0),y=Math.min(2,Math.max(1,window.devicePixelRatio||1)),p=a.style.scrollBehavior,x=f?.style.scrollBehavior??"";a.style.scrollBehavior="auto",f&&(f.style.scrollBehavior="auto");let b="",h=()=>{};try{await o.fonts?.ready.catch(()=>{}),h=await Km(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(u,m);const w=await Mh(a).catch(()=>"");b=await Fh(a,{quality:.82,pixelRatio:y,width:l,height:d,backgroundColor:zm(o),imagePlaceholder:Yi,fontEmbedCSS:w||void 0,style:{transform:`translate(${-u}px, ${-m}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${g}px`},cacheBust:!0})}finally{h(),r.scrollTo(u,m),a.style.scrollBehavior=p,f&&(f.style.scrollBehavior=x)}const N=b.split(",",2)[1]||"";return N?await Vc(N,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const qm=380,g0=1400,Ym=600,x0=24,Vu=200,b0=(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",y0=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},Qm=t=>Number.isFinite(t)?Math.min(g0,Math.max(qm,Math.round(t))):Ym,w0=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},Al=(t,e)=>{const n=Qm(t),r=w0(e);return r===null?n:Math.min(n,Math.max(1,r))},v0=(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},j0=(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"),S0=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},N0=(t,e)=>{if(t.label)return t.label;if(t.mode==="file")return S0(t.targetPath)||e("contextPanel.mode.files");if(t.mode==="preview"){const n=t.targetPath;if(n)try{const r=new URL(n);return r.host||r.hostname||e("contextPanel.mode.preview")}catch{}return e("contextPanel.mode.preview")}return t.mode==="diff"?e("contextPanel.mode.diff"):j0(t.mode,e)},k0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(Ur,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(I,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(I,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(I,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(I,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(I,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(I,{name:"global",className:"h-3.5 w-3.5"})},C0=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,Jm=`new Promise((resolve) => {
37
- const existing = document.getElementById('__openchamber_desktop_browser_overlay');
38
- if (existing) existing.remove();
39
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
40
- try { window.__openchamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
41
- }
42
- const overlay = document.createElement('div');
43
- overlay.id = '__openchamber_desktop_browser_overlay';
44
- overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
45
- document.documentElement.appendChild(overlay);
46
- const cssEscape = (value) => {
47
- try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
48
- };
49
- const selectorPart = (element) => {
50
- const tag = element.tagName.toLowerCase();
51
- if (element.id) return tag + '#' + cssEscape(element.id);
52
- const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
53
- return tag + className;
54
- };
55
- const metadata = (element) => {
56
- const rect = element.getBoundingClientRect();
57
- const style = getComputedStyle(element);
58
- const ancestry = [];
59
- let current = element;
60
- while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
61
- ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
62
- current = current.parentElement;
63
- }
64
- const attrs = {};
65
- for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
66
- const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
67
- return {
68
- frame: 'top',
69
- tag: element.tagName.toLowerCase(),
70
- text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
71
- selector: element.id ? '#' + cssEscape(element.id) : path,
72
- path,
73
- bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
74
- center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
75
- attributes: attrs,
76
- computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
77
- ancestry,
78
- };
79
- };
80
- const move = (event) => {
81
- const element = document.elementFromPoint(event.clientX, event.clientY);
82
- if (!element || element === overlay || element === document.documentElement || element === document.body) return;
83
- const rect = element.getBoundingClientRect();
84
- overlay.style.display = 'block';
85
- overlay.style.left = rect.left + 'px';
86
- overlay.style.top = rect.top + 'px';
87
- overlay.style.width = rect.width + 'px';
88
- overlay.style.height = rect.height + 'px';
89
- };
90
- const cleanup = () => {
91
- window.removeEventListener('mousemove', move, true);
92
- window.removeEventListener('click', click, true);
93
- window.removeEventListener('keydown', keydown, true);
94
- if (window.__openchamberDesktopBrowserCancelInspect === cancel) {
95
- delete window.__openchamberDesktopBrowserCancelInspect;
96
- }
97
- };
98
- const cancel = () => {
99
- cleanup();
100
- overlay.remove();
101
- resolve(null);
102
- };
103
- const click = (event) => {
104
- event.preventDefault();
105
- event.stopPropagation();
106
- const element = document.elementFromPoint(event.clientX, event.clientY);
107
- const result = element ? metadata(element) : null;
108
- cleanup();
109
- overlay.remove();
110
- resolve(result);
111
- };
112
- const keydown = (event) => {
113
- if (event.key !== 'Escape') return;
114
- cancel();
115
- };
116
- window.__openchamberDesktopBrowserCancelInspect = cancel;
117
- window.addEventListener('mousemove', move, true);
118
- window.addEventListener('click', click, true);
119
- window.addEventListener('keydown', keydown, true);
120
- });`,ua=`(() => {
121
- if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
122
- window.__openchamberDesktopBrowserCancelInspect();
123
- return;
124
- }
125
- const overlay = document.getElementById('__openchamber_desktop_browser_overlay');
126
- if (overlay) overlay.remove();
127
- })()`,A0=`(() => {
128
- if (window.__openchamberSameWebviewNavigationInstalled) return;
129
- window.__openchamberSameWebviewNavigationInstalled = true;
130
-
131
- const navigate = (rawUrl) => {
132
- if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
133
- try {
134
- const url = new URL(rawUrl, window.location.href);
135
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
136
- window.location.assign(url.href);
137
- return true;
138
- } catch (_error) {
139
- return false;
140
- }
141
- };
142
-
143
- const originalOpen = window.open.bind(window);
144
- window.open = (url, target, features) => {
145
- if (navigate(url)) return null;
146
- return originalOpen(url, target, features);
147
- };
148
-
149
- document.addEventListener('click', (event) => {
150
- if (event.defaultPrevented) return;
151
- const target = event.target;
152
- if (!(target instanceof Element)) return;
153
- const anchor = target.closest('a[target="_blank"][href]');
154
- if (!(anchor instanceof HTMLAnchorElement)) return;
155
- if (!navigate(anchor.href)) return;
156
- event.preventDefault();
157
- event.stopPropagation();
158
- }, true);
159
- })()`,Co=t=>{const e=t.trim();if(!e)return"about:blank";try{const n=new URL(e.includes("://")?e:`https://${e}`);return n.protocol!=="http:"&&n.protocol!=="https:"?"about:blank":n.toString()}catch{return"about:blank"}},_u=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)},D0=(t,e)=>t.length<=e?t:`${t.slice(0,e-3)}...`,Xm=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},$u=(t,e,n)=>{const r=Xm(e);t.postMessage(n,r)},I0=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}},P0=({rawUrl:t,onNavigate:e})=>{const{t:n}=kt(),{currentTheme:r}=Gr(),[o,a]=i.useReducer(ge=>ge+1,0),[c,l]=i.useReducer(ge=>ge+1,0),[d,u]=i.useState({status:"idle"}),[m,f]=i.useState(""),g=i.useRef(null),y=i.useRef(1),[p,x]=i.useState(!1),[b,h]=i.useState(!1),[N,w]=i.useState("all"),[S,j]=i.useState([]),[k,v]=i.useState(!1),[D,A]=i.useState(null),C=ut(ge=>ge.currentSessionId),O=ut(ge=>ge.newSessionDraft?.open),T=Sc(ge=>ge.addDraft),E=li(ge=>ge.addAttachedFile);let F=null;try{F=t?new URL(t):null}catch{F=null}const R=F?F.hostname==="localhost"||F.hostname==="127.0.0.1"||F.hostname==="::1"||F.hostname==="[::1]"||F.hostname==="0.0.0.0":!1,L=F?F.hostname==="0.0.0.0"?new URL(F.toString().replace("0.0.0.0","127.0.0.1")):F:null,B=L?L.toString():"",V=B?`${zr()||"same-origin"}|${B}`:"",M=r.metadata.variant;i.useEffect(()=>{if(!B||!R){u({status:"idle"});return}const ge=_c(V);if(ge?.previewToken){u({status:"ready",proxyBasePath:ge.proxyBasePath,previewToken:ge.previewToken,expiresAt:ge.expiresAt});return}ge&&Zn.delete(V);let Ae=!1;return u({status:"loading"}),(async()=>{try{const pe=await As("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:B})});if(!pe.ok){Zn.delete(V);const W=await pe.json().catch(()=>({})),z=typeof W?.error=="string"?W.error:`HTTP ${pe.status}`;Ae||u({status:"error",message:z});return}const ue=await pe.json(),G=typeof ue.proxyBasePath=="string"?ue.proxyBasePath:"",fe=typeof ue.previewToken=="string"?ue.previewToken:"",ce=typeof ue.expiresAt=="number"?ue.expiresAt:0;if(!G||!fe){Zn.delete(V),Ae||u({status:"error",message:n("contextPanel.preview.proxyError")});return}Zn.set(V,{proxyBasePath:G,previewToken:fe,expiresAt:ce}),Ae||u({status:"ready",proxyBasePath:G,previewToken:fe,expiresAt:ce})}catch(pe){if(Zn.delete(V),!Ae){const ue=pe instanceof Error?pe.message:String(pe);u({status:"error",message:ue})}}})(),()=>{Ae=!0}},[R,V,c,n,B]);const Z=L&&(L.protocol==="http:"||L.protocol==="https:")?L.toString():"",se=R&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!se){f("");return}let ge=!1;return f(""),dc(zr()).then(Ae=>{!ge&&Ae&&f(se)}).catch(()=>{}),()=>{ge=!0}},[se]);const Q=R&&d.status==="ready"&&L&&m===se?(()=>{const ge=L.pathname||"/",Ae=new URLSearchParams(L.search);Ae.set("ocPreview",String(o)),Ae.set("oc_preview_token",d.previewToken||"");const pe=Ae.toString(),ue=L.hash||"";return Ai().authenticatedAsset(`${d.proxyBasePath}${ge}${pe?`?${pe}`:""}${ue}`)})():"",K=R?Q:Z,ee=R?I0(Q):Z,re=R&&(d.status==="loading"||d.status==="idle"||m!==se),he=R&&d.status==="error",je=i.useCallback(ge=>{const Ae=C??(O?"draft":null);if(!Ae){de.error(n("contextPanel.preview.inspect.attachNoSession"));return}const pe=t||K||"",ue=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},G=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let fe=!1;try{const ce=g.current,W=ce?await $m(ce,ge):null;W&&(await E(W),fe=!0)}catch{fe=!1}T({sessionKey:Ae,source:"preview-annotation",fileLabel:pe||"preview",startLine:1,endLine:1,code:Bc({pageUrl:pe,viewport:ue,devicePixelRatio:G,target:ge,screenshotAttached:fe,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),de.success(n("contextPanel.preview.inspect.attached"))})()},[E,T,C,K,O,t,n]);i.useEffect(()=>{x(!1),j([]),h(!1),w("all"),v(!1),A(null),y.current=1},[K]),i.useEffect(()=>{const ge=g.current?.contentWindow;!p||!ge||$u(ge,Q,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[p,k,Q]),i.useEffect(()=>{const ge=g.current?.contentWindow;!p||!ge||$u(ge,Q,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:M})},[p,M,Q]),i.useEffect(()=>{if(!k||typeof window>"u")return;const ge=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopImmediatePropagation(),v(!1))};return window.addEventListener("keydown",ge,!0),()=>window.removeEventListener("keydown",ge,!0)},[k]),i.useEffect(()=>{if(!R||typeof window>"u")return;const ge=ue=>{if(typeof ue=="string")return ue;if(ue==null)return"";try{return JSON.stringify(ue)}catch{return String(ue)}},Ae=ue=>{const G=y.current;y.current+=1,j(fe=>{const ce=[...fe,{...ue,id:G}];return ce.length>Vu?ce.slice(ce.length-Vu):ce})},pe=ue=>{if(ue.source!==g.current?.contentWindow)return;const G=ue.data;if(!(!G||G.source!=="openchamber-preview-bridge"||G.version!==1)){if(G.type==="ready"){x(!0);return}if(G.type==="console"){const fe=G.level==="error"||G.level==="warn"||G.level==="info"||G.level==="debug"?G.level:"log",ce=Array.isArray(G.args)?G.args.map(ge).filter(Boolean):[];Ae({level:fe,message:ce.join(" "),ts:typeof G.ts=="number"?G.ts:Date.now()});return}if(G.type==="runtime-error"){const fe=ge(G.filename),ce=typeof G.line=="number"?G.line:null,W=typeof G.column=="number"?G.column:null,z=fe?`${fe}${ce!==null?`:${ce}${W!==null?`:${W}`:""}`:""}`:"",be=ge(G.stack);Ae({level:"runtime",message:ge(G.message)||n("contextPanel.preview.console.runtimeError"),details:[z,be].filter(Boolean).join(`
160
- `),ts:typeof G.ts=="number"?G.ts:Date.now()});return}if(G.type==="resource-error"){const fe=ge(G.tag)||"resource",ce=ge(G.url);Ae({level:"resource",message:ce?`${fe}: ${ce}`:fe,details:ge(G.outerHTML),ts:typeof G.ts=="number"?G.ts:Date.now()});return}if(G.type==="hover"){A(qi(G.target)?G.target:null);return}if(G.type==="select"&&qi(G.target)){A(G.target),v(!1),je(G.target);return}if(G.type==="navigate-preview"){const fe=typeof G.url=="string"?G.url:"",ce=G.navigation==="external"?"external":"proxy";if(fe&&ce==="external"){Pi(fe);return}fe&&e(fe)}}};return window.addEventListener("message",pe),()=>{window.removeEventListener("message",pe)}},[je,R,e,n]);const te=S.filter(ge=>ge.level==="error"||ge.level==="runtime"||ge.level==="resource").length,Ne=S.filter(ge=>b0(ge,N)),J=i.useCallback(()=>{const ge=[`Preview URL: ${t||K||""}`,`Events: ${S.length}`,""].join(`
161
- `),Ae=S.map(pe=>{const ue=new Date(pe.ts).toISOString(),G=pe.details?`
162
- ${pe.details}`:"";return`[${ue}] [${pe.level}] ${pe.message}${G}`}).join(`
163
- `);pr(`${ge}${Ae}`).then(pe=>{pe.ok?de.success(n("contextPanel.preview.console.copied")):de.error(n("contextPanel.preview.console.copyFailed"))})},[S,K,t,n]),H=i.useCallback(()=>{const ge=C??(O?"draft":null);if(!ge){de.error(n("contextPanel.preview.console.attachNoSession"));return}const Ae=[`Preview URL: ${t||K||""}`,`Events: ${S.length}`,""].join(`
164
- `),pe=S.map(ue=>{const G=new Date(ue.ts).toISOString(),fe=ue.details?`
165
- ${ue.details}`:"";return`[${G}] [${ue.level}] ${ue.message}${fe}`}).join(`
166
- `);T({sessionKey:ge,source:"preview-console",fileLabel:t||K||"preview",startLine:1,endLine:Math.max(1,S.length),code:`${Ae}${pe}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),de.success(n("contextPanel.preview.console.attached"))},[T,S,C,K,O,t,n]),[q,ae]=i.useState("unknown"),le=i.useRef(0),Se=i.useRef(0),Re=15e3;i.useEffect(()=>{if(!Q){ae("unknown"),le.current=0,Se.current=0;return}let ge=!1;return le.current||(le.current=Date.now(),Se.current=0),ae("unknown"),(async()=>{const pe=await(async()=>{try{return await As(Q,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(ge)return;if(!pe){ae("unreachable");return}if(pe.status===403||pe.status===404){Zn.delete(V),u({status:"loading"}),l();return}if(pe.status!==502){ae("reachable");return}const ue=le.current||Date.now();if(Date.now()-ue<Re){ae("starting"),Se.current+=1;const fe=Se.current,ce=Math.min(2e3,250*Math.pow(2,Math.min(4,fe)));setTimeout(()=>{ge||a()},ce).unref?.();return}ae("unreachable")})(),()=>{ge=!0}},[V,Q,o]);const _e=R&&d.status==="ready"&&(q==="unknown"||q==="starting"),Oe=R&&d.status==="ready"&&q==="unreachable",Me=i.useCallback(ge=>{if(!R||d.status!=="ready"||typeof window>"u")return;const Ae=ge.currentTarget.contentWindow;if(Ae)try{const pe=Ae.location,ue=Xm(Q);if(pe.origin!==ue||pe.pathname.startsWith(d.proxyBasePath))return;const G=`${d.proxyBasePath}${pe.pathname}${pe.search}${pe.hash}`;Ae.location.replace(G)}catch{}},[R,Q,d]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:ee||t,children:ee||t||n("contextPanel.preview.empty")}),s.jsx($e,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:n("contextPanel.preview.actions.reload"),"aria-label":n("contextPanel.preview.actions.reload"),disabled:!K,children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{Z&&Pi(Z)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!Z,children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})}),R?s.jsx($e,{type:"button",size:"sm",variant:k?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>v(ge=>!ge),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!p,children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}):null,R?s.jsxs($e,{type:"button",size:"sm",variant:b?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>h(ge=>!ge),title:n(p?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),"aria-label":n(p?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),disabled:!p&&S.length===0,children:[s.jsx(I,{name:"terminal-box",className:"h-3.5 w-3.5"}),te>0?s.jsx("span",{className:"typography-micro text-status-error",children:te}):null]}):null]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[_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.startingServer")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.startingServerHint")})]}):Oe?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.upstreamUnreachable")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.upstreamUnreachableHint")}),s.jsx($e,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:n("contextPanel.preview.actions.retry")})]}):K&&(!R||q==="reachable")?s.jsxs("div",{className:"relative h-full w-full",children:[s.jsx("iframe",{ref:g,src:K,title:n("contextPanel.preview.iframeTitle"),className:"h-full w-full border-0",style:{colorScheme:M},onLoad:Me,sandbox:R?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${K}:${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")}):he?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")}),b?s.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:n("contextPanel.preview.console.title")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:H,disabled:S.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:J,disabled:S.length===0,children:n("contextPanel.preview.console.copy")}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:()=>j([]),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(ge=>s.jsx($e,{type:"button",size:"xs",variant:N===ge?"secondary":"ghost",onClick:()=>w(ge),children:n(ge==="all"?"contextPanel.preview.console.filter.all":ge==="errors"?"contextPanel.preview.console.filter.errors":ge==="warnings"?"contextPanel.preview.console.filter.warnings":"contextPanel.preview.console.filter.logs")},ge))}),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")}):Ne.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):Ne.map(ge=>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:De("shrink-0 uppercase",ge.level==="error"||ge.level==="runtime"||ge.level==="resource"?"text-status-error":ge.level==="warn"?"text-status-warning":"text-muted-foreground"),children:ge.level}),s.jsx("span",{className:"min-w-0 break-words text-foreground",children:ge.message})]})},ge.id))})]}):null]})]})},T0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,R0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=kt(),o=i.useRef(null),a=Ee(J=>J.setContextPanelTabTargetPath),c=Co(t),l=c!=="about:blank"?c:"",[d,u]=i.useState(l),[m,f]=i.useState(l),[g,y]=i.useState(()=>l?[l]:[]),[p,x]=i.useState(()=>l?0:-1),[b,h]=i.useReducer(J=>J+1,0),[N,w]=i.useState(!!l),[S,j]=i.useState(!1),[k,v]=i.useState(null),[D,A]=i.useState({status:"idle"}),[C,O]=i.useState(""),T=ut(J=>J.currentSessionId),E=ut(J=>J.newSessionDraft?.open),F=Sc(J=>J.addDraft),R=li(J=>J.addAttachedFile),L=i.useCallback(J=>{!J||J==="about:blank"||!e||!n||a(e,n,J)},[e,n,a]),B=i.useCallback((J,H)=>{const q=Co(J),ae=q!=="about:blank"?q:"";f(ae),u(ae),w(!!ae),L(ae),y(le=>{if(!ae)return x(-1),[];if(H?.replaceHistory)return le;const Se=p>=0?le.slice(0,p+1):[];if(Se[Se.length-1]===ae)return x(Se.length-1),Se;const _e=[...Se,ae];return x(_e.length-1),_e})},[p,L]),V=i.useCallback(J=>{const H=g[J];H&&(x(J),f(H),u(H),w(!0),L(H))},[g,L]),M=i.useCallback(()=>{if(m){w(!0);try{o.current?.contentWindow?.location.reload()}catch{h()}}},[m]);i.useEffect(()=>{if(!m){A({status:"idle"});return}const J=s0(m),H=_c(J);if(H?.previewToken){A({status:"ready",proxyBasePath:H.proxyBasePath,previewToken:H.previewToken,expiresAt:H.expiresAt});return}H&&Zn.delete(J);let q=!1;return A({status:"loading"}),w(!0),(async()=>{try{const ae=await As("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:m,allowExternal:!0})});if(!ae.ok){const Oe=await ae.json().catch(()=>({})),Me=typeof Oe?.error=="string"?Oe.error:`HTTP ${ae.status}`;q||A({status:"error",message:Me});return}const le=await ae.json(),Se=typeof le.proxyBasePath=="string"?le.proxyBasePath:"",Re=typeof le.previewToken=="string"?le.previewToken:"",_e=typeof le.expiresAt=="number"?le.expiresAt:0;if(!Se||!Re){q||A({status:"error",message:r("contextPanel.preview.proxyError")});return}Zn.set(J,{proxyBasePath:Se,previewToken:Re,expiresAt:_e}),q||A({status:"ready",proxyBasePath:Se,previewToken:Re,expiresAt:_e})}catch(ae){if(!q){const le=ae instanceof Error?ae.message:String(ae);A({status:"error",message:le})}}})(),()=>{q=!0}},[m,r]);const Z=m&&D.status==="ready"?`${D.proxyBasePath}|${D.previewToken||""}|${b}`:"";i.useEffect(()=>{if(!Z){O("");return}let J=!1;return O(""),dc(zr()).then(H=>{!J&&H&&O(Z)}).catch(()=>{}),()=>{J=!0}},[Z]);const se=i.useMemo(()=>{if(C!==Z||!m||D.status!=="ready")return"";try{const J=new URL(m),H=J.pathname||"/",q=new URLSearchParams(J.search);q.set("ocPreview",String(b)),q.set("oc_preview_token",D.previewToken||"");const ae=q.toString();return Ai().authenticatedAsset(`${D.proxyBasePath}${H}${ae?`?${ae}`:""}${J.hash}`)}catch{return""}},[m,D,Z,b,C]),Q=se||(D.status==="error"?m:""),K=i.useCallback(J=>{if(!J||!m||D.status!=="ready")return"";try{const H=new URL(J,window.location.origin),q=D.proxyBasePath.endsWith("/")?D.proxyBasePath.slice(0,-1):D.proxyBasePath;if(H.origin!==window.location.origin||!H.pathname.startsWith(q))return"";const ae=H.pathname.slice(q.length)||"/",le=new URL(m).origin;return new URL(`${ae}${H.search}${H.hash}`,le).toString()}catch{return""}},[m,D]),ee=i.useCallback(J=>{if(!J||!m||D.status!=="ready")return"";try{const H=new URL(J,window.location.origin),q=new URL(m).origin;if(H.origin!==window.location.origin||q===window.location.origin)return"";const ae=D.proxyBasePath.endsWith("/")?D.proxyBasePath.slice(0,-1):D.proxyBasePath;return H.pathname.startsWith(ae)?"":new URL(`${H.pathname}${H.search}${H.hash}`,q).toString()}catch{return""}},[m,D]),re=i.useCallback(J=>{const H=o.current?.contentWindow;H&&H.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:J},window.location.origin)},[]),he=i.useCallback(async J=>{const H=T??(E?"draft":null);if(!H){de.error(r("contextPanel.preview.inspect.attachNoSession"));return}const q=o.current,ae=q?.contentWindow,le=q?.getBoundingClientRect(),Se={width:Number.isFinite(ae?.innerWidth)?ae?.innerWidth??le?.width??0:le?.width??0,height:Number.isFinite(ae?.innerHeight)?ae?.innerHeight??le?.height??0:le?.height??0},Re=q?await $m(q,J):null,_e=!!Re;Re&&await R(Re),F({sessionKey:H,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Bc({pageUrl:m,viewport:Se,devicePixelRatio:window.devicePixelRatio||1,target:J,screenshotAttached:_e,intro:r(_e?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),de.success(r("contextPanel.preview.inspect.attached"))},[R,F,T,m,E,r]),je=i.useCallback(()=>{const J=o.current;v(null),re(!1),J&&_u(J,ua).catch(()=>{})},[re]);i.useEffect(()=>{if(!S)return;const J=H=>{H.key==="Escape"&&(H.preventDefault(),H.stopImmediatePropagation(),j(!1),je())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[je,S]),i.useEffect(()=>()=>je(),[je]),i.useEffect(()=>{const J=H=>{if(H.source!==o.current?.contentWindow)return;const q=H.data;if(!(!q||q.source!=="openchamber-preview-bridge"||q.version!==1)){if(q.type==="ready"){const ae=typeof q.url=="string"?q.url:"",le=K(ae);le&&le!==m&&B(le);return}if(q.type==="hover"){v(qi(q.target)?q.target:null);return}if(q.type==="select"&&qi(q.target)){v(null),j(!1),re(!1),he(q.target);return}if(q.type==="navigate-preview"){const ae=typeof q.url=="string"?q.url:"",le=ee(ae);if(le){B(le);return}ae&&B(ae)}}};return window.addEventListener("message",J),()=>window.removeEventListener("message",J)},[B,he,m,K,ee,re]);const te=i.useCallback(()=>{const J=o.current;if(!(!J||!m)){if(S){j(!1),je();return}if(se){v(null),j(!0),re(!0);return}j(!0),(async()=>{try{const H=await _u(J,Jm);if(j(!1),!H||!qi(H))return;await he(H)}catch{j(!1),de.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[he,je,m,S,re,se,r]),Ne=i.useCallback(()=>{try{const J=o.current?.contentWindow?.location.href||"",H=ee(J);if(H){w(!0),B(H);return}}catch{}w(!1),S&&se&&re(!0)},[B,ee,S,re,se]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:p<=0,onClick:()=>V(p-1),children:s.jsx(I,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:p<0||p>=g.length-1,onClick:()=>V(p+1),children:s.jsx(I,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:M,children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:J=>{J.preventDefault(),B(d)},children:s.jsx("input",{value:d,onChange:J=>u(J.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx($e,{type:"button",variant:S?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:te,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:()=>{Pi(m)},children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Q?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:Q,title:r("contextPanel.browser.empty"),className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:Ne},`${Q}:${b}`),S&&k?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:k.bounds.x,top:k.bounds.y,width:k.bounds.width,height:k.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[k.tag,k.text?` · ${k.text}`:""]})}):null]}):s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(Nc,{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")})]}),N?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]})]})},E0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=kt(),o=i.useRef(null),a=Ee(A=>A.setContextPanelTabTargetPath),c=Co(t),l=c!=="about:blank"?c:"",[d,u]=i.useState(l),[m,f]=i.useState(l),[g,y]=i.useState(!1),[p,x]=i.useState(!0),b=i.useRef(null),h=p,N=i.useCallback(A=>{!A||A==="about:blank"||!e||!n||a(e,n,A)},[e,n,a]),w=ut(A=>A.currentSessionId),S=ut(A=>A.newSessionDraft?.open),j=Sc(A=>A.addDraft),k=li(A=>A.addAttachedFile);i.useEffect(()=>{const A=o.current;if(!A)return;const C=()=>{try{const L=A.getURL();L&&L!=="about:blank"&&(f(L),u(L),N(L))}catch{}},O=L=>{const B=L.detail;typeof B?.url=="string"&&B.url&&(f(B.url),u(B.url),N(B.url))},T=()=>{b.current&&clearTimeout(b.current),b.current=setTimeout(()=>x(!0),200)},E=()=>{b.current&&clearTimeout(b.current),x(!1),C()},F=L=>{const B=L.detail;if(B?.disposition==="new-window"||B?.disposition==="foreground-tab"||B?.disposition==="background-tab"){L.preventDefault();const V=o.current;typeof V?.loadURL=="function"&&B.url&&V.loadURL(B.url)}},R=()=>{try{A.executeJavaScript?.(A0,!0).catch(()=>{})}catch{}};A.addEventListener("did-navigate",O),A.addEventListener("did-navigate-in-page",O),A.addEventListener("did-start-loading",T),A.addEventListener("did-stop-loading",E),A.addEventListener("new-window",F),A.addEventListener("dom-ready",R);try{A.isLoading()||(x(!1),C())}catch{}return R(),()=>{b.current&&clearTimeout(b.current),A.removeEventListener("did-navigate",O),A.removeEventListener("did-navigate-in-page",O),A.removeEventListener("did-start-loading",T),A.removeEventListener("did-stop-loading",E),A.removeEventListener("new-window",F),A.removeEventListener("dom-ready",R)}},[N]),i.useEffect(()=>{const A=setTimeout(()=>x(!1),3e4);return()=>clearTimeout(A)},[]),i.useEffect(()=>{if(!g)return;const A=C=>{if(C.key!=="Escape")return;C.preventDefault(),C.stopImmediatePropagation(),y(!1);const O=o.current;try{O?.executeJavaScript?.(ua).catch(()=>{})}catch{}};return window.addEventListener("keydown",A,!0),()=>window.removeEventListener("keydown",A,!0)},[g]),i.useEffect(()=>{const A=o.current;return()=>{try{const C=A?.getURL?.();C&&C!=="about:blank"&&a(e,n,C)}catch{}try{A?.executeJavaScript?.(ua).catch(()=>{})}catch{}}},[e,n,a]);const v=i.useCallback(A=>{const C=o.current;if(typeof C?.loadURL!="function")return;const O=Co(A);try{C.loadURL(O)}catch{}},[]),D=i.useCallback(()=>{const A=o.current;if(A){if(g){y(!1);try{A.executeJavaScript?.(ua).catch(()=>{})}catch{}return}y(!0),A.executeJavaScript?.(Jm,!0).then(async C=>{if(y(!1),!C||!qi(C))return;const O=w??(S?"draft":null);if(!O){de.error(r("contextPanel.preview.inspect.attachNoSession"));return}const T=typeof A.getWebContentsId=="function"?A.getWebContentsId():null;if(T==null)return;const E=await ug("desktop_browser_capture_page",{webContentsId:T}),F=await A.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),R=Number.isFinite(F?.width)?F.width:E.width,L=Number.isFinite(F?.height)?F.height:E.height,B=await Vc(E.base64,E.width,E.height,R,L,C),V=!!B;B&&await k(B),j({sessionKey:O,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Bc({pageUrl:m,viewport:{width:R,height:L},devicePixelRatio:window.devicePixelRatio||1,target:C,screenshotAttached:V,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),de.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>y(!1))}},[k,j,w,m,g,S,r]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:s.jsx(I,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:s.jsx(I,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:A=>{A.preventDefault(),v(d)},children:s.jsx("input",{value:d,onChange:A=>u(A.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx($e,{type:"button",variant:g?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:D,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{Pi(m)},children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[s.jsx("webview",{ref:o,src:Co(t),partition:"persist:openchamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!m||m==="about:blank")&&!p?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(Nc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")})]}):null,h?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},M0=()=>{const{t}=kt(),e=ci()??"",n=i.useMemo(()=>y0(e),[e]),r=Ee(G=>n?G.contextPanelByDirectory[n]:void 0),o=Ee(G=>G.closeContextPanel),a=Ee(G=>G.closeContextPanelTab),c=Ee(G=>G.openContextPanelTab),l=Ee(G=>G.toggleContextPanelExpanded),d=Ee(G=>G.setContextPanelWidth),u=Ee(G=>G.setActiveContextPanelTab),m=Ee(G=>G.reorderContextPanelTabs),f=yn(G=>G.setSelectedPath),g=Ee(G=>G.openContextPreview),{themeMode:y,setThemeMode:p,lightThemeId:x,darkThemeId:b,currentTheme:h}=Gr(),N=i.useMemo(()=>r?.tabs??[],[r?.tabs]),w=N.find(G=>G.id===r?.activeTabId)??N[N.length-1]??null,S=!!(r?.isOpen&&w),j=!!(S&&r?.expanded),k=Qm(r?.width??Ym),[v,D]=i.useState(!1),[A,C]=i.useState(!1),O=i.useRef(0),T=i.useRef(k),E=i.useRef(null),F=i.useRef(null),R=i.useRef(null),L=i.useRef(new Map),B=i.useRef(new Map),V=i.useRef(!1),M=i.useRef(S),Z=i.useRef(null),se=i.useCallback(()=>{C(!0),Z.current!==null&&window.cancelAnimationFrame(Z.current),Z.current=window.requestAnimationFrame(()=>{Z.current=null,C(!1)})},[]);i.useEffect(()=>()=>{Z.current!==null&&window.cancelAnimationFrame(Z.current)},[]),i.useLayoutEffect(()=>{const G=M.current;if(M.current=S,!S){C(!1);return}G||se()},[S,se]),i.useEffect(()=>{if(!S||V.current){V.current=S;return}const G=window.requestAnimationFrame(()=>{R.current?.focus({preventScroll:!0})});return V.current=!0,()=>window.cancelAnimationFrame(G)},[S]);const Q=i.useCallback(G=>{const fe=R.current;fe&&fe.style.setProperty("--oc-context-panel-width",`${Al(G,fe)}px`)},[]),K=i.useCallback(G=>{if(!(!S||j||!n)){try{G.currentTarget.setPointerCapture(G.pointerId)}catch{}F.current=G.pointerId,D(!0),O.current=G.clientX,T.current=k,E.current=k,Q(k),G.preventDefault()}},[Q,n,j,S,k]),ee=i.useCallback(G=>{if(!v||F.current!==G.pointerId)return;const fe=O.current-G.clientX,ce=Al(T.current+fe,R.current);E.current!==ce&&(E.current=ce,Q(ce))},[Q,v]),re=i.useCallback(G=>{if(F.current!==G.pointerId||!n)return;try{G.currentTarget.releasePointerCapture(G.pointerId)}catch{}const fe=Al(E.current??k,R.current);se(),Q(fe),E.current=fe,d(n,fe),D(!1),F.current=null},[Q,n,d,se,k]);i.useEffect(()=>{v||(E.current=null)},[v]);const he=i.useCallback(()=>{n&&o(n)},[o,n]),je=i.useCallback(()=>{n&&l(n)},[n,l]),te=i.useCallback(G=>{G.key==="Escape"&&(G.preventDefault(),G.stopPropagation(),he())},[he]);i.useEffect(()=>{if(!(!n||!w)&&w.mode==="file"&&w.targetPath){f(n,w.targetPath,{allowOutsideRoot:!0});return}},[w,n,f]);const Ne=w?.mode==="chat"?w.id:null,J=i.useCallback((G,fe,ce)=>Z1(B.current,G,fe,n||null,ce,{mode:y,lightThemeId:x,darkThemeId:b,currentTheme:h}),[h,b,n,x,y]);i.useEffect(()=>{const G=new Set(N.map(fe=>fe.id));for(const fe of B.current.keys())G.has(fe)||B.current.delete(fe)},[N]);const H=i.useCallback(G=>{!n||w?.mode!=="diff"||c(n,{mode:"diff",targetPath:w.targetPath,stagedDiff:G==="staged"})},[w,n,c]),q=i.useCallback(()=>{if(typeof window>"u")return;const G={themeMode:y,lightThemeId:x,darkThemeId:b,currentTheme:h};for(const fe of L.current.values()){const ce=fe.contentWindow;if(!ce)continue;const W=ce.__openchamberApplyThemeSync;if(typeof W=="function")try{W(G);continue}catch{}ce.postMessage({type:"openchamber:theme-sync",payload:G},window.location.origin)}},[h,b,x,y]),ae=i.useCallback(()=>{if(!(typeof window>"u"))for(const[G,fe]of L.current.entries()){const ce=fe.contentWindow;if(!ce)continue;const W={visible:Ne===G},z=ce.__openchamberSetEmbeddedVisibility;if(typeof z=="function")try{z(W);continue}catch{}ce.postMessage({type:"openchamber:embedded-visibility",payload:W},window.location.origin)}},[Ne]);i.useEffect(()=>{if(typeof window>"u")return;const G=fe=>{if(fe.origin!==window.location.origin||!Array.from(L.current.values()).some(_=>_.contentWindow===fe.source)||fe.data?.type!=="openchamber:cycle-theme-request")return;const z=["light","dark","system"],xe=(z.indexOf(y)+1)%z.length;p(z[xe])};return window.addEventListener("message",G),()=>window.removeEventListener("message",G)},[p,y]),i.useLayoutEffect(()=>{N.some(fe=>fe.mode==="chat")&&(q(),ae())},[b,x,ae,q,N,y]);const le=i.useMemo(()=>N.map(G=>{const fe=N0(G,t),ce=D0(fe,x0),W=v0(G.targetPath,e);return{id:G.id,label:ce,icon:k0(G),title:W?`${fe}: ${W}`:fe,closeLabel:t("contextPanel.tab.closeTabAria",{label:ce})}}),[e,t,N]),Se=w?.mode==="context"?s.jsx(_1,{}):w?.mode==="plan"?s.jsx(_m,{targetPath:w.targetPath}):w?.mode==="preview"?s.jsx(P0,{rawUrl:w.targetPath??"",onNavigate:G=>g(e,G)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(I,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),s.jsx("div",{className:"typography-ui-header text-foreground",children:t("contextPanel.preview.title")}),s.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:t("contextPanel.preview.description")})]}),Re=i.useMemo(()=>N.filter(G=>G.mode==="chat"),[N]),_e=i.useMemo(()=>N.filter(G=>G.mode==="browser"),[N]),Oe=i.useMemo(()=>N.filter(G=>G.mode==="diff"),[N]),Me=T0()?E0:R0,ge=i.useMemo(()=>N.some(G=>G.mode==="file"),[N]),Ae=w?.mode==="file",pe=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(To,{items:le,activeId:w?.id??null,onSelect:G=>{n&&u(n,G)},onClose:G=>{n&&a(n,G)},onReorder:(G,fe)=>{n&&m(n,G,fe)},layoutMode:"scrollable",variant:"default"}),s.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:je,className:"h-7 w-7 p-0",title:t(j?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),"aria-label":t(j?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),children:j?s.jsx(I,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:he,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})})]})]}),ue=S?j?{"--oc-context-panel-width":"100%",width:"100%",minWidth:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",minWidth:`min(${qm}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${v?E.current??k:k}px`}:{"--oc-context-panel-width":`${v?E.current??k:k}px`,width:0,minWidth:0,maxWidth:0,opacity:0,overflow:"hidden",visibility:"hidden"};return s.jsxs("aside",{ref:R,"data-context-panel":"true",tabIndex:-1,inert:!S||void 0,className:De("flex min-h-0 flex-col overflow-hidden bg-background",!j&&"border-l border-border/40",j?"absolute inset-0 z-20 min-w-0":"relative h-full flex-shrink-0",!S&&"pointer-events-none",v||!S||A?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:te,style:ue,children:[!j&&s.jsx("div",{className:De("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:K,onPointerMove:ee,onPointerUp:re,onPointerCancel:re,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),pe,s.jsxs("div",{className:De("relative min-h-0 flex-1 overflow-hidden",v&&"pointer-events-none"),children:[ge?s.jsx("div",{className:De("absolute inset-0",Ae?"block":"hidden"),children:s.jsx(Vm,{mode:"editor-only"})}):null,Re.map(G=>{const fe=C0(G.dedupeKey);if(!fe)return null;const ce=J(G.id,fe,G.readOnly);return ce?s.jsx("iframe",{ref:W=>{if(!W){L.current.delete(G.id);return}L.current.set(G.id,W)},src:ce,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:fe}),className:De("absolute inset-0 h-full w-full border-0 bg-background",Ne===G.id?"block":"hidden"),onLoad:()=>{q(),ae()}},G.id):null}),_e.map(G=>s.jsx("div",{className:De("absolute inset-0",w?.id!==G.id&&"hidden"),children:s.jsx(Me,{initialUrl:G.targetPath??"",directory:n,tabID:G.id})},G.id)),Oe.map(G=>s.jsx("div",{className:De("absolute inset-0",w?.id!==G.id&&"hidden"),children:s.jsx(Fm,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:G.stagedDiff?"staged":"working",onDiffScopeChange:H,targetFilePath:G.targetPath,flushContent:!0})},G.id)),w?.mode!=="chat"&&!Ae&&w?.mode!=="browser"&&w?.mode!=="diff"?Se:null]})]})},tc=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},F0=()=>{const t=gt.c(171),{t:e}=kt(),n=Ee(L0),r=Ee(O0),o=Ee(B0),a=Ee(V0),c=Ee(_0),l=Ee($0),d=Ee(z0),u=Ee(W0),m=Ee(U0),f=Ee(H0),g=Ee(G0),y=Ee(K0),p=ut(q0),x=ut(Y0),b=jr(Q0),h=Qs(J0),N=ws(X0),w=ci(),S=cc(Z0),{files:j,git:k}=er(),v=wn(ej),{isMobile:D}=Er();let A;t[0]!==w?(A=w?tc(w):null,t[0]=w,t[1]=A):A=t[1];const C=A,[O,T]=i.useState(""),E=Ha(O,200);let F;t[2]!==E?(F=E.trim(),t[2]=E,t[3]=F):F=t[3];const R=F;let L;t[4]!==O?(L=O.trim(),t[4]=O,t[5]=L):L=t[5];const B=L;let V,M;t[6]!==n?(V=()=>{n&&T("")},M=[n],t[6]=n,t[7]=V,t[8]=M):(V=t[7],M=t[8]),i.useEffect(V,M);let Z,se;t[9]!==b||t[10]!==v||t[11]!==k||t[12]!==n?(Z=()=>{if(!n||!k)return;const Le=setTimeout(()=>{const et=new Set;for(const Vt of b){const xt=Tr(Vt);!xt||et.has(xt)||(et.add(xt),v(xt,k))}},0);return()=>clearTimeout(Le)},se=[n,b,k,v],t[9]=b,t[10]=v,t[11]=k,t[12]=n,t[13]=Z,t[14]=se):(Z=t[13],se=t[14]),i.useEffect(Z,se);let Q;t[15]!==r?(Q=()=>r(!1),t[15]=r,t[16]=Q):Q=t[16];const K=Q;let ee;t[17]!==K?(ee=Le=>()=>{K(),Le()},t[17]=K,t[18]=ee):ee=t[18];const re=ee;let he;t[19]!==N?.id||t[20]!==N?.path||t[21]!==h||t[22]!==D||t[23]!==f||t[24]!==p||t[25]!==re||t[26]!==o||t[27]!==l||t[28]!==a||t[29]!==e||t[30]!==m||t[31]!==u||t[32]!==d?(he=()=>{const Le=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(I,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:re(()=>{o("chat"),l(!1),p()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(I,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:re(tj)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(I,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:re(sj)},{id:"toggle-sidebar",title:e(D?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(I,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(D?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:re(()=>{if(D){const{isSessionSwitcherOpen:et}=Ee.getState();l(!et)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(I,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:re(()=>u())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(I,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:re(()=>m())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(I,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:re(()=>{h&&f(h)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(I,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:re(()=>a(!0))}];return Fa()&&Le.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(I,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:re(()=>{Wr("desktop_open_draft_mini_chat_window",{directory:tc(h||N?.path||""),projectId:N?.id??null}).catch(nj)})}),Le},t[19]=N?.id,t[20]=N?.path,t[21]=h,t[22]=D,t[23]=f,t[24]=p,t[25]=re,t[26]=o,t[27]=l,t[28]=a,t[29]=e,t[30]=m,t[31]=u,t[32]=d,t[33]=he):he=t[33],N?.id,N?.path;let je;t[34]!==he?(je=he(),t[34]=he,t[35]=je):je=t[35];const te=je;let Ne;t[36]===Symbol.for("react.memo_cache_sentinel")?(Ne=hr(),t[36]=Ne):Ne=t[36];const J=Ne;let H,q;t[37]===Symbol.for("react.memo_cache_sentinel")?(H=Hr(),q=!J&&uc(),t[37]=H,t[38]=q):(H=t[37],q=t[38]);let ae;t[39]!==D?(ae={isVSCode:H,isWeb:q,isDesktop:J,isMobile:D},t[39]=D,t[40]=ae):ae=t[40];const le=ae;let Se;if(t[41]!==re||t[42]!==a||t[43]!==c||t[44]!==le){let Le;t[46]!==le?(Le=Vt=>Vt.isAvailable?Vt.isAvailable(le):!0,t[46]=le,t[47]=Le):Le=t[47];let et;t[48]!==re||t[49]!==a||t[50]!==c?(et=Vt=>{const xt=Fx(Vt.slug)??"settings-3",Ft=(Vt.keywords??[]).join(" ");return{id:`settings:${Vt.slug}`,title:Vt.title,icon:Vt.slug==="mcp"?s.jsx(zl,{className:"mr-2 h-4 w-4"}):s.jsx(I,{name:xt,className:"mr-2 h-4 w-4"}),searchText:`${Vt.title} ${Vt.group} ${Ft}`,onSelect:re(()=>{c(Vt.slug),a(!0)})}},t[48]=re,t[49]=a,t[50]=c,t[51]=et):et=t[51],Se=Mx.filter(rj).filter(Le).map(et),t[41]=re,t[42]=a,t[43]=c,t[44]=le,t[45]=Se}else Se=t[45];const Re=Se,_e=ij;let Oe;if(t[52]!==b){let Le;t[54]===Symbol.for("react.memo_cache_sentinel")?(Le=(et,Vt)=>_e(Vt)-_e(et),t[54]=Le):Le=t[54],Oe=[...b].sort(Le),t[52]=b,t[53]=Oe}else Oe=t[53];const Me=Oe,ge=Qf(),Ae=ut(oj);let pe;t[55]!==ge||t[56]!==Ae?(pe=(Le,et)=>{const Vt=Ae.get(Le);return Vt?.branch?Vt.branch.trim()||null:et&&ge.get(et)?.trim()||null},t[55]=ge,t[56]=Ae,t[57]=pe):pe=t[57];const ue=pe;let G;t[58]===Symbol.for("react.memo_cache_sentinel")?(G=[],t[58]=G):G=t[58];const[fe,ce]=i.useState(G),[W,z]=i.useState(!1);let be,xe;t[59]!==C||t[60]!==n||t[61]!==S||t[62]!==R?(be=()=>{if(!n){ce([]),z(!1);return}if(!C||R.length===0){ce([]),z(!1);return}let Le=!1;return z(!0),S(C,R,10,{type:"file"}).then(et=>{Le||ce(et.map(aj))}).catch(()=>{Le||ce([])}).finally(()=>{Le||z(!1)}),()=>{Le=!0}},xe=[n,C,R,S],t[59]=C,t[60]=n,t[61]=S,t[62]=R,t[63]=be,t[64]=xe):(be=t[63],xe=t[64]),i.useEffect(be,xe);const _=B.length>0;let ye;e:{if(!_){let et;t[65]!==te?(et=te.map(lj),t[65]=te,t[66]=et):et=t[66],ye=et;break e}let Le;t[67]!==te||t[68]!==B?(Le=Wo(te,B,cj,{limit:7,noFuzzy:!0}),t[67]=te,t[68]=B,t[69]=Le):Le=t[69],ye=Le}const $=ye;let Ie;e:{if(!_){let et;t[70]===Symbol.for("react.memo_cache_sentinel")?(et=[],t[70]=et):et=t[70],Ie=et;break e}let Le;t[71]!==B||t[72]!==Re?(Le=Wo(Re,B,dj,{limit:7,noFuzzy:!0}),t[71]=B,t[72]=Re,t[73]=Le):Le=t[73],Ie=Le}const ve=Ie;let Fe;e:{if(!_){let et;t[74]!==Me?(et=Me.slice(0,5).map(uj),t[74]=Me,t[75]=et):et=t[75],Fe=et;break e}let Le;t[76]!==B||t[77]!==Me?(Le=Wo(Me,B,fj,{limit:7,threshold:.2}),t[76]=B,t[77]=Me,t[78]=Le):Le=t[78],Fe=Le}const Ce=Fe;let ne;e:{if(!_||fe.length===0){let et;t[79]===Symbol.for("react.memo_cache_sentinel")?(et=[],t[79]=et):et=t[79],ne=et;break e}let Le;t[80]!==fe||t[81]!==B?(Le=Wo(fe,B,mj,{limit:10,threshold:.4}),t[80]=fe,t[81]=B,t[82]=Le):Le=t[82],ne=Le}const P=ne;let me,oe,Be,Ue,Ke,Qe,rt,pt,jt,Ve,Ze,nt,St,Dt,wt;if(t[83]!==ue||t[84]!==K||t[85]!==C||t[86]!==j||t[87]!==_||t[88]!==n||t[89]!==g||t[90]!==O||t[91]!==$||t[92]!==P||t[93]!==Ce||t[94]!==ve||t[95]!==r||t[96]!==x||t[97]!==y||t[98]!==e){const Le=$.map(hj),et=ve.map(pj),Vt=Ce.map(gj);wt=_?P.map(xj):[];let xt;e:{if(!_){xt=["commands","sessions"];break e}const Ot=bj,It=[{key:"commands",score:Ot($)},{key:"settings",score:Ot(ve)},{key:"sessions",score:Ot(Ce)},{key:"files",score:Ot(P)}];It.sort(yj),xt=It.map(wj)}const Ft=xt;let Gt;t[114]!==K||t[115]!==x?(Gt=Ot=>{K(),x(Ot.id,Tr(Ot))},t[114]=K,t[115]=x,t[116]=Gt):Gt=t[116];const Ut=Gt;let qt;t[117]!==K||t[118]!==C||t[119]!==j||t[120]!==g?(qt=async Ot=>{if(!C)return;const It=await Fc(j,Ot);if(!It.ok){de.error(Lc(It.reason));return}g(C,Ot),K()},t[117]=K,t[118]=C,t[119]=j,t[120]=g,t[121]=qt):qt=t[121];const Xt=qt;let Lt;t[122]!==y?(Lt=Ot=>La(ri(Ot,y)),t[122]=y,t[123]=Lt):Lt=t[123];const Bt=Lt;Ue=Os,nt=n,St=r;let Yt;t[124]!==e?(Yt=e("commandPalette.title"),t[124]=e,t[125]=Yt):Yt=t[125];let Jt;t[126]!==Yt?(Jt=s.jsx(_s,{children:Yt}),t[126]=Yt,t[127]=Jt):Jt=t[127];let es;t[128]!==e?(es=e("commandPalette.description"),t[128]=e,t[129]=es):es=t[129];let Zt;t[130]!==es?(Zt=s.jsx(an,{children:es}),t[130]=es,t[131]=Zt):Zt=t[131],t[132]!==Jt||t[133]!==Zt?(Dt=s.jsxs(Us,{className:"sr-only",children:[Jt,Zt]}),t[132]=Jt,t[133]=Zt,t[134]=Dt):Dt=t[134],Be=Ls,Ve="overflow-hidden p-0",Ze=!0,oe=Oa,rt=!1,pt="[&_[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 vs;t[135]!==e?(vs=e("commandPalette.input.placeholder"),t[135]=e,t[136]=vs):vs=t[136],t[137]!==O||t[138]!==vs?(jt=s.jsx(Ba,{value:O,onValueChange:T,placeholder:vs}),t[137]=O,t[138]=vs,t[139]=jt):jt=t[139],me=Va;let bt;t[140]!==e?(bt=e("commandPalette.empty.noResults"),t[140]=e,t[141]=bt):bt=t[141],t[142]!==bt?(Ke=s.jsx(_a,{children:bt}),t[142]=bt,t[143]=Ke):Ke=t[143],Qe=Ft.map(Ot=>Ot==="commands"&&Le.length>0?s.jsx(ii,{children:Le.map(It=>s.jsxs(ai,{value:It.id,onSelect:It.onSelect,children:[It.icon,s.jsx("span",{children:It.title}),It.shortcutId?s.jsx(fg,{children:Bt(It.shortcutId)}):null]},It.id))},"commands"):Ot==="settings"&&et.length>0?s.jsx(ii,{children:et.map(vj)},"settings"):Ot==="sessions"&&Vt.length>0?s.jsx(ii,{children:Vt.map(It=>{const us=It.title||e("commandPalette.session.untitled"),He=Tr(It),ft=ue(It.id,He);return s.jsxs(ai,{value:`session:${It.id}`,onSelect:()=>Ut(It),children:[s.jsx(I,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:us}),ft?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:ft})]}):null]},It.id)})},"sessions"):Ot==="files"&&wt.length>0?s.jsx(ii,{children:wt.map(It=>{const us=mg(It.relativePath||It.name,{maxLength:80});return s.jsxs(ai,{value:`file:${It.path}`,onSelect:()=>{Xt(It.path)},children:[s.jsx(Ur,{filePath:It.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":It.relativePath,children:us})]},`file:${It.path}`)})},"files"):null),t[83]=ue,t[84]=K,t[85]=C,t[86]=j,t[87]=_,t[88]=n,t[89]=g,t[90]=O,t[91]=$,t[92]=P,t[93]=Ce,t[94]=ve,t[95]=r,t[96]=x,t[97]=y,t[98]=e,t[99]=me,t[100]=oe,t[101]=Be,t[102]=Ue,t[103]=Ke,t[104]=Qe,t[105]=rt,t[106]=pt,t[107]=jt,t[108]=Ve,t[109]=Ze,t[110]=nt,t[111]=St,t[112]=Dt,t[113]=wt}else me=t[99],oe=t[100],Be=t[101],Ue=t[102],Ke=t[103],Qe=t[104],rt=t[105],pt=t[106],jt=t[107],Ve=t[108],Ze=t[109],nt=t[110],St=t[111],Dt=t[112],wt=t[113];let ot;t[144]!==_||t[145]!==W||t[146]!==e||t[147]!==wt?(ot=_&&W&&wt.length===0?s.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:e("commandPalette.empty.searchingFiles")}):null,t[144]=_,t[145]=W,t[146]=e,t[147]=wt,t[148]=ot):ot=t[148];let at;t[149]!==me||t[150]!==Ke||t[151]!==Qe||t[152]!==ot?(at=s.jsxs(me,{children:[Ke,Qe,ot]}),t[149]=me,t[150]=Ke,t[151]=Qe,t[152]=ot,t[153]=at):at=t[153];let Kt;t[154]!==oe||t[155]!==rt||t[156]!==pt||t[157]!==jt||t[158]!==at?(Kt=s.jsxs(oe,{shouldFilter:rt,className:pt,children:[jt,at]}),t[154]=oe,t[155]=rt,t[156]=pt,t[157]=jt,t[158]=at,t[159]=Kt):Kt=t[159];let is;t[160]!==Be||t[161]!==Ve||t[162]!==Ze||t[163]!==Kt?(is=s.jsx(Be,{className:Ve,showCloseButton:Ze,children:Kt}),t[160]=Be,t[161]=Ve,t[162]=Ze,t[163]=Kt,t[164]=is):is=t[164];let $t;return t[165]!==Ue||t[166]!==nt||t[167]!==St||t[168]!==Dt||t[169]!==is?($t=s.jsxs(Ue,{open:nt,onOpenChange:St,children:[Dt,is]}),t[165]=Ue,t[166]=nt,t[167]=St,t[168]=Dt,t[169]=is,t[170]=$t):$t=t[170],$t};function L0(t){return t.isCommandPaletteOpen}function O0(t){return t.setCommandPaletteOpen}function B0(t){return t.setActiveMainTab}function V0(t){return t.setSettingsDialogOpen}function _0(t){return t.setSettingsPage}function $0(t){return t.setSessionSwitcherOpen}function z0(t){return t.toggleSidebar}function W0(t){return t.toggleRightSidebar}function U0(t){return t.toggleBottomTerminal}function H0(t){return t.openContextOverview}function G0(t){return t.openContextFile}function K0(t){return t.shortcutOverrides}function q0(t){return t.openNewSessionDraft}function Y0(t){return t.setCurrentSession}function Q0(t){return t.activeSessions}function J0(t){return t.currentDirectory}function X0(t){return t.getActiveProject()}function Z0(t){return t.searchFiles}function ej(t){return t.ensureStatus}function tj(){Jf()}function sj(){Pr.requestDirectoryDialog()}function nj(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function rj(t){return t.slug!=="home"}function ij(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function oj(t){return t.worktreeMetadata}function aj(t){return{path:tc(t.path),name:t.name,relativePath:t.relativePath}}function lj(t){return{item:t,score:0}}function cj(t){return t.searchText}function dj(t){return t.searchText}function uj(t){return{item:t,score:0}}function fj(t){return t.title||""}function mj(t){return t.name}function hj(t){return t.item}function pj(t){return t.item}function gj(t){return t.item}function xj(t){return t.item}function bj(t){return t.length?t[0].score:1/0}function yj(t,e){return t.score-e.score}function wj(t){return t.key}function vj(t){return s.jsxs(ai,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const zu=(t,e,n)=>pg(t)?La(ri(t,n)):e,jj=()=>{const t=gt.c(68),{t:e}=kt(),n=Ee(Sj),r=Ee(Nj),o=Ee(kj);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=hg(),t[0]=a):a=t[0];const c=a;let l,d,u,m,f,g,y,p,x;if(t[1]!==n||t[2]!==r||t[3]!==o||t[4]!==e){const R=[{categoryKey:"helpDialog.section.navigationCommands",items:[{id:"open_command_palette",descriptionKey:"helpDialog.item.openCommandPalette",icon:"command",keys:""},{id:"open_help",descriptionKey:"helpDialog.item.showKeyboardShortcuts",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"helpDialog.item.toggleSessionSidebar",icon:"layout-left",keys:""},{id:"cycle_agent",keys:"",descriptionKey:"helpDialog.item.cycleAgent",icon:"ai-agent"},{id:"open_model_selector",descriptionKey:"helpDialog.item.openModelSelector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"helpDialog.item.navigateModels",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"helpDialog.item.adjustThinkingMode",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"helpDialog.item.cycleThinkingVariant",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${c} + N`],descriptionKey:"helpDialog.item.newWindow",icon:"window"}]},{categoryKey:"helpDialog.section.sessionManagement",items:[{id:"new_chat",descriptionKey:"helpDialog.item.createNewSession",icon:"add",keys:""},{id:"new_chat_worktree",descriptionKey:"helpDialog.item.createNewWorktreeDraft",icon:"git-branch",keys:""},{id:"focus_input",descriptionKey:"helpDialog.item.focusChatInput",icon:"text",keys:""},{id:"abort_run",descriptionKey:"helpDialog.item.abortActiveRun",icon:"close-circle",keys:""}]},{categoryKey:"helpDialog.section.panels",items:[{id:"toggle_right_sidebar",descriptionKey:"helpDialog.item.toggleRightSidebar",icon:"layout-right",keys:""},{id:"open_right_sidebar_git",descriptionKey:"helpDialog.item.openRightSidebarGitTab",icon:"git-branch",keys:""},{id:"open_right_sidebar_files",descriptionKey:"helpDialog.item.openRightSidebarFilesTab",icon:"layout-right",keys:""},{id:"cycle_right_sidebar_tab",descriptionKey:"helpDialog.item.cycleRightSidebarTab",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{id:"toggle_terminal_expanded",descriptionKey:"helpDialog.item.toggleTerminalExpanded",icon:"window",keys:""},{id:"toggle_context_plan",descriptionKey:"helpDialog.item.togglePlanContextPanel",icon:"time",keys:""}]},{categoryKey:"helpDialog.section.interface",items:[{id:"cycle_theme",descriptionKey:"helpDialog.item.cycleTheme",icon:"palette",keys:""},{keys:[`${c} + 1...9`],descriptionKey:"helpDialog.item.switchProject",icon:"layout-left"},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"cycle_services_tab",descriptionKey:"helpDialog.item.cycleServicesTab",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"helpDialog.item.openSettings",icon:"settings-3",keys:""}]}];d=Os,p=n,x=r,l=Ls,g="max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden";let L;t[14]===Symbol.for("react.memo_cache_sentinel")?(L=s.jsx(I,{name:"settings-3",className:"h-5 w-5"}),t[14]=L):L=t[14];let B;t[15]!==e?(B=e("helpDialog.title"),t[15]=e,t[16]=B):B=t[16];let V;t[17]!==B?(V=s.jsxs(_s,{className:"flex items-center gap-2",children:[L,B]}),t[17]=B,t[18]=V):V=t[18];let M;t[19]!==e?(M=e("helpDialog.description"),t[19]=e,t[20]=M):M=t[20];let Z;t[21]!==M?(Z=s.jsx(an,{children:M}),t[21]=M,t[22]=Z):Z=t[22],t[23]!==V||t[24]!==Z?(y=s.jsxs(Us,{children:[V,Z]}),t[23]=V,t[24]=Z,t[25]=y):y=t[25],f="flex-1 overflow-y-auto mt-3 pr-1",u="space-y-4",m=R.map(se=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(se.categoryKey)}),s.jsx("div",{className:"space-y-1",children:se.items.map(Q=>{const K=Q.id?zu(Q.id,Array.isArray(Q.keys)?Q.keys[0]:Q.keys,o):Array.isArray(Q.keys)?Q.keys:Q.keys.split(" / ");return s.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[Q.icon&&s.jsx(I,{name:Q.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(Q.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(K)?K:[K]).map((ee,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:ee})]},`${ee}-${re}`))})]},Q.id||Q.descriptionKey)})})]},se.categoryKey)),t[1]=n,t[2]=r,t[3]=o,t[4]=e,t[5]=l,t[6]=d,t[7]=u,t[8]=m,t[9]=f,t[10]=g,t[11]=y,t[12]=p,t[13]=x}else l=t[5],d=t[6],u=t[7],m=t[8],f=t[9],g=t[10],y=t[11],p=t[12],x=t[13];let b;t[26]!==u||t[27]!==m?(b=s.jsx("div",{className:u,children:m}),t[26]=u,t[27]=m,t[28]=b):b=t[28];let h;t[29]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(I,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),t[29]=h):h=t[29];let N;t[30]!==e?(N=e("helpDialog.proTips.title"),t[30]=e,t[31]=N):N=t[31];let w;t[32]!==N?(w=s.jsx("p",{className:"font-medium mb-1",children:N}),t[32]=N,t[33]=w):w=t[33];let S;t[34]!==o||t[35]!==e?(S=e("helpDialog.proTips.commandPalette",{shortcut:zu("open_command_palette",`${c} P`,o)}),t[34]=o,t[35]=e,t[36]=S):S=t[36];let j;t[37]!==S?(j=s.jsxs("li",{children:["• ",S]}),t[37]=S,t[38]=j):j=t[38];let k;t[39]!==e?(k=e("helpDialog.proTips.recentSessions"),t[39]=e,t[40]=k):k=t[40];let v;t[41]!==k?(v=s.jsxs("li",{children:["• ",k]}),t[41]=k,t[42]=v):v=t[42];let D;t[43]!==e?(D=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=D):D=t[44];let A;t[45]!==D?(A=s.jsxs("li",{children:["• ",D]}),t[45]=D,t[46]=A):A=t[46];let C;t[47]!==j||t[48]!==v||t[49]!==A?(C=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[j,v,A]}),t[47]=j,t[48]=v,t[49]=A,t[50]=C):C=t[50];let O;t[51]!==w||t[52]!==C?(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:[w,C]})]})}),t[51]=w,t[52]=C,t[53]=O):O=t[53];let T;t[54]!==O||t[55]!==f||t[56]!==b?(T=s.jsxs("div",{className:f,children:[b,O]}),t[54]=O,t[55]=f,t[56]=b,t[57]=T):T=t[57];let E;t[58]!==l||t[59]!==T||t[60]!==g||t[61]!==y?(E=s.jsxs(l,{className:g,children:[y,T]}),t[58]=l,t[59]=T,t[60]=g,t[61]=y,t[62]=E):E=t[62];let F;return t[63]!==d||t[64]!==E||t[65]!==p||t[66]!==x?(F=s.jsx(d,{open:p,onOpenChange:x,children:E}),t[63]=d,t[64]=E,t[65]=p,t[66]=x,t[67]=F):F=t[67],F};function Sj(t){return t.isHelpDialogOpen}function Nj(t){return t.setHelpDialogOpen}function kj(t){return t.shortcutOverrides}const Cj=()=>{const t=gt.c(32),{t:e}=kt(),n=Ee(Aj),r=Ee(Dj),o=Ee(Ij);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await pr(o)).ok){de.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}de.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(_s,{children:l}),t[5]=l,t[6]=d):d=t[6];let u;t[7]!==e?(u=e("openCodeStatusDialog.description"),t[7]=e,t[8]=u):u=t[8];let m;t[9]!==u?(m=s.jsx(an,{children:u}),t[9]=u,t[10]=m):m=t[10];let f;t[11]!==d||t[12]!==m?(f=s.jsxs(Us,{children:[d,m]}),t[11]=d,t[12]=m,t[13]=f):f=t[13];let g;t[14]!==e?(g=e("openCodeStatusDialog.actions.copy"),t[14]=e,t[15]=g):g=t[15];let y;t[16]!==c||t[17]!==g?(y=s.jsx("div",{className:"flex items-center justify-end",children:s.jsx("button",{type:"button",onClick:c,className:"app-region-no-drag inline-flex h-9 items-center justify-center rounded-md px-3 typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:g})}),t[16]=c,t[17]=g,t[18]=y):y=t[18];let p;t[19]!==o||t[20]!==e?(p=o||e("openCodeStatusDialog.empty.noData"),t[19]=o,t[20]=e,t[21]=p):p=t[21];let x;t[22]!==p?(x=s.jsx("pre",{className:"max-h-[60vh] overflow-auto rounded-lg bg-surface-muted p-4 typography-code text-foreground whitespace-pre-wrap",children:p}),t[22]=p,t[23]=x):x=t[23];let b;t[24]!==f||t[25]!==y||t[26]!==x?(b=s.jsxs(Ls,{className:"max-w-2xl",children:[f,y,x]}),t[24]=f,t[25]=y,t[26]=x,t[27]=b):b=t[27];let h;return t[28]!==n||t[29]!==r||t[30]!==b?(h=s.jsx(Os,{open:n,onOpenChange:r,children:b}),t[28]=n,t[29]=r,t[30]=b,t[31]=h):h=t[31],h};function Aj(t){return t.isOpenCodeStatusDialogOpen}function Dj(t){return t.setOpenCodeStatusDialogOpen}function Ij(t){return t.openCodeStatusText}const Pj=180,Wu=600,Tj=1,Rj=6,Ej=({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(()=>Hr(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<Tj&&a.current.length>0;){const m=a.current.shift();if(!m)break;ut.getState().currentSessionId!==m&&(Id(m).renderable||(c.current.add(m),r(m).catch(()=>{}).finally(()=>{c.current.delete(m),d()})))}},[r,l]),u=i.useCallback(m=>{if(l||!m||m===t||typeof window>"u"||Id(m).renderable||c.current.has(m)||a.current.includes(m))return;a.current.length>=Rj&&a.current.shift();const f=o.current.get(m);f!==void 0&&window.clearTimeout(f);const g=window.setTimeout(()=>{o.current.delete(m),a.current.push(m),d()},Pj);o.current.set(m,g)},[t,l,d]);i.useEffect(()=>{if(l||!t||e.length===0)return;const m=window.setTimeout(()=>{const f=e.findIndex(g=>g.id===t);f<0||(u(e[f-1]?.id),u(e[f+1]?.id))},Wu);return()=>window.clearTimeout(m)},[t,l,u,e]),i.useEffect(()=>{if(l||!t||n.length===0)return;const m=window.setTimeout(()=>{const f=n.indexOf(t);f<0||(u(n[f-1]),u(n[f+1]))},Wu);return()=>window.clearTimeout(m)},[t,l,n,u]),i.useEffect(()=>{const m=o.current;return()=>{m.forEach(f=>{clearTimeout(f)}),m.clear(),a.current=[]}},[])};let Qi=null,Ji=null,fa=null,Eo=0,Ta=null;const Ii=new Set,Mj=3e4,Fj=45e3,Zm=()=>{fa&&(clearTimeout(fa),fa=null)},eh=()=>{if(Ji||Ii.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Eo,5)),Mj);Ji=setTimeout(()=>{Ji=null,Eo+=1,$c()},t)},Mo=()=>{Zm(),Qi&&Qi.close(),Qi=null},Uu=()=>{Zm(),Ii.size!==0&&(fa=setTimeout(()=>{Mo(),eh()},Fj))},Lj=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}},Oj=t=>{if(t.type==="openchamber:event-stream-ready"){Eo=0;return}if(t.type==="openchamber:heartbeat"||t.type!=="openchamber:scheduled-task-ran")return;const e=t.properties&&typeof t.properties=="object"?t.properties:null,n=typeof e?.projectId=="string"?e.projectId:"",r=typeof e?.taskId=="string"?e.taskId:"",o=typeof e?.ranAt=="number"?e.ranAt:Date.now(),a=e?.status,c=a==="running"||a==="error"?a:"success";if(!n||!r)return;const l={type:"scheduled-task-ran",projectId:n,taskId:r,ranAt:o,status:c,...typeof e?.sessionId=="string"&&e.sessionId.length>0?{sessionId:e.sessionId}:{}};for(const d of Ii)d(l)},$c=()=>{if(typeof window>"u"||Ii.size===0||typeof EventSource!="function"||Qi&&Qi.readyState!==EventSource.CLOSED)return;Mo();const t=new EventSource(Ai().sse("/api/openchamber/events"));t.onopen=()=>{Uu()},t.onmessage=e=>{Uu();const n=Lj(e.data);n&&Oj(n)},t.onerror=()=>{Mo(),eh()},Qi=t},Bj=()=>{Ta||typeof window>"u"||(Ta=Pf(()=>{Mo(),Eo=0,$c()}))},Vj=()=>{Ta?.(),Ta=null},th=t=>(Ii.add(t),Bj(),$c(),()=>{Ii.delete(t),Ii.size===0&&(Ji&&(clearTimeout(Ji),Ji=null),Eo=0,Mo(),Vj())}),Ya=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},ro=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},_j=async t=>{const e=ro(t),n=await As(`/api/projects/${encodeURIComponent(e)}/scheduled-tasks`);if(!n.ok)throw new Error(await Ya(n,"Failed to load scheduled tasks"));const r=await n.json().catch(()=>null);return!r||!Array.isArray(r.tasks)?[]:r.tasks},Hu=async(t,e)=>{const n=ro(t),r=await As(`/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 Ya(r,"Failed to save scheduled task"));const o=await r.json().catch(()=>null);return!o||!Array.isArray(o.tasks)?[]:o.tasks},$j=async(t,e)=>{const n=ro(t),r=ro(e),o=await As(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}`,{method:"DELETE",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Ya(o,"Failed to delete scheduled task"));const a=await o.json().catch(()=>null);return!a||!Array.isArray(a.tasks)?[]:a.tasks},zj=async(t,e)=>{const n=ro(t),r=ro(e),o=await As(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}/run`,{method:"POST",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Ya(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 sh(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return Cf.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function Wj(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=Cf.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 Uj=[{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"}],nh=[0,1,2,3,4,5,6],sc=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"],Gu=()=>{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}`},ma=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},Ku=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},Hj=(t,e,n)=>{const r=ma(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},qu=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),Gj=(t,e)=>{const n=t.getFullYear(),r=t.getMonth(),c=(new Date(n,r,1).getDay()-e+7)%7,l=new Date(n,r+1,0).getDate(),d=new Date(n,r,0).getDate(),u=[];for(let m=0;m<42;m+=1){const f=m-c+1;if(f<=0){const g=d+f;u.push({date:new Date(n,r-1,g),inCurrentMonth:!1});continue}if(f>l){u.push({date:new Date(n,r+1,f-l),inCurrentMonth:!1});continue}u.push({date:new Date(n,r,f),inCurrentMonth:!0})}return u},Kj=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}},wi=(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")}`},co=(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"},Yu=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:co(t,{min:1,max:12}),Zo=t=>/^[0-5][0-9]$/.test(t)?t:co(t,{max:59}),qj=(t,e)=>co(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),Qu=(t,e)=>co(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),Yj=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}},Qj=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}},Jj=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return nh.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},Xj=(t,e)=>[...t.slice(e),...t.slice(0,e)],Xn=t=>{const e=gt.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},Ju=t=>{const e=gt.c(84),{value:n,onChange:r,use24Hour:o,hourAriaLabel:a,minuteAriaLabel:c,periodAriaLabel:l,amLabel:d,pmLabel:u}=t;let m;e[0]!==n?(m=Kj(n),e[0]=n,e[1]=m):m=e[1];const f=m,g=tt.useRef(null),y=tt.useRef(null),[p,x]=tt.useState(null),[b,h]=tt.useState(null),N=tt.useRef(null),w=tt.useRef(null);let S;e[2]===Symbol.for("react.memo_cache_sentinel")?(S=pe=>{N.current=pe,x(pe)},e[2]=S):S=e[2];const j=S;let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=pe=>{w.current=pe,h(pe)},e[3]=k):k=e[3];const v=k,D=iS,A=oS,C=aS;let O;e[4]!==r||e[5]!==f.meridiem||e[6]!==f.minute||e[7]!==o?(O=pe=>{const ue=pe.replace(/\D/g,"").slice(0,2);j(ue),ue.length===2&&(r(o?C(D(ue),f.minute):wi(Yu(ue),f.minute,f.meridiem)),j(null),y.current?.focus())},e[4]=r,e[5]=f.meridiem,e[6]=f.minute,e[7]=o,e[8]=O):O=e[8];const T=O;let E;e[9]!==r||e[10]!==f.meridiem||e[11]!==f.minute||e[12]!==o?(E=()=>{const pe=N.current;if(pe!==null&&(j(null),pe.length!==0)){if(o){r(C(D(pe.padStart(2,"0")),f.minute));return}r(wi(Yu(pe.padStart(2,"0")),f.minute,f.meridiem))}},e[9]=r,e[10]=f.meridiem,e[11]=f.minute,e[12]=o,e[13]=E):E=e[13];const F=E;let R;e[14]!==r||e[15]!==f.hour12||e[16]!==f.hour24||e[17]!==f.meridiem||e[18]!==o?(R=pe=>{const ue=pe.replace(/\D/g,"").slice(0,2);v(ue),ue.length===2&&(r(o?C(f.hour24,Zo(ue)):wi(f.hour12,Zo(ue),f.meridiem)),v(null))},e[14]=r,e[15]=f.hour12,e[16]=f.hour24,e[17]=f.meridiem,e[18]=o,e[19]=R):R=e[19];const L=R;let B;e[20]!==r||e[21]!==f.hour12||e[22]!==f.hour24||e[23]!==f.meridiem||e[24]!==o?(B=()=>{const pe=w.current;pe!==null&&(v(null),pe.length!==0&&r(o?C(f.hour24,Zo(pe.padStart(2,"0"))):wi(f.hour12,Zo(pe.padStart(2,"0")),f.meridiem)))},e[20]=r,e[21]=f.hour12,e[22]=f.hour24,e[23]=f.meridiem,e[24]=o,e[25]=B):B=e[25];const V=B;let M;e[26]!==r||e[27]!==f.hour12||e[28]!==f.hour24||e[29]!==f.meridiem||e[30]!==f.minute||e[31]!==o?(M=pe=>r(o?C(A(f.hour24,pe),f.minute):wi(qj(f.hour12,pe),f.minute,f.meridiem)),e[26]=r,e[27]=f.hour12,e[28]=f.hour24,e[29]=f.meridiem,e[30]=f.minute,e[31]=o,e[32]=M):M=e[32];const Z=M;let se;e[33]!==r||e[34]!==f.hour12||e[35]!==f.hour24||e[36]!==f.meridiem||e[37]!==f.minute||e[38]!==o?(se=pe=>r(o?C(f.hour24,Qu(f.minute,pe)):wi(f.hour12,Qu(f.minute,pe),f.meridiem)),e[33]=r,e[34]=f.hour12,e[35]=f.hour24,e[36]=f.meridiem,e[37]=f.minute,e[38]=o,e[39]=se):se=e[39];const Q=se;let K;e[40]!==r||e[41]!==f.hour12||e[42]!==f.meridiem||e[43]!==f.minute?(K=pe=>{pe!==f.meridiem&&r(wi(f.hour12,f.minute,pe))},e[40]=r,e[41]=f.hour12,e[42]=f.meridiem,e[43]=f.minute,e[44]=K):K=e[44];const ee=K;let re;e[45]!==F||e[46]!==Z?(re=pe=>{if(pe.key==="ArrowRight"){pe.preventDefault(),F(),y.current?.focus();return}(pe.key==="ArrowUp"||pe.key==="ArrowDown")&&(pe.preventDefault(),j(null),Z(pe.key==="ArrowUp"?1:-1))},e[45]=F,e[46]=Z,e[47]=re):re=e[47];const he=re;let je;e[48]!==V||e[49]!==Q?(je=pe=>{if(pe.key==="ArrowLeft"&&(pe.currentTarget.selectionStart??0)===0){pe.preventDefault(),V(),g.current?.focus();return}(pe.key==="ArrowUp"||pe.key==="ArrowDown")&&(pe.preventDefault(),v(null),Q(pe.key==="ArrowUp"?1:-1))},e[48]=V,e[49]=Q,e[50]=je):je=e[50];const te=je,Ne=o?"px-2":"pl-2 pr-1";let J;e[51]!==Ne?(J=De("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",Ne),e[51]=Ne,e[52]=J):J=e[52];const H=p??(o?f.hour24:f.hour12);let q;e[53]!==T?(q=pe=>T(pe.target.value),e[53]=T,e[54]=q):q=e[54];let ae;e[55]===Symbol.for("react.memo_cache_sentinel")?(ae=()=>j(""),e[55]=ae):ae=e[55];let le;e[56]!==F||e[57]!==a||e[58]!==he||e[59]!==H||e[60]!==q?(le=s.jsx("input",{ref:g,inputMode:"numeric",value:H,onChange:q,onKeyDown:he,onFocus:ae,onBlur:F,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]=F,e[57]=a,e[58]=he,e[59]=H,e[60]=q,e[61]=le):le=e[61];let Se;e[62]===Symbol.for("react.memo_cache_sentinel")?(Se=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=Se):Se=e[62];const Re=b??f.minute;let _e;e[63]!==L?(_e=pe=>L(pe.target.value),e[63]=L,e[64]=_e):_e=e[64];let Oe;e[65]===Symbol.for("react.memo_cache_sentinel")?(Oe=()=>v(""),e[65]=Oe):Oe=e[65];let Me;e[66]!==V||e[67]!==c||e[68]!==te||e[69]!==Re||e[70]!==_e?(Me=s.jsx("input",{ref:y,inputMode:"numeric",value:Re,onChange:_e,onKeyDown:te,onFocus:Oe,onBlur:V,maxLength:2,"aria-label":c,className:"h-7 w-7 shrink-0 rounded-sm bg-transparent text-center font-mono text-sm tabular-nums text-foreground outline-none caret-transparent focus:bg-interactive-hover"}),e[66]=V,e[67]=c,e[68]=te,e[69]=Re,e[70]=_e,e[71]=Me):Me=e[71];let ge;e[72]!==d||e[73]!==f.meridiem||e[74]!==l||e[75]!==u||e[76]!==ee||e[77]!==o?(ge=o?null:s.jsxs(Un,{value:f.meridiem,onValueChange:pe=>ee(pe),children:[s.jsx(Hn,{"aria-label":l,className:"ml-1 h-7 w-fit border-0 bg-transparent pl-2 pr-1 shadow-none hover:bg-interactive-hover focus:ring-0",children:s.jsx(Cn,{})}),s.jsxs(Gn,{children:[s.jsx(Ts,{value:"AM",children:d}),s.jsx(Ts,{value:"PM",children:u})]})]}),e[72]=d,e[73]=f.meridiem,e[74]=l,e[75]=u,e[76]=ee,e[77]=o,e[78]=ge):ge=e[78];let Ae;return e[79]!==J||e[80]!==le||e[81]!==Me||e[82]!==ge?(Ae=s.jsxs("div",{className:J,children:[le,Se,Me,ge]}),e[79]=J,e[80]=le,e[81]=Me,e[82]=ge,e[83]=Ae):Ae=e[83],Ae},Xu=t=>new Date(t.getFullYear(),t.getMonth(),1),Zj=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},Zu=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),eS=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"]},ef=(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:eS(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:Gu(),onceTime:typeof t.schedule.time=="string"&&/^([01]\d|2[0-3]):([0-5]\d)$/.test(t.schedule.time)?t.schedule.time:"09:00",weekdays:Array.isArray(t.schedule.weekdays)?t.schedule.weekdays:[1],timezone:t.schedule.timezone||n,cronExpression:t.schedule.kind==="cron"&&typeof t.schedule.cron=="string"?t.schedule.cron:""},execution:{prompt:t.execution.prompt,providerID:t.execution.providerID,modelID:t.execution.modelID,variant:t.execution.variant||"",agent:t.execution.agent||""},state:t.state}:{name:"",enabled:!0,schedule:{kind:"daily",times:["09:00"],onceDate:Gu(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent}}},tS=(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(!sh(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")},sS=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))},nS=t=>{const e=gt.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?sh(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let u;e:{if(!d?.valid||!c.trim()){let M;e[2]===Symbol.for("react.memo_cache_sentinel")?(M=[],e[2]=M):M=e[2],u=M;break e}let V;e[3]!==c||e[4]!==n.schedule.timezone?(V=Wj(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=V):V=e[5],u=V}const m=u;let f;e[6]!==n.schedule.timezone||e[7]!==o?(f=V=>new Intl.DateTimeFormat(o,{timeZone:n.schedule.timezone,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(V),e[6]=n.schedule.timezone,e[7]=o,e[8]=f):f=e[8];const g=f;let y;e[9]!==a?(y=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=y):y=e[10];let p;e[11]!==y?(p=s.jsx(Xn,{htmlFor:"sched-cron",required:!0,children:y}),e[11]=y,e[12]=p):p=e[12];let x;e[13]!==r?(x=V=>r(M=>({...M,schedule:{...M.schedule,cronExpression:V.target.value}})),e[13]=r,e[14]=x):x=e[14];let b;e[15]!==a?(b=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=b):b=e[16];let h;e[17]!==c||e[18]!==x||e[19]!==b?(h=s.jsx(vn,{id:"sched-cron",value:c,onChange:x,placeholder:b,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=x,e[19]=b,e[20]=h):h=e[20];let N;e[21]!==c||e[22]!==d||e[23]!==a?(N=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]=N):N=e[24];let w;e[25]!==p||e[26]!==h||e[27]!==N?(w=s.jsxs("div",{className:"flex flex-col gap-1",children:[p,h,N]}),e[25]=p,e[26]=h,e[27]=N,e[28]=w):w=e[28];let S;e[29]!==g||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(g).join(", ")})]}):null,e[29]=g,e[30]=m,e[31]=a,e[32]=S):S=e[32];let j;e[33]!==a?(j=a("sessions.scheduledTasks.editor.cronExpression.examples"),e[33]=a,e[34]=j):j=e[34];let k;e[35]!==j?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:j}),e[35]=j,e[36]=k):k=e[36];let v;e[37]!==r||e[38]!==a?(v=Uj.map(V=>s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 typography-micro text-foreground hover:bg-interactive-hover",onClick:()=>r(M=>({...M,schedule:{...M.schedule,cronExpression:V.expression}})),children:[s.jsx("span",{className:"font-mono",children:V.expression}),s.jsx("span",{className:"text-muted-foreground",children:a(V.labelKey)})]},V.expression)),e[37]=r,e[38]=a,e[39]=v):v=e[39];let D;e[40]!==v?(D=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:v}),e[40]=v,e[41]=D):D=e[41];let A;e[42]!==k||e[43]!==D?(A=s.jsxs("div",{className:"flex flex-col gap-1",children:[k,D]}),e[42]=k,e[43]=D,e[44]=A):A=e[44];let C;e[45]!==a?(C=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=C):C=e[46];let O;e[47]!==C?(O=s.jsx(Xn,{children:C}),e[47]=C,e[48]=O):O=e[48];let T;e[49]!==r?(T=V=>{r(M=>({...M,schedule:{...M.schedule,timezone:V}}))},e[49]=r,e[50]=T):T=e[50];let E;e[51]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),e[51]=E):E=e[51];let F;e[52]===Symbol.for("react.memo_cache_sentinel")?(F=s.jsx(Gn,{children:sc.map(lS)}),e[52]=F):F=e[52];let R;e[53]!==n.schedule.timezone||e[54]!==T?(R=s.jsxs(Un,{value:n.schedule.timezone,onValueChange:T,children:[E,F]}),e[53]=n.schedule.timezone,e[54]=T,e[55]=R):R=e[55];let L;e[56]!==O||e[57]!==R?(L=s.jsxs("div",{className:"flex flex-col gap-1",children:[O,R]}),e[56]=O,e[57]=R,e[58]=L):L=e[58];let B;return e[59]!==w||e[60]!==S||e[61]!==A||e[62]!==L?(B=s.jsxs("div",{className:"flex flex-col gap-3",children:[w,S,A,L]}),e[59]=w,e[60]=S,e[61]=A,e[62]=L,e[63]=B):B=e[63],B};function rS(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=kt(),l=ss(ne=>ne.loadProviders),d=ss(ne=>ne.loadAgents),u=ss(ne=>ne.providers),m=ss(ne=>ne.currentProviderId),f=ss(ne=>ne.currentModelId),g=ss(ne=>ne.currentVariant||""),y=ss(ne=>ne.currentAgentName||""),p=Ee(ne=>ne.timeFormatPreference),x=Ee(ne=>ne.weekStartPreference),b=Ee(ne=>ne.isMobile),[h,N]=tt.useState(()=>ef(n,{providerID:m,modelID:f,variant:g,agent:y})),[w,S]=tt.useState(!1),[j,k]=tt.useState(!1),[v,D]=tt.useState(!1),[A,C]=tt.useState(""),[O,T]=tt.useState(!1),[E,F]=tt.useState(""),[R,L]=tt.useState(!1),[B,V]=tt.useState(""),[M,Z]=tt.useState(()=>{const ne=ma(n?.schedule?.date||"")||new Date;return new Date(ne.getFullYear(),ne.getMonth(),1)}),se=tt.useRef(null),Q=tt.useRef(null),K=tt.useRef(null),ee=tt.useRef(null),re=tt.useRef(null),he=tt.useMemo(()=>Qj(c),[c]),je=tt.useMemo(()=>Yj(c),[c]),te=tt.useMemo(()=>p==="24h"?!0:p==="12h"?!1:he,[p,he]),Ne=tt.useMemo(()=>x==="sunday"?0:x==="monday"?1:je,[x,je]),J=tt.useMemo(()=>{const ne=Jj(c);return Xj(nh.map(P=>({value:P,label:ne[P]||""})),Ne)},[c,Ne]);tt.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),tt.useEffect(()=>{if(!e)return;N(ef(n,{providerID:m,modelID:f,variant:g,agent:y}));const ne=ma(n?.schedule?.date||"")||new Date;Z(new Date(ne.getFullYear(),ne.getMonth(),1)),k(!1),T(!1),D(!1),F(""),C("")},[e,n,m,f,g,y]),tt.useEffect(()=>{if(!j)return;const ne=P=>{se.current&&!se.current.contains(P.target)&&k(!1)};return document.addEventListener("mousedown",ne),()=>{document.removeEventListener("mousedown",ne)}},[j]);const H=tt.useMemo(()=>{const P=u.find(me=>me.id===h.execution.providerID)?.models?.find(me=>me.id===h.execution.modelID);return P?.variants?Object.keys(P.variants):[]},[u,h.execution.providerID,h.execution.modelID]),q=H.length>0,ae=tt.useMemo(()=>!q||!h.execution.variant?"__default":H.includes(h.execution.variant)?h.execution.variant:"__default",[h.execution.variant,q,H]);tt.useEffect(()=>{q||!h.execution.variant||N(ne=>({...ne,execution:{...ne.execution,variant:""}}))},[q,h.execution.variant]);const le=tt.useCallback((ne,P)=>{N(me=>{const oe=new Set(me.schedule.weekdays);return P?oe.add(ne):oe.delete(ne),{...me,schedule:{...me.schedule,weekdays:Array.from(oe).sort((Be,Ue)=>Be-Ue)}}})},[]),Se=tt.useCallback((ne,P)=>{N(me=>{const oe=me.schedule.times.slice();return oe[ne]=P,{...me,schedule:{...me.schedule,times:oe}}})},[]),Re=tt.useCallback(ne=>{N(P=>{const me=P.schedule.times.filter((oe,Be)=>Be!==ne);return{...P,schedule:{...P.schedule,times:me.length>0?me:["09:00"]}}})},[]),_e=tt.useCallback(()=>{N(ne=>({...ne,schedule:{...ne.schedule,times:[...ne.schedule.times,"12:00"]}}))},[]),Oe=tt.useMemo(()=>Zj(),[]),Me=tt.useMemo(()=>Xu(Oe),[Oe]),ge=tt.useMemo(()=>{const ne=ma(h.schedule.onceDate);return ne?Zu(ne,Oe)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(ne):null},[h.schedule.onceDate,c,a,Oe]),Ae=tt.useMemo(()=>Xu(M).getTime()<=Me.getTime(),[M,Me]),pe=tt.useMemo(()=>J.map(ne=>ne.label),[J]),ue=tt.useCallback(ne=>{N(P=>({...P,schedule:{...P.schedule,onceDate:ne}}))},[]),G=tt.useCallback((ne,P)=>{if(ne.startsWith("/")){const Ue=ne.indexOf(" "),Ke=ne.indexOf(`
167
- `),Qe=Math.min(Ue===-1?ne.length:Ue,Ke===-1?ne.length:Ke);if(P<=Qe&&Ue===-1){F(ne.substring(1,Qe)),T(!0),D(!1),L(!1);return}}T(!1);const me=ne.substring(0,P),oe=me.lastIndexOf("#");if(oe!==-1){const Ue=oe>0?me[oe-1]:null,Ke=me.substring(oe+1);if((!Ue||/\s/.test(Ue))&&!Ke.includes(" ")&&!Ke.includes(`
168
- `)){V(Ke),L(!0),D(!1);return}}L(!1);const Be=me.lastIndexOf("@");if(Be!==-1){const Ue=Be>0?me[Be-1]:null,Ke=me.substring(Be+1);(!Ue||/\s/.test(Ue))&&!Ke.includes(" ")&&!Ke.includes(`
169
- `)?(C(Ke),D(!0)):D(!1);return}D(!1)},[]),fe=tt.useCallback(ne=>{N(P=>({...P,execution:{...P.execution,prompt:ne}}))},[]),ce=tt.useCallback(ne=>{const P=h.execution.prompt,oe=Q.current?.selectionStart??P.length,Ue=P.substring(0,oe).lastIndexOf("@"),Ke=ne.relativePath&&ne.relativePath.trim().length>0?ne.relativePath.trim():ne.path||ne.name,Qe=Ue!==-1?Ue:oe,rt=`${P.substring(0,Qe)}@${Ke} ${P.substring(oe)}`,pt=Qe+Ke.length+2;fe(rt),D(!1),C(""),requestAnimationFrame(()=>{const jt=Q.current;jt&&(jt.selectionStart=pt,jt.selectionEnd=pt,jt.focus()),G(rt,pt)})},[h.execution.prompt,fe,G]),W=tt.useCallback(ne=>{const P=h.execution.prompt,oe=Q.current?.selectionStart??P.length,Ue=P.substring(0,oe).lastIndexOf("@"),Ke=Ue!==-1?Ue:oe,Qe=`${P.substring(0,Ke)}@${ne} ${P.substring(oe)}`,rt=Ke+ne.length+2;fe(Qe),D(!1),C(""),requestAnimationFrame(()=>{const pt=Q.current;pt&&(pt.selectionStart=rt,pt.selectionEnd=rt,pt.focus()),G(Qe,rt)})},[h.execution.prompt,fe,G]),z=tt.useCallback(ne=>{const P=`/${ne.name} `;fe(P),T(!1),F(""),L(!1),requestAnimationFrame(()=>{const me=Q.current;me&&(me.focus(),me.selectionStart=me.value.length,me.selectionEnd=me.value.length),G(P,P.length)})},[fe,G]),be=tt.useCallback((ne,P)=>{const me=h.execution.prompt,Be=Q.current?.selectionStart??me.length,Ke=me.substring(0,Be).lastIndexOf("#"),Qe=Ke!==-1?Ke:Be,rt=`${me.substring(0,Qe)}#${P} ${me.substring(Be)}`,pt=Qe+P.length+2;fe(rt),L(!1),V(""),requestAnimationFrame(()=>{const jt=Q.current;jt&&(jt.selectionStart=pt,jt.selectionEnd=pt,jt.focus()),G(rt,pt)})},[h.execution.prompt,fe,G]),xe=tt.useCallback(ne=>{if(O&&ee.current&&(ne.key==="Enter"||ne.key==="ArrowUp"||ne.key==="ArrowDown"||ne.key==="Escape"||ne.key==="Tab")){ne.preventDefault(),ee.current.handleKeyDown(ne.key);return}v&&K.current&&(ne.key==="Enter"||ne.key==="ArrowUp"||ne.key==="ArrowDown"||ne.key==="Escape"||ne.key==="Tab")&&(ne.preventDefault(),K.current.handleKeyDown(ne.key)),R&&re.current&&(ne.key==="Enter"||ne.key==="ArrowUp"||ne.key==="ArrowDown"||ne.key==="Escape"||ne.key==="Tab")&&(ne.preventDefault(),re.current.handleKeyDown(ne.key))},[O,v,R]),_=tt.useCallback(async()=>{const ne=tS(h,a);if(ne){de.error(ne);return}const P={...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:sS(h.schedule.times),...h.schedule.kind==="weekly"?{weekdays:h.schedule.weekdays}:{}}},execution:{prompt:h.execution.prompt,providerID:h.execution.providerID,modelID:h.execution.modelID,...h.execution.variant.trim()?{variant:h.execution.variant.trim()}:{},...h.execution.agent.trim()?{agent:h.execution.agent.trim()}:{}},...h.state?{state:h.state}:{}};S(!0);try{await o(P),r(!1)}catch(me){de.error(me instanceof Error?me.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{S(!1)}},[h,r,o,a]),ye=tt.useId(),$=tt.useCallback(()=>typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"], [data-slot="select-content"]'),[]),Ie=a(n?"sessions.scheduledTasks.editor.title.edit":"sessions.scheduledTasks.editor.title.new"),ve=a("sessions.scheduledTasks.editor.description"),Fe=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(Xn,{htmlFor:"sched-name",required:!0,children:a("sessions.scheduledTasks.editor.taskName.label")}),s.jsx(vn,{id:"sched-name",value:h.name,onChange:ne=>N(P=>({...P,name:ne.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(Xn,{children:a("sessions.scheduledTasks.editor.scheduleType.label")}),s.jsxs(Un,{value:h.schedule.kind,onValueChange:ne=>{N(P=>({...P,schedule:{...P.schedule,kind:ne,...ne==="cron"&&!P.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{children:ne=>a(ne==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":ne==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":ne==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(Gn,{children:[s.jsx(Ts,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(Ts,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(Ts,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(Ts,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),h.schedule.kind==="cron"?s.jsx(nS,{draft:h,setDraft:N,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:se,children:[s.jsx(Xn,{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(ne=>!ne),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(I,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Hj(h.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"})]}),j?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:()=>Z(ne=>qu(ne,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Ae,children:s.jsx(I,{name:"arrow-left-s",className:"h-4 w-4"})}),s.jsx("div",{className:"typography-ui-label text-foreground",children:new Intl.DateTimeFormat(c,{month:"long",year:"numeric"}).format(M)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>Z(ne=>qu(ne,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4"})})]}),s.jsx("div",{className:"mb-1 grid grid-cols-7 gap-1 px-1",children:pe.map((ne,P)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:ne},`${ne}-${P}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:Gj(M,Ne).map(({date:ne,inCurrentMonth:P})=>{const me=Ku(ne),oe=me===h.schedule.onceDate,Be=Zu(ne,Oe),Ue=ne.getTime()<Oe.getTime(),Ke=oe?"bg-interactive-selection text-interactive-selection-foreground":Ue?"text-muted-foreground/40":P?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{Ue||(ue(me),k(!1))},disabled:Ue,className:["h-8 rounded-md typography-ui-label",Ke,Be&&!oe?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",Ue?"cursor-not-allowed opacity-45":""].join(" "),children:ne.getDate()},me)})}),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:ge||""}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:()=>{ue(Ku(Oe)),Z(new Date(Oe.getFullYear(),Oe.getMonth(),1))},children:a("sessions.scheduledTasks.editor.date.jumpToToday")})]})]}):null]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Xn,{children:a("sessions.scheduledTasks.editor.time.label")}),s.jsx(Ju,{value:h.schedule.onceTime,use24Hour:te,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:ne=>N(P=>({...P,schedule:{...P.schedule,onceTime:ne}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(Xn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Un,{value:h.schedule.timezone,onValueChange:ne=>{N(P=>({...P,schedule:{...P.schedule,timezone:ne}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),s.jsx(Gn,{children:sc.map(ne=>s.jsx(Ts,{value:ne,children:ne},ne))})]})]})]})]}):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(Xn,{children:a("sessions.scheduledTasks.editor.weekdays.label")}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-2",children:J.map(ne=>{const P=h.schedule.weekdays.includes(ne.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",P?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(Ri,{checked:P,onChange:me=>le(ne.value,me),ariaLabel:ne.label}),s.jsx("button",{type:"button",onClick:()=>le(ne.value,!P),className:"group-hover:text-foreground",children:ne.label})]},ne.value)})})]}):null,s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Xn,{children:a("sessions.scheduledTasks.editor.times.label")}),s.jsx("div",{className:"flex flex-col gap-2",children:h.schedule.times.map((ne,P)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ju,{value:ne,use24Hour:te,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:me=>Se(P,me)}),h.schedule.times.length>1?s.jsx($e,{type:"button",size:"icon",variant:"ghost",onClick:()=>Re(P),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null]},P))}),s.jsx("div",{children:s.jsxs($e,{type:"button",size:"sm",variant:"outline",onClick:_e,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",a("sessions.scheduledTasks.editor.times.add")]})})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Xn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Un,{value:h.schedule.timezone,onValueChange:ne=>{N(P=>({...P,schedule:{...P.schedule,timezone:ne}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{})}),s.jsx(Gn,{children:sc.map(ne=>s.jsx(Ts,{value:ne,children:ne},ne))})]})]})]}),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(Xn,{required:!0,children:a("sessions.scheduledTasks.editor.model.label")}),s.jsx($f,{providerId:h.execution.providerID,modelId:h.execution.modelID,onChange:(ne,P)=>{N(me=>({...me,execution:{...me.execution,providerID:ne,modelID:P,variant:""}}))}})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Xn,{children:a("sessions.scheduledTasks.editor.thinkingLevel.label")}),s.jsxs(Un,{value:ae,disabled:!q,onValueChange:ne=>{N(P=>({...P,execution:{...P.execution,variant:ne==="__default"?"":ne}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(Cn,{children:ne=>ne==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):ne})}),s.jsxs(Gn,{children:[s.jsx(Ts,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),H.map(ne=>s.jsx(Ts,{value:ne,children:ne},ne))]})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Xn,{children:a("sessions.scheduledTasks.editor.agent.label")}),s.jsx(zf,{agentName:h.execution.agent,filter:ne=>gc(ne.mode),onChange:ne=>N(P=>({...P,execution:{...P.execution,agent:ne}}))})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Xn,{htmlFor:"sched-prompt",required:!0,children:a("sessions.scheduledTasks.editor.prompt.label")}),s.jsxs("div",{className:"relative",children:[s.jsx(Ci,{id:"sched-prompt",ref:Q,value:h.execution.prompt,onChange:ne=>{const P=ne.target.value;fe(P);const me=ne.target.selectionStart??P.length;G(P,me)},onKeyDown:xe,rows:8,placeholder:a("sessions.scheduledTasks.editor.prompt.placeholder"),className:"typography-meta min-h-[120px] max-h-[300px] resize-none overflow-y-auto"}),O?s.jsx(Xf,{ref:ee,searchQuery:E,onCommandSelect:z,onClose:()=>T(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,v?s.jsx(Zf,{ref:K,searchQuery:A,onFileSelect:ce,onAgentSelect:W,onClose:()=>D(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,R?s.jsx(em,{ref:re,searchQuery:B,onSnippetSelect:be,onClose:()=>L(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]})]}),Ce=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(Ri,{checked:h.enabled,onChange:ne=>N(P=>({...P,enabled:ne})),ariaLabel:a("sessions.scheduledTasks.editor.enabled.aria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.enabled.label")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(!1),disabled:w,children:a("sessions.scheduledTasks.editor.actions.cancel")}),s.jsx($e,{type:"button",size:"sm",onClick:_,disabled:w,children:a(w?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return b?s.jsx($a,{open:e,title:Ie,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:ne=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:Ie}),ne]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:ve})]}),footer:Ce,children:Fe}):s.jsx(Os,{open:e,onOpenChange:ne=>{!ne&&$()||r(ne)},children:s.jsxs(Ls,{"aria-describedby":ye,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(an,{id:ye,className:"sr-only",children:ve}),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(_s,{className:"typography-ui-label font-medium text-foreground",children:Ie}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:ve})]})}),s.jsx(za,{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:Fe})}),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:Ce})})]})})}function iS(t){return co(t,{min:0,max:23})}function oS(t,e){return co(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function aS(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 lS(t){return s.jsx(Ts,{value:t,children:t},t)}const cS=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))},dS=(t,e)=>{const n=cS(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||""})},uS=(t,e)=>!t||!Number.isFinite(t)?"":Rf(t,e),tf=(t,e)=>{if(!t||!Number.isFinite(t))return"";const n=t-Date.now(),r=Math.abs(n),o=6e4,a=60*o,c=24*a,l=n>=0;if(r<o)return e(l?"sessions.scheduledTasks.dialog.relativeTime.inLessThanOneMinute":"sessions.scheduledTasks.dialog.relativeTime.justNow");if(r<a){const f=Math.round(r/o);return l?e("sessions.scheduledTasks.dialog.relativeTime.inMinutes",{count:f}):e("sessions.scheduledTasks.dialog.relativeTime.minutesAgo",{count:f})}if(r<c){const f=Math.floor(r/a),g=Math.round(r%a/o),y=g>0?`${f}h ${g}m`:`${f}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:y}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:y})}const d=Math.floor(r/c),u=Math.round(r%c/a),m=u>0?`${d}d ${u}h`:`${d}d`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:m}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:m})},fS={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"}},mS=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function hS(){const{t}=kt(),e=Ee(R=>R.isScheduledTasksDialogOpen),n=Ee(R=>R.setScheduledTasksDialogOpen),r=Ee(R=>R.isMobile),o=Ee(R=>R.timeFormatPreference),a=ws(R=>R.projects),c=ws(R=>R.getActiveProject()),l=Qs(R=>R.homeDirectory),{currentTheme:d}=Gr(),[u,m]=tt.useState(""),[f,g]=tt.useState([]),[y,p]=tt.useState(!0),[x,b]=tt.useState(!1),[h,N]=tt.useState(null),[w,S]=tt.useState(null),j=tt.useMemo(()=>a.find(R=>R.id===u)||null,[a,u]),k=tt.useCallback(R=>{const L=R.label?.trim()||Ei(R.path,l||void 0),B=R.icon?kc[R.icon]:null,V=R.color?Ga[R.color]:void 0,M=B?s.jsx(I,{name:B,className:"h-3.5 w-3.5 shrink-0",style:V?{color:V}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:V?{color:V}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[R.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:R.iconBackground?{backgroundColor:R.iconBackground}:void 0,children:s.jsx(Ka,{project:{id:R.id,iconImage:R.iconImage??null},options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:M})}):M,s.jsx("span",{className:"truncate",children:L})]})},[l,d.metadata.variant,d.colors.surface.foreground]),v=tt.useCallback(async(R,L)=>{if(!R){g([]);return}L?.silent||p(!0);try{const B=await _j(R);B.sort((V,M)=>{if(V.enabled!==M.enabled)return V.enabled?-1:1;const Z=V.name.localeCompare(M.name);return Z!==0?Z:(V.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(M.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),g(B)}catch(B){de.error(B instanceof Error?B.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),L?.silent||g([])}finally{L?.silent||p(!1)}},[t]);tt.useEffect(()=>{if(!e)return;const R=c?.id||a[0]?.id||"";m(R),R?v(R):(g([]),p(!1))},[e,c,a,v]),tt.useEffect(()=>{if(!e)return;let R=null;const L=th(B=>{B.type==="scheduled-task-ran"&&B.projectId===u&&(R&&clearTimeout(R),R=setTimeout(()=>{v(u,{silent:!0})},400))});return()=>{R&&clearTimeout(R),L()}},[e,u,v]);const D=tt.useCallback(async R=>{if(!u)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await Hu(u,R),await v(u),de.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[u,v,t]),A=tt.useCallback(async(R,L)=>{if(u){S(R.id),g(B=>B.map(V=>V.id===R.id?{...V,enabled:L}:V));try{await Hu(u,{...R,enabled:L}),await v(u,{silent:!0})}catch(B){de.error(B instanceof Error?B.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await v(u,{silent:!0})}finally{S(null)}}},[u,v,t]),C=tt.useCallback(async R=>{if(!(!u||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:R.name})))){S(R.id);try{await $j(u,R.id),await v(u,{silent:!0}),de.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(B){de.error(B instanceof Error?B.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{S(null)}}},[u,v,t]),O=tt.useCallback(async R=>{if(u){S(R.id);try{await zj(u,R.id),await Promise.all([v(u,{silent:!0}),Sa()]),de.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch(L){de.error(L instanceof Error?L.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{S(null)}}},[u,v,t]),T=s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("sessions.scheduledTasks.dialog.project.label")}),s.jsxs(Un,{value:u||"__none",onValueChange:R=>{const L=R==="__none"?"":R;m(L),L?v(L):g([])},children:[s.jsx(Hn,{className:r?"w-full":void 0,children:j?s.jsx(Cn,{children:k(j)}):s.jsx(Cn,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(Gn,{children:[a.length===0?s.jsx(Ts,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(R=>s.jsx(Ts,{value:R.id,children:k(R)},R.id))]})]})]}),E=()=>{N(null),b(!0)},F=s.jsxs("div",{className:"space-y-4",children:[r?T:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[T,s.jsxs($e,{onClick:E,disabled:!u,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:y?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"})," ",t("sessions.scheduledTasks.dialog.loading")]}):f.length===0?s.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 typography-meta text-muted-foreground",children:t(u?"sessions.scheduledTasks.dialog.empty.noTasks":"sessions.scheduledTasks.dialog.empty.selectProject")}):s.jsx("div",{className:"space-y-2.5",children:f.map(R=>{const L=w===R.id,B=R.state?.lastStatus||"idle",V=fS[B],M=t(B==="success"?"sessions.scheduledTasks.dialog.status.success":B==="error"?"sessions.scheduledTasks.dialog.status.error":B==="running"?"sessions.scheduledTasks.dialog.status.running":"sessions.scheduledTasks.dialog.status.idle"),Z=R.state?.nextRunAt,se=R.state?.lastRunAt;return s.jsxs("div",{className:De("rounded-lg border border-border p-4 transition-opacity",!R.enabled&&"opacity-60"),children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-header truncate font-semibold text-foreground",children:R.name}),s.jsx("div",{className:"typography-micro truncate text-muted-foreground",children:dS(R,t)})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-5 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.nextRun.label")}),Z?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-foreground",children:tf(Z,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:uS(Z,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(I,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),B==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(I,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):se?s.jsxs(s.Fragment,{children:[V.tone!=="muted"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:`var(--status-${V.tone})`},children:[s.jsx(I,{name:V.Icon,className:"h-3.5 w-3.5"}),M]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:tf(se,t)})]}):s.jsx("span",{children:t("sessions.scheduledTasks.dialog.lastRun.never")})]})]}),R.state?.lastError?s.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-md border p-2 typography-micro",style:mS("error"),children:[s.jsx(I,{name:"error-warning",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"min-w-0 break-words",children:R.state.lastError})]}):null,s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("label",{className:De("inline-flex cursor-pointer items-center gap-2 typography-micro font-medium",R.enabled?"text-foreground":"text-muted-foreground",L&&"cursor-not-allowed opacity-50"),children:[s.jsx(Ri,{checked:R.enabled,onChange:Q=>{A(R,Q)},ariaLabel:R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:R.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:R.name}),disabled:L}),R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.enabled"):t("sessions.scheduledTasks.dialog.taskToggle.paused")]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{O(R)},disabled:L,children:[s.jsx(I,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{N(R),b(!0)},disabled:L,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:R.name}),children:[s.jsx(I,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx($e,{variant:"destructive",size:"sm",onClick:()=>{C(R)},disabled:L,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:R.name}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})]})]})]},R.id)})})})]});return s.jsxs(s.Fragment,{children:[r?s.jsx($a,{open:e,title:t("sessions.scheduledTasks.dialog.title"),onClose:()=>n(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:R=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:t("sessions.scheduledTasks.dialog.title")}),R]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:t("sessions.scheduledTasks.dialog.description")})]}),footer:s.jsxs($e,{className:"w-full",onClick:E,disabled:!u,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:F}):s.jsx(Os,{open:e,onOpenChange:n,children:s.jsxs(Ls,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(Us,{children:[s.jsx(_s,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(an,{children:t("sessions.scheduledTasks.dialog.description")})]}),F]})}),s.jsx(rS,{open:x,task:h,onOpenChange:b,onSave:D})]})}const pS=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>as(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(d=>Ro(d,t.normalizedPath,r)))(e.archivedSessions),c=e.sessions.filter(l=>l.time?.archived||as(l.directory??null)?!1:Ro(l,t.normalizedPath,r));return no([...a,...c])},gS=t=>{const e=gt.c(12),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,isSessionsLoading:l,foldersMap:d,createFolder:u,addSessionToFolder:m,cleanupSessions:f}=t;let g,y;e[0]!==m||e[1]!==o||e[2]!==a||e[3]!==f||e[4]!==u||e[5]!==d||e[6]!==l||e[7]!==c||e[8]!==n||e[9]!==r?(g=()=>{l||n.forEach(p=>{const x=Tc(p.normalizedPath),b=pS(p,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c}),h=new Set(b.map(xS)),N=d[x]??[],w=new Map(N.map(bS));b.forEach(S=>{const j=Jx(S,p.normalizedPath),k=j.toLowerCase();let v=w.get(k);v||(v=u(x,j),w.set(k,v)),v.sessionIds.includes(S.id)||m(x,v.id,S.id)}),f(x,h)})},y=[n,r,o,a,c,l,d,u,m,f],e[0]=m,e[1]=o,e[2]=a,e[3]=f,e[4]=u,e[5]=d,e[6]=l,e[7]=c,e[8]=n,e[9]=r,e[10]=g,e[11]=y):(g=e[10],y=e[11]),i.useEffect(g,y)};function xS(t){return t.id}function bS(t){return[t.name.toLowerCase(),t]}const yS=t=>{const e=gt.c(41),{normalizedProjects:n,getSessionsForProject:r,getArchivedSessionsForProject:o,availableWorktreesByProject:a,projectRepoStatus:c,projectRootBranches:l,lastRepoStatus:d,buildGroupedSessions:u,hasSessionSearchQuery:m,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:g,buildGroupSearchText:y,foldersMap:p}=t;let x;if(e[0]!==a||e[1]!==u||e[2]!==o||e[3]!==r||e[4]!==d||e[5]!==n||e[6]!==c||e[7]!==l){let C;e[9]!==a||e[10]!==u||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(C=O=>{const T=no([...r(O),...o(O)]),E=a.get(O.normalizedPath)??[],F=c.has(O.id)?!!c.get(O.id):d,R=u(T,O.normalizedPath,E,l.get(O.id)??null,F);return{project:O,groups:R}},e[9]=a,e[10]=u,e[11]=o,e[12]=r,e[13]=d,e[14]=c,e[15]=l,e[16]=C):C=e[16],x=n.map(C),e[0]=a,e[1]=u,e[2]=o,e[3]=r,e[4]=d,e[5]=n,e[6]=c,e[7]=l,e[8]=x}else x=e[8];const b=x,h=b;let N;if(e[17]!==y||e[18]!==g||e[19]!==p||e[20]!==m||e[21]!==f||e[22]!==h){e:{const C=new WeakMap;if(!m){N=C;break e}const O=T=>T.reduce((E,F)=>E+1+O(F.children),0);h.forEach(T=>{T.groups.forEach(E=>{const F=g(E.sessions,f),R=O(F),L=y(E).includes(f),B=as(E.directory??null),M=(B?p[B]??[]:[]).filter(Z=>Z.name.toLowerCase().includes(f)).length;C.set(E,{filteredNodes:F,matchedSessionCount:R,folderNameMatchCount:M,groupMatches:L,hasMatch:L||R>0||M>0})})}),N=C}e[17]=y,e[18]=g,e[19]=p,e[20]=m,e[21]=f,e[22]=h,e[23]=N}else N=e[23];const w=N;let S;e:{if(!m){S=h;break e}let C;if(e[24]!==w||e[25]!==h){let O;e[27]!==w?(O=T=>({...T,groups:T.groups.filter(E=>w.get(E)?.hasMatch===!0)}),e[27]=w,e[28]=O):O=e[28],C=h.map(O).filter(wS),e[24]=w,e[25]=h,e[26]=C}else C=e[26];S=C}const j=S,k=m?j:h;let v;e:{if(!m){v=0;break e}let C;if(e[29]!==w||e[30]!==k){let O;e[32]!==w?(O=(T,E)=>T+E.groups.reduce((F,R)=>{const L=w.get(R);if(!L)return F;const B=L.folderNameMatchCount+(L.groupMatches?1:0);return F+L.matchedSessionCount+B},0),e[32]=w,e[33]=O):O=e[33],C=k.reduce(O,0),e[29]=w,e[30]=k,e[31]=C}else C=e[31];v=C}const D=v;let A;return e[34]!==w||e[35]!==b||e[36]!==D||e[37]!==j||e[38]!==k||e[39]!==h?(A={projectSections:b,visibleProjectSections:h,groupSearchDataByGroup:w,searchableProjectSections:j,sectionsForRender:k,searchMatchCount:D},e[34]=w,e[35]=b,e[36]=D,e[37]=j,e[38]=k,e[39]=h,e[40]=A):A=e[40],A};function wS(t){return t.groups.length>0}const vS=t=>{const e=gt.c(26),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:c,handleSessionSelect:l,newSessionDraftOpen:d,mobileVariant:u,openNewSessionDraft:m,setActiveMainTab:f,setSessionSwitcherOpen:g}=t;let y,p;if(e[0]!==n){p=new Map,y=new Map;const k=(v,D,A,C)=>{p.has(v)||p.set(v,new Map);const O=p.get(v);C.forEach(T=>{const E=as(T.worktree?.path??T.session.directory??A??D);O.set(T.session.id,{directory:E}),y.has(v)||y.set(v,{id:T.session.id,directory:E}),T.children.length>0&&k(v,D,E,T.children)})};n.forEach(v=>{v.groups.forEach(D=>{k(v.project.id,v.project.normalizedPath,D.directory,D.sessions)})}),e[0]=n,e[1]=y,e[2]=p}else y=e[1],p=e[2];let x;e[3]!==y||e[4]!==p?(x={metaByProject:p,firstSessionByProject:y},e[3]=y,e[4]=p,e[5]=x):x=e[5];const b=x,h=i.useRef(null);let N,w;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==u||e[11]!==d||e[12]!==m||e[13]!==n||e[14]!==b||e[15]!==f||e[16]!==a||e[17]!==g?(N=()=>{if(!r||d||Ee.getState().isNewWorktreeDialogOpen||h.current===r)return;const k=n.find(E=>E.project.id===r);if(!k)return;h.current=r;const v=b.metaByProject.get(r);if(c&&v&&v.has(c)){a(E=>{if(E.get(r)===c)return E;const F=new Map(E);return F.set(r,c),F});return}if(!v||v.size===0){f("chat"),u&&g(!1),m({directoryOverride:k.project.normalizedPath});return}const D=o.get(r),A=D&&v.has(D)?D:null,C=b.firstSessionByProject.get(r)?.id??null,O=A??C;if(!O||O===c)return;const T=v.get(O)?.directory??null;l(O,T,r)},w=[r,o,c,l,d,u,m,n,b,f,g,a],e[6]=r,e[7]=o,e[8]=c,e[9]=l,e[10]=u,e[11]=d,e[12]=m,e[13]=n,e[14]=b,e[15]=f,e[16]=a,e[17]=g,e[18]=N,e[19]=w):(N=e[18],w=e[19]),i.useLayoutEffect(N,w);let S,j;e[20]!==r||e[21]!==c||e[22]!==b||e[23]!==a?(S=()=>{if(!r||!c)return;const k=b.metaByProject.get(r);!k||!k.has(c)||a(v=>{if(v.get(r)===c)return v;const D=new Map(v);return D.set(r,c),D})},j=[r,c,b,a],e[20]=r,e[21]=c,e[22]=b,e[23]=a,e[24]=S,e[25]=j):(S=e[24],j=e[25]),i.useEffect(S,j)},jS=t=>{const e=gt.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(SS)),u=[];return l.forEach(m=>{const f=d.get(m);f&&(u.push(f),d.delete(m))}),c.forEach(m=>{d.has(m.id)&&u.push(m)}),u},e[0]=t,e[1]=n):n=e[1];const r=n;let o;return e[2]!==r?(o={getOrderedGroups:r},e[2]=r,e[3]=o):o=e[3],o};function SS(t){return[t.id,t]}const ea=t=>!!t.time?.archived,NS=t=>{const{t:e}=kt(),n=i.useCallback(c=>[c.label,c.branch??"",c.description??"",c.directory??""].join(" ").toLowerCase(),[]),r=i.useCallback(c=>{const l=as(c.directory??null)??"";return`${(c.title||e("sessions.sidebar.session.untitled")).trim()} ${l}`.toLowerCase()},[e]),o=i.useCallback((c,l)=>l?c.flatMap(d=>{if(r(d.session).includes(l))return[d];const m=o(d.children,l);return m.length===0?[]:[{...d,children:m}]}):c,[r]),a=i.useCallback((c,l,d,u,m)=>{const f=as(l??null),g=no(c).sort((T,E)=>Ki(T,E,t.pinnedSessionIds)),y=new Map(g.map(T=>[T.id,T])),p=new Map;g.forEach(T=>{const E=T.parentID;if(!E)return;const F=y.get(E);if(!F||ea(F)!==ea(T))return;const R=p.get(E)??[];R.push(T),p.set(E,R)}),p.forEach(T=>T.sort((E,F)=>Ki(E,F,t.pinnedSessionIds)));const x=new Map;d.forEach(T=>{if(T.path){const E=as(T.path)??T.path;x.set(E,T)}});const b=T=>{const E=as(T.directory??null),F=t.worktreeMetadata.get(T.id)??null;if(F)return F;if(E){const R=x.get(E)??null;if(R&&E!==f)return R}return null},h=T=>{const E=p.get(T.id)??[];return{session:T,children:E.map(F=>h(F)),worktree:b(T)}},N=g.filter(T=>{const E=T.parentID;if(!E)return!0;const F=y.get(E);return F?ea(F)!==ea(T):!0}),w=new Map,S="__archived__",j=T=>{if(T.time?.archived)return S;if(t.isVSCode)return f??"__project_root__";const F=as(t.worktreeMetadata.get(T.id)?.path??null)??Tr(T);return F?F!==f&&x.has(F)?F:F===f?f??"__project_root__":S:S};N.forEach(T=>{const E=h(T),F=j(T);w.has(F)||w.set(F,[]),w.get(F)?.push(E)});const k=f??"__project_root__",v=[{id:"root",label:m&&u&&u!=="HEAD"?e("sessions.sidebar.grouping.projectRootWithBranch",{branch:u}):e("sessions.sidebar.grouping.projectRoot"),branch:u??null,description:f?Na(f,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:w.get(k)??[]}],D=new Map;d.forEach(T=>{const E=as(T.path)??T.path,F=w.get(E)??[],R=F.length>0,L=F.reduce((B,V)=>{const M=Number(V.session.time?.updated??V.session.time?.created??0);return Number.isFinite(M)?Math.max(B,M):B},0);D.set(E,{hasActiveSession:R,lastUpdatedAt:L})});const A=[...d].sort((T,E)=>{const F=as(T.path)??T.path,R=as(E.path)??E.path,L=D.get(F)??{hasActiveSession:!1,lastUpdatedAt:0},B=D.get(R)??{hasActiveSession:!1,lastUpdatedAt:0};if(L.hasActiveSession!==B.hasActiveSession)return L.hasActiveSession?-1:1;if(L.hasActiveSession&&B.hasActiveSession)return B.lastUpdatedAt-L.lastUpdatedAt;const V=(T.label||T.branch||T.name||T.path||"").toLowerCase(),M=(E.label||E.branch||E.name||E.path||"").toLowerCase();return V.localeCompare(M)});(t.isVSCode?[]:A).forEach(T=>{const E=as(T.path)??T.path,F=t.gitBranches.get(E)?.trim()||null,R=T.branch?.trim()||null,B=!!(F&&R&&T.label&&zd(T.label)===zd(R))?F:T.label||T.name||Ei(E,t.homeDirectory)||E;v.push({id:`worktree:${E}`,label:B,branch:F||R,description:Na(E,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:T,directory:E,folderScopeKey:E,sessions:w.get(E)??[]})});const O=w.get(S)??[];return O.length>0&&v.push({id:"archived",label:e("sessions.sidebar.grouping.archived"),branch:null,description:e("sessions.sidebar.grouping.archivedDescription"),isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:!t.isVSCode&&f?Tc(f):null,sessions:O}),v},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitBranches,t.isVSCode,e]);return{buildGroupSearchText:n,buildSessionSearchText:r,filterSessionNodesForSearch:o,buildGroupedSessions:a}},kS=t=>{const e=gt.c(9),{isSessionSearchOpen:n,setIsSessionSearchOpen:r,sessionSearchInputRef:o,sessionSearchContainerRef:a}=t;let c,l;e[0]!==n||e[1]!==o?(c=()=>{if(!n||typeof window>"u")return;const m=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(m)},l=[n,o],e[0]=n,e[1]=o,e[2]=c,e[3]=l):(c=e[2],l=e[3]),i.useEffect(c,l);let d,u;e[4]!==n||e[5]!==a||e[6]!==r?(d=()=>{if(!n||typeof document>"u")return;const m=f=>{a.current&&(a.current.contains(f.target)||r(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},u=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=d,e[8]=u):(d=e[7],u=e[8]),i.useEffect(d,u)},CS=t=>{const e=gt.c(42),{t:n}=kt(),[r,o]=i.useState(null),a=i.useRef(null);let c,l;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=()=>()=>{a.current&&clearTimeout(a.current)},l=[],e[0]=c,e[1]=l):(c=e[0],l=e[1]),i.useEffect(c,l);let d;e[2]!==t?(d=(L,B,V)=>{const M=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(V&&V!==t.activeProjectId&&t.setActiveProjectIdOnly(V),B&&B!==t.currentDirectory&&t.setDirectory(B,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),L===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(L),M();return}t.setCurrentSession(L,B??null),t.onSessionSelected?.(L),M()},e[2]=t,e[3]=d):d=e[3];const u=d;let m;e[4]!==t?(m=(L,B)=>{t.setEditingId(L),t.setEditTitle(B)},e[4]=t,e[5]=m):m=e[5];const f=m;let g;e[6]!==t?(g=async L=>{if(!t.editingId)return;const B=(L??t.editTitle).trim();B&&await t.updateSessionTitle(t.editingId,B),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=g):g=e[7];const y=g;let p;e[8]!==t?(p=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=p):p=e[9];const x=p;let b;e[10]!==t||e[11]!==n?(b=async L=>{const B=await t.shareSession(L.id);B&&B.share?.url?de.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):de.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=b):b=e[12];const h=b;let N;e[13]!==n?(N=(L,B)=>{pr(L).then(V=>{if(!V.ok){de.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(B),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{de.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=N):N=e[14];const w=N;let S;e[15]!==t||e[16]!==n?(S=async L=>{await t.unshareSession(L)?de.success(n("sessions.sidebar.session.unshare.success")):de.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=S):S=e[17];const j=S;let k;e[18]!==t.childrenMap?(k=L=>{const B=[],V=M=>{(t.childrenMap.get(M)??[]).forEach(se=>{B.push(se),V(se.id)})};return V(L),B},e[18]=t.childrenMap,e[19]=k):k=e[19];const v=k,D=DS;let A;e[20]!==t||e[21]!==v||e[22]!==n?(A=async(L,B,V)=>{const M=B?.archivedBucket===!0||B?.hardDelete===!0,Z=V?.descendantIds??D(v(L.id),M).map(IS);if(Z.length===0){(M?await t.deleteSession(L.id):await t.archiveSession(L.id))?de.success(n(M?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):de.error(n(M?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const se=[L.id,...Z];if(M){if(await t.deleteSession(L.id)){const re=Z.length+1;de.success(re===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:re}):n("sessions.sidebar.bulkActions.deletedPlural",{count:re}))}else de.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:Q,failedIds:K}=await t.archiveSessions(se);Q.length>0&&de.success(Q.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:Q.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:Q.length})),K.length>0&&de.error(K.length===1?n("sessions.sidebar.bulkActions.failedArchiveSingle",{count:K.length}):n("sessions.sidebar.bulkActions.failedArchivePlural",{count:K.length}))},e[20]=t,e[21]=v,e[22]=n,e[23]=A):A=e[23];const C=A;let O;e[24]!==t||e[25]!==v||e[26]!==C?(O=(L,B)=>{const V=B?.archivedBucket===!0||B?.hardDelete===!0,M=D(v(L.id),V).map(PS);if(!t.showDeletionDialog){C(L,B,{descendantIds:M});return}t.setDeleteSessionConfirm({session:L,descendantCount:M.length,descendantIds:M,archivedBucket:V})},e[24]=t,e[25]=v,e[26]=C,e[27]=O):O=e[27];const T=O;let E;e[28]!==t||e[29]!==C?(E=async()=>{if(!t.deleteSessionConfirm)return;const{session:L,archivedBucket:B,descendantIds:V}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await C(L,{archivedBucket:B},{descendantIds:V})},e[28]=t,e[29]=C,e[30]=E):E=e[30];const F=E;let R;return e[31]!==F||e[32]!==r||e[33]!==x||e[34]!==w||e[35]!==T||e[36]!==y||e[37]!==f||e[38]!==u||e[39]!==h||e[40]!==j?(R={copiedSessionId:r,handleSessionSelect:u,handleSessionDoubleClick:f,handleSaveEdit:y,handleCancelEdit:x,handleShareSession:h,handleCopyShareUrl:w,handleUnshareSession:j,handleDeleteSession:T,confirmDeleteSession:F},e[31]=F,e[32]=r,e[33]=x,e[34]=w,e[35]=T,e[36]=y,e[37]=f,e[38]=u,e[39]=h,e[40]=j,e[41]=R):R=e[41],R};function AS(t){return!t.time?.archived}function DS(t,e){return e?t:t.filter(AS)}function IS(t){return t.id}function PS(t){return t.id}const TS=["project:active:","project:archived:","recent:active:","recent:archived:"],RS=t=>{const{isVSCode:e,hasLoadedGlobalSessions:n,safeStorage:r,keys:o,sessions:a,setPinnedSessionIds:c,groupOrderByProject:l,activeSessionByProject:d,collapsedGroups:u,setExpandedParents:m,setCollapsedProjects:f}=t,g=i.useRef(null),y=i.useRef(null),p=i.useCallback(()=>{if(e)return;const b=y.current;if(y.current=null,g.current=null,!b)return;const{projects:h}=ws.getState(),N=h.map(w=>({...w,sidebarCollapsed:b.has(w.id)}));lc({projects:N}).catch(()=>{})},[e]),x=i.useCallback(b=>{typeof window>"u"||e||(y.current=b,g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{p()},700))},[e,p]);return i.useEffect(()=>()=>{typeof window<"u"&&g.current!==null&&window.clearTimeout(g.current),g.current=null,y.current=null},[]),i.useEffect(()=>{try{const b=r.getItem(o.sessionExpanded);if(b){const N=JSON.parse(b);Array.isArray(N)&&m(new Set(N.filter(w=>typeof w=="string")))}else{const N=r.getItem(o.sessionExpandedLegacy);if(N){try{const w=JSON.parse(N);if(Array.isArray(w)){const S=new Set;if(w.forEach(j=>{typeof j!="string"||j.length===0||TS.forEach(k=>S.add(`${k}${j}`))}),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 N=JSON.parse(h);Array.isArray(N)&&f(new Set(N.filter(w=>typeof w=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,f,m]),i.useEffect(()=>{if(!n||a.length===0)return;const b=new Set(a.map(h=>h.id));c(h=>{let N=!1;const w=new Set;return h.forEach(S=>{b.has(S)?w.add(S):N=!0}),N?w:h})},[n,a,c]),i.useEffect(()=>{try{const b=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(b))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const b=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(b))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(u)))}catch{}},[u,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:x}},ES=t=>{const{normalizedProjects:e,gitRepoStatus:n,setProjectRepoStatus:r,setProjectRootBranches:o}=t,{git:a}=er(),c=wn(f=>f.ensureStatus);i.useEffect(()=>{if(!a||e.length===0){r(new Map);return}e.forEach(f=>{c(f.normalizedPath,a)})},[e,a,c,r]),i.useEffect(()=>{const f=new Map;e.forEach(g=>{f.set(g.id,n.get(g.normalizedPath)?.isGitRepo??null)}),r(f)},[e,n,r]);const l=i.useMemo(()=>e.map(f=>{const g=n.get(f.normalizedPath)?.branch??"";return`${f.id}:${g}`}).join("|"),[e,n]),d=i.useRef(new Map),u=i.useRef(new Map),m=5*6e4;i.useEffect(()=>{let f=!1;const g=setTimeout(()=>{(async()=>{const p=new Set(e.map(S=>S.id));for(const S of d.current.keys())p.has(S)||(d.current.delete(S),u.current.delete(S));const x=Date.now(),b=e.filter(S=>{const j=n.get(S.normalizedPath);if(j?.isGitRepo===!1)return d.current.delete(S.id),u.current.delete(S.id),!1;if(j?.isGitRepo!==!0||j.branch===null)return!1;const k=j.branch.trim(),v=`${S.normalizedPath}\0${k}`,D=d.current.get(S.id);if(D===v){const A=u.current.get(S.id);return A&&(A.at=x),!1}return!(D!==void 0&&x-(u.current.get(S.id)?.at??0)<m)});if(b.length===0)return;const h=await Am(b,2,async S=>{const j=n.get(S.normalizedPath)?.branch?.trim()??"",k=`${S.normalizedPath}\0${j}`,v=await Ua(S.normalizedPath,j?{knownBranch:j}:void 0).catch(()=>null);return{id:S.id,inputKey:k,branch:v}});if(f)return;const N=h.filter(S=>S.branch);if(N.length===0)return;const w=Date.now();o(S=>{const j=new Map(S);return N.forEach(({id:k,branch:v})=>{v&&j.set(k,v)}),j}),N.forEach(({id:S,inputKey:j,branch:k})=>{d.current.set(S,j),k&&u.current.set(S,{branch:k,at:w})})})()},150);return()=>{f=!0,clearTimeout(g)}},[e,l,n,o])},MS=t=>{const e=gt.c(19),{isVSCode:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,normalizedProjects:c}=t;let l;if(e[0]!==a||e[1]!==n||e[2]!==c){if(l=new Set,c.forEach(b=>{b.normalizedPath&&l.add(b.normalizedPath)}),!n)for(const b of a.values())for(const h of b){const N=as(h.path);N&&l.add(N)}e[0]=a,e[1]=n,e[2]=c,e[3]=l}else l=e[3];const d=l;let u;e[4]!==d||e[5]!==r?(u=new Map,r.forEach(b=>{const h=Tr(b);if(!h||!d.has(h))return;const N=u.get(h)??[];N.push(b),u.set(h,N)}),e[4]=d,e[5]=r,e[6]=u):u=e[6];const m=u;let f;e[7]!==a||e[8]!==n||e[9]!==m?(f=b=>{const h=n?[]:a.get(b.normalizedPath)??[],N=[b.normalizedPath,...h.map(FS).filter(LS)],w=new Set,S=[];return N.forEach(j=>{(m.get(j)??[]).forEach(v=>{w.has(v.id)||(w.add(v.id),S.push(v))})}),S},e[7]=a,e[8]=n,e[9]=m,e[10]=f):f=e[10];const g=f;let y;e[11]!==o||e[12]!==a||e[13]!==n||e[14]!==r?(y=b=>{if(n){const k=o.filter(D=>{const A=as(D.directory??null),C=as(D.project?.worktree??null);return A?A===b.normalizedPath:C===b.normalizedPath}),v=r.filter(D=>D.time?.archived||as(D.directory??null)?!1:as(D.project?.worktree??null)===b.normalizedPath);return no([...k,...v])}const h=n?[]:a.get(b.normalizedPath)??[],N=new Set([b.normalizedPath,...h.map(OS).filter(BS)]),S=(k=>k.filter(v=>Ro(v,b.normalizedPath,N)))(o),j=r.filter(k=>{if(k.time?.archived||as(k.directory??null))return!1;const D=as(k.project?.worktree??null);return D?D===b.normalizedPath||D.startsWith(`${b.normalizedPath}/`):!1});return no([...S,...j])},e[11]=o,e[12]=a,e[13]=n,e[14]=r,e[15]=y):y=e[15];const p=y;let x;return e[16]!==p||e[17]!==g?(x={getSessionsForProject:g,getArchivedSessionsForProject:p},e[16]=p,e[17]=g,e[18]=x):x=e[18],x};function FS(t){return as(t.path)??t.path}function LS(t){return!!t}function OS(t){return as(t.path)??t.path}function BS(t){return!!t}const VS=t=>{const e=gt.c(10),{isSessionsLoading:n,hasLoadedGlobalSessions:r,sessions:o,archivedSessions:a,normalizedProjects:c,isVSCode:l,availableWorktreesByProject:d,cleanupSessions:u}=t;let m,f;e[0]!==a||e[1]!==d||e[2]!==u||e[3]!==r||e[4]!==n||e[5]!==l||e[6]!==c||e[7]!==o?(m=()=>{if(n||!r||o.length===0&&a.length===0)return;const g=new Map;o.forEach(x=>{const b=as(x.directory??null);if(!b)return;const h=g.get(b);if(h){h.add(x.id);return}g.set(b,new Set([x.id]))}),c.forEach(x=>{const b=Tc(x.normalizedPath),h=l?[]:d.get(x.normalizedPath)??[],N=new Set([x.normalizedPath,...h.map(_S).filter($S)]),w=no([...a,...o.filter(S=>S.time?.archived||as(S.directory??null)?!1:Ro(S,x.normalizedPath,N))]).filter(S=>Ro(S,x.normalizedPath,N));g.set(b,new Set(w.map(zS)))});const y=Vn.getState().foldersMap;new Set([...Object.keys(y),...g.keys()]).forEach(x=>{u(x,g.get(x)??new Set)})},f=[a,d,u,r,n,l,c,o],e[0]=a,e[1]=d,e[2]=u,e[3]=r,e[4]=n,e[5]=l,e[6]=c,e[7]=o,e[8]=m,e[9]=f):(m=e[8],f=e[9]),i.useEffect(m,f)};function _S(t){return as(t.path)??t.path}function $S(t){return!!t}function zS(t){return t.id}const WS=t=>{const e=gt.c(8),{isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=t;let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=new Set,e[0]=a):a=e[0];const[c,l]=i.useState(a);let d;e[1]!==n||e[2]!==o?(d=()=>{if(!n)return;const m=new IntersectionObserver(f=>{f.forEach(g=>{const y=g.target.dataset.projectId;y&&l(p=>{const x=new Set(p);return g.isIntersecting?x.delete(y):x.add(y),x})})},{threshold:0});return o.current.forEach(f=>{f&&m.observe(f)}),()=>m.disconnect()},e[1]=n,e[2]=o,e[3]=d):d=e[3];let u;return e[4]!==n||e[5]!==o||e[6]!==r?(u=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=u):u=e[7],i.useEffect(d,u),c},US=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Dl=t=>{if(!t)return null;const e=t.trim();return e&&US.test(e)?e.toLowerCase():null},HS=t=>{const e=gt.c(198),{open:n,onOpenChange:r,projectId:o,projectName:a,projectPath:c,initialIcon:l,initialColor:d,initialIconBackground:u,onSave:m}=t,f=l===void 0?null:l,g=d===void 0?null:d,y=u===void 0?null:u,{t:p}=kt(),x=ws(GS),b=ws(KS),h=ws(qS);let N;e[0]!==o?(N=Ye=>Ye.projects.find(Pt=>Pt.id===o)?.iconImage??null,e[0]=o,e[1]=N):N=e[1];const w=ws(N),{currentTheme:S}=Gr(),[j,k]=i.useState(a),[v,D]=i.useState(f),[A,C]=i.useState(g);let O;e[2]!==y?(O=Dl(y),e[2]=y,e[3]=O):O=e[3];const[T,E]=i.useState(O),[F,R]=i.useState(!1),[L,B]=i.useState(!1),[V,M]=i.useState(!1),[Z,se]=i.useState(!1),[Q,K]=i.useState(null),[ee,re]=i.useState(null),[he,je]=i.useState(!1),te=i.useRef(null);let Ne;e[4]===Symbol.for("react.memo_cache_sentinel")?(Ne=()=>{K(null),re(YS)},e[4]=Ne):Ne=e[4];const J=Ne;let H,q;e[5]!==g||e[6]!==f||e[7]!==y||e[8]!==n||e[9]!==a?(H=()=>{n&&(k(a),D(f),C(g),E(Dl(y)),se(!1),J(),je(!1))},q=[n,a,f,g,y,J],e[5]=g,e[6]=f,e[7]=y,e[8]=n,e[9]=a,e[10]=H,e[11]=q):(H=e[10],q=e[11]),i.useEffect(H,q);let ae,le;e[12]===Symbol.for("react.memo_cache_sentinel")?(le=()=>()=>{J()},ae=[J],e[12]=ae,e[13]=le):(ae=e[12],le=e[13]),i.useEffect(le,ae);let Se,Re,_e;if(e[14]!==A||e[15]!==w||e[16]!==v||e[17]!==T||e[18]!==j||e[19]!==r||e[20]!==m||e[21]!==Z||e[22]!==Q||e[23]!==o||e[24]!==b||e[25]!==p||e[26]!==x){let Ye;e[30]!==A||e[31]!==v||e[32]!==T||e[33]!==j||e[34]!==r||e[35]!==m||e[36]!==Z||e[37]!==Q||e[38]!==o||e[39]!==b||e[40]!==p||e[41]!==x?(Ye=async()=>{const Pt=j.trim();if(!Pt)return;if(Q){R(!0);const Qt=await x(o,Q);if(R(!1),!Qt.ok){de.error(Qt.error||p("projectEditDialog.toast.failedToUploadIcon"));return}de.success(p("projectEditDialog.toast.iconUpdated")),J(),se(!1)}const Tt=Z&&_e;if(Tt){B(!0);const Qt=await b(o);if(B(!1),!Qt.ok){de.error(Qt.error||p("projectEditDialog.toast.failedToRemoveIcon"));return}de.success(p("projectEditDialog.toast.iconRemoved")),se(!1),E(null)}m({label:Pt,icon:v,color:A,iconBackground:Dl(Tt?null:T)}),r(!1)},e[30]=A,e[31]=v,e[32]=T,e[33]=j,e[34]=r,e[35]=m,e[36]=Z,e[37]=Q,e[38]=o,e[39]=b,e[40]=p,e[41]=x,e[42]=Ye):Ye=e[42],Re=Ye,Se=A?Ga[A]??null:null,_e=!!w,e[14]=A,e[15]=w,e[16]=v,e[17]=T,e[18]=j,e[19]=r,e[20]=m,e[21]=Z,e[22]=Q,e[23]=o,e[24]=b,e[25]=p,e[26]=x,e[27]=Se,e[28]=Re,e[29]=_e}else Se=e[27],Re=e[28],_e=e[29];const Oe=!!(Q&&ee),Me=w?.source==="custom",ge=_e&&!Z||Oe,Ae=ge,ue=!he&&(Oe||_e&&!Z);let G;e[43]===Symbol.for("react.memo_cache_sentinel")?(G=()=>{je(!1)},e[43]=G):G=e[43];const fe=w?.updatedAt;let ce;e[44]!==o||e[45]!==fe?(ce=[o,fe],e[44]=o,e[45]=fe,e[46]=ce):ce=e[46],i.useEffect(G,ce);let W;e[47]!==F||e[48]!==o?(W=Ye=>{!o||!Ye||F||(se(!1),je(!1),K(Ye),re(Pt=>(Pt&&URL.revokeObjectURL(Pt),URL.createObjectURL(Ye))))},e[47]=F,e[48]=o,e[49]=W):W=e[49];const z=W;let be;e[50]!==Oe||e[51]!==Ae||e[52]!==_e||e[53]!==L||e[54]!==o?(be=()=>{!o||!Ae||L||(Oe&&J(),se(!!_e),je(!1))},e[50]=Oe,e[51]=Ae,e[52]=_e,e[53]=L,e[54]=o,e[55]=be):be=e[55];const xe=be;let _;e[56]!==h||e[57]!==V||e[58]!==o||e[59]!==p?(_=async()=>{!o||V||(J(),se(!1),je(!1),M(!0),h(o).then(Ye=>{if(!Ye.ok){de.error(Ye.error||p("projectEditDialog.toast.failedToDiscoverIcon"));return}if(Ye.skipped){de.success(p("projectEditDialog.toast.customIconAlreadySet"));return}de.success(p("projectEditDialog.toast.iconDiscovered"))}).finally(()=>{M(!1)}))},e[56]=h,e[57]=V,e[58]=o,e[59]=p,e[60]=_):_=e[60];const ye=_;let $;e[61]!==p?($=p("projectEditDialog.title"),e[61]=p,e[62]=$):$=e[62];let Ie;e[63]!==$?(Ie=s.jsx(Us,{className:"min-w-0",children:s.jsx(_s,{children:$})}),e[63]=$,e[64]=Ie):Ie=e[64];let ve;e[65]!==p?(ve=p("projectEditDialog.field.name"),e[65]=p,e[66]=ve):ve=e[66];let Fe;e[67]!==ve?(Fe=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:ve}),e[67]=ve,e[68]=Fe):Fe=e[68];let Ce;e[69]===Symbol.for("react.memo_cache_sentinel")?(Ce=Ye=>k(Ye.target.value),e[69]=Ce):Ce=e[69];let ne;e[70]!==p?(ne=p("projectEditDialog.field.namePlaceholder"),e[70]=p,e[71]=ne):ne=e[71];let P;e[72]!==Re?(P=Ye=>{Ye.key==="Enter"&&(Ye.preventDefault(),Re())},e[72]=Re,e[73]=P):P=e[73];let me;e[74]!==j||e[75]!==ne||e[76]!==P?(me=s.jsx(vn,{value:j,onChange:Ce,placeholder:ne,onKeyDown:P,autoFocus:!0}),e[74]=j,e[75]=ne,e[76]=P,e[77]=me):me=e[77];let oe;e[78]!==c?(oe=s.jsx("p",{className:"typography-meta text-muted-foreground truncate",title:c,children:c}),e[78]=c,e[79]=oe):oe=e[79];let Be;e[80]!==Fe||e[81]!==me||e[82]!==oe?(Be=s.jsxs("div",{className:"min-w-0 space-y-1.5",children:[Fe,me,oe]}),e[80]=Fe,e[81]=me,e[82]=oe,e[83]=Be):Be=e[83];let Ue;e[84]!==p?(Ue=p("projectEditDialog.field.color"),e[84]=p,e[85]=Ue):Ue=e[85];let Ke;e[86]!==Ue?(Ke=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:Ue}),e[86]=Ue,e[87]=Ke):Ke=e[87];let Qe;e[88]===Symbol.for("react.memo_cache_sentinel")?(Qe=()=>C(null),e[88]=Qe):Qe=e[88];const rt=A===null?"border-foreground scale-110":"border-border hover:border-border/80";let pt;e[89]!==rt?(pt=De("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",rt),e[89]=rt,e[90]=pt):pt=e[90];let jt;e[91]!==p?(jt=p("projectEditDialog.option.none"),e[91]=p,e[92]=jt):jt=e[92];let Ve;e[93]===Symbol.for("react.memo_cache_sentinel")?(Ve=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[93]=Ve):Ve=e[93];let Ze;e[94]!==pt||e[95]!==jt?(Ze=s.jsx("button",{type:"button",onClick:Qe,className:pt,title:jt,children:Ve}),e[94]=pt,e[95]=jt,e[96]=Ze):Ze=e[96];let nt;e[97]!==A?(nt=gg.map(Ye=>s.jsx("button",{type:"button",onClick:()=>C(Ye.key),className:De("w-8 h-8 rounded-lg border-2 transition-all",A===Ye.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:Ye.cssVar},title:Ye.label},Ye.key)),e[97]=A,e[98]=nt):nt=e[98];let St;e[99]!==Ze||e[100]!==nt?(St=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Ze,nt]}),e[99]=Ze,e[100]=nt,e[101]=St):St=e[101];let Dt;e[102]!==Ke||e[103]!==St?(Dt=s.jsxs("div",{className:"min-w-0 space-y-2",children:[Ke,St]}),e[102]=Ke,e[103]=St,e[104]=Dt):Dt=e[104];let wt;e[105]!==p?(wt=p("projectEditDialog.field.icon"),e[105]=p,e[106]=wt):wt=e[106];let ot;e[107]!==wt?(ot=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:wt}),e[107]=wt,e[108]=ot):ot=e[108];let at;e[109]!==z?(at=s.jsx("input",{ref:te,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:Ye=>{const Pt=Ye.target.files?.[0]??null;z(Pt),Ye.currentTarget.value=""}}),e[109]=z,e[110]=at):at=e[110];let Kt;e[111]===Symbol.for("react.memo_cache_sentinel")?(Kt=()=>D(null),e[111]=Kt):Kt=e[111];const is=v===null?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80";let $t;e[112]!==is?($t=De("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",is),e[112]=is,e[113]=$t):$t=e[113];let Le;e[114]!==p?(Le=p("projectEditDialog.option.none"),e[114]=p,e[115]=Le):Le=e[115];let et;e[116]===Symbol.for("react.memo_cache_sentinel")?(et=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[116]=et):et=e[116];let Vt;e[117]!==$t||e[118]!==Le?(Vt=s.jsx("button",{type:"button",onClick:Kt,className:$t,title:Le,children:et}),e[117]=$t,e[118]=Le,e[119]=Vt):Vt=e[119];let xt;e[120]!==Se||e[121]!==v?(xt=xg.map(Ye=>{const Pt=Ye.Icon;return s.jsx("button",{type:"button",onClick:()=>D(Ye.key),className:De("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",v===Ye.key?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80"),title:Ye.label,children:s.jsx(I,{name:Pt,className:"w-4 h-4",style:Se?{color:Se}:void 0})},Ye.key)}),e[120]=Se,e[121]=v,e[122]=xt):xt=e[122];let Ft;e[123]!==Vt||e[124]!==xt?(Ft=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Vt,xt]}),e[123]=Vt,e[124]=xt,e[125]=Ft):Ft=e[125];let Gt;e[126]!==w||e[127]!==S||e[128]!==ge||e[129]!==Oe||e[130]!==T||e[131]!==ee||e[132]!==o||e[133]!==ue||e[134]!==p?(Gt=ge&&ue&&s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:p("projectEditDialog.field.preview")}),s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-1",children:s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:T?{backgroundColor:T}:void 0,children:Oe&&ee?s.jsx("img",{src:ee,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>je(!0)}):s.jsx(Ka,{project:{id:o,iconImage:w},options:{themeVariant:S.metadata.variant,iconColor:S.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>je(!0)})})})]}),e[126]=w,e[127]=S,e[128]=ge,e[129]=Oe,e[130]=T,e[131]=ee,e[132]=o,e[133]=ue,e[134]=p,e[135]=Gt):Gt=e[135];let Ut;e[136]!==ye||e[137]!==Me||e[138]!==V||e[139]!==F||e[140]!==p?(Ut=!Me&&s.jsxs(s.Fragment,{children:[s.jsx($e,{size:"sm",variant:"outline",onClick:()=>te.current?.click(),disabled:F,children:p(F?"projectEditDialog.actions.uploading":"projectEditDialog.actions.uploadIcon")}),s.jsx($e,{size:"sm",variant:"outline",onClick:()=>{ye()},disabled:V,children:p(V?"projectEditDialog.actions.discovering":"projectEditDialog.actions.discoverFavicon")})]}),e[136]=ye,e[137]=Me,e[138]=V,e[139]=F,e[140]=p,e[141]=Ut):Ut=e[141];let qt;e[142]!==xe||e[143]!==Ae||e[144]!==L||e[145]!==p?(qt=Ae&&s.jsx($e,{size:"sm",variant:"outline",onClick:()=>{xe()},disabled:L,children:p(L?"projectEditDialog.actions.removing":"projectEditDialog.actions.removeProjectIcon")}),e[142]=xe,e[143]=Ae,e[144]=L,e[145]=p,e[146]=qt):qt=e[146];let Xt;e[147]!==L||e[148]!==Z||e[149]!==p?(Xt=Z&&s.jsx($e,{size:"sm",variant:"outline",onClick:()=>se(!1),disabled:L,children:p("projectEditDialog.actions.undoRemove")}),e[147]=L,e[148]=Z,e[149]=p,e[150]=Xt):Xt=e[150];let Lt;e[151]!==Ut||e[152]!==qt||e[153]!==Xt?(Lt=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[Ut,qt,Xt]}),e[151]=Ut,e[152]=qt,e[153]=Xt,e[154]=Lt):Lt=e[154];let Bt;e[155]!==ot||e[156]!==at||e[157]!==Ft||e[158]!==Gt||e[159]!==Lt?(Bt=s.jsxs("div",{className:"min-w-0 space-y-2",children:[ot,at,Ft,Gt,Lt]}),e[155]=ot,e[156]=at,e[157]=Ft,e[158]=Gt,e[159]=Lt,e[160]=Bt):Bt=e[160];let Yt;e[161]!==ge||e[162]!==T||e[163]!==p?(Yt=ge&&s.jsxs("div",{className:"min-w-0 space-y-2",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:p("projectEditDialog.field.iconBackground")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:T??"#000000",onChange:Ye=>E(Ye.target.value),className:"h-8 w-10 cursor-pointer rounded border border-border bg-transparent p-1","aria-label":p("projectEditDialog.field.iconBackgroundAria")}),s.jsx(vn,{value:T??"",onChange:Ye=>E(Ye.target.value),placeholder:"#000000",className:"h-8 w-[8.5rem]"}),s.jsx($e,{size:"sm",variant:"outline",onClick:()=>E(null),children:p("projectEditDialog.actions.clear")})]})]}),e[161]=ge,e[162]=T,e[163]=p,e[164]=Yt):Yt=e[164];let Jt;e[165]!==Be||e[166]!==Dt||e[167]!==Bt||e[168]!==Yt?(Jt=s.jsxs("div",{className:"min-w-0 space-y-5 py-1",children:[Be,Dt,Bt,Yt]}),e[165]=Be,e[166]=Dt,e[167]=Bt,e[168]=Yt,e[169]=Jt):Jt=e[169];let es;e[170]!==r?(es=()=>r(!1),e[170]=r,e[171]=es):es=e[171];let Zt;e[172]!==p?(Zt=p("projectEditDialog.actions.cancel"),e[172]=p,e[173]=Zt):Zt=e[173];let vs;e[174]!==es||e[175]!==Zt?(vs=s.jsx($e,{variant:"ghost",onClick:es,children:Zt}),e[174]=es,e[175]=Zt,e[176]=vs):vs=e[176];let bt;e[177]!==L||e[178]!==F||e[179]!==j?(bt=!j.trim()||F||L,e[177]=L,e[178]=F,e[179]=j,e[180]=bt):bt=e[180];let Ot;e[181]!==p?(Ot=p("projectEditDialog.actions.save"),e[181]=p,e[182]=Ot):Ot=e[182];let It;e[183]!==Re||e[184]!==bt||e[185]!==Ot?(It=s.jsx($e,{onClick:Re,disabled:bt,children:Ot}),e[183]=Re,e[184]=bt,e[185]=Ot,e[186]=It):It=e[186];let us;e[187]!==vs||e[188]!==It?(us=s.jsxs(ar,{children:[vs,It]}),e[187]=vs,e[188]=It,e[189]=us):us=e[189];let He;e[190]!==Ie||e[191]!==Jt||e[192]!==us?(He=s.jsxs(Ls,{className:"max-w-md",children:[Ie,Jt,us]}),e[190]=Ie,e[191]=Jt,e[192]=us,e[193]=He):He=e[193];let ft;return e[194]!==r||e[195]!==n||e[196]!==He?(ft=s.jsx(Os,{open:n,onOpenChange:r,children:He}),e[194]=r,e[195]=n,e[196]=He,e[197]=ft):ft=e[197],ft};function GS(t){return t.uploadProjectIcon}function KS(t){return t.removeProjectIcon}function qS(t){return t.discoverProjectIcon}function YS(t){return t&&URL.revokeObjectURL(t),null}const QS=t=>{const e=gt.c(86),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:c,onRename:l,onDelete:d,renderSessionNode:u,getRenderExtras:m,groupDirectory:f,projectId:g,mobileVariant:y,alwaysShowActions:p,isRenaming:x,renameDraft:b,onRenameDraftChange:h,onRenameSave:N,onRenameCancel:w,droppableRef:S,isDropTarget:j,onNewSession:k,onNewSubFolder:v,depth:D,hideActions:A,archivedBucket:C}=t,T=p===void 0?y===void 0?!1:y:p,E=x===void 0?!1:x,F=b===void 0?"":b,R=j===void 0?!1:j,L=D===void 0?0:D,B=A===void 0?!1:A,V=C===void 0?!1:C,{t:M}=kt(),[Z,se]=i.useState(!1),[Q,K]=i.useState(""),ee=i.useRef(null),re=E||Z,he=E?F:Q;let je;e[0]!==n.name?(je=()=>{K(n.name),se(!0)},e[0]=n.name,e[1]=je):je=e[1];const te=je;let Ne;e[2]!==he||e[3]!==n.name||e[4]!==E||e[5]!==l||e[6]!==N?(Ne=()=>{const P=he.trim();P&&P!==n.name&&l(P),E&&N&&N(),se(!1),K("")},e[2]=he,e[3]=n.name,e[4]=E,e[5]=l,e[6]=N,e[7]=Ne):Ne=e[7];const J=Ne;let H;e[8]!==E||e[9]!==w?(H=()=>{E&&w&&w(),se(!1),K("")},e[8]=E,e[9]=w,e[10]=H):H=e[10];const q=H;let ae;e[11]!==E||e[12]!==h?(ae=P=>{E&&h?h(P):K(P)},e[11]=E,e[12]=h,e[13]=ae):ae=e[13];const le=ae;let Se,Re;e[14]!==E?(Se=()=>{if(!E)return;const P=()=>{const Be=ee.current;Be&&(Be.focus(),Be.select())},me=requestAnimationFrame(P),oe=window.setTimeout(P,0);return()=>{cancelAnimationFrame(me),window.clearTimeout(oe)}},Re=[E],e[14]=E,e[15]=Se,e[16]=Re):(Se=e[15],Re=e[16]),i.useEffect(Se,Re);const _e=a?"folder":"folder-open",Me=L>0&&"ml-3";let ge;e[17]!==Me?(ge=De("oc-folder",Me),e[17]=Me,e[18]=ge):ge=e[18];const Ae=R&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let pe;e[19]!==Ae?(pe=De("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",Ae),e[19]=Ae,e[20]=pe):pe=e[20];const ue=re?void 0:c,G=re?void 0:"button",fe=re?void 0:0;let ce;e[21]!==c||e[22]!==re?(ce=re?void 0:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),c())},e[21]=c,e[22]=re,e[23]=ce):ce=e[23];let W;e[24]!==n.name||e[25]!==a||e[26]!==M?(W=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]=W):W=e[27];const z=V?T?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let be;e[28]!==z?(be=De("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",z),e[28]=z,e[29]=be):be=e[29];const xe=R?"text-primary":"text-muted-foreground";let _;e[30]!==xe?(_=De("h-3.5 w-3.5 flex-shrink-0",xe),e[30]=xe,e[31]=_):_=e[31];let ye;e[32]!==_e||e[33]!==_?(ye=s.jsx(I,{name:_e,className:_}),e[32]=_e,e[33]=_,e[34]=ye):ye=e[34];let $;e[35]!==he||e[36]!==n.name||e[37]!==q||e[38]!==le||e[39]!==J||e[40]!==a||e[41]!==R||e[42]!==re||e[43]!==r||e[44]!==M?($=re?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:XS,onMouseDown:ZS,onSubmit:P=>{P.preventDefault(),J()},children:[s.jsx("input",{ref:ee,value:he,onChange:P=>le(P.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:eN,onPointerDown:tN,onMouseDown:sN,onKeyDown:P=>{if(P.key==="Escape"){P.stopPropagation(),q();return}(P.key===" "||P.key==="Enter")&&P.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:nN,onPointerDown:rN,onMouseDown:iN,children:s.jsx(I,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),q()},onPointerDown:oN,onMouseDown:aN,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:De("typography-ui-label font-semibold truncate",R?"text-primary":"text-muted-foreground"),children:n.name}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",r.length]}),a?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[35]=he,e[36]=n.name,e[37]=q,e[38]=le,e[39]=J,e[40]=a,e[41]=R,e[42]=re,e[43]=r,e[44]=M,e[45]=$):$=e[45];let Ie;e[46]!==be||e[47]!==ye||e[48]!==$?(Ie=s.jsxs("div",{className:be,children:[ye,$]}),e[46]=be,e[47]=ye,e[48]=$,e[49]=Ie):Ie=e[49];let ve;e[50]!==T||e[51]!==V||e[52]!==L||e[53]!==n.name||e[54]!==te||e[55]!==B||e[56]!==d||e[57]!==k||e[58]!==v||e[59]!==re||e[60]!==M?(ve=!re&&(!B||V)?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:De("flex items-center gap-0.5 transition-opacity",T?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100",V&&"absolute right-0.5 top-1/2 z-10 -translate-y-1/2 px-0"),children:[!V&&k?s.jsx("button",{type:"button",onClick:P=>{P.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(I,{name:"add",className:"h-3.5 w-3.5"})}):null,!V&&v&&L===0?s.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),v()},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(I,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,V?null:s.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),te()},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(I,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":V?M("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):M("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=T,e[51]=V,e[52]=L,e[53]=n.name,e[54]=te,e[55]=B,e[56]=d,e[57]=k,e[58]=v,e[59]=re,e[60]=M,e[61]=ve):ve=e[61];let Fe;e[62]!==S||e[63]!==pe||e[64]!==ue||e[65]!==G||e[66]!==fe||e[67]!==ce||e[68]!==W||e[69]!==Ie||e[70]!==ve?(Fe=s.jsxs("div",{ref:S,className:pe,onClick:ue,role:G,tabIndex:fe,onKeyDown:ce,"aria-label":W,children:[Ie,ve]}),e[62]=S,e[63]=pe,e[64]=ue,e[65]=G,e[66]=fe,e[67]=ce,e[68]=W,e[69]=Ie,e[70]=ve,e[71]=Fe):Fe=e[71];let Ce;e[72]!==V||e[73]!==m||e[74]!==f||e[75]!==a||e[76]!==g||e[77]!==u||e[78]!==r||e[79]!==o||e[80]!==M?(Ce=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(P=>u(P,0,f??null,g??null,V,void 0,"project",m?.(P))):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]=V,e[73]=m,e[74]=f,e[75]=a,e[76]=g,e[77]=u,e[78]=r,e[79]=o,e[80]=M,e[81]=Ce):Ce=e[81];let ne;return e[82]!==ge||e[83]!==Fe||e[84]!==Ce?(ne=s.jsxs("div",{className:ge,children:[Fe,Ce]}),e[82]=ge,e[83]=Fe,e[84]=Ce,e[85]=ne):ne=e[85],ne},JS=i.memo(QS);function XS(t){return t.stopPropagation()}function ZS(t){return t.stopPropagation()}function eN(t){return t.stopPropagation()}function tN(t){return t.stopPropagation()}function sN(t){return t.stopPropagation()}function nN(t){return t.stopPropagation()}function rN(t){return t.stopPropagation()}function iN(t){return t.stopPropagation()}function oN(t){return t.stopPropagation()}function aN(t){return t.stopPropagation()}const lN=t=>{const e=gt.c(15),{sessionId:n,sessionDirectory:r,sessionTitle:o,children:a}=t,c=`session-drag:${n}`;let l;e[0]!==r||e[1]!==n||e[2]!==o?(l={type:"session",sessionId:n,sessionDirectory:r,sessionTitle:o},e[0]=r,e[1]=n,e[2]=o,e[3]=l):l=e[3];let d;e[4]!==c||e[5]!==l?(d={id:c,data:l},e[4]=c,e[5]=l,e[6]=d):d=e[6];const{attributes:u,listeners:m,setNodeRef:f,isDragging:g}=Bh(d);let y;e[7]!==m?(y=h=>{h.stopPropagation(),m?.onPointerDown&&m.onPointerDown(h)},e[7]=m,e[8]=y):y=e[8];const p=y,x=g?"opacity-30":void 0;let b;return e[9]!==u||e[10]!==a||e[11]!==p||e[12]!==f||e[13]!==x?(b=s.jsx("div",{ref:f,...u,onPointerDown:p,className:x,children:a}),e[9]=u,e[10]=a,e[11]=p,e[12]=f,e[13]=x,e[14]=b):b=e[14],b},cN=t=>{const e=gt.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}=Oh(c);let u;e[5]!==r||e[6]!==d||e[7]!==l?(u=r(l,d),e[5]=r,e[6]=d,e[7]=l,e[8]=u):u=e[8];let m;return e[9]!==u?(m=s.jsx(s.Fragment,{children:u}),e[9]=u,e[10]=m):m=e[10],m},dN=t=>{const e=gt.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=ga(yo(xa,c)),[d,u]=i.useState(null),[m,f]=i.useState("Session"),[g,y]=i.useState(null),[p,x]=i.useState(null);if(!n){let v;return e[1]!==a?(v=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=v):v=e[2],v}let b;e[3]!==o?(b=v=>{u(null),y(null),x(null);const{active:D,over:A}=v;if(!A)return;const C=D.data.current,O=A.data.current;C?.type==="session"&&C.sessionId&&O?.type==="folder"&&O.folderId&&o(C.sessionId,O.folderId)},e[3]=o,e[4]=b):b=e[4];const h=b;let N,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(N=v=>{const D=v.active.data.current;if(D?.type==="session"&&D.sessionId){u(D.sessionId),f(D.sessionTitle??"Session");const A=v.active.rect.current.initial?.width,C=v.active.rect.current.initial?.height;y(typeof A=="number"?A:null),x(typeof C=="number"?C:null)}},w=()=>{u(null),y(null),x(null)},e[5]=N,e[6]=w):(N=e[5],w=e[6]);let S;e[7]!==p||e[8]!==d||e[9]!==m||e[10]!==g||e[11]!==r?(S=d&&r?s.jsxs("div",{style:{width:g?`${g}px`:"auto",height:p?`${p}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2.5 py-1 shadow-none pointer-events-none",children:[s.jsx(I,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:m})]}):null,e[7]=p,e[8]=d,e[9]=m,e[10]=g,e[11]=r,e[12]=S):S=e[12];let j;e[13]!==S?(j=s.jsx(Vl,{children:S}),e[13]=S,e[14]=j):j=e[14];let k;return e[15]!==a||e[16]!==h||e[17]!==l||e[18]!==j?(k=s.jsxs(ba,{sensors:l,collisionDetection:ya,onDragStart:N,onDragCancel:w,onDragEnd:h,children:[a,j]}),e[15]=a,e[16]=h,e[17]=l,e[18]=j,e[19]=k):k=e[19],k},Gi=(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)},$r=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if($r(n,e))return!0;return!1},Ra=t=>t.children.length===0?"":t.children.map(n=>n.children.length===0?n.session.id:`${n.session.id}:${Ra(n)}`).join("|"),Fo=(t,e,n,r)=>{if(!e)return null;const o=r?"archived":"active";let a=null;const c=l=>{if(`${n}:${o}:${l.session.id}`===e)return a=l.session.id,!0;for(const u of l.children)if(c(u))return!0;return!1};return t.forEach(l=>c(l)),a},Dr=io()(ic(t=>({displayMode:"minimal",showRecentSection:!0,showArchivedSessions:!1,setDisplayMode:e=>t({displayMode:e}),setShowRecentSection:e=>t({showRecentSection:e}),setShowArchivedSessions:e=>t({showArchivedSessions:e}),toggleRecentSection:()=>t(e=>({showRecentSection:!e.showRecentSection})),toggleArchivedSessions:()=>t(e=>({showArchivedSessions:!e.showArchivedSessions}))}),{name:"session-display-mode",version:1,migrate:(t,e)=>{const n=t??{};return e<1?{...n,displayMode:"minimal"}:n}})),uN=50,fN=30,Il=28,$i=(t,e)=>e?t.sessions.some(n=>$r(n,e)):!1,mN=(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)},hN=(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)},pN=(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)},gN=(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},xN=(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&&mN(e.group,t.pinnedSessionIds,e.pinnedSessionIds)||t.expandedParents!==e.expandedParents&&pN(e.group,t.expandedParents,e.expandedParents)||t.sessionOrderIndex!==e.sessionOrderIndex&&hN(e.group,t.sessionOrderIndex,e.sessionOrderIndex)||t.currentSessionId!==e.currentSessionId&&($i(t.group,t.currentSessionId)||$i(e.group,e.currentSessionId))||t.editingId!==e.editingId&&($i(t.group,t.editingId)||$i(e.group,e.editingId))||t.editTitle!==e.editTitle&&($i(t.group,t.editingId)||$i(e.group,e.editingId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=Fo(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket),r=Fo(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket);if(n||r)return!1}if(t.liveSessionById!==e.liveSessionById&&gN(e.group,t.liveSessionById,e.liveSessionById))return!1;if(t.prVisualStateByDirectoryBranch!==e.prVisualStateByDirectoryBranch){const n=t.group?.directory&&t.group?.branch?t.prVisualStateByDirectoryBranch.get(`${t.group.directory}::${t.group.branch.trim()}`):void 0,r=e.group?.directory&&e.group?.branch?e.prVisualStateByDirectoryBranch.get(`${e.group.directory}::${e.group.branch.trim()}`):void 0;if(!Object.is(n,r))return!1}return t.hasSessionSearchQuery===e.hasSessionSearchQuery&&t.normalizedSessionSearchQuery===e.normalizedSessionSearchQuery&&t.hideDirectoryControls===e.hideDirectoryControls&&t.collapsedFolderIds===e.collapsedFolderIds&&t.toggleFolderCollapse===e.toggleFolderCollapse&&t.renameFolder===e.renameFolder&&t.deleteFolder===e.deleteFolder&&t.showDeletionDialog===e.showDeletionDialog&&t.setDeleteFolderConfirm===e.setDeleteFolderConfirm&&t.renderSessionNode===e.renderSessionNode&&t.lastRepoStatus===e.lastRepoStatus&&t.showMoreGroupSessions===e.showMoreGroupSessions&&t.resetGroupSessionLimit===e.resetGroupSessionLimit&&t.mobileVariant===e.mobileVariant&&t.alwaysShowActions===e.alwaysShowActions&&t.activeProjectId===e.activeProjectId&&t.setActiveProjectIdOnly===e.setActiveProjectIdOnly&&t.setActiveMainTab===e.setActiveMainTab&&t.setSessionSwitcherOpen===e.setSessionSwitcherOpen&&t.openNewSessionDraft===e.openNewSessionDraft&&t.addSessionToFolder===e.addSessionToFolder&&t.createFolderAndStartRename===e.createFolderAndStartRename&&t.renamingFolderId===e.renamingFolderId&&t.renameFolderDraft===e.renameFolderDraft&&t.setRenameFolderDraft===e.setRenameFolderDraft&&t.setRenamingFolderId===e.setRenamingFolderId&&t.onToggleCollapsedGroup===e.onToggleCollapsedGroup&&t.dragHandleProps===e.dragHandleProps&&t.scrollContainerRef===e.scrollContainerRef};function bN(t){const{t:e}=kt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:u,collapsedGroups:m,hideDirectoryControls:f,collapsedFolderIds:g,toggleFolderCollapse:y,renameFolder:p,deleteFolder:x,showDeletionDialog:b,setDeleteFolderConfirm:h,renderSessionNode:N,projectRepoStatus:w,lastRepoStatus:S,showMoreGroupSessions:j,resetGroupSessionLimit:k,mobileVariant:v,alwaysShowActions:D,activeProjectId:A,setActiveProjectIdOnly:C,setActiveMainTab:O,setSessionSwitcherOpen:T,openNewSessionDraft:E,addSessionToFolder:F,createFolderAndStartRename:R,renamingFolderId:L,renameFolderDraft:B,setRenameFolderDraft:V,setRenamingFolderId:M,pinnedSessionIds:Z,expandedParents:se,sessionOrderIndex:Q,currentSessionId:K,editingId:ee,openSidebarMenuKey:re,prVisualStateByDirectoryBranch:he,onToggleCollapsedGroup:je,dragHandleProps:te,compactBodyPadding:Ne=!1,scrollContainerRef:J}=t,H=i.useCallback((He,ft)=>{const Ye=Q.get(He.session.id),Pt=Q.get(ft.session.id);if(Ye!==void 0||Pt!==void 0){if(Ye===void 0)return 1;if(Pt===void 0)return-1;if(Ye!==Pt)return Ye-Pt}return Ki(He.session,ft.session,Z)},[Z,Q]),q=c?d.get(n):null,ae=Dr(He=>He.displayMode),le=Vn(He=>He.foldersMap),Se=ae==="minimal"&&!Hr(),Re=c?!1:m.has(r),_e=f?10:5,Oe=Math.max(_e,u??_e),Me=c?q?.groupMatches===!0:!1,ge=c,Ae=i.useMemo(()=>[...ge?q?.filteredNodes??[]:n.sessions].sort(H),[H,n.sessions,q?.filteredNodes,ge]),pe=n.folderScopeKey??as(n.directory??null),ue=i.useMemo(()=>pe?le[pe]??[]:[],[pe,le]),G=i.useMemo(()=>{const He=new Map,ft=Ye=>{Ye.forEach(Pt=>{He.set(Pt.session.id,Pt),Pt.children.length>0&&ft(Pt.children)})};return ft(Ae),He},[Ae]),fe=i.useMemo(()=>ue.map(He=>{const ft=He.sessionIds.map(Ye=>G.get(Ye)).filter(Ye=>!!Ye).sort(H);return{folder:He,nodes:ft}}),[ue,G,H]),ce=i.useMemo(()=>{const He=new Map(fe.map(Tt=>[Tt.folder.id,Tt])),ft=new Map;for(const{folder:Tt}of fe){if(!Tt.parentId)continue;const Qt=ft.get(Tt.parentId);Qt?Qt.push(Tt.id):ft.set(Tt.parentId,[Tt.id])}const Ye=new Map,Pt=Tt=>{const Qt=Ye.get(Tt);if(Qt!==void 0)return Qt;const Ss=He.get(Tt);if(!Ss)return Ye.set(Tt,!1),!1;const ys=ft.get(Tt)??[];if(n.isArchivedBucket&&Ss.nodes.length===0){const js=ys.some(Ds=>Pt(Ds));return Ye.set(Tt,js),js}if(!c||Ss.folder.name.toLowerCase().includes(l)||Ss.nodes.length>0)return Ye.set(Tt,!0),!0;const Ns=ys.some(js=>Pt(js));return Ye.set(Tt,Ns),Ns};return fe.filter(({folder:Tt})=>Pt(Tt.id))},[fe,n.isArchivedBucket,c,l]),W=i.useMemo(()=>new Set(ce.flatMap(He=>He.folder.sessionIds)),[ce]),z=i.useMemo(()=>Ae.filter(He=>!W.has(He.session.id)),[Ae,W]),be=i.useMemo(()=>ce.filter(({folder:He})=>!He.parentId),[ce]),xe="project",_=i.useMemo(()=>{const He=new Set;return Gi(Ae,K,He),ce.forEach(({nodes:ft})=>{Gi(ft,K,He)}),He},[Ae,ce,K]),ye=i.useMemo(()=>{const He=new Set;return Gi(Ae,ee,He),ce.forEach(({nodes:ft})=>{Gi(ft,ee,He)}),He},[Ae,ce,ee]),$=i.useMemo(()=>{if(!re)return null;const He=Fo(Ae,re,xe,!!n.isArchivedBucket);if(He)return He;for(const{nodes:ft}of ce){const Ye=Fo(ft,re,xe,!!n.isArchivedBucket);if(Ye)return Ye}return null},[re,Ae,ce,n.isArchivedBucket]),Ie=i.useCallback(He=>{const ft=new WeakMap,Ye=Pt=>{ft.set(Pt,Ra(Pt));for(const Tt of Pt.children)Ye(Tt)};return He.forEach(Ye),ft},[]),ve=i.useMemo(()=>Ie(Ae),[Ie,Ae]),Fe=i.useMemo(()=>{const He=new WeakMap;return ce.forEach(({nodes:ft})=>{ft.forEach(Ye=>He.set(Ye,Ra(Ye)))}),He},[ce]),Ce=i.useCallback(He=>ve.get(He)??Fe.get(He)??"",[ve,Fe]),ne=i.useCallback(He=>({subtreeContainsActive:_,subtreeContainsEditing:ye,menuOpenSessionId:$,nodeStructureKey:Ce(He)}),[_,ye,$,Ce]),P=z.length,me=n.isArchivedBucket||c?z:z.slice(0,Oe),oe=P-me.length,Be=!n.isArchivedBucket&&!c&&P>_e&&oe===0,Ue=n.isArchivedBucket===!0&&!c&&me.length>=uN,Ke=n.isArchivedBucket!==!0&&!c&&me.length>=fN,Qe=Ue||Ke,rt=n.isArchivedBucket?"archived":"active",pt=Qe&&me.some(He=>{if(He.children.length===0)return!1;const ft=`project:${rt}:${He.session.id}`;return se.has(ft)}),jt=i.useRef(null),Ve=i.useRef(null),[Ze,nt]=i.useState(null),[St,Dt]=i.useState(0),[,wt]=i.useState(0);i.useEffect(()=>{if(!Qe)return;const He=jt.current;if(!He||typeof ResizeObserver>"u")return;const ft=new ResizeObserver(()=>wt(Ye=>Ye+1));return ft.observe(He),()=>ft.disconnect()},[Qe]),i.useLayoutEffect(()=>{if(!Qe){Ze!==null&&nt(null),Ve.current=null,St!==0&&Dt(0);return}const He=jt.current;if(!He)return;let ft=Ze;const Ye=J?.current??null;if(Ye&&Ye.contains(He)){if(ft=Ye,ft!==Ze){Ve.current=ft,nt(ft);return}}else if(!ft||!ft.contains(He)){let Tt=He.parentElement;for(;Tt;){const Qt=window.getComputedStyle(Tt);if(Qt.overflowY==="auto"||Qt.overflowY==="scroll"){ft=Tt;break}Tt=Tt.parentElement}if(ft!==Ze){Ve.current=ft,nt(ft);return}}if(!ft)return;const Pt=He.getBoundingClientRect().top-ft.getBoundingClientRect().top+ft.scrollTop;Dt(Tt=>Math.abs(Tt-Pt)<1?Tt:Pt)});const ot=i.useCallback(He=>{const ft=[],Ye=Pt=>{Pt.forEach(Tt=>{ft.push(Tt.session),Tt.children.length>0&&Ye(Tt.children)})};return Ye(He),ft},[]),at=i.useMemo(()=>n.isArchivedBucket?ot(Ae):[],[ot,Ae,n.isArchivedBucket]),Kt=i.useMemo(()=>{if(!n.isArchivedBucket)return new Map;const He=new Map,ft=new Map;for(const{folder:Pt}of ce){if(!Pt.parentId)continue;const Tt=ft.get(Pt.parentId)??[];Tt.push(Pt.id),ft.set(Pt.parentId,Tt)}const Ye=(Pt,Tt)=>{if(Tt.has(Pt))return[];Tt.add(Pt);const Qt=ce.find(({folder:_t})=>_t.id===Pt),Ss=Qt?ot(Qt.nodes):[],ys=ft.get(Pt)??[];for(const _t of ys)Ss.push(...Ye(_t,Tt));return Ss};for(const{folder:Pt}of ce)He.set(Pt.id,Ye(Pt.id,new Set));return He},[ce,ot,n.isArchivedBucket]);if(c&&!Me&&be.length===0&&z.length===0)return null;const is=o&&w.has(o)?!!w.get(o):S,$t=as(n.directory??null),Le=n.branch?.trim()??null,et=$t&&Le?he.get(`${$t}::${Le}`)??null:null,Vt=!!(et&&n.branch),xt=!et&&!n.isMain&&!!n.branch,Ft=et?.visualState??null,Gt=et&&et.state==="open"&&et.checks?e("sessions.sidebar.group.pr.checksPassed",{success:et.checks.success,total:et.checks.total}):null,Ut=et&&et.state==="open"&&et.checks?[et.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:et.checks.failure}):null,et.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:et.checks.pending}):null].filter(He=>!!He).join(", "):null,qt=et&&et.state==="open"?et.mergeableState==="blocked"||et.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):et.mergeableState==="clean"||et.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,Xt=et&&et.state==="open"&&et.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:et.mergeableState}):null,Lt=et?.base??null,Bt=et?.head??null,Yt=(()=>{if(!et)return n.branch&&Xx(n.branch,n.label)?{label:n.branch,color:null}:null;switch(et.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return et.canMerge===!0||et.mergeableState==="clean"||et.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:et.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}})(),Jt=Yt?.color??(Ft?`var(--pr-${Ft})`:void 0),es=He=>{He.preventDefault(),He.stopPropagation();const ft=et?.url;ft&&Pi(ft)},Zt=(He,ft,Ye)=>{const Pt=ce.filter(({folder:Ss})=>Ss.parentId===He.id),Tt=Pt.length>0?s.jsx(s.Fragment,{children:Pt.map(({folder:Ss,nodes:ys})=>Zt(Ss,ys,Ye+1))}):void 0,Qt=Kt.get(He.id)??[];return s.jsx(cN,{folderId:He.id,children:(Ss,ys)=>s.jsx(JS,{folder:He,sessions:ft,subFolderItems:Tt,isCollapsed:c?!1:g.has(He.id),onToggle:()=>y(He.id),onRename:_t=>{pe&&p(pe,He.id,_t)},onDelete:()=>{if(n.isArchivedBucket){Pr.requestDelete({sessions:Qt,mode:"session"});return}if(!pe)return;if(!b){x(pe,He.id);return}const _t=ce.filter(({folder:js})=>js.parentId===He.id).length,Ns=ft.length;h({scopeKey:pe,folderId:He.id,folderName:He.name,subFolderCount:_t,sessionCount:Ns})},renderSessionNode:N,getRenderExtras:Ce?_t=>({subtreeContainsActive:_,subtreeContainsEditing:ye,menuOpenSessionId:$,nodeStructureKey:Ce(_t),childRenderExtrasFor:ne}):void 0,groupDirectory:n.directory,projectId:o,mobileVariant:v,alwaysShowActions:D,isRenaming:L===He.id,renameDraft:L===He.id?B:void 0,onRenameDraftChange:_t=>V(_t),onRenameSave:()=>{const _t=B.trim();_t&&pe&&p(pe,He.id,_t),M(null),V("")},onRenameCancel:()=>{M(null),V("")},droppableRef:Ss,isDropTarget:ys,depth:Ye,onNewSession:()=>{o&&o!==A&&C(o),O("chat"),v&&T(!1),E({directoryOverride:n.directory,targetFolderId:He.id})},onNewSubFolder:Ye===0?()=>{pe&&R(pe,He.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},He.id)},vs=()=>be.map(({folder:He,nodes:ft})=>Zt(He,ft,0)),bt=!!(!n.isMain&&n.worktree),Ot=D?bt?"pr-14":"pr-7":Se?bt?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":bt?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",It=s.jsxs(dN,{scopeKey:pe,hasFolders:ce.length>0,onSessionDroppedOnFolder:(He,ft)=>{pe&&F(pe,ft,He)},children:[vs(),Qe?s.jsx("div",{ref:jt,children:s.jsx(Vh,{data:me,itemSize:Il,bufferSize:pt?Il*20:Il*8,scrollRef:Ve,startMargin:St,children:He=>N(He,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:_,subtreeContainsEditing:ye,menuOpenSessionId:$,nodeStructureKey:Ce(He),childRenderExtrasFor:ne})})}):me.map(He=>N(He,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:_,subtreeContainsEditing:ye,menuOpenSessionId:$,nodeStructureKey:Ce(He),childRenderExtrasFor:ne})),P===0&&ce.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:()=>j(r,me.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,Be?s.jsx("button",{type:"button",onClick:()=>k(r),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showFewer")}):null]}),us=Ne?"pb-2 pl-1":"pb-3 pl-4";return a?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:De("oc-group-body",us),children:It})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:De("group/gh relative flex items-start justify-between gap-1 py-1 min-w-0 rounded-md","cursor-pointer"),onClick:()=>je(r),role:"button",tabIndex:0,onKeyDown:He=>{(He.key==="Enter"||He.key===" ")&&(He.preventDefault(),je(r))},"aria-label":Re?e("sessions.sidebar.group.expandAria",{label:n.label}):e("sessions.sidebar.group.collapseAria",{label:n.label}),"aria-expanded":!Re,children:[s.jsx("div",{ref:te?.setActivatorNodeRef,className:De("min-w-0 flex flex-1 items-start gap-1 overflow-hidden pl-0.5 transition-[padding] cursor-grab active:cursor-grabbing",Ot),...te?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"text-[14px] font-normal truncate text-foreground/92",children:Vt&&et?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 leading-none align-middle",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(I,{name:"git-branch",className:De("h-3.5 w-3.5 shrink-0",D?"hidden":"group-hover/gh:hidden"),style:Jt?{color:Jt}:void 0}),s.jsx("span",{className:De("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Re?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),et.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:He=>He.stopPropagation(),onClick:es,children:["#",et.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",et.number]})]})}),s.jsx(Mt,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Lt||Bt?s.jsx("div",{className:"text-muted-foreground truncate",children:Lt&&Bt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Lt}),s.jsx(I,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Bt})]}):s.jsx("span",{children:Lt??Bt??""})}):null,Xt?s.jsx("div",{className:"text-muted-foreground truncate",children:Xt}):null,qt||Gt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[qt??"",qt&&Gt?" • ":"",Gt??"",Ut?` (${Ut})`:""]}):null]})})]}),s.jsx("span",{className:"ml-1 min-w-0 flex-1 truncate leading-none align-middle",children:n.branch})]}):n.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(I,{name:"archive",className:De("h-3.5 w-3.5 shrink-0 text-muted-foreground",D?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:De("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Re?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:vo(n.label,l)})]}):!n.isMain||n.worktree?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(I,{name:"git-branch",className:De("h-3.5 w-3.5 shrink-0 text-muted-foreground",D?"hidden":"group-hover/gh:hidden"),style:Jt?{color:Jt}:void 0}),s.jsx("span",{className:De("text-muted-foreground h-3.5 w-3.5 items-center justify-center",D?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Re?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:vo(n.label,l)})]}):vo(n.label,l)}),xt&&Yt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(I,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||is?Vt&&et?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:Jt?{color:Jt}:void 0})})}),s.jsx(Mt,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Lt||Bt?s.jsx("div",{className:"text-muted-foreground truncate",children:Lt&&Bt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Lt}),s.jsx(I,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Bt})]}):s.jsx("span",{children:Lt??Bt??""})}):null,Xt?s.jsx("div",{className:"text-muted-foreground truncate",children:Xt}):null,qt||Gt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[qt??"",qt&&Gt?" • ":"",Gt??"",Ut?` (${Ut})`:""]}):null]})})]}):s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:Jt?{color:Jt}:void 0}):null,s.jsx("span",{className:De("min-w-0 truncate text-[11px] font-medium",!Yt.color&&"text-muted-foreground/80"),style:Yt.color?{color:Yt.color}:void 0,children:Yt.label})]}):null]})}),n.isArchivedBucket&&at.length>0?s.jsx("div",{className:De("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(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),Pr.requestDelete({sessions:at,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.deleteArchivedInGroupAria",{label:n.label}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Mt,{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:De("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(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),Pr.requestDelete({sessions:at,mode:"worktree",worktree:n.worktree})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.deleteGroupAria",{label:n.label}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteWorktree")})})]})}):null,n.directory?s.jsx("div",{className:De("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(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:He=>{He.stopPropagation(),o&&o!==A&&C(o),O("chat"),v&&T(!1),E({directoryOverride:n.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.newDraftInGroupAria",{label:n.label}),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})}),s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),Re?null:s.jsx("div",{className:De("oc-group-body",us),children:It})]})}const yN=i.memo(bN,xN);function wN(t){const e=gt.c(182),{t:n}=kt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:u,headerActionButtonClass:m,isSessionSearchOpen:f,setIsSessionSearchOpen:g,sessionSearchInputRef:y,sessionSearchQuery:p,setSessionSearchQuery:x,hasSessionSearchQuery:b,searchMatchCount:h,collapseAllProjects:N,expandAllProjects:w,openScheduledTasksDialog:S,selectionModeEnabled:j,onToggleSelectionMode:k}=t,v=Dr(AN),D=Dr(CN),A=Dr(kN),C=Dr(NN),O=Dr(SN),T=Dr(jN);let E;e[0]===Symbol.for("react.memo_cache_sentinel")?(E=Hr(),e[0]=E):E=e[0];const F=!E;if(r)return null;let R;e[1]!==n?(R=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=R):R=e[2];let L;e[3]!==u?(L=s.jsx(I,{name:"folder-add",className:u}),e[3]=u,e[4]=L):L=e[4];let B;e[5]!==a||e[6]!==m||e[7]!==R||e[8]!==L?(B=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:m,"aria-label":R,children:L})}),e[5]=a,e[6]=m,e[7]=R,e[8]=L,e[9]=B):B=e[9];let V;e[10]!==n?(V=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=V):V=e[11];let M;e[12]!==V?(M=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:V})}),e[12]=V,e[13]=M):M=e[13];let Z;e[14]!==B||e[15]!==M?(Z=s.jsxs(Rt,{children:[B,M]}),e[14]=B,e[15]=M,e[16]=Z):Z=e[16];let se;e[17]!==n?(se=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=se):se=e[18];let Q;e[19]!==u?(Q=s.jsx(I,{name:"chat-new",className:u}),e[19]=u,e[20]=Q):Q=e[20];let K;e[21]!==m||e[22]!==c||e[23]!==se||e[24]!==Q?(K=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:m,"aria-label":se,children:Q})}),e[21]=m,e[22]=c,e[23]=se,e[24]=Q,e[25]=K):K=e[25];let ee;e[26]!==n?(ee=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=ee):ee=e[27];let re;e[28]!==ee?(re=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ee})}),e[28]=ee,e[29]=re):re=e[29];let he;e[30]!==re||e[31]!==K?(he=s.jsxs(Rt,{children:[K,re]}),e[30]=re,e[31]=K,e[32]=he):he=e[32];let je;e[33]!==n?(je=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=je):je=e[34];const te=!l;let Ne;e[35]!==u?(Ne=s.jsx(bg,{className:u}),e[35]=u,e[36]=Ne):Ne=e[36];let J;e[37]!==m||e[38]!==d||e[39]!==je||e[40]!==te||e[41]!==Ne?(J=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:m,"aria-label":je,disabled:te,children:Ne})}),e[37]=m,e[38]=d,e[39]=je,e[40]=te,e[41]=Ne,e[42]=J):J=e[42];let H;e[43]!==n?(H=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=H):H=e[44];let q;e[45]!==H?(q=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:H})}),e[45]=H,e[46]=q):q=e[46];let ae;e[47]!==J||e[48]!==q?(ae=s.jsxs(Rt,{children:[J,q]}),e[47]=J,e[48]=q,e[49]=ae):ae=e[49];let le;e[50]!==n?(le=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=le):le=e[51];let Se;e[52]!==u?(Se=s.jsx(I,{name:"calendar-schedule",className:u}),e[52]=u,e[53]=Se):Se=e[53];let Re;e[54]!==m||e[55]!==S||e[56]!==le||e[57]!==Se?(Re=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:m,"aria-label":le,children:Se})}),e[54]=m,e[55]=S,e[56]=le,e[57]=Se,e[58]=Re):Re=e[58];let _e;e[59]!==n?(_e=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=_e):_e=e[60];let Oe;e[61]!==_e?(Oe=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:_e})}),e[61]=_e,e[62]=Oe):Oe=e[62];let Me;e[63]!==Re||e[64]!==Oe?(Me=s.jsxs(Rt,{children:[Re,Oe]}),e[63]=Re,e[64]=Oe,e[65]=Me):Me=e[65];let ge;e[66]!==he||e[67]!==ae||e[68]!==Me||e[69]!==Z?(ge=s.jsxs("div",{className:"flex items-center gap-1.5",children:[Z,he,ae,Me]}),e[66]=he,e[67]=ae,e[68]=Me,e[69]=Z,e[70]=ge):ge=e[70];let Ae;e[71]!==g?(Ae=()=>g(vN),e[71]=g,e[72]=Ae):Ae=e[72];let pe;e[73]!==n?(pe=n("sessions.sidebar.header.actions.searchSessions"),e[73]=n,e[74]=pe):pe=e[74];let ue;e[75]!==u?(ue=s.jsx(I,{name:"search",className:u}),e[75]=u,e[76]=ue):ue=e[76];let G;e[77]!==m||e[78]!==f||e[79]!==Ae||e[80]!==pe||e[81]!==ue?(G=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Ae,className:m,"aria-label":pe,"aria-expanded":f,children:ue})}),e[77]=m,e[78]=f,e[79]=Ae,e[80]=pe,e[81]=ue,e[82]=G):G=e[82];let fe;e[83]!==n?(fe=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=fe):fe=e[84];let ce;e[85]!==fe?(ce=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:fe})}),e[85]=fe,e[86]=ce):ce=e[86];let W;e[87]!==G||e[88]!==ce?(W=s.jsxs(Rt,{children:[G,ce]}),e[87]=G,e[88]=ce,e[89]=W):W=e[89];const z=j&&"bg-interactive-hover text-primary";let be;e[90]!==m||e[91]!==z?(be=De(m,z),e[90]=m,e[91]=z,e[92]=be):be=e[92];let xe;e[93]!==j||e[94]!==n?(xe=n(j?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=j,e[94]=n,e[95]=xe):xe=e[95];let _;e[96]!==u?(_=s.jsx(I,{name:"checkbox-multiple",className:u}),e[96]=u,e[97]=_):_=e[97];let ye;e[98]!==k||e[99]!==j||e[100]!==be||e[101]!==xe||e[102]!==_?(ye=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:be,"aria-label":xe,"aria-pressed":j,children:_})}),e[98]=k,e[99]=j,e[100]=be,e[101]=xe,e[102]=_,e[103]=ye):ye=e[103];let $;e[104]!==j||e[105]!==n?($=n(j?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=j,e[105]=n,e[106]=$):$=e[106];let Ie;e[107]!==$?(Ie=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:$})}),e[107]=$,e[108]=Ie):Ie=e[108];let ve;e[109]!==ye||e[110]!==Ie?(ve=s.jsxs(Rt,{children:[ye,Ie]}),e[109]=ye,e[110]=Ie,e[111]=ve):ve=e[111];let Fe;e[112]!==n?(Fe=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[112]=n,e[113]=Fe):Fe=e[113];let Ce;e[114]!==u?(Ce=s.jsx(I,{name:"equalizer-2",className:u}),e[114]=u,e[115]=Ce):Ce=e[115];let ne;e[116]!==m||e[117]!==Fe||e[118]!==Ce?(ne=s.jsx(Et,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":Fe,children:Ce})})}),e[116]=m,e[117]=Fe,e[118]=Ce,e[119]=ne):ne=e[119];let P;e[120]!==n?(P=n("sessions.sidebar.header.displayMode.label"),e[120]=n,e[121]=P):P=e[121];let me;e[122]!==P?(me=s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:P})}),e[122]=P,e[123]=me):me=e[123];let oe;e[124]!==ne||e[125]!==me?(oe=s.jsxs(Rt,{children:[ne,me]}),e[124]=ne,e[125]=me,e[126]=oe):oe=e[126];let Be;e[127]!==v||e[128]!==C||e[129]!==n?(Be=F?s.jsxs(s.Fragment,{children:[s.jsxs(bs,{onClick:()=>C("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),v==="default"?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(bs,{onClick:()=>C("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),v==="minimal"?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[127]=v,e[128]=C,e[129]=n,e[130]=Be):Be=e[130];let Ue;e[131]!==A||e[132]!==o||e[133]!==D||e[134]!==n||e[135]!==T||e[136]!==O?(Ue=o?s.jsxs(s.Fragment,{children:[F?s.jsx(Rr,{}):null,s.jsxs(bs,{onClick:O,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showRecent")}),D?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(bs,{onClick:T,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),A?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[131]=A,e[132]=o,e[133]=D,e[134]=n,e[135]=T,e[136]=O,e[137]=Ue):Ue=e[137];let Ke;e[138]===Symbol.for("react.memo_cache_sentinel")?(Ke=s.jsx(Rr,{}),e[138]=Ke):Ke=e[138];let Qe;e[139]===Symbol.for("react.memo_cache_sentinel")?(Qe=s.jsx(I,{name:"contract-up-down",className:"h-4 w-4"}),e[139]=Qe):Qe=e[139];let rt;e[140]!==n?(rt=n("sessions.sidebar.header.displayMode.collapseAll"),e[140]=n,e[141]=rt):rt=e[141];let pt;e[142]!==rt?(pt=s.jsx("span",{children:rt}),e[142]=rt,e[143]=pt):pt=e[143];let jt;e[144]!==N||e[145]!==pt?(jt=s.jsxs(bs,{onClick:N,className:"flex items-center gap-2",children:[Qe,pt]}),e[144]=N,e[145]=pt,e[146]=jt):jt=e[146];let Ve;e[147]===Symbol.for("react.memo_cache_sentinel")?(Ve=s.jsx(I,{name:"expand-up-down",className:"h-4 w-4"}),e[147]=Ve):Ve=e[147];let Ze;e[148]!==n?(Ze=n("sessions.sidebar.header.displayMode.expandAll"),e[148]=n,e[149]=Ze):Ze=e[149];let nt;e[150]!==Ze?(nt=s.jsx("span",{children:Ze}),e[150]=Ze,e[151]=nt):nt=e[151];let St;e[152]!==w||e[153]!==nt?(St=s.jsxs(bs,{onClick:w,className:"flex items-center gap-2",children:[Ve,nt]}),e[152]=w,e[153]=nt,e[154]=St):St=e[154];let Dt;e[155]!==Be||e[156]!==Ue||e[157]!==jt||e[158]!==St?(Dt=s.jsxs(sn,{align:"end",className:"min-w-[160px]",children:[Be,Ue,Ke,jt,St]}),e[155]=Be,e[156]=Ue,e[157]=jt,e[158]=St,e[159]=Dt):Dt=e[159];let wt;e[160]!==oe||e[161]!==Dt?(wt=s.jsxs(nn,{children:[oe,Dt]}),e[160]=oe,e[161]=Dt,e[162]=wt):wt=e[162];let ot;e[163]!==W||e[164]!==ve||e[165]!==wt?(ot=s.jsxs("div",{className:"flex items-center gap-1.5",children:[W,ve,wt]}),e[163]=W,e[164]=ve,e[165]=wt,e[166]=ot):ot=e[166];let at;e[167]!==ge||e[168]!==ot?(at=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[ge,ot]}),e[167]=ge,e[168]=ot,e[169]=at):at=e[169];let Kt;e[170]!==b||e[171]!==f||e[172]!==h||e[173]!==y||e[174]!==p||e[175]!==g||e[176]!==x||e[177]!==n?(Kt=f?s.jsxs("div",{className:"pb-1",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:[b?s.jsx("span",{children:h===1?n("sessions.sidebar.header.search.matchCountSingle",{count:h}):n("sessions.sidebar.header.search.matchCountPlural",{count:h})}):s.jsx("span",{}),s.jsx("span",{children:n("sessions.sidebar.header.search.escapeHint")})]}),s.jsxs("div",{className:"relative",children:[s.jsx(I,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:y,value:p,onChange:$t=>x($t.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:$t=>{$t.key==="Escape"&&($t.stopPropagation(),b?x(""):g(!1))}}),p.length>0?s.jsx("button",{type:"button",onClick:()=>x(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":n("sessions.sidebar.header.search.clear"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[170]=b,e[171]=f,e[172]=h,e[173]=y,e[174]=p,e[175]=g,e[176]=x,e[177]=n,e[178]=Kt):Kt=e[178];let is;return e[179]!==at||e[180]!==Kt?(is=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:[at,Kt]})}),e[179]=at,e[180]=Kt,e[181]=is):is=e[181],is}function vN(t){return!t}function jN(t){return t.toggleArchivedSessions}function SN(t){return t.toggleRecentSection}function NN(t){return t.setDisplayMode}function kN(t){return t.showArchivedSessions}function CN(t){return t.showRecentSection}function AN(t){return t.displayMode}const nf=7;function DN({sections:t,renderSessionNode:e,currentSessionId:n,editingId:r,openSidebarMenuKey:o,variant:a="section",initialVisibleCount:c=nf,batchSize:l=nf}){const{t:d}=kt(),[u,m]=i.useState(new Set),[f,g]=i.useState(new Map),y=a==="flat",p=i.useCallback(w=>{g(S=>{if(!S.has(w))return S;const j=new Map(S);return j.delete(w),j})},[]),x=i.useCallback(w=>{p(w),m(S=>{const j=new Set(S);return j.has(w)?j.delete(w):j.add(w),j})},[p]),b=i.useCallback((w,S,j)=>{g(k=>{const v=Math.min(j,S+l),D=new Map(k);return D.set(w,v),D})},[l]),h=i.useCallback(w=>{const S=new Set;Gi(w,n,S);const j=new Set;Gi(w,r,j);const k=Fo(w,o,"recent",!1),v=new WeakMap,D=C=>{v.set(C,Ra(C)),C.children.forEach(D)};w.forEach(D);const A=C=>({subtreeContainsActive:S,subtreeContainsEditing:j,menuOpenSessionId:k,nodeStructureKey:v.get(C)??"",childRenderExtrasFor:A});return C=>({subtreeContainsActive:S,subtreeContainsEditing:j,menuOpenSessionId:k,nodeStructureKey:v.get(C)??"",childRenderExtrasFor:A})},[n,r,o]),N=t.filter(w=>w.items.length>0);return N.length===0?null:s.jsx("div",{className:De(y?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1"),children:N.map(w=>{const S=u.has(w.key),j=Math.max(c,f.get(w.key)??c),k=w.items.slice(0,j),v=w.items.length-k.length,D=!y&&w.items.length>c&&v===0,A=h(k.map(O=>O.node)),C=O=>e(O.node,0,O.groupDirectory,O.projectId,!1,O.secondaryMeta,"recent",A(O.node));return y?s.jsxs("div",{className:"space-y-0.5",children:[k.map(C),v>0?s.jsx("button",{type:"button",onClick:()=>b(w.key,k.length,w.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showMore")}):null]},w.key):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("button",{type:"button",onClick:()=>x(w.key),className:"group flex w-full items-center gap-1 rounded-md px-0.5 py-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-expanded":!S,children:[s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground",children:S?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"text-[14px] font-normal text-foreground/95",children:w.title})]}),S?null:s.jsxs("div",{className:De("space-y-0.5 pl-7"),children:[k.map(C),v>0?s.jsx("button",{type:"button",onClick:()=>b(w.key,k.length,w.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showMore")}):null,D?s.jsx("button",{type:"button",onClick:()=>p(w.key),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showFewer")}):null]})]},w.key)})})}const Pl="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 IN(t){const e=gt.c(13),{onOpenSettings:n,onOpenShortcuts:r,onOpenAbout:o,onOpenUpdate:a,showRuntimeButtons:c,showUpdateButton:l}=t,d=c===void 0?!0:c,u=l===void 0?!0:l,{t:m}=kt();let f;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==d||e[4]!==m?(f=d?s.jsxs(s.Fragment,{children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Pl,"aria-label":m("sessions.sidebar.footer.actions.settings"),children:s.jsx(I,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(Mt,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:Pl,"aria-label":m("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(I,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(Mt,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:Pl,"aria-label":m("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(I,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(Mt,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=m,e[5]=f):f=e[5];let g;e[6]!==a||e[7]!==u||e[8]!==m?(g=u?s.jsx($e,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:a,children:m("sessions.sidebar.footer.actions.update")}):null,e[6]=a,e[7]=u,e[8]=m,e[9]=g):g=e[9];let y;return e[10]!==f||e[11]!==g?(y=s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-2.5 py-2",children:[f,g]}),e[10]=f,e[11]=g,e[12]=y):y=e[12],y}const PN=t=>{const e=gt.c(58),{id:n,projectLabel:r,projectDescription:o,projectIcon:a,projectColor:c,projectIconImage:l,projectIconBackground:d,isCollapsed:u,isActiveProject:m,isRepo:f,isDesktopShell:g,isStuck:y,hideDirectoryControls:p,alwaysShowActions:x,onToggle:b,onNewSession:h,onNewWorktreeSession:N,onRenameStart:w,onClose:S,sentinelRef:j,children:k,showCreateButtons:v,hideHeader:D,openSidebarMenuKey:A,setOpenSidebarMenuKey:C}=t,O=v===void 0?!0:v,T=D===void 0?!1:D,{t:E}=kt(),{currentTheme:F}=Gr();let R;e[0]!==n?(R={id:n},e[0]=n,e[1]=R):R=e[1];const{attributes:L,listeners:B,setNodeRef:V,transform:M,transition:Z,isDragging:se}=oc(R),Q=i.useRef(!1),K=`project:${n}`,ee=A===K,[re,he]=i.useState(!1),je=a?kc[a]:null,te=c?Ga[c]??null:null;let Ne;e[2]!==K||e[3]!==C?(Ne=ce=>{ce&&he(!1),C(ce?K:null)},e[2]=K,e[3]=C,e[4]=Ne):Ne=e[4];const J=Ne;let H;e[5]!==p||e[6]!==f||e[7]!==S||e[8]!==h||e[9]!==w||e[10]!==O||e[11]!==E?(H=ce=>s.jsxs(s.Fragment,{children:[O&&!f&&!p&&h&&s.jsxs(ce,{onClick:h,children:[s.jsx(I,{name:"add",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.newSession")]}),s.jsxs(ce,{onClick:w,children:[s.jsx(I,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.session.menu.rename")]}),s.jsxs(ce,{onClick:S,className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.closeProject")]})]}),e[5]=p,e[6]=f,e[7]=S,e[8]=h,e[9]=w,e[10]=O,e[11]=E,e[12]=H):H=e[12];const q=H,ae=EN,le=MN,Se=FN;let Re;e[13]===Symbol.for("react.memo_cache_sentinel")?(Re=ce=>{(ce.button===2||ce.button===0&&ce.ctrlKey)&&(Q.current=!0)},e[13]=Re):Re=e[13];const _e=Re;let Oe;e[14]!==b?(Oe=()=>{if(Q.current){Q.current=!1;return}b()},e[14]=b,e[15]=Oe):Oe=e[15];const Me=Oe;let ge;e[16]!==M?(ge=ac.Transform.toString(M),e[16]=M,e[17]=ge):ge=e[17];let Ae;e[18]!==ge||e[19]!==Z?(Ae={transform:ge,transition:Z},e[18]=ge,e[19]=Z,e[20]=Ae):Ae=e[20];const pe=se&&"opacity-30";let ue;e[21]!==pe?(ue=De("relative",pe),e[21]=pe,e[22]=ue):ue=e[22];let G;e[23]!==x||e[24]!==L||e[25]!==F||e[26]!==J||e[27]!==Me||e[28]!==p||e[29]!==T||e[30]!==te||e[31]!==n||e[32]!==m||e[33]!==u||e[34]!==re||e[35]!==g||e[36]!==ee||e[37]!==f||e[38]!==y||e[39]!==B||e[40]!==h||e[41]!==N||e[42]!==o||e[43]!==d||e[44]!==l||e[45]!==je||e[46]!==r||e[47]!==q||e[48]!==j||e[49]!==O||e[50]!==E?(G=T?null:s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{ref:j,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsxs(Pc,{open:re,onOpenChange:he,children:[s.jsx(Ic,{render:s.jsx("div",{className:De("w-full text-left group/project select-none"),style:{backgroundColor:g&&y?"transparent":void 0},onContextMenu:ce=>{p||(ce.preventDefault(),he(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...L,children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:_e,onClick:Me,...B,className:De("flex-1 min-w-0 flex items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing transition-[padding]",f&&!p?x?"pr-20":"pr-7 group-hover/project:pr-20 group-focus-within/project:pr-20":x?"pr-14":"pr-7 group-hover/project:pr-14 group-focus-within/project:pr-14"),children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:[s.jsx("span",{className:De("h-3.5 w-3.5 items-center justify-center text-muted-foreground",x?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:u?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),l?s.jsx("span",{className:De("h-3.5 w-3.5 items-center justify-center overflow-hidden rounded-[3px]",x?"hidden":"inline-flex group-hover/project:hidden group-focus-within/project:hidden"),style:d?{backgroundColor:d}:void 0,children:s.jsx(Ka,{project:{id:n,iconImage:l},options:{themeVariant:F.metadata.variant,iconColor:F.colors.surface.foreground},className:"h-full w-full object-contain",fallback:je?s.jsx(I,{name:je,className:"h-3.5 w-3.5",style:te?{color:te}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:te?{color:te}:void 0})})}):je?s.jsx(I,{name:je,className:De("h-3.5 w-3.5",x?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:te?{color:te}:void 0}):s.jsx(I,{name:"folder",className:De("h-3.5 w-3.5 text-muted-foreground/80",x?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:te?{color:te}:void 0})]}),s.jsx("span",{className:De("text-[14px] font-normal truncate lowercase",m?"text-foreground":"text-foreground group-hover/project:text-foreground"),children:r})]})}),s.jsx(Mt,{side:"right",sideOffset:8,children:o})]}),s.jsxs("div",{className:De("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",O?"right-7":"right-0.5"),children:[O&&f&&!p&&N?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),N()},className:De("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground transition-opacity",x?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E("sessions.sidebar.project.actions.newWorktree"),children:s.jsx(I,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,p?null:s.jsxs(nn,{open:ee,onOpenChange:J,children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:De("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",ee?"opacity-100 pointer-events-auto":x?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E("sessions.sidebar.project.actions.projectMenu"),onPointerDown:le,onMouseDown:Se,onClick:ae,children:s.jsx(I,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(sn,{align:"end",className:"min-w-[180px]",children:q(bs)})]})]}),O&&h?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),h()},className:De("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",x?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E(f?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession"),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})}),s.jsx(Mt,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E(f?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(Ac,{className:"min-w-[180px]",children:q(Dc)})]})]}),e[23]=x,e[24]=L,e[25]=F,e[26]=J,e[27]=Me,e[28]=p,e[29]=T,e[30]=te,e[31]=n,e[32]=m,e[33]=u,e[34]=re,e[35]=g,e[36]=ee,e[37]=f,e[38]=y,e[39]=B,e[40]=h,e[41]=N,e[42]=o,e[43]=d,e[44]=l,e[45]=je,e[46]=r,e[47]=q,e[48]=j,e[49]=O,e[50]=E,e[51]=G):G=e[51];let fe;return e[52]!==k||e[53]!==V||e[54]!==ue||e[55]!==G||e[56]!==Ae?(fe=s.jsxs("div",{ref:V,style:Ae,className:ue,children:[G,k]}),e[52]=k,e[53]=V,e[54]=ue,e[55]=G,e[56]=Ae,e[57]=fe):fe=e[57],fe},TN=t=>{const e=gt.c(21),{id:n,disabled:r,children:o}=t,a=r===void 0?!1:r;let c;e[0]!==a||e[1]!==n?(c={id:n,disabled:a},e[0]=a,e[1]=n,e[2]=c):c=e[2];const{listeners:l,setNodeRef:d,setActivatorNodeRef:u,transform:m,transition:f,isDragging:g}=oc(c);let y;e[3]!==l||e[4]!==u?(y={listeners:l,setActivatorNodeRef:u},e[3]=l,e[4]=u,e[5]=y):y=e[5];const p=y;let x;e[6]!==m?(x=ac.Transform.toString(m),e[6]=m,e[7]=x):x=e[7];let b;e[8]!==x||e[9]!==f?(b={transform:x,transition:f},e[8]=x,e[9]=f,e[10]=b):b=e[10];const h=g&&"opacity-50";let N;e[11]!==h?(N=De("space-y-0.5 rounded-md",h),e[11]=h,e[12]=N):N=e[12];let w;e[13]!==o||e[14]!==p?(w=typeof o=="function"?o(p):o,e[13]=o,e[14]=p,e[15]=w):w=e[15];let S;return e[16]!==d||e[17]!==b||e[18]!==N||e[19]!==w?(S=s.jsx("div",{ref:d,style:b,className:N,children:w}),e[16]=d,e[17]=b,e[18]=N,e[19]=w,e[20]=S):S=e[20],S},RN=i.memo(TN);function EN(t){t.stopPropagation()}function MN(t){t.stopPropagation()}function FN(t){t.stopPropagation()}function LN(t){const{t:e}=kt(),n=ga(yo(xa,{activationConstraint:{distance:8}}),yo($h,{coordinateGetter:_h})),r=ga(yo(xa,{activationConstraint:{distance:8}})),o=i.useRef(null),a=i.useRef(new Map),c=(l,d)=>{const u=a.current,m=u.get(l);if(m&&m.groups===d)return m.ordered;const f=t.getOrderedGroups(l,d);if(u.set(l,{groups:d,ordered:f}),u.size>256){const g=u.keys().next().value;g!==void 0&&u.delete(g)}return f};return t.sharedSessionsOnly?s.jsxs(Wn,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:De("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(Wn,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:De("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.emptyState]}):t.sectionsForRender.length===0?s.jsx(Wn,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:De("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:t.searchEmptyState}):s.jsxs(Wn,{ref:o,useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:De("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const l=t.sectionsForRender.find(f=>f.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!l)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const d=l.groups.find(f=>f.isMain&&f.sessions.length>0)??l.groups.find(f=>f.sessions.length>0)??l.groups.find(f=>f.isMain)??l.groups[0];if(!d)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")});const u=l.groups.find(f=>f.isArchivedBucket);return[d,...u&&u.id!==d.id?[u]:[]].map(f=>{const g=`${l.project.id}:${f.id}`,y=f.id===d.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(f,g,l.project.id,y,null,!0,o)},g)})})()}):s.jsx(s.Fragment,{children:s.jsxs(ba,{sensors:n,collisionDetection:ya,onDragEnd:l=>{if(t.isInlineEditing)return;const{active:d,over:u}=l;if(!u||d.id===u.id)return;const m=t.sectionsForRender.findIndex(g=>g.project.id===d.id),f=t.sectionsForRender.findIndex(g=>g.project.id===u.id);m===-1||f===-1||m===f||t.reorderProjects(m,f)},children:[s.jsx(Ll,{items:t.sectionsForRender.map(l=>l.project.id),strategy:Ol,children:t.sectionsForRender.map(l=>{const d=l.project,u=d.id,m=gm(d.label?.trim()||Ei(d.normalizedPath,t.homeDirectory)||d.normalizedPath),f=Na(d.normalizedPath,t.homeDirectory),g=t.collapsedProjects.has(u),y=u===t.activeProjectId,p=t.projectRepoStatus.get(u),x=c(u,l.groups),b=x.find(N=>N.isMain)??null,h=b?x.filter(N=>N.id!==b.id):x;return s.jsx(PN,{id:u,projectLabel:m,projectDescription:f,projectIcon:d.icon,projectColor:d.color,projectIconImage:d.iconImage,projectIconBackground:d.iconBackground,isCollapsed:g,isActiveProject:y,isRepo:!!p,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(u),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,alwaysShowActions:t.alwaysShowActions,onToggle:()=>t.toggleProject(u),onNewSession:()=>{u!==t.activeProjectId&&t.setActiveProjectIdOnly(u),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:d.normalizedPath})},onNewWorktreeSession:()=>{u!==t.activeProjectId&&t.setActiveProjectIdOnly(u),t.setActiveMainTab("chat"),t.openNewWorktreeDialog()},onRenameStart:()=>t.openProjectEditDialog(u),onClose:()=>t.removeProject(u),sentinelRef:N=>{t.projectHeaderSentinelRefs.current.set(u,N)},showCreateButtons:!0,openSidebarMenuKey:t.openSidebarMenuKey,setOpenSidebarMenuKey:t.setOpenSidebarMenuKey,children:g?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:l.groups.length>0?s.jsxs(ba,{sensors:r,collisionDetection:ya,onDragEnd:N=>{if(t.isInlineEditing)return;const{active:w,over:S}=N;if(!S||w.id===S.id)return;const j=h.findIndex(A=>A.id===w.id),k=h.findIndex(A=>A.id===S.id);if(j===-1||k===-1||j===k)return;const v=kf(h,j,k).map(A=>A.id),D=b?[b.id,...v]:v;t.setGroupOrderByProject(A=>{const C=new Map(A);return C.set(u,D),C})},children:[b?t.renderGroupSessions(b,`${u}:${b.id}`,u,!0,null,void 0,o):null,s.jsx(Ll,{items:h.map(N=>N.id),strategy:Ol,children:h.map(N=>{const w=`${u}:${N.id}`;return s.jsx(RN,{id:N.id,disabled:t.isInlineEditing,children:S=>t.renderGroupSessions(N,w,u,!1,S,void 0,o)},N.id)})}),s.jsx(Vl,{dropAnimation:null})]}):s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")})})},u)})}),s.jsx(Vl,{dropAnimation:null})]})})]})}function ON(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(Zi(),{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 BN(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 VN(t){const e=t.info.role==="user"?"User":"Assistant",n=ON(t.info.time?.created),r=BN(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
170
-
171
- *${o}*`:`**${e}**`}function _N(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function rh(t){const e=VN(t),n=_N(t.parts).trim();return n?`${e}
172
-
173
- ${n}`:""}function ih(t,e){const n="#".repeat(Math.min(e+1,6)),r=t.agent?` — ${t.agent}`:"",o=`${n} Sub-agent: ${t.title}${r}
174
-
175
- ---
176
-
177
- `,a=t.records.map(rh).filter(Boolean).join(`
178
-
179
- ---
180
-
181
- `),c=[o+a];for(const l of t.children)c.push(ih(l,e+1));return c.join(`
182
-
183
- ---
184
-
185
- `)}function $N(t,e,n){const r=e?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
186
-
187
- *Exported on ${o}*
188
-
189
- ---
190
-
191
- `,c=t.map(rh).filter(Boolean).join(`
192
-
193
- ---
194
-
195
- `);let l=a+c;if(n&&n.length>0){const d=n.map(u=>ih(u,1)).join(`
196
-
197
- ---
198
-
199
- `);l+=`
200
-
201
- ---
202
-
203
- `+d}return l}function zN(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 WN(t,e){const n=await rp(e,t);if(n)return n;if(!Hr())return null;try{const r=await Lo()?.vscode?.saveMarkdown?.({fileName:e,content:t});if(!r||r.saved!==!0)return null;const o=typeof r.path=="string"?r.path.trim():"";return o.length>0?o:null}catch{return null}}async function UN(t){const e=Lo()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await ip(t)?!0:wa(t)}function HN(){return vc()}function GN(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 KN=(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},$n=io()((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 g of m)c.delete(g);d===n&&(d=null)}else{for(const g of m)c.add(g);d=n}c.size===0?t({selectedIds:c,scopeKey:null,anchorId:null}):t({selectedIds:c,scopeKey:l,anchorId:d})},setRange:(n,r,o,a,c)=>{const l=e();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),m=o.indexOf(r);if(u<0||m<0)return;const[f,g]=u<=m?[u,m]:[m,u],y=o.slice(f,g+1),p=KN(y,c),b=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const h of p)b.add(h);t({selectedIds:b,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}))}})),qN=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,oh=/^g[1-9]\d*$/,xo=(t,e,n,r,o)=>{if(!qN.test(t)||e!==void 0&&!oh.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}},ha=t=>{if(!t)return null;const e=t.split("/");if(e.length<3||e.length>5)return null;const[n]=e;if(e.length===3)return xo(n,void 0,e[1],e[2],void 0);if(e.length===4){const[,l,d,u]=e;return oh.test(l)?xo(n,l,d,u,void 0):xo(n,void 0,l,d,u)}const[,r,o,a,c]=e;return r===""?xo(n,void 0,o,a,c):xo(n,r,o,a,c)},YN=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("/")},QN=(t,e,n,r)=>{const o=[t];return r&&o.push(r),o.push(e,n,"fusion"),o.join("/")},ah=t=>{const e=gt.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=kt(),u=ss(JN),m=ss(XN),f=ss(ZN);let g;e[0]!==u?(g=u(),e[0]=u,e[1]=g):g=e[1];const y=g;let p;e[2]!==y?(p=y.filter(e2),e[2]=y,e[3]=p):p=e[3];const x=p;let b,h;e[4]!==y.length||e[5]!==m?(b=()=>{y.length===0&&m()},h=[y.length,m],e[4]=y.length,e[5]=m,e[6]=b,e[7]=h):(b=e[6],h=e[7]),i.useEffect(b,h);let N,w;e[8]!==f||e[9]!==a||e[10]!==r||e[11]!==x||e[12]!==n?(N=()=>{if(a)return;const T=n.trim();if(T.length>0&&x.some(R=>R.name===T))return;const E=typeof f=="string"&&f.trim().length>0?f.trim():null;if(E&&x.some(R=>R.name===E)){r(E);return}const F=x[0]?.name;F&&r(F)},w=[f,a,r,x,n],e[8]=f,e[9]=a,e[10]=r,e[11]=x,e[12]=n,e[13]=N,e[14]=w):(N=e[13],w=e[14]),i.useEffect(N,w);const S=n.trim().length>0?n:void 0;let j;e[15]!==o?(j=De("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]=j):j=e[16];let k;e[17]!==d?(k=d("multirun.agentSelector.placeholder"),e[17]=d,e[18]=k):k=e[18];let v;e[19]!==k?(v=s.jsx(Cn,{placeholder:k}),e[19]=k,e[20]=v):v=e[20];let D;e[21]!==c||e[22]!==j||e[23]!==v?(D=s.jsx(Hn,{id:c,size:"lg",className:j,children:v}),e[21]=c,e[22]=j,e[23]=v,e[24]=D):D=e[24];let A;e[25]!==x?(A=x.length>0&&s.jsx($l,{children:x.map(t2)}),e[25]=x,e[26]=A):A=e[26];let C;e[27]!==l||e[28]!==A?(C=s.jsx(Gn,{fitContent:!0,portalToBody:l,children:A}),e[27]=l,e[28]=A,e[29]=C):C=e[29];let O;return e[30]!==a||e[31]!==r||e[32]!==S||e[33]!==D||e[34]!==C?(O=s.jsxs(Un,{value:S,onValueChange:r,disabled:a,children:[D,C]}),e[30]=a,e[31]=r,e[32]=S,e[33]=D,e[34]=C,e[35]=O):O=e[35],O};function JN(t){return t.getVisibleAgents}function XN(t){return t.loadAgents}function ZN(t){return t.currentAgentName}function e2(t){return gc(t.mode)}function t2(t){return s.jsx(Ts,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const lh="h-7",Ao=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,s2=t=>{const e=gt.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=De("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",lh),e[0]=d):d=e[0];let u;e[1]!==n.providerID?(u=s.jsx(Do,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=u):u=e[2];let m;e[3]!==l?(m=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=m):m=e[4];let f;e[5]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(I,{name:"close",className:"h-3.5 w-3.5"}),e[5]=f):f=e[5];let g;e[6]!==a?(g=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:f}),e[6]=a,e[7]=g):g=e[7];let y;return e[8]!==u||e[9]!==m||e[10]!==g?(y=s.jsxs("div",{className:d,children:[u,m,g]}),e[8]=u,e[9]=m,e[10]=g,e[11]=y):y=e[11],y},ch=t=>{const e=gt.c(118),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:u,addButtonClassName:m,dropdownSide:f,dropdownClassName:g,containerClassName:y,triggerIcon:p}=t,x=d===void 0?!0:d,b=f===void 0?"top":f,{t:h}=kt(),N=ss(n2),w=ss(r2),S=Ee(i2),j=Ee(o2),{favoriteModelsList:k,recentModelsList:v}=yg(),D=Ee(a2),[A,C]=i.useState(!1),[O,T]=i.useState(""),[E,F]=i.useState(null),R=i.useRef(null),L=i.useRef(null),B=u===1,V=u===void 0||n.length<u||B;let M;if(e[0]!==n){M=new Map;for(const P of n){const me=`${P.providerID}:${P.modelID}`;M.set(me,(M.get(me)||0)+1)}e[0]=n,e[1]=M}else M=e[1];const Z=M;let se;e[2]!==n?(se=P=>n.filter(oe=>oe.providerID===P.providerID&&oe.modelID===P.modelID).findIndex(oe=>oe.instanceId===P.instanceId)+1,e[2]=n,e[3]=se):se=e[3];const Q=se;let K,ee;e[4]!==b||e[5]!==A?(K=()=>{if(!A||!L.current)return;const P=L.current.getBoundingClientRect();if(b==="bottom"){const Qe=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-P.bottom-16-112;F(Math.max(160,Math.min(320,Qe)));return}let me=L.current.parentElement;for(;me&&!(me.getAttribute("role")==="dialog"||me.hasAttribute("data-scroll-shadow"));){const Ue=getComputedStyle(me);if(Ue.overflow==="auto"||Ue.overflow==="hidden"||Ue.overflowY==="auto"||Ue.overflowY==="hidden")break;me=me.parentElement}const oe=me?me.getBoundingClientRect().top:0,Be=P.top-oe-16;F(Math.max(150,Math.min(300,Be)))},ee=[b,A],e[4]=b,e[5]=A,e[6]=K,e[7]=ee):(K=e[6],ee=e[7]),i.useEffect(K,ee);let re,he;e[8]!==V||e[9]!==A?(re=()=>{!V&&A&&(C(!1),T(""))},he=[V,A],e[8]=V,e[9]=A,e[10]=re,e[11]=he):(re=e[10],he=e[11]),i.useEffect(re,he);let je,te;e[12]!==A?(je=()=>{if(!A)return;const P=me=>{R.current&&!R.current.contains(me.target)&&(C(!1),T(""))};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},te=[A],e[12]=A,e[13]=je,e[14]=te):(je=e[13],te=e[14]),i.useEffect(je,te);let Ne;e[15]!==B||e[16]!==r||e[17]!==a||e[18]!==n.length?(Ne=P=>{const me={providerID:P.providerID,modelID:P.modelID,displayName:P.model.name||P.modelID,instanceId:Ao()};B&&n.length>0&&a?a(0,me):r(me),B&&(C(!1),T(""))},e[15]=B,e[16]=r,e[17]=a,e[18]=n.length,e[19]=Ne):Ne=e[19];const J=Ne;let H;e[20]!==h?(H=h("multirun.modelMultiSelect.search.placeholder"),e[20]=h,e[21]=H):H=e[21];let q;e[22]!==h?(q=h("multirun.modelMultiSelect.search.noResults"),e[22]=h,e[23]=q):q=e[23];let ae;e[24]!==h?(ae=h("multirun.modelMultiSelect.sections.favorites"),e[24]=h,e[25]=ae):ae=e[25];let le;e[26]!==h?(le=h("multirun.modelMultiSelect.sections.recent"),e[26]=h,e[27]=le):le=e[27];let Se;e[28]!==h?(Se=h("multirun.modelMultiSelect.keyboard.hint"),e[28]=h,e[29]=Se):Se=e[29];let Re;e[30]!==h?(Re=h("settings.agents.modelSelector.actions.favorite"),e[30]=h,e[31]=Re):Re=e[31];let _e;e[32]!==h?(_e=h("settings.agents.modelSelector.actions.unfavorite"),e[32]=h,e[33]=_e):_e=e[33];let Oe;e[34]!==h?(Oe=h("chat.modelControls.capabilities"),e[34]=h,e[35]=Oe):Oe=e[35];let Me;e[36]!==h?(Me=h("chat.modelControls.capability.toolCalling"),e[36]=h,e[37]=Me):Me=e[37];let ge;e[38]!==h?(ge=h("chat.modelControls.capability.reasoning"),e[38]=h,e[39]=ge):ge=e[39];let Ae;e[40]!==h?(Ae=h("chat.modelControls.input"),e[40]=h,e[41]=Ae):Ae=e[41];let pe;e[42]!==h?(pe=h("chat.modelControls.output"),e[42]=h,e[43]=pe):pe=e[43];let ue;e[44]!==h?(ue=h("chat.modelControls.costPerMillion"),e[44]=h,e[45]=ue):ue=e[45];let G;e[46]!==H||e[47]!==q||e[48]!==ae||e[49]!==le||e[50]!==Se||e[51]!==Re||e[52]!==_e||e[53]!==Oe||e[54]!==Me||e[55]!==ge||e[56]!==Ae||e[57]!==pe||e[58]!==ue?(G={searchPlaceholder:H,noResults:q,favorites:ae,recent:le,keyboardHint:Se,favorite:Re,unfavorite:_e,capabilities:Oe,capabilityToolCalling:Me,capabilityReasoning:ge,input:Ae,output:pe,costPerMillion:ue},e[46]=H,e[47]=q,e[48]=ae,e[49]=le,e[50]=Se,e[51]=Re,e[52]=_e,e[53]=Oe,e[54]=Me,e[55]=ge,e[56]=Ae,e[57]=pe,e[58]=ue,e[59]=G):G=e[59];const fe=G;let ce;e[60]!==y?(ce=De("relative",y),e[60]=y,e[61]=ce):ce=e[61];let W;e[62]!==m?(W=De(lh,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",m),e[62]=m,e[63]=W):W=e[63];const z=!V;let be;e[64]!==A?(be=()=>{C(!A)},e[64]=A,e[65]=be):be=e[65];let xe;e[66]!==p?(xe=p??s.jsx(I,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=p,e[67]=xe):xe=e[67];let _;e[68]!==l||e[69]!==h?(_=l??h("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=h,e[70]=_):_=e[70];let ye;e[71]!==W||e[72]!==z||e[73]!==be||e[74]!==xe||e[75]!==_?(ye=s.jsxs($e,{ref:L,type:"button",variant:"outline",size:"sm",className:W,disabled:z,onClick:be,children:[xe,_]}),e[71]=W,e[72]=z,e[73]=be,e[74]=xe,e[75]=_,e[76]=ye):ye=e[76];let $;e[77]!==E||e[78]!==V||e[79]!==g||e[80]!==b||e[81]!==k||e[82]!==J||e[83]!==D||e[84]!==j||e[85]!==A||e[86]!==fe||e[87]!==Z||e[88]!==w||e[89]!==N||e[90]!==v||e[91]!==O||e[92]!==S?($=A?s.jsx("div",{className:De("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",b==="top"?"bottom-full mb-1":"top-full mt-1",g),style:{background:"linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))"},children:s.jsx(wg,{providers:N,favoriteModels:k,recentModels:v,modelsMetadata:w,hiddenModels:D,searchQuery:O,onSearchQueryChange:T,onSelect:J,labels:fe,selectionCount:P=>Z.get(`${P.providerID}:${P.modelID}`)||0,disabled:!V,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:E?`${E}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:A,isFavorite:P=>j(P.providerID,P.modelID),onToggleFavorite:P=>S(P.providerID,P.modelID),onEscape:()=>{C(!1),T("")}})}):null,e[77]=E,e[78]=V,e[79]=g,e[80]=b,e[81]=k,e[82]=J,e[83]=D,e[84]=j,e[85]=A,e[86]=fe,e[87]=Z,e[88]=w,e[89]=N,e[90]=v,e[91]=O,e[92]=S,e[93]=$):$=e[93];let Ie;e[94]!==ce||e[95]!==ye||e[96]!==$?(Ie=s.jsxs("div",{className:ce,ref:R,children:[ye,$]}),e[94]=ce,e[95]=ye,e[96]=$,e[97]=Ie):Ie=e[97];let ve;e[98]!==Q||e[99]!==Z||e[100]!==o||e[101]!==a||e[102]!==N||e[103]!==n||e[104]!==x||e[105]!==h?(ve=x&&n.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:n.map((P,me)=>{const oe=`${P.providerID}:${P.modelID}`,Be=Z.get(oe)||1,Ue=Q(P),Qe=N.find(Ve=>Ve.id===P.providerID)?.models?.find(Ve=>Ve.id===P.modelID),rt=Qe?.variants?Object.keys(Qe.variants):[],pt=rt.length>0,jt=P.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(s2,{model:P,instanceIndex:Ue,totalSameModel:Be,onRemove:()=>o(me)}),pt&&s.jsxs(Un,{value:jt,onValueChange:Ve=>{if(!a)return;a(me,{...P,variant:Ve==="__default__"?void 0:Ve})},children:[s.jsxs(Hn,{size:"chip",className:"px-2 gap-1.5 rounded-md !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground",children:[s.jsx(I,{name:"brain-ai-3",className:De("h-3.5 w-3.5 flex-shrink-0",jt==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(Cn,{placeholder:h("multirun.modelMultiSelect.variant.placeholder"),children:Ve=>Ve==="__default__"?h("multirun.modelMultiSelect.variant.default"):Ve})]}),s.jsxs(Gn,{fitContent:!0,children:[s.jsx(Ts,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:h("multirun.modelMultiSelect.variant.default")}),rt.map(l2)]})]})]},P.instanceId)})}),e[98]=Q,e[99]=Z,e[100]=o,e[101]=a,e[102]=N,e[103]=n,e[104]=x,e[105]=h,e[106]=ve):ve=e[106];let Fe;e[107]!==Ie||e[108]!==ve?(Fe=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[Ie,ve]}),e[107]=Ie,e[108]=ve,e[109]=Fe):Fe=e[109];let Ce;e[110]!==u||e[111]!==c||e[112]!==n.length||e[113]!==h?(Ce=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:u!==void 0?h("multirun.modelMultiSelect.validation.minToMax",{min:c,max:u}):h("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[110]=u,e[111]=c,e[112]=n.length,e[113]=h,e[114]=Ce):Ce=e[114];let ne;return e[115]!==Fe||e[116]!==Ce?(ne=s.jsxs("div",{className:"space-y-2",children:[Fe,Ce]}),e[115]=Fe,e[116]=Ce,e[117]=ne):ne=e[117],ne};function n2(t){return t.providers}function r2(t){return t.modelsMetadata}function i2(t){return t.toggleFavoriteModel}function o2(t){return t.isFavoriteModel}function a2(t){return t.hiddenModels}function l2(t){return s.jsx(Ts,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const c2=(t,e,n)=>{const r=t.session.title?.trim()||t.session.id;return`
204
-
205
- --- RESULT ${n+1}: ${r} ---
206
- ${e.trim()}
207
- --- END RESULT ${n+1} ---`},rf=(t,e)=>ut.getState().getWorktreeMetadata(t)?.projectDirectory??e,d2=async t=>{const e=t.directory??void 0,n=vg(t.session.id,e);if(n.length===0&&t.directory){const o=(await zn.withDirectory(t.directory,()=>zn.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 Pd(c.parts??[]).trim()}return""}for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o.role==="assistant")return Pd(jg(o.id,e)).trim()}return""};function u2({session:t,open:e,onOpenChange:n}){const{t:r}=kt(),o=mc(),a=jr(V=>V.activeSessions),c=jr(V=>V.archivedSessions),l=ss(V=>V.providers),d=ss(V=>V.currentProviderId),u=ss(V=>V.currentModelId),m=ss(V=>V.currentAgentName),[f,g]=i.useState(d??""),[y,p]=i.useState(u??""),[x,b]=i.useState(()=>d&&u?[{providerID:d,modelID:u,instanceId:Ao()}]:[]),[h,N]=i.useState(""),[w,S]=i.useState(m??""),[j,k]=i.useState([]),[v,D]=i.useState(!1),A=i.useMemo(()=>ha(t.title),[t.title]),C=i.useMemo(()=>{const V=new Map;for(const M of o)V.set(M.id,M);for(const M of a)V.set(M.id,M);for(const M of c)V.set(M.id,M);return t.id&&V.set(t.id,t),Array.from(V.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!A)return;const V=ut.getState().getDirectoryForSession(t.id),M=rf(t.id,V),Z=C.map(se=>{const Q=ha(se.title);if(!Q||Q.groupSlug!==A.groupSlug||Q.fusion||(Q.runGroup??null)!==(A.runGroup??null))return null;const K=ut.getState().getDirectoryForSession(se.id)??Tr(se),ee=rf(se.id,K);return M&&ee&&M!==ee?null:{session:se,directory:K,projectDirectory:ee}}).filter(se=>se!==null).sort((se,Q)=>(se.session.time?.created??0)-(Q.session.time?.created??0));k(Z)},[C,e,A,t.id]);const T=l.find(V=>V.id===f)?.models.find(V=>V.id===y),E=T?.variants?Object.keys(T.variants):[],F=!!(A&&f&&y&&j.length>0&&!v),R=i.useCallback(V=>{b([V]),g(V.providerID),p(V.modelID),N("")},[]),L=x[0]?.displayName||x[0]?.modelID||r("multirun.fusion.model.placeholder"),B=async()=>{if(!(!A||!f||!y)){D(!0);try{const V=await Promise.all(j.map(re=>d2(re))),M=j.map((re,he)=>({source:re,text:V[he]??""})).filter(re=>re.text.trim().length>0);if(M.length===0){de.error(r("multirun.fusion.toast.noOutputs"));return}const Z=j[0]?.projectDirectory??j[0]?.directory??null,se=QN(A.groupSlug,f,y,A.runGroup),[Q,K]=await Promise.all([Fn("session.fusion.visible"),Fn("session.fusion.instructions")]),ee=await ut.getState().createSession(se,Z,null);if(!ee)throw new Error("Failed to create fusion session");ut.getState().setCurrentSession(ee.id,Z),n(!1),await zn.sendMessage({id:ee.id,providerID:f,modelID:y,variant:h||void 0,agent:w||void 0,text:Q,additionalParts:[{text:K,synthetic:!0},...M.map((re,he)=>({text:c2(re.source,re.text,he),synthetic:!0})),{text:`
208
-
209
- --- FUSION INPUTS END ---
210
- Now write the final fused answer.`,synthetic:!0}],directory:Z??zn.getDirectory()})}catch(V){console.error("[MultiRunFusion] Failed to start fusion",V),de.error(r("multirun.fusion.toast.failed"))}finally{D(!1)}}};return s.jsx(Os,{open:e,onOpenChange:n,children:s.jsxs(Ls,{className:"max-w-xl overflow-visible",children:[s.jsxs(Us,{children:[s.jsx(_s,{children:r("multirun.fusion.title")}),s.jsx(an,{children:r("multirun.fusion.description")})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("div",{className:"max-w-full",children:s.jsx(ch,{selectedModels:x,onAdd:R,onUpdate:(V,M)=>R(M),onRemove:()=>{b([]),g(""),p(""),N("")},maxModels:1,addButtonLabel:L,showChips:!1,addButtonClassName:"h-8 w-fit max-w-[min(28rem,calc(100vw-8rem))] justify-start rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5",dropdownSide:"bottom",dropdownClassName:"w-[min(28rem,calc(100vw-8rem))]",triggerIcon:f?s.jsx(Do,{providerId:f,className:"h-3.5 w-3.5 mr-1"}):void 0})}),E.length>0?s.jsxs(Un,{value:h||"__default__",onValueChange:V=>N(V==="__default__"?"":V),children:[s.jsxs(Hn,{size:"lg",className:"h-8 w-fit rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground px-3 py-1.5",children:[s.jsx(I,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(Cn,{children:V=>V==="__default__"?r("multirun.modelMultiSelect.variant.default"):V})]}),s.jsxs(Gn,{fitContent:!0,portalToBody:!0,children:[s.jsx(Ts,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),E.map(V=>s.jsx(Ts,{value:V,children:V},V))]})]}):null,s.jsx(ah,{value:w,onChange:S,portalToBody:!0,className:"h-8 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta font-medium text-foreground",children:r("multirun.fusion.sources.label",{count:j.length})}),s.jsx("div",{className:"max-h-56 space-y-1 overflow-auto rounded-lg border border-[var(--interactive-border)] p-1",children:j.map(V=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(Do,{providerId:ha(V.session.title)?.providerID??"",className:"h-4 w-4"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:V.session.title||V.session.id}),s.jsx("button",{type:"button",onClick:()=>k(M=>M.filter(Z=>Z.session.id!==V.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"h-4 w-4"})})]},V.session.id))})]}),s.jsxs(ar,{children:[s.jsx($e,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx($e,{onClick:B,disabled:!F,children:r(v?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function f2(t){const e=gt.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}function m2(t){const{t:e}=kt(),{node:n,depth:r=0,groupDirectory:o,projectId:a,archivedBucket:c=!1,currentSessionId:l,pinnedSessionIds:d,expandedParents:u,hasSessionSearchQuery:m,normalizedSessionSearchQuery:f,notifyOnSubtasks:g,editingId:y,setEditingId:p,editTitle:x,setEditTitle:b,handleSaveEdit:h,handleCancelEdit:N,toggleParent:w,handleSessionSelect:S,handleSessionDoubleClick:j,togglePinnedSession:k,handleShareSession:v,copiedSessionId:D,handleCopyShareUrl:A,handleUnshareSession:C,openSidebarMenuKey:O,setOpenSidebarMenuKey:T,renamingFolderId:E,getFoldersForScope:F,getSessionFolderId:R,removeSessionFromFolder:L,addSessionToFolder:B,createFolderAndStartRename:V,openContextPanelTab:M,handleDeleteSession:Z,mobileVariant:se,alwaysShowActions:Q,renderSessionNode:K,secondaryMeta:ee,renderContext:re="project",subtreeContainsActive:he,subtreeContainsEditing:je,menuOpenSessionId:te,childRenderExtrasFor:Ne,liveSessionById:J}=t,H=!!ee?.projectLabel,q=!!ee?.branchLabel,ae=Dr(qe=>qe.displayMode),le=i.useMemo(()=>Hr(),[]),Se=ae==="minimal"||le,Re=i.useMemo(()=>Fa(),[]),_e=i.useContext(Sg),Oe=le?"group-hover:opacity-100 group-hover:pointer-events-auto":"group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto",Me=le?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",ge=le,Ae=!c&&!se,pe=Se?le?Ae&&ge?"group-hover:pr-18":Ae||ge?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":le?Ae&&ge?"group-hover:pr-18":Ae||ge?"group-hover:pr-12":"group-hover:pr-5":Ae?"group-hover:pr-12 group-focus-within:pr-12":"group-hover:pr-5 group-focus-within:pr-5",ue=Ae?"pr-13":"pr-7",G=i.useRef(!1),[fe,ce]=i.useState(!1),W=i.useRef(y);W.current=y;const z=i.useRef(null),be=i.useRef(h);be.current=h;const[xe,_]=i.useState(x),ye=i.useRef(xe);ye.current=xe;const $=i.useRef(null),Ie=i.useRef(null),ve=n.session,Fe=J.get(ve.id)??ve,Ce=as(ve.directory??null)??as(o??null),ne=Ng(Ce??void 0,{bootstrap:!c}),P=Cc(),me=$n(qe=>qe.enabled),oe=$n(i.useCallback(qe=>qe.selectedIds.has(ve.id),[ve.id])),Be=$n(qe=>qe.toggleSelected),Ue=$n(qe=>qe.setRange),Ke=i.useCallback(qe=>{const ns=[],ps=hs=>{hs.children.forEach(rn=>{ns.push(rn.session.id),ps(rn)})};return ps(qe),ns},[]),[Qe,rt]=i.useState(!1),[pt,jt]=i.useState(!0),Ve=`${re}:${c?"archived":"active"}:${ve.id}`,Ze=tm(i.useCallback(qe=>!!qe.sessionMemoryState.get(kg(ve.id))?.isZombie,[ve.id])),nt=Cg(ve.id),St=Ag(ve.id,Ce??void 0),Dt=l===ve.id,wt=Fe.title||e("sessions.sidebar.session.untitled"),ot=n.children.length>0,at=d.has(ve.id),Kt=Ve,is=m?!0:u.has(Kt),$t=!!Fe.parentID,et=Dg(ve.id)>0&&(!$t||g),Vt=Fe.time?.updated||Fe.time?.created||Date.now(),xt=Zx(Vt),Ft=eb(Vt),Gt=O===Ve,[Ut,qt]=i.useState(!1),Xt=Gt||Ut,Lt=i.useMemo(()=>ha(Fe.title)!==null,[Fe.title]),[Bt,Yt]=i.useState(!1),Jt=le&&re==="recent"&&!Se,es=le&&re==="recent"&&Se,Zt=i.useMemo(()=>Ke(n).length,[Ke,n]),vs=i.useCallback(async qe=>{const ns=[];let ps=0;for(const hs of qe)try{await P.ensureSessionRenderable(hs.session.id);const rn=Td(ne.getState(),hs.session.id).list,Ws=hs.session.title||e("sessions.sidebar.session.export.untitledSubagent"),cn=hs.session.agent,Is=await vs(hs.children);ps+=Is.skipped,ns.push({title:Ws,agent:cn,records:rn,children:Is.children})}catch{ps+=Ke(hs).length+1}return{children:ns,skipped:ps}},[Ke,ne,P,e]),bt=i.useCallback(qe=>{qe<=0||de.warning(qe===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:qe}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:qe}))},[e]),Ot=i.useCallback(async qe=>{if(!Ce){de.error(e("sessions.sidebar.session.export.nothingToExport"));return}await P.ensureSessionRenderable(ve.id);const ns=Td(ne.getState(),ve.id).list;if(ns.length===0){de.error(e("sessions.sidebar.session.export.nothingToExport"));return}let ps,hs=0;if(qe&&n.children.length>0){const Is=await vs(n.children);ps=Is.children,hs=Is.skipped}const rn=$N(ns,Fe.title??null,ps),Ws=GN(Fe.title??null),cn=await WN(rn,Ws);if(cn){de.success(e("sessions.sidebar.session.export.success"),{action:{label:e(HN()),onClick:()=>{UN(cn).then(Is=>{Is||de.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),bt(hs);return}zN(rn,Ws),de.success(e("sessions.sidebar.session.export.success")),bt(hs)},[vs,ne,n.children,Fe.title,ve.id,Ce,bt,P,e]),It=i.useCallback(async()=>{if(n.children.length>0){jt(!0),rt(!0);return}await Ot(!1)},[Ot,n.children.length]),us=i.useCallback(()=>{Ce&&Wr("desktop_open_session_mini_chat_window",{sessionId:ve.id,directory:Ce,apiBaseUrl:zr(),clientToken:_l()}).catch(qe=>{console.warn("[session-sidebar] failed to open mini chat window",qe)})},[ve.id,Ce]);if(i.useEffect(()=>{if(y!==ve.id)return;const qe=ns=>{Ie.current&&!Ie.current.contains(ns.target)&&be.current(ye.current)};return document.addEventListener("mousedown",qe),()=>document.removeEventListener("mousedown",qe)},[y,ve.id]),i.useLayoutEffect(()=>{if(y!==ve.id){$.current===ve.id&&($.current=null);return}$.current!==ve.id&&($.current=ve.id,_(x))},[y,x,ve.id]),y===ve.id)return s.jsx("div",{className:De("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:Ie,className:"flex w-full items-center gap-2",onSubmit:qe=>{qe.preventDefault(),h(xe)},children:[s.jsx("input",{value:xe,onChange:qe=>_(qe.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:qe=>{if(qe.stopPropagation(),qe.key==="Escape"){N();return}}}),s.jsx("button",{type:"submit","aria-label":e("sessions.sidebar.session.rename.save"),title:e("sessions.sidebar.session.rename.save"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:N,"aria-label":e("sessions.sidebar.session.rename.cancel"),title:e("sessions.sidebar.session.rename.cancel"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"size-4"})})]}),Se?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:[ot?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:is?s.jsx(I,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(I,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:xt}),H?s.jsx("span",{className:"truncate",children:ee?.projectLabel}):null,q?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:ee?.branchLabel})]}):null]})})]})},ve.id);const He=nt?.type??"idle",ft=He==="busy"||He==="retry",Ye=St.length,Tt=ft||!ft&&et&&!Dt,Qt=ft?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")}),Ss=!Q&&ot&&(Tt||at),ys=at&&!Tt,_t=s.jsx(I,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}),Ns=Tt||ys?s.jsxs("span",{className:De("pointer-events-none absolute left-0.5 inline-flex h-3.5 w-3.5 items-center justify-center transition-opacity",Se?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",Ss?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[Tt?Qt:null,ys?_t:null]}):null,js=ot&&!Q&&(Tt||at),Ds=ot?s.jsx("span",{role:"button",tabIndex:0,onClick:qe=>{qe.stopPropagation(),w(Kt)},onKeyDown:qe=>{(qe.key==="Enter"||qe.key===" ")&&(qe.preventDefault(),qe.stopPropagation(),w(Kt))},style:{minWidth:14,minHeight:14},className:De("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",Jt?"absolute left-1.5 bottom-1":es?"relative mr-0.5 shrink-0":De("absolute left-0.5",Se?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!Jt&&!es&&js?"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(is?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:is?s.jsx(I,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(I,{name:"arrow-right-s",className:"h-3 w-3"})}):null,mn=Ze?s.jsx(I,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Js=qe=>{qe&&qt(!1),T(qe?Ve:null)},ln=qe=>{if(!qe&&z.current){const{id:ns,title:ps}=z.current;z.current=null,p(ns),b(ps)}},jn=qe=>{qt(qe)},$s=qe=>{qe.preventDefault(),qe.stopPropagation(),T(Gt?null:Ve)},we=qe=>{qe.preventDefault(),qe.stopPropagation()},Je=qe=>{qe.preventDefault(),qe.stopPropagation()},vt=qe=>{qe.preventDefault(),qe.stopPropagation()},Ct=qe=>{qe.preventDefault(),qe.stopPropagation()},zt=qe=>{qe.preventDefault(),qe.stopPropagation(),T(null),Z(ve,{archivedBucket:c})},mt=qe=>{qe.preventDefault(),qe.stopPropagation()},cs=qe=>{qe.preventDefault(),qe.stopPropagation()},fs=qe=>{qe.preventDefault(),qe.stopPropagation(),_e?.vscode?.executeCommand("openchamber.openSessionInEditor",ve.id,wt)},ks=qe=>{if(G.current){G.current=!1;return}if(me){if(qe?.preventDefault(),qe?.stopPropagation(),qe?.shiftKey){const ps=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Ws=>Ws.getAttribute("data-session-row")).filter(Ws=>typeof Ws=="string"&&Ws.length>0),hs=$n.getState().anchorId,rn=new Map;rn.set(ve.id,Ke(n)),Ue(hs,ve.id,ps,Ce??null,rn);return}Be(ve.id,Ce??null,Ke(n));return}S(ve.id,Ce,a)},ms=qe=>{(qe.button===2||qe.button===0&&qe.ctrlKey&&!me)&&(G.current=!0)},Hs=qe=>{se&&qe.pointerType==="touch"&&ce(!0)},zs=qe=>{se&&qe.pointerType==="touch"&&ce(!1)},hn=({Item:qe,Separator:ns,Sub:ps,SubTrigger:hs,SubContent:rn})=>s.jsxs(s.Fragment,{children:[s.jsxs(qe,{onClick:()=>{z.current={id:ve.id,title:wt}},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(qe,{onClick:()=>k(ve.id),className:"[&>svg]:mr-1",children:[at?s.jsx(I,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(I,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(at?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),Fe.share?s.jsxs(s.Fragment,{children:[s.jsx(qe,{onClick:()=>{Fe.share?.url&&A(Fe.share.url,ve.id)},className:"[&>svg]:mr-1",children:D===ve.id?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),e("sessions.sidebar.session.menu.copied")]}):s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(qe,{onClick:()=>C(ve.id),className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.unshare")]})]}):s.jsxs(qe,{onClick:()=>v(Fe),className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(qe,{onClick:()=>{It()},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),Lt?s.jsxs(qe,{onClick:()=>Yt(!0),className:"[&>svg]:mr-1",children:[s.jsx(f2,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,Ce&&!c?(()=>{const Ws=F(Ce),cn=R(Ce,ve.id);return s.jsxs(s.Fragment,{children:[s.jsx(ns,{}),s.jsxs(ps,{children:[s.jsxs(hs,{className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs(rn,{className:"min-w-[180px]",children:[Ws.length===0?s.jsx(qe,{disabled:!0,className:"text-muted-foreground",children:e("sessions.sidebar.folders.none")}):Ws.map(Is=>s.jsxs(qe,{onClick:()=>{cn===Is.id?L(Ce,ve.id):B(Ce,Is.id,ve.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:Is.name}),cn===Is.id?s.jsx(I,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Is.id)),s.jsx(ns,{}),s.jsxs(qe,{onClick:()=>{const Is=V(Ce);Is&&B(Ce,Is.id,ve.id)},children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),cn?s.jsxs(qe,{onClick:()=>{L(Ce,ve.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,le?null:s.jsxs(qe,{disabled:!Ce,onClick:()=>{Ce&&M(Ce,{mode:"chat",dedupeKey:`session:${ve.id}`,label:wt})},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"chat-4",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openInSidePanel")}),s.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:e("sessions.sidebar.session.menu.betaBadge")})]}),Re?s.jsxs(qe,{disabled:!Ce,onClick:us,className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(ns,{}),c?null:s.jsxs(qe,{className:"[&>svg]:mr-1",onClick:()=>Z(ve,{archivedBucket:c}),children:[s.jsx(I,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.archive")]}),s.jsxs(qe,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Z(ve,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(I,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),tr=s.jsx(sn,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(E||W.current),children:hn({Item:bs,Separator:Rr,Sub:Rg,SubTrigger:Eg,SubContent:Mg})}),An=s.jsx(id,{children:s.jsx(od,{className:"app-region-no-drag z-50",children:s.jsx(ad,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(E||W.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:De(Rd,"min-w-[180px]"),children:hn({Item:({className:qe,...ns})=>s.jsx(Uh,{className:De(Ig,qe),...ns}),Separator:({className:qe,...ns})=>s.jsx(Hh,{className:De(Pg,qe),...ns}),Sub:Gh,SubTrigger:({className:qe,children:ns,...ps})=>s.jsxs(Kh,{className:De(Tg,qe),...ps,children:[ns,s.jsx(I,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:qe,children:ns,...ps})=>s.jsx(id,{children:s.jsx(od,{className:"app-region-no-drag z-50",children:s.jsx(ad,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:De(Rd,qe),...ps,children:ns})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(lN,{sessionId:ve.id,sessionDirectory:Ce??null,sessionTitle:wt,children:s.jsxs(zh,{open:Ut,onOpenChange:jn,onOpenChangeComplete:ln,children:[s.jsxs(Wh,{render:s.jsx("div",{"data-session-row":ve.id,"data-session-scope":Ce??"","data-session-archived":c?"1":"0",className:De("group relative my-0.5 flex items-center rounded-md py-1 pr-1.5","-ml-3",r>0?"pl-[32px]":"pl-[18px]",Dt&&!oe&&"bg-primary/10",oe&&"bg-interactive-selection")}),children:[Ns,Ds,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:Se?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:Hs,onPointerUp:zs,onPointerCancel:zs,onMouseDown:ms,onClick:qe=>ks(qe),onDoubleClick:qe=>{qe.stopPropagation(),j(ve.id,wt)},className:De("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]",fe&&"bg-interactive-hover/70",Q?le?pe:ue:pe),children:s.jsxs("div",{className:De("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:De("block min-w-0 flex-1 truncate typography-ui-label font-normal",Dt?"text-primary":"text-foreground"),children:vo(wt,f)}),Q?s.jsx("span",{className:"ml-2 flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Ft}):null,Q?null:s.jsx("div",{className:"relative ml-1 flex h-4 min-w-4 flex-shrink-0 items-center justify-end",children:s.jsx("span",{className:De("whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",Xt?"opacity-0":Me),children:Ft})}),Ye>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(I,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Ye})]}):null]})})}),le?null:s.jsx(Mt,{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:De("flex items-center gap-3 text-left text-muted-foreground",ee?.projectLabel?"justify-between":"justify-start"),children:[ee?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:ee.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:xt})]}),ee?.branchLabel?s.jsx("div",{className:"flex items-center gap-3 text-left text-muted-foreground justify-start",children:s.jsx("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:ee.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:Hs,onPointerUp:zs,onPointerCancel:zs,onMouseDown:ms,onClick:qe=>ks(qe),onDoubleClick:qe=>{qe.stopPropagation(),j(ve.id,wt)},className:De("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]",fe&&"bg-interactive-hover/70",Q?le?pe:ue:pe),children:[s.jsxs("div",{className:De("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:De("block min-w-0 flex-1 truncate typography-ui-label font-normal",Dt?"text-primary":"text-foreground"),children:vo(wt,f)}),Ye>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(I,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Ye})]}):null]}),Se?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:De("flex min-w-0 items-center gap-1.5 overflow-hidden",Jt&&ot?"pl-4":""),children:[s.jsx("span",{className:"flex-shrink-0",children:xt}),H?s.jsx("span",{className:"truncate",children:ee?.projectLabel}):null,q?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:ee?.branchLabel})]}):null]})})]})}),mn&&!se?s.jsx("div",{className:De("absolute top-1/2 -translate-y-1/2 z-10",Se?"right-0":"right-[30px]"),children:mn}):null,s.jsxs("div",{className:De("absolute right-0 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",Xt||Q&&!le?"opacity-100":De("opacity-0",Oe)),children:[Ae?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",className:De("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",Se&&!Q?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.bulkActions.archive"),onPointerDown:vt,onMouseDown:Ct,onClick:zt,onKeyDown:qe=>qe.stopPropagation(),children:s.jsx(I,{name:"archive",className:De(Se&&!Q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Mt,{side:"left",sideOffset:8,children:e("sessions.sidebar.bulkActions.archive")})]}):null,ge?s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",className:De("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",Se&&!Q?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:mt,onMouseDown:cs,onClick:fs,onKeyDown:qe=>qe.stopPropagation(),children:s.jsx(I,{name:"external-link",className:De(Se&&!Q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Mt,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(nn,{open:Gt,onOpenChange:Js,onOpenChangeComplete:ln,children:[s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:De("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",Se&&!Q?Xt?"h-4 w-4 opacity-100":De("h-4 w-4 opacity-0",Oe):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:we,onMouseDown:Je,onClick:$s,onKeyDown:qe=>qe.stopPropagation(),children:s.jsx(I,{name:"more-2",className:De(Se&&!Q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),tr]})]})]}),An]})}),ot&&is?n.children.map(qe=>{const ns=Ne?Ne(qe):{subtreeContainsActive:he,subtreeContainsEditing:je,menuOpenSessionId:te,nodeStructureKey:""};return K(qe,r+1,Ce??o,a,c,void 0,re,ns)}):null,s.jsx(Os,{open:Qe,onOpenChange:rt,children:s.jsxs(Ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Us,{children:[s.jsx(_s,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(an,{children:Zt===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:Zt}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:Zt})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:pt,onChange:qe=>jt(qe.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(ar,{children:[s.jsx($e,{type:"button",onClick:()=>rt(!1),variant:"outline",size:"sm",children:e("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{type:"button",onClick:()=>{rt(!1),Ot(pt)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),Lt?s.jsx(u2,{session:Fe,open:Bt,onOpenChange:Yt}):null]},ve.id)}const of=t=>as(t.session.directory??null),h2=(t,e)=>(t?.projectLabel??null)===(e?.projectLabel??null)&&(t?.branchLabel??null)===(e?.branchLabel??null),p2=t=>{if(!t.openSidebarMenuKey)return null;const e=t.archivedBucket?"archived":"active",n=`${t.renderContext??"project"}:${e}:`;return t.openSidebarMenuKey.startsWith(n)?t.openSidebarMenuKey.slice(n.length):null},ta=t=>t.menuOpenSessionId??p2(t),zi=(t,e,n)=>e?n.has(t.node.session.id)?!0:$r(t.node,e):!1,Ea=(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(Ea(t.children[c],e.children[c],n,r,o))return!0;return!1},dh=(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(dh(t.children[a],e.children[a],n,r))return!0;return!1},g2=(t,e)=>{if(t.hasSessionSearchQuery||e.hasSessionSearchQuery)return!1;const n=t.archivedBucket?"archived":"active",r=e.archivedBucket?"archived":"active";return Ea(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${t.renderContext??"project"}:${n}:${o.session.id}`)||Ea(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${e.renderContext??"project"}:${r}:${o.session.id}`)},x2=(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||of(t.node)!==of(e.node)||!h2(t.secondaryMeta,e.secondaryMeta)||t.liveSessionById!==e.liveSessionById&&dh(t.node,e.node,t.liveSessionById,e.liveSessionById)||t.pinnedSessionIds!==e.pinnedSessionIds&&Ea(t.node,e.node,t.pinnedSessionIds,e.pinnedSessionIds,n=>n.session.id)||t.expandedParents!==e.expandedParents&&g2(t,e)||t.currentSessionId!==e.currentSessionId&&(zi(t,t.currentSessionId,t.subtreeContainsActive)||zi(e,e.currentSessionId,e.subtreeContainsActive))||t.editingId!==e.editingId&&(zi(t,t.editingId,t.subtreeContainsEditing)||zi(e,e.editingId,e.subtreeContainsEditing))||t.editTitle!==e.editTitle&&(zi(t,t.editingId,t.subtreeContainsEditing)||zi(e,e.editingId,e.subtreeContainsEditing))||t.copiedSessionId!==e.copiedSessionId&&($r(t.node,t.copiedSessionId)||$r(e.node,e.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=ta(t),r=ta(e);if($r(t.node,n)||$r(e.node,r))return!1}if(t.renamingFolderId!==e.renamingFolderId){const n=ta(t),r=ta(e);if($r(t.node,n)||$r(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},b2=i.memo(m2,x2);function y2(t){const e=gt.c(71),{t:n}=kt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,u,m,f,g,y,p,x,b,h;if(e[0]!==o||e[1]!==n||e[2]!==r){const M=n("sessions.sidebar.session.untitled");f=Os,b=!!r,e[13]!==o?(h=se=>{se||o(null)},e[13]=o,e[14]=h):h=e[14],m=Ls,p=!1,x="max-w-sm gap-5",u=Us;let Z;e[15]!==n||e[16]!==r?.archivedBucket?(Z=r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.title"):n("sessions.sidebar.dialogs.archiveSession.title"),e[15]=n,e[16]=r?.archivedBucket,e[17]=Z):Z=e[17],e[18]!==Z?(y=s.jsx(_s,{children:Z}),e[18]=Z,e[19]=y):y=e[19],d=an,g=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]=u,e[5]=m,e[6]=f,e[7]=g,e[8]=y,e[9]=p,e[10]=x,e[11]=b,e[12]=h}else d=e[3],u=e[4],m=e[5],f=e[6],g=e[7],y=e[8],p=e[9],x=e[10],b=e[11],h=e[12];let N;e[20]!==d||e[21]!==g?(N=s.jsx(d,{children:g}),e[20]=d,e[21]=g,e[22]=N):N=e[22];let w;e[23]!==u||e[24]!==y||e[25]!==N?(w=s.jsxs(u,{children:[y,N]}),e[23]=u,e[24]=y,e[25]=N,e[26]=w):w=e[26];let S;e[27]!==c||e[28]!==a?(S=()=>c(!a),e[27]=c,e[28]=a,e[29]=S):S=e[29];const j=!a;let k;e[30]!==a?(k=a?s.jsx(I,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(I,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[30]=a,e[31]=k):k=e[31];let v;e[32]!==n?(v=n("sessions.sidebar.dialogs.neverAsk"),e[32]=n,e[33]=v):v=e[33];let D;e[34]!==k||e[35]!==v||e[36]!==S||e[37]!==j?(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":j,children:[k,v]}),e[34]=k,e[35]=v,e[36]=S,e[37]=j,e[38]=D):D=e[38];let A;e[39]!==o?(A=()=>o(null),e[39]=o,e[40]=A):A=e[40];let C;e[41]!==n?(C=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=C):C=e[42];let O;e[43]!==A||e[44]!==C?(O=s.jsx("button",{type:"button",onClick:A,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:C}),e[43]=A,e[44]=C,e[45]=O):O=e[45];let T;e[46]!==l?(T=()=>{l()},e[46]=l,e[47]=T):T=e[47];let E;e[48]!==n||e[49]!==r?.archivedBucket?(E=r?.archivedBucket?n("sessions.sidebar.bulkActions.delete"):n("sessions.sidebar.bulkActions.archive"),e[48]=n,e[49]=r?.archivedBucket,e[50]=E):E=e[50];let F;e[51]!==T||e[52]!==E?(F=s.jsx("button",{type:"button",onClick:T,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:E}),e[51]=T,e[52]=E,e[53]=F):F=e[53];let R;e[54]!==O||e[55]!==F?(R=s.jsxs("div",{className:"flex items-center gap-2",children:[O,F]}),e[54]=O,e[55]=F,e[56]=R):R=e[56];let L;e[57]!==D||e[58]!==R?(L=s.jsxs(ar,{className:"w-full sm:items-center sm:justify-between",children:[D,R]}),e[57]=D,e[58]=R,e[59]=L):L=e[59];let B;e[60]!==m||e[61]!==p||e[62]!==L||e[63]!==x||e[64]!==w?(B=s.jsxs(m,{showCloseButton:p,className:x,children:[w,L]}),e[60]=m,e[61]=p,e[62]=L,e[63]=x,e[64]=w,e[65]=B):B=e[65];let V;return e[66]!==f||e[67]!==B||e[68]!==b||e[69]!==h?(V=s.jsx(f,{open:b,onOpenChange:h,children:B}),e[66]=f,e[67]=B,e[68]=b,e[69]=h,e[70]=V):V=e[70],V}function w2(t){const e=gt.c(57),{t:n}=kt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t,d=r?.archivedBucket===!0,u=r?.sessionCount??0;let m;e[0]!==d||e[1]!==u||e[2]!==n?(m=n(d?u===1?"sessions.sidebar.dialogs.deleteSession.title":"sessions.sidebar.dialogs.deleteSessions.title":u===1?"sessions.sidebar.dialogs.archiveSession.title":"sessions.sidebar.dialogs.archiveSessions.title"),e[0]=d,e[1]=u,e[2]=n,e[3]=m):m=e[3];const f=m;let g;e[4]!==d||e[5]!==u||e[6]!==n?(g=d?u===1?n("sessions.sidebar.dialogs.deleteSessions.singleDescription",{count:u}):n("sessions.sidebar.dialogs.deleteSessions.pluralDescription",{count:u}):u===1?n("sessions.sidebar.dialogs.archiveSessions.singleDescription",{count:u}):n("sessions.sidebar.dialogs.archiveSessions.pluralDescription",{count:u}),e[4]=d,e[5]=u,e[6]=n,e[7]=g):g=e[7];const y=g,p=!!r;let x;e[8]!==o?(x=V=>{V||o(null)},e[8]=o,e[9]=x):x=e[9];let b;e[10]!==f?(b=s.jsx(_s,{children:f}),e[10]=f,e[11]=b):b=e[11];let h;e[12]!==y?(h=s.jsx(an,{children:y}),e[12]=y,e[13]=h):h=e[13];let N;e[14]!==b||e[15]!==h?(N=s.jsxs(Us,{children:[b,h]}),e[14]=b,e[15]=h,e[16]=N):N=e[16];let w;e[17]!==c||e[18]!==a?(w=()=>c(!a),e[17]=c,e[18]=a,e[19]=w):w=e[19];const S=!a;let j;e[20]!==a?(j=a?s.jsx(I,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(I,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[20]=a,e[21]=j):j=e[21];let k;e[22]!==n?(k=n("sessions.sidebar.dialogs.neverAsk"),e[22]=n,e[23]=k):k=e[23];let v;e[24]!==k||e[25]!==w||e[26]!==S||e[27]!==j?(v=s.jsxs("button",{type:"button",onClick:w,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":S,children:[j,k]}),e[24]=k,e[25]=w,e[26]=S,e[27]=j,e[28]=v):v=e[28];let D;e[29]!==o?(D=()=>o(null),e[29]=o,e[30]=D):D=e[30];let A;e[31]!==n?(A=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=A):A=e[32];let C;e[33]!==D||e[34]!==A?(C=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:A}),e[33]=D,e[34]=A,e[35]=C):C=e[35];let O;e[36]!==l?(O=()=>{l()},e[36]=l,e[37]=O):O=e[37];let T;e[38]!==d||e[39]!==n?(T=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=T):T=e[40];let E;e[41]!==O||e[42]!==T?(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:T}),e[41]=O,e[42]=T,e[43]=E):E=e[43];let F;e[44]!==C||e[45]!==E?(F=s.jsxs("div",{className:"flex items-center gap-2",children:[C,E]}),e[44]=C,e[45]=E,e[46]=F):F=e[46];let R;e[47]!==v||e[48]!==F?(R=s.jsxs(ar,{className:"w-full sm:items-center sm:justify-between",children:[v,F]}),e[47]=v,e[48]=F,e[49]=R):R=e[49];let L;e[50]!==R||e[51]!==N?(L=s.jsxs(Ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[N,R]}),e[50]=R,e[51]=N,e[52]=L):L=e[52];let B;return e[53]!==p||e[54]!==L||e[55]!==x?(B=s.jsx(Os,{open:p,onOpenChange:x,children:L}),e[53]=p,e[54]=L,e[55]=x,e[56]=B):B=e[56],B}function v2(t){const e=gt.c(36),{t:n}=kt(),{value:r,setValue:o,onConfirm:a}=t,c=!!r;let l;e[0]!==o?(l=j=>{j||o(null)},e[0]=o,e[1]=l):l=e[1];let d;e[2]!==n?(d=n("sessions.sidebar.dialogs.deleteFolder.title"),e[2]=n,e[3]=d):d=e[3];let u;e[4]!==d?(u=s.jsx(_s,{children:d}),e[4]=d,e[5]=u):u=e[5];let m;e[6]!==n||e[7]!==r?(m=r&&(r.subFolderCount>0||r.sessionCount>0)?r.subFolderCount>0?r.subFolderCount===1?n("sessions.sidebar.dialogs.deleteFolder.withOneSubfolder",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withManySubfolders",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withContentsNoSubfolders",{folderName:r.folderName}):n("sessions.sidebar.dialogs.deleteFolder.single",{folderName:r?.folderName??""}),e[6]=n,e[7]=r,e[8]=m):m=e[8];let f;e[9]!==m?(f=s.jsx(an,{children:m}),e[9]=m,e[10]=f):f=e[10];let g;e[11]!==u||e[12]!==f?(g=s.jsxs(Us,{children:[u,f]}),e[11]=u,e[12]=f,e[13]=g):g=e[13];let y;e[14]!==o?(y=()=>o(null),e[14]=o,e[15]=y):y=e[15];let p;e[16]!==n?(p=n("sessions.sidebar.dialogs.cancel"),e[16]=n,e[17]=p):p=e[17];let x;e[18]!==y||e[19]!==p?(x=s.jsx("button",{type:"button",onClick:y,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:p}),e[18]=y,e[19]=p,e[20]=x):x=e[20];let b;e[21]!==n?(b=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=b):b=e[22];let h;e[23]!==a||e[24]!==b?(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:b}),e[23]=a,e[24]=b,e[25]=h):h=e[25];let N;e[26]!==h||e[27]!==x?(N=s.jsxs(ar,{children:[x,h]}),e[26]=h,e[27]=x,e[28]=N):N=e[28];let w;e[29]!==N||e[30]!==g?(w=s.jsxs(Ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[g,N]}),e[29]=N,e[30]=g,e[31]=w):w=e[31];let S;return e[32]!==c||e[33]!==l||e[34]!==w?(S=s.jsx(Os,{open:c,onOpenChange:l,children:w}),e[32]=c,e[33]=l,e[34]=w,e[35]=S):S=e[35],S}const j2=t=>{const e=gt.c(46),{selectedCount:n,scopeKey:r,scopeFolders:o,archivedBucket:a,onMoveToFolder:c,onCreateFolderAndMove:l,onRemoveFromFolder:d,canRemoveFromFolder:u,onDelete:m,onDone:f}=t,{t:g}=kt(),y=!!r&&!a;let p;e[0]!==a||e[1]!==g?(p=g(a?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[0]=a,e[1]=g,e[2]=p):p=e[2];const x=p;let b;e[3]!==n||e[4]!==g?(b=g("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=g,e[5]=b):b=e[5];let h;e[6]!==b?(h=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:b}),e[6]=b,e[7]=h):h=e[7];let N;e[8]!==y||e[9]!==u||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==g?(N=y?s.jsxs(nn,{children:[s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx(tn,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":g("sessions.sidebar.bulkActions.moveToFolder"),children:s.jsx(I,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(Mt,{side:"top",sideOffset:4,children:s.jsx("p",{children:g("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(sn,{align:"end",className:"min-w-[180px]",children:[o.length===0?s.jsx(bs,{disabled:!0,className:"text-muted-foreground",children:g("sessions.sidebar.folders.none")}):o.map(L=>s.jsx(bs,{onClick:()=>c(L.id),children:s.jsx("span",{className:"flex-1 truncate",children:L.name})},L.id)),s.jsx(Rr,{}),s.jsxs(bs,{onClick:l,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"}),g("sessions.sidebar.folders.newFolderEllipsis")]}),u?s.jsxs(bs,{onClick:d,className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1 h-4 w-4"}),g("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=y,e[9]=u,e[10]=l,e[11]=c,e[12]=d,e[13]=o,e[14]=g,e[15]=N):N=e[15];let w;e[16]===Symbol.for("react.memo_cache_sentinel")?(w=De("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),e[16]=w):w=e[16];let S;e[17]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(I,{name:"delete-bin",className:"h-4 w-4"}),e[17]=S):S=e[17];let j;e[18]!==x||e[19]!==m?(j=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,className:w,"aria-label":x,children:S})}),e[18]=x,e[19]=m,e[20]=j):j=e[20];let k;e[21]!==x?(k=s.jsx(Mt,{side:"top",sideOffset:4,children:s.jsx("p",{children:x})}),e[21]=x,e[22]=k):k=e[22];let v;e[23]!==j||e[24]!==k?(v=s.jsxs(Rt,{children:[j,k]}),e[23]=j,e[24]=k,e[25]=v):v=e[25];let D;e[26]!==g?(D=g("sessions.sidebar.header.actions.exitSelection"),e[26]=g,e[27]=D):D=e[27];let A;e[28]===Symbol.for("react.memo_cache_sentinel")?(A=s.jsx(I,{name:"close",className:"h-4 w-4"}),e[28]=A):A=e[28];let C;e[29]!==f||e[30]!==D?(C=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:f,className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":D,children:A})}),e[29]=f,e[30]=D,e[31]=C):C=e[31];let O;e[32]!==g?(O=g("sessions.sidebar.header.actions.exitSelection"),e[32]=g,e[33]=O):O=e[33];let T;e[34]!==O?(T=s.jsx(Mt,{side:"top",sideOffset:4,children:s.jsx("p",{children:O})}),e[34]=O,e[35]=T):T=e[35];let E;e[36]!==C||e[37]!==T?(E=s.jsxs(Rt,{children:[C,T]}),e[36]=C,e[37]=T,e[38]=E):E=e[38];let F;e[39]!==E||e[40]!==N||e[41]!==v?(F=s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[N,v,E]}),e[39]=E,e[40]=N,e[41]=v,e[42]=F):F=e[42];let R;return e[43]!==F||e[44]!==h?(R=s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-2.5 py-1.5",children:[h,F]}),e[43]=F,e[44]=h,e[45]=R):R=e[45],R},S2=t=>{const{t:e}=kt(),{isInlineEditing:n,showDeletionDialog:r,foldersMap:o,addSessionsToFolder:a,removeSessionsFromFolders:c,createFolderAndStartRename:l,archiveSessions:d,deleteSessions:u,setBulkDeleteConfirm:m}=t,f=$n(T=>T.enabled),g=$n(T=>T.selectedIds.size),y=g>0,p=$n(T=>T.selectedIds),x=$n(T=>T.scopeKey),b=i.useCallback(()=>{$n.getState().toggleMode()},[]),h=i.useCallback(()=>{$n.getState().disable()},[]),N=i.useMemo(()=>{if(!y||typeof document>"u")return!1;let T=!1,E=!1;for(const F of p){const R=document.querySelectorAll(`[data-session-row="${CSS.escape(F)}"]`);for(const L of R)L.getAttribute("data-session-archived")==="1"?E=!0:T=!0}return E&&!T},[y,p]),w=i.useMemo(()=>{if(x)return x;if(!y||typeof document>"u")return null;for(const T of p){const F=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(F&&F.length>0)return F}return null},[y,p,x]),S=i.useMemo(()=>w?o[w]??[]:[],[o,w]),j=i.useMemo(()=>{if(!w||!y)return!1;const T=o[w]??[];for(const E of T)for(const F of E.sessionIds)if(p.has(F))return!0;return!1},[o,w,y,p]),k=i.useCallback(T=>{!w||!y||a(w,T,Array.from(p))},[a,p,w,y]),v=i.useCallback(()=>{if(!w||!y)return;const T=l(w);T&&a(w,T.id,Array.from(p))},[a,l,p,w,y]),D=i.useCallback(()=>{!w||!y||c(w,Array.from(p))},[c,p,w,y]),A=i.useCallback(async()=>{const T=Array.from(p);if(T.length!==0){if(N){const{deletedIds:E,failedIds:F}=await u(T);E.length>0&&de.success(E.length===1?e("sessions.sidebar.bulkActions.deletedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.deletedPlural",{count:E.length})),F.length>0&&de.error(F.length===1?e("sessions.sidebar.bulkActions.failedDeleteSingle",{count:F.length}):e("sessions.sidebar.bulkActions.failedDeletePlural",{count:F.length}))}else{const{archivedIds:E,failedIds:F}=await d(T);E.length>0&&de.success(E.length===1?e("sessions.sidebar.bulkActions.archivedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.archivedPlural",{count:E.length})),F.length>0&&de.error(F.length===1?e("sessions.sidebar.bulkActions.failedArchiveSingle",{count:F.length}):e("sessions.sidebar.bulkActions.failedArchivePlural",{count:F.length}))}$n.getState().clear()}},[d,N,u,p,e]),C=i.useCallback(()=>{if(!y)return;const T=p.size;if(!r){A();return}m({sessionCount:T,archivedBucket:N})},[N,A,p,r,m,y]),O=i.useCallback(async()=>{m(null),await A()},[A]);return i.useEffect(()=>{if(!f)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=F=>{if(n)return;const R=F.target;if(R&&(R.tagName==="INPUT"||R.tagName==="TEXTAREA"||R.isContentEditable))return;const L=T?F.metaKey:F.ctrlKey;if(F.key==="Escape"){F.preventDefault(),$n.getState().disable();return}if(L&&F.key==="Backspace"){F.preventDefault(),C();return}if(L&&(F.key==="a"||F.key==="A")){const B=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(B.length===0)return;F.preventDefault();const M=$n.getState().scopeKey??B[0]?.getAttribute("data-session-scope")??null,Z=Q=>M?Q.getAttribute("data-session-scope")===M:!0,se=B.filter(Z).map(Q=>Q.getAttribute("data-session-row")).filter(Q=>typeof Q=="string"&&Q.length>0);if(se.length===0)return;$n.getState().replaceAll(se,M||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[C,n,f]),{selectionModeEnabled:f,hasSelection:y,selectedIdsSize:g,bulkScopeIsArchived:N,derivedSelectionScope:w,bulkScopeFolders:S,bulkCanRemoveFromFolder:j,handleToggleSelectionMode:b,handleExitSelectionMode:h,handleBulkMoveToFolder:k,handleBulkCreateFolderAndMove:v,handleBulkRemoveFromFolder:D,handleBulkDelete:C,confirmBulkDelete:O}},N2=2880*60*1e3,k2=t=>!!t.parentID,C2=t=>!!t.time?.archived,nc=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},A2=t=>[...t].sort((e,n)=>nc(n)-nc(e)),D2=(t,e=Date.now())=>{const n=e-N2,r=t.filter(o=>C2(o)||k2(o)?!1:nc(o)>=n);return A2(r)},sa="oc.sessions.projectCollapse",af="oc.sessions.groupOrder",lf="oc.sessions.groupCollapse",cf="oc.sessions.activeSessionByProject",Tl="oc.sessions.expandedParents.v2",I2="oc.sessions.expandedParents",P2="oc.sessions.pinned",T2=(t,e,n)=>{const r=new Set;for(const o of t){const a=as(o.path)?.toLowerCase();a&&r.add(a)}if(n?.includeWorktrees===!1)return r;for(const o of e.values())for(const a of o){const c=as(a.path)?.toLowerCase();c&&r.add(c)}return r},R2=(t,e,n)=>{if(t.time?.archived)return!0;const r=as(Tr(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},E2=5*6e4,df=new Set,Ar=t=>{const e=i.useRef(t);return e.current=t,i.useCallback((...n)=>e.current(...n),[])},uf=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=kt(),[c,l]=i.useState(!1),[d,u]=i.useState(""),m=i.useRef(null),f=i.useRef(null),g=i.useRef(new Set),[y,p]=i.useState(null),[x,b]=i.useState(""),[h,N]=i.useState(null),[w,S]=i.useState(new Set),j=i.useMemo(()=>ki(),[]),[k,v]=i.useState(new Set),[D,A]=i.useState(new Map),[C,O]=i.useState(new Map),T=Ee(ie=>ie.isNewWorktreeDialogOpen),E=Ee(ie=>ie.setNewWorktreeDialogOpen),[F,R]=i.useState(!1),[L,B]=i.useState(null),[V,M]=i.useState(null),[Z,se]=i.useState(""),[Q,K]=i.useState(null),[ee,re]=i.useState(null),[he,je]=i.useState(null),te=ol(ie=>ie.ids),Ne=ol(ie=>ie.setIds),J=ol(ie=>ie.toggle),[H,q]=i.useState(()=>{try{const ie=ki().getItem(lf);if(!ie)return new Set;const lt=JSON.parse(ie);return new Set(Array.isArray(lt)?lt.filter(Xe=>typeof Xe=="string"):[])}catch{return new Set}}),[ae,le]=i.useState(()=>{try{const ie=ki().getItem(af);if(!ie)return new Map;const lt=JSON.parse(ie),Xe=new Map;return Object.entries(lt).forEach(([Nt,Ht])=>{Array.isArray(Ht)&&Xe.set(Nt,Ht.filter(Cs=>typeof Cs=="string"))}),Xe}catch{return new Map}}),[Se,Re]=i.useState(()=>{try{const ie=ki().getItem(cf);if(!ie)return new Map;const lt=JSON.parse(ie),Xe=new Map;return Object.entries(lt).forEach(([Nt,Ht])=>{typeof Ht=="string"&&Ht.length>0&&Xe.set(Nt,Ht)}),Xe}catch{return new Map}}),[_e,Oe]=i.useState(new Map),Me=i.useRef(new Map),ge=i.useRef(0),Ae=Qs(ie=>ie.homeDirectory),pe=Qs(ie=>ie.currentDirectory),ue=Qs(ie=>ie.setDirectory),G=ws(ie=>ie.projects),fe=ws(ie=>ie.activeProjectId),ce=ws(ie=>ie.removeProject),W=ws(ie=>ie.setActiveProjectIdOnly),z=ws(ie=>ie.updateProjectMeta),be=ws(ie=>ie.reorderProjects),xe=Ee(ie=>ie.setActiveMainTab),_=Ee(ie=>ie.openContextPanelTab),ye=Ee(ie=>ie.setSettingsDialogOpen),$=Ee(ie=>ie.toggleHelpDialog),Ie=Ee(ie=>ie.setAboutDialogOpen),ve=Ee(ie=>ie.setSessionSwitcherOpen),Fe=Ee(ie=>ie.setScheduledTasksDialogOpen),Ce=Ee(ie=>ie.openMultiRunLauncher),ne=Ee(ie=>ie.notifyOnSubtasks),P=Ee(ie=>ie.showDeletionDialog),me=Ee(ie=>ie.setShowDeletionDialog),oe=Ha(d,120),Be=i.useMemo(()=>oe.trim().toLowerCase(),[oe]),Ue=Be.length>0,Ke=Vn(ie=>ie.collapsedFolderIds),Qe=Vn(ie=>ie.foldersMap),rt=Vn(ie=>ie.getFoldersForScope),pt=Vn(ie=>ie.createFolder),jt=Vn(ie=>ie.renameFolder),Ve=Vn(ie=>ie.deleteFolder),Ze=Vn(ie=>ie.addSessionToFolder),nt=Vn(ie=>ie.addSessionsToFolder),St=Vn(ie=>ie.removeSessionFromFolder),Dt=Vn(ie=>ie.removeSessionsFromFolders),wt=Vn(ie=>ie.toggleFolderCollapse),ot=Vn(ie=>ie.cleanupSessions),at=Vn(ie=>ie.getSessionFolderId);kS({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:f,sessionSearchContainerRef:m});const Kt=Qf(),is=Cc(),$t=mc(),Le=i.useMemo(()=>Hr(),[]),et=jr(ie=>ie.hasLoaded),Vt=jr(ie=>ie.activeSessions),xt=jr(ie=>ie.archivedSessions),Ft=ut(ie=>ie.currentSessionId),Gt=ut(ie=>!!ie.newSessionDraft?.open),Ut=ut(ie=>ie.setCurrentSession),qt=ut(ie=>ie.updateSessionTitle),Xt=ut(ie=>ie.shareSession),Lt=ut(ie=>ie.unshareSession),Bt=ut(ie=>ie.worktreeMetadata),Yt=ut(ie=>ie.availableWorktreesByProject),Jt=ut(ie=>ie.openNewSessionDraft),es=i.useCallback(ie=>{Jt(ie),Le&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[Le,Jt]),Zt=wo(Bl(ie=>({checkForUpdates:ie.checkForUpdates,available:ie.available,runtimeType:ie.runtimeType,info:ie.info,downloading:ie.downloading,downloaded:ie.downloaded,progress:ie.progress,error:ie.error,downloadUpdate:ie.downloadUpdate,restartToUpdate:ie.restartToUpdate}))),vs=i.useMemo(()=>T2(G,Yt,{includeWorktrees:!Le}),[Yt,Le,G]),bt=i.useMemo(()=>{const ie=new Map($t.map(Nt=>[Nt.id,Nt])),lt=Vt.map(Nt=>{const Ht=ie.get(Nt.id);return Ht?Fg(Ht,Nt):Nt}),Xe=new Set(lt.map(Nt=>Nt.id));return $t.forEach(Nt=>{Xe.has(Nt.id)||lt.push(Nt)}),lt.filter(Nt=>R2(Nt,vs,{allowUnknownDirectory:!Le,allowEmptyDirectorySet:!Le}))},[Vt,Le,vs,$t]),Ot=i.useMemo(()=>$t.map(ie=>{const lt=as(ie.directory??null)??"";return`${ie.id}:${ie.title??""}:${ie.time?.archived?1:0}:${lt}`}).join("|"),[$t]),It=i.useRef($t);i.useEffect(()=>{It.current=$t},[Ot,$t]);const us=i.useMemo(()=>new Map($t.map(ie=>[ie.id,ie])),[$t]),He=i.useMemo(()=>G.map(ie=>`${ie.id}:${as(ie.path)??""}`).join("|"),[G]),ft=i.useRef(!1);i.useEffect(()=>{ft.current||(ft.current=!0,Sa(It.current))},[]);const Ye=i.useRef("");i.useEffect(()=>{let ie=!1;const lt=async()=>{const Xe=ws.getState().projects;if(Xe.length===0)return;const Nt=new Map,Ht=[],Cs=3;let qs=0;const Qn=Array.from({length:Cs},async()=>{for(;;){const xn=qs;if(qs+=1,xn>=Xe.length)return;const bn=Xe[xn],Jn=as(bn.path);if(Jn)try{if(!(wn.getState().directories.get(Jn)?.isGitRepo??await sm(Jn)))continue;const xi=await Og({id:bn.id,path:Jn});if(ie||xi.length===0)continue;Nt.set(Jn,xi),Ht.push(...xi)}catch{}}});await Promise.all(Qn),!ie&&ut.setState({availableWorktrees:Ht,availableWorktreesByProject:Nt})};if(Ye.current!==He)return Ye.current=He,lt(),()=>{ie=!0}},[He]),i.useEffect(()=>{let ie=null;const lt=th(Xe=>{Xe.type==="scheduled-task-ran"&&(ie&&clearTimeout(ie),ie=setTimeout(()=>{Sa(It.current)},500))});return()=>{ie&&clearTimeout(ie),lt()}},[]);const Pt=i.useMemo(()=>hr(),[]),{isTablet:Tt}=Er(),Qt=t||Tt,{buildGroupSearchText:Ss,filterSessionNodesForSearch:ys,buildGroupedSessions:_t}=NS({homeDirectory:Ae,worktreeMetadata:Bt,pinnedSessionIds:te,gitBranches:Kt,isVSCode:Le}),{scheduleCollapsedProjectsPersist:Ns}=RS({isVSCode:Le,hasLoadedGlobalSessions:et,safeStorage:j,keys:{sessionExpanded:Tl,sessionExpandedLegacy:I2,projectCollapse:sa,sessionPinned:P2,groupOrder:af,projectActiveSession:cf,groupCollapse:lf},sessions:bt,setPinnedSessionIds:Ne,groupOrderByProject:ae,activeSessionByProject:Se,collapsedGroups:H,setExpandedParents:S,setCollapsedProjects:v}),js=i.useMemo(()=>[...bt].sort((ie,lt)=>Ki(ie,lt,te)),[bt,te]),Ds=i.useMemo(()=>js.map(ie=>`${ie.id}:${ie.time?.updated??0}`).join("|"),[js]),mn=i.useRef(null),Js=i.useMemo(()=>{const ie=mn.current;if(ie&&ie.signature===Ds)return ie.map;const lt=new Map(js.map((Xe,Nt)=>[Xe.id,Nt]));return mn.current={signature:Ds,map:lt},lt},[Ds,js]),ln=i.useMemo(()=>{const ie=new Map;return js.forEach(lt=>{const Xe=lt.parentID;if(!Xe)return;const Nt=ie.get(Xe)??[];Nt.push(lt),ie.set(Xe,Nt)}),ie.forEach(lt=>lt.sort((Xe,Nt)=>Ki(Xe,Nt,te))),ie},[js,te]),jn=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")})]}),$s=i.useMemo(()=>G.find(ie=>ie.id===h)??null,[G,h]),we=i.useCallback(ie=>{h&&(z(h,ie),N(null))},[h,z]),Je=i.useCallback(()=>{E(!0)},[E]),vt=i.useCallback(()=>{const ie=wo.getState();if(ie.available&&ie.info){R(!0);return}Zt.checkForUpdates().then(()=>{const{available:lt,error:Xe}=wo.getState();if(Xe){de.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:Xe});return}if(!lt){de.success(a("sessions.sidebar.updateCheck.latestVersion"));return}R(!0)})},[a,Zt]),Ct=i.useCallback(()=>{t&&ve(!1),ye(!0)},[t,ve,ye]),zt=Zt.available&&(Zt.runtimeType==="desktop"||Zt.runtimeType==="web"),mt=ut(ie=>ie.deleteSession),cs=ut(ie=>ie.deleteSessions),fs=ut(ie=>ie.archiveSession),ks=ut(ie=>ie.archiveSessions),{copiedSessionId:ms,handleSessionSelect:Hs,handleSessionDoubleClick:zs,handleSaveEdit:hn,handleCancelEdit:tr,handleShareSession:An,handleCopyShareUrl:qe,handleUnshareSession:ns,handleDeleteSession:ps,confirmDeleteSession:hs}=CS({activeProjectId:fe,currentDirectory:pe,currentSessionId:Ft,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:u,setIsSessionSearchOpen:l,setActiveProjectIdOnly:W,setDirectory:ue,setActiveMainTab:xe,setSessionSwitcherOpen:ve,setCurrentSession:Ut,updateSessionTitle:qt,shareSession:Xt,unshareSession:Lt,deleteSession:mt,deleteSessions:cs,archiveSession:fs,archiveSessions:ks,childrenMap:ln,showDeletionDialog:P,setDeleteSessionConfirm:K,deleteSessionConfirm:Q,setEditingId:p,setEditTitle:b,editingId:y,editTitle:x}),rn=i.useCallback(()=>{if(!ee)return;const{scopeKey:ie,folderId:lt}=ee;re(null),Ve(ie,lt)},[ee,Ve]),Ws=i.useCallback(()=>{Pr.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!Ft)return;const lt=bt.find(Nt=>Nt.id===Ft)?.parentID;if(!lt)return;const Xe=[`project:active:${lt}`,`project:archived:${lt}`,`recent:active:${lt}`,`recent:archived:${lt}`];S(Nt=>{if(Xe.every(Cs=>Nt.has(Cs)))return Nt;const Ht=new Set(Nt);Xe.forEach(Cs=>Ht.add(Cs));try{j.setItem(Tl,JSON.stringify(Array.from(Ht)))}catch{}return Ht})},[Ft,bt,j]);const cn=i.useCallback(ie=>{S(lt=>{const Xe=new Set(lt);Xe.has(ie)?Xe.delete(ie):Xe.add(ie);try{j.setItem(Tl,JSON.stringify(Array.from(Xe)))}catch{}return Xe})},[j]),Is=i.useCallback((ie,lt)=>{if(!ie)return null;lt&&Ke.has(lt)&&wt(lt);const Xe=pt(ie,a("sessions.sidebar.folder.newFolderName"),lt);return M(Xe.id),se(Xe.name),Xe},[Ke,wt,pt,a]),sr=Ar(Hs),Sr=Ar(zs),nr=Ar(hn),gr=Ar(tr),Kn=Ar(An),gs=Ar(qe),Ps=Ar(ns),Mr=Ar(ps),Sn=Ar(Is),on=i.useCallback((ie,lt)=>{O(Xe=>{const Nt=new Map(Xe);return Nt.set(ie,lt+7),Nt})},[]),lr=i.useCallback(ie=>{O(lt=>{if(!lt.has(ie))return lt;const Xe=new Map(lt);return Xe.delete(ie),Xe})},[]),Fr=i.useCallback(ie=>{O(lt=>{let Xe=!1;const Nt=new Map(lt),Ht=`${ie}:`;for(const Cs of Nt.keys())Cs.startsWith(Ht)&&(Nt.delete(Cs),Xe=!0);return Xe?Nt:lt})},[]),Kr=i.useCallback(()=>{ge.current=Date.now()+150,O(new Map),v(()=>{const ie=new Set(G.map(lt=>lt.id));try{j.setItem(sa,JSON.stringify(Array.from(ie)))}catch{}return Le||Ns(ie),ie})},[G,Le,j,Ns]),Lr=i.useCallback(()=>{ge.current=Date.now()+150,O(new Map),v(()=>{const ie=new Set;try{j.setItem(sa,JSON.stringify([]))}catch{}return Le||Ns(ie),ie})},[Le,j,Ns]),xs=i.useCallback(ie=>{ge.current=Date.now()+150,Fr(ie),v(lt=>{const Xe=new Set(lt);Xe.has(ie)?Xe.delete(ie):Xe.add(ie);try{j.setItem(sa,JSON.stringify(Array.from(Xe)))}catch{}return Le||Ns(Xe),Xe})},[Le,Fr,j,Ns]),Rs=i.useMemo(()=>G.map(ie=>({...ie,normalizedPath:as(ie.path)})).filter(ie=>!!ie.normalizedPath),[G]),qn=i.useMemo(()=>Rs.map(ie=>ie.normalizedPath),[Rs]),pn=i.useMemo(()=>{const ie=new Set;return Rs.forEach(lt=>{if(lt.normalizedPath&&ie.add(lt.normalizedPath),Le)return;(Yt.get(lt.normalizedPath)??[]).forEach(Nt=>{const Ht=as(Nt.path);Ht&&ie.add(Ht)})}),[...ie].sort()},[Yt,Le,Rs]),X=i.useRef(null);i.useEffect(()=>{const ie=new Set(pn),lt=X.current;if(X.current=ie,!lt){Le&&pn.length>0&&Ed(pn,It.current);return}const Xe=pn.filter(Nt=>!lt.has(Nt));Xe.length!==0&&Ed(Xe,It.current)},[Le,pn]);const{github:st}=er(),ht=Ti(ie=>ie.status),At=Ti(ie=>ie.hasChecked),os=Lg(qn),rs=or(ie=>ie.ensureEntry),ds=or(ie=>ie.setParams),Es=or(ie=>ie.refreshTargets);ES({normalizedProjects:Rs,gitRepoStatus:os,setProjectRepoStatus:A,setProjectRootBranches:Oe});const Gs=ut(ie=>ie.isLoading);VS({isSessionsLoading:Gs,hasLoadedGlobalSessions:et,sessions:bt,archivedSessions:xt,normalizedProjects:Rs,isVSCode:Le,availableWorktreesByProject:Yt,cleanupSessions:ot});const{getSessionsForProject:Dn,getArchivedSessionsForProject:Nr}=MS({isVSCode:Le,sessions:bt,archivedSessions:xt,availableWorktreesByProject:Yt,normalizedProjects:Rs});gS({normalizedProjects:Rs,sessions:bt,archivedSessions:xt,availableWorktreesByProject:Yt,isVSCode:Le,isSessionsLoading:Gs,foldersMap:Qe,createFolder:pt,addSessionToFolder:Ze,cleanupSessions:ot});const kr=i.useRef(!1);fe&&D.has(fe)&&(kr.current=!!D.get(fe));const{projectSections:Bs,groupSearchDataByGroup:Or,sectionsForRender:dn,searchMatchCount:Ln}=yS({normalizedProjects:Rs,getSessionsForProject:Dn,getArchivedSessionsForProject:Nr,availableWorktreesByProject:Yt,projectRepoStatus:D,projectRootBranches:_e,lastRepoStatus:kr.current,buildGroupedSessions:_t,hasSessionSearchQuery:Ue,normalizedSessionSearchQuery:Be,filterSessionNodesForSearch:ys,buildGroupSearchText:Ss,foldersMap:Qe}),In=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:a("sessions.sidebar.empty.noMatches.title")}),s.jsx("p",{className:"typography-meta mt-1",children:a("sessions.sidebar.empty.noMatches.description")})]});vS({projectSections:Bs,activeProjectId:fe,activeSessionByProject:Se,setActiveSessionByProject:Re,currentSessionId:Ft,handleSessionSelect:Hs,newSessionDraftOpen:Gt,mobileVariant:t,openNewSessionDraft:Jt,setActiveMainTab:xe,setSessionSwitcherOpen:ve});const{getOrderedGroups:Nn}=jS(ae),Pn=i.useRef(!1);i.useEffect(()=>{if(Pn.current||Bs.length===0)return;const ie=Bs.flatMap(lt=>lt.groups.filter(Xe=>Xe.isArchivedBucket).map(Xe=>`${lt.project.id}:${Xe.id}`));ie.length>0&&q(lt=>new Set([...lt,...ie])),Pn.current=!0},[Bs]);const cr=i.useMemo(()=>{const ie=new Map,lt=new Map;return Bs.forEach(Xe=>{const Nt=gm(Xe.project.label?.trim()||Ei(Xe.project.normalizedPath,Ae)||Xe.project.normalizedPath);Xe.groups.forEach(Ht=>{const Cs=Ht.branch&&Ht.branch!=="HEAD"&&Ht.branch!==Nt?Ht.branch:null,qs={projectLabel:Nt,branchLabel:Cs},Qn=xn=>{xn.forEach(bn=>{const Jn=Xe.project.normalizedPath.length,Yr=lt.get(bn.session.id)??-1;Jn<Yr||(ie.set(bn.session.id,{node:bn,projectId:Xe.project.id,groupDirectory:Ht.directory,secondaryMeta:qs}),lt.set(bn.session.id,Jn),bn.children.length>0&&Qn(bn.children))})};Qn(Ht.sessions)})}),ie},[Bs,Ae]),un=Dr(ie=>ie.showRecentSection),di=Dr(ie=>ie.showArchivedSessions),Br=i.useMemo(()=>!un||Le?[]:D2(bt).sort((ie,lt)=>Ki(ie,lt,te)),[Le,te,bt,un]),Cr=i.useMemo(()=>{if(Le||!un)return[];const ie=Br,lt=Nt=>{const Ht=cr.get(Nt.id),Cs=as(Nt.directory??null),qs=Ht?.node??{session:Nt,children:[],worktree:null},xn=(Ue?ys([qs],Be):[qs])[0];if(!xn)return null;const bn=Ht?.secondaryMeta?{projectLabel:Ht.secondaryMeta.projectLabel,branchLabel:Le?null:Ht.secondaryMeta.branchLabel}:null;return{node:xn,projectId:Ht?.projectId??null,groupDirectory:Ht?.groupDirectory??Cs,secondaryMeta:bn}},Xe=ie.map(lt).filter(Nt=>Nt!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:Xe}]},[Br,ys,Ue,Le,Be,cr,un,a]),Mi=i.useMemo(()=>Cr.some(ie=>ie.items.length>0),[Cr]),ui=i.useMemo(()=>new Set(Br.map(ie=>ie.id)),[Br]),Tn=i.useMemo(()=>[...ui],[ui]);Ej({currentSessionId:Ft,sortedSessions:js,recentSessionIds:Tn,ensureSessionRenderable:is.ensureSessionRenderable});const dr=i.useMemo(()=>di?dn:dn.map(ie=>({...ie,groups:ie.groups.filter(lt=>!lt.isArchivedBucket)})),[dn,di]),kn=i.useMemo(()=>{const ie=new Set;return dr.forEach(lt=>{lt.groups.forEach(Xe=>{const Nt=as(Xe.directory??null),Ht=Xe.branch?.trim()||Kt.get(Nt||"")?.trim();!Nt||!Ht||ie.add(No(Nt,Ht))})}),[...ie]},[Kt,dr]),Yn=xw(kn);i.useEffect(()=>{if(!At||!ht?.connected||!st)return;const ie=[],lt=Date.now();if(dr.forEach(Nt=>{k.has(Nt.project.id)||Nt.groups.forEach(Ht=>{const Cs=as(Ht.directory??null),qs=Ht.branch?.trim()||Kt.get(Cs||"")?.trim();if(!Cs||!qs)return;const Qn=No(Cs,qs),xn=or.getState().entries[Qn],bn=!!xn?.status?.pr,Jn=`${Cs}::${qs}`,Yr=Math.max(xn?.lastRefreshAt??0,xn?.lastDiscoveryPollAt??0),gi=!!(xn?.isInitialStatusResolved&&!bn&&(!g.current.has(Jn)||lt-Yr>=E2));(!xn||!xn.isInitialStatusResolved||gi)&&(gi&&g.current.add(Jn),ie.push({directory:Cs,branch:qs}))})}),ie.length===0)return;const Xe=new Map;ie.forEach(Nt=>{const Ht=No(Nt.directory,Nt.branch,Nt.remoteName??null);Xe.has(Ht)||Xe.set(Ht,Nt)}),Xe.forEach((Nt,Ht)=>{rs(Ht),ds(Ht,{directory:Nt.directory,branch:Nt.branch,remoteName:Nt.remoteName??null,canShow:!0,github:st,githubAuthChecked:At,githubConnected:ht.connected})}),Es([...Xe.values()],{silent:!0,markInitialResolved:!0})},[k,rs,st,At,ht?.connected,Kt,Es,dr,ds]);const Fi=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",On="h-4.5 w-4.5",mi=WS({isDesktopShellRuntime:Pt,projectSections:Bs,projectHeaderSentinelRefs:Me}),Xs=Ar((ie,lt=0,Xe,Nt,Ht=!1,Cs,qs="project",Qn)=>s.jsx(b2,{node:ie,depth:lt,groupDirectory:Xe,projectId:Nt,archivedBucket:Ht,currentSessionId:Ft,pinnedSessionIds:te,expandedParents:w,hasSessionSearchQuery:Ue,normalizedSessionSearchQuery:Be,notifyOnSubtasks:ne,editingId:y,setEditingId:p,editTitle:x,setEditTitle:b,handleSaveEdit:nr,handleCancelEdit:gr,toggleParent:cn,handleSessionSelect:sr,handleSessionDoubleClick:Sr,togglePinnedSession:J,handleShareSession:Kn,copiedSessionId:ms,handleCopyShareUrl:gs,handleUnshareSession:Ps,openSidebarMenuKey:L,setOpenSidebarMenuKey:B,renamingFolderId:V,getFoldersForScope:rt,getSessionFolderId:at,removeSessionFromFolder:St,addSessionToFolder:Ze,createFolderAndStartRename:Sn,openContextPanelTab:_,handleDeleteSession:Mr,mobileVariant:t,alwaysShowActions:Qt,renderSessionNode:Xs,secondaryMeta:Cs,renderContext:qs,subtreeContainsActive:Qn?.subtreeContainsActive??df,subtreeContainsEditing:Qn?.subtreeContainsEditing??df,menuOpenSessionId:Qn?.menuOpenSessionId??null,nodeStructureKey:Qn?.nodeStructureKey??"",childRenderExtrasFor:Qn?.childRenderExtrasFor,liveSessionById:us})),ur=i.useCallback(ie=>{lr(ie),q(lt=>{const Xe=new Set(lt);return Xe.has(ie)?Xe.delete(ie):Xe.add(ie),Xe})},[lr]),hi=i.useMemo(()=>{const ie=new Map;for(const[lt,Xe]of Yn)ie.set(lt,{visualState:Xe.visualState,number:Xe.number,url:Xe.url,state:Xe.prState,draft:Xe.draft,title:Xe.title,base:Xe.base,head:Xe.head,checks:Xe.checks,canMerge:Xe.canMerge,mergeableState:Xe.mergeableState,repo:Xe.repo});return ie},[Yn]),Li=i.useCallback((ie,lt,Xe,Nt,Ht,Cs,qs)=>s.jsx(yN,{group:ie,groupKey:lt,projectId:Xe,hideGroupLabel:Nt,compactBodyPadding:Cs,hasSessionSearchQuery:Ue,normalizedSessionSearchQuery:Be,groupSearchDataByGroup:Or,visibleSessionCount:C.get(lt),collapsedGroups:H,hideDirectoryControls:r,collapsedFolderIds:Ke,toggleFolderCollapse:wt,renameFolder:jt,deleteFolder:Ve,showDeletionDialog:P,setDeleteFolderConfirm:re,renderSessionNode:Xs,projectRepoStatus:D,lastRepoStatus:kr.current,showMoreGroupSessions:on,resetGroupSessionLimit:lr,mobileVariant:t,alwaysShowActions:Qt,activeProjectId:fe,setActiveProjectIdOnly:W,setActiveMainTab:xe,setSessionSwitcherOpen:ve,openNewSessionDraft:es,addSessionToFolder:Ze,createFolderAndStartRename:Sn,renamingFolderId:V,renameFolderDraft:Z,setRenameFolderDraft:se,setRenamingFolderId:M,pinnedSessionIds:te,expandedParents:w,sessionOrderIndex:Js,currentSessionId:Ft,editingId:y,editTitle:x,openSidebarMenuKey:L,liveSessionById:us,prVisualStateByDirectoryBranch:hi,onToggleCollapsedGroup:ur,dragHandleProps:Ht,scrollContainerRef:qs}),[Ue,Be,Or,C,H,r,Ke,wt,jt,Ve,P,Xs,D,on,lr,t,Qt,fe,W,xe,ve,es,Ze,Sn,V,Z,te,w,Js,Ft,y,x,L,us,hi,ur]),qr=!Le&&un&&!Ue?s.jsx(DN,{sections:Cr,renderSessionNode:Xs,currentSessionId:Ft,editingId:y,openSidebarMenuKey:L,variant:"section"}):null,pi=!!(V||y||h),{selectionModeEnabled:Zs,hasSelection:Oi,selectedIdsSize:uo,bulkScopeIsArchived:fo,derivedSelectionScope:Bi,bulkScopeFolders:Y,bulkCanRemoveFromFolder:ke,handleToggleSelectionMode:Pe,handleExitSelectionMode:ze,handleBulkMoveToFolder:dt,handleBulkCreateFolderAndMove:yt,handleBulkRemoveFromFolder:ls,handleBulkDelete:Wt,confirmBulkDelete:Ks}=S2({isInlineEditing:pi,showDeletionDialog:P,foldersMap:Qe,addSessionsToFolder:nt,removeSessionsFromFolders:Dt,createFolderAndStartRename:Is,archiveSessions:ks,deleteSessions:cs,setBulkDeleteConfirm:je}),Bn=i.useCallback(()=>{xe("chat"),t&&ve(!1),Ce()},[t,Ce,xe,ve]),fr=i.useCallback(()=>{xe("chat"),t&&ve(!1),Jt()},[t,Jt,xe,ve]);return s.jsxs("div",{ref:m,className:De("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(wN,{hideDirectoryControls:r,showRecentControls:!Le,handleOpenDirectoryDialog:Ws,openNewSessionDraft:fr,canOpenMultiRun:G.length>0,openMultiRunLauncher:Bn,headerActionIconClass:On,headerActionButtonClass:Fi,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:f,sessionSearchQuery:d,setSessionSearchQuery:u,hasSessionSearchQuery:Ue,searchMatchCount:Ln,collapseAllProjects:Kr,expandAllProjects:Lr,openScheduledTasksDialog:()=>Fe(!0),selectionModeEnabled:Zs,onToggleSelectionMode:Pe}),s.jsx(LN,{topContent:qr,hasSharedSessions:Mi,sectionsForRender:dr,projectSections:Bs,activeProjectId:fe,showOnlyMainWorkspace:o,hasSessionSearchQuery:Ue,emptyState:jn,searchEmptyState:In,renderGroupSessions:Li,homeDirectory:Ae,collapsedProjects:k,hideDirectoryControls:r,projectRepoStatus:D,isDesktopShellRuntime:Pt,stuckProjectHeaders:mi,mobileVariant:t,alwaysShowActions:Qt,toggleProject:xs,setActiveProjectIdOnly:W,setActiveMainTab:xe,setSessionSwitcherOpen:ve,openNewSessionDraft:es,openNewWorktreeDialog:Je,openProjectEditDialog:N,removeProject:ce,projectHeaderSentinelRefs:Me,reorderProjects:be,getOrderedGroups:Nn,setGroupOrderByProject:le,openSidebarMenuKey:L,setOpenSidebarMenuKey:B,isInlineEditing:pi}),Zs&&Oi?s.jsx(j2,{selectedCount:uo,scopeKey:Bi,scopeFolders:Y,archivedBucket:fo,onMoveToFolder:dt,onCreateFolderAndMove:yt,onRemoveFromFolder:ls,canRemoveFromFolder:ke,onDelete:Wt,onDone:ze}):null,s.jsx(IN,{onOpenSettings:Ct,onOpenShortcuts:$,onOpenAbout:()=>Ie(!0),onOpenUpdate:vt,showRuntimeButtons:!Le,showUpdateButton:zt}),s.jsx(cm,{open:F,onOpenChange:R,info:Zt.info,downloading:Zt.downloading,downloaded:Zt.downloaded,progress:Zt.progress,error:Zt.error,onDownload:Zt.downloadUpdate,onRestart:Zt.restartToUpdate,runtimeType:Zt.runtimeType}),$s?s.jsx(HS,{open:!!$s,onOpenChange:ie=>{ie||N(null)},projectId:$s.id,projectName:$s.label||Ei($s.path,Ae),projectPath:$s.path,initialIcon:$s.icon,initialColor:$s.color,initialIconBackground:$s.iconBackground,onSave:we}):null,s.jsx(Lx,{open:T,onOpenChange:E,onWorktreeCreated:(ie,lt)=>{if(xe("chat"),t&&ve(!1),lt?.sessionId){Ut(lt.sessionId,ie);return}Jt({directoryOverride:ie,preserveDirectoryOverride:!0})}}),s.jsx(hS,{}),s.jsx(y2,{value:Q,setValue:K,showDeletionDialog:P,setShowDeletionDialog:me,onConfirm:hs}),s.jsx(v2,{value:ee,setValue:re,onConfirm:rn}),s.jsx(w2,{value:he,setValue:je,showDeletionDialog:P,setShowDeletionDialog:me,onConfirm:Ks})]})},vi=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,yr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},M2=()=>{const{t}=kt(),[e,n]=i.useState(!1),[r,o]=i.useState(!1),[a,c]=i.useState(null),[l,d]=i.useState([]),[u,m]=i.useState(!1),[f,g]=i.useState(!1),[y,p]=i.useState(!1),[x,b]=i.useState(!1),[h,N]=i.useState(new Set),w=ut(ue=>ue.getWorktreeMetadata),S=ut(ue=>ue.newSessionDraft),j=ut(ue=>ue.setNewSessionDraftTarget),k=ut(ue=>ue.setDraftBootstrapPendingDirectory),v=Bg,D=$g,A=ut(ue=>ue.deleteSessions),C=ut(ue=>ue.archiveSessions),O=Ee(ue=>ue.showDeletionDialog),T=Ee(ue=>ue.setShowDeletionDialog),E=Qs(ue=>ue.currentDirectory),F=Qs(ue=>ue.homeDirectory),R=Qs(ue=>ue.isHomeReady),L=ws(ue=>ue.projects),B=ws(ue=>ue.activeProjectId),{isMobile:V,isTablet:M,hasTouchInput:Z}=Er(),se=V||M||Z,Q=i.useMemo(()=>{const G=(B?L.find(fe=>fe.id===B)??null:null)?.path??E;return yr(G)},[B,E,L]),K=i.useCallback(ue=>{const fe=yr(ue.projectDirectory)||Q;return{id:(L.find(W=>yr(W.path)===fe)??null)?.id??`path:${fe}`,path:fe}},[Q,L]),ee=x&&h.size>0,re=i.useMemo(()=>{const ue=a?.worktree;return ue&&typeof ue.branch=="string"&&ue.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:G})=>typeof G.branch=="string"&&G.branch.trim().length>0)},[a?.worktree,l]),he=a?.mode==="worktree",je=he,te=y||!he||!re,Ne=y||!he;i.useEffect(()=>{r||!R||L.length>0||(o(!0),n(!0))},[r,R,L.length]);const J=i.useCallback(ue=>{c({sessions:ue.sessions,dateLabel:ue.dateLabel,mode:ue.mode??"session",worktree:ue.worktree??null})},[]),H=i.useCallback(()=>{c(null),d([]),m(!1),g(!1),p(!1),b(!1),N(new Set)},[]),q=i.useCallback(async ue=>{if(ue.sessions.length===0)return;if(ue.sessions.length===1){const W=ue.sessions[0];await v(W.id)?de.success(t("sessions.sidebar.session.delete.success")):de.error(t("sessions.sidebar.session.delete.error"));return}const G=ue.sessions.map(W=>W.id),{deletedIds:fe,failedIds:ce}=await A(G);if(fe.length>0){const W=ce.length>0?ce.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:ce.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:ce.length}):ue.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:ue.dateLabel}):void 0;de.success(fe.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:fe.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:fe.length}),{description:vi(W)})}ce.length>0&&de.error(ce.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:ce.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:ce.length}),{description:vi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[v,A,t]);i.useEffect(()=>Pr.onDeleteRequest(ue=>{if(!O&&(ue.mode??"session")==="session"){q(ue);return}J(ue)}),[J,O,q]),i.useEffect(()=>Pr.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1),g(!1),b(!1),N(new Set);return}const ue=a.sessions.map(ce=>{const W=w(ce.id);return W?{session:ce,metadata:W}:null}).filter(ce=>!!ce);d(ue),m(!1),b(!1),N(new Set);const G=new Map;if(a.worktree?.path&&G.set(yr(a.worktree.path),a.worktree),ue.forEach(({metadata:ce})=>{ce.path&&G.set(yr(ce.path),ce)}),G.size===0){b(!0);return}let fe=!1;return(async()=>{const ce=new Map,W=new Set;await Promise.all(Array.from(G.entries()).map(async([z,be])=>{try{const xe=await Vg(be.path);ce.set(z,xe),xe?.isDirty&&W.add(z)}catch{be.status&&(ce.set(z,be.status),be.status.isDirty&&W.add(z))}})).catch(z=>{console.warn("Failed to inspect worktree status before deletion:",z)}),!fe&&(N(W),b(!0),c(z=>{if(!z?.worktree?.path)return z;const be=yr(z.worktree.path),xe=ce.get(be);if(!xe)return z;const _=z.worktree.status;return _?.isDirty===xe.isDirty&&_?.ahead===xe.ahead&&_?.behind===xe.behind&&_?.upstream===xe.upstream?z:{...z,worktree:{...z.worktree,status:xe}}}),d(z=>z.map(be=>{const xe=yr(be.metadata.path),_=ce.get(xe);return _?{session:be.session,metadata:{...be.metadata,status:_}}:be})))})(),()=>{fe=!0}},[a,w]),i.useEffect(()=>{re||m(!1)},[re]);const ae=i.useCallback(async(ue,G)=>{const fe=u&&re,ce=K(ue),W=yr(ue.path),z=yr(ce.path);try{await _g(ce,ue,{deleteRemoteBranch:fe,deleteLocalBranch:G});const be=yr(S?.directoryOverride);return S?.open&&W&&be===W&&z&&(k(null),j({projectId:ce.id,directoryOverride:z},{force:!0})),yr(E)===W&&z&&Qs.getState().setDirectory(z,{showOverlay:!1}),!0}catch(be){return de.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:vi(be instanceof Error?be.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[re,E,u,K,S?.directoryOverride,S?.open,k,j,t]),le=i.useCallback((ue,G)=>{const fe=u&&re;(async()=>{if(!await ae(ue,G))return;const W=t(fe?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");de.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:vi(W)})})()},[re,u,ae,t]),Se=i.useCallback(async()=>{if(a){p(!0);try{const ue=je,G=ue&&u,fe=ue&&f;if(a.sessions.length===0&&he&&a.worktree){le(a.worktree,fe),H();return}if(a.sessions.length===1){const ce=a.sessions[0];if(!(he?await D(ce.id):await v(ce.id,{archiveWorktree:!1,deleteRemoteBranch:G,deleteLocalBranch:fe}))){de.error(t(he?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),p(!1);return}const z=!he&&ue?t(G?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;de.success(t(he?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:vi(z),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const ce=a.sessions.map(be=>be.id);let W=[],z=[];if(he){const be=await C(ce);W=be.archivedIds,z=be.failedIds}else{const be=await A(ce);W=be.deletedIds,z=be.failedIds}if(he&&a.worktree&&z.length===0&&le(a.worktree,fe),W.length>0){const be=!he&&ue?t(G?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,_=[z.length>0?he?z.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:z.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:z.length}):z.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:z.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:z.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,be].filter(Boolean).join(" ");de.success(he?W.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:W.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:W.length}):W.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:W.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:W.length}),{description:vi(_||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if(z.length>0&&(de.error(he?z.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:z.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:z.length}):z.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:z.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:z.length}),{description:vi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),W.length===0)){p(!1);return}}he&&a.sessions.length===1&&a.worktree&&le(a.worktree,fe),H()}finally{p(!1)}}},[a,u,f,v,A,D,C,H,je,he,le,t]),Re=a?.worktree??l[0]?.metadata??null,_e=a?a.mode==="worktree"?a.sessions.length===0?t("sessions.sidebar.dialogs.worktreeDelete.descriptionNoLinked"):a.sessions.length===1?t("sessions.sidebar.dialogs.worktreeDelete.descriptionOneLinked",{count:a.sessions.length}):t("sessions.sidebar.dialogs.worktreeDelete.descriptionManyLinked",{count:a.sessions.length}):a.sessions.length===1?a.dateLabel?t("sessions.sidebar.dialogs.sessionDelete.descriptionOneWithDate",{dateLabel:a.dateLabel}):t("sessions.sidebar.dialogs.sessionDelete.descriptionOne"):a.dateLabel?t("sessions.sidebar.dialogs.sessionDelete.descriptionManyWithDate",{count:a.sessions.length,dateLabel:a.dateLabel}):t("sessions.sidebar.dialogs.sessionDelete.descriptionMany",{count:a.sessions.length}):"",Oe=a?s.jsxs("div",{className:De(he?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:De(he?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[he&&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:De(he?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(ue=>s.jsxs("li",{className:De(he?"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:De(!he&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:ue.title||t("sessions.sidebar.session.untitled")})]},ue.id)),a.sessions.length>5&&s.jsx("li",{className:De(he?"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})})]})]}),he?s.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:t("sessions.sidebar.sessionDialogs.worktree.label")}),Re?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Re.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Re?Na(Re.path,F):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),ee&&s.jsx("p",{className:"typography-micro text-status-warning",children:t("sessions.sidebar.sessionDialogs.worktree.uncommittedWarning")})]}):s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:t("sessions.sidebar.sessionDialogs.delete.note")})})]}):null,Me=he?re?s.jsxs("button",{type:"button",onClick:()=>{te||m(ue=>!ue)},disabled:te,className:De("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",te?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(I,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteRemoteBranch")]}):s.jsx("span",{className:"text-xs text-muted-foreground/70",children:t("sessions.sidebar.sessionDialogs.actions.remoteBranchInfoUnavailable")}):null,ge=he?s.jsxs("button",{type:"button",onClick:()=>{Ne||g(ue=>!ue)},disabled:Ne,className:De("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(I,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(I,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Ae=he?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:[ge,Me]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{variant:"ghost",onClick:H,disabled:y,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{variant:"destructive",onClick:Se,disabled:y,children:t(y?"sessions.sidebar.sessionDialogs.actions.deleting":"sessions.sidebar.sessionDialogs.actions.deleteWorktree")})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>T(!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(I,{name:"checkbox-blank",className:"size-4"}):s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}),t("sessions.sidebar.dialogs.neverAsk")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{variant:"ghost",onClick:H,disabled:y,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{variant:"destructive",onClick:Se,disabled:y,children:y?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),pe=he?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:[se?s.jsx($a,{open:!!a,onClose:()=>{y||H()},title:pe,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Ae}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[_e&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:_e}),Oe]})}):s.jsx(Os,{open:!!a,onOpenChange:ue=>{if(!ue){if(y)return;H()}},children:s.jsxs(Ls,{className:De(he?"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(Us,{children:[s.jsxs(_s,{className:De(he&&"flex items-center gap-2"),children:[he&&s.jsx(I,{name:"delete-bin",className:"h-5 w-5"}),pe]}),_e&&s.jsx(an,{children:_e})]}),s.jsx("div",{className:De(he&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:Oe}),s.jsx(ar,{className:"mt-2 gap-2 pt-1 pb-1",children:Ae})]})}),s.jsx(Ox,{open:e,onOpenChange:n})]})},rc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),F2=(t,e)=>{const n=rc(t),r=rc(e);return`${n}-${r}`.substring(0,60)},ff=(t,e)=>`${t}/${e}`,L2=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},mf=(t,e)=>{const n=L2(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};Kg(t.id,n),ut.getState().markSessionAsOpenChamberCreated(t.id),jr.getState().upsertSession(o);try{ka().ensureChild(n,{bootstrap:!1}).setState(c=>{const l=c.session.findIndex(u=>u.id===t.id);if(l>=0&&c.session[l]===o)return c;const d=l>=0?c.session.map((u,m)=>m===l?o:u):[...c.session,o].sort((u,m)=>u.id.localeCompare(m.id));return{session:d,sessionTotal:Math.max(c.sessionTotal,d.length),limit:Math.max(c.limit,d.length)}})}catch{}return o},O2=()=>{const t=ws.getState(),e=t.activeProjectId;if(!e)return null;const n=t.projects.find(o=>o.id===e);if(n?.path)return{id:n.id,path:n.path};const r=Qs.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},Rl=io()(Sf(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=O2();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,m=await sm(d)&&e.isolateRuns!==!1,f=rc(n),g=m?await Ua(d):void 0,y=m?await zg(d):null,p=[],x=c?.filter(S=>S.trim().length>0)??[];for(let S=0;S<r.length;S++){const j=r[S],k=j.prompt,v=new Map;for(const A of j.models){const C=`${A.providerID}:${A.modelID}`;v.set(C,(v.get(C)||0)+1)}const D=new Map;for(const A of j.models){const C=`${A.providerID}:${A.modelID}`,O=v.get(C)||1,T=(D.get(C)||0)+1;D.set(C,T);const E=F2(A.providerID,A.modelID),F=r.length>1?`g${S+1}`:void 0,R=O>1?ff(f,`${E}/${T}`):ff(f,E),L=F?`${F}/${R}`:R,B=YN({groupSlug:f,runGroup:F,providerID:A.providerID,modelID:A.modelID,index:O>1?T:void 0});try{if(!m){const se=await zn.withDirectory(d,()=>zn.createSession({title:B}));mf(se,d),p.push({sessionId:se.id,worktreePath:d,providerID:A.providerID,modelID:A.modelID,variant:A.variant,prompt:k});continue}const V=await Wg(l,{preferredName:L,mode:"new",branchName:L,worktreeName:L,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:x,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:y}),M={...V,createdFromBranch:g,kind:"standard"},Z=await zn.withDirectory(V.path,()=>zn.createSession({title:B}));mf(Z,V.path),ut.getState().setWorktreeMetadata(Z.id,M),p.push({sessionId:Z.id,worktreePath:V.path,providerID:A.providerID,modelID:A.modelID,variant:A.variant,prompt:k})}catch(V){console.warn("[MultiRun] Failed to create session:",V)}}}const b=c?.filter(S=>S.trim().length>0)??[];b.length>0&&Ug(l,b).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const h=p.map(S=>S.sessionId),N=p[0]?.sessionId??null;if(h.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const w=a?.map(S=>({type:"file",mime:S.mime,filename:S.filename,url:S.url}));return(async()=>{try{const S=Hg.getState().expandText;await Promise.allSettled(p.map(async j=>{try{const k=await S(j.prompt).catch(()=>j.prompt);await Gg({sessionId:j.sessionId,directory:j.worktreePath,content:k,providerID:j.providerID,modelID:j.modelID,variant:j.variant,agent:o,files:w})}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(S){console.warn("[MultiRun] Failed to start runs:",S)}})(),t({isLoading:!1}),{groupSlug:f,sessionIds:h,firstSessionId:N}}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"})),B2="oc:lastWorktreeSourceBranch";function uh(t){const e=gt.c(30),{git:n}=er(),r=Hf(t),o=yc(t),a=wc(t),c=qg(t),l=wn(W2),d=wn(z2);let u,m;e[0]!==t||e[1]!==d||e[2]!==n||e[3]!==o||e[4]!==a?(u=()=>{!t||!n||o!==null||a||d(t,n,{silent:!0})},m=[t,n,d,o,a],e[0]=t,e[1]=d,e[2]=n,e[3]=o,e[4]=a,e[5]=u,e[6]=m):(u=e[5],m=e[6]),i.useEffect(u,m);let f;e[7]!==r?.all||e[8]!==t||e[9]!==l||e[10]!==n||e[11]!==o?(f=()=>{!t||!n||o===!0&&(r?.all||l(t,n))},e[7]=r?.all,e[8]=t,e[9]=l,e[10]=n,e[11]=o,e[12]=f):f=e[12];const g=r?.all;let y;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==g?(y=[t,n,o,g,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=g,e[18]=y):y=e[18],i.useEffect(f,y);const p=a||o===!0&&c;let x;e:{if(!r?.all){let v;e[19]===Symbol.for("react.memo_cache_sentinel")?(v=[],e[19]=v):v=e[19],x=v;break e}let k;e[20]!==r.all?(k=r.all.filter($2).sort(),e[20]=r.all,e[21]=k):k=e[21],x=k}const b=x;let h;e:{if(!r?.all){let v;e[22]===Symbol.for("react.memo_cache_sentinel")?(v=[],e[22]=v):v=e[22],h=v;break e}let k;e[23]!==r.all?(k=r.all.filter(_2).map(V2).sort(),e[23]=r.all,e[24]=k):k=e[24],h=k}const N=h;let w;e:{if(!t){w=null;break e}if(o!==null){w=o;break e}if(p){w=null;break e}w=r?.all?!0:null}const S=w;let j;return e[25]!==S||e[26]!==p||e[27]!==b||e[28]!==N?(j={localBranches:b,remoteBranches:N,isLoading:p,isGitRepository:S},e[25]=S,e[26]=p,e[27]=b,e[28]=N,e[29]=j):j=e[29],j}function V2(t){return t.replace(/^remotes\//,"")}function _2(t){return t.startsWith("remotes/")}function $2(t){return!t.startsWith("remotes/")}function z2(t){return t.fetchStatus}function W2(t){return t.fetchBranches}const U2=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=kt(),{localBranches:l,remoteBranches:d,isLoading:u,isGitRepository:m}=uh(t),f=i.useMemo(()=>[...l,...d.map(y=>`remotes/${y}`)],[l,d]);i.useEffect(()=>{if(o||u||f.length===0||e&&f.includes(e))return;(async()=>{try{const p=t?await Ua(t).catch(()=>null):null,x=localStorage.getItem(B2);x&&f.includes(x)?n(x):p&&f.includes(p)?n(p):f.includes("main")?n("main"):f.includes("master")?n("master"):f[0]&&n(f[0])}catch{}})()},[f,t,o,u,n,e]);const g=o||!m||u;return s.jsxs("div",{children:[s.jsxs(Un,{value:e,onValueChange:n,disabled:g,children:[s.jsx(Hn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(Cn,{placeholder:c(u?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(Gn,{className:"max-h-[280px] max-w-[320px]",children:u?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.loadingBranches")}):l.length===0&&d.length===0?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.noBranchesFound")}):s.jsxs(s.Fragment,{children:[l.length>0&&s.jsxs($l,{children:[s.jsx(Md,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(y=>s.jsx(Ts,{value:y,className:"whitespace-normal break-all",children:y},y))]}),l.length>0&&d.length>0&&s.jsx(Yg,{}),d.length>0&&s.jsxs($l,{children:[s.jsx(Md,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(y=>s.jsx(Ts,{value:`remotes/${y}`,className:"whitespace-normal break-all",children:y},`remotes/${y}`))]})]})})]}),m===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},H2=10*1024*1024,El=5,pa=t=>{const e=gt.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",tabIndex:-1,className:"inline-flex items-center justify-center text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:s.jsx(I,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(Rt,{children:[r,s.jsx(Mt,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},Ni=t=>{const e=gt.c(9),{htmlFor:n,required:r,children:o,info:a}=t;let c;e[0]!==r?(c=r&&s.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),e[0]=r,e[1]=c):c=e[1];let l;e[2]!==o||e[3]!==n||e[4]!==c?(l=s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,c]}),e[2]=o,e[3]=n,e[4]=c,e[5]=l):l=e[5];const d=a&&a;let u;return e[6]!==l||e[7]!==d?(u=s.jsxs("div",{className:"flex items-center gap-1.5",children:[l,d]}),e[6]=l,e[7]=d,e[8]=u):u=e[8],u},G2=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=kt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:Ao(),prompt:"",models:[]}]),[u,m]=i.useState(""),[f,g]=i.useState([]),[y,p]=i.useState(!1),[x,b]=i.useState([]),[h,N]=i.useState(!1),[w,S]=i.useState(!1),[j,k]=i.useState(!0),v=i.useRef(null),D=Qs(z=>z.currentDirectory??null),A=Qs(z=>z.homeDirectory??null),C=i.useMemo(()=>{if(typeof window>"u")return null;const z=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof z=="string"&&z.trim().length>0?z.trim():null},[]),O=ws(z=>z.activeProjectId),T=ws(z=>z.setActiveProjectIdOnly),E=ws(z=>z.projects),[F,R]=i.useState(()=>O??null);i.useEffect(()=>{if(O){R(O);return}!F&&E.length>0&&R(E[0].id)},[O,E,F]);const L=i.useMemo(()=>F?E.find(z=>z.id===F)??null:null,[E,F]),B=L?.path??D,V=i.useCallback(z=>{R(z),z!==O&&T(z)},[O,T]),{currentTheme:M}=Gr(),Z=i.useCallback(z=>{const be=z.label?.trim()||Ei(z.path,A),xe=z.icon?kc[z.icon]:null,_=z.color?Ga[z.color]:void 0,ye=xe?s.jsx(I,{name:xe,className:"h-3.5 w-3.5 shrink-0",style:_?{color:_}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:_?{color:_}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[z.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:z.iconBackground?{backgroundColor:z.iconBackground}:void 0,children:s.jsx(Ka,{project:{id:z.id,iconImage:z.iconImage??null},options:{themeVariant:M.metadata.variant,iconColor:M.colors.surface.foreground},className:"h-full w-full object-contain",fallback:ye})}):ye,s.jsx("span",{className:"truncate",children:be})]})},[A,M.metadata.variant,M.colors.surface.foreground]),se=i.useMemo(()=>{if(L?.path)return{id:L.id,path:L.path};const z=D??C;return z?{id:`path:${z}`,path:z}:null},[L,D,C]),[Q]=i.useState(()=>typeof window<"u"?hr():!1),K=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),ee=Mf(),re=i.useMemo(()=>{if(typeof window>"u")return null;const z=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof z=="number"&&Number.isFinite(z)&&z>0)return z;if(typeof navigator>"u")return null;const be=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!be)return null;const xe=Number.parseInt(be[1],10),_=Number.parseInt(be[2],10);return Number.isNaN(xe)?null:xe===10?_:xe},[]),he=i.useMemo(()=>Q&&K||ee?"pl-[5.5rem]":"pl-3",[Q,K,ee]),je=i.useMemo(()=>!Q||!K||re===null?"":re>=26?"h-12":re<=15?"h-14":"",[Q,K,re]),te=i.useCallback(async z=>{z.target.closest("button, a, input, select, textarea")||z.button===0&&Q&&await Qg()},[Q]);i.useEffect(()=>{if(!n)return;const z=be=>{be.key==="Escape"&&(be.preventDefault(),be.stopPropagation(),n())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[n]);const[Ne,J]=i.useState(""),{isLoading:H,isGitRepository:q}=uh(B),ae=i.useRef(!1),le=q===!0,Se=le&&j;i.useEffect(()=>{if(q===!1){ae.current=!0,k(!1);return}q===!0&&ae.current&&(ae.current=!1,k(!0))},[q]);const Re=Rl(z=>z.createMultiRun),_e=Rl(z=>z.error),Oe=Rl(z=>z.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d(z=>{const be=[...z];return be.length>0&&!be[0].prompt.trim()&&(be[0]={...be[0],prompt:t}),be})},[t]),i.useEffect(()=>{if(!se)return;let z=!1;return S(!0),(async()=>{try{const be=await Jg(se);z||b(be)}catch{}finally{z||S(!1)}})(),()=>{z=!0}},[se]);const Me=i.useCallback((z,be)=>{d(xe=>xe.map(_=>_.id===z?{..._,...be}:_))},[]),ge=i.useCallback(z=>{d(be=>be.filter(xe=>xe.id!==z))},[]),Ae=i.useCallback(()=>{d(z=>[...z,{id:Ao(),prompt:"",models:[]}])},[]),pe=async z=>{const be=z.target.files;if(!be)return;let xe=0;for(let _=0;_<be.length;_++){const ye=be[_];if(ye.size>H2){de.error(o("multirun.launcher.toast.fileTooLarge",{fileName:ye.name}));continue}try{const $=await new Promise((Ie,ve)=>{const Fe=new FileReader;Fe.onload=()=>Ie(Fe.result),Fe.onerror=ve,Fe.readAsDataURL(ye)});g(Ie=>[...Ie,{id:Ao(),filename:ye.name,mimeType:ye.type||"application/octet-stream",size:ye.size,dataUrl:$}]),xe++}catch($){console.error("File attach failed",$),de.error(o("multirun.launcher.toast.attachFailed",{fileName:ye.name}))}}xe>0&&de.success(xe===1?o("multirun.launcher.toast.attachedSingle",{count:xe}):o("multirun.launcher.toast.attachedPlural",{count:xe})),v.current&&(v.current.value="")},ue=z=>{g(be=>be.filter(xe=>xe.id!==z))},G=i.useMemo(()=>l.reduce((z,be)=>z+be.models.length,0),[l]),fe=async z=>{z.preventDefault();const be=l.filter(xe=>xe.prompt.trim()&&xe.models.length>=1);if(be.length!==0&&!(G<1)){p(!0),Oe();try{F&&F!==O&&T(F);const xe=f.map(ve=>({mime:ve.mimeType,filename:ve.filename,url:ve.dataUrl})),_=x.filter(ve=>ve.trim().length>0),ye=be.map(ve=>({prompt:ve.prompt.trim(),models:ve.models.map(Fe=>({providerID:Fe.providerID,modelID:Fe.modelID,displayName:Fe.displayName,variant:Fe.variant}))})),$={name:a.trim(),groups:ye,agent:u||void 0,worktreeBaseBranch:Se?Ne:void 0,isolateRuns:Se,files:xe.length>0?xe:void 0,setupCommands:_.length>0?_:void 0},Ie=await Re($);Ie&&(Ie.firstSessionId&&ut.getState().setCurrentSession(Ie.firstSessionId),e?.())}finally{p(!1)}}},ce=!!(a.trim()&&l.some(z=>z.prompt.trim()&&z.models.length>=1)&&G>=1&&B&&!H&&(q===!1||!Se||Ne)),W=x.filter(z=>z.trim()).length;return s.jsxs("form",{onSubmit:fe,className:"flex flex-col h-full bg-background",children:[r?null:s.jsxs("header",{onMouseDown:te,className:De("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",he,je),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(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":o("multirun.launcher.actions.closeEsc"),className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:s.jsx(I,{name:"close",className:"h-5 w-5"})})}),s.jsx(Mt,{children:s.jsx("p",{children:o("multirun.launcher.actions.closeEsc")})})]})})]}),s.jsx(za,{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(Ni,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),E.length>0?s.jsxs(Un,{value:F??void 0,onValueChange:V,children:[s.jsx(Hn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:L?s.jsx(Cn,{children:Z(L)}):s.jsx(Cn,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(Gn,{fitContent:!0,children:E.map(z=>s.jsx(Ts,{value:z.id,className:"max-w-[24rem]",children:Z(z)},z.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(Ni,{htmlFor:"group-name",required:!0,info:s.jsx(pa,{children:o("multirun.launcher.groupName.info")}),children:o("multirun.launcher.groupName.label")}),s.jsx(vn,{id:"group-name",value:a,onChange:z=>c(z.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(Ni,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(pa,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(U2,{directory:B,value:Ne,onChange:J,disabled:!Se,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(Ri,{checked:j,onChange:k,disabled:!le,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(Ni,{htmlFor:"multirun-agent",info:s.jsx(pa,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(ah,{value:u,onChange:m,id:"multirun-agent"})]})]}),s.jsxs(to,{open:h,onOpenChange:N,children:[s.jsxs(Bo,{className:"w-full flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-lg hover:bg-[var(--interactive-hover)]/50 transition-colors group",children:[s.jsx(I,{name:"terminal",className:"h-3.5 w-3.5 text-muted-foreground/70"}),s.jsx("span",{className:"typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors",children:o("multirun.launcher.setupCommands.label")}),W>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:W}),s.jsx(I,{name:"arrow-down-s",className:De("h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto",h&&"rotate-180")})]}),s.jsx(so,{children:s.jsx("div",{className:"pt-2 space-y-1.5",children:w?s.jsx("p",{className:"typography-meta text-muted-foreground/70 px-2",children:o("multirun.launcher.setupCommands.loading")}):s.jsxs(s.Fragment,{children:[x.map((z,be)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(vn,{value:z,onChange:xe=>{const _=[...x];_[be]=xe.target.value,b(_)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>b(x.filter((xe,_)=>_!==be)),className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":o("multirun.launcher.setupCommands.removeCommandAria"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})})]},`${z}-${be}`)),s.jsxs("button",{type:"button",onClick:()=>b([...x,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(I,{name:"add",className:"h-3 w-3"}),o("multirun.launcher.setupCommands.addCommand")]})]})})})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Ni,{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:v,type:"file",multiple:!0,className:"hidden",onChange:pe,accept:"*/*"}),s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>v.current?.click(),className:"inline-flex items-center gap-1 h-6 px-2 rounded-md typography-micro text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(I,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(Mt,{children:o("multirun.launcher.attachments.tooltip")})]}),f.map(z=>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:[z.mimeType.startsWith("image/")?s.jsx(I,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(I,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:z.filename,children:z.filename}),s.jsx("button",{type:"button",onClick:()=>ue(z.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(I,{name:"close",className:"h-3 w-3"})})]},z.id))]})]}),l.map((z,be)=>s.jsx(K2,{group:z,groupIndex:be,canRemove:l.length>1,onUpdate:Me,onRemove:ge},z.id)),s.jsxs("button",{type:"button",onClick:Ae,className:"flex items-center gap-1.5 py-2 px-3 -mx-3 rounded-lg typography-meta font-medium text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(I,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),_e&&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:_e})]})})}),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:[!Se&&q!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(I,{name:"information",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:o("multirun.launcher.project.gitRequired")})]}):null,s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:n,children:o("multirun.launcher.actions.cancel")}),s.jsx($e,{type:"submit",size:"sm",disabled:!ce||y,children:y?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:G})})})]})})]})},K2=t=>{const e=gt.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=kt(),[d,u]=i.useState(!1),[m,f]=i.useState(""),[g,y]=i.useState(!1),[p,x]=i.useState(""),[b,h]=i.useState(!1),[N,w]=i.useState(""),S=i.useRef(null),j=i.useRef(null),k=i.useRef(null),v=i.useRef(null);let D;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(D=_=>{n.models.length>=El||a(n.id,{models:[...n.models,_]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=D):D=e[3];const A=D;let C;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(C=_=>{a(n.id,{models:n.models.filter((ye,$)=>$!==_)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=C):C=e[7];const O=C;let T;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(T=(_,ye)=>{a(n.id,{models:n.models.map(($,Ie)=>Ie===_?ye:$)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=T):T=e[11];const E=T;let F;e[12]===Symbol.for("react.memo_cache_sentinel")?(F=(_,ye)=>{if(_.startsWith("/")){const Fe=_.indexOf(" "),Ce=_.indexOf(`
211
- `),ne=Math.min(Fe===-1?_.length:Fe,Ce===-1?_.length:Ce);if(ye<=ne&&Fe===-1){x(_.substring(1,ne)),y(!0),u(!1),h(!1);return}}y(!1);const $=_.substring(0,ye),Ie=$.lastIndexOf("#");if(Ie!==-1){const Fe=Ie>0?$[Ie-1]:null,Ce=$.substring(Ie+1);if((!Fe||/\s/.test(Fe))&&!Ce.includes(" ")&&!Ce.includes(`
212
- `)){w(Ce),h(!0),u(!1);return}}h(!1);const ve=$.lastIndexOf("@");if(ve!==-1){const Fe=ve>0?$[ve-1]:null,Ce=$.substring(ve+1);(!Fe||/\s/.test(Fe))&&!Ce.includes(" ")&&!Ce.includes(`
213
- `)?(f(Ce),u(!0)):u(!1);return}u(!1)},e[12]=F):F=e[12];const R=F;let L;e[13]!==n.id||e[14]!==a?(L=_=>{a(n.id,{prompt:_})},e[13]=n.id,e[14]=a,e[15]=L):L=e[15];const B=L;let V;e[16]!==n.prompt||e[17]!==B?(V=_=>{const ye=n.prompt,Ie=S.current?.selectionStart??ye.length,Fe=ye.substring(0,Ie).lastIndexOf("@"),Ce=_.relativePath&&_.relativePath.trim().length>0?_.relativePath.trim():_.path||_.name,ne=Fe!==-1?Fe:Ie,P=`${ye.substring(0,ne)}@${Ce} ${ye.substring(Ie)}`,me=ne+Ce.length+2;B(P),u(!1),f(""),requestAnimationFrame(()=>{const oe=S.current;oe&&(oe.selectionStart=me,oe.selectionEnd=me,oe.focus()),R(P,me)})},e[16]=n.prompt,e[17]=B,e[18]=V):V=e[18];const M=V;let Z;e[19]!==n.prompt||e[20]!==B?(Z=_=>{const ye=n.prompt,Ie=S.current?.selectionStart??ye.length,Fe=ye.substring(0,Ie).lastIndexOf("@"),Ce=Fe!==-1?Fe:Ie,ne=`${ye.substring(0,Ce)}@${_} ${ye.substring(Ie)}`,P=Ce+_.length+2;B(ne),u(!1),f(""),requestAnimationFrame(()=>{const me=S.current;me&&(me.selectionStart=P,me.selectionEnd=P,me.focus()),R(ne,P)})},e[19]=n.prompt,e[20]=B,e[21]=Z):Z=e[21];const se=Z;let Q;e[22]!==B?(Q=_=>{const ye=`/${_.name} `;B(ye),y(!1),x(""),h(!1),requestAnimationFrame(()=>{const $=S.current;$&&($.focus(),$.selectionStart=$.value.length,$.selectionEnd=$.value.length),R(ye,ye.length)})},e[22]=B,e[23]=Q):Q=e[23];const K=Q;let ee;e[24]!==n.prompt||e[25]!==B?(ee=(_,ye)=>{const $=n.prompt,ve=S.current?.selectionStart??$.length,Ce=$.substring(0,ve).lastIndexOf("#"),ne=Ce!==-1?Ce:ve,P=`${$.substring(0,ne)}#${ye} ${$.substring(ve)}`,me=ne+ye.length+2;B(P),h(!1),w(""),requestAnimationFrame(()=>{const oe=S.current;oe&&(oe.selectionStart=me,oe.selectionEnd=me,oe.focus()),R(P,me)})},e[24]=n.prompt,e[25]=B,e[26]=ee):ee=e[26];const re=ee;let he;e[27]!==g||e[28]!==d||e[29]!==b?(he=_=>{if(g&&k.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")){_.preventDefault(),k.current.handleKeyDown(_.key);return}d&&j.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")&&(_.preventDefault(),j.current.handleKeyDown(_.key)),b&&v.current&&(_.key==="Enter"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="Escape"||_.key==="Tab")&&(_.preventDefault(),v.current.handleKeyDown(_.key))},e[27]=g,e[28]=d,e[29]=b,e[30]=he):he=e[30];const je=he,te=r+1;let Ne;e[31]!==l||e[32]!==te?(Ne=l("multirun.launcher.groups.groupLabel",{index:te}),e[31]=l,e[32]=te,e[33]=Ne):Ne=e[33];let J;e[34]!==Ne?(J=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ne}),e[34]=Ne,e[35]=J):J=e[35];let H;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(H=o&&s.jsx("button",{type:"button",onClick:()=>c(n.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":l("multirun.launcher.groups.removeGroup"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=H):H=e[40];let q;e[41]!==J||e[42]!==H?(q=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[J,H]}),e[41]=J,e[42]=H,e[43]=q):q=e[43];let ae;e[44]!==l?(ae=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=ae):ae=e[45];let le;e[46]!==ae?(le=s.jsx(Ni,{required:!0,children:ae}),e[46]=ae,e[47]=le):le=e[47];const Se=n.prompt;let Re;e[48]!==B?(Re=_=>{const ye=_.target.value;B(ye);const $=_.target.selectionStart??ye.length;R(ye,$)},e[48]=B,e[49]=Re):Re=e[49];let _e;e[50]!==l?(_e=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=_e):_e=e[51];let Oe;e[52]!==n.prompt||e[53]!==je||e[54]!==Re||e[55]!==_e?(Oe=s.jsx(Ci,{ref:S,value:Se,onChange:Re,onKeyDown:je,placeholder:_e,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]=je,e[54]=Re,e[55]=_e,e[56]=Oe):Oe=e[56];let Me;e[57]!==p||e[58]!==K||e[59]!==g?(Me=g?s.jsx(Xf,{ref:k,searchQuery:p,onCommandSelect:K,onClose:()=>y(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=p,e[58]=K,e[59]=g,e[60]=Me):Me=e[60];let ge;e[61]!==se||e[62]!==M||e[63]!==m||e[64]!==d?(ge=d?s.jsx(Zf,{ref:j,searchQuery:m,onFileSelect:M,onAgentSelect:se,onClose:()=>u(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=se,e[62]=M,e[63]=m,e[64]=d,e[65]=ge):ge=e[65];let Ae;e[66]!==re||e[67]!==b||e[68]!==N?(Ae=b?s.jsx(em,{ref:v,searchQuery:N,onSnippetSelect:re,onClose:()=>h(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=re,e[67]=b,e[68]=N,e[69]=Ae):Ae=e[69];let pe;e[70]!==Oe||e[71]!==Me||e[72]!==ge||e[73]!==Ae?(pe=s.jsxs("div",{className:"relative",children:[Oe,Me,ge,Ae]}),e[70]=Oe,e[71]=Me,e[72]=ge,e[73]=Ae,e[74]=pe):pe=e[74];let ue;e[75]!==le||e[76]!==pe?(ue=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[le,pe]}),e[75]=le,e[76]=pe,e[77]=ue):ue=e[77];let G;e[78]!==l?(G=l("multirun.launcher.models.info",{max:El}),e[78]=l,e[79]=G):G=e[79];let fe;e[80]!==G?(fe=s.jsx(pa,{children:G}),e[80]=G,e[81]=fe):fe=e[81];let ce;e[82]!==l?(ce=l("multirun.launcher.models.label"),e[82]=l,e[83]=ce):ce=e[83];let W;e[84]!==fe||e[85]!==ce?(W=s.jsx(Ni,{required:!0,info:fe,children:ce}),e[84]=fe,e[85]=ce,e[86]=W):W=e[86];let z;e[87]!==n.models||e[88]!==A||e[89]!==O||e[90]!==E?(z=s.jsx(ch,{selectedModels:n.models,onAdd:A,onRemove:O,onUpdate:E,minModels:1,maxModels:El}),e[87]=n.models,e[88]=A,e[89]=O,e[90]=E,e[91]=z):z=e[91];let be;e[92]!==W||e[93]!==z?(be=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[W,z]}),e[92]=W,e[93]=z,e[94]=be):be=e[94];let xe;return e[95]!==q||e[96]!==ue||e[97]!==be?(xe=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[q,ue,be]}),e[95]=q,e[96]=ue,e[97]=be,e[98]=xe):xe=e[98],xe},q2=i.createContext(null),Y2=t=>{const e=gt.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(q2.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},hf=ao(()=>oo(()=>import("./TerminalView-DGEBNuAp.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(t=>({default:t.TerminalView}))),Q2=ao(()=>oo(()=>import("./DiagramView-BmHROYsX.js"),__vite__mapDeps([9,1,2,4,5,3,6,7,8])).then(t=>({default:t.DiagramView}))),J2=ao(()=>oo(()=>import("./NewWorktreeDialog-CTMiE7Xd.js").then(t=>t.a7),__vite__mapDeps([6,1,2,3,4,5,7])).then(t=>({default:t.SettingsView}))),X2=ao(()=>oo(()=>import("./SettingsWindow-ChwLyQAe.js"),__vite__mapDeps([10,1,2,3,4,5,6,7])).then(t=>({default:t.SettingsWindow}))),Z2=ao(()=>oo(()=>import("./MultiRunWindow-yZoCT7F7.js"),__vite__mapDeps([11,1,2,3,4,5,6,7,8])).then(t=>({default:t.MultiRunWindow}))),ek=()=>{const o=Ee(ee=>ee.isSidebarOpen),a=Ee(ee=>ee.isRightSidebarOpen),c=Ee(ee=>ee.isBottomTerminalOpen),l=Ee(ee=>ee.setRightSidebarOpen),d=Ee(ee=>ee.setBottomTerminalOpen),u=Ee(ee=>ee.activeMainTab),m=Ee(ee=>ee.setIsMobile),f=Ee(ee=>ee.isSessionSwitcherOpen),g=Ee(ee=>ee.isSettingsDialogOpen),y=Ee(ee=>ee.setSettingsDialogOpen),p=Ee(ee=>ee.isMultiRunLauncherOpen),x=Ee(ee=>ee.setMultiRunLauncherOpen),b=Ee(ee=>ee.multiRunLauncherPrefillPrompt),{isMobile:h,isTablet:N}=Er(),w=i.useRef(!1),S=i.useRef(!1),j=i.useRef(!1),[k,v]=i.useState(!1),[D,A]=i.useState(!1),[C,O]=i.useState(!1),[T,E]=i.useState(!1),F=i.useCallback(ee=>{v(ee),Ee.getState().setSessionSwitcherOpen(ee)},[]),R=i.useRef(!1),L=i.useRef(typeof window>"u"?0:window.innerWidth),B=ld(-L.current),V=tt.useRef(0),M=ld(L.current),Z=tt.useRef(0);tt.useEffect(()=>{h&&(V.current=window.innerWidth,Z.current=window.innerWidth)},[h]),tt.useEffect(()=>{if(!h){O(!1);return}k&&O(!0),cd(B,k?0:-V.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[k,h,B]),tt.useEffect(()=>{if(!h){E(!1);return}R.current=D,D&&E(!0),cd(M,D?0:Z.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[h,D,M]),tt.useEffect(()=>{if(h)return B.on("change",ee=>{const re=V.current||L.current,he=k||ee>-re+.5;O(je=>je===he?je:he)})},[h,B,k]),tt.useEffect(()=>{if(h)return M.on("change",ee=>{const re=Z.current||L.current,he=D||ee<re-.5;E(je=>je===he?je:he)})},[h,D,M]),tt.useEffect(()=>{h&&!f&&k&&F(!1)},[f,h,k,F]),tt.useEffect(()=>{if(!h){j.current=!1;return}j.current||(j.current=!0,F(!1),A(!1),Ee.getState().isRightSidebarOpen&&l(!1))},[h,F,l]),tt.useEffect(()=>{if(!h||u!=="chat"||k||D||g)return;let ee=!1,re;const he=je=>{re=window.setTimeout(()=>{if(ee)return;const te=ut.getState(),Ne=Ee.getState();if(!(Ne.activeMainTab!=="chat"||Ne.isSettingsDialogOpen||te.currentSessionId||te.newSessionDraft?.open)){if(te.isLoading){he(250);return}te.openNewSessionDraft()}},je)};return he(500),()=>{ee=!0,re!==void 0&&window.clearTimeout(re)}},[u,h,g,k,D]),tt.useEffect(()=>{!h||!g||(F(!1),A(!1),a&&l(!1))},[h,g,a,F,l]),Bx(),i.useEffect(()=>{Ee.getState().isMobile!==h&&m(h)},[h,m]),i.useEffect(()=>{if(typeof window>"u")return;let ee;const re=()=>{ee===void 0&&(ee=window.requestAnimationFrame(()=>{ee=void 0,Ee.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",re),()=>{window.removeEventListener("resize",re),ee!==void 0&&window.cancelAnimationFrame(ee)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let ee;const re=()=>{const je=Ee.getState(),te=window.innerWidth,Ne=window.innerHeight;if(!h&&!N){const J=te<1140,H=te>=1220;J?je.isRightSidebarOpen&&(l(!1),w.current=!0):H&&w.current&&(l(!0),w.current=!1);const q=Ne<640,ae=Ne>=700;q?je.isBottomTerminalOpen&&(d(!1),S.current=!0):ae&&S.current&&(d(!0),S.current=!1)}},he=()=>{ee===void 0&&(ee=window.requestAnimationFrame(()=>{ee=void 0,re()}))};return re(),window.addEventListener("resize",he),()=>{window.removeEventListener("resize",he),ee!==void 0&&window.cancelAnimationFrame(ee)}},[h,N,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const ee=Ee.subscribe((re,he)=>{const je=window.innerWidth,te=window.innerHeight,Ne=je>=1220,J=te>=700;re.isRightSidebarOpen!==he.isRightSidebarOpen&&Ne&&(w.current=!1),re.isBottomTerminalOpen!==he.isBottomTerminalOpen&&J&&(S.current=!1)});return()=>{ee()}},[h,N,d,l]);const se=i.useCallback(()=>{k&&F(!1),A(!D)},[k,D,F]),Q=i.useMemo(()=>{switch(u){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(_m,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Ql,{isActive:!D})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Fm,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(hf,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Vm,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Tm,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Q2,{})});default:return null}},[u,D]),K=u==="chat";return s.jsx(Vx,{children:s.jsxs("div",{"data-page-scroll-lock":"true",className:De("main-content-safe-area",h?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[s.jsx(F0,{}),s.jsx(jj,{}),s.jsx(Cj,{}),s.jsx(M2,{}),h?s.jsxs(Y2,{value:{leftDrawerOpen:k,rightDrawerOpen:D,toggleLeftDrawer:()=>{const ee=!k;D&&A(!1),F(ee)},toggleRightDrawer:se,leftDrawerX:B,rightDrawerX:M,leftDrawerWidth:V,rightDrawerWidth:Z,setMobileLeftDrawerOpen:F,setRightSidebarOpen:A},children:[!g&&s.jsx(Kd,{onToggleLeftDrawer:()=>{const ee=!k;D&&A(!1),F(ee)},onToggleRightDrawer:()=>{se()},leftDrawerOpen:k,rightDrawerOpen:D}),s.jsx("div",{"data-page-scroll-lock":"true",className:De("flex flex-1 overflow-hidden relative",g&&"hidden"),children:s.jsxs("main",{className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[s.jsx("div",{className:De("absolute inset-0",!K&&"invisible"),children:s.jsx(en,{children:s.jsx(Hl,{})})}),Q&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(en,{children:Q})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(en,{children:s.jsx(G2,{initialPrompt:b,onCreated:()=>x(!1),onCancel:()=>x(!1)})})}),C&&s.jsx(dd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:B},"aria-hidden":!k,children:s.jsx(en,{children:s.jsx(uf,{mobileVariant:!0})})}),T&&s.jsx(dd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:M},"aria-hidden":!D,children:s.jsx(en,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Ql,{isActive:D})})})})]})}),g&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(en,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(J2,{onClose:()=>y(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(qb,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(Hb,{isOpen:o,isMobile:h,className:"border-border/50",topBar:s.jsx(Gb,{}),children:s.jsx(uf,{})}),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(Kd,{}),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:De("absolute inset-0",!K&&"invisible"),children:s.jsx(en,{children:s.jsx(Hl,{})})}),Q&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(en,{children:Q})})]}),s.jsx(M0,{})]})}),s.jsx(_b,{isOpen:c,isMobile:h,children:c?s.jsx(en,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(hf,{})})}):null})]}),s.jsx(ey,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(en,{children:s.jsx(bv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(X2,{open:g,onOpenChange:y})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(Z2,{open:p,onOpenChange:x,initialPrompt:b})})]})]})})},tk=t=>{if(t<1e3)return`${Math.round(t)}ms`;const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e/60),r=Math.round(e%60);return`${n}m ${r}s`},_n=t=>{const e=gt.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},pf=t=>{const e=gt.c(43),{title:n,snapshot:r,emptyLabel:o}=t,{t:a}=kt();let c;if(e[0]!==o||e[1]!==r.durationMs||e[2]!==r.entries||e[3]!==r.lastUpdatedAt||e[4]!==r.startedAt||e[5]!==a||e[6]!==n){const l=r.entries.slice(0,12);let d;e[8]!==r.entries?(d=r.entries.reduce(rk,0),e[8]=r.entries,e[9]=d):d=e[9];const u=d;let m;e[10]!==n?(m=s.jsx("div",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:n}),e[10]=n,e[11]=m):m=e[11];let f;e[12]!==r.durationMs||e[13]!==r.startedAt||e[14]!==a?(f=r.startedAt?tk(r.durationMs):a("memoryDebugPanel.common.idle"),e[12]=r.durationMs,e[13]=r.startedAt,e[14]=a,e[15]=f):f=e[15];let g;e[16]!==f?(g=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:f}),e[16]=f,e[17]=g):g=e[17];let y;e[18]!==m||e[19]!==g?(y=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m,g]}),e[18]=m,e[19]=g,e[20]=y):y=e[20];let p;e[21]!==a?(p=a("memoryDebugPanel.metric.metrics"),e[21]=a,e[22]=p):p=e[22];let x;e[23]!==r.entries.length||e[24]!==p?(x=s.jsx(_n,{label:p,value:r.entries.length}),e[23]=r.entries.length,e[24]=p,e[25]=x):x=e[25];let b;e[26]!==a?(b=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=b):b=e[27];let h;e[28]!==b||e[29]!==u?(h=s.jsx(_n,{label:b,value:u}),e[28]=b,e[29]=u,e[30]=h):h=e[30];let N;e[31]!==a?(N=a("memoryDebugPanel.metric.lastUpdate"),e[31]=a,e[32]=N):N=e[32];let w;e[33]!==r.lastUpdatedAt||e[34]!==a?(w=r.lastUpdatedAt?a("memoryDebugPanel.common.live"):a("memoryDebugPanel.common.notAvailable"),e[33]=r.lastUpdatedAt,e[34]=a,e[35]=w):w=e[35];let S;e[36]!==N||e[37]!==w?(S=s.jsx(_n,{label:N,value:w}),e[36]=N,e[37]=w,e[38]=S):S=e[38];let j;e[39]!==h||e[40]!==S||e[41]!==x?(j=s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[x,h,S]}),e[39]=h,e[40]=S,e[41]=x,e[42]=j):j=e[42],c=s.jsxs("div",{className:"space-y-2 border-t border-[var(--interactive-border)] pt-2 first:border-t-0 first:pt-0",children:[y,j,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(Wn,{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},sk=t=>{const e=gt.c(99),{onClose:n}=t,{t:r}=kt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=ut(ik),u=tm(ok),m=jc(),f=Xg(ak),g=or(lk),[y,p]=i.useState(ck),[x,b]=i.useState(dk);let h;e[0]!==y.entries?(h=new Map,y.entries.forEach(ce=>{h.set(ce.metric,ce.count)}),e[0]=y.entries,e[1]=h):h=e[1];let N;e[2]!==h?(N=h.get("ui.message_list.render")??0,e[2]=h,e[3]=N):N=e[3];let w;e[4]!==h?(w=h.get("ui.message_list.render.streaming")??0,e[4]=h,e[5]=w):w=e[5];let S;e[6]!==h?(S=h.get("ui.chat_message.render")??0,e[6]=h,e[7]=S):S=e[7];let j;e[8]!==h?(j=h.get("ui.chat_message.render.streaming")??0,e[8]=h,e[9]=j):j=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 v;e[12]!==h?(v=h.get("ui.chat_message.render.static_outside_active_turn_during_stream")??0,e[12]=h,e[13]=v):v=e[13];let D;e[14]!==N||e[15]!==w||e[16]!==S||e[17]!==j||e[18]!==k||e[19]!==v?(D={messageListRender:N,messageListRenderStreaming:w,chatMessageRender:S,chatMessageRenderStreaming:j,chatMessageRenderStaticDuringStream:k,chatMessageRenderStaticOutsideActiveTurnDuringStream:v},e[14]=N,e[15]=w,e[16]=S,e[17]=j,e[18]=k,e[19]=v,e[20]=D):D=e[20];const A=D;let C,O;e[21]===Symbol.for("react.memo_cache_sentinel")?(C=()=>{const ce=()=>{p(na()),b(ra())};ce();const W=window.setInterval(ce,500);return()=>window.clearInterval(W)},O=[],e[21]=C,e[22]=O):(C=e[21],O=e[22]),i.useEffect(C,O);let T,E;e[23]!==c?(T=()=>{if(c==="idle")return;const ce=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(ce)},E=[c],e[23]=c,e[24]=T,e[25]=E):(T=e[24],E=e[25]),i.useEffect(T,E);let F=0,R=0,L=0;for(const ce of Object.keys(f)){const W=f[ce]??[];R=R+W.length;for(const z of W)z.role==="user"?L=L+1:z.role==="assistant"&&(F=F+1)}let B;e[26]!==F||e[27]!==R||e[28]!==L?(B={assistant:F,total:R,user:L},e[26]=F,e[27]=R,e[28]=L,e[29]=B):B=e[29];const V=B;let M;if(e[30]!==d||e[31]!==f||e[32]!==u||e[33]!==m||e[34]!==r){let ce;e[36]!==d||e[37]!==f||e[38]!==u||e[39]!==r?(ce=W=>{const z=f[W.id]??[];let be=0,xe=0;for(const ye of z)ye.role==="user"?xe=xe+1:ye.role==="assistant"&&(be=be+1);const _=u.get(W.id);return{id:W.id,title:W.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:be,messageCount:z.length,userMessageCount:xe,isStreaming:_?.isStreaming||!1,isZombie:_?.isZombie||!1,backgroundCount:_?.backgroundMessageCount||0,lastAccessed:_?.lastAccessedAt||0,isCurrent:W.id===d}},e[36]=d,e[37]=f,e[38]=u,e[39]=r,e[40]=ce):ce=e[40],M=m.map(ce).sort(uk),e[30]=d,e[31]=f,e[32]=u,e[33]=m,e[34]=r,e[35]=M}else M=e[35];const Z=M;let se;e[41]!==f?(se=Object.keys(f),e[41]=f,e[42]=se):se=e[42];const Q=se.length;let K;e[43]===Symbol.for("react.memo_cache_sentinel")?(K=async()=>{try{const ce={generatedAt:new Date().toISOString(),ui:na(),vscode:ra()};await navigator.clipboard.writeText(JSON.stringify(ce,null,2)),l("copied")}catch{l("error")}},e[43]=K):K=e[43];const ee=K;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 he;e[45]!==o?(he=o==="memory"?s.jsx(I,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(I,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=he):he=e[46];let je;e[47]!==r?(je=r("memoryDebugPanel.title"),e[47]=r,e[48]=je):je=e[48];let te;e[49]!==je?(te=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:je}),e[49]=je,e[50]=te):te=e[50];let Ne;e[51]!==he||e[52]!==te?(Ne=s.jsxs("div",{className:"flex items-center gap-2",children:[he,te]}),e[51]=he,e[52]=te,e[53]=Ne):Ne=e[53];let J;e[54]!==o?(J=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx($e,{size:"xs",variant:"ghost",onClick:ee,children:s.jsx(I,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx($e,{size:"xs",variant:"ghost",onClick:()=>{op(),p(na()),b(ra())},children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=J):J=e[55];let H;e[56]!==n?(H=n?s.jsx($e,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=H):H=e[57];let q;e[58]!==J||e[59]!==H?(q=s.jsxs("div",{className:"flex items-center gap-1",children:[J,H]}),e[58]=J,e[59]=H,e[60]=q):q=e[60];let ae;e[61]!==Ne||e[62]!==q?(ae=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[Ne,q]}),e[61]=Ne,e[62]=q,e[63]=ae):ae=e[63];let le;e[64]===Symbol.for("react.memo_cache_sentinel")?(le={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=le):le=e[64];const Se=o==="memory"?"secondary":"ghost";let Re;e[65]===Symbol.for("react.memo_cache_sentinel")?(Re=()=>a("memory"),e[65]=Re):Re=e[65];let _e;e[66]!==r?(_e=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=_e):_e=e[67];let Oe;e[68]!==Se||e[69]!==_e?(Oe=s.jsx($e,{size:"sm",variant:Se,className:"flex-1",onClick:Re,children:_e}),e[68]=Se,e[69]=_e,e[70]=Oe):Oe=e[70];const Me=o==="streaming"?"secondary":"ghost";let ge;e[71]===Symbol.for("react.memo_cache_sentinel")?(ge=()=>a("streaming"),e[71]=ge):ge=e[71];let Ae;e[72]!==r?(Ae=r("memoryDebugPanel.tabs.streaming"),e[72]=r,e[73]=Ae):Ae=e[73];let pe;e[74]!==Me||e[75]!==Ae?(pe=s.jsx($e,{size:"sm",variant:Me,className:"flex-1",onClick:ge,children:Ae}),e[74]=Me,e[75]=Ae,e[76]=pe):pe=e[76];let ue;e[77]!==Oe||e[78]!==pe?(ue=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:le,children:[Oe,pe]}),e[77]=Oe,e[78]=pe,e[79]=ue):ue=e[79];let G;e[80]!==o||e[81]!==Q||e[82]!==c||e[83]!==d||e[84]!==f||e[85]!==V||e[86]!==u||e[87]!==Z||e[88]!==m||e[89]!==A||e[90]!==y||e[91]!==r||e[92]!==g||e[93]!==x?(G=o==="memory"?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[s.jsx(_n,{label:r("memoryDebugPanel.metric.totalMessages"),value:V.total}),s.jsx(_n,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${Q} / ${Fd.MAX_SESSIONS}`}),s.jsx(_n,{label:r("memoryDebugPanel.metric.userMessages"),value:V.user}),s.jsx(_n,{label:r("memoryDebugPanel.metric.assistantMessages"),value:V.assistant})]}),s.jsxs("div",{className:"typography-meta space-y-1 border-t border-[var(--interactive-border)] pt-2",children:[s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.viewportWindow")}),s.jsx("span",{className:"text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.messagesValue",{count:Zg()})})]}),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:Fd.ZOMBIE_TIMEOUT/1e3/60})})]}),s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.githubTotalRequests")}),s.jsx("span",{className:"text-[var(--surface-foreground)]",children:g})]})]}),s.jsxs("div",{className:"border-t border-[var(--interactive-border)] pt-2",children:[s.jsx("div",{className:"mb-1 typography-meta font-semibold text-[var(--surface-foreground)]",children:r("memoryDebugPanel.section.sessionsInMemory")}),s.jsx(Wn,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:Z.map(ce=>s.jsxs("div",{className:"typography-meta flex items-center justify-between rounded p-1.5",style:{backgroundColor:ce.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:ce.title}),ce.isStreaming?s.jsx(I,{name:"pulse",className:"h-3 w-3 animate-pulse text-[var(--status-info)]"}):null,ce.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:ce.assistantMessageCount,user:ce.userMessageCount})}),s.jsx("span",{className:"font-mono text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.msgsValue",{count:ce.messageCount})}),ce.backgroundCount>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["+",ce.backgroundCount]}):null]})]},ce.id))})]}),s.jsx("div",{className:"flex gap-2 border-t border-[var(--interactive-border)] pt-2",children:s.jsxs(Rt,{children:[s.jsx(Et,{asChild:!0,children:s.jsx($e,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:m.map(fk),currentSessionId:d,cachedSessions:Object.keys(f),messageRoleCounts:V,sessionMessageRoleCounts:Z.map(mk),memoryStates:Object.fromEntries(u)})},children:r("memoryDebugPanel.actions.logState")})}),s.jsx(Mt,{side:"top",children:r("memoryDebugPanel.tooltip.logCurrentState")})]})})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-[var(--interactive-border)] px-3 py-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:r(c==="copied"?"memoryDebugPanel.streaming.copy.copied":c==="error"?"memoryDebugPanel.streaming.copy.failed":"memoryDebugPanel.streaming.copy.hint")}),s.jsx($e,{size:"xs",variant:"outline",onClick:ee,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(_n,{label:r("memoryDebugPanel.metric.uiMetrics"),value:y.entries.length}),s.jsx(_n,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:x.entries.length}),s.jsx(_n,{label:r("memoryDebugPanel.metric.messageListRenders"),value:A.messageListRender}),s.jsx(_n,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:A.messageListRenderStreaming}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:A.chatMessageRender}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:A.chatMessageRenderStreaming}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:A.chatMessageRenderStaticDuringStream}),s.jsx(_n,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:A.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(pf,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:y,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),x.entries.length>0?s.jsx(pf,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:x,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=Q,e[82]=c,e[83]=d,e[84]=f,e[85]=V,e[86]=u,e[87]=Z,e[88]=m,e[89]=A,e[90]=y,e[91]=r,e[92]=g,e[93]=x,e[94]=G):G=e[94];let fe;return e[95]!==ae||e[96]!==ue||e[97]!==G?(fe=s.jsxs(ex,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:re,children:[ae,ue,G]}),e[95]=ae,e[96]=ue,e[97]=G,e[98]=fe):fe=e[98],fe},nk=sk;function rk(t,e){return t+e.count}function ik(t){return t.currentSessionId}function ok(t){return t.sessionMemoryState}function ak(t){return t.message}function lk(t){return t.totalRequestCount}function ck(){return na()}function dk(){return ra()}function uk(t,e){return e.lastAccessed-t.lastAccessed}function fk(t){return{id:t.id,title:t.title}}function mk(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const hk=()=>{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()??"":""},pk=async()=>{const t=hk()||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")},gf="openchamber:menu-action",Ml="openchamber:check-for-updates",gk=t=>{const e=ut(v=>v.openNewSessionDraft),n=Ee(v=>v.toggleCommandPalette),r=Ee(v=>v.setCommandPaletteOpen),o=Ee(v=>v.toggleHelpDialog),a=Ee(v=>v.toggleSidebar),c=Ee(v=>v.setSessionSwitcherOpen),l=Ee(v=>v.setActiveMainTab),d=Ee(v=>v.setSettingsDialogOpen),u=Ee(v=>v.setAboutDialogOpen),m=Ee(v=>v.toggleRightSidebar),f=Ee(v=>v.setRightSidebarOpen),g=Ee(v=>v.setRightSidebarTab),y=Ee(v=>v.toggleBottomTerminal),p=Ee(v=>v.setBottomTerminalExpanded),x=wo(v=>v.checkForUpdates),{setThemeMode:b}=Gr(),h=i.useRef(!1),N=i.useCallback(()=>{h.current||(h.current=!0,x().then(()=>{const{available:v,error:D}=wo.getState();if(D){de.error("Failed to check for updates",{description:D});return}v||de.success("You are on the latest version")}).finally(()=>{h.current=!1}))},[x]),w=i.useCallback(()=>{Pr.requestDirectoryDialog()},[]),S=i.useCallback(v=>{const D=tx();if(D.length===0)return;const A=ut.getState().currentSessionId,C=D.findIndex(E=>E.id===A);let O=v>0?0:D.length-1;C>=0&&(O=(C+v+D.length)%D.length);const T=D[O];T&&(l("chat"),c(!1),ut.getState().setCurrentSession(T.id))},[l,c]),j=i.useCallback(v=>{const{activeProjectId:D,projects:A,setActiveProject:C}=ws.getState();if(A.length===0)return;const O=A.findIndex(F=>F.id===D);let T=v>0?0:A.length-1;O>=0&&(T=(O+v+A.length)%A.length);const E=A[T];E&&C(E.id)},[]),k=i.useCallback(v=>{switch(v){case"about":u(!0);break;case"settings":d(!0);break;case"command-palette":n();break;case"quick-open":r(!0);break;case"new-session":l("chat"),c(!1),e();break;case"new-worktree-session":l("chat"),c(!1),Jf();break;case"change-workspace":w();break;case"toggle-right-sidebar":m();break;case"open-right-sidebar-git":f(!0),g("git");break;case"open-right-sidebar-files":f(!0),g("files");break;case"toggle-terminal":y();break;case"toggle-terminal-expanded":p(!Ee.getState().isBottomTerminalExpanded);break;case"copy":{const D=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(D)||pk();break}case"theme-light":b("light");break;case"theme-dark":b("dark");break;case"theme-system":b("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":Qs.getState().goBack();break;case"go-forward":Qs.getState().goForward();break;case"previous-session":S(-1);break;case"next-session":S(1);break;case"previous-project":j(-1);break;case"next-project":j(1);break;case"help-dialog":o();break;case"download-logs":{sx().catch(()=>{de.error("Failed to collect OpenCode status")});break}}},[w,j,S,t,e,u,l,c,r,d,p,f,g,b,y,n,o,m,a]);i.useEffect(()=>{const v=A=>{const C=A.detail;C&&k(C)},D=()=>{N()};return window.addEventListener(gf,v),window.addEventListener(Ml,D),()=>{window.removeEventListener(gf,v),window.removeEventListener(Ml,D)}},[k,N]),i.useEffect(()=>{if(typeof window>"u")return;const D=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof D!="function")return;let A=null,C=null;return D("openchamber:menu-action",O=>{const T=O?.payload;typeof T=="string"&&k(T)}).then(O=>{A=O}).catch(()=>{}),D("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Ml))}).then(O=>{C=O}).catch(()=>{}),()=>{(async()=>{try{const T=A?.();T instanceof Promise&&await T}catch{}try{const T=C?.();T instanceof Promise&&await T}catch{}})()}},[k])},xk="openchamber:tray-action",xf=5e3,bk=120,yk=45e3,fh=20,bf=()=>typeof window>"u"?!1:window.__OPENCHAMBER_PLATFORM__==="darwin",wk=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},vk=t=>{const e=Array.isArray(t.questions)?t.questions[0]:void 0;return e?.header||e?.question||"Question"},Ma=t=>t.time?.updated??t.time?.created??0,jk=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},Sk=(t,e,n,r,o)=>{if(!t)return"";const a=ox(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||jk(t),d=oa(t);let u=d&&o.get(d)||"";if(!u){for(const[m,f]of wn.getState().directories)if(oa(m)===d){u=f.status?.current??"";break}}if(!u)for(const m of r.values()){const f=m.find(g=>oa(g.path)===d);if(f?.branch){u=f.branch;break}}return u?`${l} · ${u}`:l},Nk=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=fn.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 Bf){if(!e.includes(c.id))continue;const l=o.get(c.id);if(!l||l.configured!==!0)continue;const d=[];for(const[m,f]of Object.entries(l.usage?.windows??{})){const g=r==="remaining"?f.remainingPercent:f.usedPercent;d.push({label:fc(m),value:Io(f.valueLabel,g)})}const u=!l.ok&&l.error?l.error:d.length===0?"No rate limits reported":null;a.push({provider:c.name,rows:d,status:u})}return{mode:r,groups:a}},kk=async()=>{try{if(Xi())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=zr();if(e&&ja(e,t))return"Local OpenChamber";const r=(await Ff()).hosts.find(o=>e?ja(e,Lf(o)):!1);return r?.label?.trim()?Of(r.label.trim()):"Instance"}catch{return""}},Ck=()=>{const t=new Map,e=new Map,n=[],r=new Map;let o;try{o=ka()}catch{return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}}for(const[a,c]of o.children.entries()){const l=c.getState();l.vcs?.branch&&e.set(oa(a)??a,l.vcs.branch);for(const d of l.session)d?.id&&r.set(d.id,d.title);for(const[d,u]of Object.entries(l.session_status??{})){const m=u?.type,f=m==="busy"?"busy":m==="retry"?"retry":"idle",g=t.get(d);(!g||g==="idle")&&t.set(d,f)}for(const[d,u]of Object.entries(l.permission??{}))for(const m of u??[]){if(!m?.id)continue;const f=m.sessionID||d;n.push({kind:"permission",id:m.id,sessionId:f,sessionTitle:"",label:wk(m),directory:a})}for(const[d,u]of Object.entries(l.question??{}))for(const m of u??[]){if(!m?.id)continue;const f=m.sessionID||d;n.push({kind:"question",id:m.id,sessionId:f,sessionTitle:"",label:vk(m),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},Ak=()=>{const t=jr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>Ma(o)-Ma(r)).slice(0,fh).forEach(r=>{const o=Tr(r);o&&e.add(o)});const n=new Map;for(const r of t){if(!r?.id)continue;const o=Tr(r);if(!o||!e.has(o))continue;const a=n.get(o)??[];a.push(r.id),n.set(o,a)}return n},Dk=t=>{const e=Ck(),n=nm.getState().index.session,r=jr.getState().activeSessions,o=new Map(e.titleById),a=new Map;for(const p of r)if(p?.id&&(p.title&&o.set(p.id,p.title),p.parentID)){const x=a.get(p.parentID)??[];x.push(p.id),a.set(p.parentID,x)}const c=p=>{const x=[],b=[...a.get(p)??[]],h=new Set;for(;b.length;){const N=b.pop();h.has(N)||(h.add(N),x.push(N),b.push(...a.get(N)??[]))}return x},l=rm.getState().statusById,d=p=>{const x=e.statusById.get(p);return x&&x!=="idle"?x:l.get(p)?.status??x??"idle"},u=p=>{const x=p.map(b=>d(b));return x.includes("busy")?"busy":x.includes("retry")?"retry":"idle"},m=ws.getState().projects,f=ut.getState().availableWorktreesByProject,g=r.filter(p=>p?.id&&!p.parentID).slice().sort((p,x)=>Ma(x)-Ma(p)).slice(0,fh).map(p=>{const x=[p.id,...c(p.id)],b=Tr(p)??"";return{id:p.id,title:p.title||"Untitled session",status:u(x),branch:b?e.branchByDirectory.get(b)??"":"",unseen:x.reduce((h,N)=>h+(n.unseenCount[N]??0),0),hasError:x.some(h=>n.unseenHasError[h]??!1),directory:b,subtitle:Sk(b,p,m,f,e.branchByDirectory)}}),y=e.approvals.map(p=>({...p,sessionTitle:o.get(p.sessionId)||""}));return{sessions:g,approvals:y,instanceName:t,usage:Nk()}},Ik=()=>{i.useEffect(()=>{if(!bf()||!Fa())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const j=Dk(r),k=JSON.stringify(j);k!==e&&(e=k,Wr("desktop_tray_update",j))};kk().then(j=>{t||(r=j,o())});const a=async()=>{const j=Ak();await Promise.all([...j.entries()].map(async([k,v])=>{const D=await zn.getSessionStatusForDirectory(k).catch(()=>null);t||D===null||rx(k,D,v)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},bk))},l=new Map,d=()=>{if(t)return;let j;try{j=ka()}catch{return}const k=new Set;for(const[v,D]of j.children.entries())k.add(v),l.has(v)||l.set(v,D.subscribe(()=>c()));for(const[v,D]of l)k.has(v)||(D(),l.delete(v))};let u=null;try{u=ka().subscribeRegistry(()=>{d(),c()})}catch{}d();const m=nm.subscribe(()=>c()),f=jr.subscribe(()=>c()),g=ws.subscribe(()=>c()),y=ut.subscribe(()=>c()),p=wn.subscribe(()=>c()),x=rm.subscribe(()=>c());nx(Vf());const b=window.setInterval(()=>{Sa()},yk);a();const h=window.setInterval(()=>{a()},xf),N=fn.subscribe(()=>c());fn.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:j,results:k}=fn.getState();j.length>0&&j.some(D=>!k.some(A=>A.providerId===D))&&fn.getState().fetchAllQuotas()});const w=window.setInterval(()=>{const j=fn.getState();j.autoRefresh&&j.dropdownProviderIds.length>0&&j.fetchAllQuotas()},Math.max(3e4,fn.getState().refreshIntervalMs||6e4)),S=window.setInterval(()=>{d(),o()},xf);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(S),window.clearInterval(b),window.clearInterval(h),window.clearInterval(w),m(),f(),g(),y(),p(),x(),N(),u?.();for(const j of l.values())j();l.clear()}},[]),i.useEffect(()=>{if(!bf()||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(()=>{de.error("Failed to respond to permission request")})};let r=null;return e(xk,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{}}},[])},Pk="/api/notifications/stream",Tk=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),Rk=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}},Ek=t=>{const e=gt.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||hr()||!uc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(Ai().sse(Pk));return a.onmessage=Mk,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function Mk(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Ee.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&Tk())return;const r=Rk(e);if(!r)return;Lo()?.notifications?.notifyAgentCompletion(r)}const yf="pwa-install-toast-shown",wf="pwa-install-toast-dismissed",Fk=()=>{const t=gt.c(6),{browserTab:e}=_x(),{t:n}=kt(),r=i.useRef(n);let o,a;t[0]!==n?(o=()=>{r.current=n},a=[n],t[0]=n,t[1]=o,t[2]=a):(o=t[1],a=t[2]),i.useEffect(o,a);let c,l;t[3]!==e?(c=()=>{if(typeof window>"u"||!uc()||!e)return;let d=null,u=null;const m=()=>{u!==null&&(de.dismiss(u),u=null)},f=async()=>{if(!d)return;const p=d;d=null,m(),await p.prompt();const{outcome:x}=await p.userChoice;x==="accepted"&&de.success(r.current("pwa.installPrompt.started"))},g=p=>{const x=p;if(typeof x.prompt!="function")return;x.preventDefault(),d=x;const b=ki(),h=Af();$x({dismissed:b.getItem(wf),sessionShown:h.getItem(yf),hasActiveToast:u!==null})&&(h.setItem(yf,"true"),u=de.info(r.current("pwa.installPrompt.description"),{duration:1/0,action:{label:r.current("pwa.installPrompt.action"),onClick:()=>{f()}},cancel:{label:r.current("pwa.installPrompt.dismiss"),onClick:()=>{ki().setItem(wf,"true"),m()}}}))},y=()=>{d=null,m(),de.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",g),window.addEventListener("appinstalled",y),()=>{m(),window.removeEventListener("beforeinstallprompt",g),window.removeEventListener("appinstalled",y)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},Lk=({open:t,onOpenChange:e})=>{const{t:n}=kt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,u]=i.useState(!1),[m,f]=i.useState(!1),[g,y]=i.useState(null),[p,x]=i.useState(!1);i.useCallback(async()=>{},[g,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const N=await As("/api/system/info");if(N.ok){const w=await N.json();if(typeof w.openchamberVersion=="string"&&w.openchamberVersion.trim()){a(w.openchamberVersion);return}}}catch{}a(await ax())})()},[t]),i.useEffect(()=>{if(!t)return;let h=!1;return(async()=>{try{const w=await As("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!w.ok)return;const S=await w.json().catch(()=>null),j=typeof S?.currentVersion=="string"?S.currentVersion.trim():"";!h&&j&&l(j)}catch{}})(),()=>{h=!0}},[t]),i.useEffect(()=>{{y(null),x(!1);return}},[t,r]);const b=o;return s.jsx(Os,{open:t,onOpenChange:e,children:s.jsx(Ls,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(Nc,{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:[b&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:b})}),c&&s.jsx("p",{children:n("aboutDialog.openCodeVersionLabel",{version:c})})]})]}),r,s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-center gap-4",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(I,{name:"github-fill",className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(I,{name:"discord-fill",className:"h-4 w-4"}),s.jsx("span",{children:"Discord"})]})]}),s.jsxs("a",{href:"https://x.com/openchamber_dev",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(I,{name:"twitter-xfill",className:"h-4 w-4"}),s.jsx("span",{children:"@openchamber_dev"})]})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:n("aboutDialog.footerNote")})]})})})},Fl=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},Ok=(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},Bk=()=>{const t=zx(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=Fl(a,"code"),l=Wx(a),d=Ux(a),u=Fl(a,"error"),m=Fl(a,"error_description");if(u){d&&As(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(m??u);return}(async()=>{try{if(!c)throw new Error("Missing OAuth authorization code. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");let f=l;if(!f&&d){const g=await As(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`);if(g.ok){const y=await g.json().catch(()=>null);y?.name?.trim()&&(f={name:y.name.trim(),directory:typeof y.directory=="string"&&y.directory.trim()?y.directory.trim():null})}}if(!f?.name)throw new Error("Authorization session details were not available. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");await t(f.name,c,f.directory),d&&await As(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("success"),o("Authorization completed. You can close this tab and return to OpenChamber.")}catch(f){d&&await As(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(Ok(f,"Failed to complete MCP authorization."))}})()},[t]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-6 py-12 text-foreground",children:s.jsxs("div",{className:"w-full max-w-xl rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-8 shadow-sm",children:[s.jsxs("div",{className:"space-y-3 text-center",children:[s.jsx("div",{className:e==="error"?"text-[var(--status-error)]":e==="success"?"text-[var(--status-success)]":"text-[var(--status-info)]",children:s.jsx("h1",{className:"typography-hero font-semibold",children:e==="working"?"Completing Authorization":e==="success"?"Authorization Complete":"Authorization Failed"})}),s.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}),e!=="working"&&s.jsx("div",{className:"mt-8 flex justify-center",children:s.jsx($e,{type:"button",onClick:()=>{typeof window>"u"||window.location.replace("/")},children:"Return to OpenChamber"})})]})})},vf=ao(()=>oo(()=>import("./OnboardingScreen-DpBF8dKJ.js"),__vite__mapDeps([12,1,2,4,5,3])).then(t=>({default:t.OnboardingScreen}))),Vk=()=>{const t=gt.c(3),e=Ee(Hk),n=Ee(Gk);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(Lk,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},_k=t=>{const e=gt.c(21),{onRetry:n,isRetrying:r}=t,{t:o}=kt();let a;e[0]!==o?(a=o("startup.initRecovery.title"),e[0]=o,e[1]=a):a=e[1];let c;e[2]!==a?(c=s.jsx("h1",{className:"typography-title text-foreground",children:a}),e[2]=a,e[3]=c):c=e[3];let l;e[4]!==o?(l=o("startup.initRecovery.description"),e[4]=o,e[5]=l):l=e[5];let d;e[6]!==l?(d=s.jsx("p",{className:"typography-body text-muted-foreground",children:l}),e[6]=l,e[7]=d):d=e[7];let u;e[8]!==c||e[9]!==d?(u=s.jsxs("div",{className:"flex flex-col gap-2",children:[c,d]}),e[8]=c,e[9]=d,e[10]=u):u=e[10];let m;e[11]!==r||e[12]!==o?(m=o(r?"startup.initRecovery.retrying":"startup.initRecovery.retry"),e[11]=r,e[12]=o,e[13]=m):m=e[13];let f;e[14]!==r||e[15]!==n||e[16]!==m?(f=s.jsx($e,{type:"button",onClick:n,disabled:r,children:m}),e[14]=r,e[15]=n,e[16]=m,e[17]=f):f=e[17];let g;return e[18]!==u||e[19]!==f?(g=s.jsx("div",{className:"flex h-full items-center justify-center bg-background px-6 text-foreground",children:s.jsxs("div",{className:"flex max-w-md flex-col items-center gap-4 text-center",children:[u,f]})}),e[18]=u,e[19]=f,e[20]=g):g=e[20],g},jf=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",$k=()=>{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"}},zk=()=>typeof window>"u"?!1:window.location.pathname===Kx,Wk=t=>{const e=gt.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=Qs(Kk),c=ut(qk),l=ut(Yk),d=Cc(),u=i.useRef(null);let m;e[0]!==n.directory?(m=jf(n.directory),e[0]=n.directory,e[1]=m):m=e[1];const f=m;let g;e[2]!==a?(g=jf(a),e[2]=a,e[3]=g):g=e[3];const y=g;let p,x;if(e[4]!==y||e[5]!==c||e[6]!==n.directory||e[7]!==n.sessionId||e[8]!==f||e[9]!==r||e[10]!==l||e[11]!==d?(p=()=>{if(r||f&&y!==f)return;const j=`${f}
214
- ${n.sessionId}`;u.current===j&&c===n.sessionId||(u.current=j,l(n.sessionId,n.directory),d.ensureSessionRenderable(n.sessionId,!0))},x=[y,c,n.directory,n.sessionId,f,r,l,d],e[4]=y,e[5]=c,e[6]=n.directory,e[7]=n.sessionId,e[8]=f,e[9]=r,e[10]=l,e[11]=d,e[12]=p,e[13]=x):(p=e[12],x=e[13]),i.useEffect(p,x),f&&y!==f)return null;let b;e[14]!==o?(b=s.jsx(im,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=b):b=e[15];let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(pm,{}),e[16]=h):h=e[16];let N;e[17]!==n.readOnly?(N=s.jsx(Hl,{readOnly:n.readOnly}),e[17]=n.readOnly,e[18]=N):N=e[18];let w;e[19]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx(om,{}),e[19]=w):w=e[19];let S;return e[20]!==b||e[21]!==N?(S=s.jsxs(s.Fragment,{children:[b,h,N,w]}),e[20]=b,e[21]=N,e[22]=S):S=e[22],S};function Uk({apis:t}){i.useEffect(()=>{ap("App:mounted"),lp()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=ss(H=>H.initializeApp),n=ss(H=>H.isInitialized),r=ss(H=>H.isConnected),o=ss(H=>H.providers.length),a=ss(H=>H.agents.length),c=ss(H=>H.loadProviders),l=ss(H=>H.loadAgents),d=ut(H=>H.error),u=ut(H=>H.clearError),m=Qs(H=>H.currentDirectory),f=Qs(H=>H.setDirectory),g=Qs(H=>H.isSwitchingDirectory),[y,p]=i.useState(!1),x=Ti(H=>H.refreshStatus),[b,h]=i.useState(()=>t.runtime.isVSCode),[N,w]=i.useState(!0),[S,j]=i.useState(!1),[k,v]=i.useState(0),[D,A]=i.useState(0),[C,O]=i.useState(!1),T=Ee(H=>H.wideChatLayoutEnabled),E=Ee(H=>H.mobileKeyboardMode),F=i.useMemo(()=>hr(),[]),R=hc(H=>H.setPlanModeEnabled),[L,B]=i.useState(()=>hd()),[V,M]=i.useState(()=>{const H=pd();return H!==null?gd({isDesktopShell:!0,bootOutcome:H}):null}),Z=i.useRef(!1),se=i.useMemo(()=>$k(),[]),Q=!se||N,K=i.useMemo(()=>zk(),[]);i.useEffect(()=>(xd(y),()=>{xd(!1)}),[y]),i.useEffect(()=>{cp(E)},[E]),i.useEffect(()=>{h(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>Pf(H=>{ut.getState().prepareForRuntimeSwitch(H.previousRuntimeKey),Ee.getState().prepareForRuntimeSwitch(H.previousRuntimeKey),dp(),zn.reconnectToRuntimeBaseUrl(),ss.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ws.getState().resetForRuntimeSwitch(),ut.getState().restoreForRuntimeSwitch(H.runtimeKey),Ee.getState().restoreForRuntimeSwitch(H.runtimeKey),lx(),A(q=>q+1),j(!1),v(q=>q+1)}),[]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",T),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[T]),i.useEffect(()=>(bd(t),()=>bd(null)),[t]),i.useEffect(()=>{se||x(t.github,{force:!0})},[t.github,se,x]),cx();const ee=L==="valid",re=V?.screen==="main";i.useEffect(()=>{if(!up({isDesktopShell:F,isInitialized:n,bootOutcomeKnown:ee,bootViewIsMain:re}))return;const H=setTimeout(()=>{const q=document.getElementById("initial-loading");q&&(q.classList.add("fade-out"),setTimeout(()=>{q.remove()},300))},150);return()=>clearTimeout(H)},[F,n,ee,re]),i.useEffect(()=>{if(!F||L!=="malformed")return;const H=document.getElementById("initial-loading");H&&(H.textContent="Desktop startup failed — please restart the app.")},[F,L]),i.useEffect(()=>{if(F)return;const H=setTimeout(()=>{const q=document.getElementById("initial-loading");q&&!n&&(q.classList.add("fade-out"),setTimeout(()=>{q.remove()},300))},5e3);return()=>clearTimeout(H)},[F,n]),i.useEffect(()=>{let H=!1;return(async()=>{const ae=await As("/health",{method:"GET"}).catch(()=>null);if(!ae||!ae.ok||H)return;const le=await ae.json().catch(()=>null);if(!le||H)return;const Se=le.planModeExperimentalEnabled;R(Se===!0||Se===1||Se==="1"||Se==="true")})(),()=>{H=!0}},[R]),i.useEffect(()=>{b||e()},[e,b]),i.useEffect(()=>{if(b||n)return;let H=!0,q,ae=0;const le=10,Se=1e3,Re=async()=>{if(!H)return;if(ae>=le){j(!0);return}const _e=ss.getState();if(_e.isInitialized){j(!1);return}ae+=1,await _e.initializeApp();const Oe=ss.getState();if(!H)return;if(Oe.isInitialized){j(!1);return}if(ae>=le){j(!0);return}const Me=Math.min(Se*Math.pow(2,ae-1),16e3);q=setTimeout(Re,Me)};return q=setTimeout(Re,Se),()=>{H=!1,q&&clearTimeout(q)}},[k,n,b]),i.useEffect(()=>{n&&j(!1)},[n]),i.useEffect(()=>{if(!S)return;const H=document.getElementById("initial-loading");H&&(H.classList.add("fade-out"),setTimeout(()=>{H.remove()},300))},[S]),i.useEffect(()=>{if(b||!r||o>0&&a>0)return;let H=!0,q=0;const ae=15,le=async()=>{const Re=ss.getState();if(!(Re.providers.length>0&&Re.agents.length>0))try{Re.providers.length===0&&await c({source:"startupRecovery"}),ss.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};le();const Se=setInterval(()=>{if(H){if(++q>=ae){clearInterval(Se);return}le()}},2e3);return()=>{H=!1,clearInterval(Se)}},[r,b,l,c,o,a]),i.useEffect(()=>{g||b||r&&zn.setDirectory(m)},[m,g,r,b]),i.useEffect(()=>{if(!se||typeof window>"u")return;const H=le=>{const Se=le?.visible===!0;w(Se)},q=le=>{if(le.origin!==window.location.origin)return;const Se=le.data;Se?.type==="openchamber:embedded-visibility"&&H(Se.payload)},ae=window;return ae.__openchamberSetEmbeddedVisibility=H,window.addEventListener("message",q),()=>{window.removeEventListener("message",q),ae.__openchamberSetEmbeddedVisibility===H&&delete ae.__openchamberSetEmbeddedVisibility}},[se]),i.useEffect(()=>{!se?.directory||b||m!==se.directory&&f(se.directory,{showOverlay:!1})},[m,se,b,f]),i.useEffect(()=>{if(!se||typeof window>"u")return;const H=q=>{q.storageArea===window.localStorage&&q.key==="ui-store"&&Ee.persist.rehydrate()};return window.addEventListener("storage",H),()=>{window.removeEventListener("storage",H)}},[se]),i.useEffect(()=>{if(typeof window>"u")return;const H=q=>{const ae=q.detail,le=typeof ae?.sessionId=="string"?ae.sessionId.trim():"";if(!le)return;const Se=typeof ae?.directory=="string"&&ae.directory.trim().length>0?ae.directory.trim():null;Ee.getState().setActiveMainTab("chat"),ut.getState().setCurrentSession(le,Se)};return window.addEventListener("openchamber:open-session",H),()=>window.removeEventListener("openchamber:open-session",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=()=>{const q=Qs.getState().currentDirectory,{activeProjectId:ae,projects:le}=ws.getState(),Se=le.find(Re=>Re.id===ae)??null;Wr("desktop_open_draft_mini_chat_window",{directory:q||Se?.path||"",projectId:Se?.id??null})};return window.addEventListener("openchamber:open-mini-chat",H),()=>window.removeEventListener("openchamber:open-mini-chat",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=()=>{const q=ut.getState().currentSessionId;q&&mx(q)};return window.addEventListener("focus",H),()=>window.removeEventListener("focus",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=q=>{const ae=q.detail,le=typeof ae?.directory=="string"&&ae.directory.trim().length>0?ae.directory.trim():null,Se=typeof ae?.projectId=="string"&&ae.projectId.trim().length>0?ae.projectId.trim():null;Ee.getState().setActiveMainTab("chat"),Ee.getState().setSessionSwitcherOpen(!1),ut.getState().openNewSessionDraft({selectedProjectId:Se,directoryOverride:le,preserveDirectoryOverride:!!le})};return window.addEventListener("openchamber:open-draft-session",H),()=>window.removeEventListener("openchamber:open-draft-session",H)},[]),i.useEffect(()=>{if(typeof window>"u")return;const H=q=>{const ae=q.detail,le=typeof ae?.projectPath=="string"?ae.projectPath.trim():"";if(!le)return;const Se=ws.getState(),Re=Se.projects.find(_e=>_e.path===le);Re?Se.setActiveProject(Re.id):Se.addProject(le)};return window.addEventListener("openchamber:open-project",H),()=>window.removeEventListener("openchamber:open-project",H)},[]),i.useEffect(()=>{typeof window>"u"||!n||g||Z.current||(Z.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,g]),dx({enabled:Q}),Ek({enabled:Q}),Fk(),ux(),Hx();const he=i.useCallback(()=>{p(H=>!H)},[]);gk(he),Ik(),i.useEffect(()=>{if(se)return;const H=q=>{pc(q)&&q.shiftKey&&!q.altKey&&(q.code==="KeyD"||q.key.toLowerCase()==="d")&&(q.preventDefault(),p(le=>!le))};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[se]),i.useEffect(()=>{se||d&&setTimeout(()=>u(),5e3)},[u,se,d]),i.useEffect(()=>{if(!F||L!=="not-injected")return;let H=!1,q=0;const ae=200,le=2e3,Se=50,Re=()=>{if(H)return;q++;const _e=hd();if(_e!=="not-injected"){if(H=!0,B(_e),_e==="valid"){const Me=pd();Me&&M(gd({isDesktopShell:!0,bootOutcome:Me}))}return}const Oe=Math.min(ae*Math.pow(1.1,q),le);if(q>=Se){const Me=document.getElementById("initial-loading");Me&&!Me.textContent?.includes("taking longer")&&(Me.textContent="Desktop startup is taking longer than expected...")}window.setTimeout(Re,Oe)};return window.setTimeout(Re,ae),()=>{H=!0}},[F,L]);const je=i.useCallback(async()=>{if(fp({isDesktopShell:hr(),isDesktopLocalOriginActive:Xi()})){await mp();return}window.location.reload()},[]),te=i.useCallback(async()=>{if(!C){j(!1),O(!0);try{await ss.getState().initializeApp()}finally{O(!1)}ss.getState().isInitialized||v(H=>H+1)}},[C]),Ne=H=>{if(H.screen==="recovery")return H.variant};if(F&&V&&V.screen!=="main"){if(V.screen==="chooser")return s.jsx(en,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-full"}),children:s.jsx(vf,{mode:"first-launch",onCliAvailable:je,onChooseRemote:()=>{}})})})});const H=Ne(V),q=V.screen==="recovery"&&"url"in V?V.url:void 0;return s.jsx(en,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-full"}),children:s.jsx(vf,{mode:"recovery",recoveryVariant:H,recoveryHostUrl:q,recoveryHostLabel:void 0,onCliAvailable:je})})})})}if(se)return s.jsx(en,{children:s.jsx(Ld,{sdk:zn.getSdkClient(),directory:m||"",children:s.jsx(Od,{apis:t,children:s.jsx(Bd,{delayDuration:300,skipDelayDuration:150,children:s.jsx("div",{className:"h-full text-foreground bg-background",children:s.jsx(Wk,{embeddedSessionChat:se,isVSCodeRuntime:b,embeddedBackgroundWorkEnabled:Q})})})})},D)});if(K)return s.jsx(en,{children:s.jsx(Bk,{})});if(S&&!n&&!b&&!se)return s.jsx(en,{children:s.jsx(_k,{onRetry:()=>{te()},isRetrying:C})});const J=!n&&!F;return s.jsx(en,{children:s.jsx(Ld,{sdk:zn.getSdkClient(),directory:m||"",children:s.jsx(Od,{apis:t,children:s.jsx(Sy,{children:s.jsx(fx,{children:s.jsx(Bd,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:F?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(im,{embeddedBackgroundWorkEnabled:Q}),s.jsx(pm,{}),s.jsx(ek,{}),s.jsx(om,{}),!J&&s.jsxs(s.Fragment,{children:[s.jsx(Gx,{}),s.jsx(Vk,{}),y&&s.jsx(nk,{onClose:()=>p(!1)})]})]})})})})})},D)})}function Hk(t){return t.isAboutDialogOpen}function Gk(t){return t.setAboutDialogOpen}function Kk(t){return t.currentDirectory}function qk(t){return t.currentSessionId}function Yk(t){return t.setCurrentSession}const Qk=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();hx();hp().then(()=>{Promise.all([pp(),px()]).catch(t=>{console.error("[main] settings init failed:",t)}),gx(),xx(),bx()}).catch(t=>{console.error("[main] appearance init failed:",t)});const mh=document.getElementById("root");if(!mh)throw new Error("Root element not found");qh.createRoot(mh).render(s.jsx(tt.StrictMode,{children:s.jsx(yx,{children:s.jsx(wx,{children:s.jsx(vx,{children:s.jsx(jx,{children:s.jsx(Uk,{apis:Qk})})})})})}));const iC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{e1 as D,G2 as M,iC as m,Fs as u};