@openchamber/web 1.13.5 → 1.13.6

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 (35) hide show
  1. package/dist/assets/{DiagramView-Bbj-QI7h.js → DiagramView-C_f1Il8p.js} +1 -1
  2. package/dist/assets/{MarkdownRendererImpl-BNr_9Jsb.js → MarkdownRendererImpl-BR0DXO9F.js} +3 -3
  3. package/dist/assets/{MultiRunWindow-DMMu53kw.js → MultiRunWindow-WBqBXcts.js} +1 -1
  4. package/dist/assets/NewWorktreeDialog-D7l2VA7o.js +167 -0
  5. package/dist/assets/{OnboardingScreen-BucKVBD7.js → OnboardingScreen-ChaxLu9k.js} +1 -1
  6. package/dist/assets/{SessionSwitcherDropdown-B6kvduse.js → SessionSwitcherDropdown-xaYa-FIx.js} +1 -1
  7. package/dist/assets/{SettingsWindow-BEfDro9b.js → SettingsWindow-D5aAKCEM.js} +1 -1
  8. package/dist/assets/{TerminalView-CMdqMpTy.js → TerminalView-D8GzsMZF.js} +1 -1
  9. package/dist/assets/{es-Bk-yR0w-.js → es-D0PPWgfL.js} +1 -1
  10. package/dist/assets/{fr-f1ibV7QU.js → fr-4AxG2GNC.js} +1 -1
  11. package/dist/assets/index-DJHN0H4h.js +3 -0
  12. package/dist/assets/{index-B82A6jBD.css → index-DxqTiFfR.css} +1 -1
  13. package/dist/assets/{ja-D9mS3zWP.js → ja-BPVJtPU2.js} +1 -1
  14. package/dist/assets/{ko-Cpl1IA3D.js → ko-BJHERh2a.js} +1 -1
  15. package/dist/assets/{main-KEVf2Yak.js → main-CLkcy9_q.js} +2 -2
  16. package/dist/assets/main-DUn82Iwq.js +214 -0
  17. package/dist/assets/miniChat-Ag1CYNF5.js +2 -0
  18. package/dist/assets/mobile-DtojUfiY.js +2 -0
  19. package/dist/assets/{pl-CYke_fxL.js → pl-CH00wT_K.js} +1 -1
  20. package/dist/assets/{pt-BR-Clb6Z8up.js → pt-BR-1tfKEfvN.js} +1 -1
  21. package/dist/assets/{renderElectronMiniChatApp-Cb1iUq8M.js → renderElectronMiniChatApp-BTsP-lHc.js} +2 -2
  22. package/dist/assets/{renderMobileApp-7chEBHPK.js → renderMobileApp-CSEgabkw.js} +3 -3
  23. package/dist/assets/{uk-CXn8cxXa.js → uk-BkeRI8D4.js} +1 -1
  24. package/dist/assets/{useAppFontEffects-Bd0ks39c.js → useAppFontEffects-BPhei6aO.js} +107 -107
  25. package/dist/assets/{zh-CN-BRwwlEdG.js → zh-CN-DtROWolc.js} +1 -1
  26. package/dist/assets/{zh-TW-D5pg5Z8l.js → zh-TW-CDqNEP6z.js} +1 -1
  27. package/dist/index.html +3 -3
  28. package/dist/mini-chat.html +3 -3
  29. package/dist/mobile.html +3 -3
  30. package/package.json +1 -1
  31. package/dist/assets/NewWorktreeDialog-5TYBoMMA.js +0 -167
  32. package/dist/assets/index-BsXkdBYx.js +0 -3
  33. package/dist/assets/main-DOdUrt3s.js +0 -214
  34. package/dist/assets/miniChat-Nlzqr3Df.js +0 -2
  35. package/dist/assets/mobile-BIhOFhia.js +0 -2
@@ -1,214 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalView-CMdqMpTy.js","assets/vendor-.bun-By2L9XvG.js","assets/vendor--Dwc_TRgJ.css","assets/useAppFontEffects-Bd0ks39c.js","assets/index-BsXkdBYx.js","assets/index-B82A6jBD.css","assets/NewWorktreeDialog-5TYBoMMA.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-B6kvduse.js","assets/DiagramView-Bbj-QI7h.js","assets/SettingsWindow-BEfDro9b.js","assets/MultiRunWindow-DMMu53kw.js","assets/OnboardingScreen-BucKVBD7.js"])))=>i.map(i=>d[i]);
2
- import{j as s,e as mt,a as ro,R as i,d as Pf,p as cc,b as Tf,H as Xe,I as Rf,u as ga,l as yo,n as xa,D as ba,q as ya,S as Bl,v as Vl,w as dc,C as uc,L as _l,N as Mh,O as Fh,T as Lh,W as Oh,X as ni,Y as Bh,$ as Vh,F as _h,a0 as $h,a1 as zh,a2 as Wh,a3 as Ef,a4 as Uh,a5 as Hh,a6 as $l,a7 as Gh,s as Kh,m as qh,a8 as dd,a9 as ud,aa as fd,ab as Yh,ac as Qh,ad as Jh,ae as Xh,af as Zh,ag as ep,_ as io,ah as md,ai as hd,aj as pd,G as tp}from"./vendor-.bun-By2L9XvG.js";import{f as fc,h as dr,j as Ji,k as gd,l as sp,m as wa,n as Mf,p as np,e as As,q as Lo,b as Ee,t as rp,v as Fa,w as Gr,a as Wr,x as Ur,y as zl,z as ip,A as op,R as xd,B as bd,u as Js,C as ap,D as Ni,E as Ff,F as Lf,G as mc,o as Vn,H as lp,g as Ci,I as cp,r as hc,J as dp,K as pc,L as Of,M as up,N as fp,O as na,P as ra,Q as mp,S as hp,T as pp,U as yd,V as wd,W as vd,X as jd,Y as gp,Z as xp,_ as Sd,d as Nd,$ as bp,a0 as yp,a1 as wp,i as vp,s as jp}from"./index-BsXkdBYx.js";import{u as Nt,m as Pe,ao as bs,I as D,p as ur,t as ce,ap as en,aq as Rr,ar as tn,as as sn,a as Jn,at as Er,au as Ii,av as kd,aw as Et,ax as Mt,ay as Ft,az as Sp,ac as Do,aA as va,aB as ri,ad as Io,ae as Bf,a5 as gc,aC as Vf,aD as Np,Q as ss,z as ut,aE as kp,a7 as _f,y as vr,x as xc,D as ws,R as Pi,aF as $f,aG as zf,aH as ja,aI as Wf,aJ as Uf,aK as Hf,aL as Gf,aM as Cp,aN as Ap,T as bc,aO as La,aP as ii,aQ as yc,aR as ia,X as Zs,aS as Dp,aT as Kf,aU as Ip,aV as qf,aW as wc,aX as Hs,aY as Us,B as $e,aZ as _s,a_ as $s,a$ as ci,b0 as Pp,b1 as Tp,b2 as zo,b3 as Tn,b4 as Yf,b5 as Qf,a2 as vc,b6 as Rp,b7 as Cd,b8 as Ad,b9 as ki,n as vn,ba as Ti,bb as Xi,bc as Ep,bd as Mp,be as Fp,bf as Lp,bg as Oa,bh as Ba,bi as Va,bj as _a,bk as oi,bl as li,bm as Op,bn as Bp,bo as on,bp as Vp,bq as _p,br as $p,bs as zp,bt as Wp,k as Ai,bu as jc,bv as Up,bw as Hp,bx as Gp,by as Kp,bz as qp,bA as Yp,bB as Qp,bC as _n,bD as $n,bE as zn,bF as Nn,bG as Wn,bH as Ls,bI as Jp,w as Po,M as $a,S as za,bJ as Xp,bK as ir,bL as Zp,b as di,d as Sc,c as Wa,bM as eg,bN as Jf,bO as tg,bP as sg,e as Nc,bQ as ng,f as wn,bR as Ua,a3 as Pr,j as rg,bS as ig,bT as rl,bU as og,bV as ag,F as Hr,bW as kc,bX as Ha,bY as fn,bZ as Ri,l as Zi,b_ as Xf,b$ as lg,c0 as cg,c1 as dg,c2 as Dd,c3 as ug,q as Kr,r as Id,v as Pd,c4 as Td,c5 as Zf,c6 as Rd,c7 as Ed,c8 as em,c9 as fg,ca as tm,o as Md,J as mg,cb as il,cc as Cc,cd as hg,ce as pg,cf as gg,cg as Oo,ch as xg,ci as Ac,cj as bg,ck as Dc,cl as sm,cm as Wo,cn as yg,co as Tr,cp as wg,cq as nm,cr as vg,cs as jg,ct as Fd,cu as rm,cv as im,cw as om,E as Ic,P as Ga,G as Ka,L as Sa,cx as Na,cy as Ln,H as Sg,K as Ng,cz as kg,cA as Wl,cB as Cg,cC as Ag,cD as Dg,cE as Ld,cF as Ig,cG as Pg,cH as Tg,cI as Pc,cJ as am,cK as Rg,cL as Eg,cM as Mg,cN as Fg,cO as Od,cP as Bd,cQ as Lg,cR as Og,cS as Bg,cT as Vg,cU as _g,cV as $g,N as zg,cW as Vd,cX as Wg,cY as lm,O as Ug,cZ as Hg,A as Gg,C as Kg,c_ as qg,c$ as Yg,d0 as Qg,d1 as Jg,d2 as Xg,d3 as Zg,d4 as ex,d5 as tx,d6 as sx,d7 as ka,d8 as nx,d9 as _d,da as rx,db as ix,dc as ox,dd as oo,de as ax,df as $d,dg as lx,dh as cx,di as dx,dj as ux,dk as cm,dl as dm,dm as fx,dn as mx,dp as hx,dq as oa,a9 as px,dr as gx,ds as ol,dt as xx,du as bx,U as yx,V as wx,W as vx,Y as zd,Z as Wd,_ as Ud,dv as jx,$ as um,a0 as fm,dw as Sx,aj as Nx,ak as kx,al as Cx,am as Ax,an as Dx,af as Ix,ag as Px,ah as Tx,ai as Rx}from"./useAppFontEffects-Bd0ks39c.js";import{I as Hd,o as Ex,p as Gd,q as Mx,r as Kd,t as Jr,s as Fx,v as al,w as To,U as Ca,x as Aa,y as eo,z as Bo,B as to,k as mm,M as hm,i as mn,j as Lx,Q as pm,E as Ox,F as Bx,G as Vx,l as Ul,H as gm,P as xm,J as _x,K as $x,C as zx,a as Wx,L as Tc,R as bm,T as Rc,V as Ec,W as Mc,X as ym,Y as wm,Z as Hl,_ as vm,$ as Gl,a0 as aa,a1 as Ux,a2 as Hx,e as wo,N as Gx,D as Kx,u as qx,n as Yx,m as Kl,a3 as Qx,a4 as Jx,g as Xx,a5 as Zx,a6 as eb,c as tb,O as jm,d as sb,a7 as nb}from"./NewWorktreeDialog-5TYBoMMA.js";import{S as rb,C as ib,W as ob,g as Fc,r as ab,n as cs,i as Ro,d as so,c as Gi,a as qd,b as lb,e as vo,f as Sm,h as cb,j as db,u as ll}from"./SessionSwitcherDropdown-B6kvduse.js";function Nm(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:b}=t,p=[];for(const x of e){const y=u(x);if(x.id===n){p.push({afterLine:y.end,id:`edit-${x.id}`,content:s.jsx(Hd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:y,isEditing:!0,onSave:m,onCancel:f},`edit-${x.id}`)});continue}p.push({afterLine:y.end,id:`card-${x.id}`,content:s.jsx(Ex,{draft:x,onEdit:()=>g(x),onDelete:()=>b(x)},`card-${x.id}`)})}if(a&&!n&&!c){const x={...a,start:Math.min(a.start,a.end),end:Math.max(a.start,a.end)};p.push({afterLine:x.end,id:d,content:s.jsx(Hd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:x,isEditing:!1,onSave:m,onCancel:f},d)})}return p}function Yd(t){const e=mt.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const c=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let d;e[5]!==a||e[6]!==c||e[7]!==l?(d={width:c,height:l,...a},e[5]=a,e[6]=c,e[7]=l,e[8]=d):d=e[8];let u;e[9]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"}),e[9]=u):u=e[9];let m;return e[10]!==n||e[11]!==r||e[12]!==d?(m=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:d,...r,children:u}),e[10]=n,e[11]=r,e[12]=d,e[13]=m):m=e[13],m}const ai=[{id:"finder",label:"Finder",appName:"Finder"},{id:"terminal",label:"Terminal",appName:"Terminal"},{id:"iterm2",label:"iTerm2",appName:"iTerm"},{id:"ghostty",label:"Ghostty",appName:"Ghostty"},{id:"vscode",label:"VS Code",appName:"Visual Studio Code"},{id:"intellij",label:"IntelliJ",appName:"IntelliJ IDEA"},{id:"visual-studio",label:"Visual Studio",appName:"Visual Studio"},{id:"cursor",label:"Cursor",appName:"Cursor"},{id:"android-studio",label:"Android Studio",appName:"Android Studio"},{id:"pycharm",label:"PyCharm",appName:"PyCharm"},{id:"xcode",label:"Xcode",appName:"Xcode"},{id:"sublime-text",label:"Sublime",appName:"Sublime Text"},{id:"webstorm",label:"WebStorm",appName:"WebStorm"},{id:"rider",label:"Rider",appName:"Rider"},{id:"zed",label:"Zed",appName:"Zed"},{id:"phpstorm",label:"PhpStorm",appName:"PhpStorm"},{id:"eclipse",label:"Eclipse",appName:"Eclipse"},{id:"windsurf",label:"Windsurf",appName:"Windsurf"},{id:"vscodium",label:"VSCodium",appName:"VSCodium"},{id:"rustrover",label:"RustRover",appName:"RustRover"},{id:"kiro",label:"Kiro",appName:"Kiro"},{id:"antigravity",label:"Antigravity",appName:"Antigravity"},{id:"trae",label:"Trae",appName:"Trae"}],ql="finder",Yl=new Set(["finder","terminal"]),Lc=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=ai.find(n=>n.id===t)??null;return e?Lc(e):null},cl=()=>ai.filter(t=>Yl.has(t.id)).map(t=>({...Lc(t)})),ub=()=>{if(typeof window>"u")return ql;const t=window.localStorage.getItem("openInAppId");return t&&Ql(t)?t:ql};let dl=!1,Vi=!1,Xr=!1,Zr=0,jo=null;const Qd=()=>{jo&&(clearTimeout(jo),jo=null)},yr=ro()((t,e)=>({selectedAppId:ub(),availableApps:cl(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(dl||typeof window>"u")return;dl=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:cl(),hasLoadedApps:u});return}const m=new Set(d.map(p=>p.name)),f=new Map(d.map(p=>[p.name,p.iconDataUrl??void 0])),b=ai.filter(p=>m.has(p.appName)||Yl.has(p.id)).map(p=>({...Lc(p),iconDataUrl:f.get(p.appName)}));t({availableApps:b,hasLoadedApps:!0})},r=async d=>{if(!dr()||!Ji()||Vi||e().hasLoadedApps&&!d)return;const m=ai.map(f=>f.appName);Qd(),Vi=!0,Xr=!1,t({isScanning:!0});try{const{apps:f,success:g,hasCache:b,isCacheStale:p}=await gd(m,d),x=g&&!b&&f.length===0&&Zr<3;if(t({isCacheStale:b?p:!1}),n(f,g?!x:!1),g){if(x){const h=[800,1600,3200][Zr]??3200;Zr+=1,Xr=!0,jo=setTimeout(()=>{r()},h);return}Zr=0,Xr=!1;return}if(Zr<3){const h=[1e3,3e3,7e3][Zr]??7e3;Zr+=1,Xr=!0,jo=setTimeout(()=>{r()},h)}}finally{Vi=!1,Xr||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)&&(Zr=3,Xr=!1,t({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("openchamber:settings-synced",o),window.addEventListener("openchamber:app-ready",a),window.addEventListener("openchamber:installed-apps-updated",c),window.__openchamberAppReady&&r(),window.setTimeout(()=>{e().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(dl||e().initialize(),!dr()||!Ji()||Vi||e().hasLoadedApps&&!n)return;const o=ai.map(a=>a.appName);Qd(),n&&t({hasLoadedApps:!1}),Vi=!0,Xr=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await gd(o,n),d=new Set(a.map(g=>g.name)),u=new Map(a.map(g=>[g.name,g.iconDataUrl??void 0])),f=ai.filter(g=>d.has(g.appName)||Yl.has(g.id)).map(g=>({...g,iconDataUrl:u.get(g.appName)}));t({availableApps:f.length>0?f:cl(),hasLoadedApps:f.length>0,isCacheStale:c?l:!1})}finally{Vi=!1,Xr||t({isScanning:!1})}},selectApp:async n=>{Ql(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await fc({openInAppId:n}))}})),fb="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",mb="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",ul=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__OPENCHAMBER_PLATFORM__!=="win32"?fb:t.id==="terminal"?mb:void 0}),Jd=t=>{const e=mt.c(8),{label:n,iconDataUrl:r,fallbackIconDataUrl:o}=t,[a,c]=i.useState(!1);let l;e[0]!==n?(l=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=l):l=e[1];const d=l,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 b;return e[3]!==u?(b=s.jsx("img",{src:u,alt:"",className:"h-4 w-4 rounded-sm",onError:g}),e[3]=u,e[4]=b):b=e[4],b}let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=Pe("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=m):m=e[5];let f;return e[6]!==d?(f=s.jsx("span",{className:m,children:d}),e[6]=d,e[7]=f):f=e[7],f},hb=t=>{const e=mt.c(75),{directory:n,className:r}=t,{t:o}=Nt(),a=yr(pb),c=yr(gb),l=yr(xb),d=yr(bb),u=yr(yb),m=yr(wb),f=yr(vb);let g,b;e[0]!==u?(g=()=>{u()},b=[u],e[0]=u,e[1]=g,e[2]=b):(g=e[1],b=e[2]),i.useEffect(g,b);const p=dr()&&Ji();let x;e:{let ke;e[3]!==c||e[4]!==a?(ke=c.find(F=>F.id===a)??c.find(jb)??c[0]??ai[0],e[3]=c,e[4]=a,e[5]=ke):ke=e[5];const Q=ke;if(Q){let F;e[6]!==Q?(F=ul(Q),e[6]=Q,e[7]=F):F=e[7],x=F;break e}let ge;e[8]===Symbol.for("react.memo_cache_sentinel")?(ge=ul(ai[0]),e[8]=ge):ge=e[8],x=ge}const y=x;if(!p||!n||c.length===0)return null;let h;e[9]!==n?(h=async ke=>{await sp(n,ke.id,ke.appName)||await wa(n,ke.appName)},e[9]=n,e[10]=h):h=e[10];const C=h;let w;e[11]!==C||e[12]!==f?(w=async ke=>{await f(ke.id),await C(ke)},e[11]=C,e[12]=f,e[13]=w):w=e[13];const S=w;let j;e[14]!==n||e[15]!==o?(j=async()=>{(await ur(n)).ok&&ce.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=Pe("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r),e[17]=r,e[18]=v):v=e[18];let A;e[19]!==C||e[20]!==y?(A=()=>{C(y)},e[19]=C,e[20]=y,e[21]=A):A=e[21];const I=d&&"animate-pulse";let N;e[22]!==I?(N=Pe("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",I),e[22]=I,e[23]=N):N=e[23];let O;e[24]!==y.label||e[25]!==o?(O=o("openInApp.actions.openInAria",{app:y.label}),e[24]=y.label,e[25]=o,e[26]=O):O=e[26];let P;e[27]!==y.fallbackIconDataUrl||e[28]!==y.iconDataUrl||e[29]!==y.label?(P=s.jsx(Jd,{label:y.label,iconDataUrl:y.iconDataUrl,fallbackIconDataUrl:y.fallbackIconDataUrl}),e[27]=y.fallbackIconDataUrl,e[28]=y.iconDataUrl,e[29]=y.label,e[30]=P):P=e[30];let T;e[31]!==N||e[32]!==O||e[33]!==P||e[34]!==A?(T=s.jsx("button",{type:"button",onClick:A,className:N,"aria-label":O,children:P}),e[31]=N,e[32]=O,e[33]=P,e[34]=A,e[35]=T):T=e[35];let L;e[36]===Symbol.for("react.memo_cache_sentinel")?(L=Pe("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),e[36]=L):L=e[36];let R;e[37]!==o?(R=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=R):R=e[38];let B;e[39]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=B):B=e[39];let V;e[40]!==R?(V=s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",className:L,"aria-label":R,children:B})}),e[40]=R,e[41]=V):V=e[41];let _;e[42]!==k?(_=()=>{k()},e[42]=k,e[43]=_):_=e[43];let E;e[44]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(D,{name:"file-copy",className:"h-4 w-4"}),e[44]=E):E=e[44];let Z;e[45]!==o?(Z=o("openInApp.actions.copyPath"),e[45]=o,e[46]=Z):Z=e[46];let ne;e[47]!==Z?(ne=s.jsx("span",{className:"typography-ui-label text-foreground",children:Z}),e[47]=Z,e[48]=ne):ne=e[48];let Y;e[49]!==_||e[50]!==ne?(Y=s.jsxs(bs,{className:"flex items-center gap-2",onClick:_,children:[E,ne]}),e[49]=_,e[50]=ne,e[51]=Y):Y=e[51];let H;e[52]===Symbol.for("react.memo_cache_sentinel")?(H=s.jsx(Rr,{}),e[52]=H):H=e[52];let re;if(e[53]!==c||e[54]!==S||e[55]!==y.id){let ke;e[57]!==S||e[58]!==y.id?(ke=Q=>{const ge=ul(Q);return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{S(Q)},children:[s.jsx(Jd,{label:Q.label,iconDataUrl:Q.iconDataUrl,fallbackIconDataUrl:ge.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Q.label}),y.id===Q.id?s.jsx(D,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},Q.id)},e[57]=S,e[58]=y.id,e[59]=ke):ke=e[59],re=c.map(ke),e[53]=c,e[54]=S,e[55]=y.id,e[56]=re}else re=e[56];let ae;e[60]!==l||e[61]!==m||e[62]!==o?(ae=l?s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{m(!0)},children:[s.jsx(D,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:o("openInApp.actions.refreshApps")})]}):null,e[60]=l,e[61]=m,e[62]=o,e[63]=ae):ae=e[63];let me;e[64]!==Y||e[65]!==re||e[66]!==ae?(me=s.jsxs(tn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Y,H,re,ae]}),e[64]=Y,e[65]=re,e[66]=ae,e[67]=me):me=e[67];let Se;e[68]!==V||e[69]!==me?(Se=s.jsxs(sn,{children:[V,me]}),e[68]=V,e[69]=me,e[70]=Se):Se=e[70];let te;return e[71]!==T||e[72]!==Se||e[73]!==v?(te=s.jsxs("div",{className:v,children:[T,Se]}),e[71]=T,e[72]=Se,e[73]=v,e[74]=te):te=e[74],te};function pb(t){return t.selectedAppId}function gb(t){return t.availableApps}function xb(t){return t.isCacheStale}function bb(t){return t.isScanning}function yb(t){return t.initialize}function wb(t){return t.loadInstalledApps}function vb(t){return t.selectApp}function jb(t){return t.id===ql}const Sb=1e6,Nb="terminal-store";let Xd=!1;const fl=t=>typeof t=="object"&&t!==null,kb=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function Dn(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const ml=(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}),hl=t=>({tabs:[t],activeTabId:t.id}),xr=(t,e)=>t.tabs.findIndex(n=>n.id===e),Vs=ro()(Pf(cc((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Dn(n);r&&t(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),c=`tab-${o.nextTabId}`,l=ml(c,"Terminal");return a.set(r,hl(l)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=Dn(n);return e().sessions.get(r)},getActiveTab:n=>{const r=Dn(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=Dn(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=ml(o,m);return l?c.set(r,{...l,tabs:[...l.tabs,f]}):c.set(r,hl(f)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Dn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);return!l||l.activeTabId===r||xr(l,r)<0?a:(c.set(o,{...l,activeTabId:r}),{sessions:c})})},setTabLabel:(n,r,o)=>{const a=Dn(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),u=d.get(a);if(!u)return l;const m=xr(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=Dn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=xr(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=Dn(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await np(l)}catch{}t(d=>{const u=new Map(d.sessions),m=u.get(o);if(!m)return d;const f=xr(m,r);if(f<0)return d;const g=m.tabs.filter(y=>y.id!==r),b=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,y])=>!(y.directory===o&&y.tabId===r))),p=Object.keys(b).length!==Object.keys(d.projectActionRuns).length;if(g.length===0){const y=`tab-${d.nextTabId}`,h=ml(y,"Terminal");return u.set(o,hl(h)),{sessions:u,nextTabId:d.nextTabId+1,...p?{projectActionRuns:b}:{}}}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:b}:{}}})},setTabSessionId:(n,r,o)=>{const a=Dn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=xr(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,b={...m,terminalSessionId:o,lifecycle:g,isConnecting:!1,...f?{bufferChunks:[],bufferLength:0}:{}},p=[...d.tabs];return p[u]=b,l.set(a,{...d,tabs:p}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=Dn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=xr(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=Dn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=xr(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=Dn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const u=xr(d,r);if(u<0)return c;const m=d.tabs[u],f=c.nextChunkId,g={id:f,data:o},b=[...m.bufferChunks,g];let p=m.bufferLength+o.length;for(;p>Sb&&b.length>1;){const y=b.shift();if(!y)break;p-=y.data.length}const x=[...d.tabs];return x[u]={...m,bufferChunks:b,bufferLength:p},l.set(a,{...d,tabs:x}),{sessions:l,nextChunkId:f+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=Dn(n);t(l=>{const d=new Map(l.sessions),u=d.get(c);if(!u)return l;const m=xr(u,r);if(m<0)return l;const f=u.tabs[m],g=a.autoOpened??f.previewAutoOpened,b=a.locked??f.previewUrlLocked;if(f.previewUrl===o&&f.previewAutoOpened===g&&f.previewUrlLocked===b)return l;const p=[...u.tabs];return p[m]={...f,previewUrl:o,previewAutoOpened:g,previewUrlLocked:b},d.set(c,{...u,tabs:p}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Dn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=xr(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=Dn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=xr(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=Dn(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:Nb,storage:Tf(()=>Mf()),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(!fl(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"||!fl(u))continue;const m=Array.isArray(u.tabs)?u.tabs:[],f=[];for(const p of m){if(!fl(p))continue;const x=typeof p.id=="string"?p.id:null;if(!x)continue;const y=kb(x);y!==null&&(o=Math.max(o,y));const h=typeof p.terminalSessionId=="string"||p.terminalSessionId===null?p.terminalSessionId:null,C=p.lifecycle,w=C==="idle"||C==="running"||C==="exited"?C: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,b=g?f.some(p=>p.id===g):!1;r.set(d,{tabs:f,activeTabId:b?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"&&!Xd){Xd=!0;const t=Vs.persist,e=()=>{Vs.getState().hasHydrated||Vs.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const Cb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Ab=["dev","start","preview","serve"];async function Db(t,e,n){if(!t)return null;const r=Tb(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=Rb(n);if(o){const a=await Eb(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 Ib(t)){const o=await Pb(),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 Ib(t){const e=`${t}/index.html`,n=await Da(e,t);return typeof n=="string"&&n.trim().length>0}async function Pb(){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 Tb(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(Ab.some(o=>n.includes(o)))return e}return null}function Rb(t){for(const{pattern:e}of Cb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function Eb(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 Mb(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 Fb=t=>new Promise(e=>{window.setTimeout(e,t)}),Lb="\x1B",Ob=new RegExp(`${Lb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Bb=/https?:\/\/[^\s<>'"`]+/gi,sr="__openchamber_auto_discover_preview__",Vb=15e3,_b=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},$b=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}},zb=t=>{const n=t.replace(Ob,"").match(Bb);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==="",b=!!(l.search||l.hash);let p=0;return u&&(p+=50),g&&(p+=30),p-=Math.min(f*5,20),b&&(p-=10),p};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},km=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=Nt(),{terminal:c,runtime:l}=Jn(),{isMobile:d}=Er(),u=i.useMemo(()=>dr(),[]),m=Gd(z=>z.instances),f=Gd(z=>z.load),g=Ee(z=>z.setBottomTerminalOpen),b=Ee(z=>z.setActiveMainTab),p=Ee(z=>z.setSettingsPage),x=Ee(z=>z.setSettingsDialogOpen),y=Ee(z=>z.setSettingsProjectsSelectedId),h=Ee(z=>z.openContextPreview),C=Vs(z=>z.sessions),w=Vs(z=>z.ensureDirectory),S=Vs(z=>z.setTabLabel),j=Vs(z=>z.setTabIconKey),k=Vs(z=>z.setActiveTab),v=Vs(z=>z.setConnecting),A=Vs(z=>z.setTabSessionId),I=Vs(z=>z.setTabPreviewUrl),N=Vs(z=>z.projectActionRuns),O=Vs(z=>z.setProjectActionRun),P=Vs(z=>z.updateProjectActionRunStatus),T=Vs(z=>z.removeProjectActionRun),[L,R]=i.useState([]),[B,V]=i.useState(null),[_,E]=i.useState(!1),Z=i.useRef({}),ne=i.useRef({}),Y=i.useRef({}),H=i.useRef({}),re=i.useRef(0),ae=t?.id??null,me=t?.path??"",Se=i.useMemo(()=>ae?{id:ae,path:me}:null,[ae,me]);i.useEffect(()=>{u&&f().catch(()=>{})},[u,f]);const te=i.useCallback(async z=>{await Ii(z)},[]),ke=i.useCallback(async()=>{if(!Se)return;const z=re.current+1;re.current=z,E(!0);try{const xe=await kd(Se);if(re.current!==z)return;const je=xe.actions;R(je),V(K=>K===sr||K&&je.some(ye=>ye.id===K)?K:null)}catch{if(re.current!==z)return}finally{re.current===z&&E(!1)}},[Se]),Q=i.useMemo(()=>Mx(e||Se?.path||""),[e,Se?.path]),ge=i.useMemo(()=>B?L.find(z=>z.id===B)??null:null,[L,B]),F=i.useMemo(()=>({id:sr,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),se=!d,ee=i.useMemo(()=>se?[F,...L]:L,[L,F,se]);i.useEffect(()=>{ke()},[ke]),i.useEffect(()=>{if(typeof window>"u")return;const z=xe=>{const je=xe.detail;ae&&(je?.projectId&&je.projectId!==ae||ke())};return window.addEventListener(Kd,z),()=>{window.removeEventListener(Kd,z)}},[ke,ae]),i.useEffect(()=>{B&&(B===sr&&se||L.some(z=>z.id===B)||V(null))},[L,se,B]),i.useEffect(()=>{for(const[z,xe]of Object.entries(N)){const K=C.get(xe.directory)?.tabs.find(ye=>ye.id===xe.tabId);(!K||K.terminalSessionId!==xe.sessionId)&&T(z)}},[N,T,C]),i.useEffect(()=>{for(const[z,xe]of Object.entries(N)){const je=ne.current[z]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};ne.current[z]=je;const K=ee.find(Oe=>Oe.id===xe.actionId);if(!K)continue;const Le=C.get(xe.directory)?.tabs.find(Oe=>Oe.id===xe.tabId);if(!Le||!Array.isArray(Le.bufferChunks)||Le.bufferChunks.length===0)continue;const Re=Le.bufferChunks.filter(Oe=>je.lastSeenChunkId===null?!0:Oe.id>je.lastSeenChunkId);if(Re.length===0)continue;const X=Re.map(Oe=>Oe.data).join(""),M=`${je.tail}${X}`,le=!je.openedUrl&&K.autoOpenUrl===!0?zb(M):null,ie=Re[Re.length-1]?.id??je.lastSeenChunkId;if(je.lastSeenChunkId=ie,je.tail=M.slice(-512),le)if(je.openedUrl=!0,je.openInPreview){const Oe=N[z];Oe&&(I(Oe.directory,Oe.tabId,le,{locked:!1,autoOpened:!1}),Oe.status==="waiting-for-preview"&&P(z,"running"),window.clearTimeout(H.current[z]),delete H.current[z],h(Oe.directory,le))}else te(le),ce.success(a("projectActions.toast.openedUrlFromOutput"));ne.current[z]=je}for(const z of Object.keys(ne.current))N[z]||(delete ne.current[z],window.clearTimeout(H.current[z]),delete H.current[z])},[ee,h,te,N,I,a,C,P]);const Ne=i.useCallback(async(z,xe={})=>{if(!Q)throw new Error(a("projectActions.error.noActiveDirectory"));const je=Jr(Q,z.id);w(Q);const K=Vs.getState(),ye=K.getDirectoryState(Q);let Le=Z.current[je]||null;const Re=Le?!!ye?.tabs.some(le=>le.id===Le):!1;(!Le||!Re)&&(Le=K.createTab(Q),Z.current[je]=Le),S(Q,Le,`Action: ${z.name}`),j(Q,Le,z.icon||"play"),xe.revealTerminal!==!1&&(k(Q,Le),g(!0),b("terminal"));const M=Vs.getState().getDirectoryState(Q)?.tabs.find(le=>le.id===Le);return{key:je,tabId:Le,sessionId:M?.terminalSessionId??null}},[w,Q,b,k,g,j,S,a]),De=i.useCallback(async z=>{if(l.isVSCode||!o&&d)return;if(!Q){ce.error(a("projectActions.error.noActiveDirectoryForAction"));return}const xe=Jr(Q,z.id),je=N[xe];if(!(je&&je.status==="running"))try{const K=z.id===sr?await(async()=>{const[Je,rt]=await Promise.all([kd({id:Se?.id??"",path:Q}),Mb(Q)]),bt=await Db(Q,Je.actions,rt);if(!bt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:sr,name:a("projectActions.actions.autoDiscover"),command:bt.command,icon:"search",autoOpenUrl:!0,openUrl:bt.previewUrlHint||""}})():z,ye=K.autoOpenUrl===!0&&(K.openUrl||"").trim().length>0,{key:Le,tabId:Re,sessionId:X}=await Ne(K,{revealTerminal:!ye&&z.id!==sr});let M=X,le=!1;if(!M){v(Q,Re,!0);try{M=(await c.createSession({cwd:Q})).sessionId,le=!0,A(Q,Re,M)}finally{v(Q,Re,!1)}}if(!M)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));le&&await Fb(350),K.id===sr&&(Y.current[Le]?.(),v(Q,Re,!0),Y.current[Le]=rp(M,Je=>{Je.type==="data"&&typeof Je.data=="string"&&Je.data.length>0&&Vs.getState().appendToBuffer(Q,Re,Je.data),Je.type==="exit"&&(Vs.getState().setTabLifecycle(Q,Re,"exited"),Vs.getState().setConnecting(Q,Re,!1),Vs.getState().removeProjectActionRun(Le),delete ne.current[Le],Y.current[Le]?.(),delete Y.current[Le],window.clearTimeout(H.current[Le]),delete H.current[Le])},()=>{Vs.getState().setConnecting(Q,Re,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const ie=K.autoOpenUrl===!0&&u&&(K.desktopOpenSshForward||"").trim().length>0,Oe=K.autoOpenUrl?$b(K.openUrl):null,Ge=K.autoOpenUrl&&u?Fx(K.desktopOpenSshForward,m):null;O({key:Le,directory:Q,actionId:K.id,tabId:Re,sessionId:M,status:K.id===sr&&!Oe?"waiting-for-preview":"running"}),window.clearTimeout(H.current[Le]),delete H.current[Le],K.id===sr&&!Oe&&(H.current[Le]=window.setTimeout(()=>{Vs.getState().updateProjectActionRunStatus(Le,"running"),delete H.current[Le]},Vb)),Ge?(I(Q,Re,null,{locked:!0}),te(Ge),ce.success(a("projectActions.toast.openedForwardedUrl"))):Oe?(I(Q,Re,Oe,{locked:!0,autoOpened:!0}),h(Q,Oe),ce.success(a("projectActions.toast.openedActionUrl"))):ye?(I(Q,Re,null,{locked:!0}),ce.error(a("projectActions.error.invalidCustomUrlFormat"))):ie?(I(Q,Re,null,{locked:!0}),ce.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):I(Q,Re,null,{locked:!1,autoOpened:!1}),ne.current[Le]={lastSeenChunkId:null,openedUrl:!!Ge||!!Oe||ye,tail:"",openInPreview:K.id===sr};const He=_b(K.command.trim().replace(/\r\n|\r/g,`
3
- `));await c.sendInput(M,`${He}\r`)}catch(K){T(xe),delete ne.current[xe],Y.current[xe]?.(),delete Y.current[xe],window.clearTimeout(H.current[xe]),delete H.current[xe],ce.error(K instanceof Error?K.message:a("projectActions.error.failedToRunAction"))}},[m,Ne,o,d,u,Q,te,h,N,l.isVSCode,T,v,O,I,A,Se?.id,a,c]),Be=i.useCallback(async z=>{const xe=Jr(Q,z.id),je=N[xe];if(!je)return;P(xe,"stopping");try{await c.sendInput(je.sessionId,"")}catch{}if(await new Promise(Le=>{window.setTimeout(Le,1e3)}),Vs.getState().getDirectoryState(je.directory)?.tabs.find(Le=>Le.id===je.tabId)?.terminalSessionId===je.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:je.sessionId})}catch{}else try{await c.close(je.sessionId)}catch{}A(je.directory,je.tabId,null)}T(xe),delete ne.current[xe],Y.current[xe]?.(),delete Y.current[xe],window.clearTimeout(H.current[xe]),delete H.current[xe]},[Q,N,T,A,c,P]),Fe=i.useCallback(()=>{const z=ge??ee[0];if(!z)return;const xe=Jr(Q,z.id),je=N[xe];if(je?.status!=="stopping"){if(je){Be(z);return}De(z)}},[ee,Q,De,N,ge,Be]),Me=i.useCallback((z,xe=!1)=>{if(V(z.id),!xe){De(z);return}const je=Jr(Q,z.id),K=N[je];if(K?.status!=="stopping"){if(K){Be(z);return}De(z)}},[Q,De,N,Be]),he=i.useCallback(()=>{Se?.id&&(y(Se.id),p("projects"),x(!0))},[x,p,y,Se?.id]);if(l.isVSCode||!o&&d||!Se||!Q)return null;const Ae=ge??ee[0]??null;if(!Ae)return null;const pe=Ae.icon||"play",ue=Ae.id===sr?"search":al[pe]||"play",U=Jr(Q,Ae.id),fe=N[U],de=fe?.status==="stopping",G=fe?.status==="waiting-for-preview",$=fe?C.get(fe.directory)?.tabs.find(z=>z.id===fe.tabId)?.previewUrl??null:null,ve=!!(fe&&$),be=()=>{!fe||!$||h(fe.directory,$)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:_||de,className:Pe("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:Fe,"aria-label":fe?a("projectActions.actions.stopNamedAria",{name:Ae.name}):a("projectActions.actions.runNamedAria",{name:Ae.name}),children:de||G?s.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):fe?s.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(D,{name:ue,className:"h-5 w-5"})}),ve?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":a("projectActions.actions.openPreview"),onClick:be,children:s.jsx(D,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(sn,{children:[s.jsx(en,{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(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(tn,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(bs,{className:"flex items-center gap-2",onClick:he,children:[s.jsx(D,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Rr,{}),ee.map(z=>{const xe=z.icon||"play",je=z.id===sr?"search":al[xe]||"play",K=Jr(Q,z.id),ye=N[K],Le=!!ye,Re=ye?.status==="stopping";return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Me(z,!0)},children:[s.jsx(D,{name:je,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:z.name}),Re||ye?.status==="waiting-for-preview"?s.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?s.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},z.id)})]})]})]}):s.jsxs("div",{className:Pe("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[s.jsx("button",{type:"button",onClick:Fe,disabled:_||de,className:Pe("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":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:de||G?s.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):fe?s.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(D,{name:ue,className:"h-4 w-4"})})}),ve?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:be,className:Pe(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":a("projectActions.actions.openPreview"),children:s.jsx(D,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(sn,{children:[s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":a("projectActions.actions.chooseActionAria"),children:s.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(tn,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(bs,{className:"flex items-center gap-2",onClick:he,children:[s.jsx(D,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Rr,{}),ee.map(z=>{const xe=z.icon||"play",je=z.id===sr?"search":al[xe]||"play",K=Jr(Q,z.id),ye=N[K],Le=!!ye,Re=ye?.status==="stopping";return s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Me(z,!0)},children:[s.jsx(D,{name:je,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:z.name}),Re||ye?.status==="waiting-for-preview"?s.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Le?s.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},z.id)})]})]})]})},qa="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Wb="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=mt.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 b=l??qa,p=g&&"bg-interactive-selection text-interactive-selection-foreground";let x;n[0]!==b||n[1]!==p?(x=Pe(b,p),n[0]=b,n[1]=p,n[2]=x):x=n[2];const y=u??"h-[18px] w-[18px]";let h;n[3]!==d||n[4]!==y?(h=s.jsx(D,{name:d,className:y}),n[3]=d,n[4]=y,n[5]=h):h=n[5];let C;n[6]!==a||n[7]!==c||n[8]!==g||n[9]!==x||n[10]!==h?(C=s.jsx(Mt,{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]=C):C=n[11];let w;n[12]!==o?(w=s.jsx(Ft,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=w):w=n[13];let S;return n[14]!==C||n[15]!==w?(S=s.jsxs(Et,{children:[C,w]}),n[14]=C,n[15]=w,n[16]=S):S=n[16],S}),Ub=i.memo(function(e){const n=mt.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:u}=e,{t:m}=Nt();if(!o?.connected||r)return null;if(a.length>1){let p;n[0]===Symbol.for("react.memo_cache_sentinel")?(p=Pe(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 y;n[4]!==c||n[5]!==l||n[6]!==m?(y=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(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=m,n[7]=y):y=n[7];let h;n[8]!==d||n[9]!==x||n[10]!==y?(h=s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",className:p,title:x,disabled:d,children:y})}),n[8]=d,n[9]=x,n[10]=y,n[11]=h):h=n[11];let C;n[12]!==m?(C=m("header.github.accountsTitle"),n[12]=m,n[13]=C):C=n[13];let w;n[14]!==C?(w=s.jsx(Np,{className:"typography-ui-header font-semibold text-foreground",children:C}),n[14]=C,n[15]=w):w=n[15];let S;n[16]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(Rr,{}),n[16]=S):S=n[16];let j;if(n[17]!==a||n[18]!==u||n[19]!==d||n[20]!==m){let A;n[22]!==u||n[23]!==d||n[24]!==m?(A=I=>{const N=I.user,O=!!I.current,P=I.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(I.id)},children:[N?.avatarUrl?s.jsx("img",{src:N.avatarUrl,alt:N.login?m("header.github.avatarWithLogin",{login:N.login}):m("header.github.avatar"),className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:s.jsx(D,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:N?.name?.trim()||N?.login||"GitHub"}),N?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:N.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:P})]}):null]}),O?s.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]},I.id)},n[22]=u,n[23]=d,n[24]=m,n[25]=A):A=n[25],j=a.map(A),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(tn,{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(sn,{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(D,{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 b;return n[39]!==f||n[40]!==g?(b=s.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:f,children:g}),n[39]=f,n[40]=g,n[41]=b):b=n[41],b}),Hb=i.memo(function(e){const n=mt.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:u,desktopServicesTab:m,setDesktopServicesTab:f,quotaResultsLength:g,fetchAllQuotas:b,servicesTabItems:p,quotaLastUpdated:x,quotaDisplayMode:y,quotaDisplayTabItems:h,handleDisplayModeChange:C,handleUsageRefresh:w,isQuotaLoading:S,isUsageRefreshSpinning:j,hasRateLimits:k,rateLimitGroups:v,expandedFamilies:A,toggleFamilyExpanded:I,shortcutLabel:N,showDevShutdown:O,isDevShutdownInFlight:P,onDevShutdown:T,remoteUpdateInfo:L,remoteUpdateChecking:R,remoteUpdateError:B,onOpenRemoteUpdate:V,showPredValues:_,timeFormatPreference:E}=e,{t:Z}=Nt();let ne;n[0]!==m||n[1]!==b||n[2]!==g||n[3]!==u||n[4]!==d?(ne=Me=>{d(Me),Me&&(u(),m==="usage"&&g===0&&b())},n[0]=m,n[1]=b,n[2]=g,n[3]=u,n[4]=d,n[5]=ne):ne=n[5];let Y;n[6]!==o||n[7]!==r||n[8]!==Z?(Y=r?Z("header.services.openWithCurrent",{current:o}):Z("header.services.open"),n[6]=o,n[7]=r,n[8]=Z,n[9]=Y):Y=n[9];const H=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let re;n[10]!==H?(re=Pe(qa,H),n[10]=H,n[11]=re):re=n[11];let ae;n[12]===Symbol.for("react.memo_cache_sentinel")?(ae=s.jsx(D,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=ae):ae=n[12];let me;n[13]!==a||n[14]!==r?(me=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=me):me=n[15];let Se;n[16]!==Y||n[17]!==re||n[18]!==me?(Se=s.jsx(Mt,{asChild:!0,children:s.jsx(en,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":Y,className:re,children:[ae,me]})})}),n[16]=Y,n[17]=re,n[18]=me,n[19]=Se):Se=n[19];let te;n[20]!==o||n[21]!==r||n[22]!==N||n[23]!==Z?(te=r?Z("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}):Z("header.services.tooltip.servicesWithShortcuts",{toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}),n[20]=o,n[21]=r,n[22]=N,n[23]=Z,n[24]=te):te=n[24];let ke;n[25]!==te?(ke=s.jsx(Ft,{children:s.jsx("p",{children:te})}),n[25]=te,n[26]=ke):ke=n[26];let Q;n[27]!==Se||n[28]!==ke?(Q=s.jsxs(Et,{children:[Se,ke]}),n[27]=Se,n[28]=ke,n[29]=Q):Q=n[29];let ge;n[30]!==b||n[31]!==g||n[32]!==f?(ge=Me=>{const he=Me;f(he),he==="usage"&&g===0&&b()},n[30]=b,n[31]=g,n[32]=f,n[33]=ge):ge=n[33];let F;n[34]!==m||n[35]!==p||n[36]!==ge?(F=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:ge,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=m,n[35]=p,n[36]=ge,n[37]=F):F=n[37];let se;n[38]!==c||n[39]!==m||n[40]!==r||n[41]!==l||n[42]!==V||n[43]!==R||n[44]!==B||n[45]!==L||n[46]!==d||n[47]!==Z?(se=r&&m==="instance"?s.jsxs("div",{children:[c?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:Z("header.services.remoteUpdate.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:L?.available?Z("header.services.remoteUpdate.available",{version:L.version||""}):R?Z("header.services.remoteUpdate.checking"):B||Z("header.services.remoteUpdate.upToDate")})]}),L?.available?s.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:V,children:Z("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(Sp,{embedded:!0,open:l&&m==="instance",onOpenChange:qb,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=m,n[40]=r,n[41]=l,n[42]=V,n[43]=R,n[44]=B,n[45]=L,n[46]=d,n[47]=Z,n[48]=se):se=n[48];let ee;n[49]!==m||n[50]!==l?(ee=m==="mcp"?s.jsx(hm,{active:l&&m==="mcp"}):null,n[49]=m,n[50]=l,n[51]=ee):ee=n[51];let Ne;n[52]!==m||n[53]!==A||n[54]!==C||n[55]!==w||n[56]!==k||n[57]!==S||n[58]!==j||n[59]!==y||n[60]!==h||n[61]!==x||n[62]!==v||n[63]!==_||n[64]!==Z||n[65]!==E||n[66]!==I?(Ne=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:Cm(x,E)})]}),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:y,onSelect:Me=>{C(Me)},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",className:"h-full"})}),s.jsx("button",{type:"button",className:Pe("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:w,disabled:S||j,"aria-label":Z("header.services.refreshRateLimitsAria"),children:s.jsx(D,{name:"refresh",className:Pe("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,he)=>{const Ae=A[Me.providerId]??[];return s.jsxs(i.Fragment,{children:[he>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,U]=pe,fe=y==="remaining"?U.remainingPercent:U.usedPercent,de=va(U.usedPercent,U.resetAt,U.windowSeconds,ue),G=de?.dailyAllocationPercent!=null?y==="remaining"?100-ri(de.elapsedRatio):ri(de.elapsedRatio):null,$=Io(U.valueLabel,fe),ve=Bf(U.resetAt,U.resetAfterFormatted??U.resetAtFormatted,E);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:gc(ue)}),ve?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:ve}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:$==="-"?"":$})]}),s.jsx(Ca,{percent:fe,tonePercent:U.usedPercent,className:"h-1.5",expectedMarkerPercent:G}),de&&_?s.jsx(Aa,{paceInfo:de,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",U=Ae.includes(ue);return s.jsxs(eo,{open:U,onOpenChange:()=>I(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}),U?s.jsx(D,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(to,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:pe.models.map(fe=>{const[de,G]=fe,$=y==="remaining"?G.remainingPercent:G.usedPercent,ve=va(G.usedPercent,G.resetAt,G.windowSeconds),be=ve?.dailyAllocationPercent!=null?y==="remaining"?100-ri(ve.elapsedRatio):ri(ve.elapsedRatio):null,z=Io(G.valueLabel,$);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:mm(de)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:z==="-"?"":z})]}),s.jsx(Ca,{percent:$,tonePercent:G.usedPercent,className:"h-1.5",expectedMarkerPercent:be}),ve&&_?s.jsx(Aa,{paceInfo:ve,compact:!0}):null]},`${Me.providerId}-${de}`)})})})]},ue)})}):null]})]},Me.providerId)})})]}):null,n[52]=m,n[53]=A,n[54]=C,n[55]=w,n[56]=k,n[57]=S,n[58]=j,n[59]=y,n[60]=h,n[61]=x,n[62]=v,n[63]=_,n[64]=Z,n[65]=E,n[66]=I,n[67]=Ne):Ne=n[67];let De;n[68]!==P||n[69]!==T||n[70]!==O||n[71]!==Z?(De=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:P,onSelect:()=>{T()},children:Z("header.services.shutdownDev")})})]}):null,n[68]=P,n[69]=T,n[70]=O,n[71]=Z,n[72]=De):De=n[72];let Be;n[73]!==F||n[74]!==se||n[75]!==ee||n[76]!==Ne||n[77]!==De?(Be=s.jsxs(tn,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[F,se,ee,Ne,De]}),n[73]=F,n[74]=se,n[75]=ee,n[76]=Ne,n[77]=De,n[78]=Be):Be=n[78];let Fe;return n[79]!==l||n[80]!==ne||n[81]!==Q||n[82]!==Be?(Fe=s.jsxs(sn,{open:l,onOpenChange:ne,children:[Q,Be]}),n[79]=l,n[80]=ne,n[81]=Q,n[82]=Be,n[83]=Fe):Fe=n[83],Fe}),Gb=(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??""),Kb=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},Cm=(t,e)=>{if(!t)return"-";try{return Vf(t,e,{fallback:"-"})}catch{return"-"}},In=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},ei=t=>!t?.isOpen||!Array.isArray(t.tabs)||t.tabs.length===0?null:(t.tabs.find(n=>n.id===t.activeTabId)??t.tabs[t.tabs.length-1])?.mode??null,Zd=({onToggleLeftDrawer:t,onToggleRightDrawer:e,leftDrawerOpen:n,rightDrawerOpen:r})=>{const{t:o}=Nt(),a=Ee(J=>J.setSessionSwitcherOpen),c=Ee(J=>J.toggleSidebar),l=Ee(J=>J.isSidebarOpen),d=Ee(J=>J.toggleBottomTerminal),u=Ee(J=>J.toggleRightSidebar),m=Ee(J=>J.openContextOverview),f=Ee(J=>J.openContextPlan),g=Ee(J=>J.openContextBrowser),b=Ee(J=>J.openContextPanelTab),p=Ee(J=>J.closeContextPanel),x=Ee(J=>J.contextPanelByDirectory),y=Ee(J=>J.activeMainTab),h=Ee(J=>J.setActiveMainTab),C=Ee(J=>J.shortcutOverrides),w=Ee(J=>J.timeFormatPreference),S=ss(J=>J.getCurrentModel),j=Jn(),[k,v]=i.useState(!1),A=ut(J=>J.getContextUsage),I=ut(J=>!!J.newSessionDraft?.open),N=ut(J=>J.currentSessionId),O=kp(N??""),P=_f(N??null),T=vr(J=>J.activeSessions),L=xc(),R=ws(J=>J.activeProjectId?J.projects.find(st=>st.id===J.activeProjectId)??null:null),B=i.useMemo(()=>{if(!R)return null;const J=R.label?.trim();if(J)return J;const st=R.path.split(/[\\/]/).filter(Boolean);return st[st.length-1]??null},[R]),V=mn(J=>J.results),_=mn(J=>J.fetchAllQuotas),E=mn(J=>J.isLoading),Z=mn(J=>J.lastUpdated),ne=mn(J=>J.displayMode),Y=mn(J=>J.showPredValues),H=mn(J=>J.dropdownProviderIds),re=mn(J=>J.loadSettings),ae=mn(J=>J.setDisplayMode),{isMobile:me}=Er(),Se=Pi(J=>J.status),te=Pi(J=>J.setStatus),ke=i.useRef(null),[Q,ge]=i.useState(()=>typeof window>"u"?!1:dr()),F=i.useMemo(()=>Fa(),[]),se=$f(),[ee,Ne]=i.useState(!1),De=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),Be=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32",[]),Fe=i.useMemo(()=>{if(typeof window>"u")return null;const J=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof J=="number"&&Number.isFinite(J)&&J>0)return J;if(typeof navigator>"u")return null;const st=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!st)return null;const gt=Number.parseInt(st[1],10),Pt=Number.parseInt(st[2],10);return Number.isNaN(gt)?null:gt===10?Pt:gt},[]);Xe.useEffect(()=>{typeof window>"u"||ge(dr())},[]);const Me=S(),he=Me&&typeof Me.limit=="object"&&Me.limit!==null?Me.limit:null,Ae=he&&typeof he.context=="number"?he.context:0,pe=he&&typeof he.output=="number"?he.output:0,ue=A(Ae,pe),[U,fe]=i.useState(null),de=!N||O;Xe.useEffect(()=>{if(!N){fe(J=>J===null?J:null);return}if(ue&&ue.totalTokens>0){fe(J=>Gb(J,ue)?J:ue);return}de&&fe(J=>J===null?J:null)},[ue,N,de]);const G=Ee(J=>J.isSessionSwitcherOpen),$=Se?.connected?Se.user?.avatarUrl??null:null,ve=Se?.connected?Se.user?.login??null:null,be=Se?.accounts??[],[z,xe]=i.useState(!1),[je,K]=i.useState(!1),[ye,Le]=i.useState(!1),[Re,X]=i.useState(!1),[M,le]=i.useState("Local"),[ie,Oe]=i.useState(!0),[Ge,He]=i.useState(!1),[Je,rt]=i.useState(null),[bt,yt]=i.useState(!1),[_e,Ye]=i.useState(null),nt=i.useMemo(()=>Kb(M),[M]),[wt,kt]=i.useState(Q?"instance":"usage"),[vt,St]=i.useState("usage");Xe.useEffect(()=>{!Q&&wt==="instance"&&kt("usage")},[wt,Q]);const et=i.useMemo(()=>Gr(),[]),Ot=!et&&y==="chat"&&!!U&&U.totalTokens>0,ns=U&&U.contextLimit>0?Math.min(999,U.totalTokens/U.contextLimit*100):0,Wt=i.useCallback(async()=>{if(!(typeof window>"u"||!Q))try{if(Ji()){le("Local"),Oe(!0);return}Oe(!1);const J=await zf(),st=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,gt=Wr();if(gt&&ja(gt,st)){le("Local"),Oe(!0);return}const Pt=J.hosts.find(Zt=>gt?ja(gt,Wf(Zt)):!1);if(Pt?.label?.trim()){le(Uf(Pt.label.trim()));return}le("Instance")}catch{le("Local"),Oe(!0)}},[Q]);Xe.useEffect(()=>{Wt()},[Wt]);const Ve=i.useCallback(async()=>{if(ie){rt(null),Ye(null);return}yt(!0),Ye(null);try{const J=new URLSearchParams({appType:"web",instanceMode:"remote"}),st=await As(`/api/openchamber/update-check?${J.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!st.ok)throw new Error(`Server responded with ${st.status}`);const gt=await st.json();rt({available:gt.available??!1,version:gt.version,currentVersion:gt.currentVersion??"unknown",body:gt.body,nextSuggestedCheckInSec:typeof gt.nextSuggestedCheckInSec=="number"?gt.nextSuggestedCheckInSec:void 0,packageManager:gt.packageManager,updateCommand:gt.updateCommand})}catch(J){rt(null),Ye(J instanceof Error?J.message:o("header.services.remoteUpdate.error"))}finally{yt(!1)}},[ie,o]);i.useEffect(()=>{rt(null),Ye(null),He(!1)},[ie,M]),i.useEffect(()=>{if(!Q||ie)return;const J=3e3,st=3600*1e3;let gt=!1,Pt=null;const Zt=is=>{Pt=window.setTimeout(()=>{if(gt||typeof document<"u"&&document.visibilityState!=="visible"){Zt(st);return}Ve().finally(()=>{gt||Zt(st)})},is)};return Zt(J),()=>{gt=!0,Pt!==null&&window.clearTimeout(Pt)}},[Ve,ie,M,Q]);const Ze=i.useCallback(()=>{if(Je?.available){He(!0);return}Ve()},[Ve,Je?.available]);Lx();const _t=mn(J=>J.selectedModels),jt=mn(J=>J.expandedFamilies),xt=mn(J=>J.toggleFamilyExpanded),rs=i.useMemo(()=>{const J=[];for(const st of pm){if(!H.includes(st.id))continue;const gt=V.find(Fs=>Fs.providerId===st.id),Pt=gt?.usage?.windows??{},Zt=gt?.usage?.models,is=Object.entries(Pt),ms={providerId:st.id,providerName:st.name,entries:is,error:gt&&!gt.ok&&gt.configured?gt.error:void 0};if(Zt&&Object.keys(Zt).length>0){const Fs=_t[st.id]??[],qs=Fs.length>0,er=Ox(Zt,st.id),qn=Bx(st.id),Fr=Vx(qn);ms.modelFamilies=[];for(const gn of Fr){const tr=er.get(gn.id)??[];if(tr.length===0)continue;const xn=qs?tr.filter(bn=>Fs.includes(bn)):tr;if(xn.length===0)continue;const Mn=[];for(const bn of xn){const or=Zt[bn];if(or?.windows){const Cn=Object.entries(or.windows);Cn.length>0&&Mn.push([bn,Cn[0][1]])}}Mn.length>0&&ms.modelFamilies.push({familyId:gn.id,familyLabel:gn.label,models:Mn})}const Bs=er.get(null)??[],Lr=qs?Bs.filter(gn=>Fs.includes(gn)):Bs;if(Lr.length>0){const gn=[];for(const tr of Lr){const xn=Zt[tr];if(xn?.windows){const Mn=Object.entries(xn.windows);Mn.length>0&&gn.push([tr,Mn[0][1]])}}gn.length>0&&ms.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:gn})}}(is.length>0||ms.modelFamilies&&ms.modelFamilies.length>0||ms.error)&&J.push(ms)}return J},[H,V,_t,o]),Gt=rs.length>0;i.useEffect(()=>{re()},[re]);const Ut=i.useCallback(async J=>{ae(J);try{await fc({usageDisplayMode:J})}catch(st){console.warn("Failed to update usage display mode:",st)}},[ae]),as=i.useCallback(()=>{if(Re)return;X(!0);const J=new Promise(st=>setTimeout(st,500));Promise.all([_(),J]).finally(()=>{X(!1)})},[_,Re]),Bt=i.useMemo(()=>N?L.find(J=>J.id===N)??T.find(J=>J.id===N)??P??Hf().find(J=>J.id===N)??null:null,[N,P,T,L]),Lt=i.useRef(null),[Vt,Kt]=i.useState(0);i.useEffect(()=>{if(!N){Lt.current&&(Lt.current=null,Kt(Pt=>Pt+1));return}if(Bt){Lt.current={sessionId:N,session:Bt,expiresAt:Date.now()+2e3};return}const J=Lt.current;if(!J||J.sessionId!==N)return;const st=J.expiresAt-Date.now();if(st<=0){Lt.current=null,Kt(Pt=>Pt+1);return}const gt=window.setTimeout(()=>{Lt.current?.sessionId===N&&(Lt.current=null),Kt(Pt=>Pt+1)},st);return()=>{window.clearTimeout(gt)}},[N,Bt]);const Xt=(()=>{if(Bt)return Bt;if(!N)return null;const J=Lt.current;return J&&J.sessionId===N&&J.expiresAt>Date.now()?J.session:null})(),Qt=ut(J=>N?J.worktreeMetadata.get(N)?.path??"":""),vs=ut(J=>N?J.worktreeMetadata.get(N)?.branch?.trim()??null:null),Dt=Gf(J=>N?J.getAttachment(N):void 0),$t=i.useMemo(()=>Dt?Cp(Dt,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,Dt]),Ct=i.useMemo(()=>Dt?Dt.legacy?"legacy":Dt.degraded?"degraded":Dt.worktreeStatus==="pending"?"pending":Dt.worktreeStatus==="missing"?"missing":Dt.worktreeStatus==="invalid"?"invalid":Dt.attentionReason?"attention":null:null,[Dt]),ds=i.useMemo(()=>In(Qt||""),[Qt]),qe=i.useMemo(()=>{const J=typeof Xt?.directory=="string"?Xt.directory:"";return In(J||"")},[Xt?.directory]),at=ut(J=>J.newSessionDraft?.open?In(J.newSessionDraft.bootstrapPendingDirectory??J.newSessionDraft.directoryOverride??""):""),Qe=i.useMemo(()=>ds||qe||at,[at,qe,ds]),At=ut(J=>{const st=In(ds||qe||"");if(!st)return null;for(const gt of J.availableWorktreesByProject.values()){const Zt=gt.find(is=>In(is.path)===st)?.branch?.trim();if(Zt)return Zt}return null}),ts=Ap(Qe||null)||vs||At,xs=i.useMemo(()=>{if(!N)return B??"OpenChamber";const J=Xt?.title?.trim();return J&&J.length>0?J:"Untitled Session"},[B,Xt?.title,N]),ks=i.useMemo(()=>In(Qe||R?.path||""),[R?.path,Qe]),Jt=i.useMemo(()=>R?{id:R.id,path:R.path}:null,[R]),ls=i.useRef(null);i.useEffect(()=>{!Jt||!ks||(ls.current={projectRef:Jt,directory:ks})},[ks,Jt]);const Ps=i.useMemo(()=>Jt&&ks?{projectRef:Jt,directory:ks}:ls.current,[ks,Jt]),Ts=bc(J=>J.planModeEnabled),hn=ut(J=>J.isSessionPlanAvailable),Gs=Ts&&N?hn(N):!1,an=Gs,Rn=i.useRef("");i.useEffect(()=>{if(!Ts){Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat");return}if(!N)return;const J=`${N||"none"}:${qe||"none"}:${Xt?.time?.created||0}:${Xt?.slug||"none"}`;Rn.current!==J&&(Rn.current=J),!Gs&&Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat")},[Ts,Gs,Xt?.slug,Xt?.time?.created,N,qe]);const Os=i.useCallback(async J=>{if(!(!J||z)){xe(!0);try{const st=j.github?await j.github.authActivate(J):await(async()=>{const gt=await As("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:J})}),Pt=await gt.json().catch(()=>null);if(!gt.ok||!Pt)throw new Error(Pt?.error||gt.statusText);return Pt})();te(st)}catch(st){console.error("Failed to switch GitHub account:",st)}finally{xe(!1)}}},[z,j.github,te]),we=i.useCallback(()=>{if(typeof document>"u")return;const J=document.activeElement;if(!J)return;const st=J.tagName;(st==="INPUT"||st==="TEXTAREA"||st==="SELECT"||J.isContentEditable)&&J.blur()},[]),tt=i.useCallback(()=>{if(me){we(),a(!G);return}c()},[we,me,G,a,c]),dt=i.useCallback(()=>{Ur("desktop_open_draft_mini_chat_window",{directory:In(Qe||R?.path||""),projectId:R?.id??null,apiBaseUrl:Wr(),clientToken:zl()}).catch(J=>{console.warn("[header] failed to open draft mini chat window",J)})},[R?.id,R?.path,Qe]),It=i.useCallback(()=>{if(I){dt();return}N&&Ur("desktop_open_session_mini_chat_window",{sessionId:N,directory:In(Qe||R?.path||""),apiBaseUrl:Wr(),clientToken:zl()}).catch(J=>{console.warn("[header] failed to open session mini chat window",J)})},[R?.path,N,dt,I,Qe]),Ht=i.useCallback(()=>{const J=In(Qe||"");if(!J)return;const st=x[J];if(ei(st)==="context"){p(J);return}m(J)},[p,x,m,Qe]),ht=i.useMemo(()=>{const J=In(Qe||"");if(!J)return!1;const st=x[J];return ei(st)==="context"},[x,Qe]),hs=i.useCallback(()=>{const J=In(Qe||"");if(!J)return;const st=x[J];if(ei(st)==="plan"){p(J);return}f(J)},[p,x,f,Qe]),ps=i.useCallback(()=>{const J=In(Qe||"");if(!J)return;const st=x[J];if(ei(st)==="diff"){p(J);return}b(J,{mode:"diff",stagedDiff:!1})},[p,x,b,Qe]),js=i.useCallback(()=>{const J=In(Qe||"");if(!J)return;const st=x[J];if(ei(st)==="browser"){p(J);return}g(J)},[p,x,g,Qe]),Ss=i.useMemo(()=>{const J=In(Qe||"");if(!J)return!1;const st=x[J];return ei(st)==="plan"},[x,Qe]),Ds=i.useMemo(()=>{const J=In(Qe||"");if(!J)return!1;const st=x[J];return ei(st)==="diff"},[x,Qe]),Un=i.useMemo(()=>{const J=In(Qe||"");if(!J)return!1;const st=x[J];return ei(st)==="browser"},[x,Qe]),Es=qa,En=Wb,Hn=i.useMemo(()=>je?"services":n?"sessions":r?"git":y,[y,je,n,r]),Xn=i.useCallback(()=>{K(!1),n&&t&&t(),r&&e&&e(),!t&&G&&a(!1)},[G,n,t,e,r,a]),Ue=i.useCallback(()=>{n||K(!1),t?.()},[n,t]),os=i.useCallback(()=>{r||K(!1),e?.()},[e,r]),fs=i.useMemo(()=>Q&&De&&!ee?"5.5rem":se?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!Q||Be)&&!et?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[Q,ee,De,se,et,Be]);Xe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",fs)},[fs]);const zs=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ks=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";Xe.useEffect(()=>{if(!Q||!De){Ne(!1);return}let J=!1;const st=async()=>{try{const Pt=await Ur("desktop_is_window_fullscreen");J||Ne(Pt===!0)}catch{J||Ne(!1)}},gt=()=>{st()};return st(),window.addEventListener("openchamber:window-resized",gt),()=>{J=!0,window.removeEventListener("openchamber:window-resized",gt)}},[Q,De]);const Ws=i.useMemo(()=>!Q||!De||Fe===null?"":Fe>=26?"h-12":Fe<=15?"h-14":"",[Q,De,Fe]),pn=i.useMemo(()=>{if(!(Q&&!Be||et))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))"}},[Q,et,Be]),Ns=i.useCallback(()=>{if(typeof document>"u")return;const J=ke.current?.getBoundingClientRect().height;J&&document.documentElement.style.setProperty("--oc-header-height",`${J}px`)},[]);Xe.useEffect(()=>{if(typeof window>"u")return;Ns();const J=ke.current;if(!J||typeof ResizeObserver>"u")return()=>{};let st=0;const gt=()=>{st||(st=requestAnimationFrame(()=>{st=0,Ns()}))},Pt=new ResizeObserver(gt);return Pt.observe(J),window.addEventListener("resize",gt),window.addEventListener("orientationchange",gt),()=>{st&&cancelAnimationFrame(st),Pt.disconnect(),window.removeEventListener("resize",gt),window.removeEventListener("orientationchange",gt)}},[Ns]),Xe.useEffect(()=>{Ns()},[Ns,me,Ws]);const qr=i.useCallback(async J=>{const st=J.target;st.closest(".app-region-no-drag")||st.closest("button, a, input, select, textarea")||J.button===0&&Q&&await ip()},[Q]),Gn=i.useMemo(()=>{if(me){const J=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return an&&J.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),J.push({id:"diff",label:o("layout.mainTab.diff"),icon:"diff"},{id:"files",label:o("layout.mainTab.files"),icon:"folder-6"},{id:"terminal",label:o("layout.mainTab.terminal"),icon:"terminal-box"},{id:"context",label:o("layout.mainTab.context"),icon:"file-list-2"},{id:"diagram",label:o("layout.mainTab.diagram"),icon:"file"}),J}return[]},[me,an,o]),fr=i.useCallback(J=>La(ii(J,C)),[C]);Xe.useEffect(()=>{!me&&(y==="git"||y==="terminal"||y==="diff"||y==="files"||y==="context")&&h("chat")},[y,me,h]);const Kn=i.useMemo(()=>{const J=[];return Q&&J.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(D,{name:"server",className:"h-3.5 w-3.5"})}),J.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(D,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(Ul,{className:"h-3.5 w-3.5"})}),J},[Q,o]),gs=i.useMemo(()=>Kn.map(J=>({id:J.value,label:J.label,icon:J.icon})),[Kn]),Ms=i.useMemo(()=>{if(typeof window>"u"||Q||et)return!1;const J=window.location.hostname;return J==="localhost"||J==="127.0.0.1"||J==="::1"},[Q,et]),jr=i.useCallback(async()=>{if(k)return;v(!0),Le(!1);const J=[];let st=!1;try{try{for(const[,gt]of Vs.getState().sessions.entries())for(const Pt of gt.tabs)Pt.previewUrl&&J.push(Pt.previewUrl)}catch{}try{await op({})}catch{}try{(await As("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:J})})).ok?st=!0:st=(await As("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{st||v(!1)}},[k,Le]),jn=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),ln=i.useMemo(()=>jn.map(J=>({id:J.value,label:J.label})),[jn]),Zn=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(D,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(Ul,{className:"h-3.5 w-3.5"})}],[o]);Xe.useEffect(()=>{const J=st=>{if(yc(st)&&!st.shiftKey&&!st.altKey){const gt=parseInt(st.key,10);gt>=1&&gt<=Gn.length&&(st.preventDefault(),me&&(we(),Xn()),h(Gn[gt-1].id))}};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[we,Xn,me,h,Gn]),Xe.useEffect(()=>{const J=st=>{const gt=ii("toggle_services_menu",C);if(ia(st,gt)){st.preventDefault(),ye?Le(!1):(Le(!0),Wt(),wt==="usage"&&V.length===0&&_());return}const Pt=ii("cycle_services_tab",C);if(ia(st,Pt)){st.preventDefault();const is=Kn.map(er=>er.value);if(is.length===0)return;const ms=is.indexOf(wt),Fs=ms===-1?0:(ms+1)%is.length,qs=is[Fs];kt(qs),Le(!0),Wt(),qs==="usage"&&V.length===0&&_();return}const Zt=ii("toggle_context_plan",C);ia(st,Zt)&&(st.preventDefault(),hs())};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[C,ye,wt,Kn,V.length,_,Wt,hs]);const Mr=J=>{const st=y===J.id,gt=J.icon==="diff",Pt=gt?null:J.icon,Zt=J.id==="chat",is=Fs=>gt?s.jsx(Yd,{size:Fs}):Pt?s.jsx(D,{name:Pt,className:`h-${Fs/4} w-${Fs/4}`}):null,ms=s.jsxs("button",{type:"button",onClick:()=>h(J.id),className:Pe("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",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",Zt&&!me&&"min-w-[100px] justify-center"),"aria-label":J.label,"aria-selected":st,role:"tab",children:[me?is(20):s.jsxs(s.Fragment,{children:[is(16),s.jsx("span",{className:"header-tab-label",children:J.label})]}),J.badge!==void 0&&J.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:J.badge})]});return s.jsx(i.Fragment,{children:ms},J.id)},Yr=et?null:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.toggleChangesPanelAria"),"aria-pressed":Ds,onClick:ps,className:Es,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(D,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),ui=s.jsxs(s.Fragment,{children:[an&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:hs,className:Pe(Es,Ss&&"bg-[var(--interactive-hover)]"),children:s.jsx(D,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:fr("toggle_context_plan")})})})]}),s.jsx(hb,{directory:ks,className:"mr-1"}),s.jsx(Hb,{isDesktopApp:Q,currentInstanceLabel:M,compactCurrentInstanceLabel:nt,currentInstanceIsLocal:ie,isDesktopServicesOpen:ye,setIsDesktopServicesOpen:Le,refreshCurrentInstanceLabel:Wt,desktopServicesTab:wt,setDesktopServicesTab:kt,quotaResultsLength:V.length,fetchAllQuotas:_,servicesTabItems:gs,quotaLastUpdated:Z,quotaDisplayMode:ne,showPredValues:Y,quotaDisplayTabItems:ln,handleDisplayModeChange:Ut,handleUsageRefresh:as,isQuotaLoading:E,isUsageRefreshSpinning:Re,hasRateLimits:Gt,rateLimitGroups:rs,expandedFamilies:jt,toggleFamilyExpanded:xt,shortcutLabel:fr,showDevShutdown:Ms,isDevShutdownInFlight:k,onDevShutdown:jr,remoteUpdateInfo:Je,remoteUpdateChecking:bt,remoteUpdateError:_e,onOpenRemoteUpdate:Ze,timeFormatPreference:w}),s.jsx(Uo,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:fr("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),me?null:s.jsx(Uo,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:js,pressed:Un,Icon:"global"}),s.jsx(Uo,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:fr("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:u,Icon:"layout-right"}),s.jsx(Ub,{isMobile:me,githubAuthStatus:Se,githubAccounts:be,githubAvatarUrl:$,githubLogin:ve,isSwitchingGitHubAccount:z,handleGitHubAccountSwitch:Os})]}),mr=F&&(I||!!N),us=()=>s.jsxs("div",{onMouseDown:qr,className:Pe("app-region-drag relative flex h-12 select-none items-center pr-3",Ws),style:pn,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:zs}}),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:Ks}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(rb,{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:I?o("sessions.switcher.draftTitle"):xs}),B||ts||!I&&Ct?s.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[B?s.jsx("span",{className:"truncate",children:B}):null,ts?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:ts})]}):null,!I&&Ct?s.jsxs("span",{className:Pe("inline-flex min-w-0 items-center gap-0.5",Ct==="attention"||Ct==="invalid"||Ct==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(D,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:$t})]}):null]}):null]})}),Gn.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Gn.map(J=>Mr(J))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ot&&U?s.jsx(ib,{totalTokens:U.totalTokens,percentage:ns,colorPercentage:U.percentage,contextLimit:U.contextLimit,outputLimit:U.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:Ht,pressed:ht,className:mr?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,Yr,s.jsx(Uo,{visible:mr,title:o(I?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(I?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:It,className:Pe(Es,"mr-1"),Icon:"picture-in-picture-2"}),ui,s.jsx(ob,{visible:Be})]})]})]}),cn=()=>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:Ue,className:Pe(En,Hn==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(D,{name:"layout-left",className:"h-5 w-5"})}):G?s.jsx("button",{type:"button",onClick:()=>a(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.backAria"),children:s.jsx(D,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:tt,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(D,{name:"play-list-add",className:"h-5 w-5"})}),!t&&G&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!G||!!t)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:s.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain",children:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":o("header.navigation.mainAria"),children:Gn.map(J=>{const st=y===J.id,gt=J.icon==="diff",Pt=gt?null:J.icon;return s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{me&&(we(),Xn()),h(J.id)},"aria-label":J.label,"aria-selected":st,role:"tab",className:Pe(En,"relative rounded-lg",Hn===J.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[gt?s.jsx(Yd,{className:"h-5 w-5"}):Pt?s.jsx(D,{name:Pt,className:"h-5 w-5"}):null,J.badge!==void 0&&J.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:J.badge}),J.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":o("header.changes.availableAria")})]})}),s.jsx(Ft,{children:s.jsx("p",{children:J.label})})]},J.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[Ps&&s.jsx(km,{projectRef:Ps.projectRef,directory:Ps.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(sn,{open:je,onOpenChange:J=>{J&&(n&&t&&t(),r&&e&&e()),K(J),J&&V.length===0&&_()},children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:Pe(En,Hn==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(D,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(tn,{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:Zn,activeId:vt,onSelect:J=>{const st=J;St(st),st==="usage"&&V.length===0&&_()},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:()=>K(!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(D,{name:"close",className:"h-5 w-5"})})]})}),vt==="mcp"&&s.jsx(hm,{active:je&&vt==="mcp"}),vt==="usage"&&s.jsxs("div",{className:"flex-1 overflow-y-auto overflow-x-hidden pb-[calc(4rem+env(safe-area-inset-bottom))]",children:[s.jsx("div",{className:"border-b border-[var(--interactive-border)]",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3",children:[s.jsxs("div",{className:"flex flex-col min-w-0 gap-0.5",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:o("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Cm(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:()=>Ut("usage"),className:Pe("typography-ui-label px-1 pb-0.5 transition-colors",ne==="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:()=>Ut("remaining"),className:Pe("typography-ui-label px-1 pb-0.5 transition-colors",ne==="remaining"?"text-foreground border-b-2 border-[var(--primary-base)]":"text-muted-foreground hover:text-foreground"),children:o("header.services.remaining")})]}),s.jsx("button",{type:"button",className:Pe("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:as,disabled:E||Re,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(D,{name:"refresh",className:Pe("h-4 w-4",Re&&"animate-spin")})})]})]})}),!Gt&&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:rs.map((J,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:J.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:J.providerName})]}),J.entries.length===0&&(!J.modelFamilies||J.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:J.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[J.entries.map(([gt,Pt])=>{const Zt=ne==="remaining"?Pt.remainingPercent:Pt.usedPercent,is=va(Pt.usedPercent,Pt.resetAt,Pt.windowSeconds,gt),ms=is?.dailyAllocationPercent!=null?ne==="remaining"?100-ri(is.elapsedRatio):ri(is.elapsedRatio):null,Fs=Io(Pt.valueLabel,Zt),qs=Bf(Pt.resetAt,Pt.resetAfterFormatted??Pt.resetAtFormatted,w);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:gc(gt)}),qs?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:qs}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Fs==="-"?"":Fs})]}),s.jsx(Ca,{percent:Zt,tonePercent:Pt.usedPercent,className:"h-1.5",expectedMarkerPercent:ms}),is&&Y?s.jsx(Aa,{paceInfo:is,compact:!0}):null]},`${J.providerId}-${gt}`)}),J.modelFamilies&&J.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:J.modelFamilies.map(gt=>{const Zt=(jt[J.providerId]??[]).includes(gt.familyId??"other");return s.jsxs(eo,{open:Zt,onOpenChange:()=>xt(J.providerId,gt.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:gt.familyLabel}),Zt?s.jsx(D,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(to,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:gt.models.map(([is,ms])=>{const Fs=ne==="remaining"?ms.remainingPercent:ms.usedPercent,qs=va(ms.usedPercent,ms.resetAt,ms.windowSeconds),er=qs?.dailyAllocationPercent!=null?ne==="remaining"?100-ri(qs.elapsedRatio):ri(qs.elapsedRatio):null,qn=Io(ms.valueLabel,Fs);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:mm(is)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:qn==="-"?"":qn})]}),s.jsx(Ca,{percent:Fs,tonePercent:ms.usedPercent,className:"h-1.5",expectedMarkerPercent:er}),qs&&Y?s.jsx(Aa,{paceInfo:qs,compact:!0}):null]},`${J.providerId}-${is}`)})})})]},gt.familyId??"other")})})]})]},J.providerId))})]})]})})]}),e?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:os,className:Pe(En,"relative",Hn==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ft,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),kn=Pe("header-safe-area relative z-10 bg-background",me&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:ke,className:kn,style:{"--padding-scale":"1"},children:me?cn():us()}),s.jsx(gm,{open:Ge,onOpenChange:He,info:Je,downloading:!1,downloaded:!1,progress:null,error:_e,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function qb(){}const eu=180,tu=640,Yb=110,Qb=t=>{const e=mt.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=Nt(),c=Ee(Jb),l=Ee(Xb),d=Ee(Zb),u=Ee(ey),[m,f]=i.useState(null),[g,b]=i.useState(!1),p=i.useRef(null),x=i.useRef(0),y=i.useRef(c||300),h=Math.min(tu,Math.max(eu,c||300));let C,w;e[0]!==n?(C=()=>{n||(f(null),b(!1))},w=[n],e[0]=n,e[1]=C,e[2]=w):(C=e[1],w=e[2]),i.useEffect(C,w);let S,j;e[3]!==l||e[4]!==r||e[5]!==n?(S=()=>{if(r||!n||!l)return;const re=()=>{const Se=p.current?.parentElement?.getBoundingClientRect().height;if(!Se||Se<=0)return;const te=Math.max(0,Math.round(Se));f(ke=>ke===te?ke:te)};re();const ae=p.current?.parentElement;if(!ae)return;const me=new ResizeObserver(re);return me.observe(ae),()=>{me.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 re=me=>{const Se=x.current-me.clientY,te=Math.min(tu,Math.max(eu,y.current+Se));d(te)},ae=()=>{b(!1),Ee.getState().bottomTerminalHeight<=Yb&&u(!1)};return window.addEventListener("pointermove",re),window.addEventListener("pointerup",ae,{once:!0}),()=>{window.removeEventListener("pointermove",re),window.removeEventListener("pointerup",ae)}},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 A=n?l?Math.max(0,m??h):h:0,I=n&&l;let N;e[15]!==A||e[16]!==l||e[17]!==n?(N=re=>{!n||l||(b(!0),x.current=re.clientY,y.current=A,re.preventDefault())},e[15]=A,e[16]=l,e[17]=n,e[18]=N):N=e[18];const O=N,P=I?"absolute inset-x-0 bottom-0 z-40":"relative",T=g?"transition-none":"transition-[height] duration-300 ease-in-out",L=(!n||I)&&"border-t-0";let R;e[19]!==L||e[20]!==P||e[21]!==T?(R=Pe("flex overflow-hidden border-t border-border bg-sidebar",P,T,L),e[19]=L,e[20]=P,e[21]=T,e[22]=R):R=e[22];let B;e[23]!==A||e[24]!==I?(B=I?{top:0}:{height:`${A}px`,minHeight:`${A}px`,maxHeight:`${A}px`},e[23]=A,e[24]=I,e[25]=B):B=e[25];const V=!n||!l&&A===0;let _;e[26]!==O||e[27]!==l||e[28]!==n||e[29]!==g||e[30]!==a?(_=n&&!l&&s.jsx("div",{className:Pe("absolute left-0 top-0 z-20 h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",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]=_):_=e[31];const E=!n&&"pointer-events-none select-none opacity-0";let Z;e[32]!==E?(Z=Pe("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",E),e[32]=E,e[33]=Z):Z=e[33];const ne=!n;let Y;e[34]!==o||e[35]!==Z||e[36]!==ne?(Y=s.jsx("div",{className:Z,"aria-hidden":ne,children:o}),e[34]=o,e[35]=Z,e[36]=ne,e[37]=Y):Y=e[37];let H;return e[38]!==R||e[39]!==B||e[40]!==V||e[41]!==_||e[42]!==Y?(H=s.jsxs("section",{ref:p,className:R,style:B,"aria-hidden":V,children:[_,Y]}),e[38]=R,e[39]=B,e[40]=V,e[41]=_,e[42]=Y,e[43]=H):H=e[43],H};function Jb(t){return t.bottomTerminalHeight}function Xb(t){return t.isBottomTerminalExpanded}function Zb(t){return t.setBottomTerminalHeight}function ey(t){return t.setBottomTerminalOpen}const su=280,nu=280,ru=500,ty=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=Nt(),c=Ee(v=>v.sidebarWidth),l=Ee(v=>v.setSidebarWidth),[d,u]=i.useState(!1),m=i.useRef(0),f=i.useRef(c||su),g=i.useRef(null),b=i.useRef(null),p=i.useRef(null),x=i.useCallback(v=>Math.min(ru,Math.max(nu,v)),[]),y=i.useCallback(v=>{const A=p.current;A&&(A.style.width=`${v}px`,A.style.minWidth=`${v}px`,A.style.maxWidth=`${v}px`,A.style.setProperty("--oc-left-sidebar-width",`${v}px`))},[]);if(i.useEffect(()=>{e&&d&&u(!1)},[e,d]),i.useEffect(()=>{d||(g.current=null,b.current=null)},[d]),e)return null;const h=Math.min(ru,Math.max(nu,c||su)),C=t?h:0,w=v=>{if(t){try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}b.current=v.pointerId,u(!0),m.current=v.clientX,f.current=C,g.current=C,y(C),v.preventDefault()}},S=v=>{if(e||!d||b.current!==v.pointerId)return;const A=v.clientX-m.current,I=x(f.current+A);g.current!==I&&(g.current=I,y(I))},j=v=>{if(b.current!==v.pointerId||e)return;try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}const A=x(g.current??C);b.current=null,g.current=null,u(!1),l(A)},k=d?g.current??C:C;return s.jsxs("aside",{ref:p,className:Pe("relative flex h-full overflow-hidden border-r border-border/40 will-change-[width] motion-reduce:transition-none","bg-sidebar oc-vibrancy-surface",!t&&"border-r-0",r),style:{width:`${k}px`,minWidth:`${k}px`,maxWidth:`${k}px`,"--oc-left-sidebar-width":`${d?k:h}px`,overflowX:"clip",transitionProperty:d?"none":"width, min-width, max-width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||C===0,children:[t&&s.jsx("div",{className:Pe("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",d&&"bg-[var(--interactive-border)]"),onPointerDown:w,onPointerMove:S,onPointerUp:j,onPointerCancel:j,role:"separator","aria-orientation":"vertical","aria-label":a("sidebar.resize.leftPanelAria")}),s.jsxs("div",{className:Pe("relative z-10 flex h-full shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",d&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[o,s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:s.jsx(Zs,{children:n})})]})]})},sy=()=>{const t=mt.c(3);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e={height:"var(--oc-header-height, 3rem)"},t[0]=e):e=t[0];let n;t[1]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("div",{className:"app-region-drag shrink-0",style:{width:"var(--oc-titlebar-left-inset, 0.75rem)"}}),t[1]=n):n=t[1];let r;return t[2]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsxs("div",{"aria-hidden":!0,className:"flex shrink-0",style:e,children:[n,s.jsx("div",{className:"app-region-no-drag shrink-0",style:{width:"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)"}}),s.jsx("div",{className:"app-region-drag flex-1"})]}),t[2]=r):r=t[2],r},Ho=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function ny(){const t=ws(f=>f.activeProjectId?f.projects.find(g=>g.id===f.activeProjectId)??null:null),e=ut(f=>f.currentSessionId),n=_f(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 iu="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",ry=()=>{const t=mt.c(31),{t:e}=Nt(),n=Ee(iy),r=Ee(oy),o=Ee(ay),a=ny(),c=i.useRef(null),l=La(ii("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const u=d,m=cy;let f,g;t[0]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{if(typeof document>"u")return;const L=c.current;if(!L)return;const R=()=>{const V=L.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(V)}px`)};if(R(),typeof ResizeObserver>"u")return;const B=new ResizeObserver(R);return B.observe(L),()=>{B.disconnect()}},g=[],t[0]=f,t[1]=g):(f=t[0],g=t[1]),i.useEffect(f,g);const b="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 y;t[3]!==e?(y=u?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,"aria-label":e("header.actions.openAppMenuAria"),className:Pe(iu,"shrink-0"),children:s.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ft,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=y):y=t[4];const h=Et;let C;t[5]!==e?(C=e("header.actions.openSessionsAria"),t[5]=e,t[6]=C):C=t[6];let w,S;t[7]===Symbol.for("react.memo_cache_sentinel")?(w=Pe(iu,"shrink-0"),S=s.jsx(D,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=w,t[8]=S):(w=t[7],S=t[8]);let j;t[9]!==C||t[10]!==n?(j=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":C,className:w,children:S})}),t[9]=C,t[10]=n,t[11]=j):j=t[11];const k=Ft,v=e("header.actions.openSessionsWithShortcut",{shortcut:l});let A;t[12]!==v?(A=s.jsx("p",{children:v}),t[12]=v,t[13]=A):A=t[13];let I;t[14]!==k||t[15]!==A?(I=s.jsx(k,{children:A}),t[14]=k,t[15]=A,t[16]=I):I=t[16];let N;t[17]!==h||t[18]!==j||t[19]!==I?(N=s.jsxs(h,{children:[j,I]}),t[17]=h,t[18]=j,t[19]=I,t[20]=N):N=t[20];let O;t[21]!==r||t[22]!==a?(O=a?s.jsx(km,{projectRef:a.projectRef,directory:a.directory,className:r?"oc-vibrancy-pill":void 0}):null,t[21]=r,t[22]=a,t[23]=O):O=t[23];let P;t[24]!==N||t[25]!==O||t[26]!==y?(P=s.jsxs("div",{ref:c,className:x,children:[y,N,O]}),t[24]=N,t[25]=O,t[26]=y,t[27]=P):P=t[27];let T;return t[28]!==P||t[29]!==p?(T=s.jsx("div",{className:b,style:p,children:P}),t[28]=P,t[29]=p,t[30]=T):T=t[30],T};function iy(t){return t.toggleSidebar}function oy(t){return t.isSidebarOpen}function ay(t){return t.shortcutOverrides}function ly(t){console.warn("[titlebar] failed to open app menu",t)}function cy(t){const e=t.currentTarget.getBoundingClientRect();Ur("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(ly)}const ou=420,dy=({isOpen:t,children:e,className:n})=>{const{t:r}=Nt(),o=Ee(j=>j.rightSidebarWidth),a=Ee(j=>j.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),u=i.useRef(o||ou),m=i.useRef(null),f=i.useRef(null),g=i.useRef(null),b=i.useCallback(j=>Math.min(xd,Math.max(bd,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(xd,Math.max(bd,o||ou)),y=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=y,m.current=y,p(y),j.preventDefault()}},C=j=>{if(!c||f.current!==j.pointerId)return;const k=d.current-j.clientX,v=b(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=b(m.current??y);f.current=null,m.current=null,l(!1),a(k)},S=c?m.current??y:y;return s.jsxs("aside",{ref:g,className:Pe("relative flex h-full overflow-hidden border-l border-border/40 will-change-[width] motion-reduce:transition-none","bg-sidebar",!t&&"border-l-0",n),style:{width:`${S}px`,"--oc-right-sidebar-width":`${c?S:x}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||y===0,children:[t&&s.jsx("div",{className:Pe("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",c&&"bg-[var(--interactive-border)]"),onPointerDown:h,onPointerMove:C,onPointerUp:w,onPointerCancel:w,role:"separator","aria-orientation":"vertical","aria-label":r("sidebar.resize.rightPanelAria")}),s.jsx("div",{className:Pe("relative z-10 flex h-full min-h-0 shrink-0 flex-col pt-2 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",c&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-right-sidebar-width)"},"aria-hidden":!t,children:t?e:null})]})},au=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function Am(t){const e=mt.c(120),{t:n}=Nt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,onConfirm:d}=t,u=l===void 0?!1:l,m=ss(wy),f=ss(yy),g=Dp(by),b=ss(xy),p=ss(gy),x=ss(py),y=ss(hy),h=ss(my);let C;e[0]!==h||e[1]!==x||e[2]!==p||e[3]!==y?(C=()=>au({providerID:p,modelID:x,variant:y,agent:h}),e[0]=h,e[1]=x,e[2]=p,e[3]=y,e[4]=C):C=e[4];const[w,S]=i.useState(C);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,A;e[12]!==h||e[13]!==x||e[14]!==p||e[15]!==y||e[16]!==r?(v=()=>{r&&S(au({providerID:p,modelID:x,variant:y,agent:h}))},A=[r,p,x,y,h],e[12]=h,e[13]=x,e[14]=p,e[15]=y,e[16]=r,e[17]=v,e[18]=A):(v=e[17],A=e[18]),i.useEffect(v,A);let I,N;e[19]!==w.modelID||e[20]!==w.providerID||e[21]!==r||e[22]!==b?(I=()=>{if(!r||b.length===0)return;const ye=b.find(M=>M.id===w.providerID)??b[0],Le=Array.isArray(ye?.models)?ye.models:[],Re=Le.some(M=>M.id===w.modelID),X=Le[0]?.id??"";ye?.id===w.providerID&&Re||S(M=>({...M,providerID:ye?.id??"",modelID:Re?M.modelID:X,variant:""}))},N=[r,b,w.providerID,w.modelID],e[19]=w.modelID,e[20]=w.providerID,e[21]=r,e[22]=b,e[23]=I,e[24]=N):(I=e[23],N=e[24]),i.useEffect(I,N);const O=fy;let P;if(e[25]!==w.modelID||e[26]!==w.providerID||e[27]!==b){let ye;e[29]!==w.providerID?(ye=Re=>Re.id===w.providerID,e[29]=w.providerID,e[30]=ye):ye=e[30],P=b.find(ye)?.models?.find(Re=>Re.id===w.modelID),e[25]=w.modelID,e[26]=w.providerID,e[27]=b,e[28]=P}else P=e[28];const T=P;let L;e[31]!==T?(L=T?.variants?Object.keys(T.variants):[],e[31]=T,e[32]=L):L=e[32];const R=L,B=R.length>0;let V,_;e[33]!==w.variant||e[34]!==B?(V=()=>{B||!w.variant||S(uy)},_=[B,w.variant],e[33]=w.variant,e[34]=B,e[35]=V,e[36]=_):(V=e[35],_=e[36]),i.useEffect(V,_);let E;e[37]!==w.modelID||e[38]!==w.providerID?(E=w.providerID.trim().length>0&&w.modelID.trim().length>0,e[37]=w.modelID,e[38]=w.providerID,e[39]=E):E=e[39];const Z=E;let ne;e[40]!==Z||e[41]!==w||e[42]!==d||e[43]!==u?(ne=()=>{!Z||u||d(w)},e[40]=Z,e[41]=w,e[42]=d,e[43]=u,e[44]=ne):ne=e[44];const Y=ne;let H,re;e[45]!==Y||e[46]!==r?(H=()=>{if(!r)return;const ye=Le=>{(Le.metaKey||Le.ctrlKey)&&Le.key==="Enter"&&(Le.preventDefault(),Y())};return window.addEventListener("keydown",ye),()=>window.removeEventListener("keydown",ye)},re=[r,Y],e[45]=Y,e[46]=r,e[47]=H,e[48]=re):(H=e[47],re=e[48]),i.useEffect(H,re);let ae;e[49]!==n||e[50]!==a?(ae=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[49]=n,e[50]=a,e[51]=ae):ae=e[51];const me=ae;let Se;e[52]!==o||e[53]!==u?(Se=ye=>{u||o(ye)},e[52]=o,e[53]=u,e[54]=Se):Se=e[54];let te;e[55]!==me?(te=s.jsx(Hs,{children:s.jsx(Us,{children:me})}),e[55]=me,e[56]=te):te=e[56];let ke;e[57]!==n?(ke=n("chat.modelControls.model"),e[57]=n,e[58]=ke):ke=e[58];let Q;e[59]!==ke?(Q=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ke}),e[59]=ke,e[60]=Q):Q=e[60];let ge;e[61]===Symbol.for("react.memo_cache_sentinel")?(ge=(ye,Le)=>{S(Re=>({...Re,providerID:ye,modelID:Le,variant:""}))},e[61]=ge):ge=e[61];let F;e[62]!==w.modelID||e[63]!==w.providerID?(F=s.jsx(Kf,{providerId:w.providerID,modelId:w.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:ge}),e[62]=w.modelID,e[63]=w.providerID,e[64]=F):F=e[64];let se;e[65]!==Q||e[66]!==F?(se=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[Q,F]}),e[65]=Q,e[66]=F,e[67]=se):se=e[67];let ee;e[68]!==n?(ee=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[68]=n,e[69]=ee):ee=e[69];let Ne;e[70]!==ee?(Ne=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ee}),e[70]=ee,e[71]=Ne):Ne=e[71];const De=!B;let Be;e[72]===Symbol.for("react.memo_cache_sentinel")?(Be=ye=>S(Le=>({...Le,variant:ye})),e[72]=Be):Be=e[72];let Fe;e[73]!==w.variant||e[74]!==De||e[75]!==R?(Fe=s.jsx(Ip,{value:w.variant,options:R,disabled:De,onChange:Be}),e[73]=w.variant,e[74]=De,e[75]=R,e[76]=Fe):Fe=e[76];let Me;e[77]!==Ne||e[78]!==Fe?(Me=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Ne,Fe]}),e[77]=Ne,e[78]=Fe,e[79]=Me):Me=e[79];let he;e[80]!==n?(he=n("sessions.scheduledTasks.editor.agent.label"),e[80]=n,e[81]=he):he=e[81];let Ae;e[82]!==he?(Ae=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:he}),e[82]=he,e[83]=Ae):Ae=e[83];let pe;e[84]===Symbol.for("react.memo_cache_sentinel")?(pe=ye=>S(Le=>({...Le,agent:ye})),e[84]=pe):pe=e[84];let ue;e[85]!==w.agent?(ue=s.jsx(qf,{agentName:w.agent,filter:O,dropdownPortalToBody:!0,onChange:pe}),e[85]=w.agent,e[86]=ue):ue=e[86];let U;e[87]!==Ae||e[88]!==ue?(U=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Ae,ue]}),e[87]=Ae,e[88]=ue,e[89]=U):U=e[89];let fe;e[90]!==se||e[91]!==Me||e[92]!==U?(fe=s.jsxs("div",{className:"flex flex-col gap-4",children:[se,Me,U]}),e[90]=se,e[91]=Me,e[92]=U,e[93]=fe):fe=e[93];let de;e[94]!==o?(de=()=>o(!1),e[94]=o,e[95]=de):de=e[95];let G;e[96]!==n?(G=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[96]=n,e[97]=G):G=e[97];let $;e[98]!==u||e[99]!==de||e[100]!==G?($=s.jsx($e,{variant:"ghost",size:"sm",onClick:de,disabled:u,children:G}),e[98]=u,e[99]=de,e[100]=G,e[101]=$):$=e[101];const ve=!Z||u;let be;e[102]!==u||e[103]!==n?(be=n(u?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[102]=u,e[103]=n,e[104]=be):be=e[104];let z;e[105]!==Y||e[106]!==ve||e[107]!==be?(z=s.jsx($e,{size:"sm",onClick:Y,disabled:ve,children:be}),e[105]=Y,e[106]=ve,e[107]=be,e[108]=z):z=e[108];let xe;e[109]!==$||e[110]!==z?(xe=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[$,z]}),e[109]=$,e[110]=z,e[111]=xe):xe=e[111];let je;e[112]!==te||e[113]!==fe||e[114]!==xe?(je=s.jsxs(_s,{className:"max-w-md overflow-visible",children:[te,fe,xe]}),e[112]=te,e[113]=fe,e[114]=xe,e[115]=je):je=e[115];let K;return e[116]!==r||e[117]!==Se||e[118]!==je?(K=s.jsx($s,{open:r,onOpenChange:Se,children:je}),e[116]=r,e[117]=Se,e[118]=je,e[119]=K):K=e[119],K}function uy(t){return{...t,variant:""}}function fy(t){return wc(t.mode)}function my(t){return t.currentAgentName||""}function hy(t){return t.currentVariant||""}function py(t){return t.currentModelId}function gy(t){return t.currentProviderId}function xy(t){return t.providers}function by(t){return t.loadAgents}function yy(t){return t.loadAgents}function wy(t){return t.loadProviders}const Jl=5,Dm=15,Go=new Map,la=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},vy=(t,e)=>{const n=la(e);return Math.max(n*Jl,Math.min(n*Dm,n*t))},jy=async(t,e)=>{const n=await Ep(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},Sy=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,lu=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],cu=(t,e)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},Ny=t=>{const e=mt.c(20),{id:n,children:r}=t;let o;e[0]!==n?(o={id:n},e[0]=n,e[1]=o):o=e[1];const{attributes:a,listeners:c,setNodeRef:l,setActivatorNodeRef:d,transform:u,transition:m,isDragging:f}=dc(o);let g;e[2]!==u?(g=uc.Transform.toString(u),e[2]=u,e[3]=g):g=e[3];let b;e[4]!==g||e[5]!==m?(b={transform:g,transition:m},e[4]=g,e[5]=m,e[6]=b):b=e[6];const p=f&&"opacity-60";let x;e[7]!==p?(x=Pe(p),e[7]=p,e[8]=x):x=e[8];let y;e[9]!==a||e[10]!==r||e[11]!==f||e[12]!==c||e[13]!==d?(y=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]=y):y=e[14];let h;return e[15]!==l||e[16]!==b||e[17]!==x||e[18]!==y?(h=s.jsx("li",{ref:l,style:b,className:x,children:y}),e[15]=l,e[16]=b,e[17]=x,e[18]=y,e[19]=h):h=e[19],h},ky=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=Nt(),[c,l]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState([]),[g,b]=i.useState(""),[p,x]=i.useState(null),[y,h]=i.useState(()=>new Set),[C,w]=i.useState([]),[S,j]=i.useState(null),[k,v]=i.useState(!1),[A,I]=i.useState(0),N=i.useRef(!1),O=i.useRef(""),P=i.useRef(null),T=Ee(M=>M.todoPanelHeight),L=Ee(M=>M.setTodoPanelHeight),R=Ee(M=>M.notesPanelHeight),B=Ee(M=>M.setNotesPanelHeight),[V,_]=i.useState(!1),E=i.useRef(0),Z=i.useRef(T),ne=ut(M=>M.currentSessionId),Y=ut(M=>M.createSession),H=ut(M=>M.initializeNewOpenChamberSession),re=ut(M=>M.sendMessage),ae=ut(M=>M.setCurrentSession),me=ci(M=>M.setPendingInputText),Se=Js(M=>M.currentDirectory),te=Ee(M=>M.openContextPanelTab),ke=Ee(M=>M.setActiveMainTab),Q=Ee(M=>M.setSessionSwitcherOpen),ge=Ee(M=>M.padding),F=i.useCallback(async(M,le)=>{if(!t)return!1;const ie=t.id,Ge=(Go.get(ie)??Promise.resolve()).catch(()=>{}).then(()=>Pp(t,{notes:M,todos:le}));Go.set(ie,Ge);try{const He=await Ge;return He||ce.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),He}finally{Go.get(ie)===Ge&&Go.delete(ie)}},[t,a]);i.useEffect(()=>{if(!t){u(""),f([]),w([]),b(""),h(new Set);return}let M=!1;return l(!0),(async()=>{try{const le=await Tp(t),ie=await Promise.all(le.plans.map(Oe=>jy(Oe,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(M)return;u(le.notes),f(lu(le.todos)),w(ie),O.current=le.notes,N.current=!0,b(""),h(new Set)}catch{M||(ce.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),u(""),f([]),w([]),O.current="",N.current=!0)}finally{M||l(!1)}})(),()=>{M=!0}},[A,t,a]),i.useEffect(()=>{if(!t)return;const M=le=>{const ie=le.detail;ie?.projectId&&ie.projectId!==t.id||I(Oe=>Oe+1)};return window.addEventListener("openchamber:project-plan-saved",M),window.addEventListener("openchamber:project-notes-updated",M),()=>{window.removeEventListener("openchamber:project-plan-saved",M),window.removeEventListener("openchamber:project-notes-updated",M)}},[t]),i.useEffect(()=>{if(m.length<7)return;const M=vy(m.length,ge),le=la(ge)*Jl;T!==M&&(T<le||T>M)&&L(M)},[m.length,ge,T,L]),i.useEffect(()=>{if(!V)return;const M=ie=>{const Oe=ie.clientY-E.current,Ge=Math.min(la(ge)*Dm,Math.max(la(ge)*Jl,Z.current+Oe));L(Ge)},le=()=>{_(!1)};return window.addEventListener("pointermove",M),window.addEventListener("pointerup",le,{once:!0}),window.addEventListener("pointercancel",le,{once:!0}),()=>{window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",le),window.removeEventListener("pointercancel",le)}},[V,ge,L]);const se=i.useCallback(M=>{_(!0),E.current=M.clientY,Z.current=T,M.preventDefault()},[T]),ee=i.useCallback(()=>{P.current!==null&&(window.clearTimeout(P.current),P.current=null)},[]),Ne=i.useCallback(()=>{ee(),O.current=d,F(d,m)},[ee,d,F,m]);i.useEffect(()=>{if(!(!t||!N.current)&&d!==O.current)return P.current=window.setTimeout(()=>{P.current=null,O.current=d,F(d,m)},400),()=>{ee()}},[ee,d,F,t,m]),i.useEffect(()=>()=>ee(),[ee]);const De=i.useCallback(()=>{const M=g.trim();if(!M)return;const le=cu(m,{id:Sy(),text:M.slice(0,zo),completed:!1,createdAt:Date.now()});f(le),b(""),F(d,le)},[g,d,F,m]),Be=i.useCallback(M=>{h(le=>{const ie=new Set(le);return ie.has(M)?ie.delete(M):ie.add(M),ie})},[]),Fe=i.useCallback((M,le)=>{const ie=m.find(Je=>Je.id===M);if(!ie||ie.completed===le)return;const Oe=m.filter(Je=>Je.id!==M),Ge={...ie,completed:le},He=le?[...Oe,Ge]:cu(Oe,Ge);f(He),F(d,He)},[d,F,m]),Me=i.useCallback(M=>{const le=m.filter(ie=>ie.id!==M);f(le),F(d,le)},[d,F,m]),he=i.useCallback(()=>{const M=m.filter(le=>!le.completed);M.length!==m.length&&(f(M),F(d,M))},[d,F,m]),Ae=i.useCallback(M=>{const{active:le,over:ie}=M;if(!ie||le.id===ie.id)return;const Oe=m.findIndex(Je=>Je.id===le.id),Ge=m.findIndex(Je=>Je.id===ie.id);if(Oe===-1||Ge===-1)return;const He=lu(Rf(m,Oe,Ge));f(He),F(d,He)},[d,F,m]),pe=ga(yo(xa,{activationConstraint:{distance:8}})),ue=g.slice(0,zo),U=m.reduce((M,le)=>M+(le.completed?1:0),0),fe=i.useCallback(()=>{ke("chat"),Q(!1)},[ke,Q]),de=i.useCallback((M,le)=>{!t||p||j({kind:"session",todoId:M,todoText:le})},[t,p]),G=i.useCallback(M=>{if(!ne){ce.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}fe();const le=`\`\`\`md
4
- ${M}
5
- \`\`\``;me(le,"append"),ce.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[ne,r,fe,me,a]),$=i.useCallback((M,le)=>{if(!(!t||p)){if(!n){ce.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}j({kind:"worktree",todoId:M,todoText:le})}},[n,t,p,a]),ve=i.useCallback(async M=>{if(!t||!S)return;const le=await Tn("plan.todo.visible",{todo_text:S.todoText}),Oe=[{synthetic:!0,text:await Tn("plan.todo.instructions",{todo_text:S.todoText})}];v(!0),x(S.todoId);try{fe();let Ge=null,He=t.path;if(S.kind==="worktree"){if(!n){ce.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const rt=await Yf(t.path,Qf());if(!rt?.id)return;Ge=rt.id,He=rt.path}else{const rt=await Y(void 0,t.path,null);if(!rt?.id){ce.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}Ge=rt.id,He=rt.directory??t.path,H(rt.id,ss.getState().agents??[])}if(!Ge)return;const Je=vc.getState();Je.saveSessionModelSelection(Ge,M.providerID,M.modelID),M.agent.trim()&&(Je.saveSessionAgentSelection(Ge,M.agent),Je.saveAgentModelForSession(Ge,M.agent,M.providerID,M.modelID),Je.saveAgentModelVariantForSession(Ge,M.agent,M.providerID,M.modelID,M.variant||void 0)),ae(Ge,He),await re(le,M.providerID,M.modelID,M.agent.trim()||void 0,void 0,void 0,Oe,M.variant||void 0),ce.success(S.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),j(null),r?.()}catch(Ge){const He=Ge instanceof Error?Ge.message:void 0;ce.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),He?{description:He}:void 0)}finally{v(!1),x(null)}},[n,Y,H,r,S,t,fe,re,ae,a]),be=i.useRef(null),[z,xe]=i.useState(!1),[je,K]=i.useState(null),ye=i.useCallback(async M=>{if(!(!t||je)){K(M);try{if(!await Rp(t,M)){ce.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}w(ie=>ie.filter(Oe=>Oe.id!==M)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{K(null)}}},[je,t,a]),Le=i.useCallback(async()=>{if(!t||z)return;const M=await ap({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(M.success&&M.path){xe(!0);try{const le=new URLSearchParams({path:M.path,allowOutsideWorkspace:"true"});M.outsideFileGrant&&le.set("outsideFileGrant",M.outsideFileGrant);const ie=await As(`/api/fs/read?${le.toString()}`,{cache:"no-store"});if(!ie.ok){ce.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const Oe=await ie.text();if(!Oe.trim()){ce.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Ge=M.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Cd(t,Oe,Ge)){ce.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),ce.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(le){const ie=le instanceof Error?le.message:void 0;ce.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),ie?{description:ie}:void 0)}finally{xe(!1)}}else M.error==="Native file picker not available"&&be.current?.click()},[z,t,a]),Re=i.useCallback(async M=>{if(!(!t||!M)){xe(!0);try{const le=await M.text();if(!le.trim()){ce.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const ie=M.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Cd(t,le,ie)){ce.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),ce.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(le){const ie=le instanceof Error?le.message:void 0;ce.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),ie?{description:ie}:void 0)}finally{xe(!1)}}},[t,a]),X=i.useCallback(M=>{const le=t?.path?.trim(),ie=Se?.trim()||le;ie&&te(ie,{mode:"plan",targetPath:M.path,dedupeKey:M.path,label:M.title})},[Se,te,t]);return t?s.jsxs("div",{className:Pe("w-full min-w-0 space-y-3 p-3",o),children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:t.path,children:a("rightSidebar.contextNotesTodo.notes.title",{project:e?.trim()||t.path.split("/").filter(Boolean).pop()||t.path})}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[d.length,"/",Ad]})]}),s.jsx(ki,{value:d,onChange:M=>u(M.target.value.slice(0,Ad)),onBlur:Ne,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:R,onResizeHeightChange:B,useScrollShadow:!0,scrollShadowSize:56,disabled:c})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:a("rightSidebar.contextNotesTodo.todo.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children: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:he,disabled:c||U===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:M=>b(M.target.value.slice(0,zo)),onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),De())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:De,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(D,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:Pe("overflow-y-auto rounded-lg border border-border/60 bg-background/40",V&&"transition-none"),style:m.length<7?void 0:{height:`${T}px`,maxHeight:`${T}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(Bl,{items:m.map(M=>M.id),strategy:Vl,children:s.jsx("ul",{className:"divide-y divide-border/50",children:m.map(M=>{const le=y.has(M.id);return s.jsx(Ny,{id:M.id,children:ie=>s.jsxs("div",{className:Pe("flex gap-1.5 px-2.5 py-1.5",le?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:ie.setActivatorNodeRef,...ie.attributes,...ie.listeners,onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:M.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:M.text}),children:s.jsx(D,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(Ti,{checked:M.completed,onChange:Oe=>Fe(M.id,Oe),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:M.text})})}),s.jsx("button",{type:"button",onClick:()=>Be(M.id),className:Pe("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",le?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",M.completed&&"text-muted-foreground line-through"),title:le?void 0:M.text,"aria-label":le?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:M.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:M.text}),children:M.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Me(M.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:M.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:M.text}),children:s.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(sn,{children:[s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",disabled:p===M.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:M.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:M.text}),children:s.jsx(D,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(tn,{align:"end",className:"w-56",children:[s.jsx(bs,{onClick:()=>G(M.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(bs,{onClick:()=>de(M.id,M.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(bs,{onClick:()=>{$(M.id,M.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},M.id)})})})})}),m.length>=7&&s.jsx("div",{className:Pe("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",V&&"bg-[var(--interactive-border)]"),onPointerDown:se,role:"separator","aria-orientation":"horizontal","aria-label":a("rightSidebar.contextNotesTodo.todo.resizeAria")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:a("rightSidebar.contextNotesTodo.plans.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:C.length===1?a("rightSidebar.contextNotesTodo.plans.filesSingle",{count:C.length}):a("rightSidebar.contextNotesTodo.plans.filesPlural",{count:C.length})})]}),s.jsx("input",{ref:be,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:M=>{const le=M.target.files?.[0]??null;Re(le),M.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Le,disabled:!t||z,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.plans.importFromFile"),title:a("rightSidebar.contextNotesTodo.plans.importFromFile"),children:s.jsx(D,{name:"add",className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:C.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.plans.empty")}):s.jsx("ul",{className:"divide-y divide-border/50",children:C.map(M=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>X(M),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:M.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(M.createdAt).toLocaleDateString(Xi())})]}),s.jsx("button",{type:"button",onClick:()=>{ye(M.id)},disabled:je===M.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:M.title}),children:s.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},M.id))})})]}),s.jsx(Am,{open:S!==null,onOpenChange:M=>{!M&&!k&&j(null)},target:S?.kind??"session",projectDirectory:t?.path??null,submitting:k,onConfirm:ve})]}):s.jsx("div",{className:Pe("w-full min-w-0 p-3",o),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.empty.selectProject")})})},Im=12,Cy=[{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"}],Ay=t=>{const e=mt.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,u=a===void 0?900:a,m=c===void 0?Cy:c,f=Xe.useRef(!1);let g,b;e[0]!==n||e[1]!==l?(g=()=>{!n&&f.current&&l?.(),n&&(f.current=!0)},b=[n,l],e[0]=n,e[1]=l,e[2]=g,e[3]=b):(g=e[2],b=e[3]),Xe.useEffect(g,b);let p;e[4]===Symbol.for("react.memo_cache_sentinel")?(p=Array.from({length:Im},Dy),e[4]=p):p=e[4];const x=p;if(!n)return null;let y;e[5]!==o?(y=Pe("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=y):y=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 A=k.x*S.radius,I=k.y*S.radius,N={"--translate-x":`${A}px`,"--translate-y":`${I}px`,"--particle-delay":`${k.delay}ms`,color:`var(${S.colorVar})`};return s.jsx("span",{className:"firework-particle",style:N},`${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 C;return e[14]!==d||e[15]!==y||e[16]!==h?(C=s.jsx("div",{className:y,"aria-hidden":"true","data-burst-key":d,children:h}),e[14]=d,e[15]=y,e[16]=h,e[17]=C):C=e[17],C};function Dy(t,e){const n=Math.PI*2*e/Im;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const Iy=t=>{const e=mt.c(13);let n;e[0]!==t?(n={},e[0]=t,e[1]=n):n=e[1];const{durationMs:r}=n,o=r===void 0?3400:r;let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a={isActive:!1,cycle:0},e[2]=a):a=e[2];const[c,l]=Xe.useState(a),d=Xe.useRef(null);let 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(Py)},e[4]=f):f=e[4];const g=f;let b;e[5]!==o?(b=()=>{m(),l(Ty),d.current=window.setTimeout(()=>{l(Ry),d.current=null},o)},e[5]=o,e[6]=b):b=e[6];const p=b;let x,y;e[7]===Symbol.for("react.memo_cache_sentinel")?(x=()=>()=>m(),y=[m],e[7]=x,e[8]=y):(x=e[7],y=e[8]),Xe.useEffect(x,y);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 Py(t){return t.isActive?{...t,isActive:!1}:t}function Ty(t){return{isActive:!0,cycle:t.cycle+1}}function Ry(t){return t.isActive?{...t,isActive:!1}:t}const Pm=i.createContext(void 0),Ey=t=>{const e=mt.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=Iy();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(Ay,{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(Pm.Provider,{value:d,children:[n,u]}),e[6]=n,e[7]=u,e[8]=d,e[9]=m):m=e[9],m},My=()=>{const t=i.useContext(Pm);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Tm="gitmojiCache",Fy=1e3*60*60*24*7,Rm="1",Ly="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Em=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},pl=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Tm);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==Rm||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(Em),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},Oy=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:Rm};window.localStorage.setItem(Tm,JSON.stringify(e))}catch{return}},du=t=>Date.now()-t.fetchedAt<Fy;let Ko=null;const So=new Set,uu=async()=>{if(Ko)return Ko;const t=(async()=>{try{const e=await fetch(Ly);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(Em):[];return Oy(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},By=t=>{const[e,n]=i.useState(()=>t?pl()?.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=pl();if(l&&(n(l.gitmojis),du(l)))return;So.add(n),o(!0);let d=!1;return uu().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=pl();return l&&du(l)?l.gitmojis:uu()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:c}},fu=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function Vy(t,e,n){const r=mt.c(5),[o,a]=i.useState();let c,l;return r[0]!==n||r[1]!==t||r[2]!==e?(c=()=>{if(e){a(void 0);return}if(!t){a(void 0);return}a(void 0);let d=!1;return(async()=>{const[u,m]=await Promise.all([Mp(t),Fp(t)]).catch(_y);if(d)return;const f=fu(u),g=fu(m);if(!f||!g||g===f)return;const b=n||"",p=g.split("/").filter(Boolean).pop()||g;a({source:"sdk",path:g,projectDirectory:f,branch:b,label:b||p,name:p,worktreeRoot:g,worktreeStatus:"ready",headState:b?"branch":"unborn",worktreeSource:"existing"})})(),()=>{d=!0}},l=[t,e,n],r[0]=n,r[1]=t,r[2]=e,r[3]=c,r[4]=l):(c=r[3],l=r[4]),i.useEffect(c,l),e??o}function _y(){return["",""]}const ao=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 ao("plan",t)}async function $y(t){return ao("conflict-details",{tempWorktreePath:t})}async function zy(t){return(await ao("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function Wy(t){return ao("run",{plan:t})}async function Uy(t){await ao("abort",{state:t})}async function Hy(t){return ao("continue",{state:t})}const Gy=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=Nt(),d=ut(E=>E.currentSessionId),u=Ee(E=>E.setActiveMainTab),[m,f]=Xe.useState(!1),g=Xe.useRef(null),[b,p]=Xe.useState(o);Xe.useEffect(()=>{p(o)},[o]),Xe.useEffect(()=>{if(m){const E=setTimeout(()=>{g.current?.focus()},0);return()=>clearTimeout(E)}},[m]);const x=!!(t&&e&&b&&b!=="HEAD"&&e!==b),[y,h]=Xe.useState({kind:"idle"}),[C,w]=Xe.useState(!1),[S,j]=Xe.useState([]),k=Xe.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);Xe.useEffect(()=>{if(!k||typeof window>"u")return;const E=window.localStorage.getItem(k);if(!E)return;let Z=!1;try{const ne=JSON.parse(E);if(!ne?.tempWorktreePath||ne.repoRoot!==t){window.localStorage.removeItem(k);return}(async()=>{const Y=await zy(ne.tempWorktreePath).catch(()=>!1);if(Z)return;if(!Y){window.localStorage.removeItem(k);return}const H=await $y(ne.tempWorktreePath).catch(()=>null);Z||H&&h({kind:"conflict",state:ne,details:H})})()}catch{window.localStorage.removeItem(k)}return()=>{Z=!0}},[k,t]),Xe.useEffect(()=>{if(!x){h({kind:"idle"});return}let E=!1;return h({kind:"loading"}),(async()=>{try{const Z=await ho({repoRoot:t,sourceBranch:e,targetBranch:b});if(E)return;if(h({kind:"ready",plan:Z}),Z.commits.length>0){const Y=Z.commits.slice(-50).reverse(),H=await Lp(t,Y);E||(j(H),w(!1))}else E||(j([]),w(!1))}catch{E||h({kind:"idle"})}})(),()=>{E=!0}},[x,t,e,b,a]);const v=Xe.useCallback(E=>{d&&ut.getState().setWorktreeMetadata(d,{...n,createdFromBranch:E})},[d,n]),A=ut(E=>E.openNewSessionDraft),I=Xe.useCallback(async E=>{const Z=await Tn("git.integrate.cherrypick.resolve.visible",{current_commit:E.state.currentCommit,target_branch:E.state.targetBranch}),ne=await Tn("git.integrate.cherrypick.resolve.instructions",{repo_root:E.state.repoRoot,temp_worktree_path:E.state.tempWorktreePath,source_branch:E.state.sourceBranch,target_branch:E.state.targetBranch,current_commit:E.state.currentCommit}),Y=`Cherry-pick conflict context (JSON)
6
- ${JSON.stringify({repoRoot:E.state.repoRoot,tempWorktreePath:E.state.tempWorktreePath,sourceBranch:E.state.sourceBranch,targetBranch:E.state.targetBranch,currentCommit:E.state.currentCommit,remainingCommits:E.state.remainingCommits,statusPorcelain:E.details.statusPorcelain,unmergedFiles:E.details.unmergedFiles,currentPatchMeta:E.details.currentPatchMeta,currentPatch:E.details.currentPatch,diff:E.details.diff},null,2)}`;return{visibleText:Z,instructionsText:ne,payloadText:Y}},[]),N=ci(E=>E.setPendingInputText),O=ci(E=>E.setPendingSyntheticParts),P=Xe.useCallback(async(E,Z)=>{const ne=await I(E);if(Z){A({directoryOverride:E.state.tempWorktreePath,initialPrompt:ne.visibleText,syntheticParts:[{text:ne.instructionsText,synthetic:!0},{text:ne.payloadText,synthetic:!0}]}),u("chat");return}if(!d){ce.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}N(ne.visibleText,"replace"),O([{text:ne.instructionsText,synthetic:!0},{text:ne.payloadText,synthetic:!0}]),u("chat")},[d,u,I,A,N,O,l]),T=Xe.useCallback(async()=>{if(y.kind==="ready"){if(y.plan.commits.length===0){ce.message(l("gitView.integrate.noCommitsToMoveToast"));return}h({kind:"running",plan:y.plan});try{const E=await Wy(y.plan);if(E.kind==="success"){ce.success(l("gitView.integrate.commitsMovedToast"),{description:E.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:E.moved,branch:y.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:E.moved,branch:y.plan.targetBranch})});const Z=await ho(y.plan);h({kind:"ready",plan:Z}),c?.();return}E.kind==="conflict"&&(ce.error(l("gitView.integrate.cherryPickConflictToast"),{description:l("gitView.integrate.cherryPickConflictDescription")}),h({kind:"conflict",state:E.state,details:E.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(E.state)))}catch(E){const Z=E instanceof Error?E.message:String(E);ce.error(l("gitView.integrate.failedToMoveToast"),{description:Z});const ne=await ho({repoRoot:t,sourceBranch:e,targetBranch:b}).catch(()=>null);h(ne?{kind:"ready",plan:ne}:{kind:"idle"})}}},[y,c,t,e,b,k,l]),L=Xe.useCallback(async()=>{if(y.kind==="conflict")try{await Uy(y.state),ce.message(l("gitView.integrate.cherryPickAbortedToast")),k&&typeof window<"u"&&window.localStorage.removeItem(k)}finally{const E=await ho({repoRoot:t,sourceBranch:e,targetBranch:b}).catch(()=>null);h(E?{kind:"ready",plan:E}:{kind:"idle"})}},[y,t,e,b,k,l]),R=Xe.useCallback(async()=>{if(y.kind==="conflict")try{const E=await Hy(y.state);if(E.kind==="success"){ce.success(l("gitView.integrate.cherryPickFinishedToast"));const Z=await ho({repoRoot:t,sourceBranch:e,targetBranch:b}).catch(()=>null);h(Z?{kind:"ready",plan:Z}:{kind:"idle"}),k&&typeof window<"u"&&window.localStorage.removeItem(k),c?.();return}E.kind==="conflict"&&(h({kind:"conflict",state:E.state,details:E.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(E.state)))}catch(E){const Z=E instanceof Error?E.message:String(E);ce.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:Z})}},[y,t,e,b,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(D,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.integrate.title")}),y.kind==="ready"&&y.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:y.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:y.kind==="loading"||y.kind==="running"?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.integrate.moveCommits")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",b]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(sn,{open:m,onOpenChange:f,children:[s.jsx(en,{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:b}),s.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(tn,{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:E=>E.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(oi,{heading:l("gitView.branch.localBranches"),children:r.map(E=>s.jsx(li,{value:E,onSelect:()=>{p(E),v(E),f(!1)},children:E},E))})]})]})})]}),y.kind==="ready"?s.jsx($e,{size:"sm",onClick:()=>{T()},disabled:!x||y.plan.commits.length===0,children:l("gitView.integrate.move")}):y.kind==="loading"?s.jsx($e,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):y.kind==="running"?s.jsx($e,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),y.kind==="ready"&&y.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),y.kind==="ready"&&y.plan.commits.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"typography-meta text-foreground",children:[l("gitView.integrate.commitsToMove"),s.jsxs("span",{className:"text-muted-foreground",children:[" (",y.plan.commits.length,")"]})]}),S.length>0&&y.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>w(E=>!E),className:"typography-micro text-muted-foreground hover:text-foreground",children:l(C?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),s.jsxs("div",{className:"space-y-1",children:[(C?S:S.slice(0,5)).map(E=>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:E.short}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:E.subject||E.sha})]},E.sha)),S.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.previewUnavailable")}),y.plan.commits.length>S.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:S.length})})]})]}),y.kind==="conflict"&&s.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[s.jsx("div",{className:"typography-meta text-foreground",children:l("gitView.integrate.conflictsInFiles",{count:y.details.unmergedFiles.length})}),s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[l("gitView.integrate.currentCommit"),": ",s.jsx("span",{className:"font-mono",children:y.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.details.unmergedFiles.slice(0,6).map(E=>s.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:E},E)),y.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:y.details.unmergedFiles.length-6})})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx($e,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{L()},children:l("gitView.operation.abort")}),s.jsxs($e,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{P({state:y.state,details:y.details},!1)},children:[s.jsx(D,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs($e,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{P({state:y.state,details:y.details},!0)},children:[s.jsx(D,{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")})]})]})]})]})},Ky=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=Nt(),[d,u]=i.useState([]),[m,f]=i.useState(!1),[g,b]=i.useState(""),[p,x]=i.useState(""),[y,h]=i.useState(null),[C,w]=i.useState({}),S=i.useCallback(async()=>{if(n){f(!0);try{const N=await Op(n);u(N.stashes),w({})}catch(N){ce.error(N instanceof Error?N.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 N=!1;const O=d.map(P=>P.ref);return Bp(n,O).then(P=>{N||w(P.counts)}).catch(()=>{}),()=>{N=!0}},[n,t,d]);const j=i.useMemo(()=>{const N=g.trim().toLowerCase();return N?d.filter(O=>`${O.ref} ${O.message} ${O.relativeTime}`.toLowerCase().includes(N)):d},[g,d]),k=i.useCallback(async N=>{await S(),await c?.(N)},[S,c]),v=async()=>{if(!(!n||y)){h("create");try{const N=await Vp(n,{message:p.trim()||void 0});N.created?(ce.success(l("gitView.stashes.toast.created")),x("")):ce.info(l("gitView.stashes.toast.noChanges")),await k({affectsIndex:!!(N.created&&o)})}catch(N){ce.error(N instanceof Error?N.message:l("gitView.stashes.toast.createFailed"))}finally{h(null)}}},A=async(N,O)=>{if(!(!n||y)&&!(O==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:N.ref})))){h(`${O}:${N.ref}`);try{O==="apply"&&await _p(n,{ref:N.ref}),O==="pop"&&await $p(n,{ref:N.ref}),O==="drop"&&await zp(n,{ref:N.ref});const P=O==="apply"?"gitView.stashes.toast.applySuccess":O==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";ce.success(l(P)),await k({affectsIndex:O!=="drop"})}catch(P){const T=O==="apply"?"gitView.stashes.toast.applyFailed":O==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";ce.error(P instanceof Error?P.message:l(T)),await k({affectsIndex:O!=="drop"})}finally{h(null)}}},I=y!==null;return s.jsx($s,{open:t,onOpenChange:e,children:s.jsxs(_s,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(Hs,{children:[s.jsxs(Us,{className:"flex items-center gap-2",children:[s.jsx(D,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(on,{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:N=>x(N.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:I||!r,className:"flex-1"}),s.jsxs($e,{onClick:v,disabled:!r||I||!n,children:[y==="create"?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{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(D,{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:N=>b(N.target.value),placeholder:l("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto",children:m?s.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:s.jsx(D,{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((N,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:N.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{children:O===0&&!g.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:O+1})})}),s.jsx(Ft,{sideOffset:6,children:N.ref})]})," · ",N.relativeTime," · ",typeof C[N.ref]=="number"?l("gitView.stashes.fileCount",{count:C[N.ref]}):l("gitView.stashes.fileCountLoading")]})]}),s.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[s.jsx(gl,{label:l("gitView.stashes.actions.apply"),loading:y===`apply:${N.ref}`,onClick:()=>A(N,"apply"),disabled:I,children:s.jsx(D,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(gl,{label:l("gitView.stashes.actions.pop"),loading:y===`pop:${N.ref}`,onClick:()=>A(N,"pop"),disabled:I,children:s.jsx(D,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(gl,{label:l("gitView.stashes.actions.drop"),loading:y===`drop:${N.ref}`,onClick:()=>A(N,"drop"),disabled:I,destructive:!0,children:s.jsx(D,{name:"delete-bin",className:"size-4"})})]})]},N.ref))})]})})},gl=t=>{const e=mt.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,u=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let m;e[0]!==u?(m=Pe("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",u),e[0]=u,e[1]=m):m=e[1];let f;e[2]!==l||e[3]!==r?(f=r?s.jsx(D,{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(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:m,onClick:c,disabled:o,children:f})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=m,e[10]=f,e[11]=g):g=e[11];let b;e[12]!==n?(b=s.jsx(Ft,{sideOffset:6,children:n}),e[12]=n,e[13]=b):b=e[13];let p;return e[14]!==g||e[15]!==b?(p=s.jsxs(Et,{children:[g,b]}),e[14]=g,e[15]=b,e[16]=p):p=e[16],p},qy=t=>{const e=mt.c(16),{onOpenStashes:n}=t,{t:r}=Nt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(D,{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(D,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=u):u=e[11];let m;return e[12]!==c||e[13]!==d||e[14]!==u?(m=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,u]}),e[12]=c,e[13]=d,e[14]=u,e[15]=m):m=e[15],m},ti=8,Yy=t=>{const e=mt.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,u=Math.max(r,a+1)*ti+ti/2,m=i.useRef(null),f=i.useRef(null);let g;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==u?(g=()=>{const h=m.current,C=f.current;if(!h||!C)return;const w=h.offsetHeight;if(w===0)return;const S=window.devicePixelRatio||1;C.width=u*S,C.height=w*S;const j=C.getContext("2d");if(!j)return;j.scale(S,S),j.clearRect(0,0,u,w);const k=w/2,v=a*ti+ti/2,A=getComputedStyle(C),I=A.getPropertyValue("--surface-muted-foreground").trim()||A.color,N=T=>{if(!T.startsWith("var("))return T;const L=T.slice(4,-1).trim();return A.getPropertyValue(L).trim()||I},O=[...l].sort(Jy);for(const T of O){const L=T.fromLane*ti+ti/2,R=T.toLane*ti+ti/2,B=T.type==="passing"?.72:T.type==="branch-out"||T.type==="merge-in"?.95:1;j.beginPath(),j.strokeStyle=N(T.color),j.globalAlpha=B,j.lineWidth=1.25,j.lineCap="round";e:switch(T.type){case"passing":case"commit-lane":{j.moveTo(L,0),j.lineTo(L,w);break e}case"top-stub":{j.moveTo(L,0),j.lineTo(L,k);break e}case"bottom-stub":{j.moveTo(L,k),j.lineTo(L,w);break e}case"branch-out":{const V=(k+w)/2;j.moveTo(v,k),j.bezierCurveTo(v,V,R,V,R,w);break e}case"merge-in":{const V=k/2;j.moveTo(L,0),j.bezierCurveTo(L,V,v,V,v,k);break e}default:continue}j.stroke(),j.globalAlpha=1}const P=A.getPropertyValue("--background").trim()||A.getPropertyValue("--surface-background").trim();j.beginPath(),j.arc(v,k,4,0,Math.PI*2),j.fillStyle=N(c),j.fill(),j.beginPath(),j.arc(v,k,5,0,Math.PI*2),j.strokeStyle=P||I,j.lineWidth=2,j.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=u,e[4]=g):g=e[4];let b;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==u?(b=[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]=b):b=e[12],i.useLayoutEffect(g,b);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 y;return e[16]!==p?(y=s.jsx("div",{ref:m,style:p,children:x}),e[16]=p,e[17]=y):y=e[17],y};function Qy(t){return t==="branch-out"||t==="merge-in"}function Jy(t,e){const n=Qy;return(n(t.type)?1:0)-(n(e.type)?1:0)}const mu=15e3,hu=500,pu=12,gu=8*1024*1024,xu=t=>typeof t=="string"?0:(t.original?.length??0)+(t.modified?.length??0),bu=t=>{if(t.size<=pu){let o=0;for(const a of t.values())o+=xu(a);if(o<=gu)return t}const e=Array.from(t.entries()).reverse(),n=new Map;let r=0;for(const[o,a]of e){if(n.size>=pu)continue;const c=xu(a);r+c>gu&&n.size>0||(n.set(o,a),r+=c)}return new Map(Array.from(n.entries()).reverse())};function yu(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:jc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Xy(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 Zy(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 ew=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}=Nt(),b=Ee(H=>H.timeFormatPreference),p=e==="graph",[x,y]=i.useState(null),[h,C]=i.useState(!1),[w,S]=i.useState(""),[j,k]=i.useState(null),[v,A]=i.useState(new Set),[I,N]=i.useState(new Map),[O,P]=i.useState(new Set),T=async()=>{if(u){y("checkout");try{await Qp(u,t.hash),ce.success(g("gitView.history.actions.detachedHead")),f?.()}catch(H){ce.error(String(H.message))}finally{y(null)}}},L=async()=>{if(!(!u||!w.trim())){y("createBranch");try{await Up(u,w.trim(),t.hash),C(!1),S(""),f?.()}catch(H){ce.error(String(H.message))}finally{y(null)}}},R=async()=>{if(u){y("cherryPick");try{const H=await Yp(u,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"cherry-pick"}):f?.()}catch(H){ce.error(String(H.message))}finally{y(null)}}},B=async()=>{if(u){y("revert");try{const H=await qp(u,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"revert"}):f?.()}catch(H){ce.error(String(H.message))}finally{y(null)}}},V=async(H,re=!1)=>{if(!(!u||x!==null)){y("reset");try{await Hp(u,t.hash,H,re),f?.()}catch(ae){ce.error(String(ae.message))}finally{y(null)}}},_=async()=>{if(!j)return;const H=j;switch(k(null),H){case"checkout":return T();case"cherryPick":return R();case"revert":return B();case"merge":return E();case"rebase":return Z();case"resetSoft":return V("soft");case"resetMixed":return V("mixed");case"resetHard":return V("hard",!0)}},E=async()=>{if(u){y("merge");try{const H=await Kp(u,{branch:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"merge"}):f?.()}catch(H){ce.error(String(H.message))}finally{y(null)}}},Z=async()=>{if(u){y("rebase");try{const H=await Gp(u,{onto:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"rebase"}):f?.()}catch(H){ce.error(String(H.message))}finally{y(null)}}},ne=i.useCallback(async H=>{const re=H.path;if(!u){N(ae=>new Map(ae).set(re,"error"));return}N(ae=>bu(new Map(ae).set(re,"loading")));try{const ae=Wp(u,t.hash,H.path,!1),me=new Promise((te,ke)=>{setTimeout(()=>ke(new Error(`Timed out after ${mu}ms`)),mu)}),Se=await Promise.race([ae,me]);N(te=>bu(new Map(te).set(re,Se)))}catch{N(ae=>new Map(ae).set(re,"error"))}},[u,t.hash]),Y=i.useCallback(async H=>{const re=H.path;if(H.changeType==="R"||H.isBinary){A(te=>{const ke=new Set(te);return ke.has(re)?ke.delete(re):ke.add(re),ke});return}const ae=I.get(re);if(v.has(re)&&ae&&ae!=="error"){A(te=>{const ke=new Set(te);return ke.delete(re),ke});return}A(te=>{const ke=new Set(te);return ke.add(re),ke}),!(ae&&ae!=="error"||H.insertions+H.deletions>hu&&!O.has(re))&&await ne(H)},[I,O,ne,v]);return s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:a,className:Pe("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",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(Yy,{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 H=Zy(t.refs);return H.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:H.map(re=>s.jsx("span",{className:Pe("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",re.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":re.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:re.label},re.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:yu(t.date,b),children:yu(t.date,b)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:H=>{H.stopPropagation(),d(t.hash)},children:s.jsx(D,{name:"file-copy",className:"size-3"})})}),s.jsx(Ft,{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:H=>{H.stopPropagation(),_()},children:[x!==null?s.jsx(D,{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:H=>{H.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:H=>{H.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:H=>S(H.target.value),onKeyDown:H=>{H.key==="Enter"&&L(),H.key==="Escape"&&(C(!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:H=>{H.stopPropagation(),L()},children:[x==="createBranch"?s.jsx(D,{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:H=>{H.stopPropagation(),C(!0)},children:g("gitView.history.actions.createBranch")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:H=>{H.stopPropagation(),k("cherryPick")},children:g("gitView.history.actions.cherryPick")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:H=>{H.stopPropagation(),k("revert")},children:g("gitView.history.actions.revert")}),s.jsxs(sn,{children:[s.jsx(en,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:H=>H.stopPropagation(),children:[x==="reset"?s.jsx(D,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,g("gitView.history.actions.reset")]})}),s.jsx(tn,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(H=>s.jsx(bs,{disabled:x!==null,onSelect:re=>{re.stopPropagation(),k(`reset${H.charAt(0).toUpperCase()+H.slice(1)}`)},children:g(`gitView.history.actions.reset${H.charAt(0).toUpperCase()+H.slice(1)}`)},H))})]}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:H=>{H.stopPropagation(),k("merge")},children:g("gitView.history.actions.merge")}),s.jsx($e,{variant:"outline",size:"xs",className:"h-6",disabled:x!==null,onClick:H=>{H.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(D,{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(H=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>Y(H),className:Pe("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",v.has(H.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:Pe("font-semibold w-3 text-center shrink-0",Xy(H.changeType)),children:H.changeType}),s.jsx("span",{className:"truncate text-foreground min-w-0",title:H.path,children:H.path}),!H.isBinary&&s.jsxs("span",{className:"shrink-0",children:[s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",H.insertions]}),s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",H.deletions]})]}),H.isBinary&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:g("gitView.history.binary")}),s.jsx(D,{name:v.has(H.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),v.has(H.path)&&s.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded border border-border/40 mx-2 mb-1","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:H.changeType==="R"?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.renamedNoDiff")}):H.isBinary?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.binaryNoDiff")}):(()=>{const re=H.insertions+H.deletions;if(!O.has(H.path)&&re>hu)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:re})}),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:()=>{P(me=>new Set(me).add(H.path)),ne(H)},children:g("gitView.history.renderDiffAnyway")})]});const ae=I.get(H.path);return ae==="loading"||ae===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g("gitView.history.loadingDiff")}):ae==="error"?s.jsx("button",{type:"button",onClick:()=>Y(H),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(xm,{original:ae.original,modified:ae.modified,language:Ai(H.path)||"",fileName:H.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},H.path))})]})]})}),wu=["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 wu[t%wu.length]}function tw(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let b=0;b<e.length;b++)e[b]===o.hash&&a.push(b);let c=a.length>0?a[0]:-1;if(c===-1){const b=e.indexOf(null);b!==-1?c=b:(c=e.length,e.push(null))}const l=a.slice(1),d=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 b=1;b<o.parents.length;b++){const p=o.parents[b],x=e.indexOf(p);if(x!==-1)f.push(x);else{const y=e.indexOf(null),h=y!==-1?y: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 b of l)g.push({fromLane:b,toLane:c,color:qo(b),type:"merge-in"}),e[b]=null;for(const b of f)g.push({fromLane:c,toLane:b,color:qo(b),type:"branch-out"});for(let b=0;b<e.length;b++)e[b]!==null&&b!==c&&(f.includes(b)||g.push({fromLane:b,toLane:b,color:qo(b),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:g})}return n}const sw=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],nw=t=>{const e=mt.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:b,contentMaxHeightClassName:p,branchDivider:x,onConflict:y,onActionSuccess:h}=t,C=n===void 0?"history":n,w=b===void 0?!0:b,S=p===void 0?"max-h-[50vh]":p,j=x===void 0?null:x,{t:k}=Nt(),[v,A]=i.useState(!0),I=C==="graph";let N;e[0]!==I||e[1]!==r?(N=I&&r?tw(r.all):[],e[0]=I,e[1]=r,e[2]=N):N=e[2];const O=N;let P;e[3]!==O?(P=Math.max(1,...O.map(rw)),e[3]=O,e[4]=P):P=e[4];const T=P;let L;e[5]!==O?(L=new Map(O.map(iw)),e[5]=O,e[6]=L):L=e[6];const R=L;if(!r)return null;const B=j!==null&&j.insertBeforeIndex>0&&j.insertBeforeIndex<r.all.length,V=j!==null&&j.insertBeforeIndex===r.all.length,_=B||V;let E;e[7]!==j||e[8]!==B||e[9]!==V||e[10]!==r.all?(E=B?r.all.slice(0,j.insertBeforeIndex):V?r.all:[],e[7]=j,e[8]=B,e[9]=V,e[10]=r.all,e[11]=E):E=e[11];const Z=E;let ne;if(e[12]!==j||e[13]!==u||e[14]!==S||e[15]!==g||e[16]!==l||e[17]!==B||e[18]!==_||e[19]!==I||e[20]!==o||e[21]!==R||e[22]!==m||e[23]!==r.all||e[24]!==a||e[25]!==T||e[26]!==C||e[27]!==h||e[28]!==y||e[29]!==f||e[30]!==c||e[31]!==d||e[32]!==k||e[33]!==Z){const ge=B?r.all.slice(j.insertBeforeIndex):[];let F;e[35]!==j?.direction?(F=j?.direction==="down"?s.jsx(D,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(D,{name:"arrow-up",className:"size-3.5"}),e[35]=j?.direction,e[36]=F):F=e[36];const se=F;let ee;e[37]!==u||e[38]!==g||e[39]!==l||e[40]!==I||e[41]!==R||e[42]!==m||e[43]!==T||e[44]!==C||e[45]!==h||e[46]!==y||e[47]!==f||e[48]!==d?(ee=Fe=>s.jsx("ul",{className:"divide-y divide-border/60",children:Fe.map(Me=>s.jsx(ew,{entry:Me,mode:C,laned:I?R.get(Me.hash):void 0,totalLanes:I?T: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:y,onActionSuccess:h},Me.hash))}),e[37]=u,e[38]=g,e[39]=l,e[40]=I,e[41]=R,e[42]=m,e[43]=T,e[44]=C,e[45]=h,e[46]=y,e[47]=f,e[48]=d,e[49]=ee):ee=e[49];const Ne=ee;let De;e[50]!==o||e[51]!==r.all.length||e[52]!==a||e[53]!==c||e[54]!==k?(De=r.all.length>=a?s.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:s.jsx($e,{type:"button",variant:"ghost",size:"xs",onClick:()=>c(a+25),disabled:o,className:"px-3 text-muted-foreground hover:text-foreground",children:o?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(D,{name:"loader-4",className:"size-3 animate-spin"}),k("gitView.history.loadingMore")]}):k("gitView.history.loadMore")})}):null,e[50]=o,e[51]=r.all.length,e[52]=a,e[53]=c,e[54]=k,e[55]=De):De=e[55];const Be=De;ne=s.jsx(_n,{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")})}):_&&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:Ne(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}),se]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),ge.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:Ne(ge)}):null]}),Be]}):s.jsxs(s.Fragment,{children:[Ne(r.all),Be]})}),e[12]=j,e[13]=u,e[14]=S,e[15]=g,e[16]=l,e[17]=B,e[18]=_,e[19]=I,e[20]=o,e[21]=R,e[22]=m,e[23]=r.all,e[24]=a,e[25]=T,e[26]=C,e[27]=h,e[28]=y,e[29]=f,e[30]=c,e[31]=d,e[32]=k,e[33]=Z,e[34]=ne}else ne=e[34];const Y=ne;if(!w){if(_){let F;return e[56]!==Y?(F=s.jsx("section",{className:"h-full min-h-0",children:Y}),e[56]=Y,e[57]=F):F=e[57],F}let ge;return e[58]!==Y?(ge=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:Y}),e[58]=Y,e[59]=ge):ge=e[59],ge}let H;e[60]!==k?(H=k("gitView.history.title"),e[60]=k,e[61]=H):H=e[61];let re;e[62]!==H?(re=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:H}),e[62]=H,e[63]=re):re=e[63];let ae;e[64]!==o||e[65]!==v||e[66]!==a||e[67]!==c||e[68]!==k?(ae=v&&s.jsx("div",{onClick:ow,onPointerDown:aw,children:s.jsxs($n,{value:String(a),onValueChange:ge=>c(Number(ge)),disabled:o,children:[s.jsx(zn,{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(Nn,{placeholder:k("gitView.history.commitsPlaceholder")})}),s.jsx(Wn,{children:sw.map(ge=>s.jsx(Ls,{value:String(ge.value),children:k(ge.labelKey)},ge.value))})]})}),e[64]=o,e[65]=v,e[66]=a,e[67]=c,e[68]=k,e[69]=ae):ae=e[69];let me;e[70]!==v?(me=v?s.jsx(D,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(D,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=v,e[71]=me):me=e[71];let Se;e[72]!==ae||e[73]!==me?(Se=s.jsxs("div",{className:"flex items-center gap-2",children:[ae,me]}),e[72]=ae,e[73]=me,e[74]=Se):Se=e[74];let te;e[75]!==re||e[76]!==Se?(te=s.jsxs(Bo,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[re,Se]}),e[75]=re,e[76]=Se,e[77]=te):te=e[77];let ke;e[78]!==Y?(ke=s.jsx(to,{children:Y}),e[78]=Y,e[79]=ke):ke=e[79];let Q;return e[80]!==v||e[81]!==te||e[82]!==ke?(Q=s.jsxs(eo,{open:v,onOpenChange:A,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[te,ke]}),e[80]=v,e[81]=te,e[82]=ke,e[83]=Q):Q=e[83],Q};function rw(t){return t.lane+1}function iw(t){return[t.commit.hash,t]}function ow(t){return t.stopPropagation()}function aw(t){return t.stopPropagation()}const Mm=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},lw=9e4,cw=15e3,dw=5*6e4,uw=[2e3,5e3],fw=6e4,mw=2*6e4,hw=5*6e4,pw=4,gw=720*6e4,xw="openchamber.github-pr-status",bw=t=>t==="closed"||t==="merged",yw=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,vu=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,Oc=t=>{const e=Ia(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},Fm=(t,e)=>Object.entries(t).filter(([,n])=>Oc(n)===e).map(([n])=>n),ww=(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},vw=(t,e,n)=>{const r=Fm(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&&Oc(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)},jw=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:Ia(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Sw=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}),rr=ro()(cc((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]:ww(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}),uw.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<dw)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(bw(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=yw(a.status)?fw:a.status?.checks&&a.status.checks.state!=="pending"?hw:mw;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},cw);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=Oc(a);if(!a||!c)return;const l=Fm(o.entries,c),d=l.some(f=>!!o.entries[f]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const u=vu.get(c)??0;if(!r?.force&&Date.now()-u<lw||po.has(c))return;const m=vw(o.entries,c,n);if(m){if(po.add(c),vu.set(c,Date.now()),t(f=>{const g={...f.entries};return l.forEach(b=>{const p=g[b];p&&(g[b]={...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(b=>{const p=g[b];p&&(g[b]={...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(b=>{const p=g[b];p&&(g[b]={...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 b={...g.entries};return l.forEach(p=>{const x=b[p];if(!x)return;const y=x.status?.pr,h=f.pr,w=!!(h&&y&&h.number===y.number&&(!h.body||!h.body.trim())&&typeof y.body=="string"&&y.body.trim().length>0)&&h&&y?.body?{...f,pr:{...h,body:y.body}}:f,S=w.resolvedRemoteName??x.resolvedRemoteName??m.remoteName??null,j=Ia(x)??{directory:m.directory,branch:m.branch,remoteName:m.remoteName??null};b[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:b}})}catch(f){const g=f instanceof Error?f.message:String(f);t(b=>{const p={...b.entries};return l.forEach(x=>{const y=p[x];y&&(p[x]={...y,error:g||"Failed to load PR status",isLoading:r?.silent?y.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?y.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 Mm(o,pw,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:xw,storage:Tf(()=>Ni()),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<gw}).map(([e,n])=>[e,jw(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).map(([o,a])=>[o,Sw(a)]))}}})),Nw=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"},kw=t=>{const e=Nw(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}},Cw=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 xl=new Map,ju=new Map;const Aw=t=>{const e=mt.c(2);let n;return e[0]!==t?(n=r=>{const o=new Map,a=new Map;for(const c of t){const l=r.entries[c];if(!l)continue;const d=kw(l);if(!d)continue;const u=Cw(d);o.set(c,u),a.set(c,d)}if(o.size===xl.size){let c=!0;for(const[l,d]of o)if(xl.get(l)!==d){c=!1;break}if(c)return ju}return xl=o,ju=a,a},e[0]=t,e[1]=n):n=e[1],rr(n)},Dw=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"}},Iw=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=[2e3,5e3],Su=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),si=t=>{let e=t.trim();return e?(e.startsWith("refs/heads/")&&(e=e.slice(11)),e.startsWith("heads/")&&(e=e.slice(6)),e.startsWith("remotes/")&&(e=e.slice(8)),e):""},Tw=(t,e)=>{const n=si(t);if(!n||n.includes("->"))return"";if(e){const o=`${e}/`;return n.startsWith(o)?n.slice(o.length).trim():""}const r=n.indexOf("/");return r>0?n.slice(r+1).trim():n},Rw=(t,e)=>`${t}::${e}`,Bc=t=>{const e=String(t||"").trim();if(!e)return"";const n=e.indexOf("/");return n<=0?"":e.slice(0,n).trim()},bl=(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=Bc(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)},Ew=t=>t.startsWith("pr-"),Mw=(t,e)=>{const n=Bc(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=>!Ew(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},yl=new Map,wl=Ii;function Fw(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 Lw=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=Nt(),d=Ee(we=>we.timeFormatPreference),{github:u}=Jn(),m=Pi(we=>we.status),f=Pi(we=>we.hasChecked),g=Ee(we=>we.setSettingsDialogOpen),b=Ee(we=>we.setSettingsPage),p=Ee(we=>we.setActiveMainTab),x=ut(we=>we.currentSessionId),{isMobile:y,hasTouchInput:h}=Er(),C=i.useCallback(()=>{b("github"),g(!0)},[g,b]),w=i.useMemo(()=>Rw(t,e),[t,e]),S=i.useMemo(()=>yl.get(w)??null,[w]),j=rr(we=>we.ensureEntry),k=rr(we=>we.setParams),v=rr(we=>we.startWatching),A=rr(we=>we.stopWatching),I=rr(we=>we.refresh),N=rr(we=>we.updateStatus),[O,P]=i.useState(()=>S?.title??Su(e)),[T,L]=i.useState(()=>S?.body??""),[R,B]=i.useState(()=>S?.draft??!1),[V,_]=i.useState(()=>S?.additionalContext??""),[E,Z]=i.useState(()=>{const we=typeof S?.targetBaseBranch=="string"?si(S.targetBaseBranch):"";return we||si(n)}),[ne,Y]=i.useState("squash"),[H,re]=i.useState(!1),[ae,me]=i.useState(!1),[Se,te]=i.useState(!1),[ke,Q]=i.useState(!1),[ge,F]=i.useState(!1),[se,ee]=i.useState(!1),[Ne,De]=i.useState(null),[Be,Fe]=i.useState(""),[Me,he]=i.useState(""),[Ae,pe]=i.useState(!1),[ue,U]=i.useState(!1),[fe,de]=i.useState(()=>bl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r})),[G,$]=i.useState(!1),{detectedUpstream:ve,upstreamBranches:be}=Fw(t,u);i.useEffect(()=>{$(!1)},[t]);const z=o.some(we=>we.name==="upstream"),je=!!(t&&e&&n&&(e!==n||(z||ve!==null))),K=i.useMemo(()=>No(t,e),[t,e]),ye=rr(we=>we.entries[K]),Le=ye?.isLoading??!1,Re=ye?.status??null,X=ye?.error??null,M=ye?.isInitialStatusResolved??!1,le=i.useMemo(()=>{const we=G?null:fe?.name?.trim()||null,tt=new Set;for(const Ht of a){const ht=Tw(Ht,we);!ht||ht==="HEAD"||tt.add(ht)}if(G)for(const Ht of be)Ht&&Ht!=="HEAD"&&tt.add(Ht);const dt=si(n);dt&&dt!=="HEAD"&&tt.add(dt);const It=si(E);return It&&It!=="HEAD"&&tt.add(It),Array.from(tt).sort((Ht,ht)=>Ht.localeCompare(ht))},[n,a,fe?.name,E,be,G]);i.useEffect(()=>{if(o.length===0){fe&&de(null);return}(!fe||!o.some(we=>we.name===fe.name))&&de(bl(o,{selectedRemoteName:S?.selectedRemoteName,trackingBranch:r}))},[S?.selectedRemoteName,o,fe,r]),i.useEffect(()=>{const we=si(n);if(!E&&we){Z(we);return}if(le.length!==0&&!le.includes(E)){const tt=le.includes(we)?we:le[0];tt&&Z(tt)}},[le,n,E]);const[ie,Oe]=i.useState(!1),[Ge,He]=i.useState(null),[Je,rt]=i.useState(!1),[bt,yt]=i.useState(new Set),[_e,Ye]=i.useState(!1),[nt,wt]=i.useState(null),[kt,vt]=i.useState(!1),St=i.useRef(new Set),et=i.useRef(null),Ot=i.useRef(!1),ns=i.useRef(new Set),Wt=i.useRef([]);i.useEffect(()=>{ve&&!z&&$(!0)},[ve,z]),i.useEffect(()=>{G&&ve?.defaultBranch&&Z(ve.defaultBranch)},[G,ve?.defaultBranch]);const Ve=Re?.pr??null,Ze=Ve?`${t}#${Ve.number}`:null,_t=!!(Ze&&Ne===Ze);i.useEffect(()=>{if(!u?.prContext||!Ve||typeof Ve.body=="string"&&Ve.body.length>0)return;const we=`${t}#${Ve.number}`;if(St.current.has(we))return;St.current.add(we),De(we);let tt=!1;return u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!1}).then(dt=>{if(tt)return;const It=dt?.pr;It&&N(K,Ht=>!Ht?.pr||Ht.pr.number!==Ve.number?Ht:{...Ht,pr:{...Ht.pr,body:It.body||""}})}).catch(()=>{}).finally(()=>{tt||De(dt=>dt===we?null:dt)}),()=>{tt=!0}},[t,u,Ve,K,N]),i.useEffect(()=>{if(!Ve){ee(!1),Fe(""),he(""),et.current=null;return}const we=et.current!==null&&et.current!==Ve.number;we&&ee(!1),(!se||we)&&(Fe(Ve.title||""),he(Ve.body||"")),et.current=Ve.number},[se,Ve]);const jt=i.useCallback(async()=>{if(!u?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Ve){Oe(!0),yt(new Set),rt(!0);try{const we=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!0});He(we)}catch(we){const tt=we instanceof Error?we.message:String(we);ce.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:tt})}finally{rt(!1)}}},[t,u,Ve,l]),xt=i.useCallback(async()=>{if(!u?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(Ve){Ye(!0),vt(!0);try{const we=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!1});wt(we)}catch(we){const tt=we instanceof Error?we.message:String(we);ce.error(l("gitView.pr.toast.loadCommentsFailed"),{description:tt})}finally{vt(!1)}}},[t,u,Ve,l]),rs=i.useCallback(we=>{if(!we)return"";const tt=Date.parse(we);return Number.isFinite(tt)?jc(tt,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):we},[d]),Gt=i.useMemo(()=>{const we=m?.user?.login;return typeof we=="string"?we.trim():""},[m]),Ut=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)]",[]),as=i.useCallback(we=>{const tt=Gt.toLowerCase(),dt=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return we.replace(dt,(It,Ht,ht)=>{const hs=`@${ht}`,ps=ht.toLowerCase();return`${Ht}[${hs}](https://github.com/${ps}${tt&&ps===tt?"?oc-self-mention=1":""})`})},[Gt]),Bt=i.useMemo(()=>{const we=(nt?.issueComments??[]).map(It=>({id:`issue-${It.id}`,body:It.body||"",authorName:It.author?.name||It.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:It.author?.login||null,avatarUrl:It.author?.avatarUrl||null,createdAt:It.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),tt=(nt?.reviewComments??[]).map(It=>({id:`review-${It.id}`,body:It.body||"",authorName:It.author?.name||It.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:It.author?.login||null,avatarUrl:It.author?.avatarUrl||null,createdAt:It.createdAt,context:l("gitView.pr.comments.reviewContext"),path:It.path||null,line:It.line??null})),dt=[...we,...tt];return dt.sort((It,Ht)=>{const ht=It.createdAt?Date.parse(It.createdAt):0,hs=Ht.createdAt?Date.parse(Ht.createdAt):0,ps=Number.isFinite(ht)?ht:0,js=Number.isFinite(hs)?hs:0;return ps-js}),dt},[nt,l]),Lt=i.useCallback(()=>{if(!x)return ce.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:we,currentModelId:tt,currentAgentName:dt,currentVariant:It}=ss.getState(),Ht=vc.getState().lastUsedProvider,ht=we||Ht?.providerID,hs=tt||Ht?.modelID;return!ht||!hs?(ce.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:x,providerID:ht,modelID:hs,currentAgentName:dt??null,currentVariant:It??null}},[x,l]),Vt=i.useCallback((we,tt,dt,It)=>{ut.getState().sendMessage(tt,we.providerID,we.modelID,we.currentAgentName??void 0,void 0,void 0,[{text:dt,synthetic:!0},{text:It,synthetic:!0}],we.currentVariant??void 0).catch(Ht=>{const ht=Ht instanceof Error?Ht.message:String(Ht);ce.error(l("gitView.pr.toast.sendMessageFailed"),{description:ht})})},[l]),Kt=i.useCallback(we=>{const tt=we.status||"unknown",dt=we.conclusion??void 0,It=dt?`${tt} / ${dt}`:tt,Ht=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:Ht?`${Ht} · ${It}`:It})]}),we.detailsUrl?s.jsx($e,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:we.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(D,{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((ht,hs)=>s.jsxs("div",{className:"rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)]/40 px-2 py-2",children:[s.jsxs("div",{className:"typography-micro text-[var(--status-error)]",children:[ht.title||ht.level||"Issue",ht.path?` · ${ht.path}`:"",typeof ht.startLine=="number"?`:${ht.startLine}`:"",typeof ht.endLine=="number"&&ht.endLine!==ht.startLine?`-${ht.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:ht.message}),ht.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:ht.rawDetails}):null]},`${ht.path||"file"}:${ht.startLine||hs}:${hs}`))})]}):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((ht,hs)=>{const ps=(ht.conclusion||"").toLowerCase(),js=ps&&!["success","neutral","skipped"].includes(ps),Ss=`${we.id??"run"}:${we.job?.jobId??"job"}:${ht.number??hs}:${ht.name}`,Ds=bt.has(Ss);return js?s.jsxs(eo,{open:Ds,children:[s.jsxs("button",{type:"button",onClick:()=>{yt(Un=>{const Es=new Set(Un);return Es.has(Ss)?Es.delete(Ss):Es.add(Ss),Es})},className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-left "+(js?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[Ds?s.jsx(D,{name:"arrow-down-s",className:"size-4"}):s.jsx(D,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:ht.name}),ht.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:ht.conclusion}):null]}),s.jsx(to,{children:s.jsxs("div",{className:"ml-6 mt-1 rounded border border-border/40 bg-transparent px-2 py-2 typography-micro text-muted-foreground space-y-1",children:[typeof ht.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",ht.number]}):null,ht.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",ht.status]}):null,ht.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",ht.conclusion]}):null,ht.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",rs(ht.startedAt)]}):null,ht.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",rs(ht.completedAt)]}):null]})})]},Ss):s.jsxs("div",{className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-muted-foreground",children:[s.jsx("span",{className:"truncate",children:ht.name}),ht.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:ht.conclusion}):null]},Ss)})})]}):null]})},[bt,rs,l]),Xt=i.useCallback(async()=>{if(p("chat"),!u?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Ve)return;const we=Lt();if(we)try{const tt=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!0}),It=(tt.checkRuns??[]).filter(js=>{const Ss=typeof js.conclusion=="string"?js.conclusion.toLowerCase():"";return Ss?!["success","neutral","skipped"].includes(Ss):!1});if(It.length===0){ce.message(l("gitView.pr.toast.noFailedChecks"));return}const Ht=await Tn("github.pr.checks.review.visible"),ht=await Tn("github.pr.checks.review.instructions"),hs=It.flatMap(js=>(Array.isArray(js.annotations)?js.annotations:[]).map(Ds=>({run:js.name,level:Ds.level,title:Ds.title,path:Ds.path,startLine:Ds.startLine,endLine:Ds.endLine,message:Ds.message,rawDetails:Ds.rawDetails}))),ps=`GitHub PR failed checks (JSON)
7
- ${JSON.stringify({repo:tt.repo??null,pr:tt.pr??null,failedChecks:It,failedAnnotations:hs},null,2)}`;Vt(we,Ht,ht,ps)}catch(tt){const dt=tt instanceof Error?tt.message:String(tt);ce.error(l("gitView.pr.toast.loadChecksFailed"),{description:dt})}},[t,Vt,u,Ve,Lt,p,l]),Qt=i.useCallback(async()=>{if(p("chat"),!u?.prContext){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!Ve)return;const we=Lt();if(we)try{const tt=await u.prContext(t,Ve.number,{includeDiff:!1,includeCheckDetails:!1}),dt=tt.issueComments??[],It=tt.reviewComments??[];if(dt.length+It.length===0){ce.message(l("gitView.pr.toast.noPrComments"));return}const ht=await Tn("github.pr.comments.review.visible"),hs=await Tn("github.pr.comments.review.instructions"),ps=`GitHub PR comments (JSON)
8
- ${JSON.stringify({repo:tt.repo??null,pr:tt.pr??null,issueComments:dt,reviewComments:It},null,2)}`;Vt(we,ht,hs,ps)}catch(tt){const dt=tt instanceof Error?tt.message:String(tt);ce.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:dt})}},[t,Vt,u,Ve,Lt,p,l]),vs=i.useCallback(async we=>{Ye(!1),p("chat");const tt=Lt();if(!tt)return;const dt=await Tn("github.pr.comment.single.visible"),It=await Tn("github.pr.comment.single.instructions"),Ht=`GitHub PR comment (JSON)
9
- ${JSON.stringify({repo:nt?.repo??null,pr:nt?.pr??Ve??null,comment:we},null,2)}`;Vt(tt,dt,It,Ht)},[nt,Vt,Ve,Lt,p]),Dt=i.useCallback(async we=>{await I(K,we)},[K,I]),$t=i.useCallback(()=>{Wt.current.forEach(we=>{window.clearTimeout(we)}),Wt.current=Pw.map(we=>window.setTimeout(()=>{Dt({force:!0,silent:!0,markInitialResolved:!0})},we))},[Dt]);i.useEffect(()=>{if(!u?.prStatus||!je||o.length<=1||Ot.current||Re?.pr)return;const we=`${w}::${fe?.name??""}`;if(ns.current.has(we))return;ns.current.add(we);const tt=Mw(o,r).filter(Ht=>Ht.name!==fe?.name);if(tt.length===0)return;let dt=!1;return(async()=>{for(const Ht of tt){if(dt)return;try{if(!(await u.prStatus(t,e,Ht.name))?.pr)continue;if(dt)return;de(hs=>hs?.name===Ht.name?hs:Ht);return}catch{}}})(),()=>{dt=!0}},[e,je,t,u,o,fe?.name,w,Re?.pr,r]),i.useEffect(()=>{j(K),k(K,{directory:t,branch:e,remoteName:fe?.name??null,canShow:je,github:u,githubAuthChecked:f,githubConnected:m?.connected??null})},[e,je,t,j,u,f,m?.connected,K,fe?.name,k]),i.useEffect(()=>(v(K),()=>{A(K)}),[K,v,A]),i.useEffect(()=>{const we=yl.get(w)??null;P(we?.title??Su(e)),L(we?.body??""),B(we?.draft??!1),Z(we?.targetBaseBranch?si(we.targetBaseBranch):si(n));const tt=bl(o,{selectedRemoteName:we?.selectedRemoteName,trackingBranch:r});de(dt=>dt?.name===tt?.name?dt:tt)},[n,e,o,w,r]),i.useEffect(()=>{Dt({markInitialResolved:!0})},[K,Dt]),i.useEffect(()=>{!je||!fe?.name||Dt({force:!0,silent:!0,markInitialResolved:!0})},[je,Dt,fe?.name]),i.useEffect(()=>{const we=Re?.resolvedRemoteName?.trim();if(!we||Ot.current)return;const tt=o.find(dt=>dt.name===we);tt&&de(dt=>dt?.name===tt.name?dt:tt)},[o,Re?.resolvedRemoteName]),i.useEffect(()=>{const we=Re?.pr?.state==="closed"||Re?.pr?.state==="merged",tt=ye?.lastRefreshAt??0,dt=Date.now()-tt>6e4,It=!we&&dt,Ht=()=>{It&&Dt({force:!0,silent:!0})},ht=()=>{document.visibilityState==="visible"&&It&&Dt({force:!0,silent:!0})};return window.addEventListener("focus",Ht),document.addEventListener("visibilitychange",ht),()=>{window.removeEventListener("focus",Ht),document.removeEventListener("visibilitychange",ht)}},[Dt,Re?.pr?.state,ye?.lastRefreshAt]),i.useEffect(()=>{f&&m?.connected===!1&&Dt({force:!0,silent:!0,markInitialResolved:!0})},[f,m,Dt]),i.useEffect(()=>{!t||!e||yl.set(w,{title:O,body:T,draft:R,additionalContext:V,targetBaseBranch:E,selectedRemoteName:fe?.name})},[w,O,T,R,V,E,fe?.name,t,e]),i.useEffect(()=>{const we=Wt.current;return()=>{we.forEach(tt=>{window.clearTimeout(tt)}),Wt.current=[]}},[]);const Ct=i.useCallback(async()=>{if(!H&&t){re(!0);try{const tt={base:G&&ve?.defaultBranchSha?ve.defaultBranchSha:E,head:e};V&&(tt.context=V);const dt=await Jp(t,tt);dt.title?.trim()&&P(dt.title.trim()),dt.body?.trim()&&L(dt.body.trim()),c?.()}catch(we){const tt=we instanceof Error?we.message:String(we);ce.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:tt})}finally{re(!1)}}},[V,e,ve?.defaultBranchSha,t,H,c,E,l,G]),ds=i.useCallback(async()=>{if(!u?.prCreate){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}const we=O.trim();if(!we){ce.error(l("gitView.pr.toast.titleRequired"));return}const tt=E.trim();if(!tt){ce.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!G&&tt===e){ce.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}me(!0);try{const dt=Bc(r),It=G&&ve,Ht=await u.prCreate({directory:t,title:we,head:e,base:tt,...T.trim()?{body:T}:{},draft:R,...It?{targetRepo:{owner:ve.owner,repo:ve.repo},headRemote:"origin"}:{...fe?{remote:fe.name}:{},...dt&&dt!==fe?.name?{headRemote:dt}:{}}});ce.success(l("gitView.pr.toast.prCreated")),N(K,ht=>ht&&{...ht,pr:Ht}),await Dt({force:!0}),$t()}catch(dt){const It=dt instanceof Error?dt.message:String(dt);ce.error(l("gitView.pr.toast.createPrFailed"),{description:It})}finally{me(!1)}},[T,e,ve,t,R,u,K,Dt,$t,fe,E,O,r,N,G,l]),qe=i.useCallback(async we=>{if(!u?.prMerge){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}Q(!0);try{const tt=await u.prMerge({directory:t,number:we.number,method:ne});tt.merged?ce.success(l("gitView.pr.toast.prMerged")):ce.message(l("gitView.pr.toast.prNotMerged"),{description:tt.message||l("gitView.pr.notMergeable")}),await Dt({force:!0}),$t()}catch(tt){const dt=tt instanceof Error?tt.message:String(tt);ce.error(l("gitView.pr.toast.mergeFailed"),{description:dt}),we.url&&wl(we.url)}finally{Q(!1)}},[t,u,ne,Dt,$t,l]),at=i.useCallback(async we=>{if(!u?.prReady){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}F(!0);try{await u.prReady({directory:t,number:we.number}),ce.success(l("gitView.pr.toast.markedReady")),await Dt({force:!0}),$t()}catch(tt){const dt=tt instanceof Error?tt.message:String(tt);ce.error(l("gitView.pr.toast.markReadyFailed"),{description:dt}),we.url&&wl(we.url)}finally{F(!1)}},[t,u,Dt,$t,l]),Qe=i.useCallback(async we=>{if(!u?.prUpdate){ce.error(l("gitView.pr.toast.githubApiUnavailable"));return}const tt=Be.trim();if(!tt){ce.error(l("gitView.pr.toast.titleRequired"));return}te(!0);try{const dt=await u.prUpdate({directory:t,number:we.number,title:tt,body:Me});N(K,It=>It&&{...It,pr:{...It.pr??we,...dt}}),ee(!1),ce.success(l("gitView.pr.toast.prUpdated")),await Dt({force:!0}),$t()}catch(dt){const It=dt instanceof Error?dt.message:String(dt);ce.error(l("gitView.pr.toast.updatePrFailed"),{description:It})}finally{te(!1)}},[t,Me,Be,u,K,Dt,$t,N,l]);if(!je)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 At=Re?.repo?.url||null,Tt=G&&ve?.url?ve.url:At,ts=Re?.checks??null,xs=!!Re?.canMerge,ks=!!Re?.connected,Jt=f&&Re?.connected===!1,ls=Iw(Re),Ps=ls?`var(--pr-${ls})`:"var(--status-info)",Ts=ls==="draft"?"git-pr-draft":ls==="merged"?"git-merge":ls==="closed"?"git-close-pull-request":"git-pull-request",hn=Ve?[`${Ve.state}${Ve.draft?" (draft)":""}`,Ve.mergeable===!1?l("gitView.pr.notMergeable"):null,Ve.state==="open"&&typeof Ve.mergeableState=="string"&&Ve.mergeableState&&Ve.mergeableState!=="unknown"?Ve.mergeableState:null].filter(Boolean).join(" · "):"",Gs=ts?ts.total>0?`${ts.success}/${ts.total} ${l("gitView.pr.checks.label")}`:`${ts.state} ${l("gitView.pr.checks.label")}`:"";return s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[s.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex flex-col gap-1",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Ve?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md border border-border/60 bg-background/70 hover:bg-interactive-hover/60",onClick:()=>{wl(Ve.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(D,{name:Ts,className:"size-4 shrink-0",style:{color:Ps}})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(D,{name:Ts,className:"size-4 shrink-0",style:{color:"var(--surface-muted-foreground)"}}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.pullRequest.title")}),Ve?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",Ve.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Le?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex size-5 items-center justify-center rounded hover:bg-interactive-hover/60 disabled:opacity-40",disabled:Le,onClick:()=>{Dt({force:!0})},"aria-label":l("gitView.pr.actions.refreshAria"),children:s.jsx(D,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),Ve?s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 typography-micro text-muted-foreground",children:[s.jsx("span",{style:{color:Ps},children:hn}),ts?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${Dw(ts.state)}`}),Gs]}):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:[Jt?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.githubNotConnected")}),s.jsx($e,{variant:"outline",size:"sm",onClick:C,className:"w-fit",children:l("gitView.pr.actions.openSettings")})]}):null,X?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.pr.statusUnavailable")}),s.jsx("div",{className:"typography-meta text-muted-foreground break-words",children:X}),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(D,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!Ve&&!M&&!X&&!Jt?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):Ve?s.jsx("div",{className:"flex flex-col gap-2",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[se?s.jsxs("div",{className:"space-y-2",children:[s.jsx(vn,{value:Be,onChange:we=>Fe(we.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h}),s.jsx(ki,{value:Me,onChange:we=>he(we.target.value),className:"min-h-[120px] bg-background/80",placeholder:l("gitView.pr.placeholder.description"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"typography-markdown text-xl font-semibold text-foreground break-words leading-snug",children:Ve.title}),Ve.body?.trim()?s.jsx(Po,{content:Ve.body,className:"typography-markdown-body text-muted-foreground break-words mt-1",enableFileReferences:!1}):s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap break-words mt-1",children:l(_t?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),xs&&Ve.draft?s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.draftMustBeReady")}):null,xs?null:s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.noMergePermission")})]}),s.jsxs("div",{className:"order-first w-full flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Ve.state==="open"?se?s.jsxs(s.Fragment,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{ee(!1),Fe(Ve.title||""),he(Ve.body||"")},disabled:Se,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(D,{name:"close",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>Qe(Ve),disabled:Se||!Be.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:Se?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"check",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>ee(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(D,{name:"edit",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,ts?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:jt,disabled:Je,"aria-label":l("gitView.pr.actions.openChecksAria"),children:Je?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"information",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,ts?.failure?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Xt,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(D,{name:"error-warning",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:xt,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(D,{name:"chat-4",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:Qt,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(D,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),xs&&Ve.draft&&Ve.state==="open"?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>at(Ve),disabled:ge||ke||Se||se,"aria-label":l("gitView.pr.actions.markReadyAria"),children:ge?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.markReady")})})]}):null]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:xs?s.jsxs(s.Fragment,{children:[s.jsxs($n,{value:ne,onValueChange:we=>Y(we),disabled:ke||Ve.state!=="open",children:[s.jsx(zn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(Nn,{})}),s.jsxs(Wn,{children:[s.jsx(Ls,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(Ls,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(Ls,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>qe(Ve),disabled:ke||ge||Ve.state!=="open"||Ve.draft||Se||se,"aria-label":l("gitView.pr.actions.mergePrAria"),children:ke?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"git-merge",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.mergePr")})})]})]}):null})]})]})}):s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.pr.createTitle")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," ",s.jsx("span",{className:"opacity-60",children:"(local)"})," → ",E," ",s.jsxs("span",{className:"opacity-60",children:["(",G&&ve?"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(D,{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=>P(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")}),le.length>0?s.jsxs($n,{value:E,onValueChange:Z,children:[s.jsx(zn,{className:"h-9",children:s.jsx(Nn,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(Wn,{children:le.map(we=>s.jsx(Ls,{value:we,children:we},we))})]}):s.jsx(vn,{value:E,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(ki,{value:T,onChange:we=>L(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:()=>B(we=>!we),onKeyDown:we=>{(we.key===" "||we.key==="Enter")&&(we.preventDefault(),B(tt=>!tt))},children:[s.jsx(Ti,{size:"sm",checked:R,onChange:we=>B(we),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),y?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx($e,{variant:"outline",size:"sm",onClick:()=>U(!0),children:V.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),V.trim()&&s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("span",{className:"inline-flex items-center rounded-full bg-[var(--interactive-selection)] px-2 py-0.5 text-xs text-[var(--interactive-selection-foreground)]",children:l("gitView.pr.additionalContext.added")})})]}):s.jsxs(eo,{open:Ae,onOpenChange:pe,children:[s.jsxs(Bo,{className:"flex w-full items-center justify-between rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2 hover:bg-[var(--interactive-hover)]",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx("span",{className:"typography-micro text-[var(--primary-base)]",children:Ae?l("gitView.pr.actions.hide"):V.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(to,{children:s.jsxs("div",{className:"mt-2 space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:[s.jsx(ki,{value:V,onChange:we=>_(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:()=>U(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx($e,{size:"sm",onClick:()=>U(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(ki,{value:V,onChange:we=>_(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:Ct,disabled:H||ae,children:[H?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{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:ds,disabled:ae||!ks||!E.trim()||!G&&E.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:ae?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx($s,{open:ie,onOpenChange:Oe,children:s.jsxs(_s,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(Hs,{children:[s.jsxs(Us,{className:"flex items-center gap-2",children:[s.jsx(D,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(on,{children:Ve?l("gitView.pr.numberLabel",{number:Ve.number}):l("gitView.pullRequest.title")})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[Je?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Je?null:s.jsx("div",{className:"space-y-3",children:Array.isArray(Ge?.checkRuns)&&Ge?.checkRuns.length>0?Ge.checkRuns.map((we,tt)=>{const dt=`${we.id??"run"}:${we.job?.jobId??"job"}:${we.name}:${tt}`;return s.jsx("div",{className:"p-1",children:Kt(we)},dt)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx($s,{open:_e,onOpenChange:Ye,children:s.jsxs(_s,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(Hs,{children:s.jsxs(Us,{className:"flex items-center gap-2",children:[s.jsx(D,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),Ve?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:Ve.number})}):null]})}),s.jsxs(za,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[kt?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,kt?null:s.jsx("div",{className:"space-y-4",children:Bt.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Bt.map((we,tt)=>{const dt=(we.authorName||"?").charAt(0).toUpperCase(),It=tt===Bt.length-1;return s.jsxs("div",{className:"relative pl-10 pb-5 last:pb-0",children:[It?null:s.jsx("div",{className:"absolute left-4 top-[2.375rem] bottom-[0.375rem] w-px bg-border/60"}),s.jsx("div",{className:"absolute left-0 top-0 z-10 flex size-8 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-surface-elevated text-xs text-muted-foreground",children:we.avatarUrl?s.jsx("img",{src:we.avatarUrl,alt:we.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:dt})}),s.jsxs("div",{className:"rounded-lg bg-surface-elevated px-3 pt-0 pb-3 space-y-2",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1 typography-micro text-muted-foreground sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-1 sm:gap-y-1",children:[s.jsxs("span",{className:"text-foreground whitespace-nowrap",children:[we.authorName,we.authorLogin&&we.authorLogin!==we.authorName?` · @${we.authorLogin}`:""]}),we.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:rs(we.createdAt)}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs($e,{variant:"ghost",size:"sm",className:"h-6 px-0 has-[>svg]:px-0 sm:px-2 sm:has-[>svg]:px-2.5 text-[var(--status-success)] hover:bg-[var(--status-success-background)] hover:text-[var(--status-success)] justify-start",onClick:()=>{vs(we)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(D,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[we.context,we.path?` · ${we.path}`:"",we.line?`:${we.line}`:""]}),s.jsx(Po,{content:as(we.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",Ut].filter(Boolean).join(" "),enableFileReferences:!1})]})]},we.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},Ow=t=>{const e=mt.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}=Nt(),g=ut(Bw),b=ut(Vw),p=ci(_w),x=ci($w),y=Ee(zw),[h,C]=i.useState(!1),[w,S]=i.useState(null),[j,k]=i.useState(null);let v,A;e[2]!==a||e[3]!==n||e[4]!==f?(v=()=>{!n||!a||(C(!0),k(null),S(null),Xp(a).then(G=>{S(G)}).catch(G=>{const $=G instanceof Error?G.message:f("gitView.conflict.loadFailed");k($)}).finally(()=>{C(!1)}))},A=[n,a,f],e[2]=a,e[3]=n,e[4]=f,e[5]=v,e[6]=A):(v=e[5],A=e[6]),i.useEffect(v,A);let I;e[7]!==w||e[8]!==a||e[9]!==c?(I=async()=>{if(!w)return null;const G=c==="merge"?"merge":"rebase",$=w.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),ve=c==="merge"?"git commit --no-edit":"git rebase --continue",be=await Tn("git.conflict.resolve.visible",{operation_label:G,head_ref:$}),z=await Tn("git.conflict.resolve.instructions",{operation_label:G,directory:a,operation:c,head_info:w.headInfo||"N/A",continue_cmd:ve}),xe=`${G} 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:be,instructionsText:z,payloadText:xe}},e[7]=w,e[8]=a,e[9]=c,e[10]=I):I=e[10];const N=I;let O;e[11]!==l||e[12]!==r?(O=()=>{l(),r(!1)},e[11]=l,e[12]=r,e[13]=O):O=e[13];const P=O;let T;e[14]!==d||e[15]!==r?(T=()=>{d?.(),r(!1)},e[14]=d,e[15]=r,e[16]=T):T=e[16];const L=T;let R;e[17]!==N||e[18]!==b||e[19]!==d||e[20]!==r||e[21]!==y||e[22]!==p||e[23]!==x||e[24]!==f?(R=async()=>{const G=await N();if(!G){ce.error(f("gitView.conflict.noDetailsAvailable"));return}if(!b){ce.error(f("gitView.conflict.noActiveSession"),{description:f("gitView.conflict.noActiveSessionDescription")});return}p(G.visibleText,"replace"),x([{text:G.instructionsText,synthetic:!0},{text:G.payloadText,synthetic:!0}]),y("chat"),d?.(),r(!1)},e[17]=N,e[18]=b,e[19]=d,e[20]=r,e[21]=y,e[22]=p,e[23]=x,e[24]=f,e[25]=R):R=e[25];const B=R;let V;e[26]!==N||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==g||e[31]!==y||e[32]!==f?(V=async()=>{const G=await N();if(!G){ce.error(f("gitView.conflict.noDetailsAvailable"));return}g({directoryOverride:a,initialPrompt:G.visibleText,syntheticParts:[{text:G.instructionsText,synthetic:!0},{text:G.payloadText,synthetic:!0}]}),y("chat"),d?.(),r(!1)},e[26]=N,e[27]=a,e[28]=d,e[29]=r,e[30]=g,e[31]=y,e[32]=f,e[33]=V):V=e[33];const _=V;let E,Z,ne,Y,H,re,ae,me,Se,te,ke,Q,ge,F,se,ee,Ne,De,Be,Fe,Me,he;if(e[34]!==w||e[35]!==m||e[36]!==b||e[37]!==P||e[38]!==L||e[39]!==B||e[40]!==_||e[41]!==h||e[42]!==j||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==f){const G=f(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),$=w?.unmergedFiles||m;ne=$s,Me=n,he=r,Z=_s,Fe="max-w-md w-[calc(100vw-2rem)]",F="flex flex-col gap-4 overflow-hidden";let ve;e[69]===Symbol.for("react.memo_cache_sentinel")?(ve=s.jsx(D,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=ve):ve=e[69];const be=s.jsxs("div",{className:"flex items-center gap-2",children:[ve,s.jsx(Us,{children:f("gitView.conflict.detectedTitle",{operation:G})})]});let z;e[70]!==c||e[71]!==f?(z=f("gitView.conflict.detectedDescription",{operation:c}),e[70]=c,e[71]=f,e[72]=z):z=e[72];let xe;e[73]!==z?(xe=s.jsx(on,{children:z}),e[73]=z,e[74]=xe):xe=e[74],e[75]!==be||e[76]!==xe?(se=s.jsxs(Hs,{children:[be,xe]}),e[75]=be,e[76]=xe,e[77]=se):se=e[77],e[78]!==h||e[79]!==f?(ee=h&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:f("gitView.conflict.loading")})]}),e[78]=h,e[79]=f,e[80]=ee):ee=e[80],e[81]!==j||e[82]!==f?(Ne=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]=Ne):Ne=e[83],e[84]!==$||e[85]!==f?(De=$.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:$.length})]}),s.jsx("div",{className:"bg-[var(--surface-elevated)] rounded-lg p-3 max-h-40 overflow-y-auto overflow-x-hidden",children:s.jsx("ul",{className:"space-y-1",children:$.map(Ww)})})]}),e[84]=$,e[85]=f,e[86]=De):De=e[86],e[87]!==w||e[88]!==f?(Be=w?.headInfo&&s.jsxs("div",{className:"space-y-1 overflow-hidden",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:f("gitView.conflict.headInfo")}),s.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:w.headInfo})]}),e[87]=w,e[88]=f,e[89]=Be):Be=e[89],ke="flex flex-col gap-2 pt-2";let je;e[90]!==_?(je=()=>{_()},e[90]=_,e[91]=je):je=e[91];const K=h||!w;let ye;e[92]!==h?(ye=h?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"add",className:"size-4"}),e[92]=h,e[93]=ye):ye=e[93];let Le;e[94]!==f?(Le=f("gitView.conflict.resolveNewSession"),e[94]=f,e[95]=Le):Le=e[95],e[96]!==je||e[97]!==K||e[98]!==ye||e[99]!==Le?(Q=s.jsxs($e,{variant:"default",onClick:je,disabled:K,className:"w-full gap-2",children:[ye,Le]}),e[96]=je,e[97]=K,e[98]=ye,e[99]=Le,e[100]=Q):Q=e[100];let Re;e[101]!==B?(Re=()=>{B()},e[101]=B,e[102]=Re):Re=e[102];const X=h||!w||!b;let M;e[103]!==h?(M=h?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"chat-1",className:"size-4"}),e[103]=h,e[104]=M):M=e[104];let le;e[105]!==f?(le=f("gitView.conflict.resolveCurrentSession"),e[105]=f,e[106]=le):le=e[106],e[107]!==Re||e[108]!==X||e[109]!==M||e[110]!==le?(ge=s.jsxs($e,{variant:"outline",onClick:Re,disabled:X,className:"w-full gap-2",children:[M,le]}),e[107]=Re,e[108]=X,e[109]=M,e[110]=le,e[111]=ge):ge=e[111],Se="flex gap-2 pt-1";let ie;e[112]!==f?(ie=f("gitView.conflict.continueLater"),e[112]=f,e[113]=ie):ie=e[113],e[114]!==L||e[115]!==ie?(te=s.jsx($e,{variant:"ghost",size:"sm",onClick:L,className:"flex-1",children:ie}),e[114]=L,e[115]=ie,e[116]=te):te=e[116],E=$e,Y="destructive",H="sm",re=P,ae="flex-1",me=f("gitView.conflict.abortOperation",{operation:G}),e[34]=w,e[35]=m,e[36]=b,e[37]=P,e[38]=L,e[39]=B,e[40]=_,e[41]=h,e[42]=j,e[43]=r,e[44]=n,e[45]=c,e[46]=f,e[47]=E,e[48]=Z,e[49]=ne,e[50]=Y,e[51]=H,e[52]=re,e[53]=ae,e[54]=me,e[55]=Se,e[56]=te,e[57]=ke,e[58]=Q,e[59]=ge,e[60]=F,e[61]=se,e[62]=ee,e[63]=Ne,e[64]=De,e[65]=Be,e[66]=Fe,e[67]=Me,e[68]=he}else E=e[47],Z=e[48],ne=e[49],Y=e[50],H=e[51],re=e[52],ae=e[53],me=e[54],Se=e[55],te=e[56],ke=e[57],Q=e[58],ge=e[59],F=e[60],se=e[61],ee=e[62],Ne=e[63],De=e[64],Be=e[65],Fe=e[66],Me=e[67],he=e[68];let Ae;e[117]!==E||e[118]!==Y||e[119]!==H||e[120]!==re||e[121]!==ae||e[122]!==me?(Ae=s.jsx(E,{variant:Y,size:H,onClick:re,className:ae,children:me}),e[117]=E,e[118]=Y,e[119]=H,e[120]=re,e[121]=ae,e[122]=me,e[123]=Ae):Ae=e[123];let pe;e[124]!==Se||e[125]!==te||e[126]!==Ae?(pe=s.jsxs("div",{className:Se,children:[te,Ae]}),e[124]=Se,e[125]=te,e[126]=Ae,e[127]=pe):pe=e[127];let ue;e[128]!==ke||e[129]!==Q||e[130]!==ge||e[131]!==pe?(ue=s.jsxs("div",{className:ke,children:[Q,ge,pe]}),e[128]=ke,e[129]=Q,e[130]=ge,e[131]=pe,e[132]=ue):ue=e[132];let U;e[133]!==F||e[134]!==se||e[135]!==ee||e[136]!==Ne||e[137]!==De||e[138]!==Be||e[139]!==ue?(U=s.jsxs("div",{className:F,children:[se,ee,Ne,De,Be,ue]}),e[133]=F,e[134]=se,e[135]=ee,e[136]=Ne,e[137]=De,e[138]=Be,e[139]=ue,e[140]=U):U=e[140];let fe;e[141]!==Z||e[142]!==Fe||e[143]!==U?(fe=s.jsx(Z,{className:Fe,children:U}),e[141]=Z,e[142]=Fe,e[143]=U,e[144]=fe):fe=e[144];let de;return e[145]!==ne||e[146]!==Me||e[147]!==he||e[148]!==fe?(de=s.jsx(ne,{open:Me,onOpenChange:he,children:fe}),e[145]=ne,e[146]=Me,e[147]=he,e[148]=fe,e[149]=de):de=e[149],de};function Bw(t){return t.openNewSessionDraft}function Vw(t){return t.currentSessionId}function _w(t){return t.setPendingInputText}function $w(t){return t.setPendingSyntheticParts}function zw(t){return t.setActiveMainTab}function Ww(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const Uw=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=Nt(),[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(b){const p=b instanceof Error?b.message:`Failed to ${n}`;ce.error(p)}finally{u(!1)}},g=()=>{d||e(!1)};return s.jsx($s,{open:t,onOpenChange:d?void 0:e,children:s.jsxs(_s,{className:"max-w-md",children:[s.jsxs(Hs,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(D,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(Us,{children:a("gitView.stash.title")})]}),s.jsx(on,{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(Ti,{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(ir,{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(D,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:m})})]})]})})},Hw=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=Nt(),[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 b=async()=>{u("continue");try{await n()}finally{u(null)}},p=async()=>{u("abort");try{await r()}finally{u(null)}},x=d!==null,y=l(g==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),h=g==="merge"?"git-merge":"git-branch";let C="";return t?C=t.message?l("gitView.operation.mergingMessage",{message:t.message}):l("gitView.operation.mergeInProgressWithHead",{head:t.head}):e&&(C=e.headName?l("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):l("gitView.operation.rebaseInProgress")),s.jsx("div",{className:"bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[s.jsx(D,{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:y})}),C&&s.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:C})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&o&&s.jsxs($e,{variant:"outline",size:"sm",onClick:o,disabled:x||c,className:"gap-1.5",children:[s.jsx(D,{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(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs($e,{variant:"default",size:"sm",onClick:b,disabled:x||c,className:"gap-1.5",children:[d==="continue"?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{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")})]})})},Gw=t=>{const e=mt.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,b=l===void 0?!1:l,p=d===void 0?!1:d,x=u===void 0?[]:u,y=f===void 0?"dialog":f,{t:h}=Nt(),[C,w]=i.useState(!1),[S,j]=i.useState("merge"),[k,v]=i.useState(null),[A,I]=i.useState(!1),[N,O]=i.useState(""),P=i.useRef(null),T=i.useRef(null),L=b||p,R=n||h("gitView.branch.currentBranchFallback"),B=x.length>0&&x.every(Kw),V=x.some(qw);let _;e[0]===Symbol.for("react.memo_cache_sentinel")?(_=()=>{T.current&&(T.current.scrollTop=T.current.scrollHeight)},e[0]=_):_=e[0],i.useEffect(_,[x]);let E;if(e[1]!==N||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Re=N.toLowerCase();let X;e[6]!==o?(X=new Set(o.map(Yw).filter(Boolean)),e[6]=o,e[7]=X):X=e[7];const M=X;let le;e[8]!==n||e[9]!==M?(le=Oe=>Oe!==n&&!M.has(Oe),e[8]=n,e[9]=M,e[10]=le):le=e[10];const ie=r.filter(le);if(!Re){E=ie;break e}E=ie.filter(Oe=>Oe.toLowerCase().includes(Re))}e[1]=N,e[2]=n,e[3]=r,e[4]=o,e[5]=E}else E=e[5];const Z=E;let ne;if(e[11]!==N||e[12]!==o){e:{const Re=N.toLowerCase();if(!Re){ne=o;break e}ne=o.filter(X=>X.toLowerCase().includes(Re))}e[11]=N,e[12]=o,e[13]=ne}else ne=e[13];const Y=ne;let H;e[14]!==g||e[15]!==r||e[16]!==o?(H=()=>g&&(o.includes(g)||r.includes(g))?g:null,e[14]=g,e[15]=r,e[16]=o,e[17]=H):H=e[17];const re=H;let ae;e[18]!==re||e[19]!==w?(ae=()=>{w(!0),v(re()),j("merge"),O("")},e[18]=re,e[19]=w,e[20]=ae):ae=e[20];const me=ae;let Se;e[21]===Symbol.for("react.memo_cache_sentinel")?(Se=Re=>{v(Re),I(!1),O("")},e[21]=Se):Se=e[21];const te=Se;let ke;e[22]!==a||e[23]!==c||e[24]!==S||e[25]!==k?(ke=()=>{k&&(S==="merge"?a(k):c(k))},e[22]=a,e[23]=c,e[24]=S,e[25]=k,e[26]=ke):ke=e[26];const Q=ke;let ge;e[27]!==p||e[28]!==w?(ge=()=>{p||(v(null),j("merge"),O(""),w(!1))},e[27]=p,e[28]=w,e[29]=ge):ge=e[29];const F=ge,se=()=>{p&&!B||(B&&m?.(),v(null),j("merge"),O(""),w(!1))};let ee,Ne;e[30]!==A?(ee=()=>{A||O("")},Ne=[A],e[30]=A,e[31]=ee,e[32]=Ne):(ee=e[31],Ne=e[32]),i.useEffect(ee,Ne);let De,Be;e[33]!==y||e[34]!==re||e[35]!==k?(De=()=>{y!=="inline"||k||v(re())},Be=[y,re,k],e[33]=y,e[34]=re,e[35]=k,e[36]=De,e[37]=Be):(De=e[36],Be=e[37]),i.useEffect(De,Be);const he=p?s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{ref:T,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(Qw)})}),B?y==="dialog"?s.jsx(ir,{children:s.jsx($e,{variant:"default",size:"sm",onClick:se,children:h(V?"gitView.common.close":"gitView.common.done")})}):s.jsx("div",{className:"flex justify-end",children:s.jsx($e,{variant:"default",size:"sm",onClick:se,children:h(V?"gitView.common.close":"gitView.common.done")})}):null]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:h("gitView.branch.operation")}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>j("merge"),className:Pe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",S==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(D,{name:"git-merge",className:Pe("size-4",S==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Pe("typography-ui-label",S==="merge"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.merge")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.mergeDescription")})]}),s.jsxs("button",{type:"button",onClick:()=>j("rebase"),className:Pe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",S==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(D,{name:"git-branch",className:Pe("size-4",S==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Pe("typography-ui-label",S==="rebase"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.rebase")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.rebaseDescription")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:S==="merge"?h("gitView.branch.branchToMergeInto",{branch:R}):h("gitView.branch.branchToRebaseOnto")}),s.jsxs(sn,{open:A,onOpenChange:I,modal:!1,children:[s.jsx(en,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:Pe("truncate",!k&&"text-muted-foreground"),children:k||h("gitView.branch.selectBranch")}),s.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(tn,{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:P,placeholder:h("gitView.branch.searchPlaceholder"),value:N,onValueChange:O,onKeyDown:Jw}),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(oi,{heading:h("gitView.branch.localBranches"),children:Z.map(Re=>s.jsx(li,{onSelect:()=>te(Re),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Re})},`local-${Re}`))}),Z.length>0&&Y.length>0?s.jsx(Zp,{}):null,Y.length>0&&s.jsx(oi,{heading:h("gitView.branch.remoteBranches"),children:Y.map(Re=>s.jsx(li,{onSelect:()=>te(Re),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Re})},`remote-${Re}`))})]})]})})]})]}),k?s.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children: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,y==="dialog"?s.jsxs(ir,{className:"gap-2 pt-1",children:[s.jsx($e,{variant:"ghost",size:"sm",onClick:F,children:h("gitView.common.cancel")}),s.jsx($e,{variant:"default",size:"sm",onClick:Q,disabled:!k,className:"gap-1.5",children:S==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(D,{name:"git-merge",className:"size-4"}),h("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(D,{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:F,disabled:L,children:h("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx($e,{variant:"default",size:"sm",onClick:Q,disabled:L||!k,children:h(S==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(y==="inline"){let Re;e[38]!==h?(Re=h("gitView.branch.updateTitle"),e[38]=h,e[39]=Re):Re=e[39];let X;e[40]!==Re?(X=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Re}),e[40]=Re,e[41]=X):X=e[41];let M;e[42]!==h?(M=h("gitView.branch.updateDescriptionPrefix"),e[42]=h,e[43]=M):M=e[43];let le;e[44]!==R?(le=s.jsx("span",{className:"font-mono text-foreground",children:R}),e[44]=R,e[45]=le):le=e[45];let ie;e[46]!==M||e[47]!==le?(ie=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[M," ",le,"."]}),e[46]=M,e[47]=le,e[48]=ie):ie=e[48];let Oe;e[49]!==X||e[50]!==ie?(Oe=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[X,ie]})}),e[49]=X,e[50]=ie,e[51]=Oe):Oe=e[51];let Ge;e[52]!==he?(Ge=s.jsx("div",{className:"pt-3",children:he}),e[52]=he,e[53]=Ge):Ge=e[53];let He;return e[54]!==Oe||e[55]!==Ge?(He=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Oe,Ge]}),e[54]=Oe,e[55]=Ge,e[56]=He):He=e[56],He}let Ae;e[57]!==p?(Ae=p?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{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 U;e[63]!==me||e[64]!==L||e[65]!==Ae||e[66]!==ue?(U=s.jsx(Mt,{asChild:!0,children:s.jsxs($e,{variant:"outline",size:"sm",className:"gap-1.5",onClick:me,disabled:L,children:[Ae,ue]})}),e[63]=me,e[64]=L,e[65]=Ae,e[66]=ue,e[67]=U):U=e[67];let fe;e[68]!==h?(fe=h("gitView.branch.mergeRebaseTooltip"),e[68]=h,e[69]=fe):fe=e[69];let de;e[70]!==fe?(de=s.jsx(Ft,{sideOffset:8,children:fe}),e[70]=fe,e[71]=de):de=e[71];let G;e[72]!==U||e[73]!==de?(G=s.jsxs(Et,{children:[U,de]}),e[72]=U,e[73]=de,e[74]=G):G=e[74];let $;e[75]!==se||e[76]!==w?($=Re=>{Re?w(!0):se()},e[75]=se,e[76]=w,e[77]=$):$=e[77];let ve;e[78]!==h?(ve=h("gitView.branch.updateTitle"),e[78]=h,e[79]=ve):ve=e[79];let be;e[80]!==ve?(be=s.jsx(Us,{children:ve}),e[80]=ve,e[81]=be):be=e[81];let z;e[82]!==V||e[83]!==p||e[84]!==S||e[85]!==B||e[86]!==h||e[87]!==R?(z=p?h(B?V?"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]=V,e[83]=p,e[84]=S,e[85]=B,e[86]=h,e[87]=R,e[88]=z):z=e[88];let xe;e[89]!==z?(xe=s.jsx(on,{children:z}),e[89]=z,e[90]=xe):xe=e[90];let je;e[91]!==be||e[92]!==xe?(je=s.jsxs(Hs,{children:[be,xe]}),e[91]=be,e[92]=xe,e[93]=je):je=e[93];let K;e[94]!==he||e[95]!==je?(K=s.jsxs(_s,{className:"max-w-md",children:[je,he]}),e[94]=he,e[95]=je,e[96]=K):K=e[96];let ye;e[97]!==C||e[98]!==$||e[99]!==K?(ye=s.jsx($s,{open:C,onOpenChange:$,children:K}),e[97]=C,e[98]=$,e[99]=K,e[100]=ye):ye=e[100];let Le;return e[101]!==G||e[102]!==ye?(Le=s.jsxs(s.Fragment,{children:[G,ye]}),e[101]=G,e[102]=ye,e[103]=Le):Le=e[103],Le};function Kw(t){return t.status==="done"||t.status==="error"}function qw(t){return t.status==="error"}function Yw(t){return t.slice(t.indexOf("/")+1)}function Qw(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(D,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(D,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(D,{name:"close",className:"size-3.5 text-destructive"}),t.status==="pending"&&s.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),s.jsx("span",{className:Pe("typography-micro",t.status==="error"&&"text-destructive",t.status==="done"&&"text-muted-foreground",t.status==="running"&&"text-foreground",t.status==="pending"&&"text-muted-foreground/60"),children:t.message})]},e)}function Jw(t){return t.stopPropagation()}const Xw=({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}},Nu="oc.git.actionTab",Zw=15e3,ev=t=>t==="commit"||t==="branch"||t==="pr",tv=40,sv=20,ku={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},nv=(t,e)=>{const n=t.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,o=n.match(r);if(o){const l=o[1],d=ku[l];if(d)return e.find(u=>u.code===d)||null}const a=n.split(" ")[0],c=ku[a];return c&&e.find(l=>l.code===c)||null},rv=20,zi=new Map,iv=(t,e)=>{if(zi.delete(t),zi.set(t,e),zi.size>rv){const n=zi.keys().next().value;n!==void 0&&zi.delete(n)}},$r=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Cu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},ov=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},Xl=({isActive:t})=>{const{t:e}=Nt(),{git:n}=Jn(),r=di(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=ut(q=>q.currentSessionId),u=ut(q=>q.newSessionDraft),m=ut(q=>q.setDraftBootstrapPendingDirectory),f=ut(q=>q.worktreeMetadata),g=ut(q=>q.availableWorktrees),b=$r(r),p=i.useMemo(()=>{if(!b)return;const q=g.find(Ce=>$r(Ce.path)===b);if(q)return q;for(const Ce of f.values())if($r(Ce.path)===b)return Ce},[g,b,f]),x=i.useMemo(()=>{if(d)return f.get(d)??p;if(u?.open)return p},[d,p,u?.open,f]),{profiles:y,globalIdentity:h,defaultGitIdentityId:C,loadProfiles:w,loadGlobalIdentity:S,loadDefaultGitIdentityId:j}=_x(_l(q=>({profiles:q.profiles,globalIdentity:q.globalIdentity,defaultGitIdentityId:q.defaultGitIdentityId,loadProfiles:q.loadProfiles,loadGlobalIdentity:q.loadGlobalIdentity,loadDefaultGitIdentityId:q.loadDefaultGitIdentityId}))),k=Sc(r??null),v=Wa(r??null),A=Gf(q=>d?q.getAttachment(d):void 0),I=A?eg(A):[],N=A&&!A.degraded&&!A.legacy?A.worktreeRoot??void 0:void 0,O=Vy(r,x,v?.current??void 0),P=Jf(r??null),T=tg(r??null),L=sg(r??null),R=Nc(r??null),B=ng(r??null),{setActiveDirectory:V,fetchAll:_,ensureAll:E,fetchStatus:Z,fetchBranches:ne,fetchLog:Y,setLogMaxCount:H,fetchIdentity:re,prefetchDiffs:ae,moveStatusPathsOptimistically:me,restoreStatus:Se,bumpIndexRevision:te}=wn(_l(q=>({setActiveDirectory:q.setActiveDirectory,fetchAll:q.fetchAll,ensureAll:q.ensureAll,fetchStatus:q.fetchStatus,fetchBranches:q.fetchBranches,fetchLog:q.fetchLog,setLogMaxCount:q.setLogMaxCount,fetchIdentity:q.fetchIdentity,prefetchDiffs:q.prefetchDiffs,moveStatusPathsOptimistically:q.moveStatusPathsOptimistically,restoreStatus:q.restoreStatus,bumpIndexRevision:q.bumpIndexRevision}))),ke=Ee(q=>q.isMobile),Q=Ee(q=>q.openContextDiff),ge=Ee(q=>q.navigateToDiff),F=Ee(q=>q.setRightSidebarOpen),se=i.useRef(null),ee=i.useRef(null),Ne=i.useRef(null),De=i.useRef(null),Be=i.useRef(!0);i.useEffect(()=>()=>{Be.current=!1},[]);const Fe=i.useCallback(()=>{ee.current!==null&&(window.clearTimeout(ee.current),ee.current=null)},[]),Me=i.useCallback(q=>{Fe(),ee.current=window.setTimeout(()=>{ee.current=null,$r(q)===$r(r)&&Z(q,n,{silent:!0})},Zw)},[Fe,r,Z,n]);i.useEffect(()=>Fe,[Fe]);const he=i.useCallback(()=>{Ne.current!==null&&(window.clearTimeout(Ne.current),Ne.current=null)},[]),Ae=i.useCallback(()=>{Ne.current===null&&(Ne.current=window.setTimeout(()=>{Ne.current=null,De.current?.()},0))},[]),pe=i.useCallback(async(q,Ce,Te)=>{if(Ce==="stage"){if(n.stageGitFiles){await n.stageGitFiles(q,Te);return}await Promise.all(Te.map(ze=>n.stageGitFile(q,ze)));return}if(n.unstageGitFiles){await n.unstageGitFiles(q,Te);return}await Promise.all(Te.map(ze=>n.unstageGitFile(q,ze)))},[n]),ue=i.useMemo(()=>Xw({runMutation:({directory:q,direction:Ce,paths:Te})=>pe(q,Ce,Te),onMutationComplete:({directory:q})=>{te(q),Me(q)},onMutationError:({directory:q,direction:Ce,rollback:Te},ze)=>{Te?.(),te(q),Me(q);const ft=e(Ce==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");ce.error(ze instanceof Error?ze.message:ft)},onPathsComplete:q=>{ns(Ce=>{const Te=new Set(Ce);return q.forEach(ze=>Te.delete(ze)),Te})},scheduleFlush:Ae}),[te,pe,Ae,Me,e]);i.useEffect(()=>(De.current=ue.flush,()=>{De.current=null}),[ue]),i.useEffect(()=>()=>ue.clear(),[ue]),i.useEffect(()=>he,[he]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let q=!1,Ce=null;const Te=async()=>{try{const ze=await ig(r);if(q)return;a(ze.status),ze.status==="pending"&&(Ce=window.setTimeout(()=>{Te()},500))}catch{q||a(null)}};return Te(),()=>{q=!0,Ce!==null&&window.clearTimeout(Ce)}},[t,r]),i.useEffect(()=>{const q=se.current;se.current=o,!(!r||!n)&&(q==="pending"&&o==="ready"&&(l(!0),_(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(m(null),l(!1)))},[r,_,n,m,o]);const U=$r(u?.bootstrapPendingDirectory??null),fe=!!(r&&U&&U===$r(r)),G=!!(r&&(o==="pending"||fe))||c,$=i.useMemo(()=>r?zi.get(r)??null:null,[r]),ve=ss(q=>q.settingsGitmojiEnabled),[be,z]=i.useState(null),{gitmojis:xe}=By(ve);i.useEffect(()=>{const q=N||O?.projectDirectory;if(!q){z(null);return}let Ce=!1;return Ua(q).then(Te=>{if(Ce)return;const ze=Te.trim();z(ze&&ze!=="HEAD"?ze:null)}).catch(()=>{Ce||z(null)}),()=>{Ce=!0}},[N,O?.projectDirectory]);const[je,K]=i.useState($?.commitMessage??""),[ye,Le]=i.useState([]),[Re,X]=i.useState(!1),M=i.useRef(null),[le,ie]=i.useState(null),[Oe,Ge]=i.useState(!1),[He,Je]=i.useState(null),[rt,bt]=i.useState(25),[yt,_e]=i.useState(!1),{triggerFireworks:Ye}=My(),nt=i.useRef(new Map),wt=i.useRef(0),kt=i.useCallback(()=>{wt.current+=1,Be.current&&_e(!0)},[]),vt=i.useCallback(()=>{wt.current=Math.max(0,wt.current-1),Be.current&&wt.current===0&&_e(!1)},[]),[St,et]=i.useState(new Set),[Ot,ns]=i.useState(new Set),[Wt,Ve]=i.useState(!1),[Ze,_t]=i.useState(0),[jt,xt]=i.useState(!1),[rs,Gt]=i.useState($?.generatedHighlights??[]),Ut=Ot.size>0||ue.size()>0||ue.isRunning(),as=i.useCallback(()=>{const q=M.current;q&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{q.scrollTo({top:q.scrollHeight,behavior:"smooth"})})})},[]),Bt=N||O?.projectDirectory||null,Lt=v?.current||null,Vt=i.useMemo(()=>{const q=v?.tracking;return q?q.startsWith("origin/"):!0},[v?.tracking]),Kt=i.useMemo(()=>{const q=O?.createdFromBranch,Ce=typeof q=="string"?q.trim():"",Te=typeof v?.current=="string"?v.current.trim():"",ze=typeof be=="string"?be.trim():"";return Ce?Ce===Te&&Ce.startsWith("opencode/")&&ze.length>0&&ze!==Ce?ze:Ce:ze||Te||"HEAD"},[O?.createdFromBranch,v,be]),Xt=i.useCallback(()=>{Gt([])},[]),[Qt,vs]=i.useState(new Set),[Dt,$t]=i.useState(new Map),[Ct,ds]=i.useState(new Set),qe=i.useRef(Dt),at=i.useRef(Ct),[Qe,At]=i.useState(null),[Tt,ts]=i.useState(null),[xs,ks]=i.useState(""),[Jt,ls]=i.useState(null),Ps=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(D,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(D,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(D,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[Ts,hn]=i.useState(()=>{if(typeof window>"u")return"commit";const q=window.localStorage.getItem(Nu);return q==="worktree"?"branch":ev(q)?q:"commit"}),[Gs,an]=i.useState([]),[Rn,Os]=i.useState(null),[we,tt]=i.useState(null),[dt,It]=i.useState([]),[Ht,ht]=i.useState(!1),[hs,ps]=i.useState([]),[js,Ss]=i.useState("merge"),[Ds,Un]=i.useState(null),[Es,En]=i.useState(!1),[Hn,Xn]=i.useState(100),Ue=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),os=i.useCallback((q,Ce,Te)=>{if(!Ue||typeof window>"u")return;const ze={directory:q,conflictFiles:Ce,operation:Te};window.localStorage.setItem(Ue,JSON.stringify(ze))},[Ue]),fs=i.useCallback(()=>{!Ue||typeof window>"u"||window.localStorage.removeItem(Ue)},[Ue]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Nu,Ts)},[Ts]),i.useEffect(()=>{if(!Ue||typeof window>"u"||!r)return;const q=window.localStorage.getItem(Ue);if(q)try{const Ce=JSON.parse(q);if(Ce.directory!==r){window.localStorage.removeItem(Ue);return}ps(Ce.conflictFiles??[]),Ss(Ce.operation??"merge"),ht(!0)}catch{window.localStorage.removeItem(Ue)}},[Ue,r]);const[zs,Ks]=i.useState(!1),[Ws,pn]=i.useState("merge"),[Ns,qr]=i.useState(""),Gn=i.useCallback(q=>{ur(q).then(Ce=>{if(Ce.ok){ce.success(e("gitView.toast.commitHashCopied"));return}ce.error(e("gitView.toast.copyFailed"))})},[e]),fr=i.useCallback(q=>{vs(Ce=>{const Te=new Set(Ce);return Te.has(q)?Te.delete(q):Te.add(q),Te})},[]);i.useEffect(()=>{qe.current=Dt},[Dt]),i.useEffect(()=>{at.current=Ct},[Ct]),i.useEffect(()=>{if(!r||!n)return;const q=Array.from(Qt).filter(Te=>!qe.current.has(Te)&&!at.current.has(Te));if(q.length===0)return;let Ce=!1;return ds(Te=>{const ze=new Set(Te);for(const ft of q)ze.add(ft);return at.current=ze,ze}),Promise.all(q.map(Te=>n.getCommitFiles(r,Te).then(ze=>({hash:Te,files:ze.files})).catch(ze=>(console.error("Failed to fetch commit files:",ze),{hash:Te,files:[]})))).then(Te=>{Ce||($t(ze=>{const ft=new Map(ze);for(const{hash:Rt,files:qt}of Te)ft.set(Rt,qt);return qe.current=ft,ft}),ds(ze=>{const ft=new Set(ze);for(const{hash:Rt}of Te)ft.delete(Rt);return at.current=ft,ft}))}),()=>{Ce=!0,ds(Te=>{let ze=!1;const ft=new Set(Te);for(const Rt of q)ft.delete(Rt)&&(ze=!0);return ze?(at.current=ft,ft):Te})}},[Qt,r,n]),i.useEffect(()=>{r&&iv(r,{directory:r,commitMessage:je,generatedHighlights:rs})},[je,r,rs]),i.useEffect(()=>{t&&(w(),S(),j())},[t,w,S,j]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){ts(null);return}let q=!1;return n.getRemoteUrl(r).then(Ce=>{q||ts(Ce)}).catch(()=>{q||ts(null)}),()=>{q=!0}},[t,r,n]);const Kn=i.useCallback(async()=>{if(!r||!n?.getRemotes){an([]);return}try{const q=await n.getRemotes(r);Be.current&&an(q)}catch{Be.current&&an([])}},[r,n]);i.useEffect(()=>{t&&Kn()},[t,Kn]),i.useEffect(()=>{t&&r&&(V(r),E(r,n))},[t,r,V,E,n]),i.useEffect(()=>{if(t&&r)return Pr.onGitRefreshHint(q=>{$r(q.directory)===$r(r)&&Z(r,n)})},[t,r,Z,n]);const gs=i.useCallback(async(q=!0)=>{if(r)try{await Promise.all([Z(r,n),ne(r,n)])}catch(Ce){if(q){const Te=Ce instanceof Error?Ce.message:e("gitView.toast.refreshRepositoryFailed");ce.error(Te)}}},[r,n,Z,ne,e]),Ms=i.useCallback(async()=>{r&&await Y(r,n,rt)},[r,n,Y,rt]),jr=i.useCallback(async()=>{r&&await re(r,n)},[r,n,re]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||k!==!0)return;const q=typeof C=="string"?C.trim():"";if(!q||q==="global"||nt.current.get(r)===q)return;let Te=!1;return(async()=>{try{const ft=await n.hasLocalIdentity?.(r);if(Te||ft===!0)return;kt(),await n.setGitIdentity(r,q),nt.current.set(r,q),await jr()}catch(ft){console.warn("Failed to auto-apply default git identity:",ft)}finally{Te||vt()}})(),()=>{Te=!0}},[t,kt,r,C,vt,n,k,jr]);const jn=i.useMemo(()=>v?[...v.files??[]].sort((Ce,Te)=>Ce.path.localeCompare(Te.path)):[],[v]),ln=i.useMemo(()=>jn.filter(Cu),[jn]),Zn=i.useMemo(()=>jn.filter(ov),[jn]);i.useEffect(()=>{if(!r||jn.length===0)return;const q=[],Ce=new Set,Te=ft=>{!ft||Ce.has(ft)||(Ce.add(ft),q.push(ft))};if(ln.forEach(ft=>Te(ft.path)),ye.forEach(Te),jn.slice(0,sv).forEach(ft=>Te(ft.path)),q.length===0)return;const ze=window.setTimeout(()=>{ae(r,n,q,{maxFiles:tv})},120);return()=>{window.clearTimeout(ze)}},[jn,r,n,ae,ln,ye]);const Mr=q=>q?.pushed[0]?.remote||v?.tracking?.split("/")[0]||is.find(Ce=>Ce.name==="origin")?.name||is[0]?.name||"origin",Yr=async(q,Ce)=>{if(r){ie(q);try{const Te=ze=>{const ft=`${ze.name}/`,Rt=v?.tracking?.startsWith(ft)?v.tracking.slice(ft.length):void 0;return{remote:ze.name,branch:Rt,rebase:!0}};if(q==="fetch"){if(!Ce)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:Ce.name}),ce.success(e("gitView.toast.fetchedFromRemote",{name:Ce.name}))}else if(q==="pull"){if(!Ce)throw new Error("No remote available for pull");const ze=await n.gitPull(r,Te(Ce));ce.success(ze.files.length===1?e("gitView.toast.pulledFilesSingle",{count:ze.files.length,name:Ce.name}):e("gitView.toast.pulledFilesPlural",{count:ze.files.length,name:Ce.name}))}else if(q==="push"){const ze=await n.gitPush(r);ce.success(e("gitView.toast.pushedToUpstream",{name:Mr(ze)}))}else if(q==="sync"){if(!Ce)throw new Error("No remote available for sync");let ze=0,ft=!1;await n.gitFetch(r,{remote:Ce.name});const Rt=await n.getGitStatus(r);if((Rt.behind??0)>0){if((Rt.files?.length??0)>0){ce.error(e("gitView.toast.commitOrStashBeforeSync"));return}ze=(await n.gitPull(r,Te(Ce))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),ft=!0),ze>0&&ft?ce.success(ze===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:ze,name:Ce.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:ze,name:Ce.name})):ze>0?ce.success(ze===1?e("gitView.toast.pulledFilesSingle",{count:ze,name:Ce.name}):e("gitView.toast.pulledFilesPlural",{count:ze,name:Ce.name})):ft?ce.success(e("gitView.toast.pushedToUpstream",{name:Ce.name})):ce.success(e("gitView.toast.alreadyUpToDate"))}await gs(!1),await Ms()}catch(Te){const ze=Te instanceof Error?Te.message:e("gitView.toast.syncActionFailed",{action:q==="sync"?e("gitView.sync.syncChanges"):q==="pull"?e("gitView.sync.pull"):q});ce.error(ze)}finally{ie(null)}}},ui=i.useCallback(async q=>{if(!r)return;const Ce=q.name.trim();if(!Ce){ce.error(e("gitView.toast.remoteNameRequired"));return}if(Ce==="origin"){ce.error(e("gitView.toast.cannotRemoveOriginRemote"));return}Os(Ce);try{await n.removeRemote(r,{remote:Ce}),ce.success(e("gitView.toast.removedRemote",{name:Ce})),await Promise.all([gs(!1),Kn()])}catch(Te){const ze=Te instanceof Error?Te.message:`Failed to remove ${Ce}`;ce.error(ze)}finally{Os(null)}},[r,n,Kn,gs,e]),mr=async(q={})=>{if(!r)return;if(!je.trim()){ce.error(e("gitView.toast.enterCommitMessage"));return}const Ce=ln.map(ze=>ze.path).sort();if(Ce.length===0){ce.error(e("gitView.toast.stageFileToCommit"));return}const Te=q.pushAfter?"commitAndPush":"commit";Je(Te);try{if(await n.createGitCommit(r,je.trim(),{files:Ce,stageFiles:[]}),te(r),ce.success(e("gitView.toast.commitCreated")),K(""),Xt(),await gs(),q.pushAfter){const ze=v?.tracking?.split("/")[0],ft=is.find(Cr=>Cr.name===ze)??is[0];if(!ft)throw new Error(e("mobile.changes.noRemote"));ie("sync");const Rt=`${ft.name}/`,qt=v?.tracking?.startsWith(Rt)?v.tracking.slice(Rt.length):void 0;await n.gitFetch(r,{remote:ft.name});const Yt=await n.getGitStatus(r);if((Yt.behind??0)>0){if((Yt.files?.length??0)>0){ce.error(e("gitView.toast.commitOrStashBeforeSync")),await gs(!1);return}await n.gitPull(r,{remote:ft.name,branch:qt,rebase:!0})}const ys=await n.getGitStatus(r);let pr;(ys.ahead??0)>0&&(pr=await n.gitPush(r)),ce.success(e("gitView.toast.pushedToUpstream",{name:Mr(pr)})),Ye(),await gs(!1)}else await gs(!1);await Ms(),_t(ze=>ze+1)}catch(ze){const ft=ze instanceof Error?ze.message:e("gitView.toast.createCommitFailed");ce.error(ft)}finally{Je(null),q.pushAfter&&ie(null)}},us=i.useCallback(async()=>{if(!r)return;const q=ln.map(Ce=>Ce.path).sort();if(q.length===0){ce.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:q.length}),xt(!0);try{const{message:Ce}=await rg(r,q),Te=Ce.subject?.trim()??"",ze=Array.isArray(Ce.highlights)?Ce.highlights:[];if(Te){let ft=Te;if(ve&&xe.length>0){const Rt=nv(Te,xe);if(Rt){const{code:qt,emoji:Yt}=Rt;!Te.startsWith(qt)&&!Te.startsWith(Yt)&&(ft=`${qt} ${Te}`)}}K(ft)}Gt(ze),as()}catch(Ce){console.error("[git-generation][browser] GitView generate handler failed",{message:Ce instanceof Error?Ce.message:String(Ce),error:Ce});const Te=Ce instanceof Error?Ce.message:e("gitView.toast.generateCommitMessageFailed");ce.error(Te)}finally{xt(!1)}},[r,ln,ve,xe,as,e]),cn=q=>q.reason==="attention"?`${q.attentionReason} in progress`:q.reason==="missing"?"worktree is missing":"worktree is invalid",kn=async(q,Ce)=>{if(!r||!v)return;const Te=rl(A);if(Te.length>0){ce.error(e("gitView.toast.cannotCreateBranch",{reason:cn(Te[0])}));return}const ze=v.current??null,ft=Ce?.name??"origin";try{await n.createBranch(r,q,ze??"HEAD"),ce.success(e("gitView.toast.createdBranch",{name:q})),await n.checkoutBranch(r,q);let Rt=!1;try{await n.gitPush(r,{remote:ft,branch:q,options:["--set-upstream"]}),Rt=!0}catch(qt){const Yt=qt instanceof Error?qt.message:`Unable to push new branch to ${ft}.`;ce.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Yt]})})}await gs(),await Ms(),Rt&&ce.success(e("gitView.toast.upstreamSet",{branch:q,remote:ft}))}catch(Rt){const qt=Rt instanceof Error?Rt.message:e("gitView.toast.createBranchFailed");throw ce.error(qt),Rt}},J=async(q,Ce)=>{if(!r)return;const Te=rl(A);if(Te.length>0){ce.error(e("gitView.toast.cannotRenameBranch",{reason:cn(Te[0])}));return}try{await n.renameBranch(r,q,Ce),ce.success(e("gitView.toast.renamedBranch",{oldName:q,newName:Ce})),await gs(),await Ms()}catch(ze){const ft=ze instanceof Error?ze.message:e("gitView.toast.renameBranchFailed",{oldName:q,newName:Ce});ce.error(ft)}},st=async q=>{if(!r)return;const Ce=rl(A);if(Ce.length>0){ce.error(e("gitView.toast.cannotCheckout",{reason:cn(Ce[0])}));return}const Te=q.replace(/^remotes\//,"");if(v?.current!==Te)try{await n.checkoutBranch(r,Te),ce.success(e("gitView.toast.checkedOut",{name:Te})),await gs(),await Ms()}catch(ze){const ft=ze instanceof Error?ze.message:e("gitView.toast.checkoutFailed",{name:Te});ce.error(ft)}},gt=async q=>{if(r){kt();try{await n.setGitIdentity(r,q.id),ce.success(e("gitView.toast.appliedIdentity",{name:q.name})),await jr()}catch(Ce){const Te=Ce instanceof Error?Ce.message:e("gitView.toast.applyIdentityFailed");ce.error(Te)}finally{vt()}}},Pt=i.useMemo(()=>P?.all?P.all.filter(q=>!q.startsWith("remotes/")).sort():[],[P]),Zt=i.useMemo(()=>P?.all?P.all.filter(q=>q.startsWith("remotes/")).map(q=>q.replace(/^remotes\//,"")).sort():[],[P]),is=i.useMemo(()=>{if(Gs.length>0)return Gs;const q=new Set,Ce=v?.tracking?.trim();Ce&&Ce.includes("/")&&q.add(Ce.split("/")[0]);for(const Te of Zt){const ze=Te.indexOf("/");ze>0&&q.add(Te.slice(0,ze))}return q.size===0&&Tt&&q.add("origin"),Array.from(q).map(Te=>({name:Te,fetchUrl:Tt??"",pushUrl:Tt??""}))},[Gs,Zt,Tt,v?.tracking]),ms=i.useMemo(()=>{const q=new Set(is.map(ft=>ft.name)),Ce=ft=>{if(!ft)return"";let Rt=ft.trim();if(!Rt||Rt==="HEAD")return"";if(Pt.includes(Rt))return Rt;Rt.startsWith("refs/heads/")&&(Rt=Rt.slice(11)),Rt.startsWith("heads/")&&(Rt=Rt.slice(6)),Rt.startsWith("remotes/")&&(Rt=Rt.slice(8));const qt=Rt.indexOf("/");if(qt>0){const Yt=Rt.slice(0,qt);if(q.has(Yt)){const ys=Rt.slice(qt+1).trim();ys&&(Rt=ys)}}return Rt},Te=Ce(typeof O?.createdFromBranch=="string"?O.createdFromBranch:"");if(Te)return Te;const ze=Ce(typeof be=="string"?be:"");return ze||(Pt.includes("main")?"main":Pt.includes("master")?"master":Pt.includes("develop")?"develop":"main")},[is,Pt,be,O?.createdFromBranch]),Fs=i.useMemo(()=>is.map(Te=>Te.name).map(Te=>`${Te}/${ms}`).find(Te=>Zt.includes(Te))??ms,[ms,is,Zt]),qs=i.useMemo(()=>{const q=new Map;h&&q.set(h.id,h);let Ce=null;if(Tt)try{let Te=Tt.trim();Te.startsWith("git@")&&(Te=`https://${Te.slice(4).replace(":","/")}`),Te.endsWith(".git")&&(Te=Te.slice(0,-4));const ze=new URL(Te);Ce=ze.hostname+ze.pathname}catch{}for(const Te of y){if(Te.authType!=="token"){q.set(Te.id,Te);continue}const ze=Te.host;if(!ze){q.set(Te.id,Te);continue}if(!ze.includes("/")){q.set(Te.id,Te);continue}Ce&&Ce===ze&&q.set(Te.id,Te)}return Array.from(q.values())},[y,h,Tt]),er=i.useMemo(()=>{if(L?.userName&&L?.userEmail){const q=y.find(Ce=>Ce.userName===L.userName&&Ce.userEmail===L.userEmail);return q||(h&&h.userName===L.userName&&h.userEmail===L.userEmail?h:{id:"local-config",name:L.userName,userName:L.userName,userEmail:L.userEmail,sshKey:L.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return h??null},[L,y,h]),qn=ln.length,Fr=R||le!==null||He!==null,Bs=v?.current??null,Lr=!!(O&&Bt&&Lt&&Vt),gn=!!(r&&Bs),tr=!!Bs,xn=Lr&&Bt&&Lt&&O?{repoRoot:Bt,sourceBranch:Lt,worktreeMetadata:O}:null,Mn=i.useMemo(()=>!gn||!r||!Bs?null:{directory:r,branch:Bs},[gn,Bs,r]);i.useEffect(()=>{if(!r||!n||!T?.all?.length||!Bs||!ms||Bs===ms){At(null);return}let q=!1;return(async()=>{try{const Te=await n.getGitLog(r,{from:ms,to:"HEAD",maxCount:rt});if(q)return;const ze=new Set((Te?.all??[]).map(Rt=>Rt.hash).filter(Rt=>typeof Rt=="string"&&Rt.length>0));if(ze.size===0){At(null);return}const ft=T.all.findIndex(Rt=>!ze.has(Rt.hash));if(ft===0){At(null);return}if(ft===-1){At({insertBeforeIndex:T.all.length,branchName:Bs,direction:"up"});return}At({insertBeforeIndex:ft,branchName:Bs,direction:"up"})}catch{q||At(null)}})(),()=>{q=!0}},[ms,Bs,r,n,T,rt]),i.useEffect(()=>{Un(null)},[r]),i.useEffect(()=>{if(Jt!=="graph"||!r){Jt!=="graph"&&Un(null);return}let q=!1;return En(!0),n.getGitLog(r,{maxCount:Hn,all:!0}).then(Ce=>{q||Un(Ce)}).catch(Ce=>{console.error("Failed to fetch graph log:",Ce)}).finally(()=>{q||En(!1)}),()=>{q=!0}},[Jt,r,Hn,n]);const bn=i.useCallback((q,Ce)=>{if(!r||q.length===0)return;const Te=Array.from(new Set(q));ns(ft=>{const Rt=new Set(ft);return Te.forEach(qt=>Rt.add(qt)),Rt});const ze=me(r,Te,Ce);ue.enqueue({directory:r,direction:Ce,paths:new Set(Te),rollback:()=>Se(r,ze)}),Ae()},[r,ue,me,Se,Ae]),or=i.useCallback(async q=>{if(r){et(Ce=>{const Te=new Set(Ce);return Te.add(q),Te});try{await n.revertGitFile(r,q,{scope:"working"}),ce.success(e("gitView.toast.revertedFile",{path:q})),await gs(!1)}catch(Ce){const Te=Ce instanceof Error?Ce.message:e("gitView.toast.revertFailed");ce.error(Te)}finally{et(Ce=>{const Te=new Set(Ce);return Te.delete(q),Te})}}},[r,gs,n,e]),Cn=i.useCallback(async(q,Ce,Te="all")=>{if(!r||q.length===0)return;const ze=Array.from(new Set(q));if(Wt||ze.some(Yt=>St.has(Yt)))return;const ft=new Set(ln.map(Yt=>Yt.path)),Rt=Te==="all"&&ze.some(Yt=>ft.has(Yt));Ce&&Ve(!0),et(Yt=>{const ys=new Set(Yt);return ze.forEach(pr=>ys.add(pr)),ys});const qt=[];try{if(await Promise.all(ze.map(async Yt=>{try{await n.revertGitFile(r,Yt,{scope:Te})}catch(ys){qt.push({path:Yt,message:ys instanceof Error?ys.message:e("gitView.toast.revertFailed")})}})),Rt&&qt.length<ze.length&&te(r),await gs(!1),qt.length===0)ce.success(ze.length===1?e("gitView.toast.revertedFilesSingle",{count:ze.length}):e("gitView.toast.revertedFilesPlural",{count:ze.length}));else if(qt.length===ze.length)ce.error(qt[0]?.message||e("gitView.toast.revertFailed"));else{const Yt=ze.length-qt.length;ce.warning(Yt===1?e("gitView.toast.revertedSomeSingle",{success:Yt,failed:qt.length}):e("gitView.toast.revertedSomePlural",{success:Yt,failed:qt.length}))}}finally{et(Yt=>{const ys=new Set(Yt);return ze.forEach(pr=>ys.delete(pr)),ys}),Ce&&Ve(!1)}},[te,r,n,Wt,gs,St,ln,e]),Sr=i.useCallback(async q=>{await Cn(q,!0)},[Cn]),Or=i.useCallback(async q=>{await Cn(q,!1,"working")},[Cn]),Nr=i.useCallback((q,Ce)=>{if(r&&!ke){Q(r,q,Ce);return}ge(q,Ce),ke&&F(!1)},[r,ke,ge,Q,F]),Ei=i.useCallback(()=>Ge(!0),[]),fi=i.useMemo(()=>{const q=[];return ln.length>0&&q.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:ln,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:Ce=>e("gitView.changes.unstageFileAria",{path:Ce}),onActionFile:Ce=>{bn([Ce],"unstage")},onActionAll:Ce=>{bn(Ce,"unstage")},onViewDiff:Ce=>Nr(Ce,!0),onRevertFile:or,showRevertActions:!1,accent:!0}),Zn.length>0&&q.push({id:"unstaged",title:e("gitView.changes.title"),entries:Zn,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:Ce=>e("gitView.changes.stageFileAria",{path:Ce}),onActionFile:Ce=>{bn([Ce],"stage")},onActionAll:Ce=>{bn(Ce,"stage")},onViewDiff:Ce=>Nr(Ce,!1),onRevertFile:or}),q},[or,Nr,bn,ln,e,Zn]),Mi=i.useCallback(q=>{if(q.length===0)return;const Ce=q.map(Te=>Te.trim()).filter(Boolean);if(Ce.length===0){Xt();return}K(Te=>{const ze=Te.trim(),ft=ze.length>0?`
11
-
12
- `:"";return`${ze}${ft}${Ce.join(`
13
- `)}`.trim()}),Xt()},[Xt]),nn=i.useCallback((q,Ce)=>{const Te=Ce||q;K(ze=>{const ft=ze.trimStart();return ft.startsWith(q)||Ce&&ft.startsWith(Ce)?ze:`${Te.endsWith(" ")?Te:`${Te} `}${ze}`.trimStart()}),ks(""),X(!1)},[]),hr=i.useCallback(q=>{const Ce=q instanceof Error?q.message.toLowerCase():"";return Ce.includes("uncommitted changes")||Ce.includes("local changes")||Ce.includes("your local changes would be overwritten")||Ce.includes("please commit your changes or stash them")||Ce.includes("cannot rebase: you have unstaged changes")||Ce.includes("error: cannot pull with rebase")},[]),Ys=i.useCallback((q,Ce)=>{It(Te=>[...Te,{message:q,status:Ce,timestamp:Date.now()}])},[]),yn=i.useCallback((q,Ce)=>{It(Te=>{if(Te.length===0)return Te;const ze=[...Te];return ze[ze.length-1]={...ze[ze.length-1],status:q,...Ce?{message:Ce}:{}},ze})},[]),Qr=i.useCallback(()=>{It([])},[]),co=i.useCallback(()=>{It([]),tt(null)},[]),Br=i.useCallback(q=>{const Ce=q.trim(),Te=new Set(is.map(ft=>ft.name)),ze=Ce.indexOf("/");if(ze>0){const ft=Ce.slice(0,ze),Rt=Ce.slice(ze+1);if(Te.has(ft)&&Rt)return{branch:Ce,remote:ft,remoteBranch:Rt}}for(const ft of is){const Rt=`${ft.name}/${Ce}`;if(Zt.includes(Rt))return{branch:Rt,remote:ft.name,remoteBranch:Ce}}return{branch:Ce,remote:null,remoteBranch:null}},[is,Zt]),ar=i.useCallback(async q=>{if(!r)return;tt("merge"),Qr();const Ce=v?.current,Te=Br(q);try{Te.remote&&Te.remoteBranch&&(Ys(`Fetching ${Te.remote}/${Te.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Te.remote,branch:Te.remoteBranch}),yn("done",`Fetched ${Te.remote}/${Te.remoteBranch}`)),Ys(`Merging ${Te.branch} into ${Ce}...`,"running");const ze=await n.merge(r,{branch:Te.branch});ze.conflict?(yn("error","Merge conflicts detected"),ps(ze.conflictFiles??[]),Ss("merge"),ht(!0),os(r,ze.conflictFiles??[],"merge")):(yn("done",`Merged ${Te.branch} into ${Ce}`),fs(),Ys("Refreshing repository status...","running"),await gs(),await Ms(),yn("done","Repository status updated"))}catch(ze){if(hr(ze))yn("error","Uncommitted changes detected"),pn("merge"),qr(Te.branch),Ks(!0);else{const ft=ze instanceof Error?ze.message:`Failed to merge ${Te.branch}`;yn("error",ft)}}},[r,n,v,Br,gs,Ms,hr,os,fs,Ys,yn,Qr]),kr=i.useCallback(async q=>{if(!r)return;tt("rebase"),Qr();const Ce=v?.current,Te=Br(q);try{Te.remote&&Te.remoteBranch&&(Ys(`Fetching ${Te.remote}/${Te.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Te.remote,branch:Te.remoteBranch}),yn("done",`Fetched ${Te.remote}/${Te.remoteBranch}`)),Ys(`Rebasing ${Ce} onto ${Te.branch}...`,"running");const ze=await n.rebase(r,{onto:Te.branch});ze.conflict?(yn("error","Rebase conflicts detected"),ps(ze.conflictFiles??[]),Ss("rebase"),ht(!0),os(r,ze.conflictFiles??[],"rebase")):(yn("done",`Rebased ${Ce} onto ${Te.branch}`),fs(),Ys("Refreshing repository status...","running"),await gs(),await Ms(),yn("done","Repository status updated"))}catch(ze){if(hr(ze))yn("error","Uncommitted changes detected"),pn("rebase"),qr(Te.branch),Ks(!0);else{const ft=ze instanceof Error?ze.message:`Failed to rebase onto ${Te.branch}`;yn("error",ft)}}},[r,n,v,Br,gs,Ms,hr,os,fs,Ys,yn,Qr]),dn=i.useCallback(async()=>{if(r)try{js==="merge"?(await n.abortMerge(r),ce.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),ce.success(e("gitView.toast.rebaseAborted"))),fs(),await gs(),await Ms()}catch(q){const Ce=q instanceof Error?q.message:`Failed to abort ${js}`;ce.error(Ce)}},[r,n,js,gs,Ms,fs,e]),lr=i.useMemo(()=>v?.files?v.files.some(q=>q.index==="U"||q.working_dir==="U"||q.index==="A"&&q.working_dir==="A"||q.index==="D"&&q.working_dir==="D"):!1,[v?.files]),Fi=i.useCallback(async()=>{if(r)try{const q=!!v?.mergeInProgress?.head,Ce=!!(v?.rebaseInProgress?.headName||v?.rebaseInProgress?.onto);if(q){const Te=await n.continueMerge(r);Te.conflict?(ps(Te.conflictFiles??[]),Ss("merge"),ht(!0),os(r,Te.conflictFiles??[],"merge"),ce.error(e("gitView.toast.mergeConflictsDetected"))):(fs(),ce.success(e("gitView.toast.mergeCompleted")),await gs(),await Ms())}else if(Ce){const Te=await n.continueRebase(r);Te.conflict?(ps(Te.conflictFiles??[]),Ss("rebase"),ht(!0),os(r,Te.conflictFiles??[],"rebase"),ce.error(e("gitView.toast.rebaseConflictsDetected"))):(fs(),ce.success(e("gitView.toast.rebaseStepCompleted")),await gs(),await Ms())}}catch(q){const Ce=q instanceof Error?q.message:e("gitView.toast.continueOperationFailed");ce.error(Ce)}},[r,n,v,gs,Ms,os,fs,e]),Li=i.useCallback(async()=>{if(r)try{!!v?.mergeInProgress?.head?(await n.abortMerge(r),ce.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),ce.success(e("gitView.toast.rebaseAborted"))),fs(),await gs(),await Ms()}catch(q){const Ce=q instanceof Error?q.message:e("gitView.toast.abortOperationFailed");ce.error(Ce)}},[r,n,v,gs,Ms,fs,e]),Vr=i.useCallback(()=>{if(!r)return;const Ce=!!v?.mergeInProgress?.head?"merge":"rebase",Te=v?.files?.filter(ze=>ze.index==="U"||ze.working_dir==="U").map(ze=>ze.path)??[];Te.length>0&&ps(Te),Ss(Ce),ht(!0)},[r,v]),mi=i.useCallback(async q=>{if(!r)return;const Ce=v?.current,Te=Ws,ze=Ns,ft=(v?.files??[]).some(Cu);try{await n.stash(r,{message:`Auto-stash before ${Te} with ${ze}`,includeUntracked:!0}),ft&&te(r)}catch(Yt){const ys=Yt instanceof Error?Yt.message:"Failed to stash changes";ce.error(ys);return}let Rt=!1,qt=!1;try{if(Te==="merge"){const Yt=await n.merge(r,{branch:ze});Yt.conflict?(qt=!0,ps(Yt.conflictFiles??[]),Ss("merge"),ht(!0)):(Rt=!0,ce.success(e("gitView.toast.mergedIntoBranch",{branch:ze,currentBranch:Ce||""})))}else{const Yt=await n.rebase(r,{onto:ze});Yt.conflict?(qt=!0,ps(Yt.conflictFiles??[]),Ss("rebase"),ht(!0)):(Rt=!0,ce.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:Ce||"",branch:ze})))}if(q&&Rt)try{await n.stashPop(r),te(r),ce.success(e("gitView.toast.stashedRestored"))}catch(Yt){const ys=Yt instanceof Error?Yt.message:e("gitView.toast.restoreStashFailed");ce.error(ys)}else q&&qt&&ce.info(e("gitView.toast.restoreStashManually"));await gs(),await Ms()}catch(Yt){if(q)try{await n.stashPop(r),te(r)}catch{}throw Yt}},[te,r,n,v,Ws,Ns,gs,Ms,e]),rn=i.useCallback(q=>{bt(q),r&&(H(r,q),Y(r,n,q))},[r,Y,n,H]),Oi=i.useCallback(q=>{Xn(q)},[]),uo=i.useCallback(()=>{ls(null),r&&(Z(r,n),ne(r,n),Y(r,n,rt))},[r,Z,ne,Y,rt,n]),fo=i.useCallback(q=>{if(q.conflict){if(q.operation==="cherry-pick"||q.operation==="revert"){ce.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:q.conflictFiles?.join(", ")??"unknown files"})}),r&&(Z(r,n),ne(r,n),Y(r,n,rt));return}ps(q.conflictFiles??[]),Ss(q.operation),ht(!0),r&&os(r,q.conflictFiles??[],q.operation)}},[e,ps,Ss,ht,os,r,Z,ne,Y,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(D,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):k===!1?G?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(D,{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(D,{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")}),I.includes("open-without-worktree-features")?s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:e("gitView.empty.worktreeFeaturesUnavailable")}):null]}):s.jsxs("div",{className:Pe("flex h-full flex-col overflow-hidden"),children:[s.jsx($x,{status:v,localBranches:Pt,remoteBranches:Zt,branchInfo:P?.branches,syncAction:le,remotes:is,onFetch:q=>Yr("fetch",q),onSync:q=>Yr("sync",q),onRemoveRemote:ui,removingRemoteName:Rn,onCheckoutBranch:st,onCreateBranch:kn,onRenameBranch:J,activeIdentityProfile:er,availableIdentities:qs,onSelectIdentity:gt,isApplyingIdentity:yt,isWorktreeMode:!!O,onOpenHistory:()=>ls("history"),onOpenGraph:()=>ls("graph"),onOpenStashes:Ei,actionTabItems:Ps,activeActionTab:Ts,onSelectActionTab:q=>hn(q)}),r&&(v?.mergeInProgress?.head||v?.rebaseInProgress?.headName||v?.rebaseInProgress?.onto)&&s.jsx(Hw,{mergeInProgress:v?.mergeInProgress,rebaseInProgress:v?.rebaseInProgress,onContinue:Fi,onAbort:Li,onResolveWithAI:Vr,hasUnresolvedConflicts:lr,isLoading:R}),s.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:s.jsx("div",{className:"h-full min-h-0 flex flex-col",children:s.jsx("div",{className:Pe("min-w-0 min-h-0 h-full flex flex-col"),children:s.jsxs(_n,{as:za,ref:M,outerClassName:"flex-1 min-h-0",className:Pe("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[Ts==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(jn?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(zx,{groups:fi,diffStats:v?.diffStats,revertingPaths:St,isRevertingAll:Wt,onVisiblePathsChange:Le,onRevertAll:Sr,onRevertDirectory:Or,headerBackgroundClassName:"bg-background"})}),s.jsx(Wx,{stagedCount:qn,commitMessage:je,onCommitMessageChange:K,generatedHighlights:rs,onInsertHighlights:Mi,onGenerateMessage:us,isGeneratingMessage:jt,onCommit:()=>mr({pushAfter:!1}),onCommitAndPush:()=>mr({pushAfter:!0}),commitAction:He,hasPendingIndexMutation:Ut,gitmojiEnabled:ve,onOpenGitmojiPicker:()=>X(!0)})]}):s.jsx(qy,{onOpenStashes:()=>Ge(!0)})}):null,Ts==="branch"?s.jsx("div",{className:"space-y-4",children:tr?s.jsxs(s.Fragment,{children:[s.jsx(Gw,{mode:"inline",currentBranch:v?.current,localBranches:Pt,remoteBranches:Zt,defaultTargetBranch:Fs,onMerge:ar,onRebase:kr,disabled:Fr,isOperating:we!==null,operationLogs:dt,onOperationComplete:co}),xn?s.jsx(Gy,{repoRoot:xn.repoRoot,sourceBranch:xn.sourceBranch,worktreeMetadata:xn.worktreeMetadata,localBranches:Pt,defaultTargetBranch:Kt,refreshKey:Ze,onRefresh:()=>{r&&(Z(r,n),ne(r,n),Y(r,n,rt))}},xn.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,Ts==="pr"?s.jsx("div",{className:"space-y-4",children:Mn?s.jsx(Lw,{directory:Mn.directory,branch:Mn.branch,baseBranch:ms,trackingBranch:v?.tracking??void 0,remotes:Gs,remoteBranches:Zt,onGeneratedDescription:as}):s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:e("gitView.pullRequest.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:e("gitView.pullRequest.createHint")})]})}):null]})})})}),s.jsx($s,{open:Jt!==null,onOpenChange:q=>{q||ls(null)},children:s.jsxs(_s,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(Hs,{children:[s.jsx(Us,{children:e(Jt==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(on,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(nw,{mode:Jt==="graph"?"graph":"history",log:Jt==="graph"?Ds??T:T,isLogLoading:Jt==="graph"&&Es||B,logMaxCount:Jt==="graph"?Hn:rt,onLogMaxCountChange:Jt==="graph"?Oi:rn,expandedCommitHashes:Qt,onToggleCommit:fr,commitFilesMap:Dt,loadingCommitHashes:Ct,onCopyHash:Gn,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:Jt==="graph"?null:Qe,onConflict:Jt==="graph"?fo:void 0,onActionSuccess:Jt==="graph"?uo:void 0})})]})}),s.jsx(Ky,{open:Oe,onOpenChange:Ge,directory:r,hasUncommittedChanges:(v?.files?.length??0)>0,hasStagedChanges:ln.length>0,uncommittedFileCount:v?.files?.length??0,onChanged:async q=>{r&&q?.affectsIndex&&te(r),await gs(!1),await Ms()}}),s.jsx($s,{open:Re,onOpenChange:X,children:s.jsxs(_s,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(Hs,{className:"px-4 pt-4",children:s.jsx(Us,{children:e("gitView.gitmoji.title")})}),s.jsxs(Oa,{className:"h-[420px]",children:[s.jsx(Ba,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:xs,onValueChange:ks}),s.jsxs(Va,{children:[s.jsx(_a,{children:e("gitView.gitmoji.empty")}),s.jsx(oi,{children:(xe.length===0?[]:xe.filter(q=>{const Ce=xs.trim().toLowerCase();return Ce?q.emoji.includes(Ce)||q.code.toLowerCase().includes(Ce)||q.description.toLowerCase().includes(Ce):!0})).map(q=>s.jsxs(li,{onSelect:()=>nn(q.emoji,q.code),children:[s.jsx("span",{className:"text-lg",children:q.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:q.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:q.description})]},q.code))})]})]})]})}),r&&s.jsx(Ow,{open:Ht,onOpenChange:ht,conflictFiles:hs,directory:r,operation:js,onAbort:dn,onClearState:fs}),s.jsx(Uw,{open:zs,onOpenChange:Ks,operation:Ws,targetBranch:Ns,onConfirm:mi})]}):s.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:e("gitView.empty.selectSessionOrDirectory")})})},Zl=5e3,av=(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},vl=(t,e)=>og(ag.getState().dictionary,t,e),lv=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"},cv=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()},Vc=async(t,e)=>{try{const n=await cv(t,e);return av(n,Zl)>Zl?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:lv(n)}}},_c=t=>{if(t==="too-large"){const e=Zl.toLocaleString(Xi());return vl("contextFileOpen.failure.tooLarge",{count:e})}return vl(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},dv=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Pn=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},Lm=(t,e)=>{const n=Pn(e),r=Pn(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},uv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),fv=new Set(["node_modules"]),mv=t=>fv.has(t),hv=t=>{const e=Pn(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},pv=8,Ir=new Map,gv=t=>{const e=Ir.get(t);return e?(e.touchedAt=Date.now(),Ir.delete(t),Ir.set(t,e),e):null},jl=t=>{const e=Ir.get(t);if(e)return e.touchedAt=Date.now(),e;if(Ir.size>=pv){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},xv=t=>{Ir.delete(t)},Om=(t,e)=>s.jsx(Hr,{filePath:t,extension:e}),bv=t=>{const e=mt.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},yv=t=>{const e=mt.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:b}=t,{t:p}=Nt(),x=n.type==="directory",{canRename:y,canCreateFile:h,canCreateFolder:C,canDelete:w,canReveal:S}=d,[j,k]=i.useState(!1),[v,A]=i.useState(!1);let I;e[0]!==h||e[1]!==C||e[2]!==w||e[3]!==y||e[4]!==S?(I=ge=>{!y&&!h&&!C&&!w&&!S||(ge?.preventDefault(),A(!0))},e[0]=h,e[1]=C,e[2]=w,e[3]=y,e[4]=S,e[5]=I):I=e[5];const N=I;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 P=O;let T;e[11]===Symbol.for("react.memo_cache_sentinel")?(T=ge=>{ge.stopPropagation(),A(!1),k(!0)},e[11]=T):T=e[11];const L=T;let R;e[12]!==h||e[13]!==C||e[14]!==w||e[15]!==y||e[16]!==S||e[17]!==u||e[18]!==x||e[19]!==n||e[20]!==b||e[21]!==g||e[22]!==p?(R=ge=>{const{Item:F,Separator:se}=ge;return s.jsxs(s.Fragment,{children:[y&&s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),b("rename",n)},children:[s.jsx(D,{name:"edit",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.rename")]}),s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),ur(n.path).then(Ne=>{if(Ne.ok){ce.success(p("sidebarFilesTree.toast.pathCopied"));return}ce.error(p("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(D,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.copyPath")]}),!x&&u&&s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),u(n.path).catch(Ne=>{console.error("Download failed:",Ne),ce.error(p("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(D,{name:"download",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.save")]}),S&&s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),g(n.path)},children:[s.jsx(D,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",p(kc())]}),x&&(h||C)&&s.jsxs(s.Fragment,{children:[s.jsx(se,{}),h&&s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),b("createFile",n)},children:[s.jsx(D,{name:"file-add",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.newFile")]}),C&&s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),b("createFolder",n)},children:[s.jsx(D,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.newFolder")]})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx(se,{}),s.jsxs(F,{onClick:ee=>{ee.stopPropagation(),b("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(D,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",p("sidebarFilesTree.menu.delete")]})]})]})},e[12]=h,e[13]=C,e[14]=w,e[15]=y,e[16]=S,e[17]=u,e[18]=x,e[19]=n,e[20]=b,e[21]=g,e[22]=p,e[23]=R):R=e[23];const B=R;let V;e[24]!==n.path||e[25]!==r?(V=ge=>{const F=Lm(r,n.path);!F||F==="."||(ge.dataTransfer.setData("application/x-openchamber-file-path",F),ge.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=V):V=e[26];const _=V;let E;e[27]!==N?(E=s.jsx("div",{className:"group relative flex items-center",onContextMenu:N}),e[27]=N,e[28]=E):E=e[28];const Z=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let ne;e[29]!==Z?(ne=Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",Z,"cursor-grab active:cursor-grabbing"),e[29]=Z,e[30]=ne):ne=e[30];let Y;e[31]!==x||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(Y=x?o?s.jsx(D,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(D,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Om(n.path,n.extension),e[31]=x,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=Y):Y=e[35];let H;e[36]!==n.name||e[37]!==n.path?(H=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:n.path,children:n.name}),e[36]=n.name,e[37]=n.path,e[38]=H):H=e[38];let re;e[39]!==x||e[40]!==c?(re=!x&&c&&s.jsx(bv,{status:c}),e[39]=x,e[40]=c,e[41]=re):re=e[41];let ae;e[42]!==l||e[43]!==x?(ae=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]=ae):ae=e[44];let me;e[45]!==N||e[46]!==_||e[47]!==P||e[48]!==H||e[49]!==re||e[50]!==ae||e[51]!==ne||e[52]!==Y?(me=s.jsxs("button",{type:"button",onClick:P,onContextMenu:N,draggable:!0,onDragStart:_,className:ne,children:[Y,H,re,ae]}),e[45]=N,e[46]=_,e[47]=P,e[48]=H,e[49]=re,e[50]=ae,e[51]=ne,e[52]=Y,e[53]=me):me=e[53];let Se;e[54]!==h||e[55]!==C||e[56]!==w||e[57]!==y||e[58]!==S||e[59]!==j||e[60]!==B||e[61]!==p?(Se=(y||h||C||w||S)&&s.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:s.jsxs(sn,{open:j,onOpenChange:k,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(en,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:L,title:p("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":p("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(D,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:p("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(tn,{align:"end",side:"bottom",onCloseAutoFocus:()=>k(!1),children:B({Item:bs,Separator:Rr})})]})}),e[54]=h,e[55]=C,e[56]=w,e[57]=y,e[58]=S,e[59]=j,e[60]=B,e[61]=p,e[62]=Se):Se=e[62];let te;e[63]!==me||e[64]!==Se||e[65]!==E?(te=s.jsxs(Ec,{render:E,children:[me,Se]}),e[63]=me,e[64]=Se,e[65]=E,e[66]=te):te=e[66];let ke;e[67]!==B?(ke=s.jsx(Tc,{className:"min-w-[180px]",children:B({Item:Rc,Separator:bm})}),e[67]=B,e[68]=ke):ke=e[68];let Q;return e[69]!==v||e[70]!==te||e[71]!==ke?(Q=s.jsxs(Mc,{open:v,onOpenChange:A,children:[te,ke]}),e[69]=v,e[70]=te,e[71]=ke,e[72]=Q):Q=e[72],Q},wv=(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,vv=i.memo(yv,wv),jv=()=>{const{t}=Nt(),{files:e}=Jn(),n=di()??"",r=Pn(n.trim()),o=Ff(),a=Lf(),c=mc(G=>G.searchFiles),l=Ee(G=>G.openContextFile),d=Wa(n),[u,m]=i.useState(""),f=Ha(u,200),g=i.useRef(null),[b,p]=i.useState([]),[x,y]=i.useState(!1),[h,C]=i.useState({}),[w,S]=i.useState({}),j=i.useRef(new Set),k=i.useRef(new Set);i.useEffect(()=>{if(!r){C({}),S({}),j.current=new Set;return}const G=gv(r);G?(C({...G.childrenByDir}),S({...G.loadErrorsByDir}),j.current=new Set(G.loadedDirs)):(C({}),S({}),j.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const G=jl(r);G.childrenByDir=h},[r,h]),i.useEffect(()=>{if(!r)return;const G=jl(r);G.loadErrorsByDir=w},[r,w]),i.useEffect(()=>{if(!r)return;const G=jl(r);G.loadedDirs=new Set(j.current)},[r,h,w]),i.useEffect(()=>()=>{if(!r)return;const G=Ir.get(r);G&&G.loadedDirs.size===0&&Object.keys(G.childrenByDir).length===0&&xv(r)},[r]);const v=i.useMemo(()=>[],[]),A=i.useMemo(()=>[],[]),I=fn(G=>r?G.byRoot[r]?.expandedPaths??v:v),N=fn(G=>r?G.byRoot[r]?.selectedPath??null:null),O=fn(G=>G.setSelectedPath),P=fn(G=>G.addOpenPath),T=fn(G=>G.removeOpenPathsByPrefix),L=fn(G=>G.toggleExpandedPath),R=Ee(G=>r?G.contextPanelByDirectory[r]?.tabs??A:A),B=i.useMemo(()=>new Set(R.map(G=>G.mode==="file"?G.targetPath:null).filter(G=>typeof G=="string"&&G.length>0).map(G=>Pn(G))),[R]),[V,_]=i.useState(null),[E,Z]=i.useState(null),[ne,Y]=i.useState(""),[H,re]=i.useState(!1),ae=!!e.writeFile,me=!!e.createDirectory,Se=!!e.rename,te=!!e.delete,ke=!!e.revealPath,Q=i.useMemo(()=>({canRename:Se,canCreateFile:ae,canCreateFolder:me,canDelete:te,canReveal:ke}),[Se,ae,me,te,ke]),ge=i.useCallback(G=>{e.revealPath&&e.revealPath(G).catch(()=>{ce.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),F=i.useCallback((G,$)=>{_(G),Z($),Y(G==="rename"&&$.name||""),re(!1)},[]),se=i.useCallback((G,$)=>{const ve=$.filter(be=>be&&typeof be.name=="string"&&be.name.length>0).filter(be=>o||!be.name.startsWith(".")).filter(be=>a||!mv(be.name)).map(be=>{const z=be.name,xe=Pn(be.path||""),je=xe?uv(xe)?xe:Pn(`${G}/${xe}`):Pn(`${G}/${z}`),K=be.isDirectory?"directory":"file",ye=K==="file"&&z.includes(".")?z.split(".").pop()?.toLowerCase():void 0;return{name:z,path:je,type:K,extension:ye}});return dv(ve)},[a,o]),ee=i.useCallback(async(G,$)=>{const ve=Pn(G.trim());if(!ve||j.current.has(ve)||k.current.has(ve))return;k.current=new Set(k.current),k.current.add(ve);const be=e.listDirectory?e.listDirectory(ve).then(z=>z.entries.map(xe=>({name:xe.name,path:xe.path,isDirectory:xe.isDirectory}))):Vn.listLocalDirectory(ve).then(z=>z.map(xe=>({name:xe.name,path:xe.path,isDirectory:xe.isDirectory})));try{const z=await be;if($?.())return;const xe=se(ve,z);j.current=new Set(j.current),j.current.add(ve),S(je=>{if(!je[ve])return je;const K={...je};return delete K[ve],K}),C(je=>({...je,[ve]:xe}))}catch(z){if($?.())return;const xe=z instanceof Error?z.message:String(z??"");console.error("Failed to load sidebar directory:",z),S(je=>({...je,[ve]:xe}))}finally{k.current=new Set(k.current),k.current.delete(ve)}},[e,se]),Ne=i.useCallback(async()=>{r&&(j.current=new Set,k.current=new Set,S({}),C(G=>Object.keys(G).length===0?G:{}),await ee(r))},[ee,r]),De=i.useCallback(async G=>{if(!G){await Ne();return}const $=Pn(G);j.current=new Set(j.current),j.current.delete($),k.current=new Set(k.current),k.current.delete($),await ee($)},[ee,Ne]);i.useEffect(()=>{r&&(j.current=new Set,k.current=new Set,S({}),C(G=>Object.keys(G).length===0?G:{}),ee(r))},[ee,r,o,a]),i.useEffect(()=>{if(!r||I.length===0)return;const G=I.map(be=>Pn(be)).filter(be=>!!be&&be!==r&&be.startsWith(`${r}/`)&&!j.current.has(be)&&!k.current.has(be)).sort((be,z)=>be.split("/").length-z.split("/").length);if(G.length===0)return;let $=!1;const ve=()=>$;return(async()=>{for(let be=0;be<G.length&&!$;be+=3){const z=G.slice(be,be+3);await Promise.all(z.map(xe=>ee(xe,ve)))}})(),()=>{$=!0}},[I,ee,r]),i.useEffect(()=>{if(!n){p([]),y(!1);return}const G=f.trim();if(!G){p([]),y(!1);return}let $=!1;return y(!0),c(n,G,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(ve=>{if($)return;const z=ve.filter(xe=>a||!hv(xe.path)).map(xe=>({name:xe.name,path:Pn(xe.path),type:"file",extension:xe.extension,relativePath:xe.relativePath}));p(z)}).catch(()=>{$||p([])}).finally(()=>{$||y(!1)}),()=>{$=!0}},[n,f,c,o,a]);const Be=i.useMemo(()=>{const G=new Map;if(!d?.files)return G;for(const $ of d.files)$.index==="A"||$.working_dir==="?"?G.set($.path,"git-added"):$.index==="D"?G.set($.path,"git-deleted"):($.index==="M"||$.working_dir==="M")&&G.set($.path,"git-modified");return G},[d]),Fe=i.useMemo(()=>{const G=new Map;if(!d?.files||!r)return G;for(const $ of d.files){const ve=$.index==="M"||$.working_dir==="M",be=$.index==="A"||$.working_dir==="?";if(!ve&&!be)continue;const z=$.path.split("/");if(z.length<=1)continue;let xe=r;for(let je=0;je<z.length-1;je++){xe=`${xe}/${z[je]}`;let K=G.get(xe);K||(K={modified:0,added:0},G.set(xe,K)),ve&&K.modified++,be&&K.added++}}return G},[d,r]),Me=i.useCallback(G=>{if(B.has(G))return"open";if(Be.size===0)return null;const $=G.startsWith(r+"/")?G.slice(r.length+1):G;return Be.get($)??null},[B,Be,r]),he=i.useCallback(G=>{if(Fe.size===0)return null;const $=Fe.get(G);return $&&$.modified+$.added>0?$:null},[Fe]),Ae=i.useCallback(async G=>{if(!r)return;const $=await Vc(e,G.path);if(!$.ok){ce.error(_c($.reason));return}O(r,G.path),P(r,G.path),l(r,G.path)},[P,e,l,r,O]),pe=i.useCallback(async G=>{const $=Pn(G);r&&(L(r,$),j.current.has($)||await ee($))},[ee,r,L]),ue=i.useCallback(async G=>{if(G?.preventDefault(),!E||!V)return;re(!0);const $=()=>re(!1),ve=()=>_(null);if(V==="createFile"){if(!ne.trim()){ce.error(t("sidebarFilesTree.toast.filenameRequired")),$();return}if(!e.writeFile){ce.error(t("sidebarFilesTree.toast.writeNotSupported")),$();return}const be=E.path,z=be?`${be}/`:"",xe=Pn(`${z}${ne.trim()}`);await e.writeFile(xe,"").then(async je=>{je.success&&(ce.success(t("sidebarFilesTree.toast.fileCreated")),await De(be)),ve()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}if(V==="createFolder"){if(!ne.trim()){ce.error(t("sidebarFilesTree.toast.folderNameRequired")),$();return}const be=E.path,z=be?`${be}/`:"",xe=Pn(`${z}${ne.trim()}`);await e.createDirectory(xe).then(async je=>{je.success&&(ce.success(t("sidebarFilesTree.toast.folderCreated")),await De(be)),ve()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}if(V==="rename"){if(!ne.trim()){ce.error(t("sidebarFilesTree.toast.nameRequired")),$();return}if(!e.rename){ce.error(t("sidebarFilesTree.toast.renameNotSupported")),$();return}const be=E.path,z=be.split("/").slice(0,-1).join("/"),xe=z?`${z}/`:"",je=Pn(`${xe}${ne.trim()}`);await e.rename(be,je).then(async K=>{K.success&&(ce.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await De(z),r&&T(r,be),(N===be||N&&N.startsWith(`${be}/`))&&O(r,null)),ve()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}if(V==="delete"){if(!e.delete){ce.error(t("sidebarFilesTree.toast.deleteNotSupported")),$();return}const be=E.path,z=be.split("/").slice(0,-1).join("/");await e.delete(be).then(async xe=>{xe.success&&(ce.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await De(z),r&&T(r,be),(N===be||N&&N.startsWith(be+"/"))&&O(r,null)),ve()}).catch(()=>ce.error(t("sidebarFilesTree.toast.operationFailed"))).finally($);return}$()},[V,E,ne,e,De,T,r,N,O,t]);function U(G,$){const ve=h[G]??[];return ve.map((be,z)=>{const xe=be.type==="directory",je=xe&&I.includes(be.path),K=N===be.path,ye=z===ve.length-1;return s.jsxs("li",{className:"relative",children:[$>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),ye&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),s.jsx(vv,{node:be,root:r,isExpanded:je,isActive:K,status:xe?void 0:Me(be.path),badge:xe?he(be.path):void 0,permissions:Q,downloadFile:e.downloadFile,onSelect:Ae,onToggle:pe,onRevealPath:ge,onOpenDialog:F}),xe&&je&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[w[be.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[be.path],children:w[be.path]}),s.jsxs($e,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{De(be.path)},children:[s.jsx(D,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,U(be.path,$+1)]})]},be.path)})}const fe=!!(r&&h[r]),de=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(D,{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:G=>m(G.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(D,{name:"close",className:"h-4 w-4"})}):null]}),ae&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>F("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(D,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),me&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>F("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(D,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{Ne()},className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.refreshTitle"),"aria-label":t("sidebarFilesTree.actions.refreshTitle"),children:s.jsx(D,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx(_n,{outerClassName:"flex-1 min-h-0",className:"p-2",children:s.jsx("ul",{className:"flex flex-col",children:x?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):b.length>0?b.map(G=>{const $=N===G.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>Ae(G),draggable:!0,onDragStart:ve=>{const be=G.relativePath||Lm(r??"",G.path);!be||be==="."||(ve.dataTransfer.setData("application/x-openchamber-file-path",be),ve.dataTransfer.effectAllowed="copy")},className:Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors cursor-grab active:cursor-grabbing",$?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:G.path,children:[Om(G.path,G.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:G.relativePath??G.path})]})},G.path)}):de?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{children:de}),s.jsxs($e,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{Ne()},children:[s.jsx(D,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):fe&&r?U(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx($s,{open:!!V,onOpenChange:G=>!G&&_(null),children:s.jsxs(_s,{children:[s.jsxs(Hs,{children:[s.jsxs(Us,{children:[V==="createFile"&&t("sidebarFilesTree.dialog.createFile.title"),V==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.title"),V==="rename"&&t("sidebarFilesTree.dialog.rename.title"),V==="delete"&&t("sidebarFilesTree.dialog.delete.title")]}),s.jsxs(on,{children:[V==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:E?.path??t("sidebarFilesTree.dialog.rootFallback")}),V==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:E?.path??t("sidebarFilesTree.dialog.rootFallback")}),V==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:E?.name??""}),V==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:E?.name??""})]})]}),V!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(vn,{value:ne,onChange:G=>Y(G.target.value),placeholder:t(V==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:G=>{G.key==="Enter"&&ue()},autoFocus:!0})}),s.jsxs(ir,{children:[s.jsx($e,{variant:"outline",onClick:()=>_(null),disabled:H,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx($e,{variant:V==="delete"?"destructive":"default",onClick:()=>{ue()},disabled:H||V!=="delete"&&!ne.trim(),children:H?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t(V==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},Sv=t=>t==="git"||t==="files"||t==="context",Nv="files",kv=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function Cv(t,e,n,r){const o=mt.c(6),{git:a}=Jn(),c=wn(Av),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(()=>{kv()&&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 Av(t){return t.ensureStatus}const Bm=()=>{const t=mt.c(17),e=ws(Iv),n=ws(Pv),r=Js(Tv),o=wn(Rv);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()||Ri(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 b;return t[13]!==g||t[14]!==m||t[15]!==d?(b=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(ky,{projectRef:d,projectLabel:m,canCreateWorktree:g})}),t[13]=g,t[14]=m,t[15]=d,t[16]=b):b=t[16],b},Dv=()=>{const t=mt.c(57),{t:e}=Nt(),n=Ee(Ev),r=Ee(Mv),o=Ee(Fv),a=Ee(Lv),c=di();Cv(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(Nv)},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(D,{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 b;t[10]!==e?(b=e("layout.rightSidebar.files"),t[10]=e,t[11]=b):b=t[11];let p;t[12]===Symbol.for("react.memo_cache_sentinel")?(p=s.jsx(D,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=p):p=t[12];let x;t[13]!==b?(x={id:"files",label:b,icon:p},t[13]=b,t[14]=x):x=t[14];let y;t[15]!==e?(y=e("layout.rightSidebar.context"),t[15]=e,t[16]=y):y=t[16];let h;t[17]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(D,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=h):h=t[17];let C;t[18]!==y?(C={id:"context",label:y,icon:h},t[18]=y,t[19]=C):C=t[19];let w;t[20]!==C||t[21]!==g||t[22]!==x?(w=[g,x,C],t[20]=C,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(ae=>ae.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 A;t[27]!==r?(A=ae=>{Sv(ae)&&r(ae)},t[27]=r,t[28]=A):A=t[28];const I=A;let N;t[29]!==I||t[30]!==n||t[31]!==k?(N=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(To,{items:k,activeId:n,onSelect:I,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=I,t[30]=n,t[31]=k,t[32]=N):N=t[32];const O=n!=="git"&&"hidden";let P;t[33]!==O?(P=Pe("h-full",O),t[33]=O,t[34]=P):P=t[34];let T;t[35]!==v?(T=s.jsx(Xl,{isActive:v}),t[35]=v,t[36]=T):T=t[36];let L;t[37]!==P||t[38]!==T?(L=s.jsx("div",{className:P,children:T}),t[37]=P,t[38]=T,t[39]=L):L=t[39];const R=n!=="files"&&"hidden";let B;t[40]!==R?(B=Pe("h-full",R),t[40]=R,t[41]=B):B=t[41];let V;t[42]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsx(jv,{}),t[42]=V):V=t[42];let _;t[43]!==B?(_=s.jsx("div",{className:B,children:V}),t[43]=B,t[44]=_):_=t[44];const E=n!=="context"&&"hidden";let Z;t[45]!==E?(Z=Pe("h-full",E),t[45]=E,t[46]=Z):Z=t[46];let ne;t[47]===Symbol.for("react.memo_cache_sentinel")?(ne=s.jsx(Bm,{}),t[47]=ne):ne=t[47];let Y;t[48]!==Z?(Y=s.jsx("div",{className:Z,children:ne}),t[48]=Z,t[49]=Y):Y=t[49];let H;t[50]!==L||t[51]!==_||t[52]!==Y?(H=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[L,_,Y]}),t[50]=L,t[51]=_,t[52]=Y,t[53]=H):H=t[53];let re;return t[54]!==N||t[55]!==H?(re=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[N,H]}),t[54]=N,t[55]=H,t[56]=re):re=t[56],re};function Iv(t){return t.activeProjectId}function Pv(t){return t.projects}function Tv(t){return t.homeDirectory}function Rv(t){return t.directories}function Ev(t){return t.rightSidebarTab}function Mv(t){return t.setRightSidebarTab}function Fv(t){return t.isRightSidebarOpen}function Lv(t){return t.activeMainTab}const Ov=64,Bv=3,bi=new Map,Vv=(t,e,n=Bv)=>{const r=`${t}\0${n}\0${e}`,o=bi.get(r);if(o)return bi.delete(r),bi.set(r,o),o;const a=$v(e),c=a?Mh(Fh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??Du(t):Lh(_v(t,e))[0]?.files[0]??Du(t);for(bi.set(r,c);bi.size>Ov;){const l=bi.keys().next().value;if(!l)break;bi.delete(l)}return c},_v=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
14
- ===================================================================
15
- --- ${t}
16
- +++ ${t}
17
- ${e}`,$v=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:Au(l),after:Au(d)}},Au=t=>t.map(e=>e.text+(e.newline?`
18
- `:"")).join(""),Du=t=>Oh({name:t,contents:""},{name:t,contents:""}),zv=1100,Wv=15e3,Iu=500,Pu=300,Uv=1e6,Hv=3,Gv=t=>t<=6?t:t<=12?6:t<=25?4:2,Kv=i.memo(()=>{const t=mt.c(4),{t:e}=Nt();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}),Vm={"?":{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"}},qv=Vm.M,Yv=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"},_m=t=>{const e=Yv(t);return Vm[e]??qv},Qv=t=>{const{index:e,working_dir:n}=t;return e==="A"||n==="A"||e==="?"||n==="?"},Tu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Ru=t=>!!t.working_dir?.trim()||t.index==="?",Jv=(t,e)=>dg(t,e),Eu=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Mu=(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},Xv=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},Zv=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),e1=(t,e,n)=>Zv(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:Vv(t,e),contextMode:n},$m=(t,e,n)=>{const r=t??0,o=e??0;return!r&&!o?null:s.jsxs("span",{className:Pe("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",n?.className),children:[r?s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",r]}):null,o?s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",o]}):null]})},t1=i.memo(t=>{const e=mt.c(43),{scope:n,workingCount:r,stagedCount:o,onScopeChange:a}=t,{t:c}=Nt(),[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 b;e[5]!==u?(b=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",u]}),e[5]=u,e[6]=b):b=e[6];let p;e[7]!==f||e[8]!==b?(p=s.jsxs("span",{className:"whitespace-nowrap",children:[f,b]}),e[7]=f,e[8]=b,e[9]=p):p=e[9];let x;e[10]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx(D,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=x):x=e[10];let y;e[11]!==g||e[12]!==p?(y=s.jsx(en,{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]=y):y=e[13];let h;e[14]!==a?(h=P=>{(P==="working"||P==="staged")&&(a?.(P),d(!1))},e[14]=a,e[15]=h):h=e[15];let C;e[16]!==c?(C=c("diffView.scope.changed"),e[16]=c,e[17]=C):C=e[17];let w;e[18]!==C?(w=s.jsx("span",{children:C}),e[18]=C,e[19]=w):w=e[19];let 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(Dd,{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 A;e[29]!==o?(A=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=A):A=e[30];let I;e[31]!==v||e[32]!==A?(I=s.jsx(Dd,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[v,A]})}),e[31]=v,e[32]=A,e[33]=I):I=e[33];let N;e[34]!==n||e[35]!==j||e[36]!==I||e[37]!==h?(N=s.jsx(tn,{align:"start",className:"w-40",children:s.jsxs(ug,{value:n,onValueChange:h,children:[j,I]})}),e[34]=n,e[35]=j,e[36]=I,e[37]=h,e[38]=N):N=e[38];let O;return e[39]!==l||e[40]!==N||e[41]!==y?(O=s.jsxs(sn,{open:l,onOpenChange:d,children:[y,N]}),e[39]=l,e[40]=N,e[41]=y,e[42]=O):O=e[42],O}),s1=i.memo(t=>{const e=mt.c(11),{changedFiles:n,selectedFile:r,onSelectFile:o}=t,{t:a}=Nt();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=_m(u),f=r===u.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(u.path),className:Pe("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",f?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[s.jsx(Hr,{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}),$m(u.insertions,u.deletions)]})},u.path)},e[5]=o,e[6]=r,e[7]=a,e[8]=d):d=e[8],c=n.map(d),e[0]=n,e[1]=o,e[2]=r,e[3]=a,e[4]=c}else c=e[4];let l;return e[9]!==c?(l=s.jsx(_n,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:s.jsx("ul",{className:"flex flex-col gap-1",children:c})}),e[9]=c,e[10]=l):l=e[10],l}),n1=i.memo(t=>{const e=mt.c(20),{filePath:n,diff:r,renderSideBySide:o}=t,{t:a}=Nt(),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 b;return e[16]!==d||e[17]!==f||e[18]!==g?(b=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]=b):b=e[19],b}),r1=i.memo(t=>{const e=mt.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=Ai(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(Kv,{}),e[2]=m):m=e[2],m}if(Zi(n)){let m;return e[3]!==r||e[4]!==n||e[5]!==o?(m=s.jsx(n1,{filePath:n,diff:r,renderSideBySide:o}),e[3]=r,e[4]=n,e[5]=o,e[6]=m):m=e[6],m}let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={contain:"layout"},e[7]=d):d=e[7];let 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(xm,{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}),i1=i.memo(t=>{const e=mt.c(7),{filePath:n,staged:r,busyAction:o,disabled:a,onAction:c}=t,{t:l}=Nt();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(Sl,{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(Sl,{label:l("gitView.changes.revertFileAria",{path:n}),icon:"arrow-go-back",loading:o==="discard",disabled:a,tone:"failure",onClick:()=>c("discard")}),s.jsx(Sl,{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}),Sl=t=>{const e=mt.c(14),{label:n,icon:r,loading:o,disabled:a,tone:c,onClick:l}=t,d=c==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",u=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let m;e[0]!==d||e[1]!==u?(m=Pe("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",d,u),e[0]=d,e[1]=u,e[2]=m):m=e[2];let f;e[3]!==l?(f=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(D,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(D,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=g):g=e[7];let b;return e[8]!==a||e[9]!==n||e[10]!==m||e[11]!==f||e[12]!==g?(b=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]=b):b=e[13],b},o1=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:b=!1,loadFullFiles:p=!1})=>{const{t:x}=Nt(),{git:y}=Jn(),h=wn(i.useCallback(F=>F.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),C=wn(F=>F.setDiff),w=wn(F=>F.fetchStatus),S=Ee(F=>F.setDiffFileLayout),[j,k]=i.useState(0),[v,A]=i.useState(null),[I,N]=i.useState(!1),[O,P]=i.useState(null),[T,L]=i.useState(!1),[R,B]=i.useState(null),[V,_]=i.useState(null),E=i.useRef(null),Z=i.useRef(null),ne=i.useMemo(()=>_m(e),[e]),Y=n==="side-by-side",H=p?"full":"patch",re=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,ae=i.useMemo(()=>b?V:R||(h?{original:h.original,modified:h.modified,isBinary:h.isBinary,contextMode:"full"}:null),[h,R,b,V]),me=ae?.contextMode===H,Se=i.useCallback(F=>{Z.current=F,u(e.path,F)},[e.path,u]),te=i.useCallback(F=>{d(e.path,F)},[e.path,d]),ke=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{b?_(null):B(null),A(null),E.current=null},[re,b]),i.useEffect(()=>{if(!a||!c)return;if(!t||ae&&me){E.current=null,N(!1);return}const F=`${t}::${e.path}::${b?"staged":"unstaged"}::${re}::${H}::${j}`;if(E.current===F)return;E.current=F,A(null),N(!0);let se=!1;const ee=p?Uv:Hv,Ne=Zi(e.path)?y.getGitFileDiff(t,{path:e.path,staged:b}):y.getGitDiff(t,{path:e.path,staged:b,contextLines:ee}),De=Wv,Be=new Promise((Fe,Me)=>{setTimeout(()=>Me(new Error(`Timed out after ${De}ms`)),De)});return Promise.race([Ne,Be]).then(Fe=>{if(!se){if("diff"in Fe){const Me=e1(e.path,Fe.diff,H);b?_(Me):B(Me)}else{const Me={original:Fe.original??"",modified:Fe.modified??"",isBinary:Fe.isBinary,contextMode:"full"};b?_(Me):C(t,e.path,Me)}N(!1)}}).catch(Fe=>{if(se)return;const Me=Fe instanceof Error?Fe.message:String(Fe);A(Me),N(!1)}),()=>{se=!0,E.current===F&&(E.current=null)}},[H,ae,me,j,t,e.path,re,y,a,c,p,C,b]);const Q=i.useCallback(()=>{te(!a),ke()},[te,ke,a]),ge=i.useCallback(async F=>{if(!(!t||O!==null)){P(F);try{F==="stage"?await y.stageGitFile(t,e.path):F==="unstage"?await y.unstageGitFile(t,e.path):await y.revertGitFile(t,e.path,{scope:"working"}),k(se=>se+1),await w(t,y)}catch(se){const ee=F==="unstage"?"gitView.toast.unstageFileFailed":F==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";ce.error(se instanceof Error?se.message:x(ee))}finally{P(se=>se===F?null:se)}}},[t,w,e.path,O,y,x]);return s.jsxs("div",{ref:Se,className:"scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0",children:[s.jsx("div",{className:"sticky top-0 z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80",children:s.jsxs("div",{role:"button",tabIndex:0,onClick:Q,onKeyDown:F=>{F.target===F.currentTarget&&(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),Q())},className:Pe("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",o?"bg-[var(--interactive-selection)]/35":null),children:[s.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),s.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[s.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:a?s.jsx(D,{name:"arrow-down-s",className:"size-4"}):s.jsx(D,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:ne.color},title:x(ne.descriptionKey),"aria-label":x(ne.descriptionKey),children:ne.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(Hr,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const F=e.path.lastIndexOf("/");if(F===-1)return s.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:e.path});const se=e.path.slice(0,F),ee=e.path.slice(F+1);return s.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:se}),s.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[s.jsx("span",{className:"text-muted-foreground",children:"/"}),s.jsx("span",{className:"text-foreground",children:ee})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[$m(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:F=>{F.stopPropagation(),g(e.path,ae)},disabled:f,children:f?s.jsx(D,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(D,{name:"edit",className:"size-3.5"})}):null,s.jsx(Xf,{mode:Y?"side-by-side":"unified",onModeChange:F=>{const se=F==="side-by-side"?"side-by-side":"inline";S(e.path,se)},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(F=>F+1),children:x("diffView.actions.retry")})]}):null,c&&I&&!ae&&!v?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}),x("diffView.state.loadingDiff")]}):null,c&&ae&&!T&&e.insertions+e.deletions>Iu?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:()=>L(!0),children:x("diffView.actions.renderAnyway")})]}):null,c&&ae&&(T||e.insertions+e.deletions<=Iu)?s.jsxs(s.Fragment,{children:[s.jsx(r1,{filePath:e.path,diff:ae,renderSideBySide:Y,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(i1,{filePath:e.path,staged:b,busyAction:O,disabled:O!==null,onAction:ge})})})]}):null]})]})}),zm=({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}=Nt(),{git:u,files:m}=Jn(),f=di(),{screenWidth:g,isMobile:b}=Er(),p=Sc(f??null),x=Wa(f??null),y=Nc(f??null),h=wn(_e=>_e.setActiveDirectory),C=wn(_e=>_e.ensureStatus),w=wn(_e=>_e.fetchStatus),S=wn(_e=>_e.setDiff),[j,k]=i.useState(null),[v,A]=i.useState(!1),[I,N]=i.useState(null),[O,P]=i.useState(()=>new Set),[T,L]=i.useState(()=>new Set),[R,B]=i.useState(!1),[V,_]=i.useState(0),[E,Z]=i.useState(!1),[ne,Y]=i.useState(!1),H=Ee(_e=>_e.pendingDiffFile),re=Ee(_e=>_e.pendingDiffStaged),ae=Ee(_e=>_e.setPendingDiffFile),me=Ee(_e=>_e.diffLayoutPreference),Se=Ee(_e=>_e.diffFileLayout),te=Ee(_e=>_e.setDiffFileLayout),ke=Ee(_e=>_e.diffWrapLines),Q=Ee(_e=>_e.setDiffWrapLines),ge=Ee(_e=>_e.openContextFileAtLine),F=ut(_e=>_e.currentSessionId),se=ke,ee=o==="staged"?!0:o==="working"?!1:null,Ne=ee??v,De=b||g<=768,Be=!!F&&!De&&!Gr(),Fe=!t&&!De&&g>=1024,Me=i.useRef(null),he=i.useRef(new Map),Ae=i.useRef(null),pe=i.useRef(null),ue=i.useRef(!1),U=i.useRef(null),fe=i.useRef(null),de=i.useCallback(()=>{Ae.current=null,ue.current=!1,N(null),pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null)},[]),G=i.useCallback(_e=>{P(Ye=>{if(Ye.has(_e))return Ye;const nt=new Set(Ye);return nt.add(_e),nt})},[]),$=i.useMemo(()=>{if(!x?.files)return[];const _e=x.diffStats??{},Ye=o==="staged"?Tu:o==="working"?Ru:()=>!0;return x.files.filter(Ye).map(nt=>({...nt,insertions:_e[nt.path]?.insertions??0,deletions:_e[nt.path]?.deletions??0,isNew:Qv(nt)})).sort((nt,wt)=>nt.path.localeCompare(wt.path))},[o,x]),ve=i.useMemo(()=>x?.files?x.files.filter(Ru).length:0,[x]),be=i.useMemo(()=>x?.files?x.files.filter(Tu).length:0,[x]),z=i.useMemo(()=>$.map(_e=>_e.path).join("\0"),[$]);i.useEffect(()=>{const _e=z?z.split("\0"):[],Ye=new Set(_e),nt=`${f??""}:${o}:${e?"collapsed":"default"}`,wt=fe.current!==nt;fe.current=nt,P(kt=>{if(wt){const et=e?0:Gv(_e.length);return new Set(_e.slice(0,et))}let vt=!1;const St=new Set;for(const et of kt){if(!Ye.has(et)){vt=!0;continue}St.add(et)}return vt?St:kt}),L(kt=>{if(wt)return new Set;let vt=!1;const St=new Set;for(const et of kt){if(!Ye.has(et)){vt=!0;continue}St.add(et)}return vt?St:kt})},[z,o,f,e]);const xe=i.useCallback(()=>{U.current=null;const _e=Me.current;if(!_e)return;const Ye=_e.getBoundingClientRect(),nt=Ye.top-Pu,wt=Ye.bottom+Pu,kt={};for(const[vt,St]of he.current){if(!St||!O.has(vt))continue;const et=St.getBoundingClientRect();et.bottom<nt||et.top>wt||(kt[vt]=!0)}L(vt=>{let St=!1;const et=new Set(vt);for(const Ot of Object.keys(kt))et.has(Ot)||(et.add(Ot),St=!0);return St?et:vt})},[O]),je=i.useCallback(()=>{typeof window>"u"||U.current===null&&(U.current=window.requestAnimationFrame(xe))},[xe]);i.useEffect(()=>{const _e=Me.current;if(_e)return je(),_e.addEventListener("scroll",je,{passive:!0}),window.addEventListener("resize",je),()=>{_e.removeEventListener("scroll",je),window.removeEventListener("resize",je),U.current!==null&&(window.cancelAnimationFrame(U.current),U.current=null)}},[$,O,je]);const K=i.useCallback(_e=>{const Ye=Se[_e.path];if(Ye)return Ye;if(me==="inline")return"inline";if(me==="side-by-side")return"side-by-side";const nt=g<zv;return _e.isNew||nt?"inline":"side-by-side"},[Se,me,g]),ye=i.useMemo(()=>$.length===0?null:$.every(_e=>K(_e)==="side-by-side")?"side-by-side":"inline",[$,K]);i.useEffect(()=>{f&&(h(f),C(f,u))},[f,h,C,u]),i.useEffect(()=>{if(f)return Pr.onGitRefreshHint(_e=>{Eu(_e.directory)===Eu(f)&&w(f,u)})},[f,w,u]),i.useEffect(()=>{o==="all"&&H&&(k(H),A(re),ae(null),ue.current=!0,Ae.current=H,G(H),_(_e=>_e+1))},[o,G,H,re,ae]),i.useEffect(()=>{if(o==="all")return;const _e=c?.trim();_e&&(k(_e),A(o==="staged"),ue.current=!0,Ae.current=_e,G(_e),_(Ye=>Ye+1))},[o,G,c]),i.useEffect(()=>{if(!j)return;$.some(Ye=>Ye.path===j)||(k(null),A(!1))},[$,j]);const Le=i.useCallback((_e,Ye)=>{const nt=he.current;Ye?nt.set(_e,Ye):nt.delete(_e),je()},[je]),Re=i.useCallback((_e,Ye)=>{de(),P(nt=>{const wt=nt.has(_e);if(Ye===wt)return nt;const kt=new Set(nt);return Ye?kt.add(_e):kt.delete(_e),kt}),Ye||L(nt=>{if(!nt.has(_e))return nt;const wt=new Set(nt);return wt.delete(_e),wt}),je()},[de,je]),X=i.useCallback(()=>{de(),P(_e=>_e.size>0?new Set:new Set($.map(Ye=>Ye.path))),L(new Set),je()},[de,$,je]),M=i.useCallback(async _e=>{if(!F)return;const Ye=ut.getState().getDirectoryForSession(F)||f||"";if(!Ye){ce.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}Y(!0);try{await lg({originalSessionID:F,directory:Ye,providerID:_e.providerID,modelID:_e.modelID,agent:_e.agent||void 0,variant:_e.variant||void 0,generateHandoff:_e.generateHandoff,returnAfterHandoffRequest:_e.generateHandoff,autoReview:_e.autoReview}),Z(!1)}catch(nt){console.error("[review-flow] failed to start review flow",nt),ce.error(nt instanceof Error?nt.message:d("diffView.reviewDialog.toast.startFailed"))}finally{Y(!1)}},[F,f,d]),le=i.useCallback(_e=>{const Ye=he.current.get(_e),nt=Me.current;if(!Ye||!nt)return!1;const wt=nt.getBoundingClientRect(),vt=Ye.getBoundingClientRect().top-wt.top,St=Math.max(0,nt.scrollHeight-nt.clientHeight);return nt.scrollTop=Math.min(St,Math.max(0,nt.scrollTop+vt)),!0},[]);i.useEffect(()=>{if(!Ae.current)return;let Ye=0;const nt=20;let wt=!1;const kt=()=>{wt||(wt=!0,Ae.current=null,ue.current=!1,N(null),pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null))},vt=()=>{if(wt){pe.current=null;return}const St=Ae.current;if(!St){kt(),pe.current=null;return}if(!le(St)){Ye+=1,Ye<nt?pe.current=window.requestAnimationFrame(vt):(kt(),pe.current=null);return}n&&ue.current&&N(St),kt()};return pe.current=window.requestAnimationFrame(vt),()=>{wt=!0,pe.current!==null&&(window.cancelAnimationFrame(pe.current),pe.current=null)}},[n,V,le]);const ie=i.useCallback(_e=>{},[]),Oe=i.useCallback(_e=>{de(),k(_e),A(!1),ue.current=!0,Ae.current=_e,G(_e),_(Ye=>Ye+1),le(_e)},[de,G,le]),Ge=i.useCallback(_e=>{const Ye=_e==="side-by-side"?"side-by-side":"inline";$.forEach(nt=>{te(nt.path,Ye)})},[$,te]),[He,Je]=i.useState(null),rt=i.useCallback(async(_e,Ye)=>{if(!(!f||!_e)){Je(_e);try{let nt=null;if(Ye&&!Ye.isBinary&&!Zi(_e)&&(nt=Mu(Ye.original,Ye.modified)),nt===null)try{const et=await u.getGitDiff(f,{path:_e,staged:Ne,contextLines:3});nt=Xv(et.diff)}catch{nt=null}let wt=Ye;if(nt===null||!wt){const et=await u.getGitFileDiff(f,{path:_e,staged:Ne});wt={original:et.original??"",modified:et.modified??"",isBinary:et.isBinary},Ne||S(f,_e,wt)}const kt=nt??(wt.isBinary||Zi(_e)?1:Mu(wt.original,wt.modified)),vt=Jv(f,_e),St=await Vc(m,vt);if(!St.ok){ce.error(_c(St.reason));return}ge(f,vt,kt,1)}finally{Je(nt=>nt===_e?null:nt)}}},[Ne,f,m,u,ge,S]),bt=()=>{if(!f)return null;const _e=Ye=>ee!==null?ee:v&&Ye===j;return s.jsxs("div",{className:Pe("flex min-w-0 flex-1 min-h-0 h-full",l?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[Fe&&s.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:d("diffView.section.files")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:$.length})]}),s.jsx(s1,{changedFiles:$,selectedFile:null,onSelectFile:Oe})]}),s.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:s.jsx(_n,{ref:Me,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:s.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:$.map(Ye=>s.jsx(o1,{directory:f,file:Ye,layout:K(Ye),wrapLines:se,isSelected:!1,isExpanded:O.has(Ye.path),isMounted:T.has(Ye.path)||Ye.path===I,onSelect:ie,onExpandedChange:Re,registerSectionRef:Le,showOpenInEditorAction:r,isOpeningInEditor:He===Ye.path,onOpenInEditor:(nt,wt)=>{rt(nt,wt)},staged:_e(Ye.path),loadFullFiles:R},Ye.path))})})})]})},yt=()=>f?y&&!x?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(D,{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")}):$.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.cleanWorkingTree")}):bt():s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.selectSessionDirectory")});return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[!b&&(o==="working"||o==="staged"?s.jsx(t1,{scope:o,workingCount:ve,stagedCount:be,onScopeChange:a}):s.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:y&&!x?d("diffView.state.loadingChanges"):$.length===1?d("diffView.summary.changedFilesSingle",{count:$.length}):d("diffView.summary.changedFilesPlural",{count:$.length})})})),$.length>0&&s.jsxs($e,{variant:"ghost",size:"sm",onClick:X,className:Pe("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:O.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll"),children:[s.jsx(D,{name:"expand-up-down",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:O.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll")})]}),$.length>0&&Be&&s.jsxs($e,{variant:"default",size:"sm",onClick:()=>Z(!0),disabled:ne,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[ne?s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(D,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),$.length>0&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>B(_e=>!_e),"aria-pressed":R,"aria-label":d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:Pe("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",R&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(D,{name:"file-download",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),$.length>0&&s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Q(!ke),className:Pe("h-5 w-5 p-0 transition-opacity",se?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(se?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(D,{name:"text-wrap",className:"size-4"})}),ye&&s.jsx(Xf,{mode:ye==="side-by-side"?"side-by-side":"unified",onModeChange:Ge})]}),s.jsx(cg,{open:E,onOpenChange:Z,projectDirectory:f??null,submitting:ne,onConfirm:M}),yt()]})},a1=(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)},Fu=(t,e)=>{const n=t.state.doc.lineAt(e.main.head);return{lineNumber:n.number,character:e.main.head-n.from+1,selection:e}},Lu=(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:Bh.cursor(a),effects:ni.scrollIntoView(a,{y:"center"})})};function l1({open:t,onOpenChange:e,view:n,variant:r="overlay"}){const{t:o}=Nt(),[a,c]=i.useState(""),l=i.useRef(null),d=i.useRef(!1),u=i.useRef(null),m=i.useRef(null),f=i.useMemo(()=>a1(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=Fu(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:y}=l.current;n.dispatch({selection:y,effects:ni.scrollIntoView(y.main.from,{y:"center"})});return}Lu(n,f,l.current.character)}},[f,t,n]);const g=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:y}=l.current;n.dispatch({selection:y,effects:ni.scrollIntoView(y.main.from,{y:"center"})})},[n]),b=i.useCallback(y=>{y||g(),e(y)},[e,g]),p=i.useCallback(()=>{!n||f===null||!l.current||(d.current=!0,Lu(n,f,l.current.character),e(!1),n.focus())},[f,e,n]);i.useEffect(()=>{if(!t)return;const y=C=>{const w=u.current,S=C.target;!w||!(S instanceof Node)||w.contains(S)||b(!1)},h=C=>{C.key==="Escape"&&(C.preventDefault(),b(!1))};return document.addEventListener("pointerdown",y,!0),document.addEventListener("keydown",h,!0),()=>{document.removeEventListener("pointerdown",y,!0),document.removeEventListener("keydown",h,!0)}},[b,t,r]);const x=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(f===null){const y=l.current??Fu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:y.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:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.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:Pe("absolute left-3 top-3 z-40 w-[min(32rem,calc(100%-1.5rem))] rounded-xl border border-[var(--interactive-border)] bg-[color:color-mix(in_srgb,var(--surface-elevated)_94%,transparent)] p-2.5 shadow-lg backdrop-blur-sm transition-all",t?"pointer-events-auto translate-y-0 opacity-100":"pointer-events-none -translate-y-1 opacity-0"),children:s.jsxs("div",{className:"min-w-0",children:[s.jsx(vn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.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 c1='<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 Ou(){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 d1=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(Ou),f=i.useRef(e),g=i.useRef(e);g.current!==e&&(g.current=e,f.current=e,c.current=e);const b=i.useRef(u);b.current!==u&&(b.current=u,f.current=c.current);const p=i.useRef(null);i.useEffect(()=>{const h=()=>m(Ou());h();const C=new MutationObserver(h);return C.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>C.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]),y=i.useCallback(h=>{c.current=h.xml,o?.(h.xml)},[o]);return s.jsx("div",{ref:p,className:Pe("h-full w-full",r),children:s.jsx(Vh,{ref:l,xml:f.current||c1,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:y},u?"dark":"light")})}),u1=t=>{const e=Qs(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},f1=t=>{const e=mt.c(8),{label:n,iconDataUrl:r}=t,[o,a]=i.useState(!1);let c;e[0]!==n?(c=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=c):c=e[1];const l=c;if(r&&!o){let m;e[2]===Symbol.for("react.memo_cache_sentinel")?(m=()=>a(!0),e[2]=m):m=e[2];let f;return e[3]!==r?(f=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:m}),e[3]=r,e[4]=f):f=e[4],f}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=Pe("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=d):d=e[5];let u;return e[6]!==l?(u=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=u):u=e[7],u},m1=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Qs=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},h1=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Wi=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,Pa=(t,e)=>{const n=Qs(e),r=Qs(t);if(!n||!r)return!1;const o=Wi(n),a=Wi(r);return a===o||a.startsWith(`${o}/`)},Bu=(t,e)=>{const n=Qs(e),r=Qs(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},ec=(t,e)=>{if(!e)return"";const n=Qs(e);if(!t||!Pa(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},p1=new Set(["node_modules"]),g1=t=>{const e=mt.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},Vu=t=>{const e=mt.c(11),{name:n}=t,r=i.useRef(null),o=i.useRef(null),[a,c]=i.useState(!1);let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l=()=>{const g=r.current,b=o.current;if(!g||!b)return;const p=()=>{c(b.scrollWidth>g.clientWidth+1)};p();const x=new ResizeObserver(p);return x.observe(g),x.observe(b),()=>{x.disconnect()}},e[0]=l):l=e[0];let d;e[1]!==n?(d=[n],e[1]=n,e[2]=d):d=e[2],i.useLayoutEffect(l,d);let 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},x1=t=>p1.has(t),b1=t=>{const e=Qs(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},y1=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},_u=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,Wm="openchamber:files:auto-save-enabled",w1=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
- `},Um=t=>t.replace(/\r\n/g,`
23
- `).replace(/\r/g,`
24
- `),v1=(t,e)=>{const n=Um(t);return e===`\r
25
- `?n.replace(/\n/g,`\r
26
- `):n},j1=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(Wm)!=="false"}catch{return!0}},Hm=(t,e)=>s.jsx(Hr,{filePath:t,extension:e}),$u=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},S1=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"},N1=t=>{const e=mt.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:b,rightClickMenuPath:p,setRightClickMenuPath:x,onSelect:y,onToggle:h,onRevealPath:C,onOpenDialog:w}=t,{t:S}=Nt(),j=n.type==="directory",{canRename:k,canCreateFile:v,canCreateFolder:A,canDelete:I,canReveal:N}=m;let O;e[0]!==v||e[1]!==A||e[2]!==I||e[3]!==k||e[4]!==N||e[5]!==n.path||e[6]!==x?(O=Ne=>{!k&&!v&&!A&&!I&&!N||(Ne?.preventDefault(),x(n.path))},e[0]=v,e[1]=A,e[2]=I,e[3]=k,e[4]=N,e[5]=n.path,e[6]=x,e[7]=O):O=e[7];const P=O;let T;e[8]!==j||e[9]!==n||e[10]!==y||e[11]!==h?(T=()=>{j?h(n.path):y(n)},e[8]=j,e[9]=n,e[10]=y,e[11]=h,e[12]=T):T=e[12];const L=T;let R;e[13]!==n.path||e[14]!==b||e[15]!==x?(R=Ne=>{Ne.stopPropagation(),x(null),b(n.path)},e[13]=n.path,e[14]=b,e[15]=x,e[16]=R):R=e[16];const B=R;let V;e[17]!==v||e[18]!==A||e[19]!==I||e[20]!==k||e[21]!==N||e[22]!==f||e[23]!==j||e[24]!==n||e[25]!==w||e[26]!==C||e[27]!==r||e[28]!==S?(V=Ne=>{const{Item:De,Separator:Be}=Ne;return s.jsxs(s.Fragment,{children:[k&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("rename",n)},children:[s.jsx(D,{name:"edit",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.rename")]}),s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),ur(n.path).then(Me=>{if(Me.ok){ce.success(S("sidebarFilesTree.toast.pathCopied"));return}ce.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(D,{name:"file-copy",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.copyPath")]}),s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation();const Me=ec(r,n.path)||n.path;ur(Me).then(he=>{if(he.ok){ce.success(S("filesView.toast.relativePathCopied"));return}ce.error(S("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(D,{name:"file-copy-2",className:"mr-2 size-4"})," ",S("filesView.tree.menu.copyRelativePath")]}),!j&&f&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),f(n.path).catch(Me=>{console.error("Download failed:",Me),ce.error(S("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(D,{name:"download",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.save")]}),N&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),C(n.path)},children:[s.jsx(D,{name:"folder-received",className:"mr-2 size-4"})," ",S(kc())]}),j&&(v||A)&&s.jsxs(s.Fragment,{children:[s.jsx(Be,{}),v&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("createFile",n)},children:[s.jsx(D,{name:"file-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFile")]}),A&&s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("createFolder",n)},children:[s.jsx(D,{name:"folder-add",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.newFolder")]})]}),I&&s.jsxs(s.Fragment,{children:[s.jsx(Be,{}),s.jsxs(De,{onClick:Fe=>{Fe.stopPropagation(),w("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(D,{name:"delete-bin",className:"mr-2 size-4"})," ",S("sidebarFilesTree.menu.delete")]})]})]})},e[17]=v,e[18]=A,e[19]=I,e[20]=k,e[21]=N,e[22]=f,e[23]=j,e[24]=n,e[25]=w,e[26]=C,e[27]=r,e[28]=S,e[29]=V):V=e[29];const _=V,E=p===n.path;let Z;e[30]!==n.path||e[31]!==x?(Z=Ne=>x(Ne?n.path:null),e[30]=n.path,e[31]=x,e[32]=Z):Z=e[32];const ne=c?void 0:P;let Y;e[33]!==ne?(Y=s.jsx("div",{className:"group relative flex items-center",onContextMenu:ne}),e[33]=ne,e[34]=Y):Y=e[34];const H=c?void 0:P,re=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let ae;e[35]!==re?(ae=Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",re),e[35]=re,e[36]=ae):ae=e[36];let me;e[37]!==j||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(me=j?o?s.jsx(D,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(D,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):Hm(n.path,n.extension),e[37]=j,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=me):me=e[41];let Se;e[42]!==n.name||e[43]!==n.path?(Se=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:n.path,children:n.name}),e[42]=n.name,e[43]=n.path,e[44]=Se):Se=e[44];let te;e[45]!==j||e[46]!==d?(te=!j&&d&&s.jsx(g1,{status:d}),e[45]=j,e[46]=d,e[47]=te):te=e[47];let ke;e[48]!==u||e[49]!==j?(ke=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]=ke):ke=e[50];let Q;e[51]!==L||e[52]!==ae||e[53]!==me||e[54]!==Se||e[55]!==te||e[56]!==ke||e[57]!==H?(Q=s.jsxs("button",{type:"button",onClick:L,onContextMenu:H,className:ae,children:[me,Se,te,ke]}),e[51]=L,e[52]=ae,e[53]=me,e[54]=Se,e[55]=te,e[56]=ke,e[57]=H,e[58]=Q):Q=e[58];let ge;e[59]!==l||e[60]!==v||e[61]!==A||e[62]!==I||e[63]!==k||e[64]!==N||e[65]!==g||e[66]!==B||e[67]!==c||e[68]!==n.path||e[69]!==_||e[70]!==b?(ge=(k||v||A||I||N)&&s.jsx("div",{className:Pe("absolute right-1 top-1/2 -translate-y-1/2",l?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:s.jsxs(sn,{open:g===n.path,onOpenChange:Ne=>b(Ne?n.path:null),children:[s.jsx(en,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"icon",className:"size-6",onClick:B,children:s.jsx(D,{name:"more-2-fill",className:"size-4"})})}),s.jsx(tn,{align:"end",side:"bottom",onCloseAutoFocus:()=>b(null),children:_({Item:bs,Separator:Rr})})]})}),e[59]=l,e[60]=v,e[61]=A,e[62]=I,e[63]=k,e[64]=N,e[65]=g,e[66]=B,e[67]=c,e[68]=n.path,e[69]=_,e[70]=b,e[71]=ge):ge=e[71];let F;e[72]!==Q||e[73]!==ge||e[74]!==Y?(F=s.jsxs(Ec,{render:Y,children:[Q,ge]}),e[72]=Q,e[73]=ge,e[74]=Y,e[75]=F):F=e[75];let se;e[76]!==_?(se=s.jsx(Tc,{className:"min-w-[180px]",children:_({Item:Rc,Separator:bm})}),e[76]=_,e[77]=se):se=e[77];let ee;return e[78]!==F||e[79]!==se||e[80]!==E||e[81]!==Z?(ee=s.jsxs(Mc,{open:E,onOpenChange:Z,children:[F,se]}),e[78]=F,e[79]=se,e[80]=E,e[81]=Z,e[82]=ee):ee=e[82],ee},k1=t=>{const e=mt.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:u}=t,{t:m}=Nt(),f=!!n;let g;e[0]!==d?(g=E=>!E&&d(),e[0]=d,e[1]=g):g=e[1];let b;e[2]!==n||e[3]!==m?(b=n==="createFile"&&m("filesView.dialog.createFile.title"),e[2]=n,e[3]=m,e[4]=b):b=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 y;e[11]!==n||e[12]!==m?(y=n==="delete"&&m("filesView.dialog.delete.title"),e[11]=n,e[12]=m,e[13]=y):y=e[13];let h;e[14]!==b||e[15]!==p||e[16]!==x||e[17]!==y?(h=s.jsxs(Us,{children:[b,p,x,y]}),e[14]=b,e[15]=p,e[16]=x,e[17]=y,e[18]=h):h=e[18];let C;e[19]!==n||e[20]!==r?.path||e[21]!==m?(C=n==="createFile"&&m("filesView.dialog.createFile.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[19]=n,e[20]=r?.path,e[21]=m,e[22]=C):C=e[22];let w;e[23]!==n||e[24]!==r?.path||e[25]!==m?(w=n==="createFolder"&&m("filesView.dialog.createFolder.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[23]=n,e[24]=r?.path,e[25]=m,e[26]=w):w=e[26];let S;e[27]!==n||e[28]!==r?.name||e[29]!==m?(S=n==="rename"&&m("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=m,e[30]=S):S=e[30];let 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]!==C||e[38]!==w?(k=s.jsxs(on,{children:[C,w,S,j]}),e[35]=S,e[36]=j,e[37]=C,e[38]=w,e[39]=k):k=e[39];let v;e[40]!==k||e[41]!==h?(v=s.jsxs(Hs,{children:[h,k]}),e[40]=k,e[41]=h,e[42]=v):v=e[42];let A;e[43]!==n||e[44]!==o||e[45]!==u||e[46]!==a||e[47]!==l||e[48]!==m?(A=n!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(vn,{value:o,onChange:E=>a(E.target.value),placeholder:m(n==="rename"?"filesView.dialog.rename.placeholder":"filesView.dialog.namePlaceholder"),onKeyDown:E=>{E.key==="Enter"&&l()},ref:u})}),e[43]=n,e[44]=o,e[45]=u,e[46]=a,e[47]=l,e[48]=m,e[49]=A):A=e[49];let I;e[50]!==m?(I=m("filesView.dialog.cancel"),e[50]=m,e[51]=I):I=e[51];let N;e[52]!==c||e[53]!==d||e[54]!==I?(N=s.jsx($e,{variant:"outline",onClick:d,disabled:c,children:I}),e[52]=c,e[53]=d,e[54]=I,e[55]=N):N=e[55];const O=n==="delete"?"destructive":"default";let P;e[56]!==l?(P=()=>{l()},e[56]=l,e[57]=P):P=e[57];let T;e[58]!==n||e[59]!==o||e[60]!==c?(T=c||n!=="delete"&&!o.trim(),e[58]=n,e[59]=o,e[60]=c,e[61]=T):T=e[61];let L;e[62]!==n||e[63]!==c||e[64]!==m?(L=c?s.jsx(D,{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]=L):L=e[65];let R;e[66]!==O||e[67]!==P||e[68]!==T||e[69]!==L?(R=s.jsx($e,{variant:O,onClick:P,disabled:T,children:L}),e[66]=O,e[67]=P,e[68]=T,e[69]=L,e[70]=R):R=e[70];let B;e[71]!==N||e[72]!==R?(B=s.jsxs(ir,{children:[N,R]}),e[71]=N,e[72]=R,e[73]=B):B=e[73];let V;e[74]!==u||e[75]!==v||e[76]!==A||e[77]!==B?(V=s.jsxs(_s,{initialFocus:u,children:[v,A,B]}),e[74]=u,e[75]=v,e[76]=A,e[77]=B,e[78]=V):V=e[78];let _;return e[79]!==f||e[80]!==g||e[81]!==V?(_=s.jsx($s,{open:f,onOpenChange:g,children:V}),e[79]=f,e[80]=g,e[81]=V,e[82]=_):_=e[82],_},Nl=(t,e,n)=>{const r=mt.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=Wr(),b=cp(g);hc(g).then(x=>{f||!x||(a(t),e(null))}).catch(x=>{f||(e(x instanceof Error?x.message:n),a(t))});const p=dp(()=>{f||(a(t),l(C1),e(null))});return()=>{f=!0,b(),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},Gm=({mode:t="full"})=>{const{t:e}=Nt(),{files:n,runtime:r}=Jn(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=Kr(),{isMobile:d,isTablet:u,screenWidth:m}=Er(),f=d||u,g=Ff(),b=Lf(),p=di()??"",x=Qs(p.trim()),y=d||t!=="editor-only",h=t==="editor-only"&&!d,C=mc(W=>W.searchFiles),w=Wa(p),[S,j]=i.useState(""),k=Ha(S,200),v=i.useRef(null),[A,I]=i.useState(!1),[N,O]=i.useState(!0),[P,T]=i.useState(!1),[L,R]=i.useState(!1),[B,V]=i.useState(!1),_=i.useRef(null),E=i.useRef(0),Z=i.useCallback(W=>{E.current=Math.max(0,E.current+(W?1:-1))},[]),ne=i.useCallback(W=>W instanceof Element?W.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!B)return;const W=Ie=>{E.current>0||ne(Ie.target)||_.current&&!_.current.contains(Ie.target)&&V(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[ne,B]);const[Y,H]=i.useState("edit"),[re,ae]=i.useState("edit"),[me,Se]=i.useState("tree"),[te,ke]=i.useState("edit"),[Q,ge]=i.useState("preview"),[F,se]=i.useState(0),ee=i.useRef({}),Ne=i.useRef({}),De=i.useRef({}),Be=i.useRef({}),Fe=i.useMemo(()=>a.find(W=>W.metadata.id===c)??Id(!1),[a,c]),Me=i.useMemo(()=>a.find(W=>W.metadata.id===l)??Id(!0),[a,l]);i.useEffect(()=>{Pd(Fe),Pd(Me)},[Fe,Me]);const he=i.useMemo(()=>[],[]),Ae=fn(W=>x?W.byRoot[x]?.openPaths??he:he),pe=fn(W=>x?W.byRoot[x]?.selectedPath??null:null),ue=fn(W=>x?W.byRoot[x]?.expandedPaths??he:he),U=fn(W=>W.addOpenPath),fe=fn(W=>W.removeOpenPath),de=fn(W=>W.removeOpenPathsByPrefix),G=fn(W=>W.removeExpandedPathsByPrefix),$=fn(W=>W.setSelectedPath),ve=fn(W=>W.toggleExpandedPath),be=fn(W=>W.expandPaths),z=i.useCallback(W=>{const Ie=Qs(W),We=Ie.split("/"),Ke=We[We.length-1]||Ie,ct=Ke.includes(".")?Ke.split(".").pop()?.toLowerCase():void 0;return{name:Ke,path:Ie,type:"file",extension:ct}},[]),xe=i.useMemo(()=>Ae.map(z),[Ae,z]),je=i.useMemo(()=>{if(pe){const W=Wi(pe);if(Ae.some(Ie=>Wi(Ie)===W))return pe}return Ae[0]??null},[Ae,pe]),K=i.useMemo(()=>je?z(je):null,[je,z]),ye=K?.path??"";i.useEffect(()=>{if(!x||!pe)return;const W=Wi(pe);Ae.some(We=>Wi(We)===W)||$(x,Ae[0]??null)},[Ae,x,pe,$]);const Le=!!(x&&ye&&!Pa(ye,x)),Re=Le?Td(ye):void 0,X=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&Le,outsideFileGrant:Re,directory:x||void 0}),[t,Le,Re,x]),M=i.useRef(null),[le,ie]=i.useState({left:!1,right:!1}),Oe=i.useCallback(()=>{const W=M.current;W&&ie({left:W.scrollLeft>2,right:W.scrollLeft+W.clientWidth<W.scrollWidth-2})},[]),Ge=i.useRef(Oe);Ge.current=Oe,i.useEffect(()=>{const W=M.current;if(!W)return;const Ie=()=>Ge.current();Ie(),W.addEventListener("scroll",Ie,{passive:!0});const We=new ResizeObserver(Ie);return We.observe(W),()=>{W.removeEventListener("scroll",Ie),We.disconnect()}},[xe.length]);const[He,Je]=i.useState({}),[rt,bt]=i.useState({}),yt=i.useRef(new Set),_e=i.useRef(new Set),Ye=i.useRef(new Map),nt=i.useRef(0),[wt,kt]=i.useState([]),[vt,St]=i.useState(!1),[et,Ot]=i.useState(""),{isPlaying:ns,play:Wt,stop:Ve}=Zf(),[Ze,_t]=i.useState(!1),[jt,xt]=i.useState(null),[rs,Gt]=i.useState(""),Ut=i.useRef(""),[as,Bt]=i.useState(null),[Lt,Vt]=i.useState(""),[Kt,Xt]=i.useState(!1),[Qt,vs]=i.useState(`
27
- `),Dt=i.useRef(null),$t=i.useRef(null),Ct=i.useRef(null),ds=i.useRef(""),qe=i.useRef(""),at=i.useRef(null),Qe=i.useRef(null),At=i.useRef(null),Tt=i.useRef(0),[ts,xs]=i.useState("idle"),[ks,Jt]=i.useState(!1),[ls,Ps]=i.useState(j1),[Ts,hn]=i.useState(!1),Gs=i.useRef(null),an=i.useRef(null),Rn=i.useRef(null),Os=i.useRef(!1),we=i.useRef(null),tt=i.useRef(null),dt=i.useRef(null),It=i.useRef(null),[Ht,ht]=i.useState(0),hs=i.useRef(null),ps=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{hs.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(hs.current),hs.current=null)},[]);const[js,Ss]=i.useState(null),[Ds,Un]=i.useState(null),[Es,En]=i.useState(""),[Hn,Xn]=i.useState(!1),[Ue,os]=i.useState(null),[fs,zs]=i.useState(null),[Ks,Ws]=i.useState(!1),[pn,Ns]=i.useState(!1),[qr,Gn]=i.useState(!1),fr=!!n.writeFile,Kn=!!n.createDirectory,gs=!!n.rename,Ms=!!n.delete,jr=!!n.revealPath,jn=yr(W=>W.availableApps),ln=yr(W=>W.isCacheStale),Zn=yr(W=>W.initialize),Mr=yr(W=>W.loadInstalledApps);i.useEffect(()=>{Zn()},[Zn]);const Yr=i.useCallback(W=>{n.revealPath&&n.revealPath(W).catch(()=>{ce.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),ui=i.useCallback(async W=>{if(!K?.path||await lp(K.path,W.id,W.appName)||await wa(K.path,W.appName))return;const Ke=u1(K.path)||x;Ke&&await wa(Ke,W.appName)||ce.error(e("filesView.toast.openInAppFailed",{app:W.appName}))},[x,K?.path,e]),mr=i.useCallback((W,Ie)=>{Ss(W),Un(Ie),En(W==="rename"&&Ie.name||""),Xn(!1)},[]),[us,cn]=i.useState(null),kn=i.useRef(!1),J=i.useRef(null),[st,gt]=i.useState(!1),Pt=Ee(W=>W.setMainTabGuard),Zt=Ee(W=>W.pendingFileNavigation),is=Ee(W=>W.setPendingFileNavigation),ms=Ee(W=>W.pendingFileFocusPath),Fs=Ee(W=>W.setPendingFileFocusPath),qs=Ee(W=>W.shortcutOverrides),er=Ee(W=>W.fileEditorKeymap),qn=ss(W=>W.settingsDefaultFileViewerPreview),Fr=ss(W=>W.showMessageTTSButtons),Bs=Ee(W=>W.expandedEditorToolbar);i.useEffect(()=>{const W=()=>{kn.current=!1,J.current=null,gt(!1)};return document.addEventListener("mouseup",W),()=>document.removeEventListener("mouseup",W)},[]),i.useEffect(()=>()=>{we.current!==null&&window.clearTimeout(we.current),tt.current!==null&&window.clearTimeout(tt.current)},[]);const Lr=i.useCallback((W,Ie)=>{const We=W.split(`
28
- `),Ke=Math.max(1,Ie.start),ct=Math.min(We.length,Ie.end);return Ke>ct?"":We.slice(Ke-1,ct).join(`
29
- `)},[]),gn=ym({source:"file",fileLabel:K?.path??null,language:K?.path&&Ai(K.path)||"text",getCodeForRange:W=>Lr(et,wm(W)),toStoreRange:W=>({startLine:W.start,endLine:W.end}),fromDraftRange:W=>({start:W.startLine,end:W.endLine})}),{drafts:tr,commentText:xn,setCommentText:Mn,editingDraftId:bn,setSelection:or,saveComment:Cn,cancel:Sr,reset:Or,startEdit:Nr,deleteDraft:Ei}=gn;i.useEffect(()=>{cn(null),Or(),Pt(null),Vt(""),Xt(!1)},[K?.path,Or,Pt]),i.useEffect(()=>{or(us)},[us,or]),i.useEffect(()=>{if(!us&&!bn)return;const W=We=>{const Ke=We.target;Ke.closest('[data-comment-input="true"]')||Ke.closest('[data-comment-card="true"]')||Ke.closest(".cm-gutterElement")||Ke.closest("[data-sonner-toast]")||Ke.closest("[data-sonner-toaster]")||xn.trim()||(cn(null),Sr())},Ie=setTimeout(()=>{document.addEventListener("click",W)},100);return()=>{clearTimeout(Ie),document.removeEventListener("click",W)}},[Sr,xn,bn,us]);const fi=i.useCallback((W,Ie)=>{const We=Ie??us??void 0;Ie&&cn(Ie),Cn(W,We),cn(null)},[us,Cn]),Mi=i.useCallback((W,Ie)=>{const We=[];for(const Ke of Ie){if(!(Ke&&typeof Ke.name=="string"&&Ke.name.length>0)||!g&&Ke.name.startsWith(".")||!b&&x1(Ke.name))continue;const ct=Ke.name,ot=Qs(Ke.path||""),es=ot?h1(ot)?ot:Qs(`${W}/${ot}`):Qs(`${W}/${ct}`),Cs=Ke.isDirectory?"directory":"file",Rs=Cs==="file"&&ct.includes(".")?ct.split(".").pop()?.toLowerCase():void 0;We.push({name:ct,path:es,type:Cs,extension:Rs})}return m1(We)},[b,g]),nn=i.useCallback(async W=>{const Ie=Qs(W.trim());if(!Ie||yt.current.has(Ie)||_e.current.has(Ie))return;_e.current=new Set(_e.current),_e.current.add(Ie);const We=nt.current+1;nt.current=We,Ye.current=new Map(Ye.current),Ye.current.set(Ie,We);const Ke=()=>Ye.current.get(Ie)===We;await(n.listDirectory?n.listDirectory(Ie).then(ot=>ot.entries.map(es=>({name:es.name,path:es.path,isDirectory:es.isDirectory}))):Vn.listLocalDirectory(Ie).then(ot=>ot.map(es=>({name:es.name,path:es.path,isDirectory:es.isDirectory})))).then(ot=>{if(!Ke())return;const es=Mi(Ie,ot);yt.current=new Set(yt.current),yt.current.add(Ie),bt(Cs=>{if(!Cs[Ie])return Cs;const Rs={...Cs};return delete Rs[Ie],Rs}),Je(Cs=>({...Cs,[Ie]:es}))}).catch(ot=>{if(!Ke())return;const es=ot instanceof Error?ot.message:String(ot??"");if(es==="Directory not found"&&x&&Ie!==x){G(x,Ie),bt(Cs=>{if(!Cs[Ie])return Cs;const Rs={...Cs};return delete Rs[Ie],Rs});return}console.error("Failed to load files directory:",ot),bt(Cs=>({...Cs,[Ie]:es}))}).finally(()=>{Ke()&&(Ye.current=new Map(Ye.current),Ye.current.delete(Ie),_e.current=new Set(_e.current),_e.current.delete(Ie))})},[n,Mi,G,x]),hr=i.useCallback(async()=>{x&&(yt.current=new Set,_e.current=new Set,Ye.current=new Map,bt({}),Je(W=>Object.keys(W).length===0?W:{}),await nn(x))},[nn,x]),Ys=i.useCallback(async W=>{if(!W){await hr();return}const Ie=Qs(W);yt.current=new Set(yt.current),yt.current.delete(Ie),_e.current=new Set(_e.current),_e.current.delete(Ie),await nn(Ie)},[nn,hr]),yn=i.useRef(""),Qr=i.useRef("");i.useEffect(()=>{if(!x)return;const W=`${x}|h${g?"1":"0"}|g${b?"1":"0"}`,Ie=yn.current!==x,We=Qr.current!==W;!Ie&&!We||(Ie&&(yn.current=x,Ot(""),xt(null),Gt(""),Bt(null),I(!1)),We&&(Qr.current=W,yt.current=new Set,_e.current=new Set,Ye.current=new Map,bt({}),Je(Ke=>Object.keys(Ke).length===0?Ke:{}),nn(x)))},[nn,x,b,g]),i.useEffect(()=>{if(!n.listDirectory)return;const W=()=>{if(!document.hidden&&ue.length>0)for(const Ie of ue)Ys(Ie)};return document.addEventListener("visibilitychange",W),()=>document.removeEventListener("visibilitychange",W)},[ue,n.listDirectory,Ys]),i.useEffect(()=>{if(!n.listDirectory||ue.length===0)return;const W=setInterval(()=>{if(!document.hidden)for(const Ie of ue)Ys(Ie)},8e3);return()=>clearInterval(W)},[ue,n.listDirectory,Ys]);const co=i.useCallback(async W=>{if(W?.preventDefault(),!Ds||!js)return;Xn(!0);const Ie=()=>{Ss(null)},We=ct=>{ce.error(ct)},Ke=()=>{Xn(!1)};if(js==="createFile"){if(!Es.trim()){We(e("sidebarFilesTree.toast.filenameRequired")),Ke();return}if(!n.writeFile){We(e("sidebarFilesTree.toast.writeNotSupported")),Ke();return}const ct=Ds.path,ot=ct?`${ct}/`:"",es=Qs(`${ot}${Es.trim()}`);await n.writeFile(es,"").then(async Cs=>{Cs.success&&(ce.success(e("sidebarFilesTree.toast.fileCreated")),await Ys(ct)),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}if(js==="createFolder"){if(!Es.trim()){We(e("sidebarFilesTree.toast.folderNameRequired")),Ke();return}const ct=Ds.path,ot=ct?`${ct}/`:"",es=Qs(`${ot}${Es.trim()}`);await n.createDirectory(es).then(async Cs=>{Cs.success&&(ce.success(e("sidebarFilesTree.toast.folderCreated")),await Ys(ct)),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}if(js==="rename"){if(!Es.trim()){We(e("sidebarFilesTree.toast.nameRequired")),Ke();return}if(!n.rename){We(e("sidebarFilesTree.toast.renameNotSupported")),Ke();return}const ct=Ds.path,ot=ct.split("/").slice(0,-1).join("/"),es=ot?`${ot}/`:"",Cs=Qs(`${es}${Es.trim()}`);await n.rename(ct,Cs).then(async Rs=>{Rs.success&&(ce.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await Ys(ot),x&&de(x,ct),(K?.path===ct||K?.path.startsWith(`${ct}/`))&&(x&&$(x,null),Ot(""),xt(null),Gt(""),Bt(null),d&&I(!1))),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}if(js==="delete"){if(!n.delete){We(e("sidebarFilesTree.toast.deleteNotSupported")),Ke();return}const ct=Ds.path,ot=ct.split("/").slice(0,-1).join("/");await n.delete(ct).then(async es=>{es.success&&(ce.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await Ys(ot),x&&de(x,ct),(K?.path===ct||K?.path.startsWith(`${ct}/`))&&(x&&$(x,null),Ot(""),xt(null),Gt(""),Bt(null),d&&I(!1))),Ie()}).catch(()=>We(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}Ke()},[js,Ds,Es,n,Ys,d,de,x,K?.path,$,e]);i.useEffect(()=>{if(!p){kt([]),St(!1);return}const W=k.trim();if(!W){kt([]),St(!1);return}let Ie=!1;return St(!0),C(p,W,150,{includeHidden:g,respectGitignore:!b,type:"file"}).then(We=>{if(Ie)return;const ct=We.filter(ot=>b||!b1(ot.path)).map(ot=>({name:ot.name,path:Qs(ot.path),type:"file",extension:ot.extension,relativePath:ot.relativePath}));kt(ct)}).catch(()=>{Ie||kt([])}).finally(()=>{Ie||St(!1)}),()=>{Ie=!0}},[p,k,C,g,b]);const Br=i.useCallback(async(W,Ie)=>{if(n.readFile)return(await n.readFile(W,{...Ie??{},directory:x||void 0})).content??"";const We=new URLSearchParams({path:W});Ie?.allowOutsideWorkspace&&We.set("allowOutsideWorkspace","true"),Ie?.outsideFileGrant&&We.set("outsideFileGrant",Ie.outsideFileGrant),Ie?.optional&&We.set("optional","true"),x&&We.set("directory",x);const Ke=await As(`/api/fs/read?${We.toString()}`,{cache:Ie?.optional?"no-store":"default"});if(!Ke.ok){const ct=await Ke.json().catch(()=>({error:Ke.statusText}));throw new Error(ct.error||e("filesView.error.readFileFailed"))}return Ke.text()},[n,x,e]),ar=i.useCallback(async(W,Ie)=>{if(n.statFile){const We=await n.statFile(W,{...Ie??{},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 W=!1;const Ie=[...Ae];return Promise.all(Ie.map(async We=>{try{const Ke=await n.statFile?.(We,{directory:x||void 0});!W&&Ke&&!Ke.isFile&&de(x,We)}catch(Ke){!W&&_u(Ke)&&de(x,We)}})),()=>{W=!0}},[n,Ae,de,x]);const kr=i.useMemo(()=>et.length>go?`${et.slice(0,go)}
30
-
31
- … truncated …`:et,[et]),dn=Lt!==kr,lr=i.useCallback(async()=>{if(!K||!n.writeFile)return ce.error(e("filesView.toast.savingNotSupported")),!1;if(!dn)return!0;if(Lt===""&&et!==""&&as!==K.path)return console.warn(`[saveDraft] refusing to save empty draft for "${K.path}" (${et.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;Xt(!0);try{const W=v1(Lt,Qt);return(await n.writeFile(K.path,W))?.success?(Ot(Lt),K?.path&&Rd(K.path)&&(ds.current=Lt,qe.current=Lt),ar(K.path).then(We=>{We&&(At.current=We)}).catch(()=>{}),!0):(ce.error(e("filesView.toast.writeFileFailed")),!1)}catch(W){return ce.error(W instanceof Error?W.message:e("filesView.toast.saveFailed")),!1}finally{Xt(!1)}},[Lt,et,n,dn,Qt,as,ar,K,e]);i.useEffect(()=>{if(!dn){Pt(null);return}const W=Ie=>Os.current?(Os.current=!1,!0):(hn(!0),an.current=Ie,!1);return Pt(W),()=>{Ee.getState().mainTabGuard===W&&Pt(null)}},[dn,Pt]),i.useEffect(()=>{try{window.localStorage.setItem(Wm,ls?"true":"false")}catch{}},[ls]),i.useEffect(()=>{ls||(xs("idle"),$t.current&&(clearTimeout($t.current),$t.current=null))},[ls]);const Fi=1500;i.useEffect(()=>{const W=!!(K&&n.writeFile);if(!(!ls||!dn||!W||Kt))return $t.current=setTimeout(()=>{lr().then(Ie=>{Ie&&(xs("saved"),setTimeout(()=>xs("idle"),2e3))})},Fi),()=>{$t.current&&(clearTimeout($t.current),$t.current=null)}},[ls,Lt,dn,K,n.writeFile,Kt,lr]),i.useEffect(()=>{xs("idle")},[K?.path]),i.useEffect(()=>{const W=Ie=>{yc(Ie)&&(Ie.key.toLowerCase()==="s"?(Ie.preventDefault(),$t.current&&(clearTimeout($t.current),$t.current=null),Kt||lr().then(We=>{We&&(xs("saved"),setTimeout(()=>xs("idle"),2e3))})):Ie.key.toLowerCase()==="f"&&(Ie.preventDefault(),R(!0)))};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[Kt,lr]);const Li=i.useCallback(async W=>{const Ie=Tt.current+1;Tt.current=Ie;const We=()=>{if(!x)return!1;const Rs=fn.getState().byRoot[x],gr=Rs?.selectedPath??Rs?.openPaths[0]??null;return Tt.current===Ie&&gr===W.path};xt(null),Gt(""),Bt(null);const Ke=Zi(W.path),ct=W.path.toLowerCase().endsWith(".svg"),ot=Ed(W.path);if(d&&I(!0),r.isDesktop&&Ke&&!ct){Ot(""),Vt(""),_t(!0);return}if(!r.isDesktop&&Ke&&!ct){Ot(""),Vt(""),Bt(W.path),_t(!1);return}if(ot){Ot(""),Vt(""),Bt(W.path),_t(!1);return}_t(!0);const es=Td(W.path),Cs={allowOutsideWorkspace:t==="editor-only"&&!!x&&!Pa(W.path,x),outsideFileGrant:es};await Br(W.path,Cs).then(Rs=>{if(!We())return;const gr=Um(Rs);vs(w1(Rs)),Ot(gr),ds.current=gr,qe.current=gr,Vt(gr.length>go?`${gr.slice(0,go)}
32
-
33
- … truncated …`:gr),Bt(W.path),ar(W.path,Cs).then(cr=>{cr&&We()&&(At.current=cr)}).catch(()=>{})}).catch(Rs=>{if(We()){if(y1(Rs)){if(_t(!1),x&&$(x,null),xt(null),Ot(""),Vt(""),Bt(null),At.current=null,S.trim().length>0&&j(""),d&&I(!1),x){const cr=[...Bu(W.path,x),W.path];cr.length>0&&be(x,cr);for(const sl of cr)yt.current.has(sl)||nn(sl)}return}if(_u(Rs)){x&&de(x,W.path),Ot(""),Vt(""),xt(null),At.current=null,d&&I(!1);return}Ot(""),Vt(""),xt(Rs instanceof Error?Rs.message:e("filesView.error.readFileFailed")),At.current=null}}).finally(()=>{We()&&_t(!1)})},[be,d,nn,t,Br,ar,de,x,r.isDesktop,S,$,e]),Vr=i.useCallback(async(W,Ie)=>{if(!x)return;const We=Bu(W,x),Ke=Ie?[...We,W]:We;Ke.length>0&&be(x,Ke);const ct=Ke.map(ot=>{if(!yt.current.has(ot))return nn(ot)}).filter(Boolean);await Promise.all(ct)},[be,nn,x]),mi=i.useCallback((W,Ie)=>{const We=Ie.findIndex(Ke=>Ke.path===W);return We===-1||Ie.length<=1?null:Ie[We+1]??Ie[We-1]??null},[]),rn=i.useCallback(async W=>{if(Os.current)Os.current=!1;else if(dn){hn(!0),Gs.current=W;return}x&&($(x,W.path),U(x,W.path),Vr(W.path,!1)),xt(null),Gt(""),Ot(""),ds.current="",qe.current="",Vt(""),Bt(null),d&&I(!0)},[U,Vr,dn,d,x,$]);i.useEffect(()=>{K?.path&&Vr(K.path,!1)},[Vr,K?.path]),i.useEffect(()=>{if(!K){Tt.current+=1,_t(!1);return}as!==K.path&&Li(K)},[Li,as,K]);const Oi=i.useRef(dn);Oi.current=dn,i.useEffect(()=>{if(!K?.path||as!==K.path)return;let W=!1;const Ie=window.setInterval(()=>{document.hidden||ar(K.path,X).then(We=>{if(W||!We)return;const Ke=At.current;if(!Ke||Ke.path!==K.path){At.current=We;return}const ct=We.mtimeMs!==void 0&&Ke.mtimeMs!==void 0&&We.mtimeMs!==Ke.mtimeMs,ot=We.size!==Ke.size;!ct&&!ot||Oi.current||(At.current=We,Bt(null))}).catch(()=>{})},2e3);return()=>{W=!0,window.clearInterval(Ie)}},[as,ar,K?.path,X]);const uo=i.useCallback(()=>{const W=Gs.current,Ie=an.current,We=Rn.current;if(Gs.current=null,an.current=null,Rn.current=null,Os.current=!0,hn(!1),Vt(kr),We){x&&fe(x,We),K?.path===We&&(W?rn(W):(x&&$(x,null),Ot(""),xt(null),Gt(""),Bt(null),d&&I(!1)));return}if(W){rn(W);return}Ie&&(Pt(null),Ee.getState().setActiveMainTab(Ie))},[kr,rn,d,fe,x,K?.path,Pt,$]),fo=i.useCallback(async()=>{const W=Gs.current,Ie=an.current,We=Rn.current;if(!await lr()){Os.current=!1;return}if(Gs.current=null,an.current=null,Rn.current=null,Os.current=!0,hn(!1),We){x&&fe(x,We),K?.path===We&&(W?await rn(W):(x&&$(x,null),Ot(""),xt(null),Gt(""),Bt(null),d&&I(!1)));return}if(W){await rn(W);return}Ie&&(Pt(null),Ee.getState().setActiveMainTab(Ie))},[rn,d,fe,x,lr,K?.path,Pt,$]),q=i.useCallback(W=>{const Ie=K?.path===W,We=mi(W,xe);if(Ie&&dn){hn(!0),Gs.current=We,Rn.current=W;return}if(x&&fe(x,W),!!Ie){if(We){rn(We);return}x&&$(x,null),Ot(""),xt(null),Gt(""),Bt(null),d&&I(!1)}},[mi,rn,dn,d,xe,fe,x,K?.path,$]),Ce=i.useCallback(W=>{if(Ae.includes(W))return"open";if(w?.files){const Ie=W.startsWith(x+"/")?W.slice(x.length+1):W,We=w.files.find(Ke=>Ke.path===Ie);if(We){if(We.index==="A"||We.working_dir==="?")return"git-added";if(We.index==="D")return"git-deleted";if(We.index==="M"||We.working_dir==="M")return"git-modified"}}return null},[Ae,w,x]),Te=i.useCallback(W=>{if(!w?.files)return null;const Ie=W.startsWith(x+"/")?W.slice(x.length+1):W,We=Ie?`${Ie}/`:"";let Ke=0,ct=0;for(const ot of w.files)ot.path.startsWith(We)&&((ot.index==="M"||ot.working_dir==="M")&&Ke++,(ot.index==="A"||ot.working_dir==="?")&&ct++);return Ke+ct>0?{modified:Ke,added:ct}:null},[w,x]),ze=i.useCallback(async W=>{const Ie=Qs(W);x&&(ve(x,Ie),yt.current.has(Ie)||await nn(Ie))},[nn,x,ve]),ft=i.useMemo(()=>({canRename:gs,canCreateFile:fr,canCreateFolder:Kn,canDelete:Ms,canReveal:jr}),[gs,fr,Kn,Ms,jr]);function Rt(W,Ie){const We=He[W]??[];return We.map((Ke,ct)=>{const ot=Ke.type==="directory",es=ot&&ue.includes(Ke.path),Cs=K?.path===Ke.path,Rs=ct===We.length-1;return s.jsxs("li",{className:"relative",children:[Ie>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Rs&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(N1,{node:Ke,root:x,isExpanded:es,isActive:Cs,isMobile:d,alwaysShowActions:f,status:ot?void 0:Ce(Ke.path),badge:ot?Te(Ke.path):void 0,permissions:ft,downloadFile:n.downloadFile,contextMenuPath:Ue,setContextMenuPath:os,rightClickMenuPath:fs,setRightClickMenuPath:zs,onSelect:rn,onToggle:ze,onRevealPath:Yr,onOpenDialog:mr}),ot&&es&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[rt[Ke.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:rt[Ke.path],children:rt[Ke.path]}),s.jsxs($e,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Ys(Ke.path)},children:[s.jsx(D,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,Rt(Ke.path,Ie+1)]})]},Ke.path)})}const qt=!!(K?.path&&Zi(K.path)),Yt=!!(K?.path&&K.path.toLowerCase().endsWith(".svg")),ys=!!(K?.path&&Ed(K.path)),pr=i.useMemo(()=>Qs(Zt?.path??""),[Zt?.path]),Cr=!!(Zt&&pr&&ye&&ye===pr&&!Ze&&!jt&&!qt&&!ys),oe=i.useMemo(()=>ec(x,ye),[ye,x]),lt=!!(K&&(!qt||Yt)&&!ys&&et.length>0),it=!!(K&&oe.length>0),pt=!!(K&&!Le&&!qt&&!ys&&n.writeFile&&et.length<=go),zt=!!(K?.path&&$u(K.path)),Is=!!(K?.path&&S1(K.path)),Xs=!!(K?.path&&Xo(K.path)),un=!!(K?.path&&Rd(K.path)),Sn=!!(K&&!qt&&!ys)&&!zt&&!un&&!(Xs&&te==="preview"),An=i.useMemo(()=>ye?em(ye):null,[ye]),[hi,pi]=i.useState(null);i.useEffect(()=>{let W=!1;const Ie=K?.path;if(!Ie||An){pi(null);return}return pi(null),fg(Ie).then(We=>{W||pi(We)}),()=>{W=!0}},[K?.path,An]),i.useEffect(()=>{!pt&&Y==="edit"&&H("view")},[pt,Y]);const gi="openchamber:files:md-viewer-mode",Qa="openchamber:files:html-viewer-mode",Ja="openchamber:files:json-viewer-mode";i.useEffect(()=>{const W=K?.path;if(!W)return;const Ie=qn?"view":"edit";H(ee.current[W]??Ie);let We=qn?"preview":"edit";try{const ot=localStorage.getItem(gi);(ot==="preview"||ot==="edit")&&(We=ot)}catch{}ae(Ne.current[W]??We);let Ke=qn?"preview":"edit";try{const ot=localStorage.getItem(Qa);(ot==="preview"||ot==="edit")&&(Ke=ot)}catch{}ke(De.current[W]??Ke),ge(Be.current[W]??"preview");let ct=qn?"tree":"text";try{const ot=localStorage.getItem(Ja);(ot==="tree"||ot==="text")&&(ct=ot)}catch{}Se(ct)},[K?.path,qn]);const vh=i.useCallback(W=>{const Ie=K?.path;Ie&&(ee.current[Ie]=W),H(W)},[K?.path]),jh=i.useCallback(W=>{const Ie=K?.path;Ie&&(Ne.current[Ie]=W),ae(W);try{localStorage.setItem(gi,W)}catch{}},[K?.path]),mo=i.useCallback(()=>re,[re]),Sh=i.useCallback(W=>{Se(W);try{localStorage.setItem(Ja,W)}catch{}},[]),Nh=i.useCallback(W=>{const Ie=K?.path;Ie&&(De.current[Ie]=W),ke(W);try{localStorage.setItem(Qa,W)}catch{}},[K?.path]),kh=i.useCallback(W=>{const Ie=K?.path;if(Ie&&(Be.current[Ie]=W),Ct.current&&(clearTimeout(Ct.current),Ct.current=null),at.current!==null&&(cancelAnimationFrame(at.current),at.current=null),W==="edit")Vt(ds.current||et),ge(W);else{ds.current=Lt;const We=Ie;ge("edit"),at.current=requestAnimationFrame(()=>{at.current=requestAnimationFrame(()=>{at.current=null,!(x&&We&&fn.getState().byRoot[x]?.selectedPath!==We)&&(se(Ke=>Ke+1),ge("preview"))})});return}},[Lt,et,x,K?.path]),Xa=i.useCallback(async(W,Ie)=>{if(!n.writeFile||Ie===qe.current)return!1;if(!(await n.writeFile(W,Ie))?.success)return ce.error(e("filesView.toast.writeFileFailed")),!1;ds.current=Ie,qe.current=Ie,Vt(Ie);const Ke=await ar(W,X).catch(()=>null);return Ke&&(At.current=Ke),!0},[n,ar,X,e]);i.useEffect(()=>()=>{Ct.current&&(clearTimeout(Ct.current),Ct.current=null),at.current!==null&&(cancelAnimationFrame(at.current),at.current=null)},[Q,K?.path]);const Ch=i.useCallback(W=>{if(ds.current=W,!K?.path||Q!=="preview"||!n.writeFile)return;Ct.current&&clearTimeout(Ct.current);const Ie=K.path;Ct.current=setTimeout(()=>{Ct.current=null,Xa(Ie,W).then(We=>{We&&(Jt(!0),setTimeout(()=>Jt(!1),1500))}).catch(We=>{ce.error(We instanceof Error?We.message:e("filesView.toast.saveFailed"))})},Fi)},[Q,n.writeFile,Xa,K?.path,e]),Ah=i.useMemo(()=>un&&(ds.current||Lt)||et,[Lt,et,un]),Kc=i.useCallback(()=>te,[te]);i.useEffect(()=>{const W=We=>{const Ke=We?"view":"edit",ct=We?"preview":"edit",ot=We?"tree":"text";for(const es of Ae)ee.current[es]=Ke,$u(es)&&(Ne.current[es]=ct),Xo(es)&&(De.current[es]=ct);H(Ke),ae(ct),ke(ct),Se(ot);try{localStorage.setItem(gi,ct),localStorage.setItem(Qa,ct),localStorage.setItem(Ja,ot)}catch{}},Ie=We=>{const Ke=!!We.detail?.enabled;W(Ke)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",Ie),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",Ie)}},[Ae]),i.useEffect(()=>{if(!Zt||!x)return;const W=()=>{typeof window>"u"||hs.current===null&&(hs.current=window.requestAnimationFrame(()=>{hs.current=null,ht(_r=>_r+1)}))},Ie=(_r,xi)=>{if(_r.state.doc.length!==xi.length)return!1;if(xi.length===0)return!0;const nl=Math.min(128,xi.length);if(_r.state.sliceDoc(0,nl)!==xi.slice(0,nl))return!1;const cd=Math.max(0,xi.length-nl);return _r.state.sliceDoc(cd,xi.length)===xi.slice(cd)},We=Qs(Zt.path);if(!We){is(null),ps.current={key:"",attempts:0};return}const Ke=`${We}:${Zt.line}:${Zt.column??1}`;if(ps.current.key!==Ke&&(ps.current={key:Ke,attempts:0}),K?.path!==We){if(Ts)return;rn(z(We));return}if(Ze||as!==We)return;if(jt||qt||ys){is(null),ps.current={key:"",attempts:0};return}if(!pt)return;if(Y!=="edit"){H("edit");return}const ct=dt.current;if(!ct){W();return}if(!Ie(ct,Lt)){W();return}const ot=Math.max(1,Math.min(Zt.line,ct.state.doc.lines)),es=ct.state.doc.line(ot),Cs=Math.max(1,Zt.column||1),Rs=Math.max(0,es.to-es.from),gr=Math.min(Rs,Cs-1),cr=es.from+gr;if(!(ct.state.selection.main.head===cr)||ps.current.attempts===0){ps.current.attempts+=1,ct.dispatch({selection:{anchor:cr},effects:ni.scrollIntoView(cr,{y:"center"})}),ct.focus(),W();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const _r=dt.current;_r&&(_r.dispatch({selection:{anchor:cr},effects:ni.scrollIntoView(cr,{y:"center"})}),_r.focus())}),is(null),ps.current={key:"",attempts:0}},[pt,Ts,Lt,Ht,jt,Ze,qt,ys,as,rn,Zt,x,K?.path,is,Y,z]),i.useEffect(()=>{if(!ms||!x)return;const W=Qs(ms);if(!W){Fs(null);return}if(K?.path!==W){if(Ts)return;rn(z(W));return}if(!(Ze||as!==W||jt||qt||ys)){if(pt&&Y==="edit"){const Ie=dt.current;if(!Ie)return;Ie.focus()}Fs(null)}},[pt,Ts,jt,Ze,rn,qt,ys,as,ms,x,K?.path,Fs,Y,z]);const Bi=i.useCallback(W=>{if(!d||!W||!W.hasFocus||typeof window>"u")return;const Ie=window.visualViewport;if(!Ie)return;const We=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,We-(Ie.offsetTop+Ie.height))<=0)return;const ct=W.state.selection.main.head,ot=W.coordsAtPos(ct);if(!ot)return;const es=Math.round(Ie.offsetTop+Ie.height),Rs=ot.bottom+20-es;Rs<=0||(W.scrollDOM.scrollTop+=Rs)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const W=()=>{window.requestAnimationFrame(()=>{Bi(dt.current)})},Ie=window.visualViewport;return Ie?.addEventListener("resize",W),Ie?.addEventListener("scroll",W,{passive:!0}),document.addEventListener("selectionchange",W),()=>{Ie?.removeEventListener("resize",W),Ie?.removeEventListener("scroll",W),document.removeEventListener("selectionchange",W)}},[d,Bi]),i.useEffect(()=>{if(!pt||Y!=="edit"||d)return;const W=ii("open_go_to_line",qs),Ie=We=>{const Ke=We.target;if(Ke?.closest('[role="dialog"]'))return;const ct=!!Ke?.closest(".cm-editor");Ke?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!ct||!document.activeElement?.closest(".cm-editor")||ia(We,W)&&(We.preventDefault(),Gn(!0))};return window.addEventListener("keydown",Ie),()=>window.removeEventListener("keydown",Ie)},[pt,d,qs,Y]);const qc=i.useMemo(()=>{if(!K?.path)return[Hl(o)];const W=Ai(K.path),Ie=[Hl(o,W?{syntaxColors:!1}:void 0)],We=An??hi;return We&&Ie.push(We),W&&Ie.push(vm({language:W,themeName:o.metadata.id,theme:tm(o)})),N&&Ie.push(ni.lineWrapping),d&&Ie.push(ni.updateListener.of(Ke=>{Ke.view.hasFocus&&(Ke.selectionSet||Ke.focusChanged||Ke.viewportChanged||Ke.geometryChanged)&&window.requestAnimationFrame(()=>{Bi(Ke.view)})})),Ie},[o,K?.path,An,hi,N,d,Bi]),Yc=i.useMemo(()=>({light:Fe.metadata.id,dark:Me.metadata.id}),[Fe.metadata.id,Me.metadata.id]),Vo=K?.path&&qt&&!r.isDesktop&&!Yt?`${K.path}|${X.allowOutsideWorkspace?"outside":"workspace"}|${X.outsideFileGrant??""}`:"",_o=K?.path&&ys?`${K.path}|${X.allowOutsideWorkspace?"outside":"workspace"}|${X.outsideFileGrant??""}`:"",$o=K?.path&&Xs&&te==="preview"&&!r.isVSCode?K.path:"",Za=e("filesView.error.readFileFailed"),{readyKey:Qc,nonce:Jc}=Nl(Vo,xt,Za),{readyKey:Xc,nonce:Dh}=Nl($o,xt,Za),{readyKey:Zc,nonce:ed}=Nl(_o,xt,Za),td=!!(Vo&&Qc!==Vo),Ih=!!($o&&Xc!==$o),sd=!!(_o&&Zc!==_o),nd=K?.path&&qt?r.isDesktop?Yt?`data:${Md(K.path)};utf8,${encodeURIComponent(et)}`:rs:Yt?`data:${Md(K.path)};utf8,${encodeURIComponent(et)}`:Qc===Vo?Ci().authenticatedAsset("/api/fs/raw",{path:K.path,allowOutsideWorkspace:X.allowOutsideWorkspace?"true":void 0,outsideFileGrant:X.outsideFileGrant,directory:x||void 0}):"":"",rd=K?.path&&ys&&Zc===_o?Ci().authenticatedAsset("/api/fs/raw",{path:K.path,allowOutsideWorkspace:X.allowOutsideWorkspace?"true":void 0,outsideFileGrant:X.outsideFileGrant,directory:x||void 0}):"",id=i.useCallback(W=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:rd,className:"h-full w-full border-0",title:W.name},ed)}),[rd,ed]);i.useEffect(()=>{let W=!1;return(async()=>{if(!r.isDesktop||!K?.path||!qt||Yt){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(K.path,X).then(Ke=>Ke.dataUrl):(async()=>{const Ke=await As("/api/fs/raw",{query:{path:K.path,allowOutsideWorkspace:X.allowOutsideWorkspace?"true":void 0,outsideFileGrant:X.outsideFileGrant,directory:x||void 0}});if(!Ke.ok)throw new Error(e("filesView.error.readFileFailed"));const ct=await Ke.blob(),ot=URL.createObjectURL(ct);return W?(URL.revokeObjectURL(ot),""):(Ut.current=ot,ot)})()).then(Ke=>{W||(Gt(Ke),Bt(K.path))}).catch(Ke=>{Ut.current&&(URL.revokeObjectURL(Ut.current),Ut.current=""),W||(Gt(""),xt(Ke instanceof Error?Ke.message:e("filesView.error.readFileFailed")),Bt(null))}).finally(()=>{W||_t(!1)})})(),()=>{W=!0}},[n,qt,Yt,x,r.isDesktop,K?.path,X,e]),i.useEffect(()=>()=>{Ut.current&&(URL.revokeObjectURL(Ut.current),Ut.current="")},[]);const Ph=i.useCallback(()=>Ss(null),[]),Th=i.useMemo(()=>Nm({drafts:tr,editingDraftId:bn,commentText:xn,onTextChange:Mn,selection:us,isDragging:st,fileLabel:K?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:W=>({start:W.startLine,end:W.endLine}),onSave:fi,onCancel:()=>{cn(null),Sr()},onEdit:W=>{Nr(W),cn({start:W.startLine,end:W.endLine})},onDelete:Ei}),[Sr,xn,Ei,bn,tr,fi,st,us,K?.path,Mn,Nr]),od=i.useCallback((W,Ie)=>s.jsx("div",{className:"h-full",children:s.jsx(_h,{file:{name:W.name,contents:Ie,lang:Ai(W.path)||void 0},options:{disableFileHeader:!0,overflow:N?"wrap":"scroll",theme:Yc,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,Yc,N]),el=({exitFullscreenOnly:W=!1,layout:Ie="floating"}={})=>{if(!K)return null;const Ke=Ie==="docked"?"pointer-events-auto flex flex-wrap items-center gap-1":"pointer-events-auto flex items-center gap-1 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-1 shadow-sm",ct=(ot,es)=>s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:es})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:ot})]});return s.jsxs("div",{className:Ke,children:[pt&&Y==="edit"&&s.jsxs(s.Fragment,{children:[Kt?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(D,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):ls&&ts==="saved"&&!dn?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(D,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):dn?ct(e(ls?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${il()}+S`}),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{lr()},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(ls?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${il()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${il()}+S`}),children:s.jsx(D,{name:"save-3",className:"size-4"})})):null,ct(e(ls?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Ps(ot=>!ot),className:Pe("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",ls?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(ls?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(ls?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:ls?s.jsx(D,{name:"file-check-fill",className:"size-4"}):s.jsx(D,{name:"file-check",className:"size-4"})}))]}),s.jsxs(sn,{onOpenChange:Z,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(en,{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(D,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(tn,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[jn.map(ot=>s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{ui(ot)},children:[s.jsx(f1,{label:ot.label,iconDataUrl:ot.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:ot.label})]},ot.id)),ln?s.jsxs(bs,{className:"flex items-center gap-2",onClick:()=>{Mr(!0)},children:[s.jsx(D,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!qt&&!ys&&s.jsxs(s.Fragment,{children:[ct(e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>O(!N),className:Pe("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",N?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(D,{name:"text-wrap",className:"size-4"})})),Y==="edit"&&s.jsxs(s.Fragment,{children:[ct(e("filesView.editor.findInFile"),s.jsx($e,{variant:"ghost",size:"sm",onClick:ot=>{R(!L),ot.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(D,{name:"search",className:"size-4"})})),ct(e("filesView.editor.goToLine"),s.jsx($e,{variant:"ghost",size:"sm",onClick:ot=>{Gn(es=>!es),ot.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(D,{name:"menu-fold-2",className:"size-4"})})),s.jsx(l1,{open:qr,onOpenChange:Gn,view:dt.current,variant:"inline"})]})]}),Sn&&pt&&!Is&&!Xs&&s.jsx(aa,{currentMode:Y==="view"?"preview":"edit",onToggle:()=>{vh(Y==="view"?"edit":"view")}}),(zt||Xo(K?.path??""))&&s.jsx(aa,{currentMode:zt?mo():Kc(),onToggle:()=>{Xo(K?.path??"")?Nh(Kc()==="preview"?"edit":"preview"):jh(mo()==="preview"?"edit":"preview")}}),zt&&mo()==="preview"&&Fr&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"size-6 p-0 text-muted-foreground opacity-65 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent","aria-label":e(ns?"filesView.tts.stopSpeaking":"filesView.tts.readAloud"),onClick:()=>{ns?Ve():et.trim()&&Wt(et)},children:ns?s.jsx(D,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(D,{name:"volume-up",className:"size-4"})})}),s.jsx(Ft,{sideOffset:8,children:e(ns?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),un&&s.jsxs(s.Fragment,{children:[s.jsx(aa,{currentMode:Q,onToggle:()=>kh(Q==="preview"?"edit":"preview")}),Q==="preview"&&s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{const ot=Qe.current?.getXml();if(Ct.current&&(clearTimeout(Ct.current),Ct.current=null),K?.path&&ot){if(!await Xa(K.path,ot))return;Jt(!0),setTimeout(()=>Jt(!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:ks?s.jsx(D,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(D,{name:"save-3",className:"size-4"})})]}),Is&&ct(e(me==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>Sh(me==="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(me==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:me==="tree"?s.jsx(D,{name:"code-sslash",className:"size-4"}):s.jsx(D,{name:"node-tree",className:"size-4"})})),lt&&ct(e("filesView.editor.copyFileContents"),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await ur(et)).ok?(Ws(!0),we.current!==null&&window.clearTimeout(we.current),we.current=window.setTimeout(()=>{Ws(!1)},1200)):ce.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFileContents"),"aria-label":e("filesView.editor.copyFileContents"),children:Ks?s.jsx(D,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(D,{name:"clipboard",className:"size-4"})})),it&&ct(e("filesView.editor.copyFilePathTitle",{path:oe}),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await ur(oe)).ok?(Ns(!0),tt.current!==null&&window.clearTimeout(tt.current),tt.current=window.setTimeout(()=>{Ns(!1)},1200)):ce.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFilePathTitle",{path:oe}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:oe}),children:pn?s.jsx(D,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(D,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&&ct(e("filesView.editor.saveFile"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{const ot=n.downloadFile;ot&&ot(K.path).catch(es=>{console.error("Download failed:",es),ce.error(e("sidebarFilesTree.toast.operationFailed"))})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.saveFile"),"aria-label":e("filesView.editor.saveFile"),children:s.jsx(D,{name:"download",className:"size-4"})})),W?ct(e("filesView.editor.exitFullscreen"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>T(!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(D,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&&ct(e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>T(!P),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(P?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:P?s.jsx(D,{name:"fullscreen-exit",className:"size-4"}):s.jsx(D,{name:"fullscreen",className:"size-4"})}))]})},tl=s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[s.jsx($s,{open:Ts,onOpenChange:W=>{W||hn(!0)},children:s.jsxs(_s,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(Hs,{children:[s.jsx(Us,{children:e("filesView.unsaved.title")}),s.jsx(on,{children:e("filesView.unsaved.description")})]}),s.jsxs(ir,{children:[s.jsx($e,{variant:"outline",onClick:()=>{fo()},disabled:Kt,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:e("filesView.unsaved.saveChanges")}),s.jsx($e,{variant:"destructive",onClick:uo,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:Pe("flex flex-col flex-shrink-0",y&&"border-b border-border/40"),children:[y?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&A&&s.jsx("button",{type:"button",onClick:()=>I(!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(D,{name:"arrow-left-s",className:"size-5"})}),d?K?s.jsxs(sn,{children:[s.jsx(en,{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(Hr,{filePath:K.path,extension:K.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Vu,{name:K.name}),s.jsx(D,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(tn,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:xe.map(W=>{const Ie=K?.path===W.path;return s.jsxs(bs,{onSelect:We=>{if(We.target.closest("[data-close-open-file]")){We.preventDefault();return}Ie||rn(W)},className:Pe("flex min-w-0 items-center justify-between gap-2 overflow-hidden",Ie&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[s.jsx(Hr,{filePath:W.path,extension:W.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Vu,{name:W.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:We=>{We.preventDefault(),We.stopPropagation()},onClick:We=>{We.preventDefault(),We.stopPropagation(),q(W.path)},className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":e("filesView.editor.closeFileAria",{name:W.name}),children:s.jsx(D,{name:"close",className:"size-3.5"})})]},W.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):xe.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[le.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"}),le.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:M,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:xe.map(W=>{const Ie=K?.path===W.path;return s.jsxs("div",{title:ec(x,W.path),className:Pe("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",Ie?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[s.jsx(Hr,{filePath:W.path,extension:W.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{Ie||rn(W)},className:"max-w-[12rem] truncate text-left",children:W.name}),s.jsx("button",{type:"button",onClick:We=>{We.stopPropagation(),q(W.path)},className:Pe("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Ie&&!f&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:W.name}),children:s.jsx(D,{name:"close",className:"size-3.5"})})]},W.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,Bs&&!d&&K?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:[oe?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:oe,children:oe}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:el({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[K&&!L&&!(Bs&&!d)&&s.jsx("div",{ref:_,className:"absolute right-3 top-3 z-30",onMouseEnter:()=>V(!0),onMouseLeave:()=>{E.current>0||V(!1)},children:B?el():s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>V(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":e("filesView.editor.showControlsAria"),title:e("filesView.editor.controlsTitle"),children:s.jsx(D,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})}),s.jsx(_n,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:K?Ze||td||sd?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(D,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.loading")]}):jt?s.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:jt}):qt?s.jsx("div",{className:"flex h-full items-center justify-center p-3",children:s.jsx("img",{src:nd,alt:K?.name??e("filesView.editor.imageAltFallback"),className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},Jc)}):ys?id(K):K&&un&&Q==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(d1,{ref:Qe,xml:Ah,onChange:Ch},`${K.path}:${F}`)}):K&&Is&&me==="tree"?s.jsx(Zs,{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(mg,{jsonString:et,maxHeight:"100%",initiallyExpandedDepth:2})})}):K&&zt&&mo()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-3",children:[et.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(et.length/1024)})}),s.jsx(Zs,{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:et,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):K&&Xs&&te==="preview"?Ih?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&&Xc===$o?(()=>{const W=K.path.split("/").map(Ie=>encodeURIComponent(Ie)).join("/");return Ci().authenticatedAsset(`/api/fs/serve${W.startsWith("/")?W:`/${W}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const W=K.path.substring(0,K.path.lastIndexOf("/")+1);return W?et.replace(/<head([^>]*)>/i,`<head$1><base href="${W}">`):et})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")},Dh)}):K&&Sn&&Y==="view"?od(K,Lt):s.jsxs("div",{className:Pe("relative h-full",Cr&&"overflow-hidden"),ref:It,children:[s.jsx("div",{className:Pe("h-full",Cr&&"invisible"),children:s.jsx(Gl,{value:Lt,onChange:Vt,readOnly:!pt,vimMode:er==="vim",extensions:qc,className:"h-full",blockWidgets:Th,onViewReady:W=>{dt.current=W,ht(Ie=>Ie+1),window.requestAnimationFrame(()=>{Bi(W)})},onViewDestroy:()=>{dt.current&&(dt.current=null),ht(W=>W+1)},enableSearch:!0,searchOpen:L,onSearchOpenChange:R,highlightLines:us?{start:Math.min(us.start,us.end),end:Math.max(us.start,us.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(W,Ie,We)=>{if(!(We instanceof MouseEvent)||We.button!==0)return!1;We.preventDefault();const Ke=W.state.doc.lineAt(Ie.from).number;if(us&&!We.shiftKey&&Math.min(us.start,us.end)===Ke&&Math.max(us.start,us.end)===Ke)return cn(null),Sr(),kn.current=!1,J.current=null,gt(!1),!0;if(d&&us&&!We.shiftKey){const ct=Math.min(us.start,us.end,Ke),ot=Math.max(us.start,us.end,Ke);return cn({start:ct,end:ot}),kn.current=!1,J.current=null,gt(!1),!0}if(kn.current=!0,J.current=Ke,gt(!0),us&&We.shiftKey){const ct=Math.min(us.start,Ke),ot=Math.max(us.end,Ke);cn({start:ct,end:ot})}else cn({start:Ke,end:Ke});return!0},mouseover:(W,Ie,We)=>{if(!(We instanceof MouseEvent)||We.buttons!==1||!kn.current||J.current===null)return!1;const Ke=W.state.doc.lineAt(Ie.from).number,ct=Math.min(J.current,Ke),ot=Math.max(J.current,Ke);return cn({start:ct,end:ot}),gt(!0),!1},mouseup:()=>(kn.current=!1,J.current=null,gt(!1),!1)}}})}),Cr&&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(D,{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")})})]})]}),Rh=!!(x&&He[x]),ad=x?rt[x]:null,ld=s.jsxs("section",{className:Pe("flex min-h-0 flex-col overflow-hidden",d?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[s.jsx("div",{className:Pe("flex flex-col gap-2 py-2",d?"px-3":"px-2"),children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(vn,{ref:v,value:S,onChange:W=>j(W.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(D,{name:"close",className:"size-4"})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>mr("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(D,{name:"file-add",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>mr("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(D,{name:"folder-add",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{hr()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(D,{name:"refresh",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx(_n,{outerClassName:"flex-1 min-h-0",className:Pe("py-2",d?"px-3":"px-2"),children:s.jsx("ul",{className:"flex flex-col",children:vt?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):wt.length>0?wt.map(W=>{const Ie=K?.path===W.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{rn(W)},className:Pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Ie?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[Hm(W.path,W.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:W.path,children:W.relativePath??W.path})]})},W.path)}):ad?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:ad}),s.jsxs($e,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{hr()},children:[s.jsx(D,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):Rh?Rt(x,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),Eh=t==="full"&&P&&K&&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:el({exitFullscreenOnly:!0})}),s.jsx(_n,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:Ze||td||sd?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(D,{name:"loader-4",className:"size-4 animate-spin"}),"Loading…"]}):jt?s.jsx("div",{className:"p-4 typography-ui text-[color:var(--status-error)]",children:jt}):qt?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("img",{src:nd,alt:K.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},Jc)}):ys?id(K):zt&&mo()==="preview"?s.jsxs("div",{className:"h-full overflow-auto p-4",children:[et.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(et.length/1024)})}),s.jsx(Zs,{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:et,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):Sn&&Y==="view"?od(K,Lt):s.jsxs("div",{className:Pe("relative h-full",Cr&&"overflow-hidden"),children:[s.jsx("div",{className:Pe("h-full",Cr&&"invisible"),children:s.jsx(Gl,{value:Lt,onChange:Vt,readOnly:!pt,vimMode:er==="vim",extensions:qc,className:"h-full",onViewReady:W=>{dt.current=W,window.requestAnimationFrame(()=>{Bi(W)})},onViewDestroy:()=>{dt.current&&(dt.current=null)}})}),Cr&&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(D,{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(k1,{activeDialog:js,dialogData:Ds,dialogInputValue:Es,onDialogInputChange:En,isDialogSubmitting:Hn,onDialogSubmit:co,onClose:Ph,inputRef:Dt}),Eh,d?A?tl:ld: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:tl})}):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:ld}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:tl})]})]})};function C1(t){return t+1}const wr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},kl=(t,e)=>{const n=wr(t),r=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},A1=(t,e,n)=>kl(kl(kl(t,".opencode"),"plans"),`${e}-${n}.md`),D1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,I1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},P1=(t,e)=>{const n=wr(e.currentDirectory),r=wr(e.homeDirectory),o=wr(t);return n&&o.startsWith(n+"/")?o.slice(n.length+1):r&&o===r?"~":r&&o.startsWith(r+"/")?`~${o.slice(r.length)}`:o},T1=(t,e,n)=>{const r=wr(t.trim());if(!r)return null;const o=n?e.find(c=>c.id===n)??null:null;if(o?.path){const c=wr(o.path);if(r===c||r.startsWith(`${c}/`))return{id:o.id,path:o.path}}const a=e.filter(c=>{const l=wr(c.path);return r===l||r.startsWith(`${l}/`)}).sort((c,l)=>wr(l.path).length-wr(c.path).length)[0];return a?{id:a.id,path:a.path}:null},Km=({targetPath:t=null})=>{const{t:e}=Nt(),n=ut(ie=>ie.currentSessionId),r=ut(ie=>ie.createSession),o=ut(ie=>ie.initializeNewOpenChamberSession),a=ut(ie=>ie.sendMessage),c=ut(ie=>ie.setCurrentSession),l=Cc(),d=Js(ie=>ie.homeDirectory),u=bc(ie=>ie.planModeEnabled),m=ws(ie=>ie.projects),f=ws(ie=>ie.activeProjectId),g=wn(ie=>ie.directories),b=di()??"",p=Ee(ie=>ie.setActiveMainTab),x=Ee(ie=>ie.setSessionSwitcherOpen),y=Jn(),{isMobile:h}=Er(),{currentTheme:C}=Kr(),w=i.useMemo(()=>n?l.find(ie=>ie.id===n)??null:null,[n,l]),S=i.useMemo(()=>{const ie=typeof w?.directory=="string"?w.directory:"";return wr(ie||"")},[w?.directory]),j=i.useMemo(()=>wr(b||S),[b,S]),k=i.useMemo(()=>T1(j,m,f),[f,j,m]),v=i.useMemo(()=>k?g.get(k.path)?.isGitRepo===!0:!1,[k,g]),[A,I]=i.useState(null),[N,O]=i.useState(!1),[P,T]=i.useState(null),L=i.useMemo(()=>!P||!S||!d?P:P1(P,{currentDirectory:S,homeDirectory:d}),[P,S,d]),[R,B]=i.useState(""),{isPlaying:V,play:_,stop:E}=Zf(),Z=ss(ie=>ie.showMessageTTSButtons),[ne,Y]=i.useState(null),H=i.useMemo(()=>L&&L.split("/").pop()||e("planView.file.defaultName"),[L,e]),re=i.useMemo(()=>R.trim()&&hg(R).title||e("planView.title.default"),[R,e]),ae=i.useMemo(()=>re.trim()||e("planView.title.default"),[re,e]),[me,Se]=i.useState(!1),[te,ke]=i.useState(!1),[Q,ge]=i.useState("edit"),F=i.useRef(null),[se,ee]=i.useState(null),Ne=i.useRef(null),De=i.useRef(null),Be="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const ie=localStorage.getItem(Be);if(!ie)return;const Oe=JSON.parse(ie);(Oe==="preview"||Oe==="edit")&&ge(Oe)}catch{}},[]);const Fe=i.useCallback(ie=>{ge(ie);try{localStorage.setItem(Be,JSON.stringify(ie))}catch{}},[]),Me=i.useRef(!1),he=i.useRef(null),[Ae,pe]=i.useState(!1);i.useEffect(()=>{const ie=()=>{Me.current=!1,he.current=null,pe(!1)};return document.addEventListener("mouseup",ie),()=>document.removeEventListener("mouseup",ie)},[]);const ue=i.useCallback((ie,Oe)=>{const Ge=ie.split(`
34
- `),He=Math.max(1,Oe.start),Je=Math.min(Ge.length,Oe.end);return He>Je?"":Ge.slice(He-1,Je).join(`
35
- `)},[]),U=ym({source:"plan",fileLabel:H,language:P&&Ai(P)||"markdown",getCodeForRange:ie=>ue(R,wm(ie)),toStoreRange:ie=>({startLine:ie.start,endLine:ie.end}),fromDraftRange:ie=>({start:ie.startLine,end:ie.endLine})}),{drafts:fe,commentText:de,setCommentText:G,editingDraftId:$,setSelection:ve,saveComment:be,cancel:z,reset:xe,startEdit:je,deleteDraft:K}=U;i.useEffect(()=>{ee(null),xe()},[R,xe]),i.useEffect(()=>{ve(se)},[se,ve]);const ye=i.useCallback(()=>{ee(null),z()},[z]),Le=i.useCallback((ie,Oe)=>{Oe&&ee(Oe),be(ie,Oe??se??void 0),ee(null)},[se,be]);i.useEffect(()=>{if(!se)return;const ie=Ge=>{const He=Ge.target;He.closest('[data-comment-card="true"]')||He.closest('[data-comment-input="true"]')||He.closest(".oc-block-widget")||He.closest(".cm-gutterElement")||He.closest("[data-sonner-toast]")||He.closest("[data-sonner-toaster]")||de.trim()||(ee(null),z())},Oe=window.setTimeout(()=>{document.addEventListener("click",ie)},100);return()=>{window.clearTimeout(Oe),document.removeEventListener("click",ie)}},[z,de,$,h,se]);const Re=i.useMemo(()=>{const ie=P?Ai(P):null,Oe=!!ie&&ie!=="markdown",Ge=[Hl(C,Oe?{syntaxColors:!1}:void 0)],He=em(P||"plan.md");return He&&Ge.push(He),Oe&&ie&&Ge.push(vm({language:ie,themeName:C.metadata.id,theme:tm(C)})),Ge.push(ni.lineWrapping),Ge},[C,P]);i.useEffect(()=>{if(!u&&!t){T(null),B(""),Se(!1);return}let ie=!1;const Oe=async He=>{if(y.files?.readFile)return(await y.files.readFile(He))?.content??"";const Je=Lo()?.files;if(Je?.readFile)return(await Je.readFile(He,{optional:!0}))?.content??"";const rt=await As(`/api/fs/read?path=${encodeURIComponent(He)}&optional=true`,{cache:"no-store"});if(!rt.ok)throw new Error(`Failed to read plan file (${rt.status})`);return rt.text()};return(async()=>{if(T(null),B(""),Y(null),t){Se(!0);try{const He=await Oe(t);if(ie)return;T(t),B(He)}catch{if(ie)return;T(null),B("")}finally{ie||Se(!1)}return}if(!w?.slug||!w?.time?.created||!S){T(null),B("");return}Se(!0);try{const He=A1(S,w.time.created,w.slug),Je=I1(D1(w.time.created,w.slug),d||null);let rt=null,bt=null;try{bt=await Oe(He),rt=He}catch{}if(!rt)try{bt=await Oe(Je),rt=Je}catch{}if(ie)return;if(!rt||bt===null){T(null),B("");return}T(rt),B(bt)}catch{if(ie)return;T(null),B("")}finally{ie||Se(!1)}})(),()=>{ie=!0}},[d,u,y.files,S,w?.slug,w?.time?.created,t]),i.useEffect(()=>{if(!P){Y(null);return}const ie=window.setTimeout(async()=>{Y(null);try{if(y.files?.writeFile){if(!(await y.files.writeFile(P,R))?.success)throw new Error(e("planView.error.writeFailed"))}else{const Oe=await As("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:P,content:R})});if(!Oe.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:Oe.status}))}}catch(Oe){Y(Oe instanceof Error?Oe.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(ie)}},[R,P,y.files,e]),i.useEffect(()=>()=>{F.current!==null&&window.clearTimeout(F.current)},[]);const X=i.useCallback(()=>{p("chat"),x(!1)},[p,x]),M=i.useCallback(async ie=>{if(!k||!A)return;const Oe=await Tn(A.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:ae}),He=[{synthetic:!0,text:await Tn(A.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:ae,plan_path:P??""})}];O(!0);try{X();let Je=null,rt=k.path;if(A.target==="worktree"){if(!v)return;const yt=await Yf(k.path,Qf());if(!yt?.id)return;Je=yt.id,rt=yt.path}else{const yt=await r(void 0,k.path,null);if(!yt?.id)return;Je=yt.id,rt=yt.directory??k.path,o(yt.id,ss.getState().agents??[])}if(!Je)return;const bt=vc.getState();bt.saveSessionModelSelection(Je,ie.providerID,ie.modelID),ie.agent.trim()&&(bt.saveSessionAgentSelection(Je,ie.agent),bt.saveAgentModelForSession(Je,ie.agent,ie.providerID,ie.modelID),bt.saveAgentModelVariantForSession(Je,ie.agent,ie.providerID,ie.modelID,ie.variant||void 0)),c(Je,rt),await a(Oe,ie.providerID,ie.modelID,ie.agent.trim()||void 0,void 0,void 0,He,ie.variant||void 0),I(null)}finally{O(!1)}},[v,r,k,o,A,P,X,a,ae,c]),le=i.useMemo(()=>Nm({drafts:fe,editingDraftId:$,commentText:de,onTextChange:G,selection:se,isDragging:Ae,fileLabel:H,newWidgetId:"plan-new-comment-input",mapDraftToRange:ie=>({start:ie.startLine,end:ie.endLine}),onSave:Le,onCancel:ye,onEdit:ie=>{je(ie),ee({start:ie.startLine,end:ie.endLine})},onDelete:K}),[de,K,$,ye,Le,Ae,se,fe,H,G,je]);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:re}),ne?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:ne,children:e("planView.error.saveFailed")}):null]}),P?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(sn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(en,{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(D,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(Ft,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(tn,{align:"end",children:[s.jsx(bs,{onClick:()=>I({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(bs,{onClick:()=>I({action:"improve",target:"worktree"}),disabled:!v,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(sn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(en,{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(D,{name:"code-ai",className:"size-4"})})})}),s.jsx(Ft,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(tn,{align:"end",children:[s.jsx(bs,{onClick:()=>I({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(bs,{onClick:()=>I({action:"implement",target:"worktree"}),disabled:!v,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(aa,{currentMode:Q,onToggle:()=>Fe(Q==="preview"?"edit":"preview")}),Q==="preview"&&Z&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(V?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{V?E():R.trim()&&_(R)},children:V?s.jsx(D,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(D,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:8,children:e(V?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx($e,{variant:"ghost",size:"sm",onClick:async()=>{(await ur(R)).ok&&(ke(!0),F.current!==null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{ke(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:te?s.jsx(D,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(Am,{open:A!==null,onOpenChange:ie=>{!ie&&!N&&I(null)},target:A?.target??"session",projectDirectory:k?.path??null,submitting:N,onConfirm:M}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(_n,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:me?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:Q==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(Zs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("planView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("planView.error.switchToEditMode")})]}),children:s.jsx(Po,{content:R,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:De,children:s.jsx(Gl,{value:R,onChange:B,readOnly:!1,className:"h-full",extensions:Re,onViewReady:ie=>{Ne.current=ie},onViewDestroy:()=>{Ne.current=null},blockWidgets:le,highlightLines:se?{start:Math.min(se.start,se.end),end:Math.max(se.start,se.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(ie,Oe,Ge)=>{if(!(Ge instanceof MouseEvent)||Ge.button!==0)return!1;Ge.preventDefault();const He=ie.state.doc.lineAt(Oe.from).number;if(se&&!Ge.shiftKey&&Math.min(se.start,se.end)===He&&Math.max(se.start,se.end)===He)return ee(null),z(),Me.current=!1,he.current=null,pe(!1),!0;if(h&&se&&!Ge.shiftKey){const Je=Math.min(se.start,se.end,He),rt=Math.max(se.start,se.end,He);return ee({start:Je,end:rt}),Me.current=!1,he.current=null,pe(!1),!0}if(Me.current=!0,he.current=He,pe(!0),se&&Ge.shiftKey){const Je=Math.min(se.start,He),rt=Math.max(se.end,He);ee({start:Je,end:rt})}else ee({start:He,end:He});return!0},mouseover:(ie,Oe,Ge)=>{if(!(Ge instanceof MouseEvent)||Ge.buttons!==1||!Me.current||he.current===null)return!1;const He=ie.state.doc.lineAt(Oe.from).number,Je=Math.min(he.current,He),rt=Math.max(he.current,He);return ee({start:Je,end:rt}),pe(!0),!1},mouseup:()=>(Me.current=!1,he.current=null,pe(!1),!1)}}})})})})})})]})},R1=8,$c=t=>t,tc=t=>{const e=$c(t).type;return typeof e=="string"?e:""},E1=t=>{const e=$c(t).tool;return typeof e=="string"?e:""},M1=t=>{const e=$c(t).text;return typeof e=="string"?e:""},F1=t=>{const e=tc(t);return e==="tool"?E1(t).trim().toLowerCase()||"tool":e||"unknown"},L1=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=F1(n);e.includes(r)||e.push(r)}return e.join(" + ")},O1=(t,e=R1)=>typeof t!="string"?"":t.length<=e?t:t.slice(-e),B1=t=>t.replace(/\s+/g," ").trim(),V1=t=>{for(const n of t)if(tc(n)==="text"){const r=B1(M1(n));if(r.length===0)continue;return r}const e=t.filter(n=>tc(n)!=="text").length;return e===0?"":`${e} attachment${e===1?"":"s"}`},_1=(t,e,n)=>`${n(t)} / ${n(e)}`,$1=t=>{if(t==="12h")return!0;if(t==="24h")return!1},z1=(t,e)=>{if(!t||!Number.isFinite(t))return"-";const n=$1(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}})},sc={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},ca={user:0,assistant:0,tool:0,other:0},vi=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Cl=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{...sc,total:vi(n)};if(!n||typeof n!="object")return sc;const r=n,o=vi(r.input),a=vi(r.output),c=vi(r.reasoning),l=vi(r.cache?.read),d=vi(r.cache?.write);return{input:o,output:a,reasoning:c,cacheRead:l,cacheWrite:d,total:o+a+c+l+d}},W1=(...t)=>{for(const e of t)if(typeof e=="string"&&e.trim().length>0)return e;return""},nr=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+nr(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+nr(n),0):0,U1=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...ca,assistant:nr(n.text)+nr(n.content)};const o=W1(n.text,n.content,n.value,n.source?.value,n.source?.text?.value);return r==="tool"||e==="tool"?{user:0,assistant:0,tool:nr(n.input)+nr(n.output)+nr(n.error)+nr(n.call?.input)+nr(n.call?.output)+nr(n.call?.error)+nr(n.raw)+Math.round(nr(n.metadata)*.25)+Math.round(nr(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}},zu=(t,e)=>({user:t.user+e.user,assistant:t.assistant+e.assistant,tool:t.tool+e.tool,other:t.other+e.other}),H1=t=>{const e=Oo(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},G1=(t,e)=>{if(t.length===0)return{...ca};const n=t.reduce((r,o)=>{const a=H1(o);let c={...ca};for(const l of o.parts)c=zu(c,U1(l,a));return zu(r,c)},{...ca});return n.user+=e.length,{user:Math.ceil(n.user/4),assistant:Math.ceil(n.assistant/4),tool:Math.ceil(n.tool/4),other:Math.ceil(n.other/4)}},ji=t=>t.toLocaleString(Xi()),K1=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(Xi(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(Xi(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),q1=(t,e)=>!t||!Number.isFinite(t)?"-":jc(t,e,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),Y1=(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}},Q1=()=>{const t=mt.c(202),{t:e}=Nt(),n=Ee(J1);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(X1),m=Cc(),f=pg(u??""),g=ss(Z1);let b;t[1]===Symbol.for("react.memo_cache_sentinel")?(b=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(e0),l(null)},t[1]=b):b=t[1];let p;t[2]!==u?(p=[u],t[2]=u,t[3]=p):p=t[3],i.useEffect(b,p);let x,y;t[4]===Symbol.for("react.memo_cache_sentinel")?(x=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},y=[],t[4]=x,t[5]=y):(x=t[4],y=t[5]),i.useEffect(x,y);let h;t[6]===Symbol.for("react.memo_cache_sentinel")?(h=async(jt,xt)=>{(await ur(xt)).ok?(l(jt),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(Gt=>Gt===jt?null:Gt),d.current=null},2e3)):l(null)},t[6]=h):h=t[6];const C=h;let w;t[7]!==u||t[8]!==m?(w=u?m.find(jt=>jt.id===u)??null:null,t[7]=u,t[8]=m,t[9]=w):w=t[9];const S=w;let j,k,v,A,I,N;if(t[10]!==g||t[11]!==f){j=f.filter(t0);let jt;t[18]!==f?(jt=f.filter(s0),t[18]=f,t[19]=jt):jt=t[19],N=jt;let xt=null;for(let Gt=j.length-1;Gt>=0;Gt=Gt-1,Gt){const Ut=j[Gt];if(Cl(Ut).total>0){xt=Ut;break}}A=xt?Cl(xt):sc,k=gg({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}),I=j.reduce(n0,0);const rs=xt?.info??null;v=Y1(g,rs?.providerID||"",rs?.modelID||""),t[10]=g,t[11]=f,t[12]=j,t[13]=k,t[14]=v,t[15]=A,t[16]=I,t[17]=N}else j=t[12],k=t[13],v=t[14],A=t[15],I=t[16],N=t[17];const O=v,P=O.contextLimit,T=P&&P>0?Math.min(999,A.total/P*100):0;let L;if(t[20]!==f){const jt=[...f].reverse().find(r0)?.info?.system||"";L=G1(f,jt),t[20]=f,t[21]=L}else L=t[21];const R=L,B=R.user,V=R.assistant,_=R.tool,E=Math.max(0,A.input-B-V-_),Z=B+V+_+E,ne=f[0]?.info?.time?.created,Y=f.length>0?f[f.length-1]?.info?.time?.created:null;let H;t[22]!==S?.title||t[23]!==e?(H=S?.title||e("contextSidebar.session.untitled"),t[22]=S?.title,t[23]=e,t[24]=H):H=t[24];const re=S?.time?.created??ne??null,ae=Y??S?.time?.created??null;let me;t[25]!==V||t[26]!==E||t[27]!==_||t[28]!==B?(me={user:B,assistant:V,tool:_,other:E},t[25]=V,t[26]=E,t[27]=_,t[28]=B,t[29]=me):me=t[29];let Se;t[30]!==j.length||t[31]!==Z||t[32]!==k||t[33]!==P||t[34]!==O||t[35]!==f.length||t[36]!==re||t[37]!==ae||t[38]!==me||t[39]!==H||t[40]!==A||t[41]!==I||t[42]!==T||t[43]!==N.length?(Se={sessionTitle:H,messagesCount:f.length,userMessagesCount:N.length,assistantMessagesCount:j.length,createdAt:re,lastActivityAt:ae,providerModel:O,tokenBreakdown:A,usagePercent:T,cacheHitRate:k,totalAssistantCost:I,contextLimit:P,breakdown:me,breakdownTotal:Z},t[30]=j.length,t[31]=Z,t[32]=k,t[33]=P,t[34]=O,t[35]=f.length,t[36]=re,t[37]=ae,t[38]=me,t[39]=H,t[40]=A,t[41]=I,t[42]=T,t[43]=N.length,t[44]=Se):Se=t[44];const te=Se;if(!u){let jt;t[45]!==e?(jt=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=jt):jt=t[46];let xt;return t[47]!==jt?(xt=s.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:jt}),t[47]=jt,t[48]=xt):xt=t[48],xt}let ke;t[49]!==e?(ke=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=ke):ke=t[50];let Q;t[51]!==ke||t[52]!==te.breakdown.user?(Q={key:"user",label:ke,value:te.breakdown.user,color:"var(--status-success)"},t[51]=ke,t[52]=te.breakdown.user,t[53]=Q):Q=t[53];let ge;t[54]!==e?(ge=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=ge):ge=t[55];let F;t[56]!==ge||t[57]!==te.breakdown.assistant?(F={key:"assistant",label:ge,value:te.breakdown.assistant,color:"var(--primary-base)"},t[56]=ge,t[57]=te.breakdown.assistant,t[58]=F):F=t[58];let se;t[59]!==e?(se=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=se):se=t[60];let ee;t[61]!==se||t[62]!==te.breakdown.tool?(ee={key:"tool",label:se,value:te.breakdown.tool,color:"var(--status-warning)"},t[61]=se,t[62]=te.breakdown.tool,t[63]=ee):ee=t[63];let Ne;t[64]!==e?(Ne=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=Ne):Ne=t[65];let De;t[66]!==Ne||t[67]!==te.breakdown.other?(De={key:"other",label:Ne,value:te.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=Ne,t[67]=te.breakdown.other,t[68]=De):De=t[68];let Be;t[69]!==Q||t[70]!==F||t[71]!==ee||t[72]!==De?(Be=[Q,F,ee,De],t[69]=Q,t[70]=F,t[71]=ee,t[72]=De,t[73]=Be):Be=t[73];const Fe=Be;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 he;t[76]!==te.providerModel.modelName||t[77]!==te.providerModel.providerName?(he=s.jsxs("span",{children:[te.providerModel.providerName," / ",te.providerModel.modelName]}),t[76]=te.providerModel.modelName,t[77]=te.providerModel.providerName,t[78]=he):he=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:q1(te.createdAt,n)})]}),t[79]=n,t[80]=te.createdAt,t[81]=Ae):Ae=t[81];let pe;t[82]!==he||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:[he,Ae]}),t[82]=he,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 U;t[88]!==e?(U=e("contextSidebar.section.context"),t[88]=e,t[89]=U):U=t[89];let fe;t[90]!==U?(fe=s.jsx("span",{className:"typography-micro text-muted-foreground",children:U}),t[90]=U,t[91]=fe):fe=t[91];let de;t[92]!==te.tokenBreakdown.total?(de=ji(te.tokenBreakdown.total),t[92]=te.tokenBreakdown.total,t[93]=de):de=t[93];let G;t[94]!==te.contextLimit?(G=te.contextLimit?` / ${ji(te.contextLimit)}`:"",t[94]=te.contextLimit,t[95]=G):G=t[95];let $;t[96]!==de||t[97]!==G?($=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[de,G]}),t[96]=de,t[97]=G,t[98]=$):$=t[98];let ve;t[99]!==fe||t[100]!==$?(ve=s.jsxs("div",{className:"flex items-baseline justify-between",children:[fe,$]}),t[99]=fe,t[100]=$,t[101]=ve):ve=t[101];let be;t[102]!==te.usagePercent?(be=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]=be):be=t[103];let z;t[104]!==be?(z=s.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:be}),t[104]=be,t[105]=z):z=t[105];let xe;t[106]!==e||t[107]!==te.usagePercent?(xe=e("contextSidebar.context.percentUsed",{percent:te.usagePercent.toFixed(1)}),t[106]=e,t[107]=te.usagePercent,t[108]=xe):xe=t[108];let je;t[109]!==xe?(je=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:xe}),t[109]=xe,t[110]=je):je=t[110];let K;t[111]!==ve||t[112]!==z||t[113]!==je?(K=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[ve,z,je]}),t[111]=ve,t[112]=z,t[113]=je,t[114]=K):K=t[114];let ye;t[115]!==e?(ye=e("contextSidebar.stats.messages"),t[115]=e,t[116]=ye):ye=t[116];let Le;t[117]!==te.messagesCount?(Le=ji(te.messagesCount),t[117]=te.messagesCount,t[118]=Le):Le=t[118];let Re;t[119]!==ye||t[120]!==Le?(Re={label:ye,value:Le},t[119]=ye,t[120]=Le,t[121]=Re):Re=t[121];let X;t[122]!==e?(X=e("contextSidebar.stats.user"),t[122]=e,t[123]=X):X=t[123];let M;t[124]!==te.userMessagesCount?(M=ji(te.userMessagesCount),t[124]=te.userMessagesCount,t[125]=M):M=t[125];let le;t[126]!==X||t[127]!==M?(le={label:X,value:M},t[126]=X,t[127]=M,t[128]=le):le=t[128];let ie;t[129]!==e?(ie=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=ie):ie=t[130];let Oe;t[131]!==te.assistantMessagesCount?(Oe=ji(te.assistantMessagesCount),t[131]=te.assistantMessagesCount,t[132]=Oe):Oe=t[132];let Ge;t[133]!==ie||t[134]!==Oe?(Ge={label:ie,value:Oe},t[133]=ie,t[134]=Oe,t[135]=Ge):Ge=t[135];let He;t[136]!==e?(He=e("contextSidebar.stats.cost"),t[136]=e,t[137]=He):He=t[137];let Je;t[138]!==te.totalAssistantCost?(Je=K1(te.totalAssistantCost),t[138]=te.totalAssistantCost,t[139]=Je):Je=t[139];let rt;t[140]!==He||t[141]!==Je?(rt={label:He,value:Je},t[140]=He,t[141]=Je,t[142]=rt):rt=t[142];let bt;t[143]!==Re||t[144]!==le||t[145]!==Ge||t[146]!==rt?(bt=[Re,le,Ge,rt],t[143]=Re,t[144]=le,t[145]=Ge,t[146]=rt,t[147]=bt):bt=t[147];const yt=bt;let _e;t[148]!==yt?(_e=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:yt.map(i0)}),t[148]=yt,t[149]=_e):_e=t[149];let Ye;t[150]!==e?(Ye=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Ye):Ye=t[151];let nt;t[152]!==Ye?(nt=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Ye}),t[152]=Ye,t[153]=nt):nt=t[153];let wt;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?(wt=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(o0)}),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]=wt):wt=t[162];let kt;t[163]!==nt||t[164]!==wt?(kt=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[nt,wt]}),t[163]=nt,t[164]=wt,t[165]=kt):kt=t[165];let vt;t[166]!==Fe||t[167]!==te.breakdownTotal?(vt=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:Fe.map(jt=>jt.value<=0||te.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${jt.value/te.breakdownTotal*100}%`,backgroundColor:jt.color}},jt.key))}),t[166]=Fe,t[167]=te.breakdownTotal,t[168]=vt):vt=t[168];let St;t[169]!==Fe||t[170]!==te.breakdownTotal?(St=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:Fe.map(jt=>{const xt=te.breakdownTotal>0?jt.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:jt.color}}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[jt.label," ",s.jsxs("span",{className:"tabular-nums",children:[xt.toFixed(0),"%"]})]})]},jt.key)})}),t[169]=Fe,t[170]=te.breakdownTotal,t[171]=St):St=t[171];let et;t[172]!==vt||t[173]!==St?(et=s.jsxs("div",{className:"mb-6",children:[vt,St]}),t[172]=vt,t[173]=St,t[174]=et):et=t[174];let Ot;t[175]!==e?(Ot=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=Ot):Ot=t[176];let ns;t[177]!==Ot?(ns=s.jsx("div",{className:"typography-micro text-muted-foreground",children:Ot}),t[177]=Ot,t[178]=ns):ns=t[178];let Wt;if(t[179]!==c||t[180]!==o||t[181]!==f||t[182]!==e||t[183]!==n){let jt;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(jt=xt=>{const Gt=Oo(xt.info).role,Ut=Gt==="assistant",as=Gt==="user",Bt=o[xt.info.id]===!0,Lt=c===xt.info.id,Vt=xt.info.time?.created??null,Kt=L1(xt.parts),Xt=Ut?Cl({info:xt.info,parts:xt.parts}):null,Qt=as?V1(xt.parts):"",vs=O1(xt.info.id),Dt=z1(Vt,n),$t=Kt||"—",Ct=Xt?_1(Xt.input,Xt.output,ji):"",ds=Gt||"unknown",qe=Kt,at=Bt?JSON.stringify({info:xt.info,parts:xt.parts},null,2):"";return s.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[s.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":Bt,onClick:()=>{a(Qe=>({...Qe,[xt.info.id]:Qe[xt.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:[as?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:"})," ",Qt]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:Ut?"min-w-0 truncate text-muted-foreground":"typography-ui-label text-foreground",children:Ut?$t:ds}),s.jsx("span",{className:Ut?"text-right text-muted-foreground tabular-nums":"min-w-0 truncate text-muted-foreground",children:Ut?Ct:qe})]}),s.jsx("span",{className:"text-right font-mono text-muted-foreground",children:vs}),s.jsx("span",{className:"text-right text-muted-foreground",children:Dt})]})}),Bt&&s.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:s.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[s.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:s.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:Qe=>{Qe.stopPropagation(),C(xt.info.id,at)},"aria-label":e(Lt?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Lt?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Lt?s.jsx(D,{name:"check",className:"size-3.5"}):s.jsx(D,{name:"file-copy",className:"size-3.5"})})}),s.jsx(xg,{language:"json",code:at,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},xt.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=jt):jt=t[189],Wt=[...f].reverse().map(jt),t[179]=c,t[180]=o,t[181]=f,t[182]=e,t[183]=n,t[184]=Wt}else Wt=t[184];let Ve;t[190]!==Wt?(Ve=s.jsx("div",{className:"mt-2.5 space-y-1",children:Wt}),t[190]=Wt,t[191]=Ve):Ve=t[191];let Ze;t[192]!==ns||t[193]!==Ve?(Ze=s.jsxs("div",{children:[ns,Ve]}),t[192]=ns,t[193]=Ve,t[194]=Ze):Ze=t[194];let _t;return t[195]!==ue||t[196]!==K||t[197]!==_e||t[198]!==kt||t[199]!==et||t[200]!==Ze?(_t=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,K,_e,kt,et,Ze]})}),t[195]=ue,t[196]=K,t[197]=_e,t[198]=kt,t[199]=et,t[200]=Ze,t[201]=_t):_t=t[201],_t};function J1(t){return t.timeFormatPreference}function X1(t){return t.currentSessionId}function Z1(t){return t.providers}function e0(t){return Object.keys(t).length>0?{}:t}function t0(t){return Oo(t.info).role==="assistant"}function s0(t){return Oo(t.info).isUser}function n0(t,e){const n=vi(e.info.cost);return t+n}function r0(t){return Oo(t.info).isUser&&typeof t.info.system=="string"}function i0(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 o0(t){return s.jsxs("div",{children:[s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:t.label}),s.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:t.value!==null&&t.value!==void 0?t.format==="percent"?`${t.value.toFixed(1)}%`:ji(t.value):"—"})]},t.label)}const a0=(t,e,n)=>JSON.stringify({sessionID:t,directory:e||"",readOnly:n===!0}),l0=(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()},c0=(t,e,n,r,o,a)=>{const c=a0(n,r,o),l=t.get(e);if(l?.signature===c)return l.src;const d=l0(n,r,o,a);return t.set(e,{signature:c,src:d}),d},d0=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.x=="number"&&typeof e.y=="number"},Wu=t=>!t||typeof t!="object"?!1:Object.values(t).every(e=>typeof e=="string"),Ki=t=>{if(!t||typeof t!="object")return!1;const e=t,n=e.bounds;return typeof e.tag=="string"&&typeof e.text=="string"&&typeof e.selector=="string"&&typeof e.path=="string"&&!!n&&typeof n?.x=="number"&&typeof n?.y=="number"&&typeof n?.width=="number"&&typeof n?.height=="number"&&d0(e.center)&&Wu(e.attributes)&&Wu(e.computedStyle)&&Array.isArray(e.ancestry)},zc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([b,p])=>`${b}="${p}"`).join(" "),d=r.computedStyle,u=r.bounds,m=r.center,f=a.replace(/[.:]+$/g,""),g=r.ancestry.map(b=>b.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(b=>typeof b=="string").join(`
36
- `)},qm=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Ur("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 b=await new Promise(p=>u.toBlob(p,"image/jpeg",.82));return b?new File([b],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(n){return console.warn("[preview] failed to capture annotation screenshot:",n),null}return await k0(t,e)},Wc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((y,h)=>{c.onload=()=>y(),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 b=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*b),g.fillRect(a.bounds.x*b,a.bounds.y*p,a.bounds.width*b,a.bounds.height*p),g.strokeRect(a.bounds.x*b,a.bounds.y*p,a.bounds.width*b,a.bounds.height*p);const x=await new Promise(y=>f.toBlob(y,"image/jpeg",.82));return x?new File([x],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},qi="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Qn=new Map,Al=new Map,u0=3e4,Uc=t=>{const e=Qn.get(t);return e?e.expiresAt-Date.now()<=u0?(Qn.delete(t),null):e:null},f0=t=>{try{return new URL(t).origin}catch{return t}};function Ym(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 Qm=t=>new Promise((e,n)=>{const r=new FileReader;r.onloadend=()=>e(typeof r.result=="string"?r.result:qi),r.onerror=()=>n(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),m0=async(t,e=.82)=>{const n=await new Promise(r=>t.toBlob(r,"image/jpeg",e));return n&&(await Qm(n)).split(",",2)[1]||""},h0=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},da=(...t)=>{h0()&&console.info("[preview-capture]",...t)},Jm=(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",p0=(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{}}},g0={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${ko}]`)){let r;try{r=JSON.parse(n.getAttribute(ko)||"")}catch{continue}n.style.setProperty("position","absolute","important"),n.style.setProperty("top",`${r.top}px`,"important"),n.style.setProperty("left",`${r.left}px`,"important"),n.style.setProperty("right","auto","important"),n.style.setProperty("bottom","auto","important"),n.style.setProperty("width",`${r.width}px`,"important"),n.style.setProperty("height",`${r.height}px`,"important"),n.removeAttribute(ko)}}},Ui="data-oc-scroll-pin",x0=t=>{const e=[],n=Jm(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,u=l.scrollLeft||0;if(d<=0&&u<=0)continue;const m=l!==a&&l!==c;m&&l.setAttribute(Ui,JSON.stringify({top:d,left:u})),e.push({el:l,top:d,left:u,tagged:m})}}catch{}return{reapply:()=>{for(const a of e)try{a.el.scrollHeight,a.el.scrollTop!==a.top&&(a.el.scrollTop=a.top),a.el.scrollLeft!==a.left&&(a.el.scrollLeft=a.left)}catch{}},cleanup:()=>{for(const a of e)if(a.tagged)try{a.el.removeAttribute(Ui)}catch{}},snapshot:n}},b0={name:"oc-nested-scroll",afterClone(t){const e=t?.clone;if(!e||typeof e.querySelectorAll!="function")return;const n=e.ownerDocument;if(n)for(const r of e.querySelectorAll(`[${Ui}]`)){let o;try{o=JSON.parse(r.getAttribute(Ui)||"")}catch{r.removeAttribute(Ui);continue}const a=`translate(${-o.left}px, ${-o.top}px)`,c=r.children.length===1&&r.firstElementChild instanceof HTMLElement&&r.firstElementChild.style.willChange==="transform"?r.firstElementChild:null;if(c)c.style.transform=a;else{r.style.overflow="hidden";const l=n.createElement("div");for(l.style.transform=a,l.style.willChange="transform",l.style.display="inline-block",l.style.width="100%";r.firstChild;)l.appendChild(r.firstChild);r.appendChild(l)}r.removeAttribute(Ui)}}},Dl=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await Qm(await n.blob()):null}catch{return null}},y0=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=Uc(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=Al.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 Qn.delete(e),null;const l=await c.json(),d=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",u=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Qn.delete(e),null;const m={proxyBasePath:d,expiresAt:u};return Qn.set(e,m),m}catch{return Qn.delete(e),null}finally{Al.delete(e)}})();r||Al.set(e,o);const a=await o;return a?`${a.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},Xm=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 Dl(n.toString(),"include")??qi;const r=await y0(n),o=r?await Dl(r,"include"):null;return o||(await Dl(n.toString(),"omit")??qi)}catch{return qi}},w0=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 Xm(a,e);r=r.replace(o[0],`url("${c}")`)}return r},Uu=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),Zm=t=>{const e=t.style.cssText;return()=>{t.style.cssText=e}},v0=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},j0=(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"),b=m.whiteSpace.includes("nowrap")||f==="nowrap"||g==="nowrap",p=u.height<=v0(m)*1.7;!b&&(!p||u.width>e*.72)||(r.push(Zm(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]?.()}},S0=(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,b)=>b<m&&g.contains(u)));for(const u of d){const m=u.getBoundingClientRect(),f=a.getComputedStyle(u),g=Math.ceil(m.width)+8,b=Math.ceil(m.height)+2;r?.add(u),o.push(Zm(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=`${b}px`,u.style.minHeight=`${b}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]?.()}},eh=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(S0(t,e,n,f)),o.push(j0(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 b=g.map(p=>({source:p,srcset:p.getAttribute("srcset"),sizes:p.getAttribute("sizes")}));o.push(()=>{for(const p of b)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 Uu(f);const b=await Xm(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",b||qi),await Uu(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 b=await w0(g,t);if(b===g)return;const p=f.style.backgroundImage;o.push(()=>{f.style.backgroundImage=p}),f.style.backgroundImage=b})),()=>{for(let f=o.length-1;f>=0;f-=1)try{o[f]?.()}catch{}}};async function N0(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,b=n.pageYOffset||0,p=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,x=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,y=o.scrollLeft||0,h=o.scrollTop||0,C=d?.scrollLeft||0,w=d?.scrollTop||0,S=u?.scrollLeft||0,j=u?.scrollTop||0,k=Math.max(m,g,p,y,C,S),v=Math.max(f,b,x,h,w,j);da("scroll sources",{windowScrollX:m,windowScrollY:f,pageScrollX:g,pageScrollY:b,visualViewportScrollX:p,visualViewportScrollY:x,rootScrollX:y,rootScrollY:h,bodyScrollX:C,bodyScrollY:w,scrollingElementScrollX:S,scrollingElementScrollY:j,scrollingElementTag:u?.tagName?.toLowerCase()??null,resolvedScrollX:k,resolvedScrollY:v,nestedScrolledElements:Jm(r)});const A=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),I=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),N=Math.min(2,Math.max(1,window.devicePixelRatio||1)),O=o.style.scrollBehavior,P=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const T=x0(r);da("nested scroll snapshot",T.snapshot);let L=()=>{},R=()=>{};try{await r.fonts?.ready.catch(()=>{}),L=await eh(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(k,v),R=p0(r,k,v),T.reapply();const B={backgroundColor:Ym(r),cache:"disabled",dpr:N,embedFonts:!0,fast:!1,height:I,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[g0,b0],quality:.82,width:A},_=await(await Wh(o,B)).toCanvas();if(!_.width||!_.height)return null;const E=_.width/Math.max(1,A),Z=_.height/Math.max(1,I),ne=Math.min(_.width,Math.max(1,Math.round(c*E))),Y=Math.min(_.height,Math.max(1,Math.round(l*Z))),H=Math.max(0,_.width-ne),re=Math.max(0,_.height-Y),ae=Math.min(H,Math.max(0,Math.round(k*E))),me=Math.min(re,Math.max(0,Math.round(v*Z)));da("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:A,captureHeight:I,canvasWidth:_.width,canvasHeight:_.height,xScale:E,yScale:Z,sourceX:ae,sourceY:me,sourceWidth:ne,sourceHeight:Y});const Se=r.createElement("canvas");Se.width=ne,Se.height=Y;const te=Se.getContext("2d");if(!te)return null;te.drawImage(_,ae,me,ne,Y,0,0,ne,Y);const ke=await m0(Se,.82);return ke?await Wc(ke,c,l,c,l,e):null}finally{R(),T.cleanup(),L(),n.scrollTo(k,v),T.reapply(),o.style.scrollBehavior=O,d&&(d.style.scrollBehavior=P)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function k0(t,e){const n=await N0(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),b=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 y="",h=()=>{};try{await o.fonts?.ready.catch(()=>{}),h=await eh(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(u,m);const w=await $h(a).catch(()=>"");y=await zh(a,{quality:.82,pixelRatio:b,width:l,height:d,backgroundColor:Ym(o),imagePlaceholder:qi,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 C=y.split(",",2)[1]||"";return C?await Wc(C,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const th=380,C0=1400,sh=600,A0=24,Hu=200,D0=(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",I0=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},nh=t=>Number.isFinite(t)?Math.min(C0,Math.max(th,Math.round(t))):sh,P0=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},Il=(t,e)=>{const n=nh(t),r=P0(e);return r===null?n:Math.min(n,Math.max(1,r))},T0=(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},R0=(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"),E0=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},M0=(t,e)=>{if(t.label)return t.label;if(t.mode==="file")return E0(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"):R0(t.mode,e)},F0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(Hr,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(D,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(D,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(D,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(D,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(D,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(D,{name:"global",className:"h-3.5 w-3.5"})},L0=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,rh=`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
- })()`,O0=`(() => {
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"}},Gu=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)},B0=(t,e)=>t.length<=e?t:`${t.slice(0,e-3)}...`,ih=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Ku=(t,e,n)=>{const r=ih(e);t.postMessage(n,r)},V0=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}},_0=({rawUrl:t,onNavigate:e})=>{const{t:n}=Nt(),{currentTheme:r}=Kr(),[o,a]=i.useReducer(he=>he+1,0),[c,l]=i.useReducer(he=>he+1,0),[d,u]=i.useState({status:"idle"}),[m,f]=i.useState(""),g=i.useRef(null),b=i.useRef(1),[p,x]=i.useState(!1),[y,h]=i.useState(!1),[C,w]=i.useState("all"),[S,j]=i.useState([]),[k,v]=i.useState(!1),[A,I]=i.useState(null),N=ut(he=>he.currentSessionId),O=ut(he=>he.newSessionDraft?.open),P=Ac(he=>he.addDraft),T=ci(he=>he.addAttachedFile);let L=null;try{L=t?new URL(t):null}catch{L=null}const R=L?L.hostname==="localhost"||L.hostname==="127.0.0.1"||L.hostname==="::1"||L.hostname==="[::1]"||L.hostname==="0.0.0.0":!1,B=L?L.hostname==="0.0.0.0"?new URL(L.toString().replace("0.0.0.0","127.0.0.1")):L:null,V=B?B.toString():"",_=V?`${Wr()||"same-origin"}|${V}`:"",E=r.metadata.variant;i.useEffect(()=>{if(!V||!R){u({status:"idle"});return}const he=Uc(_);if(he?.previewToken){u({status:"ready",proxyBasePath:he.proxyBasePath,previewToken:he.previewToken,expiresAt:he.expiresAt});return}he&&Qn.delete(_);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:V})});if(!pe.ok){Qn.delete(_);const G=await pe.json().catch(()=>({})),$=typeof G?.error=="string"?G.error:`HTTP ${pe.status}`;Ae||u({status:"error",message:$});return}const ue=await pe.json(),U=typeof ue.proxyBasePath=="string"?ue.proxyBasePath:"",fe=typeof ue.previewToken=="string"?ue.previewToken:"",de=typeof ue.expiresAt=="number"?ue.expiresAt:0;if(!U||!fe){Qn.delete(_),Ae||u({status:"error",message:n("contextPanel.preview.proxyError")});return}Qn.set(_,{proxyBasePath:U,previewToken:fe,expiresAt:de}),Ae||u({status:"ready",proxyBasePath:U,previewToken:fe,expiresAt:de})}catch(pe){if(Qn.delete(_),!Ae){const ue=pe instanceof Error?pe.message:String(pe);u({status:"error",message:ue})}}})(),()=>{Ae=!0}},[R,_,c,n,V]);const Z=B&&(B.protocol==="http:"||B.protocol==="https:")?B.toString():"",ne=R&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!ne){f("");return}let he=!1;return f(""),hc(Wr()).then(Ae=>{!he&&Ae&&f(ne)}).catch(()=>{}),()=>{he=!0}},[ne]);const Y=R&&d.status==="ready"&&B&&m===ne?(()=>{const he=B.pathname||"/",Ae=new URLSearchParams(B.search);Ae.set("ocPreview",String(o)),Ae.set("oc_preview_token",d.previewToken||"");const pe=Ae.toString(),ue=B.hash||"";return Ci().authenticatedAsset(`${d.proxyBasePath}${he}${pe?`?${pe}`:""}${ue}`)})():"",H=R?Y:Z,re=R?V0(Y):Z,ae=R&&(d.status==="loading"||d.status==="idle"||m!==ne),me=R&&d.status==="error",Se=i.useCallback(he=>{const Ae=N??(O?"draft":null);if(!Ae){ce.error(n("contextPanel.preview.inspect.attachNoSession"));return}const pe=t||H||"",ue=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},U=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let fe=!1;try{const de=g.current,G=de?await qm(de,he):null;G&&(await T(G),fe=!0)}catch{fe=!1}P({sessionKey:Ae,source:"preview-annotation",fileLabel:pe||"preview",startLine:1,endLine:1,code:zc({pageUrl:pe,viewport:ue,devicePixelRatio:U,target:he,screenshotAttached:fe,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),ce.success(n("contextPanel.preview.inspect.attached"))})()},[T,P,N,H,O,t,n]);i.useEffect(()=>{x(!1),j([]),h(!1),w("all"),v(!1),I(null),b.current=1},[H]),i.useEffect(()=>{const he=g.current?.contentWindow;!p||!he||Ku(he,Y,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[p,k,Y]),i.useEffect(()=>{const he=g.current?.contentWindow;!p||!he||Ku(he,Y,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:E})},[p,E,Y]),i.useEffect(()=>{if(!k||typeof window>"u")return;const he=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopImmediatePropagation(),v(!1))};return window.addEventListener("keydown",he,!0),()=>window.removeEventListener("keydown",he,!0)},[k]),i.useEffect(()=>{if(!R||typeof window>"u")return;const he=ue=>{if(typeof ue=="string")return ue;if(ue==null)return"";try{return JSON.stringify(ue)}catch{return String(ue)}},Ae=ue=>{const U=b.current;b.current+=1,j(fe=>{const de=[...fe,{...ue,id:U}];return de.length>Hu?de.slice(de.length-Hu):de})},pe=ue=>{if(ue.source!==g.current?.contentWindow)return;const U=ue.data;if(!(!U||U.source!=="openchamber-preview-bridge"||U.version!==1)){if(U.type==="ready"){x(!0);return}if(U.type==="console"){const fe=U.level==="error"||U.level==="warn"||U.level==="info"||U.level==="debug"?U.level:"log",de=Array.isArray(U.args)?U.args.map(he).filter(Boolean):[];Ae({level:fe,message:de.join(" "),ts:typeof U.ts=="number"?U.ts:Date.now()});return}if(U.type==="runtime-error"){const fe=he(U.filename),de=typeof U.line=="number"?U.line:null,G=typeof U.column=="number"?U.column:null,$=fe?`${fe}${de!==null?`:${de}${G!==null?`:${G}`:""}`:""}`:"",ve=he(U.stack);Ae({level:"runtime",message:he(U.message)||n("contextPanel.preview.console.runtimeError"),details:[$,ve].filter(Boolean).join(`
160
- `),ts:typeof U.ts=="number"?U.ts:Date.now()});return}if(U.type==="resource-error"){const fe=he(U.tag)||"resource",de=he(U.url);Ae({level:"resource",message:de?`${fe}: ${de}`:fe,details:he(U.outerHTML),ts:typeof U.ts=="number"?U.ts:Date.now()});return}if(U.type==="hover"){I(Ki(U.target)?U.target:null);return}if(U.type==="select"&&Ki(U.target)){I(U.target),v(!1),Se(U.target);return}if(U.type==="navigate-preview"){const fe=typeof U.url=="string"?U.url:"",de=U.navigation==="external"?"external":"proxy";if(fe&&de==="external"){Ii(fe);return}fe&&e(fe)}}};return window.addEventListener("message",pe),()=>{window.removeEventListener("message",pe)}},[Se,R,e,n]);const te=S.filter(he=>he.level==="error"||he.level==="runtime"||he.level==="resource").length,ke=S.filter(he=>D0(he,C)),Q=i.useCallback(()=>{const he=[`Preview URL: ${t||H||""}`,`Events: ${S.length}`,""].join(`
161
- `),Ae=S.map(pe=>{const ue=new Date(pe.ts).toISOString(),U=pe.details?`
162
- ${pe.details}`:"";return`[${ue}] [${pe.level}] ${pe.message}${U}`}).join(`
163
- `);ur(`${he}${Ae}`).then(pe=>{pe.ok?ce.success(n("contextPanel.preview.console.copied")):ce.error(n("contextPanel.preview.console.copyFailed"))})},[S,H,t,n]),ge=i.useCallback(()=>{const he=N??(O?"draft":null);if(!he){ce.error(n("contextPanel.preview.console.attachNoSession"));return}const Ae=[`Preview URL: ${t||H||""}`,`Events: ${S.length}`,""].join(`
164
- `),pe=S.map(ue=>{const U=new Date(ue.ts).toISOString(),fe=ue.details?`
165
- ${ue.details}`:"";return`[${U}] [${ue.level}] ${ue.message}${fe}`}).join(`
166
- `);P({sessionKey:he,source:"preview-console",fileLabel:t||H||"preview",startLine:1,endLine:Math.max(1,S.length),code:`${Ae}${pe}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),ce.success(n("contextPanel.preview.console.attached"))},[P,S,N,H,O,t,n]),[F,se]=i.useState("unknown"),ee=i.useRef(0),Ne=i.useRef(0),De=15e3;i.useEffect(()=>{if(!Y){se("unknown"),ee.current=0,Ne.current=0;return}let he=!1;return ee.current||(ee.current=Date.now(),Ne.current=0),se("unknown"),(async()=>{const pe=await(async()=>{try{return await As(Y,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(he)return;if(!pe){se("unreachable");return}if(pe.status===403||pe.status===404){Qn.delete(_),u({status:"loading"}),l();return}if(pe.status!==502){se("reachable");return}const ue=ee.current||Date.now();if(Date.now()-ue<De){se("starting"),Ne.current+=1;const fe=Ne.current,de=Math.min(2e3,250*Math.pow(2,Math.min(4,fe)));setTimeout(()=>{he||a()},de).unref?.();return}se("unreachable")})(),()=>{he=!0}},[_,Y,o]);const Be=R&&d.status==="ready"&&(F==="unknown"||F==="starting"),Fe=R&&d.status==="ready"&&F==="unreachable",Me=i.useCallback(he=>{if(!R||d.status!=="ready"||typeof window>"u")return;const Ae=he.currentTarget.contentWindow;if(Ae)try{const pe=Ae.location,ue=ih(Y);if(pe.origin!==ue||pe.pathname.startsWith(d.proxyBasePath))return;const U=`${d.proxyBasePath}${pe.pathname}${pe.search}${pe.hash}`;Ae.location.replace(U)}catch{}},[R,Y,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:re||t,children:re||t||n("contextPanel.preview.empty")}),s.jsx($e,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:n("contextPanel.preview.actions.reload"),"aria-label":n("contextPanel.preview.actions.reload"),disabled:!H,children:s.jsx(D,{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&&Ii(Z)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!Z,children:s.jsx(D,{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(he=>!he),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!p,children:s.jsx(D,{name:"cursor",className:"h-3.5 w-3.5"})}):null,R?s.jsxs($e,{type:"button",size:"sm",variant:y?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>h(he=>!he),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(D,{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:[Be?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.startingServer")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.startingServerHint")})]}):Fe?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.upstreamUnreachable")}),s.jsx("div",{className:"text-xs opacity-70",children:n("contextPanel.preview.upstreamUnreachableHint")}),s.jsx($e,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:n("contextPanel.preview.actions.retry")})]}):H&&(!R||F==="reachable")?s.jsxs("div",{className:"relative h-full w-full",children:[s.jsx("iframe",{ref:g,src:H,title:n("contextPanel.preview.iframeTitle"),className:"h-full w-full border-0",style:{colorScheme:E},onLoad:Me,sandbox:R?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${H}:${o}`),k&&A?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:A.bounds.x,top:A.bounds.y,width:A.bounds.width,height:A.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[A.tag,A.text?` · ${A.text}`:""]})}):null]}):ae?s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.loading")}):me?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.proxyError")}),d.status==="error"?s.jsx("div",{className:"text-center text-xs opacity-70",children:d.message}):null]}):s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.invalidUrl")}),y?s.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:n("contextPanel.preview.console.title")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:ge,disabled:S.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:Q,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(he=>s.jsx($e,{type:"button",size:"xs",variant:C===he?"secondary":"ghost",onClick:()=>w(he),children:n(he==="all"?"contextPanel.preview.console.filter.all":he==="errors"?"contextPanel.preview.console.filter.errors":he==="warnings"?"contextPanel.preview.console.filter.warnings":"contextPanel.preview.console.filter.logs")},he))}),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")}):ke.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):ke.map(he=>s.jsx("div",{className:"border-b border-border/30 px-2 py-1 last:border-b-0",children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("span",{className:Pe("shrink-0 uppercase",he.level==="error"||he.level==="runtime"||he.level==="resource"?"text-status-error":he.level==="warn"?"text-status-warning":"text-muted-foreground"),children:he.level}),s.jsx("span",{className:"min-w-0 break-words text-foreground",children:he.message})]})},he.id))})]}):null]})]})},$0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,z0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=Nt(),o=i.useRef(null),a=Ee(Q=>Q.setContextPanelTabTargetPath),c=Co(t),l=c!=="about:blank"?c:"",[d,u]=i.useState(l),[m,f]=i.useState(l),[g,b]=i.useState(()=>l?[l]:[]),[p,x]=i.useState(()=>l?0:-1),[y,h]=i.useReducer(Q=>Q+1,0),[C,w]=i.useState(!!l),[S,j]=i.useState(!1),[k,v]=i.useState(null),[A,I]=i.useState({status:"idle"}),[N,O]=i.useState(""),P=ut(Q=>Q.currentSessionId),T=ut(Q=>Q.newSessionDraft?.open),L=Ac(Q=>Q.addDraft),R=ci(Q=>Q.addAttachedFile),B=i.useCallback(Q=>{!Q||Q==="about:blank"||!e||!n||a(e,n,Q)},[e,n,a]),V=i.useCallback((Q,ge)=>{const F=Co(Q),se=F!=="about:blank"?F:"";f(se),u(se),w(!!se),B(se),b(ee=>{if(!se)return x(-1),[];if(ge?.replaceHistory)return ee;const Ne=p>=0?ee.slice(0,p+1):[];if(Ne[Ne.length-1]===se)return x(Ne.length-1),Ne;const Be=[...Ne,se];return x(Be.length-1),Be})},[p,B]),_=i.useCallback(Q=>{const ge=g[Q];ge&&(x(Q),f(ge),u(ge),w(!0),B(ge))},[g,B]),E=i.useCallback(()=>{if(m){w(!0);try{o.current?.contentWindow?.location.reload()}catch{h()}}},[m]);i.useEffect(()=>{if(!m){I({status:"idle"});return}const Q=f0(m),ge=Uc(Q);if(ge?.previewToken){I({status:"ready",proxyBasePath:ge.proxyBasePath,previewToken:ge.previewToken,expiresAt:ge.expiresAt});return}ge&&Qn.delete(Q);let F=!1;return I({status:"loading"}),w(!0),(async()=>{try{const se=await As("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:m,allowExternal:!0})});if(!se.ok){const Fe=await se.json().catch(()=>({})),Me=typeof Fe?.error=="string"?Fe.error:`HTTP ${se.status}`;F||I({status:"error",message:Me});return}const ee=await se.json(),Ne=typeof ee.proxyBasePath=="string"?ee.proxyBasePath:"",De=typeof ee.previewToken=="string"?ee.previewToken:"",Be=typeof ee.expiresAt=="number"?ee.expiresAt:0;if(!Ne||!De){F||I({status:"error",message:r("contextPanel.preview.proxyError")});return}Qn.set(Q,{proxyBasePath:Ne,previewToken:De,expiresAt:Be}),F||I({status:"ready",proxyBasePath:Ne,previewToken:De,expiresAt:Be})}catch(se){if(!F){const ee=se instanceof Error?se.message:String(se);I({status:"error",message:ee})}}})(),()=>{F=!0}},[m,r]);const Z=m&&A.status==="ready"?`${A.proxyBasePath}|${A.previewToken||""}|${y}`:"";i.useEffect(()=>{if(!Z){O("");return}let Q=!1;return O(""),hc(Wr()).then(ge=>{!Q&&ge&&O(Z)}).catch(()=>{}),()=>{Q=!0}},[Z]);const ne=i.useMemo(()=>{if(N!==Z||!m||A.status!=="ready")return"";try{const Q=new URL(m),ge=Q.pathname||"/",F=new URLSearchParams(Q.search);F.set("ocPreview",String(y)),F.set("oc_preview_token",A.previewToken||"");const se=F.toString();return Ci().authenticatedAsset(`${A.proxyBasePath}${ge}${se?`?${se}`:""}${Q.hash}`)}catch{return""}},[m,A,Z,y,N]),Y=ne||(A.status==="error"?m:""),H=i.useCallback(Q=>{if(!Q||!m||A.status!=="ready")return"";try{const ge=new URL(Q,window.location.origin),F=A.proxyBasePath.endsWith("/")?A.proxyBasePath.slice(0,-1):A.proxyBasePath;if(ge.origin!==window.location.origin||!ge.pathname.startsWith(F))return"";const se=ge.pathname.slice(F.length)||"/",ee=new URL(m).origin;return new URL(`${se}${ge.search}${ge.hash}`,ee).toString()}catch{return""}},[m,A]),re=i.useCallback(Q=>{if(!Q||!m||A.status!=="ready")return"";try{const ge=new URL(Q,window.location.origin),F=new URL(m).origin;if(ge.origin!==window.location.origin||F===window.location.origin)return"";const se=A.proxyBasePath.endsWith("/")?A.proxyBasePath.slice(0,-1):A.proxyBasePath;return ge.pathname.startsWith(se)?"":new URL(`${ge.pathname}${ge.search}${ge.hash}`,F).toString()}catch{return""}},[m,A]),ae=i.useCallback(Q=>{const ge=o.current?.contentWindow;ge&&ge.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:Q},window.location.origin)},[]),me=i.useCallback(async Q=>{const ge=P??(T?"draft":null);if(!ge){ce.error(r("contextPanel.preview.inspect.attachNoSession"));return}const F=o.current,se=F?.contentWindow,ee=F?.getBoundingClientRect(),Ne={width:Number.isFinite(se?.innerWidth)?se?.innerWidth??ee?.width??0:ee?.width??0,height:Number.isFinite(se?.innerHeight)?se?.innerHeight??ee?.height??0:ee?.height??0},De=F?await qm(F,Q):null,Be=!!De;De&&await R(De),L({sessionKey:ge,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:zc({pageUrl:m,viewport:Ne,devicePixelRatio:window.devicePixelRatio||1,target:Q,screenshotAttached:Be,intro:r(Be?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),ce.success(r("contextPanel.preview.inspect.attached"))},[R,L,P,m,T,r]),Se=i.useCallback(()=>{const Q=o.current;v(null),ae(!1),Q&&Gu(Q,ua).catch(()=>{})},[ae]);i.useEffect(()=>{if(!S)return;const Q=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ge.stopImmediatePropagation(),j(!1),Se())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[Se,S]),i.useEffect(()=>()=>Se(),[Se]),i.useEffect(()=>{const Q=ge=>{if(ge.source!==o.current?.contentWindow)return;const F=ge.data;if(!(!F||F.source!=="openchamber-preview-bridge"||F.version!==1)){if(F.type==="ready"){const se=typeof F.url=="string"?F.url:"",ee=H(se);ee&&ee!==m&&V(ee);return}if(F.type==="hover"){v(Ki(F.target)?F.target:null);return}if(F.type==="select"&&Ki(F.target)){v(null),j(!1),ae(!1),me(F.target);return}if(F.type==="navigate-preview"){const se=typeof F.url=="string"?F.url:"",ee=re(se);if(ee){V(ee);return}se&&V(se)}}};return window.addEventListener("message",Q),()=>window.removeEventListener("message",Q)},[V,me,m,H,re,ae]);const te=i.useCallback(()=>{const Q=o.current;if(!(!Q||!m)){if(S){j(!1),Se();return}if(ne){v(null),j(!0),ae(!0);return}j(!0),(async()=>{try{const ge=await Gu(Q,rh);if(j(!1),!ge||!Ki(ge))return;await me(ge)}catch{j(!1),ce.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[me,Se,m,S,ae,ne,r]),ke=i.useCallback(()=>{try{const Q=o.current?.contentWindow?.location.href||"",ge=re(Q);if(ge){w(!0),V(ge);return}}catch{}w(!1),S&&ne&&ae(!0)},[V,re,S,ae,ne]);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:()=>_(p-1),children:s.jsx(D,{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:()=>_(p+1),children:s.jsx(D,{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:E,children:s.jsx(D,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:Q=>{Q.preventDefault(),V(d)},children:s.jsx("input",{value:d,onChange:Q=>u(Q.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(D,{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:()=>{Ii(m)},children:s.jsx(D,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Y?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:Y,title:r("contextPanel.browser.empty"),className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:ke},`${Y}:${y}`),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(Dc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")}),s.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:r("contextPanel.browser.emptyHint")}),s.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:r("contextPanel.browser.trustNotice")})]}),C?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},W0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=Nt(),o=i.useRef(null),a=Ee(I=>I.setContextPanelTabTargetPath),c=Co(t),l=c!=="about:blank"?c:"",[d,u]=i.useState(l),[m,f]=i.useState(l),[g,b]=i.useState(!1),[p,x]=i.useState(!0),y=i.useRef(null),h=p,C=i.useCallback(I=>{!I||I==="about:blank"||!e||!n||a(e,n,I)},[e,n,a]),w=ut(I=>I.currentSessionId),S=ut(I=>I.newSessionDraft?.open),j=Ac(I=>I.addDraft),k=ci(I=>I.addAttachedFile);i.useEffect(()=>{const I=o.current;if(!I)return;const N=()=>{try{const B=I.getURL();B&&B!=="about:blank"&&(f(B),u(B),C(B))}catch{}},O=B=>{const V=B.detail;typeof V?.url=="string"&&V.url&&(f(V.url),u(V.url),C(V.url))},P=()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>x(!0),200)},T=()=>{y.current&&clearTimeout(y.current),x(!1),N()},L=B=>{const V=B.detail;if(V?.disposition==="new-window"||V?.disposition==="foreground-tab"||V?.disposition==="background-tab"){B.preventDefault();const _=o.current;typeof _?.loadURL=="function"&&V.url&&_.loadURL(V.url)}},R=()=>{try{I.executeJavaScript?.(O0,!0).catch(()=>{})}catch{}};I.addEventListener("did-navigate",O),I.addEventListener("did-navigate-in-page",O),I.addEventListener("did-start-loading",P),I.addEventListener("did-stop-loading",T),I.addEventListener("new-window",L),I.addEventListener("dom-ready",R);try{I.isLoading()||(x(!1),N())}catch{}return R(),()=>{y.current&&clearTimeout(y.current),I.removeEventListener("did-navigate",O),I.removeEventListener("did-navigate-in-page",O),I.removeEventListener("did-start-loading",P),I.removeEventListener("did-stop-loading",T),I.removeEventListener("new-window",L),I.removeEventListener("dom-ready",R)}},[C]),i.useEffect(()=>{const I=setTimeout(()=>x(!1),3e4);return()=>clearTimeout(I)},[]),i.useEffect(()=>{if(!g)return;const I=N=>{if(N.key!=="Escape")return;N.preventDefault(),N.stopImmediatePropagation(),b(!1);const O=o.current;try{O?.executeJavaScript?.(ua).catch(()=>{})}catch{}};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[g]),i.useEffect(()=>{const I=o.current;return()=>{try{const N=I?.getURL?.();N&&N!=="about:blank"&&a(e,n,N)}catch{}try{I?.executeJavaScript?.(ua).catch(()=>{})}catch{}}},[e,n,a]);const v=i.useCallback(I=>{const N=o.current;if(typeof N?.loadURL!="function")return;const O=Co(I);try{N.loadURL(O)}catch{}},[]),A=i.useCallback(()=>{const I=o.current;if(I){if(g){b(!1);try{I.executeJavaScript?.(ua).catch(()=>{})}catch{}return}b(!0),I.executeJavaScript?.(rh,!0).then(async N=>{if(b(!1),!N||!Ki(N))return;const O=w??(S?"draft":null);if(!O){ce.error(r("contextPanel.preview.inspect.attachNoSession"));return}const P=typeof I.getWebContentsId=="function"?I.getWebContentsId():null;if(P==null)return;const T=await bg("desktop_browser_capture_page",{webContentsId:P}),L=await I.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),R=Number.isFinite(L?.width)?L.width:T.width,B=Number.isFinite(L?.height)?L.height:T.height,V=await Wc(T.base64,T.width,T.height,R,B,N),_=!!V;V&&await k(V),j({sessionKey:O,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:zc({pageUrl:m,viewport:{width:R,height:B},devicePixelRatio:window.devicePixelRatio||1,target:N,screenshotAttached:_,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),ce.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>b(!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(D,{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(D,{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(D,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:I=>{I.preventDefault(),v(d)},children:s.jsx("input",{value:d,onChange:I=>u(I.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:A,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(D,{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:()=>{Ii(m)},children:s.jsx(D,{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(Dc,{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]})]})},U0=()=>{const{t}=Nt(),e=di()??"",n=i.useMemo(()=>I0(e),[e]),r=Ee(U=>n?U.contextPanelByDirectory[n]:void 0),o=Ee(U=>U.closeContextPanel),a=Ee(U=>U.closeContextPanelTab),c=Ee(U=>U.openContextPanelTab),l=Ee(U=>U.toggleContextPanelExpanded),d=Ee(U=>U.setContextPanelWidth),u=Ee(U=>U.setActiveContextPanelTab),m=Ee(U=>U.reorderContextPanelTabs),f=fn(U=>U.setSelectedPath),g=Ee(U=>U.openContextPreview),{themeMode:b,setThemeMode:p,lightThemeId:x,darkThemeId:y,currentTheme:h}=Kr(),C=i.useMemo(()=>r?.tabs??[],[r?.tabs]),w=C.find(U=>U.id===r?.activeTabId)??C[C.length-1]??null,S=!!(r?.isOpen&&w),j=!!(S&&r?.expanded),k=nh(r?.width??sh),[v,A]=i.useState(!1),[I,N]=i.useState(!1),O=i.useRef(0),P=i.useRef(k),T=i.useRef(null),L=i.useRef(null),R=i.useRef(null),B=i.useRef(new Map),V=i.useRef(new Map),_=i.useRef(!1),E=i.useRef(S),Z=i.useRef(null),ne=i.useCallback(()=>{N(!0),Z.current!==null&&window.cancelAnimationFrame(Z.current),Z.current=window.requestAnimationFrame(()=>{Z.current=null,N(!1)})},[]);i.useEffect(()=>()=>{Z.current!==null&&window.cancelAnimationFrame(Z.current)},[]),i.useLayoutEffect(()=>{const U=E.current;if(E.current=S,!S){N(!1);return}U||ne()},[S,ne]),i.useEffect(()=>{if(!S||_.current){_.current=S;return}const U=window.requestAnimationFrame(()=>{R.current?.focus({preventScroll:!0})});return _.current=!0,()=>window.cancelAnimationFrame(U)},[S]);const Y=i.useCallback(U=>{const fe=R.current;fe&&fe.style.setProperty("--oc-context-panel-width",`${Il(U,fe)}px`)},[]),H=i.useCallback(U=>{if(!(!S||j||!n)){try{U.currentTarget.setPointerCapture(U.pointerId)}catch{}L.current=U.pointerId,A(!0),O.current=U.clientX,P.current=k,T.current=k,Y(k),U.preventDefault()}},[Y,n,j,S,k]),re=i.useCallback(U=>{if(!v||L.current!==U.pointerId)return;const fe=O.current-U.clientX,de=Il(P.current+fe,R.current);T.current!==de&&(T.current=de,Y(de))},[Y,v]),ae=i.useCallback(U=>{if(L.current!==U.pointerId||!n)return;try{U.currentTarget.releasePointerCapture(U.pointerId)}catch{}const fe=Il(T.current??k,R.current);ne(),Y(fe),T.current=fe,d(n,fe),A(!1),L.current=null},[Y,n,d,ne,k]);i.useEffect(()=>{v||(T.current=null)},[v]);const me=i.useCallback(()=>{n&&o(n)},[o,n]),Se=i.useCallback(()=>{n&&l(n)},[n,l]),te=i.useCallback(U=>{U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),me())},[me]);i.useEffect(()=>{if(!(!n||!w)&&w.mode==="file"&&w.targetPath){f(n,w.targetPath,{allowOutsideRoot:!0});return}},[w,n,f]);const ke=w?.mode==="chat"?w.id:null,Q=i.useCallback((U,fe,de)=>c0(V.current,U,fe,n||null,de,{mode:b,lightThemeId:x,darkThemeId:y,currentTheme:h}),[h,y,n,x,b]);i.useEffect(()=>{const U=new Set(C.map(fe=>fe.id));for(const fe of V.current.keys())U.has(fe)||V.current.delete(fe)},[C]);const ge=i.useCallback(U=>{!n||w?.mode!=="diff"||c(n,{mode:"diff",targetPath:w.targetPath,stagedDiff:U==="staged"})},[w,n,c]),F=i.useCallback(()=>{if(typeof window>"u")return;const U={themeMode:b,lightThemeId:x,darkThemeId:y,currentTheme:h};for(const fe of B.current.values()){const de=fe.contentWindow;if(!de)continue;const G=de.__openchamberApplyThemeSync;if(typeof G=="function")try{G(U);continue}catch{}de.postMessage({type:"openchamber:theme-sync",payload:U},window.location.origin)}},[h,y,x,b]),se=i.useCallback(()=>{if(!(typeof window>"u"))for(const[U,fe]of B.current.entries()){const de=fe.contentWindow;if(!de)continue;const G={visible:ke===U},$=de.__openchamberSetEmbeddedVisibility;if(typeof $=="function")try{$(G);continue}catch{}de.postMessage({type:"openchamber:embedded-visibility",payload:G},window.location.origin)}},[ke]);i.useEffect(()=>{if(typeof window>"u")return;const U=fe=>{if(fe.origin!==window.location.origin||!Array.from(B.current.values()).some(z=>z.contentWindow===fe.source)||fe.data?.type!=="openchamber:cycle-theme-request")return;const $=["light","dark","system"],be=($.indexOf(b)+1)%$.length;p($[be])};return window.addEventListener("message",U),()=>window.removeEventListener("message",U)},[p,b]),i.useLayoutEffect(()=>{C.some(fe=>fe.mode==="chat")&&(F(),se())},[y,x,se,F,C,b]);const ee=i.useMemo(()=>C.map(U=>{const fe=M0(U,t),de=B0(fe,A0),G=T0(U.targetPath,e);return{id:U.id,label:de,icon:F0(U),title:G?`${fe}: ${G}`:fe,closeLabel:t("contextPanel.tab.closeTabAria",{label:de})}}),[e,t,C]),Ne=w?.mode==="context"?s.jsx(Q1,{}):w?.mode==="plan"?s.jsx(Km,{targetPath:w.targetPath}):w?.mode==="preview"?s.jsx(_0,{rawUrl:w.targetPath??"",onNavigate:U=>g(e,U)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(D,{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")})]}),De=i.useMemo(()=>C.filter(U=>U.mode==="chat"),[C]),Be=i.useMemo(()=>C.filter(U=>U.mode==="browser"),[C]),Fe=i.useMemo(()=>C.filter(U=>U.mode==="diff"),[C]),Me=$0()?W0:z0,he=i.useMemo(()=>C.some(U=>U.mode==="file"),[C]),Ae=w?.mode==="file",pe=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(To,{items:ee,activeId:w?.id??null,onSelect:U=>{n&&u(n,U)},onClose:U=>{n&&a(n,U)},onReorder:(U,fe)=>{n&&m(n,U,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:Se,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(D,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(D,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx($e,{type:"button",variant:"ghost",size:"sm",onClick:me,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(D,{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(${th}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${v?T.current??k:k}px`}:{"--oc-context-panel-width":`${v?T.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:Pe("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||I?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:te,style:ue,children:[!j&&s.jsx("div",{className:Pe("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",v&&"bg-[var(--interactive-border)]"),onPointerDown:H,onPointerMove:re,onPointerUp:ae,onPointerCancel:ae,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),pe,s.jsxs("div",{className:Pe("relative min-h-0 flex-1 overflow-hidden",v&&"pointer-events-none"),children:[he?s.jsx("div",{className:Pe("absolute inset-0",Ae?"block":"hidden"),children:s.jsx(Gm,{mode:"editor-only"})}):null,De.map(U=>{const fe=L0(U.dedupeKey);if(!fe)return null;const de=Q(U.id,fe,U.readOnly);return de?s.jsx("iframe",{ref:G=>{if(!G){B.current.delete(U.id);return}B.current.set(U.id,G)},src:de,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:fe}),className:Pe("absolute inset-0 h-full w-full border-0 bg-background",ke===U.id?"block":"hidden"),onLoad:()=>{F(),se()}},U.id):null}),Be.map(U=>s.jsx("div",{className:Pe("absolute inset-0",w?.id!==U.id&&"hidden"),children:s.jsx(Me,{initialUrl:U.targetPath??"",directory:n,tabID:U.id})},U.id)),Fe.map(U=>s.jsx("div",{className:Pe("absolute inset-0",w?.id!==U.id&&"hidden"),children:s.jsx(zm,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:U.stagedDiff?"staged":"working",onDiffScopeChange:ge,targetFilePath:U.targetPath,flushContent:!0})},U.id)),w?.mode!=="chat"&&!Ae&&w?.mode!=="browser"&&w?.mode!=="diff"?Ne:null]})]})},nc=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+/g,"/");n&&!r.startsWith("//")&&(r=`/${r}`);const o=r==="/",a=/^[A-Za-z]:\/$/.test(r);return!o&&!a&&(r=r.replace(/\/+$/,"")),r},H0=()=>{const t=mt.c(171),{t:e}=Nt(),n=Ee(G0),r=Ee(K0),o=Ee(q0),a=Ee(Y0),c=Ee(Q0),l=Ee(J0),d=Ee(X0),u=Ee(Z0),m=Ee(ej),f=Ee(tj),g=Ee(sj),b=Ee(nj),p=ut(rj),x=ut(ij),y=vr(oj),h=Js(aj),C=ws(lj),w=di(),S=mc(cj),{files:j,git:k}=Jn(),v=wn(dj),{isMobile:A}=Er();let I;t[0]!==w?(I=w?nc(w):null,t[0]=w,t[1]=I):I=t[1];const N=I,[O,P]=i.useState(""),T=Ha(O,200);let L;t[2]!==T?(L=T.trim(),t[2]=T,t[3]=L):L=t[3];const R=L;let B;t[4]!==O?(B=O.trim(),t[4]=O,t[5]=B):B=t[5];const V=B;let _,E;t[6]!==n?(_=()=>{n&&P("")},E=[n],t[6]=n,t[7]=_,t[8]=E):(_=t[7],E=t[8]),i.useEffect(_,E);let Z,ne;t[9]!==y||t[10]!==v||t[11]!==k||t[12]!==n?(Z=()=>{if(!n||!k)return;const Ve=setTimeout(()=>{const Ze=new Set;for(const _t of y){const jt=Tr(_t);!jt||Ze.has(jt)||(Ze.add(jt),v(jt,k))}},0);return()=>clearTimeout(Ve)},ne=[n,y,k,v],t[9]=y,t[10]=v,t[11]=k,t[12]=n,t[13]=Z,t[14]=ne):(Z=t[13],ne=t[14]),i.useEffect(Z,ne);let Y;t[15]!==r?(Y=()=>r(!1),t[15]=r,t[16]=Y):Y=t[16];const H=Y;let re;t[17]!==H?(re=Ve=>()=>{H(),Ve()},t[17]=H,t[18]=re):re=t[18];const ae=re;let me;t[19]!==C?.id||t[20]!==C?.path||t[21]!==h||t[22]!==A||t[23]!==f||t[24]!==p||t[25]!==ae||t[26]!==o||t[27]!==l||t[28]!==a||t[29]!==e||t[30]!==m||t[31]!==u||t[32]!==d?(me=()=>{const Ve=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(D,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:ae(()=>{o("chat"),l(!1),p()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(D,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:ae(uj)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(D,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:ae(fj)},{id:"toggle-sidebar",title:e(A?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(D,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(A?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:ae(()=>{if(A){const{isSessionSwitcherOpen:Ze}=Ee.getState();l(!Ze)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(D,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:ae(()=>u())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(D,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:ae(()=>m())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(D,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:ae(()=>{h&&f(h)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(D,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:ae(()=>a(!0))}];return Fa()&&Ve.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(D,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:ae(()=>{Ur("desktop_open_draft_mini_chat_window",{directory:nc(h||C?.path||""),projectId:C?.id??null}).catch(mj)})}),Ve},t[19]=C?.id,t[20]=C?.path,t[21]=h,t[22]=A,t[23]=f,t[24]=p,t[25]=ae,t[26]=o,t[27]=l,t[28]=a,t[29]=e,t[30]=m,t[31]=u,t[32]=d,t[33]=me):me=t[33],C?.id,C?.path;let Se;t[34]!==me?(Se=me(),t[34]=me,t[35]=Se):Se=t[35];const te=Se;let ke;t[36]===Symbol.for("react.memo_cache_sentinel")?(ke=dr(),t[36]=ke):ke=t[36];const Q=ke;let ge,F;t[37]===Symbol.for("react.memo_cache_sentinel")?(ge=Gr(),F=!Q&&pc(),t[37]=ge,t[38]=F):(ge=t[37],F=t[38]);let se;t[39]!==A?(se={isVSCode:ge,isWeb:F,isDesktop:Q,isMobile:A},t[39]=A,t[40]=se):se=t[40];const ee=se;let Ne;if(t[41]!==ae||t[42]!==a||t[43]!==c||t[44]!==ee){let Ve;t[46]!==ee?(Ve=_t=>_t.isAvailable?_t.isAvailable(ee):!0,t[46]=ee,t[47]=Ve):Ve=t[47];let Ze;t[48]!==ae||t[49]!==a||t[50]!==c?(Ze=_t=>{const jt=Hx(_t.slug)??"settings-3",xt=(_t.keywords??[]).join(" ");return{id:`settings:${_t.slug}`,title:_t.title,icon:_t.slug==="mcp"?s.jsx(Ul,{className:"mr-2 h-4 w-4"}):s.jsx(D,{name:jt,className:"mr-2 h-4 w-4"}),searchText:`${_t.title} ${_t.group} ${xt}`,onSelect:ae(()=>{c(_t.slug),a(!0)})}},t[48]=ae,t[49]=a,t[50]=c,t[51]=Ze):Ze=t[51],Ne=Ux.filter(hj).filter(Ve).map(Ze),t[41]=ae,t[42]=a,t[43]=c,t[44]=ee,t[45]=Ne}else Ne=t[45];const De=Ne,Be=pj;let Fe;if(t[52]!==y){let Ve;t[54]===Symbol.for("react.memo_cache_sentinel")?(Ve=(Ze,_t)=>Be(_t)-Be(Ze),t[54]=Ve):Ve=t[54],Fe=[...y].sort(Ve),t[52]=y,t[53]=Fe}else Fe=t[53];const Me=Fe,he=sm(),Ae=ut(gj);let pe;t[55]!==he||t[56]!==Ae?(pe=(Ve,Ze)=>{const _t=Ae.get(Ve);return _t?.branch?_t.branch.trim()||null:Ze&&he.get(Ze)?.trim()||null},t[55]=he,t[56]=Ae,t[57]=pe):pe=t[57];const ue=pe;let U;t[58]===Symbol.for("react.memo_cache_sentinel")?(U=[],t[58]=U):U=t[58];const[fe,de]=i.useState(U),[G,$]=i.useState(!1);let ve,be;t[59]!==N||t[60]!==n||t[61]!==S||t[62]!==R?(ve=()=>{if(!n){de([]),$(!1);return}if(!N||R.length===0){de([]),$(!1);return}let Ve=!1;return $(!0),S(N,R,10,{type:"file"}).then(Ze=>{Ve||de(Ze.map(xj))}).catch(()=>{Ve||de([])}).finally(()=>{Ve||$(!1)}),()=>{Ve=!0}},be=[n,N,R,S],t[59]=N,t[60]=n,t[61]=S,t[62]=R,t[63]=ve,t[64]=be):(ve=t[63],be=t[64]),i.useEffect(ve,be);const z=V.length>0;let xe;e:{if(!z){let Ze;t[65]!==te?(Ze=te.map(bj),t[65]=te,t[66]=Ze):Ze=t[66],xe=Ze;break e}let Ve;t[67]!==te||t[68]!==V?(Ve=Wo(te,V,yj,{limit:7,noFuzzy:!0}),t[67]=te,t[68]=V,t[69]=Ve):Ve=t[69],xe=Ve}const je=xe;let K;e:{if(!z){let Ze;t[70]===Symbol.for("react.memo_cache_sentinel")?(Ze=[],t[70]=Ze):Ze=t[70],K=Ze;break e}let Ve;t[71]!==V||t[72]!==De?(Ve=Wo(De,V,wj,{limit:7,noFuzzy:!0}),t[71]=V,t[72]=De,t[73]=Ve):Ve=t[73],K=Ve}const ye=K;let Le;e:{if(!z){let Ze;t[74]!==Me?(Ze=Me.slice(0,5).map(vj),t[74]=Me,t[75]=Ze):Ze=t[75],Le=Ze;break e}let Ve;t[76]!==V||t[77]!==Me?(Ve=Wo(Me,V,jj,{limit:7,threshold:.2}),t[76]=V,t[77]=Me,t[78]=Ve):Ve=t[78],Le=Ve}const Re=Le;let X;e:{if(!z||fe.length===0){let Ze;t[79]===Symbol.for("react.memo_cache_sentinel")?(Ze=[],t[79]=Ze):Ze=t[79],X=Ze;break e}let Ve;t[80]!==fe||t[81]!==V?(Ve=Wo(fe,V,Sj,{limit:10,threshold:.4}),t[80]=fe,t[81]=V,t[82]=Ve):Ve=t[82],X=Ve}const M=X;let le,ie,Oe,Ge,He,Je,rt,bt,yt,_e,Ye,nt,wt,kt,vt;if(t[83]!==ue||t[84]!==H||t[85]!==N||t[86]!==j||t[87]!==z||t[88]!==n||t[89]!==g||t[90]!==O||t[91]!==je||t[92]!==M||t[93]!==Re||t[94]!==ye||t[95]!==r||t[96]!==x||t[97]!==b||t[98]!==e){const Ve=je.map(Nj),Ze=ye.map(kj),_t=Re.map(Cj);vt=z?M.map(Aj):[];let jt;e:{if(!z){jt=["commands","sessions"];break e}const $t=Dj,Ct=[{key:"commands",score:$t(je)},{key:"settings",score:$t(ye)},{key:"sessions",score:$t(Re)},{key:"files",score:$t(M)}];Ct.sort(Ij),jt=Ct.map(Pj)}const xt=jt;let rs;t[114]!==H||t[115]!==x?(rs=$t=>{H(),x($t.id,Tr($t))},t[114]=H,t[115]=x,t[116]=rs):rs=t[116];const Gt=rs;let Ut;t[117]!==H||t[118]!==N||t[119]!==j||t[120]!==g?(Ut=async $t=>{if(!N)return;const Ct=await Vc(j,$t);if(!Ct.ok){ce.error(_c(Ct.reason));return}g(N,$t),H()},t[117]=H,t[118]=N,t[119]=j,t[120]=g,t[121]=Ut):Ut=t[121];const as=Ut;let Bt;t[122]!==b?(Bt=$t=>La(ii($t,b)),t[122]=b,t[123]=Bt):Bt=t[123];const Lt=Bt;Ge=$s,nt=n,wt=r;let Vt;t[124]!==e?(Vt=e("commandPalette.title"),t[124]=e,t[125]=Vt):Vt=t[125];let Kt;t[126]!==Vt?(Kt=s.jsx(Us,{children:Vt}),t[126]=Vt,t[127]=Kt):Kt=t[127];let Xt;t[128]!==e?(Xt=e("commandPalette.description"),t[128]=e,t[129]=Xt):Xt=t[129];let Qt;t[130]!==Xt?(Qt=s.jsx(on,{children:Xt}),t[130]=Xt,t[131]=Qt):Qt=t[131],t[132]!==Kt||t[133]!==Qt?(kt=s.jsxs(Hs,{className:"sr-only",children:[Kt,Qt]}),t[132]=Kt,t[133]=Qt,t[134]=kt):kt=t[134],Oe=_s,_e="overflow-hidden p-0",Ye=!0,ie=Oa,rt=!1,bt="[&_[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?(yt=s.jsx(Ba,{value:O,onValueChange:P,placeholder:vs}),t[137]=O,t[138]=vs,t[139]=yt):yt=t[139],le=Va;let Dt;t[140]!==e?(Dt=e("commandPalette.empty.noResults"),t[140]=e,t[141]=Dt):Dt=t[141],t[142]!==Dt?(He=s.jsx(_a,{children:Dt}),t[142]=Dt,t[143]=He):He=t[143],Je=xt.map($t=>$t==="commands"&&Ve.length>0?s.jsx(oi,{children:Ve.map(Ct=>s.jsxs(li,{value:Ct.id,onSelect:Ct.onSelect,children:[Ct.icon,s.jsx("span",{children:Ct.title}),Ct.shortcutId?s.jsx(yg,{children:Lt(Ct.shortcutId)}):null]},Ct.id))},"commands"):$t==="settings"&&Ze.length>0?s.jsx(oi,{children:Ze.map(Tj)},"settings"):$t==="sessions"&&_t.length>0?s.jsx(oi,{children:_t.map(Ct=>{const ds=Ct.title||e("commandPalette.session.untitled"),qe=Tr(Ct),at=ue(Ct.id,qe);return s.jsxs(li,{value:`session:${Ct.id}`,onSelect:()=>Gt(Ct),children:[s.jsx(D,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:ds}),at?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(D,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:at})]}):null]},Ct.id)})},"sessions"):$t==="files"&&vt.length>0?s.jsx(oi,{children:vt.map(Ct=>{const ds=wg(Ct.relativePath||Ct.name,{maxLength:80});return s.jsxs(li,{value:`file:${Ct.path}`,onSelect:()=>{as(Ct.path)},children:[s.jsx(Hr,{filePath:Ct.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":Ct.relativePath,children:ds})]},`file:${Ct.path}`)})},"files"):null),t[83]=ue,t[84]=H,t[85]=N,t[86]=j,t[87]=z,t[88]=n,t[89]=g,t[90]=O,t[91]=je,t[92]=M,t[93]=Re,t[94]=ye,t[95]=r,t[96]=x,t[97]=b,t[98]=e,t[99]=le,t[100]=ie,t[101]=Oe,t[102]=Ge,t[103]=He,t[104]=Je,t[105]=rt,t[106]=bt,t[107]=yt,t[108]=_e,t[109]=Ye,t[110]=nt,t[111]=wt,t[112]=kt,t[113]=vt}else le=t[99],ie=t[100],Oe=t[101],Ge=t[102],He=t[103],Je=t[104],rt=t[105],bt=t[106],yt=t[107],_e=t[108],Ye=t[109],nt=t[110],wt=t[111],kt=t[112],vt=t[113];let St;t[144]!==z||t[145]!==G||t[146]!==e||t[147]!==vt?(St=z&&G&&vt.length===0?s.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:e("commandPalette.empty.searchingFiles")}):null,t[144]=z,t[145]=G,t[146]=e,t[147]=vt,t[148]=St):St=t[148];let et;t[149]!==le||t[150]!==He||t[151]!==Je||t[152]!==St?(et=s.jsxs(le,{children:[He,Je,St]}),t[149]=le,t[150]=He,t[151]=Je,t[152]=St,t[153]=et):et=t[153];let Ot;t[154]!==ie||t[155]!==rt||t[156]!==bt||t[157]!==yt||t[158]!==et?(Ot=s.jsxs(ie,{shouldFilter:rt,className:bt,children:[yt,et]}),t[154]=ie,t[155]=rt,t[156]=bt,t[157]=yt,t[158]=et,t[159]=Ot):Ot=t[159];let ns;t[160]!==Oe||t[161]!==_e||t[162]!==Ye||t[163]!==Ot?(ns=s.jsx(Oe,{className:_e,showCloseButton:Ye,children:Ot}),t[160]=Oe,t[161]=_e,t[162]=Ye,t[163]=Ot,t[164]=ns):ns=t[164];let Wt;return t[165]!==Ge||t[166]!==nt||t[167]!==wt||t[168]!==kt||t[169]!==ns?(Wt=s.jsxs(Ge,{open:nt,onOpenChange:wt,children:[kt,ns]}),t[165]=Ge,t[166]=nt,t[167]=wt,t[168]=kt,t[169]=ns,t[170]=Wt):Wt=t[170],Wt};function G0(t){return t.isCommandPaletteOpen}function K0(t){return t.setCommandPaletteOpen}function q0(t){return t.setActiveMainTab}function Y0(t){return t.setSettingsDialogOpen}function Q0(t){return t.setSettingsPage}function J0(t){return t.setSessionSwitcherOpen}function X0(t){return t.toggleSidebar}function Z0(t){return t.toggleRightSidebar}function ej(t){return t.toggleBottomTerminal}function tj(t){return t.openContextOverview}function sj(t){return t.openContextFile}function nj(t){return t.shortcutOverrides}function rj(t){return t.openNewSessionDraft}function ij(t){return t.setCurrentSession}function oj(t){return t.activeSessions}function aj(t){return t.currentDirectory}function lj(t){return t.getActiveProject()}function cj(t){return t.searchFiles}function dj(t){return t.ensureStatus}function uj(){nm()}function fj(){Pr.requestDirectoryDialog()}function mj(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function hj(t){return t.slug!=="home"}function pj(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function gj(t){return t.worktreeMetadata}function xj(t){return{path:nc(t.path),name:t.name,relativePath:t.relativePath}}function bj(t){return{item:t,score:0}}function yj(t){return t.searchText}function wj(t){return t.searchText}function vj(t){return{item:t,score:0}}function jj(t){return t.title||""}function Sj(t){return t.name}function Nj(t){return t.item}function kj(t){return t.item}function Cj(t){return t.item}function Aj(t){return t.item}function Dj(t){return t.length?t[0].score:1/0}function Ij(t,e){return t.score-e.score}function Pj(t){return t.key}function Tj(t){return s.jsxs(li,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const qu=(t,e,n)=>jg(t)?La(ii(t,n)):e,Rj=()=>{const t=mt.c(68),{t:e}=Nt(),n=Ee(Ej),r=Ee(Mj),o=Ee(Fj);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=vg(),t[0]=a):a=t[0];const c=a;let l,d,u,m,f,g,b,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=$s,p=n,x=r,l=_s,g="max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden";let B;t[14]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx(D,{name:"settings-3",className:"h-5 w-5"}),t[14]=B):B=t[14];let V;t[15]!==e?(V=e("helpDialog.title"),t[15]=e,t[16]=V):V=t[16];let _;t[17]!==V?(_=s.jsxs(Us,{className:"flex items-center gap-2",children:[B,V]}),t[17]=V,t[18]=_):_=t[18];let E;t[19]!==e?(E=e("helpDialog.description"),t[19]=e,t[20]=E):E=t[20];let Z;t[21]!==E?(Z=s.jsx(on,{children:E}),t[21]=E,t[22]=Z):Z=t[22],t[23]!==_||t[24]!==Z?(b=s.jsxs(Hs,{children:[_,Z]}),t[23]=_,t[24]=Z,t[25]=b):b=t[25],f="flex-1 overflow-y-auto mt-3 pr-1",u="space-y-4",m=R.map(ne=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(ne.categoryKey)}),s.jsx("div",{className:"space-y-1",children:ne.items.map(Y=>{const H=Y.id?qu(Y.id,Array.isArray(Y.keys)?Y.keys[0]:Y.keys,o):Array.isArray(Y.keys)?Y.keys:Y.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:[Y.icon&&s.jsx(D,{name:Y.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(Y.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(H)?H:[H]).map((re,ae)=>s.jsxs(i.Fragment,{children:[ae>0&&s.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:e("helpDialog.keyCombiner.or")}),s.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:re})]},`${re}-${ae}`))})]},Y.id||Y.descriptionKey)})})]},ne.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]=b,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],b=t[11],p=t[12],x=t[13];let y;t[26]!==u||t[27]!==m?(y=s.jsx("div",{className:u,children:m}),t[26]=u,t[27]=m,t[28]=y):y=t[28];let h;t[29]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(D,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),t[29]=h):h=t[29];let C;t[30]!==e?(C=e("helpDialog.proTips.title"),t[30]=e,t[31]=C):C=t[31];let w;t[32]!==C?(w=s.jsx("p",{className:"font-medium mb-1",children:C}),t[32]=C,t[33]=w):w=t[33];let S;t[34]!==o||t[35]!==e?(S=e("helpDialog.proTips.commandPalette",{shortcut:qu("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 A;t[43]!==e?(A=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=A):A=t[44];let I;t[45]!==A?(I=s.jsxs("li",{children:["• ",A]}),t[45]=A,t[46]=I):I=t[46];let N;t[47]!==j||t[48]!==v||t[49]!==I?(N=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[j,v,I]}),t[47]=j,t[48]=v,t[49]=I,t[50]=N):N=t[50];let O;t[51]!==w||t[52]!==N?(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,N]})]})}),t[51]=w,t[52]=N,t[53]=O):O=t[53];let P;t[54]!==O||t[55]!==f||t[56]!==y?(P=s.jsxs("div",{className:f,children:[y,O]}),t[54]=O,t[55]=f,t[56]=y,t[57]=P):P=t[57];let T;t[58]!==l||t[59]!==P||t[60]!==g||t[61]!==b?(T=s.jsxs(l,{className:g,children:[b,P]}),t[58]=l,t[59]=P,t[60]=g,t[61]=b,t[62]=T):T=t[62];let L;return t[63]!==d||t[64]!==T||t[65]!==p||t[66]!==x?(L=s.jsx(d,{open:p,onOpenChange:x,children:T}),t[63]=d,t[64]=T,t[65]=p,t[66]=x,t[67]=L):L=t[67],L};function Ej(t){return t.isHelpDialogOpen}function Mj(t){return t.setHelpDialogOpen}function Fj(t){return t.shortcutOverrides}const Lj=()=>{const t=mt.c(32),{t:e}=Nt(),n=Ee(Oj),r=Ee(Bj),o=Ee(Vj);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await ur(o)).ok){ce.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}ce.error(e("openCodeStatusDialog.toast.copyFailed"))},t[0]=o,t[1]=e,t[2]=a):a=t[2];const c=a;let l;t[3]!==e?(l=e("openCodeStatusDialog.title"),t[3]=e,t[4]=l):l=t[4];let d;t[5]!==l?(d=s.jsx(Us,{children:l}),t[5]=l,t[6]=d):d=t[6];let u;t[7]!==e?(u=e("openCodeStatusDialog.description"),t[7]=e,t[8]=u):u=t[8];let m;t[9]!==u?(m=s.jsx(on,{children:u}),t[9]=u,t[10]=m):m=t[10];let f;t[11]!==d||t[12]!==m?(f=s.jsxs(Hs,{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 b;t[16]!==c||t[17]!==g?(b=s.jsx("div",{className:"flex items-center justify-end",children:s.jsx("button",{type:"button",onClick:c,className:"app-region-no-drag inline-flex h-9 items-center justify-center rounded-md px-3 typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:g})}),t[16]=c,t[17]=g,t[18]=b):b=t[18];let 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 y;t[24]!==f||t[25]!==b||t[26]!==x?(y=s.jsxs(_s,{className:"max-w-2xl",children:[f,b,x]}),t[24]=f,t[25]=b,t[26]=x,t[27]=y):y=t[27];let h;return t[28]!==n||t[29]!==r||t[30]!==y?(h=s.jsx($s,{open:n,onOpenChange:r,children:y}),t[28]=n,t[29]=r,t[30]=y,t[31]=h):h=t[31],h};function Oj(t){return t.isOpenCodeStatusDialogOpen}function Bj(t){return t.setOpenCodeStatusDialogOpen}function Vj(t){return t.openCodeStatusText}const _j=180,Yu=600,$j=1,zj=6,Wj=({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(()=>Gr(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<$j&&a.current.length>0;){const m=a.current.shift();if(!m)break;ut.getState().currentSessionId!==m&&(Fd(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"||Fd(m).renderable||c.current.has(m)||a.current.includes(m))return;a.current.length>=zj&&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()},_j);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))},Yu);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]))},Yu);return()=>window.clearTimeout(m)},[t,l,n,u]),i.useEffect(()=>{const m=o.current;return()=>{m.forEach(f=>{clearTimeout(f)}),m.clear(),a.current=[]}},[])};let Yi=null,Qi=null,fa=null,Eo=0,Ta=null;const Di=new Set,Uj=3e4,Hj=45e3,oh=()=>{fa&&(clearTimeout(fa),fa=null)},ah=()=>{if(Qi||Di.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Eo,5)),Uj);Qi=setTimeout(()=>{Qi=null,Eo+=1,Hc()},t)},Mo=()=>{oh(),Yi&&Yi.close(),Yi=null},Qu=()=>{oh(),Di.size!==0&&(fa=setTimeout(()=>{Mo(),ah()},Hj))},Gj=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}},Kj=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 Di)d(l)},Hc=()=>{if(typeof window>"u"||Di.size===0||typeof EventSource!="function"||Yi&&Yi.readyState!==EventSource.CLOSED)return;Mo();const t=new EventSource(Ci().sse("/api/openchamber/events"));t.onopen=()=>{Qu()},t.onmessage=e=>{Qu();const n=Gj(e.data);n&&Kj(n)},t.onerror=()=>{Mo(),ah()},Yi=t},qj=()=>{Ta||typeof window>"u"||(Ta=Of(()=>{Mo(),Eo=0,Hc()}))},Yj=()=>{Ta?.(),Ta=null},lh=t=>(Di.add(t),qj(),Hc(),()=>{Di.delete(t),Di.size===0&&(Qi&&(clearTimeout(Qi),Qi=null),Eo=0,Mo(),Yj())}),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},no=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},Qj=async t=>{const e=no(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},Ju=async(t,e)=>{const n=no(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},Jj=async(t,e)=>{const n=no(t),r=no(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},Xj=async(t,e)=>{const n=no(t),r=no(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 ch(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return Ef.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function Zj(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=Ef.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 eS=[{expression:"*/5 * * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.every5min"},{expression:"0 * * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.everyHour"},{expression:"0 9 * * 1",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.monday9am"},{expression:"0 9,17 * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.9am5pm"},{expression:"0 0 1 * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.firstOfMonth"}],dh=[0,1,2,3,4,5,6],rc=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"],Xu=()=>{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},Zu=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},tS=(t,e,n)=>{const r=ma(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},ef=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),sS=(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},nS=t=>{const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour24:"00",hour12:"12",minute:"00",meridiem:"AM"};const n=Number(e[1]),r=e[2],o=n>=12?"PM":"AM",a=n%12===0?12:n%12;return{hour24:String(n).padStart(2,"0"),hour12:String(a).padStart(2,"0"),minute:r,meridiem:o}},yi=(t,e,n)=>{const r=Number(t),o=Number(e),a=Number.isFinite(r)?Math.min(12,Math.max(1,r)):12,c=Number.isFinite(o)?Math.min(59,Math.max(0,o)):0;let l=a%12;return n==="PM"&&(l+=12),`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`},lo=(t,e)=>{const{max:n,min:r=0,loop:o=!1}=e;let a=Number.parseInt(t,10);return Number.isFinite(a)?(o?(a>n&&(a=r),a<r&&(a=n)):(a>n&&(a=n),a<r&&(a=r)),String(a).padStart(2,"0")):"00"},tf=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:lo(t,{min:1,max:12}),Zo=t=>/^[0-5][0-9]$/.test(t)?t:lo(t,{max:59}),rS=(t,e)=>lo(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),sf=(t,e)=>lo(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),iS=t=>{try{const e=Intl.Locale;if(typeof e!="function")return 1;const r=new e(t).weekInfo?.firstDay;return typeof r!="number"?1:r%7}catch{return 1}},oS=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}},aS=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return dh.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},lS=(t,e)=>[...t.slice(e),...t.slice(0,e)],Yn=t=>{const e=mt.c(6),{htmlFor:n,required:r,children:o}=t;let a;e[0]!==r?(a=r&&s.jsx("span",{className:"ml-0.5 text-destructive",children:"*"}),e[0]=r,e[1]=a):a=e[1];let c;return e[2]!==o||e[3]!==n||e[4]!==a?(c=s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,a]})}),e[2]=o,e[3]=n,e[4]=a,e[5]=c):c=e[5],c},nf=t=>{const e=mt.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=nS(n),e[0]=n,e[1]=m):m=e[1];const f=m,g=Xe.useRef(null),b=Xe.useRef(null),[p,x]=Xe.useState(null),[y,h]=Xe.useState(null),C=Xe.useRef(null),w=Xe.useRef(null);let S;e[2]===Symbol.for("react.memo_cache_sentinel")?(S=pe=>{C.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,A=pS,I=gS,N=xS;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?N(A(ue),f.minute):yi(tf(ue),f.minute,f.meridiem)),j(null),b.current?.focus())},e[4]=r,e[5]=f.meridiem,e[6]=f.minute,e[7]=o,e[8]=O):O=e[8];const P=O;let T;e[9]!==r||e[10]!==f.meridiem||e[11]!==f.minute||e[12]!==o?(T=()=>{const pe=C.current;if(pe!==null&&(j(null),pe.length!==0)){if(o){r(N(A(pe.padStart(2,"0")),f.minute));return}r(yi(tf(pe.padStart(2,"0")),f.minute,f.meridiem))}},e[9]=r,e[10]=f.meridiem,e[11]=f.minute,e[12]=o,e[13]=T):T=e[13];const L=T;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?N(f.hour24,Zo(ue)):yi(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 B=R;let V;e[20]!==r||e[21]!==f.hour12||e[22]!==f.hour24||e[23]!==f.meridiem||e[24]!==o?(V=()=>{const pe=w.current;pe!==null&&(v(null),pe.length!==0&&r(o?N(f.hour24,Zo(pe.padStart(2,"0"))):yi(f.hour12,Zo(pe.padStart(2,"0")),f.meridiem)))},e[20]=r,e[21]=f.hour12,e[22]=f.hour24,e[23]=f.meridiem,e[24]=o,e[25]=V):V=e[25];const _=V;let E;e[26]!==r||e[27]!==f.hour12||e[28]!==f.hour24||e[29]!==f.meridiem||e[30]!==f.minute||e[31]!==o?(E=pe=>r(o?N(I(f.hour24,pe),f.minute):yi(rS(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]=E):E=e[32];const Z=E;let ne;e[33]!==r||e[34]!==f.hour12||e[35]!==f.hour24||e[36]!==f.meridiem||e[37]!==f.minute||e[38]!==o?(ne=pe=>r(o?N(f.hour24,sf(f.minute,pe)):yi(f.hour12,sf(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]=ne):ne=e[39];const Y=ne;let H;e[40]!==r||e[41]!==f.hour12||e[42]!==f.meridiem||e[43]!==f.minute?(H=pe=>{pe!==f.meridiem&&r(yi(f.hour12,f.minute,pe))},e[40]=r,e[41]=f.hour12,e[42]=f.meridiem,e[43]=f.minute,e[44]=H):H=e[44];const re=H;let ae;e[45]!==L||e[46]!==Z?(ae=pe=>{if(pe.key==="ArrowRight"){pe.preventDefault(),L(),b.current?.focus();return}(pe.key==="ArrowUp"||pe.key==="ArrowDown")&&(pe.preventDefault(),j(null),Z(pe.key==="ArrowUp"?1:-1))},e[45]=L,e[46]=Z,e[47]=ae):ae=e[47];const me=ae;let Se;e[48]!==_||e[49]!==Y?(Se=pe=>{if(pe.key==="ArrowLeft"&&(pe.currentTarget.selectionStart??0)===0){pe.preventDefault(),_(),g.current?.focus();return}(pe.key==="ArrowUp"||pe.key==="ArrowDown")&&(pe.preventDefault(),v(null),Y(pe.key==="ArrowUp"?1:-1))},e[48]=_,e[49]=Y,e[50]=Se):Se=e[50];const te=Se,ke=o?"px-2":"pl-2 pr-1";let Q;e[51]!==ke?(Q=Pe("inline-flex h-9 w-fit items-center gap-1 rounded-md border border-border bg-background focus-within:ring-1 focus-within:ring-interactive-focusRing focus-within:border-interactive-focusRing",ke),e[51]=ke,e[52]=Q):Q=e[52];const ge=p??(o?f.hour24:f.hour12);let F;e[53]!==P?(F=pe=>P(pe.target.value),e[53]=P,e[54]=F):F=e[54];let se;e[55]===Symbol.for("react.memo_cache_sentinel")?(se=()=>j(""),e[55]=se):se=e[55];let ee;e[56]!==L||e[57]!==a||e[58]!==me||e[59]!==ge||e[60]!==F?(ee=s.jsx("input",{ref:g,inputMode:"numeric",value:ge,onChange:F,onKeyDown:me,onFocus:se,onBlur:L,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]=L,e[57]=a,e[58]=me,e[59]=ge,e[60]=F,e[61]=ee):ee=e[61];let Ne;e[62]===Symbol.for("react.memo_cache_sentinel")?(Ne=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=Ne):Ne=e[62];const De=y??f.minute;let Be;e[63]!==B?(Be=pe=>B(pe.target.value),e[63]=B,e[64]=Be):Be=e[64];let Fe;e[65]===Symbol.for("react.memo_cache_sentinel")?(Fe=()=>v(""),e[65]=Fe):Fe=e[65];let Me;e[66]!==_||e[67]!==c||e[68]!==te||e[69]!==De||e[70]!==Be?(Me=s.jsx("input",{ref:b,inputMode:"numeric",value:De,onChange:Be,onKeyDown:te,onFocus:Fe,onBlur:_,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]=_,e[67]=c,e[68]=te,e[69]=De,e[70]=Be,e[71]=Me):Me=e[71];let he;e[72]!==d||e[73]!==f.meridiem||e[74]!==l||e[75]!==u||e[76]!==re||e[77]!==o?(he=o?null:s.jsxs($n,{value:f.meridiem,onValueChange:pe=>re(pe),children:[s.jsx(zn,{"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(Nn,{})}),s.jsxs(Wn,{children:[s.jsx(Ls,{value:"AM",children:d}),s.jsx(Ls,{value:"PM",children:u})]})]}),e[72]=d,e[73]=f.meridiem,e[74]=l,e[75]=u,e[76]=re,e[77]=o,e[78]=he):he=e[78];let Ae;return e[79]!==Q||e[80]!==ee||e[81]!==Me||e[82]!==he?(Ae=s.jsxs("div",{className:Q,children:[ee,Ne,Me,he]}),e[79]=Q,e[80]=ee,e[81]=Me,e[82]=he,e[83]=Ae):Ae=e[83],Ae},rf=t=>new Date(t.getFullYear(),t.getMonth(),1),cS=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},of=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),dS=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"]},af=(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:dS(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:Xu(),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:Xu(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent}}},uS=(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(!ch(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")},fS=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))},mS=t=>{const e=mt.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?ch(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let u;e:{if(!d?.valid||!c.trim()){let E;e[2]===Symbol.for("react.memo_cache_sentinel")?(E=[],e[2]=E):E=e[2],u=E;break e}let _;e[3]!==c||e[4]!==n.schedule.timezone?(_=Zj(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=_):_=e[5],u=_}const m=u;let f;e[6]!==n.schedule.timezone||e[7]!==o?(f=_=>new Intl.DateTimeFormat(o,{timeZone:n.schedule.timezone,month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(_),e[6]=n.schedule.timezone,e[7]=o,e[8]=f):f=e[8];const g=f;let b;e[9]!==a?(b=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=b):b=e[10];let p;e[11]!==b?(p=s.jsx(Yn,{htmlFor:"sched-cron",required:!0,children:b}),e[11]=b,e[12]=p):p=e[12];let x;e[13]!==r?(x=_=>r(E=>({...E,schedule:{...E.schedule,cronExpression:_.target.value}})),e[13]=r,e[14]=x):x=e[14];let y;e[15]!==a?(y=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=y):y=e[16];let h;e[17]!==c||e[18]!==x||e[19]!==y?(h=s.jsx(vn,{id:"sched-cron",value:c,onChange:x,placeholder:y,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=x,e[19]=y,e[20]=h):h=e[20];let C;e[21]!==c||e[22]!==d||e[23]!==a?(C=d&&!d.valid&&c.trim()?s.jsx("span",{className:"typography-micro text-destructive",children:a("sessions.scheduledTasks.editor.validation.cronInvalid")}):null,e[21]=c,e[22]=d,e[23]=a,e[24]=C):C=e[24];let w;e[25]!==p||e[26]!==h||e[27]!==C?(w=s.jsxs("div",{className:"flex flex-col gap-1",children:[p,h,C]}),e[25]=p,e[26]=h,e[27]=C,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=eS.map(_=>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(E=>({...E,schedule:{...E.schedule,cronExpression:_.expression}})),children:[s.jsx("span",{className:"font-mono",children:_.expression}),s.jsx("span",{className:"text-muted-foreground",children:a(_.labelKey)})]},_.expression)),e[37]=r,e[38]=a,e[39]=v):v=e[39];let A;e[40]!==v?(A=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:v}),e[40]=v,e[41]=A):A=e[41];let I;e[42]!==k||e[43]!==A?(I=s.jsxs("div",{className:"flex flex-col gap-1",children:[k,A]}),e[42]=k,e[43]=A,e[44]=I):I=e[44];let N;e[45]!==a?(N=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=N):N=e[46];let O;e[47]!==N?(O=s.jsx(Yn,{children:N}),e[47]=N,e[48]=O):O=e[48];let P;e[49]!==r?(P=_=>{r(E=>({...E,schedule:{...E.schedule,timezone:_}}))},e[49]=r,e[50]=P):P=e[50];let T;e[51]===Symbol.for("react.memo_cache_sentinel")?(T=s.jsx(zn,{className:"w-fit max-w-full",children:s.jsx(Nn,{})}),e[51]=T):T=e[51];let L;e[52]===Symbol.for("react.memo_cache_sentinel")?(L=s.jsx(Wn,{children:rc.map(bS)}),e[52]=L):L=e[52];let R;e[53]!==n.schedule.timezone||e[54]!==P?(R=s.jsxs($n,{value:n.schedule.timezone,onValueChange:P,children:[T,L]}),e[53]=n.schedule.timezone,e[54]=P,e[55]=R):R=e[55];let B;e[56]!==O||e[57]!==R?(B=s.jsxs("div",{className:"flex flex-col gap-1",children:[O,R]}),e[56]=O,e[57]=R,e[58]=B):B=e[58];let V;return e[59]!==w||e[60]!==S||e[61]!==I||e[62]!==B?(V=s.jsxs("div",{className:"flex flex-col gap-3",children:[w,S,I,B]}),e[59]=w,e[60]=S,e[61]=I,e[62]=B,e[63]=V):V=e[63],V};function hS(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=Nt(),l=ss(X=>X.loadProviders),d=ss(X=>X.loadAgents),u=ss(X=>X.providers),m=ss(X=>X.currentProviderId),f=ss(X=>X.currentModelId),g=ss(X=>X.currentVariant||""),b=ss(X=>X.currentAgentName||""),p=Ee(X=>X.timeFormatPreference),x=Ee(X=>X.weekStartPreference),y=Ee(X=>X.isMobile),[h,C]=Xe.useState(()=>af(n,{providerID:m,modelID:f,variant:g,agent:b})),[w,S]=Xe.useState(!1),[j,k]=Xe.useState(!1),[v,A]=Xe.useState(!1),[I,N]=Xe.useState(""),[O,P]=Xe.useState(!1),[T,L]=Xe.useState(""),[R,B]=Xe.useState(!1),[V,_]=Xe.useState(""),[E,Z]=Xe.useState(()=>{const X=ma(n?.schedule?.date||"")||new Date;return new Date(X.getFullYear(),X.getMonth(),1)}),ne=Xe.useRef(null),Y=Xe.useRef(null),H=Xe.useRef(null),re=Xe.useRef(null),ae=Xe.useRef(null),me=Xe.useMemo(()=>oS(c),[c]),Se=Xe.useMemo(()=>iS(c),[c]),te=Xe.useMemo(()=>p==="24h"?!0:p==="12h"?!1:me,[p,me]),ke=Xe.useMemo(()=>x==="sunday"?0:x==="monday"?1:Se,[x,Se]),Q=Xe.useMemo(()=>{const X=aS(c);return lS(dh.map(M=>({value:M,label:X[M]||""})),ke)},[c,ke]);Xe.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),Xe.useEffect(()=>{if(!e)return;C(af(n,{providerID:m,modelID:f,variant:g,agent:b}));const X=ma(n?.schedule?.date||"")||new Date;Z(new Date(X.getFullYear(),X.getMonth(),1)),k(!1),P(!1),A(!1),L(""),N("")},[e,n,m,f,g,b]),Xe.useEffect(()=>{if(!j)return;const X=M=>{ne.current&&!ne.current.contains(M.target)&&k(!1)};return document.addEventListener("mousedown",X),()=>{document.removeEventListener("mousedown",X)}},[j]);const ge=Xe.useMemo(()=>{const M=u.find(le=>le.id===h.execution.providerID)?.models?.find(le=>le.id===h.execution.modelID);return M?.variants?Object.keys(M.variants):[]},[u,h.execution.providerID,h.execution.modelID]),F=ge.length>0,se=Xe.useMemo(()=>!F||!h.execution.variant?"__default":ge.includes(h.execution.variant)?h.execution.variant:"__default",[h.execution.variant,F,ge]);Xe.useEffect(()=>{F||!h.execution.variant||C(X=>({...X,execution:{...X.execution,variant:""}}))},[F,h.execution.variant]);const ee=Xe.useCallback((X,M)=>{C(le=>{const ie=new Set(le.schedule.weekdays);return M?ie.add(X):ie.delete(X),{...le,schedule:{...le.schedule,weekdays:Array.from(ie).sort((Oe,Ge)=>Oe-Ge)}}})},[]),Ne=Xe.useCallback((X,M)=>{C(le=>{const ie=le.schedule.times.slice();return ie[X]=M,{...le,schedule:{...le.schedule,times:ie}}})},[]),De=Xe.useCallback(X=>{C(M=>{const le=M.schedule.times.filter((ie,Oe)=>Oe!==X);return{...M,schedule:{...M.schedule,times:le.length>0?le:["09:00"]}}})},[]),Be=Xe.useCallback(()=>{C(X=>({...X,schedule:{...X.schedule,times:[...X.schedule.times,"12:00"]}}))},[]),Fe=Xe.useMemo(()=>cS(),[]),Me=Xe.useMemo(()=>rf(Fe),[Fe]),he=Xe.useMemo(()=>{const X=ma(h.schedule.onceDate);return X?of(X,Fe)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(X):null},[h.schedule.onceDate,c,a,Fe]),Ae=Xe.useMemo(()=>rf(E).getTime()<=Me.getTime(),[E,Me]),pe=Xe.useMemo(()=>Q.map(X=>X.label),[Q]),ue=Xe.useCallback(X=>{C(M=>({...M,schedule:{...M.schedule,onceDate:X}}))},[]),U=Xe.useCallback((X,M)=>{if(X.startsWith("/")){const Ge=X.indexOf(" "),He=X.indexOf(`
167
- `),Je=Math.min(Ge===-1?X.length:Ge,He===-1?X.length:He);if(M<=Je&&Ge===-1){L(X.substring(1,Je)),P(!0),A(!1),B(!1);return}}P(!1);const le=X.substring(0,M),ie=le.lastIndexOf("#");if(ie!==-1){const Ge=ie>0?le[ie-1]:null,He=le.substring(ie+1);if((!Ge||/\s/.test(Ge))&&!He.includes(" ")&&!He.includes(`
168
- `)){_(He),B(!0),A(!1);return}}B(!1);const Oe=le.lastIndexOf("@");if(Oe!==-1){const Ge=Oe>0?le[Oe-1]:null,He=le.substring(Oe+1);(!Ge||/\s/.test(Ge))&&!He.includes(" ")&&!He.includes(`
169
- `)?(N(He),A(!0)):A(!1);return}A(!1)},[]),fe=Xe.useCallback(X=>{C(M=>({...M,execution:{...M.execution,prompt:X}}))},[]),de=Xe.useCallback(X=>{const M=h.execution.prompt,ie=Y.current?.selectionStart??M.length,Ge=M.substring(0,ie).lastIndexOf("@"),He=X.relativePath&&X.relativePath.trim().length>0?X.relativePath.trim():X.path||X.name,Je=Ge!==-1?Ge:ie,rt=`${M.substring(0,Je)}@${He} ${M.substring(ie)}`,bt=Je+He.length+2;fe(rt),A(!1),N(""),requestAnimationFrame(()=>{const yt=Y.current;yt&&(yt.selectionStart=bt,yt.selectionEnd=bt,yt.focus()),U(rt,bt)})},[h.execution.prompt,fe,U]),G=Xe.useCallback(X=>{const M=h.execution.prompt,ie=Y.current?.selectionStart??M.length,Ge=M.substring(0,ie).lastIndexOf("@"),He=Ge!==-1?Ge:ie,Je=`${M.substring(0,He)}@${X} ${M.substring(ie)}`,rt=He+X.length+2;fe(Je),A(!1),N(""),requestAnimationFrame(()=>{const bt=Y.current;bt&&(bt.selectionStart=rt,bt.selectionEnd=rt,bt.focus()),U(Je,rt)})},[h.execution.prompt,fe,U]),$=Xe.useCallback(X=>{const M=`/${X.name} `;fe(M),P(!1),L(""),B(!1),requestAnimationFrame(()=>{const le=Y.current;le&&(le.focus(),le.selectionStart=le.value.length,le.selectionEnd=le.value.length),U(M,M.length)})},[fe,U]),ve=Xe.useCallback((X,M)=>{const le=h.execution.prompt,Oe=Y.current?.selectionStart??le.length,He=le.substring(0,Oe).lastIndexOf("#"),Je=He!==-1?He:Oe,rt=`${le.substring(0,Je)}#${M} ${le.substring(Oe)}`,bt=Je+M.length+2;fe(rt),B(!1),_(""),requestAnimationFrame(()=>{const yt=Y.current;yt&&(yt.selectionStart=bt,yt.selectionEnd=bt,yt.focus()),U(rt,bt)})},[h.execution.prompt,fe,U]),be=Xe.useCallback(X=>{if(O&&re.current&&(X.key==="Enter"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="Escape"||X.key==="Tab")){X.preventDefault(),re.current.handleKeyDown(X.key);return}v&&H.current&&(X.key==="Enter"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="Escape"||X.key==="Tab")&&(X.preventDefault(),H.current.handleKeyDown(X.key)),R&&ae.current&&(X.key==="Enter"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="Escape"||X.key==="Tab")&&(X.preventDefault(),ae.current.handleKeyDown(X.key))},[O,v,R]),z=Xe.useCallback(async()=>{const X=uS(h,a);if(X){ce.error(X);return}const M={...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:fS(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(M),r(!1)}catch(le){ce.error(le instanceof Error?le.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{S(!1)}},[h,r,o,a]),xe=Xe.useId(),je=Xe.useCallback(()=>typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"], [data-slot="select-content"]'),[]),K=a(n?"sessions.scheduledTasks.editor.title.edit":"sessions.scheduledTasks.editor.title.new"),ye=a("sessions.scheduledTasks.editor.description"),Le=s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{htmlFor:"sched-name",required:!0,children:a("sessions.scheduledTasks.editor.taskName.label")}),s.jsx(vn,{id:"sched-name",value:h.name,onChange:X=>C(M=>({...M,name:X.target.value})),placeholder:a("sessions.scheduledTasks.editor.taskName.placeholder"),maxLength:80,className:"w-full sm:max-w-[220px]"})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.scheduleType.label")}),s.jsxs($n,{value:h.schedule.kind,onValueChange:X=>{C(M=>({...M,schedule:{...M.schedule,kind:X,...X==="cron"&&!M.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(zn,{className:"w-fit max-w-full",children:s.jsx(Nn,{children:X=>a(X==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":X==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":X==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(Wn,{children:[s.jsx(Ls,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(Ls,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(Ls,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(Ls,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),h.schedule.kind==="cron"?s.jsx(mS,{draft:h,setDraft:C,locale:c,t:a}):h.schedule.kind==="once"?s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex flex-col gap-1",ref:ne,children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.date.label")}),s.jsxs("div",{className:"relative",children:[s.jsxs("button",{type:"button",className:"inline-flex h-9 w-fit max-w-full items-center justify-between gap-2 rounded-md border border-border bg-background px-3 text-left hover:bg-interactive-hover",onClick:()=>k(X=>!X),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(D,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:tS(h.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(D,{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(X=>ef(X,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Ae,children:s.jsx(D,{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(E)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>Z(X=>ef(X,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(D,{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((X,M)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:X},`${X}-${M}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:sS(E,ke).map(({date:X,inCurrentMonth:M})=>{const le=Zu(X),ie=le===h.schedule.onceDate,Oe=of(X,Fe),Ge=X.getTime()<Fe.getTime(),He=ie?"bg-interactive-selection text-interactive-selection-foreground":Ge?"text-muted-foreground/40":M?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{Ge||(ue(le),k(!1))},disabled:Ge,className:["h-8 rounded-md typography-ui-label",He,Oe&&!ie?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",Ge?"cursor-not-allowed opacity-45":""].join(" "),children:X.getDate()},le)})}),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:he||""}),s.jsx($e,{type:"button",size:"xs",variant:"ghost",onClick:()=>{ue(Zu(Fe)),Z(new Date(Fe.getFullYear(),Fe.getMonth(),1))},children:a("sessions.scheduledTasks.editor.date.jumpToToday")})]})]}):null]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.time.label")}),s.jsx(nf,{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:X=>C(M=>({...M,schedule:{...M.schedule,onceTime:X}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs($n,{value:h.schedule.timezone,onValueChange:X=>{C(M=>({...M,schedule:{...M.schedule,timezone:X}}))},children:[s.jsx(zn,{className:"w-fit max-w-full",children:s.jsx(Nn,{})}),s.jsx(Wn,{children:rc.map(X=>s.jsx(Ls,{value:X,children:X},X))})]})]})]})]}):s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[h.schedule.kind==="weekly"?s.jsxs("div",{className:"flex flex-col gap-1 sm:col-span-2",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.weekdays.label")}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-2",children:Q.map(X=>{const M=h.schedule.weekdays.includes(X.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",M?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(Ti,{checked:M,onChange:le=>ee(X.value,le),ariaLabel:X.label}),s.jsx("button",{type:"button",onClick:()=>ee(X.value,!M),className:"group-hover:text-foreground",children:X.label})]},X.value)})})]}):null,s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.times.label")}),s.jsx("div",{className:"flex flex-col gap-2",children:h.schedule.times.map((X,M)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nf,{value:X,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:le=>Ne(M,le)}),h.schedule.times.length>1?s.jsx($e,{type:"button",size:"icon",variant:"ghost",onClick:()=>De(M),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(D,{name:"close",className:"h-4 w-4"})}):null]},M))}),s.jsx("div",{children:s.jsxs($e,{type:"button",size:"sm",variant:"outline",onClick:Be,children:[s.jsx(D,{name:"add",className:"mr-1 h-4 w-4"})," ",a("sessions.scheduledTasks.editor.times.add")]})})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs($n,{value:h.schedule.timezone,onValueChange:X=>{C(M=>({...M,schedule:{...M.schedule,timezone:X}}))},children:[s.jsx(zn,{className:"w-fit max-w-full",children:s.jsx(Nn,{})}),s.jsx(Wn,{children:rc.map(X=>s.jsx(Ls,{value:X,children:X},X))})]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{required:!0,children:a("sessions.scheduledTasks.editor.model.label")}),s.jsx(Kf,{providerId:h.execution.providerID,modelId:h.execution.modelID,onChange:(X,M)=>{C(le=>({...le,execution:{...le.execution,providerID:X,modelID:M,variant:""}}))}})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.thinkingLevel.label")}),s.jsxs($n,{value:se,disabled:!F,onValueChange:X=>{C(M=>({...M,execution:{...M.execution,variant:X==="__default"?"":X}}))},children:[s.jsx(zn,{className:"w-fit max-w-full",children:s.jsx(Nn,{children:X=>X==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):X})}),s.jsxs(Wn,{children:[s.jsx(Ls,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),ge.map(X=>s.jsx(Ls,{value:X,children:X},X))]})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.agent.label")}),s.jsx(qf,{agentName:h.execution.agent,filter:X=>wc(X.mode),onChange:X=>C(M=>({...M,execution:{...M.execution,agent:X}}))})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{htmlFor:"sched-prompt",required:!0,children:a("sessions.scheduledTasks.editor.prompt.label")}),s.jsxs("div",{className:"relative",children:[s.jsx(ki,{id:"sched-prompt",ref:Y,value:h.execution.prompt,onChange:X=>{const M=X.target.value;fe(M);const le=X.target.selectionStart??M.length;U(M,le)},onKeyDown:be,rows:8,placeholder:a("sessions.scheduledTasks.editor.prompt.placeholder"),className:"typography-meta min-h-[120px] max-h-[300px] resize-none overflow-y-auto"}),O?s.jsx(rm,{ref:re,searchQuery:T,onCommandSelect:$,onClose:()=>P(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,v?s.jsx(im,{ref:H,searchQuery:I,onFileSelect:de,onAgentSelect:G,onClose:()=>A(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,R?s.jsx(om,{ref:ae,searchQuery:V,onSnippetSelect:ve,onClose:()=>B(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]})]}),Re=s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("label",{className:"inline-flex items-center gap-2",children:[s.jsx(Ti,{checked:h.enabled,onChange:X=>C(M=>({...M,enabled:X})),ariaLabel:a("sessions.scheduledTasks.editor.enabled.aria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.enabled.label")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($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:z,disabled:w,children:a(w?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return y?s.jsx($a,{open:e,title:K,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:X=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:K}),X]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:ye})]}),footer:Re,children:Le}):s.jsx($s,{open:e,onOpenChange:X=>{!X&&je()||r(X)},children:s.jsxs(_s,{"aria-describedby":xe,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(on,{id:xe,className:"sr-only",children:ye}),s.jsx("header",{className:"shrink-0 px-4 sm:px-6 pt-5 pb-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-2xl",children:[s.jsx(Us,{className:"typography-ui-label font-medium text-foreground",children:K}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:ye})]})}),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:Le})}),s.jsx("div",{className:"shrink-0 px-4 sm:px-6 py-3",children:s.jsx("div",{className:"mx-auto w-full max-w-2xl",children:Re})})]})})}function pS(t){return lo(t,{min:0,max:23})}function gS(t,e){return lo(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function xS(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 bS(t){return s.jsx(Ls,{value:t,children:t},t)}const yS=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))},wS=(t,e)=>{const n=yS(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||""})},vS=(t,e)=>!t||!Number.isFinite(t)?"":Vf(t,e),lf=(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),b=g>0?`${f}h ${g}m`:`${f}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:b}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:b})}const d=Math.floor(r/c),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})},jS={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"}},SS=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function NS(){const{t}=Nt(),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=Js(R=>R.homeDirectory),{currentTheme:d}=Kr(),[u,m]=Xe.useState(""),[f,g]=Xe.useState([]),[b,p]=Xe.useState(!0),[x,y]=Xe.useState(!1),[h,C]=Xe.useState(null),[w,S]=Xe.useState(null),j=Xe.useMemo(()=>a.find(R=>R.id===u)||null,[a,u]),k=Xe.useCallback(R=>{const B=R.label?.trim()||Ri(R.path,l||void 0),V=R.icon?Ic[R.icon]:null,_=R.color?Ga[R.color]:void 0,E=V?s.jsx(D,{name:V,className:"h-3.5 w-3.5 shrink-0",style:_?{color:_}:void 0}):s.jsx(D,{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:[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:E})}):E,s.jsx("span",{className:"truncate",children:B})]})},[l,d.metadata.variant,d.colors.surface.foreground]),v=Xe.useCallback(async(R,B)=>{if(!R){g([]);return}B?.silent||p(!0);try{const V=await Qj(R);V.sort((_,E)=>{if(_.enabled!==E.enabled)return _.enabled?-1:1;const Z=_.name.localeCompare(E.name);return Z!==0?Z:(_.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(E.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),g(V)}catch(V){ce.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),B?.silent||g([])}finally{B?.silent||p(!1)}},[t]);Xe.useEffect(()=>{if(!e)return;const R=c?.id||a[0]?.id||"";m(R),R?v(R):(g([]),p(!1))},[e,c,a,v]),Xe.useEffect(()=>{if(!e)return;let R=null;const B=lh(V=>{V.type==="scheduled-task-ran"&&V.projectId===u&&(R&&clearTimeout(R),R=setTimeout(()=>{v(u,{silent:!0})},400))});return()=>{R&&clearTimeout(R),B()}},[e,u,v]);const A=Xe.useCallback(async R=>{if(!u)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await Ju(u,R),await v(u),ce.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[u,v,t]),I=Xe.useCallback(async(R,B)=>{if(u){S(R.id),g(V=>V.map(_=>_.id===R.id?{..._,enabled:B}:_));try{await Ju(u,{...R,enabled:B}),await v(u,{silent:!0})}catch(V){ce.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await v(u,{silent:!0})}finally{S(null)}}},[u,v,t]),N=Xe.useCallback(async R=>{if(!(!u||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:R.name})))){S(R.id);try{await Jj(u,R.id),await v(u,{silent:!0}),ce.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(V){ce.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{S(null)}}},[u,v,t]),O=Xe.useCallback(async R=>{if(u){S(R.id);try{await Xj(u,R.id),await Promise.all([v(u,{silent:!0}),Sa()]),ce.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch(B){ce.error(B instanceof Error?B.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{S(null)}}},[u,v,t]),P=s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("sessions.scheduledTasks.dialog.project.label")}),s.jsxs($n,{value:u||"__none",onValueChange:R=>{const B=R==="__none"?"":R;m(B),B?v(B):g([])},children:[s.jsx(zn,{className:r?"w-full":void 0,children:j?s.jsx(Nn,{children:k(j)}):s.jsx(Nn,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(Wn,{children:[a.length===0?s.jsx(Ls,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(R=>s.jsx(Ls,{value:R.id,children:k(R)},R.id))]})]})]}),T=()=>{C(null),y(!0)},L=s.jsxs("div",{className:"space-y-4",children:[r?P:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[P,s.jsxs($e,{onClick:T,disabled:!u,children:[s.jsx(D,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:b?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(D,{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 B=w===R.id,V=R.state?.lastStatus||"idle",_=jS[V],E=t(V==="success"?"sessions.scheduledTasks.dialog.status.success":V==="error"?"sessions.scheduledTasks.dialog.status.error":V==="running"?"sessions.scheduledTasks.dialog.status.running":"sessions.scheduledTasks.dialog.status.idle"),Z=R.state?.nextRunAt,ne=R.state?.lastRunAt;return s.jsxs("div",{className:Pe("rounded-lg border border-border p-4 transition-opacity",!R.enabled&&"opacity-60"),children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-header truncate font-semibold text-foreground",children:R.name}),s.jsx("div",{className:"typography-micro truncate text-muted-foreground",children:wS(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(D,{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:lf(Z,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:vS(Z,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(D,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),V==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(D,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):ne?s.jsxs(s.Fragment,{children:[_.tone!=="muted"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:`var(--status-${_.tone})`},children:[s.jsx(D,{name:_.Icon,className:"h-3.5 w-3.5"}),E]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:lf(ne,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:SS("error"),children:[s.jsx(D,{name:"error-warning",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"min-w-0 break-words",children:R.state.lastError})]}):null,s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("label",{className:Pe("inline-flex cursor-pointer items-center gap-2 typography-micro font-medium",R.enabled?"text-foreground":"text-muted-foreground",B&&"cursor-not-allowed opacity-50"),children:[s.jsx(Ti,{checked:R.enabled,onChange:Y=>{I(R,Y)},ariaLabel:R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:R.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:R.name}),disabled:B}),R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.enabled"):t("sessions.scheduledTasks.dialog.taskToggle.paused")]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{O(R)},disabled:B,children:[s.jsx(D,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs($e,{variant:"outline",size:"sm",onClick:()=>{C(R),y(!0)},disabled:B,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:R.name}),children:[s.jsx(D,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx($e,{variant:"destructive",size:"sm",onClick:()=>{N(R)},disabled:B,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:R.name}),children:s.jsx(D,{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:T,disabled:!u,children:[s.jsx(D,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:L}):s.jsx($s,{open:e,onOpenChange:n,children:s.jsxs(_s,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(Hs,{children:[s.jsx(Us,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(on,{children:t("sessions.scheduledTasks.dialog.description")})]}),L]})}),s.jsx(hS,{open:x,task:h,onOpenChange:y,onSave:A})]})}const kS=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>cs(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||cs(l.directory??null)?!1:Ro(l,t.normalizedPath,r));return so([...a,...c])},CS=t=>{const e=mt.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,b;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=Fc(p.normalizedPath),y=kS(p,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c}),h=new Set(y.map(AS)),C=d[x]??[],w=new Map(C.map(DS));y.forEach(S=>{const j=ab(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)})},b=[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]=b):(g=e[10],b=e[11]),i.useEffect(g,b)};function AS(t){return t.id}function DS(t){return[t.name.toLowerCase(),t]}const IS=t=>{const e=mt.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:b,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 N;e[9]!==a||e[10]!==u||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(N=O=>{const P=so([...r(O),...o(O)]),T=a.get(O.normalizedPath)??[],L=c.has(O.id)?!!c.get(O.id):d,R=u(P,O.normalizedPath,T,l.get(O.id)??null,L);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]=N):N=e[16],x=n.map(N),e[0]=a,e[1]=u,e[2]=o,e[3]=r,e[4]=d,e[5]=n,e[6]=c,e[7]=l,e[8]=x}else x=e[8];const y=x,h=y;let C;if(e[17]!==b||e[18]!==g||e[19]!==p||e[20]!==m||e[21]!==f||e[22]!==h){e:{const N=new WeakMap;if(!m){C=N;break e}const O=P=>P.reduce((T,L)=>T+1+O(L.children),0);h.forEach(P=>{P.groups.forEach(T=>{const L=g(T.sessions,f),R=O(L),B=b(T).includes(f),V=cs(T.directory??null),E=(V?p[V]??[]:[]).filter(Z=>Z.name.toLowerCase().includes(f)).length;N.set(T,{filteredNodes:L,matchedSessionCount:R,folderNameMatchCount:E,groupMatches:B,hasMatch:B||R>0||E>0})})}),C=N}e[17]=b,e[18]=g,e[19]=p,e[20]=m,e[21]=f,e[22]=h,e[23]=C}else C=e[23];const w=C;let S;e:{if(!m){S=h;break e}let N;if(e[24]!==w||e[25]!==h){let O;e[27]!==w?(O=P=>({...P,groups:P.groups.filter(T=>w.get(T)?.hasMatch===!0)}),e[27]=w,e[28]=O):O=e[28],N=h.map(O).filter(PS),e[24]=w,e[25]=h,e[26]=N}else N=e[26];S=N}const j=S,k=m?j:h;let v;e:{if(!m){v=0;break e}let N;if(e[29]!==w||e[30]!==k){let O;e[32]!==w?(O=(P,T)=>P+T.groups.reduce((L,R)=>{const B=w.get(R);if(!B)return L;const V=B.folderNameMatchCount+(B.groupMatches?1:0);return L+B.matchedSessionCount+V},0),e[32]=w,e[33]=O):O=e[33],N=k.reduce(O,0),e[29]=w,e[30]=k,e[31]=N}else N=e[31];v=N}const A=v;let I;return e[34]!==w||e[35]!==y||e[36]!==A||e[37]!==j||e[38]!==k||e[39]!==h?(I={projectSections:y,visibleProjectSections:h,groupSearchDataByGroup:w,searchableProjectSections:j,sectionsForRender:k,searchMatchCount:A},e[34]=w,e[35]=y,e[36]=A,e[37]=j,e[38]=k,e[39]=h,e[40]=I):I=e[40],I};function PS(t){return t.groups.length>0}const TS=t=>{const e=mt.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 b,p;if(e[0]!==n){p=new Map,b=new Map;const k=(v,A,I,N)=>{p.has(v)||p.set(v,new Map);const O=p.get(v);N.forEach(P=>{const T=cs(P.worktree?.path??P.session.directory??I??A);O.set(P.session.id,{directory:T}),b.has(v)||b.set(v,{id:P.session.id,directory:T}),P.children.length>0&&k(v,A,T,P.children)})};n.forEach(v=>{v.groups.forEach(A=>{k(v.project.id,v.project.normalizedPath,A.directory,A.sessions)})}),e[0]=n,e[1]=b,e[2]=p}else b=e[1],p=e[2];let x;e[3]!==b||e[4]!==p?(x={metaByProject:p,firstSessionByProject:b},e[3]=b,e[4]=p,e[5]=x):x=e[5];const y=x,h=i.useRef(null);let C,w;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==u||e[11]!==d||e[12]!==m||e[13]!==n||e[14]!==y||e[15]!==f||e[16]!==a||e[17]!==g?(C=()=>{if(!r||d||Ee.getState().isNewWorktreeDialogOpen||h.current===r)return;const k=n.find(T=>T.project.id===r);if(!k)return;h.current=r;const v=y.metaByProject.get(r);if(c&&v&&v.has(c)){a(T=>{if(T.get(r)===c)return T;const L=new Map(T);return L.set(r,c),L});return}if(!v||v.size===0){f("chat"),u&&g(!1),m({directoryOverride:k.project.normalizedPath});return}const A=o.get(r),I=A&&v.has(A)?A:null,N=y.firstSessionByProject.get(r)?.id??null,O=I??N;if(!O||O===c)return;const P=v.get(O)?.directory??null;l(O,P,r)},w=[r,o,c,l,d,u,m,n,y,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]=y,e[15]=f,e[16]=a,e[17]=g,e[18]=C,e[19]=w):(C=e[18],w=e[19]),i.useLayoutEffect(C,w);let S,j;e[20]!==r||e[21]!==c||e[22]!==y||e[23]!==a?(S=()=>{if(!r||!c)return;const k=y.metaByProject.get(r);!k||!k.has(c)||a(v=>{if(v.get(r)===c)return v;const A=new Map(v);return A.set(r,c),A})},j=[r,c,y,a],e[20]=r,e[21]=c,e[22]=y,e[23]=a,e[24]=S,e[25]=j):(S=e[24],j=e[25]),i.useEffect(S,j)},RS=t=>{const e=mt.c(4);let n;e[0]!==t?(n=(a,c)=>{const l=t.get(a);if(!l||l.length===0)return c;const d=new Map(c.map(ES)),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 ES(t){return[t.id,t]}const ea=t=>!!t.time?.archived,MS=t=>{const{t:e}=Nt(),n=i.useCallback(c=>[c.label,c.branch??"",c.description??"",c.directory??""].join(" ").toLowerCase(),[]),r=i.useCallback(c=>{const l=cs(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=cs(l??null),g=so(c).sort((P,T)=>Gi(P,T,t.pinnedSessionIds)),b=new Map(g.map(P=>[P.id,P])),p=new Map;g.forEach(P=>{const T=P.parentID;if(!T)return;const L=b.get(T);if(!L||ea(L)!==ea(P))return;const R=p.get(T)??[];R.push(P),p.set(T,R)}),p.forEach(P=>P.sort((T,L)=>Gi(T,L,t.pinnedSessionIds)));const x=new Map;d.forEach(P=>{if(P.path){const T=cs(P.path)??P.path;x.set(T,P)}});const y=P=>{const T=cs(P.directory??null),L=t.worktreeMetadata.get(P.id)??null;if(L)return L;if(T){const R=x.get(T)??null;if(R&&T!==f)return R}return null},h=P=>{const T=p.get(P.id)??[];return{session:P,children:T.map(L=>h(L)),worktree:y(P)}},C=g.filter(P=>{const T=P.parentID;if(!T)return!0;const L=b.get(T);return L?ea(L)!==ea(P):!0}),w=new Map,S="__archived__",j=P=>{if(P.time?.archived)return S;if(t.isVSCode)return f??"__project_root__";const L=cs(t.worktreeMetadata.get(P.id)?.path??null)??Tr(P);return L?L!==f&&x.has(L)?L:L===f?f??"__project_root__":S:S};C.forEach(P=>{const T=h(P),L=j(P);w.has(L)||w.set(L,[]),w.get(L)?.push(T)});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)??[]}],A=new Map;d.forEach(P=>{const T=cs(P.path)??P.path,L=w.get(T)??[],R=L.length>0,B=L.reduce((V,_)=>{const E=Number(_.session.time?.updated??_.session.time?.created??0);return Number.isFinite(E)?Math.max(V,E):V},0);A.set(T,{hasActiveSession:R,lastUpdatedAt:B})});const I=[...d].sort((P,T)=>{const L=cs(P.path)??P.path,R=cs(T.path)??T.path,B=A.get(L)??{hasActiveSession:!1,lastUpdatedAt:0},V=A.get(R)??{hasActiveSession:!1,lastUpdatedAt:0};if(B.hasActiveSession!==V.hasActiveSession)return B.hasActiveSession?-1:1;if(B.hasActiveSession&&V.hasActiveSession)return V.lastUpdatedAt-B.lastUpdatedAt;const _=(P.label||P.branch||P.name||P.path||"").toLowerCase(),E=(T.label||T.branch||T.name||T.path||"").toLowerCase();return _.localeCompare(E)});(t.isVSCode?[]:I).forEach(P=>{const T=cs(P.path)??P.path,L=t.gitBranches.get(T)?.trim()||null,R=P.branch?.trim()||null,V=!!(L&&R&&P.label&&qd(P.label)===qd(R))?L:P.label||P.name||Ri(T,t.homeDirectory)||T;v.push({id:`worktree:${T}`,label:V,branch:L||R,description:Na(T,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:P,directory:T,folderScopeKey:T,sessions:w.get(T)??[]})});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?Fc(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}},FS=t=>{const e=mt.c(9),{isSessionSearchOpen:n,setIsSessionSearchOpen:r,sessionSearchInputRef:o,sessionSearchContainerRef:a}=t;let c,l;e[0]!==n||e[1]!==o?(c=()=>{if(!n||typeof window>"u")return;const m=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(m)},l=[n,o],e[0]=n,e[1]=o,e[2]=c,e[3]=l):(c=e[2],l=e[3]),i.useEffect(c,l);let d,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)},LS=t=>{const e=mt.c(42),{t:n}=Nt(),[r,o]=i.useState(null),a=i.useRef(null);let c,l;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=()=>()=>{a.current&&clearTimeout(a.current)},l=[],e[0]=c,e[1]=l):(c=e[0],l=e[1]),i.useEffect(c,l);let d;e[2]!==t?(d=(B,V,_)=>{const E=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))};if(_&&_!==t.activeProjectId&&t.setActiveProjectIdOnly(_),V&&V!==t.currentDirectory&&t.setDirectory(V,{showOverlay:!1}),t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),B===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(B),E();return}t.setCurrentSession(B,V??null),t.onSessionSelected?.(B),E()},e[2]=t,e[3]=d):d=e[3];const u=d;let m;e[4]!==t?(m=(B,V)=>{t.setEditingId(B),t.setEditTitle(V)},e[4]=t,e[5]=m):m=e[5];const f=m;let g;e[6]!==t?(g=async B=>{if(!t.editingId)return;const V=(B??t.editTitle).trim();V&&await t.updateSessionTitle(t.editingId,V),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=g):g=e[7];const b=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 y;e[10]!==t||e[11]!==n?(y=async B=>{const V=await t.shareSession(B.id);V&&V.share?.url?ce.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):ce.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=y):y=e[12];const h=y;let C;e[13]!==n?(C=(B,V)=>{ur(B).then(_=>{if(!_.ok){ce.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(V),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{ce.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=C):C=e[14];const w=C;let S;e[15]!==t||e[16]!==n?(S=async B=>{await t.unshareSession(B)?ce.success(n("sessions.sidebar.session.unshare.success")):ce.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=S):S=e[17];const j=S;let k;e[18]!==t.childrenMap?(k=B=>{const V=[],_=E=>{(t.childrenMap.get(E)??[]).forEach(ne=>{V.push(ne),_(ne.id)})};return _(B),V},e[18]=t.childrenMap,e[19]=k):k=e[19];const v=k,A=BS;let I;e[20]!==t||e[21]!==v||e[22]!==n?(I=async(B,V,_)=>{const E=V?.archivedBucket===!0||V?.hardDelete===!0,Z=_?.descendantIds??A(v(B.id),E).map(VS);if(Z.length===0){(E?await t.deleteSession(B.id):await t.archiveSession(B.id))?ce.success(n(E?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):ce.error(n(E?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const ne=[B.id,...Z];if(E){if(await t.deleteSession(B.id)){const ae=Z.length+1;ce.success(ae===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:ae}):n("sessions.sidebar.bulkActions.deletedPlural",{count:ae}))}else ce.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:Y,failedIds:H}=await t.archiveSessions(ne);Y.length>0&&ce.success(Y.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:Y.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:Y.length})),H.length>0&&ce.error(H.length===1?n("sessions.sidebar.bulkActions.failedArchiveSingle",{count:H.length}):n("sessions.sidebar.bulkActions.failedArchivePlural",{count:H.length}))},e[20]=t,e[21]=v,e[22]=n,e[23]=I):I=e[23];const N=I;let O;e[24]!==t||e[25]!==v||e[26]!==N?(O=(B,V)=>{const _=V?.archivedBucket===!0||V?.hardDelete===!0,E=A(v(B.id),_).map(_S);if(!t.showDeletionDialog||V?.skipConfirm===!0){N(B,V,{descendantIds:E});return}t.setDeleteSessionConfirm({session:B,descendantCount:E.length,descendantIds:E,archivedBucket:_})},e[24]=t,e[25]=v,e[26]=N,e[27]=O):O=e[27];const P=O;let T;e[28]!==t||e[29]!==N?(T=async()=>{if(!t.deleteSessionConfirm)return;const{session:B,archivedBucket:V,descendantIds:_}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await N(B,{archivedBucket:V},{descendantIds:_})},e[28]=t,e[29]=N,e[30]=T):T=e[30];const L=T;let R;return e[31]!==L||e[32]!==r||e[33]!==x||e[34]!==w||e[35]!==P||e[36]!==b||e[37]!==f||e[38]!==u||e[39]!==h||e[40]!==j?(R={copiedSessionId:r,handleSessionSelect:u,handleSessionDoubleClick:f,handleSaveEdit:b,handleCancelEdit:x,handleShareSession:h,handleCopyShareUrl:w,handleUnshareSession:j,handleDeleteSession:P,confirmDeleteSession:L},e[31]=L,e[32]=r,e[33]=x,e[34]=w,e[35]=P,e[36]=b,e[37]=f,e[38]=u,e[39]=h,e[40]=j,e[41]=R):R=e[41],R};function OS(t){return!t.time?.archived}function BS(t,e){return e?t:t.filter(OS)}function VS(t){return t.id}function _S(t){return t.id}const $S=["project:active:","project:archived:","recent:active:","recent:archived:"],zS=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),b=i.useRef(null),p=i.useCallback(()=>{if(e)return;const y=b.current;if(b.current=null,g.current=null,!y)return;const{projects:h}=ws.getState(),C=h.map(w=>({...w,sidebarCollapsed:y.has(w.id)}));fc({projects:C}).catch(()=>{})},[e]),x=i.useCallback(y=>{typeof window>"u"||e||(b.current=y,g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{p()},700))},[e,p]);return i.useEffect(()=>()=>{typeof window<"u"&&g.current!==null&&window.clearTimeout(g.current),g.current=null,b.current=null},[]),i.useEffect(()=>{try{const y=r.getItem(o.sessionExpanded);if(y){const C=JSON.parse(y);Array.isArray(C)&&m(new Set(C.filter(w=>typeof w=="string")))}else{const C=r.getItem(o.sessionExpandedLegacy);if(C){try{const w=JSON.parse(C);if(Array.isArray(w)){const S=new Set;if(w.forEach(j=>{typeof j!="string"||j.length===0||$S.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 C=JSON.parse(h);Array.isArray(C)&&f(new Set(C.filter(w=>typeof w=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,f,m]),i.useEffect(()=>{if(!n||a.length===0)return;const y=new Set(a.map(h=>h.id));c(h=>{let C=!1;const w=new Set;return h.forEach(S=>{y.has(S)?w.add(S):C=!0}),C?w:h})},[n,a,c]),i.useEffect(()=>{try{const y=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(y))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const y=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(y))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(u)))}catch{}},[u,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:x}},WS=t=>{const{normalizedProjects:e,gitRepoStatus:n,setProjectRepoStatus:r,setProjectRootBranches:o}=t,{git:a}=Jn(),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(),y=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}`,A=d.current.get(S.id);if(A===v){const I=u.current.get(S.id);return I&&(I.at=x),!1}return!(A!==void 0&&x-(u.current.get(S.id)?.at??0)<m)});if(y.length===0)return;const h=await Mm(y,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 C=h.filter(S=>S.branch);if(C.length===0)return;const w=Date.now();o(S=>{const j=new Map(S);return C.forEach(({id:k,branch:v})=>{v&&j.set(k,v)}),j}),C.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])},US=t=>{const e=mt.c(19),{isVSCode:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,normalizedProjects:c}=t;let l;if(e[0]!==a||e[1]!==n||e[2]!==c){if(l=new Set,c.forEach(y=>{y.normalizedPath&&l.add(y.normalizedPath)}),!n)for(const y of a.values())for(const h of y){const C=cs(h.path);C&&l.add(C)}e[0]=a,e[1]=n,e[2]=c,e[3]=l}else l=e[3];const d=l;let u;e[4]!==d||e[5]!==r?(u=new Map,r.forEach(y=>{const h=Tr(y);if(!h||!d.has(h))return;const C=u.get(h)??[];C.push(y),u.set(h,C)}),e[4]=d,e[5]=r,e[6]=u):u=e[6];const m=u;let f;e[7]!==a||e[8]!==n||e[9]!==m?(f=y=>{const h=n?[]:a.get(y.normalizedPath)??[],C=[y.normalizedPath,...h.map(HS).filter(GS)],w=new Set,S=[];return C.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 b;e[11]!==o||e[12]!==a||e[13]!==n||e[14]!==r?(b=y=>{if(n){const k=o.filter(A=>{const I=cs(A.directory??null),N=cs(A.project?.worktree??null);return I?I===y.normalizedPath:N===y.normalizedPath}),v=r.filter(A=>A.time?.archived||cs(A.directory??null)?!1:cs(A.project?.worktree??null)===y.normalizedPath);return so([...k,...v])}const h=n?[]:a.get(y.normalizedPath)??[],C=new Set([y.normalizedPath,...h.map(KS).filter(qS)]),S=(k=>k.filter(v=>Ro(v,y.normalizedPath,C)))(o),j=r.filter(k=>{if(k.time?.archived||cs(k.directory??null))return!1;const A=cs(k.project?.worktree??null);return A?A===y.normalizedPath||A.startsWith(`${y.normalizedPath}/`):!1});return so([...S,...j])},e[11]=o,e[12]=a,e[13]=n,e[14]=r,e[15]=b):b=e[15];const p=b;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 HS(t){return cs(t.path)??t.path}function GS(t){return!!t}function KS(t){return cs(t.path)??t.path}function qS(t){return!!t}const YS=t=>{const e=mt.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 y=cs(x.directory??null);if(!y)return;const h=g.get(y);if(h){h.add(x.id);return}g.set(y,new Set([x.id]))}),c.forEach(x=>{const y=Fc(x.normalizedPath),h=l?[]:d.get(x.normalizedPath)??[],C=new Set([x.normalizedPath,...h.map(QS).filter(JS)]),w=so([...a,...o.filter(S=>S.time?.archived||cs(S.directory??null)?!1:Ro(S,x.normalizedPath,C))]).filter(S=>Ro(S,x.normalizedPath,C));g.set(y,new Set(w.map(XS)))});const b=Ln.getState().foldersMap;new Set([...Object.keys(b),...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 QS(t){return cs(t.path)??t.path}function JS(t){return!!t}function XS(t){return t.id}const ZS=t=>{const e=mt.c(8),{isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=t;let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=new Set,e[0]=a):a=e[0];const[c,l]=i.useState(a);let d;e[1]!==n||e[2]!==o?(d=()=>{if(!n)return;const m=new IntersectionObserver(f=>{f.forEach(g=>{const b=g.target.dataset.projectId;b&&l(p=>{const x=new Set(p);return g.isIntersecting?x.delete(b):x.add(b),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},eN=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Pl=t=>{if(!t)return null;const e=t.trim();return e&&eN.test(e)?e.toLowerCase():null},tN=t=>{const e=mt.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,b=u===void 0?null:u,{t:p}=Nt(),x=ws(sN),y=ws(nN),h=ws(rN);let C;e[0]!==o?(C=Qe=>Qe.projects.find(At=>At.id===o)?.iconImage??null,e[0]=o,e[1]=C):C=e[1];const w=ws(C),{currentTheme:S}=Kr(),[j,k]=i.useState(a),[v,A]=i.useState(f),[I,N]=i.useState(g);let O;e[2]!==b?(O=Pl(b),e[2]=b,e[3]=O):O=e[3];const[P,T]=i.useState(O),[L,R]=i.useState(!1),[B,V]=i.useState(!1),[_,E]=i.useState(!1),[Z,ne]=i.useState(!1),[Y,H]=i.useState(null),[re,ae]=i.useState(null),[me,Se]=i.useState(!1),te=i.useRef(null);let ke;e[4]===Symbol.for("react.memo_cache_sentinel")?(ke=()=>{H(null),ae(iN)},e[4]=ke):ke=e[4];const Q=ke;let ge,F;e[5]!==g||e[6]!==f||e[7]!==b||e[8]!==n||e[9]!==a?(ge=()=>{n&&(k(a),A(f),N(g),T(Pl(b)),ne(!1),Q(),Se(!1))},F=[n,a,f,g,b,Q],e[5]=g,e[6]=f,e[7]=b,e[8]=n,e[9]=a,e[10]=ge,e[11]=F):(ge=e[10],F=e[11]),i.useEffect(ge,F);let se,ee;e[12]===Symbol.for("react.memo_cache_sentinel")?(ee=()=>()=>{Q()},se=[Q],e[12]=se,e[13]=ee):(se=e[12],ee=e[13]),i.useEffect(ee,se);let Ne,De,Be;if(e[14]!==I||e[15]!==w||e[16]!==v||e[17]!==P||e[18]!==j||e[19]!==r||e[20]!==m||e[21]!==Z||e[22]!==Y||e[23]!==o||e[24]!==y||e[25]!==p||e[26]!==x){let Qe;e[30]!==I||e[31]!==v||e[32]!==P||e[33]!==j||e[34]!==r||e[35]!==m||e[36]!==Z||e[37]!==Y||e[38]!==o||e[39]!==y||e[40]!==p||e[41]!==x?(Qe=async()=>{const At=j.trim();if(!At)return;if(Y){R(!0);const ts=await x(o,Y);if(R(!1),!ts.ok){ce.error(ts.error||p("projectEditDialog.toast.failedToUploadIcon"));return}ce.success(p("projectEditDialog.toast.iconUpdated")),Q(),ne(!1)}const Tt=Z&&Be;if(Tt){V(!0);const ts=await y(o);if(V(!1),!ts.ok){ce.error(ts.error||p("projectEditDialog.toast.failedToRemoveIcon"));return}ce.success(p("projectEditDialog.toast.iconRemoved")),ne(!1),T(null)}m({label:At,icon:v,color:I,iconBackground:Pl(Tt?null:P)}),r(!1)},e[30]=I,e[31]=v,e[32]=P,e[33]=j,e[34]=r,e[35]=m,e[36]=Z,e[37]=Y,e[38]=o,e[39]=y,e[40]=p,e[41]=x,e[42]=Qe):Qe=e[42],De=Qe,Ne=I?Ga[I]??null:null,Be=!!w,e[14]=I,e[15]=w,e[16]=v,e[17]=P,e[18]=j,e[19]=r,e[20]=m,e[21]=Z,e[22]=Y,e[23]=o,e[24]=y,e[25]=p,e[26]=x,e[27]=Ne,e[28]=De,e[29]=Be}else Ne=e[27],De=e[28],Be=e[29];const Fe=!!(Y&&re),Me=w?.source==="custom",he=Be&&!Z||Fe,Ae=he,ue=!me&&(Fe||Be&&!Z);let U;e[43]===Symbol.for("react.memo_cache_sentinel")?(U=()=>{Se(!1)},e[43]=U):U=e[43];const fe=w?.updatedAt;let de;e[44]!==o||e[45]!==fe?(de=[o,fe],e[44]=o,e[45]=fe,e[46]=de):de=e[46],i.useEffect(U,de);let G;e[47]!==L||e[48]!==o?(G=Qe=>{!o||!Qe||L||(ne(!1),Se(!1),H(Qe),ae(At=>(At&&URL.revokeObjectURL(At),URL.createObjectURL(Qe))))},e[47]=L,e[48]=o,e[49]=G):G=e[49];const $=G;let ve;e[50]!==Fe||e[51]!==Ae||e[52]!==Be||e[53]!==B||e[54]!==o?(ve=()=>{!o||!Ae||B||(Fe&&Q(),ne(!!Be),Se(!1))},e[50]=Fe,e[51]=Ae,e[52]=Be,e[53]=B,e[54]=o,e[55]=ve):ve=e[55];const be=ve;let z;e[56]!==h||e[57]!==_||e[58]!==o||e[59]!==p?(z=async()=>{!o||_||(Q(),ne(!1),Se(!1),E(!0),h(o).then(Qe=>{if(!Qe.ok){ce.error(Qe.error||p("projectEditDialog.toast.failedToDiscoverIcon"));return}if(Qe.skipped){ce.success(p("projectEditDialog.toast.customIconAlreadySet"));return}ce.success(p("projectEditDialog.toast.iconDiscovered"))}).finally(()=>{E(!1)}))},e[56]=h,e[57]=_,e[58]=o,e[59]=p,e[60]=z):z=e[60];const xe=z;let je;e[61]!==p?(je=p("projectEditDialog.title"),e[61]=p,e[62]=je):je=e[62];let K;e[63]!==je?(K=s.jsx(Hs,{className:"min-w-0",children:s.jsx(Us,{children:je})}),e[63]=je,e[64]=K):K=e[64];let ye;e[65]!==p?(ye=p("projectEditDialog.field.name"),e[65]=p,e[66]=ye):ye=e[66];let Le;e[67]!==ye?(Le=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:ye}),e[67]=ye,e[68]=Le):Le=e[68];let Re;e[69]===Symbol.for("react.memo_cache_sentinel")?(Re=Qe=>k(Qe.target.value),e[69]=Re):Re=e[69];let X;e[70]!==p?(X=p("projectEditDialog.field.namePlaceholder"),e[70]=p,e[71]=X):X=e[71];let M;e[72]!==De?(M=Qe=>{Qe.key==="Enter"&&(Qe.preventDefault(),De())},e[72]=De,e[73]=M):M=e[73];let le;e[74]!==j||e[75]!==X||e[76]!==M?(le=s.jsx(vn,{value:j,onChange:Re,placeholder:X,onKeyDown:M,autoFocus:!0}),e[74]=j,e[75]=X,e[76]=M,e[77]=le):le=e[77];let ie;e[78]!==c?(ie=s.jsx("p",{className:"typography-meta text-muted-foreground truncate",title:c,children:c}),e[78]=c,e[79]=ie):ie=e[79];let Oe;e[80]!==Le||e[81]!==le||e[82]!==ie?(Oe=s.jsxs("div",{className:"min-w-0 space-y-1.5",children:[Le,le,ie]}),e[80]=Le,e[81]=le,e[82]=ie,e[83]=Oe):Oe=e[83];let Ge;e[84]!==p?(Ge=p("projectEditDialog.field.color"),e[84]=p,e[85]=Ge):Ge=e[85];let He;e[86]!==Ge?(He=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:Ge}),e[86]=Ge,e[87]=He):He=e[87];let Je;e[88]===Symbol.for("react.memo_cache_sentinel")?(Je=()=>N(null),e[88]=Je):Je=e[88];const rt=I===null?"border-foreground scale-110":"border-border hover:border-border/80";let bt;e[89]!==rt?(bt=Pe("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",rt),e[89]=rt,e[90]=bt):bt=e[90];let yt;e[91]!==p?(yt=p("projectEditDialog.option.none"),e[91]=p,e[92]=yt):yt=e[92];let _e;e[93]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[93]=_e):_e=e[93];let Ye;e[94]!==bt||e[95]!==yt?(Ye=s.jsx("button",{type:"button",onClick:Je,className:bt,title:yt,children:_e}),e[94]=bt,e[95]=yt,e[96]=Ye):Ye=e[96];let nt;e[97]!==I?(nt=Sg.map(Qe=>s.jsx("button",{type:"button",onClick:()=>N(Qe.key),className:Pe("w-8 h-8 rounded-lg border-2 transition-all",I===Qe.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:Qe.cssVar},title:Qe.label},Qe.key)),e[97]=I,e[98]=nt):nt=e[98];let wt;e[99]!==Ye||e[100]!==nt?(wt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Ye,nt]}),e[99]=Ye,e[100]=nt,e[101]=wt):wt=e[101];let kt;e[102]!==He||e[103]!==wt?(kt=s.jsxs("div",{className:"min-w-0 space-y-2",children:[He,wt]}),e[102]=He,e[103]=wt,e[104]=kt):kt=e[104];let vt;e[105]!==p?(vt=p("projectEditDialog.field.icon"),e[105]=p,e[106]=vt):vt=e[106];let St;e[107]!==vt?(St=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:vt}),e[107]=vt,e[108]=St):St=e[108];let et;e[109]!==$?(et=s.jsx("input",{ref:te,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:Qe=>{const At=Qe.target.files?.[0]??null;$(At),Qe.currentTarget.value=""}}),e[109]=$,e[110]=et):et=e[110];let Ot;e[111]===Symbol.for("react.memo_cache_sentinel")?(Ot=()=>A(null),e[111]=Ot):Ot=e[111];const ns=v===null?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80";let Wt;e[112]!==ns?(Wt=Pe("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",ns),e[112]=ns,e[113]=Wt):Wt=e[113];let Ve;e[114]!==p?(Ve=p("projectEditDialog.option.none"),e[114]=p,e[115]=Ve):Ve=e[115];let Ze;e[116]===Symbol.for("react.memo_cache_sentinel")?(Ze=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[116]=Ze):Ze=e[116];let _t;e[117]!==Wt||e[118]!==Ve?(_t=s.jsx("button",{type:"button",onClick:Ot,className:Wt,title:Ve,children:Ze}),e[117]=Wt,e[118]=Ve,e[119]=_t):_t=e[119];let jt;e[120]!==Ne||e[121]!==v?(jt=Ng.map(Qe=>{const At=Qe.Icon;return s.jsx("button",{type:"button",onClick:()=>A(Qe.key),className:Pe("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",v===Qe.key?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80"),title:Qe.label,children:s.jsx(D,{name:At,className:"w-4 h-4",style:Ne?{color:Ne}:void 0})},Qe.key)}),e[120]=Ne,e[121]=v,e[122]=jt):jt=e[122];let xt;e[123]!==_t||e[124]!==jt?(xt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[_t,jt]}),e[123]=_t,e[124]=jt,e[125]=xt):xt=e[125];let rs;e[126]!==w||e[127]!==S||e[128]!==he||e[129]!==Fe||e[130]!==P||e[131]!==re||e[132]!==o||e[133]!==ue||e[134]!==p?(rs=he&&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:P?{backgroundColor:P}:void 0,children:Fe&&re?s.jsx("img",{src:re,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>Se(!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:()=>Se(!0)})})})]}),e[126]=w,e[127]=S,e[128]=he,e[129]=Fe,e[130]=P,e[131]=re,e[132]=o,e[133]=ue,e[134]=p,e[135]=rs):rs=e[135];let Gt;e[136]!==xe||e[137]!==Me||e[138]!==_||e[139]!==L||e[140]!==p?(Gt=!Me&&s.jsxs(s.Fragment,{children:[s.jsx($e,{size:"sm",variant:"outline",onClick:()=>te.current?.click(),disabled:L,children:p(L?"projectEditDialog.actions.uploading":"projectEditDialog.actions.uploadIcon")}),s.jsx($e,{size:"sm",variant:"outline",onClick:()=>{xe()},disabled:_,children:p(_?"projectEditDialog.actions.discovering":"projectEditDialog.actions.discoverFavicon")})]}),e[136]=xe,e[137]=Me,e[138]=_,e[139]=L,e[140]=p,e[141]=Gt):Gt=e[141];let Ut;e[142]!==be||e[143]!==Ae||e[144]!==B||e[145]!==p?(Ut=Ae&&s.jsx($e,{size:"sm",variant:"outline",onClick:()=>{be()},disabled:B,children:p(B?"projectEditDialog.actions.removing":"projectEditDialog.actions.removeProjectIcon")}),e[142]=be,e[143]=Ae,e[144]=B,e[145]=p,e[146]=Ut):Ut=e[146];let as;e[147]!==B||e[148]!==Z||e[149]!==p?(as=Z&&s.jsx($e,{size:"sm",variant:"outline",onClick:()=>ne(!1),disabled:B,children:p("projectEditDialog.actions.undoRemove")}),e[147]=B,e[148]=Z,e[149]=p,e[150]=as):as=e[150];let Bt;e[151]!==Gt||e[152]!==Ut||e[153]!==as?(Bt=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[Gt,Ut,as]}),e[151]=Gt,e[152]=Ut,e[153]=as,e[154]=Bt):Bt=e[154];let Lt;e[155]!==St||e[156]!==et||e[157]!==xt||e[158]!==rs||e[159]!==Bt?(Lt=s.jsxs("div",{className:"min-w-0 space-y-2",children:[St,et,xt,rs,Bt]}),e[155]=St,e[156]=et,e[157]=xt,e[158]=rs,e[159]=Bt,e[160]=Lt):Lt=e[160];let Vt;e[161]!==he||e[162]!==P||e[163]!==p?(Vt=he&&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:P??"#000000",onChange:Qe=>T(Qe.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:P??"",onChange:Qe=>T(Qe.target.value),placeholder:"#000000",className:"h-8 w-[8.5rem]"}),s.jsx($e,{size:"sm",variant:"outline",onClick:()=>T(null),children:p("projectEditDialog.actions.clear")})]})]}),e[161]=he,e[162]=P,e[163]=p,e[164]=Vt):Vt=e[164];let Kt;e[165]!==Oe||e[166]!==kt||e[167]!==Lt||e[168]!==Vt?(Kt=s.jsxs("div",{className:"min-w-0 space-y-5 py-1",children:[Oe,kt,Lt,Vt]}),e[165]=Oe,e[166]=kt,e[167]=Lt,e[168]=Vt,e[169]=Kt):Kt=e[169];let Xt;e[170]!==r?(Xt=()=>r(!1),e[170]=r,e[171]=Xt):Xt=e[171];let Qt;e[172]!==p?(Qt=p("projectEditDialog.actions.cancel"),e[172]=p,e[173]=Qt):Qt=e[173];let vs;e[174]!==Xt||e[175]!==Qt?(vs=s.jsx($e,{variant:"ghost",onClick:Xt,children:Qt}),e[174]=Xt,e[175]=Qt,e[176]=vs):vs=e[176];let Dt;e[177]!==B||e[178]!==L||e[179]!==j?(Dt=!j.trim()||L||B,e[177]=B,e[178]=L,e[179]=j,e[180]=Dt):Dt=e[180];let $t;e[181]!==p?($t=p("projectEditDialog.actions.save"),e[181]=p,e[182]=$t):$t=e[182];let Ct;e[183]!==De||e[184]!==Dt||e[185]!==$t?(Ct=s.jsx($e,{onClick:De,disabled:Dt,children:$t}),e[183]=De,e[184]=Dt,e[185]=$t,e[186]=Ct):Ct=e[186];let ds;e[187]!==vs||e[188]!==Ct?(ds=s.jsxs(ir,{children:[vs,Ct]}),e[187]=vs,e[188]=Ct,e[189]=ds):ds=e[189];let qe;e[190]!==K||e[191]!==Kt||e[192]!==ds?(qe=s.jsxs(_s,{className:"max-w-md",children:[K,Kt,ds]}),e[190]=K,e[191]=Kt,e[192]=ds,e[193]=qe):qe=e[193];let at;return e[194]!==r||e[195]!==n||e[196]!==qe?(at=s.jsx($s,{open:n,onOpenChange:r,children:qe}),e[194]=r,e[195]=n,e[196]=qe,e[197]=at):at=e[197],at};function sN(t){return t.uploadProjectIcon}function nN(t){return t.removeProjectIcon}function rN(t){return t.discoverProjectIcon}function iN(t){return t&&URL.revokeObjectURL(t),null}const oN=t=>{const e=mt.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:b,alwaysShowActions:p,isRenaming:x,renameDraft:y,onRenameDraftChange:h,onRenameSave:C,onRenameCancel:w,droppableRef:S,isDropTarget:j,onNewSession:k,onNewSubFolder:v,depth:A,hideActions:I,archivedBucket:N}=t,P=p===void 0?b===void 0?!1:b:p,T=x===void 0?!1:x,L=y===void 0?"":y,R=j===void 0?!1:j,B=A===void 0?0:A,V=I===void 0?!1:I,_=N===void 0?!1:N,{t:E}=Nt(),[Z,ne]=i.useState(!1),[Y,H]=i.useState(""),re=i.useRef(null),ae=T||Z,me=T?L:Y;let Se;e[0]!==n.name?(Se=()=>{H(n.name),ne(!0)},e[0]=n.name,e[1]=Se):Se=e[1];const te=Se;let ke;e[2]!==me||e[3]!==n.name||e[4]!==T||e[5]!==l||e[6]!==C?(ke=()=>{const M=me.trim();M&&M!==n.name&&l(M),T&&C&&C(),ne(!1),H("")},e[2]=me,e[3]=n.name,e[4]=T,e[5]=l,e[6]=C,e[7]=ke):ke=e[7];const Q=ke;let ge;e[8]!==T||e[9]!==w?(ge=()=>{T&&w&&w(),ne(!1),H("")},e[8]=T,e[9]=w,e[10]=ge):ge=e[10];const F=ge;let se;e[11]!==T||e[12]!==h?(se=M=>{T&&h?h(M):H(M)},e[11]=T,e[12]=h,e[13]=se):se=e[13];const ee=se;let Ne,De;e[14]!==T?(Ne=()=>{if(!T)return;const M=()=>{const Oe=re.current;Oe&&(Oe.focus(),Oe.select())},le=requestAnimationFrame(M),ie=window.setTimeout(M,0);return()=>{cancelAnimationFrame(le),window.clearTimeout(ie)}},De=[T],e[14]=T,e[15]=Ne,e[16]=De):(Ne=e[15],De=e[16]),i.useEffect(Ne,De);const Be=a?"folder":"folder-open",Me=B>0&&"ml-3";let he;e[17]!==Me?(he=Pe("oc-folder",Me),e[17]=Me,e[18]=he):he=e[18];const Ae=R&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let pe;e[19]!==Ae?(pe=Pe("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",Ae),e[19]=Ae,e[20]=pe):pe=e[20];const ue=ae?void 0:c,U=ae?void 0:"button",fe=ae?void 0:0;let de;e[21]!==c||e[22]!==ae?(de=ae?void 0:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c())},e[21]=c,e[22]=ae,e[23]=de):de=e[23];let G;e[24]!==n.name||e[25]!==a||e[26]!==E?(G=a?E("sessions.sidebar.folderItem.expandAria",{folderName:n.name}):E("sessions.sidebar.folderItem.collapseAria",{folderName:n.name}),e[24]=n.name,e[25]=a,e[26]=E,e[27]=G):G=e[27];const $=_?P?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let ve;e[28]!==$?(ve=Pe("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",$),e[28]=$,e[29]=ve):ve=e[29];const be=R?"text-primary":"text-muted-foreground";let z;e[30]!==be?(z=Pe("h-3.5 w-3.5 flex-shrink-0",be),e[30]=be,e[31]=z):z=e[31];let xe;e[32]!==Be||e[33]!==z?(xe=s.jsx(D,{name:Be,className:z}),e[32]=Be,e[33]=z,e[34]=xe):xe=e[34];let je;e[35]!==me||e[36]!==n.name||e[37]!==F||e[38]!==ee||e[39]!==Q||e[40]!==a||e[41]!==R||e[42]!==ae||e[43]!==r||e[44]!==E?(je=ae?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:lN,onMouseDown:cN,onSubmit:M=>{M.preventDefault(),Q()},children:[s.jsx("input",{ref:re,value:me,onChange:M=>ee(M.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.folderItem.namePlaceholder"),onClick:dN,onPointerDown:uN,onMouseDown:fN,onKeyDown:M=>{if(M.key==="Escape"){M.stopPropagation(),F();return}(M.key===" "||M.key==="Enter")&&M.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:mN,onPointerDown:hN,onMouseDown:pN,children:s.jsx(D,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),F()},onPointerDown:gN,onMouseDown:xN,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:Pe("typography-ui-label font-semibold truncate",R?"text-primary":"text-muted-foreground"),children:n.name}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",r.length]}),a?s.jsx(D,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[35]=me,e[36]=n.name,e[37]=F,e[38]=ee,e[39]=Q,e[40]=a,e[41]=R,e[42]=ae,e[43]=r,e[44]=E,e[45]=je):je=e[45];let K;e[46]!==ve||e[47]!==xe||e[48]!==je?(K=s.jsxs("div",{className:ve,children:[xe,je]}),e[46]=ve,e[47]=xe,e[48]=je,e[49]=K):K=e[49];let ye;e[50]!==P||e[51]!==_||e[52]!==B||e[53]!==n.name||e[54]!==te||e[55]!==V||e[56]!==d||e[57]!==k||e[58]!==v||e[59]!==ae||e[60]!==E?(ye=!ae&&(!V||_)?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:Pe("flex items-center gap-0.5 transition-opacity",P?"opacity-100":"opacity-0 group-hover/folder:opacity-100 group-focus-within/folder:opacity-100",_&&"absolute right-0.5 top-1/2 z-10 -translate-y-1/2 px-0"),children:[!_&&k?s.jsx("button",{type:"button",onClick:M=>{M.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":E("sessions.sidebar.folderItem.newSessionAria",{folderName:n.name}),title:E("sessions.sidebar.project.actions.newSession"),children:s.jsx(D,{name:"add",className:"h-3.5 w-3.5"})}):null,!_&&v&&B===0?s.jsx("button",{type:"button",onClick:M=>{M.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":E("sessions.sidebar.folderItem.newSubfolderAria",{folderName:n.name}),title:E("sessions.sidebar.folderItem.newSubfolder"),children:s.jsx(D,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,_?null:s.jsx("button",{type:"button",onClick:M=>{M.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":E("sessions.sidebar.folderItem.renameAria",{folderName:n.name}),children:s.jsx(D,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:M=>{M.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":_?E("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):E("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=P,e[51]=_,e[52]=B,e[53]=n.name,e[54]=te,e[55]=V,e[56]=d,e[57]=k,e[58]=v,e[59]=ae,e[60]=E,e[61]=ye):ye=e[61];let Le;e[62]!==S||e[63]!==pe||e[64]!==ue||e[65]!==U||e[66]!==fe||e[67]!==de||e[68]!==G||e[69]!==K||e[70]!==ye?(Le=s.jsxs("div",{ref:S,className:pe,onClick:ue,role:U,tabIndex:fe,onKeyDown:de,"aria-label":G,children:[K,ye]}),e[62]=S,e[63]=pe,e[64]=ue,e[65]=U,e[66]=fe,e[67]=de,e[68]=G,e[69]=K,e[70]=ye,e[71]=Le):Le=e[71];let Re;e[72]!==_||e[73]!==m||e[74]!==f||e[75]!==a||e[76]!==g||e[77]!==u||e[78]!==r||e[79]!==o||e[80]!==E?(Re=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(M=>u(M,0,f??null,g??null,_,void 0,"project",m?.(M))):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:E("sessions.sidebar.folderItem.emptyFolder")})]}),e[72]=_,e[73]=m,e[74]=f,e[75]=a,e[76]=g,e[77]=u,e[78]=r,e[79]=o,e[80]=E,e[81]=Re):Re=e[81];let X;return e[82]!==he||e[83]!==Le||e[84]!==Re?(X=s.jsxs("div",{className:he,children:[Le,Re]}),e[82]=he,e[83]=Le,e[84]=Re,e[85]=X):X=e[85],X},aN=i.memo(oN);function lN(t){return t.stopPropagation()}function cN(t){return t.stopPropagation()}function dN(t){return t.stopPropagation()}function uN(t){return t.stopPropagation()}function fN(t){return t.stopPropagation()}function mN(t){return t.stopPropagation()}function hN(t){return t.stopPropagation()}function pN(t){return t.stopPropagation()}function gN(t){return t.stopPropagation()}function xN(t){return t.stopPropagation()}const bN=t=>{const e=mt.c(15),{sessionId:n,sessionDirectory:r,sessionTitle:o,children:a}=t,c=`session-drag:${n}`;let l;e[0]!==r||e[1]!==n||e[2]!==o?(l={type:"session",sessionId:n,sessionDirectory:r,sessionTitle:o},e[0]=r,e[1]=n,e[2]=o,e[3]=l):l=e[3];let d;e[4]!==c||e[5]!==l?(d={id:c,data:l},e[4]=c,e[5]=l,e[6]=d):d=e[6];const{attributes:u,listeners:m,setNodeRef:f,isDragging:g}=Hh(d);let b;e[7]!==m?(b=h=>{h.stopPropagation(),m?.onPointerDown&&m.onPointerDown(h)},e[7]=m,e[8]=b):b=e[8];const p=b,x=g?"opacity-30":void 0;let y;return e[9]!==u||e[10]!==a||e[11]!==p||e[12]!==f||e[13]!==x?(y=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]=y):y=e[14],y},yN=t=>{const e=mt.c(11),{folderId:n,children:r}=t,o=`folder-drop:${n}`;let a;e[0]!==n?(a={type:"folder",folderId:n},e[0]=n,e[1]=a):a=e[1];let c;e[2]!==o||e[3]!==a?(c={id:o,data:a},e[2]=o,e[3]=a,e[4]=c):c=e[4];const{setNodeRef:l,isOver:d}=Uh(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},wN=t=>{const e=mt.c(20),{scopeKey:n,hasFolders:r,onSessionDroppedOnFolder:o,children:a}=t;let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c={activationConstraint:{distance:8}},e[0]=c):c=e[0];const l=ga(yo(xa,c)),[d,u]=i.useState(null),[m,f]=i.useState("Session"),[g,b]=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 y;e[3]!==o?(y=v=>{u(null),b(null),x(null);const{active:A,over:I}=v;if(!I)return;const N=A.data.current,O=I.data.current;N?.type==="session"&&N.sessionId&&O?.type==="folder"&&O.folderId&&o(N.sessionId,O.folderId)},e[3]=o,e[4]=y):y=e[4];const h=y;let C,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(C=v=>{const A=v.active.data.current;if(A?.type==="session"&&A.sessionId){u(A.sessionId),f(A.sessionTitle??"Session");const I=v.active.rect.current.initial?.width,N=v.active.rect.current.initial?.height;b(typeof I=="number"?I:null),x(typeof N=="number"?N:null)}},w=()=>{u(null),b(null),x(null)},e[5]=C,e[6]=w):(C=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(D,{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($l,{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:C,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},Hi=(t,e,n)=>{if(!e)return;const r=o=>{let a=o.session.id===e;for(const c of o.children)a=r(c)||a;return a&&n.add(o.session.id),a};for(const o of t)r(o)},zr=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if(zr(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=ro()(cc(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}})),vN=50,jN=30,Tl=28,_i=(t,e)=>e?t.sessions.some(n=>zr(n,e)):!1,SN=(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)},NN=(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)},kN=(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)},CN=(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)},cf=t=>{if(t.projectId)return t.projectRepoStatus.has(t.projectId)?t.projectRepoStatus.get(t.projectId):void 0},AN=(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&&cf(t)!==cf(e)||t.pinnedSessionIds!==e.pinnedSessionIds&&SN(e.group,t.pinnedSessionIds,e.pinnedSessionIds)||t.expandedParents!==e.expandedParents&&kN(e.group,t.expandedParents,e.expandedParents)||t.sessionOrderIndex!==e.sessionOrderIndex&&NN(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&&CN(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 DN(t){const{t:e}=Nt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:u,collapsedGroups:m,hideDirectoryControls:f,collapsedFolderIds:g,toggleFolderCollapse:b,renameFolder:p,deleteFolder:x,showDeletionDialog:y,setDeleteFolderConfirm:h,renderSessionNode:C,projectRepoStatus:w,lastRepoStatus:S,showMoreGroupSessions:j,resetGroupSessionLimit:k,mobileVariant:v,alwaysShowActions:A,activeProjectId:I,setActiveProjectIdOnly:N,setActiveMainTab:O,setSessionSwitcherOpen:P,openNewSessionDraft:T,addSessionToFolder:L,createFolderAndStartRename:R,renamingFolderId:B,renameFolderDraft:V,setRenameFolderDraft:_,setRenamingFolderId:E,pinnedSessionIds:Z,expandedParents:ne,sessionOrderIndex:Y,currentSessionId:H,editingId:re,openSidebarMenuKey:ae,prVisualStateByDirectoryBranch:me,onToggleCollapsedGroup:Se,dragHandleProps:te,compactBodyPadding:ke=!1,scrollContainerRef:Q}=t,ge=i.useCallback((qe,at)=>{const Qe=Y.get(qe.session.id),At=Y.get(at.session.id);if(Qe!==void 0||At!==void 0){if(Qe===void 0)return 1;if(At===void 0)return-1;if(Qe!==At)return Qe-At}return Gi(qe.session,at.session,Z)},[Z,Y]),F=c?d.get(n):null,se=Dr(qe=>qe.displayMode),ee=Ln(qe=>qe.foldersMap),Ne=se==="minimal"&&!Gr(),De=c?!1:m.has(r),Be=f?10:5,Fe=Math.max(Be,u??Be),Me=c?F?.groupMatches===!0:!1,he=c,Ae=i.useMemo(()=>[...he?F?.filteredNodes??[]:n.sessions].sort(ge),[ge,n.sessions,F?.filteredNodes,he]),pe=n.folderScopeKey??cs(n.directory??null),ue=i.useMemo(()=>pe?ee[pe]??[]:[],[pe,ee]),U=i.useMemo(()=>{const qe=new Map,at=Qe=>{Qe.forEach(At=>{qe.set(At.session.id,At),At.children.length>0&&at(At.children)})};return at(Ae),qe},[Ae]),fe=i.useMemo(()=>ue.map(qe=>{const at=qe.sessionIds.map(Qe=>U.get(Qe)).filter(Qe=>!!Qe).sort(ge);return{folder:qe,nodes:at}}),[ue,U,ge]),de=i.useMemo(()=>{const qe=new Map(fe.map(Tt=>[Tt.folder.id,Tt])),at=new Map;for(const{folder:Tt}of fe){if(!Tt.parentId)continue;const ts=at.get(Tt.parentId);ts?ts.push(Tt.id):at.set(Tt.parentId,[Tt.id])}const Qe=new Map,At=Tt=>{const ts=Qe.get(Tt);if(ts!==void 0)return ts;const xs=qe.get(Tt);if(!xs)return Qe.set(Tt,!1),!1;const ks=at.get(Tt)??[];if(n.isArchivedBucket&&xs.nodes.length===0){const Ps=ks.some(Ts=>At(Ts));return Qe.set(Tt,Ps),Ps}if(!c||xs.folder.name.toLowerCase().includes(l)||xs.nodes.length>0)return Qe.set(Tt,!0),!0;const ls=ks.some(Ps=>At(Ps));return Qe.set(Tt,ls),ls};return fe.filter(({folder:Tt})=>At(Tt.id))},[fe,n.isArchivedBucket,c,l]),G=i.useMemo(()=>new Set(de.flatMap(qe=>qe.folder.sessionIds)),[de]),$=i.useMemo(()=>Ae.filter(qe=>!G.has(qe.session.id)),[Ae,G]),ve=i.useMemo(()=>de.filter(({folder:qe})=>!qe.parentId),[de]),be="project",z=i.useMemo(()=>{const qe=new Set;return Hi(Ae,H,qe),de.forEach(({nodes:at})=>{Hi(at,H,qe)}),qe},[Ae,de,H]),xe=i.useMemo(()=>{const qe=new Set;return Hi(Ae,re,qe),de.forEach(({nodes:at})=>{Hi(at,re,qe)}),qe},[Ae,de,re]),je=i.useMemo(()=>{if(!ae)return null;const qe=Fo(Ae,ae,be,!!n.isArchivedBucket);if(qe)return qe;for(const{nodes:at}of de){const Qe=Fo(at,ae,be,!!n.isArchivedBucket);if(Qe)return Qe}return null},[ae,Ae,de,n.isArchivedBucket]),K=i.useCallback(qe=>{const at=new WeakMap,Qe=At=>{at.set(At,Ra(At));for(const Tt of At.children)Qe(Tt)};return qe.forEach(Qe),at},[]),ye=i.useMemo(()=>K(Ae),[K,Ae]),Le=i.useMemo(()=>{const qe=new WeakMap;return de.forEach(({nodes:at})=>{at.forEach(Qe=>qe.set(Qe,Ra(Qe)))}),qe},[de]),Re=i.useCallback(qe=>ye.get(qe)??Le.get(qe)??"",[ye,Le]),X=i.useCallback(qe=>({subtreeContainsActive:z,subtreeContainsEditing:xe,menuOpenSessionId:je,nodeStructureKey:Re(qe)}),[z,xe,je,Re]),M=$.length,le=n.isArchivedBucket||c?$:$.slice(0,Fe),ie=M-le.length,Oe=!n.isArchivedBucket&&!c&&M>Be&&ie===0,Ge=n.isArchivedBucket===!0&&!c&&le.length>=vN,He=n.isArchivedBucket!==!0&&!c&&le.length>=jN,Je=Ge||He,rt=n.isArchivedBucket?"archived":"active",bt=Je&&le.some(qe=>{if(qe.children.length===0)return!1;const at=`project:${rt}:${qe.session.id}`;return ne.has(at)}),yt=i.useRef(null),_e=i.useRef(null),[Ye,nt]=i.useState(null),[wt,kt]=i.useState(0),[,vt]=i.useState(0);i.useEffect(()=>{if(!Je)return;const qe=yt.current;if(!qe||typeof ResizeObserver>"u")return;const at=new ResizeObserver(()=>vt(Qe=>Qe+1));return at.observe(qe),()=>at.disconnect()},[Je]),i.useLayoutEffect(()=>{if(!Je){Ye!==null&&nt(null),_e.current=null,wt!==0&&kt(0);return}const qe=yt.current;if(!qe)return;let at=Ye;const Qe=Q?.current??null;if(Qe&&Qe.contains(qe)){if(at=Qe,at!==Ye){_e.current=at,nt(at);return}}else if(!at||!at.contains(qe)){let Tt=qe.parentElement;for(;Tt;){const ts=window.getComputedStyle(Tt);if(ts.overflowY==="auto"||ts.overflowY==="scroll"){at=Tt;break}Tt=Tt.parentElement}if(at!==Ye){_e.current=at,nt(at);return}}if(!at)return;const At=qe.getBoundingClientRect().top-at.getBoundingClientRect().top+at.scrollTop;kt(Tt=>Math.abs(Tt-At)<1?Tt:At)});const St=i.useCallback(qe=>{const at=[],Qe=At=>{At.forEach(Tt=>{at.push(Tt.session),Tt.children.length>0&&Qe(Tt.children)})};return Qe(qe),at},[]),et=i.useMemo(()=>n.isArchivedBucket?St(Ae):[],[St,Ae,n.isArchivedBucket]),Ot=i.useMemo(()=>{if(!n.isArchivedBucket)return new Map;const qe=new Map,at=new Map;for(const{folder:At}of de){if(!At.parentId)continue;const Tt=at.get(At.parentId)??[];Tt.push(At.id),at.set(At.parentId,Tt)}const Qe=(At,Tt)=>{if(Tt.has(At))return[];Tt.add(At);const ts=de.find(({folder:Jt})=>Jt.id===At),xs=ts?St(ts.nodes):[],ks=at.get(At)??[];for(const Jt of ks)xs.push(...Qe(Jt,Tt));return xs};for(const{folder:At}of de)qe.set(At.id,Qe(At.id,new Set));return qe},[de,St,n.isArchivedBucket]);if(c&&!Me&&ve.length===0&&$.length===0)return null;const ns=o&&w.has(o)?!!w.get(o):S,Wt=cs(n.directory??null),Ve=n.branch?.trim()??null,Ze=Wt&&Ve?me.get(`${Wt}::${Ve}`)??null:null,_t=!!(Ze&&n.branch),jt=!Ze&&!n.isMain&&!!n.branch,xt=Ze?.visualState??null,rs=Ze&&Ze.state==="open"&&Ze.checks?e("sessions.sidebar.group.pr.checksPassed",{success:Ze.checks.success,total:Ze.checks.total}):null,Gt=Ze&&Ze.state==="open"&&Ze.checks?[Ze.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:Ze.checks.failure}):null,Ze.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:Ze.checks.pending}):null].filter(qe=>!!qe).join(", "):null,Ut=Ze&&Ze.state==="open"?Ze.mergeableState==="blocked"||Ze.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):Ze.mergeableState==="clean"||Ze.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,as=Ze&&Ze.state==="open"&&Ze.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:Ze.mergeableState}):null,Bt=Ze?.base??null,Lt=Ze?.head??null,Vt=(()=>{if(!Ze)return n.branch&&lb(n.branch,n.label)?{label:n.branch,color:null}:null;switch(Ze.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return Ze.canMerge===!0||Ze.mergeableState==="clean"||Ze.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:Ze.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}})(),Kt=Vt?.color??(xt?`var(--pr-${xt})`:void 0),Xt=qe=>{qe.preventDefault(),qe.stopPropagation();const at=Ze?.url;at&&Ii(at)},Qt=(qe,at,Qe)=>{const At=de.filter(({folder:xs})=>xs.parentId===qe.id),Tt=At.length>0?s.jsx(s.Fragment,{children:At.map(({folder:xs,nodes:ks})=>Qt(xs,ks,Qe+1))}):void 0,ts=Ot.get(qe.id)??[];return s.jsx(yN,{folderId:qe.id,children:(xs,ks)=>s.jsx(aN,{folder:qe,sessions:at,subFolderItems:Tt,isCollapsed:c?!1:g.has(qe.id),onToggle:()=>b(qe.id),onRename:Jt=>{pe&&p(pe,qe.id,Jt)},onDelete:()=>{if(n.isArchivedBucket){Pr.requestDelete({sessions:ts,mode:"session"});return}if(!pe)return;if(!y){x(pe,qe.id);return}const Jt=de.filter(({folder:Ps})=>Ps.parentId===qe.id).length,ls=at.length;h({scopeKey:pe,folderId:qe.id,folderName:qe.name,subFolderCount:Jt,sessionCount:ls})},renderSessionNode:C,getRenderExtras:Re?Jt=>({subtreeContainsActive:z,subtreeContainsEditing:xe,menuOpenSessionId:je,nodeStructureKey:Re(Jt),childRenderExtrasFor:X}):void 0,groupDirectory:n.directory,projectId:o,mobileVariant:v,alwaysShowActions:A,isRenaming:B===qe.id,renameDraft:B===qe.id?V:void 0,onRenameDraftChange:Jt=>_(Jt),onRenameSave:()=>{const Jt=V.trim();Jt&&pe&&p(pe,qe.id,Jt),E(null),_("")},onRenameCancel:()=>{E(null),_("")},droppableRef:xs,isDropTarget:ks,depth:Qe,onNewSession:()=>{o&&o!==I&&N(o),O("chat"),v&&P(!1),T({directoryOverride:n.directory,targetFolderId:qe.id})},onNewSubFolder:Qe===0?()=>{pe&&R(pe,qe.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},qe.id)},vs=()=>ve.map(({folder:qe,nodes:at})=>Qt(qe,at,0)),Dt=!!(!n.isMain&&n.worktree),$t=A?Dt?"pr-14":"pr-7":Ne?Dt?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":Dt?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",Ct=s.jsxs(wN,{scopeKey:pe,hasFolders:de.length>0,onSessionDroppedOnFolder:(qe,at)=>{pe&&L(pe,at,qe)},children:[vs(),Je?s.jsx("div",{ref:yt,children:s.jsx(Gh,{data:le,itemSize:Tl,bufferSize:bt?Tl*20:Tl*8,scrollRef:_e,startMargin:wt,children:qe=>C(qe,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:z,subtreeContainsEditing:xe,menuOpenSessionId:je,nodeStructureKey:Re(qe),childRenderExtrasFor:X})})}):le.map(qe=>C(qe,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:z,subtreeContainsEditing:xe,menuOpenSessionId:je,nodeStructureKey:Re(qe),childRenderExtrasFor:X})),M===0&&de.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,ie>0?s.jsx("button",{type:"button",onClick:()=>j(r,le.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showMore")}):null,Oe?s.jsx("button",{type:"button",onClick:()=>k(r),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showFewer")}):null]}),ds=ke?"pb-2 pl-1":"pb-3 pl-4";return a?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:Pe("oc-group-body",ds),children:Ct})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:Pe("group/gh relative flex items-start justify-between gap-1 py-1 min-w-0 rounded-md","cursor-pointer"),onClick:()=>Se(r),role:"button",tabIndex:0,onKeyDown:qe=>{(qe.key==="Enter"||qe.key===" ")&&(qe.preventDefault(),Se(r))},"aria-label":De?e("sessions.sidebar.group.expandAria",{label:n.label}):e("sessions.sidebar.group.collapseAria",{label:n.label}),"aria-expanded":!De,children:[s.jsx("div",{ref:te?.setActivatorNodeRef,className:Pe("min-w-0 flex flex-1 items-start gap-1 overflow-hidden pl-0.5 transition-[padding] cursor-grab active:cursor-grabbing",$t),...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:_t&&Ze?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 leading-none align-middle",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(D,{name:"git-branch",className:Pe("h-3.5 w-3.5 shrink-0",A?"hidden":"group-hover/gh:hidden"),style:Kt?{color:Kt}:void 0}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(D,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),Ze.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:qe=>qe.stopPropagation(),onClick:Xt,children:["#",Ze.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",Ze.number]})]})}),s.jsx(Ft,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Bt||Lt?s.jsx("div",{className:"text-muted-foreground truncate",children:Bt&&Lt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Bt}),s.jsx(D,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Lt})]}):s.jsx("span",{children:Bt??Lt??""})}):null,as?s.jsx("div",{className:"text-muted-foreground truncate",children:as}):null,Ut||rs?s.jsxs("div",{className:"text-muted-foreground truncate",children:[Ut??"",Ut&&rs?" • ":"",rs??"",Gt?` (${Gt})`:""]}):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(D,{name:"archive",className:Pe("h-3.5 w-3.5 shrink-0 text-muted-foreground",A?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(D,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(D,{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(D,{name:"git-branch",className:Pe("h-3.5 w-3.5 shrink-0 text-muted-foreground",A?"hidden":"group-hover/gh:hidden"),style:Kt?{color:Kt}:void 0}),s.jsx("span",{className:Pe("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(D,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(D,{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)}),jt&&Vt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(D,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||ns?_t&&Ze?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:s.jsx(D,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:Kt?{color:Kt}:void 0})})}),s.jsx(Ft,{side:"top",sideOffset:6,align:"start",className:"max-w-sm",children:s.jsxs("div",{className:"space-y-1 text-xs",children:[Bt||Lt?s.jsx("div",{className:"text-muted-foreground truncate",children:Bt&&Lt?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Bt}),s.jsx(D,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Lt})]}):s.jsx("span",{children:Bt??Lt??""})}):null,as?s.jsx("div",{className:"text-muted-foreground truncate",children:as}):null,Ut||rs?s.jsxs("div",{className:"text-muted-foreground truncate",children:[Ut??"",Ut&&rs?" • ":"",rs??"",Gt?` (${Gt})`:""]}):null]})})]}):s.jsx(D,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:Kt?{color:Kt}:void 0}):null,s.jsx("span",{className:Pe("min-w-0 truncate text-[11px] font-medium",!Vt.color&&"text-muted-foreground/80"),style:Vt.color?{color:Vt.color}:void 0,children:Vt.label})]}):null]})}),n.isArchivedBucket&&et.length>0?s.jsx("div",{className:Pe("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",A?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:qe=>{qe.stopPropagation(),Pr.requestDelete({sessions:et,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(D,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteArchivedSessions")})})]})}):null,n.directory&&!n.isMain&&n.worktree?s.jsx("div",{className:Pe("absolute right-7 top-1/2 -translate-y-1/2 z-10 transition-opacity",A?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:qe=>{qe.stopPropagation(),Pr.requestDelete({sessions:et,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(D,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteWorktree")})})]})}):null,n.directory?s.jsx("div",{className:Pe("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",A?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:qe=>{qe.stopPropagation(),o&&o!==I&&N(o),O("chat"),v&&P(!1),T({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(D,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),De?null:s.jsx("div",{className:Pe("oc-group-body",ds),children:Ct})]})}const IN=i.memo(DN,AN);function PN(t){const e=mt.c(182),{t:n}=Nt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:u,headerActionButtonClass:m,isSessionSearchOpen:f,setIsSessionSearchOpen:g,sessionSearchInputRef:b,sessionSearchQuery:p,setSessionSearchQuery:x,hasSessionSearchQuery:y,searchMatchCount:h,collapseAllProjects:C,expandAllProjects:w,openScheduledTasksDialog:S,selectionModeEnabled:j,onToggleSelectionMode:k}=t,v=Dr(ON),A=Dr(LN),I=Dr(FN),N=Dr(MN),O=Dr(EN),P=Dr(RN);let T;e[0]===Symbol.for("react.memo_cache_sentinel")?(T=Gr(),e[0]=T):T=e[0];const L=!T;if(r)return null;let R;e[1]!==n?(R=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=R):R=e[2];let B;e[3]!==u?(B=s.jsx(D,{name:"folder-add",className:u}),e[3]=u,e[4]=B):B=e[4];let V;e[5]!==a||e[6]!==m||e[7]!==R||e[8]!==B?(V=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:m,"aria-label":R,children:B})}),e[5]=a,e[6]=m,e[7]=R,e[8]=B,e[9]=V):V=e[9];let _;e[10]!==n?(_=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=_):_=e[11];let E;e[12]!==_?(E=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:_})}),e[12]=_,e[13]=E):E=e[13];let Z;e[14]!==V||e[15]!==E?(Z=s.jsxs(Et,{children:[V,E]}),e[14]=V,e[15]=E,e[16]=Z):Z=e[16];let ne;e[17]!==n?(ne=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=ne):ne=e[18];let Y;e[19]!==u?(Y=s.jsx(D,{name:"chat-new",className:u}),e[19]=u,e[20]=Y):Y=e[20];let H;e[21]!==m||e[22]!==c||e[23]!==ne||e[24]!==Y?(H=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:m,"aria-label":ne,children:Y})}),e[21]=m,e[22]=c,e[23]=ne,e[24]=Y,e[25]=H):H=e[25];let re;e[26]!==n?(re=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=re):re=e[27];let ae;e[28]!==re?(ae=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:re})}),e[28]=re,e[29]=ae):ae=e[29];let me;e[30]!==ae||e[31]!==H?(me=s.jsxs(Et,{children:[H,ae]}),e[30]=ae,e[31]=H,e[32]=me):me=e[32];let Se;e[33]!==n?(Se=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=Se):Se=e[34];const te=!l;let ke;e[35]!==u?(ke=s.jsx(kg,{className:u}),e[35]=u,e[36]=ke):ke=e[36];let Q;e[37]!==m||e[38]!==d||e[39]!==Se||e[40]!==te||e[41]!==ke?(Q=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:m,"aria-label":Se,disabled:te,children:ke})}),e[37]=m,e[38]=d,e[39]=Se,e[40]=te,e[41]=ke,e[42]=Q):Q=e[42];let ge;e[43]!==n?(ge=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=ge):ge=e[44];let F;e[45]!==ge?(F=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ge})}),e[45]=ge,e[46]=F):F=e[46];let se;e[47]!==Q||e[48]!==F?(se=s.jsxs(Et,{children:[Q,F]}),e[47]=Q,e[48]=F,e[49]=se):se=e[49];let ee;e[50]!==n?(ee=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=ee):ee=e[51];let Ne;e[52]!==u?(Ne=s.jsx(D,{name:"calendar-schedule",className:u}),e[52]=u,e[53]=Ne):Ne=e[53];let De;e[54]!==m||e[55]!==S||e[56]!==ee||e[57]!==Ne?(De=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:m,"aria-label":ee,children:Ne})}),e[54]=m,e[55]=S,e[56]=ee,e[57]=Ne,e[58]=De):De=e[58];let Be;e[59]!==n?(Be=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=Be):Be=e[60];let Fe;e[61]!==Be?(Fe=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Be})}),e[61]=Be,e[62]=Fe):Fe=e[62];let Me;e[63]!==De||e[64]!==Fe?(Me=s.jsxs(Et,{children:[De,Fe]}),e[63]=De,e[64]=Fe,e[65]=Me):Me=e[65];let he;e[66]!==me||e[67]!==se||e[68]!==Me||e[69]!==Z?(he=s.jsxs("div",{className:"flex items-center gap-1.5",children:[Z,me,se,Me]}),e[66]=me,e[67]=se,e[68]=Me,e[69]=Z,e[70]=he):he=e[70];let Ae;e[71]!==g?(Ae=()=>g(TN),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(D,{name:"search",className:u}),e[75]=u,e[76]=ue):ue=e[76];let U;e[77]!==m||e[78]!==f||e[79]!==Ae||e[80]!==pe||e[81]!==ue?(U=s.jsx(Mt,{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]=U):U=e[82];let fe;e[83]!==n?(fe=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=fe):fe=e[84];let de;e[85]!==fe?(de=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:fe})}),e[85]=fe,e[86]=de):de=e[86];let G;e[87]!==U||e[88]!==de?(G=s.jsxs(Et,{children:[U,de]}),e[87]=U,e[88]=de,e[89]=G):G=e[89];const $=j&&"bg-interactive-hover text-primary";let ve;e[90]!==m||e[91]!==$?(ve=Pe(m,$),e[90]=m,e[91]=$,e[92]=ve):ve=e[92];let be;e[93]!==j||e[94]!==n?(be=n(j?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=j,e[94]=n,e[95]=be):be=e[95];let z;e[96]!==u?(z=s.jsx(D,{name:"checkbox-multiple",className:u}),e[96]=u,e[97]=z):z=e[97];let xe;e[98]!==k||e[99]!==j||e[100]!==ve||e[101]!==be||e[102]!==z?(xe=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:ve,"aria-label":be,"aria-pressed":j,children:z})}),e[98]=k,e[99]=j,e[100]=ve,e[101]=be,e[102]=z,e[103]=xe):xe=e[103];let je;e[104]!==j||e[105]!==n?(je=n(j?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=j,e[105]=n,e[106]=je):je=e[106];let K;e[107]!==je?(K=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:je})}),e[107]=je,e[108]=K):K=e[108];let ye;e[109]!==xe||e[110]!==K?(ye=s.jsxs(Et,{children:[xe,K]}),e[109]=xe,e[110]=K,e[111]=ye):ye=e[111];let Le;e[112]!==n?(Le=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[112]=n,e[113]=Le):Le=e[113];let Re;e[114]!==u?(Re=s.jsx(D,{name:"equalizer-2",className:u}),e[114]=u,e[115]=Re):Re=e[115];let X;e[116]!==m||e[117]!==Le||e[118]!==Re?(X=s.jsx(Mt,{asChild:!0,children:s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":Le,children:Re})})}),e[116]=m,e[117]=Le,e[118]=Re,e[119]=X):X=e[119];let M;e[120]!==n?(M=n("sessions.sidebar.header.displayMode.label"),e[120]=n,e[121]=M):M=e[121];let le;e[122]!==M?(le=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:M})}),e[122]=M,e[123]=le):le=e[123];let ie;e[124]!==X||e[125]!==le?(ie=s.jsxs(Et,{children:[X,le]}),e[124]=X,e[125]=le,e[126]=ie):ie=e[126];let Oe;e[127]!==v||e[128]!==N||e[129]!==n?(Oe=L?s.jsxs(s.Fragment,{children:[s.jsxs(bs,{onClick:()=>N("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),v==="default"?s.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(bs,{onClick:()=>N("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),v==="minimal"?s.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[127]=v,e[128]=N,e[129]=n,e[130]=Oe):Oe=e[130];let Ge;e[131]!==I||e[132]!==o||e[133]!==A||e[134]!==n||e[135]!==P||e[136]!==O?(Ge=o?s.jsxs(s.Fragment,{children:[L?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")}),A?s.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(bs,{onClick:P,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),I?s.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[131]=I,e[132]=o,e[133]=A,e[134]=n,e[135]=P,e[136]=O,e[137]=Ge):Ge=e[137];let He;e[138]===Symbol.for("react.memo_cache_sentinel")?(He=s.jsx(Rr,{}),e[138]=He):He=e[138];let Je;e[139]===Symbol.for("react.memo_cache_sentinel")?(Je=s.jsx(D,{name:"contract-up-down",className:"h-4 w-4"}),e[139]=Je):Je=e[139];let rt;e[140]!==n?(rt=n("sessions.sidebar.header.displayMode.collapseAll"),e[140]=n,e[141]=rt):rt=e[141];let bt;e[142]!==rt?(bt=s.jsx("span",{children:rt}),e[142]=rt,e[143]=bt):bt=e[143];let yt;e[144]!==C||e[145]!==bt?(yt=s.jsxs(bs,{onClick:C,className:"flex items-center gap-2",children:[Je,bt]}),e[144]=C,e[145]=bt,e[146]=yt):yt=e[146];let _e;e[147]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx(D,{name:"expand-up-down",className:"h-4 w-4"}),e[147]=_e):_e=e[147];let Ye;e[148]!==n?(Ye=n("sessions.sidebar.header.displayMode.expandAll"),e[148]=n,e[149]=Ye):Ye=e[149];let nt;e[150]!==Ye?(nt=s.jsx("span",{children:Ye}),e[150]=Ye,e[151]=nt):nt=e[151];let wt;e[152]!==w||e[153]!==nt?(wt=s.jsxs(bs,{onClick:w,className:"flex items-center gap-2",children:[_e,nt]}),e[152]=w,e[153]=nt,e[154]=wt):wt=e[154];let kt;e[155]!==Oe||e[156]!==Ge||e[157]!==yt||e[158]!==wt?(kt=s.jsxs(tn,{align:"end",className:"min-w-[160px]",children:[Oe,Ge,He,yt,wt]}),e[155]=Oe,e[156]=Ge,e[157]=yt,e[158]=wt,e[159]=kt):kt=e[159];let vt;e[160]!==ie||e[161]!==kt?(vt=s.jsxs(sn,{children:[ie,kt]}),e[160]=ie,e[161]=kt,e[162]=vt):vt=e[162];let St;e[163]!==G||e[164]!==ye||e[165]!==vt?(St=s.jsxs("div",{className:"flex items-center gap-1.5",children:[G,ye,vt]}),e[163]=G,e[164]=ye,e[165]=vt,e[166]=St):St=e[166];let et;e[167]!==he||e[168]!==St?(et=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[he,St]}),e[167]=he,e[168]=St,e[169]=et):et=e[169];let Ot;e[170]!==y||e[171]!==f||e[172]!==h||e[173]!==b||e[174]!==p||e[175]!==g||e[176]!==x||e[177]!==n?(Ot=f?s.jsxs("div",{className:"pb-1",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:[y?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(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:b,value:p,onChange:Wt=>x(Wt.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:Wt=>{Wt.key==="Escape"&&(Wt.stopPropagation(),y?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(D,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[170]=y,e[171]=f,e[172]=h,e[173]=b,e[174]=p,e[175]=g,e[176]=x,e[177]=n,e[178]=Ot):Ot=e[178];let ns;return e[179]!==et||e[180]!==Ot?(ns=s.jsx("div",{className:"select-none flex-shrink-0 px-2.5 py-1",children:s.jsxs("div",{className:"flex h-auto min-h-8 flex-col gap-1",children:[et,Ot]})}),e[179]=et,e[180]=Ot,e[181]=ns):ns=e[181],ns}function TN(t){return!t}function RN(t){return t.toggleArchivedSessions}function EN(t){return t.toggleRecentSection}function MN(t){return t.setDisplayMode}function FN(t){return t.showArchivedSessions}function LN(t){return t.showRecentSection}function ON(t){return t.displayMode}const df=7;function BN({sections:t,renderSessionNode:e,currentSessionId:n,editingId:r,openSidebarMenuKey:o,variant:a="section",initialVisibleCount:c=df,batchSize:l=df}){const{t:d}=Nt(),[u,m]=i.useState(new Set),[f,g]=i.useState(new Map),b=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]),y=i.useCallback((w,S,j)=>{g(k=>{const v=Math.min(j,S+l),A=new Map(k);return A.set(w,v),A})},[l]),h=i.useCallback(w=>{const S=new Set;Hi(w,n,S);const j=new Set;Hi(w,r,j);const k=Fo(w,o,"recent",!1),v=new WeakMap,A=N=>{v.set(N,Ra(N)),N.children.forEach(A)};w.forEach(A);const I=N=>({subtreeContainsActive:S,subtreeContainsEditing:j,menuOpenSessionId:k,nodeStructureKey:v.get(N)??"",childRenderExtrasFor:I});return N=>({subtreeContainsActive:S,subtreeContainsEditing:j,menuOpenSessionId:k,nodeStructureKey:v.get(N)??"",childRenderExtrasFor:I})},[n,r,o]),C=t.filter(w=>w.items.length>0);return C.length===0?null:s.jsx("div",{className:Pe(b?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1"),children:C.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,A=!b&&w.items.length>c&&v===0,I=h(k.map(O=>O.node)),N=O=>e(O.node,0,O.groupDirectory,O.projectId,!1,O.secondaryMeta,"recent",I(O.node));return b?s.jsxs("div",{className:"space-y-0.5",children:[k.map(N),v>0?s.jsx("button",{type:"button",onClick:()=>y(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(D,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(D,{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:Pe("space-y-0.5 pl-7"),children:[k.map(N),v>0?s.jsx("button",{type:"button",onClick:()=>y(w.key,k.length,w.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showMore")}):null,A?s.jsx("button",{type:"button",onClick:()=>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 Rl="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 VN(t){const e=mt.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}=Nt();let f;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==d||e[4]!==m?(f=d?s.jsxs(s.Fragment,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Rl,"aria-label":m("sessions.sidebar.footer.actions.settings"),children:s.jsx(D,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:Rl,"aria-label":m("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(D,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:Rl,"aria-label":m("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(D,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:m("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=m,e[5]=f):f=e[5];let 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 b;return e[10]!==f||e[11]!==g?(b=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]=b):b=e[12],b}const _N=t=>{const e=mt.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:b,hideDirectoryControls:p,alwaysShowActions:x,onToggle:y,onNewSession:h,onNewWorktreeSession:C,onRenameStart:w,onClose:S,sentinelRef:j,children:k,showCreateButtons:v,hideHeader:A,openSidebarMenuKey:I,setOpenSidebarMenuKey:N}=t,O=v===void 0?!0:v,P=A===void 0?!1:A,{t:T}=Nt(),{currentTheme:L}=Kr();let R;e[0]!==n?(R={id:n},e[0]=n,e[1]=R):R=e[1];const{attributes:B,listeners:V,setNodeRef:_,transform:E,transition:Z,isDragging:ne}=dc(R),Y=i.useRef(!1),H=`project:${n}`,re=I===H,[ae,me]=i.useState(!1),Se=a?Ic[a]:null,te=c?Ga[c]??null:null;let ke;e[2]!==H||e[3]!==N?(ke=de=>{de&&me(!1),N(de?H:null)},e[2]=H,e[3]=N,e[4]=ke):ke=e[4];const Q=ke;let ge;e[5]!==p||e[6]!==f||e[7]!==S||e[8]!==h||e[9]!==w||e[10]!==O||e[11]!==T?(ge=de=>s.jsxs(s.Fragment,{children:[O&&!f&&!p&&h&&s.jsxs(de,{onClick:h,children:[s.jsx(D,{name:"add",className:"mr-1.5 h-4 w-4"}),T("sessions.sidebar.project.actions.newSession")]}),s.jsxs(de,{onClick:w,children:[s.jsx(D,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),T("sessions.sidebar.session.menu.rename")]}),s.jsxs(de,{onClick:S,className:"text-destructive focus:text-destructive",children:[s.jsx(D,{name:"close",className:"mr-1.5 h-4 w-4"}),T("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]=T,e[12]=ge):ge=e[12];const F=ge,se=WN,ee=UN,Ne=HN;let De;e[13]===Symbol.for("react.memo_cache_sentinel")?(De=de=>{(de.button===2||de.button===0&&de.ctrlKey)&&(Y.current=!0)},e[13]=De):De=e[13];const Be=De;let Fe;e[14]!==y?(Fe=()=>{if(Y.current){Y.current=!1;return}y()},e[14]=y,e[15]=Fe):Fe=e[15];const Me=Fe;let he;e[16]!==E?(he=uc.Transform.toString(E),e[16]=E,e[17]=he):he=e[17];let Ae;e[18]!==he||e[19]!==Z?(Ae={transform:he,transition:Z},e[18]=he,e[19]=Z,e[20]=Ae):Ae=e[20];const pe=ne&&"opacity-30";let ue;e[21]!==pe?(ue=Pe("relative",pe),e[21]=pe,e[22]=ue):ue=e[22];let U;e[23]!==x||e[24]!==B||e[25]!==L||e[26]!==Q||e[27]!==Me||e[28]!==p||e[29]!==P||e[30]!==te||e[31]!==n||e[32]!==m||e[33]!==u||e[34]!==ae||e[35]!==g||e[36]!==re||e[37]!==f||e[38]!==b||e[39]!==V||e[40]!==h||e[41]!==C||e[42]!==o||e[43]!==d||e[44]!==l||e[45]!==Se||e[46]!==r||e[47]!==F||e[48]!==j||e[49]!==O||e[50]!==T?(U=P?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(Mc,{open:ae,onOpenChange:me,children:[s.jsx(Ec,{render:s.jsx("div",{className:Pe("w-full text-left group/project select-none"),style:{backgroundColor:g&&b?"transparent":void 0},onContextMenu:de=>{p||(de.preventDefault(),me(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...B,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:Be,onClick:Me,...V,className:Pe("flex-1 min-w-0 flex items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing transition-[padding]",f&&!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:Pe("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(D,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),l?s.jsx("span",{className:Pe("h-3.5 w-3.5 items-center justify-center overflow-hidden rounded-[3px]",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:L.metadata.variant,iconColor:L.colors.surface.foreground},className:"h-full w-full object-contain",fallback:Se?s.jsx(D,{name:Se,className:"h-3.5 w-3.5",style:te?{color:te}:void 0}):s.jsx(D,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:te?{color:te}:void 0})})}):Se?s.jsx(D,{name:Se,className:Pe("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(D,{name:"folder",className:Pe("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:Pe("text-[14px] font-normal truncate lowercase",m?"text-foreground":"text-foreground group-hover/project:text-foreground"),children:r})]})}),s.jsx(Ft,{side:"right",sideOffset:8,children:o})]}),s.jsxs("div",{className:Pe("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",O?"right-7":"right-0.5"),children:[O&&f&&!p&&C?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),C()},className:Pe("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground transition-opacity",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":T("sessions.sidebar.project.actions.newWorktree"),children:s.jsx(D,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:T("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,p?null:s.jsxs(sn,{open:re,onOpenChange:Q,children:[s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",re?"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":T("sessions.sidebar.project.actions.projectMenu"),onPointerDown:ee,onMouseDown:Ne,onClick:se,children:s.jsx(D,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(tn,{align:"end",className:"min-w-[180px]",children:F(bs)})]})]}),O&&h?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),h()},className:Pe("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",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":T(f?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession"),children:s.jsx(D,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:T(f?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(Tc,{className:"min-w-[180px]",children:F(Rc)})]})]}),e[23]=x,e[24]=B,e[25]=L,e[26]=Q,e[27]=Me,e[28]=p,e[29]=P,e[30]=te,e[31]=n,e[32]=m,e[33]=u,e[34]=ae,e[35]=g,e[36]=re,e[37]=f,e[38]=b,e[39]=V,e[40]=h,e[41]=C,e[42]=o,e[43]=d,e[44]=l,e[45]=Se,e[46]=r,e[47]=F,e[48]=j,e[49]=O,e[50]=T,e[51]=U):U=e[51];let fe;return e[52]!==k||e[53]!==_||e[54]!==ue||e[55]!==U||e[56]!==Ae?(fe=s.jsxs("div",{ref:_,style:Ae,className:ue,children:[U,k]}),e[52]=k,e[53]=_,e[54]=ue,e[55]=U,e[56]=Ae,e[57]=fe):fe=e[57],fe},$N=t=>{const e=mt.c(21),{id:n,disabled:r,children:o}=t,a=r===void 0?!1:r;let c;e[0]!==a||e[1]!==n?(c={id:n,disabled:a},e[0]=a,e[1]=n,e[2]=c):c=e[2];const{listeners:l,setNodeRef:d,setActivatorNodeRef:u,transform:m,transition:f,isDragging:g}=dc(c);let b;e[3]!==l||e[4]!==u?(b={listeners:l,setActivatorNodeRef:u},e[3]=l,e[4]=u,e[5]=b):b=e[5];const p=b;let x;e[6]!==m?(x=uc.Transform.toString(m),e[6]=m,e[7]=x):x=e[7];let y;e[8]!==x||e[9]!==f?(y={transform:x,transition:f},e[8]=x,e[9]=f,e[10]=y):y=e[10];const h=g&&"opacity-50";let C;e[11]!==h?(C=Pe("space-y-0.5 rounded-md",h),e[11]=h,e[12]=C):C=e[12];let w;e[13]!==o||e[14]!==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]!==y||e[18]!==C||e[19]!==w?(S=s.jsx("div",{ref:d,style:y,className:C,children:w}),e[16]=d,e[17]=y,e[18]=C,e[19]=w,e[20]=S):S=e[20],S},zN=i.memo($N);function WN(t){t.stopPropagation()}function UN(t){t.stopPropagation()}function HN(t){t.stopPropagation()}function GN(t){const{t:e}=Nt(),n=ga(yo(xa,{activationConstraint:{distance:8}}),yo(qh,{coordinateGetter:Kh})),r=ga(yo(xa,{activationConstraint:{distance:8}})),o=i.useRef(null),a=i.useRef(new Map),c=i.useRef(t.getOrderedGroups);c.current!==t.getOrderedGroups&&(c.current=t.getOrderedGroups,a.current.clear());const l=(d,u)=>{const m=a.current,f=m.get(d);if(f&&f.groups===u)return f.ordered;const g=t.getOrderedGroups(d,u);if(m.set(d,{groups:u,ordered:g}),m.size>256){const b=m.keys().next().value;b!==void 0&&m.delete(b)}return g};return t.sharedSessionsOnly?s.jsxs(_n,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("space-y-1 pb-1 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.hasSharedSessions?null:t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState]}):t.projectSections.length===0?s.jsxs(_n,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.emptyState]}):t.sectionsForRender.length===0?s.jsx(_n,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:t.searchEmptyState}):s.jsxs(_n,{ref:o,useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Pe("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const d=t.sectionsForRender.find(g=>g.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!d)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const u=d.groups.find(g=>g.isMain&&g.sessions.length>0)??d.groups.find(g=>g.sessions.length>0)??d.groups.find(g=>g.isMain)??d.groups[0];if(!u)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")});const m=d.groups.find(g=>g.isArchivedBucket);return[u,...m&&m.id!==u.id?[m]:[]].map(g=>{const b=`${d.project.id}:${g.id}`,p=g.id===u.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(g,b,d.project.id,p,null,!0,o)},b)})})()}):s.jsx(s.Fragment,{children:s.jsxs(ba,{sensors:n,collisionDetection:ya,onDragEnd:d=>{if(t.isInlineEditing)return;const{active:u,over:m}=d;if(!m||u.id===m.id)return;const f=t.sectionsForRender.findIndex(b=>b.project.id===u.id),g=t.sectionsForRender.findIndex(b=>b.project.id===m.id);f===-1||g===-1||f===g||t.reorderProjects(f,g)},children:[s.jsx(Bl,{items:t.sectionsForRender.map(d=>d.project.id),strategy:Vl,children:t.sectionsForRender.map(d=>{const u=d.project,m=u.id,f=Sm(u.label?.trim()||Ri(u.normalizedPath,t.homeDirectory)||u.normalizedPath),g=Na(u.normalizedPath,t.homeDirectory),b=t.collapsedProjects.has(m),p=m===t.activeProjectId,x=t.projectRepoStatus.get(m),y=l(m,d.groups),h=y.find(w=>w.isMain)??null,C=h?y.filter(w=>w.id!==h.id):y;return s.jsx(_N,{id:m,projectLabel:f,projectDescription:g,projectIcon:u.icon,projectColor:u.color,projectIconImage:u.iconImage,projectIconBackground:u.iconBackground,isCollapsed:b,isActiveProject:p,isRepo:!!x,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(m),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,alwaysShowActions:t.alwaysShowActions,onToggle:()=>t.toggleProject(m),onNewSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:u.normalizedPath})},onNewWorktreeSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.openNewWorktreeDialog()},onRenameStart:()=>t.openProjectEditDialog(m),onClose:()=>t.removeProject(m),sentinelRef:w=>{t.projectHeaderSentinelRefs.current.set(m,w)},showCreateButtons:!0,openSidebarMenuKey:t.openSidebarMenuKey,setOpenSidebarMenuKey:t.setOpenSidebarMenuKey,children:b?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:d.groups.length>0?s.jsxs(ba,{sensors:r,collisionDetection:ya,onDragEnd:w=>{if(t.isInlineEditing)return;const{active:S,over:j}=w;if(!j||S.id===j.id)return;const k=C.findIndex(N=>N.id===S.id),v=C.findIndex(N=>N.id===j.id);if(k===-1||v===-1||k===v)return;const A=Rf(C,k,v).map(N=>N.id),I=h?[h.id,...A]:A;t.setGroupOrderByProject(N=>{const O=new Map(N);return O.set(m,I),O})},children:[h?t.renderGroupSessions(h,`${m}:${h.id}`,m,!0,null,void 0,o):null,s.jsx(Bl,{items:C.map(w=>w.id),strategy:Vl,children:C.map(w=>{const S=`${m}:${w.id}`;return s.jsx(zN,{id:w.id,disabled:t.isInlineEditing,children:j=>t.renderGroupSessions(w,S,m,!1,j,void 0,o)},w.id)})}),s.jsx($l,{dropAnimation:null})]}):s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")})})},m)})}),s.jsx($l,{dropAnimation:null})]})})]})}function KN(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(Xi(),{month:"short"}),r=e.getDate(),o=e.getFullYear(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${a}:${c}`}function qN(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 YN(t){const e=t.info.role==="user"?"User":"Assistant",n=KN(t.info.time?.created),r=qN(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
170
-
171
- *${o}*`:`**${e}**`}function QN(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function uh(t){const e=YN(t),n=QN(t.parts).trim();return n?`${e}
172
-
173
- ${n}`:""}function fh(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(uh).filter(Boolean).join(`
178
-
179
- ---
180
-
181
- `),c=[o+a];for(const l of t.children)c.push(fh(l,e+1));return c.join(`
182
-
183
- ---
184
-
185
- `)}function JN(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(uh).filter(Boolean).join(`
192
-
193
- ---
194
-
195
- `);let l=a+c;if(n&&n.length>0){const d=n.map(u=>fh(u,1)).join(`
196
-
197
- ---
198
-
199
- `);l+=`
200
-
201
- ---
202
-
203
- `+d}return l}function XN(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 ZN(t,e){const n=await up(e,t);if(n)return n;if(!Gr())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 e2(t){const e=Lo()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await fp(t)?!0:wa(t)}function t2(){return kc()}function s2(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 n2=(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},Bn=ro()((t,e)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{e().enabled||t({enabled:!0})},disable:()=>{t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{e().enabled?t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):t({enabled:!0})},toggleSelected:(n,r,o)=>{const a=e(),c=new Set(a.selectedIds);let l=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(c.clear(),l=r,d=null):l===null&&r!==null&&(l=r);const m=o&&o.length>0?[n,...o]:[n];if(c.has(n)){for(const 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],b=o.slice(f,g+1),p=n2(b,c),y=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const h of p)y.add(h);t({selectedIds:y,scopeKey:a??l.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){t({selectedIds:new Set,scopeKey:null,anchorId:null});return}t({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{t({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=e();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?t({selectedIds:o,scopeKey:null,anchorId:null}):t({selectedIds:o}))}}));let ic=!1;const oc=new Set;let uf=!1;function r2(){for(const t of oc)t()}function Gc(t){ic!==t&&(ic=t,r2())}function i2(t){t.key==="Shift"&&Gc(!0)}function o2(t){t.key==="Shift"&&Gc(!1)}function a2(){Gc(!1)}function l2(){uf||typeof window>"u"||(uf=!0,window.addEventListener("keydown",i2),window.addEventListener("keyup",o2),window.addEventListener("blur",a2))}function c2(t){return l2(),oc.add(t),()=>{oc.delete(t)}}function d2(){return ic}function u2(){return!1}function f2(){return Xe.useSyncExternalStore(c2,d2,u2)}const m2=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,mh=/^g[1-9]\d*$/,xo=(t,e,n,r,o)=>{if(!m2.test(t)||e!==void 0&&!mh.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 mh.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)},h2=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("/")},p2=(t,e,n,r)=>{const o=[t];return r&&o.push(r),o.push(e,n,"fusion"),o.join("/")},hh=t=>{const e=mt.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=Nt(),u=ss(g2),m=ss(x2),f=ss(b2);let g;e[0]!==u?(g=u(),e[0]=u,e[1]=g):g=e[1];const b=g;let p;e[2]!==b?(p=b.filter(y2),e[2]=b,e[3]=p):p=e[3];const x=p;let y,h;e[4]!==b.length||e[5]!==m?(y=()=>{b.length===0&&m()},h=[b.length,m],e[4]=b.length,e[5]=m,e[6]=y,e[7]=h):(y=e[6],h=e[7]),i.useEffect(y,h);let C,w;e[8]!==f||e[9]!==a||e[10]!==r||e[11]!==x||e[12]!==n?(C=()=>{if(a)return;const P=n.trim();if(P.length>0&&x.some(R=>R.name===P))return;const T=typeof f=="string"&&f.trim().length>0?f.trim():null;if(T&&x.some(R=>R.name===T)){r(T);return}const L=x[0]?.name;L&&r(L)},w=[f,a,r,x,n],e[8]=f,e[9]=a,e[10]=r,e[11]=x,e[12]=n,e[13]=C,e[14]=w):(C=e[13],w=e[14]),i.useEffect(C,w);const S=n.trim().length>0?n:void 0;let j;e[15]!==o?(j=Pe("max-w-full typography-meta text-foreground !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 data-[popup-open]:!bg-[var(--interactive-active)]/70",o),e[15]=o,e[16]=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(Nn,{placeholder:k}),e[19]=k,e[20]=v):v=e[20];let A;e[21]!==c||e[22]!==j||e[23]!==v?(A=s.jsx(zn,{id:c,size:"lg",className:j,children:v}),e[21]=c,e[22]=j,e[23]=v,e[24]=A):A=e[24];let I;e[25]!==x?(I=x.length>0&&s.jsx(Wl,{children:x.map(w2)}),e[25]=x,e[26]=I):I=e[26];let N;e[27]!==l||e[28]!==I?(N=s.jsx(Wn,{fitContent:!0,portalToBody:l,children:I}),e[27]=l,e[28]=I,e[29]=N):N=e[29];let O;return e[30]!==a||e[31]!==r||e[32]!==S||e[33]!==A||e[34]!==N?(O=s.jsxs($n,{value:S,onValueChange:r,disabled:a,children:[A,N]}),e[30]=a,e[31]=r,e[32]=S,e[33]=A,e[34]=N,e[35]=O):O=e[35],O};function g2(t){return t.getVisibleAgents}function x2(t){return t.loadAgents}function b2(t){return t.currentAgentName}function y2(t){return wc(t.mode)}function w2(t){return s.jsx(Ls,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const ph="h-7",Ao=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,v2=t=>{const e=mt.c(12),{model:n,instanceIndex:r,totalSameModel:o,onRemove:a}=t,c=n.displayName||`${n.providerID}/${n.modelID}`,l=o>1?`${c} (${r})`:c;let d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=Pe("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",ph),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(D,{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 b;return e[8]!==u||e[9]!==m||e[10]!==g?(b=s.jsxs("div",{className:d,children:[u,m,g]}),e[8]=u,e[9]=m,e[10]=g,e[11]=b):b=e[11],b},gh=t=>{const e=mt.c(119),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:u,addButtonClassName:m,dropdownSide:f,dropdownClassName:g,containerClassName:b,triggerIcon:p}=t,x=d===void 0?!0:d,y=f===void 0?"top":f,{t:h}=Nt(),C=ss(j2),w=ss(S2),S=Ee(N2),j=Ee(k2),{favoriteModelsList:k,recentModelsList:v}=Cg(),A=Ee(C2),I=Ee(A2),[N,O]=i.useState(!1),[P,T]=i.useState(""),[L,R]=i.useState(null),B=i.useRef(null),V=i.useRef(null),_=u===1,E=u===void 0||n.length<u||_;let Z;if(e[0]!==n){Z=new Map;for(const le of n){const ie=`${le.providerID}:${le.modelID}`;Z.set(ie,(Z.get(ie)||0)+1)}e[0]=n,e[1]=Z}else Z=e[1];const ne=Z;let Y;e[2]!==n?(Y=le=>n.filter(Oe=>Oe.providerID===le.providerID&&Oe.modelID===le.modelID).findIndex(Oe=>Oe.instanceId===le.instanceId)+1,e[2]=n,e[3]=Y):Y=e[3];const H=Y;let re,ae;e[4]!==y||e[5]!==N?(re=()=>{if(!N||!V.current)return;const le=V.current.getBoundingClientRect();if(y==="bottom"){const rt=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-le.bottom-16-112;R(Math.max(160,Math.min(320,rt)));return}let ie=V.current.parentElement;for(;ie&&!(ie.getAttribute("role")==="dialog"||ie.hasAttribute("data-scroll-shadow"));){const He=getComputedStyle(ie);if(He.overflow==="auto"||He.overflow==="hidden"||He.overflowY==="auto"||He.overflowY==="hidden")break;ie=ie.parentElement}const Oe=ie?ie.getBoundingClientRect().top:0,Ge=le.top-Oe-16;R(Math.max(150,Math.min(300,Ge)))},ae=[y,N],e[4]=y,e[5]=N,e[6]=re,e[7]=ae):(re=e[6],ae=e[7]),i.useEffect(re,ae);let me,Se;e[8]!==E||e[9]!==N?(me=()=>{!E&&N&&(O(!1),T(""))},Se=[E,N],e[8]=E,e[9]=N,e[10]=me,e[11]=Se):(me=e[10],Se=e[11]),i.useEffect(me,Se);let te,ke;e[12]!==N?(te=()=>{if(!N)return;const le=ie=>{B.current&&!B.current.contains(ie.target)&&(O(!1),T(""))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},ke=[N],e[12]=N,e[13]=te,e[14]=ke):(te=e[13],ke=e[14]),i.useEffect(te,ke);let Q;e[15]!==_||e[16]!==r||e[17]!==a||e[18]!==n.length?(Q=le=>{const ie={providerID:le.providerID,modelID:le.modelID,displayName:le.model.name||le.modelID,instanceId:Ao()};_&&n.length>0&&a?a(0,ie):r(ie),_&&(O(!1),T(""))},e[15]=_,e[16]=r,e[17]=a,e[18]=n.length,e[19]=Q):Q=e[19];const ge=Q;let F;e[20]!==h?(F=h("multirun.modelMultiSelect.search.placeholder"),e[20]=h,e[21]=F):F=e[21];let se;e[22]!==h?(se=h("multirun.modelMultiSelect.search.noResults"),e[22]=h,e[23]=se):se=e[23];let ee;e[24]!==h?(ee=h("multirun.modelMultiSelect.sections.favorites"),e[24]=h,e[25]=ee):ee=e[25];let Ne;e[26]!==h?(Ne=h("multirun.modelMultiSelect.sections.recent"),e[26]=h,e[27]=Ne):Ne=e[27];let De;e[28]!==h?(De=h("multirun.modelMultiSelect.keyboard.hint"),e[28]=h,e[29]=De):De=e[29];let Be;e[30]!==h?(Be=h("settings.agents.modelSelector.actions.favorite"),e[30]=h,e[31]=Be):Be=e[31];let Fe;e[32]!==h?(Fe=h("settings.agents.modelSelector.actions.unfavorite"),e[32]=h,e[33]=Fe):Fe=e[33];let Me;e[34]!==h?(Me=h("chat.modelControls.capabilities"),e[34]=h,e[35]=Me):Me=e[35];let he;e[36]!==h?(he=h("chat.modelControls.capability.toolCalling"),e[36]=h,e[37]=he):he=e[37];let Ae;e[38]!==h?(Ae=h("chat.modelControls.capability.reasoning"),e[38]=h,e[39]=Ae):Ae=e[39];let pe;e[40]!==h?(pe=h("chat.modelControls.input"),e[40]=h,e[41]=pe):pe=e[41];let ue;e[42]!==h?(ue=h("chat.modelControls.output"),e[42]=h,e[43]=ue):ue=e[43];let U;e[44]!==h?(U=h("chat.modelControls.costPerMillion"),e[44]=h,e[45]=U):U=e[45];let fe;e[46]!==F||e[47]!==se||e[48]!==ee||e[49]!==Ne||e[50]!==De||e[51]!==Be||e[52]!==Fe||e[53]!==Me||e[54]!==he||e[55]!==Ae||e[56]!==pe||e[57]!==ue||e[58]!==U?(fe={searchPlaceholder:F,noResults:se,favorites:ee,recent:Ne,keyboardHint:De,favorite:Be,unfavorite:Fe,capabilities:Me,capabilityToolCalling:he,capabilityReasoning:Ae,input:pe,output:ue,costPerMillion:U},e[46]=F,e[47]=se,e[48]=ee,e[49]=Ne,e[50]=De,e[51]=Be,e[52]=Fe,e[53]=Me,e[54]=he,e[55]=Ae,e[56]=pe,e[57]=ue,e[58]=U,e[59]=fe):fe=e[59];const de=fe;let G;e[60]!==b?(G=Pe("relative",b),e[60]=b,e[61]=G):G=e[61];let $;e[62]!==m?($=Pe(ph,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",m),e[62]=m,e[63]=$):$=e[63];const ve=!E;let be;e[64]!==N?(be=()=>{O(!N)},e[64]=N,e[65]=be):be=e[65];let z;e[66]!==p?(z=p??s.jsx(D,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=p,e[67]=z):z=e[67];let xe;e[68]!==l||e[69]!==h?(xe=l??h("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=h,e[70]=xe):xe=e[70];let je;e[71]!==$||e[72]!==ve||e[73]!==be||e[74]!==z||e[75]!==xe?(je=s.jsxs($e,{ref:V,type:"button",variant:"outline",size:"sm",className:$,disabled:ve,onClick:be,children:[z,xe]}),e[71]=$,e[72]=ve,e[73]=be,e[74]=z,e[75]=xe,e[76]=je):je=e[76];let K;e[77]!==L||e[78]!==E||e[79]!==g||e[80]!==y||e[81]!==k||e[82]!==ge||e[83]!==A||e[84]!==j||e[85]!==N||e[86]!==de||e[87]!==ne||e[88]!==w||e[89]!==I||e[90]!==C||e[91]!==v||e[92]!==P||e[93]!==S?(K=N?s.jsx("div",{className:Pe("absolute left-0 z-50 w-[min(420px,calc(100vw-2rem))] max-w-[calc(100vw-2rem)] flex flex-col overflow-hidden rounded-xl border border-border/50 shadow-lg",y==="top"?"bottom-full mb-1":"top-full mt-1",g),style:{background:"linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))"},children:s.jsx(Ag,{providers:C,providerOrder:I,favoriteModels:k,recentModels:v,modelsMetadata:w,hiddenModels:A,searchQuery:P,onSearchQueryChange:T,onSelect:ge,labels:de,selectionCount:le=>ne.get(`${le.providerID}:${le.modelID}`)||0,disabled:!E,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:L?`${L}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:N,isFavorite:le=>j(le.providerID,le.modelID),onToggleFavorite:le=>S(le.providerID,le.modelID),onEscape:()=>{O(!1),T("")}})}):null,e[77]=L,e[78]=E,e[79]=g,e[80]=y,e[81]=k,e[82]=ge,e[83]=A,e[84]=j,e[85]=N,e[86]=de,e[87]=ne,e[88]=w,e[89]=I,e[90]=C,e[91]=v,e[92]=P,e[93]=S,e[94]=K):K=e[94];let ye;e[95]!==G||e[96]!==je||e[97]!==K?(ye=s.jsxs("div",{className:G,ref:B,children:[je,K]}),e[95]=G,e[96]=je,e[97]=K,e[98]=ye):ye=e[98];let Le;e[99]!==H||e[100]!==ne||e[101]!==o||e[102]!==a||e[103]!==C||e[104]!==n||e[105]!==x||e[106]!==h?(Le=x&&n.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:n.map((le,ie)=>{const Oe=`${le.providerID}:${le.modelID}`,Ge=ne.get(Oe)||1,He=H(le),rt=C.find(Ye=>Ye.id===le.providerID)?.models?.find(Ye=>Ye.id===le.modelID),bt=rt?.variants?Object.keys(rt.variants):[],yt=bt.length>0,_e=le.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(v2,{model:le,instanceIndex:He,totalSameModel:Ge,onRemove:()=>o(ie)}),yt&&s.jsxs($n,{value:_e,onValueChange:Ye=>{if(!a)return;a(ie,{...le,variant:Ye==="__default__"?void 0:Ye})},children:[s.jsxs(zn,{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(D,{name:"brain-ai-3",className:Pe("h-3.5 w-3.5 flex-shrink-0",_e==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(Nn,{placeholder:h("multirun.modelMultiSelect.variant.placeholder"),children:Ye=>Ye==="__default__"?h("multirun.modelMultiSelect.variant.default"):Ye})]}),s.jsxs(Wn,{fitContent:!0,children:[s.jsx(Ls,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:h("multirun.modelMultiSelect.variant.default")}),bt.map(D2)]})]})]},le.instanceId)})}),e[99]=H,e[100]=ne,e[101]=o,e[102]=a,e[103]=C,e[104]=n,e[105]=x,e[106]=h,e[107]=Le):Le=e[107];let Re;e[108]!==ye||e[109]!==Le?(Re=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[ye,Le]}),e[108]=ye,e[109]=Le,e[110]=Re):Re=e[110];let X;e[111]!==u||e[112]!==c||e[113]!==n.length||e[114]!==h?(X=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:u!==void 0?h("multirun.modelMultiSelect.validation.minToMax",{min:c,max:u}):h("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[111]=u,e[112]=c,e[113]=n.length,e[114]=h,e[115]=X):X=e[115];let M;return e[116]!==Re||e[117]!==X?(M=s.jsxs("div",{className:"space-y-2",children:[Re,X]}),e[116]=Re,e[117]=X,e[118]=M):M=e[118],M};function j2(t){return t.providers}function S2(t){return t.modelsMetadata}function N2(t){return t.toggleFavoriteModel}function k2(t){return t.isFavoriteModel}function C2(t){return t.hiddenModels}function A2(t){return t.providerOrder}function D2(t){return s.jsx(Ls,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const I2=(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} ---`},ff=(t,e)=>ut.getState().getWorktreeMetadata(t)?.projectDirectory??e,P2=async t=>{const e=t.directory??void 0,n=Dg(t.session.id,e);if(n.length===0&&t.directory){const o=(await Vn.withDirectory(t.directory,()=>Vn.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 Ld(c.parts??[]).trim()}return""}for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o.role==="assistant")return Ld(Ig(o.id,e)).trim()}return""};function T2({session:t,open:e,onOpenChange:n}){const{t:r}=Nt(),o=xc(),a=vr(_=>_.activeSessions),c=vr(_=>_.archivedSessions),l=ss(_=>_.providers),d=ss(_=>_.currentProviderId),u=ss(_=>_.currentModelId),m=ss(_=>_.currentAgentName),[f,g]=i.useState(d??""),[b,p]=i.useState(u??""),[x,y]=i.useState(()=>d&&u?[{providerID:d,modelID:u,instanceId:Ao()}]:[]),[h,C]=i.useState(""),[w,S]=i.useState(m??""),[j,k]=i.useState([]),[v,A]=i.useState(!1),I=i.useMemo(()=>ha(t.title),[t.title]),N=i.useMemo(()=>{const _=new Map;for(const E of o)_.set(E.id,E);for(const E of a)_.set(E.id,E);for(const E of c)_.set(E.id,E);return t.id&&_.set(t.id,t),Array.from(_.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!I)return;const _=ut.getState().getDirectoryForSession(t.id),E=ff(t.id,_),Z=N.map(ne=>{const Y=ha(ne.title);if(!Y||Y.groupSlug!==I.groupSlug||Y.fusion||(Y.runGroup??null)!==(I.runGroup??null))return null;const H=ut.getState().getDirectoryForSession(ne.id)??Tr(ne),re=ff(ne.id,H);return E&&re&&E!==re?null:{session:ne,directory:H,projectDirectory:re}}).filter(ne=>ne!==null).sort((ne,Y)=>(ne.session.time?.created??0)-(Y.session.time?.created??0));k(Z)},[N,e,I,t.id]);const P=l.find(_=>_.id===f)?.models.find(_=>_.id===b),T=P?.variants?Object.keys(P.variants):[],L=!!(I&&f&&b&&j.length>0&&!v),R=i.useCallback(_=>{y([_]),g(_.providerID),p(_.modelID),C("")},[]),B=x[0]?.displayName||x[0]?.modelID||r("multirun.fusion.model.placeholder"),V=async()=>{if(!(!I||!f||!b)){A(!0);try{const _=await Promise.all(j.map(ae=>P2(ae))),E=j.map((ae,me)=>({source:ae,text:_[me]??""})).filter(ae=>ae.text.trim().length>0);if(E.length===0){ce.error(r("multirun.fusion.toast.noOutputs"));return}const Z=j[0]?.projectDirectory??j[0]?.directory??null,ne=p2(I.groupSlug,f,b,I.runGroup),[Y,H]=await Promise.all([Tn("session.fusion.visible"),Tn("session.fusion.instructions")]),re=await ut.getState().createSession(ne,Z,null);if(!re)throw new Error("Failed to create fusion session");ut.getState().setCurrentSession(re.id,Z),n(!1),await Vn.sendMessage({id:re.id,providerID:f,modelID:b,variant:h||void 0,agent:w||void 0,text:Y,additionalParts:[{text:H,synthetic:!0},...E.map((ae,me)=>({text:I2(ae.source,ae.text,me),synthetic:!0})),{text:`
208
-
209
- --- FUSION INPUTS END ---
210
- Now write the final fused answer.`,synthetic:!0}],directory:Z??Vn.getDirectory()})}catch(_){console.error("[MultiRunFusion] Failed to start fusion",_),ce.error(r("multirun.fusion.toast.failed"))}finally{A(!1)}}};return s.jsx($s,{open:e,onOpenChange:n,children:s.jsxs(_s,{className:"max-w-xl overflow-visible",children:[s.jsxs(Hs,{children:[s.jsx(Us,{children:r("multirun.fusion.title")}),s.jsx(on,{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(gh,{selectedModels:x,onAdd:R,onUpdate:(_,E)=>R(E),onRemove:()=>{y([]),g(""),p(""),C("")},maxModels:1,addButtonLabel:B,showChips:!1,addButtonClassName:"h-8 w-fit max-w-[min(28rem,calc(100vw-8rem))] justify-start rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5",dropdownSide:"bottom",dropdownClassName:"w-[min(28rem,calc(100vw-8rem))]",triggerIcon:f?s.jsx(Do,{providerId:f,className:"h-3.5 w-3.5 mr-1"}):void 0})}),T.length>0?s.jsxs($n,{value:h||"__default__",onValueChange:_=>C(_==="__default__"?"":_),children:[s.jsxs(zn,{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(D,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(Nn,{children:_=>_==="__default__"?r("multirun.modelMultiSelect.variant.default"):_})]}),s.jsxs(Wn,{fitContent:!0,portalToBody:!0,children:[s.jsx(Ls,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),T.map(_=>s.jsx(Ls,{value:_,children:_},_))]})]}):null,s.jsx(hh,{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(_=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(Do,{providerId:ha(_.session.title)?.providerID??"",className:"h-4 w-4"}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:_.session.title||_.session.id}),s.jsx("button",{type:"button",onClick:()=>k(E=>E.filter(Z=>Z.session.id!==_.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"close",className:"h-4 w-4"})})]},_.session.id))})]}),s.jsxs(ir,{children:[s.jsx($e,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx($e,{onClick:V,disabled:!L,children:r(v?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function R2(t){const e=mt.c(7);let n,r,o,a,c;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("path",{d:"M12 4.5v6.25M12 10.75v3.5M12 10.75H7.25A3.25 3.25 0 0 0 4 14v1.25M12 10.75h4.75A3.25 3.25 0 0 1 20 14v1.25",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),r=s.jsx("path",{d:"M9.25 7.25 12 4.5l2.75 2.75",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),o=s.jsx("circle",{cx:"4",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),a=s.jsx("circle",{cx:"12",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),c=s.jsx("circle",{cx:"20",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),e[0]=n,e[1]=r,e[2]=o,e[3]=a,e[4]=c):(n=e[0],r=e[1],o=e[2],a=e[3],c=e[4]);let l;return e[5]!==t?(l=s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",...t,children:[n,r,o,a,c]}),e[5]=t,e[6]=l):l=e[6],l}const E2=i.memo(function(e){const n=mt.c(22),{archiveLabel:r,deleteLabel:o,buttonSizeClass:a,iconSizeClass:c,onPointerDown:l,onMouseDown:d,onArchive:u,onDelete:m}=e,f=f2(),g=f?o:r;let b;n[0]!==u||n[1]!==m||n[2]!==f?(b=k=>{if(f||k.shiftKey){m(k);return}u(k)},n[0]=u,n[1]=m,n[2]=f,n[3]=b):b=n[3];const p=b,x=f?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground";let y;n[4]!==a||n[5]!==x?(y=Pe("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",x,a),n[4]=a,n[5]=x,n[6]=y):y=n[6];const h=f?"delete-bin":"archive";let C;n[7]!==c||n[8]!==h?(C=s.jsx(D,{name:h,className:c}),n[7]=c,n[8]=h,n[9]=C):C=n[9];let w;n[10]!==p||n[11]!==g||n[12]!==d||n[13]!==l||n[14]!==y||n[15]!==C?(w=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:y,"aria-label":g,onPointerDown:l,onMouseDown:d,onClick:p,onKeyDown:_2,children:C})}),n[10]=p,n[11]=g,n[12]=d,n[13]=l,n[14]=y,n[15]=C,n[16]=w):w=n[16];let S;n[17]!==g?(S=s.jsx(Ft,{side:"left",sideOffset:8,children:g}),n[17]=g,n[18]=S):S=n[18];let j;return n[19]!==w||n[20]!==S?(j=s.jsxs(Et,{children:[w,S]}),n[19]=w,n[20]=S,n[21]=j):j=n[21],j});function M2(t){const{t:e}=Nt(),{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:b,setEditingId:p,editTitle:x,setEditTitle:y,handleSaveEdit:h,handleCancelEdit:C,toggleParent:w,handleSessionSelect:S,handleSessionDoubleClick:j,togglePinnedSession:k,handleShareSession:v,copiedSessionId:A,handleCopyShareUrl:I,handleUnshareSession:N,openSidebarMenuKey:O,setOpenSidebarMenuKey:P,renamingFolderId:T,getFoldersForScope:L,getSessionFolderId:R,removeSessionFromFolder:B,addSessionToFolder:V,createFolderAndStartRename:_,openContextPanelTab:E,handleDeleteSession:Z,mobileVariant:ne,alwaysShowActions:Y,renderSessionNode:H,secondaryMeta:re,renderContext:ae="project",subtreeContainsActive:me,subtreeContainsEditing:Se,menuOpenSessionId:te,childRenderExtrasFor:ke,liveSessionById:Q}=t,ge=!!re?.projectLabel,F=!!re?.branchLabel,se=Dr(Ue=>Ue.displayMode),ee=i.useMemo(()=>Gr(),[]),Ne=se==="minimal"||ee,De=i.useMemo(()=>Fa(),[]),Be=i.useContext(Pg),Fe=ee?"group-hover:opacity-100 group-hover:pointer-events-auto":"group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto",Me=ee?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",he=ee,Ae=!c&&!ne,pe=Ne?ee?Ae&&he?"group-hover:pr-18":Ae||he?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":ee?Ae&&he?"group-hover:pr-18":Ae||he?"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",U=i.useRef(!1),[fe,de]=i.useState(!1),G=i.useRef(b);G.current=b;const $=i.useRef(null),ve=i.useRef(h);ve.current=h;const[be,z]=i.useState(x),xe=i.useRef(be);xe.current=be;const je=i.useRef(null),K=i.useRef(null),ye=n.session,Le=Q.get(ye.id)??ye,Re=cs(ye.directory??null)??cs(o??null),X=Tg(Re??void 0,{bootstrap:!c}),M=Pc(),le=Bn(Ue=>Ue.enabled),ie=Bn(i.useCallback(Ue=>Ue.selectedIds.has(ye.id),[ye.id])),Oe=Bn(Ue=>Ue.toggleSelected),Ge=Bn(Ue=>Ue.setRange),He=i.useCallback(Ue=>{const os=[],fs=zs=>{zs.children.forEach(Ks=>{os.push(Ks.session.id),fs(Ks)})};return fs(Ue),os},[]),[Je,rt]=i.useState(!1),[bt,yt]=i.useState(!0),_e=`${ae}:${c?"archived":"active"}:${ye.id}`,Ye=am(i.useCallback(Ue=>!!Ue.sessionMemoryState.get(Rg(ye.id))?.isZombie,[ye.id])),nt=Eg(ye.id),wt=Mg(ye.id,Re??void 0),kt=l===ye.id,vt=Le.title||e("sessions.sidebar.session.untitled"),St=n.children.length>0,et=d.has(ye.id),Ot=_e,ns=m?!0:u.has(Ot),Wt=!!Le.parentID,Ze=Fg(ye.id)>0&&(!Wt||g),_t=Le.time?.updated||Le.time?.created||Date.now(),jt=cb(_t),xt=db(_t),rs=O===_e,[Gt,Ut]=i.useState(!1),as=rs||Gt,Bt=i.useMemo(()=>ha(Le.title)!==null,[Le.title]),[Lt,Vt]=i.useState(!1),Kt=ee&&ae==="recent"&&!Ne,Xt=ee&&ae==="recent"&&Ne,Qt=i.useMemo(()=>He(n).length,[He,n]),vs=i.useCallback(async Ue=>{const os=[];let fs=0;for(const zs of Ue)try{await M.ensureSessionRenderable(zs.session.id);const Ks=Od(X.getState(),zs.session.id).list,Ws=zs.session.title||e("sessions.sidebar.session.export.untitledSubagent"),pn=zs.session.agent,Ns=await vs(zs.children);fs+=Ns.skipped,os.push({title:Ws,agent:pn,records:Ks,children:Ns.children})}catch{fs+=He(zs).length+1}return{children:os,skipped:fs}},[He,X,M,e]),Dt=i.useCallback(Ue=>{Ue<=0||ce.warning(Ue===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:Ue}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:Ue}))},[e]),$t=i.useCallback(async Ue=>{if(!Re){ce.error(e("sessions.sidebar.session.export.nothingToExport"));return}await M.ensureSessionRenderable(ye.id);const os=Od(X.getState(),ye.id).list;if(os.length===0){ce.error(e("sessions.sidebar.session.export.nothingToExport"));return}let fs,zs=0;if(Ue&&n.children.length>0){const Ns=await vs(n.children);fs=Ns.children,zs=Ns.skipped}const Ks=JN(os,Le.title??null,fs),Ws=s2(Le.title??null),pn=await ZN(Ks,Ws);if(pn){ce.success(e("sessions.sidebar.session.export.success"),{action:{label:e(t2()),onClick:()=>{e2(pn).then(Ns=>{Ns||ce.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),Dt(zs);return}XN(Ks,Ws),ce.success(e("sessions.sidebar.session.export.success")),Dt(zs)},[vs,X,n.children,Le.title,ye.id,Re,Dt,M,e]),Ct=i.useCallback(async()=>{if(n.children.length>0){yt(!0),rt(!0);return}await $t(!1)},[$t,n.children.length]),ds=i.useCallback(()=>{Re&&Ur("desktop_open_session_mini_chat_window",{sessionId:ye.id,directory:Re,apiBaseUrl:Wr(),clientToken:zl()}).catch(Ue=>{console.warn("[session-sidebar] failed to open mini chat window",Ue)})},[ye.id,Re]);if(i.useEffect(()=>{if(b!==ye.id)return;const Ue=os=>{K.current&&!K.current.contains(os.target)&&ve.current(xe.current)};return document.addEventListener("mousedown",Ue),()=>document.removeEventListener("mousedown",Ue)},[b,ye.id]),i.useLayoutEffect(()=>{if(b!==ye.id){je.current===ye.id&&(je.current=null);return}je.current!==ye.id&&(je.current=ye.id,z(x))},[b,x,ye.id]),b===ye.id)return s.jsx("div",{className:Pe("group relative flex items-center rounded-sm px-1.5 py-1",r>0&&"pl-[20px]"),children:s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[s.jsxs("form",{ref:K,className:"flex w-full items-center gap-2",onSubmit:Ue=>{Ue.preventDefault(),h(be)},children:[s.jsx("input",{value:be,onChange:Ue=>z(Ue.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:e("sessions.sidebar.session.menu.rename"),onKeyDown:Ue=>{if(Ue.stopPropagation(),Ue.key==="Escape"){C();return}}}),s.jsx("button",{type:"submit","aria-label":e("sessions.sidebar.session.rename.save"),title:e("sessions.sidebar.session.rename.save"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:C,"aria-label":e("sessions.sidebar.session.rename.cancel"),title:e("sessions.sidebar.session.rename.cancel"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(D,{name:"close",className:"size-4"})})]}),Ne?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[St?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:ns?s.jsx(D,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(D,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:jt}),ge?s.jsx("span",{className:"truncate",children:re?.projectLabel}):null,F?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:re?.branchLabel})]}):null]})})]})},ye.id);const qe=nt?.type??"idle",at=qe==="busy"||qe==="retry",Qe=wt.length,Tt=at||!at&&Ze&&!kt,ts=at?s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-primary animate-busy-pulse","aria-label":e("sessions.sidebar.session.status.active"),title:e("sessions.sidebar.session.status.active")}):s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-[var(--status-info)]","aria-label":e("sessions.sidebar.session.status.unread"),title:e("sessions.sidebar.session.status.unread")}),xs=!Y&&St&&(Tt||et),ks=et&&!Tt,Jt=s.jsx(D,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}),ls=Tt||ks?s.jsxs("span",{className:Pe("pointer-events-none absolute left-0.5 inline-flex h-3.5 w-3.5 items-center justify-center transition-opacity",Ne?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",xs?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[Tt?ts:null,ks?Jt:null]}):null,Ps=St&&!Y&&(Tt||et),Ts=St?s.jsx("span",{role:"button",tabIndex:0,onClick:Ue=>{Ue.stopPropagation(),w(Ot)},onKeyDown:Ue=>{(Ue.key==="Enter"||Ue.key===" ")&&(Ue.preventDefault(),Ue.stopPropagation(),w(Ot))},style:{minWidth:14,minHeight:14},className:Pe("inline-flex h-3.5 w-3.5 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",Kt?"absolute left-1.5 bottom-1":Xt?"relative mr-0.5 shrink-0":Pe("absolute left-0.5",Ne?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!Kt&&!Xt&&Ps?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto":""),"aria-label":e(ns?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:ns?s.jsx(D,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(D,{name:"arrow-right-s",className:"h-3 w-3"})}):null,hn=Ye?s.jsx(D,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Gs=Ue=>{Ue&&Ut(!1),P(Ue?_e:null)},an=Ue=>{if(!Ue&&$.current){const{id:os,title:fs}=$.current;$.current=null,p(os),y(fs)}},Rn=Ue=>{Ut(Ue)},Os=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),P(rs?null:_e)},we=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},tt=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},dt=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},It=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},Ht=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),P(null),Z(ye,{archivedBucket:c})},ht=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),P(null),Z(ye,{archivedBucket:c,hardDelete:!0,skipConfirm:!0})},hs=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},ps=Ue=>{Ue.preventDefault(),Ue.stopPropagation()},js=Ue=>{Ue.preventDefault(),Ue.stopPropagation(),Be?.vscode?.executeCommand("openchamber.openSessionInEditor",ye.id,vt)},Ss=Ue=>{if(U.current){U.current=!1;return}if(le){if(Ue?.preventDefault(),Ue?.stopPropagation(),Ue?.shiftKey){const fs=(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),zs=Bn.getState().anchorId,Ks=new Map;Ks.set(ye.id,He(n)),Ge(zs,ye.id,fs,Re??null,Ks);return}Oe(ye.id,Re??null,He(n));return}S(ye.id,Re,a)},Ds=Ue=>{(Ue.button===2||Ue.button===0&&Ue.ctrlKey&&!le)&&(U.current=!0)},Un=Ue=>{ne&&Ue.pointerType==="touch"&&de(!0)},Es=Ue=>{ne&&Ue.pointerType==="touch"&&de(!1)},En=({Item:Ue,Separator:os,Sub:fs,SubTrigger:zs,SubContent:Ks})=>s.jsxs(s.Fragment,{children:[s.jsxs(Ue,{onClick:()=>{$.current={id:ye.id,title:vt}},className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(Ue,{onClick:()=>k(ye.id),className:"[&>svg]:mr-1",children:[et?s.jsx(D,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(D,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(et?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),Le.share?s.jsxs(s.Fragment,{children:[s.jsx(Ue,{onClick:()=>{Le.share?.url&&I(Le.share.url,ye.id)},className:"[&>svg]:mr-1",children:A===ye.id?s.jsxs(s.Fragment,{children:[s.jsx(D,{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(D,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(Ue,{onClick:()=>N(ye.id),className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.unshare")]})]}):s.jsxs(Ue,{onClick:()=>v(Le),className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(Ue,{onClick:()=>{Ct()},className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),Bt?s.jsxs(Ue,{onClick:()=>Vt(!0),className:"[&>svg]:mr-1",children:[s.jsx(R2,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,Re&&!c?(()=>{const Ws=L(Re),pn=R(Re,ye.id);return s.jsxs(s.Fragment,{children:[s.jsx(os,{}),s.jsxs(fs,{children:[s.jsxs(zs,{className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs(Ks,{className:"min-w-[180px]",children:[Ws.length===0?s.jsx(Ue,{disabled:!0,className:"text-muted-foreground",children:e("sessions.sidebar.folders.none")}):Ws.map(Ns=>s.jsxs(Ue,{onClick:()=>{pn===Ns.id?B(Re,ye.id):V(Re,Ns.id,ye.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:Ns.name}),pn===Ns.id?s.jsx(D,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Ns.id)),s.jsx(os,{}),s.jsxs(Ue,{onClick:()=>{const Ns=_(Re);Ns&&V(Re,Ns.id,ye.id)},children:[s.jsx(D,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),pn?s.jsxs(Ue,{onClick:()=>{B(Re,ye.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(D,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,ee?null:s.jsxs(Ue,{disabled:!Re,onClick:()=>{Re&&E(Re,{mode:"chat",dedupeKey:`session:${ye.id}`,label:vt})},className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"chat-4",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openInSidePanel")}),s.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:e("sessions.sidebar.session.menu.betaBadge")})]}),De?s.jsxs(Ue,{disabled:!Re,onClick:ds,className:"[&>svg]:mr-1",children:[s.jsx(D,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(os,{}),c?null:s.jsxs(Ue,{className:"[&>svg]:mr-1",onClick:()=>Z(ye,{archivedBucket:c}),children:[s.jsx(D,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.archive")]}),s.jsxs(Ue,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Z(ye,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(D,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),Hn=s.jsx(tn,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(T||G.current),children:En({Item:bs,Separator:Rr,Sub:Vg,SubTrigger:_g,SubContent:$g})}),Xn=s.jsx(dd,{children:s.jsx(ud,{className:"app-region-no-drag z-50",children:s.jsx(fd,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(T||G.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Pe(Bd,"min-w-[180px]"),children:En({Item:({className:Ue,...os})=>s.jsx(Jh,{className:Pe(Lg,Ue),...os}),Separator:({className:Ue,...os})=>s.jsx(Xh,{className:Pe(Og,Ue),...os}),Sub:Zh,SubTrigger:({className:Ue,children:os,...fs})=>s.jsxs(ep,{className:Pe(Bg,Ue),...fs,children:[os,s.jsx(D,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:Ue,children:os,...fs})=>s.jsx(dd,{children:s.jsx(ud,{className:"app-region-no-drag z-50",children:s.jsx(fd,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Pe(Bd,Ue),...fs,children:os})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(bN,{sessionId:ye.id,sessionDirectory:Re??null,sessionTitle:vt,children:s.jsxs(Yh,{open:Gt,onOpenChange:Rn,onOpenChangeComplete:an,children:[s.jsxs(Qh,{render:s.jsx("div",{"data-session-row":ye.id,"data-session-scope":Re??"","data-session-archived":c?"1":"0",className:Pe("group relative my-0.5 flex items-center rounded-md py-1 pr-1.5","-ml-3",r>0?"pl-[32px]":"pl-[18px]",kt&&!ie&&"bg-primary/10",ie&&"bg-interactive-selection")}),children:[ls,Ts,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:Ne?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:Un,onPointerUp:Es,onPointerCancel:Es,onMouseDown:Ds,onClick:Ue=>Ss(Ue),onDoubleClick:Ue=>{Ue.stopPropagation(),j(ye.id,vt)},className:Pe("flex min-w-0 flex-1 cursor-pointer flex-col gap-0 overflow-hidden rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none transition-[padding]",fe&&"bg-interactive-hover/70",Y?ee?pe:ue:pe),children:s.jsxs("div",{className:Pe("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Pe("block min-w-0 flex-1 truncate typography-ui-label font-normal",kt?"text-primary":"text-foreground"),children:vo(vt,f)}),Y?s.jsx("span",{className:"ml-2 flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:xt}):null,Y?null:s.jsx("div",{className:"relative ml-1 flex h-4 min-w-4 flex-shrink-0 items-center justify-end",children:s.jsx("span",{className:Pe("whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",as?"opacity-0":Me),children:xt})}),Qe>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(D,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Qe})]}):null]})})}),ee?null:s.jsx(Ft,{side:"right",sideOffset:8,className:"max-w-xs text-left",children:s.jsxs("div",{className:"flex flex-col gap-1 text-left text-xs",children:[s.jsxs("div",{className:Pe("flex items-center gap-3 text-left text-muted-foreground",re?.projectLabel?"justify-between":"justify-start"),children:[re?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:re.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:jt})]}),re?.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(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:re.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:Un,onPointerUp:Es,onPointerCancel:Es,onMouseDown:Ds,onClick:Ue=>Ss(Ue),onDoubleClick:Ue=>{Ue.stopPropagation(),j(ye.id,vt)},className:Pe("flex min-w-0 flex-1 cursor-pointer flex-col gap-0 overflow-hidden rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none transition-[padding]",fe&&"bg-interactive-hover/70",Y?ee?pe:ue:pe),children:[s.jsxs("div",{className:Pe("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Pe("block min-w-0 flex-1 truncate typography-ui-label font-normal",kt?"text-primary":"text-foreground"),children:vo(vt,f)}),Qe>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(D,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Qe})]}):null]}),Ne?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:Pe("flex min-w-0 items-center gap-1.5 overflow-hidden",Kt&&St?"pl-4":""),children:[s.jsx("span",{className:"flex-shrink-0",children:jt}),ge?s.jsx("span",{className:"truncate",children:re?.projectLabel}):null,F?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:re?.branchLabel})]}):null]})})]})}),hn&&!ne?s.jsx("div",{className:Pe("absolute top-1/2 -translate-y-1/2 z-10",Ne?"right-0":"right-[30px]"),children:hn}):null,s.jsxs("div",{className:Pe("absolute right-0 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",as||Y&&!ee?"opacity-100":Pe("opacity-0",Fe)),children:[Ae?s.jsx(E2,{archiveLabel:e("sessions.sidebar.bulkActions.archive"),deleteLabel:e("sessions.sidebar.bulkActions.delete"),buttonSizeClass:Ne&&!Y?"h-4 w-4":"h-6 w-6",iconSizeClass:Ne&&!Y?"h-2.5 w-2.5":"h-3.5 w-3.5",onPointerDown:dt,onMouseDown:It,onArchive:Ht,onDelete:ht}):null,he?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",Ne&&!Y?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:hs,onMouseDown:ps,onClick:js,onKeyDown:Ue=>Ue.stopPropagation(),children:s.jsx(D,{name:"external-link",className:Pe(Ne&&!Y?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Ft,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(sn,{open:rs,onOpenChange:Gs,onOpenChangeComplete:an,children:[s.jsx(en,{asChild:!0,children:s.jsx("button",{type:"button",className:Pe("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",Ne&&!Y?as?"h-4 w-4 opacity-100":Pe("h-4 w-4 opacity-0",Fe):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:we,onMouseDown:tt,onClick:Os,onKeyDown:Ue=>Ue.stopPropagation(),children:s.jsx(D,{name:"more-2",className:Pe(Ne&&!Y?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),Hn]})]})]}),Xn]})}),St&&ns?n.children.map(Ue=>{const os=ke?ke(Ue):{subtreeContainsActive:me,subtreeContainsEditing:Se,menuOpenSessionId:te,nodeStructureKey:""};return H(Ue,r+1,Re??o,a,c,void 0,ae,os)}):null,s.jsx($s,{open:Je,onOpenChange:rt,children:s.jsxs(_s,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Hs,{children:[s.jsx(Us,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(on,{children:Qt===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:Qt}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:Qt})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:bt,onChange:Ue=>yt(Ue.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(ir,{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),$t(bt)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),Bt?s.jsx(T2,{session:Le,open:Lt,onOpenChange:Vt}):null]},ye.id)}const mf=t=>cs(t.session.directory??null),F2=(t,e)=>(t?.projectLabel??null)===(e?.projectLabel??null)&&(t?.branchLabel??null)===(e?.branchLabel??null),L2=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??L2(t),$i=(t,e,n)=>e?n.has(t.node.session.id)?!0:zr(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},xh=(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(xh(t.children[a],e.children[a],n,r))return!0;return!1},O2=(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}`)},B2=(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||mf(t.node)!==mf(e.node)||!F2(t.secondaryMeta,e.secondaryMeta)||t.liveSessionById!==e.liveSessionById&&xh(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&&O2(t,e)||t.currentSessionId!==e.currentSessionId&&($i(t,t.currentSessionId,t.subtreeContainsActive)||$i(e,e.currentSessionId,e.subtreeContainsActive))||t.editingId!==e.editingId&&($i(t,t.editingId,t.subtreeContainsEditing)||$i(e,e.editingId,e.subtreeContainsEditing))||t.editTitle!==e.editTitle&&($i(t,t.editingId,t.subtreeContainsEditing)||$i(e,e.editingId,e.subtreeContainsEditing))||t.copiedSessionId!==e.copiedSessionId&&(zr(t.node,t.copiedSessionId)||zr(e.node,e.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=ta(t),r=ta(e);if(zr(t.node,n)||zr(e.node,r))return!1}if(t.renamingFolderId!==e.renamingFolderId){const n=ta(t),r=ta(e);if(zr(t.node,n)||zr(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},V2=i.memo(M2,B2);function _2(t){return t.stopPropagation()}function $2(t){const e=mt.c(71),{t:n}=Nt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,u,m,f,g,b,p,x,y,h;if(e[0]!==o||e[1]!==n||e[2]!==r){const E=n("sessions.sidebar.session.untitled");f=$s,y=!!r,e[13]!==o?(h=ne=>{ne||o(null)},e[13]=o,e[14]=h):h=e[14],m=_s,p=!1,x="max-w-sm gap-5",u=Hs;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?(b=s.jsx(Us,{children:Z}),e[18]=Z,e[19]=b):b=e[19],d=on,g=r&&r.descendantCount>0?r.archivedBucket?r.descendantCount===1?n("sessions.sidebar.dialogs.deleteSession.withOneSubtask",{sessionTitle:r.session.title||E,count:r.descendantCount}):n("sessions.sidebar.dialogs.deleteSession.withManySubtasks",{sessionTitle:r.session.title||E,count:r.descendantCount}):r.descendantCount===1?n("sessions.sidebar.dialogs.archiveSession.withOneSubtask",{sessionTitle:r.session.title||E,count:r.descendantCount}):n("sessions.sidebar.dialogs.archiveSession.withManySubtasks",{sessionTitle:r.session.title||E,count:r.descendantCount}):r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.single",{sessionTitle:r?.session.title||E}):n("sessions.sidebar.dialogs.archiveSession.single",{sessionTitle:r?.session.title||E}),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]=b,e[9]=p,e[10]=x,e[11]=y,e[12]=h}else d=e[3],u=e[4],m=e[5],f=e[6],g=e[7],b=e[8],p=e[9],x=e[10],y=e[11],h=e[12];let C;e[20]!==d||e[21]!==g?(C=s.jsx(d,{children:g}),e[20]=d,e[21]=g,e[22]=C):C=e[22];let w;e[23]!==u||e[24]!==b||e[25]!==C?(w=s.jsxs(u,{children:[b,C]}),e[23]=u,e[24]=b,e[25]=C,e[26]=w):w=e[26];let S;e[27]!==c||e[28]!==a?(S=()=>c(!a),e[27]=c,e[28]=a,e[29]=S):S=e[29];const j=!a;let k;e[30]!==a?(k=a?s.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(D,{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 A;e[34]!==k||e[35]!==v||e[36]!==S||e[37]!==j?(A=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]=A):A=e[38];let I;e[39]!==o?(I=()=>o(null),e[39]=o,e[40]=I):I=e[40];let N;e[41]!==n?(N=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=N):N=e[42];let O;e[43]!==I||e[44]!==N?(O=s.jsx("button",{type:"button",onClick:I,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:N}),e[43]=I,e[44]=N,e[45]=O):O=e[45];let P;e[46]!==l?(P=()=>{l()},e[46]=l,e[47]=P):P=e[47];let T;e[48]!==n||e[49]!==r?.archivedBucket?(T=r?.archivedBucket?n("sessions.sidebar.bulkActions.delete"):n("sessions.sidebar.bulkActions.archive"),e[48]=n,e[49]=r?.archivedBucket,e[50]=T):T=e[50];let L;e[51]!==P||e[52]!==T?(L=s.jsx("button",{type:"button",onClick:P,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:T}),e[51]=P,e[52]=T,e[53]=L):L=e[53];let R;e[54]!==O||e[55]!==L?(R=s.jsxs("div",{className:"flex items-center gap-2",children:[O,L]}),e[54]=O,e[55]=L,e[56]=R):R=e[56];let B;e[57]!==A||e[58]!==R?(B=s.jsxs(ir,{className:"w-full sm:items-center sm:justify-between",children:[A,R]}),e[57]=A,e[58]=R,e[59]=B):B=e[59];let V;e[60]!==m||e[61]!==p||e[62]!==B||e[63]!==x||e[64]!==w?(V=s.jsxs(m,{showCloseButton:p,className:x,children:[w,B]}),e[60]=m,e[61]=p,e[62]=B,e[63]=x,e[64]=w,e[65]=V):V=e[65];let _;return e[66]!==f||e[67]!==V||e[68]!==y||e[69]!==h?(_=s.jsx(f,{open:y,onOpenChange:h,children:V}),e[66]=f,e[67]=V,e[68]=y,e[69]=h,e[70]=_):_=e[70],_}function z2(t){const e=mt.c(57),{t:n}=Nt(),{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 b=g,p=!!r;let x;e[8]!==o?(x=_=>{_||o(null)},e[8]=o,e[9]=x):x=e[9];let y;e[10]!==f?(y=s.jsx(Us,{children:f}),e[10]=f,e[11]=y):y=e[11];let h;e[12]!==b?(h=s.jsx(on,{children:b}),e[12]=b,e[13]=h):h=e[13];let C;e[14]!==y||e[15]!==h?(C=s.jsxs(Hs,{children:[y,h]}),e[14]=y,e[15]=h,e[16]=C):C=e[16];let w;e[17]!==c||e[18]!==a?(w=()=>c(!a),e[17]=c,e[18]=a,e[19]=w):w=e[19];const S=!a;let j;e[20]!==a?(j=a?s.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(D,{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 A;e[29]!==o?(A=()=>o(null),e[29]=o,e[30]=A):A=e[30];let I;e[31]!==n?(I=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=I):I=e[32];let N;e[33]!==A||e[34]!==I?(N=s.jsx("button",{type:"button",onClick:A,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:I}),e[33]=A,e[34]=I,e[35]=N):N=e[35];let O;e[36]!==l?(O=()=>{l()},e[36]=l,e[37]=O):O=e[37];let P;e[38]!==d||e[39]!==n?(P=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=P):P=e[40];let T;e[41]!==O||e[42]!==P?(T=s.jsx("button",{type:"button",onClick:O,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:P}),e[41]=O,e[42]=P,e[43]=T):T=e[43];let L;e[44]!==N||e[45]!==T?(L=s.jsxs("div",{className:"flex items-center gap-2",children:[N,T]}),e[44]=N,e[45]=T,e[46]=L):L=e[46];let R;e[47]!==v||e[48]!==L?(R=s.jsxs(ir,{className:"w-full sm:items-center sm:justify-between",children:[v,L]}),e[47]=v,e[48]=L,e[49]=R):R=e[49];let B;e[50]!==R||e[51]!==C?(B=s.jsxs(_s,{showCloseButton:!1,className:"max-w-sm gap-5",children:[C,R]}),e[50]=R,e[51]=C,e[52]=B):B=e[52];let V;return e[53]!==p||e[54]!==B||e[55]!==x?(V=s.jsx($s,{open:p,onOpenChange:x,children:B}),e[53]=p,e[54]=B,e[55]=x,e[56]=V):V=e[56],V}function W2(t){const e=mt.c(36),{t:n}=Nt(),{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(Us,{children:d}),e[4]=d,e[5]=u):u=e[5];let m;e[6]!==n||e[7]!==r?(m=r&&(r.subFolderCount>0||r.sessionCount>0)?r.subFolderCount>0?r.subFolderCount===1?n("sessions.sidebar.dialogs.deleteFolder.withOneSubfolder",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withManySubfolders",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withContentsNoSubfolders",{folderName:r.folderName}):n("sessions.sidebar.dialogs.deleteFolder.single",{folderName:r?.folderName??""}),e[6]=n,e[7]=r,e[8]=m):m=e[8];let f;e[9]!==m?(f=s.jsx(on,{children:m}),e[9]=m,e[10]=f):f=e[10];let g;e[11]!==u||e[12]!==f?(g=s.jsxs(Hs,{children:[u,f]}),e[11]=u,e[12]=f,e[13]=g):g=e[13];let b;e[14]!==o?(b=()=>o(null),e[14]=o,e[15]=b):b=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]!==b||e[19]!==p?(x=s.jsx("button",{type:"button",onClick:b,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:p}),e[18]=b,e[19]=p,e[20]=x):x=e[20];let y;e[21]!==n?(y=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=y):y=e[22];let h;e[23]!==a||e[24]!==y?(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:y}),e[23]=a,e[24]=y,e[25]=h):h=e[25];let C;e[26]!==h||e[27]!==x?(C=s.jsxs(ir,{children:[x,h]}),e[26]=h,e[27]=x,e[28]=C):C=e[28];let w;e[29]!==C||e[30]!==g?(w=s.jsxs(_s,{showCloseButton:!1,className:"max-w-sm gap-5",children:[g,C]}),e[29]=C,e[30]=g,e[31]=w):w=e[31];let S;return e[32]!==c||e[33]!==l||e[34]!==w?(S=s.jsx($s,{open:c,onOpenChange:l,children:w}),e[32]=c,e[33]=l,e[34]=w,e[35]=S):S=e[35],S}const U2=t=>{const e=mt.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}=Nt(),b=!!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 y;e[3]!==n||e[4]!==g?(y=g("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=g,e[5]=y):y=e[5];let h;e[6]!==y?(h=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:y}),e[6]=y,e[7]=h):h=e[7];let C;e[8]!==b||e[9]!==u||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==g?(C=b?s.jsxs(sn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(en,{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(D,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:g("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(tn,{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(B=>s.jsx(bs,{onClick:()=>c(B.id),children:s.jsx("span",{className:"flex-1 truncate",children:B.name})},B.id)),s.jsx(Rr,{}),s.jsxs(bs,{onClick:l,children:[s.jsx(D,{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(D,{name:"close",className:"mr-1 h-4 w-4"}),g("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=b,e[9]=u,e[10]=l,e[11]=c,e[12]=d,e[13]=o,e[14]=g,e[15]=C):C=e[15];let w;e[16]===Symbol.for("react.memo_cache_sentinel")?(w=Pe("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),e[16]=w):w=e[16];let S;e[17]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(D,{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(Mt,{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(Ft,{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(Et,{children:[j,k]}),e[23]=j,e[24]=k,e[25]=v):v=e[25];let A;e[26]!==g?(A=g("sessions.sidebar.header.actions.exitSelection"),e[26]=g,e[27]=A):A=e[27];let I;e[28]===Symbol.for("react.memo_cache_sentinel")?(I=s.jsx(D,{name:"close",className:"h-4 w-4"}),e[28]=I):I=e[28];let N;e[29]!==f||e[30]!==A?(N=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:f,className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":A,children:I})}),e[29]=f,e[30]=A,e[31]=N):N=e[31];let O;e[32]!==g?(O=g("sessions.sidebar.header.actions.exitSelection"),e[32]=g,e[33]=O):O=e[33];let P;e[34]!==O?(P=s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:O})}),e[34]=O,e[35]=P):P=e[35];let T;e[36]!==N||e[37]!==P?(T=s.jsxs(Et,{children:[N,P]}),e[36]=N,e[37]=P,e[38]=T):T=e[38];let L;e[39]!==T||e[40]!==C||e[41]!==v?(L=s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[C,v,T]}),e[39]=T,e[40]=C,e[41]=v,e[42]=L):L=e[42];let R;return e[43]!==L||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,L]}),e[43]=L,e[44]=h,e[45]=R):R=e[45],R},H2=t=>{const{t:e}=Nt(),{isInlineEditing:n,showDeletionDialog:r,foldersMap:o,addSessionsToFolder:a,removeSessionsFromFolders:c,createFolderAndStartRename:l,archiveSessions:d,deleteSessions:u,setBulkDeleteConfirm:m}=t,f=Bn(P=>P.enabled),g=Bn(P=>P.selectedIds.size),b=g>0,p=Bn(P=>P.selectedIds),x=Bn(P=>P.scopeKey),y=i.useCallback(()=>{Bn.getState().toggleMode()},[]),h=i.useCallback(()=>{Bn.getState().disable()},[]),C=i.useMemo(()=>{if(!b||typeof document>"u")return!1;let P=!1,T=!1;for(const L of p){const R=document.querySelectorAll(`[data-session-row="${CSS.escape(L)}"]`);for(const B of R)B.getAttribute("data-session-archived")==="1"?T=!0:P=!0}return T&&!P},[b,p]),w=i.useMemo(()=>{if(x)return x;if(!b||typeof document>"u")return null;for(const P of p){const L=document.querySelector(`[data-session-row="${CSS.escape(P)}"]`)?.getAttribute("data-session-scope");if(L&&L.length>0)return L}return null},[b,p,x]),S=i.useMemo(()=>w?o[w]??[]:[],[o,w]),j=i.useMemo(()=>{if(!w||!b)return!1;const P=o[w]??[];for(const T of P)for(const L of T.sessionIds)if(p.has(L))return!0;return!1},[o,w,b,p]),k=i.useCallback(P=>{!w||!b||a(w,P,Array.from(p))},[a,p,w,b]),v=i.useCallback(()=>{if(!w||!b)return;const P=l(w);P&&a(w,P.id,Array.from(p))},[a,l,p,w,b]),A=i.useCallback(()=>{!w||!b||c(w,Array.from(p))},[c,p,w,b]),I=i.useCallback(async()=>{const P=Array.from(p);if(P.length!==0){if(C){const{deletedIds:T,failedIds:L}=await u(P);T.length>0&&ce.success(T.length===1?e("sessions.sidebar.bulkActions.deletedSingle",{count:T.length}):e("sessions.sidebar.bulkActions.deletedPlural",{count:T.length})),L.length>0&&ce.error(L.length===1?e("sessions.sidebar.bulkActions.failedDeleteSingle",{count:L.length}):e("sessions.sidebar.bulkActions.failedDeletePlural",{count:L.length}))}else{const{archivedIds:T,failedIds:L}=await d(P);T.length>0&&ce.success(T.length===1?e("sessions.sidebar.bulkActions.archivedSingle",{count:T.length}):e("sessions.sidebar.bulkActions.archivedPlural",{count:T.length})),L.length>0&&ce.error(L.length===1?e("sessions.sidebar.bulkActions.failedArchiveSingle",{count:L.length}):e("sessions.sidebar.bulkActions.failedArchivePlural",{count:L.length}))}Bn.getState().clear()}},[d,C,u,p,e]),N=i.useCallback(()=>{if(!b)return;const P=p.size;if(!r){I();return}m({sessionCount:P,archivedBucket:C})},[C,I,p,r,m,b]),O=i.useCallback(async()=>{m(null),await I()},[I]);return i.useEffect(()=>{if(!f)return;const P=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),T=L=>{if(n)return;const R=L.target;if(R&&(R.tagName==="INPUT"||R.tagName==="TEXTAREA"||R.isContentEditable))return;const B=P?L.metaKey:L.ctrlKey;if(L.key==="Escape"){L.preventDefault(),Bn.getState().disable();return}if(B&&L.key==="Backspace"){L.preventDefault(),N();return}if(B&&(L.key==="a"||L.key==="A")){const V=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(V.length===0)return;L.preventDefault();const E=Bn.getState().scopeKey??V[0]?.getAttribute("data-session-scope")??null,Z=Y=>E?Y.getAttribute("data-session-scope")===E:!0,ne=V.filter(Z).map(Y=>Y.getAttribute("data-session-row")).filter(Y=>typeof Y=="string"&&Y.length>0);if(ne.length===0)return;Bn.getState().replaceAll(ne,E||null)}};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[N,n,f]),{selectionModeEnabled:f,hasSelection:b,selectedIdsSize:g,bulkScopeIsArchived:C,derivedSelectionScope:w,bulkScopeFolders:S,bulkCanRemoveFromFolder:j,handleToggleSelectionMode:y,handleExitSelectionMode:h,handleBulkMoveToFolder:k,handleBulkCreateFolderAndMove:v,handleBulkRemoveFromFolder:A,handleBulkDelete:N,confirmBulkDelete:O}},G2=2880*60*1e3,K2=t=>!!t.parentID,q2=t=>!!t.time?.archived,ac=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},Y2=t=>[...t].sort((e,n)=>ac(n)-ac(e)),Q2=(t,e=Date.now())=>{const n=e-G2,r=t.filter(o=>q2(o)||K2(o)?!1:ac(o)>=n);return Y2(r)},sa="oc.sessions.projectCollapse",hf="oc.sessions.groupOrder",pf="oc.sessions.groupCollapse",gf="oc.sessions.activeSessionByProject",El="oc.sessions.expandedParents.v2",J2="oc.sessions.expandedParents",X2="oc.sessions.pinned",Z2=(t,e,n)=>{const r=new Set;for(const o of t){const a=cs(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=cs(a.path)?.toLowerCase();c&&r.add(c)}return r},ek=(t,e,n)=>{if(t.time?.archived)return!0;const r=cs(Tr(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},tk=5*6e4,xf=new Set,Ar=t=>{const e=i.useRef(t);return e.current=t,i.useCallback((...n)=>e.current(...n),[])},bf=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=Nt(),[c,l]=i.useState(!1),[d,u]=i.useState(""),m=i.useRef(null),f=i.useRef(null),g=i.useRef(new Set),[b,p]=i.useState(null),[x,y]=i.useState(""),[h,C]=i.useState(null),[w,S]=i.useState(new Set),j=i.useMemo(()=>Ni(),[]),[k,v]=i.useState(new Set),[A,I]=i.useState(new Map),[N,O]=i.useState(new Map),P=Ee(oe=>oe.isNewWorktreeDialogOpen),T=Ee(oe=>oe.setNewWorktreeDialogOpen),[L,R]=i.useState(!1),[B,V]=i.useState(null),[_,E]=i.useState(null),[Z,ne]=i.useState(""),[Y,H]=i.useState(null),[re,ae]=i.useState(null),[me,Se]=i.useState(null),te=ll(oe=>oe.ids),ke=ll(oe=>oe.setIds),Q=ll(oe=>oe.toggle),[ge,F]=i.useState(()=>{try{const oe=Ni().getItem(pf);if(!oe)return new Set;const lt=JSON.parse(oe);return new Set(Array.isArray(lt)?lt.filter(it=>typeof it=="string"):[])}catch{return new Set}}),[se,ee]=i.useState(()=>{try{const oe=Ni().getItem(hf);if(!oe)return new Map;const lt=JSON.parse(oe),it=new Map;return Object.entries(lt).forEach(([pt,zt])=>{Array.isArray(zt)&&it.set(pt,zt.filter(Is=>typeof Is=="string"))}),it}catch{return new Map}}),[Ne,De]=i.useState(()=>{try{const oe=Ni().getItem(gf);if(!oe)return new Map;const lt=JSON.parse(oe),it=new Map;return Object.entries(lt).forEach(([pt,zt])=>{typeof zt=="string"&&zt.length>0&&it.set(pt,zt)}),it}catch{return new Map}}),[Be,Fe]=i.useState(new Map),Me=i.useRef(new Map),he=i.useRef(0),Ae=Js(oe=>oe.homeDirectory),pe=Js(oe=>oe.currentDirectory),ue=Js(oe=>oe.setDirectory),U=ws(oe=>oe.projects),fe=ws(oe=>oe.activeProjectId),de=ws(oe=>oe.removeProject),G=ws(oe=>oe.setActiveProjectIdOnly),$=ws(oe=>oe.updateProjectMeta),ve=ws(oe=>oe.reorderProjects),be=Ee(oe=>oe.setActiveMainTab),z=Ee(oe=>oe.openContextPanelTab),xe=Ee(oe=>oe.setSettingsDialogOpen),je=Ee(oe=>oe.toggleHelpDialog),K=Ee(oe=>oe.setAboutDialogOpen),ye=Ee(oe=>oe.setSessionSwitcherOpen),Le=Ee(oe=>oe.setScheduledTasksDialogOpen),Re=Ee(oe=>oe.openMultiRunLauncher),X=Ee(oe=>oe.notifyOnSubtasks),M=Ee(oe=>oe.showDeletionDialog),le=Ee(oe=>oe.setShowDeletionDialog),ie=Ha(d,120),Oe=i.useMemo(()=>ie.trim().toLowerCase(),[ie]),Ge=Oe.length>0,He=Ln(oe=>oe.collapsedFolderIds),Je=Ln(oe=>oe.foldersMap),rt=Ln(oe=>oe.getFoldersForScope),bt=Ln(oe=>oe.createFolder),yt=Ln(oe=>oe.renameFolder),_e=Ln(oe=>oe.deleteFolder),Ye=Ln(oe=>oe.addSessionToFolder),nt=Ln(oe=>oe.addSessionsToFolder),wt=Ln(oe=>oe.removeSessionFromFolder),kt=Ln(oe=>oe.removeSessionsFromFolders),vt=Ln(oe=>oe.toggleFolderCollapse),St=Ln(oe=>oe.cleanupSessions),et=Ln(oe=>oe.getSessionFolderId);FS({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:f,sessionSearchContainerRef:m});const Ot=sm(),ns=Pc(),Wt=xc(),Ve=i.useMemo(()=>Gr(),[]),Ze=vr(oe=>oe.hasLoaded),_t=vr(oe=>oe.activeSessions),jt=vr(oe=>oe.archivedSessions),xt=ut(oe=>oe.currentSessionId),rs=ut(oe=>!!oe.newSessionDraft?.open),Gt=ut(oe=>oe.setCurrentSession),Ut=ut(oe=>oe.updateSessionTitle),as=ut(oe=>oe.shareSession),Bt=ut(oe=>oe.unshareSession),Lt=ut(oe=>oe.worktreeMetadata),Vt=ut(oe=>oe.availableWorktreesByProject),Kt=ut(oe=>oe.openNewSessionDraft),Xt=i.useCallback(oe=>{Kt(oe),Ve&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[Ve,Kt]),Qt=wo(_l(oe=>({checkForUpdates:oe.checkForUpdates,available:oe.available,runtimeType:oe.runtimeType,info:oe.info,downloading:oe.downloading,downloaded:oe.downloaded,progress:oe.progress,error:oe.error,downloadUpdate:oe.downloadUpdate,restartToUpdate:oe.restartToUpdate}))),vs=i.useMemo(()=>Z2(U,Vt,{includeWorktrees:!Ve}),[Vt,Ve,U]),Dt=i.useMemo(()=>{const oe=new Map(Wt.map(pt=>[pt.id,pt])),lt=_t.map(pt=>{const zt=oe.get(pt.id);return zt?zg(zt,pt):pt}),it=new Set(lt.map(pt=>pt.id));return Wt.forEach(pt=>{it.has(pt.id)||lt.push(pt)}),lt.filter(pt=>ek(pt,vs,{allowUnknownDirectory:!Ve,allowEmptyDirectorySet:!Ve}))},[_t,Ve,vs,Wt]),$t=i.useMemo(()=>Wt.map(oe=>{const lt=cs(oe.directory??null)??"";return`${oe.id}:${oe.title??""}:${oe.time?.archived?1:0}:${lt}`}).join("|"),[Wt]),Ct=i.useRef(Wt);i.useEffect(()=>{Ct.current=Wt},[$t,Wt]);const ds=i.useMemo(()=>new Map(Wt.map(oe=>[oe.id,oe])),[Wt]),qe=i.useMemo(()=>U.map(oe=>`${oe.id}:${cs(oe.path)??""}`).join("|"),[U]),at=i.useRef(!1);i.useEffect(()=>{at.current||(at.current=!0,Sa(Ct.current))},[]);const Qe=i.useRef("");i.useEffect(()=>{let oe=!1;const lt=async()=>{const it=ws.getState().projects;if(it.length===0)return;const pt=new Map,zt=[],Is=3;let Xs=0;const un=Array.from({length:Is},async()=>{for(;;){const Fn=Xs;if(Xs+=1,Fn>=it.length)return;const Sn=it[Fn],An=cs(Sn.path);if(An)try{if(!(wn.getState().directories.get(An)?.isGitRepo??await lm(An)))continue;const gi=await Ug({id:Sn.id,path:An});if(oe||gi.length===0)continue;pt.set(An,gi),zt.push(...gi)}catch{}}});await Promise.all(un),!oe&&ut.setState({availableWorktrees:zt,availableWorktreesByProject:pt})};if(Qe.current!==qe)return Qe.current=qe,lt(),()=>{oe=!0}},[qe]),i.useEffect(()=>{let oe=null;const lt=lh(it=>{it.type==="scheduled-task-ran"&&(oe&&clearTimeout(oe),oe=setTimeout(()=>{Sa(Ct.current)},500))});return()=>{oe&&clearTimeout(oe),lt()}},[]);const At=i.useMemo(()=>dr(),[]),{isTablet:Tt}=Er(),ts=t||Tt,{buildGroupSearchText:xs,filterSessionNodesForSearch:ks,buildGroupedSessions:Jt}=MS({homeDirectory:Ae,worktreeMetadata:Lt,pinnedSessionIds:te,gitBranches:Ot,isVSCode:Ve}),{scheduleCollapsedProjectsPersist:ls}=zS({isVSCode:Ve,hasLoadedGlobalSessions:Ze,safeStorage:j,keys:{sessionExpanded:El,sessionExpandedLegacy:J2,projectCollapse:sa,sessionPinned:X2,groupOrder:hf,projectActiveSession:gf,groupCollapse:pf},sessions:Dt,setPinnedSessionIds:ke,groupOrderByProject:se,activeSessionByProject:Ne,collapsedGroups:ge,setExpandedParents:S,setCollapsedProjects:v}),Ps=i.useMemo(()=>[...Dt].sort((oe,lt)=>Gi(oe,lt,te)),[Dt,te]),Ts=i.useMemo(()=>Ps.map(oe=>`${oe.id}:${oe.time?.updated??0}`).join("|"),[Ps]),hn=i.useRef(null),Gs=i.useMemo(()=>{const oe=hn.current;if(oe&&oe.signature===Ts)return oe.map;const lt=new Map(Ps.map((it,pt)=>[it.id,pt]));return hn.current={signature:Ts,map:lt},lt},[Ts,Ps]),an=i.useMemo(()=>{const oe=new Map;return Ps.forEach(lt=>{const it=lt.parentID;if(!it)return;const pt=oe.get(it)??[];pt.push(lt),oe.set(it,pt)}),oe.forEach(lt=>lt.sort((it,pt)=>Gi(it,pt,te))),oe},[Ps,te]),Rn=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")})]}),Os=i.useMemo(()=>U.find(oe=>oe.id===h)??null,[U,h]),we=i.useCallback(oe=>{h&&($(h,oe),C(null))},[h,$]),tt=i.useCallback(()=>{T(!0)},[T]),dt=i.useCallback(()=>{const oe=wo.getState();if(oe.available&&oe.info){R(!0);return}Qt.checkForUpdates().then(()=>{const{available:lt,error:it}=wo.getState();if(it){ce.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:it});return}if(!lt){ce.success(a("sessions.sidebar.updateCheck.latestVersion"));return}R(!0)})},[a,Qt]),It=i.useCallback(()=>{t&&ye(!1),xe(!0)},[t,ye,xe]),Ht=Qt.available&&(Qt.runtimeType==="desktop"||Qt.runtimeType==="web"),ht=ut(oe=>oe.deleteSession),hs=ut(oe=>oe.deleteSessions),ps=ut(oe=>oe.archiveSession),js=ut(oe=>oe.archiveSessions),{copiedSessionId:Ss,handleSessionSelect:Ds,handleSessionDoubleClick:Un,handleSaveEdit:Es,handleCancelEdit:En,handleShareSession:Hn,handleCopyShareUrl:Xn,handleUnshareSession:Ue,handleDeleteSession:os,confirmDeleteSession:fs}=LS({activeProjectId:fe,currentDirectory:pe,currentSessionId:xt,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:u,setIsSessionSearchOpen:l,setActiveProjectIdOnly:G,setDirectory:ue,setActiveMainTab:be,setSessionSwitcherOpen:ye,setCurrentSession:Gt,updateSessionTitle:Ut,shareSession:as,unshareSession:Bt,deleteSession:ht,deleteSessions:hs,archiveSession:ps,archiveSessions:js,childrenMap:an,showDeletionDialog:M,setDeleteSessionConfirm:H,deleteSessionConfirm:Y,setEditingId:p,setEditTitle:y,editingId:b,editTitle:x}),zs=i.useCallback(()=>{if(!re)return;const{scopeKey:oe,folderId:lt}=re;ae(null),_e(oe,lt)},[re,_e]),Ks=i.useCallback(()=>{Pr.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!xt)return;const lt=Dt.find(pt=>pt.id===xt)?.parentID;if(!lt)return;const it=[`project:active:${lt}`,`project:archived:${lt}`,`recent:active:${lt}`,`recent:archived:${lt}`];S(pt=>{if(it.every(Is=>pt.has(Is)))return pt;const zt=new Set(pt);it.forEach(Is=>zt.add(Is));try{j.setItem(El,JSON.stringify(Array.from(zt)))}catch{}return zt})},[xt,Dt,j]);const Ws=i.useCallback(oe=>{S(lt=>{const it=new Set(lt);it.has(oe)?it.delete(oe):it.add(oe);try{j.setItem(El,JSON.stringify(Array.from(it)))}catch{}return it})},[j]),pn=i.useCallback((oe,lt)=>{if(!oe)return null;lt&&He.has(lt)&&vt(lt);const it=bt(oe,a("sessions.sidebar.folder.newFolderName"),lt);return E(it.id),ne(it.name),it},[He,vt,bt,a]),Ns=Ar(Ds),qr=Ar(Un),Gn=Ar(Es),fr=Ar(En),Kn=Ar(Hn),gs=Ar(Xn),Ms=Ar(Ue),jr=Ar(os),jn=Ar(pn),ln=i.useCallback((oe,lt)=>{O(it=>{const pt=new Map(it);return pt.set(oe,lt+7),pt})},[]),Zn=i.useCallback(oe=>{O(lt=>{if(!lt.has(oe))return lt;const it=new Map(lt);return it.delete(oe),it})},[]),Mr=i.useCallback(oe=>{O(lt=>{let it=!1;const pt=new Map(lt),zt=`${oe}:`;for(const Is of pt.keys())Is.startsWith(zt)&&(pt.delete(Is),it=!0);return it?pt:lt})},[]),Yr=i.useCallback(()=>{he.current=Date.now()+150,O(new Map),v(()=>{const oe=new Set(U.map(lt=>lt.id));try{j.setItem(sa,JSON.stringify(Array.from(oe)))}catch{}return Ve||ls(oe),oe})},[U,Ve,j,ls]),ui=i.useCallback(()=>{he.current=Date.now()+150,O(new Map),v(()=>{const oe=new Set;try{j.setItem(sa,JSON.stringify([]))}catch{}return Ve||ls(oe),oe})},[Ve,j,ls]),mr=i.useCallback(oe=>{he.current=Date.now()+150,Mr(oe),v(lt=>{const it=new Set(lt);it.has(oe)?it.delete(oe):it.add(oe);try{j.setItem(sa,JSON.stringify(Array.from(it)))}catch{}return Ve||ls(it),it})},[Ve,Mr,j,ls]),us=i.useMemo(()=>U.map(oe=>({...oe,normalizedPath:cs(oe.path)})).filter(oe=>!!oe.normalizedPath),[U]),cn=i.useMemo(()=>us.map(oe=>oe.normalizedPath),[us]),kn=i.useMemo(()=>{const oe=new Set;return us.forEach(lt=>{if(lt.normalizedPath&&oe.add(lt.normalizedPath),Ve)return;(Vt.get(lt.normalizedPath)??[]).forEach(pt=>{const zt=cs(pt.path);zt&&oe.add(zt)})}),[...oe].sort()},[Vt,Ve,us]),J=i.useRef(null);i.useEffect(()=>{const oe=new Set(kn),lt=J.current;if(J.current=oe,!lt){Ve&&kn.length>0&&Vd(kn,Ct.current);return}const it=kn.filter(pt=>!lt.has(pt));it.length!==0&&Vd(it,Ct.current)},[Ve,kn]);const{github:st}=Jn(),gt=Pi(oe=>oe.status),Pt=Pi(oe=>oe.hasChecked),Zt=Wg(cn),is=rr(oe=>oe.ensureEntry),ms=rr(oe=>oe.setParams),Fs=rr(oe=>oe.refreshTargets);WS({normalizedProjects:us,gitRepoStatus:Zt,setProjectRepoStatus:I,setProjectRootBranches:Fe});const qs=ut(oe=>oe.isLoading);YS({isSessionsLoading:qs,hasLoadedGlobalSessions:Ze,sessions:Dt,archivedSessions:jt,normalizedProjects:us,isVSCode:Ve,availableWorktreesByProject:Vt,cleanupSessions:St});const{getSessionsForProject:er,getArchivedSessionsForProject:qn}=US({isVSCode:Ve,sessions:Dt,archivedSessions:jt,availableWorktreesByProject:Vt,normalizedProjects:us});CS({normalizedProjects:us,sessions:Dt,archivedSessions:jt,availableWorktreesByProject:Vt,isVSCode:Ve,isSessionsLoading:qs,foldersMap:Je,createFolder:bt,addSessionToFolder:Ye,cleanupSessions:St});const Fr=i.useRef(!1);fe&&A.has(fe)&&(Fr.current=!!A.get(fe));const{projectSections:Bs,groupSearchDataByGroup:Lr,sectionsForRender:gn,searchMatchCount:tr}=IS({normalizedProjects:us,getSessionsForProject:er,getArchivedSessionsForProject:qn,availableWorktreesByProject:Vt,projectRepoStatus:A,projectRootBranches:Be,lastRepoStatus:Fr.current,buildGroupedSessions:Jt,hasSessionSearchQuery:Ge,normalizedSessionSearchQuery:Oe,filterSessionNodesForSearch:ks,buildGroupSearchText:xs,foldersMap:Je}),xn=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")})]});TS({projectSections:Bs,activeProjectId:fe,activeSessionByProject:Ne,setActiveSessionByProject:De,currentSessionId:xt,handleSessionSelect:Ds,newSessionDraftOpen:rs,mobileVariant:t,openNewSessionDraft:Kt,setActiveMainTab:be,setSessionSwitcherOpen:ye});const{getOrderedGroups:Mn}=RS(se),bn=i.useRef(!1);i.useEffect(()=>{if(bn.current||Bs.length===0)return;const oe=Bs.flatMap(lt=>lt.groups.filter(it=>it.isArchivedBucket).map(it=>`${lt.project.id}:${it.id}`));oe.length>0&&F(lt=>new Set([...lt,...oe])),bn.current=!0},[Bs]);const or=i.useMemo(()=>{const oe=new Map,lt=new Map;return Bs.forEach(it=>{const pt=Sm(it.project.label?.trim()||Ri(it.project.normalizedPath,Ae)||it.project.normalizedPath);it.groups.forEach(zt=>{const Is=zt.branch&&zt.branch!=="HEAD"&&zt.branch!==pt?zt.branch:null,Xs={projectLabel:pt,branchLabel:Is},un=Fn=>{Fn.forEach(Sn=>{const An=it.project.normalizedPath.length,hi=lt.get(Sn.session.id)??-1;An<hi||(oe.set(Sn.session.id,{node:Sn,projectId:it.project.id,groupDirectory:zt.directory,secondaryMeta:Xs}),lt.set(Sn.session.id,An),Sn.children.length>0&&un(Sn.children))})};un(zt.sessions)})}),oe},[Bs,Ae]),Cn=Dr(oe=>oe.showRecentSection),Sr=Dr(oe=>oe.showArchivedSessions),Or=i.useMemo(()=>!Cn||Ve?[]:Q2(Dt).sort((oe,lt)=>Gi(oe,lt,te)),[Ve,te,Dt,Cn]),Nr=i.useMemo(()=>{if(Ve||!Cn)return[];const oe=Or,lt=pt=>{const zt=or.get(pt.id),Is=cs(pt.directory??null),Xs=zt?.node??{session:pt,children:[],worktree:null},Fn=(Ge?ks([Xs],Oe):[Xs])[0];if(!Fn)return null;const Sn=zt?.secondaryMeta?{projectLabel:zt.secondaryMeta.projectLabel,branchLabel:Ve?null:zt.secondaryMeta.branchLabel}:null;return{node:Fn,projectId:zt?.projectId??null,groupDirectory:zt?.groupDirectory??Is,secondaryMeta:Sn}},it=oe.map(lt).filter(pt=>pt!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:it}]},[Or,ks,Ge,Ve,Oe,or,Cn,a]),Ei=i.useMemo(()=>Nr.some(oe=>oe.items.length>0),[Nr]),fi=i.useMemo(()=>new Set(Or.map(oe=>oe.id)),[Or]),Mi=i.useMemo(()=>[...fi],[fi]);Wj({currentSessionId:xt,sortedSessions:Ps,recentSessionIds:Mi,ensureSessionRenderable:ns.ensureSessionRenderable});const nn=i.useMemo(()=>Sr?gn:gn.map(oe=>({...oe,groups:oe.groups.filter(lt=>!lt.isArchivedBucket)})),[gn,Sr]),hr=i.useMemo(()=>{const oe=new Set;return nn.forEach(lt=>{lt.groups.forEach(it=>{const pt=cs(it.directory??null),zt=it.branch?.trim()||Ot.get(pt||"")?.trim();!pt||!zt||oe.add(No(pt,zt))})}),[...oe]},[Ot,nn]),Ys=Aw(hr);i.useEffect(()=>{if(!Pt||!gt?.connected||!st)return;const oe=[],lt=Date.now();if(nn.forEach(pt=>{k.has(pt.project.id)||pt.groups.forEach(zt=>{const Is=cs(zt.directory??null),Xs=zt.branch?.trim()||Ot.get(Is||"")?.trim();if(!Is||!Xs)return;const un=No(Is,Xs),Fn=rr.getState().entries[un],Sn=!!Fn?.status?.pr,An=`${Is}::${Xs}`,hi=Math.max(Fn?.lastRefreshAt??0,Fn?.lastDiscoveryPollAt??0),pi=!!(Fn?.isInitialStatusResolved&&!Sn&&(!g.current.has(An)||lt-hi>=tk));(!Fn||!Fn.isInitialStatusResolved||pi)&&(pi&&g.current.add(An),oe.push({directory:Is,branch:Xs}))})}),oe.length===0)return;const it=new Map;oe.forEach(pt=>{const zt=No(pt.directory,pt.branch,pt.remoteName??null);it.has(zt)||it.set(zt,pt)}),it.forEach((pt,zt)=>{is(zt),ms(zt,{directory:pt.directory,branch:pt.branch,remoteName:pt.remoteName??null,canShow:!0,github:st,githubAuthChecked:Pt,githubConnected:gt.connected})}),Fs([...it.values()],{silent:!0,markInitialResolved:!0})},[k,is,st,Pt,gt?.connected,Ot,Fs,nn,ms]);const co=t?"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Br="h-4.5 w-4.5",ar=ZS({isDesktopShellRuntime:At,projectSections:Bs,projectHeaderSentinelRefs:Me}),kr=Ar((oe,lt=0,it,pt,zt=!1,Is,Xs="project",un)=>s.jsx(V2,{node:oe,depth:lt,groupDirectory:it,projectId:pt,archivedBucket:zt,currentSessionId:xt,pinnedSessionIds:te,expandedParents:w,hasSessionSearchQuery:Ge,normalizedSessionSearchQuery:Oe,notifyOnSubtasks:X,editingId:b,setEditingId:p,editTitle:x,setEditTitle:y,handleSaveEdit:Gn,handleCancelEdit:fr,toggleParent:Ws,handleSessionSelect:Ns,handleSessionDoubleClick:qr,togglePinnedSession:Q,handleShareSession:Kn,copiedSessionId:Ss,handleCopyShareUrl:gs,handleUnshareSession:Ms,openSidebarMenuKey:B,setOpenSidebarMenuKey:V,renamingFolderId:_,getFoldersForScope:rt,getSessionFolderId:et,removeSessionFromFolder:wt,addSessionToFolder:Ye,createFolderAndStartRename:jn,openContextPanelTab:z,handleDeleteSession:jr,mobileVariant:t,alwaysShowActions:ts,renderSessionNode:kr,secondaryMeta:Is,renderContext:Xs,subtreeContainsActive:un?.subtreeContainsActive??xf,subtreeContainsEditing:un?.subtreeContainsEditing??xf,menuOpenSessionId:un?.menuOpenSessionId??null,nodeStructureKey:un?.nodeStructureKey??"",childRenderExtrasFor:un?.childRenderExtrasFor,liveSessionById:ds})),dn=i.useCallback(oe=>{Zn(oe),F(lt=>{const it=new Set(lt);return it.has(oe)?it.delete(oe):it.add(oe),it})},[Zn]),lr=i.useMemo(()=>{const oe=new Map;for(const[lt,it]of Ys)oe.set(lt,{visualState:it.visualState,number:it.number,url:it.url,state:it.prState,draft:it.draft,title:it.title,base:it.base,head:it.head,checks:it.checks,canMerge:it.canMerge,mergeableState:it.mergeableState,repo:it.repo});return oe},[Ys]),Fi=i.useCallback((oe,lt,it,pt,zt,Is,Xs)=>s.jsx(IN,{group:oe,groupKey:lt,projectId:it,hideGroupLabel:pt,compactBodyPadding:Is,hasSessionSearchQuery:Ge,normalizedSessionSearchQuery:Oe,groupSearchDataByGroup:Lr,visibleSessionCount:N.get(lt),collapsedGroups:ge,hideDirectoryControls:r,collapsedFolderIds:He,toggleFolderCollapse:vt,renameFolder:yt,deleteFolder:_e,showDeletionDialog:M,setDeleteFolderConfirm:ae,renderSessionNode:kr,projectRepoStatus:A,lastRepoStatus:Fr.current,showMoreGroupSessions:ln,resetGroupSessionLimit:Zn,mobileVariant:t,alwaysShowActions:ts,activeProjectId:fe,setActiveProjectIdOnly:G,setActiveMainTab:be,setSessionSwitcherOpen:ye,openNewSessionDraft:Xt,addSessionToFolder:Ye,createFolderAndStartRename:jn,renamingFolderId:_,renameFolderDraft:Z,setRenameFolderDraft:ne,setRenamingFolderId:E,pinnedSessionIds:te,expandedParents:w,sessionOrderIndex:Gs,currentSessionId:xt,editingId:b,editTitle:x,openSidebarMenuKey:B,liveSessionById:ds,prVisualStateByDirectoryBranch:lr,onToggleCollapsedGroup:dn,dragHandleProps:zt,scrollContainerRef:Xs}),[Ge,Oe,Lr,N,ge,r,He,vt,yt,_e,M,kr,A,ln,Zn,t,ts,fe,G,be,ye,Xt,Ye,jn,_,Z,te,w,Gs,xt,b,x,B,ds,lr,dn]),Li=!Ve&&Cn&&!Ge?s.jsx(BN,{sections:Nr,renderSessionNode:kr,currentSessionId:xt,editingId:b,openSidebarMenuKey:B,variant:"section"}):null,Vr=!!(_||b||h),{selectionModeEnabled:mi,hasSelection:rn,selectedIdsSize:Oi,bulkScopeIsArchived:uo,derivedSelectionScope:fo,bulkScopeFolders:q,bulkCanRemoveFromFolder:Ce,handleToggleSelectionMode:Te,handleExitSelectionMode:ze,handleBulkMoveToFolder:ft,handleBulkCreateFolderAndMove:Rt,handleBulkRemoveFromFolder:qt,handleBulkDelete:Yt,confirmBulkDelete:ys}=H2({isInlineEditing:Vr,showDeletionDialog:M,foldersMap:Je,addSessionsToFolder:nt,removeSessionsFromFolders:kt,createFolderAndStartRename:pn,archiveSessions:js,deleteSessions:hs,setBulkDeleteConfirm:Se}),pr=i.useCallback(()=>{be("chat"),t&&ye(!1),Re()},[t,Re,be,ye]),Cr=i.useCallback(()=>{be("chat"),t&&ye(!1),Kt()},[t,Kt,be,ye]);return s.jsxs("div",{ref:m,className:Pe("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(PN,{hideDirectoryControls:r,showRecentControls:!Ve,handleOpenDirectoryDialog:Ks,openNewSessionDraft:Cr,canOpenMultiRun:U.length>0,openMultiRunLauncher:pr,headerActionIconClass:Br,headerActionButtonClass:co,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:f,sessionSearchQuery:d,setSessionSearchQuery:u,hasSessionSearchQuery:Ge,searchMatchCount:tr,collapseAllProjects:Yr,expandAllProjects:ui,openScheduledTasksDialog:()=>Le(!0),selectionModeEnabled:mi,onToggleSelectionMode:Te}),s.jsx(GN,{topContent:Li,hasSharedSessions:Ei,sectionsForRender:nn,projectSections:Bs,activeProjectId:fe,showOnlyMainWorkspace:o,hasSessionSearchQuery:Ge,emptyState:Rn,searchEmptyState:xn,renderGroupSessions:Fi,homeDirectory:Ae,collapsedProjects:k,hideDirectoryControls:r,projectRepoStatus:A,isDesktopShellRuntime:At,stuckProjectHeaders:ar,mobileVariant:t,alwaysShowActions:ts,toggleProject:mr,setActiveProjectIdOnly:G,setActiveMainTab:be,setSessionSwitcherOpen:ye,openNewSessionDraft:Xt,openNewWorktreeDialog:tt,openProjectEditDialog:C,removeProject:de,projectHeaderSentinelRefs:Me,reorderProjects:ve,getOrderedGroups:Mn,setGroupOrderByProject:ee,openSidebarMenuKey:B,setOpenSidebarMenuKey:V,isInlineEditing:Vr}),mi&&rn?s.jsx(U2,{selectedCount:Oi,scopeKey:fo,scopeFolders:q,archivedBucket:uo,onMoveToFolder:ft,onCreateFolderAndMove:Rt,onRemoveFromFolder:qt,canRemoveFromFolder:Ce,onDelete:Yt,onDone:ze}):null,s.jsx(VN,{onOpenSettings:It,onOpenShortcuts:je,onOpenAbout:()=>K(!0),onOpenUpdate:dt,showRuntimeButtons:!Ve,showUpdateButton:Ht}),s.jsx(gm,{open:L,onOpenChange:R,info:Qt.info,downloading:Qt.downloading,downloaded:Qt.downloaded,progress:Qt.progress,error:Qt.error,onDownload:Qt.downloadUpdate,onRestart:Qt.restartToUpdate,runtimeType:Qt.runtimeType}),Os?s.jsx(tN,{open:!!Os,onOpenChange:oe=>{oe||C(null)},projectId:Os.id,projectName:Os.label||Ri(Os.path,Ae),projectPath:Os.path,initialIcon:Os.icon,initialColor:Os.color,initialIconBackground:Os.iconBackground,onSave:we}):null,s.jsx(Gx,{open:P,onOpenChange:T,onWorktreeCreated:(oe,lt)=>{if(be("chat"),t&&ye(!1),lt?.sessionId){Gt(lt.sessionId,oe);return}Kt({directoryOverride:oe,preserveDirectoryOverride:!0})}}),s.jsx(NS,{}),s.jsx($2,{value:Y,setValue:H,showDeletionDialog:M,setShowDeletionDialog:le,onConfirm:fs}),s.jsx(W2,{value:re,setValue:ae,onConfirm:zs}),s.jsx(z2,{value:me,setValue:Se,showDeletionDialog:M,setShowDeletionDialog:le,onConfirm:ys})]})},wi=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,br=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},sk=()=>{const{t}=Nt(),[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),[b,p]=i.useState(!1),[x,y]=i.useState(!1),[h,C]=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=Hg,A=qg,I=ut(ue=>ue.deleteSessions),N=ut(ue=>ue.archiveSessions),O=Ee(ue=>ue.showDeletionDialog),P=Ee(ue=>ue.setShowDeletionDialog),T=Js(ue=>ue.currentDirectory),L=Js(ue=>ue.homeDirectory),R=Js(ue=>ue.isHomeReady),B=ws(ue=>ue.projects),V=ws(ue=>ue.activeProjectId),{isMobile:_,isTablet:E,hasTouchInput:Z}=Er(),ne=_||E||Z,Y=i.useMemo(()=>{const U=(V?B.find(fe=>fe.id===V)??null:null)?.path??T;return br(U)},[V,T,B]),H=i.useCallback(ue=>{const fe=br(ue.projectDirectory)||Y;return{id:(B.find(G=>br(G.path)===fe)??null)?.id??`path:${fe}`,path:fe}},[Y,B]),re=x&&h.size>0,ae=i.useMemo(()=>{const ue=a?.worktree;return ue&&typeof ue.branch=="string"&&ue.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:U})=>typeof U.branch=="string"&&U.branch.trim().length>0)},[a?.worktree,l]),me=a?.mode==="worktree",Se=me,te=b||!me||!ae,ke=b||!me;i.useEffect(()=>{r||!R||B.length>0||(o(!0),n(!0))},[r,R,B.length]);const Q=i.useCallback(ue=>{c({sessions:ue.sessions,dateLabel:ue.dateLabel,mode:ue.mode??"session",worktree:ue.worktree??null})},[]),ge=i.useCallback(()=>{c(null),d([]),m(!1),g(!1),p(!1),y(!1),C(new Set)},[]),F=i.useCallback(async ue=>{if(ue.sessions.length===0)return;if(ue.sessions.length===1){const G=ue.sessions[0];await v(G.id)?ce.success(t("sessions.sidebar.session.delete.success")):ce.error(t("sessions.sidebar.session.delete.error"));return}const U=ue.sessions.map(G=>G.id),{deletedIds:fe,failedIds:de}=await I(U);if(fe.length>0){const G=de.length>0?de.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:de.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:de.length}):ue.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:ue.dateLabel}):void 0;ce.success(fe.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:fe.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:fe.length}),{description:wi(G)})}de.length>0&&ce.error(de.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:de.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:de.length}),{description:wi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[v,I,t]);i.useEffect(()=>Pr.onDeleteRequest(ue=>{if(!O&&(ue.mode??"session")==="session"){F(ue);return}Q(ue)}),[Q,O,F]),i.useEffect(()=>Pr.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1),g(!1),y(!1),C(new Set);return}const ue=a.sessions.map(de=>{const G=w(de.id);return G?{session:de,metadata:G}:null}).filter(de=>!!de);d(ue),m(!1),y(!1),C(new Set);const U=new Map;if(a.worktree?.path&&U.set(br(a.worktree.path),a.worktree),ue.forEach(({metadata:de})=>{de.path&&U.set(br(de.path),de)}),U.size===0){y(!0);return}let fe=!1;return(async()=>{const de=new Map,G=new Set;await Promise.all(Array.from(U.entries()).map(async([$,ve])=>{try{const be=await Gg(ve.path);de.set($,be),be?.isDirty&&G.add($)}catch{ve.status&&(de.set($,ve.status),ve.status.isDirty&&G.add($))}})).catch($=>{console.warn("Failed to inspect worktree status before deletion:",$)}),!fe&&(C(G),y(!0),c($=>{if(!$?.worktree?.path)return $;const ve=br($.worktree.path),be=de.get(ve);if(!be)return $;const z=$.worktree.status;return z?.isDirty===be.isDirty&&z?.ahead===be.ahead&&z?.behind===be.behind&&z?.upstream===be.upstream?$:{...$,worktree:{...$.worktree,status:be}}}),d($=>$.map(ve=>{const be=br(ve.metadata.path),z=de.get(be);return z?{session:ve.session,metadata:{...ve.metadata,status:z}}:ve})))})(),()=>{fe=!0}},[a,w]),i.useEffect(()=>{ae||m(!1)},[ae]);const se=i.useCallback(async(ue,U)=>{const fe=u&&ae,de=H(ue),G=br(ue.path),$=br(de.path);try{await Kg(de,ue,{deleteRemoteBranch:fe,deleteLocalBranch:U});const ve=br(S?.directoryOverride);return S?.open&&G&&ve===G&&$&&(k(null),j({projectId:de.id,directoryOverride:$},{force:!0})),br(T)===G&&$&&Js.getState().setDirectory($,{showOverlay:!1}),!0}catch(ve){return ce.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:wi(ve instanceof Error?ve.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[ae,T,u,H,S?.directoryOverride,S?.open,k,j,t]),ee=i.useCallback((ue,U)=>{const fe=u&&ae;(async()=>{if(!await se(ue,U))return;const G=t(fe?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");ce.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:wi(G)})})()},[ae,u,se,t]),Ne=i.useCallback(async()=>{if(a){p(!0);try{const ue=Se,U=ue&&u,fe=ue&&f;if(a.sessions.length===0&&me&&a.worktree){ee(a.worktree,fe),ge();return}if(a.sessions.length===1){const de=a.sessions[0];if(!(me?await A(de.id):await v(de.id,{archiveWorktree:!1,deleteRemoteBranch:U,deleteLocalBranch:fe}))){ce.error(t(me?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),p(!1);return}const $=!me&&ue?t(U?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;ce.success(t(me?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:wi($),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const de=a.sessions.map(ve=>ve.id);let G=[],$=[];if(me){const ve=await N(de);G=ve.archivedIds,$=ve.failedIds}else{const ve=await I(de);G=ve.deletedIds,$=ve.failedIds}if(me&&a.worktree&&$.length===0&&ee(a.worktree,fe),G.length>0){const ve=!me&&ue?t(U?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,z=[$.length>0?me?$.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:$.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:$.length}):$.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:$.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:$.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,ve].filter(Boolean).join(" ");ce.success(me?G.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:G.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:G.length}):G.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:G.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:G.length}),{description:wi(z||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if($.length>0&&(ce.error(me?$.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:$.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:$.length}):$.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:$.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:$.length}),{description:wi(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),G.length===0)){p(!1);return}}me&&a.sessions.length===1&&a.worktree&&ee(a.worktree,fe),ge()}finally{p(!1)}}},[a,u,f,v,I,A,N,ge,Se,me,ee,t]),De=a?.worktree??l[0]?.metadata??null,Be=a?a.mode==="worktree"?a.sessions.length===0?t("sessions.sidebar.dialogs.worktreeDelete.descriptionNoLinked"):a.sessions.length===1?t("sessions.sidebar.dialogs.worktreeDelete.descriptionOneLinked",{count:a.sessions.length}):t("sessions.sidebar.dialogs.worktreeDelete.descriptionManyLinked",{count:a.sessions.length}):a.sessions.length===1?a.dateLabel?t("sessions.sidebar.dialogs.sessionDelete.descriptionOneWithDate",{dateLabel:a.dateLabel}):t("sessions.sidebar.dialogs.sessionDelete.descriptionOne"):a.dateLabel?t("sessions.sidebar.dialogs.sessionDelete.descriptionManyWithDate",{count:a.sessions.length,dateLabel:a.dateLabel}):t("sessions.sidebar.dialogs.sessionDelete.descriptionMany",{count:a.sessions.length}):"",Fe=a?s.jsxs("div",{className:Pe(me?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:Pe(me?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[me&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?t("sessions.sidebar.sessionDialogs.linkedSessionSingle"):t("sessions.sidebar.sessionDialogs.linkedSessionPlural")}),s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:a.sessions.length})]}),s.jsxs("ul",{className:Pe(me?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(ue=>s.jsxs("li",{className:Pe(me?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[s.jsx("span",{className:Pe(!me&&"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:Pe(me?"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})})]})]}),me?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(D,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:t("sessions.sidebar.sessionDialogs.worktree.label")}),De?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:De.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:De?Na(De.path,L):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),re&&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=me?ae?s.jsxs("button",{type:"button",onClick:()=>{te||m(ue=>!ue)},disabled:te,className:Pe("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(D,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(D,{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,he=me?s.jsxs("button",{type:"button",onClick:()=>{ke||g(ue=>!ue)},disabled:ke,className:Pe("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ke?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[f?s.jsx(D,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(D,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Ae=me?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:[he,Me]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{variant:"ghost",onClick:ge,disabled:b,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{variant:"destructive",onClick:Ne,disabled:b,children:t(b?"sessions.sidebar.sessionDialogs.actions.deleting":"sessions.sidebar.sessionDialogs.actions.deleteWorktree")})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>P(!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(D,{name:"checkbox-blank",className:"size-4"}):s.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),t("sessions.sidebar.dialogs.neverAsk")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{variant:"ghost",onClick:ge,disabled:b,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx($e,{variant:"destructive",onClick:Ne,disabled:b,children:b?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),pe=me?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:[ne?s.jsx($a,{open:!!a,onClose:()=>{b||ge()},title:pe,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Ae}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[Be&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Be}),Fe]})}):s.jsx($s,{open:!!a,onOpenChange:ue=>{if(!ue){if(b)return;ge()}},children:s.jsxs(_s,{className:Pe(me?"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(Hs,{children:[s.jsxs(Us,{className:Pe(me&&"flex items-center gap-2"),children:[me&&s.jsx(D,{name:"delete-bin",className:"h-5 w-5"}),pe]}),Be&&s.jsx(on,{children:Be})]}),s.jsx("div",{className:Pe(me&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:Fe}),s.jsx(ir,{className:"mt-2 gap-2 pt-1 pb-1",children:Ae})]})}),s.jsx(Kx,{open:e,onOpenChange:n})]})},lc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),nk=(t,e)=>{const n=lc(t),r=lc(e);return`${n}-${r}`.substring(0,60)},yf=(t,e)=>`${t}/${e}`,rk=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},wf=(t,e)=>{const n=rk(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};sx(t.id,n),ut.getState().markSessionAsOpenChamberCreated(t.id),vr.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},ik=()=>{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=Js.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},Ml=ro()(Pf(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=ik();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,m=await lm(d)&&e.isolateRuns!==!1,f=lc(n),g=m?await Ua(d):void 0,b=m?await Yg(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 I of j.models){const N=`${I.providerID}:${I.modelID}`;v.set(N,(v.get(N)||0)+1)}const A=new Map;for(const I of j.models){const N=`${I.providerID}:${I.modelID}`,O=v.get(N)||1,P=(A.get(N)||0)+1;A.set(N,P);const T=nk(I.providerID,I.modelID),L=r.length>1?`g${S+1}`:void 0,R=O>1?yf(f,`${T}/${P}`):yf(f,T),B=L?`${L}/${R}`:R,V=h2({groupSlug:f,runGroup:L,providerID:I.providerID,modelID:I.modelID,index:O>1?P:void 0});try{if(!m){const ne=await Vn.withDirectory(d,()=>Vn.createSession({title:V}));wf(ne,d),p.push({sessionId:ne.id,worktreePath:d,providerID:I.providerID,modelID:I.modelID,variant:I.variant,prompt:k});continue}const _=await Qg(l,{preferredName:B,mode:"new",branchName:B,worktreeName:B,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:x,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:b}),E={..._,createdFromBranch:g,kind:"standard"};await Jg(l)&&await Xg(_.path);const Z=await Vn.withDirectory(_.path,()=>Vn.createSession({title:V}));wf(Z,_.path),ut.getState().setWorktreeMetadata(Z.id,E),p.push({sessionId:Z.id,worktreePath:_.path,providerID:I.providerID,modelID:I.modelID,variant:I.variant,prompt:k})}catch(_){console.warn("[MultiRun] Failed to create session:",_)}}}const y=c?.filter(S=>S.trim().length>0)??[];y.length>0&&Zg(l,y).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const h=p.map(S=>S.sessionId),C=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=ex.getState().expandText;await Promise.allSettled(p.map(async j=>{try{const k=await S(j.prompt).catch(()=>j.prompt);await tx({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:C}}catch(l){return t({error:l instanceof Error?l.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"})),ok="oc:lastWorktreeSourceBranch";function bh(t){const e=mt.c(30),{git:n}=Jn(),r=Jf(t),o=Sc(t),a=Nc(t),c=nx(t),l=wn(uk),d=wn(dk);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 b;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==g?(b=[t,n,o,g,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=g,e[18]=b):b=e[18],i.useEffect(f,b);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(ck).sort(),e[20]=r.all,e[21]=k):k=e[21],x=k}const y=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(lk).map(ak).sort(),e[23]=r.all,e[24]=k):k=e[24],h=k}const C=h;let w;e:{if(!t){w=null;break e}if(o!==null){w=o;break e}if(p){w=null;break e}w=r?.all?!0:null}const S=w;let j;return e[25]!==S||e[26]!==p||e[27]!==y||e[28]!==C?(j={localBranches:y,remoteBranches:C,isLoading:p,isGitRepository:S},e[25]=S,e[26]=p,e[27]=y,e[28]=C,e[29]=j):j=e[29],j}function ak(t){return t.replace(/^remotes\//,"")}function lk(t){return t.startsWith("remotes/")}function ck(t){return!t.startsWith("remotes/")}function dk(t){return t.fetchStatus}function uk(t){return t.fetchBranches}const fk=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=Nt(),{localBranches:l,remoteBranches:d,isLoading:u,isGitRepository:m}=bh(t),f=i.useMemo(()=>[...l,...d.map(b=>`remotes/${b}`)],[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(ok);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($n,{value:e,onValueChange:n,disabled:g,children:[s.jsx(zn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(Nn,{placeholder:c(u?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(Wn,{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(Wl,{children:[s.jsx(_d,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(b=>s.jsx(Ls,{value:b,className:"whitespace-normal break-all",children:b},b))]}),l.length>0&&d.length>0&&s.jsx(rx,{}),d.length>0&&s.jsxs(Wl,{children:[s.jsx(_d,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(b=>s.jsx(Ls,{value:`remotes/${b}`,className:"whitespace-normal break-all",children:b},`remotes/${b}`))]})]})})]}),m===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},mk=10*1024*1024,Fl=5,pa=t=>{const e=mt.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",tabIndex:-1,className:"inline-flex items-center justify-center text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:s.jsx(D,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(Et,{children:[r,s.jsx(Ft,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},Si=t=>{const e=mt.c(9),{htmlFor:n,required:r,children:o,info:a}=t;let c;e[0]!==r?(c=r&&s.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),e[0]=r,e[1]=c):c=e[1];let l;e[2]!==o||e[3]!==n||e[4]!==c?(l=s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,c]}),e[2]=o,e[3]=n,e[4]=c,e[5]=l):l=e[5];const d=a&&a;let 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},hk=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=Nt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:Ao(),prompt:"",models:[]}]),[u,m]=i.useState(""),[f,g]=i.useState([]),[b,p]=i.useState(!1),[x,y]=i.useState([]),[h,C]=i.useState(!1),[w,S]=i.useState(!1),[j,k]=i.useState(!0),v=i.useRef(null),A=Js($=>$.currentDirectory??null),I=Js($=>$.homeDirectory??null),N=i.useMemo(()=>{if(typeof window>"u")return null;const $=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof $=="string"&&$.trim().length>0?$.trim():null},[]),O=ws($=>$.activeProjectId),P=ws($=>$.setActiveProjectIdOnly),T=ws($=>$.projects),[L,R]=i.useState(()=>O??null);i.useEffect(()=>{if(O){R(O);return}!L&&T.length>0&&R(T[0].id)},[O,T,L]);const B=i.useMemo(()=>L?T.find($=>$.id===L)??null:null,[T,L]),V=B?.path??A,_=i.useCallback($=>{R($),$!==O&&P($)},[O,P]),{currentTheme:E}=Kr(),Z=i.useCallback($=>{const ve=$.label?.trim()||Ri($.path,I),be=$.icon?Ic[$.icon]:null,z=$.color?Ga[$.color]:void 0,xe=be?s.jsx(D,{name:be,className:"h-3.5 w-3.5 shrink-0",style:z?{color:z}:void 0}):s.jsx(D,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:z?{color:z}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[$.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:$.iconBackground?{backgroundColor:$.iconBackground}:void 0,children:s.jsx(Ka,{project:{id:$.id,iconImage:$.iconImage??null},options:{themeVariant:E.metadata.variant,iconColor:E.colors.surface.foreground},className:"h-full w-full object-contain",fallback:xe})}):xe,s.jsx("span",{className:"truncate",children:ve})]})},[I,E.metadata.variant,E.colors.surface.foreground]),ne=i.useMemo(()=>{if(B?.path)return{id:B.id,path:B.path};const $=A??N;return $?{id:`path:${$}`,path:$}:null},[B,A,N]),[Y]=i.useState(()=>typeof window<"u"?dr():!1),H=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),re=$f(),ae=i.useMemo(()=>{if(typeof window>"u")return null;const $=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof $=="number"&&Number.isFinite($)&&$>0)return $;if(typeof navigator>"u")return null;const ve=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ve)return null;const be=Number.parseInt(ve[1],10),z=Number.parseInt(ve[2],10);return Number.isNaN(be)?null:be===10?z:be},[]),me=i.useMemo(()=>Y&&H||re?"pl-[5.5rem]":"pl-3",[Y,H,re]),Se=i.useMemo(()=>!Y||!H||ae===null?"":ae>=26?"h-12":ae<=15?"h-14":"",[Y,H,ae]),te=i.useCallback(async $=>{$.target.closest("button, a, input, select, textarea")||$.button===0&&Y&&await ix()},[Y]);i.useEffect(()=>{if(!n)return;const $=ve=>{ve.key==="Escape"&&(ve.preventDefault(),ve.stopPropagation(),n())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[n]);const[ke,Q]=i.useState(""),{isLoading:ge,isGitRepository:F}=bh(V),se=i.useRef(!1),ee=F===!0,Ne=ee&&j;i.useEffect(()=>{if(F===!1){se.current=!0,k(!1);return}F===!0&&se.current&&(se.current=!1,k(!0))},[F]);const De=Ml($=>$.createMultiRun),Be=Ml($=>$.error),Fe=Ml($=>$.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d($=>{const ve=[...$];return ve.length>0&&!ve[0].prompt.trim()&&(ve[0]={...ve[0],prompt:t}),ve})},[t]),i.useEffect(()=>{if(!ne)return;let $=!1;return S(!0),(async()=>{try{const ve=await ox(ne);$||y(ve)}catch{}finally{$||S(!1)}})(),()=>{$=!0}},[ne]);const Me=i.useCallback(($,ve)=>{d(be=>be.map(z=>z.id===$?{...z,...ve}:z))},[]),he=i.useCallback($=>{d(ve=>ve.filter(be=>be.id!==$))},[]),Ae=i.useCallback(()=>{d($=>[...$,{id:Ao(),prompt:"",models:[]}])},[]),pe=async $=>{const ve=$.target.files;if(!ve)return;let be=0;for(let z=0;z<ve.length;z++){const xe=ve[z];if(xe.size>mk){ce.error(o("multirun.launcher.toast.fileTooLarge",{fileName:xe.name}));continue}try{const je=await new Promise((K,ye)=>{const Le=new FileReader;Le.onload=()=>K(Le.result),Le.onerror=ye,Le.readAsDataURL(xe)});g(K=>[...K,{id:Ao(),filename:xe.name,mimeType:xe.type||"application/octet-stream",size:xe.size,dataUrl:je}]),be++}catch(je){console.error("File attach failed",je),ce.error(o("multirun.launcher.toast.attachFailed",{fileName:xe.name}))}}be>0&&ce.success(be===1?o("multirun.launcher.toast.attachedSingle",{count:be}):o("multirun.launcher.toast.attachedPlural",{count:be})),v.current&&(v.current.value="")},ue=$=>{g(ve=>ve.filter(be=>be.id!==$))},U=i.useMemo(()=>l.reduce(($,ve)=>$+ve.models.length,0),[l]),fe=async $=>{$.preventDefault();const ve=l.filter(be=>be.prompt.trim()&&be.models.length>=1);if(ve.length!==0&&!(U<1)){p(!0),Fe();try{L&&L!==O&&P(L);const be=f.map(ye=>({mime:ye.mimeType,filename:ye.filename,url:ye.dataUrl})),z=x.filter(ye=>ye.trim().length>0),xe=ve.map(ye=>({prompt:ye.prompt.trim(),models:ye.models.map(Le=>({providerID:Le.providerID,modelID:Le.modelID,displayName:Le.displayName,variant:Le.variant}))})),je={name:a.trim(),groups:xe,agent:u||void 0,worktreeBaseBranch:Ne?ke:void 0,isolateRuns:Ne,files:be.length>0?be:void 0,setupCommands:z.length>0?z:void 0},K=await De(je);K&&(K.firstSessionId&&ut.getState().setCurrentSession(K.firstSessionId),e?.())}finally{p(!1)}}},de=!!(a.trim()&&l.some($=>$.prompt.trim()&&$.models.length>=1)&&U>=1&&V&&!ge&&(F===!1||!Ne||ke)),G=x.filter($=>$.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:Pe("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",me,Se),style:{borderColor:"var(--interactive-border)"},children:[s.jsx("h1",{className:"typography-ui-label font-medium",children:o("multirun.launcher.title")}),n&&s.jsx("div",{className:"absolute right-0 flex items-center pr-3",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":o("multirun.launcher.actions.closeEsc"),className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:s.jsx(D,{name:"close",className:"h-5 w-5"})})}),s.jsx(Ft,{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(Si,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),T.length>0?s.jsxs($n,{value:L??void 0,onValueChange:_,children:[s.jsx(zn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:B?s.jsx(Nn,{children:Z(B)}):s.jsx(Nn,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(Wn,{fitContent:!0,children:T.map($=>s.jsx(Ls,{value:$.id,className:"max-w-[24rem]",children: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(Si,{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:$=>c($.target.value),placeholder:o("multirun.launcher.groupName.placeholder"),className:"typography-meta w-full",required:!0})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Si,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(pa,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(fk,{directory:V,value:ke,onChange:Q,disabled:!Ne,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(Ti,{checked:j,onChange:k,disabled:!ee,ariaLabel:o("multirun.launcher.isolateRuns.label")}),s.jsx("span",{children:o("multirun.launcher.isolateRuns.label")})]})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Si,{htmlFor:"multirun-agent",info:s.jsx(pa,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(hh,{value:u,onChange:m,id:"multirun-agent"})]})]}),s.jsxs(eo,{open:h,onOpenChange:C,children:[s.jsxs(Bo,{className:"w-full flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-lg hover:bg-[var(--interactive-hover)]/50 transition-colors group",children:[s.jsx(D,{name:"terminal",className:"h-3.5 w-3.5 text-muted-foreground/70"}),s.jsx("span",{className:"typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors",children:o("multirun.launcher.setupCommands.label")}),G>0&&s.jsx("span",{className:"inline-flex items-center justify-center h-4 min-w-4 px-1 rounded-full typography-micro font-medium",style:{backgroundColor:"var(--primary-base)",color:"var(--primary-foreground)",fontSize:"0.625rem",lineHeight:1},children:G}),s.jsx(D,{name:"arrow-down-s",className:Pe("h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto",h&&"rotate-180")})]}),s.jsx(to,{children:s.jsx("div",{className:"pt-2 space-y-1.5",children:w?s.jsx("p",{className:"typography-meta text-muted-foreground/70 px-2",children:o("multirun.launcher.setupCommands.loading")}):s.jsxs(s.Fragment,{children:[x.map(($,ve)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(vn,{value:$,onChange:be=>{const z=[...x];z[ve]=be.target.value,y(z)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>y(x.filter((be,z)=>z!==ve)),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(D,{name:"close",className:"h-3.5 w-3.5"})})]},`${$}-${ve}`)),s.jsxs("button",{type:"button",onClick:()=>y([...x,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(D,{name:"add",className:"h-3 w-3"}),o("multirun.launcher.setupCommands.addCommand")]})]})})})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Si,{htmlFor:"prompt",required:!0,children:o("multirun.launcher.attachments.label")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("input",{ref:v,type:"file",multiple:!0,className:"hidden",onChange:pe,accept:"*/*"}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>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(D,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(Ft,{children:o("multirun.launcher.attachments.tooltip")})]}),f.map($=>s.jsxs("div",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md typography-micro border",style:{backgroundColor:"var(--surface-elevated)",borderColor:"var(--interactive-border)"},children:[$.mimeType.startsWith("image/")?s.jsx(D,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(D,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:$.filename,children:$.filename}),s.jsx("button",{type:"button",onClick:()=>ue($.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(D,{name:"close",className:"h-3 w-3"})})]},$.id))]})]}),l.map(($,ve)=>s.jsx(pk,{group:$,groupIndex:ve,canRemove:l.length>1,onUpdate:Me,onRemove:he},$.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(D,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),Be&&s.jsx("div",{className:"px-3 py-2 rounded-lg typography-meta",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderWidth:1,borderColor:"var(--status-error-border)"},children:Be})]})})}),s.jsx("div",{className:"shrink-0 px-4 sm:px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-2xl flex items-center justify-end gap-2",children:[!Ne&&F!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(D,{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:!de||b,children:b?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:U})})})]})})]})},pk=t=>{const e=mt.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=Nt(),[d,u]=i.useState(!1),[m,f]=i.useState(""),[g,b]=i.useState(!1),[p,x]=i.useState(""),[y,h]=i.useState(!1),[C,w]=i.useState(""),S=i.useRef(null),j=i.useRef(null),k=i.useRef(null),v=i.useRef(null);let A;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(A=z=>{n.models.length>=Fl||a(n.id,{models:[...n.models,z]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=A):A=e[3];const I=A;let N;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(N=z=>{a(n.id,{models:n.models.filter((xe,je)=>je!==z)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=N):N=e[7];const O=N;let P;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(P=(z,xe)=>{a(n.id,{models:n.models.map((je,K)=>K===z?xe:je)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=P):P=e[11];const T=P;let L;e[12]===Symbol.for("react.memo_cache_sentinel")?(L=(z,xe)=>{if(z.startsWith("/")){const Le=z.indexOf(" "),Re=z.indexOf(`
211
- `),X=Math.min(Le===-1?z.length:Le,Re===-1?z.length:Re);if(xe<=X&&Le===-1){x(z.substring(1,X)),b(!0),u(!1),h(!1);return}}b(!1);const je=z.substring(0,xe),K=je.lastIndexOf("#");if(K!==-1){const Le=K>0?je[K-1]:null,Re=je.substring(K+1);if((!Le||/\s/.test(Le))&&!Re.includes(" ")&&!Re.includes(`
212
- `)){w(Re),h(!0),u(!1);return}}h(!1);const ye=je.lastIndexOf("@");if(ye!==-1){const Le=ye>0?je[ye-1]:null,Re=je.substring(ye+1);(!Le||/\s/.test(Le))&&!Re.includes(" ")&&!Re.includes(`
213
- `)?(f(Re),u(!0)):u(!1);return}u(!1)},e[12]=L):L=e[12];const R=L;let B;e[13]!==n.id||e[14]!==a?(B=z=>{a(n.id,{prompt:z})},e[13]=n.id,e[14]=a,e[15]=B):B=e[15];const V=B;let _;e[16]!==n.prompt||e[17]!==V?(_=z=>{const xe=n.prompt,K=S.current?.selectionStart??xe.length,Le=xe.substring(0,K).lastIndexOf("@"),Re=z.relativePath&&z.relativePath.trim().length>0?z.relativePath.trim():z.path||z.name,X=Le!==-1?Le:K,M=`${xe.substring(0,X)}@${Re} ${xe.substring(K)}`,le=X+Re.length+2;V(M),u(!1),f(""),requestAnimationFrame(()=>{const ie=S.current;ie&&(ie.selectionStart=le,ie.selectionEnd=le,ie.focus()),R(M,le)})},e[16]=n.prompt,e[17]=V,e[18]=_):_=e[18];const E=_;let Z;e[19]!==n.prompt||e[20]!==V?(Z=z=>{const xe=n.prompt,K=S.current?.selectionStart??xe.length,Le=xe.substring(0,K).lastIndexOf("@"),Re=Le!==-1?Le:K,X=`${xe.substring(0,Re)}@${z} ${xe.substring(K)}`,M=Re+z.length+2;V(X),u(!1),f(""),requestAnimationFrame(()=>{const le=S.current;le&&(le.selectionStart=M,le.selectionEnd=M,le.focus()),R(X,M)})},e[19]=n.prompt,e[20]=V,e[21]=Z):Z=e[21];const ne=Z;let Y;e[22]!==V?(Y=z=>{const xe=`/${z.name} `;V(xe),b(!1),x(""),h(!1),requestAnimationFrame(()=>{const je=S.current;je&&(je.focus(),je.selectionStart=je.value.length,je.selectionEnd=je.value.length),R(xe,xe.length)})},e[22]=V,e[23]=Y):Y=e[23];const H=Y;let re;e[24]!==n.prompt||e[25]!==V?(re=(z,xe)=>{const je=n.prompt,ye=S.current?.selectionStart??je.length,Re=je.substring(0,ye).lastIndexOf("#"),X=Re!==-1?Re:ye,M=`${je.substring(0,X)}#${xe} ${je.substring(ye)}`,le=X+xe.length+2;V(M),h(!1),w(""),requestAnimationFrame(()=>{const ie=S.current;ie&&(ie.selectionStart=le,ie.selectionEnd=le,ie.focus()),R(M,le)})},e[24]=n.prompt,e[25]=V,e[26]=re):re=e[26];const ae=re;let me;e[27]!==g||e[28]!==d||e[29]!==y?(me=z=>{if(g&&k.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")){z.preventDefault(),k.current.handleKeyDown(z.key);return}d&&j.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")&&(z.preventDefault(),j.current.handleKeyDown(z.key)),y&&v.current&&(z.key==="Enter"||z.key==="ArrowUp"||z.key==="ArrowDown"||z.key==="Escape"||z.key==="Tab")&&(z.preventDefault(),v.current.handleKeyDown(z.key))},e[27]=g,e[28]=d,e[29]=y,e[30]=me):me=e[30];const Se=me,te=r+1;let ke;e[31]!==l||e[32]!==te?(ke=l("multirun.launcher.groups.groupLabel",{index:te}),e[31]=l,e[32]=te,e[33]=ke):ke=e[33];let Q;e[34]!==ke?(Q=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:ke}),e[34]=ke,e[35]=Q):Q=e[35];let ge;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(ge=o&&s.jsx("button",{type:"button",onClick:()=>c(n.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":l("multirun.launcher.groups.removeGroup"),children:s.jsx(D,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=ge):ge=e[40];let F;e[41]!==Q||e[42]!==ge?(F=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Q,ge]}),e[41]=Q,e[42]=ge,e[43]=F):F=e[43];let se;e[44]!==l?(se=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=se):se=e[45];let ee;e[46]!==se?(ee=s.jsx(Si,{required:!0,children:se}),e[46]=se,e[47]=ee):ee=e[47];const Ne=n.prompt;let De;e[48]!==V?(De=z=>{const xe=z.target.value;V(xe);const je=z.target.selectionStart??xe.length;R(xe,je)},e[48]=V,e[49]=De):De=e[49];let Be;e[50]!==l?(Be=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=Be):Be=e[51];let Fe;e[52]!==n.prompt||e[53]!==Se||e[54]!==De||e[55]!==Be?(Fe=s.jsx(ki,{ref:S,value:Ne,onChange:De,onKeyDown:Se,placeholder:Be,className:"typography-meta min-h-[80px] max-h-[200px] resize-none overflow-y-auto field-sizing-content",required:!0}),e[52]=n.prompt,e[53]=Se,e[54]=De,e[55]=Be,e[56]=Fe):Fe=e[56];let Me;e[57]!==p||e[58]!==H||e[59]!==g?(Me=g?s.jsx(rm,{ref:k,searchQuery:p,onCommandSelect:H,onClose:()=>b(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=p,e[58]=H,e[59]=g,e[60]=Me):Me=e[60];let he;e[61]!==ne||e[62]!==E||e[63]!==m||e[64]!==d?(he=d?s.jsx(im,{ref:j,searchQuery:m,onFileSelect:E,onAgentSelect:ne,onClose:()=>u(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=ne,e[62]=E,e[63]=m,e[64]=d,e[65]=he):he=e[65];let Ae;e[66]!==ae||e[67]!==y||e[68]!==C?(Ae=y?s.jsx(om,{ref:v,searchQuery:C,onSnippetSelect:ae,onClose:()=>h(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=ae,e[67]=y,e[68]=C,e[69]=Ae):Ae=e[69];let pe;e[70]!==Fe||e[71]!==Me||e[72]!==he||e[73]!==Ae?(pe=s.jsxs("div",{className:"relative",children:[Fe,Me,he,Ae]}),e[70]=Fe,e[71]=Me,e[72]=he,e[73]=Ae,e[74]=pe):pe=e[74];let ue;e[75]!==ee||e[76]!==pe?(ue=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[ee,pe]}),e[75]=ee,e[76]=pe,e[77]=ue):ue=e[77];let U;e[78]!==l?(U=l("multirun.launcher.models.info",{max:Fl}),e[78]=l,e[79]=U):U=e[79];let fe;e[80]!==U?(fe=s.jsx(pa,{children:U}),e[80]=U,e[81]=fe):fe=e[81];let de;e[82]!==l?(de=l("multirun.launcher.models.label"),e[82]=l,e[83]=de):de=e[83];let G;e[84]!==fe||e[85]!==de?(G=s.jsx(Si,{required:!0,info:fe,children:de}),e[84]=fe,e[85]=de,e[86]=G):G=e[86];let $;e[87]!==n.models||e[88]!==I||e[89]!==O||e[90]!==T?($=s.jsx(gh,{selectedModels:n.models,onAdd:I,onRemove:O,onUpdate:T,minModels:1,maxModels:Fl}),e[87]=n.models,e[88]=I,e[89]=O,e[90]=T,e[91]=$):$=e[91];let ve;e[92]!==G||e[93]!==$?(ve=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[G,$]}),e[92]=G,e[93]=$,e[94]=ve):ve=e[94];let be;return e[95]!==F||e[96]!==ue||e[97]!==ve?(be=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[F,ue,ve]}),e[95]=F,e[96]=ue,e[97]=ve,e[98]=be):be=e[98],be},gk=i.createContext(null),xk=t=>{const e=mt.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(gk.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},vf=oo(()=>io(()=>import("./TerminalView-CMdqMpTy.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(t=>({default:t.TerminalView}))),bk=oo(()=>io(()=>import("./DiagramView-Bbj-QI7h.js"),__vite__mapDeps([9,1,2,4,5,3,6,7,8])).then(t=>({default:t.DiagramView}))),yk=oo(()=>io(()=>import("./NewWorktreeDialog-5TYBoMMA.js").then(t=>t.a8),__vite__mapDeps([6,1,2,3,4,5,7])).then(t=>({default:t.SettingsView}))),wk=oo(()=>io(()=>import("./SettingsWindow-BEfDro9b.js"),__vite__mapDeps([10,1,2,3,4,5,6,7])).then(t=>({default:t.SettingsWindow}))),vk=oo(()=>io(()=>import("./MultiRunWindow-DMMu53kw.js"),__vite__mapDeps([11,1,2,3,4,5,6,7,8])).then(t=>({default:t.MultiRunWindow}))),jk=()=>{const o=Ee(re=>re.isSidebarOpen),a=Ee(re=>re.isRightSidebarOpen),c=Ee(re=>re.isBottomTerminalOpen),l=Ee(re=>re.setRightSidebarOpen),d=Ee(re=>re.setBottomTerminalOpen),u=Ee(re=>re.activeMainTab),m=Ee(re=>re.setIsMobile),f=Ee(re=>re.isSessionSwitcherOpen),g=Ee(re=>re.isSettingsDialogOpen),b=Ee(re=>re.setSettingsDialogOpen),p=Ee(re=>re.isMultiRunLauncherOpen),x=Ee(re=>re.setMultiRunLauncherOpen),y=Ee(re=>re.multiRunLauncherPrefillPrompt),{isMobile:h,isTablet:C}=Er(),w=i.useRef(!1),S=i.useRef(!1),j=i.useRef(!1),[k,v]=i.useState(!1),[A,I]=i.useState(!1),[N,O]=i.useState(!1),[P,T]=i.useState(!1),L=i.useCallback(re=>{v(re),Ee.getState().setSessionSwitcherOpen(re)},[]),R=i.useRef(!1),B=i.useRef(typeof window>"u"?0:window.innerWidth),V=md(-B.current),_=Xe.useRef(0),E=md(B.current),Z=Xe.useRef(0);Xe.useEffect(()=>{h&&(_.current=window.innerWidth,Z.current=window.innerWidth)},[h]),Xe.useEffect(()=>{if(!h){O(!1);return}k&&O(!0),hd(V,k?0:-_.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[k,h,V]),Xe.useEffect(()=>{if(!h){T(!1);return}R.current=A,A&&T(!0),hd(E,A?0:Z.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[h,A,E]),Xe.useEffect(()=>{if(h)return V.on("change",re=>{const ae=_.current||B.current,me=k||re>-ae+.5;O(Se=>Se===me?Se:me)})},[h,V,k]),Xe.useEffect(()=>{if(h)return E.on("change",re=>{const ae=Z.current||B.current,me=A||re<ae-.5;T(Se=>Se===me?Se:me)})},[h,A,E]),Xe.useEffect(()=>{h&&!f&&k&&L(!1)},[f,h,k,L]),Xe.useEffect(()=>{if(!h){j.current=!1;return}j.current||(j.current=!0,L(!1),I(!1),Ee.getState().isRightSidebarOpen&&l(!1))},[h,L,l]),Xe.useEffect(()=>{if(!h||u!=="chat"||k||A||g)return;let re=!1,ae;const me=Se=>{ae=window.setTimeout(()=>{if(re)return;const te=ut.getState(),ke=Ee.getState();if(!(ke.activeMainTab!=="chat"||ke.isSettingsDialogOpen||te.currentSessionId||te.newSessionDraft?.open)){if(te.isLoading){me(250);return}te.openNewSessionDraft()}},Se)};return me(500),()=>{re=!0,ae!==void 0&&window.clearTimeout(ae)}},[u,h,g,k,A]),Xe.useEffect(()=>{!h||!g||(L(!1),I(!1),a&&l(!1))},[h,g,a,L,l]),qx(),i.useEffect(()=>{Ee.getState().isMobile!==h&&m(h)},[h,m]),i.useEffect(()=>{if(typeof window>"u")return;let re;const ae=()=>{re===void 0&&(re=window.requestAnimationFrame(()=>{re=void 0,Ee.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",ae),()=>{window.removeEventListener("resize",ae),re!==void 0&&window.cancelAnimationFrame(re)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let re;const ae=()=>{const Se=Ee.getState(),te=window.innerWidth,ke=window.innerHeight;if(!h&&!C){const Q=te<1140,ge=te>=1220;Q?Se.isRightSidebarOpen&&(l(!1),w.current=!0):ge&&w.current&&(l(!0),w.current=!1);const F=ke<640,se=ke>=700;F?Se.isBottomTerminalOpen&&(d(!1),S.current=!0):se&&S.current&&(d(!0),S.current=!1)}},me=()=>{re===void 0&&(re=window.requestAnimationFrame(()=>{re=void 0,ae()}))};return ae(),window.addEventListener("resize",me),()=>{window.removeEventListener("resize",me),re!==void 0&&window.cancelAnimationFrame(re)}},[h,C,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const re=Ee.subscribe((ae,me)=>{const Se=window.innerWidth,te=window.innerHeight,ke=Se>=1220,Q=te>=700;ae.isRightSidebarOpen!==me.isRightSidebarOpen&&ke&&(w.current=!1),ae.isBottomTerminalOpen!==me.isBottomTerminalOpen&&Q&&(S.current=!1)});return()=>{re()}},[h,C,d,l]);const ne=i.useCallback(()=>{k&&L(!1),I(!A)},[k,A,L]),Y=i.useMemo(()=>{switch(u){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Km,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Xl,{isActive:!A})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(zm,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(vf,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Gm,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Bm,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(bk,{})});default:return null}},[u,A]),H=u==="chat";return s.jsx(Yx,{children:s.jsxs("div",{"data-page-scroll-lock":"true",className:Pe("main-content-safe-area",h?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[s.jsx(H0,{}),s.jsx(Rj,{}),s.jsx(Lj,{}),s.jsx(sk,{}),h?s.jsxs(xk,{value:{leftDrawerOpen:k,rightDrawerOpen:A,toggleLeftDrawer:()=>{const re=!k;A&&I(!1),L(re)},toggleRightDrawer:ne,leftDrawerX:V,rightDrawerX:E,leftDrawerWidth:_,rightDrawerWidth:Z,setMobileLeftDrawerOpen:L,setRightSidebarOpen:I},children:[!g&&s.jsx(Zd,{onToggleLeftDrawer:()=>{const re=!k;A&&I(!1),L(re)},onToggleRightDrawer:()=>{ne()},leftDrawerOpen:k,rightDrawerOpen:A}),s.jsx("div",{"data-page-scroll-lock":"true",className:Pe("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:Pe("absolute inset-0",!H&&"invisible"),children:s.jsx(Zs,{children:s.jsx(Kl,{})})}),Y&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Zs,{children:Y})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(Zs,{children:s.jsx(hk,{initialPrompt:y,onCreated:()=>x(!1),onCancel:()=>x(!1)})})}),N&&s.jsx(pd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:V},"aria-hidden":!k,children:s.jsx(Zs,{children:s.jsx(bf,{mobileVariant:!0})})}),P&&s.jsx(pd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:E},"aria-hidden":!A,children:s.jsx(Zs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Xl,{isActive:A})})})})]})}),g&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(Zs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(yk,{onClose:()=>b(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(ry,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(ty,{isOpen:o,isMobile:h,className:"border-border/50",topBar:s.jsx(sy,{}),children:s.jsx(bf,{})}),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(Zd,{}),s.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden bg-background","data-page-scroll-lock":"true",children:[s.jsxs("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border/50 bg-background","data-page-scroll-lock":"true",children:[s.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden","data-page-scroll-lock":"true",children:s.jsxs("div",{className:"relative flex flex-1 min-h-0 min-w-0 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[s.jsx("div",{className:Pe("absolute inset-0",!H&&"invisible"),children:s.jsx(Zs,{children:s.jsx(Kl,{})})}),Y&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Zs,{children:Y})})]}),s.jsx(U0,{})]})}),s.jsx(Qb,{isOpen:c,isMobile:h,children:c?s.jsx(Zs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(vf,{})})}):null})]}),s.jsx(dy,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(Zs,{children:s.jsx(Dv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(wk,{open:g,onOpenChange:b})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(vk,{open:p,onOpenChange:x,initialPrompt:y})})]})]})})},Sk=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`},On=t=>{const e=mt.c(8),{label:n,value:r}=t;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[0]=o):o=e[0];let a;e[1]!==n?(a=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:n}),e[1]=n,e[2]=a):a=e[2];let c;e[3]!==r?(c=s.jsx("div",{className:"typography-markdown font-semibold text-[var(--surface-foreground)]",children:r}),e[3]=r,e[4]=c):c=e[4];let l;return e[5]!==a||e[6]!==c?(l=s.jsxs("div",{className:"rounded-md p-2",style:o,children:[a,c]}),e[5]=a,e[6]=c,e[7]=l):l=e[7],l},jf=t=>{const e=mt.c(43),{title:n,snapshot:r,emptyLabel:o}=t,{t:a}=Nt();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(Ck,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?Sk(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 b;e[18]!==m||e[19]!==g?(b=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m,g]}),e[18]=m,e[19]=g,e[20]=b):b=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(On,{label:p,value:r.entries.length}),e[23]=r.entries.length,e[24]=p,e[25]=x):x=e[25];let y;e[26]!==a?(y=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=y):y=e[27];let h;e[28]!==y||e[29]!==u?(h=s.jsx(On,{label:y,value:u}),e[28]=y,e[29]=u,e[30]=h):h=e[30];let C;e[31]!==a?(C=a("memoryDebugPanel.metric.lastUpdate"),e[31]=a,e[32]=C):C=e[32];let w;e[33]!==r.lastUpdatedAt||e[34]!==a?(w=r.lastUpdatedAt?a("memoryDebugPanel.common.live"):a("memoryDebugPanel.common.notAvailable"),e[33]=r.lastUpdatedAt,e[34]=a,e[35]=w):w=e[35];let S;e[36]!==C||e[37]!==w?(S=s.jsx(On,{label:C,value:w}),e[36]=C,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:[b,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(_n,{outerClassName:"max-h-64",className:"pr-1",children:s.jsx("div",{className:"space-y-1",children:l.map(k=>s.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] p-2",style:{backgroundColor:"color-mix(in srgb, var(--surface-elevated) 88%, transparent)"},children:[s.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)] break-all",children:k.metric}),s.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:a("memoryDebugPanel.metric.countValue",{value:k.count})}),s.jsx("span",{children:a("memoryDebugPanel.metric.avgValue",{value:k.avg})}),s.jsx("span",{children:a("memoryDebugPanel.metric.maxValue",{value:k.max})}),s.jsx("span",{children:a("memoryDebugPanel.metric.totalValue",{value:k.total})})]})]},k.metric))})})]}),e[0]=o,e[1]=r.durationMs,e[2]=r.entries,e[3]=r.lastUpdatedAt,e[4]=r.startedAt,e[5]=a,e[6]=n,e[7]=c}else c=e[7];return c},Nk=t=>{const e=mt.c(99),{onClose:n}=t,{t:r}=Nt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=ut(Ak),u=am(Dk),m=Cc(),f=ax(Ik),g=rr(Pk),[b,p]=i.useState(Tk),[x,y]=i.useState(Rk);let h;e[0]!==b.entries?(h=new Map,b.entries.forEach(de=>{h.set(de.metric,de.count)}),e[0]=b.entries,e[1]=h):h=e[1];let C;e[2]!==h?(C=h.get("ui.message_list.render")??0,e[2]=h,e[3]=C):C=e[3];let w;e[4]!==h?(w=h.get("ui.message_list.render.streaming")??0,e[4]=h,e[5]=w):w=e[5];let S;e[6]!==h?(S=h.get("ui.chat_message.render")??0,e[6]=h,e[7]=S):S=e[7];let 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 A;e[14]!==C||e[15]!==w||e[16]!==S||e[17]!==j||e[18]!==k||e[19]!==v?(A={messageListRender:C,messageListRenderStreaming:w,chatMessageRender:S,chatMessageRenderStreaming:j,chatMessageRenderStaticDuringStream:k,chatMessageRenderStaticOutsideActiveTurnDuringStream:v},e[14]=C,e[15]=w,e[16]=S,e[17]=j,e[18]=k,e[19]=v,e[20]=A):A=e[20];const I=A;let N,O;e[21]===Symbol.for("react.memo_cache_sentinel")?(N=()=>{const de=()=>{p(na()),y(ra())};de();const G=window.setInterval(de,500);return()=>window.clearInterval(G)},O=[],e[21]=N,e[22]=O):(N=e[21],O=e[22]),i.useEffect(N,O);let P,T;e[23]!==c?(P=()=>{if(c==="idle")return;const de=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(de)},T=[c],e[23]=c,e[24]=P,e[25]=T):(P=e[24],T=e[25]),i.useEffect(P,T);let L=0,R=0,B=0;for(const de of Object.keys(f)){const G=f[de]??[];R=R+G.length;for(const $ of G)$.role==="user"?B=B+1:$.role==="assistant"&&(L=L+1)}let V;e[26]!==L||e[27]!==R||e[28]!==B?(V={assistant:L,total:R,user:B},e[26]=L,e[27]=R,e[28]=B,e[29]=V):V=e[29];const _=V;let E;if(e[30]!==d||e[31]!==f||e[32]!==u||e[33]!==m||e[34]!==r){let de;e[36]!==d||e[37]!==f||e[38]!==u||e[39]!==r?(de=G=>{const $=f[G.id]??[];let ve=0,be=0;for(const xe of $)xe.role==="user"?be=be+1:xe.role==="assistant"&&(ve=ve+1);const z=u.get(G.id);return{id:G.id,title:G.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:ve,messageCount:$.length,userMessageCount:be,isStreaming:z?.isStreaming||!1,isZombie:z?.isZombie||!1,backgroundCount:z?.backgroundMessageCount||0,lastAccessed:z?.lastAccessedAt||0,isCurrent:G.id===d}},e[36]=d,e[37]=f,e[38]=u,e[39]=r,e[40]=de):de=e[40],E=m.map(de).sort(Ek),e[30]=d,e[31]=f,e[32]=u,e[33]=m,e[34]=r,e[35]=E}else E=e[35];const Z=E;let ne;e[41]!==f?(ne=Object.keys(f),e[41]=f,e[42]=ne):ne=e[42];const Y=ne.length;let H;e[43]===Symbol.for("react.memo_cache_sentinel")?(H=async()=>{try{const de={generatedAt:new Date().toISOString(),ui:na(),vscode:ra()};await navigator.clipboard.writeText(JSON.stringify(de,null,2)),l("copied")}catch{l("error")}},e[43]=H):H=e[43];const re=H;let ae;e[44]===Symbol.for("react.memo_cache_sentinel")?(ae={backgroundColor:"color-mix(in srgb, var(--surface-background) 94%, transparent)"},e[44]=ae):ae=e[44];let me;e[45]!==o?(me=o==="memory"?s.jsx(D,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(D,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=me):me=e[46];let Se;e[47]!==r?(Se=r("memoryDebugPanel.title"),e[47]=r,e[48]=Se):Se=e[48];let te;e[49]!==Se?(te=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:Se}),e[49]=Se,e[50]=te):te=e[50];let ke;e[51]!==me||e[52]!==te?(ke=s.jsxs("div",{className:"flex items-center gap-2",children:[me,te]}),e[51]=me,e[52]=te,e[53]=ke):ke=e[53];let Q;e[54]!==o?(Q=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx($e,{size:"xs",variant:"ghost",onClick:re,children:s.jsx(D,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx($e,{size:"xs",variant:"ghost",onClick:()=>{mp(),p(na()),y(ra())},children:s.jsx(D,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=Q):Q=e[55];let ge;e[56]!==n?(ge=n?s.jsx($e,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(D,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=ge):ge=e[57];let F;e[58]!==Q||e[59]!==ge?(F=s.jsxs("div",{className:"flex items-center gap-1",children:[Q,ge]}),e[58]=Q,e[59]=ge,e[60]=F):F=e[60];let se;e[61]!==ke||e[62]!==F?(se=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[ke,F]}),e[61]=ke,e[62]=F,e[63]=se):se=e[63];let ee;e[64]===Symbol.for("react.memo_cache_sentinel")?(ee={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=ee):ee=e[64];const Ne=o==="memory"?"secondary":"ghost";let De;e[65]===Symbol.for("react.memo_cache_sentinel")?(De=()=>a("memory"),e[65]=De):De=e[65];let Be;e[66]!==r?(Be=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=Be):Be=e[67];let Fe;e[68]!==Ne||e[69]!==Be?(Fe=s.jsx($e,{size:"sm",variant:Ne,className:"flex-1",onClick:De,children:Be}),e[68]=Ne,e[69]=Be,e[70]=Fe):Fe=e[70];const Me=o==="streaming"?"secondary":"ghost";let he;e[71]===Symbol.for("react.memo_cache_sentinel")?(he=()=>a("streaming"),e[71]=he):he=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:he,children:Ae}),e[74]=Me,e[75]=Ae,e[76]=pe):pe=e[76];let ue;e[77]!==Fe||e[78]!==pe?(ue=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:ee,children:[Fe,pe]}),e[77]=Fe,e[78]=pe,e[79]=ue):ue=e[79];let U;e[80]!==o||e[81]!==Y||e[82]!==c||e[83]!==d||e[84]!==f||e[85]!==_||e[86]!==u||e[87]!==Z||e[88]!==m||e[89]!==I||e[90]!==b||e[91]!==r||e[92]!==g||e[93]!==x?(U=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(On,{label:r("memoryDebugPanel.metric.totalMessages"),value:_.total}),s.jsx(On,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${Y} / ${$d.MAX_SESSIONS}`}),s.jsx(On,{label:r("memoryDebugPanel.metric.userMessages"),value:_.user}),s.jsx(On,{label:r("memoryDebugPanel.metric.assistantMessages"),value:_.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:lx()})})]}),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:$d.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(_n,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:Z.map(de=>s.jsxs("div",{className:"typography-meta flex items-center justify-between rounded p-1.5",style:{backgroundColor:de.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:de.title}),de.isStreaming?s.jsx(D,{name:"pulse",className:"h-3 w-3 animate-pulse text-[var(--status-info)]"}):null,de.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:de.assistantMessageCount,user:de.userMessageCount})}),s.jsx("span",{className:"font-mono text-[var(--surface-foreground)]",children:r("memoryDebugPanel.metric.msgsValue",{count:de.messageCount})}),de.backgroundCount>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["+",de.backgroundCount]}):null]})]},de.id))})]}),s.jsx("div",{className:"flex gap-2 border-t border-[var(--interactive-border)] pt-2",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx($e,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:m.map(Mk),currentSessionId:d,cachedSessions:Object.keys(f),messageRoleCounts:_,sessionMessageRoleCounts:Z.map(Fk),memoryStates:Object.fromEntries(u)})},children:r("memoryDebugPanel.actions.logState")})}),s.jsx(Ft,{side:"top",children:r("memoryDebugPanel.tooltip.logCurrentState")})]})})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md border border-[var(--interactive-border)] px-3 py-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:r(c==="copied"?"memoryDebugPanel.streaming.copy.copied":c==="error"?"memoryDebugPanel.streaming.copy.failed":"memoryDebugPanel.streaming.copy.hint")}),s.jsx($e,{size:"xs",variant:"outline",onClick:re,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx(On,{label:r("memoryDebugPanel.metric.uiMetrics"),value:b.entries.length}),s.jsx(On,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:x.entries.length}),s.jsx(On,{label:r("memoryDebugPanel.metric.messageListRenders"),value:I.messageListRender}),s.jsx(On,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:I.messageListRenderStreaming}),s.jsx(On,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:I.chatMessageRender}),s.jsx(On,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:I.chatMessageRenderStreaming}),s.jsx(On,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:I.chatMessageRenderStaticDuringStream}),s.jsx(On,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:I.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(jf,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:b,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),x.entries.length>0?s.jsx(jf,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:x,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=Y,e[82]=c,e[83]=d,e[84]=f,e[85]=_,e[86]=u,e[87]=Z,e[88]=m,e[89]=I,e[90]=b,e[91]=r,e[92]=g,e[93]=x,e[94]=U):U=e[94];let fe;return e[95]!==se||e[96]!==ue||e[97]!==U?(fe=s.jsxs(cx,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:ae,children:[se,ue,U]}),e[95]=se,e[96]=ue,e[97]=U,e[98]=fe):fe=e[98],fe},kk=Nk;function Ck(t,e){return t+e.count}function Ak(t){return t.currentSessionId}function Dk(t){return t.sessionMemoryState}function Ik(t){return t.message}function Pk(t){return t.totalRequestCount}function Tk(){return na()}function Rk(){return ra()}function Ek(t,e){return e.lastAccessed-t.lastAccessed}function Mk(t){return{id:t.id,title:t.title}}function Fk(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const Lk=()=>{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()??"":""},Ok=async()=>{const t=Lk()||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")},Sf="openchamber:menu-action",Ll="openchamber:check-for-updates",Bk=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),b=Ee(v=>v.toggleBottomTerminal),p=Ee(v=>v.setBottomTerminalExpanded),x=wo(v=>v.checkForUpdates),{setThemeMode:y}=Kr(),h=i.useRef(!1),C=i.useCallback(()=>{h.current||(h.current=!0,x().then(()=>{const{available:v,error:A}=wo.getState();if(A){ce.error("Failed to check for updates",{description:A});return}v||ce.success("You are on the latest version")}).finally(()=>{h.current=!1}))},[x]),w=i.useCallback(()=>{Pr.requestDirectoryDialog()},[]),S=i.useCallback(v=>{const A=dx();if(A.length===0)return;const I=ut.getState().currentSessionId,N=A.findIndex(T=>T.id===I);let O=v>0?0:A.length-1;N>=0&&(O=(N+v+A.length)%A.length);const P=A[O];P&&(l("chat"),c(!1),ut.getState().setCurrentSession(P.id))},[l,c]),j=i.useCallback(v=>{const{activeProjectId:A,projects:I,setActiveProject:N}=ws.getState();if(I.length===0)return;const O=I.findIndex(L=>L.id===A);let P=v>0?0:I.length-1;O>=0&&(P=(O+v+I.length)%I.length);const T=I[P];T&&N(T.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),nm();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":b();break;case"toggle-terminal-expanded":p(!Ee.getState().isBottomTerminalExpanded);break;case"copy":{const A=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(A)||Ok();break}case"theme-light":y("light");break;case"theme-dark":y("dark");break;case"theme-system":y("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":Js.getState().goBack();break;case"go-forward":Js.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":{ux().catch(()=>{ce.error("Failed to collect OpenCode status")});break}}},[w,j,S,t,e,u,l,c,r,d,p,f,g,y,b,n,o,m,a]);i.useEffect(()=>{const v=I=>{const N=I.detail;N&&k(N)},A=()=>{C()};return window.addEventListener(Sf,v),window.addEventListener(Ll,A),()=>{window.removeEventListener(Sf,v),window.removeEventListener(Ll,A)}},[k,C]),i.useEffect(()=>{if(typeof window>"u")return;const A=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof A!="function")return;let I=null,N=null;return A("openchamber:menu-action",O=>{const P=O?.payload;typeof P=="string"&&k(P)}).then(O=>{I=O}).catch(()=>{}),A("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(Ll))}).then(O=>{N=O}).catch(()=>{}),()=>{(async()=>{try{const P=I?.();P instanceof Promise&&await P}catch{}try{const P=N?.();P instanceof Promise&&await P}catch{}})()}},[k])},Vk="openchamber:tray-action",Nf=5e3,_k=120,$k=45e3,yh=20,kf=()=>typeof window>"u"?!1:window.__OPENCHAMBER_PLATFORM__==="darwin",zk=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},Wk=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,Uk=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},Hk=(t,e,n,r,o)=>{if(!t)return"";const a=px(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||Uk(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},Gk=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=mn.getState(),r=n==="remaining"?"remaining":"usage";if(!e.length)return{mode:r,groups:[]};const o=new Map(t.map(c=>[c.providerId,c])),a=[];for(const c of pm){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:gc(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(Ji())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=Wr();if(e&&ja(e,t))return"Local OpenChamber";const r=(await zf()).hosts.find(o=>e?ja(e,Wf(o)):!1);return r?.label?.trim()?Uf(r.label.trim()):"Instance"}catch{return""}},qk=()=>{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:zk(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:Wk(m),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},Yk=()=>{const t=vr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>Ma(o)-Ma(r)).slice(0,yh).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},Qk=t=>{const e=qk(),n=cm.getState().index.session,r=vr.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=[],y=[...a.get(p)??[]],h=new Set;for(;y.length;){const C=y.pop();h.has(C)||(h.add(C),x.push(C),y.push(...a.get(C)??[]))}return x},l=dm.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(y=>d(y));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,yh).map(p=>{const x=[p.id,...c(p.id)],y=Tr(p)??"";return{id:p.id,title:p.title||"Untitled session",status:u(x),branch:y?e.branchByDirectory.get(y)??"":"",unseen:x.reduce((h,C)=>h+(n.unseenCount[C]??0),0),hasError:x.some(h=>n.unseenHasError[h]??!1),directory:y,subtitle:Hk(y,p,m,f,e.branchByDirectory)}}),b=e.approvals.map(p=>({...p,sessionTitle:o.get(p.sessionId)||""}));return{sessions:g,approvals:b,instanceName:t,usage:Gk()}},Jk=()=>{i.useEffect(()=>{if(!kf()||!Fa())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const j=Qk(r),k=JSON.stringify(j);k!==e&&(e=k,Ur("desktop_tray_update",j))};Kk().then(j=>{t||(r=j,o())});const a=async()=>{const j=Yk();await Promise.all([...j.entries()].map(async([k,v])=>{const A=await Vn.getSessionStatusForDirectory(k).catch(()=>null);t||A===null||mx(k,A,v)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},_k))},l=new Map,d=()=>{if(t)return;let j;try{j=ka()}catch{return}const k=new Set;for(const[v,A]of j.children.entries())k.add(v),l.has(v)||l.set(v,A.subscribe(()=>c()));for(const[v,A]of l)k.has(v)||(A(),l.delete(v))};let u=null;try{u=ka().subscribeRegistry(()=>{d(),c()})}catch{}d();const m=cm.subscribe(()=>c()),f=vr.subscribe(()=>c()),g=ws.subscribe(()=>c()),b=ut.subscribe(()=>c()),p=wn.subscribe(()=>c()),x=dm.subscribe(()=>c());fx(Hf());const y=window.setInterval(()=>{Sa()},$k);a();const h=window.setInterval(()=>{a()},Nf),C=mn.subscribe(()=>c());mn.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:j,results:k}=mn.getState();j.length>0&&j.some(A=>!k.some(I=>I.providerId===A))&&mn.getState().fetchAllQuotas()});const w=window.setInterval(()=>{const j=mn.getState();j.autoRefresh&&j.dropdownProviderIds.length>0&&j.fetchAllQuotas()},Math.max(3e4,mn.getState().refreshIntervalMs||6e4)),S=window.setInterval(()=>{d(),o()},Nf);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(S),window.clearInterval(y),window.clearInterval(h),window.clearInterval(w),m(),f(),g(),b(),p(),x(),C(),u?.();for(const j of l.values())j();l.clear()}},[]),i.useEffect(()=>{if(!kf()||typeof window>"u")return;const e=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof e!="function")return;const n=o=>{o.type==="respond-permission"&&hx(o.sessionId,o.id,o.response).catch(()=>{ce.error("Failed to respond to permission request")})};let r=null;return e(Vk,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{}}},[])},Xk="/api/notifications/stream",Zk=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),eC=t=>{if(!t||typeof t!="object")return null;const e=t,n=e.properties&&typeof e.properties=="object"?e.properties:null;return e.type!=="openchamber:notification"||!n?null:{title:typeof n.title=="string"?n.title:void 0,body:typeof n.body=="string"?n.body:void 0,tag:typeof n.tag=="string"?n.tag:void 0}},tC=t=>{const e=mt.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||dr()||!pc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(Ci().sse(Xk));return a.onmessage=sC,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function sC(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Ee.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&Zk())return;const r=eC(e);if(!r)return;Lo()?.notifications?.notifyAgentCompletion(r)}const Cf="pwa-install-toast-shown",Af="pwa-install-toast-dismissed",nC=()=>{const t=mt.c(6),{browserTab:e}=Qx(),{t:n}=Nt(),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"||!pc()||!e)return;let d=null,u=null;const m=()=>{u!==null&&(ce.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"&&ce.success(r.current("pwa.installPrompt.started"))},g=p=>{const x=p;if(typeof x.prompt!="function")return;x.preventDefault(),d=x;const y=Ni(),h=Mf();Jx({dismissed:y.getItem(Af),sessionShown:h.getItem(Cf),hasActiveToast:u!==null})&&(h.setItem(Cf,"true"),u=ce.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:()=>{Ni().setItem(Af,"true"),m()}}}))},b=()=>{d=null,m(),ce.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",g),window.addEventListener("appinstalled",b),()=>{m(),window.removeEventListener("beforeinstallprompt",g),window.removeEventListener("appinstalled",b)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},rC=({open:t,onOpenChange:e})=>{const{t:n}=Nt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,u]=i.useState(!1),[m,f]=i.useState(!1),[g,b]=i.useState(null),[p,x]=i.useState(!1);i.useCallback(async()=>{},[g,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const C=await As("/api/system/info");if(C.ok){const w=await C.json();if(typeof w.openchamberVersion=="string"&&w.openchamberVersion.trim()){a(w.openchamberVersion);return}}}catch{}a(await gx())})()},[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(()=>{{b(null),x(!1);return}},[t,r]);const y=o;return s.jsx($s,{open:t,onOpenChange:e,children:s.jsx(_s,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(Dc,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),s.jsxs("div",{className:"space-y-0.5 typography-meta text-muted-foreground",children:[y&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:y})}),c&&s.jsx("p",{children:n("aboutDialog.openCodeVersionLabel",{version:c})})]})]}),r,s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-center gap-4",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(D,{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(D,{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(D,{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")})]})})})},Ol=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},iC=(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},oC=()=>{const t=Xx(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=Ol(a,"code"),l=Zx(a),d=eb(a),u=Ol(a,"error"),m=Ol(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 b=await g.json().catch(()=>null);b?.name?.trim()&&(f={name:b.name.trim(),directory:typeof b.directory=="string"&&b.directory.trim()?b.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(iC(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"})})]})})},Df=oo(()=>io(()=>import("./OnboardingScreen-BucKVBD7.js"),__vite__mapDeps([12,1,2,4,5,3])).then(t=>({default:t.OnboardingScreen}))),aC=()=>{const t=mt.c(3),e=Ee(mC),n=Ee(hC);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(rC,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},lC=t=>{const e=mt.c(21),{onRetry:n,isRetrying:r}=t,{t:o}=Nt();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},If=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",cC=()=>{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"}},dC=()=>typeof window>"u"?!1:window.location.pathname===nb,uC=t=>{const e=mt.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=Js(pC),c=ut(gC),l=ut(xC),d=Pc(),u=i.useRef(null);let m;e[0]!==n.directory?(m=If(n.directory),e[0]=n.directory,e[1]=m):m=e[1];const f=m;let g;e[2]!==a?(g=If(a),e[2]=a,e[3]=g):g=e[3];const b=g;let p,x;if(e[4]!==b||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&&b!==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=[b,c,n.directory,n.sessionId,f,r,l,d],e[4]=b,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&&b!==f)return null;let y;e[14]!==o?(y=s.jsx(um,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=y):y=e[15];let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(jm,{}),e[16]=h):h=e[16];let C;e[17]!==n.readOnly?(C=s.jsx(Kl,{readOnly:n.readOnly}),e[17]=n.readOnly,e[18]=C):C=e[18];let w;e[19]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx(fm,{}),e[19]=w):w=e[19];let S;return e[20]!==y||e[21]!==C?(S=s.jsxs(s.Fragment,{children:[y,h,C,w]}),e[20]=y,e[21]=C,e[22]=S):S=e[22],S};function fC({apis:t}){i.useEffect(()=>{hp("App:mounted"),pp()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=ss(F=>F.initializeApp),n=ss(F=>F.isInitialized),r=ss(F=>F.isConnected),o=ss(F=>F.providers.length),a=ss(F=>F.agents.length),c=ss(F=>F.loadProviders),l=ss(F=>F.loadAgents),d=ut(F=>F.error),u=ut(F=>F.clearError),m=Js(F=>F.currentDirectory),f=Js(F=>F.setDirectory),g=Js(F=>F.isSwitchingDirectory),[b,p]=i.useState(!1),x=Pi(F=>F.refreshStatus),[y,h]=i.useState(()=>t.runtime.isVSCode),[C,w]=i.useState(!0),[S,j]=i.useState(!1),[k,v]=i.useState(0),[A,I]=i.useState(0),[N,O]=i.useState(!1),P=Ee(F=>F.wideChatLayoutEnabled),T=Ee(F=>F.mobileKeyboardMode),L=i.useMemo(()=>dr(),[]),R=bc(F=>F.setPlanModeEnabled),[B,V]=i.useState(()=>yd()),[_,E]=i.useState(()=>{const F=wd();return F!==null?vd({isDesktopShell:!0,bootOutcome:F}):null}),Z=i.useRef(!1),ne=i.useMemo(()=>cC(),[]),Y=!ne||C,H=i.useMemo(()=>dC(),[]);i.useEffect(()=>(jd(b),()=>{jd(!1)}),[b]),i.useEffect(()=>{gp(T)},[T]),i.useEffect(()=>{h(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>Of(F=>{ut.getState().prepareForRuntimeSwitch(F.previousRuntimeKey),Ee.getState().prepareForRuntimeSwitch(F.previousRuntimeKey),F.previousRuntimeKey&&ol.getState().stopRunningRunsForRuntime(F.previousRuntimeKey),xp(),Vn.reconnectToRuntimeBaseUrl(),ss.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ws.getState().resetForRuntimeSwitch(),ut.getState().restoreForRuntimeSwitch(F.runtimeKey),Ee.getState().restoreForRuntimeSwitch(F.runtimeKey),xx(),I(se=>se+1),j(!1),v(se=>se+1)}),[]);const re=ol(F=>{const se=Sd();return Object.values(F.runsByOriginalSessionID).filter(ee=>ee.status==="running"&&ee.runtimeKey===se).map(ee=>`${ee.originalSessionID}:${ee.phase}:${ee.lastForwardedMessageID??""}:${ee.expectedAssistantParentID??""}`).sort().join("|")});i.useEffect(()=>{if(ne)return;const F=Sd(),se=Object.values(ol.getState().runsByOriginalSessionID).filter(ee=>ee.status==="running"&&ee.runtimeKey===F);for(const ee of se)bx(ee.originalSessionID)},[re,ne,A]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",P),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[P]),i.useEffect(()=>(Nd(t),()=>Nd(null)),[t]),i.useEffect(()=>{ne||x(t.github,{force:!0})},[t.github,ne,x]),yx();const ae=B==="valid",me=_?.screen==="main";i.useEffect(()=>{if(!bp({isDesktopShell:L,isInitialized:n,bootOutcomeKnown:ae,bootViewIsMain:me}))return;const F=setTimeout(()=>{const se=document.getElementById("initial-loading");se&&(se.classList.add("fade-out"),setTimeout(()=>{se.remove()},300))},150);return()=>clearTimeout(F)},[L,n,ae,me]),i.useEffect(()=>{if(!L||B!=="malformed")return;const F=document.getElementById("initial-loading");F&&(F.textContent="Desktop startup failed — please restart the app.")},[L,B]),i.useEffect(()=>{if(L)return;const F=setTimeout(()=>{const se=document.getElementById("initial-loading");se&&!n&&(se.classList.add("fade-out"),setTimeout(()=>{se.remove()},300))},5e3);return()=>clearTimeout(F)},[L,n]),i.useEffect(()=>{let F=!1;return(async()=>{const ee=await As("/health",{method:"GET"}).catch(()=>null);if(!ee||!ee.ok||F)return;const Ne=await ee.json().catch(()=>null);if(!Ne||F)return;const De=Ne.planModeExperimentalEnabled;R(De===!0||De===1||De==="1"||De==="true")})(),()=>{F=!0}},[R]),i.useEffect(()=>{y||e()},[e,y]),i.useEffect(()=>{if(y||n)return;let F=!0,se,ee=0;const Ne=10,De=1e3,Be=async()=>{if(!F)return;if(ee>=Ne){j(!0);return}const Fe=ss.getState();if(Fe.isInitialized){j(!1);return}ee+=1,await Fe.initializeApp();const Me=ss.getState();if(!F)return;if(Me.isInitialized){j(!1);return}if(ee>=Ne){j(!0);return}const he=Math.min(De*Math.pow(2,ee-1),16e3);se=setTimeout(Be,he)};return se=setTimeout(Be,De),()=>{F=!1,se&&clearTimeout(se)}},[k,n,y]),i.useEffect(()=>{n&&j(!1)},[n]),i.useEffect(()=>{if(!S)return;const F=document.getElementById("initial-loading");F&&(F.classList.add("fade-out"),setTimeout(()=>{F.remove()},300))},[S]),i.useEffect(()=>{if(y||!r||o>0&&a>0)return;let F=!0,se=0;const ee=15,Ne=async()=>{const Be=ss.getState();if(!(Be.providers.length>0&&Be.agents.length>0))try{Be.providers.length===0&&await c({source:"startupRecovery"}),ss.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};Ne();const De=setInterval(()=>{if(F){if(++se>=ee){clearInterval(De);return}Ne()}},2e3);return()=>{F=!1,clearInterval(De)}},[r,y,l,c,o,a]),i.useEffect(()=>{g||y||r&&Vn.setDirectory(m)},[m,g,r,y]),i.useEffect(()=>{if(!ne||typeof window>"u")return;const F=Ne=>{const De=Ne?.visible===!0;w(De)},se=Ne=>{if(Ne.origin!==window.location.origin)return;const De=Ne.data;De?.type==="openchamber:embedded-visibility"&&F(De.payload)},ee=window;return ee.__openchamberSetEmbeddedVisibility=F,window.addEventListener("message",se),()=>{window.removeEventListener("message",se),ee.__openchamberSetEmbeddedVisibility===F&&delete ee.__openchamberSetEmbeddedVisibility}},[ne]),i.useEffect(()=>{!ne?.directory||y||m!==ne.directory&&f(ne.directory,{showOverlay:!1})},[m,ne,y,f]),i.useEffect(()=>{if(!ne||typeof window>"u")return;const F=se=>{se.storageArea===window.localStorage&&se.key==="ui-store"&&Ee.persist.rehydrate()};return window.addEventListener("storage",F),()=>{window.removeEventListener("storage",F)}},[ne]),i.useEffect(()=>{if(typeof window>"u")return;const F=se=>{const ee=se.detail,Ne=typeof ee?.sessionId=="string"?ee.sessionId.trim():"";if(!Ne)return;const De=typeof ee?.directory=="string"&&ee.directory.trim().length>0?ee.directory.trim():null;Ee.getState().setActiveMainTab("chat"),ut.getState().setCurrentSession(Ne,De)};return window.addEventListener("openchamber:open-session",F),()=>window.removeEventListener("openchamber:open-session",F)},[]),i.useEffect(()=>{if(typeof window>"u")return;const F=()=>{const se=Js.getState().currentDirectory,{activeProjectId:ee,projects:Ne}=ws.getState(),De=Ne.find(Be=>Be.id===ee)??null;Ur("desktop_open_draft_mini_chat_window",{directory:se||De?.path||"",projectId:De?.id??null})};return window.addEventListener("openchamber:open-mini-chat",F),()=>window.removeEventListener("openchamber:open-mini-chat",F)},[]),i.useEffect(()=>{if(typeof window>"u")return;const F=()=>{const se=ut.getState().currentSessionId;se&&Sx(se)};return window.addEventListener("focus",F),()=>window.removeEventListener("focus",F)},[]),i.useEffect(()=>{if(typeof window>"u")return;const F=se=>{const ee=se.detail,Ne=typeof ee?.directory=="string"&&ee.directory.trim().length>0?ee.directory.trim():null,De=typeof ee?.projectId=="string"&&ee.projectId.trim().length>0?ee.projectId.trim():null;Ee.getState().setActiveMainTab("chat"),Ee.getState().setSessionSwitcherOpen(!1),ut.getState().openNewSessionDraft({selectedProjectId:De,directoryOverride:Ne,preserveDirectoryOverride:!!Ne})};return window.addEventListener("openchamber:open-draft-session",F),()=>window.removeEventListener("openchamber:open-draft-session",F)},[]),i.useEffect(()=>{if(typeof window>"u")return;const F=se=>{const ee=se.detail,Ne=typeof ee?.projectPath=="string"?ee.projectPath.trim():"";if(!Ne)return;const De=ws.getState(),Be=De.projects.find(Fe=>Fe.path===Ne);Be?De.setActiveProject(Be.id):De.addProject(Ne)};return window.addEventListener("openchamber:open-project",F),()=>window.removeEventListener("openchamber:open-project",F)},[]),i.useEffect(()=>{typeof window>"u"||!n||g||Z.current||(Z.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,g]),wx({enabled:Y}),tC({enabled:Y}),nC(),vx(),tb();const Se=i.useCallback(()=>{p(F=>!F)},[]);Bk(Se),Jk(),i.useEffect(()=>{if(ne)return;const F=se=>{yc(se)&&se.shiftKey&&!se.altKey&&(se.code==="KeyD"||se.key.toLowerCase()==="d")&&(se.preventDefault(),p(Ne=>!Ne))};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[ne]),i.useEffect(()=>{ne||d&&setTimeout(()=>u(),5e3)},[u,ne,d]),i.useEffect(()=>{if(!L||B!=="not-injected")return;let F=!1,se=0;const ee=200,Ne=2e3,De=50,Be=()=>{if(F)return;se++;const Fe=yd();if(Fe!=="not-injected"){if(F=!0,V(Fe),Fe==="valid"){const he=wd();he&&E(vd({isDesktopShell:!0,bootOutcome:he}))}return}const Me=Math.min(ee*Math.pow(1.1,se),Ne);if(se>=De){const he=document.getElementById("initial-loading");he&&!he.textContent?.includes("taking longer")&&(he.textContent="Desktop startup is taking longer than expected...")}window.setTimeout(Be,Me)};return window.setTimeout(Be,ee),()=>{F=!0}},[L,B]);const te=i.useCallback(async()=>{if(yp({isDesktopShell:dr(),isDesktopLocalOriginActive:Ji()})){await wp();return}window.location.reload()},[]),ke=i.useCallback(async()=>{if(!N){j(!1),O(!0);try{await ss.getState().initializeApp()}finally{O(!1)}ss.getState().isInitialized||v(F=>F+1)}},[N]),Q=F=>{if(F.screen==="recovery")return F.variant};if(L&&_&&_.screen!=="main"){if(_.screen==="chooser")return s.jsx(Zs,{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(Df,{mode:"first-launch",onCliAvailable:te,onChooseRemote:()=>{}})})})});const F=Q(_),se=_.screen==="recovery"&&"url"in _?_.url:void 0;return s.jsx(Zs,{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(Df,{mode:"recovery",recoveryVariant:F,recoveryHostUrl:se,recoveryHostLabel:void 0,onCliAvailable:te})})})})}if(ne)return s.jsx(Zs,{children:s.jsx(zd,{sdk:Vn.getSdkClient(),directory:m||"",children:s.jsx(Wd,{apis:t,children:s.jsx(Ud,{delayDuration:300,skipDelayDuration:150,children:s.jsx("div",{className:"h-full text-foreground bg-background",children:s.jsx(uC,{embeddedSessionChat:ne,isVSCodeRuntime:y,embeddedBackgroundWorkEnabled:Y})})})})},A)});if(H)return s.jsx(Zs,{children:s.jsx(oC,{})});if(S&&!n&&!y&&!ne)return s.jsx(Zs,{children:s.jsx(lC,{onRetry:()=>{ke()},isRetrying:N})});const ge=!n&&!L;return s.jsx(Zs,{children:s.jsx(zd,{sdk:Vn.getSdkClient(),directory:m||"",children:s.jsx(Wd,{apis:t,children:s.jsx(Ey,{children:s.jsx(jx,{children:s.jsx(Ud,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:L?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(um,{embeddedBackgroundWorkEnabled:Y}),s.jsx(jm,{}),s.jsx(jk,{}),s.jsx(fm,{}),!ge&&s.jsxs(s.Fragment,{children:[s.jsx(sb,{}),s.jsx(aC,{}),b&&s.jsx(kk,{onClose:()=>p(!1)})]})]})})})})})},A)})}function mC(t){return t.isAboutDialogOpen}function hC(t){return t.setAboutDialogOpen}function pC(t){return t.currentDirectory}function gC(t){return t.currentSessionId}function xC(t){return t.setCurrentSession}const bC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();Nx();vp().then(()=>{Promise.all([jp(),kx()]).catch(t=>{console.error("[main] settings init failed:",t)}),Cx(),Ax(),Dx()}).catch(t=>{console.error("[main] appearance init failed:",t)});const wh=document.getElementById("root");if(!wh)throw new Error("Root element not found");tp.createRoot(wh).render(s.jsx(Xe.StrictMode,{children:s.jsx(Ix,{children:s.jsx(Px,{children:s.jsx(Tx,{children:s.jsx(Rx,{children:s.jsx(fC,{apis:bC})})})})})}));const AC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{d1 as D,hk as M,AC as m,Vs as u};