@openchamber/web 1.14.1 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.test.js +8 -0
- package/bin/lib/DOCUMENTATION.md +3 -0
- package/bin/lib/cli-args.js +10 -0
- package/bin/lib/commands-connect-url.js +169 -22
- package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
- package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
- package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
- package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
- package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
- package/dist/assets/es-r0_jT91q.js +15 -0
- package/dist/assets/fr-Bo8rtAJ1.js +13 -0
- package/dist/assets/index-8J6waVO6.js +2 -0
- package/dist/assets/index-DEMqM4Lz.css +1 -0
- package/dist/assets/ja-BPWtkG-c.js +15 -0
- package/dist/assets/ko-Bv0k-0E3.js +15 -0
- package/dist/assets/main-B-GA5Tg5.js +237 -0
- package/dist/assets/main-Dfm-VKZ9.js +2 -0
- package/dist/assets/miniChat-CfmCFFfu.js +2 -0
- package/dist/assets/mobile-CXJqeDlm.js +2 -0
- package/dist/assets/pl-CiTP50bz.js +15 -0
- package/dist/assets/pt-BR-DadIjX5L.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
- package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
- package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
- package/dist/assets/uk-2RpsWGoZ.js +15 -0
- package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
- package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
- package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
- package/dist/assets/zh-TW--f_BqBpD.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +236 -2
- package/server/lib/client-auth/pairing.js +308 -0
- package/server/lib/client-auth/pairing.test.js +142 -0
- package/server/lib/client-auth/remote-clients.js +65 -3
- package/server/lib/notifications/DOCUMENTATION.md +1 -1
- package/server/lib/notifications/apns-runtime.js +11 -16
- package/server/lib/notifications/runtime.js +135 -33
- package/server/lib/opencode/DOCUMENTATION.md +1 -0
- package/server/lib/opencode/agents.js +3 -0
- package/server/lib/opencode/bootstrap-runtime.js +15 -0
- package/server/lib/opencode/core-routes.js +321 -8
- package/server/lib/opencode/core-routes.test.js +329 -9
- package/server/lib/opencode/feature-routes-runtime.js +6 -0
- package/server/lib/opencode/network-runtime.js +14 -1
- package/server/lib/opencode/network-runtime.test.js +29 -9
- package/server/lib/opencode/proxy.js +47 -6
- package/server/lib/opencode/settings-helpers.js +24 -0
- package/server/lib/opencode/settings-helpers.test.js +25 -0
- package/server/lib/opencode/settings-normalization-runtime.js +21 -4
- package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
- package/server/lib/opencode/settings-runtime.js +25 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/tunnel-auth.js +4 -9
- package/server/lib/package-manager.js +18 -5
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
- package/server/lib/permission-auto-accept/runtime.js +263 -0
- package/server/lib/permission-auto-accept/runtime.test.js +137 -0
- package/server/lib/projects/project-config.js +8 -0
- package/server/lib/quota/DOCUMENTATION.md +5 -2
- package/server/lib/quota/credentials/providers.js +43 -0
- package/server/lib/quota/credentials/store.js +48 -0
- package/server/lib/quota/credentials/store.test.js +26 -0
- package/server/lib/quota/opencode-go-credentials.js +11 -0
- package/server/lib/quota/opencode-go-credentials.test.js +32 -0
- package/server/lib/quota/providers/codex.js +7 -4
- package/server/lib/quota/providers/codex.test.js +48 -0
- package/server/lib/quota/providers/cursor.js +28 -39
- package/server/lib/quota/providers/index.js +7 -0
- package/server/lib/quota/providers/ollama-cloud.js +23 -42
- package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
- package/server/lib/quota/providers/opencode-go.js +70 -0
- package/server/lib/quota/providers/opencode-go.test.js +17 -0
- package/server/lib/quota/routes.js +78 -7
- package/server/lib/quota/routes.test.js +40 -0
- package/server/lib/relay/DOCUMENTATION.md +98 -0
- package/server/lib/relay/cross-compat.test.js +135 -0
- package/server/lib/relay/e2ee.js +341 -0
- package/server/lib/relay/e2ee.test.js +124 -0
- package/server/lib/relay/host-client.js +389 -0
- package/server/lib/relay/host-client.test.js +280 -0
- package/server/lib/relay/host-lock.js +101 -0
- package/server/lib/relay/host-lock.test.js +129 -0
- package/server/lib/relay/identity.js +93 -0
- package/server/lib/relay/identity.test.js +78 -0
- package/server/lib/relay/service.js +334 -0
- package/server/lib/relay/signing-key.js +73 -0
- package/server/lib/relay/tunnel-codec.js +373 -0
- package/server/lib/relay/tunnel-codec.test.js +58 -0
- package/server/lib/relay/tunnel-host.js +462 -0
- package/server/lib/scheduled-tasks/runtime.js +104 -0
- package/server/lib/session-goal/DOCUMENTATION.md +176 -0
- package/server/lib/session-goal/objectives.js +61 -0
- package/server/lib/session-goal/routes.js +36 -0
- package/server/lib/session-goal/runtime.js +764 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
- package/server/lib/ui-auth/ui-auth.js +10 -0
- package/server/opencode-proxy.test.js +38 -0
- package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
- package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
- package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
- package/dist/assets/es-bWcuDy_2.js +0 -15
- package/dist/assets/fr-DzRs3OzV.js +0 -13
- package/dist/assets/index-KnWk9fmM.css +0 -1
- package/dist/assets/index-ZJTzZ0_U.js +0 -2
- package/dist/assets/ja-BqUX_UD3.js +0 -15
- package/dist/assets/ko-BQo10SNx.js +0 -15
- package/dist/assets/main-BDoqLlQB.js +0 -236
- package/dist/assets/main-DUGyTrDt.js +0 -2
- package/dist/assets/miniChat-DNDiX8GA.js +0 -2
- package/dist/assets/mobile-DnghtOCb.js +0 -2
- package/dist/assets/pl-Bgx_ATJT.js +0 -15
- package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
- package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
- package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
- package/dist/assets/uk-C9k8SP8q.js +0 -15
- package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
- package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
|
@@ -1,236 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalView-fTYjnQkh.js","assets/vendor-.bun-C6iL44L9.js","assets/useAppFontEffects-BUUJYbAZ.js","assets/index-ZJTzZ0_U.js","assets/index-KnWk9fmM.css","assets/runtimeEndpointReset-By39StyB.js","assets/mobileLayoutPreference-Dio-WWkI.js","assets/SessionSwitcherDropdown-4FWg9xMC.js","assets/DiagramView-Cb58svCq.js","assets/SettingsWindow-CY8q4msv.js","assets/MultiRunWindow-BPSxV_B7.js","assets/OnboardingScreen-Sl-6JgaP.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{j as s,b as ft,a as ao,R as i,d as Lf,p as fc,I as zh,H as tt,L as Bf,u as ba,k as vo,m as ya,D as wa,o as va,S as $l,v as zl,t as mc,C as hc,N as Wl,O as Wh,T as Uh,W as Hh,X as Gh,Y as li,$ as Kh,a0 as qh,F as Yh,a1 as Qh,a2 as Jh,a3 as Xh,a4 as _f,a5 as Zh,a6 as ep,a7 as Ul,a8 as tp,s as sp,l as np,a9 as md,aa as hd,ab as pd,ac as rp,ad as ip,ae as op,af as ap,ag as lp,ah as cp,_ as lo,ai as gd,aj as xd,ak as bd,G as dp}from"./vendor-.bun-C6iL44L9.js";import{k as pc,l as dr,m as eo,n as yd,p as up,q as ja,t as Vf,v as fp,h as Cs,d as Lo,u as Ee,w as mp,x as _a,y as Yr,a as Hr,z as Gr,A as Hl,B as hp,C as pp,R as wd,D as vd,b as Ys,E as gp,F as xp,G as $f,H as zf,I as gc,o as Jn,J as bp,g as Pi,K as yp,r as xc,L as wp,M as bc,f as Wf,N as vp,O as jp,P as Hi,Q as ra,S as ia,T as Sp,U as Np,V as kp,W as jd,X as Sd,Y as Nd,Z as kd,_ as Cp,$ as Cd,e as Ad,a0 as Ap,a1 as Dp,a2 as Ip,i as Pp,j as Tp}from"./index-ZJTzZ0_U.js";import{c as Nt,p as Te,ax as ws,I,w as ur,t as le,ay as Zs,az as Fr,aA as en,aB as tn,d as Xn,aC as Or,aD as qr,aE as Dd,aF as Et,aG as Mt,aH as Ft,aI as Rp,aj as Po,aJ as Sa,aK as ci,ak as To,al as Uf,ac as yc,aL as Hf,aM as Ep,X as ss,D as ut,aN as Mp,ae as Gf,u as jr,C as wc,b as Ss,Y as Mi,aO as Kf,aP as qf,aQ as Na,aR as Yf,aS as Qf,aT as Jf,aU as Xf,aV as Fp,aW as Op,Z as vc,aX as Va,aY as di,aZ as jc,a_ as oa,a2 as Xs,a$ as Lp,b0 as Zf,b1 as Bp,b2 as em,b3 as Sc,b4 as Gs,b5 as Vs,B as Ve,b6 as Es,b7 as Ms,b8 as hi,b9 as _p,ba as Vp,bb as Wo,bc as En,bd as tm,be as sm,a9 as Nc,bf as $p,bg as Id,bh as Pd,bi as Ii,q as vn,bj as Fi,bk as to,bl as zp,bm as Wp,bn as Up,bo as Hp,bp as $a,bq as za,br as Wa,bs as Ua,bt as ui,bu as mi,bv as Gp,bw as Kp,bx as an,by as qp,bz as Yp,bA as Qp,bB as Jp,bC as Xp,n as Ti,bD as kc,bE as Zp,bF as eg,bG as tg,bH as sg,bI as ng,bJ as rg,bK as ig,bL as Wn,bM as Un,bN as Hn,bO as An,bP as Gn,bQ as Rs,bR as og,A as so,M as Ha,S as Ga,bS as ag,bT as nr,bU as lg,e as pi,g as Cc,f as Ka,bV as cg,bW as nm,bX as dg,bY as ug,h as Ac,bZ as fg,i as wn,b_ as qa,aa as Er,m as mg,b$ as hg,c0 as ll,c1 as pg,c2 as gg,F as Kr,c3 as Dc,c4 as Ya,c5 as fn,c6 as Oi,o as Ri,c7 as rm,c8 as xg,c9 as bg,ca as yg,cb as Td,cc as wg,x as Qr,y as Rd,z as Ed,cd as Md,ce as im,cf as Fd,cg as Od,ch as om,ci as vg,cj as am,v as Ld,J as jg,ck as cl,cl as Ic,cm as Sg,cn as Ng,co as kg,cp as Bo,cq as Cg,cr as dl,cs as lm,ct as cm,cu as Pc,cv as Ag,a1 as Tc,cw as dm,cx as Uo,cy as Dg,r as Mr,cz as Ig,cA as um,cB as Pg,cC as Tg,cD as Bd,cE as fm,cF as mm,cG as hm,H as Rc,P as Qa,K as Ja,O as ka,cH as Ca,cI as Vn,L as Rg,N as Eg,cJ as Mg,cK as Gl,cL as Fg,cM as Og,cN as Lg,cO as _d,cP as Bg,cQ as _g,cR as Ec,cS as pm,cT as Vg,cU as $g,cV as zg,cW as Wg,cX as Vd,cY as $d,cZ as Ug,c_ as Hg,c$ as Gg,d0 as Kg,d1 as qg,d2 as Yg,Q as Qg,d3 as zd,d4 as Jg,d5 as gm,R as Xg,d6 as Zg,E as ex,G as tx,d7 as sx,d8 as nx,d9 as rx,da as ix,db as ox,dc as ax,dd as lx,de as cx,df as dx,dg as Aa,dh as ux,di as Wd,dj as fx,dk as mx,dl as hx,dm as co,dn as px,dp as Ud,dq as gx,dr as xx,ds as bx,dt as yx,a as xm,du as bm,dv as wx,dw as vx,dx as jx,dy as aa,ag as Sx,dz as Nx,dA as Hd,dB as kx,_ as Cx,$ as Ax,a0 as Dx,a3 as Gd,a4 as Kd,a5 as qd,a6 as ym,a7 as wm,as as Ix,at as Px,au as Tx,av as Rx,aw as Ex,ao as Mx,ap as Fx,aq as Ox,ar as Lx}from"./useAppFontEffects-BUUJYbAZ.js";import{I as Yd,o as Bx,p as Qd,q as _x,s as Jd,t as si,v as Vx,w as ul,x as Ro,U as Da,y as Ia,z as no,B as _o,E as ro,k as vm,M as jm,i as mn,j as $x,Q as Sm,F as zx,G as Wx,H as Ux,l as Kl,J as Nm,P as km,K as Hx,L as Gx,C as Kx,a as qx,R as Mc,T as Cm,V as Fc,W as Oc,X as Lc,Y as Am,Z as Dm,_ as ql,$ as Im,a0 as Yl,a1 as la,a2 as Yx,a3 as Qx,e as jo,N as Jx,D as Xx,u as Zx,n as eb,m as Ql,a4 as tb,a5 as sb,g as nb,a6 as rb,a7 as ib,r as ob,c as ab,O as Pm,d as lb,a8 as cb}from"./runtimeEndpointReset-By39StyB.js";import{S as db,C as ub,W as fb,g as Bc,r as mb,n as as,i as Eo,d as io,c as Yi,a as Xd,b as hb,e as So,f as Tm,h as pb,j as gb,u as fl}from"./SessionSwitcherDropdown-4FWg9xMC.js";function Rm(t){const{drafts:e,editingDraftId:n,commentText:r,onTextChange:o,selection:a,isDragging:c,fileLabel:l,newWidgetId:d,mapDraftToRange:f,onSave:m,onCancel:u,onEdit:p,onDelete:y}=t,g=[];for(const b of e){const x=f(b);if(b.id===n){g.push({afterLine:x.end,id:`edit-${b.id}`,content:s.jsx(Yd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:x,isEditing:!0,onSave:m,onCancel:u},`edit-${b.id}`)});continue}g.push({afterLine:x.end,id:`card-${b.id}`,content:s.jsx(Bx,{draft:b,onEdit:()=>p(b),onDelete:()=>y(b)},`card-${b.id}`)})}if(a&&!n&&!c){const b={...a,start:Math.min(a.start,a.end),end:Math.max(a.start,a.end)};g.push({afterLine:b.end,id:d,content:s.jsx(Yd,{initialText:r,onTextChange:o,fileLabel:l,lineRange:b,isEditing:!1,onSave:m,onCancel:u},d)})}return g}function Zd(t){const e=ft.c(14);let n,r,o,a;e[0]!==t?({size:o,className:n,style:a,...r}=t,e[0]=t,e[1]=n,e[2]=r,e[3]=o,e[4]=a):(n=e[1],r=e[2],o=e[3],a=e[4]);const c=typeof o=="number"?`${o}px`:o,l=typeof o=="number"?`${o}px`:o;let d;e[5]!==a||e[6]!==c||e[7]!==l?(d={width:c,height:l,...a},e[5]=a,e[6]=c,e[7]=l,e[8]=d):d=e[8];let f;e[9]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"}),e[9]=f):f=e[9];let m;return e[10]!==n||e[11]!==r||e[12]!==d?(m=s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:d,...r,children:f}),e[10]=n,e[11]=r,e[12]=d,e[13]=m):m=e[13],m}const fi=[{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"}],Jl="finder",Xl=new Set(["finder","terminal"]),_c=t=>typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32"&&t.id==="finder"?{...t,label:"Explorer",appName:"File Explorer"}:t,Zl=t=>{if(!t)return null;const e=fi.find(n=>n.id===t)??null;return e?_c(e):null},ml=()=>fi.filter(t=>Xl.has(t.id)).map(t=>({..._c(t)})),xb=()=>{if(typeof window>"u")return Jl;const t=window.localStorage.getItem("openInAppId");return t&&Zl(t)?t:Jl};let hl=!1,$i=!1,ni=!1,ri=0,No=null;const eu=()=>{No&&(clearTimeout(No),No=null)},wr=ao()((t,e)=>({selectedAppId:xb(),availableApps:ml(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(hl||typeof window>"u")return;hl=!0;const n=(d,f=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:ml(),hasLoadedApps:f});return}const m=new Set(d.map(g=>g.name)),u=new Map(d.map(g=>[g.name,g.iconDataUrl??void 0])),y=fi.filter(g=>m.has(g.appName)||Xl.has(g.id)).map(g=>({..._c(g),iconDataUrl:u.get(g.appName)}));t({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!dr()||!eo()||$i||e().hasLoadedApps&&!d)return;const m=fi.map(u=>u.appName);eu(),$i=!0,ni=!1,t({isScanning:!0});try{const{apps:u,success:p,hasCache:y,isCacheStale:g}=await yd(m,d),b=p&&!y&&u.length===0&&ri<3;if(t({isCacheStale:y?g:!1}),n(u,p?!b:!1),p){if(b){const h=[800,1600,3200][ri]??3200;ri+=1,ni=!0,No=setTimeout(()=>{r()},h);return}ri=0,ni=!1;return}if(ri<3){const h=[1e3,3e3,7e3][ri]??7e3;ri+=1,ni=!0,No=setTimeout(()=>{r()},h)}}finally{$i=!1,ni||t({isScanning:!1})}};r();const o=d=>{const f=d.detail,m=f&&typeof f.openInAppId=="string"&&f.openInAppId.length>0&&Zl(f.openInAppId)?f.openInAppId:null;m&&(window.localStorage.setItem("openInAppId",m),t({selectedAppId:m}))},a=()=>{r()},c=d=>{const f=d.detail;Array.isArray(f)&&(ri=3,ni=!1,t({isScanning:!1,isCacheStale:!1}),n(f))};window.addEventListener("openchamber:settings-synced",o),window.addEventListener("openchamber:app-ready",a),window.addEventListener("openchamber:installed-apps-updated",c),window.__openchamberAppReady&&r(),window.setTimeout(()=>{e().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(hl||e().initialize(),!dr()||!eo()||$i||e().hasLoadedApps&&!n)return;const o=fi.map(a=>a.appName);eu(),n&&t({hasLoadedApps:!1}),$i=!0,ni=!1,t({isScanning:!0});try{const{apps:a,hasCache:c,isCacheStale:l}=await yd(o,n),d=new Set(a.map(p=>p.name)),f=new Map(a.map(p=>[p.name,p.iconDataUrl??void 0])),u=fi.filter(p=>d.has(p.appName)||Xl.has(p.id)).map(p=>({...p,iconDataUrl:f.get(p.appName)}));t({availableApps:u.length>0?u:ml(),hasLoadedApps:u.length>0,isCacheStale:c?l:!1})}finally{$i=!1,ni||t({isScanning:!1})}},selectApp:async n=>{Zl(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await pc({openInAppId:n}))}})),bb="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",yb="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",pl=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__OPENCHAMBER_PLATFORM__!=="win32"?bb:t.id==="terminal"?yb:void 0}),tu=t=>{const e=ft.c(8),{label:n,iconDataUrl:r,fallbackIconDataUrl:o}=t,[a,c]=i.useState(!1);let l;e[0]!==n?(l=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=l):l=e[1];const d=l,f=r||o;if(f&&!a){let p;e[2]===Symbol.for("react.memo_cache_sentinel")?(p=()=>c(!0),e[2]=p):p=e[2];let y;return e[3]!==f?(y=s.jsx("img",{src:f,alt:"",className:"h-4 w-4 rounded-sm",onError:p}),e[3]=f,e[4]=y):y=e[4],y}let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=Te("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=m):m=e[5];let u;return e[6]!==d?(u=s.jsx("span",{className:m,children:d}),e[6]=d,e[7]=u):u=e[7],u},wb=t=>{const e=ft.c(75),{directory:n,className:r}=t,{t:o}=Nt(),a=wr(vb),c=wr(jb),l=wr(Sb),d=wr(Nb),f=wr(kb),m=wr(Cb),u=wr(Ab);let p,y;e[0]!==f?(p=()=>{f()},y=[f],e[0]=f,e[1]=p,e[2]=y):(p=e[1],y=e[2]),i.useEffect(p,y);const g=dr()&&eo();let b;e:{let Ne;e[3]!==c||e[4]!==a?(Ne=c.find(L=>L.id===a)??c.find(Db)??c[0]??fi[0],e[3]=c,e[4]=a,e[5]=Ne):Ne=e[5];const K=Ne;if(K){let L;e[6]!==K?(L=pl(K),e[6]=K,e[7]=L):L=e[7],b=L;break e}let pe;e[8]===Symbol.for("react.memo_cache_sentinel")?(pe=pl(fi[0]),e[8]=pe):pe=e[8],b=pe}const x=b;if(!g||!n||c.length===0)return null;let h;e[9]!==n?(h=async Ne=>{await up(n,Ne.id,Ne.appName)||await ja(n,Ne.appName)},e[9]=n,e[10]=h):h=e[10];const C=h;let w;e[11]!==C||e[12]!==u?(w=async Ne=>{await u(Ne.id),await C(Ne)},e[11]=C,e[12]=u,e[13]=w):w=e[13];const v=w;let S;e[14]!==n||e[15]!==o?(S=async()=>{(await ur(n)).ok&&le.success(o("openInApp.toast.pathCopied"))},e[14]=n,e[15]=o,e[16]=S):S=e[16];const k=S;let j;e[17]!==r?(j=Te("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r),e[17]=r,e[18]=j):j=e[18];let A;e[19]!==C||e[20]!==x?(A=()=>{C(x)},e[19]=C,e[20]=x,e[21]=A):A=e[21];const D=d&&"animate-pulse";let N;e[22]!==D?(N=Te("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",D),e[22]=D,e[23]=N):N=e[23];let B;e[24]!==x.label||e[25]!==o?(B=o("openInApp.actions.openInAria",{app:x.label}),e[24]=x.label,e[25]=o,e[26]=B):B=e[26];let T;e[27]!==x.fallbackIconDataUrl||e[28]!==x.iconDataUrl||e[29]!==x.label?(T=s.jsx(tu,{label:x.label,iconDataUrl:x.iconDataUrl,fallbackIconDataUrl:x.fallbackIconDataUrl}),e[27]=x.fallbackIconDataUrl,e[28]=x.iconDataUrl,e[29]=x.label,e[30]=T):T=e[30];let E;e[31]!==N||e[32]!==B||e[33]!==T||e[34]!==A?(E=s.jsx("button",{type:"button",onClick:A,className:N,"aria-label":B,children:T}),e[31]=N,e[32]=B,e[33]=T,e[34]=A,e[35]=E):E=e[35];let _;e[36]===Symbol.for("react.memo_cache_sentinel")?(_=Te("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),e[36]=_):_=e[36];let R;e[37]!==o?(R=o("openInApp.actions.chooseAppAria"),e[37]=o,e[38]=R):R=e[38];let z;e[39]===Symbol.for("react.memo_cache_sentinel")?(z=s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4"}),e[39]=z):z=e[39];let V;e[40]!==R?(V=s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:_,"aria-label":R,children:z})}),e[40]=R,e[41]=V):V=e[41];let $;e[42]!==k?($=()=>{k()},e[42]=k,e[43]=$):$=e[43];let M;e[44]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(I,{name:"file-copy",className:"h-4 w-4"}),e[44]=M):M=e[44];let te;e[45]!==o?(te=o("openInApp.actions.copyPath"),e[45]=o,e[46]=te):te=e[46];let re;e[47]!==te?(re=s.jsx("span",{className:"typography-ui-label text-foreground",children:te}),e[47]=te,e[48]=re):re=e[48];let Q;e[49]!==$||e[50]!==re?(Q=s.jsxs(ws,{className:"flex items-center gap-2",onClick:$,children:[M,re]}),e[49]=$,e[50]=re,e[51]=Q):Q=e[51];let H;e[52]===Symbol.for("react.memo_cache_sentinel")?(H=s.jsx(Fr,{}),e[52]=H):H=e[52];let X;if(e[53]!==c||e[54]!==v||e[55]!==x.id){let Ne;e[57]!==v||e[58]!==x.id?(Ne=K=>{const pe=pl(K);return s.jsxs(ws,{className:"flex items-center gap-2",onClick:()=>{v(K)},children:[s.jsx(tu,{label:K.label,iconDataUrl:K.iconDataUrl,fallbackIconDataUrl:pe.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:K.label}),x.id===K.id?s.jsx(I,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},K.id)},e[57]=v,e[58]=x.id,e[59]=Ne):Ne=e[59],X=c.map(Ne),e[53]=c,e[54]=v,e[55]=x.id,e[56]=X}else X=e[56];let oe;e[60]!==l||e[61]!==m||e[62]!==o?(oe=l?s.jsxs(ws,{className:"flex items-center gap-2",onClick:()=>{m(!0)},children:[s.jsx(I,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:o("openInApp.actions.refreshApps")})]}):null,e[60]=l,e[61]=m,e[62]=o,e[63]=oe):oe=e[63];let fe;e[64]!==Q||e[65]!==X||e[66]!==oe?(fe=s.jsxs(en,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Q,H,X,oe]}),e[64]=Q,e[65]=X,e[66]=oe,e[67]=fe):fe=e[67];let ve;e[68]!==V||e[69]!==fe?(ve=s.jsxs(tn,{children:[V,fe]}),e[68]=V,e[69]=fe,e[70]=ve):ve=e[70];let ie;return e[71]!==E||e[72]!==ve||e[73]!==j?(ie=s.jsxs("div",{className:j,children:[E,ve]}),e[71]=E,e[72]=ve,e[73]=j,e[74]=ie):ie=e[74],ie};function vb(t){return t.selectedAppId}function jb(t){return t.availableApps}function Sb(t){return t.isCacheStale}function Nb(t){return t.isScanning}function kb(t){return t.initialize}function Cb(t){return t.loadInstalledApps}function Ab(t){return t.selectApp}function Db(t){return t.id===Jl}const Ib=1e6,Pb="terminal-store";let su=!1;const gl=t=>typeof t=="object"&&t!==null,Tb=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function Pn(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const xl=(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}),bl=t=>({tabs:[t],activeTabId:t.id}),br=(t,e)=>t.tabs.findIndex(n=>n.id===e),_s=ao()(Lf(fc((t,e)=>({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Pn(n);r&&t(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),c=`tab-${o.nextTabId}`,l=xl(c,"Terminal");return a.set(r,bl(l)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=Pn(n);return e().sessions.get(r)},getActiveTab:n=>{const r=Pn(n),o=e().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(c=>c.id===a)??o.tabs[0]:o.tabs[0]},createTab:n=>{const r=Pn(n);if(!r)return"tab-invalid";const o=`tab-${e().nextTabId}`;return t(a=>{const c=new Map(a.sessions),l=c.get(r),d=a.nextTabId+1,m=`Terminal ${(l?.tabs.length??0)+1}`,u=xl(o,m);return l?c.set(r,{...l,tabs:[...l.tabs,u]}):c.set(r,bl(u)),{sessions:c,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Pn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);return!l||l.activeTabId===r||br(l,r)<0?a:(c.set(o,{...l,activeTabId:r}),{sessions:c})})},setTabLabel:(n,r,o)=>{const a=Pn(n),c=o.trim();c&&t(l=>{const d=new Map(l.sessions),f=d.get(a);if(!f)return l;const m=br(f,r);if(m<0||f.tabs[m]?.label===c)return l;const u=[...f.tabs];return u[m]={...u[m],label:c},d.set(a,{...f,tabs:u}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=o?.trim()||null;if(d.tabs[f]?.iconKey===m)return c;const u=[...d.tabs];return u[f]={...u[f],iconKey:m},l.set(a,{...d,tabs:u}),{sessions:l}})},closeTab:async(n,r)=>{const o=Pn(n),l=e().sessions.get(o)?.tabs.find(d=>d.id===r)?.terminalSessionId??null;if(l)try{await fp(l)}catch{}t(d=>{const f=new Map(d.sessions),m=f.get(o);if(!m)return d;const u=br(m,r);if(u<0)return d;const p=m.tabs.filter(x=>x.id!==r),y=Object.fromEntries(Object.entries(d.projectActionRuns).filter(([,x])=>!(x.directory===o&&x.tabId===r))),g=Object.keys(y).length!==Object.keys(d.projectActionRuns).length;if(p.length===0){const x=`tab-${d.nextTabId}`,h=xl(x,"Terminal");return f.set(o,bl(h)),{sessions:f,nextTabId:d.nextTabId+1,...g?{projectActionRuns:y}:{}}}let b=m.activeTabId;return m.activeTabId===r&&(b=p[Math.min(u,p.length-1)]?.id??p[0]?.id??null),f.set(o,{...m,tabs:p,activeTabId:b}),{sessions:f,...g?{projectActionRuns:y}:{}}})},setTabSessionId:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=d.tabs[f],u=o!==null&&m.terminalSessionId!==o,p=o?"running":m.terminalSessionId?"exited":m.lifecycle,y={...m,terminalSessionId:o,lifecycle:p,isConnecting:!1,...u?{bufferChunks:[],bufferLength:0}:{}},g=[...d.tabs];return g[f]=y,l.set(a,{...d,tabs:g}),{sessions:l}})},setTabLifecycle:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=[...d.tabs];return m[f]={...m[f],lifecycle:o,isConnecting:!1},l.set(a,{...d,tabs:m}),{sessions:l}})},setConnecting:(n,r,o)=>{const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=[...d.tabs];return m[f]={...m[f],isConnecting:o},l.set(a,{...d,tabs:m}),{sessions:l}})},appendToBuffer:(n,r,o)=>{if(!o)return;const a=Pn(n);t(c=>{const l=new Map(c.sessions),d=l.get(a);if(!d)return c;const f=br(d,r);if(f<0)return c;const m=d.tabs[f],u=c.nextChunkId,p={id:u,data:o},y=[...m.bufferChunks,p];let g=m.bufferLength+o.length;for(;g>Ib&&y.length>1;){const x=y.shift();if(!x)break;g-=x.data.length}const b=[...d.tabs];return b[f]={...m,bufferChunks:y,bufferLength:g},l.set(a,{...d,tabs:b}),{sessions:l,nextChunkId:u+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const c=Pn(n);t(l=>{const d=new Map(l.sessions),f=d.get(c);if(!f)return l;const m=br(f,r);if(m<0)return l;const u=f.tabs[m],p=a.autoOpened??u.previewAutoOpened,y=a.locked??u.previewUrlLocked;if(u.previewUrl===o&&u.previewAutoOpened===p&&u.previewUrlLocked===y)return l;const g=[...f.tabs];return g[m]={...u,previewUrl:o,previewAutoOpened:p,previewUrlLocked:y},d.set(c,{...f,tabs:g}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Pn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=br(l,r);if(d<0)return a;const f=l.tabs[d];if(!f.previewUrl||f.previewAutoOpened)return a;const m=[...l.tabs];return m[d]={...f,previewAutoOpened:!0},c.set(o,{...l,tabs:m}),{sessions:c}})},setProjectActionRun:n=>{t(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{t(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{t(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},clearBuffer:(n,r)=>{const o=Pn(n);t(a=>{const c=new Map(a.sessions),l=c.get(o);if(!l)return a;const d=br(l,r);if(d<0)return a;const f=[...l.tabs];return f[d]={...f[d],bufferChunks:[],bufferLength:0},c.set(o,{...l,tabs:f}),{sessions:c}})},removeDirectory:n=>{const r=Pn(n);t(o=>{const a=new Map(o.sessions);a.delete(r);const c=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,l])=>l.directory!==r));return{sessions:a,projectActionRuns:c}})},clearAll:()=>{t({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Pb,storage:zh(()=>Vf()),partialize:t=>({sessions:Array.from(t.sessions.entries()).map(([e,n])=>[e,{activeTabId:n.activeTabId,tabs:n.tabs.map(r=>({id:r.id,label:r.label,iconKey:r.iconKey,terminalSessionId:r.terminalSessionId,lifecycle:r.lifecycle,createdAt:r.createdAt}))}]),nextTabId:t.nextTabId}),merge:(t,e)=>{if(!gl(t))return e;const n=Array.isArray(t.sessions)?t.sessions:[],r=new Map;let o=0;for(const l of n){if(!Array.isArray(l)||l.length!==2)continue;const[d,f]=l;if(typeof d!="string"||!gl(f))continue;const m=Array.isArray(f.tabs)?f.tabs:[],u=[];for(const g of m){if(!gl(g))continue;const b=typeof g.id=="string"?g.id:null;if(!b)continue;const x=Tb(b);x!==null&&(o=Math.max(o,x));const h=typeof g.terminalSessionId=="string"||g.terminalSessionId===null?g.terminalSessionId:null,C=g.lifecycle,w=C==="idle"||C==="running"||C==="exited"?C:h?"running":"idle";u.push({id:b,label:typeof g.label=="string"?g.label:"Terminal",iconKey:typeof g.iconKey=="string"?g.iconKey:null,terminalSessionId:h,lifecycle:w,createdAt:typeof g.createdAt=="number"?g.createdAt:Date.now(),bufferChunks:[],bufferLength:0,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(u.length===0)continue;const p=typeof f.activeTabId=="string"?f.activeTabId:null,y=p?u.some(g=>g.id===p):!1;r.set(d,{tabs:u,activeTabId:y?p:u[0].id})}const a=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,c=Math.max(e.nextTabId,a,o+1);return{...e,sessions:r,nextChunkId:1,nextTabId:c,hasHydrated:!0}}})));if(typeof window<"u"&&!su){su=!0;const t=_s.persist,e=()=>{_s.getState().hasHydrated||_s.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}const Rb=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Eb=["dev","start","preview","serve"];async function Mb(t,e,n){if(!t)return null;const r=Lb(e);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id};if(n){const o=Bb(n);if(o){const a=await _b(t);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await Fb(t)){const o=await Ob(),a=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function Fb(t){const e=`${t}/index.html`,n=await Pa(e,t);return typeof n=="string"&&n.trim().length>0}async function Ob(){try{const t=await Cs("/api/system/free-port",{cache:"no-store"});if(!t.ok)return null;const e=await t.json().catch(()=>null),n=typeof e?.port=="number"?e.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Lb(t){for(const e of t){const n=`${e.name} ${e.command}`.toLowerCase();if(Eb.some(o=>n.includes(o)))return e}return null}function Bb(t){for(const{pattern:e}of Rb)for(const n of Object.keys(t))if(e.test(n))return n;return null}async function _b(t){const e=await Pa(`${t}/package.json`,t);if(e)try{const r=JSON.parse(e),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Pa(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Pa(t,e){if(e?.trim())try{const r=new URLSearchParams({path:t,directory:e,optional:"true"}),o=await Cs(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Lo()?.files;if(n?.readFile)try{const r=await n.readFile(t,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Cs(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Vb(t){try{const e=await Pa(`${t}/package.json`,t);if(e==null)return null;const r=JSON.parse(e).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const $b=t=>new Promise(e=>{window.setTimeout(e,t)}),zb="\x1B",Wb=new RegExp(`${zb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ub=/https?:\/\/[^\s<>'"`]+/gi,er="__openchamber_auto_discover_preview__",Hb=15e3,Gb=t=>{let e="";for(let n=0;n<t.length;n+=1){const r=t.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(e+=t[n])}return e},Kb=t=>{const e=(t||"").trim();if(!e)return null;const n=/^https?:\/\//i.test(e)?e:`http://${e}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},qb=t=>{const n=t.replace(Wb,"").match(Ub);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const c=new URL(a);c.port&&c.port.length>0&&o.push({raw:a,parsed:c})}catch{}if(o.length>0){const a=c=>{const{parsed:l}=c,d=l.hostname.toLowerCase(),f=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",m=l.pathname||"/",u=m.split("/").filter(Boolean).length,p=m==="/"||m==="",y=!!(l.search||l.hash);let g=0;return f&&(g+=50),p&&(g+=30),g-=Math.min(u*5,20),y&&(g-=10),g};return o.sort((c,l)=>a(l)-a(c)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},Em=({projectRef:t,directory:e,className:n,compact:r=!1,allowMobile:o=!1})=>{const{t:a}=Nt(),{terminal:c,runtime:l}=Xn(),{isMobile:d}=Or(),f=i.useMemo(()=>dr(),[]),m=Qd(W=>W.instances),u=Qd(W=>W.load),p=Ee(W=>W.setBottomTerminalOpen),y=Ee(W=>W.setActiveMainTab),g=Ee(W=>W.setSettingsPage),b=Ee(W=>W.setSettingsDialogOpen),x=Ee(W=>W.setSettingsProjectsSelectedId),h=Ee(W=>W.openContextPreview),C=_s(W=>W.sessions),w=_s(W=>W.ensureDirectory),v=_s(W=>W.setTabLabel),S=_s(W=>W.setTabIconKey),k=_s(W=>W.setActiveTab),j=_s(W=>W.setConnecting),A=_s(W=>W.setTabSessionId),D=_s(W=>W.setTabPreviewUrl),N=_s(W=>W.projectActionRuns),B=_s(W=>W.setProjectActionRun),T=_s(W=>W.updateProjectActionRunStatus),E=_s(W=>W.removeProjectActionRun),[_,R]=i.useState([]),[z,V]=i.useState(null),[$,M]=i.useState(!1),te=i.useRef({}),re=i.useRef({}),Q=i.useRef({}),H=i.useRef({}),X=i.useRef(0),oe=t?.id??null,fe=t?.path??"",ve=i.useMemo(()=>oe?{id:oe,path:fe}:null,[oe,fe]);i.useEffect(()=>{f&&u().catch(()=>{})},[f,u]);const ie=i.useCallback(async W=>{await qr(W)},[]),Ne=i.useCallback(async()=>{if(!ve)return;const W=X.current+1;X.current=W,M(!0);try{const ge=await Dd(ve);if(X.current!==W)return;const we=ge.actions;R(we),V(G=>G===er||G&&we.some(Se=>Se.id===G)?G:null)}catch{if(X.current!==W)return}finally{X.current===W&&M(!1)}},[ve]),K=i.useMemo(()=>_x(e||ve?.path||""),[e,ve?.path]),pe=i.useMemo(()=>z?_.find(W=>W.id===z)??null:null,[_,z]),L=i.useMemo(()=>({id:er,name:a("projectActions.actions.autoDiscover"),command:"",icon:"search",autoOpenUrl:!0}),[a]),se=!d,Z=i.useMemo(()=>se?[L,..._]:_,[_,L,se]);i.useEffect(()=>{Ne()},[Ne]),i.useEffect(()=>{if(typeof window>"u")return;const W=ge=>{const we=ge.detail;oe&&(we?.projectId&&we.projectId!==oe||Ne())};return window.addEventListener(Jd,W),()=>{window.removeEventListener(Jd,W)}},[Ne,oe]),i.useEffect(()=>{z&&(z===er&&se||_.some(W=>W.id===z)||V(null))},[_,se,z]),i.useEffect(()=>{for(const[W,ge]of Object.entries(N)){const G=C.get(ge.directory)?.tabs.find(Se=>Se.id===ge.tabId);(!G||G.terminalSessionId!==ge.sessionId)&&E(W)}},[N,E,C]),i.useEffect(()=>{for(const[W,ge]of Object.entries(N)){const we=re.current[W]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};re.current[W]=we;const G=Z.find(Be=>Be.id===ge.actionId);if(!G)continue;const Oe=C.get(ge.directory)?.tabs.find(Be=>Be.id===ge.tabId);if(!Oe||!Array.isArray(Oe.bufferChunks)||Oe.bufferChunks.length===0)continue;const Ae=Oe.bufferChunks.filter(Be=>we.lastSeenChunkId===null?!0:Be.id>we.lastSeenChunkId);if(Ae.length===0)continue;const J=Ae.map(Be=>Be.data).join(""),O=`${we.tail}${J}`,ae=!we.openedUrl&&G.autoOpenUrl===!0?qb(O):null,ne=Ae[Ae.length-1]?.id??we.lastSeenChunkId;if(we.lastSeenChunkId=ne,we.tail=O.slice(-512),ae)if(we.openedUrl=!0,we.openInPreview){const Be=N[W];Be&&(D(Be.directory,Be.tabId,ae,{locked:!1,autoOpened:!1}),Be.status==="waiting-for-preview"&&T(W,"running"),window.clearTimeout(H.current[W]),delete H.current[W],h(Be.directory,ae))}else ie(ae),le.success(a("projectActions.toast.openedUrlFromOutput"));re.current[W]=we}for(const W of Object.keys(re.current))N[W]||(delete re.current[W],window.clearTimeout(H.current[W]),delete H.current[W])},[Z,h,ie,N,D,a,C,T]);const je=i.useCallback(async(W,ge={})=>{if(!K)throw new Error(a("projectActions.error.noActiveDirectory"));const we=si(K,W.id);w(K);const G=_s.getState(),Se=G.getDirectoryState(K);let Oe=te.current[we]||null;const Ae=Oe?!!Se?.tabs.some(ae=>ae.id===Oe):!1;(!Oe||!Ae)&&(Oe=G.createTab(K),te.current[we]=Oe),v(K,Oe,`Action: ${W.name}`),S(K,Oe,W.icon||"play"),ge.revealTerminal!==!1&&(k(K,Oe),p(!0),y("terminal"));const O=_s.getState().getDirectoryState(K)?.tabs.find(ae=>ae.id===Oe);return{key:we,tabId:Oe,sessionId:O?.terminalSessionId??null}},[w,K,y,k,p,S,v,a]),De=i.useCallback(async W=>{if(l.isVSCode||!o&&d)return;if(!K){le.error(a("projectActions.error.noActiveDirectoryForAction"));return}const ge=si(K,W.id),we=N[ge];if(!(we&&we.status==="running"))try{const G=W.id===er?await(async()=>{const[Je,nt]=await Promise.all([Dd({id:ve?.id??"",path:K}),Vb(K)]),xt=await Mb(K,Je.actions,nt);if(!xt)throw new Error(a("contextPanel.preview.noDevServer"));return{id:er,name:a("projectActions.actions.autoDiscover"),command:xt.command,icon:"search",autoOpenUrl:!0,openUrl:xt.previewUrlHint||""}})():W,Se=G.autoOpenUrl===!0&&(G.openUrl||"").trim().length>0,{key:Oe,tabId:Ae,sessionId:J}=await je(G,{revealTerminal:!Se&&W.id!==er});let O=J,ae=!1;if(!O){j(K,Ae,!0);try{O=(await c.createSession({cwd:K})).sessionId,ae=!0,A(K,Ae,O)}finally{j(K,Ae,!1)}}if(!O)throw new Error(a("projectActions.error.failedToCreateTerminalSession"));ae&&await $b(350),G.id===er&&(Q.current[Oe]?.(),j(K,Ae,!0),Q.current[Oe]=mp(O,Je=>{Je.type==="data"&&typeof Je.data=="string"&&Je.data.length>0&&_s.getState().appendToBuffer(K,Ae,Je.data),Je.type==="exit"&&(_s.getState().setTabLifecycle(K,Ae,"exited"),_s.getState().setConnecting(K,Ae,!1),_s.getState().removeProjectActionRun(Oe),delete re.current[Oe],Q.current[Oe]?.(),delete Q.current[Oe],window.clearTimeout(H.current[Oe]),delete H.current[Oe])},()=>{_s.getState().setConnecting(K,Ae,!1)},{maxRetries:60,initialRetryDelay:250,maxRetryDelay:2e3,connectionTimeout:5e3}));const ne=G.autoOpenUrl===!0&&f&&(G.desktopOpenSshForward||"").trim().length>0,Be=G.autoOpenUrl?Kb(G.openUrl):null,Ye=G.autoOpenUrl&&f?Vx(G.desktopOpenSshForward,m):null;B({key:Oe,directory:K,actionId:G.id,tabId:Ae,sessionId:O,status:G.id===er&&!Be?"waiting-for-preview":"running"}),window.clearTimeout(H.current[Oe]),delete H.current[Oe],G.id===er&&!Be&&(H.current[Oe]=window.setTimeout(()=>{_s.getState().updateProjectActionRunStatus(Oe,"running"),delete H.current[Oe]},Hb)),Ye?(D(K,Ae,null,{locked:!0}),ie(Ye),le.success(a("projectActions.toast.openedForwardedUrl"))):Be?(D(K,Ae,Be,{locked:!0,autoOpened:!0}),h(K,Be),le.success(a("projectActions.toast.openedActionUrl"))):Se?(D(K,Ae,null,{locked:!0}),le.error(a("projectActions.error.invalidCustomUrlFormat"))):ne?(D(K,Ae,null,{locked:!0}),le.error(a("projectActions.error.selectedDesktopSshForwardUnavailable"))):D(K,Ae,null,{locked:!1,autoOpened:!1}),re.current[Oe]={lastSeenChunkId:null,openedUrl:!!Ye||!!Be||Se,tail:"",openInPreview:G.id===er};const He=Gb(G.command.trim().replace(/\r\n|\r/g,`
|
|
3
|
-
`));await c.sendInput(O,`${He}\r`)}catch(G){E(ge),delete re.current[ge],Q.current[ge]?.(),delete Q.current[ge],window.clearTimeout(H.current[ge]),delete H.current[ge],le.error(G instanceof Error?G.message:a("projectActions.error.failedToRunAction"))}},[m,je,o,d,f,K,ie,h,N,l.isVSCode,E,j,B,D,A,ve?.id,a,c]),Le=i.useCallback(async W=>{const ge=si(K,W.id),we=N[ge];if(!we)return;T(ge,"stopping");try{await c.sendInput(we.sessionId,"")}catch{}if(await new Promise(Oe=>{window.setTimeout(Oe,1e3)}),_s.getState().getDirectoryState(we.directory)?.tabs.find(Oe=>Oe.id===we.tabId)?.terminalSessionId===we.sessionId){if(typeof c.forceKill=="function")try{await c.forceKill({sessionId:we.sessionId})}catch{}else try{await c.close(we.sessionId)}catch{}A(we.directory,we.tabId,null)}E(ge),delete re.current[ge],Q.current[ge]?.(),delete Q.current[ge],window.clearTimeout(H.current[ge]),delete H.current[ge]},[K,N,E,A,c,T]),Me=i.useCallback(()=>{const W=pe??Z[0];if(!W)return;const ge=si(K,W.id),we=N[ge];if(we?.status!=="stopping"){if(we){Le(W);return}De(W)}},[Z,K,De,N,pe,Le]),Fe=i.useCallback((W,ge=!1)=>{if(V(W.id),!ge){De(W);return}const we=si(K,W.id),G=N[we];if(G?.status!=="stopping"){if(G){Le(W);return}De(W)}},[K,De,N,Le]),he=i.useCallback(()=>{ve?.id&&(x(ve.id),g("projects"),b(!0))},[b,g,x,ve?.id]);if(l.isVSCode||!o&&d||!ve||!K)return null;const Ie=pe??Z[0]??null;if(!Ie)return null;const me=Ie.icon||"play",ce=Ie.id===er?"search":ul[me]||"play",xe=si(K,Ie.id),ke=N[xe],de=ke?.status==="stopping",P=ke?.status==="waiting-for-preview",F=ke?C.get(ke.directory)?.tabs.find(W=>W.id===ke.tabId)?.previewUrl??null:null,ue=!!(ke&&F),be=()=>{!ke||!F||h(ke.directory,F)};return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsx("button",{type:"button",disabled:$||de,className:Te("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:Me,"aria-label":ke?a("projectActions.actions.stopNamedAria",{name:Ie.name}):a("projectActions.actions.runNamedAria",{name:Ie.name}),children:de||P?s.jsx(I,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):ke?s.jsx(I,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(I,{name:ce,className:"h-5 w-5"})}),ue?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(I,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":a("projectActions.actions.chooseActionAria"),children:s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(en,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ws,{className:"flex items-center gap-2",onClick:he,children:[s.jsx(I,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Fr,{}),Z.map(W=>{const ge=W.icon||"play",we=W.id===er?"search":ul[ge]||"play",G=si(K,W.id),Se=N[G],Oe=!!Se,Ae=Se?.status==="stopping";return s.jsxs(ws,{className:"flex items-center gap-2",onClick:()=>{Fe(W,!0)},children:[s.jsx(I,{name:we,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:W.name}),Ae||Se?.status==="waiting-for-preview"?s.jsx(I,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Oe?s.jsx(I,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},W.id)})]})]})]}):s.jsxs("div",{className:Te("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:Me,disabled:$||de,className:Te("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":ke?a("projectActions.actions.stopNamedAria",{name:Ie.name}):a("projectActions.actions.runNamedAria",{name:Ie.name}),children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:de||P?s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):ke?s.jsx(I,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(I,{name:ce,className:"h-4 w-4"})})}),ue?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:be,className:Te(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":a("projectActions.actions.openPreview"),children:s.jsx(I,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:6,children:a("projectActions.actions.openPreview")})]}):null,s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:Te(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":a("projectActions.actions.chooseActionAria"),children:s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(en,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ws,{className:"flex items-center gap-2",onClick:he,children:[s.jsx(I,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:a("projectActions.actions.addNewAction")})]}),s.jsx(Fr,{}),Z.map(W=>{const ge=W.icon||"play",we=W.id===er?"search":ul[ge]||"play",G=si(K,W.id),Se=N[G],Oe=!!Se,Ae=Se?.status==="stopping";return s.jsxs(ws,{className:"flex items-center gap-2",onClick:()=>{Fe(W,!0)},children:[s.jsx(I,{name:we,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:W.name}),Ae||Se?.status==="waiting-for-preview"?s.jsx(I,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):Oe?s.jsx(I,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},W.id)})]})]})]})},Xa="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Yb="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Ho=i.memo(function(e){const n=ft.c(17),{visible:r,title:o,ariaLabel:a,onClick:c,className:l,Icon:d,iconClassName:f,pressed:m}=e,u=r===void 0?!0:r,p=m===void 0?!1:m;if(!u)return null;const y=l??Xa,g=p&&"bg-interactive-selection text-interactive-selection-foreground";let b;n[0]!==y||n[1]!==g?(b=Te(y,g),n[0]=y,n[1]=g,n[2]=b):b=n[2];const x=f??"h-[18px] w-[18px]";let h;n[3]!==d||n[4]!==x?(h=s.jsx(I,{name:d,className:x}),n[3]=d,n[4]=x,n[5]=h):h=n[5];let C;n[6]!==a||n[7]!==c||n[8]!==p||n[9]!==b||n[10]!==h?(C=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,"aria-label":a,"aria-pressed":p,className:b,children:h})}),n[6]=a,n[7]=c,n[8]=p,n[9]=b,n[10]=h,n[11]=C):C=n[11];let w;n[12]!==o?(w=s.jsx(Ft,{children:s.jsx("p",{children:o})}),n[12]=o,n[13]=w):w=n[13];let v;return n[14]!==C||n[15]!==w?(v=s.jsxs(Et,{children:[C,w]}),n[14]=C,n[15]=w,n[16]=v):v=n[16],v}),Qb=i.memo(function(e){const n=ft.c(42),{isMobile:r,githubAuthStatus:o,githubAccounts:a,githubAvatarUrl:c,githubLogin:l,isSwitchingGitHubAccount:d,handleGitHubAccountSwitch:f}=e,{t:m}=Nt();if(!o?.connected||r)return null;if(a.length>1){let g;n[0]===Symbol.for("react.memo_cache_sentinel")?(g=Te(Xa,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),n[0]=g):g=n[0];let b;n[1]!==l||n[2]!==m?(b=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[1]=l,n[2]=m,n[3]=b):b=n[3];let x;n[4]!==c||n[5]!==l||n[6]!==m?(x=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(I,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[4]=c,n[5]=l,n[6]=m,n[7]=x):x=n[7];let h;n[8]!==d||n[9]!==b||n[10]!==x?(h=s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:g,title:b,disabled:d,children:x})}),n[8]=d,n[9]=b,n[10]=x,n[11]=h):h=n[11];let C;n[12]!==m?(C=m("header.github.accountsTitle"),n[12]=m,n[13]=C):C=n[13];let w;n[14]!==C?(w=s.jsx(Ep,{className:"typography-ui-header font-semibold text-foreground",children:C}),n[14]=C,n[15]=w):w=n[15];let v;n[16]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx(Fr,{}),n[16]=v):v=n[16];let S;if(n[17]!==a||n[18]!==f||n[19]!==d||n[20]!==m){let A;n[22]!==f||n[23]!==d||n[24]!==m?(A=D=>{const N=D.user,B=!!D.current,T=D.source==="gh-cli"?m("header.github.accountSource.cli"):m("header.github.accountSource.oauth");return s.jsxs(ws,{className:"gap-2",disabled:d,onSelect:()=>{B||f(D.id)},children:[N?.avatarUrl?s.jsx("img",{src:N.avatarUrl,alt:N.login?m("header.github.avatarWithLogin",{login:N.login}):m("header.github.avatar"),className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:s.jsx(I,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:N?.name?.trim()||N?.login||"GitHub"}),N?.login?s.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[s.jsx("span",{className:"font-mono",children:N.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:T})]}):null]}),B?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]},D.id)},n[22]=f,n[23]=d,n[24]=m,n[25]=A):A=n[25],S=a.map(A),n[17]=a,n[18]=f,n[19]=d,n[20]=m,n[21]=S}else S=n[21];let k;n[26]!==w||n[27]!==S?(k=s.jsxs(en,{align:"end",className:"w-64",children:[w,v,S]}),n[26]=w,n[27]=S,n[28]=k):k=n[28];let j;return n[29]!==h||n[30]!==k?(j=s.jsxs(tn,{children:[h,k]}),n[29]=h,n[30]=k,n[31]=j):j=n[31],j}let u;n[32]!==l||n[33]!==m?(u=l?m("header.github.connectedWithLogin",{login:l}):m("header.github.connected"),n[32]=l,n[33]=m,n[34]=u):u=n[34];let p;n[35]!==c||n[36]!==l||n[37]!==m?(p=c?s.jsx("img",{src:c,alt:l?m("header.github.avatarWithLogin",{login:l}):m("header.github.avatar"),className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx(I,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"}),n[35]=c,n[36]=l,n[37]=m,n[38]=p):p=n[38];let y;return n[39]!==u||n[40]!==p?(y=s.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:u,children:p}),n[39]=u,n[40]=p,n[41]=y):y=n[41],y}),Jb=i.memo(function(e){const n=ft.c(84),{isDesktopApp:r,currentInstanceLabel:o,compactCurrentInstanceLabel:a,currentInstanceIsLocal:c,isDesktopServicesOpen:l,setIsDesktopServicesOpen:d,refreshCurrentInstanceLabel:f,desktopServicesTab:m,setDesktopServicesTab:u,quotaResultsLength:p,fetchAllQuotas:y,servicesTabItems:g,quotaLastUpdated:b,quotaDisplayMode:x,quotaDisplayTabItems:h,handleDisplayModeChange:C,handleUsageRefresh:w,isQuotaLoading:v,isUsageRefreshSpinning:S,hasRateLimits:k,rateLimitGroups:j,expandedFamilies:A,toggleFamilyExpanded:D,shortcutLabel:N,showDevShutdown:B,isDevShutdownInFlight:T,onDevShutdown:E,remoteUpdateInfo:_,remoteUpdateChecking:R,remoteUpdateError:z,onOpenRemoteUpdate:V,showPredValues:$,timeFormatPreference:M}=e,{t:te}=Nt();let re;n[0]!==m||n[1]!==y||n[2]!==p||n[3]!==f||n[4]!==d?(re=Fe=>{d(Fe),Fe&&(f(),m==="usage"&&p===0&&y())},n[0]=m,n[1]=y,n[2]=p,n[3]=f,n[4]=d,n[5]=re):re=n[5];let Q;n[6]!==o||n[7]!==r||n[8]!==te?(Q=r?te("header.services.openWithCurrent",{current:o}):te("header.services.open"),n[6]=o,n[7]=r,n[8]=te,n[9]=Q):Q=n[9];const H=r?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8";let X;n[10]!==H?(X=Te(Xa,H),n[10]=H,n[11]=X):X=n[11];let oe;n[12]===Symbol.for("react.memo_cache_sentinel")?(oe=s.jsx(I,{name:"stack",className:"h-[18px] w-[18px]"}),n[12]=oe):oe=n[12];let fe;n[13]!==a||n[14]!==r?(fe=r?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:a}):null,n[13]=a,n[14]=r,n[15]=fe):fe=n[15];let ve;n[16]!==Q||n[17]!==X||n[18]!==fe?(ve=s.jsx(Mt,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":Q,className:X,children:[oe,fe]})})}),n[16]=Q,n[17]=X,n[18]=fe,n[19]=ve):ve=n[19];let ie;n[20]!==o||n[21]!==r||n[22]!==N||n[23]!==te?(ie=r?te("header.services.tooltip.currentInstanceWithShortcuts",{current:o,toggle:N("toggle_services_menu"),nextTab:N("cycle_services_tab")}):te("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]=te,n[24]=ie):ie=n[24];let Ne;n[25]!==ie?(Ne=s.jsx(Ft,{children:s.jsx("p",{children:ie})}),n[25]=ie,n[26]=Ne):Ne=n[26];let K;n[27]!==ve||n[28]!==Ne?(K=s.jsxs(Et,{children:[ve,Ne]}),n[27]=ve,n[28]=Ne,n[29]=K):K=n[29];let pe;n[30]!==y||n[31]!==p||n[32]!==u?(pe=Fe=>{const he=Fe;u(he),he==="usage"&&p===0&&y()},n[30]=y,n[31]=p,n[32]=u,n[33]=pe):pe=n[33];let L;n[34]!==m||n[35]!==g||n[36]!==pe?(L=s.jsx("div",{className:"sticky top-0 z-20 px-2 pt-1.5 pb-px",children:s.jsx("div",{className:"h-9",children:s.jsx(Ro,{items:g,activeId:m,onSelect:pe,layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",activePillButtonClassName:"h-8",className:"h-full"})})}),n[34]=m,n[35]=g,n[36]=pe,n[37]=L):L=n[37];let se;n[38]!==c||n[39]!==m||n[40]!==r||n[41]!==l||n[42]!==V||n[43]!==R||n[44]!==z||n[45]!==_||n[46]!==d||n[47]!==te?(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:te("header.services.remoteUpdate.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:_?.available?te("header.services.remoteUpdate.available",{version:_.version||""}):R?te("header.services.remoteUpdate.checking"):z||te("header.services.remoteUpdate.upToDate")})]}),_?.available?s.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:V,children:te("header.services.remoteUpdate.actions.open")}):null]})}),s.jsx(Rp,{embedded:!0,open:l&&m==="instance",onOpenChange:ey,onHostSwitched:()=>d(!1)})]}):null,n[38]=c,n[39]=m,n[40]=r,n[41]=l,n[42]=V,n[43]=R,n[44]=z,n[45]=_,n[46]=d,n[47]=te,n[48]=se):se=n[48];let Z;n[49]!==m||n[50]!==l?(Z=m==="mcp"?s.jsx(jm,{active:l&&m==="mcp"}):null,n[49]=m,n[50]=l,n[51]=Z):Z=n[51];let je;n[52]!==m||n[53]!==A||n[54]!==C||n[55]!==w||n[56]!==k||n[57]!==v||n[58]!==S||n[59]!==x||n[60]!==h||n[61]!==b||n[62]!==j||n[63]!==$||n[64]!==te||n[65]!==M||n[66]!==D?(je=m==="usage"?s.jsxs("div",{className:"overflow-x-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--interactive-border)] px-4 py-2.5",children:[s.jsxs("div",{className:"flex min-w-0 items-baseline gap-2",children:[s.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:te("header.services.rateLimits")}),s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Mm(b,M)})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"h-7 w-[10.5rem]",children:s.jsx(Ro,{items:h,activeId:x,onSelect:Fe=>{C(Fe)},layoutMode:"fit",variant:"active-pill",activePillInsetClassName:"gap-0.5 px-px py-0",className:"h-full"})}),s.jsx("button",{type:"button",className:Te("inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors","hover:text-foreground hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),onClick:w,disabled:v||S,"aria-label":te("header.services.refreshRateLimitsAria"),children:s.jsx(I,{name:"refresh",className:Te("h-4 w-4",S&&"animate-spin")})})]})]}),k?null:s.jsx("div",{className:"px-4 py-5 text-center",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:te("header.services.noRateLimits")})}),s.jsx("div",{className:"py-2",children:j.map((Fe,he)=>{const Ie=A[Fe.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(Po,{providerId:Fe.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:Fe.providerName})]}),Fe.entries.length===0&&(!Fe.modelFamilies||Fe.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:Fe.error??te("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[Fe.entries.map(me=>{const[ce,xe]=me,ke=x==="remaining"?xe.remainingPercent:xe.usedPercent,de=Sa(xe.usedPercent,xe.resetAt,xe.windowSeconds,ce),P=de?.dailyAllocationPercent!=null?x==="remaining"?100-ci(de.elapsedRatio):ci(de.elapsedRatio):null,F=To(xe.valueLabel,ke),ue=Uf(xe.resetAt,xe.resetAfterFormatted??xe.resetAtFormatted,M);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:yc(ce)}),ue?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:ue}):null]}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:F==="-"?"":F})]}),s.jsx(Da,{percent:ke,tonePercent:xe.usedPercent,className:"h-1.5",expectedMarkerPercent:P}),de&&$?s.jsx(Ia,{paceInfo:de,compact:!0}):null]},`${Fe.providerId}-${ce}`)}),Fe.modelFamilies&&Fe.modelFamilies.length>0?s.jsx("div",{className:"space-y-0.5",children:Fe.modelFamilies.map(me=>{const ce=me.familyId??"other",xe=Ie.includes(ce);return s.jsxs(no,{open:xe,onOpenChange:()=>D(Fe.providerId,ce),children:[s.jsxs(_o,{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:me.familyLabel}),xe?s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ro,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:me.models.map(ke=>{const[de,P]=ke,F=x==="remaining"?P.remainingPercent:P.usedPercent,ue=Sa(P.usedPercent,P.resetAt,P.windowSeconds),be=ue?.dailyAllocationPercent!=null?x==="remaining"?100-ci(ue.elapsedRatio):ci(ue.elapsedRatio):null,W=To(P.valueLabel,F);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:vm(de)}),s.jsx("span",{className:"typography-ui-label tabular-nums text-foreground",children:W==="-"?"":W})]}),s.jsx(Da,{percent:F,tonePercent:P.usedPercent,className:"h-1.5",expectedMarkerPercent:be}),ue&&$?s.jsx(Ia,{paceInfo:ue,compact:!0}):null]},`${Fe.providerId}-${de}`)})})})]},ce)})}):null]})]},Fe.providerId)})})]}):null,n[52]=m,n[53]=A,n[54]=C,n[55]=w,n[56]=k,n[57]=v,n[58]=S,n[59]=x,n[60]=h,n[61]=b,n[62]=j,n[63]=$,n[64]=te,n[65]=M,n[66]=D,n[67]=je):je=n[67];let De;n[68]!==T||n[69]!==E||n[70]!==B||n[71]!==te?(De=B?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mx-4 my-2 border-t border-[var(--interactive-border)]"}),s.jsx("div",{className:"px-2 pb-2",children:s.jsx(ws,{disabled:T,onSelect:()=>{E()},children:te("header.services.shutdownDev")})})]}):null,n[68]=T,n[69]=E,n[70]=B,n[71]=te,n[72]=De):De=n[72];let Le;n[73]!==L||n[74]!==se||n[75]!==Z||n[76]!==je||n[77]!==De?(Le=s.jsxs(en,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto bg-[var(--surface-elevated)] p-0",children:[L,se,Z,je,De]}),n[73]=L,n[74]=se,n[75]=Z,n[76]=je,n[77]=De,n[78]=Le):Le=n[78];let Me;return n[79]!==l||n[80]!==re||n[81]!==K||n[82]!==Le?(Me=s.jsxs(tn,{open:l,onOpenChange:re,children:[K,Le]}),n[79]=l,n[80]=re,n[81]=K,n[82]=Le,n[83]=Me):Me=n[83],Me}),Xb=(t,e)=>t===e?!0:!t||!e?!1:t.totalTokens===e.totalTokens&&t.percentage===e.percentage&&t.contextLimit===e.contextLimit&&(t.outputLimit??0)===(e.outputLimit??0)&&(t.normalizedOutput??0)===(e.normalizedOutput??0)&&t.thresholdLimit===e.thresholdLimit&&(t.lastMessageId??"")===(e.lastMessageId??""),Zb=t=>{const e=t.trim();if(!e)return"";const n=e.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<e.length?`${a}...`:a}return e.length>12?`${e.slice(0,9).trimEnd()}...`:e},Mm=(t,e)=>{if(!t)return"-";try{return Hf(t,e,{fallback:"-"})}catch{return"-"}},Tn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},ii=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,nu=({onToggleLeftDrawer:t,onToggleRightDrawer:e,leftDrawerOpen:n,rightDrawerOpen:r})=>{const{t:o}=Nt(),a=Ee(q=>q.setSessionSwitcherOpen),c=Ee(q=>q.toggleSidebar),l=Ee(q=>q.isSidebarOpen),d=Ee(q=>q.toggleBottomTerminal),f=Ee(q=>q.toggleRightSidebar),m=Ee(q=>q.openContextOverview),u=Ee(q=>q.openContextPlan),p=Ee(q=>q.openContextBrowser),y=Ee(q=>q.openContextPanelTab),g=Ee(q=>q.closeContextPanel),b=Ee(q=>q.contextPanelByDirectory),x=Ee(q=>q.activeMainTab),h=Ee(q=>q.setActiveMainTab),C=Ee(q=>q.shortcutOverrides),w=Ee(q=>q.timeFormatPreference),v=ss(q=>q.getCurrentModel),S=Xn(),[k,j]=i.useState(!1),A=ut(q=>q.getContextUsage),D=ut(q=>!!q.newSessionDraft?.open),N=ut(q=>q.currentSessionId),B=Mp(N??""),T=Gf(N??null),E=jr(q=>q.activeSessions),_=wc(),R=Ss(q=>q.activeProjectId?q.projects.find(rt=>rt.id===q.activeProjectId)??null:null),z=i.useMemo(()=>{if(!R)return null;const q=R.label?.trim();if(q)return q;const rt=R.path.split(/[\\/]/).filter(Boolean);return rt[rt.length-1]??null},[R]),V=mn(q=>q.results),$=mn(q=>q.fetchAllQuotas),M=mn(q=>q.isLoading),te=mn(q=>q.lastUpdated),re=mn(q=>q.displayMode),Q=mn(q=>q.showPredValues),H=mn(q=>q.dropdownProviderIds),X=mn(q=>q.loadSettings),oe=mn(q=>q.setDisplayMode),{isMobile:fe}=Or(),ve=Mi(q=>q.status),ie=Mi(q=>q.setStatus),Ne=i.useRef(null),[K,pe]=i.useState(()=>typeof window>"u"?!1:dr()),L=i.useMemo(()=>_a(),[]),se=Kf(),[Z,je]=i.useState(!1),De=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),Le=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32",[]),Me=i.useMemo(()=>{if(typeof window>"u")return null;const q=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof q=="number"&&Number.isFinite(q)&&q>0)return q;if(typeof navigator>"u")return null;const rt=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!rt)return null;const ht=Number.parseInt(rt[1],10),Tt=Number.parseInt(rt[2],10);return Number.isNaN(ht)?null:ht===10?Tt:ht},[]);tt.useEffect(()=>{typeof window>"u"||pe(dr())},[]);const Fe=v(),he=Fe&&typeof Fe.limit=="object"&&Fe.limit!==null?Fe.limit:null,Ie=he&&typeof he.context=="number"?he.context:0,me=he&&typeof he.output=="number"?he.output:0,ce=A(Ie,me),[xe,ke]=i.useState(null),de=!N||B;tt.useEffect(()=>{if(!N){ke(q=>q===null?q:null);return}if(ce&&ce.totalTokens>0){ke(q=>Xb(q,ce)?q:ce);return}de&&ke(q=>q===null?q:null)},[ce,N,de]);const P=Ee(q=>q.isSessionSwitcherOpen),F=ve?.connected?ve.user?.avatarUrl??null:null,ue=ve?.connected?ve.user?.login??null:null,be=ve?.accounts??[],[W,ge]=i.useState(!1),[we,G]=i.useState(!1),[Se,Oe]=i.useState(!1),[Ae,J]=i.useState(!1),[O,ae]=i.useState("Local"),[ne,Be]=i.useState(!0),[Ye,He]=i.useState(!1),[Je,nt]=i.useState(null),[xt,bt]=i.useState(!1),[_e,Qe]=i.useState(null),st=i.useMemo(()=>Zb(O),[O]),[pt,At]=i.useState(K?"instance":"usage"),[vt,kt]=i.useState("usage");tt.useEffect(()=>{!K&&pt==="instance"&&At("usage")},[pt,K]);const et=i.useMemo(()=>Yr(),[]),_t=!et&&x==="chat"&&!!xe&&xe.totalTokens>0,ns=xe&&xe.contextLimit>0?Math.min(999,xe.totalTokens/xe.contextLimit*100):0,Kt=i.useCallback(async()=>{if(!(typeof window>"u"||!K))try{if(eo()){ae("Local"),Be(!0);return}Be(!1);const q=await qf(),rt=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,ht=Hr();if(ht&&Na(ht,rt)){ae("Local"),Be(!0);return}const Tt=q.hosts.find(Yt=>ht?Na(ht,Yf(Yt)):!1);if(Tt?.label?.trim()){ae(Qf(Tt.label.trim()));return}ae("Instance")}catch{ae("Local"),Be(!0)}},[K]);tt.useEffect(()=>{Kt()},[Kt]);const qe=i.useCallback(async()=>{if(ne){nt(null),Qe(null);return}bt(!0),Qe(null);try{const q=new URLSearchParams({appType:"web",instanceMode:"remote"}),rt=await Cs(`/api/openchamber/update-check?${q.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!rt.ok)throw new Error(`Server responded with ${rt.status}`);const ht=await rt.json();nt({available:ht.available??!1,version:ht.version,currentVersion:ht.currentVersion??"unknown",body:ht.body,nextSuggestedCheckInSec:typeof ht.nextSuggestedCheckInSec=="number"?ht.nextSuggestedCheckInSec:void 0,packageManager:ht.packageManager,updateCommand:ht.updateCommand})}catch(q){nt(null),Qe(q instanceof Error?q.message:o("header.services.remoteUpdate.error"))}finally{bt(!1)}},[ne,o]);i.useEffect(()=>{nt(null),Qe(null),He(!1)},[ne,O]),i.useEffect(()=>{if(!K||ne)return;const q=3e3,rt=3600*1e3;let ht=!1,Tt=null;const Yt=ts=>{Tt=window.setTimeout(()=>{if(ht||typeof document<"u"&&document.visibilityState!=="visible"){Yt(rt);return}qe().finally(()=>{ht||Yt(rt)})},ts)};return Yt(q),()=>{ht=!0,Tt!==null&&window.clearTimeout(Tt)}},[qe,ne,O,K]);const gt=i.useCallback(()=>{if(Je?.available){He(!0);return}qe()},[qe,Je?.available]);$x();const Xe=mn(q=>q.selectedModels),jt=mn(q=>q.expandedFamilies),Pt=mn(q=>q.toggleFamilyExpanded),is=i.useMemo(()=>{const q=[];for(const rt of Sm){if(!H.includes(rt.id))continue;const ht=V.find(Ls=>Ls.providerId===rt.id),Tt=ht?.usage?.windows??{},Yt=ht?.usage?.models,ts=Object.entries(Tt),ds={providerId:rt.id,providerName:rt.name,entries:ts,error:ht&&!ht.ok&&ht.configured?ht.error:void 0};if(Yt&&Object.keys(Yt).length>0){const Ls=Xe[rt.id]??[],Ks=Ls.length>0,qn=zx(Yt,rt.id),Bn=Wx(rt.id),Jr=Ux(Bn);ds.modelFamilies=[];for(const xn of Jr){const nn=qn.get(xn.id)??[];if(nn.length===0)continue;const un=Ks?nn.filter(Nn=>Ls.includes(Nn)):nn;if(un.length===0)continue;const Sn=[];for(const Nn of un){const mr=Yt[Nn];if(mr?.windows){const or=Object.entries(mr.windows);or.length>0&&Sn.push([Nn,or[0][1]])}}Sn.length>0&&ds.modelFamilies.push({familyId:xn.id,familyLabel:xn.label,models:Sn})}const gn=qn.get(null)??[],Xr=Ks?gn.filter(xn=>Ls.includes(xn)):gn;if(Xr.length>0){const xn=[];for(const nn of Xr){const un=Yt[nn];if(un?.windows){const Sn=Object.entries(un.windows);Sn.length>0&&xn.push([nn,Sn[0][1]])}}xn.length>0&&ds.modelFamilies.push({familyId:null,familyLabel:o("header.services.modelFamily.other"),models:xn})}}(ts.length>0||ds.modelFamilies&&ds.modelFamilies.length>0||ds.error)&&q.push(ds)}return q},[H,V,Xe,o]),Bt=is.length>0;i.useEffect(()=>{X()},[X]);const Gt=i.useCallback(async q=>{oe(q);try{await pc({usageDisplayMode:q})}catch(rt){console.warn("Failed to update usage display mode:",rt)}},[oe]),es=i.useCallback(()=>{if(Ae)return;J(!0);const q=new Promise(rt=>setTimeout(rt,500));Promise.all([$(),q]).finally(()=>{J(!1)})},[$,Ae]),Wt=i.useMemo(()=>N?_.find(q=>q.id===N)??E.find(q=>q.id===N)??T??Jf().find(q=>q.id===N)??null:null,[N,T,E,_]),Lt=i.useRef(null),[Ut,rs]=i.useState(0);i.useEffect(()=>{if(!N){Lt.current&&(Lt.current=null,rs(Tt=>Tt+1));return}if(Wt){Lt.current={sessionId:N,session:Wt,expiresAt:Date.now()+2e3};return}const q=Lt.current;if(!q||q.sessionId!==N)return;const rt=q.expiresAt-Date.now();if(rt<=0){Lt.current=null,rs(Tt=>Tt+1);return}const ht=window.setTimeout(()=>{Lt.current?.sessionId===N&&(Lt.current=null),rs(Tt=>Tt+1)},rt);return()=>{window.clearTimeout(ht)}},[N,Wt]);const $t=(()=>{if(Wt)return Wt;if(!N)return null;const q=Lt.current;return q&&q.sessionId===N&&q.expiresAt>Date.now()?q.session:null})(),ls=ut(q=>N?q.worktreeMetadata.get(N)?.path??"":""),xs=ut(q=>N?q.worktreeMetadata.get(N)?.branch?.trim()??null:null),Ct=Xf(q=>N?q.getAttachment(N):void 0),Vt=i.useMemo(()=>Ct?Fp(Ct,{pending:o("gitView.empty.worktreeSetupInProgress")}):null,[o,Ct]),yt=i.useMemo(()=>Ct?Ct.legacy?"legacy":Ct.degraded?"degraded":Ct.worktreeStatus==="pending"?"pending":Ct.worktreeStatus==="missing"?"missing":Ct.worktreeStatus==="invalid"?"invalid":Ct.attentionReason?"attention":null:null,[Ct]),us=i.useMemo(()=>Tn(ls||""),[ls]),cs=i.useMemo(()=>{const q=typeof $t?.directory=="string"?$t.directory:"";return Tn(q||"")},[$t?.directory]),Ue=ut(q=>q.newSessionDraft?.open?Tn(q.newSessionDraft.bootstrapPendingDirectory??q.newSessionDraft.directoryOverride??""):""),Ge=i.useMemo(()=>us||cs||Ue,[Ue,cs,us]),wt=ut(q=>{const rt=Tn(us||cs||"");if(!rt)return null;for(const ht of q.availableWorktreesByProject.values()){const Yt=ht.find(ts=>Tn(ts.path)===rt)?.branch?.trim();if(Yt)return Yt}return null}),Dt=Op(Ge||null)||xs||wt,bs=i.useMemo(()=>{if(!N)return z??"OpenChamber";const q=$t?.title?.trim();return q&&q.length>0?q:"Untitled Session"},[z,$t?.title,N]),fs=i.useMemo(()=>Tn(Ge||R?.path||""),[R?.path,Ge]),os=i.useMemo(()=>R?{id:R.id,path:R.path}:null,[R]),qt=i.useRef(null);i.useEffect(()=>{!os||!fs||(qt.current={projectRef:os,directory:fs})},[fs,os]);const ln=i.useMemo(()=>os&&fs?{projectRef:os,directory:fs}:qt.current,[fs,os]),ps=vc(q=>q.planModeEnabled),Fs=ut(q=>q.isSessionPlanAvailable),Ws=ps&&N?Fs(N):!1,sn=Ws,Dn=i.useRef("");i.useEffect(()=>{if(!ps){Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat");return}if(!N)return;const q=`${N||"none"}:${cs||"none"}:${$t?.time?.created||0}:${$t?.slug||"none"}`;Dn.current!==q&&(Dn.current=q),!Ws&&Ee.getState().activeMainTab==="plan"&&Ee.getState().setActiveMainTab("chat")},[ps,Ws,$t?.slug,$t?.time?.created,N,cs]);const jn=i.useCallback(async q=>{if(!(!q||W)){ge(!0);try{const rt=S.github?await S.github.authActivate(q):await(async()=>{const ht=await Cs("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:q})}),Tt=await ht.json().catch(()=>null);if(!ht.ok||!Tt)throw new Error(Tt?.error||ht.statusText);return Tt})();ie(rt)}catch(rt){console.error("Failed to switch GitHub account:",rt)}finally{ge(!1)}}},[W,S.github,ie]),ye=i.useCallback(()=>{if(typeof document>"u")return;const q=document.activeElement;if(!q)return;const rt=q.tagName;(rt==="INPUT"||rt==="TEXTAREA"||rt==="SELECT"||q.isContentEditable)&&q.blur()},[]),Ze=i.useCallback(()=>{if(fe){ye(),a(!P);return}c()},[ye,fe,P,a,c]),ct=i.useCallback(()=>{Gr("desktop_open_draft_mini_chat_window",{directory:Tn(Ge||R?.path||""),projectId:R?.id??null,apiBaseUrl:Hr(),clientToken:Hl()}).catch(q=>{console.warn("[header] failed to open draft mini chat window",q)})},[R?.id,R?.path,Ge]),It=i.useCallback(()=>{if(D){ct();return}N&&Gr("desktop_open_session_mini_chat_window",{sessionId:N,directory:Tn(Ge||R?.path||""),apiBaseUrl:Hr(),clientToken:Hl()}).catch(q=>{console.warn("[header] failed to open session mini chat window",q)})},[R?.path,N,ct,D,Ge]),Ht=i.useCallback(()=>{const q=Tn(Ge||"");if(!q)return;const rt=b[q];if(ii(rt)==="context"){g(q);return}m(q)},[g,b,m,Ge]),mt=i.useMemo(()=>{const q=Tn(Ge||"");if(!q)return!1;const rt=b[q];return ii(rt)==="context"},[b,Ge]),ms=i.useCallback(()=>{const q=Tn(Ge||"");if(!q)return;const rt=b[q];if(ii(rt)==="plan"){g(q);return}u(q)},[g,b,u,Ge]),hs=i.useCallback(()=>{const q=Tn(Ge||"");if(!q)return;const rt=b[q];if(ii(rt)==="diff"){g(q);return}y(q,{mode:"diff",stagedDiff:!1})},[g,b,y,Ge]),Ns=i.useCallback(()=>{const q=Tn(Ge||"");if(!q)return;const rt=b[q];if(ii(rt)==="browser"){g(q);return}p(q)},[g,b,p,Ge]),ys=i.useMemo(()=>{const q=Tn(Ge||"");if(!q)return!1;const rt=b[q];return ii(rt)==="plan"},[b,Ge]),Is=i.useMemo(()=>{const q=Tn(Ge||"");if(!q)return!1;const rt=b[q];return ii(rt)==="diff"},[b,Ge]),Mn=i.useMemo(()=>{const q=Tn(Ge||"");if(!q)return!1;const rt=b[q];return ii(rt)==="browser"},[b,Ge]),$s=Xa,hn=Yb,Fn=i.useMemo(()=>we?"services":n?"sessions":r?"git":x,[x,we,n,r]),Zn=i.useCallback(()=>{G(!1),n&&t&&t(),r&&e&&e(),!t&&P&&a(!1)},[P,n,t,e,r,a]),cn=i.useCallback(()=>{n||G(!1),t?.()},[n,t]),We=i.useCallback(()=>{r||G(!1),e?.()},[e,r]),Xt=i.useMemo(()=>K&&De&&!Z?"5.5rem":se?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":(!K||Le)&&!et?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,Z,De,se,et,Le]);tt.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Xt)},[Xt]);const As=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ps=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";tt.useEffect(()=>{if(!K||!De){je(!1);return}let q=!1;const rt=async()=>{try{const Tt=await Gr("desktop_is_window_fullscreen");q||je(Tt===!0)}catch{q||je(!1)}},ht=()=>{rt()};return rt(),window.addEventListener("openchamber:window-resized",ht),()=>{q=!0,window.removeEventListener("openchamber:window-resized",ht)}},[K,De]);const zs=i.useMemo(()=>!K||!De||Me===null?"":Me>=26?"h-12":Me<=15?"h-14":"",[K,De,Me]),Qs=i.useMemo(()=>{if(!(K&&!Le||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))"}},[K,et,Le]),Us=i.useCallback(()=>{if(typeof document>"u")return;const q=Ne.current?.getBoundingClientRect().height;q&&document.documentElement.style.setProperty("--oc-header-height",`${q}px`)},[]);tt.useEffect(()=>{if(typeof window>"u")return;Us();const q=Ne.current;if(!q||typeof ResizeObserver>"u")return()=>{};let rt=0;const ht=()=>{rt||(rt=requestAnimationFrame(()=>{rt=0,Us()}))},Tt=new ResizeObserver(ht);return Tt.observe(q),window.addEventListener("resize",ht),window.addEventListener("orientationchange",ht),()=>{rt&&cancelAnimationFrame(rt),Tt.disconnect(),window.removeEventListener("resize",ht),window.removeEventListener("orientationchange",ht)}},[Us]),tt.useEffect(()=>{Us()},[Us,fe,zs]);const Os=i.useCallback(async q=>{const rt=q.target;rt.closest(".app-region-no-drag")||rt.closest("button, a, input, select, textarea")||q.button===0&&K&&await hp()},[K]),On=i.useMemo(()=>{if(fe){const q=[{id:"chat",label:o("layout.mainTab.chat"),icon:"chat-4"}];return sn&&q.push({id:"plan",label:o("layout.mainTab.plan"),icon:"file-text"}),q.push({id:"diff",label:o("layout.mainTab.diff"),icon:"diff"},{id:"files",label:o("layout.mainTab.files"),icon:"folder-6"},{id:"terminal",label:o("layout.mainTab.terminal"),icon:"terminal-box"},{id:"context",label:o("layout.mainTab.context"),icon:"file-list-2"},{id:"diagram",label:o("layout.mainTab.diagram"),icon:"file"}),q}return[]},[fe,sn,o]),fr=i.useCallback(q=>Va(di(q,C)),[C]);tt.useEffect(()=>{!fe&&(x==="git"||x==="terminal"||x==="diff"||x==="files"||x==="context")&&h("chat")},[x,fe,h]);const Kn=i.useMemo(()=>{const q=[];return K&&q.push({value:"instance",label:o("layout.services.instance"),icon:s.jsx(I,{name:"server",className:"h-3.5 w-3.5"})}),q.push({value:"usage",label:o("layout.services.usage"),icon:s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"})},{value:"mcp",label:"MCP",icon:s.jsx(Kl,{className:"h-3.5 w-3.5"})}),q},[K,o]),gs=i.useMemo(()=>Kn.map(q=>({id:q.value,label:q.label,icon:q.icon})),[Kn]),Ts=i.useMemo(()=>{if(typeof window>"u"||K||et)return!1;const q=window.location.hostname;return q==="localhost"||q==="127.0.0.1"||q==="::1"},[K,et]),Sr=i.useCallback(async()=>{if(k)return;j(!0),Oe(!1);const q=[];let rt=!1;try{try{for(const[,ht]of _s.getState().sessions.entries())for(const Tt of ht.tabs)Tt.previewUrl&&q.push(Tt.previewUrl)}catch{}try{await pp({})}catch{}try{(await Cs("/api/system/dev-shutdown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({previewUrls:q})})).ok?rt=!0:rt=(await Cs("/api/system/shutdown",{method:"POST"})).ok}catch{}}finally{rt||j(!1)}},[k,Oe]),Ln=i.useMemo(()=>[{value:"usage",label:o("header.services.used")},{value:"remaining",label:o("header.services.remaining")}],[o]),pn=i.useMemo(()=>Ln.map(q=>({id:q.value,label:q.label})),[Ln]),Nr=i.useMemo(()=>[{id:"usage",label:o("layout.services.usage"),icon:s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"})},{id:"mcp",label:"MCP",icon:s.jsx(Kl,{className:"h-3.5 w-3.5"})}],[o]);tt.useEffect(()=>{const q=rt=>{if(jc(rt)&&!rt.shiftKey&&!rt.altKey){const ht=parseInt(rt.key,10);ht>=1&&ht<=On.length&&(rt.preventDefault(),fe&&(ye(),Zn()),h(On[ht-1].id))}};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[ye,Zn,fe,h,On]),tt.useEffect(()=>{const q=rt=>{const ht=di("toggle_services_menu",C);if(oa(rt,ht)){rt.preventDefault(),Se?Oe(!1):(Oe(!0),Kt(),pt==="usage"&&V.length===0&&$());return}const Tt=di("cycle_services_tab",C);if(oa(rt,Tt)){rt.preventDefault();const ts=Kn.map(qn=>qn.value);if(ts.length===0)return;const ds=ts.indexOf(pt),Ls=ds===-1?0:(ds+1)%ts.length,Ks=ts[Ls];At(Ks),Oe(!0),Kt(),Ks==="usage"&&V.length===0&&$();return}const Yt=di("toggle_context_plan",C);oa(rt,Yt)&&(rt.preventDefault(),ms())};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[C,Se,pt,Kn,V.length,$,Kt,ms]);const kr=q=>{const rt=x===q.id,ht=q.icon==="diff",Tt=ht?null:q.icon,Yt=q.id==="chat",ts=Ls=>ht?s.jsx(Zd,{size:Ls}):Tt?s.jsx(I,{name:Tt,className:`h-${Ls/4} w-${Ls/4}`}):null,ds=s.jsxs("button",{type:"button",onClick:()=>h(q.id),className:Te("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",rt?"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",Yt&&!fe&&"min-w-[100px] justify-center"),"aria-label":q.label,"aria-selected":rt,role:"tab",children:[fe?ts(20):s.jsxs(s.Fragment,{children:[ts(16),s.jsx("span",{className:"header-tab-label",children:q.label})]}),q.badge!==void 0&&q.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:q.badge})]});return s.jsx(i.Fragment,{children:ds},q.id)},Lr=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":Is,onClick:hs,className:$s,children:s.jsxs("span",{className:"relative h-5 w-5 overflow-hidden rounded-[2px]",children:[s.jsx("span",{className:"absolute left-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[4px] top-[4px] h-3 w-[5px] bg-[var(--status-success)]/25"}),s.jsx(I,{name:"layout-column",className:"absolute inset-0 h-5 w-5"})]})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.actions.toggleChangesPanel")})})]}),Cr=s.jsxs(s.Fragment,{children:[sn&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.actions.openPlanAria"),onClick:ms,className:Te($s,ys&&"bg-[var(--interactive-hover)]"),children:s.jsx(I,{name:"file-text",className:"h-[18px] w-[18px]"})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.actions.planWithShortcut",{shortcut:fr("toggle_context_plan")})})})]}),s.jsx(wb,{directory:fs,className:"mr-1"}),s.jsx(Jb,{isDesktopApp:K,currentInstanceLabel:O,compactCurrentInstanceLabel:st,currentInstanceIsLocal:ne,isDesktopServicesOpen:Se,setIsDesktopServicesOpen:Oe,refreshCurrentInstanceLabel:Kt,desktopServicesTab:pt,setDesktopServicesTab:At,quotaResultsLength:V.length,fetchAllQuotas:$,servicesTabItems:gs,quotaLastUpdated:te,quotaDisplayMode:re,showPredValues:Q,quotaDisplayTabItems:pn,handleDisplayModeChange:Gt,handleUsageRefresh:es,isQuotaLoading:M,isUsageRefreshSpinning:Ae,hasRateLimits:Bt,rateLimitGroups:is,expandedFamilies:jt,toggleFamilyExpanded:Pt,shortcutLabel:fr,showDevShutdown:Ts,isDevShutdownInFlight:k,onDevShutdown:Sr,remoteUpdateInfo:Je,remoteUpdateChecking:xt,remoteUpdateError:_e,onOpenRemoteUpdate:gt,timeFormatPreference:w}),s.jsx(Ho,{title:o("header.actions.terminalPanelWithShortcut",{shortcut:fr("toggle_terminal")}),ariaLabel:o("header.actions.toggleTerminalPanelAria"),onClick:d,Icon:"terminal-box"}),fe?null:s.jsx(Ho,{title:o("contextPanel.browser.open"),ariaLabel:o("contextPanel.browser.open"),onClick:Ns,pressed:Mn,Icon:"global"}),s.jsx(Ho,{title:o("header.actions.rightSidebarWithShortcut",{shortcut:fr("toggle_right_sidebar")}),ariaLabel:o("header.actions.toggleRightSidebarAria"),onClick:f,Icon:"layout-right"}),s.jsx(Qb,{isMobile:fe,githubAuthStatus:ve,githubAccounts:be,githubAvatarUrl:F,githubLogin:ue,isSwitchingGitHubAccount:W,handleGitHubAccountSwitch:jn})]}),rr=L&&(D||!!N),js=()=>s.jsxs("div",{onMouseDown:Os,className:Te("app-region-drag relative flex h-12 select-none items-center pr-3",zs),style:Qs,role:"tablist","aria-label":o("header.navigation.mainAria"),children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:As}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:Ps}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[s.jsx(db,{children:s.jsxs("button",{type:"button","aria-label":o("sessions.switcher.openAria"),className:"app-region-no-drag mr-3 flex min-w-0 flex-col items-start rounded-md px-1 py-0.5 -my-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:D?o("sessions.switcher.draftTitle"):bs}),z||Dt||!D&&yt?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:[z?s.jsx("span",{className:"truncate",children:z}):null,Dt?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:Dt})]}):null,!D&&yt?s.jsxs("span",{className:Te("inline-flex min-w-0 items-center gap-0.5",yt==="attention"||yt==="invalid"||yt==="missing"?"text-status-warning":"text-muted-foreground/60"),children:[s.jsx(I,{name:"alert",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:Vt})]}):null]}):null]})}),On.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:On.map(q=>kr(q))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[_t&&xe?s.jsx(ub,{totalTokens:xe.totalTokens,percentage:ns,colorPercentage:xe.percentage,contextLimit:xe.contextLimit,outputLimit:xe.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:Ht,pressed:mt,className:rr?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,Lr,s.jsx(Ho,{visible:rr,title:o(D?"header.actions.newMiniChat":"header.actions.openSessionMiniChat"),ariaLabel:o(D?"header.actions.newMiniChatAria":"header.actions.openSessionMiniChatAria"),onClick:It,className:Te($s,"mr-1"),Icon:"picture-in-picture-2"}),Cr,s.jsx(fb,{visible:Le})]})]})]}),dn=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t?s.jsx("button",{type:"button",onClick:cn,className:Te(hn,Fn==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o(n?"header.actions.closeSessionsAria":"header.actions.openSessionsAria"),children:s.jsx(I,{name:"layout-left",className:"h-5 w-5"})}):P?s.jsx("button",{type:"button",onClick:()=>a(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.backAria"),children:s.jsx(I,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Ze,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":o("header.actions.openSessionsAria"),children:s.jsx(I,{name:"play-list-add",className:"h-5 w-5"})}),!t&&P&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o("header.sessions.title")})]}),(!P||!!t)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:s.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain",children:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":o("header.navigation.mainAria"),children:On.map(q=>{const rt=x===q.id,ht=q.icon==="diff",Tt=ht?null:q.icon;return s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{fe&&(ye(),Zn()),h(q.id)},"aria-label":q.label,"aria-selected":rt,role:"tab",className:Te(hn,"relative rounded-lg",Fn===q.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ht?s.jsx(Zd,{className:"h-5 w-5"}):Tt?s.jsx(I,{name:Tt,className:"h-5 w-5"}):null,q.badge!==void 0&&q.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:q.badge}),q.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":o("header.changes.availableAria")})]})}),s.jsx(Ft,{children:s.jsx("p",{children:q.label})})]},q.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[ln&&s.jsx(Em,{projectRef:ln.projectRef,directory:ln.directory,compact:!0,allowMobile:!0,className:"h-9"}),s.jsxs(tn,{open:we,onOpenChange:q=>{q&&(n&&t&&t(),r&&e&&e()),G(q),q&&V.length===0&&$()},children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":o("header.services.viewAria"),className:Te(hn,Fn==="services"&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(I,{name:"stack",className:"h-5 w-5"})})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("header.services.title")})})]}),s.jsx(en,{align:"end",sideOffset:0,positionerClassName:"!fixed !bottom-0 !left-0 !right-0 !top-[var(--oc-header-height,56px)] !transform-none",className:"h-full w-screen max-h-none rounded-none border-0 p-0 pt-1 overflow-hidden",children:s.jsxs("div",{className:"flex h-full flex-col bg-[var(--surface-elevated)]",children:[s.jsx("div",{className:"sticky top-0 z-20 bg-[var(--surface-elevated)] px-2 py-px",children:s.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-0",children:[s.jsx("div",{className:"h-10 min-w-0 flex-1",children:s.jsx(Ro,{items:Nr,activeId:vt,onSelect:q=>{const rt=q;kt(rt),rt==="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:()=>G(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover","aria-label":o("header.services.closeAria"),children:s.jsx(I,{name:"close",className:"h-5 w-5"})})]})}),vt==="mcp"&&s.jsx(jm,{active:we&&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:Mm(te,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:()=>Gt("usage"),className:Te("typography-ui-label px-1 pb-0.5 transition-colors",re==="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:()=>Gt("remaining"),className:Te("typography-ui-label px-1 pb-0.5 transition-colors",re==="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:Te("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:es,disabled:M||Ae,"aria-label":o("header.services.refreshRateLimitsAria"),children:s.jsx(I,{name:"refresh",className:Te("h-4 w-4",Ae&&"animate-spin")})})]})]})}),!Bt&&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:is.map((q,rt)=>s.jsxs(i.Fragment,{children:[rt>0?s.jsx("div",{className:"mx-4 my-1 border-t border-[var(--interactive-border)]"}):null,s.jsxs("div",{className:"flex items-center gap-2 px-4 py-2",children:[s.jsx(Po,{providerId:q.providerId,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:q.providerName})]}),q.entries.length===0&&(!q.modelFamilies||q.modelFamilies.length===0)?s.jsx("div",{className:"px-4 pb-2",children:s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:q.error??o("header.services.noRateLimitsReported")})}):s.jsxs("div",{className:"space-y-3 px-4 pb-2",children:[q.entries.map(([ht,Tt])=>{const Yt=re==="remaining"?Tt.remainingPercent:Tt.usedPercent,ts=Sa(Tt.usedPercent,Tt.resetAt,Tt.windowSeconds,ht),ds=ts?.dailyAllocationPercent!=null?re==="remaining"?100-ci(ts.elapsedRatio):ci(ts.elapsedRatio):null,Ls=To(Tt.valueLabel,Yt),Ks=Uf(Tt.resetAt,Tt.resetAfterFormatted??Tt.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:yc(ht)}),Ks?s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:Ks}):null]}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Ls==="-"?"":Ls})]}),s.jsx(Da,{percent:Yt,tonePercent:Tt.usedPercent,className:"h-1.5",expectedMarkerPercent:ds}),ts&&Q?s.jsx(Ia,{paceInfo:ts,compact:!0}):null]},`${q.providerId}-${ht}`)}),q.modelFamilies&&q.modelFamilies.length>0&&s.jsx("div",{className:"space-y-0.5",children:q.modelFamilies.map(ht=>{const Yt=(jt[q.providerId]??[]).includes(ht.familyId??"other");return s.jsxs(no,{open:Yt,onOpenChange:()=>Pt(q.providerId,ht.familyId??"other"),children:[s.jsxs(_o,{className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:ht.familyLabel}),Yt?s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ro,{children:s.jsx("div",{className:"space-y-2.5 pb-1 pl-1 pt-1",children:ht.models.map(([ts,ds])=>{const Ls=re==="remaining"?ds.remainingPercent:ds.usedPercent,Ks=Sa(ds.usedPercent,ds.resetAt,ds.windowSeconds),qn=Ks?.dailyAllocationPercent!=null?re==="remaining"?100-ci(Ks.elapsedRatio):ci(Ks.elapsedRatio):null,Bn=To(ds.valueLabel,Ls);return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[s.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:vm(ts)}),s.jsx("span",{className:"typography-ui-label text-foreground tabular-nums",children:Bn==="-"?"":Bn})]}),s.jsx(Da,{percent:Ls,tonePercent:ds.usedPercent,className:"h-1.5",expectedMarkerPercent:qn}),Ks&&Q?s.jsx(Ia,{paceInfo:Ks,compact:!0}):null]},`${q.providerId}-${ts}`)})})})]},ht.familyId??"other")})})]})]},q.providerId))})]})]})})]}),e?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:We,className:Te(hn,"relative",Fn==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(I,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ft,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),ir=Te("header-safe-area relative z-10 bg-background",fe&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:Ne,className:ir,style:{"--padding-scale":"1"},children:fe?dn():js()}),s.jsx(Nm,{open:Ye,onOpenChange:He,info:Je,downloading:!1,downloaded:!1,progress:null,error:_e,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})};function ey(){}const ru=180,iu=640,ty=110,sy=t=>{const e=ft.c(44),{isOpen:n,isMobile:r,children:o}=t,{t:a}=Nt(),c=Ee(ny),l=Ee(ry),d=Ee(iy),f=Ee(oy),[m,u]=i.useState(null),[p,y]=i.useState(!1),g=i.useRef(null),b=i.useRef(0),x=i.useRef(c||300),h=Math.min(iu,Math.max(ru,c||300));let C,w;e[0]!==n?(C=()=>{n||(u(null),y(!1))},w=[n],e[0]=n,e[1]=C,e[2]=w):(C=e[1],w=e[2]),i.useEffect(C,w);let v,S;e[3]!==l||e[4]!==r||e[5]!==n?(v=()=>{if(r||!n||!l)return;const X=()=>{const ve=g.current?.parentElement?.getBoundingClientRect().height;if(!ve||ve<=0)return;const ie=Math.max(0,Math.round(ve));u(Ne=>Ne===ie?Ne:ie)};X();const oe=g.current?.parentElement;if(!oe)return;const fe=new ResizeObserver(X);return fe.observe(oe),()=>{fe.disconnect()}},S=[l,r,n],e[3]=l,e[4]=r,e[5]=n,e[6]=v,e[7]=S):(v=e[6],S=e[7]),i.useEffect(v,S);let k,j;if(e[8]!==l||e[9]!==r||e[10]!==p||e[11]!==d||e[12]!==f?(k=()=>{if(r||!p||l)return;const X=fe=>{const ve=b.current-fe.clientY,ie=Math.min(iu,Math.max(ru,x.current+ve));d(ie)},oe=()=>{y(!1),Ee.getState().bottomTerminalHeight<=ty&&f(!1)};return window.addEventListener("pointermove",X),window.addEventListener("pointerup",oe,{once:!0}),()=>{window.removeEventListener("pointermove",X),window.removeEventListener("pointerup",oe)}},j=[l,r,p,d,f],e[8]=l,e[9]=r,e[10]=p,e[11]=d,e[12]=f,e[13]=k,e[14]=j):(k=e[13],j=e[14]),i.useEffect(k,j),r)return null;const A=n?l?Math.max(0,m??h):h:0,D=n&&l;let N;e[15]!==A||e[16]!==l||e[17]!==n?(N=X=>{!n||l||(y(!0),b.current=X.clientY,x.current=A,X.preventDefault())},e[15]=A,e[16]=l,e[17]=n,e[18]=N):N=e[18];const B=N,T=D?"absolute inset-x-0 bottom-0 z-40":"relative",E=p?"transition-none":"transition-[height] duration-300 ease-in-out",_=(!n||D)&&"border-t-0";let R;e[19]!==_||e[20]!==T||e[21]!==E?(R=Te("flex overflow-hidden border-t border-border bg-sidebar",T,E,_),e[19]=_,e[20]=T,e[21]=E,e[22]=R):R=e[22];let z;e[23]!==A||e[24]!==D?(z=D?{top:0}:{height:`${A}px`,minHeight:`${A}px`,maxHeight:`${A}px`},e[23]=A,e[24]=D,e[25]=z):z=e[25];const V=!n||!l&&A===0;let $;e[26]!==B||e[27]!==l||e[28]!==n||e[29]!==p||e[30]!==a?($=n&&!l&&s.jsx("div",{className:Te("absolute left-0 top-0 z-20 h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",p&&"bg-[var(--interactive-border)]"),onPointerDown:B,role:"separator","aria-orientation":"horizontal","aria-label":a("terminalView.bottomDock.resizeAria")}),e[26]=B,e[27]=l,e[28]=n,e[29]=p,e[30]=a,e[31]=$):$=e[31];const M=!n&&"pointer-events-none select-none opacity-0";let te;e[32]!==M?(te=Te("relative z-10 flex h-full min-h-0 w-full flex-col transition-opacity duration-300 ease-in-out",M),e[32]=M,e[33]=te):te=e[33];const re=!n;let Q;e[34]!==o||e[35]!==te||e[36]!==re?(Q=s.jsx("div",{className:te,"aria-hidden":re,children:o}),e[34]=o,e[35]=te,e[36]=re,e[37]=Q):Q=e[37];let H;return e[38]!==R||e[39]!==z||e[40]!==V||e[41]!==$||e[42]!==Q?(H=s.jsxs("section",{ref:g,className:R,style:z,"aria-hidden":V,children:[$,Q]}),e[38]=R,e[39]=z,e[40]=V,e[41]=$,e[42]=Q,e[43]=H):H=e[43],H};function ny(t){return t.bottomTerminalHeight}function ry(t){return t.isBottomTerminalExpanded}function iy(t){return t.setBottomTerminalHeight}function oy(t){return t.setBottomTerminalOpen}const ou=280,au=280,lu=500,ay=({isOpen:t,isMobile:e,children:n,className:r,topBar:o})=>{const{t:a}=Nt(),c=Ee(j=>j.sidebarWidth),l=Ee(j=>j.setSidebarWidth),[d,f]=i.useState(!1),m=i.useRef(0),u=i.useRef(c||ou),p=i.useRef(null),y=i.useRef(null),g=i.useRef(null),b=i.useCallback(j=>Math.min(lu,Math.max(au,j)),[]),x=i.useCallback(j=>{const A=g.current;A&&(A.style.width=`${j}px`,A.style.minWidth=`${j}px`,A.style.maxWidth=`${j}px`,A.style.setProperty("--oc-left-sidebar-width",`${j}px`))},[]);if(i.useEffect(()=>{e&&d&&f(!1)},[e,d]),i.useEffect(()=>{d||(p.current=null,y.current=null)},[d]),e)return null;const h=Math.min(lu,Math.max(au,c||ou)),C=t?h:0,w=j=>{if(t){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}y.current=j.pointerId,f(!0),m.current=j.clientX,u.current=C,p.current=C,x(C),j.preventDefault()}},v=j=>{if(e||!d||y.current!==j.pointerId)return;const A=j.clientX-m.current,D=b(u.current+A);p.current!==D&&(p.current=D,x(D))},S=j=>{if(y.current!==j.pointerId||e)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const A=b(p.current??C);y.current=null,p.current=null,f(!1),l(A)},k=d?p.current??C:C;return s.jsxs("aside",{ref:g,className:Te("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:Te("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",d&&"bg-[var(--interactive-border)]"),onPointerDown:w,onPointerMove:v,onPointerUp:S,onPointerCancel:S,role:"separator","aria-orientation":"vertical","aria-label":a("sidebar.resize.leftPanelAria")}),s.jsxs("div",{className:Te("relative z-10 flex h-full shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",d&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[o,s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:s.jsx(Xs,{children:n})})]})]})},ly=()=>{const t=ft.c(3);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e={height:"var(--oc-header-height, 3rem)"},t[0]=e):e=t[0];let n;t[1]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("div",{className:"app-region-drag shrink-0",style:{width:"var(--oc-titlebar-left-inset, 0.75rem)"}}),t[1]=n):n=t[1];let r;return t[2]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsxs("div",{"aria-hidden":!0,className:"flex shrink-0",style:e,children:[n,s.jsx("div",{className:"app-region-no-drag shrink-0",style:{width:"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)"}}),s.jsx("div",{className:"app-region-drag flex-1"})]}),t[2]=r):r=t[2],r},Go=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function cy(){const t=Ss(u=>u.activeProjectId?u.projects.find(p=>p.id===u.activeProjectId)??null:null),e=ut(u=>u.currentSessionId),n=Gf(e??null),r=ut(u=>e?u.worktreeMetadata.get(e)?.path??"":""),o=ut(u=>u.newSessionDraft?.open?Go(u.newSessionDraft.bootstrapPendingDirectory??u.newSessionDraft.directoryOverride??""):""),a=i.useMemo(()=>Go(r||""),[r]),c=i.useMemo(()=>{const u=typeof n?.directory=="string"?n.directory:"";return Go(u||"")},[n?.directory]),l=a||c||o,d=i.useMemo(()=>Go(l||t?.path||""),[t?.path,l]),f=i.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),m=i.useRef(null);return i.useEffect(()=>{f&&d&&(m.current={projectRef:f,directory:d})},[d,f]),i.useMemo(()=>f&&d?{projectRef:f,directory:d}:m.current,[f,d])}const cu="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",dy=()=>{const t=ft.c(31),{t:e}=Nt(),n=Ee(uy),r=Ee(fy),o=Ee(my),a=cy(),c=i.useRef(null),l=Va(di("toggle_sidebar",o));let d;e:{if(typeof window>"u"){d=!1;break e}d=!!window.__OPENCHAMBER_ELECTRON__&&window.__OPENCHAMBER_PLATFORM__==="win32"}const f=d,m=py;let u,p;t[0]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{if(typeof document>"u")return;const _=c.current;if(!_)return;const R=()=>{const V=_.getBoundingClientRect().width;document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(V)}px`)};if(R(),typeof ResizeObserver>"u")return;const z=new ResizeObserver(R);return z.observe(_),()=>{z.disconnect()}},p=[],t[0]=u,t[1]=p):(u=t[0],p=t[1]),i.useEffect(u,p);const y="app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2";let g;t[2]===Symbol.for("react.memo_cache_sentinel")?(g={height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},t[2]=g):g=t[2];const b="flex items-center gap-2";let x;t[3]!==e?(x=f?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,"aria-label":e("header.actions.openAppMenuAria"),className:Te(cu,"shrink-0"),children:s.jsx(I,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ft,{children:s.jsx("p",{children:e("header.actions.openAppMenu")})})]}):null,t[3]=e,t[4]=x):x=t[4];const h=Et;let C;t[5]!==e?(C=e("header.actions.openSessionsAria"),t[5]=e,t[6]=C):C=t[6];let w,v;t[7]===Symbol.for("react.memo_cache_sentinel")?(w=Te(cu,"shrink-0"),v=s.jsx(I,{name:"layout-left",className:"h-[18px] w-[18px]"}),t[7]=w,t[8]=v):(w=t[7],v=t[8]);let S;t[9]!==C||t[10]!==n?(S=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":C,className:w,children:v})}),t[9]=C,t[10]=n,t[11]=S):S=t[11];const k=Ft,j=e("header.actions.openSessionsWithShortcut",{shortcut:l});let A;t[12]!==j?(A=s.jsx("p",{children:j}),t[12]=j,t[13]=A):A=t[13];let D;t[14]!==k||t[15]!==A?(D=s.jsx(k,{children:A}),t[14]=k,t[15]=A,t[16]=D):D=t[16];let N;t[17]!==h||t[18]!==S||t[19]!==D?(N=s.jsxs(h,{children:[S,D]}),t[17]=h,t[18]=S,t[19]=D,t[20]=N):N=t[20];let B;t[21]!==r||t[22]!==a?(B=a?s.jsx(Em,{projectRef:a.projectRef,directory:a.directory,className:r?"oc-vibrancy-pill":void 0}):null,t[21]=r,t[22]=a,t[23]=B):B=t[23];let T;t[24]!==N||t[25]!==B||t[26]!==x?(T=s.jsxs("div",{ref:c,className:b,children:[x,N,B]}),t[24]=N,t[25]=B,t[26]=x,t[27]=T):T=t[27];let E;return t[28]!==T||t[29]!==g?(E=s.jsx("div",{className:y,style:g,children:T}),t[28]=T,t[29]=g,t[30]=E):E=t[30],E};function uy(t){return t.toggleSidebar}function fy(t){return t.isSidebarOpen}function my(t){return t.shortcutOverrides}function hy(t){console.warn("[titlebar] failed to open app menu",t)}function py(t){const e=t.currentTarget.getBoundingClientRect();Gr("desktop_show_app_menu",{x:e.left,y:e.bottom}).catch(hy)}const du=420,gy=({isOpen:t,children:e,className:n})=>{const{t:r}=Nt(),o=Ee(S=>S.rightSidebarWidth),a=Ee(S=>S.setRightSidebarWidth),[c,l]=i.useState(!1),d=i.useRef(0),f=i.useRef(o||du),m=i.useRef(null),u=i.useRef(null),p=i.useRef(null),y=i.useCallback(S=>Math.min(wd,Math.max(vd,S)),[]),g=i.useCallback(S=>{const k=p.current;k&&(k.style.width=`${S}px`,k.style.minWidth=`${S}px`,k.style.maxWidth=`${S}px`,k.style.setProperty("--oc-right-sidebar-width",`${S}px`))},[]),b=Math.min(wd,Math.max(vd,o||du)),x=t?b:0,h=S=>{if(t){try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}u.current=S.pointerId,l(!0),d.current=S.clientX,f.current=x,m.current=x,g(x),S.preventDefault()}},C=S=>{if(!c||u.current!==S.pointerId)return;const k=d.current-S.clientX,j=y(f.current+k);m.current!==j&&(m.current=j,g(j))},w=S=>{if(u.current!==S.pointerId)return;try{S.currentTarget.releasePointerCapture(S.pointerId)}catch{}const k=y(m.current??x);u.current=null,m.current=null,l(!1),a(k)},v=c?m.current??x:x;return s.jsxs("aside",{ref:p,className:Te("relative flex h-full overflow-hidden border-l border-border/40 will-change-[width] motion-reduce:transition-none","bg-sidebar",!t&&"border-l-0",n),style:{width:`${v}px`,"--oc-right-sidebar-width":`${c?v:b}px`,overflowX:"clip",transitionProperty:c?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||x===0,children:[t&&s.jsx("div",{className:Te("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:Te("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})]})},uu=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function Fm(t){const e=ft.c(120),{t:n}=Nt(),{open:r,onOpenChange:o,target:a,projectDirectory:c,submitting:l,onConfirm:d}=t,f=l===void 0?!1:l,m=ss(Cy),u=ss(ky),p=Lp(Ny),y=ss(Sy),g=ss(jy),b=ss(vy),x=ss(wy),h=ss(yy);let C;e[0]!==h||e[1]!==b||e[2]!==g||e[3]!==x?(C=()=>uu({providerID:g,modelID:b,variant:x,agent:h}),e[0]=h,e[1]=b,e[2]=g,e[3]=x,e[4]=C):C=e[4];const[w,v]=i.useState(C);let S,k;e[5]!==p||e[6]!==u||e[7]!==m||e[8]!==r||e[9]!==c?(S=()=>{r&&(m({directory:c,source:"todoSendDialog"}),u({directory:c}),p())},k=[r,m,u,p,c],e[5]=p,e[6]=u,e[7]=m,e[8]=r,e[9]=c,e[10]=S,e[11]=k):(S=e[10],k=e[11]),i.useEffect(S,k);let j,A;e[12]!==h||e[13]!==b||e[14]!==g||e[15]!==x||e[16]!==r?(j=()=>{r&&v(uu({providerID:g,modelID:b,variant:x,agent:h}))},A=[r,g,b,x,h],e[12]=h,e[13]=b,e[14]=g,e[15]=x,e[16]=r,e[17]=j,e[18]=A):(j=e[17],A=e[18]),i.useEffect(j,A);let D,N;e[19]!==w.modelID||e[20]!==w.providerID||e[21]!==r||e[22]!==y?(D=()=>{if(!r||y.length===0)return;const Se=y.find(O=>O.id===w.providerID)??y[0],Oe=Array.isArray(Se?.models)?Se.models:[],Ae=Oe.some(O=>O.id===w.modelID),J=Oe[0]?.id??"";Se?.id===w.providerID&&Ae||v(O=>({...O,providerID:Se?.id??"",modelID:Ae?O.modelID:J,variant:""}))},N=[r,y,w.providerID,w.modelID],e[19]=w.modelID,e[20]=w.providerID,e[21]=r,e[22]=y,e[23]=D,e[24]=N):(D=e[23],N=e[24]),i.useEffect(D,N);const B=by;let T;if(e[25]!==w.modelID||e[26]!==w.providerID||e[27]!==y){let Se;e[29]!==w.providerID?(Se=Ae=>Ae.id===w.providerID,e[29]=w.providerID,e[30]=Se):Se=e[30],T=y.find(Se)?.models?.find(Ae=>Ae.id===w.modelID),e[25]=w.modelID,e[26]=w.providerID,e[27]=y,e[28]=T}else T=e[28];const E=T;let _;e[31]!==E?(_=E?.variants?Object.keys(E.variants):[],e[31]=E,e[32]=_):_=e[32];const R=_,z=R.length>0;let V,$;e[33]!==w.variant||e[34]!==z?(V=()=>{z||!w.variant||v(xy)},$=[z,w.variant],e[33]=w.variant,e[34]=z,e[35]=V,e[36]=$):(V=e[35],$=e[36]),i.useEffect(V,$);let M;e[37]!==w.modelID||e[38]!==w.providerID?(M=w.providerID.trim().length>0&&w.modelID.trim().length>0,e[37]=w.modelID,e[38]=w.providerID,e[39]=M):M=e[39];const te=M;let re;e[40]!==te||e[41]!==w||e[42]!==d||e[43]!==f?(re=()=>{!te||f||d(w)},e[40]=te,e[41]=w,e[42]=d,e[43]=f,e[44]=re):re=e[44];const Q=re;let H,X;e[45]!==Q||e[46]!==r?(H=()=>{if(!r)return;const Se=Oe=>{(Oe.metaKey||Oe.ctrlKey)&&Oe.key==="Enter"&&(Oe.preventDefault(),Q())};return window.addEventListener("keydown",Se),()=>window.removeEventListener("keydown",Se)},X=[r,Q],e[45]=Q,e[46]=r,e[47]=H,e[48]=X):(H=e[47],X=e[48]),i.useEffect(H,X);let oe;e[49]!==n||e[50]!==a?(oe=n(a==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[49]=n,e[50]=a,e[51]=oe):oe=e[51];const fe=oe;let ve;e[52]!==o||e[53]!==f?(ve=Se=>{f||o(Se)},e[52]=o,e[53]=f,e[54]=ve):ve=e[54];let ie;e[55]!==fe?(ie=s.jsx(Gs,{children:s.jsx(Vs,{children:fe})}),e[55]=fe,e[56]=ie):ie=e[56];let Ne;e[57]!==n?(Ne=n("chat.modelControls.model"),e[57]=n,e[58]=Ne):Ne=e[58];let K;e[59]!==Ne?(K=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:Ne}),e[59]=Ne,e[60]=K):K=e[60];let pe;e[61]===Symbol.for("react.memo_cache_sentinel")?(pe=(Se,Oe)=>{v(Ae=>({...Ae,providerID:Se,modelID:Oe,variant:""}))},e[61]=pe):pe=e[61];let L;e[62]!==w.modelID||e[63]!==w.providerID?(L=s.jsx(Zf,{providerId:w.providerID,modelId:w.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:pe}),e[62]=w.modelID,e[63]=w.providerID,e[64]=L):L=e[64];let se;e[65]!==K||e[66]!==L?(se=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[K,L]}),e[65]=K,e[66]=L,e[67]=se):se=e[67];let Z;e[68]!==n?(Z=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[68]=n,e[69]=Z):Z=e[69];let je;e[70]!==Z?(je=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:Z}),e[70]=Z,e[71]=je):je=e[71];const De=!z;let Le;e[72]===Symbol.for("react.memo_cache_sentinel")?(Le=Se=>v(Oe=>({...Oe,variant:Se})),e[72]=Le):Le=e[72];let Me;e[73]!==w.variant||e[74]!==De||e[75]!==R?(Me=s.jsx(Bp,{value:w.variant,options:R,disabled:De,onChange:Le}),e[73]=w.variant,e[74]=De,e[75]=R,e[76]=Me):Me=e[76];let Fe;e[77]!==je||e[78]!==Me?(Fe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[je,Me]}),e[77]=je,e[78]=Me,e[79]=Fe):Fe=e[79];let he;e[80]!==n?(he=n("sessions.scheduledTasks.editor.agent.label"),e[80]=n,e[81]=he):he=e[81];let Ie;e[82]!==he?(Ie=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:he}),e[82]=he,e[83]=Ie):Ie=e[83];let me;e[84]===Symbol.for("react.memo_cache_sentinel")?(me=Se=>v(Oe=>({...Oe,agent:Se})),e[84]=me):me=e[84];let ce;e[85]!==w.agent?(ce=s.jsx(em,{agentName:w.agent,filter:B,dropdownPortalToBody:!0,onChange:me}),e[85]=w.agent,e[86]=ce):ce=e[86];let xe;e[87]!==Ie||e[88]!==ce?(xe=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Ie,ce]}),e[87]=Ie,e[88]=ce,e[89]=xe):xe=e[89];let ke;e[90]!==se||e[91]!==Fe||e[92]!==xe?(ke=s.jsxs("div",{className:"flex flex-col gap-4",children:[se,Fe,xe]}),e[90]=se,e[91]=Fe,e[92]=xe,e[93]=ke):ke=e[93];let de;e[94]!==o?(de=()=>o(!1),e[94]=o,e[95]=de):de=e[95];let P;e[96]!==n?(P=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[96]=n,e[97]=P):P=e[97];let F;e[98]!==f||e[99]!==de||e[100]!==P?(F=s.jsx(Ve,{variant:"ghost",size:"sm",onClick:de,disabled:f,children:P}),e[98]=f,e[99]=de,e[100]=P,e[101]=F):F=e[101];const ue=!te||f;let be;e[102]!==f||e[103]!==n?(be=n(f?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[102]=f,e[103]=n,e[104]=be):be=e[104];let W;e[105]!==Q||e[106]!==ue||e[107]!==be?(W=s.jsx(Ve,{size:"sm",onClick:Q,disabled:ue,children:be}),e[105]=Q,e[106]=ue,e[107]=be,e[108]=W):W=e[108];let ge;e[109]!==F||e[110]!==W?(ge=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[F,W]}),e[109]=F,e[110]=W,e[111]=ge):ge=e[111];let we;e[112]!==ie||e[113]!==ke||e[114]!==ge?(we=s.jsxs(Es,{className:"max-w-md overflow-visible",children:[ie,ke,ge]}),e[112]=ie,e[113]=ke,e[114]=ge,e[115]=we):we=e[115];let G;return e[116]!==r||e[117]!==ve||e[118]!==we?(G=s.jsx(Ms,{open:r,onOpenChange:ve,children:we}),e[116]=r,e[117]=ve,e[118]=we,e[119]=G):G=e[119],G}function xy(t){return{...t,variant:""}}function by(t){return Sc(t.mode)}function yy(t){return t.currentAgentName||""}function wy(t){return t.currentVariant||""}function vy(t){return t.currentModelId}function jy(t){return t.currentProviderId}function Sy(t){return t.providers}function Ny(t){return t.loadAgents}function ky(t){return t.loadAgents}function Cy(t){return t.loadProviders}const ec=5,Om=15,Ko=new Map,ca=t=>{const e=Math.sqrt(t/100),n=12*e,r=24*e;return Math.ceil(n+r+1)},Ay=(t,e)=>{const n=ca(e);return Math.max(n*ec,Math.min(n*Om,n*t))},Dy=async(t,e)=>{const n=await zp(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},Iy=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,fu=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],mu=(t,e)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},Py=t=>{const e=ft.c(20),{id:n,children:r}=t;let o;e[0]!==n?(o={id:n},e[0]=n,e[1]=o):o=e[1];const{attributes:a,listeners:c,setNodeRef:l,setActivatorNodeRef:d,transform:f,transition:m,isDragging:u}=mc(o);let p;e[2]!==f?(p=hc.Transform.toString(f),e[2]=f,e[3]=p):p=e[3];let y;e[4]!==p||e[5]!==m?(y={transform:p,transition:m},e[4]=p,e[5]=m,e[6]=y):y=e[6];const g=u&&"opacity-60";let b;e[7]!==g?(b=Te(g),e[7]=g,e[8]=b):b=e[8];let x;e[9]!==a||e[10]!==r||e[11]!==u||e[12]!==c||e[13]!==d?(x=r({attributes:a,listeners:c,setActivatorNodeRef:d,isDragging:u}),e[9]=a,e[10]=r,e[11]=u,e[12]=c,e[13]=d,e[14]=x):x=e[14];let h;return e[15]!==l||e[16]!==y||e[17]!==b||e[18]!==x?(h=s.jsx("li",{ref:l,style:y,className:b,children:x}),e[15]=l,e[16]=y,e[17]=b,e[18]=x,e[19]=h):h=e[19],h},Ty=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:r,className:o})=>{const{t:a}=Nt(),[c,l]=i.useState(!1),[d,f]=i.useState(""),[m,u]=i.useState([]),[p,y]=i.useState(""),[g,b]=i.useState(null),[x,h]=i.useState(()=>new Set),[C,w]=i.useState([]),[v,S]=i.useState(null),[k,j]=i.useState(!1),[A,D]=i.useState(0),N=i.useRef(!1),B=i.useRef(""),T=i.useRef(null),E=Ee(O=>O.todoPanelHeight),_=Ee(O=>O.setTodoPanelHeight),R=Ee(O=>O.notesPanelHeight),z=Ee(O=>O.setNotesPanelHeight),[V,$]=i.useState(!1),M=i.useRef(0),te=i.useRef(E),re=ut(O=>O.currentSessionId),Q=ut(O=>O.createSession),H=ut(O=>O.initializeNewOpenChamberSession),X=ut(O=>O.sendMessage),oe=ut(O=>O.setCurrentSession),fe=hi(O=>O.setPendingInputText),ve=Ys(O=>O.currentDirectory),ie=Ee(O=>O.openContextPanelTab),Ne=Ee(O=>O.setActiveMainTab),K=Ee(O=>O.setSessionSwitcherOpen),pe=Ee(O=>O.padding),L=i.useCallback(async(O,ae)=>{if(!t)return!1;const ne=t.id,Ye=(Ko.get(ne)??Promise.resolve()).catch(()=>{}).then(()=>_p(t,{notes:O,todos:ae}));Ko.set(ne,Ye);try{const He=await Ye;return He||le.error(a("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),He}finally{Ko.get(ne)===Ye&&Ko.delete(ne)}},[t,a]);i.useEffect(()=>{if(!t){f(""),u([]),w([]),y(""),h(new Set);return}let O=!1;return l(!0),(async()=>{try{const ae=await Vp(t),ne=await Promise.all(ae.plans.map(Be=>Dy(Be,a("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(O)return;f(ae.notes),u(fu(ae.todos)),w(ne),B.current=ae.notes,N.current=!0,y(""),h(new Set)}catch{O||(le.error(a("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),f(""),u([]),w([]),B.current="",N.current=!0)}finally{O||l(!1)}})(),()=>{O=!0}},[A,t,a]),i.useEffect(()=>{if(!t)return;const O=ae=>{const ne=ae.detail;ne?.projectId&&ne.projectId!==t.id||D(Be=>Be+1)};return window.addEventListener("openchamber:project-plan-saved",O),window.addEventListener("openchamber:project-notes-updated",O),()=>{window.removeEventListener("openchamber:project-plan-saved",O),window.removeEventListener("openchamber:project-notes-updated",O)}},[t]),i.useEffect(()=>{if(m.length<7)return;const O=Ay(m.length,pe),ae=ca(pe)*ec;E!==O&&(E<ae||E>O)&&_(O)},[m.length,pe,E,_]),i.useEffect(()=>{if(!V)return;const O=ne=>{const Be=ne.clientY-M.current,Ye=Math.min(ca(pe)*Om,Math.max(ca(pe)*ec,te.current+Be));_(Ye)},ae=()=>{$(!1)};return window.addEventListener("pointermove",O),window.addEventListener("pointerup",ae,{once:!0}),window.addEventListener("pointercancel",ae,{once:!0}),()=>{window.removeEventListener("pointermove",O),window.removeEventListener("pointerup",ae),window.removeEventListener("pointercancel",ae)}},[V,pe,_]);const se=i.useCallback(O=>{$(!0),M.current=O.clientY,te.current=E,O.preventDefault()},[E]),Z=i.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),je=i.useCallback(()=>{Z(),B.current=d,L(d,m)},[Z,d,L,m]);i.useEffect(()=>{if(!(!t||!N.current)&&d!==B.current)return T.current=window.setTimeout(()=>{T.current=null,B.current=d,L(d,m)},400),()=>{Z()}},[Z,d,L,t,m]),i.useEffect(()=>()=>Z(),[Z]);const De=i.useCallback(()=>{const O=p.trim();if(!O)return;const ae=mu(m,{id:Iy(),text:O.slice(0,Wo),completed:!1,createdAt:Date.now()});u(ae),y(""),L(d,ae)},[p,d,L,m]),Le=i.useCallback(O=>{h(ae=>{const ne=new Set(ae);return ne.has(O)?ne.delete(O):ne.add(O),ne})},[]),Me=i.useCallback((O,ae)=>{const ne=m.find(Je=>Je.id===O);if(!ne||ne.completed===ae)return;const Be=m.filter(Je=>Je.id!==O),Ye={...ne,completed:ae},He=ae?[...Be,Ye]:mu(Be,Ye);u(He),L(d,He)},[d,L,m]),Fe=i.useCallback(O=>{const ae=m.filter(ne=>ne.id!==O);u(ae),L(d,ae)},[d,L,m]),he=i.useCallback(()=>{const O=m.filter(ae=>!ae.completed);O.length!==m.length&&(u(O),L(d,O))},[d,L,m]),Ie=i.useCallback(O=>{const{active:ae,over:ne}=O;if(!ne||ae.id===ne.id)return;const Be=m.findIndex(Je=>Je.id===ae.id),Ye=m.findIndex(Je=>Je.id===ne.id);if(Be===-1||Ye===-1)return;const He=fu(Bf(m,Be,Ye));u(He),L(d,He)},[d,L,m]),me=ba(vo(ya,{activationConstraint:{distance:8}})),ce=p.slice(0,Wo),xe=m.reduce((O,ae)=>O+(ae.completed?1:0),0),ke=i.useCallback(()=>{Ne("chat"),K(!1)},[Ne,K]),de=i.useCallback((O,ae)=>{!t||g||S({kind:"session",todoId:O,todoText:ae})},[t,g]),P=i.useCallback(O=>{if(!re){le.error(a("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}ke();const ae=`\`\`\`md
|
|
4
|
-
${O}
|
|
5
|
-
\`\`\``;fe(ae,"append"),le.success(a("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),r?.()},[re,r,ke,fe,a]),F=i.useCallback((O,ae)=>{if(!(!t||g)){if(!n){le.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}S({kind:"worktree",todoId:O,todoText:ae})}},[n,t,g,a]),ue=i.useCallback(async O=>{if(!t||!v)return;const ae=await En("plan.todo.visible",{todo_text:v.todoText}),Be=[{synthetic:!0,text:await En("plan.todo.instructions",{todo_text:v.todoText})}];j(!0),b(v.todoId);try{ke();let Ye=null,He=t.path;if(v.kind==="worktree"){if(!n){le.error(a("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const nt=await tm(t.path,sm());if(!nt?.id)return;Ye=nt.id,He=nt.path}else{const nt=await Q(void 0,t.path,null);if(!nt?.id){le.error(a("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}Ye=nt.id,He=nt.directory??t.path,H(nt.id,ss.getState().agents??[])}if(!Ye)return;const Je=Nc.getState();Je.saveSessionModelSelection(Ye,O.providerID,O.modelID),O.agent.trim()&&(Je.saveSessionAgentSelection(Ye,O.agent),Je.saveAgentModelForSession(Ye,O.agent,O.providerID,O.modelID),Je.saveAgentModelVariantForSession(Ye,O.agent,O.providerID,O.modelID,O.variant||void 0)),oe(Ye,He),await X(ae,O.providerID,O.modelID,O.agent.trim()||void 0,void 0,void 0,Be,O.variant||void 0),le.success(v.kind==="worktree"?a("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):a("rightSidebar.contextNotesTodo.toast.sentToNewSession")),S(null),r?.()}catch(Ye){const He=Ye instanceof Error?Ye.message:void 0;le.error(a("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),He?{description:He}:void 0)}finally{j(!1),b(null)}},[n,Q,H,r,v,t,ke,X,oe,a]),be=i.useRef(null),[W,ge]=i.useState(!1),[we,G]=i.useState(null),Se=i.useCallback(async O=>{if(!(!t||we)){G(O);try{if(!await $p(t,O)){le.error(a("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}w(ne=>ne.filter(Be=>Be.id!==O)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{G(null)}}},[we,t,a]),Oe=i.useCallback(async()=>{if(!t||W)return;const O=await gp({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(O.success&&O.path){ge(!0);try{const ae=new URLSearchParams({path:O.path,allowOutsideWorkspace:"true"});O.outsideFileGrant&&ae.set("outsideFileGrant",O.outsideFileGrant);const ne=await Cs(`/api/fs/read?${ae.toString()}`,{cache:"no-store"});if(!ne.ok){le.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const Be=await ne.text();if(!Be.trim()){le.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const Ye=O.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Id(t,Be,Ye)){le.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),le.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(ae){const ne=ae instanceof Error?ae.message:void 0;le.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),ne?{description:ne}:void 0)}finally{ge(!1)}}else O.error==="Native file picker not available"&&be.current?.click()},[W,t,a]),Ae=i.useCallback(async O=>{if(!(!t||!O)){ge(!0);try{const ae=await O.text();if(!ae.trim()){le.error(a("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const ne=O.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Id(t,ae,ne)){le.error(a("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),le.success(a("rightSidebar.contextNotesTodo.toast.planImported"))}catch(ae){const ne=ae instanceof Error?ae.message:void 0;le.error(a("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),ne?{description:ne}:void 0)}finally{ge(!1)}}},[t,a]),J=i.useCallback(O=>{const ae=t?.path?.trim(),ne=ve?.trim()||ae;ne&&ie(ne,{mode:"plan",targetPath:O.path,dedupeKey:O.path,label:O.title})},[ve,ie,t]);return t?s.jsxs("div",{className:Te("w-full min-w-0 space-y-3 p-3",o),children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:t.path,children:a("rightSidebar.contextNotesTodo.notes.title",{project:e?.trim()||t.path.split("/").filter(Boolean).pop()||t.path})}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[d.length,"/",Pd]})]}),s.jsx(Ii,{value:d,onChange:O=>f(O.target.value.slice(0,Pd)),onBlur:je,placeholder:a("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:R,onResizeHeightChange:z,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||xe===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:a("rightSidebar.contextNotesTodo.todo.clearCompleted")})]}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ce.length,"/",Wo]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(vn,{value:ce,onChange:O=>y(O.target.value.slice(0,Wo)),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),De())},placeholder:a("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:c,className:"h-8"}),s.jsx("button",{type:"button",onClick:De,disabled:c||ce.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.todo.addAria"),title:a("rightSidebar.contextNotesTodo.todo.addAria"),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:Te("overflow-y-auto rounded-lg border border-border/60 bg-background/40",V&&"transition-none"),style:m.length<7?void 0:{height:`${E}px`,maxHeight:`${E}px`},children:m.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.todo.empty")}):s.jsx(wa,{sensors:me,collisionDetection:va,onDragEnd:Ie,children:s.jsx($l,{items:m.map(O=>O.id),strategy:zl,children:s.jsx("ul",{className:"divide-y divide-border/50",children:m.map(O=>{const ae=x.has(O.id);return s.jsx(Py,{id:O.id,children:ne=>s.jsxs("div",{className:Te("flex gap-1.5 px-2.5 py-1.5",ae?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:ne.setActivatorNodeRef,...ne.attributes,...ne.listeners,onClick:Be=>{Be.preventDefault(),Be.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:O.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:O.text}),children:s.jsx(I,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(Fi,{checked:O.completed,onChange:Be=>Me(O.id,Be),ariaLabel:a("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:O.text})})}),s.jsx("button",{type:"button",onClick:()=>Le(O.id),className:Te("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",ae?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",O.completed&&"text-muted-foreground line-through"),title:ae?void 0:O.text,"aria-label":ae?a("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:O.text}):a("rightSidebar.contextNotesTodo.todo.actions.expand",{text:O.text}),children:O.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>Fe(O.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:O.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.delete",{text:O.text}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",disabled:g===O.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:O.text}),title:a("rightSidebar.contextNotesTodo.todo.actions.send",{text:O.text}),children:s.jsx(I,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(en,{align:"end",className:"w-56",children:[s.jsx(ws,{onClick:()=>P(O.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(ws,{onClick:()=>de(O.id,O.text),children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(ws,{onClick:()=>{F(O.id,O.text)},disabled:!n,children:a("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},O.id)})})})})}),m.length>=7&&s.jsx("div",{className:Te("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:O=>{const ae=O.target.files?.[0]??null;Ae(ae),O.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Oe,disabled:!t||W,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":a("rightSidebar.contextNotesTodo.plans.importFromFile"),title:a("rightSidebar.contextNotesTodo.plans.importFromFile"),children:s.jsx(I,{name:"add",className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:C.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.plans.empty")}):s.jsx("ul",{className:"divide-y divide-border/50",children:C.map(O=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>J(O),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:O.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(O.createdAt).toLocaleDateString(to())})]}),s.jsx("button",{type:"button",onClick:()=>{Se(O.id)},disabled:we===O.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:O.title}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},O.id))})})]}),s.jsx(Fm,{open:v!==null,onOpenChange:O=>{!O&&!k&&S(null)},target:v?.kind??"session",projectDirectory:t?.path??null,submitting:k,onConfirm:ue})]}):s.jsx("div",{className:Te("w-full min-w-0 p-3",o),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("rightSidebar.contextNotesTodo.empty.selectProject")})})},Lm=12,Ry=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],Ey=t=>{const e=ft.c(18),{isActive:n,burstKey:r,className:o,durationMs:a,bursts:c,onComplete:l}=t,d=r===void 0?0:r,f=a===void 0?900:a,m=c===void 0?Ry:c,u=tt.useRef(!1);let p,y;e[0]!==n||e[1]!==l?(p=()=>{!n&&u.current&&l?.(),n&&(u.current=!0)},y=[n,l],e[0]=n,e[1]=l,e[2]=p,e[3]=y):(p=e[2],y=e[3]),tt.useEffect(p,y);let g;e[4]===Symbol.for("react.memo_cache_sentinel")?(g=Array.from({length:Lm},My),e[4]=g):g=e[4];const b=g;if(!n)return null;let x;e[5]!==o?(x=Te("fireworks-overlay pointer-events-none",o),e[5]=o,e[6]=x):x=e[6];let h;if(e[7]!==d||e[8]!==m||e[9]!==f){let w;e[11]!==d||e[12]!==f?(w=v=>{const S={"--burst-delay":`${v.delay}ms`,"--burst-x":`${v.x}%`,"--burst-y":`${v.y}%`,"--firework-color":`var(${v.colorVar})`,"--firework-duration":`${f}ms`};return s.jsx("div",{className:"firework-burst",style:S,children:b.map((k,j)=>{const A=k.x*v.radius,D=k.y*v.radius,N={"--translate-x":`${A}px`,"--translate-y":`${D}px`,"--particle-delay":`${k.delay}ms`,color:`var(${v.colorVar})`};return s.jsx("span",{className:"firework-particle",style:N},`${v.id}-${j}-${d}`)})},`${v.id}-${d}`)},e[11]=d,e[12]=f,e[13]=w):w=e[13],h=m.map(w),e[7]=d,e[8]=m,e[9]=f,e[10]=h}else h=e[10];let C;return e[14]!==d||e[15]!==x||e[16]!==h?(C=s.jsx("div",{className:x,"aria-hidden":"true","data-burst-key":d,children:h}),e[14]=d,e[15]=x,e[16]=h,e[17]=C):C=e[17],C};function My(t,e){const n=Math.PI*2*e/Lm;return{x:Math.cos(n),y:Math.sin(n),delay:e*18}}const Fy=t=>{const e=ft.c(13);let n;e[0]!==t?(n={},e[0]=t,e[1]=n):n=e[1];const{durationMs:r}=n,o=r===void 0?3400:r;let a;e[2]===Symbol.for("react.memo_cache_sentinel")?(a={isActive:!1,cycle:0},e[2]=a):a=e[2];const[c,l]=tt.useState(a),d=tt.useRef(null);let f;e[3]===Symbol.for("react.memo_cache_sentinel")?(f=()=>{d.current&&(window.clearTimeout(d.current),d.current=null)},e[3]=f):f=e[3];const m=f;let u;e[4]===Symbol.for("react.memo_cache_sentinel")?(u=()=>{m(),l(Oy)},e[4]=u):u=e[4];const p=u;let y;e[5]!==o?(y=()=>{m(),l(Ly),d.current=window.setTimeout(()=>{l(By),d.current=null},o)},e[5]=o,e[6]=y):y=e[6];const g=y;let b,x;e[7]===Symbol.for("react.memo_cache_sentinel")?(b=()=>()=>m(),x=[m],e[7]=b,e[8]=x):(b=e[7],x=e[8]),tt.useEffect(b,x);let h;return e[9]!==c.cycle||e[10]!==c.isActive||e[11]!==g?(h={isActive:c.isActive,burstKey:c.cycle,triggerFireworks:g,dismissFireworks:p},e[9]=c.cycle,e[10]=c.isActive,e[11]=g,e[12]=h):h=e[12],h};function Oy(t){return t.isActive?{...t,isActive:!1}:t}function Ly(t){return{isActive:!0,cycle:t.cycle+1}}function By(t){return t.isActive?{...t,isActive:!1}:t}const Bm=i.createContext(void 0),_y=t=>{const e=ft.c(10),{children:n}=t,{isActive:r,burstKey:o,triggerFireworks:a,dismissFireworks:c}=Fy();let l;e[0]!==c||e[1]!==a?(l={triggerFireworks:a,dismissFireworks:c},e[0]=c,e[1]=a,e[2]=l):l=e[2];const d=l;let f;e[3]!==o||e[4]!==r?(f=s.jsx(Ey,{isActive:r,burstKey:o}),e[3]=o,e[4]=r,e[5]=f):f=e[5];let m;return e[6]!==n||e[7]!==f||e[8]!==d?(m=s.jsxs(Bm.Provider,{value:d,children:[n,f]}),e[6]=n,e[7]=f,e[8]=d,e[9]=m):m=e[9],m},Vy=()=>{const t=i.useContext(Bm);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},_m="gitmojiCache",$y=1e3*60*60*24*7,Vm="1",zy="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",$m=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},yl=()=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(_m);if(!t)return null;const e=JSON.parse(t);return!e||e.version!==Vm||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter($m),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},Wy=t=>{if(!(typeof window>"u"))try{const e={gitmojis:t,fetchedAt:Date.now(),version:Vm};window.localStorage.setItem(_m,JSON.stringify(e))}catch{return}},hu=t=>Date.now()-t.fetchedAt<$y;let qo=null;const ko=new Set,pu=async()=>{if(qo)return qo;const t=(async()=>{try{const e=await fetch(zy);if(!e.ok)throw new Error(`Failed to load gitmojis: ${e.statusText}`);const n=await e.json(),r=Array.isArray(n.gitmojis)?n.gitmojis.filter($m):[];return Wy(r),ko.forEach(o=>o(r)),r}catch(e){console.warn("Failed to load gitmoji list:",e);const n=[];return ko.forEach(r=>r(n)),n}finally{qo=null}})();return qo=t,t},Uy=t=>{const[e,n]=i.useState(()=>t?yl()?.gitmojis??[]:[]),[r,o]=i.useState(!1),a=i.useRef(t);a.current=t,i.useEffect(()=>{if(!t){ko.delete(n),n([]),o(!1);return}const l=yl();if(l&&(n(l.gitmojis),hu(l)))return;ko.add(n),o(!0);let d=!1;return pu().finally(()=>{!d&&a.current&&o(!1)}),()=>{d=!0,ko.delete(n)}},[t]);const c=i.useCallback(async()=>{if(!a.current)return[];if(e.length>0)return e;const l=yl();return l&&hu(l)?l.gitmojis:pu()},[e]);return{gitmojis:e,isLoading:r,ensureLoaded:c}},gu=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")};function Hy(t,e,n){const r=ft.c(5),[o,a]=i.useState();let c,l;return r[0]!==n||r[1]!==t||r[2]!==e?(c=()=>{if(e){a(void 0);return}if(!t){a(void 0);return}a(void 0);let d=!1;return(async()=>{const[f,m]=await Promise.all([Wp(t),Up(t)]).catch(Gy);if(d)return;const u=gu(f),p=gu(m);if(!u||!p||p===u)return;const y=n||"",g=p.split("/").filter(Boolean).pop()||p;a({source:"sdk",path:p,projectDirectory:u,branch:y,label:y||g,name:g,worktreeRoot:p,worktreeStatus:"ready",headState:y?"branch":"unborn",worktreeSource:"existing"})})(),()=>{d=!0}},l=[t,e,n],r[0]=n,r[1]=t,r[2]=e,r[3]=c,r[4]=l):(c=r[3],l=r[4]),i.useEffect(c,l),e??o}function Gy(){return["",""]}const uo=async(t,e)=>{const n=await Cs(`/api/git/integrate/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){const r=await n.json().catch(()=>null);throw new Error(r?.error||`Git integrate request failed: ${n.statusText}`)}return n.json()};async function go(t){return uo("plan",t)}async function Ky(t){return uo("conflict-details",{tempWorktreePath:t})}async function qy(t){return(await uo("cherry-pick-status",{tempWorktreePath:t})).inProgress}async function Yy(t){return uo("run",{plan:t})}async function Qy(t){await uo("abort",{state:t})}async function Jy(t){return uo("continue",{state:t})}const Xy=({repoRoot:t,sourceBranch:e,worktreeMetadata:n,localBranches:r,defaultTargetBranch:o,refreshKey:a,onRefresh:c})=>{const{t:l}=Nt(),d=ut(M=>M.currentSessionId),f=Ee(M=>M.setActiveMainTab),[m,u]=tt.useState(!1),p=tt.useRef(null),[y,g]=tt.useState(o);tt.useEffect(()=>{g(o)},[o]),tt.useEffect(()=>{if(m){const M=setTimeout(()=>{p.current?.focus()},0);return()=>clearTimeout(M)}},[m]);const b=!!(t&&e&&y&&y!=="HEAD"&&e!==y),[x,h]=tt.useState({kind:"idle"}),[C,w]=tt.useState(!1),[v,S]=tt.useState([]),k=tt.useMemo(()=>d?`openchamber.integrate.conflict:${d}`:null,[d]);tt.useEffect(()=>{if(!k||typeof window>"u")return;const M=window.localStorage.getItem(k);if(!M)return;let te=!1;try{const re=JSON.parse(M);if(!re?.tempWorktreePath||re.repoRoot!==t){window.localStorage.removeItem(k);return}(async()=>{const Q=await qy(re.tempWorktreePath).catch(()=>!1);if(te)return;if(!Q){window.localStorage.removeItem(k);return}const H=await Ky(re.tempWorktreePath).catch(()=>null);te||H&&h({kind:"conflict",state:re,details:H})})()}catch{window.localStorage.removeItem(k)}return()=>{te=!0}},[k,t]),tt.useEffect(()=>{if(!b){h({kind:"idle"});return}let M=!1;return h({kind:"loading"}),(async()=>{try{const te=await go({repoRoot:t,sourceBranch:e,targetBranch:y});if(M)return;if(h({kind:"ready",plan:te}),te.commits.length>0){const Q=te.commits.slice(-50).reverse(),H=await Hp(t,Q);M||(S(H),w(!1))}else M||(S([]),w(!1))}catch{M||h({kind:"idle"})}})(),()=>{M=!0}},[b,t,e,y,a]);const j=tt.useCallback(M=>{d&&ut.getState().setWorktreeMetadata(d,{...n,createdFromBranch:M})},[d,n]),A=ut(M=>M.openNewSessionDraft),D=tt.useCallback(async M=>{const te=await En("git.integrate.cherrypick.resolve.visible",{current_commit:M.state.currentCommit,target_branch:M.state.targetBranch}),re=await En("git.integrate.cherrypick.resolve.instructions",{repo_root:M.state.repoRoot,temp_worktree_path:M.state.tempWorktreePath,source_branch:M.state.sourceBranch,target_branch:M.state.targetBranch,current_commit:M.state.currentCommit}),Q=`Cherry-pick conflict context (JSON)
|
|
6
|
-
${JSON.stringify({repoRoot:M.state.repoRoot,tempWorktreePath:M.state.tempWorktreePath,sourceBranch:M.state.sourceBranch,targetBranch:M.state.targetBranch,currentCommit:M.state.currentCommit,remainingCommits:M.state.remainingCommits,statusPorcelain:M.details.statusPorcelain,unmergedFiles:M.details.unmergedFiles,currentPatchMeta:M.details.currentPatchMeta,currentPatch:M.details.currentPatch,diff:M.details.diff},null,2)}`;return{visibleText:te,instructionsText:re,payloadText:Q}},[]),N=hi(M=>M.setPendingInputText),B=hi(M=>M.setPendingSyntheticParts),T=tt.useCallback(async(M,te)=>{const re=await D(M);if(te){A({directoryOverride:M.state.tempWorktreePath,initialPrompt:re.visibleText,syntheticParts:[{text:re.instructionsText,synthetic:!0},{text:re.payloadText,synthetic:!0}]}),f("chat");return}if(!d){le.error(l("gitView.integrate.noActiveSession"),{description:l("gitView.integrate.noActiveSessionDescription")});return}N(re.visibleText,"replace"),B([{text:re.instructionsText,synthetic:!0},{text:re.payloadText,synthetic:!0}]),f("chat")},[d,f,D,A,N,B,l]),E=tt.useCallback(async()=>{if(x.kind==="ready"){if(x.plan.commits.length===0){le.message(l("gitView.integrate.noCommitsToMoveToast"));return}h({kind:"running",plan:x.plan});try{const M=await Yy(x.plan);if(M.kind==="success"){le.success(l("gitView.integrate.commitsMovedToast"),{description:M.moved===1?l("gitView.integrate.commitsMovedDescriptionSingle",{count:M.moved,branch:x.plan.targetBranch}):l("gitView.integrate.commitsMovedDescriptionPlural",{count:M.moved,branch:x.plan.targetBranch})});const te=await go(x.plan);h({kind:"ready",plan:te}),c?.();return}M.kind==="conflict"&&(le.error(l("gitView.integrate.cherryPickConflictToast"),{description:l("gitView.integrate.cherryPickConflictDescription")}),h({kind:"conflict",state:M.state,details:M.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(M.state)))}catch(M){const te=M instanceof Error?M.message:String(M);le.error(l("gitView.integrate.failedToMoveToast"),{description:te});const re=await go({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(re?{kind:"ready",plan:re}:{kind:"idle"})}}},[x,c,t,e,y,k,l]),_=tt.useCallback(async()=>{if(x.kind==="conflict")try{await Qy(x.state),le.message(l("gitView.integrate.cherryPickAbortedToast")),k&&typeof window<"u"&&window.localStorage.removeItem(k)}finally{const M=await go({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(M?{kind:"ready",plan:M}:{kind:"idle"})}},[x,t,e,y,k,l]),R=tt.useCallback(async()=>{if(x.kind==="conflict")try{const M=await Jy(x.state);if(M.kind==="success"){le.success(l("gitView.integrate.cherryPickFinishedToast"));const te=await go({repoRoot:t,sourceBranch:e,targetBranch:y}).catch(()=>null);h(te?{kind:"ready",plan:te}:{kind:"idle"}),k&&typeof window<"u"&&window.localStorage.removeItem(k),c?.();return}M.kind==="conflict"&&(h({kind:"conflict",state:M.state,details:M.details}),k&&typeof window<"u"&&window.localStorage.setItem(k,JSON.stringify(M.state)))}catch(M){const te=M instanceof Error?M.message:String(M);le.error(l("gitView.integrate.cherryPickContinueFailedToast"),{description:te})}},[x,t,e,y,c,k,l]);return!t||!e?null:s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[s.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(I,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:l("gitView.integrate.title")}),x.kind==="ready"&&x.plan.commits.length>0?s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:l("gitView.integrate.toMoveCount",{count:x.plan.commits.length})}):null]}),s.jsx("div",{className:"flex items-center gap-2",children:x.kind==="loading"||x.kind==="running"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.integrate.moveCommits")}),s.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",y]})]}),s.jsx("div",{className:"flex-1"}),s.jsxs(tn,{open:m,onOpenChange:u,children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(Ve,{variant:"outline",size:"sm",className:"gap-1.5",children:[l("gitView.integrate.target"),s.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:y}),s.jsx(I,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),s.jsx(en,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:s.jsxs($a,{className:"h-full min-h-0",children:[s.jsx(za,{ref:p,placeholder:l("gitView.branch.searchPlaceholder"),onKeyDown:M=>M.stopPropagation()}),s.jsxs(Wa,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(Ua,{children:l("gitView.branch.empty")}),s.jsx(ui,{heading:l("gitView.branch.localBranches"),children:r.map(M=>s.jsx(mi,{value:M,onSelect:()=>{g(M),j(M),u(!1)},children:M},M))})]})]})})]}),x.kind==="ready"?s.jsx(Ve,{size:"sm",onClick:()=>{E()},disabled:!b||x.plan.commits.length===0,children:l("gitView.integrate.move")}):x.kind==="loading"?s.jsx(Ve,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.checking")}):x.kind==="running"?s.jsx(Ve,{size:"sm",variant:"outline",disabled:!0,children:l("gitView.integrate.moving")}):null]}),x.kind==="ready"&&x.plan.commits.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.noCommitsToMove")}),x.kind==="ready"&&x.plan.commits.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"typography-meta text-foreground",children:[l("gitView.integrate.commitsToMove"),s.jsxs("span",{className:"text-muted-foreground",children:[" (",x.plan.commits.length,")"]})]}),v.length>0&&x.plan.commits.length>5&&s.jsx("button",{type:"button",onClick:()=>w(M=>!M),className:"typography-micro text-muted-foreground hover:text-foreground",children:l(C?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),s.jsxs("div",{className:"space-y-1",children:[(C?v:v.slice(0,5)).map(M=>s.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[s.jsx("span",{className:"font-mono text-xs text-muted-foreground flex-shrink-0",children:M.short}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:M.subject||M.sha})]},M.sha)),v.length===0&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.integrate.previewUnavailable")}),x.plan.commits.length>v.length&&s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:l("gitView.integrate.showingFirstCommits",{count:v.length})})]})]}),x.kind==="conflict"&&s.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[s.jsx("div",{className:"typography-meta text-foreground",children:l("gitView.integrate.conflictsInFiles",{count:x.details.unmergedFiles.length})}),s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[l("gitView.integrate.currentCommit"),": ",s.jsx("span",{className:"font-mono",children:x.state.currentCommit.slice(0,7)})]}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.details.unmergedFiles.slice(0,6).map(M=>s.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:M},M)),x.details.unmergedFiles.length>6&&s.jsx("span",{className:"text-xs text-muted-foreground",children:l("gitView.integrate.moreFiles",{count:x.details.unmergedFiles.length-6})})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(Ve,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{_()},children:l("gitView.operation.abort")}),s.jsxs(Ve,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!d,onClick:()=>{T({state:x.state,details:x.details},!1)},children:[s.jsx(I,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.currentSession")]}),s.jsxs(Ve,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{T({state:x.state,details:x.details},!0)},children:[s.jsx(I,{name:"sparkling",className:"size-3.5"}),l("gitView.integrate.newSession")]}),s.jsx(Ve,{size:"sm",className:"typography-meta",onClick:()=>{R()},children:l("gitView.operation.continue")})]})]})]})]})},Zy=({open:t,onOpenChange:e,directory:n,hasUncommittedChanges:r,hasStagedChanges:o=!1,uncommittedFileCount:a,onChanged:c})=>{const{t:l}=Nt(),[d,f]=i.useState([]),[m,u]=i.useState(!1),[p,y]=i.useState(""),[g,b]=i.useState(""),[x,h]=i.useState(null),[C,w]=i.useState({}),v=i.useCallback(async()=>{if(n){u(!0);try{const N=await Gp(n);f(N.stashes),w({})}catch(N){le.error(N instanceof Error?N.message:l("gitView.stashes.toast.loadFailed"))}finally{u(!1)}}},[n,l]);i.useEffect(()=>{t&&v()},[v,t]),i.useEffect(()=>{if(!t||!n||d.length===0)return;let N=!1;const B=d.map(T=>T.ref);return Kp(n,B).then(T=>{N||w(T.counts)}).catch(()=>{}),()=>{N=!0}},[n,t,d]);const S=i.useMemo(()=>{const N=p.trim().toLowerCase();return N?d.filter(B=>`${B.ref} ${B.message} ${B.relativeTime}`.toLowerCase().includes(N)):d},[p,d]),k=i.useCallback(async N=>{await v(),await c?.(N)},[v,c]),j=async()=>{if(!(!n||x)){h("create");try{const N=await qp(n,{message:g.trim()||void 0});N.created?(le.success(l("gitView.stashes.toast.created")),b("")):le.info(l("gitView.stashes.toast.noChanges")),await k({affectsIndex:!!(N.created&&o)})}catch(N){le.error(N instanceof Error?N.message:l("gitView.stashes.toast.createFailed"))}finally{h(null)}}},A=async(N,B)=>{if(!(!n||x)&&!(B==="drop"&&!window.confirm(l("gitView.stashes.confirm.drop",{ref:N.ref})))){h(`${B}:${N.ref}`);try{B==="apply"&&await Yp(n,{ref:N.ref}),B==="pop"&&await Qp(n,{ref:N.ref}),B==="drop"&&await Jp(n,{ref:N.ref});const T=B==="apply"?"gitView.stashes.toast.applySuccess":B==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";le.success(l(T)),await k({affectsIndex:B!=="drop"})}catch(T){const E=B==="apply"?"gitView.stashes.toast.applyFailed":B==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";le.error(T instanceof Error?T.message:l(E)),await k({affectsIndex:B!=="drop"})}finally{h(null)}}},D=x!==null;return s.jsx(Ms,{open:t,onOpenChange:e,children:s.jsxs(Es,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsxs(Gs,{children:[s.jsxs(Vs,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"archive-stack",className:"h-5 w-5"}),l("gitView.stashes.title")]}),s.jsx(an,{children:l("gitView.stashes.description")})]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[s.jsx(vn,{value:g,onChange:N=>b(N.target.value),placeholder:l("gitView.stashes.messagePlaceholder"),disabled:D||!r,className:"flex-1"}),s.jsxs(Ve,{onClick:j,disabled:!r||D||!n,children:[x==="create"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"inbox-archive",className:"size-4"}),l("gitView.stashes.actions.stashCurrentWithCount",{count:a})]})]}),s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:l("gitView.stashes.includeUntrackedHint")})]}),s.jsxs("div",{className:"relative mt-2",children:[s.jsx(I,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx(vn,{value:p,onChange:N=>y(N.target.value),placeholder:l("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),s.jsx("div",{className:"flex-1 overflow-y-auto",children:m?s.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:s.jsx(I,{name:"loader-4",className:"size-5 animate-spin"})}):S.length===0?s.jsx("div",{className:"py-8 text-center text-muted-foreground",children:l(p?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):S.map((N,B)=>s.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[s.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[s.jsx("p",{className:"typography-small truncate text-foreground",children:N.message||l("gitView.stashes.untitled")}),s.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{children:B===0&&!p.trim()?l("gitView.stashes.latestLabel"):l("gitView.stashes.itemNumber",{number:B+1})})}),s.jsx(Ft,{sideOffset:6,children:N.ref})]})," · ",N.relativeTime," · ",typeof C[N.ref]=="number"?l("gitView.stashes.fileCount",{count:C[N.ref]}):l("gitView.stashes.fileCountLoading")]})]}),s.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[s.jsx(wl,{label:l("gitView.stashes.actions.apply"),loading:x===`apply:${N.ref}`,onClick:()=>A(N,"apply"),disabled:D,children:s.jsx(I,{name:"inbox-unarchive",className:"size-4"})}),s.jsx(wl,{label:l("gitView.stashes.actions.pop"),loading:x===`pop:${N.ref}`,onClick:()=>A(N,"pop"),disabled:D,children:s.jsx(I,{name:"inbox-unarchive-fill",className:"size-4"})}),s.jsx(wl,{label:l("gitView.stashes.actions.drop"),loading:x===`drop:${N.ref}`,onClick:()=>A(N,"drop"),disabled:D,destructive:!0,children:s.jsx(I,{name:"delete-bin",className:"size-4"})})]})]},N.ref))})]})})},wl=t=>{const e=ft.c(17),{label:n,loading:r,disabled:o,destructive:a,onClick:c,children:l}=t,d=r||void 0,f=a?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let m;e[0]!==f?(m=Te("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",f),e[0]=f,e[1]=m):m=e[1];let u;e[2]!==l||e[3]!==r?(u=r?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):l,e[2]=l,e[3]=r,e[4]=u):u=e[4];let p;e[5]!==o||e[6]!==n||e[7]!==c||e[8]!==d||e[9]!==m||e[10]!==u?(p=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":n,"aria-busy":d,className:m,onClick:c,disabled:o,children:u})}),e[5]=o,e[6]=n,e[7]=c,e[8]=d,e[9]=m,e[10]=u,e[11]=p):p=e[11];let y;e[12]!==n?(y=s.jsx(Ft,{sideOffset:6,children:n}),e[12]=n,e[13]=y):y=e[13];let g;return e[14]!==p||e[15]!==y?(g=s.jsxs(Et,{children:[p,y]}),e[14]=p,e[15]=y,e[16]=g):g=e[16],g},ew=t=>{const e=ft.c(16),{onOpenStashes:n}=t,{t:r}=Nt();let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx(I,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e[0]=o):o=e[0];let a;e[1]!==r?(a=r("gitView.empty.cleanTitle"),e[1]=r,e[2]=a):a=e[2];let c;e[3]!==a?(c=s.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:a}),e[3]=a,e[4]=c):c=e[4];let l;e[5]!==r?(l=r("gitView.empty.cleanDescription"),e[5]=r,e[6]=l):l=e[6];let d;e[7]!==l?(d=s.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:l}),e[7]=l,e[8]=d):d=e[8];let f;e[9]!==n||e[10]!==r?(f=n?s.jsxs(Ve,{type:"button",variant:"outline",size:"sm",onClick:n,className:"gap-1.5",children:[s.jsx(I,{name:"archive-stack",className:"size-4"}),r("gitView.stashes.title")]}):null,e[9]=n,e[10]=r,e[11]=f):f=e[11];let m;return e[12]!==c||e[13]!==d||e[14]!==f?(m=s.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[o,c,d,f]}),e[12]=c,e[13]=d,e[14]=f,e[15]=m):m=e[15],m},oi=8,tw=t=>{const e=ft.c(18),{laned:n,totalLanes:r,isExpanded:o}=t,{lane:a,color:c,connectors:l}=n,f=Math.max(r,a+1)*oi+oi/2,m=i.useRef(null),u=i.useRef(null);let p;e[0]!==c||e[1]!==l||e[2]!==a||e[3]!==f?(p=()=>{const h=m.current,C=u.current;if(!h||!C)return;const w=h.offsetHeight;if(w===0)return;const v=window.devicePixelRatio||1;C.width=f*v,C.height=w*v;const S=C.getContext("2d");if(!S)return;S.scale(v,v),S.clearRect(0,0,f,w);const k=w/2,j=a*oi+oi/2,A=getComputedStyle(C),D=A.getPropertyValue("--surface-muted-foreground").trim()||A.color,N=E=>{if(!E.startsWith("var("))return E;const _=E.slice(4,-1).trim();return A.getPropertyValue(_).trim()||D},B=[...l].sort(nw);for(const E of B){const _=E.fromLane*oi+oi/2,R=E.toLane*oi+oi/2,z=E.type==="passing"?.72:E.type==="branch-out"||E.type==="merge-in"?.95:1;S.beginPath(),S.strokeStyle=N(E.color),S.globalAlpha=z,S.lineWidth=1.25,S.lineCap="round";e:switch(E.type){case"passing":case"commit-lane":{S.moveTo(_,0),S.lineTo(_,w);break e}case"top-stub":{S.moveTo(_,0),S.lineTo(_,k);break e}case"bottom-stub":{S.moveTo(_,k),S.lineTo(_,w);break e}case"branch-out":{const V=(k+w)/2;S.moveTo(j,k),S.bezierCurveTo(j,V,R,V,R,w);break e}case"merge-in":{const V=k/2;S.moveTo(_,0),S.bezierCurveTo(_,V,j,V,j,k);break e}default:continue}S.stroke(),S.globalAlpha=1}const T=A.getPropertyValue("--background").trim()||A.getPropertyValue("--surface-background").trim();S.beginPath(),S.arc(j,k,4,0,Math.PI*2),S.fillStyle=N(c),S.fill(),S.beginPath(),S.arc(j,k,5,0,Math.PI*2),S.strokeStyle=T||D,S.lineWidth=2,S.stroke()},e[0]=c,e[1]=l,e[2]=a,e[3]=f,e[4]=p):p=e[4];let y;e[5]!==c||e[6]!==l||e[7]!==o||e[8]!==a||e[9]!==n||e[10]!==r||e[11]!==f?(y=[n,a,c,l,r,o,f],e[5]=c,e[6]=l,e[7]=o,e[8]=a,e[9]=n,e[10]=r,e[11]=f,e[12]=y):y=e[12],i.useLayoutEffect(p,y);let g;e[13]!==f?(g={width:f,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=f,e[14]=g):g=e[14];let b;e[15]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx("canvas",{ref:u,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=b):b=e[15];let x;return e[16]!==g?(x=s.jsx("div",{ref:m,style:g,children:b}),e[16]=g,e[17]=x):x=e[17],x};function sw(t){return t==="branch-out"||t==="merge-in"}function nw(t,e){const n=sw;return(n(t.type)?1:0)-(n(e.type)?1:0)}const xu=15e3,bu=500,yu=12,wu=8*1024*1024,vu=t=>typeof t=="string"?0:(t.original?.length??0)+(t.modified?.length??0),ju=t=>{if(t.size<=yu){let o=0;for(const a of t.values())o+=vu(a);if(o<=wu)return t}const e=Array.from(t.entries()).reverse(),n=new Map;let r=0;for(const[o,a]of e){if(n.size>=yu)continue;const c=vu(a);r+c>wu&&n.size>0||(n.set(o,a),r+=c)}return new Map(Array.from(n.entries()).reverse())};function Su(t,e){const n=new Date(t);return Number.isNaN(n.getTime())?t:kc(n,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function rw(t){switch(t){case"A":return"text-[var(--status-success)]";case"D":return"text-[var(--status-error)]";case"M":return"text-[var(--status-warning)]";case"R":return"text-[var(--status-info)]";default:return"text-muted-foreground"}}function iw(t){return t?t.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{const n=e.startsWith("HEAD ->");return{label:n?e.replace("HEAD -> ",""):e.replace("tag: ",""),isHead:n,isTag:e.startsWith("tag: ")}}):[]}const ow=i.memo(({entry:t,mode:e="history",laned:n,totalLanes:r,isExpanded:o,onToggle:a,files:c,isLoadingFiles:l,onCopyHash:d,directory:f,onConflict:m,onActionSuccess:u})=>{const{t:p}=Nt(),y=Ee(H=>H.timeFormatPreference),g=e==="graph",[b,x]=i.useState(null),[h,C]=i.useState(!1),[w,v]=i.useState(""),[S,k]=i.useState(null),[j,A]=i.useState(new Set),[D,N]=i.useState(new Map),[B,T]=i.useState(new Set),E=async()=>{if(f){x("checkout");try{await ig(f,t.hash),le.success(p("gitView.history.actions.detachedHead")),u?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},_=async()=>{if(!(!f||!w.trim())){x("createBranch");try{await Zp(f,w.trim(),t.hash),C(!1),v(""),u?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},R=async()=>{if(f){x("cherryPick");try{const H=await rg(f,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"cherry-pick"}):u?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},z=async()=>{if(f){x("revert");try{const H=await ng(f,t.hash);H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"revert"}):u?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},V=async(H,X=!1)=>{if(!(!f||b!==null)){x("reset");try{await eg(f,t.hash,H,X),u?.()}catch(oe){le.error(String(oe.message))}finally{x(null)}}},$=async()=>{if(!S)return;const H=S;switch(k(null),H){case"checkout":return E();case"cherryPick":return R();case"revert":return z();case"merge":return M();case"rebase":return te();case"resetSoft":return V("soft");case"resetMixed":return V("mixed");case"resetHard":return V("hard",!0)}},M=async()=>{if(f){x("merge");try{const H=await sg(f,{branch:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"merge"}):u?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},te=async()=>{if(f){x("rebase");try{const H=await tg(f,{onto:t.hash});H.conflict?m?.({conflict:!0,conflictFiles:H.conflictFiles,operation:"rebase"}):u?.()}catch(H){le.error(String(H.message))}finally{x(null)}}},re=i.useCallback(async H=>{const X=H.path;if(!f){N(oe=>new Map(oe).set(X,"error"));return}N(oe=>ju(new Map(oe).set(X,"loading")));try{const oe=Xp(f,t.hash,H.path,!1),fe=new Promise((ie,Ne)=>{setTimeout(()=>Ne(new Error(`Timed out after ${xu}ms`)),xu)}),ve=await Promise.race([oe,fe]);N(ie=>ju(new Map(ie).set(X,ve)))}catch{N(oe=>new Map(oe).set(X,"error"))}},[f,t.hash]),Q=i.useCallback(async H=>{const X=H.path;if(H.changeType==="R"||H.isBinary){A(ie=>{const Ne=new Set(ie);return Ne.has(X)?Ne.delete(X):Ne.add(X),Ne});return}const oe=D.get(X);if(j.has(X)&&oe&&oe!=="error"){A(ie=>{const Ne=new Set(ie);return Ne.delete(X),Ne});return}A(ie=>{const Ne=new Set(ie);return Ne.add(X),Ne}),!(oe&&oe!=="error"||H.insertions+H.deletions>bu&&!B.has(X))&&await re(H)},[D,B,re,j]);return s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:a,className:Te("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",g?"hover:bg-[var(--interactive-hover)]/40":o?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[g&&n&&r!==void 0?s.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:s.jsx(tw,{laned:n,totalLanes:r,isExpanded:o})}):s.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),s.jsxs("div",{className:"min-w-0 flex-1",children:[g?(()=>{const H=iw(t.refs);return H.length>0?s.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:H.map(X=>s.jsx("span",{className:Te("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",X.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":X.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:X.label},X.label))}):null})():null,s.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:t.message}),s.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[s.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[s.jsx("span",{className:"truncate min-w-[3ch]",title:t.author_name,children:t.author_name}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("span",{className:"truncate min-w-0",title:Su(t.date,y),children:Su(t.date,y)})]}),s.jsx("span",{className:"shrink-0",children:"·"}),s.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:H=>{H.stopPropagation(),d(t.hash)},children:s.jsx(I,{name:"file-copy",className:"size-3"})})}),s.jsx(Ft,{sideOffset:8,children:p("gitView.history.copySha")})]})]})]})]}),o&&s.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[g&&S?s.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:p(`gitView.history.actions.${S}Confirm`)}),s.jsxs(Ve,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:b!==null,onClick:H=>{H.stopPropagation(),$()},children:[b!==null?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.confirmButton")]}),s.jsx(Ve,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:b!==null,onClick:H=>{H.stopPropagation(),k(null)},children:p("gitView.history.actions.cancelButton")})]}):g?s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[s.jsx(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("checkout")},children:p("gitView.history.actions.checkout")}),h?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("input",{autoFocus:!0,value:w,onChange:H=>v(H.target.value),onKeyDown:H=>{H.key==="Enter"&&_(),H.key==="Escape"&&(C(!1),v(""))},placeholder:p("gitView.history.actions.createBranchPlaceholder"),className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),s.jsxs(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:!w.trim()||b!==null,onClick:H=>{H.stopPropagation(),_()},children:[b==="createBranch"?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.createBranchConfirm")]})]}):s.jsx(Ve,{variant:"outline",size:"xs",className:"h-6",onClick:H=>{H.stopPropagation(),C(!0)},children:p("gitView.history.actions.createBranch")}),s.jsx(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("cherryPick")},children:p("gitView.history.actions.cherryPick")}),s.jsx(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("revert")},children:p("gitView.history.actions.revert")}),s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>H.stopPropagation(),children:[b==="reset"?s.jsx(I,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,p("gitView.history.actions.reset")]})}),s.jsx(en,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(H=>s.jsx(ws,{disabled:b!==null,onSelect:X=>{X.stopPropagation(),k(`reset${H.charAt(0).toUpperCase()+H.slice(1)}`)},children:p(`gitView.history.actions.reset${H.charAt(0).toUpperCase()+H.slice(1)}`)},H))})]}),s.jsx(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("merge")},children:p("gitView.history.actions.merge")}),s.jsx(Ve,{variant:"outline",size:"xs",className:"h-6",disabled:b!==null,onClick:H=>{H.stopPropagation(),k("rebase")},children:p("gitView.history.actions.rebase")})]}):null,l?s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:p("gitView.history.loadingFiles")})]}):c.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:p("gitView.history.noFiles")}):s.jsx("ul",{className:"space-y-0.5 py-2",children:c.map(H=>s.jsxs("li",{children:[s.jsxs("button",{type:"button",onClick:()=>Q(H),className:Te("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",j.has(H.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[s.jsx("span",{className:Te("font-semibold w-3 text-center shrink-0",rw(H.changeType)),children:H.changeType}),s.jsx("span",{className:"truncate text-foreground min-w-0",title:H.path,children:H.path}),!H.isBinary&&s.jsxs("span",{className:"shrink-0",children:[s.jsxs("span",{style:{color:"var(--status-success)"},children:["+",H.insertions]}),s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),s.jsxs("span",{style:{color:"var(--status-error)"},children:["-",H.deletions]})]}),H.isBinary&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:p("gitView.history.binary")}),s.jsx(I,{name:j.has(H.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),j.has(H.path)&&s.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded border border-border/40 mx-2 mb-1","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:H.changeType==="R"?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.renamedNoDiff")}):H.isBinary?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.binaryNoDiff")}):(()=>{const X=H.insertions+H.deletions;if(!B.has(H.path)&&X>bu)return s.jsxs("div",{className:"flex flex-col items-start gap-1 px-3 py-2 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:p("gitView.history.largeDiffTitle",{count:X})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:p("gitView.history.largeDiffDescription")}),s.jsx(Ve,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{T(fe=>new Set(fe).add(H.path)),re(H)},children:p("gitView.history.renderDiffAnyway")})]});const oe=D.get(H.path);return oe==="loading"||oe===void 0?s.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:p("gitView.history.loadingDiff")}):oe==="error"?s.jsx("button",{type:"button",onClick:()=>Q(H),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:p("gitView.history.diffError")}):s.jsx(km,{original:oe.original,modified:oe.modified,language:Ti(H.path)||"",fileName:H.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},H.path))})]})]})}),Nu=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)","var(--syntax-keyword)","var(--syntax-string)","var(--status-info)"];function Yo(t){return Nu[t%Nu.length]}function aw(t){if(t.length===0)return[];const e=[],n=[];for(let r=0;r<t.length;r++){const o=t[r],a=[];for(let y=0;y<e.length;y++)e[y]===o.hash&&a.push(y);let c=a.length>0?a[0]:-1;if(c===-1){const y=e.indexOf(null);y!==-1?c=y:(c=e.length,e.push(null))}const l=a.slice(1),d=Yo(c),f=e[c]===o.hash,m=o.parents.length>0;m?e[c]=o.parents[0]:e[c]=null;const u=[];for(let y=1;y<o.parents.length;y++){const g=o.parents[y],b=e.indexOf(g);if(b!==-1)u.push(b);else{const x=e.indexOf(null),h=x!==-1?x:e.length;e[h]=g,h===e.length&&e.push(g),u.push(h)}}const p=[];f&&m?p.push({fromLane:c,toLane:c,color:d,type:"commit-lane"}):f&&!m?p.push({fromLane:c,toLane:c,color:d,type:"top-stub"}):!f&&m&&p.push({fromLane:c,toLane:c,color:d,type:"bottom-stub"});for(const y of l)p.push({fromLane:y,toLane:c,color:Yo(y),type:"merge-in"}),e[y]=null;for(const y of u)p.push({fromLane:c,toLane:y,color:Yo(y),type:"branch-out"});for(let y=0;y<e.length;y++)e[y]!==null&&y!==c&&(u.includes(y)||p.push({fromLane:y,toLane:y,color:Yo(y),type:"passing"}));n.push({commit:o,lane:c,color:d,connectors:p})}return n}const lw=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],cw=t=>{const e=ft.c(84),{mode:n,log:r,isLogLoading:o,logMaxCount:a,onLogMaxCountChange:c,expandedCommitHashes:l,onToggleCommit:d,commitFilesMap:f,loadingCommitHashes:m,onCopyHash:u,directory:p,showHeader:y,contentMaxHeightClassName:g,branchDivider:b,onConflict:x,onActionSuccess:h}=t,C=n===void 0?"history":n,w=y===void 0?!0:y,v=g===void 0?"max-h-[50vh]":g,S=b===void 0?null:b,{t:k}=Nt(),[j,A]=i.useState(!0),D=C==="graph";let N;e[0]!==D||e[1]!==r?(N=D&&r?aw(r.all):[],e[0]=D,e[1]=r,e[2]=N):N=e[2];const B=N;let T;e[3]!==B?(T=Math.max(1,...B.map(dw)),e[3]=B,e[4]=T):T=e[4];const E=T;let _;e[5]!==B?(_=new Map(B.map(uw)),e[5]=B,e[6]=_):_=e[6];const R=_;if(!r)return null;const z=S!==null&&S.insertBeforeIndex>0&&S.insertBeforeIndex<r.all.length,V=S!==null&&S.insertBeforeIndex===r.all.length,$=z||V;let M;e[7]!==S||e[8]!==z||e[9]!==V||e[10]!==r.all?(M=z?r.all.slice(0,S.insertBeforeIndex):V?r.all:[],e[7]=S,e[8]=z,e[9]=V,e[10]=r.all,e[11]=M):M=e[11];const te=M;let re;if(e[12]!==S||e[13]!==f||e[14]!==v||e[15]!==p||e[16]!==l||e[17]!==z||e[18]!==$||e[19]!==D||e[20]!==o||e[21]!==R||e[22]!==m||e[23]!==r.all||e[24]!==a||e[25]!==E||e[26]!==C||e[27]!==h||e[28]!==x||e[29]!==u||e[30]!==c||e[31]!==d||e[32]!==k||e[33]!==te){const pe=z?r.all.slice(S.insertBeforeIndex):[];let L;e[35]!==S?.direction?(L=S?.direction==="down"?s.jsx(I,{name:"arrow-down-s",className:"size-3.5"}):s.jsx(I,{name:"arrow-up",className:"size-3.5"}),e[35]=S?.direction,e[36]=L):L=e[36];const se=L;let Z;e[37]!==f||e[38]!==p||e[39]!==l||e[40]!==D||e[41]!==R||e[42]!==m||e[43]!==E||e[44]!==C||e[45]!==h||e[46]!==x||e[47]!==u||e[48]!==d?(Z=Me=>s.jsx("ul",{className:"divide-y divide-border/60",children:Me.map(Fe=>s.jsx(ow,{entry:Fe,mode:C,laned:D?R.get(Fe.hash):void 0,totalLanes:D?E:void 0,isExpanded:l.has(Fe.hash),onToggle:()=>d(Fe.hash),files:f.get(Fe.hash)??[],isLoadingFiles:m.has(Fe.hash),onCopyHash:u,directory:p,onConflict:x,onActionSuccess:h},Fe.hash))}),e[37]=f,e[38]=p,e[39]=l,e[40]=D,e[41]=R,e[42]=m,e[43]=E,e[44]=C,e[45]=h,e[46]=x,e[47]=u,e[48]=d,e[49]=Z):Z=e[49];const je=Z;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(Ve,{type:"button",variant:"ghost",size:"xs",onClick:()=>c(a+25),disabled:o,className:"px-3 text-muted-foreground hover:text-foreground",children:o?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(I,{name:"loader-4",className:"size-3 animate-spin"}),k("gitView.history.loadingMore")]}):k("gitView.history.loadMore")})}):null,e[50]=o,e[51]=r.all.length,e[52]=a,e[53]=c,e[54]=k,e[55]=De):De=e[55];const Le=De;re=s.jsx(Wn,{outerClassName:`min-h-0 ${v}`,className:"h-full w-full",children:r.all.length===0?s.jsx("div",{className:"flex h-full items-center justify-center p-4",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:k("gitView.history.noCommits")})}):$&&S?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col gap-0",children:[te.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:je(te)}):null,s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5","aria-hidden":!0,children:[s.jsx("span",{className:"h-px flex-1 bg-border/60"}),s.jsxs("span",{className:"inline-flex max-w-[80%] items-center gap-1 typography-micro text-muted-foreground",children:[s.jsx("span",{className:"truncate",title:S.branchName,children:S.branchName}),se]}),s.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),pe.length>0?s.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:je(pe)}):null]}),Le]}):s.jsxs(s.Fragment,{children:[je(r.all),Le]})}),e[12]=S,e[13]=f,e[14]=v,e[15]=p,e[16]=l,e[17]=z,e[18]=$,e[19]=D,e[20]=o,e[21]=R,e[22]=m,e[23]=r.all,e[24]=a,e[25]=E,e[26]=C,e[27]=h,e[28]=x,e[29]=u,e[30]=c,e[31]=d,e[32]=k,e[33]=te,e[34]=re}else re=e[34];const Q=re;if(!w){if($){let L;return e[56]!==Q?(L=s.jsx("section",{className:"h-full min-h-0",children:Q}),e[56]=Q,e[57]=L):L=e[57],L}let pe;return e[58]!==Q?(pe=s.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:Q}),e[58]=Q,e[59]=pe):pe=e[59],pe}let H;e[60]!==k?(H=k("gitView.history.title"),e[60]=k,e[61]=H):H=e[61];let X;e[62]!==H?(X=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:H}),e[62]=H,e[63]=X):X=e[63];let oe;e[64]!==o||e[65]!==j||e[66]!==a||e[67]!==c||e[68]!==k?(oe=j&&s.jsx("div",{onClick:fw,onPointerDown:mw,children:s.jsxs(Un,{value:String(a),onValueChange:pe=>c(Number(pe)),disabled:o,children:[s.jsx(Hn,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:o,children:s.jsx(An,{placeholder:k("gitView.history.commitsPlaceholder")})}),s.jsx(Gn,{children:lw.map(pe=>s.jsx(Rs,{value:String(pe.value),children:k(pe.labelKey)},pe.value))})]})}),e[64]=o,e[65]=j,e[66]=a,e[67]=c,e[68]=k,e[69]=oe):oe=e[69];let fe;e[70]!==j?(fe=j?s.jsx(I,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):s.jsx(I,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=j,e[71]=fe):fe=e[71];let ve;e[72]!==oe||e[73]!==fe?(ve=s.jsxs("div",{className:"flex items-center gap-2",children:[oe,fe]}),e[72]=oe,e[73]=fe,e[74]=ve):ve=e[74];let ie;e[75]!==X||e[76]!==ve?(ie=s.jsxs(_o,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[X,ve]}),e[75]=X,e[76]=ve,e[77]=ie):ie=e[77];let Ne;e[78]!==Q?(Ne=s.jsx(ro,{children:Q}),e[78]=Q,e[79]=Ne):Ne=e[79];let K;return e[80]!==j||e[81]!==ie||e[82]!==Ne?(K=s.jsxs(no,{open:j,onOpenChange:A,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[ie,Ne]}),e[80]=j,e[81]=ie,e[82]=Ne,e[83]=K):K=e[83],K};function dw(t){return t.lane+1}function uw(t){return[t.commit.hash,t]}function fw(t){return t.stopPropagation()}function mw(t){return t.stopPropagation()}const zm=async(t,e,n)=>{if(t.length===0)return[];const r=Math.max(1,Math.min(e,t.length)),o=new Array(t.length);let a=0;const c=async()=>{for(;;){const l=a;if(a+=1,l>=t.length)return;o[l]=await n(t[l])}};return await Promise.all(Array.from({length:r},()=>c())),o},hw=9e4,pw=15e3,gw=5*6e4,xw=[2e3,5e3],bw=6e4,yw=2*6e4,ww=5*6e4,vw=4,jw=720*6e4,Sw="openchamber.github-pr-status",Nw=t=>t==="closed"||t==="merged",kw=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},Co=(t,e,n)=>`${t}::${e}`,Qo=new Map,Jo=new Map,xo=new Set,ku=new Map,Cw=2;let Ta=0;const Wm=[],Aw=()=>Ta<Cw?(Ta+=1,Promise.resolve()):new Promise(t=>{Wm.push(t)}),Dw=()=>{const t=Wm.shift();if(t){t();return}Ta=Math.max(0,Ta-1)},wo=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null}),Ra=t=>t?.params?.directory&&t.params.branch?{directory:t.params.directory,branch:t.params.branch,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null}:!t?.identity?.directory||!t.identity.branch?null:t.identity,Vc=t=>{const e=Ra(t);return!e?.directory||!e.branch?null:`${e.directory}::${e.branch}`},Um=(t,e)=>Object.entries(t).filter(([,n])=>Vc(n)===e).map(([n])=>n),Iw=(t,e)=>{const n=e.remoteName??t.params?.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null;return{...t,params:t.params?{...t.params,...e,remoteName:n}:{...e,remoteName:n},identity:{directory:e.directory,branch:e.branch,remoteName:n}}},Xo=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},Pw=(t,e,n)=>{const r=Um(t,e),o=r.map(d=>Xo(t[d])).filter(d=>!!d);if(o.length===0)return null;const a=Xo(t[n]);if(a&&Vc(t[n])===e)return a;const c=r.map(d=>t[d]).find(d=>!!(d?.resolvedRemoteName&&Xo(d)));if(c)return Xo(c);const l=o.find(d=>!!d.remoteName);return l||(o[0]??null)},Tw=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:Ra(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Rw=t=>({...wo(),status:t?.status??null,isInitialStatusResolved:t?.isInitialStatusResolved??!1,lastRefreshAt:t?.lastRefreshAt??0,lastDiscoveryPollAt:t?.lastDiscoveryPollAt??0,identity:t?.identity??null,resolvedRemoteName:t?.resolvedRemoteName??t?.status?.resolvedRemoteName??null}),sr=ao()(fc((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,ensureEntry:n=>{t(r=>r.entries[n]?r:{entries:{...r.entries,[n]:wo()}})},setParams:(n,r)=>{t(o=>{const a=o.entries[n]??wo();return{entries:{...o.entries,[n]:Iw(a,r)}}})},startWatching:n=>{if(t(a=>{const c=a.entries[n]??wo();return{entries:{...a.entries,[n]:{...c,watchers:c.watchers+1}}}}),Qo.has(n))return;const r=a=>{const c=window.setTimeout(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const d=e().entries[n];!d||d.watchers<=0||d.status?.pr||e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0})},a),l=Jo.get(n)??[];l.push(c),Jo.set(n,l)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),xw.forEach(a=>r(a));const o=window.setInterval(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const a=e().entries[n];if(!a||a.watchers<=0)return;if(!!!a.status?.pr){const f=Date.now();if(f-a.lastDiscoveryPollAt<gw)return;t(m=>{const u=m.entries[n];return u?{entries:{...m.entries,[n]:{...u,lastDiscoveryPollAt:f}}}:m}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(Nw(a.status?.pr?.state))return;const l=Date.now()-a.lastRefreshAt,d=kw(a.status)?bw:a.status?.checks&&a.status.checks.state!=="pending"?ww:yw;l<d||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},pw);Qo.set(n,o)},stopWatching:n=>{t(c=>{const l=c.entries[n];if(!l)return c;const d=Math.max(0,l.watchers-1);return{entries:{...c.entries,[n]:{...l,watchers:d}}}});const r=e().entries[n];if(r&&r.watchers>0)return;const o=Qo.get(n);typeof o=="number"&&window.clearInterval(o),Qo.delete(n);const a=Jo.get(n);a&&a.length>0&&a.forEach(c=>{window.clearTimeout(c)}),Jo.delete(n)},refresh:async(n,r)=>{const o=e(),a=o.entries[n],c=Vc(a);if(!a||!c)return;const l=Um(o.entries,c),d=l.some(u=>!!o.entries[u]?.status?.pr);if(r?.onlyExistingPr&&!d)return;const f=ku.get(c)??0;if(!r?.force&&Date.now()-f<hw||xo.has(c))return;const m=Pw(o.entries,c,n);if(m){if(xo.add(c),ku.set(c,Date.now()),t(u=>{const p={...u.entries};return l.forEach(y=>{const g=p[y];g&&(p[y]={...g,lastRefreshAt:Date.now(),isLoading:r?.silent?g.isLoading:!0,error:null})}),{entries:p}}),m.githubAuthChecked&&m.githubConnected===!1){t(u=>{const p={...u.entries};return l.forEach(y=>{const g=p[y];g&&(p[y]={...g,status:{connected:!1},error:null,isLoading:r?.silent?g.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?g.isInitialStatusResolved:!0})}),{entries:p}}),xo.delete(c);return}if(!m.github?.prStatus){t(u=>{const p={...u.entries};return l.forEach(y=>{const g=p[y];g&&(p[y]={...g,status:null,error:"GitHub runtime API unavailable",isLoading:r?.silent?g.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?g.isInitialStatusResolved:!0})}),{entries:p}}),xo.delete(c);return}try{t(p=>({...p,activeRequestCount:p.activeRequestCount+1,totalRequestCount:p.totalRequestCount+1})),await Aw();let u;try{u=await m.github.prStatus(m.directory,m.branch,m.remoteName??void 0,{force:r?.force})}finally{Dw()}t(p=>{const y={...p.entries};return l.forEach(g=>{const b=y[g];if(!b)return;const x=b.status?.pr,h=u.pr,w=!!(h&&x&&h.number===x.number&&(!h.body||!h.body.trim())&&typeof x.body=="string"&&x.body.trim().length>0)&&h&&x?.body?{...u,pr:{...h,body:x.body}}:u,v=w.resolvedRemoteName??b.resolvedRemoteName??m.remoteName??null,S=Ra(b)??{directory:m.directory,branch:m.branch,remoteName:m.remoteName??null};y[g]={...b,status:w,error:null,isLoading:r?.silent?b.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?b.isInitialStatusResolved:!0,resolvedRemoteName:v,identity:{...S,remoteName:v??S.remoteName??null}}}),{entries:y}})}catch(u){const p=u instanceof Error?u.message:String(u);t(y=>{const g={...y.entries};return l.forEach(b=>{const x=g[b];x&&(g[b]={...x,error:p||"Failed to load PR status",isLoading:r?.silent?x.isLoading:!1,isInitialStatusResolved:r?.markInitialResolved===!1?x.isInitialStatusResolved:!0})}),{entries:g}})}finally{xo.delete(c),t(u=>({...u,activeRequestCount:Math.max(0,u.activeRequestCount-1)}))}}},refreshTargets:async(n,r)=>{const o=Array.from(new Set(n.map(a=>{const c=a.directory.trim(),l=a.branch.trim();return!c||!l?null:Co(c,l,a.remoteName??null)}).filter(a=>!!a)));await zm(o,vw,a=>e().refresh(a,r))},updateStatus:(n,r)=>{t(o=>{const a=o.entries[n]??wo();return{entries:{...o.entries,[n]:{...a,status:r(a.status)}}}})}}),{name:Sw,storage:xp(),partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=Ra(e);if(!n?.directory||!n.branch)return!1;const r=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return r===0||Date.now()-r<jw}).map(([e,n])=>[e,Tw(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).map(([o,a])=>[o,Rw(a)]))}}})),Ew=t=>{const e=t?.pr;if(!e)return null;if(e.state==="merged")return"merged";if(e.state==="closed")return"closed";if(e.draft)return"draft";const n=t?.checks?.state==="failure",r=typeof e.mergeableState=="string"?e.mergeableState:"",o=e.mergeable===!1||r==="blocked"||r==="dirty";return n||o?"blocked":"open"},Mw=t=>{const e=Ew(t.status??null),n=t.status?.pr;return!e||!n?.number?null:{number:n.number,visualState:e,prState:n.state,draft:!!n.draft,title:typeof n.title=="string"&&n.title.trim().length>0?n.title:null,url:typeof n.url=="string"&&n.url.trim().length>0?n.url:null,base:typeof n.base=="string"&&n.base.trim().length>0?n.base:null,head:typeof n.head=="string"&&n.head.trim().length>0?n.head:null,checks:t.status?.checks?{state:t.status.checks.state,total:t.status.checks.total,success:t.status.checks.success,failure:t.status.checks.failure,pending:t.status.checks.pending}:null,canMerge:typeof t.status?.canMerge=="boolean"?t.status.canMerge:null,mergeableState:typeof n.mergeableState=="string"?n.mergeableState:null,repo:t.status?.repo?{owner:t.status.repo.owner,repo:t.status.repo.repo}:null}},Fw=t=>`${t.number}:${t.visualState}:${t.prState}:${t.draft}:${t.title??""}:${t.url??""}:${t.base??""}:${t.head??""}:${t.canMerge??""}:${t.mergeableState??""}:${t.checks?.state??""}:${t.checks?.total??""}:${t.checks?.success??""}:${t.checks?.failure??""}:${t.checks?.pending??""}:${t.repo?.owner??""}:${t.repo?.repo??""}`;let vl=new Map,Cu=new Map;const Ow=t=>{const e=ft.c(2);let n;return e[0]!==t?(n=r=>{const o=new Map,a=new Map;for(const c of t){const l=r.entries[c];if(!l)continue;const d=Mw(l);if(!d)continue;const f=Fw(d);o.set(c,f),a.set(c,d)}if(o.size===vl.size){let c=!0;for(const[l,d]of o)if(vl.get(l)!==d){c=!1;break}if(c)return Cu}return vl=o,Cu=a,a},e[0]=t,e[1]=n):n=e[1],sr(n)},Lw=t=>{switch(t){case"success":return"bg-[color:var(--status-success)]";case"failure":return"bg-[color:var(--status-error)]";case"pending":return"bg-[color:var(--status-warning)]";default:return"bg-muted-foreground/40"}},Bw=t=>{const e=t?.pr;if(!e)return null;if(e.state==="merged")return"merged";if(e.state==="closed")return"closed";if(e.draft)return"draft";const n=t?.checks?.state==="failure",r=typeof e.mergeableState=="string"?e.mergeableState:"",o=e.mergeable===!1||r==="blocked"||r==="dirty";return n||o?"blocked":"open"},_w=[2e3,5e3],Au=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase()),ai=t=>{let e=t.trim();return e?(e.startsWith("refs/heads/")&&(e=e.slice(11)),e.startsWith("heads/")&&(e=e.slice(6)),e.startsWith("remotes/")&&(e=e.slice(8)),e):""},Vw=(t,e)=>{const n=ai(t);if(!n||n.includes("->"))return"";if(e){const o=`${e}/`;return n.startsWith(o)?n.slice(o.length).trim():""}const r=n.indexOf("/");return r>0?n.slice(r+1).trim():n},$w=(t,e)=>`${t}::${e}`,$c=t=>{const e=String(t||"").trim();if(!e)return"";const n=e.indexOf("/");return n<=0?"":e.slice(0,n).trim()},jl=(t,e)=>{if(t.length===0)return null;const n=String(e.selectedRemoteName||"").trim();if(n){const a=t.find(c=>c.name===n);if(a)return a}const r=$c(e.trackingBranch);if(r){const a=r==="origin"?t.find(l=>l.name==="upstream"):null;if(a)return a;const c=t.find(l=>l.name===r);if(c)return c}const o=t.find(a=>a.name==="origin");return o||(t[0]??null)},zw=t=>t.startsWith("pr-"),Ww=(t,e)=>{const n=$c(e),r=new Map(t.map(c=>[c.name,c])),o=[],a=c=>{c&&(o.some(l=>l.name===c.name)||o.push(c))};return n&&a(r.get(n)),a(r.get("upstream")),a(r.get("origin")),t.filter(c=>!zw(c.name)).forEach(c=>a(c)),t.forEach(c=>a(c)),o},Sl=new Map,Nl=qr;function Uw(t,e){const[n,r]=i.useState(null),[o,a]=i.useState([]),c=i.useRef(null);return i.useEffect(()=>{r(null),a([])},[t]),i.useEffect(()=>{if(!t||!e?.repoUpstream||c.current===t)return;c.current=t;let l=!1;return(async()=>{try{const d=await e.repoUpstream(t);if(l||!d?.isFork||!d.upstream||(r(d.upstream),!e.repoBranches))return;try{const f=await e.repoBranches(d.upstream.owner,d.upstream.repo);l||a(f)}catch{}}catch{}})(),()=>{l=!0}},[t,e]),{detectedUpstream:n,upstreamBranches:o}}const Hw=({directory:t,branch:e,baseBranch:n,trackingBranch:r,remotes:o=[],remoteBranches:a=[],onGeneratedDescription:c})=>{const{t:l}=Nt(),d=Ee(ye=>ye.timeFormatPreference),{github:f}=Xn(),m=Mi(ye=>ye.status),u=Mi(ye=>ye.hasChecked),p=Ee(ye=>ye.setSettingsDialogOpen),y=Ee(ye=>ye.setSettingsPage),g=Ee(ye=>ye.setActiveMainTab),b=ut(ye=>ye.currentSessionId),{isMobile:x,hasTouchInput:h}=Or(),C=i.useCallback(()=>{y("github"),p(!0)},[p,y]),w=i.useMemo(()=>$w(t,e),[t,e]),v=i.useMemo(()=>Sl.get(w)??null,[w]),S=sr(ye=>ye.ensureEntry),k=sr(ye=>ye.setParams),j=sr(ye=>ye.startWatching),A=sr(ye=>ye.stopWatching),D=sr(ye=>ye.refresh),N=sr(ye=>ye.updateStatus),[B,T]=i.useState(()=>v?.title??Au(e)),[E,_]=i.useState(()=>v?.body??""),[R,z]=i.useState(()=>v?.draft??!1),[V,$]=i.useState(()=>v?.additionalContext??""),[M,te]=i.useState(()=>{const ye=typeof v?.targetBaseBranch=="string"?ai(v.targetBaseBranch):"";return ye||ai(n)}),[re,Q]=i.useState("squash"),[H,X]=i.useState(!1),[oe,fe]=i.useState(!1),[ve,ie]=i.useState(!1),[Ne,K]=i.useState(!1),[pe,L]=i.useState(!1),[se,Z]=i.useState(!1),[je,De]=i.useState(null),[Le,Me]=i.useState(""),[Fe,he]=i.useState(""),[Ie,me]=i.useState(!1),[ce,xe]=i.useState(!1),[ke,de]=i.useState(()=>jl(o,{selectedRemoteName:v?.selectedRemoteName,trackingBranch:r})),[P,F]=i.useState(!1),{detectedUpstream:ue,upstreamBranches:be}=Uw(t,f);i.useEffect(()=>{F(!1)},[t]);const W=o.some(ye=>ye.name==="upstream"),we=!!(t&&e&&n&&(e!==n||(W||ue!==null))),G=i.useMemo(()=>Co(t,e),[t,e]),Se=sr(ye=>ye.entries[G]),Oe=Se?.isLoading??!1,Ae=Se?.status??null,J=Se?.error??null,O=Se?.isInitialStatusResolved??!1,ae=i.useMemo(()=>{const ye=P?null:ke?.name?.trim()||null,Ze=new Set;for(const Ht of a){const mt=Vw(Ht,ye);!mt||mt==="HEAD"||Ze.add(mt)}if(P)for(const Ht of be)Ht&&Ht!=="HEAD"&&Ze.add(Ht);const ct=ai(n);ct&&ct!=="HEAD"&&Ze.add(ct);const It=ai(M);return It&&It!=="HEAD"&&Ze.add(It),Array.from(Ze).sort((Ht,mt)=>Ht.localeCompare(mt))},[n,a,ke?.name,M,be,P]);i.useEffect(()=>{if(o.length===0){ke&&de(null);return}(!ke||!o.some(ye=>ye.name===ke.name))&&de(jl(o,{selectedRemoteName:v?.selectedRemoteName,trackingBranch:r}))},[v?.selectedRemoteName,o,ke,r]),i.useEffect(()=>{const ye=ai(n);if(!M&&ye){te(ye);return}if(ae.length!==0&&!ae.includes(M)){const Ze=ae.includes(ye)?ye:ae[0];Ze&&te(Ze)}},[ae,n,M]);const[ne,Be]=i.useState(!1),[Ye,He]=i.useState(null),[Je,nt]=i.useState(!1),[xt,bt]=i.useState(new Set),[_e,Qe]=i.useState(!1),[st,pt]=i.useState(null),[At,vt]=i.useState(!1),kt=i.useRef(new Set),et=i.useRef(null),_t=i.useRef(!1),ns=i.useRef(new Set),Kt=i.useRef([]);i.useEffect(()=>{ue&&!W&&F(!0)},[ue,W]),i.useEffect(()=>{P&&ue?.defaultBranch&&te(ue.defaultBranch)},[P,ue?.defaultBranch]);const qe=Ae?.pr??null,gt=qe?`${t}#${qe.number}`:null,Xe=!!(gt&&je===gt);i.useEffect(()=>{if(!f?.prContext||!qe||typeof qe.body=="string"&&qe.body.length>0)return;const ye=`${t}#${qe.number}`;if(kt.current.has(ye))return;kt.current.add(ye),De(ye);let Ze=!1;return f.prContext(t,qe.number,{includeDiff:!1,includeCheckDetails:!1}).then(ct=>{if(Ze)return;const It=ct?.pr;It&&N(G,Ht=>!Ht?.pr||Ht.pr.number!==qe.number?Ht:{...Ht,pr:{...Ht.pr,body:It.body||""}})}).catch(()=>{}).finally(()=>{Ze||De(ct=>ct===ye?null:ct)}),()=>{Ze=!0}},[t,f,qe,G,N]),i.useEffect(()=>{if(!qe){Z(!1),Me(""),he(""),et.current=null;return}const ye=et.current!==null&&et.current!==qe.number;ye&&Z(!1),(!se||ye)&&(Me(qe.title||""),he(qe.body||"")),et.current=qe.number},[se,qe]);const jt=i.useCallback(async()=>{if(!f?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(qe){Be(!0),bt(new Set),nt(!0);try{const ye=await f.prContext(t,qe.number,{includeDiff:!1,includeCheckDetails:!0});He(ye)}catch(ye){const Ze=ye instanceof Error?ye.message:String(ye);le.error(l("gitView.pr.toast.loadCheckDetailsFailed"),{description:Ze})}finally{nt(!1)}}},[t,f,qe,l]),Pt=i.useCallback(async()=>{if(!f?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(qe){Qe(!0),vt(!0);try{const ye=await f.prContext(t,qe.number,{includeDiff:!1,includeCheckDetails:!1});pt(ye)}catch(ye){const Ze=ye instanceof Error?ye.message:String(ye);le.error(l("gitView.pr.toast.loadCommentsFailed"),{description:Ze})}finally{vt(!1)}}},[t,f,qe,l]),is=i.useCallback(ye=>{if(!ye)return"";const Ze=Date.parse(ye);return Number.isFinite(Ze)?kc(Ze,d,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}):ye},[d]),Bt=i.useMemo(()=>{const ye=m?.user?.login;return typeof ye=="string"?ye.trim():""},[m]),Gt=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)]",[]),es=i.useCallback(ye=>{const Ze=Bt.toLowerCase(),ct=/(^|[^\w`])@([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,38}))/g;return ye.replace(ct,(It,Ht,mt)=>{const ms=`@${mt}`,hs=mt.toLowerCase();return`${Ht}[${ms}](https://github.com/${hs}${Ze&&hs===Ze?"?oc-self-mention=1":""})`})},[Bt]),Wt=i.useMemo(()=>{const ye=(st?.issueComments??[]).map(It=>({id:`issue-${It.id}`,body:It.body||"",authorName:It.author?.name||It.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:It.author?.login||null,avatarUrl:It.author?.avatarUrl||null,createdAt:It.createdAt,context:l("gitView.pr.comments.generalContext"),path:null,line:null})),Ze=(st?.reviewComments??[]).map(It=>({id:`review-${It.id}`,body:It.body||"",authorName:It.author?.name||It.author?.login||l("gitView.pr.comments.unknownAuthor"),authorLogin:It.author?.login||null,avatarUrl:It.author?.avatarUrl||null,createdAt:It.createdAt,context:l("gitView.pr.comments.reviewContext"),path:It.path||null,line:It.line??null})),ct=[...ye,...Ze];return ct.sort((It,Ht)=>{const mt=It.createdAt?Date.parse(It.createdAt):0,ms=Ht.createdAt?Date.parse(Ht.createdAt):0,hs=Number.isFinite(mt)?mt:0,Ns=Number.isFinite(ms)?ms:0;return hs-Ns}),ct},[st,l]),Lt=i.useCallback(()=>{if(!b)return le.error(l("gitView.pr.toast.noActiveSession"),{description:l("gitView.pr.toast.noActiveSessionDescription")}),null;const{currentProviderId:ye,currentModelId:Ze,currentAgentName:ct,currentVariant:It}=ss.getState(),Ht=Nc.getState().lastUsedProvider,mt=ye||Ht?.providerID,ms=Ze||Ht?.modelID;return!mt||!ms?(le.error(l("gitView.pr.toast.noModelSelected")),null):{sessionId:b,providerID:mt,modelID:ms,currentAgentName:ct??null,currentVariant:It??null}},[b,l]),Ut=i.useCallback((ye,Ze,ct,It)=>{ut.getState().sendMessage(Ze,ye.providerID,ye.modelID,ye.currentAgentName??void 0,void 0,void 0,[{text:ct,synthetic:!0},{text:It,synthetic:!0}],ye.currentVariant??void 0).catch(Ht=>{const mt=Ht instanceof Error?Ht.message:String(Ht);le.error(l("gitView.pr.toast.sendMessageFailed"),{description:mt})})},[l]),rs=i.useCallback(ye=>{const Ze=ye.status||"unknown",ct=ye.conclusion??void 0,It=ct?`${Ze} / ${ct}`:Ze,Ht=ye.app?.name||ye.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:ye.name}),s.jsx("div",{className:"typography-micro text-muted-foreground truncate",children:Ht?`${Ht} · ${It}`:It})]}),ye.detailsUrl?s.jsx(Ve,{variant:"outline",size:"sm",asChild:!0,className:"flex-shrink-0",children:s.jsxs("a",{href:ye.detailsUrl,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),"Open"]})}):null]}),ye.output?.title?s.jsx("div",{className:"typography-micro text-foreground",children:ye.output.title}):null,ye.output?.summary?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap",children:ye.output.summary}):null,ye.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:ye.output.text}):null,Array.isArray(ye.annotations)&&ye.annotations.length>0?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Failed annotations",ye.annotations.length>20?` (showing 20/${ye.annotations.length})`:""]}),s.jsx("div",{className:"space-y-1",children:ye.annotations.slice(0,20).map((mt,ms)=>s.jsxs("div",{className:"rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)]/40 px-2 py-2",children:[s.jsxs("div",{className:"typography-micro text-[var(--status-error)]",children:[mt.title||mt.level||"Issue",mt.path?` · ${mt.path}`:"",typeof mt.startLine=="number"?`:${mt.startLine}`:"",typeof mt.endLine=="number"&&mt.endLine!==mt.startLine?`-${mt.endLine}`:""]}),s.jsx("div",{className:"typography-micro text-foreground whitespace-pre-wrap mt-1",children:mt.message}),mt.rawDetails?s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap mt-1",children:mt.rawDetails}):null]},`${mt.path||"file"}:${mt.startLine||ms}:${ms}`))})]}):null,ye.job?.steps&&ye.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:ye.job.steps.map((mt,ms)=>{const hs=(mt.conclusion||"").toLowerCase(),Ns=hs&&!["success","neutral","skipped"].includes(hs),ys=`${ye.id??"run"}:${ye.job?.jobId??"job"}:${mt.number??ms}:${mt.name}`,Is=xt.has(ys);return Ns?s.jsxs(no,{open:Is,children:[s.jsxs("button",{type:"button",onClick:()=>{bt(Mn=>{const $s=new Set(Mn);return $s.has(ys)?$s.delete(ys):$s.add(ys),$s})},className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-left "+(Ns?"bg-destructive/10 text-destructive":"text-muted-foreground"),children:[Is?s.jsx(I,{name:"arrow-down-s",className:"size-4"}):s.jsx(I,{name:"arrow-right-s",className:"size-4"}),s.jsx("span",{className:"truncate",children:mt.name}),mt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:mt.conclusion}):null]}),s.jsx(ro,{children:s.jsxs("div",{className:"ml-6 mt-1 rounded border border-border/40 bg-transparent px-2 py-2 typography-micro text-muted-foreground space-y-1",children:[typeof mt.number=="number"?s.jsxs("div",{children:[l("gitView.pr.checks.stepLabel"),": ",mt.number]}):null,mt.status?s.jsxs("div",{children:[l("gitView.pr.checks.statusLabel"),": ",mt.status]}):null,mt.conclusion?s.jsxs("div",{children:[l("gitView.pr.checks.conclusionLabel"),": ",mt.conclusion]}):null,mt.startedAt?s.jsxs("div",{children:[l("gitView.pr.checks.startedLabel"),": ",is(mt.startedAt)]}):null,mt.completedAt?s.jsxs("div",{children:[l("gitView.pr.checks.completedLabel"),": ",is(mt.completedAt)]}):null]})})]},ys):s.jsxs("div",{className:"typography-micro flex w-full items-center gap-2 rounded px-2 py-1 text-muted-foreground",children:[s.jsx("span",{className:"truncate",children:mt.name}),mt.conclusion?s.jsx("span",{className:"ml-auto flex-shrink-0",children:mt.conclusion}):null]},ys)})})]}):null]})},[xt,is,l]),$t=i.useCallback(async()=>{if(g("chat"),!f?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!qe)return;const ye=Lt();if(ye)try{const Ze=await f.prContext(t,qe.number,{includeDiff:!1,includeCheckDetails:!0}),It=(Ze.checkRuns??[]).filter(Ns=>{const ys=typeof Ns.conclusion=="string"?Ns.conclusion.toLowerCase():"";return ys?!["success","neutral","skipped"].includes(ys):!1});if(It.length===0){le.message(l("gitView.pr.toast.noFailedChecks"));return}const Ht=await En("github.pr.checks.review.visible"),mt=await En("github.pr.checks.review.instructions"),ms=It.flatMap(Ns=>(Array.isArray(Ns.annotations)?Ns.annotations:[]).map(Is=>({run:Ns.name,level:Is.level,title:Is.title,path:Is.path,startLine:Is.startLine,endLine:Is.endLine,message:Is.message,rawDetails:Is.rawDetails}))),hs=`GitHub PR failed checks (JSON)
|
|
7
|
-
${JSON.stringify({repo:Ze.repo??null,pr:Ze.pr??null,failedChecks:It,failedAnnotations:ms},null,2)}`;Ut(ye,Ht,mt,hs)}catch(Ze){const ct=Ze instanceof Error?Ze.message:String(Ze);le.error(l("gitView.pr.toast.loadChecksFailed"),{description:ct})}},[t,Ut,f,qe,Lt,g,l]),ls=i.useCallback(async()=>{if(g("chat"),!f?.prContext){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}if(!t||!qe)return;const ye=Lt();if(ye)try{const Ze=await f.prContext(t,qe.number,{includeDiff:!1,includeCheckDetails:!1}),ct=Ze.issueComments??[],It=Ze.reviewComments??[];if(ct.length+It.length===0){le.message(l("gitView.pr.toast.noPrComments"));return}const mt=await En("github.pr.comments.review.visible"),ms=await En("github.pr.comments.review.instructions"),hs=`GitHub PR comments (JSON)
|
|
8
|
-
${JSON.stringify({repo:Ze.repo??null,pr:Ze.pr??null,issueComments:ct,reviewComments:It},null,2)}`;Ut(ye,mt,ms,hs)}catch(Ze){const ct=Ze instanceof Error?Ze.message:String(Ze);le.error(l("gitView.pr.toast.loadPrCommentsFailed"),{description:ct})}},[t,Ut,f,qe,Lt,g,l]),xs=i.useCallback(async ye=>{Qe(!1),g("chat");const Ze=Lt();if(!Ze)return;const ct=await En("github.pr.comment.single.visible"),It=await En("github.pr.comment.single.instructions"),Ht=`GitHub PR comment (JSON)
|
|
9
|
-
${JSON.stringify({repo:st?.repo??null,pr:st?.pr??qe??null,comment:ye},null,2)}`;Ut(Ze,ct,It,Ht)},[st,Ut,qe,Lt,g]),Ct=i.useCallback(async ye=>{await D(G,ye)},[G,D]),Vt=i.useCallback(()=>{Kt.current.forEach(ye=>{window.clearTimeout(ye)}),Kt.current=_w.map(ye=>window.setTimeout(()=>{Ct({force:!0,silent:!0,markInitialResolved:!0})},ye))},[Ct]);i.useEffect(()=>{if(!f?.prStatus||!we||o.length<=1||_t.current||Ae?.pr)return;const ye=`${w}::${ke?.name??""}`;if(ns.current.has(ye))return;ns.current.add(ye);const Ze=Ww(o,r).filter(Ht=>Ht.name!==ke?.name);if(Ze.length===0)return;let ct=!1;return(async()=>{for(const Ht of Ze){if(ct)return;try{if(!(await f.prStatus(t,e,Ht.name))?.pr)continue;if(ct)return;de(ms=>ms?.name===Ht.name?ms:Ht);return}catch{}}})(),()=>{ct=!0}},[e,we,t,f,o,ke?.name,w,Ae?.pr,r]),i.useEffect(()=>{S(G),k(G,{directory:t,branch:e,remoteName:ke?.name??null,canShow:we,github:f,githubAuthChecked:u,githubConnected:m?.connected??null})},[e,we,t,S,f,u,m?.connected,G,ke?.name,k]),i.useEffect(()=>(j(G),()=>{A(G)}),[G,j,A]),i.useEffect(()=>{const ye=Sl.get(w)??null;T(ye?.title??Au(e)),_(ye?.body??""),z(ye?.draft??!1),te(ye?.targetBaseBranch?ai(ye.targetBaseBranch):ai(n));const Ze=jl(o,{selectedRemoteName:ye?.selectedRemoteName,trackingBranch:r});de(ct=>ct?.name===Ze?.name?ct:Ze)},[n,e,o,w,r]),i.useEffect(()=>{Ct({markInitialResolved:!0})},[G,Ct]),i.useEffect(()=>{!we||!ke?.name||Ct({force:!0,silent:!0,markInitialResolved:!0})},[we,Ct,ke?.name]),i.useEffect(()=>{const ye=Ae?.resolvedRemoteName?.trim();if(!ye||_t.current)return;const Ze=o.find(ct=>ct.name===ye);Ze&&de(ct=>ct?.name===Ze.name?ct:Ze)},[o,Ae?.resolvedRemoteName]),i.useEffect(()=>{const ye=Ae?.pr?.state==="closed"||Ae?.pr?.state==="merged",Ze=Se?.lastRefreshAt??0,ct=Date.now()-Ze>6e4,It=!ye&&ct,Ht=()=>{It&&Ct({force:!0,silent:!0})},mt=()=>{document.visibilityState==="visible"&&It&&Ct({force:!0,silent:!0})};return window.addEventListener("focus",Ht),document.addEventListener("visibilitychange",mt),()=>{window.removeEventListener("focus",Ht),document.removeEventListener("visibilitychange",mt)}},[Ct,Ae?.pr?.state,Se?.lastRefreshAt]),i.useEffect(()=>{u&&m?.connected===!1&&Ct({force:!0,silent:!0,markInitialResolved:!0})},[u,m,Ct]),i.useEffect(()=>{!t||!e||Sl.set(w,{title:B,body:E,draft:R,additionalContext:V,targetBaseBranch:M,selectedRemoteName:ke?.name})},[w,B,E,R,V,M,ke?.name,t,e]),i.useEffect(()=>{const ye=Kt.current;return()=>{ye.forEach(Ze=>{window.clearTimeout(Ze)}),Kt.current=[]}},[]);const yt=i.useCallback(async()=>{if(!H&&t){X(!0);try{const Ze={base:P&&ue?.defaultBranchSha?ue.defaultBranchSha:M,head:e};V&&(Ze.context=V);const ct=await og(t,Ze);ct.title?.trim()&&T(ct.title.trim()),ct.body?.trim()&&_(ct.body.trim()),c?.()}catch(ye){const Ze=ye instanceof Error?ye.message:String(ye);le.error(l("gitView.pr.toast.generateDescriptionFailed"),{description:Ze})}finally{X(!1)}}},[V,e,ue?.defaultBranchSha,t,H,c,M,l,P]),us=i.useCallback(async()=>{if(!f?.prCreate){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}const ye=B.trim();if(!ye){le.error(l("gitView.pr.toast.titleRequired"));return}const Ze=M.trim();if(!Ze){le.error(l("gitView.pr.toast.baseBranchRequired"));return}if(!P&&Ze===e){le.error(l("gitView.pr.toast.baseMustDifferFromHead"));return}fe(!0);try{const ct=$c(r),It=P&&ue,Ht=await f.prCreate({directory:t,title:ye,head:e,base:Ze,...E.trim()?{body:E}:{},draft:R,...It?{targetRepo:{owner:ue.owner,repo:ue.repo},headRemote:"origin"}:{...ke?{remote:ke.name}:{},...ct&&ct!==ke?.name?{headRemote:ct}:{}}});le.success(l("gitView.pr.toast.prCreated")),N(G,mt=>mt&&{...mt,pr:Ht}),await Ct({force:!0}),Vt()}catch(ct){const It=ct instanceof Error?ct.message:String(ct);le.error(l("gitView.pr.toast.createPrFailed"),{description:It})}finally{fe(!1)}},[E,e,ue,t,R,f,G,Ct,Vt,ke,M,B,r,N,P,l]),cs=i.useCallback(async ye=>{if(!f?.prMerge){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}K(!0);try{const Ze=await f.prMerge({directory:t,number:ye.number,method:re});Ze.merged?le.success(l("gitView.pr.toast.prMerged")):le.message(l("gitView.pr.toast.prNotMerged"),{description:Ze.message||l("gitView.pr.notMergeable")}),await Ct({force:!0}),Vt()}catch(Ze){const ct=Ze instanceof Error?Ze.message:String(Ze);le.error(l("gitView.pr.toast.mergeFailed"),{description:ct}),ye.url&&Nl(ye.url)}finally{K(!1)}},[t,f,re,Ct,Vt,l]),Ue=i.useCallback(async ye=>{if(!f?.prReady){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}L(!0);try{await f.prReady({directory:t,number:ye.number}),le.success(l("gitView.pr.toast.markedReady")),await Ct({force:!0}),Vt()}catch(Ze){const ct=Ze instanceof Error?Ze.message:String(Ze);le.error(l("gitView.pr.toast.markReadyFailed"),{description:ct}),ye.url&&Nl(ye.url)}finally{L(!1)}},[t,f,Ct,Vt,l]),Ge=i.useCallback(async ye=>{if(!f?.prUpdate){le.error(l("gitView.pr.toast.githubApiUnavailable"));return}const Ze=Le.trim();if(!Ze){le.error(l("gitView.pr.toast.titleRequired"));return}ie(!0);try{const ct=await f.prUpdate({directory:t,number:ye.number,title:Ze,body:Fe});N(G,It=>It&&{...It,pr:{...It.pr??ye,...ct}}),Z(!1),le.success(l("gitView.pr.toast.prUpdated")),await Ct({force:!0}),Vt()}catch(ct){const It=ct instanceof Error?ct.message:String(ct);le.error(l("gitView.pr.toast.updatePrFailed"),{description:It})}finally{ie(!1)}},[t,Fe,Le,f,G,Ct,Vt,N,l]);if(!we)return s.jsx("section",{className:"border-0 bg-transparent rounded-none",children:s.jsxs("div",{className:"space-y-1 pt-3",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:l("gitView.pullRequest.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pullRequest.availableOnFeatureBranches")})]})});const wt=Ae?.repo?.url||null,Ot=P&&ue?.url?ue.url:wt,Dt=Ae?.checks??null,bs=!!Ae?.canMerge,fs=!!Ae?.connected,os=u&&Ae?.connected===!1,qt=Bw(Ae),ln=qt?`var(--pr-${qt})`:"var(--status-info)",ps=qt==="draft"?"git-pr-draft":qt==="merged"?"git-merge":qt==="closed"?"git-close-pull-request":"git-pull-request",Fs=qe?[`${qe.state}${qe.draft?" (draft)":""}`,qe.mergeable===!1?l("gitView.pr.notMergeable"):null,qe.state==="open"&&typeof qe.mergeableState=="string"&&qe.mergeableState&&qe.mergeableState!=="unknown"?qe.mergeableState:null].filter(Boolean).join(" · "):"",Ws=Dt?Dt.total>0?`${Dt.success}/${Dt.total} ${l("gitView.pr.checks.label")}`:`${Dt.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:[qe?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:()=>{Nl(qe.url)},"aria-label":l("gitView.pr.actions.openOnGitHubAria"),children:s.jsx(I,{name:ps,className:"size-4 shrink-0",style:{color:ln}})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openOnGitHub")})})]}):s.jsx(I,{name:ps,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")}),qe?s.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",qe.number]}):null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Oe?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex size-5 items-center justify-center rounded hover:bg-interactive-hover/60 disabled:opacity-40",disabled:Oe,onClick:()=>{Ct({force:!0})},"aria-label":l("gitView.pr.actions.refreshAria"),children:s.jsx(I,{name:"refresh",className:"size-3.5 text-muted-foreground"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.refresh")})})]})]})]}),qe?s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 typography-micro text-muted-foreground",children:[s.jsx("span",{style:{color:ln},children:Fs}),Dt?s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${Lw(Dt.state)}`}),Ws]}):null,r&&ke&&r.split("/")[0]!==ke.name?s.jsxs("span",{className:"min-w-0 truncate",children:[r.split("/")[0]," → ",ke.name]}):null]}):null]}),s.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[os?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.githubNotConnected")}),s.jsx(Ve,{variant:"outline",size:"sm",onClick:C,className:"w-fit",children:l("gitView.pr.actions.openSettings")})]}):null,J?s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:l("gitView.pr.statusUnavailable")}),s.jsx("div",{className:"typography-meta text-muted-foreground break-words",children:J}),Ot?s.jsx(Ve,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:s.jsxs("a",{href:Ot,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),"Open Repo"]})}):null]}):null,!qe&&!O&&!J&&!os?s.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),l("gitView.pr.checkingStatus")]}):qe?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:Le,onChange:ye=>Me(ye.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h}),s.jsx(Ii,{value:Fe,onChange:ye=>he(ye.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:qe.title}),qe.body?.trim()?s.jsx(so,{content:qe.body,className:"typography-markdown-body text-muted-foreground break-words mt-1",enableFileReferences:!1}):s.jsx("div",{className:"typography-micro text-muted-foreground whitespace-pre-wrap break-words mt-1",children:l(Xe?"gitView.pr.loadingDescription":"gitView.pr.noDescription")})]}),bs&&qe.draft?s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.draftMustBeReady")}):null,bs?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:[qe.state==="open"?se?s.jsxs(s.Fragment,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>{Z(!1),Me(qe.title||""),he(qe.body||"")},disabled:ve,"aria-label":l("gitView.pr.actions.cancelEditingAria"),children:s.jsx(I,{name:"close",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.cancelEditing")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>Ge(qe),disabled:ve||!Le.trim(),"aria-label":l("gitView.pr.actions.savePrAria"),children:ve?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"check",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.savePr")})})]})]}):s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>Z(!0),"aria-label":l("gitView.pr.actions.editPrAria"),children:s.jsx(I,{name:"edit",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.editPr")})})]}):null,Dt?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{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(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"information",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openChecks")})})]}):null,Dt?.failure?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"outline",size:"sm",className:"h-7 w-7 px-0 border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",onClick:$t,"aria-label":l("gitView.pr.actions.resolveFailedChecksAria"),children:s.jsx(I,{name:"error-warning",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.resolveFailedChecks")})})]}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:Pt,"aria-label":l("gitView.pr.actions.openCommentsAria"),children:s.jsx(I,{name:"chat-4",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.openComments")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{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:ls,"aria-label":l("gitView.pr.actions.shareCommentsAria"),children:s.jsx(I,{name:"ai-generate-2",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.shareComments")})})]}),bs&&qe.draft&&qe.state==="open"?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"outline",size:"sm",className:"h-7 w-7 px-0",onClick:()=>Ue(qe),disabled:pe||Ne||ve||se,"aria-label":l("gitView.pr.actions.markReadyAria"),children:pe?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"checkbox-circle",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.markReady")})})]}):null]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:bs?s.jsxs(s.Fragment,{children:[s.jsxs(Un,{value:re,onValueChange:ye=>Q(ye),disabled:Ne||qe.state!=="open",children:[s.jsx(Hn,{size:"lg",className:"h-7 w-auto min-w-0",children:s.jsx(An,{})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"squash",children:l("gitView.pr.mergeMethod.squash")}),s.jsx(Rs,{value:"merge",children:l("gitView.pr.mergeMethod.merge")}),s.jsx(Rs,{value:"rebase",children:l("gitView.pr.mergeMethod.rebase")})]})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{size:"sm",className:"h-7 w-7 px-0",onClick:()=>cs(qe),disabled:Ne||pe||qe.state!=="open"||qe.draft||ve||se,"aria-label":l("gitView.pr.actions.mergePrAria"),children:Ne?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-merge",className:"size-4"})})}),s.jsx(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)"})," → ",M," ",s.jsxs("span",{className:"opacity-60",children:["(",P&&ue?"upstream":"remote",")"]})]})]}),Ot?s.jsx(Ve,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:Ot,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(I,{name:"external-link",className:"size-4"}),l("gitView.pr.actions.repo")]})}):null]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.title")}),s.jsx(vn,{value:B,onChange:ye=>T(ye.target.value),placeholder:l("gitView.pr.placeholder.title"),autoCorrect:h?"on":"off",autoCapitalize:h?"sentences":"off",spellCheck:h})]}),s.jsxs("label",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.field.baseBranch")}),ae.length>0?s.jsxs(Un,{value:M,onValueChange:te,children:[s.jsx(Hn,{className:"h-9",children:s.jsx(An,{placeholder:l("gitView.pr.placeholder.selectBaseBranch")})}),s.jsx(Gn,{children:ae.map(ye=>s.jsx(Rs,{value:ye,children:ye},ye))})]}):s.jsx(vn,{value:M,onChange:ye=>te(ye.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(Ii,{value:E,onChange:ye=>_(ye.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:()=>z(ye=>!ye),onKeyDown:ye=>{(ye.key===" "||ye.key==="Enter")&&(ye.preventDefault(),z(Ze=>!Ze))},children:[s.jsx(Fi,{size:"sm",checked:R,onChange:ye=>z(ye),ariaLabel:l("gitView.pr.actions.toggleDraftAria")}),s.jsx("span",{className:"typography-ui-label text-foreground select-none",children:l("gitView.pr.field.draft")})]}),x?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.optional")}),s.jsx(Ve,{variant:"outline",size:"sm",onClick:()=>xe(!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(no,{open:Ie,onOpenChange:me,children:[s.jsxs(_o,{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:Ie?l("gitView.pr.actions.hide"):V.trim()?l("gitView.pr.actions.edit"):l("gitView.pr.actions.add")})]}),s.jsx(ro,{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(Ii,{value:V,onChange:ye=>$(ye.target.value),className:"min-h-[100px] bg-transparent",placeholder:l("gitView.pr.placeholder.additionalContext")}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l("gitView.pr.additionalContext.hint")})]})})]}),s.jsx(Ha,{open:ce,onClose:()=>xe(!1),title:l("gitView.pr.additionalContext.title"),footer:s.jsx(Ve,{size:"sm",onClick:()=>xe(!1),className:"w-full",children:l("gitView.common.done")}),children:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ii,{value:V,onChange:ye=>$(ye.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(Ve,{variant:"outline",size:"sm",onClick:yt,disabled:H||oe,children:[H?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"ai-generate-2",className:"size-4 text-primary"}),l("gitView.commit.generate")]}),s.jsx("div",{className:"flex-1"}),s.jsxs(Ve,{size:"sm",className:"min-w-[7.5rem] justify-center gap-2",onClick:us,disabled:oe||!fs||!M.trim()||!P&&M.trim()===e,children:[s.jsx("span",{className:"inline-flex size-4 items-center justify-center",children:oe?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-pull-request",className:"size-4"})}),s.jsx("span",{children:l("gitView.pr.actions.createPr")})]})]})]})]}),s.jsx(Ms,{open:ne,onOpenChange:Be,children:s.jsxs(Es,{className:"max-w-2xl max-h-[70vh] flex flex-col min-h-0",children:[s.jsxs(Gs,{children:[s.jsxs(Vs,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.checkDetails.title")]}),s.jsx(an,{children:qe?l("gitView.pr.numberLabel",{number:qe.number}):l("gitView.pullRequest.title")})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto mt-2",children:[Je?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,Je?null:s.jsx("div",{className:"space-y-3",children:Array.isArray(Ye?.checkRuns)&&Ye?.checkRuns.length>0?Ye.checkRuns.map((ye,Ze)=>{const ct=`${ye.id??"run"}:${ye.job?.jobId??"job"}:${ye.name}:${Ze}`;return s.jsx("div",{className:"p-1",children:rs(ye)},ct)}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.checkDetails.empty")})})]})]})}),s.jsx(Ms,{open:_e,onOpenChange:Qe,children:s.jsxs(Es,{className:"max-w-2xl max-h-[82vh] min-h-[38rem] flex flex-col gap-2",children:[s.jsx(Gs,{children:s.jsxs(Vs,{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-pull-request",className:"h-5 w-5"}),l("gitView.pr.comments.title"),qe?s.jsx("span",{className:"typography-meta text-muted-foreground",children:l("gitView.pr.numberLabel",{number:qe.number})}):null]})}),s.jsxs(Ga,{className:"mt-2 max-h-[66vh] overflow-y-auto overlay-scrollbar-target overlay-scrollbar-container",children:[At?s.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),l("gitView.loading.loading")]}):null,At?null:s.jsx("div",{className:"space-y-4",children:Wt.length>0?s.jsx("div",{className:"relative pl-3",children:s.jsx("div",{children:Wt.map((ye,Ze)=>{const ct=(ye.authorName||"?").charAt(0).toUpperCase(),It=Ze===Wt.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:ye.avatarUrl?s.jsx("img",{src:ye.avatarUrl,alt:ye.authorName,className:"h-full w-full object-cover"}):s.jsx("span",{children:ct})}),s.jsxs("div",{className:"rounded-lg bg-surface-elevated px-3 pt-0 pb-3 space-y-2",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1 typography-micro text-muted-foreground sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-1 sm:gap-y-1",children:[s.jsxs("span",{className:"text-foreground whitespace-nowrap",children:[ye.authorName,ye.authorLogin&&ye.authorLogin!==ye.authorName?` · @${ye.authorLogin}`:""]}),ye.createdAt?s.jsx("span",{className:"whitespace-nowrap",children:is(ye.createdAt)}):null,s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs(Ve,{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:()=>{xs(ye)},"aria-label":l("gitView.pr.actions.sendCommentToAgentAria"),children:[s.jsx(I,{name:"ai-generate-2",className:"size-3.5"}),l("gitView.pr.actions.sendToAgent")]})}),s.jsx(Ft,{children:s.jsx("p",{children:l("gitView.pr.actions.sendCommentToAgent")})})]})]}),s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[ye.context,ye.path?` · ${ye.path}`:"",ye.line?`:${ye.line}`:""]}),s.jsx(so,{content:es(ye.body),className:["typography-markdown-body text-foreground break-words [&_a]:no-underline [&_a:hover]:no-underline",Gt].filter(Boolean).join(" "),enableFileReferences:!1})]})]},ye.id)})})}):s.jsx("div",{className:"text-center text-muted-foreground py-8",children:l("gitView.pr.comments.empty")})})]})]})})]})},Gw=t=>{const e=ft.c(150),{open:n,onOpenChange:r,conflictFiles:o,directory:a,operation:c,onAbort:l,onClearState:d}=t;let f;e[0]!==o?(f=o===void 0?[]:o,e[0]=o,e[1]=f):f=e[1];const m=f,{t:u}=Nt(),p=ut(Kw),y=ut(qw),g=hi(Yw),b=hi(Qw),x=Ee(Jw),[h,C]=i.useState(!1),[w,v]=i.useState(null),[S,k]=i.useState(null);let j,A;e[2]!==a||e[3]!==n||e[4]!==u?(j=()=>{!n||!a||(C(!0),k(null),v(null),ag(a).then(P=>{v(P)}).catch(P=>{const F=P instanceof Error?P.message:u("gitView.conflict.loadFailed");k(F)}).finally(()=>{C(!1)}))},A=[n,a,u],e[2]=a,e[3]=n,e[4]=u,e[5]=j,e[6]=A):(j=e[5],A=e[6]),i.useEffect(j,A);let D;e[7]!==w||e[8]!==a||e[9]!==c?(D=async()=>{if(!w)return null;const P=c==="merge"?"merge":"rebase",F=w.headInfo||(c==="merge"?"MERGE_HEAD":"REBASE_HEAD"),ue=c==="merge"?"git commit --no-edit":"git rebase --continue",be=await En("git.conflict.resolve.visible",{operation_label:P,head_ref:F}),W=await En("git.conflict.resolve.instructions",{operation_label:P,directory:a,operation:c,head_info:w.headInfo||"N/A",continue_cmd:ue}),ge=`${P} conflict context (JSON)
|
|
10
|
-
${JSON.stringify({directory:a,operation:w.operation,headInfo:w.headInfo,statusPorcelain:w.statusPorcelain,unmergedFiles:w.unmergedFiles,diff:w.diff},null,2)}`;return{visibleText:be,instructionsText:W,payloadText:ge}},e[7]=w,e[8]=a,e[9]=c,e[10]=D):D=e[10];const N=D;let B;e[11]!==l||e[12]!==r?(B=()=>{l(),r(!1)},e[11]=l,e[12]=r,e[13]=B):B=e[13];const T=B;let E;e[14]!==d||e[15]!==r?(E=()=>{d?.(),r(!1)},e[14]=d,e[15]=r,e[16]=E):E=e[16];const _=E;let R;e[17]!==N||e[18]!==y||e[19]!==d||e[20]!==r||e[21]!==x||e[22]!==g||e[23]!==b||e[24]!==u?(R=async()=>{const P=await N();if(!P){le.error(u("gitView.conflict.noDetailsAvailable"));return}if(!y){le.error(u("gitView.conflict.noActiveSession"),{description:u("gitView.conflict.noActiveSessionDescription")});return}g(P.visibleText,"replace"),b([{text:P.instructionsText,synthetic:!0},{text:P.payloadText,synthetic:!0}]),x("chat"),d?.(),r(!1)},e[17]=N,e[18]=y,e[19]=d,e[20]=r,e[21]=x,e[22]=g,e[23]=b,e[24]=u,e[25]=R):R=e[25];const z=R;let V;e[26]!==N||e[27]!==a||e[28]!==d||e[29]!==r||e[30]!==p||e[31]!==x||e[32]!==u?(V=async()=>{const P=await N();if(!P){le.error(u("gitView.conflict.noDetailsAvailable"));return}p({directoryOverride:a,initialPrompt:P.visibleText,syntheticParts:[{text:P.instructionsText,synthetic:!0},{text:P.payloadText,synthetic:!0}]}),x("chat"),d?.(),r(!1)},e[26]=N,e[27]=a,e[28]=d,e[29]=r,e[30]=p,e[31]=x,e[32]=u,e[33]=V):V=e[33];const $=V;let M,te,re,Q,H,X,oe,fe,ve,ie,Ne,K,pe,L,se,Z,je,De,Le,Me,Fe,he;if(e[34]!==w||e[35]!==m||e[36]!==y||e[37]!==T||e[38]!==_||e[39]!==z||e[40]!==$||e[41]!==h||e[42]!==S||e[43]!==r||e[44]!==n||e[45]!==c||e[46]!==u){const P=u(c==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),F=w?.unmergedFiles||m;re=Ms,Fe=n,he=r,te=Es,Me="max-w-md w-[calc(100vw-2rem)]",L="flex flex-col gap-4 overflow-hidden";let ue;e[69]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(I,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[69]=ue):ue=e[69];const be=s.jsxs("div",{className:"flex items-center gap-2",children:[ue,s.jsx(Vs,{children:u("gitView.conflict.detectedTitle",{operation:P})})]});let W;e[70]!==c||e[71]!==u?(W=u("gitView.conflict.detectedDescription",{operation:c}),e[70]=c,e[71]=u,e[72]=W):W=e[72];let ge;e[73]!==W?(ge=s.jsx(an,{children:W}),e[73]=W,e[74]=ge):ge=e[74],e[75]!==be||e[76]!==ge?(se=s.jsxs(Gs,{children:[be,ge]}),e[75]=be,e[76]=ge,e[77]=se):se=e[77],e[78]!==h||e[79]!==u?(Z=h&&s.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:u("gitView.conflict.loading")})]}),e[78]=h,e[79]=u,e[80]=Z):Z=e[80],e[81]!==S||e[82]!==u?(je=S&&s.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:u("gitView.conflict.errorLoadingDetails",{message:S})}),e[81]=S,e[82]=u,e[83]=je):je=e[83],e[84]!==F||e[85]!==u?(De=F.length>0&&s.jsxs("div",{className:"space-y-2 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:u("gitView.conflict.conflictedFiles")}),s.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:F.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:F.map(Xw)})})]}),e[84]=F,e[85]=u,e[86]=De):De=e[86],e[87]!==w||e[88]!==u?(Le=w?.headInfo&&s.jsxs("div",{className:"space-y-1 overflow-hidden",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:u("gitView.conflict.headInfo")}),s.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:w.headInfo})]}),e[87]=w,e[88]=u,e[89]=Le):Le=e[89],Ne="flex flex-col gap-2 pt-2";let we;e[90]!==$?(we=()=>{$()},e[90]=$,e[91]=we):we=e[91];const G=h||!w;let Se;e[92]!==h?(Se=h?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"add",className:"size-4"}),e[92]=h,e[93]=Se):Se=e[93];let Oe;e[94]!==u?(Oe=u("gitView.conflict.resolveNewSession"),e[94]=u,e[95]=Oe):Oe=e[95],e[96]!==we||e[97]!==G||e[98]!==Se||e[99]!==Oe?(K=s.jsxs(Ve,{variant:"default",onClick:we,disabled:G,className:"w-full gap-2",children:[Se,Oe]}),e[96]=we,e[97]=G,e[98]=Se,e[99]=Oe,e[100]=K):K=e[100];let Ae;e[101]!==z?(Ae=()=>{z()},e[101]=z,e[102]=Ae):Ae=e[102];const J=h||!w||!y;let O;e[103]!==h?(O=h?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"chat-1",className:"size-4"}),e[103]=h,e[104]=O):O=e[104];let ae;e[105]!==u?(ae=u("gitView.conflict.resolveCurrentSession"),e[105]=u,e[106]=ae):ae=e[106],e[107]!==Ae||e[108]!==J||e[109]!==O||e[110]!==ae?(pe=s.jsxs(Ve,{variant:"outline",onClick:Ae,disabled:J,className:"w-full gap-2",children:[O,ae]}),e[107]=Ae,e[108]=J,e[109]=O,e[110]=ae,e[111]=pe):pe=e[111],ve="flex gap-2 pt-1";let ne;e[112]!==u?(ne=u("gitView.conflict.continueLater"),e[112]=u,e[113]=ne):ne=e[113],e[114]!==_||e[115]!==ne?(ie=s.jsx(Ve,{variant:"ghost",size:"sm",onClick:_,className:"flex-1",children:ne}),e[114]=_,e[115]=ne,e[116]=ie):ie=e[116],M=Ve,Q="destructive",H="sm",X=T,oe="flex-1",fe=u("gitView.conflict.abortOperation",{operation:P}),e[34]=w,e[35]=m,e[36]=y,e[37]=T,e[38]=_,e[39]=z,e[40]=$,e[41]=h,e[42]=S,e[43]=r,e[44]=n,e[45]=c,e[46]=u,e[47]=M,e[48]=te,e[49]=re,e[50]=Q,e[51]=H,e[52]=X,e[53]=oe,e[54]=fe,e[55]=ve,e[56]=ie,e[57]=Ne,e[58]=K,e[59]=pe,e[60]=L,e[61]=se,e[62]=Z,e[63]=je,e[64]=De,e[65]=Le,e[66]=Me,e[67]=Fe,e[68]=he}else M=e[47],te=e[48],re=e[49],Q=e[50],H=e[51],X=e[52],oe=e[53],fe=e[54],ve=e[55],ie=e[56],Ne=e[57],K=e[58],pe=e[59],L=e[60],se=e[61],Z=e[62],je=e[63],De=e[64],Le=e[65],Me=e[66],Fe=e[67],he=e[68];let Ie;e[117]!==M||e[118]!==Q||e[119]!==H||e[120]!==X||e[121]!==oe||e[122]!==fe?(Ie=s.jsx(M,{variant:Q,size:H,onClick:X,className:oe,children:fe}),e[117]=M,e[118]=Q,e[119]=H,e[120]=X,e[121]=oe,e[122]=fe,e[123]=Ie):Ie=e[123];let me;e[124]!==ve||e[125]!==ie||e[126]!==Ie?(me=s.jsxs("div",{className:ve,children:[ie,Ie]}),e[124]=ve,e[125]=ie,e[126]=Ie,e[127]=me):me=e[127];let ce;e[128]!==Ne||e[129]!==K||e[130]!==pe||e[131]!==me?(ce=s.jsxs("div",{className:Ne,children:[K,pe,me]}),e[128]=Ne,e[129]=K,e[130]=pe,e[131]=me,e[132]=ce):ce=e[132];let xe;e[133]!==L||e[134]!==se||e[135]!==Z||e[136]!==je||e[137]!==De||e[138]!==Le||e[139]!==ce?(xe=s.jsxs("div",{className:L,children:[se,Z,je,De,Le,ce]}),e[133]=L,e[134]=se,e[135]=Z,e[136]=je,e[137]=De,e[138]=Le,e[139]=ce,e[140]=xe):xe=e[140];let ke;e[141]!==te||e[142]!==Me||e[143]!==xe?(ke=s.jsx(te,{className:Me,children:xe}),e[141]=te,e[142]=Me,e[143]=xe,e[144]=ke):ke=e[144];let de;return e[145]!==re||e[146]!==Fe||e[147]!==he||e[148]!==ke?(de=s.jsx(re,{open:Fe,onOpenChange:he,children:ke}),e[145]=re,e[146]=Fe,e[147]=he,e[148]=ke,e[149]=de):de=e[149],de};function Kw(t){return t.openNewSessionDraft}function qw(t){return t.currentSessionId}function Yw(t){return t.setPendingInputText}function Qw(t){return t.setPendingSyntheticParts}function Jw(t){return t.setActiveMainTab}function Xw(t){return s.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:t,children:t},t)}const Zw=({open:t,onOpenChange:e,operation:n,targetBranch:r,onConfirm:o})=>{const{t:a}=Nt(),[c,l]=i.useState(!0),[d,f]=i.useState(!1),m=a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),u=async()=>{f(!0);try{await o(c),e(!1)}catch(y){const g=y instanceof Error?y.message:`Failed to ${n}`;le.error(g)}finally{f(!1)}},p=()=>{d||e(!1)};return s.jsx(Ms,{open:t,onOpenChange:d?void 0:e,children:s.jsxs(Es,{className:"max-w-md",children:[s.jsxs(Gs,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),s.jsx(Vs,{children:a("gitView.stash.title")})]}),s.jsx(an,{children:a("gitView.stash.description",{operation:n})})]}),s.jsxs("div",{className:"py-2",children:[s.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:a("gitView.stash.thisWill")}),s.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[s.jsx("li",{children:a("gitView.stash.stepStash")}),s.jsxs("li",{children:[a(n==="merge"?"gitView.operation.merge":"gitView.operation.rebase")," ",a(n==="merge"?"gitView.stash.mergeWith":"gitView.stash.rebaseOnto")," ",s.jsx("span",{className:"font-mono text-primary",children:r})]}),c&&s.jsx("li",{children:a("gitView.stash.stepRestore")})]})]}),s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx(Fi,{checked:c,onChange:l,disabled:d,ariaLabel:a("gitView.stash.restoreAria")}),s.jsx("span",{className:"typography-ui-label text-foreground cursor-pointer select-none",onClick:()=>!d&&l(!c),children:a("gitView.stash.restoreAfterOperation",{operation:n})})]}),s.jsxs(nr,{className:"gap-2",children:[s.jsx(Ve,{variant:"ghost",size:"sm",onClick:p,disabled:d,children:a("gitView.common.cancel")}),s.jsx(Ve,{variant:"default",size:"sm",onClick:u,disabled:d,className:"gap-1.5",children:d?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),a("gitView.common.processing")]}):a("gitView.stash.confirmButton",{operation:m})})]})]})})},ev=({mergeInProgress:t,rebaseInProgress:e,onContinue:n,onAbort:r,onResolveWithAI:o,hasUnresolvedConflicts:a=!1,isLoading:c=!1})=>{const{t:l}=Nt(),[d,f]=i.useState(null),m=t&&t.head,u=e&&(e.headName||e.onto),p=m?"merge":u?"rebase":null;if(!p)return null;const y=async()=>{f("continue");try{await n()}finally{f(null)}},g=async()=>{f("abort");try{await r()}finally{f(null)}},b=d!==null,x=l(p==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),h=p==="merge"?"git-merge":"git-branch";let C="";return t?C=t.message?l("gitView.operation.mergingMessage",{message:t.message}):l("gitView.operation.mergeInProgressWithHead",{head:t.head}):e&&(C=e.headName?l("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):l("gitView.operation.rebaseInProgress")),s.jsx("div",{className:"bg-[var(--status-warning-bg)] border border-[var(--status-warning)] rounded-lg p-3 mx-3 mt-3",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[s.jsx(I,{name:h,className:"size-4 text-[var(--status-warning)] shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:l("gitView.operation.inProgressTitle",{operation:x})}),C&&s.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:C})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&o&&s.jsxs(Ve,{variant:"outline",size:"sm",onClick:o,disabled:b||c,className:"gap-1.5",children:[s.jsx(I,{name:"sparkling",className:"size-4"}),l("gitView.operation.resolveWithAi")]}),d!=="continue"&&s.jsxs(Ve,{variant:"ghost",size:"sm",onClick:g,disabled:b||c,className:"gap-1.5",children:[d==="abort"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"close",className:"size-4"}),l("gitView.operation.abort")]}),!a&&s.jsxs(Ve,{variant:"default",size:"sm",onClick:y,disabled:b||c,className:"gap-1.5",children:[d==="continue"?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"check",className:"size-4"}),l("gitView.operation.continue")]})]}),a&&s.jsx("p",{className:"typography-micro text-[var(--status-warning)]",children:l("gitView.operation.resolveConflictsHint")})]})})},tv=t=>{const e=ft.c(104),{currentBranch:n,localBranches:r,remoteBranches:o,onMerge:a,onRebase:c,disabled:l,isOperating:d,operationLogs:f,onOperationComplete:m,mode:u,defaultTargetBranch:p}=t,y=l===void 0?!1:l,g=d===void 0?!1:d,b=f===void 0?[]:f,x=u===void 0?"dialog":u,{t:h}=Nt(),[C,w]=i.useState(!1),[v,S]=i.useState("merge"),[k,j]=i.useState(null),[A,D]=i.useState(!1),[N,B]=i.useState(""),T=i.useRef(null),E=i.useRef(null),_=y||g,R=n||h("gitView.branch.currentBranchFallback"),z=b.length>0&&b.every(sv),V=b.some(nv);let $;e[0]===Symbol.for("react.memo_cache_sentinel")?($=()=>{E.current&&(E.current.scrollTop=E.current.scrollHeight)},e[0]=$):$=e[0],i.useEffect($,[b]);let M;if(e[1]!==N||e[2]!==n||e[3]!==r||e[4]!==o){e:{const Ae=N.toLowerCase();let J;e[6]!==o?(J=new Set(o.map(rv).filter(Boolean)),e[6]=o,e[7]=J):J=e[7];const O=J;let ae;e[8]!==n||e[9]!==O?(ae=Be=>Be!==n&&!O.has(Be),e[8]=n,e[9]=O,e[10]=ae):ae=e[10];const ne=r.filter(ae);if(!Ae){M=ne;break e}M=ne.filter(Be=>Be.toLowerCase().includes(Ae))}e[1]=N,e[2]=n,e[3]=r,e[4]=o,e[5]=M}else M=e[5];const te=M;let re;if(e[11]!==N||e[12]!==o){e:{const Ae=N.toLowerCase();if(!Ae){re=o;break e}re=o.filter(J=>J.toLowerCase().includes(Ae))}e[11]=N,e[12]=o,e[13]=re}else re=e[13];const Q=re;let H;e[14]!==p||e[15]!==r||e[16]!==o?(H=()=>p&&(o.includes(p)||r.includes(p))?p:null,e[14]=p,e[15]=r,e[16]=o,e[17]=H):H=e[17];const X=H;let oe;e[18]!==X||e[19]!==w?(oe=()=>{w(!0),j(X()),S("merge"),B("")},e[18]=X,e[19]=w,e[20]=oe):oe=e[20];const fe=oe;let ve;e[21]===Symbol.for("react.memo_cache_sentinel")?(ve=Ae=>{j(Ae),D(!1),B("")},e[21]=ve):ve=e[21];const ie=ve;let Ne;e[22]!==a||e[23]!==c||e[24]!==v||e[25]!==k?(Ne=()=>{k&&(v==="merge"?a(k):c(k))},e[22]=a,e[23]=c,e[24]=v,e[25]=k,e[26]=Ne):Ne=e[26];const K=Ne;let pe;e[27]!==g||e[28]!==w?(pe=()=>{g||(j(null),S("merge"),B(""),w(!1))},e[27]=g,e[28]=w,e[29]=pe):pe=e[29];const L=pe,se=()=>{g&&!z||(z&&m?.(),j(null),S("merge"),B(""),w(!1))};let Z,je;e[30]!==A?(Z=()=>{A||B("")},je=[A],e[30]=A,e[31]=Z,e[32]=je):(Z=e[31],je=e[32]),i.useEffect(Z,je);let De,Le;e[33]!==x||e[34]!==X||e[35]!==k?(De=()=>{x!=="inline"||k||j(X())},Le=[x,X,k],e[33]=x,e[34]=X,e[35]=k,e[36]=De,e[37]=Le):(De=e[36],Le=e[37]),i.useEffect(De,Le);const he=g?s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{ref:E,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:s.jsx("div",{className:"space-y-2",children:b.map(iv)})}),z?x==="dialog"?s.jsx(nr,{children:s.jsx(Ve,{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(Ve,{variant:"default",size:"sm",onClick:se,children:h(V?"gitView.common.close":"gitView.common.done")})}):null]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:h("gitView.branch.operation")}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>S("merge"),className:Te("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",v==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-merge",className:Te("size-4",v==="merge"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Te("typography-ui-label",v==="merge"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.merge")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.mergeDescription")})]}),s.jsxs("button",{type:"button",onClick:()=>S("rebase"),className:Te("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",v==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-branch",className:Te("size-4",v==="rebase"?"text-primary":"text-muted-foreground")}),s.jsx("span",{className:Te("typography-ui-label",v==="rebase"?"text-foreground":"text-muted-foreground"),children:h("gitView.operation.rebase")})]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:h("gitView.branch.rebaseDescription")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:v==="merge"?h("gitView.branch.branchToMergeInto",{branch:R}):h("gitView.branch.branchToRebaseOnto")}),s.jsxs(tn,{open:A,onOpenChange:D,modal:!1,children:[s.jsx(Zs,{asChild:!0,children:s.jsxs(Ve,{variant:"outline",size:"lg",className:"w-full justify-between",children:[s.jsx("span",{className:Te("truncate",!k&&"text-muted-foreground"),children:k||h("gitView.branch.selectBranch")}),s.jsx(I,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),s.jsx(en,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:s.jsxs($a,{className:"h-full min-h-0",children:[s.jsx(za,{ref:T,placeholder:h("gitView.branch.searchPlaceholder"),value:N,onValueChange:B,onKeyDown:ov}),s.jsxs(Wa,{className:"h-full min-h-0",disableHorizontal:!0,children:[s.jsx(Ua,{children:h("gitView.branch.empty")}),te.length>0&&s.jsx(ui,{heading:h("gitView.branch.localBranches"),children:te.map(Ae=>s.jsx(mi,{onSelect:()=>ie(Ae),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ae})},`local-${Ae}`))}),te.length>0&&Q.length>0?s.jsx(lg,{}):null,Q.length>0&&s.jsx(ui,{heading:h("gitView.branch.remoteBranches"),children:Q.map(Ae=>s.jsx(mi,{onSelect:()=>ie(Ae),children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Ae})},`remote-${Ae}`))})]})]})})]})]}),k?s.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:v==="merge"?s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryMergePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})," ",h("gitView.branch.summaryMergeInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R})]}):s.jsxs(s.Fragment,{children:[h("gitView.branch.summaryRebasePrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R})," ",h("gitView.branch.summaryRebaseInfix")," ",s.jsx("span",{className:"font-mono text-foreground",children:k})]})})}):null,x==="dialog"?s.jsxs(nr,{className:"gap-2 pt-1",children:[s.jsx(Ve,{variant:"ghost",size:"sm",onClick:L,children:h("gitView.common.cancel")}),s.jsx(Ve,{variant:"default",size:"sm",onClick:K,disabled:!k,className:"gap-1.5",children:v==="merge"?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"git-merge",className:"size-4"}),h("gitView.operation.merge")]}):s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"git-branch",className:"size-4"}),h("gitView.operation.rebase")]})})]}):s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(Ve,{variant:"destructive",size:"sm",onClick:L,disabled:_,children:h("gitView.common.reset")}),s.jsx("div",{className:"flex-1"}),s.jsx(Ve,{variant:"default",size:"sm",onClick:K,disabled:_||!k,children:h(v==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(x==="inline"){let Ae;e[38]!==h?(Ae=h("gitView.branch.updateTitle"),e[38]=h,e[39]=Ae):Ae=e[39];let J;e[40]!==Ae?(J=s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Ae}),e[40]=Ae,e[41]=J):J=e[41];let O;e[42]!==h?(O=h("gitView.branch.updateDescriptionPrefix"),e[42]=h,e[43]=O):O=e[43];let ae;e[44]!==R?(ae=s.jsx("span",{className:"font-mono text-foreground",children:R}),e[44]=R,e[45]=ae):ae=e[45];let ne;e[46]!==O||e[47]!==ae?(ne=s.jsxs("div",{className:"typography-micro text-muted-foreground",children:[O," ",ae,"."]}),e[46]=O,e[47]=ae,e[48]=ne):ne=e[48];let Be;e[49]!==J||e[50]!==ne?(Be=s.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:s.jsxs("div",{className:"space-y-1",children:[J,ne]})}),e[49]=J,e[50]=ne,e[51]=Be):Be=e[51];let Ye;e[52]!==he?(Ye=s.jsx("div",{className:"pt-3",children:he}),e[52]=he,e[53]=Ye):Ye=e[53];let He;return e[54]!==Be||e[55]!==Ye?(He=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Be,Ye]}),e[54]=Be,e[55]=Ye,e[56]=He):He=e[56],He}let Ie;e[57]!==g?(Ie=g?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"git-merge",className:"size-4"}),e[57]=g,e[58]=Ie):Ie=e[58];let me;e[59]!==h?(me=h("gitView.branch.mergeRebase"),e[59]=h,e[60]=me):me=e[60];let ce;e[61]!==me?(ce=s.jsx("span",{children:me}),e[61]=me,e[62]=ce):ce=e[62];let xe;e[63]!==fe||e[64]!==_||e[65]!==Ie||e[66]!==ce?(xe=s.jsx(Mt,{asChild:!0,children:s.jsxs(Ve,{variant:"outline",size:"sm",className:"gap-1.5",onClick:fe,disabled:_,children:[Ie,ce]})}),e[63]=fe,e[64]=_,e[65]=Ie,e[66]=ce,e[67]=xe):xe=e[67];let ke;e[68]!==h?(ke=h("gitView.branch.mergeRebaseTooltip"),e[68]=h,e[69]=ke):ke=e[69];let de;e[70]!==ke?(de=s.jsx(Ft,{sideOffset:8,children:ke}),e[70]=ke,e[71]=de):de=e[71];let P;e[72]!==xe||e[73]!==de?(P=s.jsxs(Et,{children:[xe,de]}),e[72]=xe,e[73]=de,e[74]=P):P=e[74];let F;e[75]!==se||e[76]!==w?(F=Ae=>{Ae?w(!0):se()},e[75]=se,e[76]=w,e[77]=F):F=e[77];let ue;e[78]!==h?(ue=h("gitView.branch.updateTitle"),e[78]=h,e[79]=ue):ue=e[79];let be;e[80]!==ue?(be=s.jsx(Vs,{children:ue}),e[80]=ue,e[81]=be):be=e[81];let W;e[82]!==V||e[83]!==g||e[84]!==v||e[85]!==z||e[86]!==h||e[87]!==R?(W=g?h(z?V?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":v==="merge"?"gitView.branch.mergingInProgress":"gitView.branch.rebasingInProgress"):s.jsxs(s.Fragment,{children:[h("gitView.branch.dialogDescriptionPrefix")," ",s.jsx("span",{className:"font-mono text-foreground",children:R}),"."]}),e[82]=V,e[83]=g,e[84]=v,e[85]=z,e[86]=h,e[87]=R,e[88]=W):W=e[88];let ge;e[89]!==W?(ge=s.jsx(an,{children:W}),e[89]=W,e[90]=ge):ge=e[90];let we;e[91]!==be||e[92]!==ge?(we=s.jsxs(Gs,{children:[be,ge]}),e[91]=be,e[92]=ge,e[93]=we):we=e[93];let G;e[94]!==he||e[95]!==we?(G=s.jsxs(Es,{className:"max-w-md",children:[we,he]}),e[94]=he,e[95]=we,e[96]=G):G=e[96];let Se;e[97]!==C||e[98]!==F||e[99]!==G?(Se=s.jsx(Ms,{open:C,onOpenChange:F,children:G}),e[97]=C,e[98]=F,e[99]=G,e[100]=Se):Se=e[100];let Oe;return e[101]!==P||e[102]!==Se?(Oe=s.jsxs(s.Fragment,{children:[P,Se]}),e[101]=P,e[102]=Se,e[103]=Oe):Oe=e[103],Oe};function sv(t){return t.status==="done"||t.status==="error"}function nv(t){return t.status==="error"}function rv(t){return t.slice(t.indexOf("/")+1)}function iv(t,e){return s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"mt-0.5 shrink-0",children:[t.status==="running"&&s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),t.status==="done"&&s.jsx(I,{name:"check",className:"size-3.5 text-success"}),t.status==="error"&&s.jsx(I,{name:"close",className:"size-3.5 text-destructive"}),t.status==="pending"&&s.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),s.jsx("span",{className:Te("typography-micro",t.status==="error"&&"text-destructive",t.status==="done"&&"text-muted-foreground",t.status==="running"&&"text-foreground",t.status==="pending"&&"text-muted-foreground/60"),children:t.message})]},e)}function ov(t){return t.stopPropagation()}const av=({runMutation:t,onMutationComplete:e,onMutationError:n,onPathsComplete:r,scheduleFlush:o})=>{const a=[];let c=!1;return{enqueue:d=>{const f=a[a.length-1];if(f?.directory===d.directory&&f.direction===d.direction){d.paths.forEach(m=>f.paths.add(m));return}a.push(d)},flush:()=>{if(c)return;const d=a.shift();if(!d)return;c=!0;const f={directory:d.directory,direction:d.direction,paths:Array.from(d.paths),rollback:d.rollback};(async()=>{try{await t(f),e(f)}catch(m){n(f,m)}finally{r(f.paths),c=!1,a.length>0&&o()}})()},clear:()=>{a.length=0},size:()=>a.length,isRunning:()=>c}},Du="oc.git.actionTab",lv=15e3,cv=t=>t==="commit"||t==="branch"||t==="pr",dv=40,uv=20,Iu={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},fv=(t,e)=>{const n=t.toLowerCase(),r=/^([a-z]+)(?:\(.*\))?!?:/,o=n.match(r);if(o){const l=o[1],d=Iu[l];if(d)return e.find(f=>f.code===d)||null}const a=n.split(" ")[0],c=Iu[a];return c&&e.find(l=>l.code===c)||null},mv=20,Ui=new Map,hv=(t,e)=>{if(Ui.delete(t),Ui.set(t,e),Ui.size>mv){const n=Ui.keys().next().value;n!==void 0&&Ui.delete(n)}},Wr=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),Pu=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},pv=t=>{const e=t.working_dir?.trim(),n=t.index?.trim();return!!(e||n==="?")},tc=({isActive:t})=>{const{t:e}=Nt(),{git:n}=Xn(),r=pi(),[o,a]=i.useState(null),[c,l]=i.useState(!1),d=ut(Y=>Y.currentSessionId),f=ut(Y=>Y.newSessionDraft),m=ut(Y=>Y.setDraftBootstrapPendingDirectory),u=ut(Y=>Y.worktreeMetadata),p=ut(Y=>Y.availableWorktrees),y=Wr(r),g=i.useMemo(()=>{if(!y)return;const Y=p.find(Ce=>Wr(Ce.path)===y);if(Y)return Y;for(const Ce of u.values())if(Wr(Ce.path)===y)return Ce},[p,y,u]),b=i.useMemo(()=>{if(d)return u.get(d)??g;if(f?.open)return g},[d,g,f?.open,u]),{profiles:x,globalIdentity:h,defaultGitIdentityId:C,loadProfiles:w,loadGlobalIdentity:v,loadDefaultGitIdentityId:S}=Hx(Wl(Y=>({profiles:Y.profiles,globalIdentity:Y.globalIdentity,defaultGitIdentityId:Y.defaultGitIdentityId,loadProfiles:Y.loadProfiles,loadGlobalIdentity:Y.loadGlobalIdentity,loadDefaultGitIdentityId:Y.loadDefaultGitIdentityId}))),k=Cc(r??null),j=Ka(r??null),A=Xf(Y=>d?Y.getAttachment(d):void 0),D=A?cg(A):[],N=A&&!A.degraded&&!A.legacy?A.worktreeRoot??void 0:void 0,B=Hy(r,b,j?.current??void 0),T=nm(r??null),E=dg(r??null),_=ug(r??null),R=Ac(r??null),z=fg(r??null),{setActiveDirectory:V,fetchAll:$,ensureAll:M,fetchStatus:te,fetchBranches:re,fetchLog:Q,setLogMaxCount:H,fetchIdentity:X,prefetchDiffs:oe,moveStatusPathsOptimistically:fe,restoreStatus:ve,bumpIndexRevision:ie}=wn(Wl(Y=>({setActiveDirectory:Y.setActiveDirectory,fetchAll:Y.fetchAll,ensureAll:Y.ensureAll,fetchStatus:Y.fetchStatus,fetchBranches:Y.fetchBranches,fetchLog:Y.fetchLog,setLogMaxCount:Y.setLogMaxCount,fetchIdentity:Y.fetchIdentity,prefetchDiffs:Y.prefetchDiffs,moveStatusPathsOptimistically:Y.moveStatusPathsOptimistically,restoreStatus:Y.restoreStatus,bumpIndexRevision:Y.bumpIndexRevision}))),Ne=Ee(Y=>Y.isMobile),K=Ee(Y=>Y.openContextDiff),pe=Ee(Y=>Y.navigateToDiff),L=Ee(Y=>Y.setRightSidebarOpen),se=i.useRef(null),Z=i.useRef(null),je=i.useRef(null),De=i.useRef(null),Le=i.useRef(!0);i.useEffect(()=>()=>{Le.current=!1},[]);const Me=i.useCallback(()=>{Z.current!==null&&(window.clearTimeout(Z.current),Z.current=null)},[]),Fe=i.useCallback(Y=>{Me(),Z.current=window.setTimeout(()=>{Z.current=null,Wr(Y)===Wr(r)&&te(Y,n,{silent:!0})},lv)},[Me,r,te,n]);i.useEffect(()=>Me,[Me]);const he=i.useCallback(()=>{je.current!==null&&(window.clearTimeout(je.current),je.current=null)},[]),Ie=i.useCallback(()=>{je.current===null&&(je.current=window.setTimeout(()=>{je.current=null,De.current?.()},0))},[]),me=i.useCallback(async(Y,Ce,Re)=>{if(Ce==="stage"){if(n.stageGitFiles){await n.stageGitFiles(Y,Re);return}await Promise.all(Re.map($e=>n.stageGitFile(Y,$e)));return}if(n.unstageGitFiles){await n.unstageGitFiles(Y,Re);return}await Promise.all(Re.map($e=>n.unstageGitFile(Y,$e)))},[n]),ce=i.useMemo(()=>av({runMutation:({directory:Y,direction:Ce,paths:Re})=>me(Y,Ce,Re),onMutationComplete:({directory:Y})=>{ie(Y),Fe(Y)},onMutationError:({directory:Y,direction:Ce,rollback:Re},$e)=>{Re?.(),ie(Y),Fe(Y);const dt=e(Ce==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");le.error($e instanceof Error?$e.message:dt)},onPathsComplete:Y=>{ns(Ce=>{const Re=new Set(Ce);return Y.forEach($e=>Re.delete($e)),Re})},scheduleFlush:Ie}),[ie,me,Ie,Fe,e]);i.useEffect(()=>(De.current=ce.flush,()=>{De.current=null}),[ce]),i.useEffect(()=>()=>ce.clear(),[ce]),i.useEffect(()=>he,[he]),i.useEffect(()=>{if(!t)return;if(!r){a(null),l(!1);return}let Y=!1,Ce=null;const Re=async()=>{try{const $e=await hg(r);if(Y)return;a($e.status),$e.status==="pending"&&(Ce=window.setTimeout(()=>{Re()},500))}catch{Y||a(null)}};return Re(),()=>{Y=!0,Ce!==null&&window.clearTimeout(Ce)}},[t,r]),i.useEffect(()=>{const Y=se.current;se.current=o,!(!r||!n)&&(Y==="pending"&&o==="ready"&&(l(!0),$(r,n).finally(()=>{window.setTimeout(()=>{l(!1)},1200)})),o==="failed"&&(m(null),l(!1)))},[r,$,n,m,o]);const xe=Wr(f?.bootstrapPendingDirectory??null),ke=!!(r&&xe&&xe===Wr(r)),P=!!(r&&(o==="pending"||ke))||c,F=i.useMemo(()=>r?Ui.get(r)??null:null,[r]),ue=ss(Y=>Y.settingsGitmojiEnabled),[be,W]=i.useState(null),{gitmojis:ge}=Uy(ue);i.useEffect(()=>{const Y=N||B?.projectDirectory;if(!Y){W(null);return}let Ce=!1;return qa(Y).then(Re=>{if(Ce)return;const $e=Re.trim();W($e&&$e!=="HEAD"?$e:null)}).catch(()=>{Ce||W(null)}),()=>{Ce=!0}},[N,B?.projectDirectory]);const[we,G]=i.useState(F?.commitMessage??""),[Se,Oe]=i.useState([]),[Ae,J]=i.useState(!1),O=i.useRef(null),[ae,ne]=i.useState(null),[Be,Ye]=i.useState(!1),[He,Je]=i.useState(null),[nt,xt]=i.useState(25),[bt,_e]=i.useState(!1),{triggerFireworks:Qe}=Vy(),st=i.useRef(new Map),pt=i.useRef(0),At=i.useCallback(()=>{pt.current+=1,Le.current&&_e(!0)},[]),vt=i.useCallback(()=>{pt.current=Math.max(0,pt.current-1),Le.current&&pt.current===0&&_e(!1)},[]),[kt,et]=i.useState(new Set),[_t,ns]=i.useState(new Set),[Kt,qe]=i.useState(!1),[gt,Xe]=i.useState(0),[jt,Pt]=i.useState(!1),[is,Bt]=i.useState(F?.generatedHighlights??[]),Gt=_t.size>0||ce.size()>0||ce.isRunning(),es=i.useCallback(()=>{const Y=O.current;Y&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{Y.scrollTo({top:Y.scrollHeight,behavior:"smooth"})})})},[]),Wt=N||B?.projectDirectory||null,Lt=j?.current||null,Ut=i.useMemo(()=>{const Y=j?.tracking;return Y?Y.startsWith("origin/"):!0},[j?.tracking]),rs=i.useMemo(()=>{const Y=B?.createdFromBranch,Ce=typeof Y=="string"?Y.trim():"",Re=typeof j?.current=="string"?j.current.trim():"",$e=typeof be=="string"?be.trim():"";return Ce?Ce===Re&&Ce.startsWith("opencode/")&&$e.length>0&&$e!==Ce?$e:Ce:$e||Re||"HEAD"},[B?.createdFromBranch,j,be]),$t=i.useCallback(()=>{Bt([])},[]),[ls,xs]=i.useState(new Set),[Ct,Vt]=i.useState(new Map),[yt,us]=i.useState(new Set),cs=i.useRef(Ct),Ue=i.useRef(yt),[Ge,wt]=i.useState(null),[Ot,Dt]=i.useState(null),[bs,fs]=i.useState(""),[os,qt]=i.useState(null),ln=i.useMemo(()=>[{id:"commit",label:e("gitView.tabs.commit"),icon:s.jsx(I,{name:"git-commit",className:"h-3.5 w-3.5"})},{id:"branch",label:e("gitView.tabs.update"),icon:s.jsx(I,{name:"git-merge",className:"h-3.5 w-3.5"})},{id:"pr",label:e("gitView.tabs.pr"),icon:s.jsx(I,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],[e]),[ps,Fs]=i.useState(()=>{if(typeof window>"u")return"commit";const Y=window.localStorage.getItem(Du);return Y==="worktree"?"branch":cv(Y)?Y:"commit"}),[Ws,sn]=i.useState([]),[Dn,jn]=i.useState(null),[ye,Ze]=i.useState(null),[ct,It]=i.useState([]),[Ht,mt]=i.useState(!1),[ms,hs]=i.useState([]),[Ns,ys]=i.useState("merge"),[Is,Mn]=i.useState(null),[$s,hn]=i.useState(!1),[Fn,Zn]=i.useState(100),cn=i.useMemo(()=>d?`openchamber.conflict:${d}`:null,[d]),We=i.useCallback((Y,Ce,Re)=>{if(!cn||typeof window>"u")return;const $e={directory:Y,conflictFiles:Ce,operation:Re};window.localStorage.setItem(cn,JSON.stringify($e))},[cn]),Xt=i.useCallback(()=>{!cn||typeof window>"u"||window.localStorage.removeItem(cn)},[cn]);i.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Du,ps)},[ps]),i.useEffect(()=>{if(!cn||typeof window>"u"||!r)return;const Y=window.localStorage.getItem(cn);if(Y)try{const Ce=JSON.parse(Y);if(Ce.directory!==r){window.localStorage.removeItem(cn);return}hs(Ce.conflictFiles??[]),ys(Ce.operation??"merge"),mt(!0)}catch{window.localStorage.removeItem(cn)}},[cn,r]);const[As,Ps]=i.useState(!1),[zs,Qs]=i.useState("merge"),[Us,Os]=i.useState(""),On=i.useCallback(Y=>{ur(Y).then(Ce=>{if(Ce.ok){le.success(e("gitView.toast.commitHashCopied"));return}le.error(e("gitView.toast.copyFailed"))})},[e]),fr=i.useCallback(Y=>{xs(Ce=>{const Re=new Set(Ce);return Re.has(Y)?Re.delete(Y):Re.add(Y),Re})},[]);i.useEffect(()=>{cs.current=Ct},[Ct]),i.useEffect(()=>{Ue.current=yt},[yt]),i.useEffect(()=>{if(!r||!n)return;const Y=Array.from(ls).filter(Re=>!cs.current.has(Re)&&!Ue.current.has(Re));if(Y.length===0)return;let Ce=!1;return us(Re=>{const $e=new Set(Re);for(const dt of Y)$e.add(dt);return Ue.current=$e,$e}),Promise.all(Y.map(Re=>n.getCommitFiles(r,Re).then($e=>({hash:Re,files:$e.files})).catch($e=>(console.error("Failed to fetch commit files:",$e),{hash:Re,files:[]})))).then(Re=>{Ce||(Vt($e=>{const dt=new Map($e);for(const{hash:Rt,files:Qt}of Re)dt.set(Rt,Qt);return cs.current=dt,dt}),us($e=>{const dt=new Set($e);for(const{hash:Rt}of Re)dt.delete(Rt);return Ue.current=dt,dt}))}),()=>{Ce=!0,us(Re=>{let $e=!1;const dt=new Set(Re);for(const Rt of Y)dt.delete(Rt)&&($e=!0);return $e?(Ue.current=dt,dt):Re})}},[ls,r,n]),i.useEffect(()=>{r&&hv(r,{directory:r,commitMessage:we,generatedHighlights:is})},[we,r,is]),i.useEffect(()=>{t&&(w(),v(),S())},[t,w,v,S]),i.useEffect(()=>{if(!t)return;if(!r||!n?.getRemoteUrl){Dt(null);return}let Y=!1;return n.getRemoteUrl(r).then(Ce=>{Y||Dt(Ce)}).catch(()=>{Y||Dt(null)}),()=>{Y=!0}},[t,r,n]);const Kn=i.useCallback(async()=>{if(!r||!n?.getRemotes){sn([]);return}try{const Y=await n.getRemotes(r);Le.current&&sn(Y)}catch{Le.current&&sn([])}},[r,n]);i.useEffect(()=>{t&&Kn()},[t,Kn]),i.useEffect(()=>{t&&r&&(V(r),M(r,n))},[t,r,V,M,n]),i.useEffect(()=>{if(t&&r)return Er.onGitRefreshHint(Y=>{Wr(Y.directory)===Wr(r)&&te(r,n)})},[t,r,te,n]);const gs=i.useCallback(async(Y=!0)=>{if(r)try{await Promise.all([te(r,n),re(r,n)])}catch(Ce){if(Y){const Re=Ce instanceof Error?Ce.message:e("gitView.toast.refreshRepositoryFailed");le.error(Re)}}},[r,n,te,re,e]),Ts=i.useCallback(async()=>{r&&await Q(r,n,nt)},[r,n,Q,nt]),Sr=i.useCallback(async()=>{r&&await X(r,n)},[r,n,X]);i.useEffect(()=>{if(!t||!r||!n?.hasLocalIdentity||k!==!0)return;const Y=typeof C=="string"?C.trim():"";if(!Y||Y==="global"||st.current.get(r)===Y)return;let Re=!1;return(async()=>{try{const dt=await n.hasLocalIdentity?.(r);if(Re||dt===!0)return;At(),await n.setGitIdentity(r,Y),st.current.set(r,Y),await Sr()}catch(dt){console.warn("Failed to auto-apply default git identity:",dt)}finally{Re||vt()}})(),()=>{Re=!0}},[t,At,r,C,vt,n,k,Sr]);const Ln=i.useMemo(()=>j?[...j.files??[]].sort((Ce,Re)=>Ce.path.localeCompare(Re.path)):[],[j]),pn=i.useMemo(()=>Ln.filter(Pu),[Ln]),Nr=i.useMemo(()=>Ln.filter(pv),[Ln]);i.useEffect(()=>{if(!r||Ln.length===0)return;const Y=[],Ce=new Set,Re=dt=>{!dt||Ce.has(dt)||(Ce.add(dt),Y.push(dt))};if(pn.forEach(dt=>Re(dt.path)),Se.forEach(Re),Ln.slice(0,uv).forEach(dt=>Re(dt.path)),Y.length===0)return;const $e=window.setTimeout(()=>{oe(r,n,Y,{maxFiles:dv})},120);return()=>{window.clearTimeout($e)}},[Ln,r,n,oe,pn,Se]);const kr=Y=>Y?.pushed[0]?.remote||j?.tracking?.split("/")[0]||ts.find(Ce=>Ce.name==="origin")?.name||ts[0]?.name||"origin",Lr=async(Y,Ce)=>{if(r){ne(Y);try{const Re=$e=>{const dt=`${$e.name}/`,Rt=j?.tracking?.startsWith(dt)?j.tracking.slice(dt.length):void 0;return{remote:$e.name,branch:Rt,rebase:!0}};if(Y==="fetch"){if(!Ce)throw new Error("No remote available for fetch");await n.gitFetch(r,{remote:Ce.name}),le.success(e("gitView.toast.fetchedFromRemote",{name:Ce.name}))}else if(Y==="pull"){if(!Ce)throw new Error("No remote available for pull");const $e=await n.gitPull(r,Re(Ce));le.success($e.files.length===1?e("gitView.toast.pulledFilesSingle",{count:$e.files.length,name:Ce.name}):e("gitView.toast.pulledFilesPlural",{count:$e.files.length,name:Ce.name}))}else if(Y==="push"){const $e=await n.gitPush(r);le.success(e("gitView.toast.pushedToUpstream",{name:kr($e)}))}else if(Y==="sync"){if(!Ce)throw new Error("No remote available for sync");let $e=0,dt=!1;await n.gitFetch(r,{remote:Ce.name});const Rt=await n.getGitStatus(r);if((Rt.behind??0)>0){if((Rt.files?.length??0)>0){le.error(e("gitView.toast.commitOrStashBeforeSync"));return}$e=(await n.gitPull(r,Re(Ce))).files.length}((await n.getGitStatus(r)).ahead??0)>0&&(await n.gitPush(r),dt=!0),$e>0&&dt?le.success($e===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:$e,name:Ce.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:$e,name:Ce.name})):$e>0?le.success($e===1?e("gitView.toast.pulledFilesSingle",{count:$e,name:Ce.name}):e("gitView.toast.pulledFilesPlural",{count:$e,name:Ce.name})):dt?le.success(e("gitView.toast.pushedToUpstream",{name:Ce.name})):le.success(e("gitView.toast.alreadyUpToDate"))}await gs(!1),await Ts()}catch(Re){const $e=Re instanceof Error?Re.message:e("gitView.toast.syncActionFailed",{action:Y==="sync"?e("gitView.sync.syncChanges"):Y==="pull"?e("gitView.sync.pull"):Y});le.error($e)}finally{ne(null)}}},Cr=i.useCallback(async Y=>{if(!r)return;const Ce=Y.name.trim();if(!Ce){le.error(e("gitView.toast.remoteNameRequired"));return}if(Ce==="origin"){le.error(e("gitView.toast.cannotRemoveOriginRemote"));return}jn(Ce);try{await n.removeRemote(r,{remote:Ce}),le.success(e("gitView.toast.removedRemote",{name:Ce})),await Promise.all([gs(!1),Kn()])}catch(Re){const $e=Re instanceof Error?Re.message:`Failed to remove ${Ce}`;le.error($e)}finally{jn(null)}},[r,n,Kn,gs,e]),rr=async(Y={})=>{if(!r)return;if(!we.trim()){le.error(e("gitView.toast.enterCommitMessage"));return}const Ce=pn.map($e=>$e.path).sort();if(Ce.length===0){le.error(e("gitView.toast.stageFileToCommit"));return}const Re=Y.pushAfter?"commitAndPush":"commit";Je(Re);try{if(await n.createGitCommit(r,we.trim(),{files:Ce,stageFiles:[]}),ie(r),le.success(e("gitView.toast.commitCreated")),G(""),$t(),await gs(),Y.pushAfter){const $e=j?.tracking?.split("/")[0],dt=ts.find(Dr=>Dr.name===$e)??ts[0];if(!dt)throw new Error(e("mobile.changes.noRemote"));ne("sync");const Rt=`${dt.name}/`,Qt=j?.tracking?.startsWith(Rt)?j.tracking.slice(Rt.length):void 0;await n.gitFetch(r,{remote:dt.name});const Jt=await n.getGitStatus(r);if((Jt.behind??0)>0){if((Jt.files?.length??0)>0){le.error(e("gitView.toast.commitOrStashBeforeSync")),await gs(!1);return}await n.gitPull(r,{remote:dt.name,branch:Qt,rebase:!0})}const vs=await n.getGitStatus(r);let gr;(vs.ahead??0)>0&&(gr=await n.gitPush(r)),le.success(e("gitView.toast.pushedToUpstream",{name:kr(gr)})),Qe(),await gs(!1)}else await gs(!1);await Ts(),Xe($e=>$e+1)}catch($e){const dt=$e instanceof Error?$e.message:e("gitView.toast.createCommitFailed");le.error(dt)}finally{Je(null),Y.pushAfter&&ne(null)}},js=i.useCallback(async()=>{if(!r)return;const Y=pn.map(Ce=>Ce.path).sort();if(Y.length===0){le.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:Y.length}),Pt(!0);try{const{message:Ce}=await mg(r,Y),Re=Ce.subject?.trim()??"",$e=Array.isArray(Ce.highlights)?Ce.highlights:[];if(Re){let dt=Re;if(ue&&ge.length>0){const Rt=fv(Re,ge);if(Rt){const{code:Qt,emoji:Jt}=Rt;!Re.startsWith(Qt)&&!Re.startsWith(Jt)&&(dt=`${Qt} ${Re}`)}}G(dt)}Bt($e),es()}catch(Ce){console.error("[git-generation][browser] GitView generate handler failed",{message:Ce instanceof Error?Ce.message:String(Ce),error:Ce});const Re=Ce instanceof Error?Ce.message:e("gitView.toast.generateCommitMessageFailed");le.error(Re)}finally{Pt(!1)}},[r,pn,ue,ge,es,e]),dn=Y=>Y.reason==="attention"?`${Y.attentionReason} in progress`:Y.reason==="missing"?"worktree is missing":"worktree is invalid",ir=async(Y,Ce)=>{if(!r||!j)return;const Re=ll(A);if(Re.length>0){le.error(e("gitView.toast.cannotCreateBranch",{reason:dn(Re[0])}));return}const $e=j.current??null,dt=Ce?.name??"origin";try{await n.createBranch(r,Y,$e??"HEAD"),le.success(e("gitView.toast.createdBranch",{name:Y})),await n.checkoutBranch(r,Y);let Rt=!1;try{await n.gitPush(r,{remote:dt,branch:Y,options:["--set-upstream"]}),Rt=!0}catch(Qt){const Jt=Qt instanceof Error?Qt.message:`Unable to push new branch to ${dt}.`;le.warning(e("gitView.toast.branchCreatedLocally"),{description:s.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Jt]})})}await gs(),await Ts(),Rt&&le.success(e("gitView.toast.upstreamSet",{branch:Y,remote:dt}))}catch(Rt){const Qt=Rt instanceof Error?Rt.message:e("gitView.toast.createBranchFailed");throw le.error(Qt),Rt}},q=async(Y,Ce)=>{if(!r)return;const Re=ll(A);if(Re.length>0){le.error(e("gitView.toast.cannotRenameBranch",{reason:dn(Re[0])}));return}try{await n.renameBranch(r,Y,Ce),le.success(e("gitView.toast.renamedBranch",{oldName:Y,newName:Ce})),await gs(),await Ts()}catch($e){const dt=$e instanceof Error?$e.message:e("gitView.toast.renameBranchFailed",{oldName:Y,newName:Ce});le.error(dt)}},rt=async Y=>{if(!r)return;const Ce=ll(A);if(Ce.length>0){le.error(e("gitView.toast.cannotCheckout",{reason:dn(Ce[0])}));return}const Re=Y.replace(/^remotes\//,"");if(j?.current!==Re)try{await n.checkoutBranch(r,Re),le.success(e("gitView.toast.checkedOut",{name:Re})),await gs(),await Ts()}catch($e){const dt=$e instanceof Error?$e.message:e("gitView.toast.checkoutFailed",{name:Re});le.error(dt)}},ht=async Y=>{if(r){At();try{await n.setGitIdentity(r,Y.id),le.success(e("gitView.toast.appliedIdentity",{name:Y.name})),await Sr()}catch(Ce){const Re=Ce instanceof Error?Ce.message:e("gitView.toast.applyIdentityFailed");le.error(Re)}finally{vt()}}},Tt=i.useMemo(()=>T?.all?T.all.filter(Y=>!Y.startsWith("remotes/")).sort():[],[T]),Yt=i.useMemo(()=>T?.all?T.all.filter(Y=>Y.startsWith("remotes/")).map(Y=>Y.replace(/^remotes\//,"")).sort():[],[T]),ts=i.useMemo(()=>{if(Ws.length>0)return Ws;const Y=new Set,Ce=j?.tracking?.trim();Ce&&Ce.includes("/")&&Y.add(Ce.split("/")[0]);for(const Re of Yt){const $e=Re.indexOf("/");$e>0&&Y.add(Re.slice(0,$e))}return Y.size===0&&Ot&&Y.add("origin"),Array.from(Y).map(Re=>({name:Re,fetchUrl:Ot??"",pushUrl:Ot??""}))},[Ws,Yt,Ot,j?.tracking]),ds=i.useMemo(()=>{const Y=new Set(ts.map(dt=>dt.name)),Ce=dt=>{if(!dt)return"";let Rt=dt.trim();if(!Rt||Rt==="HEAD")return"";if(Tt.includes(Rt))return Rt;Rt.startsWith("refs/heads/")&&(Rt=Rt.slice(11)),Rt.startsWith("heads/")&&(Rt=Rt.slice(6)),Rt.startsWith("remotes/")&&(Rt=Rt.slice(8));const Qt=Rt.indexOf("/");if(Qt>0){const Jt=Rt.slice(0,Qt);if(Y.has(Jt)){const vs=Rt.slice(Qt+1).trim();vs&&(Rt=vs)}}return Rt},Re=Ce(typeof B?.createdFromBranch=="string"?B.createdFromBranch:"");if(Re)return Re;const $e=Ce(typeof be=="string"?be:"");return $e||(Tt.includes("main")?"main":Tt.includes("master")?"master":Tt.includes("develop")?"develop":"main")},[ts,Tt,be,B?.createdFromBranch]),Ls=i.useMemo(()=>ts.map(Re=>Re.name).map(Re=>`${Re}/${ds}`).find(Re=>Yt.includes(Re))??ds,[ds,ts,Yt]),Ks=i.useMemo(()=>{const Y=new Map;h&&Y.set(h.id,h);let Ce=null;if(Ot)try{let Re=Ot.trim();Re.startsWith("git@")&&(Re=`https://${Re.slice(4).replace(":","/")}`),Re.endsWith(".git")&&(Re=Re.slice(0,-4));const $e=new URL(Re);Ce=$e.hostname+$e.pathname}catch{}for(const Re of x){if(Re.authType!=="token"){Y.set(Re.id,Re);continue}const $e=Re.host;if(!$e){Y.set(Re.id,Re);continue}if(!$e.includes("/")){Y.set(Re.id,Re);continue}Ce&&Ce===$e&&Y.set(Re.id,Re)}return Array.from(Y.values())},[x,h,Ot]),qn=i.useMemo(()=>{if(_?.userName&&_?.userEmail){const Y=x.find(Ce=>Ce.userName===_.userName&&Ce.userEmail===_.userEmail);return Y||(h&&h.userName===_.userName&&h.userEmail===_.userEmail?h:{id:"local-config",name:_.userName,userName:_.userName,userEmail:_.userEmail,sshKey:_.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return h??null},[_,x,h]),Bn=pn.length,Jr=R||ae!==null||He!==null,gn=j?.current??null,Xr=!!(B&&Wt&&Lt&&Ut),xn=!!(r&&gn),nn=!!gn,un=Xr&&Wt&&Lt&&B?{repoRoot:Wt,sourceBranch:Lt,worktreeMetadata:B}:null,Sn=i.useMemo(()=>!xn||!r||!gn?null:{directory:r,branch:gn},[xn,gn,r]);i.useEffect(()=>{if(!r||!n||!E?.all?.length||!gn||!ds||gn===ds){wt(null);return}let Y=!1;return(async()=>{try{const Re=await n.getGitLog(r,{from:ds,to:"HEAD",maxCount:nt});if(Y)return;const $e=new Set((Re?.all??[]).map(Rt=>Rt.hash).filter(Rt=>typeof Rt=="string"&&Rt.length>0));if($e.size===0){wt(null);return}const dt=E.all.findIndex(Rt=>!$e.has(Rt.hash));if(dt===0){wt(null);return}if(dt===-1){wt({insertBeforeIndex:E.all.length,branchName:gn,direction:"up"});return}wt({insertBeforeIndex:dt,branchName:gn,direction:"up"})}catch{Y||wt(null)}})(),()=>{Y=!0}},[ds,gn,r,n,E,nt]),i.useEffect(()=>{Mn(null)},[r]),i.useEffect(()=>{if(os!=="graph"||!r){os!=="graph"&&Mn(null);return}let Y=!1;return hn(!0),n.getGitLog(r,{maxCount:Fn,all:!0}).then(Ce=>{Y||Mn(Ce)}).catch(Ce=>{console.error("Failed to fetch graph log:",Ce)}).finally(()=>{Y||hn(!1)}),()=>{Y=!0}},[os,r,Fn,n]);const Nn=i.useCallback((Y,Ce)=>{if(!r||Y.length===0)return;const Re=Array.from(new Set(Y));ns(dt=>{const Rt=new Set(dt);return Re.forEach(Qt=>Rt.add(Qt)),Rt});const $e=fe(r,Re,Ce);ce.enqueue({directory:r,direction:Ce,paths:new Set(Re),rollback:()=>ve(r,$e)}),Ie()},[r,ce,fe,ve,Ie]),mr=i.useCallback(async Y=>{if(r){et(Ce=>{const Re=new Set(Ce);return Re.add(Y),Re});try{await n.revertGitFile(r,Y,{scope:"working"}),le.success(e("gitView.toast.revertedFile",{path:Y})),await gs(!1)}catch(Ce){const Re=Ce instanceof Error?Ce.message:e("gitView.toast.revertFailed");le.error(Re)}finally{et(Ce=>{const Re=new Set(Ce);return Re.delete(Y),Re})}}},[r,gs,n,e]),or=i.useCallback(async(Y,Ce,Re="all")=>{if(!r||Y.length===0)return;const $e=Array.from(new Set(Y));if(Kt||$e.some(Jt=>kt.has(Jt)))return;const dt=new Set(pn.map(Jt=>Jt.path)),Rt=Re==="all"&&$e.some(Jt=>dt.has(Jt));Ce&&qe(!0),et(Jt=>{const vs=new Set(Jt);return $e.forEach(gr=>vs.add(gr)),vs});const Qt=[];try{if(await Promise.all($e.map(async Jt=>{try{await n.revertGitFile(r,Jt,{scope:Re})}catch(vs){Qt.push({path:Jt,message:vs instanceof Error?vs.message:e("gitView.toast.revertFailed")})}})),Rt&&Qt.length<$e.length&&ie(r),await gs(!1),Qt.length===0)le.success($e.length===1?e("gitView.toast.revertedFilesSingle",{count:$e.length}):e("gitView.toast.revertedFilesPlural",{count:$e.length}));else if(Qt.length===$e.length)le.error(Qt[0]?.message||e("gitView.toast.revertFailed"));else{const Jt=$e.length-Qt.length;le.warning(Jt===1?e("gitView.toast.revertedSomeSingle",{success:Jt,failed:Qt.length}):e("gitView.toast.revertedSomePlural",{success:Jt,failed:Qt.length}))}}finally{et(Jt=>{const vs=new Set(Jt);return $e.forEach(gr=>vs.delete(gr)),vs}),Ce&&qe(!1)}},[ie,r,n,Kt,gs,kt,pn,e]),Ar=i.useCallback(async Y=>{await or(Y,!0)},[or]),gi=i.useCallback(async Y=>{await or(Y,!1,"working")},[or]),ar=i.useCallback((Y,Ce)=>{if(r&&!Ne){K(r,Y,Ce);return}pe(Y,Ce),Ne&&L(!1)},[r,Ne,pe,K,L]),xi=i.useCallback(()=>Ye(!0),[]),Br=i.useMemo(()=>{const Y=[];return pn.length>0&&Y.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:pn,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:Ce=>e("gitView.changes.unstageFileAria",{path:Ce}),onActionFile:Ce=>{Nn([Ce],"unstage")},onActionAll:Ce=>{Nn(Ce,"unstage")},onViewDiff:Ce=>ar(Ce,!0),onRevertFile:mr,showRevertActions:!1,accent:!0}),Nr.length>0&&Y.push({id:"unstaged",title:e("gitView.changes.title"),entries:Nr,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:Ce=>e("gitView.changes.stageFileAria",{path:Ce}),onActionFile:Ce=>{Nn([Ce],"stage")},onActionAll:Ce=>{Nn(Ce,"stage")},onViewDiff:Ce=>ar(Ce,!1),onRevertFile:mr}),Y},[mr,ar,Nn,pn,e,Nr]),Zr=i.useCallback(Y=>{if(Y.length===0)return;const Ce=Y.map(Re=>Re.trim()).filter(Boolean);if(Ce.length===0){$t();return}G(Re=>{const $e=Re.trim(),dt=$e.length>0?`
|
|
11
|
-
|
|
12
|
-
`:"";return`${$e}${dt}${Ce.join(`
|
|
13
|
-
`)}`.trim()}),$t()},[$t]),In=i.useCallback((Y,Ce)=>{const Re=Ce||Y;G($e=>{const dt=$e.trimStart();return dt.startsWith(Y)||Ce&&dt.startsWith(Ce)?$e:`${Re.endsWith(" ")?Re:`${Re} `}${$e}`.trimStart()}),fs(""),J(!1)},[]),lr=i.useCallback(Y=>{const Ce=Y instanceof Error?Y.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")},[]),Js=i.useCallback((Y,Ce)=>{It(Re=>[...Re,{message:Y,status:Ce,timestamp:Date.now()}])},[]),Hs=i.useCallback((Y,Ce)=>{It(Re=>{if(Re.length===0)return Re;const $e=[...Re];return $e[$e.length-1]={...$e[$e.length-1],status:Y,...Ce?{message:Ce}:{}},$e})},[]),_r=i.useCallback(()=>{It([])},[]),Li=i.useCallback(()=>{It([]),Ze(null)},[]),ei=i.useCallback(Y=>{const Ce=Y.trim(),Re=new Set(ts.map(dt=>dt.name)),$e=Ce.indexOf("/");if($e>0){const dt=Ce.slice(0,$e),Rt=Ce.slice($e+1);if(Re.has(dt)&&Rt)return{branch:Ce,remote:dt,remoteBranch:Rt}}for(const dt of ts){const Rt=`${dt.name}/${Ce}`;if(Yt.includes(Rt))return{branch:Rt,remote:dt.name,remoteBranch:Ce}}return{branch:Ce,remote:null,remoteBranch:null}},[ts,Yt]),hr=i.useCallback(async Y=>{if(!r)return;Ze("merge"),_r();const Ce=j?.current,Re=ei(Y);try{Re.remote&&Re.remoteBranch&&(Js(`Fetching ${Re.remote}/${Re.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Re.remote,branch:Re.remoteBranch}),Hs("done",`Fetched ${Re.remote}/${Re.remoteBranch}`)),Js(`Merging ${Re.branch} into ${Ce}...`,"running");const $e=await n.merge(r,{branch:Re.branch});$e.conflict?(Hs("error","Merge conflicts detected"),hs($e.conflictFiles??[]),ys("merge"),mt(!0),We(r,$e.conflictFiles??[],"merge")):(Hs("done",`Merged ${Re.branch} into ${Ce}`),Xt(),Js("Refreshing repository status...","running"),await gs(),await Ts(),Hs("done","Repository status updated"))}catch($e){if(lr($e))Hs("error","Uncommitted changes detected"),Qs("merge"),Os(Re.branch),Ps(!0);else{const dt=$e instanceof Error?$e.message:`Failed to merge ${Re.branch}`;Hs("error",dt)}}},[r,n,j,ei,gs,Ts,lr,We,Xt,Js,Hs,_r]),bi=i.useCallback(async Y=>{if(!r)return;Ze("rebase"),_r();const Ce=j?.current,Re=ei(Y);try{Re.remote&&Re.remoteBranch&&(Js(`Fetching ${Re.remote}/${Re.remoteBranch}...`,"running"),await n.gitFetch(r,{remote:Re.remote,branch:Re.remoteBranch}),Hs("done",`Fetched ${Re.remote}/${Re.remoteBranch}`)),Js(`Rebasing ${Ce} onto ${Re.branch}...`,"running");const $e=await n.rebase(r,{onto:Re.branch});$e.conflict?(Hs("error","Rebase conflicts detected"),hs($e.conflictFiles??[]),ys("rebase"),mt(!0),We(r,$e.conflictFiles??[],"rebase")):(Hs("done",`Rebased ${Ce} onto ${Re.branch}`),Xt(),Js("Refreshing repository status...","running"),await gs(),await Ts(),Hs("done","Repository status updated"))}catch($e){if(lr($e))Hs("error","Uncommitted changes detected"),Qs("rebase"),Os(Re.branch),Ps(!0);else{const dt=$e instanceof Error?$e.message:`Failed to rebase onto ${Re.branch}`;Hs("error",dt)}}},[r,n,j,ei,gs,Ts,lr,We,Xt,Js,Hs,_r]),bn=i.useCallback(async()=>{if(r)try{Ns==="merge"?(await n.abortMerge(r),le.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),le.success(e("gitView.toast.rebaseAborted"))),Xt(),await gs(),await Ts()}catch(Y){const Ce=Y instanceof Error?Y.message:`Failed to abort ${Ns}`;le.error(Ce)}},[r,n,Ns,gs,Ts,Xt,e]),pr=i.useMemo(()=>j?.files?j.files.some(Y=>Y.index==="U"||Y.working_dir==="U"||Y.index==="A"&&Y.working_dir==="A"||Y.index==="D"&&Y.working_dir==="D"):!1,[j?.files]),Vr=i.useCallback(async()=>{if(r)try{const Y=!!j?.mergeInProgress?.head,Ce=!!(j?.rebaseInProgress?.headName||j?.rebaseInProgress?.onto);if(Y){const Re=await n.continueMerge(r);Re.conflict?(hs(Re.conflictFiles??[]),ys("merge"),mt(!0),We(r,Re.conflictFiles??[],"merge"),le.error(e("gitView.toast.mergeConflictsDetected"))):(Xt(),le.success(e("gitView.toast.mergeCompleted")),await gs(),await Ts())}else if(Ce){const Re=await n.continueRebase(r);Re.conflict?(hs(Re.conflictFiles??[]),ys("rebase"),mt(!0),We(r,Re.conflictFiles??[],"rebase"),le.error(e("gitView.toast.rebaseConflictsDetected"))):(Xt(),le.success(e("gitView.toast.rebaseStepCompleted")),await gs(),await Ts())}}catch(Y){const Ce=Y instanceof Error?Y.message:e("gitView.toast.continueOperationFailed");le.error(Ce)}},[r,n,j,gs,Ts,We,Xt,e]),yi=i.useCallback(async()=>{if(r)try{!!j?.mergeInProgress?.head?(await n.abortMerge(r),le.success(e("gitView.toast.mergeAborted"))):(await n.abortRebase(r),le.success(e("gitView.toast.rebaseAborted"))),Xt(),await gs(),await Ts()}catch(Y){const Ce=Y instanceof Error?Y.message:e("gitView.toast.abortOperationFailed");le.error(Ce)}},[r,n,j,gs,Ts,Xt,e]),$r=i.useCallback(()=>{if(!r)return;const Ce=!!j?.mergeInProgress?.head?"merge":"rebase",Re=j?.files?.filter($e=>$e.index==="U"||$e.working_dir==="U").map($e=>$e.path)??[];Re.length>0&&hs(Re),ys(Ce),mt(!0)},[r,j]),Bi=i.useCallback(async Y=>{if(!r)return;const Ce=j?.current,Re=zs,$e=Us,dt=(j?.files??[]).some(Pu);try{await n.stash(r,{message:`Auto-stash before ${Re} with ${$e}`,includeUntracked:!0}),dt&&ie(r)}catch(Jt){const vs=Jt instanceof Error?Jt.message:"Failed to stash changes";le.error(vs);return}let Rt=!1,Qt=!1;try{if(Re==="merge"){const Jt=await n.merge(r,{branch:$e});Jt.conflict?(Qt=!0,hs(Jt.conflictFiles??[]),ys("merge"),mt(!0)):(Rt=!0,le.success(e("gitView.toast.mergedIntoBranch",{branch:$e,currentBranch:Ce||""})))}else{const Jt=await n.rebase(r,{onto:$e});Jt.conflict?(Qt=!0,hs(Jt.conflictFiles??[]),ys("rebase"),mt(!0)):(Rt=!0,le.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:Ce||"",branch:$e})))}if(Y&&Rt)try{await n.stashPop(r),ie(r),le.success(e("gitView.toast.stashedRestored"))}catch(Jt){const vs=Jt instanceof Error?Jt.message:e("gitView.toast.restoreStashFailed");le.error(vs)}else Y&&Qt&&le.info(e("gitView.toast.restoreStashManually"));await gs(),await Ts()}catch(Jt){if(Y)try{await n.stashPop(r),ie(r)}catch{}throw Jt}},[ie,r,n,j,zs,Us,gs,Ts,e]),rn=i.useCallback(Y=>{xt(Y),r&&(H(r,Y),Q(r,n,Y))},[r,Q,n,H]),wi=i.useCallback(Y=>{Zn(Y)},[]),_i=i.useCallback(()=>{qt(null),r&&(te(r,n),re(r,n),Q(r,n,nt))},[r,te,re,Q,nt,n]),mo=i.useCallback(Y=>{if(Y.conflict){if(Y.operation==="cherry-pick"||Y.operation==="revert"){le.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:Y.conflictFiles?.join(", ")??"unknown files"})}),r&&(te(r,n),re(r,n),Q(r,n,nt));return}hs(Y.conflictFiles??[]),ys(Y.operation),mt(!0),r&&We(r,Y.conflictFiles??[],Y.operation)}},[e,hs,ys,mt,We,r,te,re,Q,nt,n]);return r?k===null||k===!0&&!j?s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):k===!1?P?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(I,{name:"loader-4",className:"mb-3 size-6 animate-spin text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.worktreeSetupInProgress")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.worktreeSetupDescription")})]}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[s.jsx(I,{name:"git-branch",className:"mb-3 size-6 text-muted-foreground"}),s.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e("gitView.empty.notGitRepository")}),s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.notGitRepositoryDescription")}),D.includes("open-without-worktree-features")?s.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:e("gitView.empty.worktreeFeaturesUnavailable")}):null]}):s.jsxs("div",{className:Te("flex h-full flex-col overflow-hidden"),children:[s.jsx(Gx,{status:j,localBranches:Tt,remoteBranches:Yt,branchInfo:T?.branches,syncAction:ae,remotes:ts,onFetch:Y=>Lr("fetch",Y),onSync:Y=>Lr("sync",Y),onRemoveRemote:Cr,removingRemoteName:Dn,onCheckoutBranch:rt,onCreateBranch:ir,onRenameBranch:q,activeIdentityProfile:qn,availableIdentities:Ks,onSelectIdentity:ht,isApplyingIdentity:bt,isWorktreeMode:!!B,onOpenHistory:()=>qt("history"),onOpenGraph:()=>qt("graph"),onOpenStashes:xi,actionTabItems:ln,activeActionTab:ps,onSelectActionTab:Y=>Fs(Y)}),r&&(j?.mergeInProgress?.head||j?.rebaseInProgress?.headName||j?.rebaseInProgress?.onto)&&s.jsx(ev,{mergeInProgress:j?.mergeInProgress,rebaseInProgress:j?.rebaseInProgress,onContinue:Vr,onAbort:yi,onResolveWithAI:$r,hasUnresolvedConflicts:pr,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:Te("min-w-0 min-h-0 h-full flex flex-col"),children:s.jsxs(Wn,{as:Ga,ref:O,outerClassName:"flex-1 min-h-0",className:Te("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:[ps==="commit"?s.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(Ln?.length??0)>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s.jsx(Kx,{groups:Br,diffStats:j?.diffStats,revertingPaths:kt,isRevertingAll:Kt,onVisiblePathsChange:Oe,onRevertAll:Ar,onRevertDirectory:gi,headerBackgroundClassName:"bg-background"})}),s.jsx(qx,{stagedCount:Bn,commitMessage:we,onCommitMessageChange:G,generatedHighlights:is,onInsertHighlights:Zr,onGenerateMessage:js,isGeneratingMessage:jt,onCommit:()=>rr({pushAfter:!1}),onCommitAndPush:()=>rr({pushAfter:!0}),commitAction:He,hasPendingIndexMutation:Gt,gitmojiEnabled:ue,onOpenGitmojiPicker:()=>J(!0)})]}):s.jsx(ew,{onOpenStashes:()=>Ye(!0)})}):null,ps==="branch"?s.jsx("div",{className:"space-y-4",children:nn?s.jsxs(s.Fragment,{children:[s.jsx(tv,{mode:"inline",currentBranch:j?.current,localBranches:Tt,remoteBranches:Yt,defaultTargetBranch:Ls,onMerge:hr,onRebase:bi,disabled:Jr,isOperating:ye!==null,operationLogs:ct,onOperationComplete:Li}),un?s.jsx(Xy,{repoRoot:un.repoRoot,sourceBranch:un.sourceBranch,worktreeMetadata:un.worktreeMetadata,localBranches:Tt,defaultTargetBranch:rs,refreshKey:gt,onRefresh:()=>{r&&(te(r,n),re(r,n),Q(r,n,nt))}},un.worktreeMetadata.path):null]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})}):null,ps==="pr"?s.jsx("div",{className:"space-y-4",children:Sn?s.jsx(Hw,{directory:Sn.directory,branch:Sn.branch,baseBranch:ds,trackingBranch:j?.tracking??void 0,remotes:Ws,remoteBranches:Yt,onGeneratedDescription:es}):s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:e("gitView.pullRequest.title")}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:e("gitView.pullRequest.createHint")})]})}):null]})})})}),s.jsx(Ms,{open:os!==null,onOpenChange:Y=>{Y||qt(null)},children:s.jsxs(Es,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[s.jsxs(Gs,{children:[s.jsx(Vs,{children:e(os==="graph"?"gitView.graph.title":"gitView.history.title")}),s.jsx(an,{children:e("gitView.history.dialogDescription")})]}),s.jsx("div",{className:"flex-1 min-h-0",children:s.jsx(cw,{mode:os==="graph"?"graph":"history",log:os==="graph"?Is??E:E,isLogLoading:os==="graph"&&$s||z,logMaxCount:os==="graph"?Fn:nt,onLogMaxCountChange:os==="graph"?wi:rn,expandedCommitHashes:ls,onToggleCommit:fr,commitFilesMap:Ct,loadingCommitHashes:yt,onCopyHash:On,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:os==="graph"?null:Ge,onConflict:os==="graph"?mo:void 0,onActionSuccess:os==="graph"?_i:void 0})})]})}),s.jsx(Zy,{open:Be,onOpenChange:Ye,directory:r,hasUncommittedChanges:(j?.files?.length??0)>0,hasStagedChanges:pn.length>0,uncommittedFileCount:j?.files?.length??0,onChanged:async Y=>{r&&Y?.affectsIndex&&ie(r),await gs(!1),await Ts()}}),s.jsx(Ms,{open:Ae,onOpenChange:J,children:s.jsxs(Es,{className:"max-w-md p-0 overflow-hidden",children:[s.jsx(Gs,{className:"px-4 pt-4",children:s.jsx(Vs,{children:e("gitView.gitmoji.title")})}),s.jsxs($a,{className:"h-[420px]",children:[s.jsx(za,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:bs,onValueChange:fs}),s.jsxs(Wa,{children:[s.jsx(Ua,{children:e("gitView.gitmoji.empty")}),s.jsx(ui,{children:(ge.length===0?[]:ge.filter(Y=>{const Ce=bs.trim().toLowerCase();return Ce?Y.emoji.includes(Ce)||Y.code.toLowerCase().includes(Ce)||Y.description.toLowerCase().includes(Ce):!0})).map(Y=>s.jsxs(mi,{onSelect:()=>In(Y.emoji,Y.code),children:[s.jsx("span",{className:"text-lg",children:Y.emoji}),s.jsx("span",{className:"typography-ui-label text-foreground",children:Y.code}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:Y.description})]},Y.code))})]})]})]})}),r&&s.jsx(Gw,{open:Ht,onOpenChange:mt,conflictFiles:ms,directory:r,operation:Ns,onAbort:bn,onClearState:Xt}),s.jsx(Zw,{open:As,onOpenChange:Ps,operation:zs,targetBranch:Us,onConfirm:Bi})]}):s.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:e("gitView.empty.selectSessionOrDirectory")})})},sc=5e3,gv=(t,e)=>{if(!t)return 1;let n=1;for(let r=0;r<t.length;r+=1)if(t.charCodeAt(r)===10&&(n+=1,n>e))return n;return n},kl=(t,e)=>pg(gg.getState().dictionary,t,e),xv=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("file not found")||n.includes("not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")?"missing":"unreadable"},bv=async(t,e)=>{if(t.readFile)return(await t.readFile(e,{optional:!0})).content??"";const n=new URLSearchParams({path:e,optional:"true"}),r=await Cs(`/api/fs/read?${n.toString()}`,{cache:"no-store"});if(!r.ok){const o=await r.json().catch(()=>({error:r.statusText}));throw new Error(o.error||"Failed to read file")}return r.text()},zc=async(t,e)=>{try{const n=await bv(t,e);return gv(n,sc)>sc?{ok:!1,reason:"too-large"}:{ok:!0}}catch(n){return{ok:!1,reason:xv(n)}}},Wc=t=>{if(t==="too-large"){const e=sc.toLocaleString(to());return kl("contextFileOpen.failure.tooLarge",{count:e})}return kl(t==="missing"?"contextFileOpen.failure.missing":"contextFileOpen.failure.unreadable")},yv=t=>t.slice().sort((e,n)=>e.type!==n.type?e.type==="directory"?-1:1:e.name.localeCompare(n.name)),Rn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},Hm=(t,e)=>{const n=Rn(e),r=Rn(t).replace(/\/+$/,"");return n===r?".":!r||!n.startsWith(`${r}/`)?n:n.slice(r.length+1)},wv=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),vv=new Set(["node_modules"]),jv=t=>vv.has(t),Sv=t=>{const e=Rn(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},Nv=8,Rr=new Map,kv=t=>{const e=Rr.get(t);return e?(e.touchedAt=Date.now(),Rr.delete(t),Rr.set(t,e),e):null},Cl=t=>{const e=Rr.get(t);if(e)return e.touchedAt=Date.now(),e;if(Rr.size>=Nv){const r=Rr.keys().next().value;r!==void 0&&Rr.delete(r)}const n={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Rr.set(t,n),n},Cv=t=>{Rr.delete(t)},Gm=(t,e)=>s.jsx(Kr,{filePath:t,extension:e}),Av=t=>{const e=ft.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},Dv=t=>{const e=ft.c(73),{node:n,root:r,isExpanded:o,isActive:a,status:c,badge:l,permissions:d,downloadFile:f,onSelect:m,onToggle:u,onRevealPath:p,onOpenDialog:y}=t,{t:g}=Nt(),b=n.type==="directory",{canRename:x,canCreateFile:h,canCreateFolder:C,canDelete:w,canReveal:v}=d,[S,k]=i.useState(!1),[j,A]=i.useState(!1);let D;e[0]!==h||e[1]!==C||e[2]!==w||e[3]!==x||e[4]!==v?(D=pe=>{!x&&!h&&!C&&!w&&!v||(pe?.preventDefault(),A(!0))},e[0]=h,e[1]=C,e[2]=w,e[3]=x,e[4]=v,e[5]=D):D=e[5];const N=D;let B;e[6]!==b||e[7]!==n||e[8]!==m||e[9]!==u?(B=()=>{b?u(n.path):m(n)},e[6]=b,e[7]=n,e[8]=m,e[9]=u,e[10]=B):B=e[10];const T=B;let E;e[11]===Symbol.for("react.memo_cache_sentinel")?(E=pe=>{pe.stopPropagation(),A(!1),k(!0)},e[11]=E):E=e[11];const _=E;let R;e[12]!==h||e[13]!==C||e[14]!==w||e[15]!==x||e[16]!==v||e[17]!==f||e[18]!==b||e[19]!==n||e[20]!==y||e[21]!==p||e[22]!==g?(R=pe=>{const{Item:L,Separator:se}=pe;return s.jsxs(s.Fragment,{children:[x&&s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),y("rename",n)},children:[s.jsx(I,{name:"edit",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.rename")]}),s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),ur(n.path).then(je=>{if(je.ok){le.success(g("sidebarFilesTree.toast.pathCopied"));return}le.error(g("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.copyPath")]}),!b&&f&&s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),f(n.path).catch(je=>{console.error("Download failed:",je),le.error(g("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(I,{name:"download",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.save")]}),v&&s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),p(n.path)},children:[s.jsx(I,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",g(Dc())]}),b&&(h||C)&&s.jsxs(s.Fragment,{children:[s.jsx(se,{}),h&&s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),y("createFile",n)},children:[s.jsx(I,{name:"file-add",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.newFile")]}),C&&s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),y("createFolder",n)},children:[s.jsx(I,{name:"folder-add",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.newFolder")]})]}),w&&s.jsxs(s.Fragment,{children:[s.jsx(se,{}),s.jsxs(L,{onClick:Z=>{Z.stopPropagation(),y("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ",g("sidebarFilesTree.menu.delete")]})]})]})},e[12]=h,e[13]=C,e[14]=w,e[15]=x,e[16]=v,e[17]=f,e[18]=b,e[19]=n,e[20]=y,e[21]=p,e[22]=g,e[23]=R):R=e[23];const z=R;let V;e[24]!==n.path||e[25]!==r?(V=pe=>{const L=Hm(r,n.path);!L||L==="."||(pe.dataTransfer.setData("application/x-openchamber-file-path",L),pe.dataTransfer.effectAllowed="copy")},e[24]=n.path,e[25]=r,e[26]=V):V=e[26];const $=V;let M;e[27]!==N?(M=s.jsx("div",{className:"group relative flex items-center",onContextMenu:N}),e[27]=N,e[28]=M):M=e[28];const te=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let re;e[29]!==te?(re=Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",te,"cursor-grab active:cursor-grabbing"),e[29]=te,e[30]=re):re=e[30];let Q;e[31]!==b||e[32]!==o||e[33]!==n.extension||e[34]!==n.path?(Q=b?o?s.jsx(I,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(I,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Gm(n.path,n.extension),e[31]=b,e[32]=o,e[33]=n.extension,e[34]=n.path,e[35]=Q):Q=e[35];let H;e[36]!==n.name||e[37]!==n.path?(H=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:n.path,children:n.name}),e[36]=n.name,e[37]=n.path,e[38]=H):H=e[38];let X;e[39]!==b||e[40]!==c?(X=!b&&c&&s.jsx(Av,{status:c}),e[39]=b,e[40]=c,e[41]=X):X=e[41];let oe;e[42]!==l||e[43]!==b?(oe=b&&l&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[l.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",l.modified]}),l.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",l.added]})]}),e[42]=l,e[43]=b,e[44]=oe):oe=e[44];let fe;e[45]!==N||e[46]!==$||e[47]!==T||e[48]!==H||e[49]!==X||e[50]!==oe||e[51]!==re||e[52]!==Q?(fe=s.jsxs("button",{type:"button",onClick:T,onContextMenu:N,draggable:!0,onDragStart:$,className:re,children:[Q,H,X,oe]}),e[45]=N,e[46]=$,e[47]=T,e[48]=H,e[49]=X,e[50]=oe,e[51]=re,e[52]=Q,e[53]=fe):fe=e[53];let ve;e[54]!==h||e[55]!==C||e[56]!==w||e[57]!==x||e[58]!==v||e[59]!==S||e[60]!==z||e[61]!==g?(ve=(x||h||C||w||v)&&s.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:s.jsxs(tn,{open:S,onOpenChange:k,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Zs,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:_,title:g("sidebarFilesTree.actions.fileMenuTitle"),"aria-label":g("sidebarFilesTree.actions.fileMenuTitle"),children:s.jsx(I,{name:"more-2-fill",className:"h-4 w-4"})})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:g("sidebarFilesTree.actions.fileMenuTitle")})]}),s.jsx(en,{align:"end",side:"bottom",onCloseAutoFocus:()=>k(!1),children:z({Item:ws,Separator:Fr})})]})}),e[54]=h,e[55]=C,e[56]=w,e[57]=x,e[58]=v,e[59]=S,e[60]=z,e[61]=g,e[62]=ve):ve=e[62];let ie;e[63]!==fe||e[64]!==ve||e[65]!==M?(ie=s.jsxs(Oc,{render:M,children:[fe,ve]}),e[63]=fe,e[64]=ve,e[65]=M,e[66]=ie):ie=e[66];let Ne;e[67]!==z?(Ne=s.jsx(Mc,{className:"min-w-[180px]",children:z({Item:Fc,Separator:Cm})}),e[67]=z,e[68]=Ne):Ne=e[68];let K;return e[69]!==j||e[70]!==ie||e[71]!==Ne?(K=s.jsxs(Lc,{open:j,onOpenChange:A,children:[ie,Ne]}),e[69]=j,e[70]=ie,e[71]=Ne,e[72]=K):K=e[72],K},Iv=(t,e)=>t.node===e.node&&t.root===e.root&&t.isExpanded===e.isExpanded&&t.isActive===e.isActive&&t.status===e.status&&t.badge===e.badge&&t.permissions===e.permissions&&t.downloadFile===e.downloadFile&&t.onSelect===e.onSelect&&t.onToggle===e.onToggle&&t.onRevealPath===e.onRevealPath&&t.onOpenDialog===e.onOpenDialog,Pv=i.memo(Dv,Iv),Tv=()=>{const{t}=Nt(),{files:e}=Xn(),n=pi()??"",r=Rn(n.trim()),o=$f(),a=zf(),c=gc(P=>P.searchFiles),l=Ee(P=>P.openContextFile),d=Ka(n),[f,m]=i.useState(""),u=Ya(f,200),p=i.useRef(null),[y,g]=i.useState([]),[b,x]=i.useState(!1),[h,C]=i.useState({}),[w,v]=i.useState({}),S=i.useRef(new Set),k=i.useRef(new Set);i.useEffect(()=>{if(!r){C({}),v({}),S.current=new Set;return}const P=kv(r);P?(C({...P.childrenByDir}),v({...P.loadErrorsByDir}),S.current=new Set(P.loadedDirs)):(C({}),v({}),S.current=new Set)},[r]),i.useEffect(()=>{if(!r)return;const P=Cl(r);P.childrenByDir=h},[r,h]),i.useEffect(()=>{if(!r)return;const P=Cl(r);P.loadErrorsByDir=w},[r,w]),i.useEffect(()=>{if(!r)return;const P=Cl(r);P.loadedDirs=new Set(S.current)},[r,h,w]),i.useEffect(()=>()=>{if(!r)return;const P=Rr.get(r);P&&P.loadedDirs.size===0&&Object.keys(P.childrenByDir).length===0&&Cv(r)},[r]);const j=i.useMemo(()=>[],[]),A=i.useMemo(()=>[],[]),D=fn(P=>r?P.byRoot[r]?.expandedPaths??j:j),N=fn(P=>r?P.byRoot[r]?.selectedPath??null:null),B=fn(P=>P.setSelectedPath),T=fn(P=>P.addOpenPath),E=fn(P=>P.removeOpenPathsByPrefix),_=fn(P=>P.toggleExpandedPath),R=Ee(P=>r?P.contextPanelByDirectory[r]?.tabs??A:A),z=i.useMemo(()=>new Set(R.map(P=>P.mode==="file"?P.targetPath:null).filter(P=>typeof P=="string"&&P.length>0).map(P=>Rn(P))),[R]),[V,$]=i.useState(null),[M,te]=i.useState(null),[re,Q]=i.useState(""),[H,X]=i.useState(!1),oe=!!e.writeFile,fe=!!e.createDirectory,ve=!!e.rename,ie=!!e.delete,Ne=!!e.revealPath,K=i.useMemo(()=>({canRename:ve,canCreateFile:oe,canCreateFolder:fe,canDelete:ie,canReveal:Ne}),[ve,oe,fe,ie,Ne]),pe=i.useCallback(P=>{e.revealPath&&e.revealPath(P).catch(()=>{le.error(t("sidebarFilesTree.toast.revealFailed"))})},[e,t]),L=i.useCallback((P,F)=>{$(P),te(F),Q(P==="rename"&&F.name||""),X(!1)},[]),se=i.useCallback((P,F)=>{const ue=F.filter(be=>be&&typeof be.name=="string"&&be.name.length>0).filter(be=>o||!be.name.startsWith(".")).filter(be=>a||!jv(be.name)).map(be=>{const W=be.name,ge=Rn(be.path||""),we=ge?wv(ge)?ge:Rn(`${P}/${ge}`):Rn(`${P}/${W}`),G=be.isDirectory?"directory":"file",Se=G==="file"&&W.includes(".")?W.split(".").pop()?.toLowerCase():void 0;return{name:W,path:we,type:G,extension:Se}});return yv(ue)},[a,o]),Z=i.useCallback(async(P,F)=>{const ue=Rn(P.trim());if(!ue||S.current.has(ue)||k.current.has(ue))return;k.current=new Set(k.current),k.current.add(ue);const be=e.listDirectory?e.listDirectory(ue).then(W=>W.entries.map(ge=>({name:ge.name,path:ge.path,isDirectory:ge.isDirectory}))):Jn.listLocalDirectory(ue).then(W=>W.map(ge=>({name:ge.name,path:ge.path,isDirectory:ge.isDirectory})));try{const W=await be;if(F?.())return;const ge=se(ue,W);S.current=new Set(S.current),S.current.add(ue),v(we=>{if(!we[ue])return we;const G={...we};return delete G[ue],G}),C(we=>({...we,[ue]:ge}))}catch(W){if(F?.())return;const ge=W instanceof Error?W.message:String(W??"");console.error("Failed to load sidebar directory:",W),v(we=>({...we,[ue]:ge}))}finally{k.current=new Set(k.current),k.current.delete(ue)}},[e,se]),je=i.useCallback(async()=>{r&&(S.current=new Set,k.current=new Set,v({}),C(P=>Object.keys(P).length===0?P:{}),await Z(r))},[Z,r]),De=i.useCallback(async P=>{if(!P){await je();return}const F=Rn(P);S.current=new Set(S.current),S.current.delete(F),k.current=new Set(k.current),k.current.delete(F),await Z(F)},[Z,je]);i.useEffect(()=>{r&&(S.current=new Set,k.current=new Set,v({}),C(P=>Object.keys(P).length===0?P:{}),Z(r))},[Z,r,o,a]),i.useEffect(()=>{if(!r||D.length===0)return;const P=D.map(be=>Rn(be)).filter(be=>!!be&&be!==r&&be.startsWith(`${r}/`)&&!S.current.has(be)&&!k.current.has(be)).sort((be,W)=>be.split("/").length-W.split("/").length);if(P.length===0)return;let F=!1;const ue=()=>F;return(async()=>{for(let be=0;be<P.length&&!F;be+=3){const W=P.slice(be,be+3);await Promise.all(W.map(ge=>Z(ge,ue)))}})(),()=>{F=!0}},[D,Z,r]),i.useEffect(()=>{if(!n){g([]),x(!1);return}const P=u.trim();if(!P){g([]),x(!1);return}let F=!1;return x(!0),c(n,P,150,{includeHidden:o,respectGitignore:!a,type:"file"}).then(ue=>{if(F)return;const W=ue.filter(ge=>a||!Sv(ge.path)).map(ge=>({name:ge.name,path:Rn(ge.path),type:"file",extension:ge.extension,relativePath:ge.relativePath}));g(W)}).catch(()=>{F||g([])}).finally(()=>{F||x(!1)}),()=>{F=!0}},[n,u,c,o,a]);const Le=i.useMemo(()=>{const P=new Map;if(!d?.files)return P;for(const F of d.files)F.index==="A"||F.working_dir==="?"?P.set(F.path,"git-added"):F.index==="D"?P.set(F.path,"git-deleted"):(F.index==="M"||F.working_dir==="M")&&P.set(F.path,"git-modified");return P},[d]),Me=i.useMemo(()=>{const P=new Map;if(!d?.files||!r)return P;for(const F of d.files){const ue=F.index==="M"||F.working_dir==="M",be=F.index==="A"||F.working_dir==="?";if(!ue&&!be)continue;const W=F.path.split("/");if(W.length<=1)continue;let ge=r;for(let we=0;we<W.length-1;we++){ge=`${ge}/${W[we]}`;let G=P.get(ge);G||(G={modified:0,added:0},P.set(ge,G)),ue&&G.modified++,be&&G.added++}}return P},[d,r]),Fe=i.useCallback(P=>{if(z.has(P))return"open";if(Le.size===0)return null;const F=P.startsWith(r+"/")?P.slice(r.length+1):P;return Le.get(F)??null},[z,Le,r]),he=i.useCallback(P=>{if(Me.size===0)return null;const F=Me.get(P);return F&&F.modified+F.added>0?F:null},[Me]),Ie=i.useCallback(async P=>{if(!r)return;const F=await zc(e,P.path);if(!F.ok){le.error(Wc(F.reason));return}B(r,P.path),T(r,P.path),l(r,P.path)},[T,e,l,r,B]),me=i.useCallback(async P=>{const F=Rn(P);r&&(_(r,F),S.current.has(F)||await Z(F))},[Z,r,_]),ce=i.useCallback(async P=>{if(P?.preventDefault(),!M||!V)return;X(!0);const F=()=>X(!1),ue=()=>$(null);if(V==="createFile"){if(!re.trim()){le.error(t("sidebarFilesTree.toast.filenameRequired")),F();return}if(!e.writeFile){le.error(t("sidebarFilesTree.toast.writeNotSupported")),F();return}const be=M.path,W=be?`${be}/`:"",ge=Rn(`${W}${re.trim()}`);await e.writeFile(ge,"").then(async we=>{we.success&&(le.success(t("sidebarFilesTree.toast.fileCreated")),await De(be)),ue()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(F);return}if(V==="createFolder"){if(!re.trim()){le.error(t("sidebarFilesTree.toast.folderNameRequired")),F();return}const be=M.path,W=be?`${be}/`:"",ge=Rn(`${W}${re.trim()}`);await e.createDirectory(ge).then(async we=>{we.success&&(le.success(t("sidebarFilesTree.toast.folderCreated")),await De(be)),ue()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(F);return}if(V==="rename"){if(!re.trim()){le.error(t("sidebarFilesTree.toast.nameRequired")),F();return}if(!e.rename){le.error(t("sidebarFilesTree.toast.renameNotSupported")),F();return}const be=M.path,W=be.split("/").slice(0,-1).join("/"),ge=W?`${W}/`:"",we=Rn(`${ge}${re.trim()}`);await e.rename(be,we).then(async G=>{G.success&&(le.success(t("sidebarFilesTree.toast.renamedSuccessfully")),await De(W),r&&E(r,be),(N===be||N&&N.startsWith(`${be}/`))&&B(r,null)),ue()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(F);return}if(V==="delete"){if(!e.delete){le.error(t("sidebarFilesTree.toast.deleteNotSupported")),F();return}const be=M.path,W=be.split("/").slice(0,-1).join("/");await e.delete(be).then(async ge=>{ge.success&&(le.success(t("sidebarFilesTree.toast.deletedSuccessfully")),await De(W),r&&E(r,be),(N===be||N&&N.startsWith(be+"/"))&&B(r,null)),ue()}).catch(()=>le.error(t("sidebarFilesTree.toast.operationFailed"))).finally(F);return}F()},[V,M,re,e,De,E,r,N,B,t]);function xe(P,F){const ue=h[P]??[];return ue.map((be,W)=>{const ge=be.type==="directory",we=ge&&D.includes(be.path),G=N===be.path,Se=W===ue.length-1;return s.jsxs("li",{className:"relative",children:[F>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Se&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),s.jsx(Pv,{node:be,root:r,isExpanded:we,isActive:G,status:ge?void 0:Fe(be.path),badge:ge?he(be.path):void 0,permissions:K,downloadFile:e.downloadFile,onSelect:Ie,onToggle:me,onRevealPath:pe,onOpenDialog:L}),ge&&we&&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(Ve,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{De(be.path)},children:[s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):null,xe(be.path,F+1)]})]},be.path)})}const ke=!!(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(I,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),s.jsx(vn,{ref:p,value:f,onChange:P=>m(P.target.value),placeholder:t("sidebarFilesTree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),f.trim().length>0?s.jsx("button",{type:"button","aria-label":t("sidebarFilesTree.search.clearAria"),className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{m(""),p.current?.focus()},children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null]}),oe&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>L("createFile",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFileTitle"),"aria-label":t("sidebarFilesTree.actions.newFileTitle"),children:s.jsx(I,{name:"file-add",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFileTitle")})]}),fe&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>L("createFolder",{path:n,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.newFolderTitle"),"aria-label":t("sidebarFilesTree.actions.newFolderTitle"),children:s.jsx(I,{name:"folder-add",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.newFolderTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>{je()},className:"h-8 w-8 p-0 flex-shrink-0",title:t("sidebarFilesTree.actions.refreshTitle"),"aria-label":t("sidebarFilesTree.actions.refreshTitle"),children:s.jsx(I,{name:"refresh",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:t("sidebarFilesTree.actions.refreshTitle")})]})]}),s.jsx(Wn,{outerClassName:"flex-1 min-h-0",className:"p-2",children:s.jsx("ul",{className:"flex flex-col",children:b?s.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"}),t("sidebarFilesTree.state.searching")]}):y.length>0?y.map(P=>{const F=N===P.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>Ie(P),draggable:!0,onDragStart:ue=>{const be=P.relativePath||Hm(r??"",P.path);!be||be==="."||(ue.dataTransfer.setData("application/x-openchamber-file-path",be),ue.dataTransfer.effectAllowed="copy")},className:Te("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",F?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:P.path,children:[Gm(P.path,P.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:P.relativePath??P.path})]})},P.path)}):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(Ve,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{je()},children:[s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"}),t("sidebarFilesTree.actions.refreshTitle")]})]}):ke&&r?xe(r,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:t("sidebarFilesTree.state.loading")})})}),s.jsx(Ms,{open:!!V,onOpenChange:P=>!P&&$(null),children:s.jsxs(Es,{children:[s.jsxs(Gs,{children:[s.jsxs(Vs,{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(an,{children:[V==="createFile"&&t("sidebarFilesTree.dialog.createFile.description",{path:M?.path??t("sidebarFilesTree.dialog.rootFallback")}),V==="createFolder"&&t("sidebarFilesTree.dialog.createFolder.description",{path:M?.path??t("sidebarFilesTree.dialog.rootFallback")}),V==="rename"&&t("sidebarFilesTree.dialog.rename.description",{name:M?.name??""}),V==="delete"&&t("sidebarFilesTree.dialog.delete.description",{name:M?.name??""})]})]}),V!=="delete"&&s.jsx("div",{className:"py-4",children:s.jsx(vn,{value:re,onChange:P=>Q(P.target.value),placeholder:t(V==="rename"?"sidebarFilesTree.dialog.rename.placeholder":"sidebarFilesTree.dialog.namePlaceholder"),onKeyDown:P=>{P.key==="Enter"&&ce()},autoFocus:!0})}),s.jsxs(nr,{children:[s.jsx(Ve,{variant:"outline",onClick:()=>$(null),disabled:H,children:t("sidebarFilesTree.dialog.cancel")}),s.jsx(Ve,{variant:V==="delete"?"destructive":"default",onClick:()=>{ce()},disabled:H||V!=="delete"&&!re.trim(),children:H?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):t(V==="delete"?"sidebarFilesTree.dialog.delete.confirm":"sidebarFilesTree.dialog.confirm")})]})]})})]})},Rv=t=>t==="git"||t==="files"||t==="context",Ev="files",Mv=()=>!(typeof document<"u"&&document.hidden||typeof navigator<"u"&&!navigator.onLine);function Fv(t,e,n,r){const o=ft.c(6),{git:a}=Xn(),c=wn(Ov),l=!!(t&&a&&e&&n==="git"&&r!=="git");let d,f;o[0]!==t||o[1]!==c||o[2]!==a||o[3]!==l?(d=()=>{if(!l||!t||!a)return;c(t,a);const m=window.setInterval(()=>{Mv()&&c(t,a)},1e4);return()=>window.clearInterval(m)},f=[l,t,a,c],o[0]=t,o[1]=c,o[2]=a,o[3]=l,o[4]=d,o[5]=f):(d=o[4],f=o[5]),i.useEffect(d,f)}function Ov(t){return t.ensureStatus}const Km=()=>{const t=ft.c(17),e=Ss(Bv),n=Ss(_v),r=Ys(Vv),o=wn($v);let a;e:{if(e){let g;t[0]!==e||t[1]!==n?(g=n.find(b=>b.id===e)??n[0]??null,t[0]=e,t[1]=n,t[2]=g):g=t[2],a=g;break e}a=n[0]??null}const c=a;let l;e:{if(!c){l=null;break e}let g;t[3]!==c.id||t[4]!==c.path?(g={id:c.id,path:c.path},t[3]=c.id,t[4]=c.path,t[5]=g):g=t[5],l=g}const d=l;let f;e:{if(!c){f=null;break e}let g;t[6]!==c.label||t[7]!==c.path||t[8]!==r?(g=c.label?.trim()||Oi(c.path,r)||c.path,t[6]=c.label,t[7]=c.path,t[8]=r,t[9]=g):g=t[9],f=g}const m=f;let u;e:{if(!c){u=!1;break e}let g;t[10]!==c.path||t[11]!==o?(g=o.get(c.path)?.isGitRepo,t[10]=c.path,t[11]=o,t[12]=g):g=t[12],u=g===!0}const p=u;let y;return t[13]!==p||t[14]!==m||t[15]!==d?(y=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(Ty,{projectRef:d,projectLabel:m,canCreateWorktree:p})}),t[13]=p,t[14]=m,t[15]=d,t[16]=y):y=t[16],y},Lv=()=>{const t=ft.c(57),{t:e}=Nt(),n=Ee(zv),r=Ee(Wv),o=Ee(Uv),a=Ee(Hv),c=pi();Fv(c,o,n,a);const l=a==="git"?"git":a==="context"?"context":null;let d,f;t[0]!==l||t[1]!==n||t[2]!==r?(d=()=>{l&&n===l&&r(Ev)},f=[l,n,r],t[0]=l,t[1]=n,t[2]=r,t[3]=d,t[4]=f):(d=t[3],f=t[4]),i.useEffect(d,f);let m;t[5]!==e?(m=e("layout.rightSidebar.git"),t[5]=e,t[6]=m):m=t[6];let u;t[7]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5"}),t[7]=u):u=t[7];let p;t[8]!==m?(p={id:"git",label:m,icon:u},t[8]=m,t[9]=p):p=t[9];let y;t[10]!==e?(y=e("layout.rightSidebar.files"),t[10]=e,t[11]=y):y=t[11];let g;t[12]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(I,{name:"folder-3",className:"h-3.5 w-3.5"}),t[12]=g):g=t[12];let b;t[13]!==y?(b={id:"files",label:y,icon:g},t[13]=y,t[14]=b):b=t[14];let x;t[15]!==e?(x=e("layout.rightSidebar.context"),t[15]=e,t[16]=x):x=t[16];let h;t[17]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(I,{name:"file-list-2",className:"h-3.5 w-3.5"}),t[17]=h):h=t[17];let C;t[18]!==x?(C={id:"context",label:x,icon:h},t[18]=x,t[19]=C):C=t[19];let w;t[20]!==C||t[21]!==p||t[22]!==b?(w=[p,b,C],t[20]=C,t[21]=p,t[22]=b,t[23]=w):w=t[23];const v=w;let S;t[24]!==l||t[25]!==v?(S=l?v.filter(oe=>oe.id!==l):v,t[24]=l,t[25]=v,t[26]=S):S=t[26];const k=S,j=o&&n==="git"&&l!=="git";let A;t[27]!==r?(A=oe=>{Rv(oe)&&r(oe)},t[27]=r,t[28]=A):A=t[28];const D=A;let N;t[29]!==D||t[30]!==n||t[31]!==k?(N=s.jsx("div",{className:"h-9 bg-background pt-1 px-2",children:s.jsx(Ro,{items:k,activeId:n,onSelect:D,layoutMode:"fit",variant:"active-pill",className:"h-full"})}),t[29]=D,t[30]=n,t[31]=k,t[32]=N):N=t[32];const B=n!=="git"&&"hidden";let T;t[33]!==B?(T=Te("h-full",B),t[33]=B,t[34]=T):T=t[34];let E;t[35]!==j?(E=s.jsx(tc,{isActive:j}),t[35]=j,t[36]=E):E=t[36];let _;t[37]!==T||t[38]!==E?(_=s.jsx("div",{className:T,children:E}),t[37]=T,t[38]=E,t[39]=_):_=t[39];const R=n!=="files"&&"hidden";let z;t[40]!==R?(z=Te("h-full",R),t[40]=R,t[41]=z):z=t[41];let V;t[42]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsx(Tv,{}),t[42]=V):V=t[42];let $;t[43]!==z?($=s.jsx("div",{className:z,children:V}),t[43]=z,t[44]=$):$=t[44];const M=n!=="context"&&"hidden";let te;t[45]!==M?(te=Te("h-full",M),t[45]=M,t[46]=te):te=t[46];let re;t[47]===Symbol.for("react.memo_cache_sentinel")?(re=s.jsx(Km,{}),t[47]=re):re=t[47];let Q;t[48]!==te?(Q=s.jsx("div",{className:te,children:re}),t[48]=te,t[49]=Q):Q=t[49];let H;t[50]!==_||t[51]!==$||t[52]!==Q?(H=s.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[_,$,Q]}),t[50]=_,t[51]=$,t[52]=Q,t[53]=H):H=t[53];let X;return t[54]!==N||t[55]!==H?(X=s.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden bg-background",children:[N,H]}),t[54]=N,t[55]=H,t[56]=X):X=t[56],X};function Bv(t){return t.activeProjectId}function _v(t){return t.projects}function Vv(t){return t.homeDirectory}function $v(t){return t.directories}function zv(t){return t.rightSidebarTab}function Wv(t){return t.setRightSidebarTab}function Uv(t){return t.isRightSidebarOpen}function Hv(t){return t.activeMainTab}const Gv=64,Kv=3,Si=new Map,qv=(t,e,n=Kv)=>{const r=`${t}\0${n}\0${e}`,o=Si.get(r);if(o)return Si.delete(r),Si.set(r,o),o;const a=Qv(e),c=a?Wh(Uh(e,n),{oldFile:{name:t,contents:a.before},newFile:{name:t,contents:a.after}})??Ru(t):Hh(Yv(t,e))[0]?.files[0]??Ru(t);for(Si.set(r,c);Si.size>Gv;){const l=Si.keys().next().value;if(!l)break;Si.delete(l)}return c},Yv=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
|
|
14
|
-
===================================================================
|
|
15
|
-
--- ${t}
|
|
16
|
-
+++ ${t}
|
|
17
|
-
${e}`,Qv=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(t))return;const e=[...t.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(e.length!==1)return;const n=e[0],r=Number.parseInt(n[1]??"",10),o=Number.parseInt(n[2]??"",10);if(r>1||o>1||!Number.isFinite(r)||!Number.isFinite(o))return;const a=(n.index??0)+n[0].length,c=t.slice(a),l=[],d=[];let f;for(const m of c.split(/\r?\n/)){if(m.startsWith("diff --git ")||m.startsWith("@@ "))break;if(m.startsWith("\\")){if(f==="-"||f===" "){const u=l.at(-1);u&&(u.newline=!1)}if(f==="+"||f===" "){const u=d.at(-1);u&&(u.newline=!1)}continue}if(m.startsWith("-")){l.push({text:m.slice(1),newline:!0}),f="-";continue}if(m.startsWith("+")){d.push({text:m.slice(1),newline:!0}),f="+";continue}m.startsWith(" ")&&(l.push({text:m.slice(1),newline:!0}),d.push({text:m.slice(1),newline:!0}),f=" ")}return{before:Tu(l),after:Tu(d)}},Tu=t=>t.map(e=>e.text+(e.newline?`
|
|
18
|
-
`:"")).join(""),Ru=t=>Gh({name:t,contents:""},{name:t,contents:""}),Eu=t=>{if(!t)return null;const e=t.split(`
|
|
19
|
-
`);let n=null;for(const r of e){const o=r.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(o){const a=Number.parseInt(o[1]??"",10);n=Number.isFinite(a)&&a>=1?a:null;continue}if(n!==null){if(r.startsWith(" ")){n+=1;continue}if(r.startsWith("+"))return n;if(r.startsWith("-"))return Math.max(1,n)}}return null},Jv=1100,Xv=15e3,Mu=500,Fu=300,Zv=1e6,e1=3,t1=t=>t<=6?t:t<=12?6:t<=25?4:2,s1=i.memo(()=>{const t=ft.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}),qm={"?":{code:"?",color:"var(--status-info)",descriptionKey:"diffView.change.untracked"},A:{code:"A",color:"var(--status-success)",descriptionKey:"diffView.change.new"},D:{code:"D",color:"var(--status-error)",descriptionKey:"diffView.change.deleted"},R:{code:"R",color:"var(--status-info)",descriptionKey:"diffView.change.renamed"},C:{code:"C",color:"var(--status-info)",descriptionKey:"diffView.change.copied"},M:{code:"M",color:"var(--status-warning)",descriptionKey:"diffView.change.modified"}},n1=qm.M,r1=t=>{const e=t.index?.trim(),n=t.working_dir?.trim();return e&&e!=="?"?e.charAt(0):n?n.charAt(0):e?.charAt(0)||n?.charAt(0)||"M"},Ym=t=>{const e=r1(t);return qm[e]??n1},i1=t=>{const{index:e,working_dir:n}=t;return e==="A"||n==="A"||e==="?"||n==="?"},Ou=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},Lu=t=>!!t.working_dir?.trim()||t.index==="?",o1=(t,e)=>yg(t,e),Bu=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),_u=(t,e)=>{const n=t.split(`
|
|
20
|
-
`),r=e.split(`
|
|
21
|
-
`),o=Math.min(n.length,r.length);for(let a=0;a<o;a+=1)if(n[a]!==r[a])return a+1;return r.length>n.length?n.length+1:n.length>r.length?Math.max(1,r.length):1},a1=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),l1=(t,e,n)=>a1(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:n}:{original:"",modified:"",patch:e,fileDiff:qv(t,e),contextMode:n},Qm=(t,e,n)=>{const r=t??0,o=e??0;return!r&&!o?null:s.jsxs("span",{className:Te("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]})},c1=i.memo(t=>{const e=ft.c(43),{scope:n,workingCount:r,stagedCount:o,onScopeChange:a}=t,{t:c}=Nt(),[l,d]=i.useState(!1),f=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 u=m;let p;e[3]!==c?(p=c("diffView.scope.selectorAria"),e[3]=c,e[4]=p):p=e[4];let y;e[5]!==f?(y=s.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",f]}),e[5]=f,e[6]=y):y=e[6];let g;e[7]!==u||e[8]!==y?(g=s.jsxs("span",{className:"whitespace-nowrap",children:[u,y]}),e[7]=u,e[8]=y,e[9]=g):g=e[9];let b;e[10]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx(I,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"}),e[10]=b):b=e[10];let x;e[11]!==p||e[12]!==g?(x=s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":p,children:[g,b]})}),e[11]=p,e[12]=g,e[13]=x):x=e[13];let h;e[14]!==a?(h=T=>{(T==="working"||T==="staged")&&(a?.(T),d(!1))},e[14]=a,e[15]=h):h=e[15];let C;e[16]!==c?(C=c("diffView.scope.changed"),e[16]=c,e[17]=C):C=e[17];let w;e[18]!==C?(w=s.jsx("span",{children:C}),e[18]=C,e[19]=w):w=e[19];let v;e[20]!==r?(v=s.jsx("span",{className:"typography-meta text-muted-foreground",children:r}),e[20]=r,e[21]=v):v=e[21];let S;e[22]!==v||e[23]!==w?(S=s.jsx(Td,{value:"working",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[w,v]})}),e[22]=v,e[23]=w,e[24]=S):S=e[24];let k;e[25]!==c?(k=c("diffView.scope.staged"),e[25]=c,e[26]=k):k=e[26];let j;e[27]!==k?(j=s.jsx("span",{children:k}),e[27]=k,e[28]=j):j=e[28];let A;e[29]!==o?(A=s.jsx("span",{className:"typography-meta text-muted-foreground",children:o}),e[29]=o,e[30]=A):A=e[30];let D;e[31]!==j||e[32]!==A?(D=s.jsx(Td,{value:"staged",children:s.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[j,A]})}),e[31]=j,e[32]=A,e[33]=D):D=e[33];let N;e[34]!==n||e[35]!==S||e[36]!==D||e[37]!==h?(N=s.jsx(en,{align:"start",className:"w-40",children:s.jsxs(wg,{value:n,onValueChange:h,children:[S,D]})}),e[34]=n,e[35]=S,e[36]=D,e[37]=h,e[38]=N):N=e[38];let B;return e[39]!==l||e[40]!==N||e[41]!==x?(B=s.jsxs(tn,{open:l,onOpenChange:d,children:[x,N]}),e[39]=l,e[40]=N,e[41]=x,e[42]=B):B=e[42],B}),d1=i.memo(t=>{const e=ft.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=f=>{const m=Ym(f),u=r===f.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>o(f.path),className:Te("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",u?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[s.jsx(Kr,{filePath:f.path,className:"h-3.5 w-3.5 flex-shrink-0"}),s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:m.color},title:a(m.descriptionKey),"aria-label":a(m.descriptionKey),children:m.code}),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:f.path,children:f.path}),Qm(f.insertions,f.deletions)]})},f.path)},e[5]=o,e[6]=r,e[7]=a,e[8]=d):d=e[8],c=n.map(d),e[0]=n,e[1]=o,e[2]=r,e[3]=a,e[4]=c}else c=e[4];let l;return e[9]!==c?(l=s.jsx(Wn,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:s.jsx("ul",{className:"flex flex-col gap-1",children:c})}),e[9]=c,e[10]=l):l=e[10],l}),u1=i.memo(t=>{const e=ft.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",f=o?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m={contain:"layout"},e[0]=m):m=e[0];let u;e[1]!==r.original||e[2]!==n||e[3]!==c||e[4]!==f||e[5]!==o||e[6]!==a?(u=c&&s.jsxs("div",{className:f,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a("diffView.image.original")}),s.jsx("img",{src:r.original,alt:a("diffView.image.originalAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[1]=r.original,e[2]=n,e[3]=c,e[4]=f,e[5]=o,e[6]=a,e[7]=u):u=e[7];let p;e[8]!==r.modified||e[9]!==n||e[10]!==l||e[11]!==c||e[12]!==f||e[13]!==o||e[14]!==a?(p=l&&s.jsxs("div",{className:f,children:[s.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a(c?"diffView.image.modified":"diffView.image.new")}),s.jsx("img",{src:r.modified,alt:a("diffView.image.modifiedAlt",{path:n}),className:o?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),e[8]=r.modified,e[9]=n,e[10]=l,e[11]=c,e[12]=f,e[13]=o,e[14]=a,e[15]=p):p=e[15];let y;return e[16]!==d||e[17]!==u||e[18]!==p?(y=s.jsx("div",{className:"w-full overflow-auto p-4",style:m,children:s.jsxs("div",{className:d,children:[u,p]})}),e[16]=d,e[17]=u,e[18]=p,e[19]=y):y=e[19],y}),f1=i.memo(t=>{const e=ft.c(16),{filePath:n,diff:r,renderSideBySide:o,wrapLines:a}=t;let c;e[0]!==n?(c=Ti(n)||"text",e[0]=n,e[1]=c):c=e[1];const l=c;if(r.isBinary){let m;return e[2]===Symbol.for("react.memo_cache_sentinel")?(m=s.jsx(s1,{}),e[2]=m):m=e[2],m}if(Ri(n)){let m;return e[3]!==r||e[4]!==n||e[5]!==o?(m=s.jsx(u1,{filePath:n,diff:r,renderSideBySide:o}),e[3]=r,e[4]=n,e[5]=o,e[6]=m):m=e[6],m}let d;e[7]===Symbol.for("react.memo_cache_sentinel")?(d={contain:"layout"},e[7]=d):d=e[7];let f;return e[8]!==r.fileDiff||e[9]!==r.modified||e[10]!==r.original||e[11]!==n||e[12]!==l||e[13]!==o||e[14]!==a?(f=s.jsx("div",{className:"w-full",style:d,children:s.jsx(km,{original:r.original,modified:r.modified,fileDiff:r.fileDiff,language:l,fileName:n,renderSideBySide:o,wrapLines:a,layout:"inline"})}),e[8]=r.fileDiff,e[9]=r.modified,e[10]=r.original,e[11]=n,e[12]=l,e[13]=o,e[14]=a,e[15]=f):f=e[15],f}),m1=i.memo(t=>{const e=ft.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(Al,{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(Al,{label:l("gitView.changes.revertFileAria",{path:n}),icon:"arrow-go-back",loading:o==="discard",disabled:a,tone:"failure",onClick:()=>c("discard")}),s.jsx(Al,{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}),Al=t=>{const e=ft.c(14),{label:n,icon:r,loading:o,disabled:a,tone:c,onClick:l}=t,d=c==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",f=c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]";let m;e[0]!==d||e[1]!==f?(m=Te("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",d,f),e[0]=d,e[1]=f,e[2]=m):m=e[2];let u;e[3]!==l?(u=g=>{g.stopPropagation(),l()},e[3]=l,e[4]=u):u=e[4];let p;e[5]!==r||e[6]!==o?(p=o?s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(I,{name:r,className:r==="add"?"size-4":"size-3.5"}),e[5]=r,e[6]=o,e[7]=p):p=e[7];let y;return e[8]!==a||e[9]!==n||e[10]!==m||e[11]!==u||e[12]!==p?(y=s.jsx(Ve,{variant:"ghost",size:"sm",className:m,disabled:a,title:n,"aria-label":n,onClick:u,children:p}),e[8]=a,e[9]=n,e[10]=m,e[11]=u,e[12]=p,e[13]=y):y=e[13],y},h1=i.memo(({directory:t,file:e,layout:n,wrapLines:r,isSelected:o,isExpanded:a,isMounted:c,onSelect:l,onExpandedChange:d,registerSectionRef:f,showOpenInEditorAction:m=!1,isOpeningInEditor:u=!1,onOpenInEditor:p,staged:y=!1,loadFullFiles:g=!1})=>{const{t:b}=Nt(),{git:x}=Xn(),h=wn(i.useCallback(L=>L.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),C=wn(L=>L.setDiff),w=wn(L=>L.fetchStatus),v=Ee(L=>L.setDiffFileLayout),[S,k]=i.useState(0),[j,A]=i.useState(null),[D,N]=i.useState(!1),[B,T]=i.useState(null),[E,_]=i.useState(!1),[R,z]=i.useState(null),[V,$]=i.useState(null),M=i.useRef(null),te=i.useRef(null),re=i.useMemo(()=>Ym(e),[e]),Q=n==="side-by-side",H=g?"full":"patch",X=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,oe=i.useMemo(()=>y?V:R||(h?{original:h.original,modified:h.modified,isBinary:h.isBinary,contextMode:"full"}:null),[h,R,y,V]),fe=oe?.contextMode===H,ve=i.useCallback(L=>{te.current=L,f(e.path,L)},[e.path,f]),ie=i.useCallback(L=>{d(e.path,L)},[e.path,d]),Ne=i.useCallback(()=>{l(e.path)},[e.path,l]);i.useEffect(()=>{y?$(null):z(null),A(null),M.current=null},[X,y]),i.useEffect(()=>{if(!a||!c)return;if(!t||oe&&fe){M.current=null,N(!1);return}const L=`${t}::${e.path}::${y?"staged":"unstaged"}::${X}::${H}::${S}`;if(M.current===L)return;M.current=L,A(null),N(!0);let se=!1;const Z=g?Zv:e1,je=Ri(e.path)?x.getGitFileDiff(t,{path:e.path,staged:y}):x.getGitDiff(t,{path:e.path,staged:y,contextLines:Z}),De=Xv,Le=new Promise((Me,Fe)=>{setTimeout(()=>Fe(new Error(`Timed out after ${De}ms`)),De)});return Promise.race([je,Le]).then(Me=>{if(!se){if("diff"in Me){const Fe=l1(e.path,Me.diff,H);y?$(Fe):z(Fe)}else{const Fe={original:Me.original??"",modified:Me.modified??"",isBinary:Me.isBinary,contextMode:"full"};y?$(Fe):C(t,e.path,Fe)}N(!1)}}).catch(Me=>{if(se)return;const Fe=Me instanceof Error?Me.message:String(Me);A(Fe),N(!1)}),()=>{se=!0,M.current===L&&(M.current=null)}},[H,oe,fe,S,t,e.path,X,x,a,c,g,C,y]);const K=i.useCallback(()=>{ie(!a),Ne()},[ie,Ne,a]),pe=i.useCallback(async L=>{if(!(!t||B!==null)){T(L);try{L==="stage"?await x.stageGitFile(t,e.path):L==="unstage"?await x.unstageGitFile(t,e.path):await x.revertGitFile(t,e.path,{scope:"working"}),k(se=>se+1),await w(t,x)}catch(se){const Z=L==="unstage"?"gitView.toast.unstageFileFailed":L==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.revertFailed";le.error(se instanceof Error?se.message:b(Z))}finally{T(se=>se===L?null:se)}}},[t,w,e.path,B,x,b]);return s.jsxs("div",{ref:ve,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:K,onKeyDown:L=>{L.target===L.currentTarget&&(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),K())},className:Te("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",o?"bg-[var(--interactive-selection)]/35":null),children:[s.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),s.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[s.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:a?s.jsx(I,{name:"arrow-down-s",className:"size-4"}):s.jsx(I,{name:"arrow-right-s",className:"size-4"})}),s.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:re.color},title:b(re.descriptionKey),"aria-label":b(re.descriptionKey),children:re.code}),s.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:e.path,children:s.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(Kr,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const L=e.path.lastIndexOf("/");if(L===-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,L),Z=e.path.slice(L+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:Z})]})]})})()]})})]}),s.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[Qm(e.insertions,e.deletions),m&&p?s.jsx(Ve,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:b("diffView.actions.openFileInEditorAtChange"),onClick:L=>{L.stopPropagation(),p(e.path,oe)},disabled:u,children:u?s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(I,{name:"edit",className:"size-3.5"})}):null,s.jsx(rm,{mode:Q?"side-by-side":"unified",onModeChange:L=>{const se=L==="side-by-side"?"side-by-side":"inline";v(e.path,se)},className:"opacity-70"})]})]})}),a&&s.jsxs("div",{className:"relative bg-background overflow-hidden",children:[!c&&!j?s.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,j?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:b("diffView.state.failedToLoadDiff")}),s.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:j}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>k(L=>L+1),children:b("diffView.actions.retry")})]}):null,c&&D&&!oe&&!j?s.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),b("diffView.state.loadingDiff")]}):null,c&&oe&&!E&&e.insertions+e.deletions>Mu?s.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[s.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:b("diffView.state.largeDiff",{count:e.insertions+e.deletions})}),s.jsx("div",{className:"typography-meta text-muted-foreground",children:b("diffView.state.largeDiffDescription")}),s.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>_(!0),children:b("diffView.actions.renderAnyway")})]}):null,c&&oe&&(E||e.insertions+e.deletions<=Mu)?s.jsxs(s.Fragment,{children:[s.jsx(f1,{filePath:e.path,diff:oe,renderSideBySide:Q,wrapLines:r}),s.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:s.jsx("div",{className:"pointer-events-auto",children:s.jsx(m1,{filePath:e.path,staged:y,busyAction:B,disabled:B!==null,onAction:pe})})})]}):null]})]})}),Jm=({hideStackedFileSidebar:t=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:n=!1,showOpenInEditorAction:r=!1,diffScope:o="all",onDiffScopeChange:a,targetFilePath:c=null,flushContent:l=!1})=>{const{t:d}=Nt(),{git:f,files:m}=Xn(),u=pi(),{screenWidth:p,isMobile:y}=Or(),g=Cc(u??null),b=Ka(u??null),x=Ac(u??null),h=wn(_e=>_e.setActiveDirectory),C=wn(_e=>_e.ensureStatus),w=wn(_e=>_e.fetchStatus),v=wn(_e=>_e.setDiff),[S,k]=i.useState(null),[j,A]=i.useState(!1),[D,N]=i.useState(null),[B,T]=i.useState(()=>new Set),[E,_]=i.useState(()=>new Set),[R,z]=i.useState(!1),[V,$]=i.useState(0),[M,te]=i.useState(!1),[re,Q]=i.useState(!1),H=Ee(_e=>_e.pendingDiffFile),X=Ee(_e=>_e.pendingDiffStaged),oe=Ee(_e=>_e.setPendingDiffFile),fe=Ee(_e=>_e.diffLayoutPreference),ve=Ee(_e=>_e.diffFileLayout),ie=Ee(_e=>_e.setDiffFileLayout),Ne=Ee(_e=>_e.diffWrapLines),K=Ee(_e=>_e.setDiffWrapLines),pe=Ee(_e=>_e.openContextFileAtLine),L=ut(_e=>_e.currentSessionId),se=Ne,Z=o==="staged"?!0:o==="working"?!1:null,je=Z??j,De=y||p<=768,Le=!!L&&!De&&!Yr(),Me=!t&&!De&&p>=1024,Fe=i.useRef(null),he=i.useRef(new Map),Ie=i.useRef(null),me=i.useRef(null),ce=i.useRef(!1),xe=i.useRef(null),ke=i.useRef(null),de=i.useCallback(()=>{Ie.current=null,ce.current=!1,N(null),me.current!==null&&(window.cancelAnimationFrame(me.current),me.current=null)},[]),P=i.useCallback(_e=>{T(Qe=>{if(Qe.has(_e))return Qe;const st=new Set(Qe);return st.add(_e),st})},[]),F=i.useMemo(()=>{if(!b?.files)return[];const _e=b.diffStats??{},Qe=o==="staged"?Ou:o==="working"?Lu:()=>!0;return b.files.filter(Qe).map(st=>({...st,insertions:_e[st.path]?.insertions??0,deletions:_e[st.path]?.deletions??0,isNew:i1(st)})).sort((st,pt)=>st.path.localeCompare(pt.path))},[o,b]),ue=i.useMemo(()=>b?.files?b.files.filter(Lu).length:0,[b]),be=i.useMemo(()=>b?.files?b.files.filter(Ou).length:0,[b]),W=i.useMemo(()=>F.map(_e=>_e.path).join("\0"),[F]);i.useEffect(()=>{const _e=W?W.split("\0"):[],Qe=new Set(_e),st=`${u??""}:${o}:${e?"collapsed":"default"}`,pt=ke.current!==st;ke.current=st,T(At=>{if(pt){const et=e?0:t1(_e.length);return new Set(_e.slice(0,et))}let vt=!1;const kt=new Set;for(const et of At){if(!Qe.has(et)){vt=!0;continue}kt.add(et)}return vt?kt:At}),_(At=>{if(pt)return new Set;let vt=!1;const kt=new Set;for(const et of At){if(!Qe.has(et)){vt=!0;continue}kt.add(et)}return vt?kt:At})},[W,o,u,e]);const ge=i.useCallback(()=>{xe.current=null;const _e=Fe.current;if(!_e)return;const Qe=_e.getBoundingClientRect(),st=Qe.top-Fu,pt=Qe.bottom+Fu,At={};for(const[vt,kt]of he.current){if(!kt||!B.has(vt))continue;const et=kt.getBoundingClientRect();et.bottom<st||et.top>pt||(At[vt]=!0)}_(vt=>{let kt=!1;const et=new Set(vt);for(const _t of Object.keys(At))et.has(_t)||(et.add(_t),kt=!0);return kt?et:vt})},[B]),we=i.useCallback(()=>{typeof window>"u"||xe.current===null&&(xe.current=window.requestAnimationFrame(ge))},[ge]);i.useEffect(()=>{const _e=Fe.current;if(_e)return we(),_e.addEventListener("scroll",we,{passive:!0}),window.addEventListener("resize",we),()=>{_e.removeEventListener("scroll",we),window.removeEventListener("resize",we),xe.current!==null&&(window.cancelAnimationFrame(xe.current),xe.current=null)}},[F,B,we]);const G=i.useCallback(_e=>{const Qe=ve[_e.path];if(Qe)return Qe;if(fe==="inline")return"inline";if(fe==="side-by-side")return"side-by-side";const st=p<Jv;return _e.isNew||st?"inline":"side-by-side"},[ve,fe,p]),Se=i.useMemo(()=>F.length===0?null:F.every(_e=>G(_e)==="side-by-side")?"side-by-side":"inline",[F,G]);i.useEffect(()=>{u&&(h(u),C(u,f))},[u,h,C,f]),i.useEffect(()=>{if(u)return Er.onGitRefreshHint(_e=>{Bu(_e.directory)===Bu(u)&&w(u,f)})},[u,w,f]),i.useEffect(()=>{o==="all"&&H&&(k(H),A(X),oe(null),ce.current=!0,Ie.current=H,P(H),$(_e=>_e+1))},[o,P,H,X,oe]),i.useEffect(()=>{if(o==="all")return;const _e=c?.trim();_e&&(k(_e),A(o==="staged"),ce.current=!0,Ie.current=_e,P(_e),$(Qe=>Qe+1))},[o,P,c]),i.useEffect(()=>{if(!S)return;F.some(Qe=>Qe.path===S)||(k(null),A(!1))},[F,S]);const Oe=i.useCallback((_e,Qe)=>{const st=he.current;Qe?st.set(_e,Qe):st.delete(_e),we()},[we]),Ae=i.useCallback((_e,Qe)=>{de(),T(st=>{const pt=st.has(_e);if(Qe===pt)return st;const At=new Set(st);return Qe?At.add(_e):At.delete(_e),At}),Qe||_(st=>{if(!st.has(_e))return st;const pt=new Set(st);return pt.delete(_e),pt}),we()},[de,we]),J=i.useCallback(()=>{de(),T(_e=>_e.size>0?new Set:new Set(F.map(Qe=>Qe.path))),_(new Set),we()},[de,F,we]),O=i.useCallback(async _e=>{if(!L)return;const Qe=ut.getState().getDirectoryForSession(L)||u||"";if(!Qe){le.error(d("diffView.reviewDialog.toast.noSessionDirectory"));return}Q(!0);try{await xg({originalSessionID:L,directory:Qe,providerID:_e.providerID,modelID:_e.modelID,agent:_e.agent||void 0,variant:_e.variant||void 0,generateHandoff:_e.generateHandoff,returnAfterHandoffRequest:_e.generateHandoff,autoReview:_e.autoReview}),te(!1)}catch(st){console.error("[review-flow] failed to start review flow",st),le.error(st instanceof Error?st.message:d("diffView.reviewDialog.toast.startFailed"))}finally{Q(!1)}},[L,u,d]),ae=i.useCallback(_e=>{const Qe=he.current.get(_e),st=Fe.current;if(!Qe||!st)return!1;const pt=st.getBoundingClientRect(),vt=Qe.getBoundingClientRect().top-pt.top,kt=Math.max(0,st.scrollHeight-st.clientHeight);return st.scrollTop=Math.min(kt,Math.max(0,st.scrollTop+vt)),!0},[]);i.useEffect(()=>{if(!Ie.current)return;let Qe=0;const st=20;let pt=!1;const At=()=>{pt||(pt=!0,Ie.current=null,ce.current=!1,N(null),me.current!==null&&(window.cancelAnimationFrame(me.current),me.current=null))},vt=()=>{if(pt){me.current=null;return}const kt=Ie.current;if(!kt){At(),me.current=null;return}if(!ae(kt)){Qe+=1,Qe<st?me.current=window.requestAnimationFrame(vt):(At(),me.current=null);return}n&&ce.current&&N(kt),At()};return me.current=window.requestAnimationFrame(vt),()=>{pt=!0,me.current!==null&&(window.cancelAnimationFrame(me.current),me.current=null)}},[n,V,ae]);const ne=i.useCallback(_e=>{},[]),Be=i.useCallback(_e=>{de(),k(_e),A(!1),ce.current=!0,Ie.current=_e,P(_e),$(Qe=>Qe+1),ae(_e)},[de,P,ae]),Ye=i.useCallback(_e=>{const Qe=_e==="side-by-side"?"side-by-side":"inline";F.forEach(st=>{ie(st.path,Qe)})},[F,ie]),[He,Je]=i.useState(null),nt=i.useCallback(async(_e,Qe)=>{if(!(!u||!_e)){Je(_e);try{let st=null;if(Qe?.patch&&!Qe.isBinary&&!Ri(_e)?st=Eu(Qe.patch):Qe&&Qe.contextMode==="full"&&!Qe.isBinary&&!Ri(_e)&&(st=_u(Qe.original,Qe.modified)),st===null)try{const et=await f.getGitDiff(u,{path:_e,staged:je,contextLines:3});st=Eu(et.diff)}catch{st=null}let pt=Qe;if(st===null||!pt){const et=await f.getGitFileDiff(u,{path:_e,staged:je});pt={original:et.original??"",modified:et.modified??"",isBinary:et.isBinary},je||v(u,_e,pt)}const At=st??(pt.isBinary||Ri(_e)?1:_u(pt.original,pt.modified)),vt=o1(u,_e),kt=await zc(m,vt);if(!kt.ok){le.error(Wc(kt.reason));return}pe(u,vt,At,1)}finally{Je(st=>st===_e?null:st)}}},[je,u,m,f,pe,v]),xt=()=>{if(!u)return null;const _e=Qe=>Z!==null?Z:j&&Qe===S;return s.jsxs("div",{className:Te("flex min-w-0 flex-1 min-h-0 h-full",l?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[Me&&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:F.length})]}),s.jsx(d1,{changedFiles:F,selectedFile:null,onSelectFile:Be})]}),s.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:s.jsx(Wn,{ref:Fe,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:F.map(Qe=>s.jsx(h1,{directory:u,file:Qe,layout:G(Qe),wrapLines:se,isSelected:!1,isExpanded:B.has(Qe.path),isMounted:E.has(Qe.path)||Qe.path===D,onSelect:ne,onExpandedChange:Ae,registerSectionRef:Oe,showOpenInEditorAction:r,isOpeningInEditor:He===Qe.path,onOpenInEditor:(st,pt)=>{nt(st,pt)},staged:_e(Qe.path),loadFullFiles:R},Qe.path))})})})]})},bt=()=>u?x&&!b?s.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),d("diffView.state.loadingRepositoryStatus")]}):g===!1?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.notGitRepository")}):F.length===0?s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.cleanWorkingTree")}):xt():s.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d("diffView.state.selectSessionDirectory")});return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[!y&&(o==="working"||o==="staged"?s.jsx(c1,{scope:o,workingCount:ue,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:x&&!b?d("diffView.state.loadingChanges"):F.length===1?d("diffView.summary.changedFilesSingle",{count:F.length}):d("diffView.summary.changedFilesPlural",{count:F.length})})})),F.length>0&&s.jsxs(Ve,{variant:"ghost",size:"sm",onClick:J,className:Te("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:B.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll"),children:[s.jsx(I,{name:"expand-up-down",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:B.size>0?d("diffView.actions.collapseAll"):d("diffView.actions.expandAll")})]}),F.length>0&&Le&&s.jsxs(Ve,{variant:"default",size:"sm",onClick:()=>te(!0),disabled:re,className:"diff-toolbar__review-button h-7 flex-shrink-0 gap-1.5 px-2","aria-label":d("diffView.actions.reviewAria"),children:[re?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(I,{name:"search-eye",className:"size-4"}),s.jsx("span",{className:"diff-toolbar__review-label typography-ui-label",children:d("diffView.actions.review")})]}),F.length>0&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>z(_e=>!_e),"aria-pressed":R,"aria-label":d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles"),className:Te("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",R&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(I,{name:"file-download",className:"size-4"})})}),s.jsx(Ft,{children:s.jsx("p",{children:d(R?"diffView.actions.disableFullFiles":"diffView.actions.loadFullFiles")})})]}),F.length>0&&s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>K(!Ne),className:Te("h-5 w-5 p-0 transition-opacity",se?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:d(se?"diffView.actions.disableLineWrap":"diffView.actions.enableLineWrap"),children:s.jsx(I,{name:"text-wrap",className:"size-4"})}),Se&&s.jsx(rm,{mode:Se==="side-by-side"?"side-by-side":"unified",onModeChange:Ye})]}),s.jsx(bg,{open:M,onOpenChange:te,projectDirectory:u??null,submitting:re,onConfirm:O}),bt()]})},p1=(t,e)=>{if(!e)return null;const n=Number.parseInt(t.trim(),10);return!Number.isFinite(n)||n<1?null:Math.min(n,e.state.doc.lines)},Vu=(t,e)=>{const n=t.state.doc.lineAt(e.main.head);return{lineNumber:n.number,character:e.main.head-n.from+1,selection:e}},$u=(t,e,n)=>{const r=t.state.doc.line(e),o=Math.max(1,Math.min(n,r.length+1)),a=r.from+o-1;t.dispatch({selection:Kh.cursor(a),effects:li.scrollIntoView(a,{y:"center"})})};function g1({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),f=i.useRef(null),m=i.useRef(null),u=i.useMemo(()=>p1(a,n),[a,n]);i.useEffect(()=>{!t||!n||(d.current=!1,l.current=Vu(n,n.state.selection),c(""))},[t,n]),i.useEffect(()=>{t&&window.requestAnimationFrame(()=>{m.current?.focus(),m.current?.select()})},[t]),i.useEffect(()=>{if(!(!t||!n||!l.current)){if(u===null){const{selection:x}=l.current;n.dispatch({selection:x,effects:li.scrollIntoView(x.main.from,{y:"center"})});return}$u(n,u,l.current.character)}},[u,t,n]);const p=i.useCallback(()=>{if(!n||d.current||!l.current)return;const{selection:x}=l.current;n.dispatch({selection:x,effects:li.scrollIntoView(x.main.from,{y:"center"})})},[n]),y=i.useCallback(x=>{x||p(),e(x)},[e,p]),g=i.useCallback(()=>{!n||u===null||!l.current||(d.current=!0,$u(n,u,l.current.character),e(!1),n.focus())},[u,e,n]);i.useEffect(()=>{if(!t)return;const x=C=>{const w=f.current,v=C.target;!w||!(v instanceof Node)||w.contains(v)||y(!1)},h=C=>{C.key==="Escape"&&(C.preventDefault(),y(!1))};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",h,!0),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",h,!0)}},[y,t,r]);const b=i.useMemo(()=>{if(!n)return o("goToLineDialog.helper.editorUnavailable");if(u===null){const x=l.current??Vu(n,n.state.selection);return o("goToLineDialog.helper.currentLineRange",{current:x.lineNumber,max:n.state.doc.lines})}return o("goToLineDialog.helper.goToLine",{line:u})},[u,o,n]);return r==="inline"?t?s.jsxs("div",{ref:f,className:"ml-1 flex h-6 items-center gap-1",children:[s.jsx(vn,{ref:m,type:"number",min:1,step:1,inputMode:"numeric",value:a,onChange:x=>c(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g())},placeholder:o("goToLineDialog.field.linePlaceholderShort"),className:"h-6 w-20 rounded-md border-border/70 bg-transparent px-2 typography-meta"}),s.jsx(Ve,{variant:"outline",size:"xs",onClick:g,disabled:!n||u===null,className:"h-6 px-2",children:o("goToLineDialog.actions.go")})]}):null:s.jsx("div",{ref:f,className:Te("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:x=>c(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),g())},placeholder:o("goToLineDialog.field.linePlaceholder"),className:"h-8 w-full rounded-md border-border/70 bg-background/60 typography-ui-label"}),s.jsx("div",{className:"mt-2 rounded-md bg-primary/15 px-3 py-1.5 typography-ui-label text-foreground/95",children:b})]})})}const x1='<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 zu(){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 b1=i.forwardRef(function({xml:e,readOnly:n,className:r,onChange:o},a){const c=i.useRef(e),l=i.useRef(null),d=i.useRef(!1),[f,m]=i.useState(zu),u=i.useRef(e),p=i.useRef(e);p.current!==e&&(p.current=e,u.current=e,c.current=e);const y=i.useRef(f);y.current!==f&&(y.current=f,u.current=c.current);const g=i.useRef(null);i.useEffect(()=>{const h=()=>m(zu());h();const C=new MutationObserver(h);return C.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>C.disconnect()},[]),i.useEffect(()=>{const h=setTimeout(()=>{g.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(h)},[]),i.useImperativeHandle(a,()=>({getXml:()=>c.current}));const b=i.useCallback(()=>{!e&&!d.current&&(d.current=!0,setTimeout(()=>{l.current?.template({})},500))},[e]),x=i.useCallback(h=>{c.current=h.xml,o?.(h.xml)},[o]);return s.jsx("div",{ref:g,className:Te("h-full w-full",r),children:s.jsx(qh,{ref:l,xml:u.current||x1,autosave:!0,urlParameters:{ui:n?"simple":f?"dark":"kennedy",spin:!0,libraries:!n,chrome:n,nav:n,layers:n,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:x},f?"dark":"light")})}),y1=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},w1=t=>{const e=ft.c(8),{label:n,iconDataUrl:r}=t,[o,a]=i.useState(!1);let c;e[0]!==n?(c=n.trim().slice(0,1).toUpperCase()||"?",e[0]=n,e[1]=c):c=e[1];const l=c;if(r&&!o){let m;e[2]===Symbol.for("react.memo_cache_sentinel")?(m=()=>a(!0),e[2]=m):m=e[2];let u;return e[3]!==r?(u=s.jsx("img",{src:r,alt:"",className:"size-4 rounded-sm",onError:m}),e[3]=r,e[4]=u):u=e[4],u}let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=Te("size-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),e[5]=d):d=e[5];let f;return e[6]!==l?(f=s.jsx("span",{className:d,children:l}),e[6]=l,e[7]=f):f=e[7],f},v1=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},j1=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Gi=t=>/^[A-Za-z]:\//.test(t)?t.toLowerCase():t,Ea=(t,e)=>{const n=qs(e),r=qs(t);if(!n||!r)return!1;const o=Gi(n),a=Gi(r);return a===o||a.startsWith(`${o}/`)},Wu=(t,e)=>{const n=qs(e),r=qs(t);if(!Ea(r,n))return[];const a=r.slice(n.length).replace(/^\//,"").split("/"),c=[];let l=n;for(let d=0;d<a.length-1;d++)l=l?`${l}/${a[d]}`:a[d],c.push(l);return c},nc=(t,e)=>{if(!e)return"";const n=qs(e);if(!t||!Ea(n,t))return n;const r=n.slice(t.length);return r.startsWith("/")?r.slice(1):r},S1=new Set(["node_modules"]),N1=t=>{const e=ft.c(3),{status:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"},e[0]=r):r=e[0];const o=r[n];let a;return e[1]!==o?(a=s.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:o}}),e[1]=o,e[2]=a):a=e[2],a},Uu=t=>{const e=ft.c(11),{name:n}=t,r=i.useRef(null),o=i.useRef(null),[a,c]=i.useState(!1);let l;e[0]===Symbol.for("react.memo_cache_sentinel")?(l=()=>{const p=r.current,y=o.current;if(!p||!y)return;const g=()=>{c(y.scrollWidth>p.clientWidth+1)};g();const b=new ResizeObserver(g);return b.observe(p),b.observe(y),()=>{b.disconnect()}},e[0]=l):l=e[0];let d;e[1]!==n?(d=[n],e[1]=n,e[2]=d):d=e[2],i.useLayoutEffect(l,d);let f;e[3]!==n?(f=s.jsx("span",{ref:o,"aria-hidden":"true",className:"invisible absolute whitespace-nowrap",children:n}),e[3]=n,e[4]=f):f=e[4];let m;e[5]!==n||e[6]!==a?(m=a?s.jsxs("span",{className:"open-file-name-marquee-track",children:[s.jsx("span",{className:"open-file-name-marquee-item",children:n}),s.jsx("span",{className:"open-file-name-marquee-item","aria-hidden":"true",children:n})]}):s.jsx("span",{className:"block min-w-0 truncate",children:n}),e[5]=n,e[6]=a,e[7]=m):m=e[7];let u;return e[8]!==f||e[9]!==m?(u=s.jsxs("span",{ref:r,className:"relative block min-w-0 flex-1 overflow-hidden whitespace-nowrap",children:[f,m]}),e[8]=f,e[9]=m,e[10]=u):u=e[10],u},k1=t=>S1.has(t),C1=t=>{const e=qs(t);return e==="node_modules"||e.endsWith("/node_modules")||e.includes("/node_modules/")},A1=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("is a directory")||n.includes("eisdir")},Hu=t=>{const n=(t instanceof Error?t.message:String(t??"")).toLowerCase();return n.includes("file not found")||n.includes("enoent")||n.includes("no such file")||n.includes("does not exist")},bo=2e5,Xm="openchamber:files:auto-save-enabled",D1=t=>{let e=0,n=0;for(let r=0;r<t.length;r+=1)t.charCodeAt(r)===10&&(r>0&&t.charCodeAt(r-1)===13?e+=1:n+=1);return e>n?`\r
|
|
22
|
-
`:`
|
|
23
|
-
`},Zm=t=>t.replace(/\r\n/g,`
|
|
24
|
-
`).replace(/\r/g,`
|
|
25
|
-
`),I1=(t,e)=>{const n=Zm(t);return e===`\r
|
|
26
|
-
`?n.replace(/\n/g,`\r
|
|
27
|
-
`):n},P1=()=>{if(typeof window>"u")return!0;try{return window.localStorage.getItem(Xm)!=="false"}catch{return!0}},eh=(t,e)=>s.jsx(Kr,{filePath:t,extension:e}),Gu=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="md"||e==="markdown"},T1=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="json"||e==="jsonc"||e==="json5"||e==="geojson"},Zo=t=>{if(!t)return!1;const e=t.toLowerCase().split(".").pop();return e==="html"||e==="htm"},R1=t=>{const e=ft.c(83),{node:n,root:r,isExpanded:o,isActive:a,isMobile:c,alwaysShowActions:l,status:d,badge:f,permissions:m,downloadFile:u,contextMenuPath:p,setContextMenuPath:y,rightClickMenuPath:g,setRightClickMenuPath:b,onSelect:x,onToggle:h,onRevealPath:C,onOpenDialog:w}=t,{t:v}=Nt(),S=n.type==="directory",{canRename:k,canCreateFile:j,canCreateFolder:A,canDelete:D,canReveal:N}=m;let B;e[0]!==j||e[1]!==A||e[2]!==D||e[3]!==k||e[4]!==N||e[5]!==n.path||e[6]!==b?(B=je=>{!k&&!j&&!A&&!D&&!N||(je?.preventDefault(),b(n.path))},e[0]=j,e[1]=A,e[2]=D,e[3]=k,e[4]=N,e[5]=n.path,e[6]=b,e[7]=B):B=e[7];const T=B;let E;e[8]!==S||e[9]!==n||e[10]!==x||e[11]!==h?(E=()=>{S?h(n.path):x(n)},e[8]=S,e[9]=n,e[10]=x,e[11]=h,e[12]=E):E=e[12];const _=E;let R;e[13]!==n.path||e[14]!==y||e[15]!==b?(R=je=>{je.stopPropagation(),b(null),y(n.path)},e[13]=n.path,e[14]=y,e[15]=b,e[16]=R):R=e[16];const z=R;let V;e[17]!==j||e[18]!==A||e[19]!==D||e[20]!==k||e[21]!==N||e[22]!==u||e[23]!==S||e[24]!==n||e[25]!==w||e[26]!==C||e[27]!==r||e[28]!==v?(V=je=>{const{Item:De,Separator:Le}=je;return s.jsxs(s.Fragment,{children:[k&&s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),w("rename",n)},children:[s.jsx(I,{name:"edit",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.rename")]}),s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),ur(n.path).then(Fe=>{if(Fe.ok){le.success(v("sidebarFilesTree.toast.pathCopied"));return}le.error(v("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.copyPath")]}),s.jsxs(De,{onClick:Me=>{Me.stopPropagation();const Fe=nc(r,n.path)||n.path;ur(Fe).then(he=>{if(he.ok){le.success(v("filesView.toast.relativePathCopied"));return}le.error(v("sidebarFilesTree.toast.copyFailed"))})},children:[s.jsx(I,{name:"file-copy-2",className:"mr-2 size-4"})," ",v("filesView.tree.menu.copyRelativePath")]}),!S&&u&&s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),u(n.path).catch(Fe=>{console.error("Download failed:",Fe),le.error(v("sidebarFilesTree.toast.operationFailed"))})},children:[s.jsx(I,{name:"download",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.save")]}),N&&s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),C(n.path)},children:[s.jsx(I,{name:"folder-received",className:"mr-2 size-4"})," ",v(Dc())]}),S&&(j||A)&&s.jsxs(s.Fragment,{children:[s.jsx(Le,{}),j&&s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),w("createFile",n)},children:[s.jsx(I,{name:"file-add",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.newFile")]}),A&&s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),w("createFolder",n)},children:[s.jsx(I,{name:"folder-add",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.newFolder")]})]}),D&&s.jsxs(s.Fragment,{children:[s.jsx(Le,{}),s.jsxs(De,{onClick:Me=>{Me.stopPropagation(),w("delete",n)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"delete-bin",className:"mr-2 size-4"})," ",v("sidebarFilesTree.menu.delete")]})]})]})},e[17]=j,e[18]=A,e[19]=D,e[20]=k,e[21]=N,e[22]=u,e[23]=S,e[24]=n,e[25]=w,e[26]=C,e[27]=r,e[28]=v,e[29]=V):V=e[29];const $=V,M=g===n.path;let te;e[30]!==n.path||e[31]!==b?(te=je=>b(je?n.path:null),e[30]=n.path,e[31]=b,e[32]=te):te=e[32];const re=c?void 0:T;let Q;e[33]!==re?(Q=s.jsx("div",{className:"group relative flex items-center",onContextMenu:re}),e[33]=re,e[34]=Q):Q=e[34];const H=c?void 0:T,X=a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40";let oe;e[35]!==X?(oe=Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",X),e[35]=X,e[36]=oe):oe=e[36];let fe;e[37]!==S||e[38]!==o||e[39]!==n.extension||e[40]!==n.path?(fe=S?o?s.jsx(I,{name:"folder-open-fill",className:"size-4 flex-shrink-0 text-primary/60"}):s.jsx(I,{name:"folder-3-fill",className:"size-4 flex-shrink-0 text-primary/60"}):eh(n.path,n.extension),e[37]=S,e[38]=o,e[39]=n.extension,e[40]=n.path,e[41]=fe):fe=e[41];let ve;e[42]!==n.name||e[43]!==n.path?(ve=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:n.path,children:n.name}),e[42]=n.name,e[43]=n.path,e[44]=ve):ve=e[44];let ie;e[45]!==S||e[46]!==d?(ie=!S&&d&&s.jsx(N1,{status:d}),e[45]=S,e[46]=d,e[47]=ie):ie=e[47];let Ne;e[48]!==f||e[49]!==S?(Ne=S&&f&&s.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[f.modified>0&&s.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",f.modified]}),f.added>0&&s.jsxs("span",{className:"text-[var(--status-success)]",children:["+",f.added]})]}),e[48]=f,e[49]=S,e[50]=Ne):Ne=e[50];let K;e[51]!==_||e[52]!==oe||e[53]!==fe||e[54]!==ve||e[55]!==ie||e[56]!==Ne||e[57]!==H?(K=s.jsxs("button",{type:"button",onClick:_,onContextMenu:H,className:oe,children:[fe,ve,ie,Ne]}),e[51]=_,e[52]=oe,e[53]=fe,e[54]=ve,e[55]=ie,e[56]=Ne,e[57]=H,e[58]=K):K=e[58];let pe;e[59]!==l||e[60]!==j||e[61]!==A||e[62]!==D||e[63]!==k||e[64]!==N||e[65]!==p||e[66]!==z||e[67]!==c||e[68]!==n.path||e[69]!==$||e[70]!==y?(pe=(k||j||A||D||N)&&s.jsx("div",{className:Te("absolute right-1 top-1/2 -translate-y-1/2",l?"opacity-100":"opacity-0 focus-within:opacity-100 group-hover:opacity-100"),children:s.jsxs(tn,{open:p===n.path,onOpenChange:je=>y(je?n.path:null),children:[s.jsx(Zs,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"icon",className:"size-6",onClick:z,children:s.jsx(I,{name:"more-2-fill",className:"size-4"})})}),s.jsx(en,{align:"end",side:"bottom",onCloseAutoFocus:()=>y(null),children:$({Item:ws,Separator:Fr})})]})}),e[59]=l,e[60]=j,e[61]=A,e[62]=D,e[63]=k,e[64]=N,e[65]=p,e[66]=z,e[67]=c,e[68]=n.path,e[69]=$,e[70]=y,e[71]=pe):pe=e[71];let L;e[72]!==K||e[73]!==pe||e[74]!==Q?(L=s.jsxs(Oc,{render:Q,children:[K,pe]}),e[72]=K,e[73]=pe,e[74]=Q,e[75]=L):L=e[75];let se;e[76]!==$?(se=s.jsx(Mc,{className:"min-w-[180px]",children:$({Item:Fc,Separator:Cm})}),e[76]=$,e[77]=se):se=e[77];let Z;return e[78]!==L||e[79]!==se||e[80]!==M||e[81]!==te?(Z=s.jsxs(Lc,{open:M,onOpenChange:te,children:[L,se]}),e[78]=L,e[79]=se,e[80]=M,e[81]=te,e[82]=Z):Z=e[82],Z},E1=t=>{const e=ft.c(83),{activeDialog:n,dialogData:r,dialogInputValue:o,onDialogInputChange:a,isDialogSubmitting:c,onDialogSubmit:l,onClose:d,inputRef:f}=t,{t:m}=Nt(),u=!!n;let p;e[0]!==d?(p=M=>!M&&d(),e[0]=d,e[1]=p):p=e[1];let y;e[2]!==n||e[3]!==m?(y=n==="createFile"&&m("filesView.dialog.createFile.title"),e[2]=n,e[3]=m,e[4]=y):y=e[4];let g;e[5]!==n||e[6]!==m?(g=n==="createFolder"&&m("filesView.dialog.createFolder.title"),e[5]=n,e[6]=m,e[7]=g):g=e[7];let b;e[8]!==n||e[9]!==m?(b=n==="rename"&&m("filesView.dialog.rename.title"),e[8]=n,e[9]=m,e[10]=b):b=e[10];let x;e[11]!==n||e[12]!==m?(x=n==="delete"&&m("filesView.dialog.delete.title"),e[11]=n,e[12]=m,e[13]=x):x=e[13];let h;e[14]!==y||e[15]!==g||e[16]!==b||e[17]!==x?(h=s.jsxs(Vs,{children:[y,g,b,x]}),e[14]=y,e[15]=g,e[16]=b,e[17]=x,e[18]=h):h=e[18];let C;e[19]!==n||e[20]!==r?.path||e[21]!==m?(C=n==="createFile"&&m("filesView.dialog.createFile.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[19]=n,e[20]=r?.path,e[21]=m,e[22]=C):C=e[22];let w;e[23]!==n||e[24]!==r?.path||e[25]!==m?(w=n==="createFolder"&&m("filesView.dialog.createFolder.description",{path:r?.path??m("filesView.dialog.rootFallback")}),e[23]=n,e[24]=r?.path,e[25]=m,e[26]=w):w=e[26];let v;e[27]!==n||e[28]!==r?.name||e[29]!==m?(v=n==="rename"&&m("filesView.dialog.rename.description",{name:r?.name??""}),e[27]=n,e[28]=r?.name,e[29]=m,e[30]=v):v=e[30];let S;e[31]!==n||e[32]!==r?.name||e[33]!==m?(S=n==="delete"&&m("filesView.dialog.delete.description",{name:r?.name??""}),e[31]=n,e[32]=r?.name,e[33]=m,e[34]=S):S=e[34];let k;e[35]!==v||e[36]!==S||e[37]!==C||e[38]!==w?(k=s.jsxs(an,{children:[C,w,v,S]}),e[35]=v,e[36]=S,e[37]=C,e[38]=w,e[39]=k):k=e[39];let j;e[40]!==k||e[41]!==h?(j=s.jsxs(Gs,{children:[h,k]}),e[40]=k,e[41]=h,e[42]=j):j=e[42];let A;e[43]!==n||e[44]!==o||e[45]!==f||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:M=>a(M.target.value),placeholder:m(n==="rename"?"filesView.dialog.rename.placeholder":"filesView.dialog.namePlaceholder"),onKeyDown:M=>{M.key==="Enter"&&l()},ref:f})}),e[43]=n,e[44]=o,e[45]=f,e[46]=a,e[47]=l,e[48]=m,e[49]=A):A=e[49];let D;e[50]!==m?(D=m("filesView.dialog.cancel"),e[50]=m,e[51]=D):D=e[51];let N;e[52]!==c||e[53]!==d||e[54]!==D?(N=s.jsx(Ve,{variant:"outline",onClick:d,disabled:c,children:D}),e[52]=c,e[53]=d,e[54]=D,e[55]=N):N=e[55];const B=n==="delete"?"destructive":"default";let T;e[56]!==l?(T=()=>{l()},e[56]=l,e[57]=T):T=e[57];let E;e[58]!==n||e[59]!==o||e[60]!==c?(E=c||n!=="delete"&&!o.trim(),e[58]=n,e[59]=o,e[60]=c,e[61]=E):E=e[61];let _;e[62]!==n||e[63]!==c||e[64]!==m?(_=c?s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}):m(n==="delete"?"filesView.dialog.delete.confirm":"filesView.dialog.confirm"),e[62]=n,e[63]=c,e[64]=m,e[65]=_):_=e[65];let R;e[66]!==B||e[67]!==T||e[68]!==E||e[69]!==_?(R=s.jsx(Ve,{variant:B,onClick:T,disabled:E,children:_}),e[66]=B,e[67]=T,e[68]=E,e[69]=_,e[70]=R):R=e[70];let z;e[71]!==N||e[72]!==R?(z=s.jsxs(nr,{children:[N,R]}),e[71]=N,e[72]=R,e[73]=z):z=e[73];let V;e[74]!==f||e[75]!==j||e[76]!==A||e[77]!==z?(V=s.jsxs(Es,{initialFocus:f,children:[j,A,z]}),e[74]=f,e[75]=j,e[76]=A,e[77]=z,e[78]=V):V=e[78];let $;return e[79]!==u||e[80]!==p||e[81]!==V?($=s.jsx(Ms,{open:u,onOpenChange:p,children:V}),e[79]=u,e[80]=p,e[81]=V,e[82]=$):$=e[82],$},Dl=(t,e,n)=>{const r=ft.c(8),[o,a]=i.useState(""),[c,l]=i.useState(0);let d,f;r[0]!==t||r[1]!==n||r[2]!==e?(d=()=>{if(!t){a("");return}let u=!1;a("");const p=Hr(),y=yp(p);xc(p).then(b=>{u||!b||(a(t),e(null))}).catch(b=>{u||(e(b instanceof Error?b.message:n),a(t))});const g=wp(()=>{u||(a(t),l(M1),e(null))});return()=>{u=!0,y(),g()}},f=[t,e,n],r[0]=t,r[1]=n,r[2]=e,r[3]=d,r[4]=f):(d=r[3],f=r[4]),i.useEffect(d,f);let m;return r[5]!==c||r[6]!==o?(m={readyKey:o,nonce:c},r[5]=c,r[6]=o,r[7]=m):m=r[7],m},th=({mode:t="full"})=>{const{t:e}=Nt(),{files:n,runtime:r}=Xn(),{currentTheme:o,availableThemes:a,lightThemeId:c,darkThemeId:l}=Qr(),{isMobile:d,isTablet:f,screenWidth:m}=Or(),u=d||f,p=$f(),y=zf(),g=pi()??"",b=qs(g.trim()),x=d||t!=="editor-only",h=t==="editor-only"&&!d,C=gc(U=>U.searchFiles),w=Ka(g),[v,S]=i.useState(""),k=Ya(v,200),j=i.useRef(null),[A,D]=i.useState(!1),[N,B]=i.useState(!0),[T,E]=i.useState(!1),[_,R]=i.useState(!1),[z,V]=i.useState(!1),$=i.useRef(null),M=i.useRef(0),te=i.useCallback(U=>{M.current=Math.max(0,M.current+(U?1:-1))},[]),re=i.useCallback(U=>U instanceof Element?U.closest('[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-item"]')!==null:!1,[]);i.useEffect(()=>{if(!z)return;const U=Pe=>{M.current>0||re(Pe.target)||$.current&&!$.current.contains(Pe.target)&&V(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[re,z]);const[Q,H]=i.useState("edit"),[X,oe]=i.useState("edit"),[fe,ve]=i.useState("tree"),[ie,Ne]=i.useState("edit"),[K,pe]=i.useState("preview"),[L,se]=i.useState(0),Z=i.useRef({}),je=i.useRef({}),De=i.useRef({}),Le=i.useRef({}),Me=i.useMemo(()=>a.find(U=>U.metadata.id===c)??Rd(!1),[a,c]),Fe=i.useMemo(()=>a.find(U=>U.metadata.id===l)??Rd(!0),[a,l]);i.useEffect(()=>{Ed(Me),Ed(Fe)},[Me,Fe]);const he=i.useMemo(()=>[],[]),Ie=fn(U=>b?U.byRoot[b]?.openPaths??he:he),me=fn(U=>b?U.byRoot[b]?.selectedPath??null:null),ce=fn(U=>b?U.byRoot[b]?.expandedPaths??he:he),xe=fn(U=>U.addOpenPath),ke=fn(U=>U.removeOpenPath),de=fn(U=>U.removeOpenPathsByPrefix),P=fn(U=>U.removeExpandedPathsByPrefix),F=fn(U=>U.setSelectedPath),ue=fn(U=>U.toggleExpandedPath),be=fn(U=>U.expandPaths),W=i.useCallback(U=>{const Pe=qs(U),ze=Pe.split("/"),Ke=ze[ze.length-1]||Pe,lt=Ke.includes(".")?Ke.split(".").pop()?.toLowerCase():void 0;return{name:Ke,path:Pe,type:"file",extension:lt}},[]),ge=i.useMemo(()=>Ie.map(W),[Ie,W]),we=i.useMemo(()=>{if(me){const U=Gi(me);if(Ie.some(Pe=>Gi(Pe)===U))return me}return Ie[0]??null},[Ie,me]),G=i.useMemo(()=>we?W(we):null,[we,W]),Se=G?.path??"";i.useEffect(()=>{if(!b||!me)return;const U=Gi(me);Ie.some(ze=>Gi(ze)===U)||F(b,Ie[0]??null)},[Ie,b,me,F]);const Oe=!!(b&&Se&&!Ea(Se,b)),Ae=Oe?Md(Se):void 0,J=i.useMemo(()=>({allowOutsideWorkspace:t==="editor-only"&&Oe,outsideFileGrant:Ae,directory:b||void 0}),[t,Oe,Ae,b]),O=i.useRef(null),[ae,ne]=i.useState({left:!1,right:!1}),Be=i.useCallback(()=>{const U=O.current;U&&ne({left:U.scrollLeft>2,right:U.scrollLeft+U.clientWidth<U.scrollWidth-2})},[]),Ye=i.useRef(Be);Ye.current=Be,i.useEffect(()=>{const U=O.current;if(!U)return;const Pe=()=>Ye.current();Pe(),U.addEventListener("scroll",Pe,{passive:!0});const ze=new ResizeObserver(Pe);return ze.observe(U),()=>{U.removeEventListener("scroll",Pe),ze.disconnect()}},[ge.length]);const[He,Je]=i.useState({}),[nt,xt]=i.useState({}),bt=i.useRef(new Set),_e=i.useRef(new Set),Qe=i.useRef(new Map),st=i.useRef(0),[pt,At]=i.useState([]),[vt,kt]=i.useState(!1),[et,_t]=i.useState(""),{isPlaying:ns,play:Kt,stop:qe}=im(),[gt,Xe]=i.useState(!1),[jt,Pt]=i.useState(null),[is,Bt]=i.useState(""),Gt=i.useRef(""),[es,Wt]=i.useState(null),[Lt,Ut]=i.useState(""),[rs,$t]=i.useState(!1),[ls,xs]=i.useState(`
|
|
28
|
-
`),Ct=i.useRef(null),Vt=i.useRef(null),yt=i.useRef(null),us=i.useRef(""),cs=i.useRef(""),Ue=i.useRef(null),Ge=i.useRef(null),wt=i.useRef(null),Ot=i.useRef(0),[Dt,bs]=i.useState("idle"),[fs,os]=i.useState(!1),[qt,ln]=i.useState(P1),[ps,Fs]=i.useState(!1),Ws=i.useRef(null),sn=i.useRef(null),Dn=i.useRef(null),jn=i.useRef(!1),ye=i.useRef(null),Ze=i.useRef(null),ct=i.useRef(null),It=i.useRef(null),[Ht,mt]=i.useState(0),ms=i.useRef(null),hs=i.useRef({key:"",attempts:0});i.useEffect(()=>()=>{ms.current!==null&&typeof window<"u"&&(window.cancelAnimationFrame(ms.current),ms.current=null)},[]);const[Ns,ys]=i.useState(null),[Is,Mn]=i.useState(null),[$s,hn]=i.useState(""),[Fn,Zn]=i.useState(!1),[cn,We]=i.useState(null),[Xt,As]=i.useState(null),[Ps,zs]=i.useState(!1),[Qs,Us]=i.useState(!1),[Os,On]=i.useState(!1),fr=!!n.writeFile,Kn=!!n.createDirectory,gs=!!n.rename,Ts=!!n.delete,Sr=!!n.revealPath,Ln=wr(U=>U.availableApps),pn=wr(U=>U.isCacheStale),Nr=wr(U=>U.initialize),kr=wr(U=>U.loadInstalledApps);i.useEffect(()=>{Nr()},[Nr]);const Lr=i.useCallback(U=>{n.revealPath&&n.revealPath(U).catch(()=>{le.error(e("sidebarFilesTree.toast.revealFailed"))})},[n,e]),Cr=i.useCallback(async U=>{if(!G?.path||await bp(G.path,U.id,U.appName)||await ja(G.path,U.appName))return;const Ke=y1(G.path)||b;Ke&&await ja(Ke,U.appName)||le.error(e("filesView.toast.openInAppFailed",{app:U.appName}))},[b,G?.path,e]),rr=i.useCallback((U,Pe)=>{ys(U),Mn(Pe),hn(U==="rename"&&Pe.name||""),Zn(!1)},[]),[js,dn]=i.useState(null),ir=i.useRef(!1),q=i.useRef(null),[rt,ht]=i.useState(!1),Tt=Ee(U=>U.setMainTabGuard),Yt=Ee(U=>U.pendingFileNavigation),ts=Ee(U=>U.setPendingFileNavigation),ds=Ee(U=>U.pendingFileFocusPath),Ls=Ee(U=>U.setPendingFileFocusPath),Ks=Ee(U=>U.shortcutOverrides),qn=Ee(U=>U.fileEditorKeymap),Bn=ss(U=>U.settingsDefaultFileViewerPreview),Jr=ss(U=>U.showMessageTTSButtons),gn=Ee(U=>U.expandedEditorToolbar);i.useEffect(()=>{const U=()=>{ir.current=!1,q.current=null,ht(!1)};return document.addEventListener("mouseup",U),()=>document.removeEventListener("mouseup",U)},[]),i.useEffect(()=>()=>{ye.current!==null&&window.clearTimeout(ye.current),Ze.current!==null&&window.clearTimeout(Ze.current)},[]);const Xr=i.useCallback((U,Pe)=>{const ze=U.split(`
|
|
29
|
-
`),Ke=Math.max(1,Pe.start),lt=Math.min(ze.length,Pe.end);return Ke>lt?"":ze.slice(Ke-1,lt).join(`
|
|
30
|
-
`)},[]),xn=Am({source:"file",fileLabel:G?.path??null,language:G?.path&&Ti(G.path)||"text",getCodeForRange:U=>Xr(et,Dm(U)),toStoreRange:U=>({startLine:U.start,endLine:U.end}),fromDraftRange:U=>({start:U.startLine,end:U.endLine})}),{drafts:nn,commentText:un,setCommentText:Sn,editingDraftId:Nn,setSelection:mr,saveComment:or,cancel:Ar,reset:gi,startEdit:ar,deleteDraft:xi}=xn;i.useEffect(()=>{dn(null),gi(),Tt(null),Ut(""),$t(!1)},[G?.path,gi,Tt]),i.useEffect(()=>{mr(js)},[js,mr]),i.useEffect(()=>{if(!js&&!Nn)return;const U=ze=>{const Ke=ze.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]")||un.trim()||(dn(null),Ar())},Pe=setTimeout(()=>{document.addEventListener("click",U)},100);return()=>{clearTimeout(Pe),document.removeEventListener("click",U)}},[Ar,un,Nn,js]);const Br=i.useCallback((U,Pe)=>{const ze=Pe??js??void 0;Pe&&dn(Pe),or(U,ze),dn(null)},[js,or]),Zr=i.useCallback((U,Pe)=>{const ze=[];for(const Ke of Pe){if(!(Ke&&typeof Ke.name=="string"&&Ke.name.length>0)||!p&&Ke.name.startsWith(".")||!y&&k1(Ke.name))continue;const lt=Ke.name,ot=qs(Ke.path||""),Zt=ot?j1(ot)?ot:qs(`${U}/${ot}`):qs(`${U}/${lt}`),ks=Ke.isDirectory?"directory":"file",Ds=ks==="file"&<.includes(".")?lt.split(".").pop()?.toLowerCase():void 0;ze.push({name:lt,path:Zt,type:ks,extension:Ds})}return v1(ze)},[y,p]),In=i.useCallback(async U=>{const Pe=qs(U.trim());if(!Pe||bt.current.has(Pe)||_e.current.has(Pe))return;_e.current=new Set(_e.current),_e.current.add(Pe);const ze=st.current+1;st.current=ze,Qe.current=new Map(Qe.current),Qe.current.set(Pe,ze);const Ke=()=>Qe.current.get(Pe)===ze;await(n.listDirectory?n.listDirectory(Pe).then(ot=>ot.entries.map(Zt=>({name:Zt.name,path:Zt.path,isDirectory:Zt.isDirectory}))):Jn.listLocalDirectory(Pe).then(ot=>ot.map(Zt=>({name:Zt.name,path:Zt.path,isDirectory:Zt.isDirectory})))).then(ot=>{if(!Ke())return;const Zt=Zr(Pe,ot);bt.current=new Set(bt.current),bt.current.add(Pe),xt(ks=>{if(!ks[Pe])return ks;const Ds={...ks};return delete Ds[Pe],Ds}),Je(ks=>({...ks,[Pe]:Zt}))}).catch(ot=>{if(!Ke())return;const Zt=ot instanceof Error?ot.message:String(ot??"");if(Zt==="Directory not found"&&b&&Pe!==b){P(b,Pe),xt(ks=>{if(!ks[Pe])return ks;const Ds={...ks};return delete Ds[Pe],Ds});return}console.error("Failed to load files directory:",ot),xt(ks=>({...ks,[Pe]:Zt}))}).finally(()=>{Ke()&&(Qe.current=new Map(Qe.current),Qe.current.delete(Pe),_e.current=new Set(_e.current),_e.current.delete(Pe))})},[n,Zr,P,b]),lr=i.useCallback(async()=>{b&&(bt.current=new Set,_e.current=new Set,Qe.current=new Map,xt({}),Je(U=>Object.keys(U).length===0?U:{}),await In(b))},[In,b]),Js=i.useCallback(async U=>{if(!U){await lr();return}const Pe=qs(U);bt.current=new Set(bt.current),bt.current.delete(Pe),_e.current=new Set(_e.current),_e.current.delete(Pe),await In(Pe)},[In,lr]),Hs=i.useRef(""),_r=i.useRef("");i.useEffect(()=>{if(!b)return;const U=`${b}|h${p?"1":"0"}|g${y?"1":"0"}`,Pe=Hs.current!==b,ze=_r.current!==U;!Pe&&!ze||(Pe&&(Hs.current=b,_t(""),Pt(null),Bt(""),Wt(null),D(!1)),ze&&(_r.current=U,bt.current=new Set,_e.current=new Set,Qe.current=new Map,xt({}),Je(Ke=>Object.keys(Ke).length===0?Ke:{}),In(b)))},[In,b,y,p]),i.useEffect(()=>{if(!n.listDirectory)return;const U=()=>{if(!document.hidden&&ce.length>0)for(const Pe of ce)Js(Pe)};return document.addEventListener("visibilitychange",U),()=>document.removeEventListener("visibilitychange",U)},[ce,n.listDirectory,Js]),i.useEffect(()=>{if(!n.listDirectory||ce.length===0)return;const U=setInterval(()=>{if(!document.hidden)for(const Pe of ce)Js(Pe)},8e3);return()=>clearInterval(U)},[ce,n.listDirectory,Js]);const Li=i.useCallback(async U=>{if(U?.preventDefault(),!Is||!Ns)return;Zn(!0);const Pe=()=>{ys(null)},ze=lt=>{le.error(lt)},Ke=()=>{Zn(!1)};if(Ns==="createFile"){if(!$s.trim()){ze(e("sidebarFilesTree.toast.filenameRequired")),Ke();return}if(!n.writeFile){ze(e("sidebarFilesTree.toast.writeNotSupported")),Ke();return}const lt=Is.path,ot=lt?`${lt}/`:"",Zt=qs(`${ot}${$s.trim()}`);await n.writeFile(Zt,"").then(async ks=>{ks.success&&(le.success(e("sidebarFilesTree.toast.fileCreated")),await Js(lt)),Pe()}).catch(()=>ze(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}if(Ns==="createFolder"){if(!$s.trim()){ze(e("sidebarFilesTree.toast.folderNameRequired")),Ke();return}const lt=Is.path,ot=lt?`${lt}/`:"",Zt=qs(`${ot}${$s.trim()}`);await n.createDirectory(Zt).then(async ks=>{ks.success&&(le.success(e("sidebarFilesTree.toast.folderCreated")),await Js(lt)),Pe()}).catch(()=>ze(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}if(Ns==="rename"){if(!$s.trim()){ze(e("sidebarFilesTree.toast.nameRequired")),Ke();return}if(!n.rename){ze(e("sidebarFilesTree.toast.renameNotSupported")),Ke();return}const lt=Is.path,ot=lt.split("/").slice(0,-1).join("/"),Zt=ot?`${ot}/`:"",ks=qs(`${Zt}${$s.trim()}`);await n.rename(lt,ks).then(async Ds=>{Ds.success&&(le.success(e("sidebarFilesTree.toast.renamedSuccessfully")),await Js(ot),b&&de(b,lt),(G?.path===lt||G?.path.startsWith(`${lt}/`))&&(b&&F(b,null),_t(""),Pt(null),Bt(""),Wt(null),d&&D(!1))),Pe()}).catch(()=>ze(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}if(Ns==="delete"){if(!n.delete){ze(e("sidebarFilesTree.toast.deleteNotSupported")),Ke();return}const lt=Is.path,ot=lt.split("/").slice(0,-1).join("/");await n.delete(lt).then(async Zt=>{Zt.success&&(le.success(e("sidebarFilesTree.toast.deletedSuccessfully")),await Js(ot),b&&de(b,lt),(G?.path===lt||G?.path.startsWith(`${lt}/`))&&(b&&F(b,null),_t(""),Pt(null),Bt(""),Wt(null),d&&D(!1))),Pe()}).catch(()=>ze(e("sidebarFilesTree.toast.operationFailed"))).finally(Ke);return}Ke()},[Ns,Is,$s,n,Js,d,de,b,G?.path,F,e]);i.useEffect(()=>{if(!g){At([]),kt(!1);return}const U=k.trim();if(!U){At([]),kt(!1);return}let Pe=!1;return kt(!0),C(g,U,150,{includeHidden:p,respectGitignore:!y,type:"file"}).then(ze=>{if(Pe)return;const lt=ze.filter(ot=>y||!C1(ot.path)).map(ot=>({name:ot.name,path:qs(ot.path),type:"file",extension:ot.extension,relativePath:ot.relativePath}));At(lt)}).catch(()=>{Pe||At([])}).finally(()=>{Pe||kt(!1)}),()=>{Pe=!0}},[g,k,C,p,y]);const ei=i.useCallback(async(U,Pe)=>{if(n.readFile)return(await n.readFile(U,{...Pe??{},directory:b||void 0})).content??"";const ze=new URLSearchParams({path:U});Pe?.allowOutsideWorkspace&&ze.set("allowOutsideWorkspace","true"),Pe?.outsideFileGrant&&ze.set("outsideFileGrant",Pe.outsideFileGrant),Pe?.optional&&ze.set("optional","true"),b&&ze.set("directory",b);const Ke=await Cs(`/api/fs/read?${ze.toString()}`,{cache:Pe?.optional?"no-store":"default"});if(!Ke.ok){const lt=await Ke.json().catch(()=>({error:Ke.statusText}));throw new Error(lt.error||e("filesView.error.readFileFailed"))}return Ke.text()},[n,b,e]),hr=i.useCallback(async(U,Pe)=>{if(n.statFile){const ze=await n.statFile(U,{...Pe??{},directory:b||void 0});return{path:ze.path,size:ze.size,mtimeMs:ze.mtimeMs}}return null},[n,b]);i.useEffect(()=>{if(!b||!n.statFile||Ie.length===0)return;let U=!1;const Pe=[...Ie];return Promise.all(Pe.map(async ze=>{try{const Ke=await n.statFile?.(ze,{directory:b||void 0});!U&&Ke&&!Ke.isFile&&de(b,ze)}catch(Ke){!U&&Hu(Ke)&&de(b,ze)}})),()=>{U=!0}},[n,Ie,de,b]);const bi=i.useMemo(()=>et.length>bo?`${et.slice(0,bo)}
|
|
31
|
-
|
|
32
|
-
… truncated …`:et,[et]),bn=Lt!==bi,pr=i.useCallback(async()=>{if(!G||!n.writeFile)return le.error(e("filesView.toast.savingNotSupported")),!1;if(!bn)return!0;if(Lt===""&&et!==""&&es!==G.path)return console.warn(`[saveDraft] refusing to save empty draft for "${G.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;$t(!0);try{const U=I1(Lt,ls);return(await n.writeFile(G.path,U))?.success?(_t(Lt),G?.path&&Fd(G.path)&&(us.current=Lt,cs.current=Lt),hr(G.path).then(ze=>{ze&&(wt.current=ze)}).catch(()=>{}),!0):(le.error(e("filesView.toast.writeFileFailed")),!1)}catch(U){return le.error(U instanceof Error?U.message:e("filesView.toast.saveFailed")),!1}finally{$t(!1)}},[Lt,et,n,bn,ls,es,hr,G,e]);i.useEffect(()=>{if(!bn){Tt(null);return}const U=Pe=>jn.current?(jn.current=!1,!0):(Fs(!0),sn.current=Pe,!1);return Tt(U),()=>{Ee.getState().mainTabGuard===U&&Tt(null)}},[bn,Tt]),i.useEffect(()=>{try{window.localStorage.setItem(Xm,qt?"true":"false")}catch{}},[qt]),i.useEffect(()=>{qt||(bs("idle"),Vt.current&&(clearTimeout(Vt.current),Vt.current=null))},[qt]);const Vr=1500;i.useEffect(()=>{const U=!!(G&&n.writeFile);if(!(!qt||!bn||!U||rs))return Vt.current=setTimeout(()=>{pr().then(Pe=>{Pe&&(bs("saved"),setTimeout(()=>bs("idle"),2e3))})},Vr),()=>{Vt.current&&(clearTimeout(Vt.current),Vt.current=null)}},[qt,Lt,bn,G,n.writeFile,rs,pr]),i.useEffect(()=>{bs("idle")},[G?.path]),i.useEffect(()=>{const U=Pe=>{jc(Pe)&&(Pe.key.toLowerCase()==="s"?(Pe.preventDefault(),Vt.current&&(clearTimeout(Vt.current),Vt.current=null),rs||pr().then(ze=>{ze&&(bs("saved"),setTimeout(()=>bs("idle"),2e3))})):Pe.key.toLowerCase()==="f"&&(Pe.preventDefault(),R(!0)))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[rs,pr]);const yi=i.useCallback(async U=>{const Pe=Ot.current+1;Ot.current=Pe;const ze=()=>{if(!b)return!1;const Ds=fn.getState().byRoot[b],xr=Ds?.selectedPath??Ds?.openPaths[0]??null;return Ot.current===Pe&&xr===U.path};Pt(null),Bt(""),Wt(null);const Ke=Ri(U.path),lt=U.path.toLowerCase().endsWith(".svg"),ot=Od(U.path);if(d&&D(!0),r.isDesktop&&Ke&&!lt){_t(""),Ut(""),Xe(!0);return}if(!r.isDesktop&&Ke&&!lt){_t(""),Ut(""),Wt(U.path),Xe(!1);return}if(ot){_t(""),Ut(""),Wt(U.path),Xe(!1);return}Xe(!0);const Zt=Md(U.path),ks={allowOutsideWorkspace:t==="editor-only"&&!!b&&!Ea(U.path,b),outsideFileGrant:Zt};await ei(U.path,ks).then(Ds=>{if(!ze())return;const xr=Zm(Ds);xs(D1(Ds)),_t(xr),us.current=xr,cs.current=xr,Ut(xr.length>bo?`${xr.slice(0,bo)}
|
|
33
|
-
|
|
34
|
-
… truncated …`:xr),Wt(U.path),hr(U.path,ks).then(cr=>{cr&&ze()&&(wt.current=cr)}).catch(()=>{})}).catch(Ds=>{if(ze()){if(A1(Ds)){if(Xe(!1),b&&F(b,null),Pt(null),_t(""),Ut(""),Wt(null),wt.current=null,v.trim().length>0&&S(""),d&&D(!1),b){const cr=[...Wu(U.path,b),U.path];cr.length>0&&be(b,cr);for(const ol of cr)bt.current.has(ol)||In(ol)}return}if(Hu(Ds)){b&&de(b,U.path),_t(""),Ut(""),Pt(null),wt.current=null,d&&D(!1);return}_t(""),Ut(""),Pt(Ds instanceof Error?Ds.message:e("filesView.error.readFileFailed")),wt.current=null}}).finally(()=>{ze()&&Xe(!1)})},[be,d,In,t,ei,hr,de,b,r.isDesktop,v,F,e]),$r=i.useCallback(async(U,Pe)=>{if(!b)return;const ze=Wu(U,b),Ke=Pe?[...ze,U]:ze;Ke.length>0&&be(b,Ke);const lt=Ke.map(ot=>{if(!bt.current.has(ot))return In(ot)}).filter(Boolean);await Promise.all(lt)},[be,In,b]),Bi=i.useCallback((U,Pe)=>{const ze=Pe.findIndex(Ke=>Ke.path===U);return ze===-1||Pe.length<=1?null:Pe[ze+1]??Pe[ze-1]??null},[]),rn=i.useCallback(async U=>{if(jn.current)jn.current=!1;else if(bn){Fs(!0),Ws.current=U;return}b&&(F(b,U.path),xe(b,U.path),$r(U.path,!1)),Pt(null),Bt(""),_t(""),us.current="",cs.current="",Ut(""),Wt(null),d&&D(!0)},[xe,$r,bn,d,b,F]);i.useEffect(()=>{G?.path&&$r(G.path,!1)},[$r,G?.path]),i.useEffect(()=>{if(!G){Ot.current+=1,Xe(!1);return}es!==G.path&&yi(G)},[yi,es,G]);const wi=i.useRef(bn);wi.current=bn,i.useEffect(()=>{if(!G?.path||es!==G.path)return;let U=!1;const Pe=window.setInterval(()=>{document.hidden||hr(G.path,J).then(ze=>{if(U||!ze)return;const Ke=wt.current;if(!Ke||Ke.path!==G.path){wt.current=ze;return}const lt=ze.mtimeMs!==void 0&&Ke.mtimeMs!==void 0&&ze.mtimeMs!==Ke.mtimeMs,ot=ze.size!==Ke.size;!lt&&!ot||wi.current||(wt.current=ze,Wt(null))}).catch(()=>{})},2e3);return()=>{U=!0,window.clearInterval(Pe)}},[es,hr,G?.path,J]);const _i=i.useCallback(()=>{const U=Ws.current,Pe=sn.current,ze=Dn.current;if(Ws.current=null,sn.current=null,Dn.current=null,jn.current=!0,Fs(!1),Ut(bi),ze){b&&ke(b,ze),G?.path===ze&&(U?rn(U):(b&&F(b,null),_t(""),Pt(null),Bt(""),Wt(null),d&&D(!1)));return}if(U){rn(U);return}Pe&&(Tt(null),Ee.getState().setActiveMainTab(Pe))},[bi,rn,d,ke,b,G?.path,Tt,F]),mo=i.useCallback(async()=>{const U=Ws.current,Pe=sn.current,ze=Dn.current;if(!await pr()){jn.current=!1;return}if(Ws.current=null,sn.current=null,Dn.current=null,jn.current=!0,Fs(!1),ze){b&&ke(b,ze),G?.path===ze&&(U?await rn(U):(b&&F(b,null),_t(""),Pt(null),Bt(""),Wt(null),d&&D(!1)));return}if(U){await rn(U);return}Pe&&(Tt(null),Ee.getState().setActiveMainTab(Pe))},[rn,d,ke,b,pr,G?.path,Tt,F]),Y=i.useCallback(U=>{const Pe=G?.path===U,ze=Bi(U,ge);if(Pe&&bn){Fs(!0),Ws.current=ze,Dn.current=U;return}if(b&&ke(b,U),!!Pe){if(ze){rn(ze);return}b&&F(b,null),_t(""),Pt(null),Bt(""),Wt(null),d&&D(!1)}},[Bi,rn,bn,d,ge,ke,b,G?.path,F]),Ce=i.useCallback(U=>{if(Ie.includes(U))return"open";if(w?.files){const Pe=U.startsWith(b+"/")?U.slice(b.length+1):U,ze=w.files.find(Ke=>Ke.path===Pe);if(ze){if(ze.index==="A"||ze.working_dir==="?")return"git-added";if(ze.index==="D")return"git-deleted";if(ze.index==="M"||ze.working_dir==="M")return"git-modified"}}return null},[Ie,w,b]),Re=i.useCallback(U=>{if(!w?.files)return null;const Pe=U.startsWith(b+"/")?U.slice(b.length+1):U,ze=Pe?`${Pe}/`:"";let Ke=0,lt=0;for(const ot of w.files)ot.path.startsWith(ze)&&((ot.index==="M"||ot.working_dir==="M")&&Ke++,(ot.index==="A"||ot.working_dir==="?")&<++);return Ke+lt>0?{modified:Ke,added:lt}:null},[w,b]),$e=i.useCallback(async U=>{const Pe=qs(U);b&&(ue(b,Pe),bt.current.has(Pe)||await In(Pe))},[In,b,ue]),dt=i.useMemo(()=>({canRename:gs,canCreateFile:fr,canCreateFolder:Kn,canDelete:Ts,canReveal:Sr}),[gs,fr,Kn,Ts,Sr]);function Rt(U,Pe){const ze=He[U]??[];return ze.map((Ke,lt)=>{const ot=Ke.type==="directory",Zt=ot&&ce.includes(Ke.path),ks=G?.path===Ke.path,Ds=lt===ze.length-1;return s.jsxs("li",{className:"relative",children:[Pe>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ds&&s.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),s.jsx(R1,{node:Ke,root:b,isExpanded:Zt,isActive:ks,isMobile:d,alwaysShowActions:u,status:ot?void 0:Ce(Ke.path),badge:ot?Re(Ke.path):void 0,permissions:dt,downloadFile:n.downloadFile,contextMenuPath:cn,setContextMenuPath:We,rightClickMenuPath:Xt,setRightClickMenuPath:As,onSelect:rn,onToggle:$e,onRevealPath:Lr,onOpenDialog:rr}),ot&&Zt&&s.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[nt[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:nt[Ke.path],children:nt[Ke.path]}),s.jsxs(Ve,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Js(Ke.path)},children:[s.jsx(I,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):null,Rt(Ke.path,Pe+1)]})]},Ke.path)})}const Qt=!!(G?.path&&Ri(G.path)),Jt=!!(G?.path&&G.path.toLowerCase().endsWith(".svg")),vs=!!(G?.path&&Od(G.path)),gr=i.useMemo(()=>qs(Yt?.path??""),[Yt?.path]),Dr=!!(Yt&&gr&&Se&&Se===gr&&!gt&&!jt&&!Qt&&!vs),Ir=i.useMemo(()=>nc(b,Se),[Se,b]),el=!!(G&&(!Qt||Jt)&&!vs&&et.length>0),tl=!!(G&&Ir.length>0),ee=!!(G&&!Oe&&!Qt&&!vs&&n.writeFile&&et.length<=bo),at=!!(G?.path&&Gu(G.path)),it=!!(G?.path&&T1(G.path)),St=!!(G?.path&&Zo(G.path)),zt=!!(G?.path&&Fd(G.path)),on=!!(G&&!Qt&&!vs)&&!at&&!zt&&!(St&&ie==="preview"),yn=i.useMemo(()=>Se?om(Se):null,[Se]),[kn,Cn]=i.useState(null);i.useEffect(()=>{let U=!1;const Pe=G?.path;if(!Pe||yn){Cn(null);return}return Cn(null),vg(Pe).then(ze=>{U||Cn(ze)}),()=>{U=!0}},[G?.path,yn]),i.useEffect(()=>{!ee&&Q==="edit"&&H("view")},[ee,Q]);const _n="openchamber:files:md-viewer-mode",ti="openchamber:files:html-viewer-mode",vi="openchamber:files:json-viewer-mode";i.useEffect(()=>{const U=G?.path;if(!U)return;const Pe=Bn?"view":"edit";H(Z.current[U]??Pe);let ze=Bn?"preview":"edit";try{const ot=localStorage.getItem(_n);(ot==="preview"||ot==="edit")&&(ze=ot)}catch{}oe(je.current[U]??ze);let Ke=Bn?"preview":"edit";try{const ot=localStorage.getItem(ti);(ot==="preview"||ot==="edit")&&(Ke=ot)}catch{}Ne(De.current[U]??Ke),pe(Le.current[U]??"preview");let lt=Bn?"tree":"text";try{const ot=localStorage.getItem(vi);(ot==="tree"||ot==="text")&&(lt=ot)}catch{}ve(lt)},[G?.path,Bn]);const ho=i.useCallback(U=>{const Pe=G?.path;Pe&&(Z.current[Pe]=U),H(U)},[G?.path]),Ph=i.useCallback(U=>{const Pe=G?.path;Pe&&(je.current[Pe]=U),oe(U);try{localStorage.setItem(_n,U)}catch{}},[G?.path]),po=i.useCallback(()=>X,[X]),Th=i.useCallback(U=>{ve(U);try{localStorage.setItem(vi,U)}catch{}},[]),Rh=i.useCallback(U=>{const Pe=G?.path;Pe&&(De.current[Pe]=U),Ne(U);try{localStorage.setItem(ti,U)}catch{}},[G?.path]),Eh=i.useCallback(U=>{const Pe=G?.path;if(Pe&&(Le.current[Pe]=U),yt.current&&(clearTimeout(yt.current),yt.current=null),Ue.current!==null&&(cancelAnimationFrame(Ue.current),Ue.current=null),U==="edit")Ut(us.current||et),pe(U);else{us.current=Lt;const ze=Pe;pe("edit"),Ue.current=requestAnimationFrame(()=>{Ue.current=requestAnimationFrame(()=>{Ue.current=null,!(b&&ze&&fn.getState().byRoot[b]?.selectedPath!==ze)&&(se(Ke=>Ke+1),pe("preview"))})});return}},[Lt,et,b,G?.path]),sl=i.useCallback(async(U,Pe)=>{if(!n.writeFile||Pe===cs.current)return!1;if(!(await n.writeFile(U,Pe))?.success)return le.error(e("filesView.toast.writeFileFailed")),!1;us.current=Pe,cs.current=Pe,Ut(Pe);const Ke=await hr(U,J).catch(()=>null);return Ke&&(wt.current=Ke),!0},[n,hr,J,e]);i.useEffect(()=>()=>{yt.current&&(clearTimeout(yt.current),yt.current=null),Ue.current!==null&&(cancelAnimationFrame(Ue.current),Ue.current=null)},[K,G?.path]);const Mh=i.useCallback(U=>{if(us.current=U,!G?.path||K!=="preview"||!n.writeFile)return;yt.current&&clearTimeout(yt.current);const Pe=G.path;yt.current=setTimeout(()=>{yt.current=null,sl(Pe,U).then(ze=>{ze&&(os(!0),setTimeout(()=>os(!1),1500))}).catch(ze=>{le.error(ze instanceof Error?ze.message:e("filesView.toast.saveFailed"))})},Vr)},[K,n.writeFile,sl,G?.path,e]),Fh=i.useMemo(()=>zt&&(us.current||Lt)||et,[Lt,et,zt]),Qc=i.useCallback(()=>ie,[ie]);i.useEffect(()=>{const U=ze=>{const Ke=ze?"view":"edit",lt=ze?"preview":"edit",ot=ze?"tree":"text";for(const Zt of Ie)Z.current[Zt]=Ke,Gu(Zt)&&(je.current[Zt]=lt),Zo(Zt)&&(De.current[Zt]=lt);H(Ke),oe(lt),Ne(lt),ve(ot);try{localStorage.setItem(_n,lt),localStorage.setItem(ti,lt),localStorage.setItem(vi,ot)}catch{}},Pe=ze=>{const Ke=!!ze.detail?.enabled;U(Ke)};return window.addEventListener("openchamber:file-viewer-preview-mode-changed",Pe),()=>{window.removeEventListener("openchamber:file-viewer-preview-mode-changed",Pe)}},[Ie]),i.useEffect(()=>{if(!Yt||!b)return;const U=()=>{typeof window>"u"||ms.current===null&&(ms.current=window.requestAnimationFrame(()=>{ms.current=null,mt(zr=>zr+1)}))},Pe=(zr,ji)=>{if(zr.state.doc.length!==ji.length)return!1;if(ji.length===0)return!0;const al=Math.min(128,ji.length);if(zr.state.sliceDoc(0,al)!==ji.slice(0,al))return!1;const fd=Math.max(0,ji.length-al);return zr.state.sliceDoc(fd,ji.length)===ji.slice(fd)},ze=qs(Yt.path);if(!ze){ts(null),hs.current={key:"",attempts:0};return}const Ke=`${ze}:${Yt.line}:${Yt.column??1}`;if(hs.current.key!==Ke&&(hs.current={key:Ke,attempts:0}),G?.path!==ze){if(ps)return;rn(W(ze));return}if(gt||es!==ze)return;if(jt||Qt||vs){ts(null),hs.current={key:"",attempts:0};return}if(!ee)return;if(Q!=="edit"){H("edit");return}const lt=ct.current;if(!lt){U();return}if(!Pe(lt,Lt)){U();return}const ot=Math.max(1,Math.min(Yt.line,lt.state.doc.lines)),Zt=lt.state.doc.line(ot),ks=Math.max(1,Yt.column||1),Ds=Math.max(0,Zt.to-Zt.from),xr=Math.min(Ds,ks-1),cr=Zt.from+xr;if(!(lt.state.selection.main.head===cr)||hs.current.attempts===0){hs.current.attempts+=1,lt.dispatch({selection:{anchor:cr},effects:li.scrollIntoView(cr,{y:"center"})}),lt.focus(),U();return}typeof window<"u"&&window.requestAnimationFrame(()=>{const zr=ct.current;zr&&(zr.dispatch({selection:{anchor:cr},effects:li.scrollIntoView(cr,{y:"center"})}),zr.focus())}),ts(null),hs.current={key:"",attempts:0}},[ee,ps,Lt,Ht,jt,gt,Qt,vs,es,rn,Yt,b,G?.path,ts,Q,W]),i.useEffect(()=>{if(!ds||!b)return;const U=qs(ds);if(!U){Ls(null);return}if(G?.path!==U){if(ps)return;rn(W(U));return}if(!(gt||es!==U||jt||Qt||vs)){if(ee&&Q==="edit"){const Pe=ct.current;if(!Pe)return;Pe.focus()}Ls(null)}},[ee,ps,jt,gt,rn,Qt,vs,es,ds,b,G?.path,Ls,Q,W]);const Vi=i.useCallback(U=>{if(!d||!U||!U.hasFocus||typeof window>"u")return;const Pe=window.visualViewport;if(!Pe)return;const ze=document.documentElement.clientHeight||window.innerHeight;if(Math.max(0,ze-(Pe.offsetTop+Pe.height))<=0)return;const lt=U.state.selection.main.head,ot=U.coordsAtPos(lt);if(!ot)return;const Zt=Math.round(Pe.offsetTop+Pe.height),Ds=ot.bottom+20-Zt;Ds<=0||(U.scrollDOM.scrollTop+=Ds)},[d]);i.useEffect(()=>{if(!d||typeof window>"u")return;const U=()=>{window.requestAnimationFrame(()=>{Vi(ct.current)})},Pe=window.visualViewport;return Pe?.addEventListener("resize",U),Pe?.addEventListener("scroll",U,{passive:!0}),document.addEventListener("selectionchange",U),()=>{Pe?.removeEventListener("resize",U),Pe?.removeEventListener("scroll",U),document.removeEventListener("selectionchange",U)}},[d,Vi]),i.useEffect(()=>{if(!ee||Q!=="edit"||d)return;const U=di("open_go_to_line",Ks),Pe=ze=>{const Ke=ze.target;if(Ke?.closest('[role="dialog"]'))return;const lt=!!Ke?.closest(".cm-editor");Ke?.closest('input, textarea, [contenteditable="true"], [role="textbox"]')&&!lt||!document.activeElement?.closest(".cm-editor")||oa(ze,U)&&(ze.preventDefault(),On(!0))};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[ee,d,Ks,Q]);const Jc=i.useMemo(()=>{if(!G?.path)return[ql(o)];const U=Ti(G.path),Pe=[ql(o,U?{syntaxColors:!1}:void 0)],ze=yn??kn;return ze&&Pe.push(ze),U&&Pe.push(Im({language:U,themeName:o.metadata.id,theme:am(o)})),N&&Pe.push(li.lineWrapping),d&&Pe.push(li.updateListener.of(Ke=>{Ke.view.hasFocus&&(Ke.selectionSet||Ke.focusChanged||Ke.viewportChanged||Ke.geometryChanged)&&window.requestAnimationFrame(()=>{Vi(Ke.view)})})),Pe},[o,G?.path,yn,kn,N,d,Vi]),Xc=i.useMemo(()=>({light:Me.metadata.id,dark:Fe.metadata.id}),[Me.metadata.id,Fe.metadata.id]),Vo=G?.path&&Qt&&!r.isDesktop&&!Jt?`${G.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",$o=G?.path&&vs?`${G.path}|${J.allowOutsideWorkspace?"outside":"workspace"}|${J.outsideFileGrant??""}`:"",zo=G?.path&&St&&ie==="preview"&&!r.isVSCode?G.path:"",nl=e("filesView.error.readFileFailed"),{readyKey:Zc,nonce:ed}=Dl(Vo,Pt,nl),{readyKey:td,nonce:Oh}=Dl(zo,Pt,nl),{readyKey:sd,nonce:nd}=Dl($o,Pt,nl),rd=!!(Vo&&Zc!==Vo),Lh=!!(zo&&td!==zo),id=!!($o&&sd!==$o),od=G?.path&&Qt?r.isDesktop?Jt?`data:${Ld(G.path)};utf8,${encodeURIComponent(et)}`:is:Jt?`data:${Ld(G.path)};utf8,${encodeURIComponent(et)}`:Zc===Vo?Pi().authenticatedAsset("/api/fs/raw",{path:G.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:b||void 0}):"":"",ad=G?.path&&vs&&sd===$o?Pi().authenticatedAsset("/api/fs/raw",{path:G.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:b||void 0}):"",ld=i.useCallback(U=>s.jsx("div",{className:"h-full overflow-hidden bg-[var(--surface-background)]",children:s.jsx("iframe",{src:ad,className:"h-full w-full border-0",title:U.name},nd)}),[ad,nd]);i.useEffect(()=>{let U=!1;return(async()=>{if(!r.isDesktop||!G?.path||!Qt||Jt){Gt.current&&(URL.revokeObjectURL(Gt.current),Gt.current=""),Bt("");return}Pt(null),Gt.current&&(URL.revokeObjectURL(Gt.current),Gt.current=""),await(n.readFileBinary?n.readFileBinary(G.path,J).then(Ke=>Ke.dataUrl):(async()=>{const Ke=await Cs("/api/fs/raw",{query:{path:G.path,allowOutsideWorkspace:J.allowOutsideWorkspace?"true":void 0,outsideFileGrant:J.outsideFileGrant,directory:b||void 0}});if(!Ke.ok)throw new Error(e("filesView.error.readFileFailed"));const lt=await Ke.blob(),ot=URL.createObjectURL(lt);return U?(URL.revokeObjectURL(ot),""):(Gt.current=ot,ot)})()).then(Ke=>{U||(Bt(Ke),Wt(G.path))}).catch(Ke=>{Gt.current&&(URL.revokeObjectURL(Gt.current),Gt.current=""),U||(Bt(""),Pt(Ke instanceof Error?Ke.message:e("filesView.error.readFileFailed")),Wt(null))}).finally(()=>{U||Xe(!1)})})(),()=>{U=!0}},[n,Qt,Jt,b,r.isDesktop,G?.path,J,e]),i.useEffect(()=>()=>{Gt.current&&(URL.revokeObjectURL(Gt.current),Gt.current="")},[]);const Bh=i.useCallback(()=>ys(null),[]),_h=i.useMemo(()=>Rm({drafts:nn,editingDraftId:Nn,commentText:un,onTextChange:Sn,selection:js,isDragging:rt,fileLabel:G?.path??"",newWidgetId:"files-new-comment-input",mapDraftToRange:U=>({start:U.startLine,end:U.endLine}),onSave:Br,onCancel:()=>{dn(null),Ar()},onEdit:U=>{ar(U),dn({start:U.startLine,end:U.endLine})},onDelete:xi}),[Ar,un,xi,Nn,nn,Br,rt,js,G?.path,Sn,ar]),cd=i.useCallback((U,Pe)=>s.jsx("div",{className:"h-full",children:s.jsx(Yh,{file:{name:U.name,contents:Pe,lang:Ti(U.path)||void 0},options:{disableFileHeader:!0,overflow:N?"wrap":"scroll",theme:Xc,themeType:o.metadata.variant==="dark"?"dark":"light"},className:"block h-full w-full",style:{height:"100%"}})}),[o.metadata.variant,Xc,N]),rl=({exitFullscreenOnly:U=!1,layout:Pe="floating"}={})=>{if(!G)return null;const Ke=Pe==="docked"?"pointer-events-auto flex flex-wrap items-center gap-1":"pointer-events-auto flex items-center gap-1 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-1 shadow-sm",lt=(ot,Zt)=>s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:Zt})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:ot})]});return s.jsxs("div",{className:Ke,children:[ee&&Q==="edit"&&s.jsxs(s.Fragment,{children:[rs?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-muted-foreground typography-meta",children:[s.jsx(I,{name:"loader-4",className:"size-3.5 animate-spin"}),e("filesView.editor.saving")]}):qt&&Dt==="saved"&&!bn?s.jsxs("span",{className:"flex items-center gap-1 px-1 text-[color:var(--status-success)] typography-meta",children:[s.jsx(I,{name:"check",className:"size-3.5"}),e("filesView.editor.saved")]}):bn?lt(e(qt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${cl()}+S`}),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>{pr()},className:"h-6 gap-1 px-1 text-muted-foreground opacity-80 hover:bg-transparent hover:opacity-100 focus-visible:bg-transparent active:bg-transparent",title:e(qt?"filesView.editor.saveNowTitle":"filesView.editor.saveNowManualTitle",{shortcut:`${cl()}+S`}),"aria-label":e("filesView.editor.saveAria",{shortcut:`${cl()}+S`}),children:s.jsx(I,{name:"save-3",className:"size-4"})})):null,lt(e(qt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>ln(ot=>!ot),className:Te("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",qt?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(qt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),"aria-label":e(qt?"filesView.editor.autoSaveOn":"filesView.editor.manualSave"),children:qt?s.jsx(I,{name:"file-check-fill",className:"size-4"}):s.jsx(I,{name:"file-check",className:"size-4"})}))]}),s.jsxs(tn,{onOpenChange:te,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Zs,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"sm",className:"size-6 p-0 text-foreground opacity-100 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.openInDesktopApp"),"aria-label":e("filesView.editor.openInDesktopApp"),children:s.jsx(I,{name:"file-transfer",className:"size-4"})})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.editor.openInDesktopApp")})]}),s.jsxs(en,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[Ln.map(ot=>s.jsxs(ws,{className:"flex items-center gap-2",onClick:()=>{Cr(ot)},children:[s.jsx(w1,{label:ot.label,iconDataUrl:ot.iconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:ot.label})]},ot.id)),pn?s.jsxs(ws,{className:"flex items-center gap-2",onClick:()=>{kr(!0)},children:[s.jsx(I,{name:"refresh",className:"size-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:e("filesView.editor.refreshApps")})]}):null]})]}),!Qt&&!vs&&s.jsxs(s.Fragment,{children:[lt(e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>B(!N),className:Te("size-6 p-0 transition-opacity hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",N?"text-foreground opacity-100":"text-muted-foreground opacity-65 hover:opacity-100"),title:e(N?"filesView.editor.disableLineWrap":"filesView.editor.enableLineWrap"),children:s.jsx(I,{name:"text-wrap",className:"size-4"})})),Q==="edit"&&s.jsxs(s.Fragment,{children:[lt(e("filesView.editor.findInFile"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:ot=>{R(!_),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(I,{name:"search",className:"size-4"})})),lt(e("filesView.editor.goToLine"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:ot=>{On(Zt=>!Zt),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(I,{name:"menu-fold-2",className:"size-4"})})),s.jsx(g1,{open:Os,onOpenChange:On,view:ct.current,variant:"inline"})]})]}),on&&ee&&!it&&!St&&s.jsx(la,{currentMode:Q==="view"?"preview":"edit",onToggle:()=>{ho(Q==="view"?"edit":"view")}}),(at||Zo(G?.path??""))&&s.jsx(la,{currentMode:at?po():Qc(),onToggle:()=>{Zo(G?.path??"")?Rh(Qc()==="preview"?"edit":"preview"):Ph(po()==="preview"?"edit":"preview")}}),at&&po()==="preview"&&Jr&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{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?qe():et.trim()&&Kt(et)},children:ns?s.jsx(I,{name:"stop",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"volume-up",className:"size-4"})})}),s.jsx(Ft,{sideOffset:8,children:e(ns?"filesView.tts.stopSpeaking":"filesView.tts.readAloud")})]}),zt&&s.jsxs(s.Fragment,{children:[s.jsx(la,{currentMode:K,onToggle:()=>Eh(K==="preview"?"edit":"preview")}),K==="preview"&&s.jsx(Ve,{variant:"ghost",size:"sm",onClick:async()=>{const ot=Ge.current?.getXml();if(yt.current&&(clearTimeout(yt.current),yt.current=null),G?.path&&ot){if(!await sl(G.path,ot))return;os(!0),setTimeout(()=>os(!1),1500)}},className:"size-6 p-0 text-foreground hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.diagram.saveDiagram"),children:fs?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"save-3",className:"size-4"})})]}),it&<(e(fe==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>Th(fe==="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(fe==="tree"?"filesView.editor.switchToTextView":"filesView.editor.switchToTreeView"),children:fe==="tree"?s.jsx(I,{name:"code-sslash",className:"size-4"}):s.jsx(I,{name:"node-tree",className:"size-4"})})),el&<(e("filesView.editor.copyFileContents"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:async()=>{(await ur(et)).ok?(zs(!0),ye.current!==null&&window.clearTimeout(ye.current),ye.current=window.setTimeout(()=>{zs(!1)},1200)):le.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFileContents"),"aria-label":e("filesView.editor.copyFileContents"),children:Ps?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"clipboard",className:"size-4"})})),tl&<(e("filesView.editor.copyFilePathTitle",{path:Ir}),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:async()=>{(await ur(Ir)).ok?(Us(!0),Ze.current!==null&&window.clearTimeout(Ze.current),Ze.current=window.setTimeout(()=>{Us(!1)},1200)):le.error(e("filesView.toast.copyFailed"))},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.copyFilePathTitle",{path:Ir}),"aria-label":e("filesView.editor.copyFilePathTitle",{path:Ir}),children:Qs?s.jsx(I,{name:"check",className:"size-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"file-copy-2",className:"size-4"})})),n.downloadFile&<(e("filesView.editor.saveFile"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>{const ot=n.downloadFile;ot&&ot(G.path).catch(Zt=>{console.error("Download failed:",Zt),le.error(e("sidebarFilesTree.toast.operationFailed"))})},className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.saveFile"),"aria-label":e("filesView.editor.saveFile"),children:s.jsx(I,{name:"download",className:"size-4"})})),U?lt(e("filesView.editor.exitFullscreen"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>E(!1),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e("filesView.editor.exitFullscreen"),"aria-label":e("filesView.editor.exitFullscreen"),children:s.jsx(I,{name:"fullscreen-exit",className:"size-4"})})):!d&&t==="full"&<(e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>E(!T),className:"size-6 p-0 hover:bg-transparent focus-visible:bg-transparent active:bg-transparent",title:e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),"aria-label":e(T?"filesView.editor.exitFullscreen":"filesView.editor.fullscreen"),children:T?s.jsx(I,{name:"fullscreen-exit",className:"size-4"}):s.jsx(I,{name:"fullscreen",className:"size-4"})}))]})},il=s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[s.jsx(Ms,{open:ps,onOpenChange:U=>{U||Fs(!0)},children:s.jsxs(Es,{showCloseButton:!1,className:"max-w-md",children:[s.jsxs(Gs,{children:[s.jsx(Vs,{children:e("filesView.unsaved.title")}),s.jsx(an,{children:e("filesView.unsaved.description")})]}),s.jsxs(nr,{children:[s.jsx(Ve,{variant:"outline",onClick:()=>{mo()},disabled:rs,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(Ve,{variant:"destructive",onClick:_i,children:e("filesView.unsaved.discard")})]})]})}),s.jsxs("div",{className:Te("flex flex-col flex-shrink-0",x&&"border-b border-border/40"),children:[x?s.jsxs("div",{className:"flex min-w-0 items-center px-3 py-1.5",children:[d&&A&&s.jsx("button",{type:"button",onClick:()=>D(!1),"aria-label":e("filesView.editor.back"),className:"inline-flex size-7 flex-shrink-0 items-center justify-center mr-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(I,{name:"arrow-left-s",className:"size-5"})}),d?G?s.jsxs(tn,{children:[s.jsx(Zs,{asChild:!0,children:s.jsxs("button",{type:"button",className:"inline-flex min-w-0 max-w-full items-center gap-1 text-left typography-ui-label font-medium","aria-label":e("filesView.editor.openFilesAria"),children:[s.jsx(Kr,{filePath:G.path,extension:G.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Uu,{name:G.name}),s.jsx(I,{name:"arrow-down-s",className:"size-4 flex-shrink-0 text-muted-foreground"})]})}),s.jsx(en,{align:"start",className:"w-[min(24rem,calc(100vw-2rem))] max-w-[calc(100vw-2rem)]",children:ge.map(U=>{const Pe=G?.path===U.path;return s.jsxs(ws,{onSelect:ze=>{if(ze.target.closest("[data-close-open-file]")){ze.preventDefault();return}Pe||rn(U)},className:Te("flex min-w-0 items-center justify-between gap-2 overflow-hidden",Pe&&"bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]"),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-hidden",children:[s.jsx(Kr,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx(Uu,{name:U.name})]}),s.jsx("button",{type:"button","data-close-open-file":!0,onPointerDown:ze=>{ze.preventDefault(),ze.stopPropagation()},onClick:ze=>{ze.preventDefault(),ze.stopPropagation(),Y(U.path)},className:"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]","aria-label":e("filesView.editor.closeFileAria",{name:U.name}),children:s.jsx(I,{name:"close",className:"size-3.5"})})]},U.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")}):ge.length>0?s.jsxs("div",{className:"relative min-w-0 flex-1",children:[ae.left&&s.jsx("div",{className:"pointer-events-none absolute left-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-r from-background to-transparent"}),ae.right&&s.jsx("div",{className:"pointer-events-none absolute right-0 top-0 bottom-0 w-6 z-10 bg-gradient-to-l from-background to-transparent"}),s.jsx("div",{ref:O,className:"flex min-w-0 items-center gap-1 overflow-x-auto scrollbar-none",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:ge.map(U=>{const Pe=G?.path===U.path;return s.jsxs("div",{title:nc(b,U.path),className:Te("group inline-flex items-center gap-1 rounded-md border px-2 py-1 typography-ui-label transition-colors whitespace-nowrap",Pe?"bg-[var(--interactive-selection)] border-[var(--primary-muted)] text-[var(--interactive-selection-foreground)]":"bg-transparent border-[var(--interactive-border)] text-[var(--surface-muted-foreground)] hover:bg-[var(--interactive-hover)] hover:text-[var(--surface-foreground)]"),children:[s.jsx(Kr,{filePath:U.path,extension:U.extension,className:"size-3.5 flex-shrink-0"}),s.jsx("button",{type:"button",onClick:()=>{Pe||rn(U)},className:"max-w-[12rem] truncate text-left",children:U.name}),s.jsx("button",{type:"button",onClick:ze=>{ze.stopPropagation(),Y(U.path)},className:Te("rounded-sm p-0.5 text-[var(--surface-muted-foreground)] hover:text-[var(--surface-foreground)]",!Pe&&!u&&"opacity-0 group-hover:opacity-100"),"aria-label":e("filesView.editor.closeFileAria",{name:U.name}),children:s.jsx(I,{name:"close",className:"size-3.5"})})]},U.path)})})]}):s.jsx("div",{className:"typography-ui-label font-medium truncate",children:e("filesView.editor.selectFile")})]}):null,gn&&!d&&G?s.jsxs("div",{className:"flex min-w-0 items-center gap-3 border-t border-border/40 bg-[var(--surface-subtle)] px-3 py-1",children:[Ir?s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta text-muted-foreground",title:Ir,children:Ir}):null,s.jsx("div",{className:"ml-auto min-w-0 shrink-0 overflow-x-auto",children:rl({layout:"docked"})})]}):null]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[G&&!_&&!(gn&&!d)&&s.jsx("div",{ref:$,className:"absolute right-3 top-3 z-30",onMouseEnter:()=>V(!0),onMouseLeave:()=>{M.current>0||V(!1)},children:z?rl():s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>V(!0),className:"size-8 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-0 text-muted-foreground shadow-sm hover:text-foreground","aria-label":e("filesView.editor.showControlsAria"),title:e("filesView.editor.controlsTitle"),children:s.jsx(I,{name:"more-2-fill",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.editor.controlsTitle")})]})}),s.jsx(Wn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:G?gt||rd||id?h?s.jsx("div",{className:"p-3"}):s.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{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:od,alt:G?.name??e("filesView.editor.imageAltFallback"),className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"},ed)}):vs?ld(G):G&&zt&&K==="preview"?s.jsx("div",{className:"h-full overflow-hidden",style:{minHeight:"400px"},children:s.jsx(b1,{ref:Ge,xml:Fh,onChange:Mh},`${G.path}:${L}`)}):G&&it&&fe==="tree"?s.jsx(Xs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.jsonViewerUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToTextMode")})]}),children:s.jsx("div",{className:"h-full overflow-auto",children:s.jsx(jg,{jsonString:et,maxHeight:"100%",initiallyExpandedDepth:2})})}):G&&at&&po()==="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(Xs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(so,{content:et,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):G&&St&&ie==="preview"?Lh?s.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground typography-ui-label",children:e("common.loading")}):s.jsx("div",{className:"h-full overflow-hidden",children:s.jsx("iframe",{src:!r.isVSCode&&td===zo?(()=>{const U=G.path.split("/").map(Pe=>encodeURIComponent(Pe)).join("/");return Pi().authenticatedAsset(`/api/fs/serve${U.startsWith("/")?U:`/${U}`}`)})():void 0,srcDoc:r.isVSCode?(()=>{const U=G.path.substring(0,G.path.lastIndexOf("/")+1);return U?et.replace(/<head([^>]*)>/i,`<head$1><base href="${U}">`):et})():void 0,className:"w-full h-full border-none",sandbox:"allow-scripts allow-same-origin allow-forms",title:e("filesView.editor.htmlPreviewTitle")},Oh)}):G&&on&&Q==="view"?cd(G,Lt):s.jsxs("div",{className:Te("relative h-full",Dr&&"overflow-hidden"),ref:It,children:[s.jsx("div",{className:Te("h-full",Dr&&"invisible"),children:s.jsx(Yl,{value:Lt,onChange:Ut,readOnly:!ee,vimMode:qn==="vim",extensions:Jc,className:"h-full",blockWidgets:_h,onViewReady:U=>{ct.current=U,mt(Pe=>Pe+1),window.requestAnimationFrame(()=>{Vi(U)})},onViewDestroy:()=>{ct.current&&(ct.current=null),mt(U=>U+1)},enableSearch:!0,searchOpen:_,onSearchOpenChange:R,highlightLines:js?{start:Math.min(js.start,js.end),end:Math.max(js.start,js.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(U,Pe,ze)=>{if(!(ze instanceof MouseEvent)||ze.button!==0)return!1;ze.preventDefault();const Ke=U.state.doc.lineAt(Pe.from).number;if(js&&!ze.shiftKey&&Math.min(js.start,js.end)===Ke&&Math.max(js.start,js.end)===Ke)return dn(null),Ar(),ir.current=!1,q.current=null,ht(!1),!0;if(d&&js&&!ze.shiftKey){const lt=Math.min(js.start,js.end,Ke),ot=Math.max(js.start,js.end,Ke);return dn({start:lt,end:ot}),ir.current=!1,q.current=null,ht(!1),!0}if(ir.current=!0,q.current=Ke,ht(!0),js&&ze.shiftKey){const lt=Math.min(js.start,Ke),ot=Math.max(js.end,Ke);dn({start:lt,end:ot})}else dn({start:Ke,end:Ke});return!0},mouseover:(U,Pe,ze)=>{if(!(ze instanceof MouseEvent)||ze.buttons!==1||!ir.current||q.current===null)return!1;const Ke=U.state.doc.lineAt(Pe.from).number,lt=Math.min(q.current,Ke),ot=Math.max(q.current,Ke);return dn({start:lt,end:ot}),ht(!0),!1},mouseup:()=>(ir.current=!1,q.current=null,ht(!1),!1)}}})}),Dr&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]}):s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:e("filesView.editor.pickFileFromTree")})})]})]}),Vh=!!(b&&He[b]),dd=b?nt[b]:null,ud=s.jsxs("section",{className:Te("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:Te("flex flex-col gap-2 py-2",d?"px-3":"px-2"),children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1 min-w-0",children:[s.jsx(I,{name:"search",className:"pointer-events-none absolute left-2 top-2 size-4 text-muted-foreground"}),s.jsx(vn,{ref:j,value:v,onChange:U=>S(U.target.value),placeholder:e("filesView.tree.search.placeholder"),className:"h-8 pl-8 pr-8 typography-meta"}),v.trim().length>0&&s.jsx("button",{type:"button","aria-label":e("filesView.tree.search.clearAria"),className:"absolute right-2 top-2 inline-flex size-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{S(""),j.current?.focus()},children:s.jsx(I,{name:"close",className:"size-4"})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>rr("createFile",{path:g,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFileTitle"),"aria-label":e("filesView.tree.actions.newFileTitle"),children:s.jsx(I,{name:"file-add",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFileTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>rr("createFolder",{path:g,type:"directory"}),className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.newFolderTitle"),"aria-label":e("filesView.tree.actions.newFolderTitle"),children:s.jsx(I,{name:"folder-add",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.newFolderTitle")})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex flex-shrink-0",children:s.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>{lr()},className:"size-8 p-0 flex-shrink-0",title:e("filesView.tree.actions.refreshTitle"),"aria-label":e("filesView.tree.actions.refreshTitle"),children:s.jsx(I,{name:"refresh",className:"size-4"})})})}),s.jsx(Ft,{side:"bottom",sideOffset:6,children:e("filesView.tree.actions.refreshTitle")})]})]})}),s.jsx(Wn,{outerClassName:"flex-1 min-h-0",className:Te("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(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.tree.search.searching")]}):pt.length>0?pt.map(U=>{const Pe=G?.path===U.path;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>{rn(U)},className:Te("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Pe?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),children:[eh(U.path,U.extension),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:U.path,children:U.relativePath??U.path})]})},U.path)}):dd?s.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[s.jsx("span",{className:"text-[var(--status-error)]",children:dd}),s.jsxs(Ve,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{lr()},children:[s.jsx(I,{name:"refresh",className:"size-3.5"}),e("filesView.tree.actions.refreshTitle")]})]}):Vh?Rt(b,0):s.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:e("filesView.state.loading")})})})]}),$h=t==="full"&&T&&G&&s.jsx("div",{className:"absolute inset-0 z-50 flex flex-col bg-background",children:s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 relative",children:[s.jsx("div",{className:"absolute right-4 top-4 z-30",children:rl({exitFullscreenOnly:!0})}),s.jsx(Wn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:gt||rd||id?h?s.jsx("div",{className:"p-4"}):s.jsxs("div",{className:"p-4 flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{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:od,alt:G.name,className:"max-w-full max-h-full object-contain rounded-md border border-border/30 bg-primary/10"},ed)}):vs?ld(G):at&&po()==="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(Xs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("filesView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("filesView.error.switchToEditMode")})]}),children:s.jsx(so,{content:et,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})]}):on&&Q==="view"?cd(G,Lt):s.jsxs("div",{className:Te("relative h-full",Dr&&"overflow-hidden"),children:[s.jsx("div",{className:Te("h-full",Dr&&"invisible"),children:s.jsx(Yl,{value:Lt,onChange:Ut,readOnly:!ee,vimMode:qn==="vim",extensions:Jc,className:"h-full",onViewReady:U=>{ct.current=U,window.requestAnimationFrame(()=>{Vi(U)})},onViewDestroy:()=>{ct.current&&(ct.current=null)}})}),Dr&&s.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-background",children:s.jsxs("div",{className:"flex items-center gap-2 typography-ui text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"size-4 animate-spin"}),e("filesView.state.openingFileAtChange")]})})]})})]})});return s.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background relative",children:[s.jsx(E1,{activeDialog:Ns,dialogData:Is,dialogInputValue:$s,onDialogInputChange:hn,isDialogSubmitting:Fn,onDialogSubmit:Li,onClose:Bh,inputRef:Ct}),$h,d?A?il:ud:t==="editor-only"?s.jsx("div",{className:"flex flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden bg-background",children:il})}):s.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[m>=700&&s.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:ud}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:il})]})]})};function M1(t){return t+1}const vr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Il=(t,e)=>{const n=vr(t),r=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${r}`:`${n}/${r}`},F1=(t,e,n)=>Il(Il(Il(t,".opencode"),"plans"),`${e}-${n}.md`),O1=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,L1=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},B1=(t,e)=>{const n=vr(e.currentDirectory),r=vr(e.homeDirectory),o=vr(t);return n&&o.startsWith(n+"/")?o.slice(n.length+1):r&&o===r?"~":r&&o.startsWith(r+"/")?`~${o.slice(r.length)}`:o},_1=(t,e,n)=>{const r=vr(t.trim());if(!r)return null;const o=n?e.find(c=>c.id===n)??null:null;if(o?.path){const c=vr(o.path);if(r===c||r.startsWith(`${c}/`))return{id:o.id,path:o.path}}const a=e.filter(c=>{const l=vr(c.path);return r===l||r.startsWith(`${l}/`)}).sort((c,l)=>vr(l.path).length-vr(c.path).length)[0];return a?{id:a.id,path:a.path}:null},sh=({targetPath:t=null})=>{const{t:e}=Nt(),n=ut(ne=>ne.currentSessionId),r=ut(ne=>ne.createSession),o=ut(ne=>ne.initializeNewOpenChamberSession),a=ut(ne=>ne.sendMessage),c=ut(ne=>ne.setCurrentSession),l=Ic(),d=Ys(ne=>ne.homeDirectory),f=vc(ne=>ne.planModeEnabled),m=Ss(ne=>ne.projects),u=Ss(ne=>ne.activeProjectId),p=wn(ne=>ne.directories),y=pi()??"",g=Ee(ne=>ne.setActiveMainTab),b=Ee(ne=>ne.setSessionSwitcherOpen),x=Xn(),{isMobile:h}=Or(),{currentTheme:C}=Qr(),w=i.useMemo(()=>n?l.find(ne=>ne.id===n)??null:null,[n,l]),v=i.useMemo(()=>{const ne=typeof w?.directory=="string"?w.directory:"";return vr(ne||"")},[w?.directory]),S=i.useMemo(()=>vr(y||v),[y,v]),k=i.useMemo(()=>_1(S,m,u),[u,S,m]),j=i.useMemo(()=>k?p.get(k.path)?.isGitRepo===!0:!1,[k,p]),[A,D]=i.useState(null),[N,B]=i.useState(!1),[T,E]=i.useState(null),_=i.useMemo(()=>!T||!v||!d?T:B1(T,{currentDirectory:v,homeDirectory:d}),[T,v,d]),[R,z]=i.useState(""),{isPlaying:V,play:$,stop:M}=im(),te=ss(ne=>ne.showMessageTTSButtons),[re,Q]=i.useState(null),H=i.useMemo(()=>_&&_.split("/").pop()||e("planView.file.defaultName"),[_,e]),X=i.useMemo(()=>R.trim()&&Sg(R).title||e("planView.title.default"),[R,e]),oe=i.useMemo(()=>X.trim()||e("planView.title.default"),[X,e]),[fe,ve]=i.useState(!1),[ie,Ne]=i.useState(!1),[K,pe]=i.useState("edit"),L=i.useRef(null),[se,Z]=i.useState(null),je=i.useRef(null),De=i.useRef(null),Le="openchamber:plan:md-viewer-mode";i.useEffect(()=>{try{const ne=localStorage.getItem(Le);if(!ne)return;const Be=JSON.parse(ne);(Be==="preview"||Be==="edit")&&pe(Be)}catch{}},[]);const Me=i.useCallback(ne=>{pe(ne);try{localStorage.setItem(Le,JSON.stringify(ne))}catch{}},[]),Fe=i.useRef(!1),he=i.useRef(null),[Ie,me]=i.useState(!1);i.useEffect(()=>{const ne=()=>{Fe.current=!1,he.current=null,me(!1)};return document.addEventListener("mouseup",ne),()=>document.removeEventListener("mouseup",ne)},[]);const ce=i.useCallback((ne,Be)=>{const Ye=ne.split(`
|
|
35
|
-
`),He=Math.max(1,Be.start),Je=Math.min(Ye.length,Be.end);return He>Je?"":Ye.slice(He-1,Je).join(`
|
|
36
|
-
`)},[]),xe=Am({source:"plan",fileLabel:H,language:T&&Ti(T)||"markdown",getCodeForRange:ne=>ce(R,Dm(ne)),toStoreRange:ne=>({startLine:ne.start,endLine:ne.end}),fromDraftRange:ne=>({start:ne.startLine,end:ne.endLine})}),{drafts:ke,commentText:de,setCommentText:P,editingDraftId:F,setSelection:ue,saveComment:be,cancel:W,reset:ge,startEdit:we,deleteDraft:G}=xe;i.useEffect(()=>{Z(null),ge()},[R,ge]),i.useEffect(()=>{ue(se)},[se,ue]);const Se=i.useCallback(()=>{Z(null),W()},[W]),Oe=i.useCallback((ne,Be)=>{Be&&Z(Be),be(ne,Be??se??void 0),Z(null)},[se,be]);i.useEffect(()=>{if(!se)return;const ne=Ye=>{const He=Ye.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()||(Z(null),W())},Be=window.setTimeout(()=>{document.addEventListener("click",ne)},100);return()=>{window.clearTimeout(Be),document.removeEventListener("click",ne)}},[W,de,F,h,se]);const Ae=i.useMemo(()=>{const ne=T?Ti(T):null,Be=!!ne&&ne!=="markdown",Ye=[ql(C,Be?{syntaxColors:!1}:void 0)],He=om(T||"plan.md");return He&&Ye.push(He),Be&&ne&&Ye.push(Im({language:ne,themeName:C.metadata.id,theme:am(C)})),Ye.push(li.lineWrapping),Ye},[C,T]);i.useEffect(()=>{if(!f&&!t){E(null),z(""),ve(!1);return}let ne=!1;const Be=async He=>{if(x.files?.readFile)return(await x.files.readFile(He))?.content??"";const Je=Lo()?.files;if(Je?.readFile)return(await Je.readFile(He,{optional:!0}))?.content??"";const nt=await Cs(`/api/fs/read?path=${encodeURIComponent(He)}&optional=true`,{cache:"no-store"});if(!nt.ok)throw new Error(`Failed to read plan file (${nt.status})`);return nt.text()};return(async()=>{if(E(null),z(""),Q(null),t){ve(!0);try{const He=await Be(t);if(ne)return;E(t),z(He)}catch{if(ne)return;E(null),z("")}finally{ne||ve(!1)}return}if(!w?.slug||!w?.time?.created||!v){E(null),z("");return}ve(!0);try{const He=F1(v,w.time.created,w.slug),Je=L1(O1(w.time.created,w.slug),d||null);let nt=null,xt=null;try{xt=await Be(He),nt=He}catch{}if(!nt)try{xt=await Be(Je),nt=Je}catch{}if(ne)return;if(!nt||xt===null){E(null),z("");return}E(nt),z(xt)}catch{if(ne)return;E(null),z("")}finally{ne||ve(!1)}})(),()=>{ne=!0}},[d,f,x.files,v,w?.slug,w?.time?.created,t]),i.useEffect(()=>{if(!T){Q(null);return}const ne=window.setTimeout(async()=>{Q(null);try{if(x.files?.writeFile){if(!(await x.files.writeFile(T,R))?.success)throw new Error(e("planView.error.writeFailed"))}else{const Be=await Cs("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:T,content:R})});if(!Be.ok)throw new Error(e("planView.error.writePlanFileFailed",{status:Be.status}))}}catch(Be){Q(Be instanceof Error?Be.message:e("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(ne)}},[R,T,x.files,e]),i.useEffect(()=>()=>{L.current!==null&&window.clearTimeout(L.current)},[]);const J=i.useCallback(()=>{g("chat"),b(!1)},[g,b]),O=i.useCallback(async ne=>{if(!k||!A)return;const Be=await En(A.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:oe}),He=[{synthetic:!0,text:await En(A.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:oe,plan_path:T??""})}];B(!0);try{J();let Je=null,nt=k.path;if(A.target==="worktree"){if(!j)return;const bt=await tm(k.path,sm());if(!bt?.id)return;Je=bt.id,nt=bt.path}else{const bt=await r(void 0,k.path,null);if(!bt?.id)return;Je=bt.id,nt=bt.directory??k.path,o(bt.id,ss.getState().agents??[])}if(!Je)return;const xt=Nc.getState();xt.saveSessionModelSelection(Je,ne.providerID,ne.modelID),ne.agent.trim()&&(xt.saveSessionAgentSelection(Je,ne.agent),xt.saveAgentModelForSession(Je,ne.agent,ne.providerID,ne.modelID),xt.saveAgentModelVariantForSession(Je,ne.agent,ne.providerID,ne.modelID,ne.variant||void 0)),c(Je,nt),await a(Be,ne.providerID,ne.modelID,ne.agent.trim()||void 0,void 0,void 0,He,ne.variant||void 0),D(null)}finally{B(!1)}},[j,r,k,o,A,T,J,a,oe,c]),ae=i.useMemo(()=>Rm({drafts:ke,editingDraftId:F,commentText:de,onTextChange:P,selection:se,isDragging:Ie,fileLabel:H,newWidgetId:"plan-new-comment-input",mapDraftToRange:ne=>({start:ne.startLine,end:ne.endLine}),onSave:Oe,onCancel:Se,onEdit:ne=>{we(ne),Z({start:ne.startLine,end:ne.endLine})},onDelete:G}),[de,G,F,Se,Oe,Ie,se,ke,H,P,we]);return s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"typography-ui-label font-medium truncate",children:X}),re?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:re,children:e("planView.error.saveFailed")}):null]}),T?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(tn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.improvePlanAria"),disabled:!R.trim(),children:s.jsx(I,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(Ft,{sideOffset:8,children:e("planView.actions.improve")})]}),s.jsxs(en,{align:"end",children:[s.jsx(ws,{onClick:()=>D({action:"improve",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(ws,{onClick:()=>D({action:"improve",target:"worktree"}),disabled:!j,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(tn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e("planView.actions.implementPlanAria"),disabled:!R.trim(),children:s.jsx(I,{name:"code-ai",className:"size-4"})})})}),s.jsx(Ft,{sideOffset:8,children:e("planView.actions.implement")})]}),s.jsxs(en,{align:"end",children:[s.jsx(ws,{onClick:()=>D({action:"implement",target:"session"}),children:e("planView.actions.sendToNewSession")}),s.jsx(ws,{onClick:()=>D({action:"implement",target:"worktree"}),disabled:!j,children:e("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(la,{currentMode:K,onToggle:()=>Me(K==="preview"?"edit":"preview")}),K==="preview"&&te&&s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Ve,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":e(V?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{V?M():R.trim()&&$(R)},children:V?s.jsx(I,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(Ft,{sideOffset:8,children:e(V?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx(Ve,{variant:"ghost",size:"sm",onClick:async()=>{(await ur(R)).ok&&(Ne(!0),L.current!==null&&window.clearTimeout(L.current),L.current=window.setTimeout(()=>{Ne(!1)},1200))},className:"h-5 w-5 p-0",title:e("planView.actions.copyPlanContents"),"aria-label":e("planView.actions.copyPlanContents"),children:ie?s.jsx(I,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(I,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(Fm,{open:A!==null,onOpenChange:ne=>{!ne&&!N&&D(null)},target:A?.target??"session",projectDirectory:k?.path??null,submitting:N,onConfirm:O}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(Wn,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:fe?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:K==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(Xs,{fallback:s.jsxs("div",{className:"rounded-md border border-destructive/20 bg-destructive/10 px-3 py-2",children:[s.jsx("div",{className:"mb-1 font-medium text-destructive",children:e("planView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:e("planView.error.switchToEditMode")})]}),children:s.jsx(so,{content:R,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:De,children:s.jsx(Yl,{value:R,onChange:z,readOnly:!1,className:"h-full",extensions:Ae,onViewReady:ne=>{je.current=ne},onViewDestroy:()=>{je.current=null},blockWidgets:ae,highlightLines:se?{start:Math.min(se.start,se.end),end:Math.max(se.start,se.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(ne,Be,Ye)=>{if(!(Ye instanceof MouseEvent)||Ye.button!==0)return!1;Ye.preventDefault();const He=ne.state.doc.lineAt(Be.from).number;if(se&&!Ye.shiftKey&&Math.min(se.start,se.end)===He&&Math.max(se.start,se.end)===He)return Z(null),W(),Fe.current=!1,he.current=null,me(!1),!0;if(h&&se&&!Ye.shiftKey){const Je=Math.min(se.start,se.end,He),nt=Math.max(se.start,se.end,He);return Z({start:Je,end:nt}),Fe.current=!1,he.current=null,me(!1),!0}if(Fe.current=!0,he.current=He,me(!0),se&&Ye.shiftKey){const Je=Math.min(se.start,He),nt=Math.max(se.end,He);Z({start:Je,end:nt})}else Z({start:He,end:He});return!0},mouseover:(ne,Be,Ye)=>{if(!(Ye instanceof MouseEvent)||Ye.buttons!==1||!Fe.current||he.current===null)return!1;const He=ne.state.doc.lineAt(Be.from).number,Je=Math.min(he.current,He),nt=Math.max(he.current,He);return Z({start:Je,end:nt}),me(!0),!1},mouseup:()=>(Fe.current=!1,he.current=null,me(!1),!1)}}})})})})})})]})},V1=8,Uc=t=>t,rc=t=>{const e=Uc(t).type;return typeof e=="string"?e:""},$1=t=>{const e=Uc(t).tool;return typeof e=="string"?e:""},z1=t=>{const e=Uc(t).text;return typeof e=="string"?e:""},W1=t=>{const e=rc(t);return e==="tool"?$1(t).trim().toLowerCase()||"tool":e||"unknown"},U1=t=>{if(t.length===0)return"";const e=[];for(const n of t){const r=W1(n);e.includes(r)||e.push(r)}return e.join(" + ")},H1=(t,e=V1)=>typeof t!="string"?"":t.length<=e?t:t.slice(-e),G1=t=>t.replace(/\s+/g," ").trim(),K1=t=>{for(const n of t)if(rc(n)==="text"){const r=G1(z1(n));if(r.length===0)continue;return r}const e=t.filter(n=>rc(n)!=="text").length;return e===0?"":`${e} attachment${e===1?"":"s"}`},q1=(t,e,n)=>`${n(t)} / ${n(e)}`,Y1=t=>{if(t==="12h")return!0;if(t==="24h")return!1},Q1=(t,e)=>{if(!t||!Number.isFinite(t))return"-";const n=Y1(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}})},ic={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},da={user:0,assistant:0,tool:0,other:0},Ci=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Pl=t=>{const e=t.info.tokens,n=e!==void 0?e:t.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof n=="number")return{...ic,total:Ci(n)};if(!n||typeof n!="object")return ic;const r=n,o=Ci(r.input),a=Ci(r.output),c=Ci(r.reasoning),l=Ci(r.cache?.read),d=Ci(r.cache?.write);return{input:o,output:a,reasoning:c,cacheRead:l,cacheWrite:d,total:o+a+c+l+d}},J1=(...t)=>{for(const e of t)if(typeof e=="string"&&e.trim().length>0)return e;return""},tr=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((e,n)=>e+tr(n),0):t&&typeof t=="object"?Object.values(t).reduce((e,n)=>e+tr(n),0):0,X1=(t,e)=>{const n=t,r=typeof n.type=="string"?n.type:"";if(r==="reasoning")return{...da,assistant:tr(n.text)+tr(n.content)};const o=J1(n.text,n.content,n.value,n.source?.value,n.source?.text?.value);return r==="tool"||e==="tool"?{user:0,assistant:0,tool:tr(n.input)+tr(n.output)+tr(n.error)+tr(n.call?.input)+tr(n.call?.output)+tr(n.call?.error)+tr(n.raw)+Math.round(tr(n.metadata)*.25)+Math.round(tr(n.state)*.1),other:0}:e==="user"?{user:o.length,assistant:0,tool:0,other:0}:e==="assistant"?{user:0,assistant:o.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:o.length}},Ku=(t,e)=>({user:t.user+e.user,assistant:t.assistant+e.assistant,tool:t.tool+e.tool,other:t.other+e.other}),Z1=t=>{const e=Bo(t.info);return e.isUser?"user":e.role==="assistant"?"assistant":e.role==="tool"?"tool":"other"},e0=(t,e)=>{if(t.length===0)return{...da};const n=t.reduce((r,o)=>{const a=Z1(o);let c={...da};for(const l of o.parts)c=Ku(c,X1(l,a));return Ku(r,c)},{...da});return n.user+=e.length,{user:Math.ceil(n.user/4),assistant:Math.ceil(n.assistant/4),tool:Math.ceil(n.tool/4),other:Math.ceil(n.other/4)}},Ai=t=>t.toLocaleString(to()),t0=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat(to(),{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat(to(),{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),s0=(t,e)=>!t||!Number.isFinite(t)?"-":kc(t,e,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),n0=(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}},r0=()=>{const t=ft.c(202),{t:e}=Nt(),n=Ee(i0);let r;t[0]===Symbol.for("react.memo_cache_sentinel")?(r={},t[0]=r):r=t[0];const[o,a]=i.useState(r),[c,l]=i.useState(null),d=i.useRef(null),f=ut(o0),m=Ic(),u=Ng(f??""),p=ss(a0);let y;t[1]===Symbol.for("react.memo_cache_sentinel")?(y=()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),a(l0),l(null)},t[1]=y):y=t[1];let g;t[2]!==f?(g=[f],t[2]=f,t[3]=g):g=t[3],i.useEffect(y,g);let b,x;t[4]===Symbol.for("react.memo_cache_sentinel")?(b=()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},x=[],t[4]=b,t[5]=x):(b=t[4],x=t[5]),i.useEffect(b,x);let h;t[6]===Symbol.for("react.memo_cache_sentinel")?(h=async(jt,Pt)=>{(await ur(Pt)).ok?(l(jt),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{l(Bt=>Bt===jt?null:Bt),d.current=null},2e3)):l(null)},t[6]=h):h=t[6];const C=h;let w;t[7]!==f||t[8]!==m?(w=f?m.find(jt=>jt.id===f)??null:null,t[7]=f,t[8]=m,t[9]=w):w=t[9];const v=w;let S,k,j,A,D,N;if(t[10]!==p||t[11]!==u){S=u.filter(c0);let jt;t[18]!==u?(jt=u.filter(d0),t[18]=u,t[19]=jt):jt=t[19],N=jt;let Pt=null;for(let Bt=S.length-1;Bt>=0;Bt=Bt-1,Bt){const Gt=S[Bt];if(Pl(Gt).total>0){Pt=Gt;break}}A=Pt?Pl(Pt):ic,k=kg({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}),D=S.reduce(u0,0);const is=Pt?.info??null;j=n0(p,is?.providerID||"",is?.modelID||""),t[10]=p,t[11]=u,t[12]=S,t[13]=k,t[14]=j,t[15]=A,t[16]=D,t[17]=N}else S=t[12],k=t[13],j=t[14],A=t[15],D=t[16],N=t[17];const B=j,T=B.contextLimit,E=T&&T>0?Math.min(999,A.total/T*100):0;let _;if(t[20]!==u){const jt=[...u].reverse().find(f0)?.info?.system||"";_=e0(u,jt),t[20]=u,t[21]=_}else _=t[21];const R=_,z=R.user,V=R.assistant,$=R.tool,M=Math.max(0,A.input-z-V-$),te=z+V+$+M,re=u[0]?.info?.time?.created,Q=u.length>0?u[u.length-1]?.info?.time?.created:null;let H;t[22]!==v?.title||t[23]!==e?(H=v?.title||e("contextSidebar.session.untitled"),t[22]=v?.title,t[23]=e,t[24]=H):H=t[24];const X=v?.time?.created??re??null,oe=Q??v?.time?.created??null;let fe;t[25]!==V||t[26]!==M||t[27]!==$||t[28]!==z?(fe={user:z,assistant:V,tool:$,other:M},t[25]=V,t[26]=M,t[27]=$,t[28]=z,t[29]=fe):fe=t[29];let ve;t[30]!==S.length||t[31]!==te||t[32]!==k||t[33]!==T||t[34]!==B||t[35]!==u.length||t[36]!==X||t[37]!==oe||t[38]!==fe||t[39]!==H||t[40]!==A||t[41]!==D||t[42]!==E||t[43]!==N.length?(ve={sessionTitle:H,messagesCount:u.length,userMessagesCount:N.length,assistantMessagesCount:S.length,createdAt:X,lastActivityAt:oe,providerModel:B,tokenBreakdown:A,usagePercent:E,cacheHitRate:k,totalAssistantCost:D,contextLimit:T,breakdown:fe,breakdownTotal:te},t[30]=S.length,t[31]=te,t[32]=k,t[33]=T,t[34]=B,t[35]=u.length,t[36]=X,t[37]=oe,t[38]=fe,t[39]=H,t[40]=A,t[41]=D,t[42]=E,t[43]=N.length,t[44]=ve):ve=t[44];const ie=ve;if(!f){let jt;t[45]!==e?(jt=e("contextSidebar.empty.openSession"),t[45]=e,t[46]=jt):jt=t[46];let Pt;return t[47]!==jt?(Pt=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]=Pt):Pt=t[48],Pt}let Ne;t[49]!==e?(Ne=e("contextSidebar.breakdown.user"),t[49]=e,t[50]=Ne):Ne=t[50];let K;t[51]!==Ne||t[52]!==ie.breakdown.user?(K={key:"user",label:Ne,value:ie.breakdown.user,color:"var(--status-success)"},t[51]=Ne,t[52]=ie.breakdown.user,t[53]=K):K=t[53];let pe;t[54]!==e?(pe=e("contextSidebar.breakdown.assistant"),t[54]=e,t[55]=pe):pe=t[55];let L;t[56]!==pe||t[57]!==ie.breakdown.assistant?(L={key:"assistant",label:pe,value:ie.breakdown.assistant,color:"var(--primary-base)"},t[56]=pe,t[57]=ie.breakdown.assistant,t[58]=L):L=t[58];let se;t[59]!==e?(se=e("contextSidebar.breakdown.toolCalls"),t[59]=e,t[60]=se):se=t[60];let Z;t[61]!==se||t[62]!==ie.breakdown.tool?(Z={key:"tool",label:se,value:ie.breakdown.tool,color:"var(--status-warning)"},t[61]=se,t[62]=ie.breakdown.tool,t[63]=Z):Z=t[63];let je;t[64]!==e?(je=e("contextSidebar.breakdown.other"),t[64]=e,t[65]=je):je=t[65];let De;t[66]!==je||t[67]!==ie.breakdown.other?(De={key:"other",label:je,value:ie.breakdown.other,color:"var(--surface-muted-foreground)"},t[66]=je,t[67]=ie.breakdown.other,t[68]=De):De=t[68];let Le;t[69]!==K||t[70]!==L||t[71]!==Z||t[72]!==De?(Le=[K,L,Z,De],t[69]=K,t[70]=L,t[71]=Z,t[72]=De,t[73]=Le):Le=t[73];const Me=Le;let Fe;t[74]!==ie.sessionTitle?(Fe=s.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:ie.sessionTitle}),t[74]=ie.sessionTitle,t[75]=Fe):Fe=t[75];let he;t[76]!==ie.providerModel.modelName||t[77]!==ie.providerModel.providerName?(he=s.jsxs("span",{children:[ie.providerModel.providerName," / ",ie.providerModel.modelName]}),t[76]=ie.providerModel.modelName,t[77]=ie.providerModel.providerName,t[78]=he):he=t[78];let Ie;t[79]!==n||t[80]!==ie.createdAt?(Ie=ie.createdAt&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:s0(ie.createdAt,n)})]}),t[79]=n,t[80]=ie.createdAt,t[81]=Ie):Ie=t[81];let me;t[82]!==he||t[83]!==Ie?(me=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,Ie]}),t[82]=he,t[83]=Ie,t[84]=me):me=t[84];let ce;t[85]!==Fe||t[86]!==me?(ce=s.jsxs("div",{className:"mb-6",children:[Fe,me]}),t[85]=Fe,t[86]=me,t[87]=ce):ce=t[87];let xe;t[88]!==e?(xe=e("contextSidebar.section.context"),t[88]=e,t[89]=xe):xe=t[89];let ke;t[90]!==xe?(ke=s.jsx("span",{className:"typography-micro text-muted-foreground",children:xe}),t[90]=xe,t[91]=ke):ke=t[91];let de;t[92]!==ie.tokenBreakdown.total?(de=Ai(ie.tokenBreakdown.total),t[92]=ie.tokenBreakdown.total,t[93]=de):de=t[93];let P;t[94]!==ie.contextLimit?(P=ie.contextLimit?` / ${Ai(ie.contextLimit)}`:"",t[94]=ie.contextLimit,t[95]=P):P=t[95];let F;t[96]!==de||t[97]!==P?(F=s.jsxs("span",{className:"typography-micro tabular-nums text-muted-foreground/70",children:[de,P]}),t[96]=de,t[97]=P,t[98]=F):F=t[98];let ue;t[99]!==ke||t[100]!==F?(ue=s.jsxs("div",{className:"flex items-baseline justify-between",children:[ke,F]}),t[99]=ke,t[100]=F,t[101]=ue):ue=t[101];let be;t[102]!==ie.usagePercent?(be=ie.usagePercent>0&&s.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,ie.usagePercent)}%`,backgroundColor:ie.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}}),t[102]=ie.usagePercent,t[103]=be):be=t[103];let W;t[104]!==be?(W=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]=W):W=t[105];let ge;t[106]!==e||t[107]!==ie.usagePercent?(ge=e("contextSidebar.context.percentUsed",{percent:ie.usagePercent.toFixed(1)}),t[106]=e,t[107]=ie.usagePercent,t[108]=ge):ge=t[108];let we;t[109]!==ge?(we=s.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:ge}),t[109]=ge,t[110]=we):we=t[110];let G;t[111]!==ue||t[112]!==W||t[113]!==we?(G=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[ue,W,we]}),t[111]=ue,t[112]=W,t[113]=we,t[114]=G):G=t[114];let Se;t[115]!==e?(Se=e("contextSidebar.stats.messages"),t[115]=e,t[116]=Se):Se=t[116];let Oe;t[117]!==ie.messagesCount?(Oe=Ai(ie.messagesCount),t[117]=ie.messagesCount,t[118]=Oe):Oe=t[118];let Ae;t[119]!==Se||t[120]!==Oe?(Ae={label:Se,value:Oe},t[119]=Se,t[120]=Oe,t[121]=Ae):Ae=t[121];let J;t[122]!==e?(J=e("contextSidebar.stats.user"),t[122]=e,t[123]=J):J=t[123];let O;t[124]!==ie.userMessagesCount?(O=Ai(ie.userMessagesCount),t[124]=ie.userMessagesCount,t[125]=O):O=t[125];let ae;t[126]!==J||t[127]!==O?(ae={label:J,value:O},t[126]=J,t[127]=O,t[128]=ae):ae=t[128];let ne;t[129]!==e?(ne=e("contextSidebar.stats.assistant"),t[129]=e,t[130]=ne):ne=t[130];let Be;t[131]!==ie.assistantMessagesCount?(Be=Ai(ie.assistantMessagesCount),t[131]=ie.assistantMessagesCount,t[132]=Be):Be=t[132];let Ye;t[133]!==ne||t[134]!==Be?(Ye={label:ne,value:Be},t[133]=ne,t[134]=Be,t[135]=Ye):Ye=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]!==ie.totalAssistantCost?(Je=t0(ie.totalAssistantCost),t[138]=ie.totalAssistantCost,t[139]=Je):Je=t[139];let nt;t[140]!==He||t[141]!==Je?(nt={label:He,value:Je},t[140]=He,t[141]=Je,t[142]=nt):nt=t[142];let xt;t[143]!==Ae||t[144]!==ae||t[145]!==Ye||t[146]!==nt?(xt=[Ae,ae,Ye,nt],t[143]=Ae,t[144]=ae,t[145]=Ye,t[146]=nt,t[147]=xt):xt=t[147];const bt=xt;let _e;t[148]!==bt?(_e=s.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:bt.map(m0)}),t[148]=bt,t[149]=_e):_e=t[149];let Qe;t[150]!==e?(Qe=e("contextSidebar.section.lastAssistantMessage"),t[150]=e,t[151]=Qe):Qe=t[151];let st;t[152]!==Qe?(st=s.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:Qe}),t[152]=Qe,t[153]=st):st=t[153];let pt;t[154]!==e||t[155]!==ie.cacheHitRate.hasInput||t[156]!==ie.cacheHitRate.percent||t[157]!==ie.tokenBreakdown.cacheRead||t[158]!==ie.tokenBreakdown.cacheWrite||t[159]!==ie.tokenBreakdown.input||t[160]!==ie.tokenBreakdown.output||t[161]!==ie.tokenBreakdown.reasoning?(pt=s.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:e("contextSidebar.tokens.input"),value:ie.tokenBreakdown.input,format:"count"},{label:e("contextSidebar.tokens.output"),value:ie.tokenBreakdown.output,format:"count"},{label:e("contextSidebar.tokens.reasoning"),value:ie.tokenBreakdown.reasoning,format:"count"},{label:e("contextSidebar.tokens.cacheRead"),value:ie.tokenBreakdown.cacheRead,format:"count"},{label:e("contextSidebar.tokens.cacheWrite"),value:ie.tokenBreakdown.cacheWrite,format:"count"},{label:e("contextSidebar.tokens.cacheHit"),value:ie.cacheHitRate.hasInput?ie.cacheHitRate.percent:null,format:"percent"}].map(h0)}),t[154]=e,t[155]=ie.cacheHitRate.hasInput,t[156]=ie.cacheHitRate.percent,t[157]=ie.tokenBreakdown.cacheRead,t[158]=ie.tokenBreakdown.cacheWrite,t[159]=ie.tokenBreakdown.input,t[160]=ie.tokenBreakdown.output,t[161]=ie.tokenBreakdown.reasoning,t[162]=pt):pt=t[162];let At;t[163]!==st||t[164]!==pt?(At=s.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[st,pt]}),t[163]=st,t[164]=pt,t[165]=At):At=t[165];let vt;t[166]!==Me||t[167]!==ie.breakdownTotal?(vt=s.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:Me.map(jt=>jt.value<=0||ie.breakdownTotal<=0?null:s.jsx("div",{style:{width:`${jt.value/ie.breakdownTotal*100}%`,backgroundColor:jt.color}},jt.key))}),t[166]=Me,t[167]=ie.breakdownTotal,t[168]=vt):vt=t[168];let kt;t[169]!==Me||t[170]!==ie.breakdownTotal?(kt=s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:Me.map(jt=>{const Pt=ie.breakdownTotal>0?jt.value/ie.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:[Pt.toFixed(0),"%"]})]})]},jt.key)})}),t[169]=Me,t[170]=ie.breakdownTotal,t[171]=kt):kt=t[171];let et;t[172]!==vt||t[173]!==kt?(et=s.jsxs("div",{className:"mb-6",children:[vt,kt]}),t[172]=vt,t[173]=kt,t[174]=et):et=t[174];let _t;t[175]!==e?(_t=e("contextSidebar.section.rawMessages"),t[175]=e,t[176]=_t):_t=t[176];let ns;t[177]!==_t?(ns=s.jsx("div",{className:"typography-micro text-muted-foreground",children:_t}),t[177]=_t,t[178]=ns):ns=t[178];let Kt;if(t[179]!==c||t[180]!==o||t[181]!==u||t[182]!==e||t[183]!==n){let jt;t[185]!==c||t[186]!==o||t[187]!==e||t[188]!==n?(jt=Pt=>{const Bt=Bo(Pt.info).role,Gt=Bt==="assistant",es=Bt==="user",Wt=o[Pt.info.id]===!0,Lt=c===Pt.info.id,Ut=Pt.info.time?.created??null,rs=U1(Pt.parts),$t=Gt?Pl({info:Pt.info,parts:Pt.parts}):null,ls=es?K1(Pt.parts):"",xs=H1(Pt.info.id),Ct=Q1(Ut,n),Vt=rs||"—",yt=$t?q1($t.input,$t.output,Ai):"",us=Bt||"unknown",cs=rs,Ue=Wt?JSON.stringify({info:Pt.info,parts:Pt.parts},null,2):"";return s.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[s.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":Wt,onClick:()=>{a(Ge=>({...Ge,[Pt.info.id]:Ge[Pt.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:[es?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:"})," ",ls]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:Gt?"min-w-0 truncate text-muted-foreground":"typography-ui-label text-foreground",children:Gt?Vt:us}),s.jsx("span",{className:Gt?"text-right text-muted-foreground tabular-nums":"min-w-0 truncate text-muted-foreground",children:Gt?yt:cs})]}),s.jsx("span",{className:"text-right font-mono text-muted-foreground",children:xs}),s.jsx("span",{className:"text-right text-muted-foreground",children:Ct})]})}),Wt&&s.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:s.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[s.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:s.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:Ge=>{Ge.stopPropagation(),C(Pt.info.id,Ue)},"aria-label":e(Lt?"contextSidebar.actions.copied":"contextSidebar.actions.copyJson"),title:e(Lt?"contextSidebar.actions.copied":"contextSidebar.actions.copy"),children:Lt?s.jsx(I,{name:"check",className:"size-3.5"}):s.jsx(I,{name:"file-copy",className:"size-3.5"})})}),s.jsx(Cg,{language:"json",code:Ue,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},Pt.info.id)},t[185]=c,t[186]=o,t[187]=e,t[188]=n,t[189]=jt):jt=t[189],Kt=[...u].reverse().map(jt),t[179]=c,t[180]=o,t[181]=u,t[182]=e,t[183]=n,t[184]=Kt}else Kt=t[184];let qe;t[190]!==Kt?(qe=s.jsx("div",{className:"mt-2.5 space-y-1",children:Kt}),t[190]=Kt,t[191]=qe):qe=t[191];let gt;t[192]!==ns||t[193]!==qe?(gt=s.jsxs("div",{children:[ns,qe]}),t[192]=ns,t[193]=qe,t[194]=gt):gt=t[194];let Xe;return t[195]!==ce||t[196]!==G||t[197]!==_e||t[198]!==At||t[199]!==et||t[200]!==gt?(Xe=s.jsx("div",{className:"h-full overflow-y-auto bg-background",children:s.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[ce,G,_e,At,et,gt]})}),t[195]=ce,t[196]=G,t[197]=_e,t[198]=At,t[199]=et,t[200]=gt,t[201]=Xe):Xe=t[201],Xe};function i0(t){return t.timeFormatPreference}function o0(t){return t.currentSessionId}function a0(t){return t.providers}function l0(t){return Object.keys(t).length>0?{}:t}function c0(t){return Bo(t.info).role==="assistant"}function d0(t){return Bo(t.info).isUser}function u0(t,e){const n=Ci(e.info.cost);return t+n}function f0(t){return Bo(t.info).isUser&&typeof t.info.system=="string"}function m0(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 h0(t){return s.jsxs("div",{children:[s.jsx("div",{className:"typography-micro text-muted-foreground/70",children:t.label}),s.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:t.value!==null&&t.value!==void 0?t.format==="percent"?`${t.value.toFixed(1)}%`:Ai(t.value):"—"})]},t.label)}const p0=(t,e,n)=>JSON.stringify({sessionID:t,directory:e||"",readOnly:n===!0}),g0=(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()},x0=(t,e,n,r,o,a)=>{const c=p0(n,r,o),l=t.get(e);if(l?.signature===c)return l.src;const d=g0(n,r,o,a);return t.set(e,{signature:c,src:d}),d},b0=t=>{if(!t||typeof t!="object")return!1;const e=t;return typeof e.x=="number"&&typeof e.y=="number"},qu=t=>!t||typeof t!="object"?!1:Object.values(t).every(e=>typeof e=="string"),Qi=t=>{if(!t||typeof t!="object")return!1;const e=t,n=e.bounds;return typeof e.tag=="string"&&typeof e.text=="string"&&typeof e.selector=="string"&&typeof e.path=="string"&&!!n&&typeof n?.x=="number"&&typeof n?.y=="number"&&typeof n?.width=="number"&&typeof n?.height=="number"&&b0(e.center)&&qu(e.attributes)&&qu(e.computedStyle)&&Array.isArray(e.ancestry)},Hc=({pageUrl:t,viewport:e,devicePixelRatio:n,target:r,screenshotAttached:o,intro:a})=>{const c=r.text.trim(),l=Object.entries(r.attributes).map(([y,g])=>`${y}="${g}"`).join(" "),d=r.computedStyle,f=r.bounds,m=r.center,u=a.replace(/[.:]+$/g,""),p=r.ancestry.map(y=>y.selectorPart).join(" > ");return[`${u}:`,`Page: ${t||"preview"}`,`Viewport: ${e.width}x${e.height}, DPR ${n}`,`Screenshot: ${o?"attached":"not attached"}`,`Element: ${r.tag}`,c?`Text: ${c}`:null,`- Selector: ${r.selector}`,`- Path: ${r.path}`,p?`- Ancestry: ${p}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(f.x)}, y=${Math.round(f.y)}, width=${Math.round(f.width)}, height=${Math.round(f.height)}`,`- Center: x=${Math.round(m.x)}, y=${Math.round(m.y)}`,`Styles: display=${d.display}; position=${d.position}; font=${d.fontWeight} ${d.fontSize} / ${d.lineHeight} ${d.fontFamily}; color=${d.color}; background=${d.backgroundColor}; z-index=${d.zIndex}`].filter(y=>typeof y=="string").join(`
|
|
37
|
-
`)},nh=async(t,e)=>{if(typeof window<"u")try{const n=t.getBoundingClientRect(),r=await Gr("desktop_capture_page_rect",{x:n.left,y:n.top,width:n.width,height:n.height});if(!r)throw new Error("Desktop screenshot capture is not available");const o=new Image;await new Promise((g,b)=>{o.onload=()=>g(),o.onerror=()=>b(new Error("Failed to load desktop preview screenshot")),o.src=`data:${r.mime};base64,${r.base64}`});const a=Math.max(1,o.naturalWidth||r.width||Math.floor(n.width)),c=Math.max(1,o.naturalHeight||r.height||Math.floor(n.height)),d=Math.min(1,1200/a),f=document.createElement("canvas");f.width=Math.floor(a*d),f.height=Math.floor(c*d);const m=f.getContext("2d");if(!m)return null;m.scale(d,d),m.drawImage(o,0,0,a,c);const u=a/Math.max(1,n.width),p=c/Math.max(1,n.height);m.fillStyle="rgba(37, 99, 235, 0.28)",m.strokeStyle="rgb(37, 99, 235)",m.lineWidth=Math.max(2,2*u),m.fillRect(e.bounds.x*u,e.bounds.y*p,e.bounds.width*u,e.bounds.height*p),m.strokeRect(e.bounds.x*u,e.bounds.y*p,e.bounds.width*u,e.bounds.height*p);const y=await new Promise(g=>f.toBlob(g,"image/jpeg",.82));return y?new File([y],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(n){return console.warn("[preview] failed to capture annotation screenshot:",n),null}return await E0(t,e)},Gc=async(t,e,n,r,o,a)=>{if(!t)return null;try{const c=new Image;await new Promise((x,h)=>{c.onload=()=>x(),c.onerror=()=>h(new Error("Failed to load desktop browser screenshot")),c.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,c.naturalWidth||e),d=Math.max(1,c.naturalHeight||n),m=Math.min(1,1200/l),u=document.createElement("canvas");u.width=Math.floor(l*m),u.height=Math.floor(d*m);const p=u.getContext("2d");if(!p)return null;p.scale(m,m),p.drawImage(c,0,0,l,d);const y=l/Math.max(1,r||l),g=d/Math.max(1,o||d);p.fillStyle="rgba(37, 99, 235, 0.14)",p.strokeStyle="rgb(37, 99, 235)",p.lineWidth=Math.max(2,2*y),p.fillRect(a.bounds.x*y,a.bounds.y*g,a.bounds.width*y,a.bounds.height*g),p.strokeRect(a.bounds.x*y,a.bounds.y*g,a.bounds.width*y,a.bounds.height*g);const b=await new Promise(x=>u.toBlob(x,"image/jpeg",.82));return b?new File([b],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Ji="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Qn=new Map,Tl=new Map,y0=3e4,Kc=t=>{const e=Qn.get(t);return e?e.expiresAt-Date.now()<=y0?(Qn.delete(t),null):e:null},w0=t=>{try{return new URL(t).origin}catch{return t}};function rh(t){const e="#ffffff",n=t.defaultView??window;try{const r=t.body?n.getComputedStyle(t.body).backgroundColor:"";if(r&&r!=="rgba(0, 0, 0, 0)"&&r!=="transparent")return r;const o=n.getComputedStyle(t.documentElement).backgroundColor;if(o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent")return o}catch{}return e}const ih=t=>new Promise((e,n)=>{const r=new FileReader;r.onloadend=()=>e(typeof r.result=="string"?r.result:Ji),r.onerror=()=>n(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),v0=async(t,e=.82)=>{const n=await new Promise(r=>t.toBlob(r,"image/jpeg",e));return n&&(await ih(n)).split(",",2)[1]||""},j0=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},ua=(...t)=>{j0()&&console.info("[preview-capture]",...t)},oh=(t,e=8)=>{const n=[];try{const r=t.querySelectorAll("*");for(const o of r){const a=o.scrollTop||0,c=o.scrollLeft||0;if(a<=0&&c<=0)continue;const l=o.tagName.toLowerCase(),d=o.id?`#${o.id}`:"",f=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(n.push({selector:`${l}${d}${f}`,scrollTop:a,scrollLeft:c,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),n.length>=e)break}}catch{}return n},Ao="data-oc-fixed-pin",S0=(t,e,n)=>{if(e<=0&&n<=0)return()=>{};const r=t.defaultView;if(!r)return()=>{};const o=[],a=[];try{for(const c of t.querySelectorAll("*")){if(r.getComputedStyle(c).position!=="fixed")continue;const l=c.getBoundingClientRect();if(!(l.width>0&&l.height>0))continue;c.setAttribute(Ao,JSON.stringify({top:l.top+n,left:l.left+e,width:l.width,height:l.height})),o.push(c);const d=c.tagName.toLowerCase(),f=typeof c.className=="string"&&c.className?`.${c.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";a.push({selector:`${d}${f}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return ua("tagged fixed elements",a),()=>{for(const c of o)try{c.removeAttribute(Ao)}catch{}}},N0={name:"oc-fixed-pin",afterClone(t){const e=t?.clone;if(!(!e||typeof e.querySelectorAll!="function"))for(const n of e.querySelectorAll(`[${Ao}]`)){let r;try{r=JSON.parse(n.getAttribute(Ao)||"")}catch{continue}n.style.setProperty("position","absolute","important"),n.style.setProperty("top",`${r.top}px`,"important"),n.style.setProperty("left",`${r.left}px`,"important"),n.style.setProperty("right","auto","important"),n.style.setProperty("bottom","auto","important"),n.style.setProperty("width",`${r.width}px`,"important"),n.style.setProperty("height",`${r.height}px`,"important"),n.removeAttribute(Ao)}}},Ki="data-oc-scroll-pin",k0=t=>{const e=[],n=oh(t,64);try{const a=t.documentElement,c=t.body;for(const l of t.querySelectorAll("*")){const d=l.scrollTop||0,f=l.scrollLeft||0;if(d<=0&&f<=0)continue;const m=l!==a&&l!==c;m&&l.setAttribute(Ki,JSON.stringify({top:d,left:f})),e.push({el:l,top:d,left:f,tagged:m})}}catch{}return{reapply:()=>{for(const a of e)try{a.el.scrollHeight,a.el.scrollTop!==a.top&&(a.el.scrollTop=a.top),a.el.scrollLeft!==a.left&&(a.el.scrollLeft=a.left)}catch{}},cleanup:()=>{for(const a of e)if(a.tagged)try{a.el.removeAttribute(Ki)}catch{}},snapshot:n}},C0={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(`[${Ki}]`)){let o;try{o=JSON.parse(r.getAttribute(Ki)||"")}catch{r.removeAttribute(Ki);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(Ki)}}},Rl=async(t,e)=>{try{const n=await fetch(t,{credentials:e});return n.ok?await ih(await n.blob()):null}catch{return null}},A0=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const e=t.origin,n=Kc(e);if(n)return`${n.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=Tl.get(e),o=r??(async()=>{try{const c=await Cs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!c.ok)return Qn.delete(e),null;const l=await c.json(),d=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",f=typeof l.expiresAt=="number"?l.expiresAt:0;if(!d)return Qn.delete(e),null;const m={proxyBasePath:d,expiresAt:f};return Qn.set(e,m),m}catch{return Qn.delete(e),null}finally{Tl.delete(e)}})();r||Tl.set(e,o);const a=await o;return a?`${a.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},ah=async(t,e)=>{if(!t||t.startsWith("data:"))return t;try{const n=new URL(t,e.baseURI);if(n.origin===window.location.origin||n.protocol!=="http:"&&n.protocol!=="https:")return await Rl(n.toString(),"include")??Ji;const r=await A0(n),o=r?await Rl(r,"include"):null;return o||(await Rl(n.toString(),"omit")??Ji)}catch{return Ji}},D0=async(t,e)=>{if(!t||t==="none"||!t.includes("url("))return t;const n=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let r=t;for(const o of n){const a=o[2]||"";if(!a||a.startsWith("data:"))continue;const c=await ah(a,e);r=r.replace(o[0],`url("${c}")`)}return r},Yu=t=>t.complete?Promise.resolve():new Promise(e=>{t.addEventListener("load",()=>e(),{once:!0}),t.addEventListener("error",()=>e(),{once:!0})}),lh=t=>{const e=t.style.cssText;return()=>{t.style.cssText=e}},I0=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},P0=(t,e,n)=>{const r=[],o=t.defaultView??window,c=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of c){const d=l.textContent?.replace(/\s+/g," ").trim()??"";if(!d||!d.includes(" "))continue;const f=l.getBoundingClientRect();if(f.width<=0||f.height<=0||f.right<0||f.bottom<0||f.left>e||f.top>n)continue;const m=o.getComputedStyle(l);if(m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)continue;const u=m.getPropertyValue("text-wrap"),p=m.getPropertyValue("text-wrap-mode"),y=m.whiteSpace.includes("nowrap")||u==="nowrap"||p==="nowrap",g=f.height<=I0(m)*1.7;!y&&(!g||f.width>e*.72)||(r.push(lh(l)),l.style.whiteSpace="nowrap",l.style.overflowWrap="normal",l.style.wordBreak="normal",l.style.setProperty("text-wrap","nowrap"),l.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let l=r.length-1;l>=0;l-=1)r[l]?.()}},T0=(t,e,n,r)=>{const o=[],a=t.defaultView??window,c=a.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=a.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,d=Array.from(t.querySelectorAll("*")).filter(f=>{const m=a.getComputedStyle(f);if(m.position!=="fixed"||m.display==="none"||m.visibility==="hidden"||Number(m.opacity)===0)return!1;const u=f.getBoundingClientRect();return u.width>0&&u.height>0&&u.right>=0&&u.bottom>=0&&u.left<=e&&u.top<=n}).filter((f,m,u)=>!u.some((p,y)=>y<m&&p.contains(f)));for(const f of d){const m=f.getBoundingClientRect(),u=a.getComputedStyle(f),p=Math.ceil(m.width)+8,y=Math.ceil(m.height)+2;r?.add(f),o.push(lh(f)),f.style.position="absolute",f.style.top=`${m.top+l}px`,f.style.left=`${m.left+c}px`,f.style.right="auto",f.style.bottom="auto",f.style.width=`${p}px`,f.style.minWidth=`${p}px`,f.style.height=`${y}px`,f.style.minHeight=`${y}px`,f.style.margin="0",f.style.boxSizing="border-box",f.style.transform="none",u.zIndex!=="auto"&&(f.style.zIndex=u.zIndex)}return()=>{for(let f=o.length-1;f>=0;f-=1)o[f]?.()}},ch=async(t,e,n,r={})=>{const o=[],a=t.defaultView??window,c=u=>{if(u===t.documentElement||u===t.body)return!0;try{const p=u.getBoundingClientRect();return p.width>0&&p.height>0&&p.right>=0&&p.bottom>=0&&p.left<=e&&p.top<=n}catch{return!1}};if(r.applyLayoutWorkarounds){const u=new WeakSet;o.push(T0(t,e,n,u)),o.push(P0(t,e,n))}const l=new Map;for(const u of Array.from(t.images))l.set(u,u.currentSrc||u.src||u.getAttribute("src")||"");const d=Array.from(t.querySelectorAll("picture"));for(const u of d){const p=Array.from(u.querySelectorAll("source"));if(p.length===0)continue;const y=p.map(g=>({source:g,srcset:g.getAttribute("srcset"),sizes:g.getAttribute("sizes")}));o.push(()=>{for(const g of y)g.srcset===null?g.source.removeAttribute("srcset"):g.source.setAttribute("srcset",g.srcset),g.sizes===null?g.source.removeAttribute("sizes"):g.source.setAttribute("sizes",g.sizes)});for(const g of p)g.removeAttribute("srcset"),g.removeAttribute("sizes")}const f=Array.from(t.images).filter(u=>c(u));await Promise.all(f.map(async u=>{const p=l.get(u)||u.currentSrc||u.src||u.getAttribute("src")||"";if(!p)return;await Yu(u);const y=await ah(p,t),g={src:u.getAttribute("src"),srcset:u.getAttribute("srcset"),sizes:u.getAttribute("sizes")};o.push(()=>{g.src===null?u.removeAttribute("src"):u.setAttribute("src",g.src),g.srcset===null?u.removeAttribute("srcset"):u.setAttribute("srcset",g.srcset),g.sizes===null?u.removeAttribute("sizes"):u.setAttribute("sizes",g.sizes)}),u.removeAttribute("srcset"),u.removeAttribute("sizes"),u.setAttribute("src",y||Ji),await Yu(u)}));const m=Array.from(t.querySelectorAll("*")).filter(c);return await Promise.all(m.map(async u=>{const p=a.getComputedStyle(u).backgroundImage;if(!p||p==="none"||!p.includes("url("))return;const y=await D0(p,t);if(y===p)return;const g=u.style.backgroundImage;o.push(()=>{u.style.backgroundImage=g}),u.style.backgroundImage=y})),()=>{for(let u=o.length-1;u>=0;u-=1)try{o[u]?.()}catch{}}};async function R0(t,e){try{const n=t.contentWindow,r=t.contentDocument??n?.document,o=r?.documentElement;if(!n||!r||!o)return null;const a=t.getBoundingClientRect(),c=Math.max(1,Math.ceil(n.innerWidth||t.clientWidth||a.width)),l=Math.max(1,Math.ceil(n.innerHeight||t.clientHeight||a.height)),d=r.body,f=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,m=n.scrollX||0,u=n.scrollY||0,p=n.pageXOffset||0,y=n.pageYOffset||0,g=n.visualViewport?.pageLeft||n.visualViewport?.offsetLeft||0,b=n.visualViewport?.pageTop||n.visualViewport?.offsetTop||0,x=o.scrollLeft||0,h=o.scrollTop||0,C=d?.scrollLeft||0,w=d?.scrollTop||0,v=f?.scrollLeft||0,S=f?.scrollTop||0,k=Math.max(m,p,g,x,C,v),j=Math.max(u,y,b,h,w,S);ua("scroll sources",{windowScrollX:m,windowScrollY:u,pageScrollX:p,pageScrollY:y,visualViewportScrollX:g,visualViewportScrollY:b,rootScrollX:x,rootScrollY:h,bodyScrollX:C,bodyScrollY:w,scrollingElementScrollX:v,scrollingElementScrollY:S,scrollingElementTag:f?.tagName?.toLowerCase()??null,resolvedScrollX:k,resolvedScrollY:j,nestedScrolledElements:oh(r)});const A=Math.max(c,o.scrollWidth||0,d?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),D=Math.max(l,o.scrollHeight||0,d?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),N=Math.min(2,Math.max(1,window.devicePixelRatio||1)),B=o.style.scrollBehavior,T=d?.style.scrollBehavior??"";o.style.scrollBehavior="auto",d&&(d.style.scrollBehavior="auto");const E=k0(r);ua("nested scroll snapshot",E.snapshot);let _=()=>{},R=()=>{};try{await r.fonts?.ready.catch(()=>{}),_=await ch(r,c,l,{applyLayoutWorkarounds:!1}),n.scrollTo(k,j),R=S0(r,k,j),E.reapply();const z={backgroundColor:rh(r),cache:"disabled",dpr:N,embedFonts:!0,fast:!1,height:D,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[N0,C0],quality:.82,width:A},$=await(await Xh(o,z)).toCanvas();if(!$.width||!$.height)return null;const M=$.width/Math.max(1,A),te=$.height/Math.max(1,D),re=Math.min($.width,Math.max(1,Math.round(c*M))),Q=Math.min($.height,Math.max(1,Math.round(l*te))),H=Math.max(0,$.width-re),X=Math.max(0,$.height-Q),oe=Math.min(H,Math.max(0,Math.round(k*M))),fe=Math.min(X,Math.max(0,Math.round(j*te)));ua("capture geometry",{viewportWidth:c,viewportHeight:l,captureWidth:A,captureHeight:D,canvasWidth:$.width,canvasHeight:$.height,xScale:M,yScale:te,sourceX:oe,sourceY:fe,sourceWidth:re,sourceHeight:Q});const ve=r.createElement("canvas");ve.width=re,ve.height=Q;const ie=ve.getContext("2d");if(!ie)return null;ie.drawImage($,oe,fe,re,Q,0,0,re,Q);const Ne=await v0(ve,.82);return Ne?await Gc(Ne,c,l,c,l,e):null}finally{R(),E.cleanup(),_(),n.scrollTo(k,j),E.reapply(),o.style.scrollBehavior=B,d&&(d.style.scrollBehavior=T)}}catch(n){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",n),null}}async function E0(t,e){const n=await R0(t,e);if(n)return n;try{const r=t.contentWindow,o=t.contentDocument??r?.document,a=o?.documentElement;if(!r||!o||!a)return null;const c=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||c.width)),d=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||c.height)),f=r.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,m=r.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,u=o.body,p=Math.max(d,a.scrollHeight||0,u?.scrollHeight||0),y=Math.min(2,Math.max(1,window.devicePixelRatio||1)),g=a.style.scrollBehavior,b=u?.style.scrollBehavior??"";a.style.scrollBehavior="auto",u&&(u.style.scrollBehavior="auto");let x="",h=()=>{};try{await o.fonts?.ready.catch(()=>{}),h=await ch(o,l,d,{applyLayoutWorkarounds:!0}),r.scrollTo(f,m);const w=await Qh(a).catch(()=>"");x=await Jh(a,{quality:.82,pixelRatio:y,width:l,height:d,backgroundColor:rh(o),imagePlaceholder:Ji,fontEmbedCSS:w||void 0,style:{transform:`translate(${-f}px, ${-m}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${p}px`},cacheBust:!0})}finally{h(),r.scrollTo(f,m),a.style.scrollBehavior=g,u&&(u.style.scrollBehavior=b)}const C=x.split(",",2)[1]||"";return C?await Gc(C,l,d,l,d,e):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const dh=380,M0=1400,uh=600,F0=24,Ma=new Map,Qu=200,O0=(t,e)=>e==="all"?!0:e==="errors"?t.level==="error"||t.level==="runtime"||t.level==="resource":e==="warnings"?t.level==="warn":t.level==="log"||t.level==="info"||t.level==="debug",L0=t=>{if(!t)return"";const e=t.replace(/\\/g,"/"),n=e.startsWith("//");let r=e.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),n&&!r.startsWith("//")&&(r=`/${r}`),r===""?e.startsWith("/")?"/":"":r},fh=t=>Number.isFinite(t)?Math.min(M0,Math.max(dh,Math.round(t))):uh,B0=t=>{const e=t?.parentElement?.clientWidth;return!e||e<=0?null:e},El=(t,e)=>{const n=fh(t),r=B0(e);return r===null?n:Math.min(n,Math.max(1,r))},_0=(t,e)=>{if(!t)return"";const n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return r&&n.startsWith(r+"/")?n.slice(r.length+1):n},V0=(t,e)=>e(t==="chat"?"contextPanel.mode.chat":t==="file"?"contextPanel.mode.files":t==="diff"?"contextPanel.mode.diff":t==="plan"?"contextPanel.mode.plan":t==="preview"?"contextPanel.mode.preview":t==="browser"?"contextPanel.mode.browser":"contextPanel.mode.context"),$0=t=>{if(!t)return null;const e=t.replace(/\\/g,"/").trim();if(!e)return null;const n=e.split("/").filter(Boolean);return n.length===0?e:n[n.length-1]||null},z0=(t,e,n)=>{if(t.mode==="chat"){const r=fa(t.dedupeKey);if(r){const a=e.get(r)?.trim();if(a)return a}const o=t.sessionTitleFallback?.trim();return o||n("contextPanel.mode.chat")}if(t.label)return t.label;if(t.mode==="file")return $0(t.targetPath)||n("contextPanel.mode.files");if(t.mode==="preview"){const r=t.targetPath;if(r)try{const o=new URL(r);return o.host||o.hostname||n("contextPanel.mode.preview")}catch{}return n("contextPanel.mode.preview")}return t.mode==="diff"?n("contextPanel.mode.diff"):V0(t.mode,n)},W0=t=>{if(t.mode==="file")return t.targetPath?s.jsx(Kr,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return s.jsx(I,{name:"arrow-left-right",className:"h-3.5 w-3.5"});if(t.mode==="plan")return s.jsx(I,{name:"file-text",className:"h-3.5 w-3.5"});if(t.mode==="context")return s.jsx(I,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return s.jsx(I,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return s.jsx(I,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return s.jsx(I,{name:"global",className:"h-3.5 w-3.5"})},fa=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,U0=(t,e)=>{if(t.size!==e.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0},H0=(t,e)=>{if(e.length===0)return Ma;const n=new Set(e),r=new Map;for(const o of t){if(!n.has(o.id))continue;const a=o.title?.trim();a&&r.set(o.id,a)}return r.size===0?Ma:r},G0=(t,e)=>{const n=lm(t),r=i.useRef(Ma),o=i.useRef(e);return o.current=e,i.useSyncExternalStore(n.subscribe,i.useCallback(()=>{const a=H0(n.getState().session,o.current);return U0(r.current,a)?r.current:(r.current=a,a)},[n]),()=>Ma)},mh=`new Promise((resolve) => {
|
|
38
|
-
const existing = document.getElementById('__openchamber_desktop_browser_overlay');
|
|
39
|
-
if (existing) existing.remove();
|
|
40
|
-
if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
|
|
41
|
-
try { window.__openchamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
|
|
42
|
-
}
|
|
43
|
-
const overlay = document.createElement('div');
|
|
44
|
-
overlay.id = '__openchamber_desktop_browser_overlay';
|
|
45
|
-
overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
|
|
46
|
-
document.documentElement.appendChild(overlay);
|
|
47
|
-
const cssEscape = (value) => {
|
|
48
|
-
try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
|
|
49
|
-
};
|
|
50
|
-
const selectorPart = (element) => {
|
|
51
|
-
const tag = element.tagName.toLowerCase();
|
|
52
|
-
if (element.id) return tag + '#' + cssEscape(element.id);
|
|
53
|
-
const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
|
|
54
|
-
return tag + className;
|
|
55
|
-
};
|
|
56
|
-
const metadata = (element) => {
|
|
57
|
-
const rect = element.getBoundingClientRect();
|
|
58
|
-
const style = getComputedStyle(element);
|
|
59
|
-
const ancestry = [];
|
|
60
|
-
let current = element;
|
|
61
|
-
while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
|
|
62
|
-
ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
|
|
63
|
-
current = current.parentElement;
|
|
64
|
-
}
|
|
65
|
-
const attrs = {};
|
|
66
|
-
for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
|
|
67
|
-
const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
|
|
68
|
-
return {
|
|
69
|
-
frame: 'top',
|
|
70
|
-
tag: element.tagName.toLowerCase(),
|
|
71
|
-
text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
|
|
72
|
-
selector: element.id ? '#' + cssEscape(element.id) : path,
|
|
73
|
-
path,
|
|
74
|
-
bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
75
|
-
center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
|
|
76
|
-
attributes: attrs,
|
|
77
|
-
computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
|
|
78
|
-
ancestry,
|
|
79
|
-
};
|
|
80
|
-
};
|
|
81
|
-
const move = (event) => {
|
|
82
|
-
const element = document.elementFromPoint(event.clientX, event.clientY);
|
|
83
|
-
if (!element || element === overlay || element === document.documentElement || element === document.body) return;
|
|
84
|
-
const rect = element.getBoundingClientRect();
|
|
85
|
-
overlay.style.display = 'block';
|
|
86
|
-
overlay.style.left = rect.left + 'px';
|
|
87
|
-
overlay.style.top = rect.top + 'px';
|
|
88
|
-
overlay.style.width = rect.width + 'px';
|
|
89
|
-
overlay.style.height = rect.height + 'px';
|
|
90
|
-
};
|
|
91
|
-
const cleanup = () => {
|
|
92
|
-
window.removeEventListener('mousemove', move, true);
|
|
93
|
-
window.removeEventListener('click', click, true);
|
|
94
|
-
window.removeEventListener('keydown', keydown, true);
|
|
95
|
-
if (window.__openchamberDesktopBrowserCancelInspect === cancel) {
|
|
96
|
-
delete window.__openchamberDesktopBrowserCancelInspect;
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
const cancel = () => {
|
|
100
|
-
cleanup();
|
|
101
|
-
overlay.remove();
|
|
102
|
-
resolve(null);
|
|
103
|
-
};
|
|
104
|
-
const click = (event) => {
|
|
105
|
-
event.preventDefault();
|
|
106
|
-
event.stopPropagation();
|
|
107
|
-
const element = document.elementFromPoint(event.clientX, event.clientY);
|
|
108
|
-
const result = element ? metadata(element) : null;
|
|
109
|
-
cleanup();
|
|
110
|
-
overlay.remove();
|
|
111
|
-
resolve(result);
|
|
112
|
-
};
|
|
113
|
-
const keydown = (event) => {
|
|
114
|
-
if (event.key !== 'Escape') return;
|
|
115
|
-
cancel();
|
|
116
|
-
};
|
|
117
|
-
window.__openchamberDesktopBrowserCancelInspect = cancel;
|
|
118
|
-
window.addEventListener('mousemove', move, true);
|
|
119
|
-
window.addEventListener('click', click, true);
|
|
120
|
-
window.addEventListener('keydown', keydown, true);
|
|
121
|
-
});`,ma=`(() => {
|
|
122
|
-
if (typeof window.__openchamberDesktopBrowserCancelInspect === 'function') {
|
|
123
|
-
window.__openchamberDesktopBrowserCancelInspect();
|
|
124
|
-
return;
|
|
125
|
-
}
|
|
126
|
-
const overlay = document.getElementById('__openchamber_desktop_browser_overlay');
|
|
127
|
-
if (overlay) overlay.remove();
|
|
128
|
-
})()`,K0=`(() => {
|
|
129
|
-
if (window.__openchamberSameWebviewNavigationInstalled) return;
|
|
130
|
-
window.__openchamberSameWebviewNavigationInstalled = true;
|
|
131
|
-
|
|
132
|
-
const navigate = (rawUrl) => {
|
|
133
|
-
if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
|
|
134
|
-
try {
|
|
135
|
-
const url = new URL(rawUrl, window.location.href);
|
|
136
|
-
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
137
|
-
window.location.assign(url.href);
|
|
138
|
-
return true;
|
|
139
|
-
} catch (_error) {
|
|
140
|
-
return false;
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
|
|
144
|
-
const originalOpen = window.open.bind(window);
|
|
145
|
-
window.open = (url, target, features) => {
|
|
146
|
-
if (navigate(url)) return null;
|
|
147
|
-
return originalOpen(url, target, features);
|
|
148
|
-
};
|
|
149
|
-
|
|
150
|
-
document.addEventListener('click', (event) => {
|
|
151
|
-
if (event.defaultPrevented) return;
|
|
152
|
-
const target = event.target;
|
|
153
|
-
if (!(target instanceof Element)) return;
|
|
154
|
-
const anchor = target.closest('a[target="_blank"][href]');
|
|
155
|
-
if (!(anchor instanceof HTMLAnchorElement)) return;
|
|
156
|
-
if (!navigate(anchor.href)) return;
|
|
157
|
-
event.preventDefault();
|
|
158
|
-
event.stopPropagation();
|
|
159
|
-
}, true);
|
|
160
|
-
})()`,Do=t=>{const e=t.trim();if(!e)return"about:blank";try{const n=new URL(e.includes("://")?e:`https://${e}`);return n.protocol!=="http:"&&n.protocol!=="https:"?"about:blank":n.toString()}catch{return"about:blank"}},Ju=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)},q0=(t,e)=>t.length<=e?t:`${t.slice(0,e-3)}...`,hh=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Xu=(t,e,n)=>{const r=hh(e);t.postMessage(n,r)},Y0=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}},Zu=t=>{if(!t)return t;try{const e=new URL(t);return e.searchParams.delete("ocPreview"),e.searchParams.delete("oc_preview_token"),e.searchParams.delete("oc_client_token"),e.searchParams.delete("oc_url_token"),e.toString()}catch{return t}},Q0=({rawUrl:t,onNavigate:e})=>{const{t:n}=Nt(),{currentTheme:r}=Qr(),[o,a]=i.useReducer(he=>he+1,0),[c,l]=i.useReducer(he=>he+1,0),[d,f]=i.useState({status:"idle"}),[m,u]=i.useState(""),p=i.useRef(null),y=i.useRef(1),[g,b]=i.useState(!1),[x,h]=i.useState(!1),[C,w]=i.useState("all"),[v,S]=i.useState([]),[k,j]=i.useState(!1),[A,D]=i.useState(null),N=ut(he=>he.currentSessionId),B=ut(he=>he.newSessionDraft?.open),T=Pc(he=>he.addDraft),E=hi(he=>he.addAttachedFile);let _=null;try{_=t?new URL(t):null}catch{_=null}const R=_?_.hostname==="localhost"||_.hostname==="127.0.0.1"||_.hostname==="::1"||_.hostname==="[::1]"||_.hostname==="0.0.0.0":!1,z=_?_.hostname==="0.0.0.0"?new URL(_.toString().replace("0.0.0.0","127.0.0.1")):_:null,V=z?z.toString():"",$=V?`${Hr()||"same-origin"}|${V}`:"",M=r.metadata.variant;i.useEffect(()=>{if(!V||!R){f({status:"idle"});return}const he=Kc($);if(he?.previewToken){f({status:"ready",proxyBasePath:he.proxyBasePath,previewToken:he.previewToken,expiresAt:he.expiresAt});return}he&&Qn.delete($);let Ie=!1;return f({status:"loading"}),(async()=>{try{const me=await Cs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:V})});if(!me.ok){Qn.delete($);const P=await me.json().catch(()=>({})),F=typeof P?.error=="string"?P.error:`HTTP ${me.status}`;Ie||f({status:"error",message:F});return}const ce=await me.json(),xe=typeof ce.proxyBasePath=="string"?ce.proxyBasePath:"",ke=typeof ce.previewToken=="string"?ce.previewToken:"",de=typeof ce.expiresAt=="number"?ce.expiresAt:0;if(!xe||!ke){Qn.delete($),Ie||f({status:"error",message:n("contextPanel.preview.proxyError")});return}Qn.set($,{proxyBasePath:xe,previewToken:ke,expiresAt:de}),Ie||f({status:"ready",proxyBasePath:xe,previewToken:ke,expiresAt:de})}catch(me){if(Qn.delete($),!Ie){const ce=me instanceof Error?me.message:String(me);f({status:"error",message:ce})}}})(),()=>{Ie=!0}},[R,$,c,n,V]);const te=z&&(z.protocol==="http:"||z.protocol==="https:")?z.toString():"",re=R&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";i.useEffect(()=>{if(!re){u("");return}let he=!1;return u(""),xc(Hr()).then(Ie=>{!he&&Ie&&u(re)}).catch(()=>{}),()=>{he=!0}},[re]);const Q=R&&d.status==="ready"&&z&&m===re?(()=>{const he=z.pathname||"/",Ie=new URLSearchParams(z.search);Ie.delete("oc_url_token"),Ie.delete("oc_client_token"),Ie.set("ocPreview",String(o)),Ie.set("oc_preview_token",d.previewToken||"");const me=Ie.toString(),ce=z.hash||"";return Pi().authenticatedAsset(`${d.proxyBasePath}${he}${me?`?${me}`:""}${ce}`)})():"",H=R?Q:te,X=R?Y0(Q):te,oe=R&&(d.status==="loading"||d.status==="idle"||m!==re),fe=R&&d.status==="error",ve=i.useCallback(he=>{const Ie=N??(B?"draft":null);if(!Ie){le.error(n("contextPanel.preview.inspect.attachNoSession"));return}const me=t||H||"",ce=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},xe=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let ke=!1;try{const de=p.current,P=de?await nh(de,he):null;P&&(await E(P),ke=!0)}catch{ke=!1}T({sessionKey:Ie,source:"preview-annotation",fileLabel:me||"preview",startLine:1,endLine:1,code:Hc({pageUrl:me,viewport:ce,devicePixelRatio:xe,target:he,screenshotAttached:ke,intro:n("contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),le.success(n("contextPanel.preview.inspect.attached"))})()},[E,T,N,H,B,t,n]);i.useEffect(()=>{b(!1),S([]),h(!1),w("all"),j(!1),D(null),y.current=1},[H]),i.useEffect(()=>{const he=p.current?.contentWindow;!g||!he||Xu(he,Q,{source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[g,k,Q]),i.useEffect(()=>{const he=p.current?.contentWindow;!g||!he||Xu(he,Q,{source:"openchamber-preview-parent",version:1,type:"set-color-scheme",scheme:M})},[g,M,Q]),i.useEffect(()=>{if(!k||typeof window>"u")return;const he=Ie=>{Ie.key==="Escape"&&(Ie.preventDefault(),Ie.stopImmediatePropagation(),j(!1))};return window.addEventListener("keydown",he,!0),()=>window.removeEventListener("keydown",he,!0)},[k]),i.useEffect(()=>{if(!R||typeof window>"u")return;const he=ce=>{if(typeof ce=="string")return ce;if(ce==null)return"";try{return JSON.stringify(ce)}catch{return String(ce)}},Ie=ce=>{const xe=y.current;y.current+=1,S(ke=>{const de=[...ke,{...ce,id:xe}];return de.length>Qu?de.slice(de.length-Qu):de})},me=ce=>{if(ce.source!==p.current?.contentWindow)return;const xe=ce.data;if(!(!xe||xe.source!=="openchamber-preview-bridge"||xe.version!==1)){if(xe.type==="ready"){b(!0);return}if(xe.type==="console"){const ke=xe.level==="error"||xe.level==="warn"||xe.level==="info"||xe.level==="debug"?xe.level:"log",de=Array.isArray(xe.args)?xe.args.map(he).filter(Boolean):[];Ie({level:ke,message:de.join(" "),ts:typeof xe.ts=="number"?xe.ts:Date.now()});return}if(xe.type==="runtime-error"){const ke=he(xe.filename),de=typeof xe.line=="number"?xe.line:null,P=typeof xe.column=="number"?xe.column:null,F=ke?`${ke}${de!==null?`:${de}${P!==null?`:${P}`:""}`:""}`:"",ue=he(xe.stack);Ie({level:"runtime",message:he(xe.message)||n("contextPanel.preview.console.runtimeError"),details:[F,ue].filter(Boolean).join(`
|
|
161
|
-
`),ts:typeof xe.ts=="number"?xe.ts:Date.now()});return}if(xe.type==="resource-error"){const ke=he(xe.tag)||"resource",de=he(xe.url);Ie({level:"resource",message:de?`${ke}: ${de}`:ke,details:he(xe.outerHTML),ts:typeof xe.ts=="number"?xe.ts:Date.now()});return}if(xe.type==="hover"){D(Qi(xe.target)?xe.target:null);return}if(xe.type==="select"&&Qi(xe.target)){D(xe.target),j(!1),ve(xe.target);return}if(xe.type==="navigate-preview"){const ke=typeof xe.url=="string"?xe.url:"",de=xe.navigation==="external"?"external":"proxy";if(ke&&de==="external"){qr(ke);return}ke&&e(ke)}}};return window.addEventListener("message",me),()=>{window.removeEventListener("message",me)}},[ve,R,e,n]);const ie=v.filter(he=>he.level==="error"||he.level==="runtime"||he.level==="resource").length,Ne=v.filter(he=>O0(he,C)),K=i.useCallback(()=>{const he=[`Preview URL: ${t||H||""}`,`Events: ${v.length}`,""].join(`
|
|
162
|
-
`),Ie=v.map(me=>{const ce=new Date(me.ts).toISOString(),xe=me.details?`
|
|
163
|
-
${me.details}`:"";return`[${ce}] [${me.level}] ${me.message}${xe}`}).join(`
|
|
164
|
-
`);ur(`${he}${Ie}`).then(me=>{me.ok?le.success(n("contextPanel.preview.console.copied")):le.error(n("contextPanel.preview.console.copyFailed"))})},[v,H,t,n]),pe=i.useCallback(()=>{const he=N??(B?"draft":null);if(!he){le.error(n("contextPanel.preview.console.attachNoSession"));return}const Ie=[`Preview URL: ${t||H||""}`,`Events: ${v.length}`,""].join(`
|
|
165
|
-
`),me=v.map(ce=>{const xe=new Date(ce.ts).toISOString(),ke=ce.details?`
|
|
166
|
-
${ce.details}`:"";return`[${xe}] [${ce.level}] ${ce.message}${ke}`}).join(`
|
|
167
|
-
`);T({sessionKey:he,source:"preview-console",fileLabel:t||H||"preview",startLine:1,endLine:Math.max(1,v.length),code:`${Ie}${me}`,language:"text",text:n("contextPanel.preview.console.attachAnnotation")}),le.success(n("contextPanel.preview.console.attached"))},[T,v,N,H,B,t,n]),[L,se]=i.useState("unknown"),Z=i.useRef(0),je=i.useRef(0),De=15e3;i.useEffect(()=>{if(!Q){se("unknown"),Z.current=0,je.current=0;return}let he=!1;return Z.current||(Z.current=Date.now(),je.current=0),se("unknown"),(async()=>{const me=await(async()=>{try{return await Cs(Q,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(he)return;if(!me){se("unreachable");return}if(me.status===403||me.status===404){Qn.delete($),f({status:"loading"}),l();return}if(me.status!==502){se("reachable");return}const ce=Z.current||Date.now();if(Date.now()-ce<De){se("starting"),je.current+=1;const ke=je.current,de=Math.min(2e3,250*Math.pow(2,Math.min(4,ke)));setTimeout(()=>{he||a()},de).unref?.();return}se("unreachable")})(),()=>{he=!0}},[$,Q,o]);const Le=R&&d.status==="ready"&&(L==="unknown"||L==="starting"),Me=R&&d.status==="ready"&&L==="unreachable",Fe=i.useCallback(he=>{if(!R||d.status!=="ready"||typeof window>"u")return;const Ie=he.currentTarget.contentWindow;if(Ie)try{const me=Ie.location,ce=hh(Q);if(me.origin!==ce||me.pathname.startsWith(d.proxyBasePath))return;const xe=`${d.proxyBasePath}${me.pathname}${me.search}${me.hash}`;Ie.location.replace(xe)}catch{}},[R,Q,d]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:X||t,children:X||t||n("contextPanel.preview.empty")}),s.jsx(Ve,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:n("contextPanel.preview.actions.reload"),"aria-label":n("contextPanel.preview.actions.reload"),disabled:!H,children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{te&&qr(te)},title:n("contextPanel.preview.actions.openExternal"),"aria-label":n("contextPanel.preview.actions.openExternal"),disabled:!te,children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})}),R?s.jsx(Ve,{type:"button",size:"sm",variant:k?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>j(he=>!he),title:n("contextPanel.preview.inspect.toggle"),"aria-label":n("contextPanel.preview.inspect.toggle"),disabled:!g,children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}):null,R?s.jsxs(Ve,{type:"button",size:"sm",variant:x?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>h(he=>!he),title:n(g?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),"aria-label":n(g?"contextPanel.preview.console.open":"contextPanel.preview.console.waiting"),disabled:!g&&v.length===0,children:[s.jsx(I,{name:"terminal-box",className:"h-3.5 w-3.5"}),ie>0?s.jsx("span",{className:"typography-micro text-status-error",children:ie}):null]}):null]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Le?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")})]}):Me?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(Ve,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:n("contextPanel.preview.actions.retry")})]}):H&&(!R||L==="reachable")?s.jsxs("div",{className:"relative h-full w-full",children:[s.jsx("iframe",{ref:p,src:H,title:n("contextPanel.preview.iframeTitle"),className:"h-full w-full border-0",style:{colorScheme:M},onLoad:Fe,sandbox:R?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${H}:${o}`),k&&A?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:A.bounds.x,top:A.bounds.y,width:A.bounds.width,height:A.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[A.tag,A.text?` · ${A.text}`:""]})}):null]}):oe?s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.loading")}):fe?s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[s.jsx("div",{children:n("contextPanel.preview.proxyError")}),d.status==="error"?s.jsx("div",{className:"text-center text-xs opacity-70",children:d.message}):null]}):s.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:n("contextPanel.preview.invalidUrl")}),x?s.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:n("contextPanel.preview.console.title")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Ve,{type:"button",size:"xs",variant:"ghost",onClick:pe,disabled:v.length===0,children:n("contextPanel.preview.console.attach")}),s.jsx(Ve,{type:"button",size:"xs",variant:"ghost",onClick:K,disabled:v.length===0,children:n("contextPanel.preview.console.copy")}),s.jsx(Ve,{type:"button",size:"xs",variant:"ghost",onClick:()=>S([]),disabled:v.length===0,children:n("contextPanel.preview.console.clear")})]})]}),s.jsx("div",{className:"flex items-center gap-1 border-b border-border/30 px-3 py-1.5",children:["all","errors","warnings","logs"].map(he=>s.jsx(Ve,{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:v.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.empty")}):Ne.length===0?s.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:n("contextPanel.preview.console.noFilteredEvents")}):Ne.map(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:Te("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]})]})},J0=()=>typeof window<"u"&&!!window.__OPENCHAMBER_ELECTRON__,X0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=Nt(),o=i.useRef(null),a=Ee(K=>K.setContextPanelTabTargetPath),c=Do(t),l=c!=="about:blank"?c:"",[d,f]=i.useState(l),[m,u]=i.useState(l),[p,y]=i.useState(()=>l?[l]:[]),[g,b]=i.useState(()=>l?0:-1),[x,h]=i.useReducer(K=>K+1,0),[C,w]=i.useState(!!l),[v,S]=i.useState(!1),[k,j]=i.useState(null),[A,D]=i.useState({status:"idle"}),[N,B]=i.useState(""),T=ut(K=>K.currentSessionId),E=ut(K=>K.newSessionDraft?.open),_=Pc(K=>K.addDraft),R=hi(K=>K.addAttachedFile),z=i.useCallback(K=>{!K||K==="about:blank"||!e||!n||a(e,n,K)},[e,n,a]),V=i.useCallback((K,pe)=>{const L=Do(K),se=L!=="about:blank"?L:"";u(se),f(se),w(!!se),z(se),y(Z=>{if(!se)return b(-1),[];if(pe?.replaceHistory)return Z;const je=g>=0?Z.slice(0,g+1):[];if(je[je.length-1]===se)return b(je.length-1),je;const Le=[...je,se];return b(Le.length-1),Le})},[g,z]),$=i.useCallback(K=>{const pe=p[K];pe&&(b(K),u(pe),f(pe),w(!0),z(pe))},[p,z]),M=i.useCallback(()=>{if(m){w(!0);try{o.current?.contentWindow?.location.reload()}catch{h()}}},[m]);i.useEffect(()=>{if(!m){D({status:"idle"});return}const K=w0(m),pe=Kc(K);if(pe?.previewToken){D({status:"ready",proxyBasePath:pe.proxyBasePath,previewToken:pe.previewToken,expiresAt:pe.expiresAt});return}pe&&Qn.delete(K);let L=!1;return D({status:"loading"}),w(!0),(async()=>{try{const se=await Cs("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:m,allowExternal:!0})});if(!se.ok){const Me=await se.json().catch(()=>({})),Fe=typeof Me?.error=="string"?Me.error:`HTTP ${se.status}`;L||D({status:"error",message:Fe});return}const Z=await se.json(),je=typeof Z.proxyBasePath=="string"?Z.proxyBasePath:"",De=typeof Z.previewToken=="string"?Z.previewToken:"",Le=typeof Z.expiresAt=="number"?Z.expiresAt:0;if(!je||!De){L||D({status:"error",message:r("contextPanel.preview.proxyError")});return}Qn.set(K,{proxyBasePath:je,previewToken:De,expiresAt:Le}),L||D({status:"ready",proxyBasePath:je,previewToken:De,expiresAt:Le})}catch(se){if(!L){const Z=se instanceof Error?se.message:String(se);D({status:"error",message:Z})}}})(),()=>{L=!0}},[m,r]);const te=m&&A.status==="ready"?`${A.proxyBasePath}|${A.previewToken||""}|${x}`:"";i.useEffect(()=>{if(!te){B("");return}let K=!1;return B(""),xc(Hr()).then(pe=>{!K&&pe&&B(te)}).catch(()=>{}),()=>{K=!0}},[te]);const re=i.useMemo(()=>{if(N!==te||!m||A.status!=="ready")return"";try{const K=new URL(m),pe=K.pathname||"/",L=new URLSearchParams(K.search);L.delete("oc_url_token"),L.delete("oc_client_token"),L.set("ocPreview",String(x)),L.set("oc_preview_token",A.previewToken||"");const se=L.toString();return Pi().authenticatedAsset(`${A.proxyBasePath}${pe}${se?`?${se}`:""}${K.hash}`)}catch{return""}},[m,A,te,x,N]),Q=re||(A.status==="error"?m:""),H=i.useCallback(K=>{if(!K||!m||A.status!=="ready")return"";try{const pe=new URL(K,window.location.origin),L=A.proxyBasePath.endsWith("/")?A.proxyBasePath.slice(0,-1):A.proxyBasePath;if(pe.origin!==window.location.origin||!pe.pathname.startsWith(L))return"";const se=pe.pathname.slice(L.length)||"/",Z=new URL(m).origin;return Zu(new URL(`${se}${pe.search}${pe.hash}`,Z).toString())}catch{return""}},[m,A]),X=i.useCallback(K=>{if(!K||!m||A.status!=="ready")return"";try{const pe=new URL(K,window.location.origin),L=new URL(m).origin;if(pe.origin!==window.location.origin||L===window.location.origin)return"";const se=A.proxyBasePath.endsWith("/")?A.proxyBasePath.slice(0,-1):A.proxyBasePath;return pe.pathname.startsWith(se)?"":Zu(new URL(`${pe.pathname}${pe.search}${pe.hash}`,L).toString())}catch{return""}},[m,A]),oe=i.useCallback(K=>{const pe=o.current?.contentWindow;pe&&pe.postMessage({source:"openchamber-preview-parent",version:1,type:"set-inspect-mode",enabled:K},window.location.origin)},[]),fe=i.useCallback(async K=>{const pe=T??(E?"draft":null);if(!pe){le.error(r("contextPanel.preview.inspect.attachNoSession"));return}const L=o.current,se=L?.contentWindow,Z=L?.getBoundingClientRect(),je={width:Number.isFinite(se?.innerWidth)?se?.innerWidth??Z?.width??0:Z?.width??0,height:Number.isFinite(se?.innerHeight)?se?.innerHeight??Z?.height??0:Z?.height??0},De=L?await nh(L,K):null,Le=!!De;De&&await R(De),_({sessionKey:pe,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Hc({pageUrl:m,viewport:je,devicePixelRatio:window.devicePixelRatio||1,target:K,screenshotAttached:Le,intro:r(Le?"contextPanel.preview.inspect.attachAnnotationWithScreenshot":"contextPanel.preview.inspect.attachAnnotation")}),language:"markdown",text:""}),le.success(r("contextPanel.preview.inspect.attached"))},[R,_,T,m,E,r]),ve=i.useCallback(()=>{const K=o.current;j(null),oe(!1),K&&Ju(K,ma).catch(()=>{})},[oe]);i.useEffect(()=>{if(!v)return;const K=pe=>{pe.key==="Escape"&&(pe.preventDefault(),pe.stopImmediatePropagation(),S(!1),ve())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[ve,v]),i.useEffect(()=>()=>ve(),[ve]),i.useEffect(()=>{const K=pe=>{if(pe.source!==o.current?.contentWindow)return;const L=pe.data;if(!(!L||L.source!=="openchamber-preview-bridge"||L.version!==1)){if(L.type==="ready"){const se=typeof L.url=="string"?L.url:"",Z=H(se);Z&&Z!==m&&V(Z);return}if(L.type==="hover"){j(Qi(L.target)?L.target:null);return}if(L.type==="select"&&Qi(L.target)){j(null),S(!1),oe(!1),fe(L.target);return}if(L.type==="navigate-preview"){const se=typeof L.url=="string"?L.url:"",Z=X(se);if(Z){V(Z);return}se&&V(se)}}};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)},[V,fe,m,H,X,oe]);const ie=i.useCallback(()=>{const K=o.current;if(!(!K||!m)){if(v){S(!1),ve();return}if(re){j(null),S(!0),oe(!0);return}S(!0),(async()=>{try{const pe=await Ju(K,mh);if(S(!1),!pe||!Qi(pe))return;await fe(pe)}catch{S(!1),le.error(r("contextPanel.browser.inspectUnavailable"))}})()}},[fe,ve,m,v,oe,re,r]),Ne=i.useCallback(()=>{try{const K=o.current?.contentWindow?.location.href||"",pe=X(K);if(pe){w(!0),V(pe);return}}catch{}w(!1),v&&re&&oe(!0)},[V,X,v,oe,re]);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(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:g<=0,onClick:()=>$(g-1),children:s.jsx(I,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:g<0||g>=p.length-1,onClick:()=>$(g+1),children:s.jsx(I,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:M,children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:K=>{K.preventDefault(),V(d)},children:s.jsx("input",{value:d,onChange:K=>f(K.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(Ve,{type:"button",variant:v?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:ie,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!m,onClick:()=>{qr(m)},children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Q?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("iframe",{ref:o,src:Q,title:r("contextPanel.browser.empty"),className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:Ne},`${Q}:${x}`),v&&k?s.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:k.bounds.x,top:k.bounds.y,width:k.bounds.width,height:k.bounds.height},children:s.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[k.tag,k.text?` · ${k.text}`:""]})}):null]}):s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(Tc,{width:140,height:140,className:"opacity-20"}),s.jsx("span",{className:"typography-ui-header text-muted-foreground",children:r("contextPanel.browser.empty")}),s.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:r("contextPanel.browser.emptyHint")}),s.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:r("contextPanel.browser.trustNotice")})]}),C?s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:r("common.loading")}):null]})]})},Z0=({initialUrl:t,directory:e,tabID:n})=>{const{t:r}=Nt(),o=i.useRef(null),a=Ee(D=>D.setContextPanelTabTargetPath),c=Do(t),l=c!=="about:blank"?c:"",[d,f]=i.useState(l),[m,u]=i.useState(l),[p,y]=i.useState(!1),[g,b]=i.useState(!0),x=i.useRef(null),h=g,C=i.useCallback(D=>{!D||D==="about:blank"||!e||!n||a(e,n,D)},[e,n,a]),w=ut(D=>D.currentSessionId),v=ut(D=>D.newSessionDraft?.open),S=Pc(D=>D.addDraft),k=hi(D=>D.addAttachedFile);i.useEffect(()=>{const D=o.current;if(!D)return;const N=()=>{try{const z=D.getURL();z&&z!=="about:blank"&&(u(z),f(z),C(z))}catch{}},B=z=>{const V=z.detail;typeof V?.url=="string"&&V.url&&(u(V.url),f(V.url),C(V.url))},T=()=>{x.current&&clearTimeout(x.current),x.current=setTimeout(()=>b(!0),200)},E=()=>{x.current&&clearTimeout(x.current),b(!1),N()},_=z=>{const V=z.detail;if(V?.disposition==="new-window"||V?.disposition==="foreground-tab"||V?.disposition==="background-tab"){z.preventDefault();const $=o.current;typeof $?.loadURL=="function"&&V.url&&$.loadURL(V.url)}},R=()=>{try{D.executeJavaScript?.(K0,!0).catch(()=>{})}catch{}};D.addEventListener("did-navigate",B),D.addEventListener("did-navigate-in-page",B),D.addEventListener("did-start-loading",T),D.addEventListener("did-stop-loading",E),D.addEventListener("new-window",_),D.addEventListener("dom-ready",R);try{D.isLoading()||(b(!1),N())}catch{}return R(),()=>{x.current&&clearTimeout(x.current),D.removeEventListener("did-navigate",B),D.removeEventListener("did-navigate-in-page",B),D.removeEventListener("did-start-loading",T),D.removeEventListener("did-stop-loading",E),D.removeEventListener("new-window",_),D.removeEventListener("dom-ready",R)}},[C]),i.useEffect(()=>{const D=setTimeout(()=>b(!1),3e4);return()=>clearTimeout(D)},[]),i.useEffect(()=>{if(!p)return;const D=N=>{if(N.key!=="Escape")return;N.preventDefault(),N.stopImmediatePropagation(),y(!1);const B=o.current;try{B?.executeJavaScript?.(ma).catch(()=>{})}catch{}};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[p]),i.useEffect(()=>{const D=o.current;return()=>{try{const N=D?.getURL?.();N&&N!=="about:blank"&&a(e,n,N)}catch{}try{D?.executeJavaScript?.(ma).catch(()=>{})}catch{}}},[e,n,a]);const j=i.useCallback(D=>{const N=o.current;if(typeof N?.loadURL!="function")return;const B=Do(D);try{N.loadURL(B)}catch{}},[]),A=i.useCallback(()=>{const D=o.current;if(D){if(p){y(!1);try{D.executeJavaScript?.(ma).catch(()=>{})}catch{}return}y(!0),D.executeJavaScript?.(mh,!0).then(async N=>{if(y(!1),!N||!Qi(N))return;const B=w??(v?"draft":null);if(!B){le.error(r("contextPanel.preview.inspect.attachNoSession"));return}const T=typeof D.getWebContentsId=="function"?D.getWebContentsId():null;if(T==null)return;const E=await Ag("desktop_browser_capture_page",{webContentsId:T}),_=await D.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),R=Number.isFinite(_?.width)?_.width:E.width,z=Number.isFinite(_?.height)?_.height:E.height,V=await Gc(E.base64,E.width,E.height,R,z,N),$=!!V;V&&await k(V),S({sessionKey:B,source:"preview-annotation",fileLabel:m||"browser",startLine:1,endLine:1,code:Hc({pageUrl:m,viewport:{width:R,height:z},devicePixelRatio:window.devicePixelRatio||1,target:N,screenshotAttached:$,intro:r("contextPanel.preview.inspect.attachAnnotationWithScreenshot")}),language:"markdown",text:""}),le.success(r("contextPanel.preview.inspect.attached"))}).catch(()=>y(!1))}},[k,S,w,m,p,v,r]);return s.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[s.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 bg-[var(--surface-background)] px-2 py-1",children:[s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:s.jsx(I,{name:"arrow-left",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:s.jsx(I,{name:"arrow-right",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})}),s.jsx("form",{className:"min-w-0 flex-1",onSubmit:D=>{D.preventDefault(),j(d)},children:s.jsx("input",{value:d,onChange:D=>f(D.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":r("contextPanel.browser.addressAria")})}),s.jsx(Ve,{type:"button",variant:p?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:A,title:r("contextPanel.preview.inspect.toggle"),"aria-label":r("contextPanel.preview.inspect.toggle"),children:s.jsx(I,{name:"cursor",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{qr(m)},children:s.jsx(I,{name:"external-link",className:"h-3.5 w-3.5"})})]}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[s.jsx("webview",{ref:o,src:Do(t),partition:"persist:openchamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!m||m==="about:blank")&&!g?s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[s.jsx(Tc,{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]})]})},ej=()=>{const{t}=Nt(),e=pi()??"",n=i.useMemo(()=>L0(e),[e]),r=Ee(P=>n?P.contextPanelByDirectory[n]:void 0),o=Ee(P=>P.closeContextPanel),a=Ee(P=>P.closeContextPanelTab),c=Ee(P=>P.openContextPanelTab),l=Ee(P=>P.toggleContextPanelExpanded),d=Ee(P=>P.setContextPanelWidth),f=Ee(P=>P.setActiveContextPanelTab),m=Ee(P=>P.reorderContextPanelTabs),u=fn(P=>P.setSelectedPath),p=Ee(P=>P.openContextPreview),{themeMode:y,setThemeMode:g,lightThemeId:b,darkThemeId:x,currentTheme:h}=Qr(),C=i.useMemo(()=>r?.tabs??[],[r?.tabs]),w=C.find(P=>P.id===r?.activeTabId)??C[C.length-1]??null,v=!!(r?.isOpen&&w),S=!!(v&&r?.expanded),k=fh(r?.width??uh),j=i.useMemo(()=>{const P=[];for(const F of C){if(F.mode!=="chat")continue;const ue=fa(F.dedupeKey);ue&&!P.includes(ue)&&P.push(ue)}return P},[C]),A=G0(n||void 0,j),[D,N]=i.useState(!1),[B,T]=i.useState(!1),E=i.useRef(0),_=i.useRef(k),R=i.useRef(null),z=i.useRef(null),V=i.useRef(null),$=i.useRef(new Map),M=i.useRef(new Map),te=i.useRef(!1),re=i.useRef(v),Q=i.useRef(null),H=i.useCallback(()=>{T(!0),Q.current!==null&&window.cancelAnimationFrame(Q.current),Q.current=window.requestAnimationFrame(()=>{Q.current=null,T(!1)})},[]);i.useEffect(()=>()=>{Q.current!==null&&window.cancelAnimationFrame(Q.current)},[]),i.useLayoutEffect(()=>{const P=re.current;if(re.current=v,!v){T(!1);return}P||H()},[v,H]),i.useEffect(()=>{if(!v||te.current){te.current=v;return}const P=window.requestAnimationFrame(()=>{V.current?.focus({preventScroll:!0})});return te.current=!0,()=>window.cancelAnimationFrame(P)},[v]);const X=i.useCallback(P=>{const F=V.current;F&&F.style.setProperty("--oc-context-panel-width",`${El(P,F)}px`)},[]),oe=i.useCallback(P=>{if(!(!v||S||!n)){try{P.currentTarget.setPointerCapture(P.pointerId)}catch{}z.current=P.pointerId,N(!0),E.current=P.clientX,_.current=k,R.current=k,X(k),P.preventDefault()}},[X,n,S,v,k]),fe=i.useCallback(P=>{if(!D||z.current!==P.pointerId)return;const F=E.current-P.clientX,ue=El(_.current+F,V.current);R.current!==ue&&(R.current=ue,X(ue))},[X,D]),ve=i.useCallback(P=>{if(z.current!==P.pointerId||!n)return;try{P.currentTarget.releasePointerCapture(P.pointerId)}catch{}const F=El(R.current??k,V.current);H(),X(F),R.current=F,d(n,F),N(!1),z.current=null},[X,n,d,H,k]);i.useEffect(()=>{D||(R.current=null)},[D]);const ie=i.useCallback(()=>{n&&o(n)},[o,n]),Ne=i.useCallback(()=>{n&&l(n)},[n,l]),K=i.useCallback(P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),ie())},[ie]);i.useEffect(()=>{if(!(!n||!w)&&w.mode==="file"&&w.targetPath){u(n,w.targetPath,{allowOutsideRoot:!0});return}},[w,n,u]);const pe=w?.mode==="chat"?w.id:null,L=w?.mode==="chat"?fa(w.dedupeKey):null;i.useEffect(()=>{if(!v||!n||!L||typeof window>"u")return;const P=()=>{if(document.visibilityState==="hidden"||!document.hasFocus()){dl(n,L,!1);return}cm(L),dl(n,L,!0)};P();const F=window.setInterval(P,1e4);return window.addEventListener("focus",P),window.addEventListener("blur",P),document.addEventListener("visibilitychange",P),()=>{window.clearInterval(F),window.removeEventListener("focus",P),window.removeEventListener("blur",P),document.removeEventListener("visibilitychange",P),dl(n,L,!1)}},[L,n,v]);const se=i.useCallback((P,F,ue)=>x0(M.current,P,F,n||null,ue,{mode:y,lightThemeId:b,darkThemeId:x,currentTheme:h}),[h,x,n,b,y]);i.useEffect(()=>{const P=new Set(C.map(F=>F.id));for(const F of M.current.keys())P.has(F)||M.current.delete(F)},[C]);const Z=i.useCallback(P=>{!n||w?.mode!=="diff"||c(n,{mode:"diff",targetPath:w.targetPath,stagedDiff:P==="staged"})},[w,n,c]),je=i.useCallback(()=>{if(typeof window>"u")return;const P={themeMode:y,lightThemeId:b,darkThemeId:x,currentTheme:h};for(const F of $.current.values()){const ue=F.contentWindow;if(!ue)continue;const be=ue.__openchamberApplyThemeSync;if(typeof be=="function")try{be(P);continue}catch{}ue.postMessage({type:"openchamber:theme-sync",payload:P},window.location.origin)}},[h,x,b,y]),De=i.useCallback(()=>{if(!(typeof window>"u"))for(const[P,F]of $.current.entries()){const ue=F.contentWindow;if(!ue)continue;const be={visible:pe===P},W=ue.__openchamberSetEmbeddedVisibility;if(typeof W=="function")try{W(be);continue}catch{}ue.postMessage({type:"openchamber:embedded-visibility",payload:be},window.location.origin)}},[pe]);i.useEffect(()=>{if(typeof window>"u")return;const P=F=>{if(F.origin!==window.location.origin||!Array.from($.current.values()).some(G=>G.contentWindow===F.source)||F.data?.type!=="openchamber:cycle-theme-request")return;const W=["light","dark","system"],we=(W.indexOf(y)+1)%W.length;g(W[we])};return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[g,y]),i.useLayoutEffect(()=>{C.some(F=>F.mode==="chat")&&(je(),De())},[x,b,De,je,C,y]);const Le=i.useMemo(()=>C.map(P=>{const F=z0(P,A,t),ue=q0(F,F0),be=_0(P.targetPath,e);return{id:P.id,label:ue,icon:W0(P),title:be?`${F}: ${be}`:F,closeLabel:t("contextPanel.tab.closeTabAria",{label:ue})}}),[e,A,t,C]),Me=w?.mode==="context"?s.jsx(r0,{}):w?.mode==="plan"?s.jsx(sh,{targetPath:w.targetPath}):w?.mode==="preview"?s.jsx(Q0,{rawUrl:w.targetPath??"",onNavigate:P=>p(e,P)}):s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[s.jsx(I,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),s.jsx("div",{className:"typography-ui-header text-foreground",children:t("contextPanel.preview.title")}),s.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:t("contextPanel.preview.description")})]}),Fe=i.useMemo(()=>C.filter(P=>P.mode==="chat"),[C]),he=i.useMemo(()=>C.filter(P=>P.mode==="browser"),[C]),Ie=i.useMemo(()=>C.filter(P=>P.mode==="diff"),[C]),me=J0()?Z0:X0,ce=i.useMemo(()=>C.some(P=>P.mode==="file"),[C]),xe=w?.mode==="file",ke=s.jsxs("header",{className:"flex h-10 items-stretch border-b border-transparent",children:[s.jsx(Ro,{items:Le,activeId:w?.id??null,onSelect:P=>{n&&f(n,P)},onClose:P=>{n&&a(n,P)},onReorder:(P,F)=>{n&&m(n,P,F)},layoutMode:"scrollable",variant:"default"}),s.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",onClick:Ne,className:"h-7 w-7 p-0",title:t(S?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),"aria-label":t(S?"contextPanel.actions.collapsePanel":"contextPanel.actions.expandPanel"),children:S?s.jsx(I,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"fullscreen",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",onClick:ie,className:"h-7 w-7 p-0",title:t("contextPanel.actions.closePanel"),"aria-label":t("contextPanel.actions.closePanel"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})})]})]}),de=v?S?{"--oc-context-panel-width":"100%",width:"100%",minWidth:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",minWidth:`min(${dh}px, 100%)`,maxWidth:"100%","--oc-context-panel-width":`${D?R.current??k:k}px`}:{"--oc-context-panel-width":`${D?R.current??k:k}px`,width:0,minWidth:0,maxWidth:0,opacity:0,overflow:"hidden",visibility:"hidden"};return s.jsxs("aside",{ref:V,"data-context-panel":"true",tabIndex:-1,inert:!v||void 0,className:Te("flex min-h-0 flex-col overflow-hidden bg-background",!S&&"border-l border-border/40",S?"absolute inset-0 z-20 min-w-0":"relative h-full flex-shrink-0",!v&&"pointer-events-none",D||!v||B?"transition-none":"transition-[width] duration-200 ease-in-out"),onKeyDownCapture:K,style:de,children:[!S&&s.jsx("div",{className:Te("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",D&&"bg-[var(--interactive-border)]"),onPointerDown:oe,onPointerMove:fe,onPointerUp:ve,onPointerCancel:ve,role:"separator","aria-orientation":"vertical","aria-label":t("contextPanel.actions.resizePanelAria")}),ke,s.jsxs("div",{className:Te("relative min-h-0 flex-1 overflow-hidden",D&&"pointer-events-none"),children:[ce?s.jsx("div",{className:Te("absolute inset-0",xe?"block":"hidden"),children:s.jsx(th,{mode:"editor-only"})}):null,Fe.map(P=>{const F=fa(P.dedupeKey);if(!F)return null;const ue=se(P.id,F,P.readOnly);return ue?s.jsx("iframe",{ref:be=>{if(!be){$.current.delete(P.id);return}$.current.set(P.id,be)},src:ue,title:t("contextPanel.iframe.sessionChatTitle",{sessionID:F}),className:Te("absolute inset-0 h-full w-full border-0 bg-background",pe===P.id?"block":"hidden"),onLoad:()=>{je(),De()}},P.id):null}),he.map(P=>s.jsx("div",{className:Te("absolute inset-0",w?.id!==P.id&&"hidden"),children:s.jsx(me,{initialUrl:P.targetPath??"",directory:n,tabID:P.id})},P.id)),Ie.map(P=>s.jsx("div",{className:Te("absolute inset-0",w?.id!==P.id&&"hidden"),children:s.jsx(Jm,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:P.stagedDiff?"staged":"working",onDiffScopeChange:Z,targetFilePath:P.targetPath,flushContent:!0})},P.id)),w?.mode!=="chat"&&!xe&&w?.mode!=="browser"&&w?.mode!=="diff"?Me:null]})]})},oc=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},tj=()=>{const t=ft.c(171),{t:e}=Nt(),n=Ee(sj),r=Ee(nj),o=Ee(rj),a=Ee(ij),c=Ee(oj),l=Ee(aj),d=Ee(lj),f=Ee(cj),m=Ee(dj),u=Ee(uj),p=Ee(fj),y=Ee(mj),g=ut(hj),b=ut(pj),x=jr(gj),h=Ys(xj),C=Ss(bj),w=pi(),v=gc(yj),{files:S,git:k}=Xn(),j=wn(wj),{isMobile:A}=Or();let D;t[0]!==w?(D=w?oc(w):null,t[0]=w,t[1]=D):D=t[1];const N=D,[B,T]=i.useState(""),E=Ya(B,200);let _;t[2]!==E?(_=E.trim(),t[2]=E,t[3]=_):_=t[3];const R=_;let z;t[4]!==B?(z=B.trim(),t[4]=B,t[5]=z):z=t[5];const V=z;let $,M;t[6]!==n?($=()=>{n&&T("")},M=[n],t[6]=n,t[7]=$,t[8]=M):($=t[7],M=t[8]),i.useEffect($,M);let te,re;t[9]!==x||t[10]!==j||t[11]!==k||t[12]!==n?(te=()=>{if(!n||!k)return;const qe=setTimeout(()=>{const gt=new Set;for(const Xe of x){const jt=Mr(Xe);!jt||gt.has(jt)||(gt.add(jt),j(jt,k))}},0);return()=>clearTimeout(qe)},re=[n,x,k,j],t[9]=x,t[10]=j,t[11]=k,t[12]=n,t[13]=te,t[14]=re):(te=t[13],re=t[14]),i.useEffect(te,re);let Q;t[15]!==r?(Q=()=>r(!1),t[15]=r,t[16]=Q):Q=t[16];const H=Q;let X;t[17]!==H?(X=qe=>()=>{H(),qe()},t[17]=H,t[18]=X):X=t[18];const oe=X;let fe;t[19]!==C?.id||t[20]!==C?.path||t[21]!==h||t[22]!==A||t[23]!==u||t[24]!==g||t[25]!==oe||t[26]!==o||t[27]!==l||t[28]!==a||t[29]!==e||t[30]!==m||t[31]!==f||t[32]!==d?(fe=()=>{const qe=[{id:"new-session",title:e("commandPalette.item.newSession"),icon:s.jsx(I,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:e("commandPalette.item.newSession"),onSelect:oe(()=>{o("chat"),l(!1),g()})},{id:"new-worktree",title:e("commandPalette.item.newWorktreeDraft"),icon:s.jsx(I,{name:"git-branch",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat_worktree",searchText:e("commandPalette.item.newWorktreeDraft"),onSelect:oe(vj)},{id:"add-project",title:e("commandPalette.item.addProject"),icon:s.jsx(I,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.addProject"),onSelect:oe(jj)},{id:"toggle-sidebar",title:e(A?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),icon:s.jsx(I,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:e(A?"commandPalette.item.showSessionSwitcher":"commandPalette.item.toggleSidebar"),onSelect:oe(()=>{if(A){const{isSessionSwitcherOpen:gt}=Ee.getState();l(!gt)}else d()})},{id:"toggle-right-sidebar",title:e("commandPalette.item.toggleRightSidebar"),icon:s.jsx(I,{name:"layout-right",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_right_sidebar",searchText:e("commandPalette.item.toggleRightSidebar"),onSelect:oe(()=>f())},{id:"toggle-terminal",title:e("commandPalette.item.toggleTerminal"),icon:s.jsx(I,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:e("commandPalette.item.toggleTerminal"),onSelect:oe(()=>m())},{id:"context-usage",title:e("commandPalette.item.showContextUsage"),icon:s.jsx(I,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:e("commandPalette.item.showContextUsage"),onSelect:oe(()=>{h&&u(h)})},{id:"open-settings",title:e("commandPalette.item.openSettings"),icon:s.jsx(I,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:e("commandPalette.item.openSettings"),onSelect:oe(()=>a(!0))}];return _a()&&qe.splice(1,0,{id:"new-mini-chat",title:e("commandPalette.item.newMiniChat"),icon:s.jsx(I,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:e("commandPalette.item.newMiniChat"),onSelect:oe(()=>{Gr("desktop_open_draft_mini_chat_window",{directory:oc(h||C?.path||""),projectId:C?.id??null}).catch(Sj)})}),qe},t[19]=C?.id,t[20]=C?.path,t[21]=h,t[22]=A,t[23]=u,t[24]=g,t[25]=oe,t[26]=o,t[27]=l,t[28]=a,t[29]=e,t[30]=m,t[31]=f,t[32]=d,t[33]=fe):fe=t[33],C?.id,C?.path;let ve;t[34]!==fe?(ve=fe(),t[34]=fe,t[35]=ve):ve=t[35];const ie=ve;let Ne;t[36]===Symbol.for("react.memo_cache_sentinel")?(Ne=dr(),t[36]=Ne):Ne=t[36];const K=Ne;let pe,L;t[37]===Symbol.for("react.memo_cache_sentinel")?(pe=Yr(),L=!K&&bc(),t[37]=pe,t[38]=L):(pe=t[37],L=t[38]);let se;t[39]!==A?(se={isVSCode:pe,isWeb:L,isDesktop:K,isMobile:A},t[39]=A,t[40]=se):se=t[40];const Z=se;let je;if(t[41]!==oe||t[42]!==a||t[43]!==c||t[44]!==Z){let qe;t[46]!==Z?(qe=Xe=>Xe.isAvailable?Xe.isAvailable(Z):!0,t[46]=Z,t[47]=qe):qe=t[47];let gt;t[48]!==oe||t[49]!==a||t[50]!==c?(gt=Xe=>{const jt=Qx(Xe.slug)??"settings-3",Pt=(Xe.keywords??[]).join(" ");return{id:`settings:${Xe.slug}`,title:Xe.title,icon:Xe.slug==="mcp"?s.jsx(Kl,{className:"mr-2 h-4 w-4"}):s.jsx(I,{name:jt,className:"mr-2 h-4 w-4"}),searchText:`${Xe.title} ${Xe.group} ${Pt}`,onSelect:oe(()=>{c(Xe.slug),a(!0)})}},t[48]=oe,t[49]=a,t[50]=c,t[51]=gt):gt=t[51],je=Yx.filter(Nj).filter(qe).map(gt),t[41]=oe,t[42]=a,t[43]=c,t[44]=Z,t[45]=je}else je=t[45];const De=je,Le=kj;let Me;if(t[52]!==x){let qe;t[54]===Symbol.for("react.memo_cache_sentinel")?(qe=(gt,Xe)=>Le(Xe)-Le(gt),t[54]=qe):qe=t[54],Me=[...x].sort(qe),t[52]=x,t[53]=Me}else Me=t[53];const Fe=Me,he=dm(),Ie=ut(Cj);let me;t[55]!==he||t[56]!==Ie?(me=(qe,gt)=>{const Xe=Ie.get(qe);return Xe?.branch?Xe.branch.trim()||null:gt&&he.get(gt)?.trim()||null},t[55]=he,t[56]=Ie,t[57]=me):me=t[57];const ce=me;let xe;t[58]===Symbol.for("react.memo_cache_sentinel")?(xe=[],t[58]=xe):xe=t[58];const[ke,de]=i.useState(xe),[P,F]=i.useState(!1);let ue,be;t[59]!==N||t[60]!==n||t[61]!==v||t[62]!==R?(ue=()=>{if(!n){de([]),F(!1);return}if(!N||R.length===0){de([]),F(!1);return}let qe=!1;return F(!0),v(N,R,10,{type:"file"}).then(gt=>{qe||de(gt.map(Aj))}).catch(()=>{qe||de([])}).finally(()=>{qe||F(!1)}),()=>{qe=!0}},be=[n,N,R,v],t[59]=N,t[60]=n,t[61]=v,t[62]=R,t[63]=ue,t[64]=be):(ue=t[63],be=t[64]),i.useEffect(ue,be);const W=V.length>0;let ge;e:{if(!W){let gt;t[65]!==ie?(gt=ie.map(Dj),t[65]=ie,t[66]=gt):gt=t[66],ge=gt;break e}let qe;t[67]!==ie||t[68]!==V?(qe=Uo(ie,V,Ij,{limit:7,noFuzzy:!0}),t[67]=ie,t[68]=V,t[69]=qe):qe=t[69],ge=qe}const we=ge;let G;e:{if(!W){let gt;t[70]===Symbol.for("react.memo_cache_sentinel")?(gt=[],t[70]=gt):gt=t[70],G=gt;break e}let qe;t[71]!==V||t[72]!==De?(qe=Uo(De,V,Pj,{limit:7,noFuzzy:!0}),t[71]=V,t[72]=De,t[73]=qe):qe=t[73],G=qe}const Se=G;let Oe;e:{if(!W){let gt;t[74]!==Fe?(gt=Fe.slice(0,5).map(Tj),t[74]=Fe,t[75]=gt):gt=t[75],Oe=gt;break e}let qe;t[76]!==V||t[77]!==Fe?(qe=Uo(Fe,V,Rj,{limit:7,threshold:.2}),t[76]=V,t[77]=Fe,t[78]=qe):qe=t[78],Oe=qe}const Ae=Oe;let J;e:{if(!W||ke.length===0){let gt;t[79]===Symbol.for("react.memo_cache_sentinel")?(gt=[],t[79]=gt):gt=t[79],J=gt;break e}let qe;t[80]!==ke||t[81]!==V?(qe=Uo(ke,V,Ej,{limit:10,threshold:.4}),t[80]=ke,t[81]=V,t[82]=qe):qe=t[82],J=qe}const O=J;let ae,ne,Be,Ye,He,Je,nt,xt,bt,_e,Qe,st,pt,At,vt;if(t[83]!==ce||t[84]!==H||t[85]!==N||t[86]!==S||t[87]!==W||t[88]!==n||t[89]!==p||t[90]!==B||t[91]!==we||t[92]!==O||t[93]!==Ae||t[94]!==Se||t[95]!==r||t[96]!==b||t[97]!==y||t[98]!==e){const qe=we.map(Mj),gt=Se.map(Fj),Xe=Ae.map(Oj);vt=W?O.map(Lj):[];let jt;e:{if(!W){jt=["commands","sessions"];break e}const Vt=Bj,yt=[{key:"commands",score:Vt(we)},{key:"settings",score:Vt(Se)},{key:"sessions",score:Vt(Ae)},{key:"files",score:Vt(O)}];yt.sort(_j),jt=yt.map(Vj)}const Pt=jt;let is;t[114]!==H||t[115]!==b?(is=Vt=>{H(),b(Vt.id,Mr(Vt))},t[114]=H,t[115]=b,t[116]=is):is=t[116];const Bt=is;let Gt;t[117]!==H||t[118]!==N||t[119]!==S||t[120]!==p?(Gt=async Vt=>{if(!N)return;const yt=await zc(S,Vt);if(!yt.ok){le.error(Wc(yt.reason));return}p(N,Vt),H()},t[117]=H,t[118]=N,t[119]=S,t[120]=p,t[121]=Gt):Gt=t[121];const es=Gt;let Wt;t[122]!==y?(Wt=Vt=>Va(di(Vt,y)),t[122]=y,t[123]=Wt):Wt=t[123];const Lt=Wt;Ye=Ms,st=n,pt=r;let Ut;t[124]!==e?(Ut=e("commandPalette.title"),t[124]=e,t[125]=Ut):Ut=t[125];let rs;t[126]!==Ut?(rs=s.jsx(Vs,{children:Ut}),t[126]=Ut,t[127]=rs):rs=t[127];let $t;t[128]!==e?($t=e("commandPalette.description"),t[128]=e,t[129]=$t):$t=t[129];let ls;t[130]!==$t?(ls=s.jsx(an,{children:$t}),t[130]=$t,t[131]=ls):ls=t[131],t[132]!==rs||t[133]!==ls?(At=s.jsxs(Gs,{className:"sr-only",children:[rs,ls]}),t[132]=rs,t[133]=ls,t[134]=At):At=t[134],Be=Es,_e="overflow-hidden p-0",Qe=!0,ne=$a,nt=!1,xt="[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta";let xs;t[135]!==e?(xs=e("commandPalette.input.placeholder"),t[135]=e,t[136]=xs):xs=t[136],t[137]!==B||t[138]!==xs?(bt=s.jsx(za,{value:B,onValueChange:T,placeholder:xs}),t[137]=B,t[138]=xs,t[139]=bt):bt=t[139],ae=Wa;let Ct;t[140]!==e?(Ct=e("commandPalette.empty.noResults"),t[140]=e,t[141]=Ct):Ct=t[141],t[142]!==Ct?(He=s.jsx(Ua,{children:Ct}),t[142]=Ct,t[143]=He):He=t[143],Je=Pt.map(Vt=>Vt==="commands"&&qe.length>0?s.jsx(ui,{children:qe.map(yt=>s.jsxs(mi,{value:yt.id,onSelect:yt.onSelect,children:[yt.icon,s.jsx("span",{children:yt.title}),yt.shortcutId?s.jsx(Dg,{children:Lt(yt.shortcutId)}):null]},yt.id))},"commands"):Vt==="settings"&>.length>0?s.jsx(ui,{children:gt.map($j)},"settings"):Vt==="sessions"&&Xe.length>0?s.jsx(ui,{children:Xe.map(yt=>{const us=yt.title||e("commandPalette.session.untitled"),cs=Mr(yt),Ue=ce(yt.id,cs);return s.jsxs(mi,{value:`session:${yt.id}`,onSelect:()=>Bt(yt),children:[s.jsx(I,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),s.jsx("span",{className:"truncate",children:us}),Ue?s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3"}),s.jsx("span",{className:"truncate max-w-[160px]",children:Ue})]}):null]},yt.id)})},"sessions"):Vt==="files"&&vt.length>0?s.jsx(ui,{children:vt.map(yt=>{const us=Ig(yt.relativePath||yt.name,{maxLength:80});return s.jsxs(mi,{value:`file:${yt.path}`,onSelect:()=>{es(yt.path)},children:[s.jsx(Kr,{filePath:yt.path,className:"mr-2 size-4 shrink-0"}),s.jsx("span",{className:"truncate","aria-label":yt.relativePath,children:us})]},`file:${yt.path}`)})},"files"):null),t[83]=ce,t[84]=H,t[85]=N,t[86]=S,t[87]=W,t[88]=n,t[89]=p,t[90]=B,t[91]=we,t[92]=O,t[93]=Ae,t[94]=Se,t[95]=r,t[96]=b,t[97]=y,t[98]=e,t[99]=ae,t[100]=ne,t[101]=Be,t[102]=Ye,t[103]=He,t[104]=Je,t[105]=nt,t[106]=xt,t[107]=bt,t[108]=_e,t[109]=Qe,t[110]=st,t[111]=pt,t[112]=At,t[113]=vt}else ae=t[99],ne=t[100],Be=t[101],Ye=t[102],He=t[103],Je=t[104],nt=t[105],xt=t[106],bt=t[107],_e=t[108],Qe=t[109],st=t[110],pt=t[111],At=t[112],vt=t[113];let kt;t[144]!==W||t[145]!==P||t[146]!==e||t[147]!==vt?(kt=W&&P&&vt.length===0?s.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:e("commandPalette.empty.searchingFiles")}):null,t[144]=W,t[145]=P,t[146]=e,t[147]=vt,t[148]=kt):kt=t[148];let et;t[149]!==ae||t[150]!==He||t[151]!==Je||t[152]!==kt?(et=s.jsxs(ae,{children:[He,Je,kt]}),t[149]=ae,t[150]=He,t[151]=Je,t[152]=kt,t[153]=et):et=t[153];let _t;t[154]!==ne||t[155]!==nt||t[156]!==xt||t[157]!==bt||t[158]!==et?(_t=s.jsxs(ne,{shouldFilter:nt,className:xt,children:[bt,et]}),t[154]=ne,t[155]=nt,t[156]=xt,t[157]=bt,t[158]=et,t[159]=_t):_t=t[159];let ns;t[160]!==Be||t[161]!==_e||t[162]!==Qe||t[163]!==_t?(ns=s.jsx(Be,{className:_e,showCloseButton:Qe,children:_t}),t[160]=Be,t[161]=_e,t[162]=Qe,t[163]=_t,t[164]=ns):ns=t[164];let Kt;return t[165]!==Ye||t[166]!==st||t[167]!==pt||t[168]!==At||t[169]!==ns?(Kt=s.jsxs(Ye,{open:st,onOpenChange:pt,children:[At,ns]}),t[165]=Ye,t[166]=st,t[167]=pt,t[168]=At,t[169]=ns,t[170]=Kt):Kt=t[170],Kt};function sj(t){return t.isCommandPaletteOpen}function nj(t){return t.setCommandPaletteOpen}function rj(t){return t.setActiveMainTab}function ij(t){return t.setSettingsDialogOpen}function oj(t){return t.setSettingsPage}function aj(t){return t.setSessionSwitcherOpen}function lj(t){return t.toggleSidebar}function cj(t){return t.toggleRightSidebar}function dj(t){return t.toggleBottomTerminal}function uj(t){return t.openContextOverview}function fj(t){return t.openContextFile}function mj(t){return t.shortcutOverrides}function hj(t){return t.openNewSessionDraft}function pj(t){return t.setCurrentSession}function gj(t){return t.activeSessions}function xj(t){return t.currentDirectory}function bj(t){return t.getActiveProject()}function yj(t){return t.searchFiles}function wj(t){return t.ensureStatus}function vj(){um()}function jj(){Er.requestDirectoryDialog()}function Sj(t){console.warn("[command-palette] failed to open draft mini chat window",t)}function Nj(t){return t.slug!=="home"}function kj(t){return(typeof t.time?.updated=="number"?t.time.updated:0)||(typeof t.time?.created=="number"?t.time.created:0)}function Cj(t){return t.worktreeMetadata}function Aj(t){return{path:oc(t.path),name:t.name,relativePath:t.relativePath}}function Dj(t){return{item:t,score:0}}function Ij(t){return t.searchText}function Pj(t){return t.searchText}function Tj(t){return{item:t,score:0}}function Rj(t){return t.title||""}function Ej(t){return t.name}function Mj(t){return t.item}function Fj(t){return t.item}function Oj(t){return t.item}function Lj(t){return t.item}function Bj(t){return t.length?t[0].score:1/0}function _j(t,e){return t.score-e.score}function Vj(t){return t.key}function $j(t){return s.jsxs(mi,{value:t.id,onSelect:t.onSelect,children:[t.icon,s.jsx("span",{children:t.title})]},t.id)}const ef=(t,e,n)=>Tg(t)?Va(di(t,n)):e,zj=()=>{const t=ft.c(68),{t:e}=Nt(),n=Ee(Wj),r=Ee(Uj),o=Ee(Hj);let a;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=Pg(),t[0]=a):a=t[0];const c=a;let l,d,f,m,u,p,y,g,b;if(t[1]!==n||t[2]!==r||t[3]!==o||t[4]!==e){const R=[{categoryKey:"helpDialog.section.navigationCommands",items:[{id:"open_command_palette",descriptionKey:"helpDialog.item.openCommandPalette",icon:"command",keys:""},{id:"open_help",descriptionKey:"helpDialog.item.showKeyboardShortcuts",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"helpDialog.item.toggleSessionSidebar",icon:"layout-left",keys:""},{id:"cycle_agent",keys:"",descriptionKey:"helpDialog.item.cycleAgent",icon:"ai-agent"},{id:"open_model_selector",descriptionKey:"helpDialog.item.openModelSelector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"helpDialog.item.navigateModels",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"helpDialog.item.adjustThinkingMode",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"helpDialog.item.cycleThinkingVariant",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${c} + N`],descriptionKey:"helpDialog.item.newWindow",icon:"window"}]},{categoryKey:"helpDialog.section.sessionManagement",items:[{id:"new_chat",descriptionKey:"helpDialog.item.createNewSession",icon:"add",keys:""},{id:"new_chat_worktree",descriptionKey:"helpDialog.item.createNewWorktreeDraft",icon:"git-branch",keys:""},{id:"focus_input",descriptionKey:"helpDialog.item.focusChatInput",icon:"text",keys:""},{id:"abort_run",descriptionKey:"helpDialog.item.abortActiveRun",icon:"close-circle",keys:""}]},{categoryKey:"helpDialog.section.panels",items:[{id:"toggle_right_sidebar",descriptionKey:"helpDialog.item.toggleRightSidebar",icon:"layout-right",keys:""},{id:"open_right_sidebar_git",descriptionKey:"helpDialog.item.openRightSidebarGitTab",icon:"git-branch",keys:""},{id:"open_right_sidebar_files",descriptionKey:"helpDialog.item.openRightSidebarFilesTab",icon:"layout-right",keys:""},{id:"cycle_right_sidebar_tab",descriptionKey:"helpDialog.item.cycleRightSidebarTab",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{id:"toggle_terminal_expanded",descriptionKey:"helpDialog.item.toggleTerminalExpanded",icon:"window",keys:""},{id:"toggle_context_plan",descriptionKey:"helpDialog.item.togglePlanContextPanel",icon:"time",keys:""}]},{categoryKey:"helpDialog.section.interface",items:[{id:"cycle_theme",descriptionKey:"helpDialog.item.cycleTheme",icon:"palette",keys:""},{keys:[`${c} + 1...9`],descriptionKey:"helpDialog.item.switchProject",icon:"layout-left"},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"cycle_services_tab",descriptionKey:"helpDialog.item.cycleServicesTab",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"helpDialog.item.openSettings",icon:"settings-3",keys:""}]}];d=Ms,g=n,b=r,l=Es,p="max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden";let z;t[14]===Symbol.for("react.memo_cache_sentinel")?(z=s.jsx(I,{name:"settings-3",className:"h-5 w-5"}),t[14]=z):z=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(Vs,{className:"flex items-center gap-2",children:[z,V]}),t[17]=V,t[18]=$):$=t[18];let M;t[19]!==e?(M=e("helpDialog.description"),t[19]=e,t[20]=M):M=t[20];let te;t[21]!==M?(te=s.jsx(an,{children:M}),t[21]=M,t[22]=te):te=t[22],t[23]!==$||t[24]!==te?(y=s.jsxs(Gs,{children:[$,te]}),t[23]=$,t[24]=te,t[25]=y):y=t[25],u="flex-1 overflow-y-auto mt-3 pr-1",f="space-y-4",m=R.map(re=>s.jsxs("div",{children:[s.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:e(re.categoryKey)}),s.jsx("div",{className:"space-y-1",children:re.items.map(Q=>{const H=Q.id?ef(Q.id,Array.isArray(Q.keys)?Q.keys[0]:Q.keys,o):Array.isArray(Q.keys)?Q.keys:Q.keys.split(" / ");return s.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[Q.icon&&s.jsx(I,{name:Q.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("span",{className:"typography-meta",children:e(Q.descriptionKey)})]}),s.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(H)?H:[H]).map((X,oe)=>s.jsxs(i.Fragment,{children:[oe>0&&s.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:e("helpDialog.keyCombiner.or")}),s.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:X})]},`${X}-${oe}`))})]},Q.id||Q.descriptionKey)})})]},re.categoryKey)),t[1]=n,t[2]=r,t[3]=o,t[4]=e,t[5]=l,t[6]=d,t[7]=f,t[8]=m,t[9]=u,t[10]=p,t[11]=y,t[12]=g,t[13]=b}else l=t[5],d=t[6],f=t[7],m=t[8],u=t[9],p=t[10],y=t[11],g=t[12],b=t[13];let x;t[26]!==f||t[27]!==m?(x=s.jsx("div",{className:f,children:m}),t[26]=f,t[27]=m,t[28]=x):x=t[28];let h;t[29]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(I,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),t[29]=h):h=t[29];let C;t[30]!==e?(C=e("helpDialog.proTips.title"),t[30]=e,t[31]=C):C=t[31];let w;t[32]!==C?(w=s.jsx("p",{className:"font-medium mb-1",children:C}),t[32]=C,t[33]=w):w=t[33];let v;t[34]!==o||t[35]!==e?(v=e("helpDialog.proTips.commandPalette",{shortcut:ef("open_command_palette",`${c} P`,o)}),t[34]=o,t[35]=e,t[36]=v):v=t[36];let S;t[37]!==v?(S=s.jsxs("li",{children:["• ",v]}),t[37]=v,t[38]=S):S=t[38];let k;t[39]!==e?(k=e("helpDialog.proTips.recentSessions"),t[39]=e,t[40]=k):k=t[40];let j;t[41]!==k?(j=s.jsxs("li",{children:["• ",k]}),t[41]=k,t[42]=j):j=t[42];let A;t[43]!==e?(A=e("helpDialog.proTips.themeCycling"),t[43]=e,t[44]=A):A=t[44];let D;t[45]!==A?(D=s.jsxs("li",{children:["• ",A]}),t[45]=A,t[46]=D):D=t[46];let N;t[47]!==S||t[48]!==j||t[49]!==D?(N=s.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[S,j,D]}),t[47]=S,t[48]=j,t[49]=D,t[50]=N):N=t[50];let B;t[51]!==w||t[52]!==N?(B=s.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:s.jsxs("div",{className:"flex items-start gap-2",children:[h,s.jsxs("div",{className:"typography-meta text-muted-foreground",children:[w,N]})]})}),t[51]=w,t[52]=N,t[53]=B):B=t[53];let T;t[54]!==B||t[55]!==u||t[56]!==x?(T=s.jsxs("div",{className:u,children:[x,B]}),t[54]=B,t[55]=u,t[56]=x,t[57]=T):T=t[57];let E;t[58]!==l||t[59]!==T||t[60]!==p||t[61]!==y?(E=s.jsxs(l,{className:p,children:[y,T]}),t[58]=l,t[59]=T,t[60]=p,t[61]=y,t[62]=E):E=t[62];let _;return t[63]!==d||t[64]!==E||t[65]!==g||t[66]!==b?(_=s.jsx(d,{open:g,onOpenChange:b,children:E}),t[63]=d,t[64]=E,t[65]=g,t[66]=b,t[67]=_):_=t[67],_};function Wj(t){return t.isHelpDialogOpen}function Uj(t){return t.setHelpDialogOpen}function Hj(t){return t.shortcutOverrides}const Gj=()=>{const t=ft.c(32),{t:e}=Nt(),n=Ee(Kj),r=Ee(qj),o=Ee(Yj);let a;t[0]!==o||t[1]!==e?(a=async()=>{if(!o)return;if((await ur(o)).ok){le.success(e("openCodeStatusDialog.toast.copiedTitle"),{description:e("openCodeStatusDialog.toast.copiedDescription")});return}le.error(e("openCodeStatusDialog.toast.copyFailed"))},t[0]=o,t[1]=e,t[2]=a):a=t[2];const c=a;let l;t[3]!==e?(l=e("openCodeStatusDialog.title"),t[3]=e,t[4]=l):l=t[4];let d;t[5]!==l?(d=s.jsx(Vs,{children:l}),t[5]=l,t[6]=d):d=t[6];let f;t[7]!==e?(f=e("openCodeStatusDialog.description"),t[7]=e,t[8]=f):f=t[8];let m;t[9]!==f?(m=s.jsx(an,{children:f}),t[9]=f,t[10]=m):m=t[10];let u;t[11]!==d||t[12]!==m?(u=s.jsxs(Gs,{children:[d,m]}),t[11]=d,t[12]=m,t[13]=u):u=t[13];let p;t[14]!==e?(p=e("openCodeStatusDialog.actions.copy"),t[14]=e,t[15]=p):p=t[15];let y;t[16]!==c||t[17]!==p?(y=s.jsx("div",{className:"flex items-center justify-end",children:s.jsx("button",{type:"button",onClick:c,className:"app-region-no-drag inline-flex h-9 items-center justify-center rounded-md px-3 typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:p})}),t[16]=c,t[17]=p,t[18]=y):y=t[18];let g;t[19]!==o||t[20]!==e?(g=o||e("openCodeStatusDialog.empty.noData"),t[19]=o,t[20]=e,t[21]=g):g=t[21];let b;t[22]!==g?(b=s.jsx("pre",{className:"max-h-[60vh] overflow-auto rounded-lg bg-surface-muted p-4 typography-code text-foreground whitespace-pre-wrap",children:g}),t[22]=g,t[23]=b):b=t[23];let x;t[24]!==u||t[25]!==y||t[26]!==b?(x=s.jsxs(Es,{className:"max-w-2xl",children:[u,y,b]}),t[24]=u,t[25]=y,t[26]=b,t[27]=x):x=t[27];let h;return t[28]!==n||t[29]!==r||t[30]!==x?(h=s.jsx(Ms,{open:n,onOpenChange:r,children:x}),t[28]=n,t[29]=r,t[30]=x,t[31]=h):h=t[31],h};function Kj(t){return t.isOpenCodeStatusDialogOpen}function qj(t){return t.setOpenCodeStatusDialogOpen}function Yj(t){return t.openCodeStatusText}const Qj=180,tf=600,Jj=1,Xj=6,Zj=({currentSessionId:t,sortedSessions:e,recentSessionIds:n=[],ensureSessionRenderable:r})=>{const o=i.useRef(new Map),a=i.useRef([]),c=i.useRef(new Set),l=i.useMemo(()=>Yr(),[]),d=i.useCallback(()=>{if(!(l||typeof window>"u"))for(;c.current.size<Jj&&a.current.length>0;){const m=a.current.shift();if(!m)break;ut.getState().currentSessionId!==m&&(Bd(m).renderable||(c.current.add(m),r(m).catch(()=>{}).finally(()=>{c.current.delete(m),d()})))}},[r,l]),f=i.useCallback(m=>{if(l||!m||m===t||typeof window>"u"||Bd(m).renderable||c.current.has(m)||a.current.includes(m))return;a.current.length>=Xj&&a.current.shift();const u=o.current.get(m);u!==void 0&&window.clearTimeout(u);const p=window.setTimeout(()=>{o.current.delete(m),a.current.push(m),d()},Qj);o.current.set(m,p)},[t,l,d]);i.useEffect(()=>{if(l||!t||e.length===0)return;const m=window.setTimeout(()=>{const u=e.findIndex(p=>p.id===t);u<0||(f(e[u-1]?.id),f(e[u+1]?.id))},tf);return()=>window.clearTimeout(m)},[t,l,f,e]),i.useEffect(()=>{if(l||!t||n.length===0)return;const m=window.setTimeout(()=>{const u=n.indexOf(t);u<0||(f(n[u-1]),f(n[u+1]))},tf);return()=>window.clearTimeout(m)},[t,l,n,f]),i.useEffect(()=>{const m=o.current;return()=>{m.forEach(u=>{clearTimeout(u)}),m.clear(),a.current=[]}},[])};let Xi=null,Zi=null,ha=null,Mo=0,Fa=null;const Ei=new Set,eS=3e4,tS=45e3,ph=()=>{ha&&(clearTimeout(ha),ha=null)},gh=()=>{if(Zi||Ei.size===0)return;const t=Math.min(1e3*Math.pow(2,Math.min(Mo,5)),eS);Zi=setTimeout(()=>{Zi=null,Mo+=1,qc()},t)},Fo=()=>{ph(),Xi&&Xi.close(),Xi=null},sf=()=>{ph(),Ei.size!==0&&(ha=setTimeout(()=>{Fo(),gh()},tS))},sS=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}},nS=t=>{if(t.type==="openchamber:event-stream-ready"){Mo=0;return}if(t.type==="openchamber:heartbeat"||t.type!=="openchamber:scheduled-task-ran")return;const e=t.properties&&typeof t.properties=="object"?t.properties:null,n=typeof e?.projectId=="string"?e.projectId:"",r=typeof e?.taskId=="string"?e.taskId:"",o=typeof e?.ranAt=="number"?e.ranAt:Date.now(),a=e?.status,c=a==="running"||a==="error"?a:"success";if(!n||!r)return;const l={type:"scheduled-task-ran",projectId:n,taskId:r,ranAt:o,status:c,...typeof e?.sessionId=="string"&&e.sessionId.length>0?{sessionId:e.sessionId}:{}};for(const d of Ei)d(l)},qc=()=>{if(typeof window>"u"||Ei.size===0||typeof EventSource!="function"||Xi&&Xi.readyState!==EventSource.CLOSED)return;Fo();const t=new EventSource(Pi().sse("/api/openchamber/events"));t.onopen=()=>{sf()},t.onmessage=e=>{sf();const n=sS(e.data);n&&nS(n)},t.onerror=()=>{Fo(),gh()},Xi=t},rS=()=>{Fa||typeof window>"u"||(Fa=Wf(()=>{Fo(),Mo=0,qc()}))},iS=()=>{Fa?.(),Fa=null},xh=t=>(Ei.add(t),rS(),qc(),()=>{Ei.delete(t),Ei.size===0&&(Zi&&(clearTimeout(Zi),Zi=null),Mo=0,Fo(),iS())}),Za=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},oo=t=>{const e=typeof t=="string"?t.trim():"";if(!e)throw new Error("projectId is required");return e},oS=async t=>{const e=oo(t),n=await Cs(`/api/projects/${encodeURIComponent(e)}/scheduled-tasks`);if(!n.ok)throw new Error(await Za(n,"Failed to load scheduled tasks"));const r=await n.json().catch(()=>null);return!r||!Array.isArray(r.tasks)?[]:r.tasks},nf=async(t,e)=>{const n=oo(t),r=await Cs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks`,{method:"PUT",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({task:e})});if(!r.ok)throw new Error(await Za(r,"Failed to save scheduled task"));const o=await r.json().catch(()=>null);return!o||!Array.isArray(o.tasks)?[]:o.tasks},aS=async(t,e)=>{const n=oo(t),r=oo(e),o=await Cs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}`,{method:"DELETE",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Za(o,"Failed to delete scheduled task"));const a=await o.json().catch(()=>null);return!a||!Array.isArray(a.tasks)?[]:a.tasks},lS=async(t,e)=>{const n=oo(t),r=oo(e),o=await Cs(`/api/projects/${encodeURIComponent(n)}/scheduled-tasks/${encodeURIComponent(r)}/run`,{method:"POST",headers:{accept:"application/json"}});if(!o.ok)throw new Error(await Za(o,"Failed to run scheduled task"));const a=await o.json().catch(()=>null);return{sessionId:typeof a?.sessionId=="string"&&a.sessionId.length>0?a.sessionId:void 0}};function bh(t){if(!t||!t.trim())return{valid:!1,error:"required"};try{return _f.CronExpressionParser.parse(t),{valid:!0}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"Invalid cron expression"}}}function cS(t,e,n=4){try{const r=e?{tz:e,currentDate:new Date}:{currentDate:new Date},o=_f.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 dS=[{expression:"*/5 * * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.every5min"},{expression:"0 * * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.everyHour"},{expression:"0 9 * * 1",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.monday9am"},{expression:"0 9,17 * * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.9am5pm"},{expression:"0 0 1 * *",labelKey:"sessions.scheduledTasks.editor.cronExpression.examples.firstOfMonth"}],yh=[0,1,2,3,4,5,6],ac=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"],rf=()=>{const t=new Date,e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},pa=t=>{const e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!e)return null;const n=Number(e[1]),r=Number(e[2]),o=Number(e[3]),a=new Date(n,r-1,o);return Number.isNaN(a.getTime())||a.getFullYear()!==n||a.getMonth()!==r-1||a.getDate()!==o?null:a},of=t=>{const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${r}`},uS=(t,e,n)=>{const r=pa(t);return r?new Intl.DateTimeFormat(n,{month:"short",day:"numeric",year:"numeric"}).format(r):e},af=(t,e)=>new Date(t.getFullYear(),t.getMonth()+e,1),fS=(t,e)=>{const n=t.getFullYear(),r=t.getMonth(),c=(new Date(n,r,1).getDay()-e+7)%7,l=new Date(n,r+1,0).getDate(),d=new Date(n,r,0).getDate(),f=[];for(let m=0;m<42;m+=1){const u=m-c+1;if(u<=0){const p=d+u;f.push({date:new Date(n,r-1,p),inCurrentMonth:!1});continue}if(u>l){f.push({date:new Date(n,r+1,u-l),inCurrentMonth:!1});continue}f.push({date:new Date(n,r,u),inCurrentMonth:!0})}return f},mS=t=>{const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour24:"00",hour12:"12",minute:"00",meridiem:"AM"};const n=Number(e[1]),r=e[2],o=n>=12?"PM":"AM",a=n%12===0?12:n%12;return{hour24:String(n).padStart(2,"0"),hour12:String(a).padStart(2,"0"),minute:r,meridiem:o}},Ni=(t,e,n)=>{const r=Number(t),o=Number(e),a=Number.isFinite(r)?Math.min(12,Math.max(1,r)):12,c=Number.isFinite(o)?Math.min(59,Math.max(0,o)):0;let l=a%12;return n==="PM"&&(l+=12),`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`},fo=(t,e)=>{const{max:n,min:r=0,loop:o=!1}=e;let a=Number.parseInt(t,10);return Number.isFinite(a)?(o?(a>n&&(a=r),a<r&&(a=n)):(a>n&&(a=n),a<r&&(a=r)),String(a).padStart(2,"0")):"00"},lf=t=>/^(0[1-9]|1[0-2])$/.test(t)?t:fo(t,{min:1,max:12}),ea=t=>/^[0-5][0-9]$/.test(t)?t:fo(t,{max:59}),hS=(t,e)=>fo(String(Number.parseInt(t,10)+e),{min:1,max:12,loop:!0}),cf=(t,e)=>fo(String(Number.parseInt(t,10)+e),{min:0,max:59,loop:!0}),pS=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}},gS=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}},xS=t=>{const e=new Intl.DateTimeFormat(t,{weekday:"short"}),n=new Date(2023,0,1);return yh.map(r=>e.format(new Date(n.getFullYear(),n.getMonth(),n.getDate()+r)))},bS=(t,e)=>[...t.slice(e),...t.slice(0,e)],Yn=t=>{const e=ft.c(6),{htmlFor:n,required:r,children:o}=t;let a;e[0]!==r?(a=r&&s.jsx("span",{className:"ml-0.5 text-destructive",children:"*"}),e[0]=r,e[1]=a):a=e[1];let c;return e[2]!==o||e[3]!==n||e[4]!==a?(c=s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,a]})}),e[2]=o,e[3]=n,e[4]=a,e[5]=c):c=e[5],c},df=t=>{const e=ft.c(84),{value:n,onChange:r,use24Hour:o,hourAriaLabel:a,minuteAriaLabel:c,periodAriaLabel:l,amLabel:d,pmLabel:f}=t;let m;e[0]!==n?(m=mS(n),e[0]=n,e[1]=m):m=e[1];const u=m,p=tt.useRef(null),y=tt.useRef(null),[g,b]=tt.useState(null),[x,h]=tt.useState(null),C=tt.useRef(null),w=tt.useRef(null);let v;e[2]===Symbol.for("react.memo_cache_sentinel")?(v=me=>{C.current=me,b(me)},e[2]=v):v=e[2];const S=v;let k;e[3]===Symbol.for("react.memo_cache_sentinel")?(k=me=>{w.current=me,h(me)},e[3]=k):k=e[3];const j=k,A=kS,D=CS,N=AS;let B;e[4]!==r||e[5]!==u.meridiem||e[6]!==u.minute||e[7]!==o?(B=me=>{const ce=me.replace(/\D/g,"").slice(0,2);S(ce),ce.length===2&&(r(o?N(A(ce),u.minute):Ni(lf(ce),u.minute,u.meridiem)),S(null),y.current?.focus())},e[4]=r,e[5]=u.meridiem,e[6]=u.minute,e[7]=o,e[8]=B):B=e[8];const T=B;let E;e[9]!==r||e[10]!==u.meridiem||e[11]!==u.minute||e[12]!==o?(E=()=>{const me=C.current;if(me!==null&&(S(null),me.length!==0)){if(o){r(N(A(me.padStart(2,"0")),u.minute));return}r(Ni(lf(me.padStart(2,"0")),u.minute,u.meridiem))}},e[9]=r,e[10]=u.meridiem,e[11]=u.minute,e[12]=o,e[13]=E):E=e[13];const _=E;let R;e[14]!==r||e[15]!==u.hour12||e[16]!==u.hour24||e[17]!==u.meridiem||e[18]!==o?(R=me=>{const ce=me.replace(/\D/g,"").slice(0,2);j(ce),ce.length===2&&(r(o?N(u.hour24,ea(ce)):Ni(u.hour12,ea(ce),u.meridiem)),j(null))},e[14]=r,e[15]=u.hour12,e[16]=u.hour24,e[17]=u.meridiem,e[18]=o,e[19]=R):R=e[19];const z=R;let V;e[20]!==r||e[21]!==u.hour12||e[22]!==u.hour24||e[23]!==u.meridiem||e[24]!==o?(V=()=>{const me=w.current;me!==null&&(j(null),me.length!==0&&r(o?N(u.hour24,ea(me.padStart(2,"0"))):Ni(u.hour12,ea(me.padStart(2,"0")),u.meridiem)))},e[20]=r,e[21]=u.hour12,e[22]=u.hour24,e[23]=u.meridiem,e[24]=o,e[25]=V):V=e[25];const $=V;let M;e[26]!==r||e[27]!==u.hour12||e[28]!==u.hour24||e[29]!==u.meridiem||e[30]!==u.minute||e[31]!==o?(M=me=>r(o?N(D(u.hour24,me),u.minute):Ni(hS(u.hour12,me),u.minute,u.meridiem)),e[26]=r,e[27]=u.hour12,e[28]=u.hour24,e[29]=u.meridiem,e[30]=u.minute,e[31]=o,e[32]=M):M=e[32];const te=M;let re;e[33]!==r||e[34]!==u.hour12||e[35]!==u.hour24||e[36]!==u.meridiem||e[37]!==u.minute||e[38]!==o?(re=me=>r(o?N(u.hour24,cf(u.minute,me)):Ni(u.hour12,cf(u.minute,me),u.meridiem)),e[33]=r,e[34]=u.hour12,e[35]=u.hour24,e[36]=u.meridiem,e[37]=u.minute,e[38]=o,e[39]=re):re=e[39];const Q=re;let H;e[40]!==r||e[41]!==u.hour12||e[42]!==u.meridiem||e[43]!==u.minute?(H=me=>{me!==u.meridiem&&r(Ni(u.hour12,u.minute,me))},e[40]=r,e[41]=u.hour12,e[42]=u.meridiem,e[43]=u.minute,e[44]=H):H=e[44];const X=H;let oe;e[45]!==_||e[46]!==te?(oe=me=>{if(me.key==="ArrowRight"){me.preventDefault(),_(),y.current?.focus();return}(me.key==="ArrowUp"||me.key==="ArrowDown")&&(me.preventDefault(),S(null),te(me.key==="ArrowUp"?1:-1))},e[45]=_,e[46]=te,e[47]=oe):oe=e[47];const fe=oe;let ve;e[48]!==$||e[49]!==Q?(ve=me=>{if(me.key==="ArrowLeft"&&(me.currentTarget.selectionStart??0)===0){me.preventDefault(),$(),p.current?.focus();return}(me.key==="ArrowUp"||me.key==="ArrowDown")&&(me.preventDefault(),j(null),Q(me.key==="ArrowUp"?1:-1))},e[48]=$,e[49]=Q,e[50]=ve):ve=e[50];const ie=ve,Ne=o?"px-2":"pl-2 pr-1";let K;e[51]!==Ne?(K=Te("inline-flex h-9 w-fit items-center gap-1 rounded-md border border-border bg-background focus-within:ring-1 focus-within:ring-interactive-focusRing focus-within:border-interactive-focusRing",Ne),e[51]=Ne,e[52]=K):K=e[52];const pe=g??(o?u.hour24:u.hour12);let L;e[53]!==T?(L=me=>T(me.target.value),e[53]=T,e[54]=L):L=e[54];let se;e[55]===Symbol.for("react.memo_cache_sentinel")?(se=()=>S(""),e[55]=se):se=e[55];let Z;e[56]!==_||e[57]!==a||e[58]!==fe||e[59]!==pe||e[60]!==L?(Z=s.jsx("input",{ref:p,inputMode:"numeric",value:pe,onChange:L,onKeyDown:fe,onFocus:se,onBlur:_,maxLength:2,"aria-label":a,className:"h-7 w-7 shrink-0 rounded-sm bg-transparent text-center font-mono text-sm tabular-nums text-foreground outline-none caret-transparent focus:bg-interactive-hover"}),e[56]=_,e[57]=a,e[58]=fe,e[59]=pe,e[60]=L,e[61]=Z):Z=e[61];let je;e[62]===Symbol.for("react.memo_cache_sentinel")?(je=s.jsx("span",{className:"font-mono text-sm text-muted-foreground",children:":"}),e[62]=je):je=e[62];const De=x??u.minute;let Le;e[63]!==z?(Le=me=>z(me.target.value),e[63]=z,e[64]=Le):Le=e[64];let Me;e[65]===Symbol.for("react.memo_cache_sentinel")?(Me=()=>j(""),e[65]=Me):Me=e[65];let Fe;e[66]!==$||e[67]!==c||e[68]!==ie||e[69]!==De||e[70]!==Le?(Fe=s.jsx("input",{ref:y,inputMode:"numeric",value:De,onChange:Le,onKeyDown:ie,onFocus:Me,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]=ie,e[69]=De,e[70]=Le,e[71]=Fe):Fe=e[71];let he;e[72]!==d||e[73]!==u.meridiem||e[74]!==l||e[75]!==f||e[76]!==X||e[77]!==o?(he=o?null:s.jsxs(Un,{value:u.meridiem,onValueChange:me=>X(me),children:[s.jsx(Hn,{"aria-label":l,className:"ml-1 h-7 w-fit border-0 bg-transparent pl-2 pr-1 shadow-none hover:bg-interactive-hover focus:ring-0",children:s.jsx(An,{})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"AM",children:d}),s.jsx(Rs,{value:"PM",children:f})]})]}),e[72]=d,e[73]=u.meridiem,e[74]=l,e[75]=f,e[76]=X,e[77]=o,e[78]=he):he=e[78];let Ie;return e[79]!==K||e[80]!==Z||e[81]!==Fe||e[82]!==he?(Ie=s.jsxs("div",{className:K,children:[Z,je,Fe,he]}),e[79]=K,e[80]=Z,e[81]=Fe,e[82]=he,e[83]=Ie):Ie=e[83],Ie},uf=t=>new Date(t.getFullYear(),t.getMonth(),1),yS=()=>{const t=new Date;return new Date(t.getFullYear(),t.getMonth(),t.getDate())},ff=(t,e)=>t.getFullYear()===e.getFullYear()&&t.getMonth()===e.getMonth()&&t.getDate()===e.getDate(),wS=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"]},mf=(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:wS(t),onceDate:typeof t.schedule.date=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.date)?t.schedule.date:rf(),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:rf(),onceTime:"09:00",weekdays:[1],timezone:n,cronExpression:""},execution:{prompt:"",providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent}}},vS=(t,e)=>{if(!t.name.trim())return e("sessions.scheduledTasks.editor.validation.taskNameRequired");if(!t.execution.prompt.trim())return e("sessions.scheduledTasks.editor.validation.promptRequired");if(!t.execution.providerID.trim()||!t.execution.modelID.trim())return e("sessions.scheduledTasks.editor.validation.modelRequired");if(t.schedule.kind==="once"){if(!/^\d{4}-\d{2}-\d{2}$/.test(t.schedule.onceDate))return e("sessions.scheduledTasks.editor.validation.dateFormat");if(!/^([01]\d|2[0-3]):([0-5]\d)$/.test(t.schedule.onceTime))return e("sessions.scheduledTasks.editor.validation.timeFormat")}else if(t.schedule.kind==="cron"){if(!t.schedule.cronExpression.trim())return e("sessions.scheduledTasks.editor.validation.cronRequired");if(!bh(t.schedule.cronExpression).valid)return e("sessions.scheduledTasks.editor.validation.cronInvalid")}else if(t.schedule.times.filter(r=>/^([01]\d|2[0-3]):([0-5]\d)$/.test(r)).length===0)return e("sessions.scheduledTasks.editor.validation.atLeastOneTime");return t.schedule.kind==="weekly"&&t.schedule.weekdays.length===0?e("sessions.scheduledTasks.editor.validation.atLeastOneWeekday"):t.schedule.timezone.trim()?null:e("sessions.scheduledTasks.editor.validation.timezoneRequired")},jS=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))},SS=t=>{const e=ft.c(64),{draft:n,setDraft:r,locale:o,t:a}=t,c=n.schedule.cronExpression;let l;e[0]!==c?(l=c.trim()?bh(c):null,e[0]=c,e[1]=l):l=e[1];const d=l;let f;e:{if(!d?.valid||!c.trim()){let M;e[2]===Symbol.for("react.memo_cache_sentinel")?(M=[],e[2]=M):M=e[2],f=M;break e}let $;e[3]!==c||e[4]!==n.schedule.timezone?($=cS(c,n.schedule.timezone),e[3]=c,e[4]=n.schedule.timezone,e[5]=$):$=e[5],f=$}const m=f;let u;e[6]!==n.schedule.timezone||e[7]!==o?(u=$=>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]=u):u=e[8];const p=u;let y;e[9]!==a?(y=a("sessions.scheduledTasks.editor.cronExpression.label"),e[9]=a,e[10]=y):y=e[10];let g;e[11]!==y?(g=s.jsx(Yn,{htmlFor:"sched-cron",required:!0,children:y}),e[11]=y,e[12]=g):g=e[12];let b;e[13]!==r?(b=$=>r(M=>({...M,schedule:{...M.schedule,cronExpression:$.target.value}})),e[13]=r,e[14]=b):b=e[14];let x;e[15]!==a?(x=a("sessions.scheduledTasks.editor.cronExpression.placeholder"),e[15]=a,e[16]=x):x=e[16];let h;e[17]!==c||e[18]!==b||e[19]!==x?(h=s.jsx(vn,{id:"sched-cron",value:c,onChange:b,placeholder:x,className:"w-full max-w-xs font-mono"}),e[17]=c,e[18]=b,e[19]=x,e[20]=h):h=e[20];let C;e[21]!==c||e[22]!==d||e[23]!==a?(C=d&&!d.valid&&c.trim()?s.jsx("span",{className:"typography-micro text-destructive",children:a("sessions.scheduledTasks.editor.validation.cronInvalid")}):null,e[21]=c,e[22]=d,e[23]=a,e[24]=C):C=e[24];let w;e[25]!==g||e[26]!==h||e[27]!==C?(w=s.jsxs("div",{className:"flex flex-col gap-1",children:[g,h,C]}),e[25]=g,e[26]=h,e[27]=C,e[28]=w):w=e[28];let v;e[29]!==p||e[30]!==m||e[31]!==a?(v=m.length>0?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:a("sessions.scheduledTasks.editor.cronExpression.nextRuns")}),s.jsx("span",{className:"typography-micro text-foreground",children:m.map(p).join(", ")})]}):null,e[29]=p,e[30]=m,e[31]=a,e[32]=v):v=e[32];let S;e[33]!==a?(S=a("sessions.scheduledTasks.editor.cronExpression.examples"),e[33]=a,e[34]=S):S=e[34];let k;e[35]!==S?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:S}),e[35]=S,e[36]=k):k=e[36];let j;e[37]!==r||e[38]!==a?(j=dS.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(M=>({...M,schedule:{...M.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]=j):j=e[39];let A;e[40]!==j?(A=s.jsx("div",{className:"flex flex-wrap gap-1.5",children:j}),e[40]=j,e[41]=A):A=e[41];let D;e[42]!==k||e[43]!==A?(D=s.jsxs("div",{className:"flex flex-col gap-1",children:[k,A]}),e[42]=k,e[43]=A,e[44]=D):D=e[44];let N;e[45]!==a?(N=a("sessions.scheduledTasks.editor.timezone.label"),e[45]=a,e[46]=N):N=e[46];let B;e[47]!==N?(B=s.jsx(Yn,{children:N}),e[47]=N,e[48]=B):B=e[48];let T;e[49]!==r?(T=$=>{r(M=>({...M,schedule:{...M.schedule,timezone:$}}))},e[49]=r,e[50]=T):T=e[50];let E;e[51]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(An,{})}),e[51]=E):E=e[51];let _;e[52]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx(Gn,{children:ac.map(DS)}),e[52]=_):_=e[52];let R;e[53]!==n.schedule.timezone||e[54]!==T?(R=s.jsxs(Un,{value:n.schedule.timezone,onValueChange:T,children:[E,_]}),e[53]=n.schedule.timezone,e[54]=T,e[55]=R):R=e[55];let z;e[56]!==B||e[57]!==R?(z=s.jsxs("div",{className:"flex flex-col gap-1",children:[B,R]}),e[56]=B,e[57]=R,e[58]=z):z=e[58];let V;return e[59]!==w||e[60]!==v||e[61]!==D||e[62]!==z?(V=s.jsxs("div",{className:"flex flex-col gap-3",children:[w,v,D,z]}),e[59]=w,e[60]=v,e[61]=D,e[62]=z,e[63]=V):V=e[63],V};function NS(t){const{open:e,task:n,onOpenChange:r,onSave:o}=t,{t:a,locale:c}=Nt(),l=ss(J=>J.loadProviders),d=ss(J=>J.loadAgents),f=ss(J=>J.providers),m=ss(J=>J.currentProviderId),u=ss(J=>J.currentModelId),p=ss(J=>J.currentVariant||""),y=ss(J=>J.currentAgentName||""),g=Ee(J=>J.timeFormatPreference),b=Ee(J=>J.weekStartPreference),x=Ee(J=>J.isMobile),[h,C]=tt.useState(()=>mf(n,{providerID:m,modelID:u,variant:p,agent:y})),[w,v]=tt.useState(!1),[S,k]=tt.useState(!1),[j,A]=tt.useState(!1),[D,N]=tt.useState(""),[B,T]=tt.useState(!1),[E,_]=tt.useState(""),[R,z]=tt.useState(!1),[V,$]=tt.useState(""),[M,te]=tt.useState(()=>{const J=pa(n?.schedule?.date||"")||new Date;return new Date(J.getFullYear(),J.getMonth(),1)}),re=tt.useRef(null),Q=tt.useRef(null),H=tt.useRef(null),X=tt.useRef(null),oe=tt.useRef(null),fe=tt.useMemo(()=>gS(c),[c]),ve=tt.useMemo(()=>pS(c),[c]),ie=tt.useMemo(()=>g==="24h"?!0:g==="12h"?!1:fe,[g,fe]),Ne=tt.useMemo(()=>b==="sunday"?0:b==="monday"?1:ve,[b,ve]),K=tt.useMemo(()=>{const J=xS(c);return bS(yh.map(O=>({value:O,label:J[O]||""})),Ne)},[c,Ne]);tt.useEffect(()=>{e&&(l({source:"scheduledTaskEditor"}),d({source:"scheduledTaskEditor"}))},[e,l,d]),tt.useEffect(()=>{if(!e)return;C(mf(n,{providerID:m,modelID:u,variant:p,agent:y}));const J=pa(n?.schedule?.date||"")||new Date;te(new Date(J.getFullYear(),J.getMonth(),1)),k(!1),T(!1),A(!1),_(""),N("")},[e,n,m,u,p,y]),tt.useEffect(()=>{if(!S)return;const J=O=>{re.current&&!re.current.contains(O.target)&&k(!1)};return document.addEventListener("mousedown",J),()=>{document.removeEventListener("mousedown",J)}},[S]);const pe=tt.useMemo(()=>{const O=f.find(ae=>ae.id===h.execution.providerID)?.models?.find(ae=>ae.id===h.execution.modelID);return O?.variants?Object.keys(O.variants):[]},[f,h.execution.providerID,h.execution.modelID]),L=pe.length>0,se=tt.useMemo(()=>!L||!h.execution.variant?"__default":pe.includes(h.execution.variant)?h.execution.variant:"__default",[h.execution.variant,L,pe]);tt.useEffect(()=>{L||!h.execution.variant||C(J=>({...J,execution:{...J.execution,variant:""}}))},[L,h.execution.variant]);const Z=tt.useCallback((J,O)=>{C(ae=>{const ne=new Set(ae.schedule.weekdays);return O?ne.add(J):ne.delete(J),{...ae,schedule:{...ae.schedule,weekdays:Array.from(ne).sort((Be,Ye)=>Be-Ye)}}})},[]),je=tt.useCallback((J,O)=>{C(ae=>{const ne=ae.schedule.times.slice();return ne[J]=O,{...ae,schedule:{...ae.schedule,times:ne}}})},[]),De=tt.useCallback(J=>{C(O=>{const ae=O.schedule.times.filter((ne,Be)=>Be!==J);return{...O,schedule:{...O.schedule,times:ae.length>0?ae:["09:00"]}}})},[]),Le=tt.useCallback(()=>{C(J=>({...J,schedule:{...J.schedule,times:[...J.schedule.times,"12:00"]}}))},[]),Me=tt.useMemo(()=>yS(),[]),Fe=tt.useMemo(()=>uf(Me),[Me]),he=tt.useMemo(()=>{const J=pa(h.schedule.onceDate);return J?ff(J,Me)?a("sessions.scheduledTasks.editor.date.today"):new Intl.DateTimeFormat(c,{weekday:"short"}).format(J):null},[h.schedule.onceDate,c,a,Me]),Ie=tt.useMemo(()=>uf(M).getTime()<=Fe.getTime(),[M,Fe]),me=tt.useMemo(()=>K.map(J=>J.label),[K]),ce=tt.useCallback(J=>{C(O=>({...O,schedule:{...O.schedule,onceDate:J}}))},[]),xe=tt.useCallback((J,O)=>{if(J.startsWith("/")){const Ye=J.indexOf(" "),He=J.indexOf(`
|
|
168
|
-
`),Je=Math.min(Ye===-1?J.length:Ye,He===-1?J.length:He);if(O<=Je&&Ye===-1){_(J.substring(1,Je)),T(!0),A(!1),z(!1);return}}T(!1);const ae=J.substring(0,O),ne=ae.lastIndexOf("#");if(ne!==-1){const Ye=ne>0?ae[ne-1]:null,He=ae.substring(ne+1);if((!Ye||/\s/.test(Ye))&&!He.includes(" ")&&!He.includes(`
|
|
169
|
-
`)){$(He),z(!0),A(!1);return}}z(!1);const Be=ae.lastIndexOf("@");if(Be!==-1){const Ye=Be>0?ae[Be-1]:null,He=ae.substring(Be+1);(!Ye||/\s/.test(Ye))&&!He.includes(" ")&&!He.includes(`
|
|
170
|
-
`)?(N(He),A(!0)):A(!1);return}A(!1)},[]),ke=tt.useCallback(J=>{C(O=>({...O,execution:{...O.execution,prompt:J}}))},[]),de=tt.useCallback(J=>{const O=h.execution.prompt,ne=Q.current?.selectionStart??O.length,Ye=O.substring(0,ne).lastIndexOf("@"),He=J.relativePath&&J.relativePath.trim().length>0?J.relativePath.trim():J.path||J.name,Je=Ye!==-1?Ye:ne,nt=`${O.substring(0,Je)}@${He} ${O.substring(ne)}`,xt=Je+He.length+2;ke(nt),A(!1),N(""),requestAnimationFrame(()=>{const bt=Q.current;bt&&(bt.selectionStart=xt,bt.selectionEnd=xt,bt.focus()),xe(nt,xt)})},[h.execution.prompt,ke,xe]),P=tt.useCallback(J=>{const O=h.execution.prompt,ne=Q.current?.selectionStart??O.length,Ye=O.substring(0,ne).lastIndexOf("@"),He=Ye!==-1?Ye:ne,Je=`${O.substring(0,He)}@${J} ${O.substring(ne)}`,nt=He+J.length+2;ke(Je),A(!1),N(""),requestAnimationFrame(()=>{const xt=Q.current;xt&&(xt.selectionStart=nt,xt.selectionEnd=nt,xt.focus()),xe(Je,nt)})},[h.execution.prompt,ke,xe]),F=tt.useCallback(J=>{const O=`/${J.name} `;ke(O),T(!1),_(""),z(!1),requestAnimationFrame(()=>{const ae=Q.current;ae&&(ae.focus(),ae.selectionStart=ae.value.length,ae.selectionEnd=ae.value.length),xe(O,O.length)})},[ke,xe]),ue=tt.useCallback((J,O)=>{const ae=h.execution.prompt,Be=Q.current?.selectionStart??ae.length,He=ae.substring(0,Be).lastIndexOf("#"),Je=He!==-1?He:Be,nt=`${ae.substring(0,Je)}#${O} ${ae.substring(Be)}`,xt=Je+O.length+2;ke(nt),z(!1),$(""),requestAnimationFrame(()=>{const bt=Q.current;bt&&(bt.selectionStart=xt,bt.selectionEnd=xt,bt.focus()),xe(nt,xt)})},[h.execution.prompt,ke,xe]),be=tt.useCallback(J=>{if(B&&X.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")){J.preventDefault(),X.current.handleKeyDown(J.key);return}j&&H.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")&&(J.preventDefault(),H.current.handleKeyDown(J.key)),R&&oe.current&&(J.key==="Enter"||J.key==="ArrowUp"||J.key==="ArrowDown"||J.key==="Escape"||J.key==="Tab")&&(J.preventDefault(),oe.current.handleKeyDown(J.key))},[B,j,R]),W=tt.useCallback(async()=>{const J=vS(h,a);if(J){le.error(J);return}const O={...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:jS(h.schedule.times),...h.schedule.kind==="weekly"?{weekdays:h.schedule.weekdays}:{}}},execution:{prompt:h.execution.prompt,providerID:h.execution.providerID,modelID:h.execution.modelID,...h.execution.variant.trim()?{variant:h.execution.variant.trim()}:{},...h.execution.agent.trim()?{agent:h.execution.agent.trim()}:{}},...h.state?{state:h.state}:{}};v(!0);try{await o(O),r(!1)}catch(ae){le.error(ae instanceof Error?ae.message:a("sessions.scheduledTasks.editor.toast.saveFailed"))}finally{v(!1)}},[h,r,o,a]),ge=tt.useId(),we=tt.useCallback(()=>typeof document>"u"?!1:!!document.querySelector('[data-slot="dropdown-menu-content"], [data-slot="select-content"]'),[]),G=a(n?"sessions.scheduledTasks.editor.title.edit":"sessions.scheduledTasks.editor.title.new"),Se=a("sessions.scheduledTasks.editor.description"),Oe=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:J=>C(O=>({...O,name:J.target.value})),placeholder:a("sessions.scheduledTasks.editor.taskName.placeholder"),maxLength:80,className:"w-full sm:max-w-[220px]"})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.scheduleType.label")}),s.jsxs(Un,{value:h.schedule.kind,onValueChange:J=>{C(O=>({...O,schedule:{...O.schedule,kind:J,...J==="cron"&&!O.schedule.cronExpression?{cronExpression:"0 * * * *"}:{}}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(An,{children:J=>a(J==="daily"?"sessions.scheduledTasks.editor.scheduleType.daily":J==="weekly"?"sessions.scheduledTasks.editor.scheduleType.weekly":J==="cron"?"sessions.scheduledTasks.editor.scheduleType.cron":"sessions.scheduledTasks.editor.scheduleType.once")})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"daily",children:a("sessions.scheduledTasks.editor.scheduleType.daily")}),s.jsx(Rs,{value:"weekly",children:a("sessions.scheduledTasks.editor.scheduleType.weekly")}),s.jsx(Rs,{value:"once",children:a("sessions.scheduledTasks.editor.scheduleType.once")}),s.jsx(Rs,{value:"cron",children:a("sessions.scheduledTasks.editor.scheduleType.cron")})]})]})]})]}),h.schedule.kind==="cron"?s.jsx(SS,{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:re,children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.date.label")}),s.jsxs("div",{className:"relative",children:[s.jsxs("button",{type:"button",className:"inline-flex h-9 w-fit max-w-full items-center justify-between gap-2 rounded-md border border-border bg-background px-3 text-left hover:bg-interactive-hover",onClick:()=>k(J=>!J),children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(I,{name:"calendar",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:uS(h.schedule.onceDate,a("sessions.scheduledTasks.editor.date.placeholder"),c)})]}),s.jsx(I,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"})]}),S?s.jsxs("div",{className:"absolute left-0 top-[calc(100%+6px)] z-50 w-[288px] rounded-xl border border-border bg-background p-3 shadow-sm",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover disabled:cursor-not-allowed disabled:opacity-40",onClick:()=>te(J=>af(J,-1)),"aria-label":a("sessions.scheduledTasks.editor.date.previousMonth"),disabled:Ie,children:s.jsx(I,{name:"arrow-left-s",className:"h-4 w-4"})}),s.jsx("div",{className:"typography-ui-label text-foreground",children:new Intl.DateTimeFormat(c,{month:"long",year:"numeric"}).format(M)}),s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-interactive-hover",onClick:()=>te(J=>af(J,1)),"aria-label":a("sessions.scheduledTasks.editor.date.nextMonth"),children:s.jsx(I,{name:"arrow-right-s",className:"h-4 w-4"})})]}),s.jsx("div",{className:"mb-1 grid grid-cols-7 gap-1 px-1",children:me.map((J,O)=>s.jsx("div",{className:"py-1 text-center typography-micro text-muted-foreground",children:J},`${J}-${O}`))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:fS(M,Ne).map(({date:J,inCurrentMonth:O})=>{const ae=of(J),ne=ae===h.schedule.onceDate,Be=ff(J,Me),Ye=J.getTime()<Me.getTime(),He=ne?"bg-interactive-selection text-interactive-selection-foreground":Ye?"text-muted-foreground/40":O?"text-foreground hover:bg-interactive-hover":"text-muted-foreground/60 hover:bg-interactive-hover";return s.jsx("button",{type:"button",onClick:()=>{Ye||(ce(ae),k(!1))},disabled:Ye,className:["h-8 rounded-md typography-ui-label",He,Be&&!ne?"ring-1 ring-inset ring-interactive-focusRing bg-interactive-hover/50":"",Ye?"cursor-not-allowed opacity-45":""].join(" "),children:J.getDate()},ae)})}),s.jsxs("div",{className:"mt-2 flex items-center justify-between border-t border-border pt-2",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:he||""}),s.jsx(Ve,{type:"button",size:"xs",variant:"ghost",onClick:()=>{ce(of(Me)),te(new Date(Me.getFullYear(),Me.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(df,{value:h.schedule.onceTime,use24Hour:ie,hourAriaLabel:a("sessions.scheduledTasks.editor.time.hourAria"),minuteAriaLabel:a("sessions.scheduledTasks.editor.time.minuteAria"),periodAriaLabel:a("sessions.scheduledTasks.editor.time.periodAria"),amLabel:a("sessions.scheduledTasks.editor.time.period.am"),pmLabel:a("sessions.scheduledTasks.editor.time.period.pm"),onChange:J=>C(O=>({...O,schedule:{...O.schedule,onceTime:J}}))}),s.jsxs("div",{className:"mt-2 flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Un,{value:h.schedule.timezone,onValueChange:J=>{C(O=>({...O,schedule:{...O.schedule,timezone:J}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(An,{})}),s.jsx(Gn,{children:ac.map(J=>s.jsx(Rs,{value:J,children:J},J))})]})]})]})]}):s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[h.schedule.kind==="weekly"?s.jsxs("div",{className:"flex flex-col gap-1 sm:col-span-2",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.weekdays.label")}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-2",children:K.map(J=>{const O=h.schedule.weekdays.includes(J.value);return s.jsxs("div",{className:["group inline-flex items-center gap-1.5 px-0.5 py-0.5 typography-meta",O?"text-foreground":"text-muted-foreground"].join(" "),children:[s.jsx(Fi,{checked:O,onChange:ae=>Z(J.value,ae),ariaLabel:J.label}),s.jsx("button",{type:"button",onClick:()=>Z(J.value,!O),className:"group-hover:text-foreground",children:J.label})]},J.value)})})]}):null,s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.times.label")}),s.jsx("div",{className:"flex flex-col gap-2",children:h.schedule.times.map((J,O)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(df,{value:J,use24Hour:ie,hourAriaLabel:a("sessions.scheduledTasks.editor.time.hourAria"),minuteAriaLabel:a("sessions.scheduledTasks.editor.time.minuteAria"),periodAriaLabel:a("sessions.scheduledTasks.editor.time.periodAria"),amLabel:a("sessions.scheduledTasks.editor.time.period.am"),pmLabel:a("sessions.scheduledTasks.editor.time.period.pm"),onChange:ae=>je(O,ae)}),h.schedule.times.length>1?s.jsx(Ve,{type:"button",size:"icon",variant:"ghost",onClick:()=>De(O),"aria-label":a("sessions.scheduledTasks.editor.times.removeAria"),children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null]},O))}),s.jsx("div",{children:s.jsxs(Ve,{type:"button",size:"sm",variant:"outline",onClick:Le,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",a("sessions.scheduledTasks.editor.times.add")]})})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.timezone.label")}),s.jsxs(Un,{value:h.schedule.timezone,onValueChange:J=>{C(O=>({...O,schedule:{...O.schedule,timezone:J}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(An,{})}),s.jsx(Gn,{children:ac.map(J=>s.jsx(Rs,{value:J,children:J},J))})]})]})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{required:!0,children:a("sessions.scheduledTasks.editor.model.label")}),s.jsx(Zf,{providerId:h.execution.providerID,modelId:h.execution.modelID,onChange:(J,O)=>{C(ae=>({...ae,execution:{...ae.execution,providerID:J,modelID:O,variant:""}}))}})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.thinkingLevel.label")}),s.jsxs(Un,{value:se,disabled:!L,onValueChange:J=>{C(O=>({...O,execution:{...O.execution,variant:J==="__default"?"":J}}))},children:[s.jsx(Hn,{className:"w-fit max-w-full",children:s.jsx(An,{children:J=>J==="__default"?a("sessions.scheduledTasks.editor.thinkingLevel.default"):J})}),s.jsxs(Gn,{children:[s.jsx(Rs,{value:"__default",children:a("sessions.scheduledTasks.editor.thinkingLevel.default")}),pe.map(J=>s.jsx(Rs,{value:J,children:J},J))]})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx(Yn,{children:a("sessions.scheduledTasks.editor.agent.label")}),s.jsx(em,{agentName:h.execution.agent,filter:J=>Sc(J.mode),onChange:J=>C(O=>({...O,execution:{...O.execution,agent:J}}))})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Yn,{htmlFor:"sched-prompt",required:!0,children:a("sessions.scheduledTasks.editor.prompt.label")}),s.jsxs("div",{className:"relative",children:[s.jsx(Ii,{id:"sched-prompt",ref:Q,value:h.execution.prompt,onChange:J=>{const O=J.target.value;ke(O);const ae=J.target.selectionStart??O.length;xe(O,ae)},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"}),B?s.jsx(fm,{ref:X,searchQuery:E,onCommandSelect:F,onClose:()=>T(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,j?s.jsx(mm,{ref:H,searchQuery:D,onFileSelect:de,onAgentSelect:P,onClose:()=>A(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,R?s.jsx(hm,{ref:oe,searchQuery:V,onSnippetSelect:ue,onClose:()=>z(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null]})]})]}),Ae=s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("label",{className:"inline-flex items-center gap-2",children:[s.jsx(Fi,{checked:h.enabled,onChange:J=>C(O=>({...O,enabled:J})),ariaLabel:a("sessions.scheduledTasks.editor.enabled.aria")}),s.jsx("span",{className:"typography-meta",children:a("sessions.scheduledTasks.editor.enabled.label")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(!1),disabled:w,children:a("sessions.scheduledTasks.editor.actions.cancel")}),s.jsx(Ve,{type:"button",size:"sm",onClick:W,disabled:w,children:a(w?"sessions.scheduledTasks.editor.actions.saving":"sessions.scheduledTasks.editor.actions.save")})]})]});return x?s.jsx(Ha,{open:e,title:G,onClose:()=>r(!1),contentMaxHeightClassName:"max-h-[min(80vh,640px)]",renderHeader:J=>s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:G}),J]}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:Se})]}),footer:Ae,children:Oe}):s.jsx(Ms,{open:e,onOpenChange:J=>{!J&&we()||r(J)},children:s.jsxs(Es,{"aria-describedby":ge,className:"!max-w-[720px] w-[90vw] h-[680px] max-h-[85vh] gap-0 p-0 overflow-hidden",children:[s.jsx(an,{id:ge,className:"sr-only",children:Se}),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(Vs,{className:"typography-ui-label font-medium text-foreground",children:G}),s.jsx("p",{className:"typography-meta mt-0.5 text-muted-foreground",children:Se})]})}),s.jsx(Ga,{className:"flex-1 min-h-0 overflow-auto [scrollbar-gutter:stable_both-edges]",size:64,hideTopShadow:!0,children:s.jsx("div",{className:"mx-auto w-full max-w-2xl px-4 sm:px-6 pb-5",children:Oe})}),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:Ae})})]})})}function kS(t){return fo(t,{min:0,max:23})}function CS(t,e){return fo(String(Number.parseInt(t,10)+e),{min:0,max:23,loop:!0})}function AS(t,e){const n=Number(t),r=Number(e),o=Number.isFinite(n)?Math.min(23,Math.max(0,n)):0,a=Number.isFinite(r)?Math.min(59,Math.max(0,r)):0;return`${String(o).padStart(2,"0")}:${String(a).padStart(2,"0")}`}function DS(t){return s.jsx(Rs,{value:t,children:t},t)}const IS=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))},PS=(t,e)=>{const n=IS(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||""})},TS=(t,e)=>!t||!Number.isFinite(t)?"":Hf(t,e),hf=(t,e)=>{if(!t||!Number.isFinite(t))return"";const n=t-Date.now(),r=Math.abs(n),o=6e4,a=60*o,c=24*a,l=n>=0;if(r<o)return e(l?"sessions.scheduledTasks.dialog.relativeTime.inLessThanOneMinute":"sessions.scheduledTasks.dialog.relativeTime.justNow");if(r<a){const u=Math.round(r/o);return l?e("sessions.scheduledTasks.dialog.relativeTime.inMinutes",{count:u}):e("sessions.scheduledTasks.dialog.relativeTime.minutesAgo",{count:u})}if(r<c){const u=Math.floor(r/a),p=Math.round(r%a/o),y=p>0?`${u}h ${p}m`:`${u}h`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:y}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:y})}const d=Math.floor(r/c),f=Math.round(r%c/a),m=f>0?`${d}d ${f}h`:`${d}d`;return l?e("sessions.scheduledTasks.dialog.relativeTime.inDuration",{duration:m}):e("sessions.scheduledTasks.dialog.relativeTime.durationAgo",{duration:m})},RS={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"}},ES=t=>({color:`var(--status-${t})`,backgroundColor:`var(--status-${t}-background)`,borderColor:`var(--status-${t}-border)`});function MS(){const{t}=Nt(),e=Ee(R=>R.isScheduledTasksDialogOpen),n=Ee(R=>R.setScheduledTasksDialogOpen),r=Ee(R=>R.isMobile),o=Ee(R=>R.timeFormatPreference),a=Ss(R=>R.projects),c=Ss(R=>R.getActiveProject()),l=Ys(R=>R.homeDirectory),{currentTheme:d}=Qr(),[f,m]=tt.useState(""),[u,p]=tt.useState([]),[y,g]=tt.useState(!0),[b,x]=tt.useState(!1),[h,C]=tt.useState(null),[w,v]=tt.useState(null),S=tt.useMemo(()=>a.find(R=>R.id===f)||null,[a,f]),k=tt.useCallback(R=>{const z=R.label?.trim()||Oi(R.path,l||void 0),V=R.icon?Rc[R.icon]:null,$=R.color?Qa[R.color]:void 0,M=V?s.jsx(I,{name:V,className:"h-3.5 w-3.5 shrink-0",style:$?{color:$}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:$?{color:$}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[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(Ja,{project:{id:R.id,iconImage:R.iconImage??null},options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:M})}):M,s.jsx("span",{className:"truncate",children:z})]})},[l,d.metadata.variant,d.colors.surface.foreground]),j=tt.useCallback(async(R,z)=>{if(!R){p([]);return}z?.silent||g(!0);try{const V=await oS(R);V.sort(($,M)=>{if($.enabled!==M.enabled)return $.enabled?-1:1;const te=$.name.localeCompare(M.name);return te!==0?te:($.state?.nextRunAt||Number.MAX_SAFE_INTEGER)-(M.state?.nextRunAt||Number.MAX_SAFE_INTEGER)}),p(V)}catch(V){le.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.loadFailed")),z?.silent||p([])}finally{z?.silent||g(!1)}},[t]);tt.useEffect(()=>{if(!e)return;const R=c?.id||a[0]?.id||"";m(R),R?j(R):(p([]),g(!1))},[e,c,a,j]),tt.useEffect(()=>{if(!e)return;let R=null;const z=xh(V=>{V.type==="scheduled-task-ran"&&V.projectId===f&&(R&&clearTimeout(R),R=setTimeout(()=>{j(f,{silent:!0})},400))});return()=>{R&&clearTimeout(R),z()}},[e,f,j]);const A=tt.useCallback(async R=>{if(!f)throw new Error(t("sessions.scheduledTasks.dialog.error.chooseProjectFirst"));await nf(f,R),await j(f),le.success(t("sessions.scheduledTasks.dialog.toast.saved"))},[f,j,t]),D=tt.useCallback(async(R,z)=>{if(f){v(R.id),p(V=>V.map($=>$.id===R.id?{...$,enabled:z}:$));try{await nf(f,{...R,enabled:z}),await j(f,{silent:!0})}catch(V){le.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.updateFailed")),await j(f,{silent:!0})}finally{v(null)}}},[f,j,t]),N=tt.useCallback(async R=>{if(!(!f||!window.confirm(t("sessions.scheduledTasks.dialog.confirm.deleteTask",{taskName:R.name})))){v(R.id);try{await aS(f,R.id),await j(f,{silent:!0}),le.success(t("sessions.scheduledTasks.dialog.toast.deleted"))}catch(V){le.error(V instanceof Error?V.message:t("sessions.scheduledTasks.dialog.toast.deleteFailed"))}finally{v(null)}}},[f,j,t]),B=tt.useCallback(async R=>{if(f){v(R.id);try{await lS(f,R.id),await Promise.all([j(f,{silent:!0}),ka()]),le.success(t("sessions.scheduledTasks.dialog.toast.started"))}catch(z){le.error(z instanceof Error?z.message:t("sessions.scheduledTasks.dialog.toast.runFailed"))}finally{v(null)}}},[f,j,t]),T=s.jsxs("div",{className:"flex flex-col items-start gap-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("sessions.scheduledTasks.dialog.project.label")}),s.jsxs(Un,{value:f||"__none",onValueChange:R=>{const z=R==="__none"?"":R;m(z),z?j(z):p([])},children:[s.jsx(Hn,{className:r?"w-full":void 0,children:S?s.jsx(An,{children:k(S)}):s.jsx(An,{placeholder:t("sessions.scheduledTasks.dialog.project.placeholder")})}),s.jsxs(Gn,{children:[a.length===0?s.jsx(Rs,{value:"__none",children:t("sessions.scheduledTasks.dialog.project.empty")}):null,a.map(R=>s.jsx(Rs,{value:R.id,children:k(R)},R.id))]})]})]}),E=()=>{C(null),x(!0)},_=s.jsxs("div",{className:"space-y-4",children:[r?T:s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[T,s.jsxs(Ve,{onClick:E,disabled:!f,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]})]}),s.jsx("div",{className:"min-h-[280px]",children:y?s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(I,{name:"loader-4",className:"h-4 w-4 animate-spin"})," ",t("sessions.scheduledTasks.dialog.loading")]}):u.length===0?s.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 typography-meta text-muted-foreground",children:t(f?"sessions.scheduledTasks.dialog.empty.noTasks":"sessions.scheduledTasks.dialog.empty.selectProject")}):s.jsx("div",{className:"space-y-2.5",children:u.map(R=>{const z=w===R.id,V=R.state?.lastStatus||"idle",$=RS[V],M=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"),te=R.state?.nextRunAt,re=R.state?.lastRunAt;return s.jsxs("div",{className:Te("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:PS(R,t)})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-x-5 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(I,{name:"timer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.nextRun.label")}),te?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-foreground",children:hf(te,t)}),s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:TS(te,o)})]}):s.jsx("span",{children:"—"})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(I,{name:"history",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-medium text-foreground",children:t("sessions.scheduledTasks.dialog.lastRun.label")}),V==="running"?s.jsxs("span",{className:"inline-flex items-center gap-1",style:{color:"var(--status-warning)"},children:[s.jsx(I,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),t("sessions.scheduledTasks.dialog.lastRun.runningNow")]}):re?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(I,{name:$.Icon,className:"h-3.5 w-3.5"}),M]}):null,s.jsx("span",{className:"text-muted-foreground/50",children:"·"}),s.jsx("span",{children:hf(re,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:ES("error"),children:[s.jsx(I,{name:"error-warning",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"min-w-0 break-words",children:R.state.lastError})]}):null,s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("label",{className:Te("inline-flex cursor-pointer items-center gap-2 typography-micro font-medium",R.enabled?"text-foreground":"text-muted-foreground",z&&"cursor-not-allowed opacity-50"),children:[s.jsx(Fi,{checked:R.enabled,onChange:Q=>{D(R,Q)},ariaLabel:R.enabled?t("sessions.scheduledTasks.dialog.taskToggle.pauseAria",{taskName:R.name}):t("sessions.scheduledTasks.dialog.taskToggle.enableAria",{taskName:R.name}),disabled:z}),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(Ve,{variant:"outline",size:"sm",onClick:()=>{B(R)},disabled:z,children:[s.jsx(I,{name:"play",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.runNow")]}),s.jsxs(Ve,{variant:"outline",size:"sm",onClick:()=>{C(R),x(!0)},disabled:z,"aria-label":t("sessions.scheduledTasks.dialog.actions.editAria",{taskName:R.name}),children:[s.jsx(I,{name:"edit-2",className:"h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.edit")]}),s.jsx(Ve,{variant:"destructive",size:"sm",onClick:()=>{N(R)},disabled:z,"aria-label":t("sessions.scheduledTasks.dialog.actions.deleteAria",{taskName:R.name}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})]})]})]},R.id)})})})]});return s.jsxs(s.Fragment,{children:[r?s.jsx(Ha,{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(Ve,{className:"w-full",onClick:E,disabled:!f,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"})," ",t("sessions.scheduledTasks.dialog.actions.newTask")]}),children:_}):s.jsx(Ms,{open:e,onOpenChange:n,children:s.jsxs(Es,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[s.jsxs(Gs,{children:[s.jsx(Vs,{children:t("sessions.scheduledTasks.dialog.title")}),s.jsx(an,{children:t("sessions.scheduledTasks.dialog.description")})]}),_]})}),s.jsx(NS,{open:b,task:h,onOpenChange:x,onSave:A})]})}const FS=(t,e)=>{const n=e.isVSCode?[]:e.availableWorktreesByProject.get(t.normalizedPath)??[],r=new Set([t.normalizedPath,...n.map(l=>as(l.path)??l.path).filter(l=>!!l)]),a=(l=>l.filter(d=>Eo(d,t.normalizedPath,r)))(e.archivedSessions),c=e.sessions.filter(l=>l.time?.archived||as(l.directory??null)?!1:Eo(l,t.normalizedPath,r));return io([...a,...c])},OS=t=>{const e=ft.c(12),{normalizedProjects:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c,isSessionsLoading:l,foldersMap:d,createFolder:f,addSessionToFolder:m,cleanupSessions:u}=t;let p,y;e[0]!==m||e[1]!==o||e[2]!==a||e[3]!==u||e[4]!==f||e[5]!==d||e[6]!==l||e[7]!==c||e[8]!==n||e[9]!==r?(p=()=>{l||n.forEach(g=>{const b=Bc(g.normalizedPath),x=FS(g,{sessions:r,archivedSessions:o,availableWorktreesByProject:a,isVSCode:c}),h=new Set(x.map(LS)),C=d[b]??[],w=new Map(C.map(BS));x.forEach(v=>{const S=mb(v,g.normalizedPath),k=S.toLowerCase();let j=w.get(k);j||(j=f(b,S),w.set(k,j)),j.sessionIds.includes(v.id)||m(b,j.id,v.id)}),u(b,h)})},y=[n,r,o,a,c,l,d,f,m,u],e[0]=m,e[1]=o,e[2]=a,e[3]=u,e[4]=f,e[5]=d,e[6]=l,e[7]=c,e[8]=n,e[9]=r,e[10]=p,e[11]=y):(p=e[10],y=e[11]),i.useEffect(p,y)};function LS(t){return t.id}function BS(t){return[t.name.toLowerCase(),t]}const _S=t=>{const e=ft.c(41),{normalizedProjects:n,getSessionsForProject:r,getArchivedSessionsForProject:o,availableWorktreesByProject:a,projectRepoStatus:c,projectRootBranches:l,lastRepoStatus:d,buildGroupedSessions:f,hasSessionSearchQuery:m,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:p,buildGroupSearchText:y,foldersMap:g}=t;let b;if(e[0]!==a||e[1]!==f||e[2]!==o||e[3]!==r||e[4]!==d||e[5]!==n||e[6]!==c||e[7]!==l){let N;e[9]!==a||e[10]!==f||e[11]!==o||e[12]!==r||e[13]!==d||e[14]!==c||e[15]!==l?(N=B=>{const T=io([...r(B),...o(B)]),E=a.get(B.normalizedPath)??[],_=c.has(B.id)?!!c.get(B.id):d,R=f(T,B.normalizedPath,E,l.get(B.id)??null,_);return{project:B,groups:R}},e[9]=a,e[10]=f,e[11]=o,e[12]=r,e[13]=d,e[14]=c,e[15]=l,e[16]=N):N=e[16],b=n.map(N),e[0]=a,e[1]=f,e[2]=o,e[3]=r,e[4]=d,e[5]=n,e[6]=c,e[7]=l,e[8]=b}else b=e[8];const x=b,h=x;let C;if(e[17]!==y||e[18]!==p||e[19]!==g||e[20]!==m||e[21]!==u||e[22]!==h){e:{const N=new WeakMap;if(!m){C=N;break e}const B=T=>T.reduce((E,_)=>E+1+B(_.children),0);h.forEach(T=>{T.groups.forEach(E=>{const _=p(E.sessions,u),R=B(_),z=y(E).includes(u),V=as(E.directory??null),M=(V?g[V]??[]:[]).filter(te=>te.name.toLowerCase().includes(u)).length;N.set(E,{filteredNodes:_,matchedSessionCount:R,folderNameMatchCount:M,groupMatches:z,hasMatch:z||R>0||M>0})})}),C=N}e[17]=y,e[18]=p,e[19]=g,e[20]=m,e[21]=u,e[22]=h,e[23]=C}else C=e[23];const w=C;let v;e:{if(!m){v=h;break e}let N;if(e[24]!==w||e[25]!==h){let B;e[27]!==w?(B=T=>({...T,groups:T.groups.filter(E=>w.get(E)?.hasMatch===!0)}),e[27]=w,e[28]=B):B=e[28],N=h.map(B).filter(VS),e[24]=w,e[25]=h,e[26]=N}else N=e[26];v=N}const S=v,k=m?S:h;let j;e:{if(!m){j=0;break e}let N;if(e[29]!==w||e[30]!==k){let B;e[32]!==w?(B=(T,E)=>T+E.groups.reduce((_,R)=>{const z=w.get(R);if(!z)return _;const V=z.folderNameMatchCount+(z.groupMatches?1:0);return _+z.matchedSessionCount+V},0),e[32]=w,e[33]=B):B=e[33],N=k.reduce(B,0),e[29]=w,e[30]=k,e[31]=N}else N=e[31];j=N}const A=j;let D;return e[34]!==w||e[35]!==x||e[36]!==A||e[37]!==S||e[38]!==k||e[39]!==h?(D={projectSections:x,visibleProjectSections:h,groupSearchDataByGroup:w,searchableProjectSections:S,sectionsForRender:k,searchMatchCount:A},e[34]=w,e[35]=x,e[36]=A,e[37]=S,e[38]=k,e[39]=h,e[40]=D):D=e[40],D};function VS(t){return t.groups.length>0}const $S=t=>{const e=ft.c(26),{projectSections:n,activeProjectId:r,activeSessionByProject:o,setActiveSessionByProject:a,currentSessionId:c,handleSessionSelect:l,newSessionDraftOpen:d,mobileVariant:f,openNewSessionDraft:m,setActiveMainTab:u,setSessionSwitcherOpen:p}=t;let y,g;if(e[0]!==n){g=new Map,y=new Map;const k=(j,A,D,N)=>{g.has(j)||g.set(j,new Map);const B=g.get(j);N.forEach(T=>{const E=as(T.worktree?.path??T.session.directory??D??A);B.set(T.session.id,{directory:E}),y.has(j)||y.set(j,{id:T.session.id,directory:E}),T.children.length>0&&k(j,A,E,T.children)})};n.forEach(j=>{j.groups.forEach(A=>{k(j.project.id,j.project.normalizedPath,A.directory,A.sessions)})}),e[0]=n,e[1]=y,e[2]=g}else y=e[1],g=e[2];let b;e[3]!==y||e[4]!==g?(b={metaByProject:g,firstSessionByProject:y},e[3]=y,e[4]=g,e[5]=b):b=e[5];const x=b,h=i.useRef(null);let C,w;e[6]!==r||e[7]!==o||e[8]!==c||e[9]!==l||e[10]!==f||e[11]!==d||e[12]!==m||e[13]!==n||e[14]!==x||e[15]!==u||e[16]!==a||e[17]!==p?(C=()=>{if(!r||d||Ee.getState().isNewWorktreeDialogOpen||h.current===r)return;const k=n.find(E=>E.project.id===r);if(!k)return;h.current=r;const j=x.metaByProject.get(r);if(c&&j&&j.has(c)){a(E=>{if(E.get(r)===c)return E;const _=new Map(E);return _.set(r,c),_});return}if(c&&j)return;if(!j||j.size===0){u("chat"),f&&p(!1),m({directoryOverride:k.project.normalizedPath});return}const A=o.get(r),D=A&&j.has(A)?A:null,N=x.firstSessionByProject.get(r)?.id??null,B=D??N;if(!B||B===c)return;const T=j.get(B)?.directory??null;l(B,T,r)},w=[r,o,c,l,d,f,m,n,x,u,p,a],e[6]=r,e[7]=o,e[8]=c,e[9]=l,e[10]=f,e[11]=d,e[12]=m,e[13]=n,e[14]=x,e[15]=u,e[16]=a,e[17]=p,e[18]=C,e[19]=w):(C=e[18],w=e[19]),i.useLayoutEffect(C,w);let v,S;e[20]!==r||e[21]!==c||e[22]!==x||e[23]!==a?(v=()=>{if(!r||!c)return;const k=x.metaByProject.get(r);!k||!k.has(c)||a(j=>{if(j.get(r)===c)return j;const A=new Map(j);return A.set(r,c),A})},S=[r,c,x,a],e[20]=r,e[21]=c,e[22]=x,e[23]=a,e[24]=v,e[25]=S):(v=e[24],S=e[25]),i.useEffect(v,S)},zS=t=>{const e=ft.c(4);let n;e[0]!==t?(n=(a,c)=>{const l=t.get(a);if(!l||l.length===0)return c;const d=new Map(c.map(WS)),f=[];return l.forEach(m=>{const u=d.get(m);u&&(f.push(u),d.delete(m))}),c.forEach(m=>{d.has(m.id)&&f.push(m)}),f},e[0]=t,e[1]=n):n=e[1];const r=n;let o;return e[2]!==r?(o={getOrderedGroups:r},e[2]=r,e[3]=o):o=e[3],o};function WS(t){return[t.id,t]}const ta=t=>!!t.time?.archived,US=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=as(c.directory??null)??"";return`${(c.title||e("sessions.sidebar.session.untitled")).trim()} ${l}`.toLowerCase()},[e]),o=i.useCallback((c,l)=>l?c.flatMap(d=>{if(r(d.session).includes(l))return[d];const m=o(d.children,l);return m.length===0?[]:[{...d,children:m}]}):c,[r]),a=i.useCallback((c,l,d,f,m)=>{const u=as(l??null),p=io(c).sort((T,E)=>Yi(T,E,t.pinnedSessionIds)),y=new Map(p.map(T=>[T.id,T])),g=new Map;p.forEach(T=>{const E=T.parentID;if(!E)return;const _=y.get(E);if(!_||ta(_)!==ta(T))return;const R=g.get(E)??[];R.push(T),g.set(E,R)}),g.forEach(T=>T.sort((E,_)=>Yi(E,_,t.pinnedSessionIds)));const b=new Map;d.forEach(T=>{if(T.path){const E=as(T.path)??T.path;b.set(E,T)}});const x=T=>{const E=as(T.directory??null),_=t.worktreeMetadata.get(T.id)??null;if(_)return _;if(E){const R=b.get(E)??null;if(R&&E!==u)return R}return null},h=T=>{const E=g.get(T.id)??[];return{session:T,children:E.map(_=>h(_)),worktree:x(T)}},C=p.filter(T=>{const E=T.parentID;if(!E)return!0;const _=y.get(E);return _?ta(_)!==ta(T):!0}),w=new Map,v="__archived__",S=T=>{if(T.time?.archived)return v;if(t.isVSCode)return u??"__project_root__";const _=as(t.worktreeMetadata.get(T.id)?.path??null)??Mr(T);return _?_!==u&&b.has(_)?_:_===u?u??"__project_root__":v:v};C.forEach(T=>{const E=h(T),_=S(T);w.has(_)||w.set(_,[]),w.get(_)?.push(E)});const k=u??"__project_root__",j=[{id:"root",label:m&&f&&f!=="HEAD"?e("sessions.sidebar.grouping.projectRootWithBranch",{branch:f}):e("sessions.sidebar.grouping.projectRoot"),branch:f??null,description:u?Ca(u,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:u,folderScopeKey:u,sessions:w.get(k)??[]}],A=new Map;d.forEach(T=>{const E=as(T.path)??T.path,_=w.get(E)??[],R=_.length>0,z=_.reduce((V,$)=>{const M=Number($.session.time?.updated??$.session.time?.created??0);return Number.isFinite(M)?Math.max(V,M):V},0);A.set(E,{hasActiveSession:R,lastUpdatedAt:z})});const D=[...d].sort((T,E)=>{const _=as(T.path)??T.path,R=as(E.path)??E.path,z=A.get(_)??{hasActiveSession:!1,lastUpdatedAt:0},V=A.get(R)??{hasActiveSession:!1,lastUpdatedAt:0};if(z.hasActiveSession!==V.hasActiveSession)return z.hasActiveSession?-1:1;if(z.hasActiveSession&&V.hasActiveSession)return V.lastUpdatedAt-z.lastUpdatedAt;const $=(T.label||T.branch||T.name||T.path||"").toLowerCase(),M=(E.label||E.branch||E.name||E.path||"").toLowerCase();return $.localeCompare(M)});(t.isVSCode?[]:D).forEach(T=>{const E=as(T.path)??T.path,_=t.gitBranches.get(E)?.trim()||null,R=T.branch?.trim()||null,V=!!(_&&R&&T.label&&Xd(T.label)===Xd(R))?_:T.label||T.name||Oi(E,t.homeDirectory)||E;j.push({id:`worktree:${E}`,label:V,branch:_||R,description:Ca(E,t.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:T,directory:E,folderScopeKey:E,sessions:w.get(E)??[]})});const B=w.get(v)??[];return B.length>0&&j.push({id:"archived",label:e("sessions.sidebar.grouping.archived"),branch:null,description:e("sessions.sidebar.grouping.archivedDescription"),isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:!t.isVSCode&&u?Bc(u):null,sessions:B}),j},[t.homeDirectory,t.worktreeMetadata,t.pinnedSessionIds,t.gitBranches,t.isVSCode,e]);return{buildGroupSearchText:n,buildSessionSearchText:r,filterSessionNodesForSearch:o,buildGroupedSessions:a}},HS=t=>{const e=ft.c(9),{isSessionSearchOpen:n,setIsSessionSearchOpen:r,sessionSearchInputRef:o,sessionSearchContainerRef:a}=t;let c,l;e[0]!==n||e[1]!==o?(c=()=>{if(!n||typeof window>"u")return;const m=window.requestAnimationFrame(()=>{o.current?.focus(),o.current?.select()});return()=>window.cancelAnimationFrame(m)},l=[n,o],e[0]=n,e[1]=o,e[2]=c,e[3]=l):(c=e[2],l=e[3]),i.useEffect(c,l);let d,f;e[4]!==n||e[5]!==a||e[6]!==r?(d=()=>{if(!n||typeof document>"u")return;const m=u=>{a.current&&(a.current.contains(u.target)||r(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},f=[n,r,a],e[4]=n,e[5]=a,e[6]=r,e[7]=d,e[8]=f):(d=e[7],f=e[8]),i.useEffect(d,f)},GS=t=>{const e=ft.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=(z,V,$)=>{const M=()=>{!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)),z===t.currentSessionId){t.allowReselect&&t.onSessionSelected?.(z),M();return}t.setCurrentSession(z,V??null),t.onSessionSelected?.(z),M()},e[2]=t,e[3]=d):d=e[3];const f=d;let m;e[4]!==t?(m=(z,V)=>{t.setEditingId(z),t.setEditTitle(V)},e[4]=t,e[5]=m):m=e[5];const u=m;let p;e[6]!==t?(p=async z=>{if(!t.editingId)return;const V=(z??t.editTitle).trim();V&&await t.updateSessionTitle(t.editingId,V),t.setEditingId(null),t.setEditTitle("")},e[6]=t,e[7]=p):p=e[7];const y=p;let g;e[8]!==t?(g=()=>{t.setEditingId(null),t.setEditTitle("")},e[8]=t,e[9]=g):g=e[9];const b=g;let x;e[10]!==t||e[11]!==n?(x=async z=>{const V=await t.shareSession(z.id);V&&V.share?.url?le.success(n("sessions.sidebar.session.share.successTitle"),{description:n("sessions.sidebar.session.share.successDescription")}):le.error(n("sessions.sidebar.session.share.error"))},e[10]=t,e[11]=n,e[12]=x):x=e[12];const h=x;let C;e[13]!==n?(C=(z,V)=>{ur(z).then($=>{if(!$.ok){le.error(n("sessions.sidebar.session.share.copyUrlError"));return}o(V),a.current&&clearTimeout(a.current),a.current=window.setTimeout(()=>{o(null),a.current=null},2e3)}).catch(()=>{le.error(n("sessions.sidebar.session.share.copyUrlError"))})},e[13]=n,e[14]=C):C=e[14];const w=C;let v;e[15]!==t||e[16]!==n?(v=async z=>{await t.unshareSession(z)?le.success(n("sessions.sidebar.session.unshare.success")):le.error(n("sessions.sidebar.session.unshare.error"))},e[15]=t,e[16]=n,e[17]=v):v=e[17];const S=v;let k;e[18]!==t.childrenMap?(k=z=>{const V=[],$=M=>{(t.childrenMap.get(M)??[]).forEach(re=>{V.push(re),$(re.id)})};return $(z),V},e[18]=t.childrenMap,e[19]=k):k=e[19];const j=k,A=qS;let D;e[20]!==t||e[21]!==j||e[22]!==n?(D=async(z,V,$)=>{const M=V?.archivedBucket===!0||V?.hardDelete===!0,te=$?.descendantIds??A(j(z.id),M).map(YS);if(te.length===0){(M?await t.deleteSession(z.id):await t.archiveSession(z.id))?le.success(n(M?"sessions.sidebar.session.delete.success":"sessions.sidebar.session.archive.success")):le.error(n(M?"sessions.sidebar.session.delete.error":"sessions.sidebar.session.archive.error"));return}const re=[z.id,...te];if(M){const{deletedIds:X,failedIds:oe}=await t.deleteSessions(re);if(oe.length===0){const fe=X.length;le.success(fe===1?n("sessions.sidebar.bulkActions.deletedSingle",{count:fe}):n("sessions.sidebar.bulkActions.deletedPlural",{count:fe}))}else le.error(n("sessions.sidebar.session.delete.error"));return}const{archivedIds:Q,failedIds:H}=await t.archiveSessions(re);Q.length>0&&le.success(Q.length===1?n("sessions.sidebar.bulkActions.archivedSingle",{count:Q.length}):n("sessions.sidebar.bulkActions.archivedPlural",{count:Q.length})),H.length>0&&le.error(H.length===1?n("sessions.sidebar.bulkActions.failedArchiveSingle",{count:H.length}):n("sessions.sidebar.bulkActions.failedArchivePlural",{count:H.length}))},e[20]=t,e[21]=j,e[22]=n,e[23]=D):D=e[23];const N=D;let B;e[24]!==t||e[25]!==j||e[26]!==N?(B=(z,V)=>{const $=V?.archivedBucket===!0||V?.hardDelete===!0,M=A(j(z.id),$).map(QS);if(!t.showDeletionDialog||V?.skipConfirm===!0){N(z,V,{descendantIds:M});return}t.setDeleteSessionConfirm({session:z,descendantCount:M.length,descendantIds:M,archivedBucket:$})},e[24]=t,e[25]=j,e[26]=N,e[27]=B):B=e[27];const T=B;let E;e[28]!==t||e[29]!==N?(E=async()=>{if(!t.deleteSessionConfirm)return;const{session:z,archivedBucket:V,descendantIds:$}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await N(z,{archivedBucket:V},{descendantIds:$})},e[28]=t,e[29]=N,e[30]=E):E=e[30];const _=E;let R;return e[31]!==_||e[32]!==r||e[33]!==b||e[34]!==w||e[35]!==T||e[36]!==y||e[37]!==u||e[38]!==f||e[39]!==h||e[40]!==S?(R={copiedSessionId:r,handleSessionSelect:f,handleSessionDoubleClick:u,handleSaveEdit:y,handleCancelEdit:b,handleShareSession:h,handleCopyShareUrl:w,handleUnshareSession:S,handleDeleteSession:T,confirmDeleteSession:_},e[31]=_,e[32]=r,e[33]=b,e[34]=w,e[35]=T,e[36]=y,e[37]=u,e[38]=f,e[39]=h,e[40]=S,e[41]=R):R=e[41],R};function KS(t){return!t.time?.archived}function qS(t,e){return e?t:t.filter(KS)}function YS(t){return t.id}function QS(t){return t.id}const JS=["project:active:","project:archived:","recent:active:","recent:archived:"],XS=t=>{const{isVSCode:e,hasLoadedGlobalSessions:n,safeStorage:r,keys:o,sessions:a,setPinnedSessionIds:c,groupOrderByProject:l,activeSessionByProject:d,collapsedGroups:f,setExpandedParents:m,setCollapsedProjects:u}=t,p=i.useRef(null),y=i.useRef(null),g=i.useCallback(()=>{if(e)return;const x=y.current;if(y.current=null,p.current=null,!x)return;const{projects:h}=Ss.getState(),C=h.map(w=>({...w,sidebarCollapsed:x.has(w.id)}));pc({projects:C}).catch(()=>{})},[e]),b=i.useCallback(x=>{typeof window>"u"||e||(y.current=x,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{g()},700))},[e,g]);return i.useEffect(()=>()=>{typeof window<"u"&&p.current!==null&&window.clearTimeout(p.current),p.current=null,y.current=null},[]),i.useEffect(()=>{try{const x=r.getItem(o.sessionExpanded);if(x){const C=JSON.parse(x);Array.isArray(C)&&m(new Set(C.filter(w=>typeof w=="string")))}else{const C=r.getItem(o.sessionExpandedLegacy);if(C){try{const w=JSON.parse(C);if(Array.isArray(w)){const v=new Set;if(w.forEach(S=>{typeof S!="string"||S.length===0||JS.forEach(k=>v.add(`${k}${S}`))}),v.size>0){m(v);try{r.setItem(o.sessionExpanded,JSON.stringify(Array.from(v)))}catch{}}}}catch{}try{r.removeItem?.(o.sessionExpandedLegacy)}catch{}}}const h=r.getItem(o.projectCollapse);if(h){const C=JSON.parse(h);Array.isArray(C)&&u(new Set(C.filter(w=>typeof w=="string")))}}catch{}},[o.projectCollapse,o.sessionExpanded,o.sessionExpandedLegacy,r,u,m]),i.useEffect(()=>{if(!n||a.length===0)return;const x=new Set(a.map(h=>h.id));c(h=>{let C=!1;const w=new Set;return h.forEach(v=>{x.has(v)?w.add(v):C=!0}),C?w:h})},[n,a,c]),i.useEffect(()=>{try{const x=Object.fromEntries(l.entries());r.setItem(o.groupOrder,JSON.stringify(x))}catch{}},[l,o.groupOrder,r]),i.useEffect(()=>{try{const x=Object.fromEntries(d.entries());r.setItem(o.projectActiveSession,JSON.stringify(x))}catch{}},[d,o.projectActiveSession,r]),i.useEffect(()=>{try{r.setItem(o.groupCollapse,JSON.stringify(Array.from(f)))}catch{}},[f,o.groupCollapse,r]),{scheduleCollapsedProjectsPersist:b}},ZS=t=>{const{normalizedProjects:e,gitRepoStatus:n,setProjectRepoStatus:r,setProjectRootBranches:o}=t,{git:a}=Xn(),c=wn(u=>u.ensureStatus);i.useEffect(()=>{if(!a||e.length===0){r(new Map);return}e.forEach(u=>{c(u.normalizedPath,a)})},[e,a,c,r]),i.useEffect(()=>{const u=new Map;e.forEach(p=>{u.set(p.id,n.get(p.normalizedPath)?.isGitRepo??null)}),r(u)},[e,n,r]);const l=i.useMemo(()=>e.map(u=>{const p=n.get(u.normalizedPath)?.branch??"";return`${u.id}:${p}`}).join("|"),[e,n]),d=i.useRef(new Map),f=i.useRef(new Map),m=5*6e4;i.useEffect(()=>{let u=!1;const p=setTimeout(()=>{(async()=>{const g=new Set(e.map(v=>v.id));for(const v of d.current.keys())g.has(v)||(d.current.delete(v),f.current.delete(v));const b=Date.now(),x=e.filter(v=>{const S=n.get(v.normalizedPath);if(S?.isGitRepo===!1)return d.current.delete(v.id),f.current.delete(v.id),!1;if(S?.isGitRepo!==!0||S.branch===null)return!1;const k=S.branch.trim(),j=`${v.normalizedPath}\0${k}`,A=d.current.get(v.id);if(A===j){const D=f.current.get(v.id);return D&&(D.at=b),!1}return!(A!==void 0&&b-(f.current.get(v.id)?.at??0)<m)});if(x.length===0)return;const h=await zm(x,2,async v=>{const S=n.get(v.normalizedPath)?.branch?.trim()??"",k=`${v.normalizedPath}\0${S}`,j=await qa(v.normalizedPath,S?{knownBranch:S}:void 0).catch(()=>null);return{id:v.id,inputKey:k,branch:j}});if(u)return;const C=h.filter(v=>v.branch);if(C.length===0)return;const w=Date.now();o(v=>{const S=new Map(v);return C.forEach(({id:k,branch:j})=>{j&&S.set(k,j)}),S}),C.forEach(({id:v,inputKey:S,branch:k})=>{d.current.set(v,S),k&&f.current.set(v,{branch:k,at:w})})})()},150);return()=>{u=!0,clearTimeout(p)}},[e,l,n,o])},eN=t=>{const e=ft.c(19),{isVSCode:n,sessions:r,archivedSessions:o,availableWorktreesByProject:a,normalizedProjects:c}=t;let l;if(e[0]!==a||e[1]!==n||e[2]!==c){if(l=new Set,c.forEach(x=>{x.normalizedPath&&l.add(x.normalizedPath)}),!n)for(const x of a.values())for(const h of x){const C=as(h.path);C&&l.add(C)}e[0]=a,e[1]=n,e[2]=c,e[3]=l}else l=e[3];const d=l;let f;e[4]!==d||e[5]!==r?(f=new Map,r.forEach(x=>{const h=Mr(x);if(!h||!d.has(h))return;const C=f.get(h)??[];C.push(x),f.set(h,C)}),e[4]=d,e[5]=r,e[6]=f):f=e[6];const m=f;let u;e[7]!==a||e[8]!==n||e[9]!==m?(u=x=>{const h=n?[]:a.get(x.normalizedPath)??[],C=[x.normalizedPath,...h.map(tN).filter(sN)],w=new Set,v=[];return C.forEach(S=>{(m.get(S)??[]).forEach(j=>{w.has(j.id)||(w.add(j.id),v.push(j))})}),v},e[7]=a,e[8]=n,e[9]=m,e[10]=u):u=e[10];const p=u;let y;e[11]!==o||e[12]!==a||e[13]!==n||e[14]!==r?(y=x=>{if(n){const k=o.filter(A=>{const D=as(A.directory??null),N=as(A.project?.worktree??null);return D?D===x.normalizedPath:N===x.normalizedPath}),j=r.filter(A=>A.time?.archived||as(A.directory??null)?!1:as(A.project?.worktree??null)===x.normalizedPath);return io([...k,...j])}const h=n?[]:a.get(x.normalizedPath)??[],C=new Set([x.normalizedPath,...h.map(nN).filter(rN)]),v=(k=>k.filter(j=>Eo(j,x.normalizedPath,C)))(o),S=r.filter(k=>{if(k.time?.archived||as(k.directory??null))return!1;const A=as(k.project?.worktree??null);return A?A===x.normalizedPath||A.startsWith(`${x.normalizedPath}/`):!1});return io([...v,...S])},e[11]=o,e[12]=a,e[13]=n,e[14]=r,e[15]=y):y=e[15];const g=y;let b;return e[16]!==g||e[17]!==p?(b={getSessionsForProject:p,getArchivedSessionsForProject:g},e[16]=g,e[17]=p,e[18]=b):b=e[18],b};function tN(t){return as(t.path)??t.path}function sN(t){return!!t}function nN(t){return as(t.path)??t.path}function rN(t){return!!t}const iN=t=>{const e=ft.c(10),{isSessionsLoading:n,hasLoadedGlobalSessions:r,sessions:o,archivedSessions:a,normalizedProjects:c,isVSCode:l,availableWorktreesByProject:d,cleanupSessions:f}=t;let m,u;e[0]!==a||e[1]!==d||e[2]!==f||e[3]!==r||e[4]!==n||e[5]!==l||e[6]!==c||e[7]!==o?(m=()=>{if(n||!r||o.length===0&&a.length===0)return;const p=new Map;o.forEach(b=>{const x=as(b.directory??null);if(!x)return;const h=p.get(x);if(h){h.add(b.id);return}p.set(x,new Set([b.id]))}),c.forEach(b=>{const x=Bc(b.normalizedPath),h=l?[]:d.get(b.normalizedPath)??[],C=new Set([b.normalizedPath,...h.map(oN).filter(aN)]),w=io([...a,...o.filter(v=>v.time?.archived||as(v.directory??null)?!1:Eo(v,b.normalizedPath,C))]).filter(v=>Eo(v,b.normalizedPath,C));p.set(x,new Set(w.map(lN)))});const y=Vn.getState().foldersMap;new Set([...Object.keys(y),...p.keys()]).forEach(b=>{f(b,p.get(b)??new Set)})},u=[a,d,f,r,n,l,c,o],e[0]=a,e[1]=d,e[2]=f,e[3]=r,e[4]=n,e[5]=l,e[6]=c,e[7]=o,e[8]=m,e[9]=u):(m=e[8],u=e[9]),i.useEffect(m,u)};function oN(t){return as(t.path)??t.path}function aN(t){return!!t}function lN(t){return t.id}const cN=t=>{const e=ft.c(8),{isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=t;let a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a=new Set,e[0]=a):a=e[0];const[c,l]=i.useState(a);let d;e[1]!==n||e[2]!==o?(d=()=>{if(!n)return;const m=new IntersectionObserver(u=>{u.forEach(p=>{const y=p.target.dataset.projectId;y&&l(g=>{const b=new Set(g);return p.isIntersecting?b.delete(y):b.add(y),b})})},{threshold:0});return o.current.forEach(u=>{u&&m.observe(u)}),()=>m.disconnect()},e[1]=n,e[2]=o,e[3]=d):d=e[3];let f;return e[4]!==n||e[5]!==o||e[6]!==r?(f=[n,o,r],e[4]=n,e[5]=o,e[6]=r,e[7]=f):f=e[7],i.useEffect(d,f),c},dN=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Ml=t=>{if(!t)return null;const e=t.trim();return e&&dN.test(e)?e.toLowerCase():null},uN=t=>{const e=ft.c(198),{open:n,onOpenChange:r,projectId:o,projectName:a,projectPath:c,initialIcon:l,initialColor:d,initialIconBackground:f,onSave:m}=t,u=l===void 0?null:l,p=d===void 0?null:d,y=f===void 0?null:f,{t:g}=Nt(),b=Ss(fN),x=Ss(mN),h=Ss(hN);let C;e[0]!==o?(C=Ge=>Ge.projects.find(wt=>wt.id===o)?.iconImage??null,e[0]=o,e[1]=C):C=e[1];const w=Ss(C),{currentTheme:v}=Qr(),[S,k]=i.useState(a),[j,A]=i.useState(u),[D,N]=i.useState(p);let B;e[2]!==y?(B=Ml(y),e[2]=y,e[3]=B):B=e[3];const[T,E]=i.useState(B),[_,R]=i.useState(!1),[z,V]=i.useState(!1),[$,M]=i.useState(!1),[te,re]=i.useState(!1),[Q,H]=i.useState(null),[X,oe]=i.useState(null),[fe,ve]=i.useState(!1),ie=i.useRef(null);let Ne;e[4]===Symbol.for("react.memo_cache_sentinel")?(Ne=()=>{H(null),oe(pN)},e[4]=Ne):Ne=e[4];const K=Ne;let pe,L;e[5]!==p||e[6]!==u||e[7]!==y||e[8]!==n||e[9]!==a?(pe=()=>{n&&(k(a),A(u),N(p),E(Ml(y)),re(!1),K(),ve(!1))},L=[n,a,u,p,y,K],e[5]=p,e[6]=u,e[7]=y,e[8]=n,e[9]=a,e[10]=pe,e[11]=L):(pe=e[10],L=e[11]),i.useEffect(pe,L);let se,Z;e[12]===Symbol.for("react.memo_cache_sentinel")?(Z=()=>()=>{K()},se=[K],e[12]=se,e[13]=Z):(se=e[12],Z=e[13]),i.useEffect(Z,se);let je,De,Le;if(e[14]!==D||e[15]!==w||e[16]!==j||e[17]!==T||e[18]!==S||e[19]!==r||e[20]!==m||e[21]!==te||e[22]!==Q||e[23]!==o||e[24]!==x||e[25]!==g||e[26]!==b){let Ge;e[30]!==D||e[31]!==j||e[32]!==T||e[33]!==S||e[34]!==r||e[35]!==m||e[36]!==te||e[37]!==Q||e[38]!==o||e[39]!==x||e[40]!==g||e[41]!==b?(Ge=async()=>{const wt=S.trim();if(!wt)return;if(Q){R(!0);const Dt=await b(o,Q);if(R(!1),!Dt.ok){le.error(Dt.error||g("projectEditDialog.toast.failedToUploadIcon"));return}le.success(g("projectEditDialog.toast.iconUpdated")),K(),re(!1)}const Ot=te&&Le;if(Ot){V(!0);const Dt=await x(o);if(V(!1),!Dt.ok){le.error(Dt.error||g("projectEditDialog.toast.failedToRemoveIcon"));return}le.success(g("projectEditDialog.toast.iconRemoved")),re(!1),E(null)}m({label:wt,icon:j,color:D,iconBackground:Ml(Ot?null:T)}),r(!1)},e[30]=D,e[31]=j,e[32]=T,e[33]=S,e[34]=r,e[35]=m,e[36]=te,e[37]=Q,e[38]=o,e[39]=x,e[40]=g,e[41]=b,e[42]=Ge):Ge=e[42],De=Ge,je=D?Qa[D]??null:null,Le=!!w,e[14]=D,e[15]=w,e[16]=j,e[17]=T,e[18]=S,e[19]=r,e[20]=m,e[21]=te,e[22]=Q,e[23]=o,e[24]=x,e[25]=g,e[26]=b,e[27]=je,e[28]=De,e[29]=Le}else je=e[27],De=e[28],Le=e[29];const Me=!!(Q&&X),Fe=w?.source==="custom",he=Le&&!te||Me,Ie=he,ce=!fe&&(Me||Le&&!te);let xe;e[43]===Symbol.for("react.memo_cache_sentinel")?(xe=()=>{ve(!1)},e[43]=xe):xe=e[43];const ke=w?.updatedAt;let de;e[44]!==o||e[45]!==ke?(de=[o,ke],e[44]=o,e[45]=ke,e[46]=de):de=e[46],i.useEffect(xe,de);let P;e[47]!==_||e[48]!==o?(P=Ge=>{!o||!Ge||_||(re(!1),ve(!1),H(Ge),oe(wt=>(wt&&URL.revokeObjectURL(wt),URL.createObjectURL(Ge))))},e[47]=_,e[48]=o,e[49]=P):P=e[49];const F=P;let ue;e[50]!==Me||e[51]!==Ie||e[52]!==Le||e[53]!==z||e[54]!==o?(ue=()=>{!o||!Ie||z||(Me&&K(),re(!!Le),ve(!1))},e[50]=Me,e[51]=Ie,e[52]=Le,e[53]=z,e[54]=o,e[55]=ue):ue=e[55];const be=ue;let W;e[56]!==h||e[57]!==$||e[58]!==o||e[59]!==g?(W=async()=>{!o||$||(K(),re(!1),ve(!1),M(!0),h(o).then(Ge=>{if(!Ge.ok){le.error(Ge.error||g("projectEditDialog.toast.failedToDiscoverIcon"));return}if(Ge.skipped){le.success(g("projectEditDialog.toast.customIconAlreadySet"));return}le.success(g("projectEditDialog.toast.iconDiscovered"))}).finally(()=>{M(!1)}))},e[56]=h,e[57]=$,e[58]=o,e[59]=g,e[60]=W):W=e[60];const ge=W;let we;e[61]!==g?(we=g("projectEditDialog.title"),e[61]=g,e[62]=we):we=e[62];let G;e[63]!==we?(G=s.jsx(Gs,{className:"min-w-0",children:s.jsx(Vs,{children:we})}),e[63]=we,e[64]=G):G=e[64];let Se;e[65]!==g?(Se=g("projectEditDialog.field.name"),e[65]=g,e[66]=Se):Se=e[66];let Oe;e[67]!==Se?(Oe=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:Se}),e[67]=Se,e[68]=Oe):Oe=e[68];let Ae;e[69]===Symbol.for("react.memo_cache_sentinel")?(Ae=Ge=>k(Ge.target.value),e[69]=Ae):Ae=e[69];let J;e[70]!==g?(J=g("projectEditDialog.field.namePlaceholder"),e[70]=g,e[71]=J):J=e[71];let O;e[72]!==De?(O=Ge=>{Ge.key==="Enter"&&(Ge.preventDefault(),De())},e[72]=De,e[73]=O):O=e[73];let ae;e[74]!==S||e[75]!==J||e[76]!==O?(ae=s.jsx(vn,{value:S,onChange:Ae,placeholder:J,onKeyDown:O,autoFocus:!0}),e[74]=S,e[75]=J,e[76]=O,e[77]=ae):ae=e[77];let ne;e[78]!==c?(ne=s.jsx("p",{className:"typography-meta text-muted-foreground truncate",title:c,children:c}),e[78]=c,e[79]=ne):ne=e[79];let Be;e[80]!==Oe||e[81]!==ae||e[82]!==ne?(Be=s.jsxs("div",{className:"min-w-0 space-y-1.5",children:[Oe,ae,ne]}),e[80]=Oe,e[81]=ae,e[82]=ne,e[83]=Be):Be=e[83];let Ye;e[84]!==g?(Ye=g("projectEditDialog.field.color"),e[84]=g,e[85]=Ye):Ye=e[85];let He;e[86]!==Ye?(He=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:Ye}),e[86]=Ye,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 nt=D===null?"border-foreground scale-110":"border-border hover:border-border/80";let xt;e[89]!==nt?(xt=Te("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",nt),e[89]=nt,e[90]=xt):xt=e[90];let bt;e[91]!==g?(bt=g("projectEditDialog.option.none"),e[91]=g,e[92]=bt):bt=e[92];let _e;e[93]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[93]=_e):_e=e[93];let Qe;e[94]!==xt||e[95]!==bt?(Qe=s.jsx("button",{type:"button",onClick:Je,className:xt,title:bt,children:_e}),e[94]=xt,e[95]=bt,e[96]=Qe):Qe=e[96];let st;e[97]!==D?(st=Rg.map(Ge=>s.jsx("button",{type:"button",onClick:()=>N(Ge.key),className:Te("w-8 h-8 rounded-lg border-2 transition-all",D===Ge.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:Ge.cssVar},title:Ge.label},Ge.key)),e[97]=D,e[98]=st):st=e[98];let pt;e[99]!==Qe||e[100]!==st?(pt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Qe,st]}),e[99]=Qe,e[100]=st,e[101]=pt):pt=e[101];let At;e[102]!==He||e[103]!==pt?(At=s.jsxs("div",{className:"min-w-0 space-y-2",children:[He,pt]}),e[102]=He,e[103]=pt,e[104]=At):At=e[104];let vt;e[105]!==g?(vt=g("projectEditDialog.field.icon"),e[105]=g,e[106]=vt):vt=e[106];let kt;e[107]!==vt?(kt=s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:vt}),e[107]=vt,e[108]=kt):kt=e[108];let et;e[109]!==F?(et=s.jsx("input",{ref:ie,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:Ge=>{const wt=Ge.target.files?.[0]??null;F(wt),Ge.currentTarget.value=""}}),e[109]=F,e[110]=et):et=e[110];let _t;e[111]===Symbol.for("react.memo_cache_sentinel")?(_t=()=>A(null),e[111]=_t):_t=e[111];const ns=j===null?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80";let Kt;e[112]!==ns?(Kt=Te("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",ns),e[112]=ns,e[113]=Kt):Kt=e[113];let qe;e[114]!==g?(qe=g("projectEditDialog.option.none"),e[114]=g,e[115]=qe):qe=e[115];let gt;e[116]===Symbol.for("react.memo_cache_sentinel")?(gt=s.jsx("span",{className:"w-4 h-0.5 bg-muted-foreground/40 rotate-45 rounded-full"}),e[116]=gt):gt=e[116];let Xe;e[117]!==Kt||e[118]!==qe?(Xe=s.jsx("button",{type:"button",onClick:_t,className:Kt,title:qe,children:gt}),e[117]=Kt,e[118]=qe,e[119]=Xe):Xe=e[119];let jt;e[120]!==je||e[121]!==j?(jt=Eg.map(Ge=>{const wt=Ge.Icon;return s.jsx("button",{type:"button",onClick:()=>A(Ge.key),className:Te("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",j===Ge.key?"border-foreground scale-110 bg-[var(--surface-elevated)]":"border-border hover:border-border/80"),title:Ge.label,children:s.jsx(I,{name:wt,className:"w-4 h-4",style:je?{color:je}:void 0})},Ge.key)}),e[120]=je,e[121]=j,e[122]=jt):jt=e[122];let Pt;e[123]!==Xe||e[124]!==jt?(Pt=s.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Xe,jt]}),e[123]=Xe,e[124]=jt,e[125]=Pt):Pt=e[125];let is;e[126]!==w||e[127]!==v||e[128]!==he||e[129]!==Me||e[130]!==T||e[131]!==X||e[132]!==o||e[133]!==ce||e[134]!==g?(is=he&&ce&&s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:g("projectEditDialog.field.preview")}),s.jsx("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-1",children:s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:T?{backgroundColor:T}:void 0,children:Me&&X?s.jsx("img",{src:X,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>ve(!0)}):s.jsx(Ja,{project:{id:o,iconImage:w},options:{themeVariant:v.metadata.variant,iconColor:v.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>ve(!0)})})})]}),e[126]=w,e[127]=v,e[128]=he,e[129]=Me,e[130]=T,e[131]=X,e[132]=o,e[133]=ce,e[134]=g,e[135]=is):is=e[135];let Bt;e[136]!==ge||e[137]!==Fe||e[138]!==$||e[139]!==_||e[140]!==g?(Bt=!Fe&&s.jsxs(s.Fragment,{children:[s.jsx(Ve,{size:"sm",variant:"outline",onClick:()=>ie.current?.click(),disabled:_,children:g(_?"projectEditDialog.actions.uploading":"projectEditDialog.actions.uploadIcon")}),s.jsx(Ve,{size:"sm",variant:"outline",onClick:()=>{ge()},disabled:$,children:g($?"projectEditDialog.actions.discovering":"projectEditDialog.actions.discoverFavicon")})]}),e[136]=ge,e[137]=Fe,e[138]=$,e[139]=_,e[140]=g,e[141]=Bt):Bt=e[141];let Gt;e[142]!==be||e[143]!==Ie||e[144]!==z||e[145]!==g?(Gt=Ie&&s.jsx(Ve,{size:"sm",variant:"outline",onClick:()=>{be()},disabled:z,children:g(z?"projectEditDialog.actions.removing":"projectEditDialog.actions.removeProjectIcon")}),e[142]=be,e[143]=Ie,e[144]=z,e[145]=g,e[146]=Gt):Gt=e[146];let es;e[147]!==z||e[148]!==te||e[149]!==g?(es=te&&s.jsx(Ve,{size:"sm",variant:"outline",onClick:()=>re(!1),disabled:z,children:g("projectEditDialog.actions.undoRemove")}),e[147]=z,e[148]=te,e[149]=g,e[150]=es):es=e[150];let Wt;e[151]!==Bt||e[152]!==Gt||e[153]!==es?(Wt=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[Bt,Gt,es]}),e[151]=Bt,e[152]=Gt,e[153]=es,e[154]=Wt):Wt=e[154];let Lt;e[155]!==kt||e[156]!==et||e[157]!==Pt||e[158]!==is||e[159]!==Wt?(Lt=s.jsxs("div",{className:"min-w-0 space-y-2",children:[kt,et,Pt,is,Wt]}),e[155]=kt,e[156]=et,e[157]=Pt,e[158]=is,e[159]=Wt,e[160]=Lt):Lt=e[160];let Ut;e[161]!==he||e[162]!==T||e[163]!==g?(Ut=he&&s.jsxs("div",{className:"min-w-0 space-y-2",children:[s.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:g("projectEditDialog.field.iconBackground")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:T??"#000000",onChange:Ge=>E(Ge.target.value),className:"h-8 w-10 cursor-pointer rounded border border-border bg-transparent p-1","aria-label":g("projectEditDialog.field.iconBackgroundAria")}),s.jsx(vn,{value:T??"",onChange:Ge=>E(Ge.target.value),placeholder:"#000000",className:"h-8 w-[8.5rem]"}),s.jsx(Ve,{size:"sm",variant:"outline",onClick:()=>E(null),children:g("projectEditDialog.actions.clear")})]})]}),e[161]=he,e[162]=T,e[163]=g,e[164]=Ut):Ut=e[164];let rs;e[165]!==Be||e[166]!==At||e[167]!==Lt||e[168]!==Ut?(rs=s.jsxs("div",{className:"min-w-0 space-y-5 py-1",children:[Be,At,Lt,Ut]}),e[165]=Be,e[166]=At,e[167]=Lt,e[168]=Ut,e[169]=rs):rs=e[169];let $t;e[170]!==r?($t=()=>r(!1),e[170]=r,e[171]=$t):$t=e[171];let ls;e[172]!==g?(ls=g("projectEditDialog.actions.cancel"),e[172]=g,e[173]=ls):ls=e[173];let xs;e[174]!==$t||e[175]!==ls?(xs=s.jsx(Ve,{variant:"ghost",onClick:$t,children:ls}),e[174]=$t,e[175]=ls,e[176]=xs):xs=e[176];let Ct;e[177]!==z||e[178]!==_||e[179]!==S?(Ct=!S.trim()||_||z,e[177]=z,e[178]=_,e[179]=S,e[180]=Ct):Ct=e[180];let Vt;e[181]!==g?(Vt=g("projectEditDialog.actions.save"),e[181]=g,e[182]=Vt):Vt=e[182];let yt;e[183]!==De||e[184]!==Ct||e[185]!==Vt?(yt=s.jsx(Ve,{onClick:De,disabled:Ct,children:Vt}),e[183]=De,e[184]=Ct,e[185]=Vt,e[186]=yt):yt=e[186];let us;e[187]!==xs||e[188]!==yt?(us=s.jsxs(nr,{children:[xs,yt]}),e[187]=xs,e[188]=yt,e[189]=us):us=e[189];let cs;e[190]!==G||e[191]!==rs||e[192]!==us?(cs=s.jsxs(Es,{className:"max-w-md",children:[G,rs,us]}),e[190]=G,e[191]=rs,e[192]=us,e[193]=cs):cs=e[193];let Ue;return e[194]!==r||e[195]!==n||e[196]!==cs?(Ue=s.jsx(Ms,{open:n,onOpenChange:r,children:cs}),e[194]=r,e[195]=n,e[196]=cs,e[197]=Ue):Ue=e[197],Ue};function fN(t){return t.uploadProjectIcon}function mN(t){return t.removeProjectIcon}function hN(t){return t.discoverProjectIcon}function pN(t){return t&&URL.revokeObjectURL(t),null}const gN=`**Help shape what OpenChamber becomes next!**
|
|
171
|
-
|
|
172
|
-
Hey 👋,
|
|
173
|
-
|
|
174
|
-
OpenChamber has grown mostly through word of mouth, GitHub issues, Discord feedback, and people telling me what is broken, confusing, or surprisingly useful.
|
|
175
|
-
|
|
176
|
-
I'm planning the next chapter now - mobile, better remote access, a tighter VS Code ↔ desktop/web/mobile flow, and more, but before building too much, I want to hear from the people actually using it.
|
|
177
|
-
|
|
178
|
-
I'm doing a round of short 1-on-1 calls. No sales pitch, no formal script - just a real conversation about how you use OpenChamber, what you love, what frustrates you, and what would make it much more valuable.
|
|
179
|
-
|
|
180
|
-
You can book a call or use the short survey below.
|
|
181
|
-
|
|
182
|
-
What you get:
|
|
183
|
-
|
|
184
|
-
- A direct chance to influence the roadmap
|
|
185
|
-
- Your pain points and feature requests prioritized with more context
|
|
186
|
-
- A Power User role in Discord for people helping shape the product
|
|
187
|
-
- My genuine thanks for helping make OpenChamber better
|
|
188
|
-
|
|
189
|
-
**This project is what it is because of your feedback. Thank you, genuinely.**
|
|
190
|
-
|
|
191
|
-
I'll remove this button in 10 days 🙂`;function xN(t){const e=ft.c(25),{open:n,onOpenChange:r}=t,{t:o}=Nt();let a;e[0]!==o?(a=o("shareOpinion.dialog.title"),e[0]=o,e[1]=a):a=e[1];let c;e[2]!==a?(c=s.jsx(Vs,{className:"sr-only",children:a}),e[2]=a,e[3]=c):c=e[3];let l;e[4]===Symbol.for("react.memo_cache_sentinel")?(l=s.jsx(so,{content:gN,className:"typography-markdown-body",enableFileReferences:!1}),e[4]=l):l=e[4];let d;e[5]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(I,{name:"video-chat",className:"size-5 text-[var(--status-warning)]"}),e[5]=d):d=e[5];let f;e[6]!==o?(f=o("shareOpinion.actions.bookCall"),e[6]=o,e[7]=f):f=e[7];let m;e[8]!==f?(m=s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-2.5 typography-ui-label text-foreground hover:bg-[var(--interactive-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",onClick:yN,children:[d,f]}),e[8]=f,e[9]=m):m=e[9];let u;e[10]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(I,{name:"survey",className:"size-5 text-[var(--pr-merged)]"}),e[10]=u):u=e[10];let p;e[11]!==o?(p=o("shareOpinion.actions.shortSurvey"),e[11]=o,e[12]=p):p=e[12];let y;e[13]!==p?(y=s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-2.5 typography-ui-label text-foreground hover:bg-[var(--interactive-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",onClick:bN,children:[u,p]}),e[13]=p,e[14]=y):y=e[14];let g;e[15]!==m||e[16]!==y?(g=s.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[m,y]}),e[15]=m,e[16]=y,e[17]=g):g=e[17];let b;e[18]!==g||e[19]!==c?(b=s.jsxs(Es,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[c,l,g]}),e[18]=g,e[19]=c,e[20]=b):b=e[20];let x;return e[21]!==r||e[22]!==n||e[23]!==b?(x=s.jsx(Ms,{open:n,onOpenChange:r,children:b}),e[21]=r,e[22]=n,e[23]=b,e[24]=x):x=e[24],x}function bN(){qr("https://forms.gle/cdMVKUGs5QuLWkA86")}function yN(){qr("https://calendly.com/artmore/30min")}const wN=t=>{const e=ft.c(86),{folder:n,sessions:r,subFolderItems:o,isCollapsed:a,onToggle:c,onRename:l,onDelete:d,renderSessionNode:f,getRenderExtras:m,groupDirectory:u,projectId:p,mobileVariant:y,alwaysShowActions:g,isRenaming:b,renameDraft:x,onRenameDraftChange:h,onRenameSave:C,onRenameCancel:w,droppableRef:v,isDropTarget:S,onNewSession:k,onNewSubFolder:j,depth:A,hideActions:D,archivedBucket:N}=t,T=g===void 0?y===void 0?!1:y:g,E=b===void 0?!1:b,_=x===void 0?"":x,R=S===void 0?!1:S,z=A===void 0?0:A,V=D===void 0?!1:D,$=N===void 0?!1:N,{t:M}=Nt(),[te,re]=i.useState(!1),[Q,H]=i.useState(""),X=i.useRef(null),oe=E||te,fe=E?_:Q;let ve;e[0]!==n.name?(ve=()=>{H(n.name),re(!0)},e[0]=n.name,e[1]=ve):ve=e[1];const ie=ve;let Ne;e[2]!==fe||e[3]!==n.name||e[4]!==E||e[5]!==l||e[6]!==C?(Ne=()=>{const O=fe.trim();O&&O!==n.name&&l(O),E&&C&&C(),re(!1),H("")},e[2]=fe,e[3]=n.name,e[4]=E,e[5]=l,e[6]=C,e[7]=Ne):Ne=e[7];const K=Ne;let pe;e[8]!==E||e[9]!==w?(pe=()=>{E&&w&&w(),re(!1),H("")},e[8]=E,e[9]=w,e[10]=pe):pe=e[10];const L=pe;let se;e[11]!==E||e[12]!==h?(se=O=>{E&&h?h(O):H(O)},e[11]=E,e[12]=h,e[13]=se):se=e[13];const Z=se;let je,De;e[14]!==E?(je=()=>{if(!E)return;const O=()=>{const Be=X.current;Be&&(Be.focus(),Be.select())},ae=requestAnimationFrame(O),ne=window.setTimeout(O,0);return()=>{cancelAnimationFrame(ae),window.clearTimeout(ne)}},De=[E],e[14]=E,e[15]=je,e[16]=De):(je=e[15],De=e[16]),i.useEffect(je,De);const Le=a?"folder":"folder-open",Fe=z>0&&"ml-3";let he;e[17]!==Fe?(he=Te("oc-folder",Fe),e[17]=Fe,e[18]=he):he=e[18];const Ie=R&&"bg-primary/10 ring-1 ring-inset ring-primary/30";let me;e[19]!==Ie?(me=Te("group/folder relative flex items-center justify-between gap-1.5 py-1 min-w-0 rounded-md","cursor-pointer",Ie),e[19]=Ie,e[20]=me):me=e[20];const ce=oe?void 0:c,xe=oe?void 0:"button",ke=oe?void 0:0;let de;e[21]!==c||e[22]!==oe?(de=oe?void 0:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),c())},e[21]=c,e[22]=oe,e[23]=de):de=e[23];let P;e[24]!==n.name||e[25]!==a||e[26]!==M?(P=a?M("sessions.sidebar.folderItem.expandAria",{folderName:n.name}):M("sessions.sidebar.folderItem.collapseAria",{folderName:n.name}),e[24]=n.name,e[25]=a,e[26]=M,e[27]=P):P=e[27];const F=$?T?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":"";let ue;e[28]!==F?(ue=Te("min-w-0 flex items-center gap-1.5 pl-1.5 flex-1 transition-[padding]",F),e[28]=F,e[29]=ue):ue=e[29];const be=R?"text-primary":"text-muted-foreground";let W;e[30]!==be?(W=Te("h-3.5 w-3.5 flex-shrink-0",be),e[30]=be,e[31]=W):W=e[31];let ge;e[32]!==Le||e[33]!==W?(ge=s.jsx(I,{name:Le,className:W}),e[32]=Le,e[33]=W,e[34]=ge):ge=e[34];let we;e[35]!==fe||e[36]!==n.name||e[37]!==L||e[38]!==Z||e[39]!==K||e[40]!==a||e[41]!==R||e[42]!==oe||e[43]!==r||e[44]!==M?(we=oe?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:jN,onMouseDown:SN,onSubmit:O=>{O.preventDefault(),K()},children:[s.jsx("input",{ref:X,value:fe,onChange:O=>Z(O.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:M("sessions.sidebar.folderItem.namePlaceholder"),onClick:NN,onPointerDown:kN,onMouseDown:CN,onKeyDown:O=>{if(O.key==="Escape"){O.stopPropagation(),L();return}(O.key===" "||O.key==="Enter")&&O.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:AN,onPointerDown:DN,onMouseDown:IN,children:s.jsx(I,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),L()},onPointerDown:PN,onMouseDown:TN,className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsx("span",{className:Te("typography-ui-label font-semibold truncate",R?"text-primary":"text-muted-foreground"),children:n.name}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",r.length]}),a?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"})]}),e[35]=fe,e[36]=n.name,e[37]=L,e[38]=Z,e[39]=K,e[40]=a,e[41]=R,e[42]=oe,e[43]=r,e[44]=M,e[45]=we):we=e[45];let G;e[46]!==ue||e[47]!==ge||e[48]!==we?(G=s.jsxs("div",{className:ue,children:[ge,we]}),e[46]=ue,e[47]=ge,e[48]=we,e[49]=G):G=e[49];let Se;e[50]!==T||e[51]!==$||e[52]!==z||e[53]!==n.name||e[54]!==ie||e[55]!==V||e[56]!==d||e[57]!==k||e[58]!==j||e[59]!==oe||e[60]!==M?(Se=!oe&&(!V||$)?s.jsx("div",{className:"flex items-center gap-0.5 px-0.5",children:s.jsxs("div",{className:Te("flex items-center gap-0.5 transition-opacity",T?"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:O=>{O.stopPropagation(),k()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":M("sessions.sidebar.folderItem.newSessionAria",{folderName:n.name}),title:M("sessions.sidebar.project.actions.newSession"),children:s.jsx(I,{name:"add",className:"h-3.5 w-3.5"})}):null,!$&&j&&z===0?s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),j()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":M("sessions.sidebar.folderItem.newSubfolderAria",{folderName:n.name}),title:M("sessions.sidebar.folderItem.newSubfolder"),children:s.jsx(I,{name:"folder-add",className:"h-3.5 w-3.5"})}):null,$?null:s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),ie()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":M("sessions.sidebar.folderItem.renameAria",{folderName:n.name}),children:s.jsx(I,{name:"pencil-ai",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:O=>{O.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":$?M("sessions.sidebar.folderItem.deleteArchivedInFolderAria",{folderName:n.name}):M("sessions.sidebar.folderItem.deleteFolderAria",{folderName:n.name}),children:s.jsx(I,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})}):null,e[50]=T,e[51]=$,e[52]=z,e[53]=n.name,e[54]=ie,e[55]=V,e[56]=d,e[57]=k,e[58]=j,e[59]=oe,e[60]=M,e[61]=Se):Se=e[61];let Oe;e[62]!==v||e[63]!==me||e[64]!==ce||e[65]!==xe||e[66]!==ke||e[67]!==de||e[68]!==P||e[69]!==G||e[70]!==Se?(Oe=s.jsxs("div",{ref:v,className:me,onClick:ce,role:xe,tabIndex:ke,onKeyDown:de,"aria-label":P,children:[G,Se]}),e[62]=v,e[63]=me,e[64]=ce,e[65]=xe,e[66]=ke,e[67]=de,e[68]=P,e[69]=G,e[70]=Se,e[71]=Oe):Oe=e[71];let Ae;e[72]!==$||e[73]!==m||e[74]!==u||e[75]!==a||e[76]!==p||e[77]!==f||e[78]!==r||e[79]!==o||e[80]!==M?(Ae=a?null:s.jsxs("div",{className:"pb-1 pl-2",children:[o,r.length>0?r.map(O=>f(O,0,u??null,p??null,$,void 0,"project",m?.(O))):o?null:s.jsx("div",{className:"py-1 pl-1.5 text-left typography-micro text-muted-foreground/70",children:M("sessions.sidebar.folderItem.emptyFolder")})]}),e[72]=$,e[73]=m,e[74]=u,e[75]=a,e[76]=p,e[77]=f,e[78]=r,e[79]=o,e[80]=M,e[81]=Ae):Ae=e[81];let J;return e[82]!==he||e[83]!==Oe||e[84]!==Ae?(J=s.jsxs("div",{className:he,children:[Oe,Ae]}),e[82]=he,e[83]=Oe,e[84]=Ae,e[85]=J):J=e[85],J},vN=i.memo(wN);function jN(t){return t.stopPropagation()}function SN(t){return t.stopPropagation()}function NN(t){return t.stopPropagation()}function kN(t){return t.stopPropagation()}function CN(t){return t.stopPropagation()}function AN(t){return t.stopPropagation()}function DN(t){return t.stopPropagation()}function IN(t){return t.stopPropagation()}function PN(t){return t.stopPropagation()}function TN(t){return t.stopPropagation()}const RN=t=>{const e=ft.c(15),{sessionId:n,sessionDirectory:r,sessionTitle:o,children:a}=t,c=`session-drag:${n}`;let l;e[0]!==r||e[1]!==n||e[2]!==o?(l={type:"session",sessionId:n,sessionDirectory:r,sessionTitle:o},e[0]=r,e[1]=n,e[2]=o,e[3]=l):l=e[3];let d;e[4]!==c||e[5]!==l?(d={id:c,data:l},e[4]=c,e[5]=l,e[6]=d):d=e[6];const{attributes:f,listeners:m,setNodeRef:u,isDragging:p}=ep(d);let y;e[7]!==m?(y=h=>{h.stopPropagation(),m?.onPointerDown&&m.onPointerDown(h)},e[7]=m,e[8]=y):y=e[8];const g=y,b=p?"opacity-30":void 0;let x;return e[9]!==f||e[10]!==a||e[11]!==g||e[12]!==u||e[13]!==b?(x=s.jsx("div",{ref:u,...f,onPointerDown:g,className:b,children:a}),e[9]=f,e[10]=a,e[11]=g,e[12]=u,e[13]=b,e[14]=x):x=e[14],x},EN=t=>{const e=ft.c(11),{folderId:n,children:r}=t,o=`folder-drop:${n}`;let a;e[0]!==n?(a={type:"folder",folderId:n},e[0]=n,e[1]=a):a=e[1];let c;e[2]!==o||e[3]!==a?(c={id:o,data:a},e[2]=o,e[3]=a,e[4]=c):c=e[4];const{setNodeRef:l,isOver:d}=Zh(c);let f;e[5]!==r||e[6]!==d||e[7]!==l?(f=r(l,d),e[5]=r,e[6]=d,e[7]=l,e[8]=f):f=e[8];let m;return e[9]!==f?(m=s.jsx(s.Fragment,{children:f}),e[9]=f,e[10]=m):m=e[10],m},MN=t=>{const e=ft.c(20),{scopeKey:n,hasFolders:r,onSessionDroppedOnFolder:o,children:a}=t;let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c={activationConstraint:{distance:8}},e[0]=c):c=e[0];const l=ba(vo(ya,c)),[d,f]=i.useState(null),[m,u]=i.useState("Session"),[p,y]=i.useState(null),[g,b]=i.useState(null);if(!n){let j;return e[1]!==a?(j=s.jsx(s.Fragment,{children:a}),e[1]=a,e[2]=j):j=e[2],j}let x;e[3]!==o?(x=j=>{f(null),y(null),b(null);const{active:A,over:D}=j;if(!D)return;const N=A.data.current,B=D.data.current;N?.type==="session"&&N.sessionId&&B?.type==="folder"&&B.folderId&&o(N.sessionId,B.folderId)},e[3]=o,e[4]=x):x=e[4];const h=x;let C,w;e[5]===Symbol.for("react.memo_cache_sentinel")?(C=j=>{const A=j.active.data.current;if(A?.type==="session"&&A.sessionId){f(A.sessionId),u(A.sessionTitle??"Session");const D=j.active.rect.current.initial?.width,N=j.active.rect.current.initial?.height;y(typeof D=="number"?D:null),b(typeof N=="number"?N:null)}},w=()=>{f(null),y(null),b(null)},e[5]=C,e[6]=w):(C=e[5],w=e[6]);let v;e[7]!==g||e[8]!==d||e[9]!==m||e[10]!==p||e[11]!==r?(v=d&&r?s.jsxs("div",{style:{width:p?`${p}px`:"auto",height:g?`${g}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2.5 py-1 shadow-none pointer-events-none",children:[s.jsx(I,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:m})]}):null,e[7]=g,e[8]=d,e[9]=m,e[10]=p,e[11]=r,e[12]=v):v=e[12];let S;e[13]!==v?(S=s.jsx(Ul,{children:v}),e[13]=v,e[14]=S):S=e[14];let k;return e[15]!==a||e[16]!==h||e[17]!==l||e[18]!==S?(k=s.jsxs(wa,{sensors:l,collisionDetection:va,onDragStart:C,onDragCancel:w,onDragEnd:h,children:[a,S]}),e[15]=a,e[16]=h,e[17]=l,e[18]=S,e[19]=k):k=e[19],k},qi=(t,e,n)=>{if(!e)return;const r=o=>{let a=o.session.id===e;for(const c of o.children)a=r(c)||a;return a&&n.add(o.session.id),a};for(const o of t)r(o)},Ur=(t,e)=>{if(!e)return!1;if(t.session.id===e)return!0;for(const n of t.children)if(Ur(n,e))return!0;return!1},Oa=t=>t.children.length===0?"":t.children.map(n=>n.children.length===0?n.session.id:`${n.session.id}:${Oa(n)}`).join("|"),Oo=(t,e,n,r)=>{if(!e)return null;const o=r?"archived":"active";let a=null;const c=l=>{if(`${n}:${o}:${l.session.id}`===e)return a=l.session.id,!0;for(const f of l.children)if(c(f))return!0;return!1};return t.forEach(l=>c(l)),a},Tr=ao()(fc(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}})),FN=50,ON=30,LN=28,zi=(t,e)=>e?t.sessions.some(n=>Ur(n,e)):!1,BN=(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)},_N=(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)},VN=(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)},$N=(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)},pf=t=>{if(t.projectId)return t.projectRepoStatus.has(t.projectId)?t.projectRepoStatus.get(t.projectId):void 0},zN=(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&&pf(t)!==pf(e)||t.pinnedSessionIds!==e.pinnedSessionIds&&BN(e.group,t.pinnedSessionIds,e.pinnedSessionIds)||t.expandedParents!==e.expandedParents&&VN(e.group,t.expandedParents,e.expandedParents)||t.sessionOrderIndex!==e.sessionOrderIndex&&_N(e.group,t.sessionOrderIndex,e.sessionOrderIndex)||t.currentSessionId!==e.currentSessionId&&(zi(t.group,t.currentSessionId)||zi(e.group,e.currentSessionId))||t.editingId!==e.editingId&&(zi(t.group,t.editingId)||zi(e.group,e.editingId))||t.editTitle!==e.editTitle&&(zi(t.group,t.editingId)||zi(e.group,e.editingId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=Oo(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket),r=Oo(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket);if(n||r)return!1}if(t.liveSessionById!==e.liveSessionById&&$N(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 WN(t){const{t:e}=Nt(),{group:n,groupKey:r,projectId:o,hideGroupLabel:a,hasSessionSearchQuery:c,normalizedSessionSearchQuery:l,groupSearchDataByGroup:d,visibleSessionCount:f,collapsedGroups:m,hideDirectoryControls:u,collapsedFolderIds:p,toggleFolderCollapse:y,renameFolder:g,deleteFolder:b,showDeletionDialog:x,setDeleteFolderConfirm:h,renderSessionNode:C,projectRepoStatus:w,lastRepoStatus:v,showMoreGroupSessions:S,resetGroupSessionLimit:k,mobileVariant:j,alwaysShowActions:A,activeProjectId:D,setActiveProjectIdOnly:N,setActiveMainTab:B,setSessionSwitcherOpen:T,openNewSessionDraft:E,addSessionToFolder:_,createFolderAndStartRename:R,renamingFolderId:z,renameFolderDraft:V,setRenameFolderDraft:$,setRenamingFolderId:M,pinnedSessionIds:te,expandedParents:re,sessionOrderIndex:Q,currentSessionId:H,editingId:X,openSidebarMenuKey:oe,prVisualStateByDirectoryBranch:fe,onToggleCollapsedGroup:ve,dragHandleProps:ie,compactBodyPadding:Ne=!1,scrollContainerRef:K}=t,pe=i.useCallback((Ue,Ge)=>{const wt=Q.get(Ue.session.id),Ot=Q.get(Ge.session.id);if(wt!==void 0||Ot!==void 0){if(wt===void 0)return 1;if(Ot===void 0)return-1;if(wt!==Ot)return wt-Ot}return Yi(Ue.session,Ge.session,te)},[te,Q]),L=c?d.get(n):null,se=Tr(Ue=>Ue.displayMode),Z=Vn(Ue=>Ue.foldersMap),je=se==="minimal"&&!Yr(),De=c?!1:m.has(r),Le=u?10:5,Me=Math.max(Le,f??Le),Fe=c?L?.groupMatches===!0:!1,he=c,Ie=i.useMemo(()=>[...he?L?.filteredNodes??[]:n.sessions].sort(pe),[pe,n.sessions,L?.filteredNodes,he]),me=n.folderScopeKey??as(n.directory??null),ce=i.useMemo(()=>me?Z[me]??[]:[],[me,Z]),xe=i.useMemo(()=>{const Ue=new Map,Ge=wt=>{wt.forEach(Ot=>{Ue.set(Ot.session.id,Ot),Ot.children.length>0&&Ge(Ot.children)})};return Ge(Ie),Ue},[Ie]),ke=i.useMemo(()=>ce.map(Ue=>{const Ge=Ue.sessionIds.map(wt=>xe.get(wt)).filter(wt=>!!wt).sort(pe);return{folder:Ue,nodes:Ge}}),[ce,xe,pe]),de=i.useMemo(()=>{const Ue=new Map(ke.map(Dt=>[Dt.folder.id,Dt])),Ge=new Map;for(const{folder:Dt}of ke){if(!Dt.parentId)continue;const bs=Ge.get(Dt.parentId);bs?bs.push(Dt.id):Ge.set(Dt.parentId,[Dt.id])}const wt=new Map,Ot=Dt=>{const bs=wt.get(Dt);if(bs!==void 0)return bs;const fs=Ue.get(Dt);if(!fs)return wt.set(Dt,!1),!1;const os=Ge.get(Dt)??[];if(n.isArchivedBucket&&fs.nodes.length===0){const ps=os.some(Fs=>Ot(Fs));return wt.set(Dt,ps),ps}if(!c||fs.folder.name.toLowerCase().includes(l)||fs.nodes.length>0)return wt.set(Dt,!0),!0;const ln=os.some(ps=>Ot(ps));return wt.set(Dt,ln),ln};return ke.filter(({folder:Dt})=>Ot(Dt.id))},[ke,n.isArchivedBucket,c,l]),P=i.useMemo(()=>new Set(de.flatMap(Ue=>Ue.folder.sessionIds)),[de]),F=i.useMemo(()=>Ie.filter(Ue=>!P.has(Ue.session.id)),[Ie,P]),ue=i.useMemo(()=>de.filter(({folder:Ue})=>!Ue.parentId),[de]),be="project",W=i.useMemo(()=>{const Ue=new Set;return qi(Ie,H,Ue),de.forEach(({nodes:Ge})=>{qi(Ge,H,Ue)}),Ue},[Ie,de,H]),ge=i.useMemo(()=>{const Ue=new Set;return qi(Ie,X,Ue),de.forEach(({nodes:Ge})=>{qi(Ge,X,Ue)}),Ue},[Ie,de,X]),we=i.useMemo(()=>{if(!oe)return null;const Ue=Oo(Ie,oe,be,!!n.isArchivedBucket);if(Ue)return Ue;for(const{nodes:Ge}of de){const wt=Oo(Ge,oe,be,!!n.isArchivedBucket);if(wt)return wt}return null},[oe,Ie,de,n.isArchivedBucket]),G=i.useCallback(Ue=>{const Ge=new WeakMap,wt=Ot=>{Ge.set(Ot,Oa(Ot));for(const Dt of Ot.children)wt(Dt)};return Ue.forEach(wt),Ge},[]),Se=i.useMemo(()=>G(Ie),[G,Ie]),Oe=i.useMemo(()=>{const Ue=new WeakMap;return de.forEach(({nodes:Ge})=>{Ge.forEach(wt=>Ue.set(wt,Oa(wt)))}),Ue},[de]),Ae=i.useCallback(Ue=>Se.get(Ue)??Oe.get(Ue)??"",[Se,Oe]),J=i.useCallback(Ue=>({subtreeContainsActive:W,subtreeContainsEditing:ge,menuOpenSessionId:we,nodeStructureKey:Ae(Ue)}),[W,ge,we,Ae]),O=F.length,ae=n.isArchivedBucket||c?F:F.slice(0,Me),ne=O-ae.length,Be=!n.isArchivedBucket&&!c&&O>Le&&ne===0,Ye=n.isArchivedBucket===!0&&!c&&ae.length>=FN,He=n.isArchivedBucket!==!0&&!c&&ae.length>=ON,Je=Ye||He,nt=n.isArchivedBucket?"archived":"active",xt=Je&&ae.some(Ue=>{if(Ue.children.length===0)return!1;const Ge=`project:${nt}:${Ue.session.id}`;return re.has(Ge)}),bt=i.useRef(null),[_e,Qe]=i.useState(null),[st,pt]=i.useState(0),[,At]=i.useState(0);i.useEffect(()=>{if(!Je)return;const Ue=bt.current;if(!Ue||typeof ResizeObserver>"u")return;const Ge=new ResizeObserver(()=>At(wt=>wt+1));return Ge.observe(Ue),()=>Ge.disconnect()},[Je]),i.useLayoutEffect(()=>{if(!Je){_e!==null&&Qe(null),st!==0&&pt(0);return}const Ue=bt.current;if(!Ue)return;let Ge=_e;const wt=K?.current??null;if(wt&&wt.contains(Ue)){if(Ge=wt,Ge!==_e){Qe(Ge);return}}else if(!Ge||!Ge.contains(Ue)){let Dt=Ue.parentElement;for(;Dt;){const bs=window.getComputedStyle(Dt);if(bs.overflowY==="auto"||bs.overflowY==="scroll"){Ge=Dt;break}Dt=Dt.parentElement}if(Ge!==_e){Qe(Ge);return}}if(!Ge)return;const Ot=Ue.getBoundingClientRect().top-Ge.getBoundingClientRect().top+Ge.scrollTop;pt(Dt=>Math.abs(Dt-Ot)<1?Dt:Ot)});const vt=Je&&_e!==null,kt=tp({count:ae.length,enabled:vt,getScrollElement:()=>_e,initialOffset:()=>_e?.scrollTop??0,estimateSize:()=>LN,overscan:xt?20:8,scrollMargin:st,getItemKey:Ue=>ae[Ue]?.session.id??Ue}),et=i.useCallback(Ue=>{const Ge=[],wt=Ot=>{Ot.forEach(Dt=>{Ge.push(Dt.session),Dt.children.length>0&&wt(Dt.children)})};return wt(Ue),Ge},[]),_t=i.useMemo(()=>et(Ie),[et,Ie]),ns=i.useMemo(()=>{if(!n.isArchivedBucket)return new Map;const Ue=new Map,Ge=new Map;for(const{folder:Ot}of de){if(!Ot.parentId)continue;const Dt=Ge.get(Ot.parentId)??[];Dt.push(Ot.id),Ge.set(Ot.parentId,Dt)}const wt=(Ot,Dt)=>{if(Dt.has(Ot))return[];Dt.add(Ot);const bs=de.find(({folder:qt})=>qt.id===Ot),fs=bs?et(bs.nodes):[],os=Ge.get(Ot)??[];for(const qt of os)fs.push(...wt(qt,Dt));return fs};for(const{folder:Ot}of de)Ue.set(Ot.id,wt(Ot.id,new Set));return Ue},[de,et,n.isArchivedBucket]);if(c&&!Fe&&ue.length===0&&F.length===0)return null;const Kt=o&&w.has(o)?!!w.get(o):v,qe=as(n.directory??null),gt=n.branch?.trim()??null,Xe=qe&>?fe.get(`${qe}::${gt}`)??null:null,jt=!!(Xe&&n.branch),Pt=!Xe&&!n.isMain&&!!n.branch,is=Xe?.visualState??null,Bt=Xe&&Xe.state==="open"&&Xe.checks?e("sessions.sidebar.group.pr.checksPassed",{success:Xe.checks.success,total:Xe.checks.total}):null,Gt=Xe&&Xe.state==="open"&&Xe.checks?[Xe.checks.failure>0?e("sessions.sidebar.group.pr.failingCount",{count:Xe.checks.failure}):null,Xe.checks.pending>0?e("sessions.sidebar.group.pr.pendingCount",{count:Xe.checks.pending}):null].filter(Ue=>!!Ue).join(", "):null,es=Xe&&Xe.state==="open"?Xe.mergeableState==="blocked"||Xe.mergeableState==="dirty"?e("sessions.sidebar.group.pr.conflictsOrBlocked"):Xe.mergeableState==="clean"||Xe.canMerge===!0?e("sessions.sidebar.group.pr.mergeable"):null:null,Wt=Xe&&Xe.state==="open"&&Xe.mergeableState?e("sessions.sidebar.group.pr.mergeState",{state:Xe.mergeableState}):null,Lt=Xe?.base??null,Ut=Xe?.head??null,rs=(()=>{if(!Xe)return n.branch&&hb(n.branch,n.label)?{label:n.branch,color:null}:null;switch(Xe.visualState){case"merged":return{label:e("sessions.sidebar.group.pr.status.merged"),color:"var(--pr-merged)"};case"open":return Xe.canMerge===!0||Xe.mergeableState==="clean"||Xe.checks?.state==="success"?{label:e("sessions.sidebar.group.pr.status.readyToMerge"),color:"var(--pr-open)"}:{label:e("sessions.sidebar.group.pr.status.open"),color:"var(--pr-open)"};case"blocked":return{label:Xe.mergeableState==="dirty"?e("sessions.sidebar.group.pr.status.mergeConflicts"):e("sessions.sidebar.group.pr.status.mergeBlocked"),color:"var(--pr-blocked)"};case"draft":return{label:e("sessions.sidebar.group.pr.status.draft"),color:"var(--pr-draft)"};case"closed":return{label:e("sessions.sidebar.group.pr.status.closed"),color:"var(--pr-closed)"};default:return null}})(),$t=rs?.color??(is?`var(--pr-${is})`:void 0),ls=Ue=>{Ue.preventDefault(),Ue.stopPropagation();const Ge=Xe?.url;Ge&&qr(Ge)},xs=(Ue,Ge,wt)=>{const Ot=de.filter(({folder:fs})=>fs.parentId===Ue.id),Dt=Ot.length>0?s.jsx(s.Fragment,{children:Ot.map(({folder:fs,nodes:os})=>xs(fs,os,wt+1))}):void 0,bs=ns.get(Ue.id)??[];return s.jsx(EN,{folderId:Ue.id,children:(fs,os)=>s.jsx(vN,{folder:Ue,sessions:Ge,subFolderItems:Dt,isCollapsed:c?!1:p.has(Ue.id),onToggle:()=>y(Ue.id),onRename:qt=>{me&&g(me,Ue.id,qt)},onDelete:()=>{if(n.isArchivedBucket){Er.requestDelete({sessions:bs,mode:"session"});return}if(!me)return;if(!x){b(me,Ue.id);return}const qt=de.filter(({folder:ps})=>ps.parentId===Ue.id).length,ln=Ge.length;h({scopeKey:me,folderId:Ue.id,folderName:Ue.name,subFolderCount:qt,sessionCount:ln})},renderSessionNode:C,getRenderExtras:Ae?qt=>({subtreeContainsActive:W,subtreeContainsEditing:ge,menuOpenSessionId:we,nodeStructureKey:Ae(qt),childRenderExtrasFor:J}):void 0,groupDirectory:n.directory,projectId:o,mobileVariant:j,alwaysShowActions:A,isRenaming:z===Ue.id,renameDraft:z===Ue.id?V:void 0,onRenameDraftChange:qt=>$(qt),onRenameSave:()=>{const qt=V.trim();qt&&me&&g(me,Ue.id,qt),M(null),$("")},onRenameCancel:()=>{M(null),$("")},droppableRef:fs,isDropTarget:os,depth:wt,onNewSession:()=>{o&&o!==D&&N(o),B("chat"),j&&T(!1),E({directoryOverride:n.directory,targetFolderId:Ue.id})},onNewSubFolder:wt===0?()=>{me&&R(me,Ue.id)}:void 0,hideActions:!1,archivedBucket:n.isArchivedBucket===!0})},Ue.id)},Ct=()=>ue.map(({folder:Ue,nodes:Ge})=>xs(Ue,Ge,0)),Vt=!!(!n.isMain&&n.worktree),yt=A?Vt?"pr-14":"pr-7":je?Vt?"pr-2 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-2":Vt?"pr-5 group-hover/gh:pr-14 group-focus-within/gh:pr-14":"pr-5",us=s.jsxs(MN,{scopeKey:me,hasFolders:de.length>0,onSessionDroppedOnFolder:(Ue,Ge)=>{me&&_(me,Ge,Ue)},children:[Ct(),Je?s.jsx("div",{ref:bt,children:vt?s.jsx("div",{style:{height:kt.getTotalSize(),position:"relative"},children:kt.getVirtualItems().map(Ue=>{const Ge=ae[Ue.index];return Ge?s.jsx("div",{"data-index":Ue.index,ref:kt.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${Ue.start-st}px)`},children:C(Ge,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:W,subtreeContainsEditing:ge,menuOpenSessionId:we,nodeStructureKey:Ae(Ge),childRenderExtrasFor:J})},Ge.session.id):null})}):ae.map(Ue=>C(Ue,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:W,subtreeContainsEditing:ge,menuOpenSessionId:we,nodeStructureKey:Ae(Ue),childRenderExtrasFor:J}))}):ae.map(Ue=>C(Ue,0,n.directory,o,n.isArchivedBucket===!0,void 0,"project",{subtreeContainsActive:W,subtreeContainsEditing:ge,menuOpenSessionId:we,nodeStructureKey:Ae(Ue),childRenderExtrasFor:J})),O===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,ne>0?s.jsx("button",{type:"button",onClick:()=>S(r,ae.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showMore")}):null,Be?s.jsx("button",{type:"button",onClick:()=>k(r),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:e("sessions.sidebar.group.showFewer")}):null]}),cs=Ne?"pb-2 pl-1":"pb-3 pl-4";return a?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:Te("oc-group-body",cs),children:us})}):s.jsxs("div",{className:"oc-group",children:[s.jsxs("div",{className:Te("group/gh relative flex items-start justify-between gap-1 py-1 min-w-0 rounded-md","cursor-pointer"),onClick:()=>ve(r),role:"button",tabIndex:0,onKeyDown:Ue=>{(Ue.key==="Enter"||Ue.key===" ")&&(Ue.preventDefault(),ve(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:ie?.setActivatorNodeRef,className:Te("min-w-0 flex flex-1 items-start gap-1 overflow-hidden pl-0.5 transition-[padding] cursor-grab active:cursor-grabbing",yt),...ie?.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:jt&&Xe?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center",children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 leading-none align-middle",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(I,{name:"git-branch",className:Te("h-3.5 w-3.5 shrink-0",A?"hidden":"group-hover/gh:hidden"),style:$t?{color:$t}:void 0}),s.jsx("span",{className:Te("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),Xe.url?s.jsxs("button",{type:"button",className:"inline-flex shrink-0 items-center leading-none",onMouseDown:Ue=>Ue.stopPropagation(),onClick:ls,children:["#",Xe.number]}):s.jsxs("span",{className:"inline-flex shrink-0 items-center leading-none",children:["#",Xe.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:[Lt||Ut?s.jsx("div",{className:"text-muted-foreground truncate",children:Lt&&Ut?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Lt}),s.jsx(I,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Ut})]}):s.jsx("span",{children:Lt??Ut??""})}):null,Wt?s.jsx("div",{className:"text-muted-foreground truncate",children:Wt}):null,es||Bt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[es??"",es&&Bt?" • ":"",Bt??"",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(I,{name:"archive",className:Te("h-3.5 w-3.5 shrink-0 text-muted-foreground",A?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:Te("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:So(n.label,l)})]}):!n.isMain||n.worktree?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:[s.jsx(I,{name:"git-branch",className:Te("h-3.5 w-3.5 shrink-0 text-muted-foreground",A?"hidden":"group-hover/gh:hidden"),style:$t?{color:$t}:void 0}),s.jsx("span",{className:Te("text-muted-foreground h-3.5 w-3.5 items-center justify-center",A?"inline-flex":"hidden group-hover/gh:inline-flex"),children:De?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:So(n.label,l)})]}):So(n.label,l)}),Pt&&rs?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.isArchivedBucket?s.jsx(I,{name:"archive",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground"}):!n.isMain||Kt?jt&&Xe?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5 text-muted-foreground",style:$t?{color:$t}: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:[Lt||Ut?s.jsx("div",{className:"text-muted-foreground truncate",children:Lt&&Ut?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:Lt}),s.jsx(I,{name:"arrow-left-long",className:"mx-0.5 inline h-3 w-3 align-[-2px]"}),s.jsx("span",{children:Ut})]}):s.jsx("span",{children:Lt??Ut??""})}):null,Wt?s.jsx("div",{className:"text-muted-foreground truncate",children:Wt}):null,es||Bt?s.jsxs("div",{className:"text-muted-foreground truncate",children:[es??"",es&&Bt?" • ":"",Bt??"",Gt?` (${Gt})`:""]}):null]})})]}):s.jsx(I,{name:"git-branch",className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",style:$t?{color:$t}:void 0}):null,s.jsx("span",{className:Te("min-w-0 truncate text-[11px] font-medium",!rs.color&&"text-muted-foreground/80"),style:rs.color?{color:rs.color}:void 0,children:rs.label})]}):null]})}),n.isArchivedBucket&&_t.length>0?s.jsx("div",{className:Te("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:Ue=>{Ue.stopPropagation(),Er.requestDelete({sessions:_t,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.deleteArchivedInGroupAria",{label:n.label}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteArchivedSessions")})})]})}):null,n.directory&&!n.isMain&&n.worktree?s.jsx("div",{className:Te("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:Ue=>{Ue.stopPropagation(),Er.requestDelete({sessions:_t,mode:"worktree",worktree:n.worktree})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.deleteGroupAria",{label:n.label}),children:s.jsx(I,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.group.actions.deleteWorktree")})})]})}):null,n.directory?s.jsx("div",{className:Te("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:Ue=>{Ue.stopPropagation(),o&&o!==D&&N(o),B("chat"),j&&T(!1),E({directoryOverride:n.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":e("sessions.sidebar.group.actions.newDraftInGroupAria",{label:n.label}),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:e("sessions.sidebar.project.actions.newDraftSession")})})]})}):null]}),De?null:s.jsx("div",{className:Te("oc-group-body",cs),children:us})]})}const UN=i.memo(WN,zN);function HN(t){const e=ft.c(182),{t:n}=Nt(),{hideDirectoryControls:r,showRecentControls:o,handleOpenDirectoryDialog:a,openNewSessionDraft:c,canOpenMultiRun:l,openMultiRunLauncher:d,headerActionIconClass:f,headerActionButtonClass:m,isSessionSearchOpen:u,setIsSessionSearchOpen:p,sessionSearchInputRef:y,sessionSearchQuery:g,setSessionSearchQuery:b,hasSessionSearchQuery:x,searchMatchCount:h,collapseAllProjects:C,expandAllProjects:w,openScheduledTasksDialog:v,selectionModeEnabled:S,onToggleSelectionMode:k}=t,j=Tr(XN),A=Tr(JN),D=Tr(QN),N=Tr(YN),B=Tr(qN),T=Tr(KN);let E;e[0]===Symbol.for("react.memo_cache_sentinel")?(E=Yr(),e[0]=E):E=e[0];const _=!E;if(r)return null;let R;e[1]!==n?(R=n("sessions.sidebar.header.actions.addProject"),e[1]=n,e[2]=R):R=e[2];let z;e[3]!==f?(z=s.jsx(I,{name:"folder-add",className:f}),e[3]=f,e[4]=z):z=e[4];let V;e[5]!==a||e[6]!==m||e[7]!==R||e[8]!==z?(V=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:a,className:m,"aria-label":R,children:z})}),e[5]=a,e[6]=m,e[7]=R,e[8]=z,e[9]=V):V=e[9];let $;e[10]!==n?($=n("sessions.sidebar.header.actions.addProject"),e[10]=n,e[11]=$):$=e[11];let M;e[12]!==$?(M=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:$})}),e[12]=$,e[13]=M):M=e[13];let te;e[14]!==V||e[15]!==M?(te=s.jsxs(Et,{children:[V,M]}),e[14]=V,e[15]=M,e[16]=te):te=e[16];let re;e[17]!==n?(re=n("sessions.sidebar.header.actions.newSession"),e[17]=n,e[18]=re):re=e[18];let Q;e[19]!==f?(Q=s.jsx(I,{name:"chat-new",className:f}),e[19]=f,e[20]=Q):Q=e[20];let H;e[21]!==m||e[22]!==c||e[23]!==re||e[24]!==Q?(H=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:m,"aria-label":re,children:Q})}),e[21]=m,e[22]=c,e[23]=re,e[24]=Q,e[25]=H):H=e[25];let X;e[26]!==n?(X=n("sessions.sidebar.header.actions.newSession"),e[26]=n,e[27]=X):X=e[27];let oe;e[28]!==X?(oe=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:X})}),e[28]=X,e[29]=oe):oe=e[29];let fe;e[30]!==oe||e[31]!==H?(fe=s.jsxs(Et,{children:[H,oe]}),e[30]=oe,e[31]=H,e[32]=fe):fe=e[32];let ve;e[33]!==n?(ve=n("sessions.sidebar.header.actions.newMultiRun"),e[33]=n,e[34]=ve):ve=e[34];const ie=!l;let Ne;e[35]!==f?(Ne=s.jsx(Mg,{className:f}),e[35]=f,e[36]=Ne):Ne=e[36];let K;e[37]!==m||e[38]!==d||e[39]!==ve||e[40]!==ie||e[41]!==Ne?(K=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:d,className:m,"aria-label":ve,disabled:ie,children:Ne})}),e[37]=m,e[38]=d,e[39]=ve,e[40]=ie,e[41]=Ne,e[42]=K):K=e[42];let pe;e[43]!==n?(pe=n("sessions.sidebar.header.actions.newMultiRun"),e[43]=n,e[44]=pe):pe=e[44];let L;e[45]!==pe?(L=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:pe})}),e[45]=pe,e[46]=L):L=e[46];let se;e[47]!==K||e[48]!==L?(se=s.jsxs(Et,{children:[K,L]}),e[47]=K,e[48]=L,e[49]=se):se=e[49];let Z;e[50]!==n?(Z=n("sessions.sidebar.header.actions.scheduledTasks"),e[50]=n,e[51]=Z):Z=e[51];let je;e[52]!==f?(je=s.jsx(I,{name:"calendar-schedule",className:f}),e[52]=f,e[53]=je):je=e[53];let De;e[54]!==m||e[55]!==v||e[56]!==Z||e[57]!==je?(De=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:v,className:m,"aria-label":Z,children:je})}),e[54]=m,e[55]=v,e[56]=Z,e[57]=je,e[58]=De):De=e[58];let Le;e[59]!==n?(Le=n("sessions.sidebar.header.actions.scheduledTasks"),e[59]=n,e[60]=Le):Le=e[60];let Me;e[61]!==Le?(Me=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:Le})}),e[61]=Le,e[62]=Me):Me=e[62];let Fe;e[63]!==De||e[64]!==Me?(Fe=s.jsxs(Et,{children:[De,Me]}),e[63]=De,e[64]=Me,e[65]=Fe):Fe=e[65];let he;e[66]!==fe||e[67]!==se||e[68]!==Fe||e[69]!==te?(he=s.jsxs("div",{className:"flex items-center gap-1.5",children:[te,fe,se,Fe]}),e[66]=fe,e[67]=se,e[68]=Fe,e[69]=te,e[70]=he):he=e[70];let Ie;e[71]!==p?(Ie=()=>p(GN),e[71]=p,e[72]=Ie):Ie=e[72];let me;e[73]!==n?(me=n("sessions.sidebar.header.actions.searchSessions"),e[73]=n,e[74]=me):me=e[74];let ce;e[75]!==f?(ce=s.jsx(I,{name:"search",className:f}),e[75]=f,e[76]=ce):ce=e[76];let xe;e[77]!==m||e[78]!==u||e[79]!==Ie||e[80]!==me||e[81]!==ce?(xe=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Ie,className:m,"aria-label":me,"aria-expanded":u,children:ce})}),e[77]=m,e[78]=u,e[79]=Ie,e[80]=me,e[81]=ce,e[82]=xe):xe=e[82];let ke;e[83]!==n?(ke=n("sessions.sidebar.header.actions.searchSessions"),e[83]=n,e[84]=ke):ke=e[84];let de;e[85]!==ke?(de=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:ke})}),e[85]=ke,e[86]=de):de=e[86];let P;e[87]!==xe||e[88]!==de?(P=s.jsxs(Et,{children:[xe,de]}),e[87]=xe,e[88]=de,e[89]=P):P=e[89];const F=S&&"bg-interactive-hover text-primary";let ue;e[90]!==m||e[91]!==F?(ue=Te(m,F),e[90]=m,e[91]=F,e[92]=ue):ue=e[92];let be;e[93]!==S||e[94]!==n?(be=n(S?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[93]=S,e[94]=n,e[95]=be):be=e[95];let W;e[96]!==f?(W=s.jsx(I,{name:"checkbox-multiple",className:f}),e[96]=f,e[97]=W):W=e[97];let ge;e[98]!==k||e[99]!==S||e[100]!==ue||e[101]!==be||e[102]!==W?(ge=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:ue,"aria-label":be,"aria-pressed":S,children:W})}),e[98]=k,e[99]=S,e[100]=ue,e[101]=be,e[102]=W,e[103]=ge):ge=e[103];let we;e[104]!==S||e[105]!==n?(we=n(S?"sessions.sidebar.header.actions.exitSelection":"sessions.sidebar.header.actions.selectSessions"),e[104]=S,e[105]=n,e[106]=we):we=e[106];let G;e[107]!==we?(G=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:we})}),e[107]=we,e[108]=G):G=e[108];let Se;e[109]!==ge||e[110]!==G?(Se=s.jsxs(Et,{children:[ge,G]}),e[109]=ge,e[110]=G,e[111]=Se):Se=e[111];let Oe;e[112]!==n?(Oe=n("sessions.sidebar.header.actions.sessionDisplayMode"),e[112]=n,e[113]=Oe):Oe=e[113];let Ae;e[114]!==f?(Ae=s.jsx(I,{name:"equalizer-2",className:f}),e[114]=f,e[115]=Ae):Ae=e[115];let J;e[116]!==m||e[117]!==Oe||e[118]!==Ae?(J=s.jsx(Mt,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:m,"aria-label":Oe,children:Ae})})}),e[116]=m,e[117]=Oe,e[118]=Ae,e[119]=J):J=e[119];let O;e[120]!==n?(O=n("sessions.sidebar.header.displayMode.label"),e[120]=n,e[121]=O):O=e[121];let ae;e[122]!==O?(ae=s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:O})}),e[122]=O,e[123]=ae):ae=e[123];let ne;e[124]!==J||e[125]!==ae?(ne=s.jsxs(Et,{children:[J,ae]}),e[124]=J,e[125]=ae,e[126]=ne):ne=e[126];let Be;e[127]!==j||e[128]!==N||e[129]!==n?(Be=_?s.jsxs(s.Fragment,{children:[s.jsxs(ws,{onClick:()=>N("default"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.default")}),j==="default"?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(ws,{onClick:()=>N("minimal"),className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.minimal")}),j==="minimal"?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[127]=j,e[128]=N,e[129]=n,e[130]=Be):Be=e[130];let Ye;e[131]!==D||e[132]!==o||e[133]!==A||e[134]!==n||e[135]!==T||e[136]!==B?(Ye=o?s.jsxs(s.Fragment,{children:[_?s.jsx(Fr,{}):null,s.jsxs(ws,{onClick:B,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showRecent")}),A?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]}),s.jsxs(ws,{onClick:T,className:"flex items-center justify-between",children:[s.jsx("span",{children:n("sessions.sidebar.header.displayMode.showArchived")}),D?s.jsx(I,{name:"check",className:"h-4 w-4 text-primary"}):null]})]}):null,e[131]=D,e[132]=o,e[133]=A,e[134]=n,e[135]=T,e[136]=B,e[137]=Ye):Ye=e[137];let He;e[138]===Symbol.for("react.memo_cache_sentinel")?(He=s.jsx(Fr,{}),e[138]=He):He=e[138];let Je;e[139]===Symbol.for("react.memo_cache_sentinel")?(Je=s.jsx(I,{name:"contract-up-down",className:"h-4 w-4"}),e[139]=Je):Je=e[139];let nt;e[140]!==n?(nt=n("sessions.sidebar.header.displayMode.collapseAll"),e[140]=n,e[141]=nt):nt=e[141];let xt;e[142]!==nt?(xt=s.jsx("span",{children:nt}),e[142]=nt,e[143]=xt):xt=e[143];let bt;e[144]!==C||e[145]!==xt?(bt=s.jsxs(ws,{onClick:C,className:"flex items-center gap-2",children:[Je,xt]}),e[144]=C,e[145]=xt,e[146]=bt):bt=e[146];let _e;e[147]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx(I,{name:"expand-up-down",className:"h-4 w-4"}),e[147]=_e):_e=e[147];let Qe;e[148]!==n?(Qe=n("sessions.sidebar.header.displayMode.expandAll"),e[148]=n,e[149]=Qe):Qe=e[149];let st;e[150]!==Qe?(st=s.jsx("span",{children:Qe}),e[150]=Qe,e[151]=st):st=e[151];let pt;e[152]!==w||e[153]!==st?(pt=s.jsxs(ws,{onClick:w,className:"flex items-center gap-2",children:[_e,st]}),e[152]=w,e[153]=st,e[154]=pt):pt=e[154];let At;e[155]!==Be||e[156]!==Ye||e[157]!==bt||e[158]!==pt?(At=s.jsxs(en,{align:"end",className:"min-w-[160px]",children:[Be,Ye,He,bt,pt]}),e[155]=Be,e[156]=Ye,e[157]=bt,e[158]=pt,e[159]=At):At=e[159];let vt;e[160]!==ne||e[161]!==At?(vt=s.jsxs(tn,{children:[ne,At]}),e[160]=ne,e[161]=At,e[162]=vt):vt=e[162];let kt;e[163]!==P||e[164]!==Se||e[165]!==vt?(kt=s.jsxs("div",{className:"flex items-center gap-1.5",children:[P,Se,vt]}),e[163]=P,e[164]=Se,e[165]=vt,e[166]=kt):kt=e[166];let et;e[167]!==he||e[168]!==kt?(et=s.jsxs("div",{className:"flex h-8 items-center justify-between gap-2",children:[he,kt]}),e[167]=he,e[168]=kt,e[169]=et):et=e[169];let _t;e[170]!==x||e[171]!==u||e[172]!==h||e[173]!==y||e[174]!==g||e[175]!==p||e[176]!==b||e[177]!==n?(_t=u?s.jsxs("div",{className:"pb-1",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:[x?s.jsx("span",{children:h===1?n("sessions.sidebar.header.search.matchCountSingle",{count:h}):n("sessions.sidebar.header.search.matchCountPlural",{count:h})}):s.jsx("span",{}),s.jsx("span",{children:n("sessions.sidebar.header.search.escapeHint")})]}),s.jsxs("div",{className:"relative",children:[s.jsx(I,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:y,value:g,onChange:Kt=>b(Kt.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:Kt=>{Kt.key==="Escape"&&(Kt.stopPropagation(),x?b(""):p(!1))}}),g.length>0?s.jsx("button",{type:"button",onClick:()=>b(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":n("sessions.sidebar.header.search.clear"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null,e[170]=x,e[171]=u,e[172]=h,e[173]=y,e[174]=g,e[175]=p,e[176]=b,e[177]=n,e[178]=_t):_t=e[178];let ns;return e[179]!==et||e[180]!==_t?(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,_t]})}),e[179]=et,e[180]=_t,e[181]=ns):ns=e[181],ns}function GN(t){return!t}function KN(t){return t.toggleArchivedSessions}function qN(t){return t.toggleRecentSection}function YN(t){return t.setDisplayMode}function QN(t){return t.showArchivedSessions}function JN(t){return t.showRecentSection}function XN(t){return t.displayMode}const gf=7;function ZN({sections:t,renderSessionNode:e,currentSessionId:n,editingId:r,openSidebarMenuKey:o,variant:a="section",initialVisibleCount:c=gf,batchSize:l=gf}){const{t:d}=Nt(),[f,m]=i.useState(new Set),[u,p]=i.useState(new Map),y=a==="flat",g=i.useCallback(w=>{p(v=>{if(!v.has(w))return v;const S=new Map(v);return S.delete(w),S})},[]),b=i.useCallback(w=>{g(w),m(v=>{const S=new Set(v);return S.has(w)?S.delete(w):S.add(w),S})},[g]),x=i.useCallback((w,v,S)=>{p(k=>{const j=Math.min(S,v+l),A=new Map(k);return A.set(w,j),A})},[l]),h=i.useCallback(w=>{const v=new Set;qi(w,n,v);const S=new Set;qi(w,r,S);const k=Oo(w,o,"recent",!1),j=new WeakMap,A=N=>{j.set(N,Oa(N)),N.children.forEach(A)};w.forEach(A);const D=N=>({subtreeContainsActive:v,subtreeContainsEditing:S,menuOpenSessionId:k,nodeStructureKey:j.get(N)??"",childRenderExtrasFor:D});return N=>({subtreeContainsActive:v,subtreeContainsEditing:S,menuOpenSessionId:k,nodeStructureKey:j.get(N)??"",childRenderExtrasFor:D})},[n,r,o]),C=t.filter(w=>w.items.length>0);return C.length===0?null:s.jsx("div",{className:Te(y?"space-y-0.5 pb-2":"space-y-2 pb-2 pt-1"),children:C.map(w=>{const v=f.has(w.key),S=Math.max(c,u.get(w.key)??c),k=w.items.slice(0,S),j=w.items.length-k.length,A=!y&&w.items.length>c&&j===0,D=h(k.map(B=>B.node)),N=B=>e(B.node,0,B.groupDirectory,B.projectId,!1,B.secondaryMeta,"recent",D(B.node));return y?s.jsxs("div",{className:"space-y-0.5",children:[k.map(N),j>0?s.jsx("button",{type:"button",onClick:()=>x(w.key,k.length,w.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showMore")}):null]},w.key):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("button",{type:"button",onClick:()=>b(w.key),className:"group flex w-full items-center gap-1 rounded-md px-0.5 py-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-expanded":!v,children:[s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center text-muted-foreground",children:v?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"text-[14px] font-normal text-foreground/95",children:w.title})]}),v?null:s.jsxs("div",{className:Te("space-y-0.5 pl-7"),children:[k.map(N),j>0?s.jsx("button",{type:"button",onClick:()=>x(w.key,k.length,w.items.length),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showMore")}):null,A?s.jsx("button",{type:"button",onClick:()=>g(w.key),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:d("sessions.sidebar.group.showFewer")}):null]})]},w.key)})})}const Fl="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 e2(t){const e=ft.c(14),{onOpenSettings:n,onOpenShortcuts:r,onOpenAbout:o,onOpenUpdate:a,onOpenShareOpinion:c,showRuntimeButtons:l,showUpdateButton:d}=t,f=l===void 0?!0:l,m=d===void 0?!0:d,{t:u}=Nt();let p;e[0]!==o||e[1]!==n||e[2]!==r||e[3]!==f||e[4]!==u?(p=f?s.jsxs(s.Fragment,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Fl,"aria-label":u("sessions.sidebar.footer.actions.settings"),children:s.jsx(I,{name:"settings-3",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.settings")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:Fl,"aria-label":u("sessions.sidebar.footer.actions.shortcuts"),children:s.jsx(I,{name:"question",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.shortcuts")})})]}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:Fl,"aria-label":u("sessions.sidebar.footer.actions.aboutOpenChamber"),children:s.jsx(I,{name:"information",className:"h-4.5 w-4.5"})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:u("sessions.sidebar.footer.actions.aboutOpenChamber")})})]})]}):null,e[0]=o,e[1]=n,e[2]=r,e[3]=f,e[4]=u,e[5]=p):p=e[5];let y;e[6]!==c||e[7]!==a||e[8]!==m||e[9]!==u?(y=m?s.jsx(Ve,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:a,children:u("sessions.sidebar.footer.actions.update")}):s.jsx(Ve,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--primary-base)]/15 bg-[var(--primary-base)]/5 text-[var(--primary-base)]/60 hover:bg-[var(--primary-base)]/10 hover:text-[var(--primary-base)]/75",onClick:c,children:u("sessions.sidebar.footer.actions.shareOpinion")}),e[6]=c,e[7]=a,e[8]=m,e[9]=u,e[10]=y):y=e[10];let g;return e[11]!==p||e[12]!==y?(g=s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-2.5 py-2",children:[p,y]}),e[11]=p,e[12]=y,e[13]=g):g=e[13],g}const t2=t=>{const e=ft.c(58),{id:n,projectLabel:r,projectDescription:o,projectIcon:a,projectColor:c,projectIconImage:l,projectIconBackground:d,isCollapsed:f,isActiveProject:m,isRepo:u,isDesktopShell:p,isStuck:y,hideDirectoryControls:g,alwaysShowActions:b,onToggle:x,onNewSession:h,onNewWorktreeSession:C,onRenameStart:w,onClose:v,sentinelRef:S,children:k,showCreateButtons:j,hideHeader:A,openSidebarMenuKey:D,setOpenSidebarMenuKey:N}=t,B=j===void 0?!0:j,T=A===void 0?!1:A,{t:E}=Nt(),{currentTheme:_}=Qr();let R;e[0]!==n?(R={id:n},e[0]=n,e[1]=R):R=e[1];const{attributes:z,listeners:V,setNodeRef:$,transform:M,transition:te,isDragging:re}=mc(R),Q=i.useRef(!1),H=`project:${n}`,X=D===H,[oe,fe]=i.useState(!1),ve=a?Rc[a]:null,ie=c?Qa[c]??null:null;let Ne;e[2]!==H||e[3]!==N?(Ne=de=>{de&&fe(!1),N(de?H:null)},e[2]=H,e[3]=N,e[4]=Ne):Ne=e[4];const K=Ne;let pe;e[5]!==g||e[6]!==u||e[7]!==v||e[8]!==h||e[9]!==w||e[10]!==B||e[11]!==E?(pe=de=>s.jsxs(s.Fragment,{children:[B&&!u&&!g&&h&&s.jsxs(de,{onClick:h,children:[s.jsx(I,{name:"add",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.newSession")]}),s.jsxs(de,{onClick:w,children:[s.jsx(I,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.session.menu.rename")]}),s.jsxs(de,{onClick:v,className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1.5 h-4 w-4"}),E("sessions.sidebar.project.actions.closeProject")]})]}),e[5]=g,e[6]=u,e[7]=v,e[8]=h,e[9]=w,e[10]=B,e[11]=E,e[12]=pe):pe=e[12];const L=pe,se=r2,Z=i2,je=o2;let De;e[13]===Symbol.for("react.memo_cache_sentinel")?(De=de=>{(de.button===2||de.button===0&&de.ctrlKey)&&(Q.current=!0)},e[13]=De):De=e[13];const Le=De;let Me;e[14]!==x?(Me=()=>{if(Q.current){Q.current=!1;return}x()},e[14]=x,e[15]=Me):Me=e[15];const Fe=Me;let he;e[16]!==M?(he=hc.Transform.toString(M),e[16]=M,e[17]=he):he=e[17];let Ie;e[18]!==he||e[19]!==te?(Ie={transform:he,transition:te},e[18]=he,e[19]=te,e[20]=Ie):Ie=e[20];const me=re&&"opacity-30";let ce;e[21]!==me?(ce=Te("relative",me),e[21]=me,e[22]=ce):ce=e[22];let xe;e[23]!==b||e[24]!==z||e[25]!==_||e[26]!==K||e[27]!==Fe||e[28]!==g||e[29]!==T||e[30]!==ie||e[31]!==n||e[32]!==m||e[33]!==f||e[34]!==oe||e[35]!==p||e[36]!==X||e[37]!==u||e[38]!==y||e[39]!==V||e[40]!==h||e[41]!==C||e[42]!==o||e[43]!==d||e[44]!==l||e[45]!==ve||e[46]!==r||e[47]!==L||e[48]!==S||e[49]!==B||e[50]!==E?(xe=T?null:s.jsxs(s.Fragment,{children:[p&&s.jsx("div",{ref:S,"data-project-id":n,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),s.jsxs(Lc,{open:oe,onOpenChange:fe,children:[s.jsx(Oc,{render:s.jsx("div",{className:Te("w-full text-left group/project select-none"),style:{backgroundColor:p&&y?"transparent":void 0},onContextMenu:de=>{g||(de.preventDefault(),fe(!0))}}),children:s.jsxs("div",{className:"relative flex items-center gap-1 px-0.5 py-0.5",...z,children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onMouseDown:Le,onClick:Fe,...V,className:Te("flex-1 min-w-0 flex items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing transition-[padding]",u&&!g?b?"pr-20":"pr-7 group-hover/project:pr-20 group-focus-within/project:pr-20":b?"pr-14":"pr-7 group-hover/project:pr-14 group-focus-within/project:pr-14"),children:[s.jsxs("span",{className:"inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center",children:[s.jsx("span",{className:Te("h-3.5 w-3.5 items-center justify-center text-muted-foreground",b?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:f?s.jsx(I,{name:"arrow-right-s",className:"h-3.5 w-3.5"}):s.jsx(I,{name:"arrow-down-s",className:"h-3.5 w-3.5"})}),l?s.jsx("span",{className:Te("h-3.5 w-3.5 items-center justify-center overflow-hidden rounded-[3px]",b?"hidden":"inline-flex group-hover/project:hidden group-focus-within/project:hidden"),style:d?{backgroundColor:d}:void 0,children:s.jsx(Ja,{project:{id:n,iconImage:l},options:{themeVariant:_.metadata.variant,iconColor:_.colors.surface.foreground},className:"h-full w-full object-contain",fallback:ve?s.jsx(I,{name:ve,className:"h-3.5 w-3.5",style:ie?{color:ie}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 text-muted-foreground/80",style:ie?{color:ie}:void 0})})}):ve?s.jsx(I,{name:ve,className:Te("h-3.5 w-3.5",b?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:ie?{color:ie}:void 0}):s.jsx(I,{name:"folder",className:Te("h-3.5 w-3.5 text-muted-foreground/80",b?"hidden":"group-hover/project:hidden group-focus-within/project:hidden"),style:ie?{color:ie}:void 0})]}),s.jsx("span",{className:Te("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:Te("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-1",B?"right-7":"right-0.5"),children:[B&&u&&!g&&C?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),C()},className:Te("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground transition-opacity",b?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E("sessions.sidebar.project.actions.newWorktree"),children:s.jsx(I,{name:"node-tree",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E("sessions.sidebar.project.actions.newWorktreeEllipsis")})})]}):null,g?null:s.jsxs(tn,{open:X,onOpenChange:K,children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",X?"opacity-100 pointer-events-auto":b?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E("sessions.sidebar.project.actions.projectMenu"),onPointerDown:Z,onMouseDown:je,onClick:se,children:s.jsx(I,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(en,{align:"end",className:"min-w-[180px]",children:L(ws)})]})]}),B&&h?s.jsx("div",{className:"absolute right-0.5 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),h()},className:Te("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",b?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":E(u?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession"),children:s.jsx(I,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ft,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:E(u?"sessions.sidebar.project.actions.newDraftSession":"sessions.sidebar.project.actions.newSession")})})]})}):null]})}),s.jsx(Mc,{className:"min-w-[180px]",children:L(Fc)})]})]}),e[23]=b,e[24]=z,e[25]=_,e[26]=K,e[27]=Fe,e[28]=g,e[29]=T,e[30]=ie,e[31]=n,e[32]=m,e[33]=f,e[34]=oe,e[35]=p,e[36]=X,e[37]=u,e[38]=y,e[39]=V,e[40]=h,e[41]=C,e[42]=o,e[43]=d,e[44]=l,e[45]=ve,e[46]=r,e[47]=L,e[48]=S,e[49]=B,e[50]=E,e[51]=xe):xe=e[51];let ke;return e[52]!==k||e[53]!==$||e[54]!==ce||e[55]!==xe||e[56]!==Ie?(ke=s.jsxs("div",{ref:$,style:Ie,className:ce,children:[xe,k]}),e[52]=k,e[53]=$,e[54]=ce,e[55]=xe,e[56]=Ie,e[57]=ke):ke=e[57],ke},s2=t=>{const e=ft.c(21),{id:n,disabled:r,children:o}=t,a=r===void 0?!1:r;let c;e[0]!==a||e[1]!==n?(c={id:n,disabled:a},e[0]=a,e[1]=n,e[2]=c):c=e[2];const{listeners:l,setNodeRef:d,setActivatorNodeRef:f,transform:m,transition:u,isDragging:p}=mc(c);let y;e[3]!==l||e[4]!==f?(y={listeners:l,setActivatorNodeRef:f},e[3]=l,e[4]=f,e[5]=y):y=e[5];const g=y;let b;e[6]!==m?(b=hc.Transform.toString(m),e[6]=m,e[7]=b):b=e[7];let x;e[8]!==b||e[9]!==u?(x={transform:b,transition:u},e[8]=b,e[9]=u,e[10]=x):x=e[10];const h=p&&"opacity-50";let C;e[11]!==h?(C=Te("space-y-0.5 rounded-md",h),e[11]=h,e[12]=C):C=e[12];let w;e[13]!==o||e[14]!==g?(w=typeof o=="function"?o(g):o,e[13]=o,e[14]=g,e[15]=w):w=e[15];let v;return e[16]!==d||e[17]!==x||e[18]!==C||e[19]!==w?(v=s.jsx("div",{ref:d,style:x,className:C,children:w}),e[16]=d,e[17]=x,e[18]=C,e[19]=w,e[20]=v):v=e[20],v},n2=i.memo(s2);function r2(t){t.stopPropagation()}function i2(t){t.stopPropagation()}function o2(t){t.stopPropagation()}function a2(t){const{t:e}=Nt(),n=ba(vo(ya,{activationConstraint:{distance:8}}),vo(np,{coordinateGetter:sp})),r=ba(vo(ya,{activationConstraint:{distance:8}})),o=i.useRef(null),a=i.useRef(new Map),c=i.useRef(t.getOrderedGroups);c.current!==t.getOrderedGroups&&(c.current=t.getOrderedGroups,a.current.clear());const l=(d,f)=>{const m=a.current,u=m.get(d);if(u&&u.groups===f)return u.ordered;const p=t.getOrderedGroups(d,f);if(m.set(d,{groups:f,ordered:p}),m.size>256){const y=m.keys().next().value;y!==void 0&&m.delete(y)}return p};return t.sharedSessionsOnly?s.jsxs(Wn,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Te("space-y-1 pb-1 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.hasSharedSessions?null:t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState]}):t.projectSections.length===0?s.jsxs(Wn,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Te("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:[t.topContent,t.emptyState]}):t.sectionsForRender.length===0?s.jsx(Wn,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Te("space-y-1 pb-1 pl-2.5 pr-2",(t.mobileVariant,"")),children:t.searchEmptyState}):s.jsxs(Wn,{ref:o,useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:Te("space-y-1 pb-1 pl-2.5 pr-2 [overflow-anchor:none]",(t.mobileVariant,"")),children:[t.topContent,t.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const d=t.sectionsForRender.find(p=>p.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!d)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const f=d.groups.find(p=>p.isMain&&p.sessions.length>0)??d.groups.find(p=>p.sessions.length>0)??d.groups.find(p=>p.isMain)??d.groups[0];if(!f)return s.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:e("sessions.sidebar.empty.noSessions.title")});const m=d.groups.find(p=>p.isArchivedBucket);return[f,...m&&m.id!==f.id?[m]:[]].map(p=>{const y=`${d.project.id}:${p.id}`,g=p.id===f.id;return s.jsx(i.Fragment,{children:t.renderGroupSessions(p,y,d.project.id,g,null,!0,o)},y)})})()}):s.jsx(s.Fragment,{children:s.jsxs(wa,{sensors:n,collisionDetection:va,onDragEnd:d=>{if(t.isInlineEditing)return;const{active:f,over:m}=d;if(!m||f.id===m.id)return;const u=t.sectionsForRender.findIndex(y=>y.project.id===f.id),p=t.sectionsForRender.findIndex(y=>y.project.id===m.id);u===-1||p===-1||u===p||t.reorderProjects(u,p)},children:[s.jsx($l,{items:t.sectionsForRender.map(d=>d.project.id),strategy:zl,children:t.sectionsForRender.map(d=>{const f=d.project,m=f.id,u=Tm(f.label?.trim()||Oi(f.normalizedPath,t.homeDirectory)||f.normalizedPath),p=Ca(f.normalizedPath,t.homeDirectory),y=t.collapsedProjects.has(m),g=m===t.activeProjectId,b=t.projectRepoStatus.get(m),x=l(m,d.groups),h=x.find(w=>w.isMain)??null,C=h?x.filter(w=>w.id!==h.id):x;return s.jsx(t2,{id:m,projectLabel:u,projectDescription:p,projectIcon:f.icon,projectColor:f.color,projectIconImage:f.iconImage,projectIconBackground:f.iconBackground,isCollapsed:y,isActiveProject:g,isRepo:!!b,isDesktopShell:t.isDesktopShellRuntime,isStuck:t.stuckProjectHeaders.has(m),hideDirectoryControls:t.hideDirectoryControls,mobileVariant:t.mobileVariant,alwaysShowActions:t.alwaysShowActions,onToggle:()=>t.toggleProject(m),onNewSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.mobileVariant&&t.setSessionSwitcherOpen(!1),t.openNewSessionDraft({directoryOverride:f.normalizedPath})},onNewWorktreeSession:()=>{m!==t.activeProjectId&&t.setActiveProjectIdOnly(m),t.setActiveMainTab("chat"),t.openNewWorktreeDialog()},onRenameStart:()=>t.openProjectEditDialog(m),onClose:()=>t.removeProject(m),sentinelRef:w=>{t.projectHeaderSentinelRefs.current.set(m,w)},showCreateButtons:!0,openSidebarMenuKey:t.openSidebarMenuKey,setOpenSidebarMenuKey:t.setOpenSidebarMenuKey,children:y?null:s.jsx("div",{className:"space-y-0 pt-0 pb-0.5 pl-3",children:d.groups.length>0?s.jsxs(wa,{sensors:r,collisionDetection:va,onDragEnd:w=>{if(t.isInlineEditing)return;const{active:v,over:S}=w;if(!S||v.id===S.id)return;const k=C.findIndex(N=>N.id===v.id),j=C.findIndex(N=>N.id===S.id);if(k===-1||j===-1||k===j)return;const A=Bf(C,k,j).map(N=>N.id),D=h?[h.id,...A]:A;t.setGroupOrderByProject(N=>{const B=new Map(N);return B.set(m,D),B})},children:[h?t.renderGroupSessions(h,`${m}:${h.id}`,m,!0,null,void 0,o):null,s.jsx($l,{items:C.map(w=>w.id),strategy:zl,children:C.map(w=>{const v=`${m}:${w.id}`;return s.jsx(n2,{id:w.id,disabled:t.isInlineEditing,children:S=>t.renderGroupSessions(w,v,m,!1,S,void 0,o)},w.id)})}),s.jsx(Ul,{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(Ul,{dropAnimation:null})]})})]})}function l2(t){if(typeof t!="number"||!Number.isFinite(t))return"";const e=new Date(t);if(Number.isNaN(e.getTime()))return"";const n=e.toLocaleString(to(),{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 c2(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 d2(t){const e=t.info.role==="user"?"User":"Assistant",n=l2(t.info.time?.created),r=c2(t),o=n&&r?`${n} (${r})`:n||r;return o?`**${e}**
|
|
192
|
-
|
|
193
|
-
*${o}*`:`**${e}**`}function u2(t){return t.filter(e=>e.type==="text"&&typeof e.text=="string").map(e=>e.text).join("")}function wh(t){const e=d2(t),n=u2(t.parts).trim();return n?`${e}
|
|
194
|
-
|
|
195
|
-
${n}`:""}function vh(t,e){const n="#".repeat(Math.min(e+1,6)),r=t.agent?` — ${t.agent}`:"",o=`${n} Sub-agent: ${t.title}${r}
|
|
196
|
-
|
|
197
|
-
---
|
|
198
|
-
|
|
199
|
-
`,a=t.records.map(wh).filter(Boolean).join(`
|
|
200
|
-
|
|
201
|
-
---
|
|
202
|
-
|
|
203
|
-
`),c=[o+a];for(const l of t.children)c.push(vh(l,e+1));return c.join(`
|
|
204
|
-
|
|
205
|
-
---
|
|
206
|
-
|
|
207
|
-
`)}function f2(t,e,n){const r=e?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
208
|
-
|
|
209
|
-
*Exported on ${o}*
|
|
210
|
-
|
|
211
|
-
---
|
|
212
|
-
|
|
213
|
-
`,c=t.map(wh).filter(Boolean).join(`
|
|
214
|
-
|
|
215
|
-
---
|
|
216
|
-
|
|
217
|
-
`);let l=a+c;if(n&&n.length>0){const d=n.map(f=>vh(f,1)).join(`
|
|
218
|
-
|
|
219
|
-
---
|
|
220
|
-
|
|
221
|
-
`);l+=`
|
|
222
|
-
|
|
223
|
-
---
|
|
224
|
-
|
|
225
|
-
`+d}return l}function m2(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 h2(t,e){const n=await vp(e,t);if(n)return n;if(!Yr())return null;try{const r=await Lo()?.vscode?.saveMarkdown?.({fileName:e,content:t});if(!r||r.saved!==!0)return null;const o=typeof r.path=="string"?r.path.trim():"";return o.length>0?o:null}catch{return null}}async function p2(t){const e=Lo()?.files;if(e?.revealPath)try{return!!(await e.revealPath(t))?.success}catch{return!1}return await jp(t)?!0:ja(t)}function g2(){return Dc()}function x2(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 b2=(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},zn=ao()((t,e)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{e().enabled||t({enabled:!0})},disable:()=>{t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{e().enabled?t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):t({enabled:!0})},toggleSelected:(n,r,o)=>{const a=e(),c=new Set(a.selectedIds);let l=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(c.clear(),l=r,d=null):l===null&&r!==null&&(l=r);const m=o&&o.length>0?[n,...o]:[n];if(c.has(n)){for(const p of m)c.delete(p);d===n&&(d=null)}else{for(const p of m)c.add(p);d=n}c.size===0?t({selectedIds:c,scopeKey:null,anchorId:null}):t({selectedIds:c,scopeKey:l,anchorId:d})},setRange:(n,r,o,a,c)=>{const l=e();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],f=o.indexOf(d),m=o.indexOf(r);if(f<0||m<0)return;const[u,p]=f<=m?[f,m]:[m,f],y=o.slice(u,p+1),g=b2(y,c),x=a!==null&&l.scopeKey!==null&&a!==l.scopeKey?new Set:new Set(l.selectedIds);for(const h of g)x.add(h);t({selectedIds:x,scopeKey:a??l.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){t({selectedIds:new Set,scopeKey:null,anchorId:null});return}t({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{t({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=e();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?t({selectedIds:o,scopeKey:null,anchorId:null}):t({selectedIds:o}))}}));let lc=!1;const cc=new Set;let xf=!1;function y2(){for(const t of cc)t()}function Yc(t){lc!==t&&(lc=t,y2())}function w2(t){t.key==="Shift"&&Yc(!0)}function v2(t){t.key==="Shift"&&Yc(!1)}function j2(){Yc(!1)}function S2(){xf||typeof window>"u"||(xf=!0,window.addEventListener("keydown",w2),window.addEventListener("keyup",v2),window.addEventListener("blur",j2))}function N2(t){return S2(),cc.add(t),()=>{cc.delete(t)}}function k2(){return lc}function C2(){return!1}function A2(){return tt.useSyncExternalStore(N2,k2,C2)}const D2=/^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/,jh=/^g[1-9]\d*$/,yo=(t,e,n,r,o)=>{if(!D2.test(t)||e!==void 0&&!jh.test(e)||!n?.trim()||!r?.trim()||n!==n.trim()||r!==r.trim())return null;if(o===void 0)return{groupSlug:t,runGroup:e,providerID:n,modelID:r,fusion:!1};if(o==="fusion")return{groupSlug:t,runGroup:e,providerID:n,modelID:r,fusion:!0};if(!/^\d+$/.test(o))return null;const a=Number.parseInt(o,10);return!Number.isSafeInteger(a)||a<=0?null:{groupSlug:t,runGroup:e,providerID:n,modelID:r,index:a,fusion:!1}},ga=t=>{if(!t)return null;const e=t.split("/");if(e.length<3||e.length>5)return null;const[n]=e;if(e.length===3)return yo(n,void 0,e[1],e[2],void 0);if(e.length===4){const[,l,d,f]=e;return jh.test(l)?yo(n,l,d,f,void 0):yo(n,void 0,l,d,f)}const[,r,o,a,c]=e;return r===""?yo(n,void 0,o,a,c):yo(n,r,o,a,c)},I2=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("/")},Sh=t=>{const e=ft.c(36),{value:n,onChange:r,className:o,disabled:a,id:c,portalToBody:l}=t,{t:d}=Nt(),f=ss(T2),m=ss(R2),u=ss(E2);let p;e[0]!==f?(p=f(),e[0]=f,e[1]=p):p=e[1];const y=p;let g;e[2]!==y?(g=y.filter(M2),e[2]=y,e[3]=g):g=e[3];const b=g;let x,h;e[4]!==y.length||e[5]!==m?(x=()=>{y.length===0&&m()},h=[y.length,m],e[4]=y.length,e[5]=m,e[6]=x,e[7]=h):(x=e[6],h=e[7]),i.useEffect(x,h);let C,w;e[8]!==u||e[9]!==a||e[10]!==r||e[11]!==b||e[12]!==n?(C=()=>{if(a)return;const T=n.trim();if(T.length>0&&b.some(R=>R.name===T))return;const E=typeof u=="string"&&u.trim().length>0?u.trim():null;if(E&&b.some(R=>R.name===E)){r(E);return}const _=b[0]?.name;_&&r(_)},w=[u,a,r,b,n],e[8]=u,e[9]=a,e[10]=r,e[11]=b,e[12]=n,e[13]=C,e[14]=w):(C=e[13],w=e[14]),i.useEffect(C,w);const v=n.trim().length>0?n:void 0;let S;e[15]!==o?(S=Te("max-w-full typography-meta text-foreground !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 data-[popup-open]:!bg-[var(--interactive-active)]/70",o),e[15]=o,e[16]=S):S=e[16];let k;e[17]!==d?(k=d("multirun.agentSelector.placeholder"),e[17]=d,e[18]=k):k=e[18];let j;e[19]!==k?(j=s.jsx(An,{placeholder:k}),e[19]=k,e[20]=j):j=e[20];let A;e[21]!==c||e[22]!==S||e[23]!==j?(A=s.jsx(Hn,{id:c,size:"lg",className:S,children:j}),e[21]=c,e[22]=S,e[23]=j,e[24]=A):A=e[24];let D;e[25]!==b?(D=b.length>0&&s.jsx(Gl,{children:b.map(F2)}),e[25]=b,e[26]=D):D=e[26];let N;e[27]!==l||e[28]!==D?(N=s.jsx(Gn,{fitContent:!0,portalToBody:l,children:D}),e[27]=l,e[28]=D,e[29]=N):N=e[29];let B;return e[30]!==a||e[31]!==r||e[32]!==v||e[33]!==A||e[34]!==N?(B=s.jsxs(Un,{value:v,onValueChange:r,disabled:a,children:[A,N]}),e[30]=a,e[31]=r,e[32]=v,e[33]=A,e[34]=N,e[35]=B):B=e[35],B};function T2(t){return t.getVisibleAgents}function R2(t){return t.loadAgents}function E2(t){return t.currentAgentName}function M2(t){return Sc(t.mode)}function F2(t){return s.jsx(Rs,{value:t.name,className:"w-auto whitespace-nowrap",children:t.name},t.name)}const Nh="h-7",Io=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,O2=t=>{const e=ft.c(12),{model:n,instanceIndex:r,totalSameModel:o,onRemove:a}=t,c=n.displayName||`${n.providerID}/${n.modelID}`,l=o>1?`${c} (${r})`:c;let d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=Te("flex items-center gap-1.5 px-2 rounded-md bg-interactive-selection/20 border border-border/30",Nh),e[0]=d):d=e[0];let f;e[1]!==n.providerID?(f=s.jsx(Po,{providerId:n.providerID,className:"h-3.5 w-3.5"}),e[1]=n.providerID,e[2]=f):f=e[2];let m;e[3]!==l?(m=s.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:l}),e[3]=l,e[4]=m):m=e[4];let u;e[5]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(I,{name:"close",className:"h-3.5 w-3.5"}),e[5]=u):u=e[5];let p;e[6]!==a?(p=s.jsx("button",{type:"button",onClick:a,className:"text-muted-foreground hover:text-foreground ml-0.5",children:u}),e[6]=a,e[7]=p):p=e[7];let y;return e[8]!==f||e[9]!==m||e[10]!==p?(y=s.jsxs("div",{className:d,children:[f,m,p]}),e[8]=f,e[9]=m,e[10]=p,e[11]=y):y=e[11],y},kh=t=>{const e=ft.c(119),{selectedModels:n,onAdd:r,onRemove:o,onUpdate:a,minModels:c,addButtonLabel:l,showChips:d,maxModels:f,addButtonClassName:m,dropdownSide:u,dropdownClassName:p,containerClassName:y,triggerIcon:g}=t,b=d===void 0?!0:d,x=u===void 0?"top":u,{t:h}=Nt(),C=ss(L2),w=ss(B2),v=Ee(_2),S=Ee(V2),{favoriteModelsList:k,recentModelsList:j}=Fg(),A=Ee($2),D=Ee(z2),[N,B]=i.useState(!1),[T,E]=i.useState(""),[_,R]=i.useState(null),z=i.useRef(null),V=i.useRef(null),$=f===1,M=f===void 0||n.length<f||$;let te;if(e[0]!==n){te=new Map;for(const ae of n){const ne=`${ae.providerID}:${ae.modelID}`;te.set(ne,(te.get(ne)||0)+1)}e[0]=n,e[1]=te}else te=e[1];const re=te;let Q;e[2]!==n?(Q=ae=>n.filter(Be=>Be.providerID===ae.providerID&&Be.modelID===ae.modelID).findIndex(Be=>Be.instanceId===ae.instanceId)+1,e[2]=n,e[3]=Q):Q=e[3];const H=Q;let X,oe;e[4]!==x||e[5]!==N?(X=()=>{if(!N||!V.current)return;const ae=V.current.getBoundingClientRect();if(x==="bottom"){const nt=(window.visualViewport?.height??document.documentElement.clientHeight??window.innerHeight)-ae.bottom-16-112;R(Math.max(160,Math.min(320,nt)));return}let ne=V.current.parentElement;for(;ne&&!(ne.getAttribute("role")==="dialog"||ne.hasAttribute("data-scroll-shadow"));){const He=getComputedStyle(ne);if(He.overflow==="auto"||He.overflow==="hidden"||He.overflowY==="auto"||He.overflowY==="hidden")break;ne=ne.parentElement}const Be=ne?ne.getBoundingClientRect().top:0,Ye=ae.top-Be-16;R(Math.max(150,Math.min(300,Ye)))},oe=[x,N],e[4]=x,e[5]=N,e[6]=X,e[7]=oe):(X=e[6],oe=e[7]),i.useEffect(X,oe);let fe,ve;e[8]!==M||e[9]!==N?(fe=()=>{!M&&N&&(B(!1),E(""))},ve=[M,N],e[8]=M,e[9]=N,e[10]=fe,e[11]=ve):(fe=e[10],ve=e[11]),i.useEffect(fe,ve);let ie,Ne;e[12]!==N?(ie=()=>{if(!N)return;const ae=ne=>{z.current&&!z.current.contains(ne.target)&&(B(!1),E(""))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},Ne=[N],e[12]=N,e[13]=ie,e[14]=Ne):(ie=e[13],Ne=e[14]),i.useEffect(ie,Ne);let K;e[15]!==$||e[16]!==r||e[17]!==a||e[18]!==n.length?(K=ae=>{const ne={providerID:ae.providerID,modelID:ae.modelID,displayName:ae.model.name||ae.modelID,instanceId:Io()};$&&n.length>0&&a?a(0,ne):r(ne),$&&(B(!1),E(""))},e[15]=$,e[16]=r,e[17]=a,e[18]=n.length,e[19]=K):K=e[19];const pe=K;let L;e[20]!==h?(L=h("multirun.modelMultiSelect.search.placeholder"),e[20]=h,e[21]=L):L=e[21];let se;e[22]!==h?(se=h("multirun.modelMultiSelect.search.noResults"),e[22]=h,e[23]=se):se=e[23];let Z;e[24]!==h?(Z=h("multirun.modelMultiSelect.sections.favorites"),e[24]=h,e[25]=Z):Z=e[25];let je;e[26]!==h?(je=h("multirun.modelMultiSelect.sections.recent"),e[26]=h,e[27]=je):je=e[27];let De;e[28]!==h?(De=h("multirun.modelMultiSelect.keyboard.hint"),e[28]=h,e[29]=De):De=e[29];let Le;e[30]!==h?(Le=h("settings.agents.modelSelector.actions.favorite"),e[30]=h,e[31]=Le):Le=e[31];let Me;e[32]!==h?(Me=h("settings.agents.modelSelector.actions.unfavorite"),e[32]=h,e[33]=Me):Me=e[33];let Fe;e[34]!==h?(Fe=h("chat.modelControls.capabilities"),e[34]=h,e[35]=Fe):Fe=e[35];let he;e[36]!==h?(he=h("chat.modelControls.capability.toolCalling"),e[36]=h,e[37]=he):he=e[37];let Ie;e[38]!==h?(Ie=h("chat.modelControls.capability.reasoning"),e[38]=h,e[39]=Ie):Ie=e[39];let me;e[40]!==h?(me=h("chat.modelControls.input"),e[40]=h,e[41]=me):me=e[41];let ce;e[42]!==h?(ce=h("chat.modelControls.output"),e[42]=h,e[43]=ce):ce=e[43];let xe;e[44]!==h?(xe=h("chat.modelControls.costPerMillion"),e[44]=h,e[45]=xe):xe=e[45];let ke;e[46]!==L||e[47]!==se||e[48]!==Z||e[49]!==je||e[50]!==De||e[51]!==Le||e[52]!==Me||e[53]!==Fe||e[54]!==he||e[55]!==Ie||e[56]!==me||e[57]!==ce||e[58]!==xe?(ke={searchPlaceholder:L,noResults:se,favorites:Z,recent:je,keyboardHint:De,favorite:Le,unfavorite:Me,capabilities:Fe,capabilityToolCalling:he,capabilityReasoning:Ie,input:me,output:ce,costPerMillion:xe},e[46]=L,e[47]=se,e[48]=Z,e[49]=je,e[50]=De,e[51]=Le,e[52]=Me,e[53]=Fe,e[54]=he,e[55]=Ie,e[56]=me,e[57]=ce,e[58]=xe,e[59]=ke):ke=e[59];const de=ke;let P;e[60]!==y?(P=Te("relative",y),e[60]=y,e[61]=P):P=e[61];let F;e[62]!==m?(F=Te(Nh,"!border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70",m),e[62]=m,e[63]=F):F=e[63];const ue=!M;let be;e[64]!==N?(be=()=>{B(!N)},e[64]=N,e[65]=be):be=e[65];let W;e[66]!==g?(W=g??s.jsx(I,{name:"add",className:"h-3.5 w-3.5 mr-1"}),e[66]=g,e[67]=W):W=e[67];let ge;e[68]!==l||e[69]!==h?(ge=l??h("multirun.modelMultiSelect.actions.addModel"),e[68]=l,e[69]=h,e[70]=ge):ge=e[70];let we;e[71]!==F||e[72]!==ue||e[73]!==be||e[74]!==W||e[75]!==ge?(we=s.jsxs(Ve,{ref:V,type:"button",variant:"outline",size:"sm",className:F,disabled:ue,onClick:be,children:[W,ge]}),e[71]=F,e[72]=ue,e[73]=be,e[74]=W,e[75]=ge,e[76]=we):we=e[76];let G;e[77]!==_||e[78]!==M||e[79]!==p||e[80]!==x||e[81]!==k||e[82]!==pe||e[83]!==A||e[84]!==S||e[85]!==N||e[86]!==de||e[87]!==re||e[88]!==w||e[89]!==D||e[90]!==C||e[91]!==j||e[92]!==T||e[93]!==v?(G=N?s.jsx("div",{className:Te("absolute left-0 z-50 w-[min(420px,calc(100vw-2rem))] max-w-[calc(100vw-2rem)] flex flex-col overflow-hidden rounded-xl border border-border/50 shadow-lg",x==="top"?"bottom-full mb-1":"top-full mt-1",p),style:{background:"linear-gradient(var(--surface-elevated),var(--surface-elevated)),linear-gradient(var(--surface-background),var(--surface-background))"},children:s.jsx(Og,{providers:C,providerOrder:D,favoriteModels:k,recentModels:j,modelsMetadata:w,hiddenModels:A,searchQuery:T,onSearchQueryChange:E,onSelect:pe,labels:de,selectionCount:ae=>re.get(`${ae.providerID}:${ae.modelID}`)||0,disabled:!M,maxHeightClassName:"flex-1",maxHeightStyle:{maxHeight:_?`${_}px`:"300px"},stickyHeaders:!0,tooltipsEnabled:N,isFavorite:ae=>S(ae.providerID,ae.modelID),onToggleFavorite:ae=>v(ae.providerID,ae.modelID),onEscape:()=>{B(!1),E("")}})}):null,e[77]=_,e[78]=M,e[79]=p,e[80]=x,e[81]=k,e[82]=pe,e[83]=A,e[84]=S,e[85]=N,e[86]=de,e[87]=re,e[88]=w,e[89]=D,e[90]=C,e[91]=j,e[92]=T,e[93]=v,e[94]=G):G=e[94];let Se;e[95]!==P||e[96]!==we||e[97]!==G?(Se=s.jsxs("div",{className:P,ref:z,children:[we,G]}),e[95]=P,e[96]=we,e[97]=G,e[98]=Se):Se=e[98];let Oe;e[99]!==H||e[100]!==re||e[101]!==o||e[102]!==a||e[103]!==C||e[104]!==n||e[105]!==b||e[106]!==h?(Oe=b&&n.length>0&&s.jsx("div",{className:"flex flex-col gap-2 w-full",children:n.map((ae,ne)=>{const Be=`${ae.providerID}:${ae.modelID}`,Ye=re.get(Be)||1,He=H(ae),nt=C.find(Qe=>Qe.id===ae.providerID)?.models?.find(Qe=>Qe.id===ae.modelID),xt=nt?.variants?Object.keys(nt.variants):[],bt=xt.length>0,_e=ae.variant??"__default__";return s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(O2,{model:ae,instanceIndex:He,totalSameModel:Ye,onRemove:()=>o(ne)}),bt&&s.jsxs(Un,{value:_e,onValueChange:Qe=>{if(!a)return;a(ne,{...ae,variant:Qe==="__default__"?void 0:Qe})},children:[s.jsxs(Hn,{size:"chip",className:"px-2 gap-1.5 rounded-md !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground",children:[s.jsx(I,{name:"brain-ai-3",className:Te("h-3.5 w-3.5 flex-shrink-0",_e==="__default__"?"text-muted-foreground":"text-[color:var(--status-info)]")}),s.jsx(An,{placeholder:h("multirun.modelMultiSelect.variant.placeholder"),children:Qe=>Qe==="__default__"?h("multirun.modelMultiSelect.variant.default"):Qe})]}),s.jsxs(Gn,{fitContent:!0,children:[s.jsx(Rs,{value:"__default__",className:"pr-2 [&>span:first-child]:hidden",children:h("multirun.modelMultiSelect.variant.default")}),xt.map(W2)]})]})]},ae.instanceId)})}),e[99]=H,e[100]=re,e[101]=o,e[102]=a,e[103]=C,e[104]=n,e[105]=b,e[106]=h,e[107]=Oe):Oe=e[107];let Ae;e[108]!==Se||e[109]!==Oe?(Ae=s.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[Se,Oe]}),e[108]=Se,e[109]=Oe,e[110]=Ae):Ae=e[110];let J;e[111]!==f||e[112]!==c||e[113]!==n.length||e[114]!==h?(J=c!==void 0&&n.length<c&&s.jsx("p",{className:"typography-micro text-muted-foreground",children:f!==void 0?h("multirun.modelMultiSelect.validation.minToMax",{min:c,max:f}):h("multirun.modelMultiSelect.validation.minOnly",{min:c})}),e[111]=f,e[112]=c,e[113]=n.length,e[114]=h,e[115]=J):J=e[115];let O;return e[116]!==Ae||e[117]!==J?(O=s.jsxs("div",{className:"space-y-2",children:[Ae,J]}),e[116]=Ae,e[117]=J,e[118]=O):O=e[118],O};function L2(t){return t.providers}function B2(t){return t.modelsMetadata}function _2(t){return t.toggleFavoriteModel}function V2(t){return t.isFavoriteModel}function $2(t){return t.hiddenModels}function z2(t){return t.providerOrder}function W2(t){return s.jsx(Rs,{value:t,className:"pr-2 [&>span:first-child]:hidden",children:t},t)}const U2=(t,e,n)=>{const r=t.session.title?.trim()||t.session.id;return`
|
|
226
|
-
|
|
227
|
-
--- RESULT ${n+1}: ${r} ---
|
|
228
|
-
${e.trim()}
|
|
229
|
-
--- END RESULT ${n+1} ---`},bf=(t,e)=>ut.getState().getWorktreeMetadata(t)?.projectDirectory??e,H2=async t=>{const e=t.directory??void 0,n=Lg(t.session.id,e);if(n.length===0&&t.directory){const o=(await Jn.withDirectory(t.directory,()=>Jn.getSdkClient().session.messages({sessionID:t.session.id,directory:t.directory??void 0,limit:50}))).data??[];for(let a=o.length-1;a>=0;a-=1){const c=o[a];if(c.info?.role==="assistant")return _d(c.parts??[]).trim()}return""}for(let r=n.length-1;r>=0;r-=1){const o=n[r];if(o.role==="assistant")return _d(Bg(o.id,e)).trim()}return""};function G2({session:t,open:e,onOpenChange:n}){const{t:r}=Nt(),o=wc(),a=jr($=>$.activeSessions),c=jr($=>$.archivedSessions),l=ss($=>$.providers),d=ss($=>$.currentProviderId),f=ss($=>$.currentModelId),m=ss($=>$.currentAgentName),[u,p]=i.useState(d??""),[y,g]=i.useState(f??""),[b,x]=i.useState(()=>d&&f?[{providerID:d,modelID:f,instanceId:Io()}]:[]),[h,C]=i.useState(""),[w,v]=i.useState(m??""),[S,k]=i.useState([]),[j,A]=i.useState(!1),D=i.useMemo(()=>ga(t.title),[t.title]),N=i.useMemo(()=>{const $=new Map;for(const M of o)$.set(M.id,M);for(const M of a)$.set(M.id,M);for(const M of c)$.set(M.id,M);return t.id&&$.set(t.id,t),Array.from($.values())},[a,c,o,t]);i.useEffect(()=>{if(!e||!D)return;const $=ut.getState().getDirectoryForSession(t.id),M=bf(t.id,$),te=N.map(re=>{const Q=ga(re.title);if(!Q||Q.groupSlug!==D.groupSlug||Q.fusion||(Q.runGroup??null)!==(D.runGroup??null))return null;const H=ut.getState().getDirectoryForSession(re.id)??Mr(re),X=bf(re.id,H);return M&&X&&M!==X?null:{session:re,directory:H,projectDirectory:X}}).filter(re=>re!==null).sort((re,Q)=>(re.session.time?.created??0)-(Q.session.time?.created??0));k(te)},[N,e,D,t.id]);const T=l.find($=>$.id===u)?.models.find($=>$.id===y),E=T?.variants?Object.keys(T.variants):[],_=!!(D&&u&&y&&S.length>0&&!j),R=i.useCallback($=>{x([$]),p($.providerID),g($.modelID),C("")},[]),z=b[0]?.displayName||b[0]?.modelID||r("multirun.fusion.model.placeholder"),V=async()=>{if(!(!D||!u||!y)){A(!0);try{const $=await Promise.all(S.map(oe=>H2(oe))),M=S.map((oe,fe)=>({source:oe,text:$[fe]??""})).filter(oe=>oe.text.trim().length>0);if(M.length===0){le.error(r("multirun.fusion.toast.noOutputs"));return}const te=S[0]?.projectDirectory??S[0]?.directory??null,re=P2(D.groupSlug,u,y,D.runGroup),[Q,H]=await Promise.all([En("session.fusion.visible"),En("session.fusion.instructions")]),X=await ut.getState().createSession(re,te,null);if(!X)throw new Error("Failed to create fusion session");ut.getState().setCurrentSession(X.id,te),n(!1),await Jn.sendMessage({id:X.id,providerID:u,modelID:y,variant:h||void 0,agent:w||void 0,text:Q,additionalParts:[{text:H,synthetic:!0},...M.map((oe,fe)=>({text:U2(oe.source,oe.text,fe),synthetic:!0})),{text:`
|
|
230
|
-
|
|
231
|
-
--- FUSION INPUTS END ---
|
|
232
|
-
Now write the final fused answer.`,synthetic:!0}],directory:te??Jn.getDirectory()})}catch($){console.error("[MultiRunFusion] Failed to start fusion",$),le.error(r("multirun.fusion.toast.failed"))}finally{A(!1)}}};return s.jsx(Ms,{open:e,onOpenChange:n,children:s.jsxs(Es,{className:"max-w-xl overflow-visible",children:[s.jsxs(Gs,{children:[s.jsx(Vs,{children:r("multirun.fusion.title")}),s.jsx(an,{children:r("multirun.fusion.description")})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("div",{className:"max-w-full",children:s.jsx(kh,{selectedModels:b,onAdd:R,onUpdate:($,M)=>R(M),onRemove:()=>{x([]),p(""),g(""),C("")},maxModels:1,addButtonLabel:z,showChips:!1,addButtonClassName:"h-8 w-fit max-w-[min(28rem,calc(100vw-8rem))] justify-start rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5",dropdownSide:"bottom",dropdownClassName:"w-[min(28rem,calc(100vw-8rem))]",triggerIcon:u?s.jsx(Po,{providerId:u,className:"h-3.5 w-3.5 mr-1"}):void 0})}),E.length>0?s.jsxs(Un,{value:h||"__default__",onValueChange:$=>C($==="__default__"?"":$),children:[s.jsxs(Hn,{size:"lg",className:"h-8 w-fit rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] !border-border/80 !bg-[var(--surface-subtle)] hover:!bg-[var(--interactive-hover)]/70 typography-meta font-medium text-foreground px-3 py-1.5",children:[s.jsx(I,{name:"brain-ai-3",className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx(An,{children:$=>$==="__default__"?r("multirun.modelMultiSelect.variant.default"):$})]}),s.jsxs(Gn,{fitContent:!0,portalToBody:!0,children:[s.jsx(Rs,{value:"__default__",children:r("multirun.modelMultiSelect.variant.default")}),E.map($=>s.jsx(Rs,{value:$,children:$},$))]})]}):null,s.jsx(Sh,{value:w,onChange:v,portalToBody:!0,className:"h-8 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] px-3 py-1.5"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-meta font-medium text-foreground",children:r("multirun.fusion.sources.label",{count:S.length})}),s.jsx("div",{className:"max-h-56 space-y-1 overflow-auto rounded-lg border border-[var(--interactive-border)] p-1",children:S.map($=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 typography-meta",children:[s.jsx(Po,{providerId:ga($.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(M=>M.filter(te=>te.session.id!==$.session.id)),className:"text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"h-4 w-4"})})]},$.session.id))})]}),s.jsxs(nr,{children:[s.jsx(Ve,{variant:"ghost",onClick:()=>n(!1),children:r("multirun.fusion.actions.cancel")}),s.jsx(Ve,{onClick:V,disabled:!_,children:r(j?"multirun.fusion.actions.starting":"multirun.fusion.actions.start")})]})]})})}function K2(t){const e=ft.c(7);let n,r,o,a,c;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("path",{d:"M12 4.5v6.25M12 10.75v3.5M12 10.75H7.25A3.25 3.25 0 0 0 4 14v1.25M12 10.75h4.75A3.25 3.25 0 0 1 20 14v1.25",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),r=s.jsx("path",{d:"M9.25 7.25 12 4.5l2.75 2.75",stroke:"currentColor",strokeWidth:"1.65",strokeLinecap:"round",strokeLinejoin:"round"}),o=s.jsx("circle",{cx:"4",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),a=s.jsx("circle",{cx:"12",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),c=s.jsx("circle",{cx:"20",cy:"17.25",r:"1.55",stroke:"currentColor",strokeWidth:"1.65"}),e[0]=n,e[1]=r,e[2]=o,e[3]=a,e[4]=c):(n=e[0],r=e[1],o=e[2],a=e[3],c=e[4]);let l;return e[5]!==t?(l=s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",...t,children:[n,r,o,a,c]}),e[5]=t,e[6]=l):l=e[6],l}const q2=i.memo(function(e){const n=ft.c(22),{archiveLabel:r,deleteLabel:o,buttonSizeClass:a,iconSizeClass:c,onPointerDown:l,onMouseDown:d,onArchive:f,onDelete:m}=e,u=A2(),p=u?o:r;let y;n[0]!==f||n[1]!==m||n[2]!==u?(y=k=>{if(u||k.shiftKey){m(k);return}f(k)},n[0]=f,n[1]=m,n[2]=u,n[3]=y):y=n[3];const g=y,b=u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground";let x;n[4]!==a||n[5]!==b?(x=Te("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",b,a),n[4]=a,n[5]=b,n[6]=x):x=n[6];const h=u?"delete-bin":"archive";let C;n[7]!==c||n[8]!==h?(C=s.jsx(I,{name:h,className:c}),n[7]=c,n[8]=h,n[9]=C):C=n[9];let w;n[10]!==g||n[11]!==p||n[12]!==d||n[13]!==l||n[14]!==x||n[15]!==C?(w=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:x,"aria-label":p,onPointerDown:l,onMouseDown:d,onClick:g,onKeyDown:tk,children:C})}),n[10]=g,n[11]=p,n[12]=d,n[13]=l,n[14]=x,n[15]=C,n[16]=w):w=n[16];let v;n[17]!==p?(v=s.jsx(Ft,{side:"left",sideOffset:8,children:p}),n[17]=p,n[18]=v):v=n[18];let S;return n[19]!==w||n[20]!==v?(S=s.jsxs(Et,{children:[w,v]}),n[19]=w,n[20]=v,n[21]=S):S=n[21],S});function Y2(t){const{t:e}=Nt(),{node:n,depth:r=0,groupDirectory:o,projectId:a,archivedBucket:c=!1,currentSessionId:l,pinnedSessionIds:d,expandedParents:f,hasSessionSearchQuery:m,normalizedSessionSearchQuery:u,notifyOnSubtasks:p,editingId:y,setEditingId:g,editTitle:b,setEditTitle:x,handleSaveEdit:h,handleCancelEdit:C,toggleParent:w,handleSessionSelect:v,handleSessionDoubleClick:S,togglePinnedSession:k,handleShareSession:j,copiedSessionId:A,handleCopyShareUrl:D,handleUnshareSession:N,openSidebarMenuKey:B,setOpenSidebarMenuKey:T,renamingFolderId:E,getFoldersForScope:_,getSessionFolderId:R,removeSessionFromFolder:z,addSessionToFolder:V,createFolderAndStartRename:$,openContextPanelTab:M,handleDeleteSession:te,mobileVariant:re,alwaysShowActions:Q,renderSessionNode:H,secondaryMeta:X,renderContext:oe="project",subtreeContainsActive:fe,subtreeContainsEditing:ve,menuOpenSessionId:ie,childRenderExtrasFor:Ne,liveSessionById:K}=t,pe=!!X?.projectLabel,L=!!X?.branchLabel,se=Tr(We=>We.displayMode),Z=i.useMemo(()=>Yr(),[]),je=se==="minimal"||Z,De=i.useMemo(()=>_a(),[]),Le=i.useContext(_g),Me=Z?"group-hover:opacity-100 group-hover:pointer-events-auto":"group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto",Fe=Z?"group-hover:opacity-0":"group-hover:opacity-0 group-focus-within:opacity-0",he=Z,Ie=!c&&!re,me=je?Z?Ie&&he?"group-hover:pr-18":Ie||he?"group-hover:pr-14":"group-hover:pr-8":"group-hover:pr-2 group-focus-within:pr-2":Z?Ie&&he?"group-hover:pr-18":Ie||he?"group-hover:pr-12":"group-hover:pr-5":Ie?"group-hover:pr-12 group-focus-within:pr-12":"group-hover:pr-5 group-focus-within:pr-5",ce=Ie?"pr-13":"pr-7",xe=i.useRef(!1),[ke,de]=i.useState(!1),P=i.useRef(y);P.current=y;const F=i.useRef(null),ue=i.useRef(h);ue.current=h;const[be,W]=i.useState(b),ge=i.useRef(be);ge.current=be;const we=i.useRef(null),G=i.useRef(null),Se=n.session,Oe=K.get(Se.id)??Se,Ae=as(Se.directory??null)??as(o??null),J=lm(Ae??void 0,{bootstrap:!c}),O=Ec(),ae=zn(We=>We.enabled),ne=zn(i.useCallback(We=>We.selectedIds.has(Se.id),[Se.id])),Be=zn(We=>We.toggleSelected),Ye=zn(We=>We.setRange),He=i.useCallback(We=>{const Xt=[],As=Ps=>{Ps.children.forEach(zs=>{Xt.push(zs.session.id),As(zs)})};return As(We),Xt},[]),[Je,nt]=i.useState(!1),[xt,bt]=i.useState(!0),_e=`${oe}:${c?"archived":"active"}:${Se.id}`,Qe=pm(i.useCallback(We=>!!We.sessionMemoryState.get(Vg(Se.id))?.isZombie,[Se.id])),st=$g(Se.id),pt=zg(Se.id,Ae??void 0),At=l===Se.id,vt=Oe.title||e("sessions.sidebar.session.untitled"),kt=n.children.length>0,et=d.has(Se.id),_t=_e,ns=m?!0:f.has(_t),Kt=!!Oe.parentID,gt=Wg(Se.id)>0&&(!Kt||p),Xe=Oe.time?.updated||Oe.time?.created||Date.now(),jt=pb(Xe),Pt=gb(Xe),is=B===_e,[Bt,Gt]=i.useState(!1),es=is||Bt,Wt=i.useMemo(()=>ga(Oe.title)!==null,[Oe.title]),[Lt,Ut]=i.useState(!1),rs=Z&&oe==="recent"&&!je,$t=Z&&oe==="recent"&&je,ls=i.useMemo(()=>He(n).length,[He,n]),xs=i.useCallback(async We=>{const Xt=[];let As=0;for(const Ps of We)try{await O.ensureSessionRenderable(Ps.session.id);const zs=Vd(J.getState(),Ps.session.id).list,Qs=Ps.session.title||e("sessions.sidebar.session.export.untitledSubagent"),Us=Ps.session.agent,Os=await xs(Ps.children);As+=Os.skipped,Xt.push({title:Qs,agent:Us,records:zs,children:Os.children})}catch{As+=He(Ps).length+1}return{children:Xt,skipped:As}},[He,J,O,e]),Ct=i.useCallback(We=>{We<=0||le.warning(We===1?e("sessions.sidebar.session.export.skippedSubtaskSingle",{count:We}):e("sessions.sidebar.session.export.skippedSubtaskMany",{count:We}))},[e]),Vt=i.useCallback(async We=>{if(!Ae){le.error(e("sessions.sidebar.session.export.nothingToExport"));return}await O.ensureSessionRenderable(Se.id);const Xt=Vd(J.getState(),Se.id).list;if(Xt.length===0){le.error(e("sessions.sidebar.session.export.nothingToExport"));return}let As,Ps=0;if(We&&n.children.length>0){const Os=await xs(n.children);As=Os.children,Ps=Os.skipped}const zs=f2(Xt,Oe.title??null,As),Qs=x2(Oe.title??null),Us=await h2(zs,Qs);if(Us){le.success(e("sessions.sidebar.session.export.success"),{action:{label:e(g2()),onClick:()=>{p2(Us).then(Os=>{Os||le.error(e("sessions.sidebar.session.export.failedRevealPath"))})}}}),Ct(Ps);return}m2(zs,Qs),le.success(e("sessions.sidebar.session.export.success")),Ct(Ps)},[xs,J,n.children,Oe.title,Se.id,Ae,Ct,O,e]),yt=i.useCallback(async()=>{if(n.children.length>0){bt(!0),nt(!0);return}await Vt(!1)},[Vt,n.children.length]),us=i.useCallback(()=>{Ae&&Gr("desktop_open_session_mini_chat_window",{sessionId:Se.id,directory:Ae,apiBaseUrl:Hr(),clientToken:Hl()}).catch(We=>{console.warn("[session-sidebar] failed to open mini chat window",We)})},[Se.id,Ae]);if(i.useEffect(()=>{if(y!==Se.id)return;const We=Xt=>{G.current&&!G.current.contains(Xt.target)&&ue.current(ge.current)};return document.addEventListener("mousedown",We),()=>document.removeEventListener("mousedown",We)},[y,Se.id]),i.useLayoutEffect(()=>{if(y!==Se.id){we.current===Se.id&&(we.current=null);return}we.current!==Se.id&&(we.current=Se.id,W(b))},[y,b,Se.id]),y===Se.id)return s.jsx("div",{className:Te("group relative flex items-center rounded-sm px-1.5 py-1",r>0&&"pl-[20px]"),children:s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[s.jsxs("form",{ref:G,className:"flex w-full items-center gap-2",onSubmit:We=>{We.preventDefault(),h(be)},children:[s.jsx("input",{value:be,onChange:We=>W(We.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:We=>{if(We.stopPropagation(),We.key==="Escape"){C();return}}}),s.jsx("button",{type:"submit","aria-label":e("sessions.sidebar.session.rename.save"),title:e("sessions.sidebar.session.rename.save"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:C,"aria-label":e("sessions.sidebar.session.rename.cancel"),title:e("sessions.sidebar.session.rename.cancel"),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(I,{name:"close",className:"size-4"})})]}),je?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:[kt?s.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:ns?s.jsx(I,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(I,{name:"arrow-right-s",className:"h-3 w-3"})}):null,s.jsx("span",{className:"flex-shrink-0",children:jt}),pe?s.jsx("span",{className:"truncate",children:X?.projectLabel}):null,L?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:X?.branchLabel})]}):null]})})]})},Se.id);const cs=st?.type??"idle",Ue=cs==="busy"||cs==="retry",Ge=pt.length,Ot=Ue||!Ue&>&&!At,Dt=Ue?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")}),bs=!Q&&kt&&(Ot||et),fs=et&&!Ot,os=s.jsx(I,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":e("sessions.sidebar.session.status.pinned")}),qt=Ot||fs?s.jsxs("span",{className:Te("pointer-events-none absolute left-0.5 inline-flex h-3.5 w-3.5 items-center justify-center transition-opacity",je?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2",bs?"opacity-100 group-hover:opacity-0 group-focus-within:opacity-0":""),children:[Ot?Dt:null,fs?os:null]}):null,ln=kt&&!Q&&(Ot||et),ps=kt?s.jsx("span",{role:"button",tabIndex:0,onClick:We=>{We.stopPropagation(),w(_t)},onKeyDown:We=>{(We.key==="Enter"||We.key===" ")&&(We.preventDefault(),We.stopPropagation(),w(_t))},style:{minWidth:14,minHeight:14},className:Te("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",rs?"absolute left-1.5 bottom-1":$t?"relative mr-0.5 shrink-0":Te("absolute left-0.5",je?"top-1/2 -translate-y-1/2":"top-[14.5px] -translate-y-1/2"),!rs&&!$t&&ln?"opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto":""),"aria-label":e(ns?"sessions.sidebar.session.subsessions.collapse":"sessions.sidebar.session.subsessions.expand"),children:ns?s.jsx(I,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(I,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Fs=Qe?s.jsx(I,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Ws=We=>{We&&Gt(!1),T(We?_e:null)},sn=We=>{if(!We&&F.current){const{id:Xt,title:As}=F.current;F.current=null,g(Xt),x(As)}},Dn=We=>{Gt(We)},jn=We=>{We.preventDefault(),We.stopPropagation(),T(is?null:_e)},ye=We=>{We.preventDefault(),We.stopPropagation()},Ze=We=>{We.preventDefault(),We.stopPropagation()},ct=We=>{We.preventDefault(),We.stopPropagation()},It=We=>{We.preventDefault(),We.stopPropagation()},Ht=We=>{We.preventDefault(),We.stopPropagation(),T(null),te(Se,{archivedBucket:c})},mt=We=>{We.preventDefault(),We.stopPropagation(),T(null),te(Se,{archivedBucket:c,hardDelete:!0,skipConfirm:!0})},ms=We=>{We.preventDefault(),We.stopPropagation()},hs=We=>{We.preventDefault(),We.stopPropagation()},Ns=We=>{We.preventDefault(),We.stopPropagation(),Le?.vscode?.executeCommand("openchamber.openSessionInEditor",Se.id,vt)},ys=We=>{if(xe.current){xe.current=!1;return}if(ae){if(We?.preventDefault(),We?.stopPropagation(),We?.shiftKey){const As=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Qs=>Qs.getAttribute("data-session-row")).filter(Qs=>typeof Qs=="string"&&Qs.length>0),Ps=zn.getState().anchorId,zs=new Map;zs.set(Se.id,He(n)),Ye(Ps,Se.id,As,Ae??null,zs);return}Be(Se.id,Ae??null,He(n));return}v(Se.id,Ae,a)},Is=We=>{We.defaultPrevented||We.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||ys(We)},Mn=We=>{(We.button===2||We.button===0&&We.ctrlKey&&!ae)&&(xe.current=!0)},$s=We=>{re&&We.pointerType==="touch"&&de(!0)},hn=We=>{re&&We.pointerType==="touch"&&de(!1)},Fn=({Item:We,Separator:Xt,Sub:As,SubTrigger:Ps,SubContent:zs})=>s.jsxs(s.Fragment,{children:[s.jsxs(We,{onClick:()=>{F.current={id:Se.id,title:vt}},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.rename")]}),s.jsxs(We,{onClick:()=>k(Se.id),className:"[&>svg]:mr-1",children:[et?s.jsx(I,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(I,{name:"pushpin",className:"mr-1 h-4 w-4"}),e(et?"sessions.sidebar.session.menu.unpin":"sessions.sidebar.session.menu.pin")]}),Oe.share?s.jsxs(s.Fragment,{children:[s.jsx(We,{onClick:()=>{Oe.share?.url&&D(Oe.share.url,Se.id)},className:"[&>svg]:mr-1",children:A===Se.id?s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),e("sessions.sidebar.session.menu.copied")]}):s.jsxs(s.Fragment,{children:[s.jsx(I,{name:"file-copy",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.copyLink")]})}),s.jsxs(We,{onClick:()=>N(Se.id),className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.unshare")]})]}):s.jsxs(We,{onClick:()=>j(Oe),className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"share-2",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.share")]}),s.jsxs(We,{onClick:()=>{yt()},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"download",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.exportMarkdown")]}),Wt?s.jsxs(We,{onClick:()=>Ut(!0),className:"[&>svg]:mr-1",children:[s.jsx(K2,{className:"mr-1 h-4 w-4"}),e("sessions.sidebar.session.menu.runFusion")]}):null,Ae&&!c?(()=>{const Qs=_(Ae),Us=R(Ae,Se.id);return s.jsxs(s.Fragment,{children:[s.jsx(Xt,{}),s.jsxs(As,{children:[s.jsxs(Ps,{className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"folder",className:"h-4 w-4"}),e("sessions.sidebar.folders.moveToFolder")]}),s.jsxs(zs,{className:"min-w-[180px]",children:[Qs.length===0?s.jsx(We,{disabled:!0,className:"text-muted-foreground",children:e("sessions.sidebar.folders.none")}):Qs.map(Os=>s.jsxs(We,{onClick:()=>{Us===Os.id?z(Ae,Se.id):V(Ae,Os.id,Se.id)},children:[s.jsx("span",{className:"flex-1 truncate",children:Os.name}),Us===Os.id?s.jsx(I,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Os.id)),s.jsx(Xt,{}),s.jsxs(We,{onClick:()=>{const Os=$(Ae);Os&&V(Ae,Os.id,Se.id)},children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.newFolderEllipsis")]}),Us?s.jsxs(We,{onClick:()=>{z(Ae,Se.id)},className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.folders.removeFromFolder")]}):null]})]})]})})():null,Z?null:s.jsxs(We,{disabled:!Ae,onClick:()=>{Ae&&M(Ae,{mode:"chat",dedupeKey:`session:${Se.id}`,label:vt,sessionTitleFallback:vt})},className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"chat-4",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openInSidePanel")}),s.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:e("sessions.sidebar.session.menu.betaBadge")})]}),De?s.jsxs(We,{disabled:!Ae,onClick:us,className:"[&>svg]:mr-1",children:[s.jsx(I,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:e("sessions.sidebar.session.menu.openMiniChatWindow")})]}):null,s.jsx(Xt,{}),c?null:s.jsxs(We,{className:"[&>svg]:mr-1",onClick:()=>te(Se,{archivedBucket:c}),children:[s.jsx(I,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.archive")]}),s.jsxs(We,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>te(Se,{archivedBucket:c,hardDelete:!0}),children:[s.jsx(I,{name:"delete-bin",className:"mr-1 h-4 w-4"}),e("sessions.sidebar.bulkActions.delete")]})]}),Zn=s.jsx(en,{align:"end",className:"min-w-[180px]",finalFocus:()=>!(E||P.current),children:Fn({Item:ws,Separator:Fr,Sub:Kg,SubTrigger:qg,SubContent:Yg})}),cn=s.jsx(md,{children:s.jsx(hd,{className:"app-region-no-drag z-50",children:s.jsx(pd,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(E||P.current),style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Te($d,"min-w-[180px]"),children:Fn({Item:({className:We,...Xt})=>s.jsx(op,{className:Te(Ug,We),...Xt}),Separator:({className:We,...Xt})=>s.jsx(ap,{className:Te(Hg,We),...Xt}),Sub:lp,SubTrigger:({className:We,children:Xt,...As})=>s.jsxs(cp,{className:Te(Gg,We),...As,children:[Xt,s.jsx(I,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:We,children:Xt,...As})=>s.jsx(md,{children:s.jsx(hd,{className:"app-region-no-drag z-50",children:s.jsx(pd,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:Te($d,We),...As,children:Xt})})})})})})});return s.jsxs(i.Fragment,{children:[s.jsx(RN,{sessionId:Se.id,sessionDirectory:Ae??null,sessionTitle:vt,children:s.jsxs(rp,{open:Bt,onOpenChange:Dn,onOpenChangeComplete:sn,children:[s.jsxs(ip,{render:s.jsx("div",{"data-session-row":Se.id,"data-session-scope":Ae??"","data-session-archived":c?"1":"0",onClick:Is,className:Te("group relative my-0.5 flex cursor-pointer items-center rounded-md py-1 pr-1.5","-ml-3",r>0?"pl-[32px]":"pl-[18px]",At&&!ne&&"bg-primary/10",ne&&"bg-interactive-selection")}),children:[qt,ps,s.jsx("div",{className:"flex min-w-0 flex-1 items-center",children:je?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onPointerDown:$s,onPointerUp:hn,onPointerCancel:hn,onMouseDown:Mn,onClick:We=>ys(We),onDoubleClick:We=>{We.stopPropagation(),S(Se.id,vt)},className:Te("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]",ke&&"bg-interactive-hover/70",Q?Z?me:ce:me),children:s.jsxs("div",{className:Te("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Te("block min-w-0 flex-1 truncate typography-ui-label font-normal",At?"text-primary":"text-foreground"),children:So(vt,u)}),Q?s.jsx("span",{className:"ml-2 flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Pt}):null,Q?null:s.jsx("div",{className:"relative ml-1 flex h-4 min-w-4 flex-shrink-0 items-center justify-end",children:s.jsx("span",{className:Te("whitespace-nowrap text-right text-[0.72rem] text-muted-foreground/75 transition-opacity duration-150",es?"opacity-0":Fe),children:Pt})}),Ge>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(I,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Ge})]}):null]})})}),Z?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:Te("flex items-center gap-3 text-left text-muted-foreground",X?.projectLabel?"justify-between":"justify-start"),children:[X?.projectLabel?s.jsx("div",{className:"min-w-0 truncate",children:X.projectLabel}):null,s.jsx("div",{className:"flex-shrink-0",children:jt})]}),X?.branchLabel?s.jsx("div",{className:"flex items-center gap-3 text-left text-muted-foreground justify-start",children:s.jsx("div",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden",children:s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:X.branchLabel})]})})}):null]})})]}):s.jsxs("button",{type:"button",onPointerDown:$s,onPointerUp:hn,onPointerCancel:hn,onMouseDown:Mn,onClick:We=>ys(We),onDoubleClick:We=>{We.stopPropagation(),S(Se.id,vt)},className:Te("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]",ke&&"bg-interactive-hover/70",Q?Z?me:ce:me),children:[s.jsxs("div",{className:Te("flex w-full items-center min-w-0 flex-1 overflow-hidden","gap-1"),children:[s.jsx("div",{className:Te("block min-w-0 flex-1 truncate typography-ui-label font-normal",At?"text-primary":"text-foreground"),children:So(vt,u)}),Ge>0?s.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:e("sessions.sidebar.session.status.permissionRequired"),"aria-label":e("sessions.sidebar.session.status.permissionRequired"),children:[s.jsx(I,{name:"shield",className:"h-3 w-3"}),s.jsx("span",{className:"leading-none",children:Ge})]}):null]}),je?null:s.jsx("div",{className:"flex items-center justify-between gap-3 text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",style:{fontSize:"calc(var(--text-ui-label) * 0.85)"},children:s.jsxs("div",{className:Te("flex min-w-0 items-center gap-1.5 overflow-hidden",rs&&kt?"pl-4":""),children:[s.jsx("span",{className:"flex-shrink-0",children:jt}),pe?s.jsx("span",{className:"truncate",children:X?.projectLabel}):null,L?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(I,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:X?.branchLabel})]}):null]})})]})}),Fs&&!re?s.jsx("div",{className:Te("absolute top-1/2 -translate-y-1/2 z-10",je?"right-0":"right-[30px]"),children:Fs}):null,s.jsxs("div",{className:Te("absolute right-0 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",es||Q&&!Z?"opacity-100":Te("opacity-0",Me)),children:[Ie?s.jsx(q2,{archiveLabel:e("sessions.sidebar.bulkActions.archive"),deleteLabel:e("sessions.sidebar.bulkActions.delete"),buttonSizeClass:je&&!Q?"h-4 w-4":"h-6 w-6",iconSizeClass:je&&!Q?"h-2.5 w-2.5":"h-3.5 w-3.5",onPointerDown:ct,onMouseDown:It,onArchive:Ht,onDelete:mt}):null,he?s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",je&&!Q?"h-4 w-4":"h-6 w-6"),"aria-label":e("sessions.sidebar.session.actions.openInEditor"),onPointerDown:ms,onMouseDown:hs,onClick:Ns,onKeyDown:We=>We.stopPropagation(),children:s.jsx(I,{name:"external-link",className:Te(je&&!Q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),s.jsx(Ft,{side:"left",sideOffset:8,children:e("sessions.sidebar.session.actions.openInEditor")})]}):null,s.jsxs(tn,{open:is,onOpenChange:Ws,onOpenChangeComplete:sn,children:[s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:Te("inline-flex items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",je&&!Q?es?"h-4 w-4 opacity-100":Te("h-4 w-4 opacity-0",Me):"h-6 w-6 opacity-100"),"aria-label":e("sessions.sidebar.session.menu.label"),onPointerDown:ye,onMouseDown:Ze,onClick:jn,onKeyDown:We=>We.stopPropagation(),children:s.jsx(I,{name:"more-2",className:Te(je&&!Q?"h-2.5 w-2.5":"h-3.5 w-3.5")})})}),Zn]})]})]}),cn]})}),kt&&ns?n.children.map(We=>{const Xt=Ne?Ne(We):{subtreeContainsActive:fe,subtreeContainsEditing:ve,menuOpenSessionId:ie,nodeStructureKey:""};return H(We,r+1,Ae??o,a,c,void 0,oe,Xt)}):null,s.jsx(Ms,{open:Je,onOpenChange:nt,children:s.jsxs(Es,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Gs,{children:[s.jsx(Vs,{children:e("sessions.sidebar.session.export.dialog.title")}),s.jsx(an,{children:ls===1?e("sessions.sidebar.session.export.dialog.descriptionSingle",{count:ls}):e("sessions.sidebar.session.export.dialog.descriptionMany",{count:ls})})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:xt,onChange:We=>bt(We.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),e("sessions.sidebar.session.export.dialog.includeSubtasks")]}),s.jsxs(nr,{children:[s.jsx(Ve,{type:"button",onClick:()=>nt(!1),variant:"outline",size:"sm",children:e("sessions.sidebar.dialogs.cancel")}),s.jsx(Ve,{type:"button",onClick:()=>{nt(!1),Vt(xt)},size:"sm",children:e("sessions.sidebar.session.export.dialog.confirm")})]})]})}),Wt?s.jsx(G2,{session:Oe,open:Lt,onOpenChange:Ut}):null]},Se.id)}const yf=t=>as(t.session.directory??null),Q2=(t,e)=>(t?.projectLabel??null)===(e?.projectLabel??null)&&(t?.branchLabel??null)===(e?.branchLabel??null),J2=t=>{if(!t.openSidebarMenuKey)return null;const e=t.archivedBucket?"archived":"active",n=`${t.renderContext??"project"}:${e}:`;return t.openSidebarMenuKey.startsWith(n)?t.openSidebarMenuKey.slice(n.length):null},sa=t=>t.menuOpenSessionId??J2(t),Wi=(t,e,n)=>e?n.has(t.node.session.id)?!0:Ur(t.node,e):!1,La=(t,e,n,r,o)=>{if(t.session.id!==e.session.id)return!0;const a=o(t);if(n.has(a)!==r.has(a)||t.children.length!==e.children.length)return!0;for(let c=0;c<t.children.length;c+=1)if(La(t.children[c],e.children[c],n,r,o))return!0;return!1},Ch=(t,e,n,r)=>{if(t.session.id!==e.session.id)return!0;const o=t.session.id;if((n.get(o)??t.session)!==(r.get(o)??e.session)||t.children.length!==e.children.length)return!0;for(let a=0;a<t.children.length;a+=1)if(Ch(t.children[a],e.children[a],n,r))return!0;return!1},X2=(t,e)=>{if(t.hasSessionSearchQuery||e.hasSessionSearchQuery)return!1;const n=t.archivedBucket?"archived":"active",r=e.archivedBucket?"archived":"active";return La(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${t.renderContext??"project"}:${n}:${o.session.id}`)||La(t.node,e.node,t.expandedParents,e.expandedParents,o=>`${e.renderContext??"project"}:${r}:${o.session.id}`)},Z2=(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||yf(t.node)!==yf(e.node)||!Q2(t.secondaryMeta,e.secondaryMeta)||t.liveSessionById!==e.liveSessionById&&Ch(t.node,e.node,t.liveSessionById,e.liveSessionById)||t.pinnedSessionIds!==e.pinnedSessionIds&&La(t.node,e.node,t.pinnedSessionIds,e.pinnedSessionIds,n=>n.session.id)||t.expandedParents!==e.expandedParents&&X2(t,e)||t.currentSessionId!==e.currentSessionId&&(Wi(t,t.currentSessionId,t.subtreeContainsActive)||Wi(e,e.currentSessionId,e.subtreeContainsActive))||t.editingId!==e.editingId&&(Wi(t,t.editingId,t.subtreeContainsEditing)||Wi(e,e.editingId,e.subtreeContainsEditing))||t.editTitle!==e.editTitle&&(Wi(t,t.editingId,t.subtreeContainsEditing)||Wi(e,e.editingId,e.subtreeContainsEditing))||t.copiedSessionId!==e.copiedSessionId&&(Ur(t.node,t.copiedSessionId)||Ur(e.node,e.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==e.openSidebarMenuKey){const n=sa(t),r=sa(e);if(Ur(t.node,n)||Ur(e.node,r))return!1}if(t.renamingFolderId!==e.renamingFolderId){const n=sa(t),r=sa(e);if(Ur(t.node,n)||Ur(e.node,r))return!1}return t.setEditingId===e.setEditingId&&t.setEditTitle===e.setEditTitle&&t.handleSaveEdit===e.handleSaveEdit&&t.handleCancelEdit===e.handleCancelEdit&&t.toggleParent===e.toggleParent&&t.handleSessionSelect===e.handleSessionSelect&&t.handleSessionDoubleClick===e.handleSessionDoubleClick&&t.togglePinnedSession===e.togglePinnedSession&&t.handleShareSession===e.handleShareSession&&t.handleCopyShareUrl===e.handleCopyShareUrl&&t.handleUnshareSession===e.handleUnshareSession&&t.setOpenSidebarMenuKey===e.setOpenSidebarMenuKey&&t.getFoldersForScope===e.getFoldersForScope&&t.getSessionFolderId===e.getSessionFolderId&&t.removeSessionFromFolder===e.removeSessionFromFolder&&t.addSessionToFolder===e.addSessionToFolder&&t.createFolderAndStartRename===e.createFolderAndStartRename&&t.openContextPanelTab===e.openContextPanelTab&&t.handleDeleteSession===e.handleDeleteSession&&t.renderSessionNode===e.renderSessionNode},ek=i.memo(Y2,Z2);function tk(t){return t.stopPropagation()}function sk(t){const e=ft.c(71),{t:n}=Nt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t;let d,f,m,u,p,y,g,b,x,h;if(e[0]!==o||e[1]!==n||e[2]!==r){const M=n("sessions.sidebar.session.untitled");u=Ms,x=!!r,e[13]!==o?(h=re=>{re||o(null)},e[13]=o,e[14]=h):h=e[14],m=Es,g=!1,b="max-w-sm gap-5",f=Gs;let te;e[15]!==n||e[16]!==r?.archivedBucket?(te=r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.title"):n("sessions.sidebar.dialogs.archiveSession.title"),e[15]=n,e[16]=r?.archivedBucket,e[17]=te):te=e[17],e[18]!==te?(y=s.jsx(Vs,{children:te}),e[18]=te,e[19]=y):y=e[19],d=an,p=r&&r.descendantCount>0?r.archivedBucket?r.descendantCount===1?n("sessions.sidebar.dialogs.deleteSession.withOneSubtask",{sessionTitle:r.session.title||M,count:r.descendantCount}):n("sessions.sidebar.dialogs.deleteSession.withManySubtasks",{sessionTitle:r.session.title||M,count:r.descendantCount}):r.descendantCount===1?n("sessions.sidebar.dialogs.archiveSession.withOneSubtask",{sessionTitle:r.session.title||M,count:r.descendantCount}):n("sessions.sidebar.dialogs.archiveSession.withManySubtasks",{sessionTitle:r.session.title||M,count:r.descendantCount}):r?.archivedBucket?n("sessions.sidebar.dialogs.deleteSession.single",{sessionTitle:r?.session.title||M}):n("sessions.sidebar.dialogs.archiveSession.single",{sessionTitle:r?.session.title||M}),e[0]=o,e[1]=n,e[2]=r,e[3]=d,e[4]=f,e[5]=m,e[6]=u,e[7]=p,e[8]=y,e[9]=g,e[10]=b,e[11]=x,e[12]=h}else d=e[3],f=e[4],m=e[5],u=e[6],p=e[7],y=e[8],g=e[9],b=e[10],x=e[11],h=e[12];let C;e[20]!==d||e[21]!==p?(C=s.jsx(d,{children:p}),e[20]=d,e[21]=p,e[22]=C):C=e[22];let w;e[23]!==f||e[24]!==y||e[25]!==C?(w=s.jsxs(f,{children:[y,C]}),e[23]=f,e[24]=y,e[25]=C,e[26]=w):w=e[26];let v;e[27]!==c||e[28]!==a?(v=()=>c(!a),e[27]=c,e[28]=a,e[29]=v):v=e[29];const S=!a;let k;e[30]!==a?(k=a?s.jsx(I,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(I,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[30]=a,e[31]=k):k=e[31];let j;e[32]!==n?(j=n("sessions.sidebar.dialogs.neverAsk"),e[32]=n,e[33]=j):j=e[33];let A;e[34]!==k||e[35]!==j||e[36]!==v||e[37]!==S?(A=s.jsxs("button",{type:"button",onClick:v,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":S,children:[k,j]}),e[34]=k,e[35]=j,e[36]=v,e[37]=S,e[38]=A):A=e[38];let D;e[39]!==o?(D=()=>o(null),e[39]=o,e[40]=D):D=e[40];let N;e[41]!==n?(N=n("sessions.sidebar.dialogs.cancel"),e[41]=n,e[42]=N):N=e[42];let B;e[43]!==D||e[44]!==N?(B=s.jsx("button",{type:"button",onClick:D,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:N}),e[43]=D,e[44]=N,e[45]=B):B=e[45];let T;e[46]!==l?(T=()=>{l()},e[46]=l,e[47]=T):T=e[47];let E;e[48]!==n||e[49]!==r?.archivedBucket?(E=r?.archivedBucket?n("sessions.sidebar.bulkActions.delete"):n("sessions.sidebar.bulkActions.archive"),e[48]=n,e[49]=r?.archivedBucket,e[50]=E):E=e[50];let _;e[51]!==T||e[52]!==E?(_=s.jsx("button",{type:"button",onClick:T,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:E}),e[51]=T,e[52]=E,e[53]=_):_=e[53];let R;e[54]!==B||e[55]!==_?(R=s.jsxs("div",{className:"flex items-center gap-2",children:[B,_]}),e[54]=B,e[55]=_,e[56]=R):R=e[56];let z;e[57]!==A||e[58]!==R?(z=s.jsxs(nr,{className:"w-full sm:items-center sm:justify-between",children:[A,R]}),e[57]=A,e[58]=R,e[59]=z):z=e[59];let V;e[60]!==m||e[61]!==g||e[62]!==z||e[63]!==b||e[64]!==w?(V=s.jsxs(m,{showCloseButton:g,className:b,children:[w,z]}),e[60]=m,e[61]=g,e[62]=z,e[63]=b,e[64]=w,e[65]=V):V=e[65];let $;return e[66]!==u||e[67]!==V||e[68]!==x||e[69]!==h?($=s.jsx(u,{open:x,onOpenChange:h,children:V}),e[66]=u,e[67]=V,e[68]=x,e[69]=h,e[70]=$):$=e[70],$}function nk(t){const e=ft.c(57),{t:n}=Nt(),{value:r,setValue:o,showDeletionDialog:a,setShowDeletionDialog:c,onConfirm:l}=t,d=r?.archivedBucket===!0,f=r?.sessionCount??0;let m;e[0]!==d||e[1]!==f||e[2]!==n?(m=n(d?f===1?"sessions.sidebar.dialogs.deleteSession.title":"sessions.sidebar.dialogs.deleteSessions.title":f===1?"sessions.sidebar.dialogs.archiveSession.title":"sessions.sidebar.dialogs.archiveSessions.title"),e[0]=d,e[1]=f,e[2]=n,e[3]=m):m=e[3];const u=m;let p;e[4]!==d||e[5]!==f||e[6]!==n?(p=d?f===1?n("sessions.sidebar.dialogs.deleteSessions.singleDescription",{count:f}):n("sessions.sidebar.dialogs.deleteSessions.pluralDescription",{count:f}):f===1?n("sessions.sidebar.dialogs.archiveSessions.singleDescription",{count:f}):n("sessions.sidebar.dialogs.archiveSessions.pluralDescription",{count:f}),e[4]=d,e[5]=f,e[6]=n,e[7]=p):p=e[7];const y=p,g=!!r;let b;e[8]!==o?(b=$=>{$||o(null)},e[8]=o,e[9]=b):b=e[9];let x;e[10]!==u?(x=s.jsx(Vs,{children:u}),e[10]=u,e[11]=x):x=e[11];let h;e[12]!==y?(h=s.jsx(an,{children:y}),e[12]=y,e[13]=h):h=e[13];let C;e[14]!==x||e[15]!==h?(C=s.jsxs(Gs,{children:[x,h]}),e[14]=x,e[15]=h,e[16]=C):C=e[16];let w;e[17]!==c||e[18]!==a?(w=()=>c(!a),e[17]=c,e[18]=a,e[19]=w):w=e[19];const v=!a;let S;e[20]!==a?(S=a?s.jsx(I,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(I,{name:"checkbox",className:"h-4 w-4 text-primary"}),e[20]=a,e[21]=S):S=e[21];let k;e[22]!==n?(k=n("sessions.sidebar.dialogs.neverAsk"),e[22]=n,e[23]=k):k=e[23];let j;e[24]!==k||e[25]!==w||e[26]!==v||e[27]!==S?(j=s.jsxs("button",{type:"button",onClick:w,className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":v,children:[S,k]}),e[24]=k,e[25]=w,e[26]=v,e[27]=S,e[28]=j):j=e[28];let A;e[29]!==o?(A=()=>o(null),e[29]=o,e[30]=A):A=e[30];let D;e[31]!==n?(D=n("sessions.sidebar.dialogs.cancel"),e[31]=n,e[32]=D):D=e[32];let N;e[33]!==A||e[34]!==D?(N=s.jsx("button",{type:"button",onClick:A,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:D}),e[33]=A,e[34]=D,e[35]=N):N=e[35];let B;e[36]!==l?(B=()=>{l()},e[36]=l,e[37]=B):B=e[37];let T;e[38]!==d||e[39]!==n?(T=n(d?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[38]=d,e[39]=n,e[40]=T):T=e[40];let E;e[41]!==B||e[42]!==T?(E=s.jsx("button",{type:"button",onClick:B,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:T}),e[41]=B,e[42]=T,e[43]=E):E=e[43];let _;e[44]!==N||e[45]!==E?(_=s.jsxs("div",{className:"flex items-center gap-2",children:[N,E]}),e[44]=N,e[45]=E,e[46]=_):_=e[46];let R;e[47]!==j||e[48]!==_?(R=s.jsxs(nr,{className:"w-full sm:items-center sm:justify-between",children:[j,_]}),e[47]=j,e[48]=_,e[49]=R):R=e[49];let z;e[50]!==R||e[51]!==C?(z=s.jsxs(Es,{showCloseButton:!1,className:"max-w-sm gap-5",children:[C,R]}),e[50]=R,e[51]=C,e[52]=z):z=e[52];let V;return e[53]!==g||e[54]!==z||e[55]!==b?(V=s.jsx(Ms,{open:g,onOpenChange:b,children:z}),e[53]=g,e[54]=z,e[55]=b,e[56]=V):V=e[56],V}function rk(t){const e=ft.c(36),{t:n}=Nt(),{value:r,setValue:o,onConfirm:a}=t,c=!!r;let l;e[0]!==o?(l=S=>{S||o(null)},e[0]=o,e[1]=l):l=e[1];let d;e[2]!==n?(d=n("sessions.sidebar.dialogs.deleteFolder.title"),e[2]=n,e[3]=d):d=e[3];let f;e[4]!==d?(f=s.jsx(Vs,{children:d}),e[4]=d,e[5]=f):f=e[5];let m;e[6]!==n||e[7]!==r?(m=r&&(r.subFolderCount>0||r.sessionCount>0)?r.subFolderCount>0?r.subFolderCount===1?n("sessions.sidebar.dialogs.deleteFolder.withOneSubfolder",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withManySubfolders",{folderName:r.folderName,count:r.subFolderCount}):n("sessions.sidebar.dialogs.deleteFolder.withContentsNoSubfolders",{folderName:r.folderName}):n("sessions.sidebar.dialogs.deleteFolder.single",{folderName:r?.folderName??""}),e[6]=n,e[7]=r,e[8]=m):m=e[8];let u;e[9]!==m?(u=s.jsx(an,{children:m}),e[9]=m,e[10]=u):u=e[10];let p;e[11]!==f||e[12]!==u?(p=s.jsxs(Gs,{children:[f,u]}),e[11]=f,e[12]=u,e[13]=p):p=e[13];let y;e[14]!==o?(y=()=>o(null),e[14]=o,e[15]=y):y=e[15];let g;e[16]!==n?(g=n("sessions.sidebar.dialogs.cancel"),e[16]=n,e[17]=g):g=e[17];let b;e[18]!==y||e[19]!==g?(b=s.jsx("button",{type:"button",onClick:y,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:g}),e[18]=y,e[19]=g,e[20]=b):b=e[20];let x;e[21]!==n?(x=n("sessions.sidebar.bulkActions.delete"),e[21]=n,e[22]=x):x=e[22];let h;e[23]!==a||e[24]!==x?(h=s.jsx("button",{type:"button",onClick:a,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:x}),e[23]=a,e[24]=x,e[25]=h):h=e[25];let C;e[26]!==h||e[27]!==b?(C=s.jsxs(nr,{children:[b,h]}),e[26]=h,e[27]=b,e[28]=C):C=e[28];let w;e[29]!==C||e[30]!==p?(w=s.jsxs(Es,{showCloseButton:!1,className:"max-w-sm gap-5",children:[p,C]}),e[29]=C,e[30]=p,e[31]=w):w=e[31];let v;return e[32]!==c||e[33]!==l||e[34]!==w?(v=s.jsx(Ms,{open:c,onOpenChange:l,children:w}),e[32]=c,e[33]=l,e[34]=w,e[35]=v):v=e[35],v}const ik=t=>{const e=ft.c(46),{selectedCount:n,scopeKey:r,scopeFolders:o,archivedBucket:a,onMoveToFolder:c,onCreateFolderAndMove:l,onRemoveFromFolder:d,canRemoveFromFolder:f,onDelete:m,onDone:u}=t,{t:p}=Nt(),y=!!r&&!a;let g;e[0]!==a||e[1]!==p?(g=p(a?"sessions.sidebar.bulkActions.delete":"sessions.sidebar.bulkActions.archive"),e[0]=a,e[1]=p,e[2]=g):g=e[2];const b=g;let x;e[3]!==n||e[4]!==p?(x=p("sessions.sidebar.bulkActions.selectedCount",{count:n}),e[3]=n,e[4]=p,e[5]=x):x=e[5];let h;e[6]!==x?(h=s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:x}),e[6]=x,e[7]=h):h=e[7];let C;e[8]!==y||e[9]!==f||e[10]!==l||e[11]!==c||e[12]!==d||e[13]!==o||e[14]!==p?(C=y?s.jsxs(tn,{children:[s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx(Zs,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":p("sessions.sidebar.bulkActions.moveToFolder"),children:s.jsx(I,{name:"folder",className:"h-4 w-4"})})})}),s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:p("sessions.sidebar.bulkActions.moveToFolder")})})]}),s.jsxs(en,{align:"end",className:"min-w-[180px]",children:[o.length===0?s.jsx(ws,{disabled:!0,className:"text-muted-foreground",children:p("sessions.sidebar.folders.none")}):o.map(z=>s.jsx(ws,{onClick:()=>c(z.id),children:s.jsx("span",{className:"flex-1 truncate",children:z.name})},z.id)),s.jsx(Fr,{}),s.jsxs(ws,{onClick:l,children:[s.jsx(I,{name:"add",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.newFolderEllipsis")]}),f?s.jsxs(ws,{onClick:d,className:"text-destructive focus:text-destructive",children:[s.jsx(I,{name:"close",className:"mr-1 h-4 w-4"}),p("sessions.sidebar.folders.removeFromFolder")]}):null]})]}):null,e[8]=y,e[9]=f,e[10]=l,e[11]=c,e[12]=d,e[13]=o,e[14]=p,e[15]=C):C=e[15];let w;e[16]===Symbol.for("react.memo_cache_sentinel")?(w=Te("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),e[16]=w):w=e[16];let v;e[17]===Symbol.for("react.memo_cache_sentinel")?(v=s.jsx(I,{name:"delete-bin",className:"h-4 w-4"}),e[17]=v):v=e[17];let S;e[18]!==b||e[19]!==m?(S=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:m,className:w,"aria-label":b,children:v})}),e[18]=b,e[19]=m,e[20]=S):S=e[20];let k;e[21]!==b?(k=s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:b})}),e[21]=b,e[22]=k):k=e[22];let j;e[23]!==S||e[24]!==k?(j=s.jsxs(Et,{children:[S,k]}),e[23]=S,e[24]=k,e[25]=j):j=e[25];let A;e[26]!==p?(A=p("sessions.sidebar.header.actions.exitSelection"),e[26]=p,e[27]=A):A=e[27];let D;e[28]===Symbol.for("react.memo_cache_sentinel")?(D=s.jsx(I,{name:"close",className:"h-4 w-4"}),e[28]=D):D=e[28];let N;e[29]!==u||e[30]!==A?(N=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:u,className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":A,children:D})}),e[29]=u,e[30]=A,e[31]=N):N=e[31];let B;e[32]!==p?(B=p("sessions.sidebar.header.actions.exitSelection"),e[32]=p,e[33]=B):B=e[33];let T;e[34]!==B?(T=s.jsx(Ft,{side:"top",sideOffset:4,children:s.jsx("p",{children:B})}),e[34]=B,e[35]=T):T=e[35];let E;e[36]!==N||e[37]!==T?(E=s.jsxs(Et,{children:[N,T]}),e[36]=N,e[37]=T,e[38]=E):E=e[38];let _;e[39]!==E||e[40]!==C||e[41]!==j?(_=s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[C,j,E]}),e[39]=E,e[40]=C,e[41]=j,e[42]=_):_=e[42];let R;return e[43]!==_||e[44]!==h?(R=s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-2.5 py-1.5",children:[h,_]}),e[43]=_,e[44]=h,e[45]=R):R=e[45],R},ok=t=>{const{t:e}=Nt(),{isInlineEditing:n,showDeletionDialog:r,foldersMap:o,addSessionsToFolder:a,removeSessionsFromFolders:c,createFolderAndStartRename:l,archiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:m}=t,u=zn(T=>T.enabled),p=zn(T=>T.selectedIds.size),y=p>0,g=zn(T=>T.selectedIds),b=zn(T=>T.scopeKey),x=i.useCallback(()=>{zn.getState().toggleMode()},[]),h=i.useCallback(()=>{zn.getState().disable()},[]),C=i.useMemo(()=>{if(!y||typeof document>"u")return!1;let T=!1,E=!1;for(const _ of g){const R=document.querySelectorAll(`[data-session-row="${CSS.escape(_)}"]`);for(const z of R)z.getAttribute("data-session-archived")==="1"?E=!0:T=!0}return E&&!T},[y,g]),w=i.useMemo(()=>{if(b)return b;if(!y||typeof document>"u")return null;for(const T of g){const _=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(_&&_.length>0)return _}return null},[y,g,b]),v=i.useMemo(()=>w?o[w]??[]:[],[o,w]),S=i.useMemo(()=>{if(!w||!y)return!1;const T=o[w]??[];for(const E of T)for(const _ of E.sessionIds)if(g.has(_))return!0;return!1},[o,w,y,g]),k=i.useCallback(T=>{!w||!y||a(w,T,Array.from(g))},[a,g,w,y]),j=i.useCallback(()=>{if(!w||!y)return;const T=l(w);T&&a(w,T.id,Array.from(g))},[a,l,g,w,y]),A=i.useCallback(()=>{!w||!y||c(w,Array.from(g))},[c,g,w,y]),D=i.useCallback(async()=>{const T=Array.from(g);if(T.length!==0){if(C){const{deletedIds:E,failedIds:_}=await f(T);E.length>0&&le.success(E.length===1?e("sessions.sidebar.bulkActions.deletedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.deletedPlural",{count:E.length})),_.length>0&&le.error(_.length===1?e("sessions.sidebar.bulkActions.failedDeleteSingle",{count:_.length}):e("sessions.sidebar.bulkActions.failedDeletePlural",{count:_.length}))}else{const{archivedIds:E,failedIds:_}=await d(T);E.length>0&&le.success(E.length===1?e("sessions.sidebar.bulkActions.archivedSingle",{count:E.length}):e("sessions.sidebar.bulkActions.archivedPlural",{count:E.length})),_.length>0&&le.error(_.length===1?e("sessions.sidebar.bulkActions.failedArchiveSingle",{count:_.length}):e("sessions.sidebar.bulkActions.failedArchivePlural",{count:_.length}))}zn.getState().clear()}},[d,C,f,g,e]),N=i.useCallback(()=>{if(!y)return;const T=g.size;if(!r){D();return}m({sessionCount:T,archivedBucket:C})},[C,D,g,r,m,y]),B=i.useCallback(async()=>{m(null),await D()},[D]);return i.useEffect(()=>{if(!u)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=_=>{if(n)return;const R=_.target;if(R&&(R.tagName==="INPUT"||R.tagName==="TEXTAREA"||R.isContentEditable))return;const z=T?_.metaKey:_.ctrlKey;if(_.key==="Escape"){_.preventDefault(),zn.getState().disable();return}if(z&&_.key==="Backspace"){_.preventDefault(),N();return}if(z&&(_.key==="a"||_.key==="A")){const V=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(V.length===0)return;_.preventDefault();const M=zn.getState().scopeKey??V[0]?.getAttribute("data-session-scope")??null,te=Q=>M?Q.getAttribute("data-session-scope")===M:!0,re=V.filter(te).map(Q=>Q.getAttribute("data-session-row")).filter(Q=>typeof Q=="string"&&Q.length>0);if(re.length===0)return;zn.getState().replaceAll(re,M||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[N,n,u]),{selectionModeEnabled:u,hasSelection:y,selectedIdsSize:p,bulkScopeIsArchived:C,derivedSelectionScope:w,bulkScopeFolders:v,bulkCanRemoveFromFolder:S,handleToggleSelectionMode:x,handleExitSelectionMode:h,handleBulkMoveToFolder:k,handleBulkCreateFolderAndMove:j,handleBulkRemoveFromFolder:A,handleBulkDelete:N,confirmBulkDelete:B}},ak=2880*60*1e3,lk=t=>!!t.parentID,ck=t=>!!t.time?.archived,dc=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},dk=t=>[...t].sort((e,n)=>dc(n)-dc(e)),uk=(t,e=Date.now())=>{const n=e-ak,r=t.filter(o=>ck(o)||lk(o)?!1:dc(o)>=n);return dk(r)},wf="openchamber.shareOpinionToast.dismissed.v2",na="oc.sessions.projectCollapse",vf="oc.sessions.groupOrder",jf="oc.sessions.groupCollapse",Sf="oc.sessions.activeSessionByProject",Ol="oc.sessions.expandedParents.v2",fk="oc.sessions.expandedParents",mk="oc.sessions.pinned",hk=(t,e,n)=>{const r=new Set;for(const o of t){const a=as(o.path)?.toLowerCase();a&&r.add(a)}if(n?.includeWorktrees===!1)return r;for(const o of e.values())for(const a of o){const c=as(a.path)?.toLowerCase();c&&r.add(c)}return r},pk=(t,e,n)=>{if(t.time?.archived)return!0;const r=as(Mr(t))?.toLowerCase();return r?e.size===0?n?.allowEmptyDirectorySet??!0:e.has(r):n?.allowUnknownDirectory??!0},gk=5*6e4,Nf=new Set,Pr=t=>{const e=i.useRef(t);return e.current=t,i.useCallback((...n)=>e.current(...n),[])},kf=({mobileVariant:t=!1,onSessionSelected:e,allowReselect:n=!1,hideDirectoryControls:r=!1,showOnlyMainWorkspace:o=!1})=>{const{t:a}=Nt(),[c,l]=i.useState(!1),[d,f]=i.useState(""),m=i.useRef(null),u=i.useRef(null),p=i.useRef(new Set),[y,g]=i.useState(null),[b,x]=i.useState(""),[h,C]=i.useState(null),[w,v]=i.useState(new Set),S=i.useMemo(()=>Hi(),[]),[k,j]=i.useState(new Set),[A,D]=i.useState(new Map),[N,B]=i.useState(new Map),T=Ee(ee=>ee.isNewWorktreeDialogOpen),E=Ee(ee=>ee.setNewWorktreeDialogOpen),[_,R]=i.useState(!1),[z,V]=i.useState(!1),[$,M]=i.useState(null),[te,re]=i.useState(null),[Q,H]=i.useState(""),[X,oe]=i.useState(null),[fe,ve]=i.useState(null),[ie,Ne]=i.useState(null),K=fl(ee=>ee.ids),pe=fl(ee=>ee.setIds),L=fl(ee=>ee.toggle),[se,Z]=i.useState(()=>{try{const ee=Hi().getItem(jf);if(!ee)return new Set;const at=JSON.parse(ee);return new Set(Array.isArray(at)?at.filter(it=>typeof it=="string"):[])}catch{return new Set}}),[je,De]=i.useState(()=>{try{const ee=Hi().getItem(vf);if(!ee)return new Map;const at=JSON.parse(ee),it=new Map;return Object.entries(at).forEach(([St,zt])=>{Array.isArray(zt)&&it.set(St,zt.filter(Bs=>typeof Bs=="string"))}),it}catch{return new Map}}),[Le,Me]=i.useState(()=>{try{const ee=Hi().getItem(Sf);if(!ee)return new Map;const at=JSON.parse(ee),it=new Map;return Object.entries(at).forEach(([St,zt])=>{typeof zt=="string"&&zt.length>0&&it.set(St,zt)}),it}catch{return new Map}}),[Fe,he]=i.useState(new Map),Ie=i.useRef(new Map),me=i.useRef(0),ce=Ys(ee=>ee.homeDirectory),xe=Ys(ee=>ee.currentDirectory),ke=Ys(ee=>ee.setDirectory),de=Ss(ee=>ee.projects),P=Ss(ee=>ee.activeProjectId),F=Ss(ee=>ee.removeProject),ue=Ss(ee=>ee.setActiveProjectIdOnly),be=Ss(ee=>ee.updateProjectMeta),W=Ss(ee=>ee.reorderProjects),ge=Ee(ee=>ee.setActiveMainTab),we=Ee(ee=>ee.openContextPanelTab),G=Ee(ee=>ee.setSettingsDialogOpen),Se=Ee(ee=>ee.toggleHelpDialog),Oe=Ee(ee=>ee.setAboutDialogOpen),Ae=Ee(ee=>ee.setSessionSwitcherOpen),J=Ee(ee=>ee.setScheduledTasksDialogOpen),O=Ee(ee=>ee.openMultiRunLauncher),ae=Ee(ee=>ee.notifyOnSubtasks),ne=Ee(ee=>ee.showDeletionDialog),Be=Ee(ee=>ee.setShowDeletionDialog),Ye=Ya(d,120),He=i.useMemo(()=>Ye.trim().toLowerCase(),[Ye]),Je=He.length>0,nt=Vn(ee=>ee.collapsedFolderIds),xt=Vn(ee=>ee.foldersMap),bt=Vn(ee=>ee.getFoldersForScope),_e=Vn(ee=>ee.createFolder),Qe=Vn(ee=>ee.renameFolder),st=Vn(ee=>ee.deleteFolder),pt=Vn(ee=>ee.addSessionToFolder),At=Vn(ee=>ee.addSessionsToFolder),vt=Vn(ee=>ee.removeSessionFromFolder),kt=Vn(ee=>ee.removeSessionsFromFolders),et=Vn(ee=>ee.toggleFolderCollapse),_t=Vn(ee=>ee.cleanupSessions),ns=Vn(ee=>ee.getSessionFolderId);HS({isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchContainerRef:m});const Kt=dm(),qe=Ec(),gt=wc(),Xe=i.useMemo(()=>Yr(),[]),jt=jr(ee=>ee.hasLoaded),Pt=jr(ee=>ee.activeSessions),is=jr(ee=>ee.archivedSessions),Bt=ut(ee=>ee.currentSessionId),Gt=ut(ee=>!!ee.newSessionDraft?.open),es=ut(ee=>ee.setCurrentSession),Wt=ut(ee=>ee.updateSessionTitle),Lt=ut(ee=>ee.shareSession),Ut=ut(ee=>ee.unshareSession),rs=ut(ee=>ee.worktreeMetadata),$t=ut(ee=>ee.availableWorktreesByProject),ls=ut(ee=>ee.openNewSessionDraft),xs=i.useCallback(ee=>{ls(ee),Xe&&window.dispatchEvent(new CustomEvent("openchamber:navigate",{detail:{view:"chat"}}))},[Xe,ls]),Ct=jo(Wl(ee=>({checkForUpdates:ee.checkForUpdates,available:ee.available,runtimeType:ee.runtimeType,info:ee.info,downloading:ee.downloading,downloaded:ee.downloaded,progress:ee.progress,error:ee.error,downloadUpdate:ee.downloadUpdate,restartToUpdate:ee.restartToUpdate}))),Vt=i.useMemo(()=>hk(de,$t,{includeWorktrees:!Xe}),[$t,Xe,de]),yt=i.useMemo(()=>{const ee=new Map(gt.map(St=>[St.id,St])),at=Pt.map(St=>{const zt=ee.get(St.id);return zt?Qg(zt,St):St}),it=new Set(at.map(St=>St.id));return gt.forEach(St=>{it.has(St.id)||at.push(St)}),at.filter(St=>pk(St,Vt,{allowUnknownDirectory:!Xe,allowEmptyDirectorySet:!Xe}))},[Pt,Xe,Vt,gt]),us=i.useMemo(()=>gt.map(ee=>{const at=as(ee.directory??null)??"";return`${ee.id}:${ee.title??""}:${ee.time?.archived?1:0}:${at}`}).join("|"),[gt]),cs=i.useRef(gt);i.useEffect(()=>{cs.current=gt},[us,gt]);const Ue=i.useMemo(()=>new Map(gt.map(ee=>[ee.id,ee])),[gt]),Ge=i.useMemo(()=>de.map(ee=>`${ee.id}:${as(ee.path)??""}`).join("|"),[de]),wt=i.useRef(!1);i.useEffect(()=>{wt.current||(wt.current=!0,ka(cs.current))},[]);const Ot=i.useRef("");i.useEffect(()=>{let ee=!1;const at=async()=>{const it=Ss.getState().projects;if(it.length===0)return;const St=new Map,zt=[],Bs=3;let on=0;const yn=Array.from({length:Bs},async()=>{for(;;){const kn=on;if(on+=1,kn>=it.length)return;const Cn=it[kn],_n=as(Cn.path);if(_n)try{if(!(wn.getState().directories.get(_n)?.isGitRepo??await gm(_n)))continue;const ho=await Xg({id:Cn.id,path:_n});if(ee||ho.length===0)continue;St.set(_n,ho),zt.push(...ho)}catch{}}});await Promise.all(yn),!ee&&ut.setState({availableWorktrees:zt,availableWorktreesByProject:St})};if(Ot.current!==Ge)return Ot.current=Ge,at(),()=>{ee=!0}},[Ge]),i.useEffect(()=>{let ee=null;const at=xh(it=>{it.type==="scheduled-task-ran"&&(ee&&clearTimeout(ee),ee=setTimeout(()=>{ka(cs.current)},500))});return()=>{ee&&clearTimeout(ee),at()}},[]);const Dt=i.useMemo(()=>dr(),[]),{isTablet:bs}=Or(),fs=t||bs,{buildGroupSearchText:os,filterSessionNodesForSearch:qt,buildGroupedSessions:ln}=US({homeDirectory:ce,worktreeMetadata:rs,pinnedSessionIds:K,gitBranches:Kt,isVSCode:Xe}),{scheduleCollapsedProjectsPersist:ps}=XS({isVSCode:Xe,hasLoadedGlobalSessions:jt,safeStorage:S,keys:{sessionExpanded:Ol,sessionExpandedLegacy:fk,projectCollapse:na,sessionPinned:mk,groupOrder:vf,projectActiveSession:Sf,groupCollapse:jf},sessions:yt,setPinnedSessionIds:pe,groupOrderByProject:je,activeSessionByProject:Le,collapsedGroups:se,setExpandedParents:v,setCollapsedProjects:j}),Fs=i.useMemo(()=>[...yt].sort((ee,at)=>Yi(ee,at,K)),[yt,K]),Ws=i.useMemo(()=>Fs.map(ee=>`${ee.id}:${ee.time?.updated??0}`).join("|"),[Fs]),sn=i.useRef(null),Dn=i.useMemo(()=>{const ee=sn.current;if(ee&&ee.signature===Ws)return ee.map;const at=new Map(Fs.map((it,St)=>[it.id,St]));return sn.current={signature:Ws,map:at},at},[Ws,Fs]),jn=i.useMemo(()=>{const ee=new Map;return Fs.forEach(at=>{const it=at.parentID;if(!it)return;const St=ee.get(it)??[];St.push(at),ee.set(it,St)}),ee.forEach(at=>at.sort((it,St)=>Yi(it,St,K))),ee},[Fs,K]),ye=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:a("sessions.sidebar.empty.noSessions.title")}),s.jsx("p",{className:"typography-meta mt-1",children:a("sessions.sidebar.empty.noSessions.description")})]}),Ze=i.useMemo(()=>de.find(ee=>ee.id===h)??null,[de,h]),ct=i.useCallback(ee=>{h&&(be(h,ee),C(null))},[h,be]),It=i.useCallback(()=>{E(!0)},[E]),Ht=i.useCallback(()=>{const ee=jo.getState();if(ee.available&&ee.info){R(!0);return}Ct.checkForUpdates().then(()=>{const{available:at,error:it}=jo.getState();if(it){le.error(a("sessions.sidebar.updateCheck.errorTitle"),{description:it});return}if(!at){le.success(a("sessions.sidebar.updateCheck.latestVersion"));return}R(!0)})},[a,Ct]),mt=i.useCallback(()=>{V(!0)},[]);i.useEffect(()=>{if(typeof window>"u")return;try{if(window.localStorage.getItem(wf)==="true")return;window.localStorage.setItem(wf,"true")}catch{}const ee=window.setTimeout(()=>{le.info(a("shareOpinion.toast.title"),{description:a("shareOpinion.toast.description"),action:{label:a("shareOpinion.actions.shareOpinion"),onClick:()=>V(!0)},duration:12e3})},1e3);return()=>window.clearTimeout(ee)},[a]);const ms=i.useCallback(()=>{t&&Ae(!1),G(!0)},[t,Ae,G]),hs=Ct.available&&(Ct.runtimeType==="desktop"||Ct.runtimeType==="web"),Ns=ut(ee=>ee.deleteSession),ys=ut(ee=>ee.deleteSessions),Is=ut(ee=>ee.archiveSession),Mn=ut(ee=>ee.archiveSessions),{copiedSessionId:$s,handleSessionSelect:hn,handleSessionDoubleClick:Fn,handleSaveEdit:Zn,handleCancelEdit:cn,handleShareSession:We,handleCopyShareUrl:Xt,handleUnshareSession:As,handleDeleteSession:Ps,confirmDeleteSession:zs}=GS({activeProjectId:P,currentDirectory:xe,currentSessionId:Bt,mobileVariant:t,allowReselect:n,onSessionSelected:e,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:l,setActiveProjectIdOnly:ue,setDirectory:ke,setActiveMainTab:ge,setSessionSwitcherOpen:Ae,setCurrentSession:es,updateSessionTitle:Wt,shareSession:Lt,unshareSession:Ut,deleteSession:Ns,deleteSessions:ys,archiveSession:Is,archiveSessions:Mn,childrenMap:jn,showDeletionDialog:ne,setDeleteSessionConfirm:oe,deleteSessionConfirm:X,setEditingId:g,setEditTitle:x,editingId:y,editTitle:b}),Qs=i.useCallback(()=>{if(!fe)return;const{scopeKey:ee,folderId:at}=fe;ve(null),st(ee,at)},[fe,st]),Us=i.useCallback(()=>{Er.requestDirectoryDialog()},[]);i.useEffect(()=>{if(!Bt)return;const at=yt.find(St=>St.id===Bt)?.parentID;if(!at)return;const it=[`project:active:${at}`,`project:archived:${at}`,`recent:active:${at}`,`recent:archived:${at}`];v(St=>{if(it.every(Bs=>St.has(Bs)))return St;const zt=new Set(St);it.forEach(Bs=>zt.add(Bs));try{S.setItem(Ol,JSON.stringify(Array.from(zt)))}catch{}return zt})},[Bt,yt,S]);const Os=i.useCallback(ee=>{v(at=>{const it=new Set(at);it.has(ee)?it.delete(ee):it.add(ee);try{S.setItem(Ol,JSON.stringify(Array.from(it)))}catch{}return it})},[S]),On=i.useCallback((ee,at)=>{if(!ee)return null;at&&nt.has(at)&&et(at);const it=_e(ee,a("sessions.sidebar.folder.newFolderName"),at);return re(it.id),H(it.name),it},[nt,et,_e,a]),fr=Pr(hn),Kn=Pr(Fn),gs=Pr(Zn),Ts=Pr(cn),Sr=Pr(We),Ln=Pr(Xt),pn=Pr(As),Nr=Pr(Ps),kr=Pr(On),Lr=i.useCallback((ee,at)=>{B(it=>{const St=new Map(it);return St.set(ee,at+7),St})},[]),Cr=i.useCallback(ee=>{B(at=>{if(!at.has(ee))return at;const it=new Map(at);return it.delete(ee),it})},[]),rr=i.useCallback(ee=>{B(at=>{let it=!1;const St=new Map(at),zt=`${ee}:`;for(const Bs of St.keys())Bs.startsWith(zt)&&(St.delete(Bs),it=!0);return it?St:at})},[]),js=i.useCallback(()=>{me.current=Date.now()+150,B(new Map),j(()=>{const ee=new Set(de.map(at=>at.id));try{S.setItem(na,JSON.stringify(Array.from(ee)))}catch{}return Xe||ps(ee),ee})},[de,Xe,S,ps]),dn=i.useCallback(()=>{me.current=Date.now()+150,B(new Map),j(()=>{const ee=new Set;try{S.setItem(na,JSON.stringify([]))}catch{}return Xe||ps(ee),ee})},[Xe,S,ps]),ir=i.useCallback(ee=>{me.current=Date.now()+150,rr(ee),j(at=>{const it=new Set(at);it.has(ee)?it.delete(ee):it.add(ee);try{S.setItem(na,JSON.stringify(Array.from(it)))}catch{}return Xe||ps(it),it})},[Xe,rr,S,ps]),q=i.useMemo(()=>de.map(ee=>({...ee,normalizedPath:as(ee.path)})).filter(ee=>!!ee.normalizedPath),[de]),rt=i.useMemo(()=>q.map(ee=>ee.normalizedPath),[q]),ht=i.useMemo(()=>{const ee=new Set;return q.forEach(at=>{if(at.normalizedPath&&ee.add(at.normalizedPath),Xe)return;($t.get(at.normalizedPath)??[]).forEach(St=>{const zt=as(St.path);zt&&ee.add(zt)})}),[...ee].sort()},[$t,Xe,q]),Tt=i.useRef(null);i.useEffect(()=>{const ee=new Set(ht),at=Tt.current;if(Tt.current=ee,!at){Xe&&ht.length>0&&zd(ht,cs.current);return}const it=ht.filter(St=>!at.has(St));it.length!==0&&zd(it,cs.current)},[Xe,ht]);const{github:Yt}=Xn(),ts=Mi(ee=>ee.status),ds=Mi(ee=>ee.hasChecked),Ls=Jg(rt),Ks=sr(ee=>ee.ensureEntry),qn=sr(ee=>ee.setParams),Bn=sr(ee=>ee.refreshTargets);ZS({normalizedProjects:q,gitRepoStatus:Ls,setProjectRepoStatus:D,setProjectRootBranches:he});const Jr=ut(ee=>ee.isLoading);iN({isSessionsLoading:Jr,hasLoadedGlobalSessions:jt,sessions:yt,archivedSessions:is,normalizedProjects:q,isVSCode:Xe,availableWorktreesByProject:$t,cleanupSessions:_t});const{getSessionsForProject:gn,getArchivedSessionsForProject:Xr}=eN({isVSCode:Xe,sessions:yt,archivedSessions:is,availableWorktreesByProject:$t,normalizedProjects:q});OS({normalizedProjects:q,sessions:yt,archivedSessions:is,availableWorktreesByProject:$t,isVSCode:Xe,isSessionsLoading:Jr,foldersMap:xt,createFolder:_e,addSessionToFolder:pt,cleanupSessions:_t});const xn=i.useRef(!1);P&&A.has(P)&&(xn.current=!!A.get(P));const{projectSections:nn,groupSearchDataByGroup:un,sectionsForRender:Sn,searchMatchCount:Nn}=_S({normalizedProjects:q,getSessionsForProject:gn,getArchivedSessionsForProject:Xr,availableWorktreesByProject:$t,projectRepoStatus:A,projectRootBranches:Fe,lastRepoStatus:xn.current,buildGroupedSessions:ln,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:He,filterSessionNodesForSearch:qt,buildGroupSearchText:os,foldersMap:xt}),mr=s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:a("sessions.sidebar.empty.noMatches.title")}),s.jsx("p",{className:"typography-meta mt-1",children:a("sessions.sidebar.empty.noMatches.description")})]});$S({projectSections:nn,activeProjectId:P,activeSessionByProject:Le,setActiveSessionByProject:Me,currentSessionId:Bt,handleSessionSelect:hn,newSessionDraftOpen:Gt,mobileVariant:t,openNewSessionDraft:ls,setActiveMainTab:ge,setSessionSwitcherOpen:Ae});const{getOrderedGroups:or}=zS(je),Ar=i.useRef(!1);i.useEffect(()=>{if(Ar.current||nn.length===0)return;const ee=nn.flatMap(at=>at.groups.filter(it=>it.isArchivedBucket).map(it=>`${at.project.id}:${it.id}`));ee.length>0&&Z(at=>new Set([...at,...ee])),Ar.current=!0},[nn]);const gi=i.useMemo(()=>{const ee=new Map,at=new Map;return nn.forEach(it=>{const St=Tm(it.project.label?.trim()||Oi(it.project.normalizedPath,ce)||it.project.normalizedPath);it.groups.forEach(zt=>{const Bs=zt.branch&&zt.branch!=="HEAD"&&zt.branch!==St?zt.branch:null,on={projectLabel:St,branchLabel:Bs},yn=kn=>{kn.forEach(Cn=>{const _n=it.project.normalizedPath.length,ti=at.get(Cn.session.id)??-1;_n<ti||(ee.set(Cn.session.id,{node:Cn,projectId:it.project.id,groupDirectory:zt.directory,secondaryMeta:on}),at.set(Cn.session.id,_n),Cn.children.length>0&&yn(Cn.children))})};yn(zt.sessions)})}),ee},[nn,ce]),ar=Tr(ee=>ee.showRecentSection),xi=Tr(ee=>ee.showArchivedSessions),Br=i.useMemo(()=>!ar||Xe?[]:uk(yt).sort((ee,at)=>Yi(ee,at,K)),[Xe,K,yt,ar]),Zr=i.useMemo(()=>{if(Xe||!ar)return[];const ee=Br,at=St=>{const zt=gi.get(St.id),Bs=as(St.directory??null),on=zt?.node??{session:St,children:[],worktree:null},kn=(Je?qt([on],He):[on])[0];if(!kn)return null;const Cn=zt?.secondaryMeta?{projectLabel:zt.secondaryMeta.projectLabel,branchLabel:Xe?null:zt.secondaryMeta.branchLabel}:null;return{node:kn,projectId:zt?.projectId??null,groupDirectory:zt?.groupDirectory??Bs,secondaryMeta:Cn}},it=ee.map(at).filter(St=>St!==null);return[{key:"active-now",title:a("sessions.sidebar.activity.recentTitle"),items:it}]},[Br,qt,Je,Xe,He,gi,ar,a]),In=i.useMemo(()=>Zr.some(ee=>ee.items.length>0),[Zr]),lr=i.useMemo(()=>new Set(Br.map(ee=>ee.id)),[Br]),Js=i.useMemo(()=>[...lr],[lr]);Zj({currentSessionId:Bt,sortedSessions:Fs,recentSessionIds:Js,ensureSessionRenderable:qe.ensureSessionRenderable});const Hs=i.useMemo(()=>xi?Sn:Sn.map(ee=>({...ee,groups:ee.groups.filter(at=>!at.isArchivedBucket)})),[Sn,xi]),_r=i.useMemo(()=>{const ee=new Set;return Hs.forEach(at=>{at.groups.forEach(it=>{const St=as(it.directory??null),zt=it.branch?.trim()||Kt.get(St||"")?.trim();!St||!zt||ee.add(Co(St,zt))})}),[...ee]},[Kt,Hs]),Li=Ow(_r);i.useEffect(()=>{if(!ds||!ts?.connected||!Yt)return;const ee=[],at=Date.now();if(Hs.forEach(St=>{k.has(St.project.id)||St.groups.forEach(zt=>{const Bs=as(zt.directory??null),on=zt.branch?.trim()||Kt.get(Bs||"")?.trim();if(!Bs||!on)return;const yn=Co(Bs,on),kn=sr.getState().entries[yn],Cn=!!kn?.status?.pr,_n=`${Bs}::${on}`,ti=Math.max(kn?.lastRefreshAt??0,kn?.lastDiscoveryPollAt??0),vi=!!(kn?.isInitialStatusResolved&&!Cn&&(!p.current.has(_n)||at-ti>=gk));(!kn||!kn.isInitialStatusResolved||vi)&&(vi&&p.current.add(_n),ee.push({directory:Bs,branch:on}))})}),ee.length===0)return;const it=new Map;ee.forEach(St=>{const zt=Co(St.directory,St.branch,St.remoteName??null);it.has(zt)||it.set(zt,St)}),it.forEach((St,zt)=>{Ks(zt),qn(zt,{directory:St.directory,branch:St.branch,remoteName:St.remoteName??null,canShow:!0,github:Yt,githubAuthChecked:ds,githubConnected:ts.connected})}),Bn([...it.values()],{silent:!0,markInitialResolved:!0})},[k,Ks,Yt,ds,ts?.connected,Kt,Bn,Hs,qn]);const bi=t?"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",bn="h-4.5 w-4.5",pr=cN({isDesktopShellRuntime:Dt,projectSections:nn,projectHeaderSentinelRefs:Ie}),Vr=Pr((ee,at=0,it,St,zt=!1,Bs,on="project",yn)=>s.jsx(ek,{node:ee,depth:at,groupDirectory:it,projectId:St,archivedBucket:zt,currentSessionId:Bt,pinnedSessionIds:K,expandedParents:w,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:He,notifyOnSubtasks:ae,editingId:y,setEditingId:g,editTitle:b,setEditTitle:x,handleSaveEdit:gs,handleCancelEdit:Ts,toggleParent:Os,handleSessionSelect:fr,handleSessionDoubleClick:Kn,togglePinnedSession:L,handleShareSession:Sr,copiedSessionId:$s,handleCopyShareUrl:Ln,handleUnshareSession:pn,openSidebarMenuKey:$,setOpenSidebarMenuKey:M,renamingFolderId:te,getFoldersForScope:bt,getSessionFolderId:ns,removeSessionFromFolder:vt,addSessionToFolder:pt,createFolderAndStartRename:kr,openContextPanelTab:we,handleDeleteSession:Nr,mobileVariant:t,alwaysShowActions:fs,renderSessionNode:Vr,secondaryMeta:Bs,renderContext:on,subtreeContainsActive:yn?.subtreeContainsActive??Nf,subtreeContainsEditing:yn?.subtreeContainsEditing??Nf,menuOpenSessionId:yn?.menuOpenSessionId??null,nodeStructureKey:yn?.nodeStructureKey??"",childRenderExtrasFor:yn?.childRenderExtrasFor,liveSessionById:Ue})),yi=i.useCallback(ee=>{Cr(ee),Z(at=>{const it=new Set(at);return it.has(ee)?it.delete(ee):it.add(ee),it})},[Cr]),$r=i.useMemo(()=>{const ee=new Map;for(const[at,it]of Li)ee.set(at,{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 ee},[Li]),Bi=i.useCallback((ee,at,it,St,zt,Bs,on)=>s.jsx(UN,{group:ee,groupKey:at,projectId:it,hideGroupLabel:St,compactBodyPadding:Bs,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:He,groupSearchDataByGroup:un,visibleSessionCount:N.get(at),collapsedGroups:se,hideDirectoryControls:r,collapsedFolderIds:nt,toggleFolderCollapse:et,renameFolder:Qe,deleteFolder:st,showDeletionDialog:ne,setDeleteFolderConfirm:ve,renderSessionNode:Vr,projectRepoStatus:A,lastRepoStatus:xn.current,showMoreGroupSessions:Lr,resetGroupSessionLimit:Cr,mobileVariant:t,alwaysShowActions:fs,activeProjectId:P,setActiveProjectIdOnly:ue,setActiveMainTab:ge,setSessionSwitcherOpen:Ae,openNewSessionDraft:xs,addSessionToFolder:pt,createFolderAndStartRename:kr,renamingFolderId:te,renameFolderDraft:Q,setRenameFolderDraft:H,setRenamingFolderId:re,pinnedSessionIds:K,expandedParents:w,sessionOrderIndex:Dn,currentSessionId:Bt,editingId:y,editTitle:b,openSidebarMenuKey:$,liveSessionById:Ue,prVisualStateByDirectoryBranch:$r,onToggleCollapsedGroup:yi,dragHandleProps:zt,scrollContainerRef:on}),[Je,He,un,N,se,r,nt,et,Qe,st,ne,Vr,A,Lr,Cr,t,fs,P,ue,ge,Ae,xs,pt,kr,te,Q,K,w,Dn,Bt,y,b,$,Ue,$r,yi]),rn=!Xe&&ar&&!Je?s.jsx(ZN,{sections:Zr,renderSessionNode:Vr,currentSessionId:Bt,editingId:y,openSidebarMenuKey:$,variant:"section"}):null,wi=!!(te||y||h),{selectionModeEnabled:_i,hasSelection:mo,selectedIdsSize:Y,bulkScopeIsArchived:Ce,derivedSelectionScope:Re,bulkScopeFolders:$e,bulkCanRemoveFromFolder:dt,handleToggleSelectionMode:Rt,handleExitSelectionMode:Qt,handleBulkMoveToFolder:Jt,handleBulkCreateFolderAndMove:vs,handleBulkRemoveFromFolder:gr,handleBulkDelete:Dr,confirmBulkDelete:Ir}=ok({isInlineEditing:wi,showDeletionDialog:ne,foldersMap:xt,addSessionsToFolder:At,removeSessionsFromFolders:kt,createFolderAndStartRename:On,archiveSessions:Mn,deleteSessions:ys,setBulkDeleteConfirm:Ne}),el=i.useCallback(()=>{ge("chat"),t&&Ae(!1),O()},[t,O,ge,Ae]),tl=i.useCallback(()=>{ge("chat"),t&&Ae(!1),ls()},[t,ls,ge,Ae]);return s.jsxs("div",{ref:m,className:Te("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(HN,{hideDirectoryControls:r,showRecentControls:!Xe,handleOpenDirectoryDialog:Us,openNewSessionDraft:tl,canOpenMultiRun:de.length>0,openMultiRunLauncher:el,headerActionIconClass:bn,headerActionButtonClass:bi,isSessionSearchOpen:c,setIsSessionSearchOpen:l,sessionSearchInputRef:u,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:Je,searchMatchCount:Nn,collapseAllProjects:js,expandAllProjects:dn,openScheduledTasksDialog:()=>J(!0),selectionModeEnabled:_i,onToggleSelectionMode:Rt}),s.jsx(a2,{topContent:rn,hasSharedSessions:In,sectionsForRender:Hs,projectSections:nn,activeProjectId:P,showOnlyMainWorkspace:o,hasSessionSearchQuery:Je,emptyState:ye,searchEmptyState:mr,renderGroupSessions:Bi,homeDirectory:ce,collapsedProjects:k,hideDirectoryControls:r,projectRepoStatus:A,isDesktopShellRuntime:Dt,stuckProjectHeaders:pr,mobileVariant:t,alwaysShowActions:fs,toggleProject:ir,setActiveProjectIdOnly:ue,setActiveMainTab:ge,setSessionSwitcherOpen:Ae,openNewSessionDraft:xs,openNewWorktreeDialog:It,openProjectEditDialog:C,removeProject:F,projectHeaderSentinelRefs:Ie,reorderProjects:W,getOrderedGroups:or,setGroupOrderByProject:De,openSidebarMenuKey:$,setOpenSidebarMenuKey:M,isInlineEditing:wi}),_i&&mo?s.jsx(ik,{selectedCount:Y,scopeKey:Re,scopeFolders:$e,archivedBucket:Ce,onMoveToFolder:Jt,onCreateFolderAndMove:vs,onRemoveFromFolder:gr,canRemoveFromFolder:dt,onDelete:Dr,onDone:Qt}):null,s.jsx(e2,{onOpenSettings:ms,onOpenShortcuts:Se,onOpenAbout:()=>Oe(!0),onOpenUpdate:Ht,onOpenShareOpinion:mt,showRuntimeButtons:!Xe,showUpdateButton:hs}),s.jsx(xN,{open:z,onOpenChange:V}),s.jsx(Nm,{open:_,onOpenChange:R,info:Ct.info,downloading:Ct.downloading,downloaded:Ct.downloaded,progress:Ct.progress,error:Ct.error,onDownload:Ct.downloadUpdate,onRestart:Ct.restartToUpdate,runtimeType:Ct.runtimeType}),Ze?s.jsx(uN,{open:!!Ze,onOpenChange:ee=>{ee||C(null)},projectId:Ze.id,projectName:Ze.label||Oi(Ze.path,ce),projectPath:Ze.path,initialIcon:Ze.icon,initialColor:Ze.color,initialIconBackground:Ze.iconBackground,onSave:ct}):null,s.jsx(Jx,{open:T,onOpenChange:E,onWorktreeCreated:(ee,at)=>{if(ge("chat"),t&&Ae(!1),at?.sessionId){es(at.sessionId,ee);return}ls({directoryOverride:ee,preserveDirectoryOverride:!0})}}),s.jsx(MS,{}),s.jsx(sk,{value:X,setValue:oe,showDeletionDialog:ne,setShowDeletionDialog:Be,onConfirm:zs}),s.jsx(rk,{value:fe,setValue:ve,onConfirm:Qs}),s.jsx(nk,{value:ie,setValue:Ne,showDeletionDialog:ne,setShowDeletionDialog:Be,onConfirm:Ir})]})},ki=t=>t?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,yr=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},xk=()=>{const{t}=Nt(),[e,n]=i.useState(!1),[r,o]=i.useState(!1),[a,c]=i.useState(null),[l,d]=i.useState([]),[f,m]=i.useState(!1),[u,p]=i.useState(!1),[y,g]=i.useState(!1),[b,x]=i.useState(!1),[h,C]=i.useState(new Set),w=ut(ce=>ce.getWorktreeMetadata),v=ut(ce=>ce.newSessionDraft),S=ut(ce=>ce.setNewSessionDraftTarget),k=ut(ce=>ce.setDraftBootstrapPendingDirectory),j=Zg,A=sx,D=ut(ce=>ce.deleteSessions),N=ut(ce=>ce.archiveSessions),B=Ee(ce=>ce.showDeletionDialog),T=Ee(ce=>ce.setShowDeletionDialog),E=Ys(ce=>ce.currentDirectory),_=Ys(ce=>ce.homeDirectory),R=Ys(ce=>ce.isHomeReady),z=Ss(ce=>ce.projects),V=Ss(ce=>ce.activeProjectId),{isMobile:$,isTablet:M,hasTouchInput:te}=Or(),re=$||M||te,Q=i.useMemo(()=>{const xe=(V?z.find(ke=>ke.id===V)??null:null)?.path??E;return yr(xe)},[V,E,z]),H=i.useCallback(ce=>{const ke=yr(ce.projectDirectory)||Q;return{id:(z.find(P=>yr(P.path)===ke)??null)?.id??`path:${ke}`,path:ke}},[Q,z]),X=b&&h.size>0,oe=i.useMemo(()=>{const ce=a?.worktree;return ce&&typeof ce.branch=="string"&&ce.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:xe})=>typeof xe.branch=="string"&&xe.branch.trim().length>0)},[a?.worktree,l]),fe=a?.mode==="worktree",ve=fe,ie=y||!fe||!oe,Ne=y||!fe;i.useEffect(()=>{r||!R||z.length>0||(o(!0),n(!0))},[r,R,z.length]);const K=i.useCallback(ce=>{c({sessions:ce.sessions,dateLabel:ce.dateLabel,mode:ce.mode??"session",worktree:ce.worktree??null})},[]),pe=i.useCallback(()=>{c(null),d([]),m(!1),p(!1),g(!1),x(!1),C(new Set)},[]),L=i.useCallback(async ce=>{if(ce.sessions.length===0)return;if(ce.sessions.length===1){const P=ce.sessions[0];await j(P.id)?le.success(t("sessions.sidebar.session.delete.success")):le.error(t("sessions.sidebar.session.delete.error"));return}const xe=ce.sessions.map(P=>P.id),{deletedIds:ke,failedIds:de}=await D(xe);if(ke.length>0){const P=de.length>0?de.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:de.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:de.length}):ce.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:ce.dateLabel}):void 0;le.success(ke.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:ke.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:ke.length}),{description:ki(P)})}de.length>0&&le.error(de.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:de.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:de.length}),{description:ki(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))})},[j,D,t]);i.useEffect(()=>Er.onDeleteRequest(ce=>{if(!B&&(ce.mode??"session")==="session"){L(ce);return}K(ce)}),[K,B,L]),i.useEffect(()=>Er.onDirectoryRequest(()=>{n(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1),p(!1),x(!1),C(new Set);return}const ce=a.sessions.map(de=>{const P=w(de.id);return P?{session:de,metadata:P}:null}).filter(de=>!!de);d(ce),m(!1),x(!1),C(new Set);const xe=new Map;if(a.worktree?.path&&xe.set(yr(a.worktree.path),a.worktree),ce.forEach(({metadata:de})=>{de.path&&xe.set(yr(de.path),de)}),xe.size===0){x(!0);return}let ke=!1;return(async()=>{const de=new Map,P=new Set;await Promise.all(Array.from(xe.entries()).map(async([F,ue])=>{try{const be=await ex(ue.path);de.set(F,be),be?.isDirty&&P.add(F)}catch{ue.status&&(de.set(F,ue.status),ue.status.isDirty&&P.add(F))}})).catch(F=>{console.warn("Failed to inspect worktree status before deletion:",F)}),!ke&&(C(P),x(!0),c(F=>{if(!F?.worktree?.path)return F;const ue=yr(F.worktree.path),be=de.get(ue);if(!be)return F;const W=F.worktree.status;return W?.isDirty===be.isDirty&&W?.ahead===be.ahead&&W?.behind===be.behind&&W?.upstream===be.upstream?F:{...F,worktree:{...F.worktree,status:be}}}),d(F=>F.map(ue=>{const be=yr(ue.metadata.path),W=de.get(be);return W?{session:ue.session,metadata:{...ue.metadata,status:W}}:ue})))})(),()=>{ke=!0}},[a,w]),i.useEffect(()=>{oe||m(!1)},[oe]);const se=i.useCallback(async(ce,xe)=>{const ke=f&&oe,de=H(ce),P=yr(ce.path),F=yr(de.path);try{await tx(de,ce,{deleteRemoteBranch:ke,deleteLocalBranch:xe});const ue=yr(v?.directoryOverride);return v?.open&&P&&ue===P&&F&&(k(null),S({projectId:de.id,directoryOverride:F},{force:!0})),yr(E)===P&&F&&Ys.getState().setDirectory(F,{showOverlay:!1}),!0}catch(ue){return le.error(t("sessions.sidebar.sessionDialogs.worktree.errorRemoveTitle"),{description:ki(ue instanceof Error?ue.message:t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),!1}},[oe,E,f,H,v?.directoryOverride,v?.open,k,S,t]),Z=i.useCallback((ce,xe)=>{const ke=f&&oe;(async()=>{if(!await se(ce,xe))return;const P=t(ke?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.removed");le.success(t("sessions.sidebar.sessionDialogs.worktree.removedTitle"),{description:ki(P)})})()},[oe,f,se,t]),je=i.useCallback(async()=>{if(a){g(!0);try{const ce=ve,xe=ce&&f,ke=ce&&u;if(a.sessions.length===0&&fe&&a.worktree){Z(a.worktree,ke),pe();return}if(a.sessions.length===1){const de=a.sessions[0];if(!(fe?await A(de.id):await j(de.id,{archiveWorktree:!1,deleteRemoteBranch:xe,deleteLocalBranch:ke}))){le.error(t(fe?"sessions.sidebar.session.archive.error":"sessions.sidebar.session.delete.error")),g(!1);return}const F=!fe&&ce?t(xe?"sessions.sidebar.sessionDialogs.worktree.removedWithRemote":"sessions.sidebar.sessionDialogs.worktree.attachedArchived"):void 0;le.success(t(fe?"sessions.sidebar.session.archive.success":"sessions.sidebar.session.delete.success"),{description:ki(F),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}else{const de=a.sessions.map(ue=>ue.id);let P=[],F=[];if(fe){const ue=await N(de);P=ue.archivedIds,F=ue.failedIds}else{const ue=await D(de);P=ue.deletedIds,F=ue.failedIds}if(fe&&a.worktree&&F.length===0&&Z(a.worktree,ke),P.length>0){const ue=!fe&&ce?t(xe?"sessions.sidebar.sessionDialogs.worktree.archivedAndRemoteRemoved":"sessions.sidebar.sessionDialogs.worktree.attachedArchivedPlural"):void 0,W=[F.length>0?fe?F.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToArchive",{count:F.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToArchive",{count:F.length}):F.length===1?t("sessions.sidebar.dialogs.deleteResult.singleFailedToDelete",{count:F.length}):t("sessions.sidebar.dialogs.deleteResult.manyFailedToDelete",{count:F.length}):a.dateLabel?t("sessions.sidebar.dialogs.deleteResult.removedFromDate",{dateLabel:a.dateLabel}):void 0,ue].filter(Boolean).join(" ");le.success(fe?P.length===1?t("sessions.sidebar.bulkActions.archivedSingle",{count:P.length}):t("sessions.sidebar.bulkActions.archivedPlural",{count:P.length}):P.length===1?t("sessions.sidebar.bulkActions.deletedSingle",{count:P.length}):t("sessions.sidebar.bulkActions.deletedPlural",{count:P.length}),{description:ki(W||void 0),action:{label:t("sessions.sidebar.sessionDialogs.ok"),onClick:()=>{}}})}if(F.length>0&&(le.error(fe?F.length===1?t("sessions.sidebar.bulkActions.failedArchiveSingle",{count:F.length}):t("sessions.sidebar.bulkActions.failedArchivePlural",{count:F.length}):F.length===1?t("sessions.sidebar.bulkActions.failedDeleteSingle",{count:F.length}):t("sessions.sidebar.bulkActions.failedDeletePlural",{count:F.length}),{description:ki(t("sessions.sidebar.dialogs.deleteResult.tryAgain"))}),P.length===0)){g(!1);return}}fe&&a.sessions.length===1&&a.worktree&&Z(a.worktree,ke),pe()}finally{g(!1)}}},[a,f,u,j,D,A,N,pe,ve,fe,Z,t]),De=a?.worktree??l[0]?.metadata??null,Le=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}):"",Me=a?s.jsxs("div",{className:Te(fe?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&s.jsxs("div",{className:Te(fe?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[fe&&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:Te(fe?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(ce=>s.jsxs("li",{className:Te(fe?"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:Te(!fe&&"hidden"),children:"•"}),s.jsx("span",{className:"truncate",children:ce.title||t("sessions.sidebar.session.untitled")})]},ce.id)),a.sessions.length>5&&s.jsx("li",{className:Te(fe?"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})})]})]}),fe?s.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(I,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-meta font-medium text-foreground",children:t("sessions.sidebar.sessionDialogs.worktree.label")}),De?.label?s.jsx("span",{className:"typography-micro text-muted-foreground/70",children:De.label}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:De?Ca(De.path,_):t("sessions.sidebar.sessionDialogs.worktree.pathUnavailable")}),X&&s.jsx("p",{className:"typography-micro text-status-warning",children:t("sessions.sidebar.sessionDialogs.worktree.uncommittedWarning")})]}):s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:t("sessions.sidebar.sessionDialogs.delete.note")})})]}):null,Fe=fe?oe?s.jsxs("button",{type:"button",onClick:()=>{ie||m(ce=>!ce)},disabled:ie,className:Te("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",ie?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[f?s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(I,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteRemoteBranch")]}):s.jsx("span",{className:"text-xs text-muted-foreground/70",children:t("sessions.sidebar.sessionDialogs.actions.remoteBranchInfoUnavailable")}):null,he=fe?s.jsxs("button",{type:"button",onClick:()=>{Ne||p(ce=>!ce)},disabled:Ne,className:Te("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",Ne?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}):s.jsx(I,{name:"checkbox-blank",className:"size-4"}),t("sessions.sidebar.sessionDialogs.actions.deleteLocalBranch")]}):null,Ie=fe?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,Fe]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ve,{variant:"ghost",onClick:pe,disabled:y,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(Ve,{variant:"destructive",onClick:je,disabled:y,children:t(y?"sessions.sidebar.sessionDialogs.actions.deleting":"sessions.sidebar.sessionDialogs.actions.deleteWorktree")})]})]}):s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>T(!B),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!B,children:[B?s.jsx(I,{name:"checkbox-blank",className:"size-4"}):s.jsx(I,{name:"checkbox",className:"size-4 text-primary"}),t("sessions.sidebar.dialogs.neverAsk")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ve,{variant:"ghost",onClick:pe,disabled:y,children:t("sessions.sidebar.dialogs.cancel")}),s.jsx(Ve,{variant:"destructive",onClick:je,disabled:y,children:y?t("sessions.sidebar.sessionDialogs.actions.deleting"):a?.sessions.length===1?t("sessions.sidebar.dialogs.deleteSession.titleAction"):t("sessions.sidebar.dialogs.deleteSessions.titleAction")})]})]}),me=fe?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:[re?s.jsx(Ha,{open:!!a,onClose:()=>{y||pe()},title:me,footer:s.jsx("div",{className:"flex justify-end gap-2",children:Ie}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[Le&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Le}),Me]})}):s.jsx(Ms,{open:!!a,onOpenChange:ce=>{if(!ce){if(y)return;pe()}},children:s.jsxs(Es,{className:Te(fe?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[s.jsxs(Gs,{children:[s.jsxs(Vs,{className:Te(fe&&"flex items-center gap-2"),children:[fe&&s.jsx(I,{name:"delete-bin",className:"h-5 w-5"}),me]}),Le&&s.jsx(an,{children:Le})]}),s.jsx("div",{className:Te(fe&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:Me}),s.jsx(nr,{className:"mt-2 gap-2 pt-1 pb-1",children:Ie})]})}),s.jsx(Xx,{open:e,onOpenChange:n})]})},uc=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),bk=(t,e)=>{const n=uc(t),r=uc(e);return`${n}-${r}`.substring(0,60)},Cf=(t,e)=>`${t}/${e}`,yk=t=>{const e=t.replace(/\\/g,"/");return e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e},Af=(t,e)=>{const n=yk(e),r=t.directory,o=typeof r=="string"&&r.trim().length>0?t:{...t,directory:n};dx(t.id,n),ut.getState().markSessionAsOpenChamberCreated(t.id),jr.getState().upsertSession(o);try{Aa().ensureChild(n,{bootstrap:!1}).setState(c=>{const l=c.session.findIndex(f=>f.id===t.id);if(l>=0&&c.session[l]===o)return c;const d=l>=0?c.session.map((f,m)=>m===l?o:f):[...c.session,o].sort((f,m)=>f.id.localeCompare(m.id));return{session:d,sessionTotal:Math.max(c.sessionTotal,d.length),limit:Math.max(c.limit,d.length)}})}catch{}return o},wk=()=>{const t=Ss.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=Ys.getState().currentDirectory??null;if(r&&r.trim().length>0){const o=r.replace(/\\/g,"/").replace(/\/+$/,"")||r;return{id:`path:${o}`,path:o}}return null},Ll=ao()(Lf(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=wk();if(!l)return t({error:"Select a project",isLoading:!1}),null;const d=l.path,m=await gm(d)&&e.isolateRuns!==!1,u=uc(n),p=m?await qa(d):void 0,y=m?await nx(d):null,g=[],b=c?.filter(v=>v.trim().length>0)??[];for(let v=0;v<r.length;v++){const S=r[v],k=S.prompt,j=new Map;for(const D of S.models){const N=`${D.providerID}:${D.modelID}`;j.set(N,(j.get(N)||0)+1)}const A=new Map;for(const D of S.models){const N=`${D.providerID}:${D.modelID}`,B=j.get(N)||1,T=(A.get(N)||0)+1;A.set(N,T);const E=bk(D.providerID,D.modelID),_=r.length>1?`g${v+1}`:void 0,R=B>1?Cf(u,`${E}/${T}`):Cf(u,E),z=_?`${_}/${R}`:R,V=I2({groupSlug:u,runGroup:_,providerID:D.providerID,modelID:D.modelID,index:B>1?T:void 0});try{if(!m){const re=await Jn.withDirectory(d,()=>Jn.createSession({title:V}));Af(re,d),g.push({sessionId:re.id,worktreePath:d,providerID:D.providerID,modelID:D.modelID,variant:D.variant,prompt:k});continue}const $=await rx(l,{preferredName:z,mode:"new",branchName:z,worktreeName:z,startRef:e.worktreeBaseBranch||"HEAD",setupCommands:b,returnAfterDirectoryCreated:!0},{resolvedRootTrackingRemote:y}),M={...$,createdFromBranch:p,kind:"standard"};await ix(l)&&await ox($.path);const te=await Jn.withDirectory($.path,()=>Jn.createSession({title:V}));Af(te,$.path),ut.getState().setWorktreeMetadata(te.id,M),g.push({sessionId:te.id,worktreePath:$.path,providerID:D.providerID,modelID:D.modelID,variant:D.variant,prompt:k})}catch($){console.warn("[MultiRun] Failed to create session:",$)}}}const x=c?.filter(v=>v.trim().length>0)??[];x.length>0&&ax(l,x).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const h=g.map(v=>v.sessionId),C=g[0]?.sessionId??null;if(h.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const w=a?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));return(async()=>{try{const v=lx.getState().expandText;await Promise.allSettled(g.map(async S=>{try{const k=await v(S.prompt).catch(()=>S.prompt);await cx({sessionId:S.sessionId,directory:S.worktreePath,content:k,providerID:S.providerID,modelID:S.modelID,variant:S.variant,agent:o,files:w})}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),t({isLoading:!1}),{groupSlug:u,sessionIds:h,firstSessionId:C}}catch(l){return t({error:l instanceof Error?l.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"})),vk="oc:lastWorktreeSourceBranch";function Ah(t){const e=ft.c(30),{git:n}=Xn(),r=nm(t),o=Cc(t),a=Ac(t),c=ux(t),l=wn(Ck),d=wn(kk);let f,m;e[0]!==t||e[1]!==d||e[2]!==n||e[3]!==o||e[4]!==a?(f=()=>{!t||!n||o!==null||a||d(t,n,{silent:!0})},m=[t,n,d,o,a],e[0]=t,e[1]=d,e[2]=n,e[3]=o,e[4]=a,e[5]=f,e[6]=m):(f=e[5],m=e[6]),i.useEffect(f,m);let u;e[7]!==r?.all||e[8]!==t||e[9]!==l||e[10]!==n||e[11]!==o?(u=()=>{!t||!n||o===!0&&(r?.all||l(t,n))},e[7]=r?.all,e[8]=t,e[9]=l,e[10]=n,e[11]=o,e[12]=u):u=e[12];const p=r?.all;let y;e[13]!==t||e[14]!==l||e[15]!==n||e[16]!==o||e[17]!==p?(y=[t,n,o,p,l],e[13]=t,e[14]=l,e[15]=n,e[16]=o,e[17]=p,e[18]=y):y=e[18],i.useEffect(u,y);const g=a||o===!0&&c;let b;e:{if(!r?.all){let j;e[19]===Symbol.for("react.memo_cache_sentinel")?(j=[],e[19]=j):j=e[19],b=j;break e}let k;e[20]!==r.all?(k=r.all.filter(Nk).sort(),e[20]=r.all,e[21]=k):k=e[21],b=k}const x=b;let h;e:{if(!r?.all){let j;e[22]===Symbol.for("react.memo_cache_sentinel")?(j=[],e[22]=j):j=e[22],h=j;break e}let k;e[23]!==r.all?(k=r.all.filter(Sk).map(jk).sort(),e[23]=r.all,e[24]=k):k=e[24],h=k}const C=h;let w;e:{if(!t){w=null;break e}if(o!==null){w=o;break e}if(g){w=null;break e}w=r?.all?!0:null}const v=w;let S;return e[25]!==v||e[26]!==g||e[27]!==x||e[28]!==C?(S={localBranches:x,remoteBranches:C,isLoading:g,isGitRepository:v},e[25]=v,e[26]=g,e[27]=x,e[28]=C,e[29]=S):S=e[29],S}function jk(t){return t.replace(/^remotes\//,"")}function Sk(t){return t.startsWith("remotes/")}function Nk(t){return!t.startsWith("remotes/")}function kk(t){return t.fetchStatus}function Ck(t){return t.fetchBranches}const Ak=({directory:t,value:e,onChange:n,className:r,disabled:o,id:a})=>{const{t:c}=Nt(),{localBranches:l,remoteBranches:d,isLoading:f,isGitRepository:m}=Ah(t),u=i.useMemo(()=>[...l,...d.map(y=>`remotes/${y}`)],[l,d]);i.useEffect(()=>{if(o||f||u.length===0||e&&u.includes(e))return;(async()=>{try{const g=t?await qa(t).catch(()=>null):null,b=localStorage.getItem(vk);b&&u.includes(b)?n(b):g&&u.includes(g)?n(g):u.includes("main")?n("main"):u.includes("master")?n("master"):u[0]&&n(u[0])}catch{}})()},[u,t,o,f,n,e]);const p=o||!m||f;return s.jsxs("div",{children:[s.jsxs(Un,{value:e,onValueChange:n,disabled:p,children:[s.jsx(Hn,{id:a,size:"lg",className:r??"w-fit typography-meta text-foreground",children:s.jsx(An,{placeholder:c(f?"multiRun.branchSelector.status.loadingBranches":"multiRun.branchSelector.placeholder.selectSourceBranch")})}),s.jsx(Gn,{className:"max-h-[280px] max-w-[320px]",children:f?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.loadingBranches")}):l.length===0&&d.length===0?s.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:c("multiRun.branchSelector.status.noBranchesFound")}):s.jsxs(s.Fragment,{children:[l.length>0&&s.jsxs(Gl,{children:[s.jsx(Wd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.localBranches")}),l.map(y=>s.jsx(Rs,{value:y,className:"whitespace-normal break-all",children:y},y))]}),l.length>0&&d.length>0&&s.jsx(fx,{}),d.length>0&&s.jsxs(Gl,{children:[s.jsx(Wd,{className:"font-semibold text-foreground",children:c("multiRun.branchSelector.groups.remoteBranches")}),d.map(y=>s.jsx(Rs,{value:`remotes/${y}`,className:"whitespace-normal break-all",children:y},`remotes/${y}`))]})]})})]}),m===!1&&s.jsx("p",{className:"typography-micro text-muted-foreground/70 mt-2",children:c("multiRun.branchSelector.status.notInGitRepository")})]})},Dk=10*1024*1024,Bl=5,xa=t=>{const e=ft.c(3),{children:n}=t;let r;e[0]===Symbol.for("react.memo_cache_sentinel")?(r=s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",tabIndex:-1,className:"inline-flex items-center justify-center text-muted-foreground/50 hover:text-muted-foreground transition-colors",children:s.jsx(I,{name:"information",className:"h-3.5 w-3.5"})})}),e[0]=r):r=e[0];let o;return e[1]!==n?(o=s.jsxs(Et,{children:[r,s.jsx(Ft,{side:"top",className:"max-w-[240px]",children:n})]}),e[1]=n,e[2]=o):o=e[2],o},Di=t=>{const e=ft.c(9),{htmlFor:n,required:r,children:o,info:a}=t;let c;e[0]!==r?(c=r&&s.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),e[0]=r,e[1]=c):c=e[1];let l;e[2]!==o||e[3]!==n||e[4]!==c?(l=s.jsxs("label",{htmlFor:n,className:"typography-meta font-medium text-foreground",children:[o,c]}),e[2]=o,e[3]=n,e[4]=c,e[5]=l):l=e[5];const d=a&&a;let f;return e[6]!==l||e[7]!==d?(f=s.jsxs("div",{className:"flex items-center gap-1.5",children:[l,d]}),e[6]=l,e[7]=d,e[8]=f):f=e[8],f},Ik=({initialPrompt:t,onCreated:e,onCancel:n,isWindowed:r=!1})=>{const{t:o}=Nt(),[a,c]=i.useState(""),[l,d]=i.useState(()=>[{id:Io(),prompt:"",models:[]}]),[f,m]=i.useState(""),[u,p]=i.useState([]),[y,g]=i.useState(!1),[b,x]=i.useState([]),[h,C]=i.useState(!1),[w,v]=i.useState(!1),[S,k]=i.useState(!0),j=i.useRef(null),A=Ys(F=>F.currentDirectory??null),D=Ys(F=>F.homeDirectory??null),N=i.useMemo(()=>{if(typeof window>"u")return null;const F=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof F=="string"&&F.trim().length>0?F.trim():null},[]),B=Ss(F=>F.activeProjectId),T=Ss(F=>F.setActiveProjectIdOnly),E=Ss(F=>F.projects),[_,R]=i.useState(()=>B??null);i.useEffect(()=>{if(B){R(B);return}!_&&E.length>0&&R(E[0].id)},[B,E,_]);const z=i.useMemo(()=>_?E.find(F=>F.id===_)??null:null,[E,_]),V=z?.path??A,$=i.useCallback(F=>{R(F),F!==B&&T(F)},[B,T]),{currentTheme:M}=Qr(),te=i.useCallback(F=>{const ue=F.label?.trim()||Oi(F.path,D),be=F.icon?Rc[F.icon]:null,W=F.color?Qa[F.color]:void 0,ge=be?s.jsx(I,{name:be,className:"h-3.5 w-3.5 shrink-0",style:W?{color:W}:void 0}):s.jsx(I,{name:"folder",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/80",style:W?{color:W}:void 0});return s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5",children:[F.iconImage?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center overflow-hidden rounded-[3px]",style:F.iconBackground?{backgroundColor:F.iconBackground}:void 0,children:s.jsx(Ja,{project:{id:F.id,iconImage:F.iconImage??null},options:{themeVariant:M.metadata.variant,iconColor:M.colors.surface.foreground},className:"h-full w-full object-contain",fallback:ge})}):ge,s.jsx("span",{className:"truncate",children:ue})]})},[D,M.metadata.variant,M.colors.surface.foreground]),re=i.useMemo(()=>{if(z?.path)return{id:z.id,path:z.path};const F=A??N;return F?{id:`path:${F}`,path:F}:null},[z,A,N]),[Q]=i.useState(()=>typeof window<"u"?dr():!1),H=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),X=Kf(),oe=i.useMemo(()=>{if(typeof window>"u")return null;const F=window.__OPENCHAMBER_MACOS_MAJOR__;if(typeof F=="number"&&Number.isFinite(F)&&F>0)return F;if(typeof navigator>"u")return null;const ue=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ue)return null;const be=Number.parseInt(ue[1],10),W=Number.parseInt(ue[2],10);return Number.isNaN(be)?null:be===10?W:be},[]),fe=i.useMemo(()=>Q&&H||X?"pl-[5.5rem]":"pl-3",[Q,H,X]),ve=i.useMemo(()=>!Q||!H||oe===null?"":oe>=26?"h-12":oe<=15?"h-14":"",[Q,H,oe]),ie=i.useCallback(async F=>{F.target.closest("button, a, input, select, textarea")||F.button===0&&Q&&await mx()},[Q]);i.useEffect(()=>{if(!n)return;const F=ue=>{ue.key==="Escape"&&(ue.preventDefault(),ue.stopPropagation(),n())};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[n]);const[Ne,K]=i.useState(""),{isLoading:pe,isGitRepository:L}=Ah(V),se=i.useRef(!1),Z=L===!0,je=Z&&S;i.useEffect(()=>{if(L===!1){se.current=!0,k(!1);return}L===!0&&se.current&&(se.current=!1,k(!0))},[L]);const De=Ll(F=>F.createMultiRun),Le=Ll(F=>F.error),Me=Ll(F=>F.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&d(F=>{const ue=[...F];return ue.length>0&&!ue[0].prompt.trim()&&(ue[0]={...ue[0],prompt:t}),ue})},[t]),i.useEffect(()=>{if(!re)return;let F=!1;return v(!0),(async()=>{try{const ue=await hx(re);F||x(ue)}catch{}finally{F||v(!1)}})(),()=>{F=!0}},[re]);const Fe=i.useCallback((F,ue)=>{d(be=>be.map(W=>W.id===F?{...W,...ue}:W))},[]),he=i.useCallback(F=>{d(ue=>ue.filter(be=>be.id!==F))},[]),Ie=i.useCallback(()=>{d(F=>[...F,{id:Io(),prompt:"",models:[]}])},[]),me=async F=>{const ue=F.target.files;if(!ue)return;let be=0;for(let W=0;W<ue.length;W++){const ge=ue[W];if(ge.size>Dk){le.error(o("multirun.launcher.toast.fileTooLarge",{fileName:ge.name}));continue}try{const we=await new Promise((G,Se)=>{const Oe=new FileReader;Oe.onload=()=>G(Oe.result),Oe.onerror=Se,Oe.readAsDataURL(ge)});p(G=>[...G,{id:Io(),filename:ge.name,mimeType:ge.type||"application/octet-stream",size:ge.size,dataUrl:we}]),be++}catch(we){console.error("File attach failed",we),le.error(o("multirun.launcher.toast.attachFailed",{fileName:ge.name}))}}be>0&&le.success(be===1?o("multirun.launcher.toast.attachedSingle",{count:be}):o("multirun.launcher.toast.attachedPlural",{count:be})),j.current&&(j.current.value="")},ce=F=>{p(ue=>ue.filter(be=>be.id!==F))},xe=i.useMemo(()=>l.reduce((F,ue)=>F+ue.models.length,0),[l]),ke=async F=>{F.preventDefault();const ue=l.filter(be=>be.prompt.trim()&&be.models.length>=1);if(ue.length!==0&&!(xe<1)){g(!0),Me();try{_&&_!==B&&T(_);const be=u.map(Se=>({mime:Se.mimeType,filename:Se.filename,url:Se.dataUrl})),W=b.filter(Se=>Se.trim().length>0),ge=ue.map(Se=>({prompt:Se.prompt.trim(),models:Se.models.map(Oe=>({providerID:Oe.providerID,modelID:Oe.modelID,displayName:Oe.displayName,variant:Oe.variant}))})),we={name:a.trim(),groups:ge,agent:f||void 0,worktreeBaseBranch:je?Ne:void 0,isolateRuns:je,files:be.length>0?be:void 0,setupCommands:W.length>0?W:void 0},G=await De(we);G&&(G.firstSessionId&&ut.getState().setCurrentSession(G.firstSessionId),e?.())}finally{g(!1)}}},de=!!(a.trim()&&l.some(F=>F.prompt.trim()&&F.models.length>=1)&&xe>=1&&V&&!pe&&(L===!1||!je||Ne)),P=b.filter(F=>F.trim()).length;return s.jsxs("form",{onSubmit:ke,className:"flex flex-col h-full bg-background",children:[r?null:s.jsxs("header",{onMouseDown:ie,className:Te("relative flex h-12 shrink-0 items-center justify-center border-b app-region-drag select-none",fe,ve),style:{borderColor:"var(--interactive-border)"},children:[s.jsx("h1",{className:"typography-ui-label font-medium",children:o("multirun.launcher.title")}),n&&s.jsx("div",{className:"absolute right-0 flex items-center pr-3",children:s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,"aria-label":o("multirun.launcher.actions.closeEsc"),className:"inline-flex h-9 w-9 items-center justify-center p-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:s.jsx(I,{name:"close",className:"h-5 w-5"})})}),s.jsx(Ft,{children:s.jsx("p",{children:o("multirun.launcher.actions.closeEsc")})})]})})]}),s.jsx(Ga,{className:"flex-1 min-h-0 overflow-auto",size:64,hideTopShadow:!0,children:s.jsx("div",{className:"mx-auto w-full max-w-2xl px-4 sm:px-6 py-5",children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:[s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Di,{htmlFor:"multirun-project",required:!0,children:o("multirun.launcher.project.label")}),E.length>0?s.jsxs(Un,{value:_??void 0,onValueChange:$,children:[s.jsx(Hn,{id:"multirun-project",size:"lg",className:"w-fit max-w-full",children:z?s.jsx(An,{children:te(z)}):s.jsx(An,{placeholder:o("multirun.launcher.project.placeholder")})}),s.jsx(Gn,{fitContent:!0,children:E.map(F=>s.jsx(Rs,{value:F.id,className:"max-w-[24rem]",children:te(F)},F.id))})]}):s.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:o("multirun.launcher.project.empty")})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Di,{htmlFor:"group-name",required:!0,info:s.jsx(xa,{children:o("multirun.launcher.groupName.info")}),children:o("multirun.launcher.groupName.label")}),s.jsx(vn,{id:"group-name",value:a,onChange:F=>c(F.target.value),placeholder:o("multirun.launcher.groupName.placeholder"),className:"typography-meta w-full",required:!0})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Di,{htmlFor:"multirun-worktree-base-branch",info:s.jsx(xa,{children:o("multirun.launcher.baseBranch.info")}),children:o("multirun.launcher.baseBranch.label")}),s.jsx(Ak,{directory:V,value:Ne,onChange:K,disabled:!je,id:"multirun-worktree-base-branch"}),s.jsxs("label",{className:"mt-1.5 flex w-fit items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(Fi,{checked:S,onChange:k,disabled:!Z,ariaLabel:o("multirun.launcher.isolateRuns.label")}),s.jsx("span",{children:o("multirun.launcher.isolateRuns.label")})]})]}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx(Di,{htmlFor:"multirun-agent",info:s.jsx(xa,{children:o("multirun.launcher.agent.info")}),children:o("multirun.launcher.agent.label")}),s.jsx(Sh,{value:f,onChange:m,id:"multirun-agent"})]})]}),s.jsxs(no,{open:h,onOpenChange:C,children:[s.jsxs(_o,{className:"w-full flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-lg hover:bg-[var(--interactive-hover)]/50 transition-colors group",children:[s.jsx(I,{name:"terminal",className:"h-3.5 w-3.5 text-muted-foreground/70"}),s.jsx("span",{className:"typography-meta font-medium text-muted-foreground group-hover:text-foreground transition-colors",children:o("multirun.launcher.setupCommands.label")}),P>0&&s.jsx("span",{className:"inline-flex items-center justify-center h-4 min-w-4 px-1 rounded-full typography-micro font-medium",style:{backgroundColor:"var(--primary-base)",color:"var(--primary-foreground)",fontSize:"0.625rem",lineHeight:1},children:P}),s.jsx(I,{name:"arrow-down-s",className:Te("h-3.5 w-3.5 text-muted-foreground/50 transition-transform duration-200 ml-auto",h&&"rotate-180")})]}),s.jsx(ro,{children:s.jsx("div",{className:"pt-2 space-y-1.5",children:w?s.jsx("p",{className:"typography-meta text-muted-foreground/70 px-2",children:o("multirun.launcher.setupCommands.loading")}):s.jsxs(s.Fragment,{children:[b.map((F,ue)=>s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx(vn,{value:F,onChange:be=>{const W=[...b];W[ue]=be.target.value,x(W)},placeholder:o("multirun.launcher.setupCommands.commandPlaceholder"),className:"h-8 flex-1 font-mono text-xs"}),s.jsx("button",{type:"button",onClick:()=>x(b.filter((be,W)=>W!==ue)),className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":o("multirun.launcher.setupCommands.removeCommandAria"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})})]},`${F}-${ue}`)),s.jsxs("button",{type:"button",onClick:()=>x([...b,""]),className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors px-1",children:[s.jsx(I,{name:"add",className:"h-3 w-3"}),o("multirun.launcher.setupCommands.addCommand")]})]})})})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Di,{htmlFor:"prompt",required:!0,children:o("multirun.launcher.attachments.label")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("input",{ref:j,type:"file",multiple:!0,className:"hidden",onChange:me,accept:"*/*"}),s.jsxs(Et,{children:[s.jsx(Mt,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>j.current?.click(),className:"inline-flex items-center gap-1 h-6 px-2 rounded-md typography-micro text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(I,{name:"attachment-2",className:"h-3 w-3"}),o("multirun.launcher.attachments.attach")]})}),s.jsx(Ft,{children:o("multirun.launcher.attachments.tooltip")})]}),u.map(F=>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:[F.mimeType.startsWith("image/")?s.jsx(I,{name:"file-image",className:"h-3 w-3 text-muted-foreground"}):s.jsx(I,{name:"file",className:"h-3 w-3 text-muted-foreground"}),s.jsx("span",{className:"truncate max-w-[100px]",title:F.filename,children:F.filename}),s.jsx("button",{type:"button",onClick:()=>ce(F.id),className:"text-muted-foreground hover:text-destructive",children:s.jsx(I,{name:"close",className:"h-3 w-3"})})]},F.id))]})]}),l.map((F,ue)=>s.jsx(Pk,{group:F,groupIndex:ue,canRemove:l.length>1,onUpdate:Fe,onRemove:he},F.id)),s.jsxs("button",{type:"button",onClick:Ie,className:"flex items-center gap-1.5 py-2 px-3 -mx-3 rounded-lg typography-meta font-medium text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50 transition-colors",children:[s.jsx(I,{name:"add",className:"h-3.5 w-3.5"}),o("multirun.launcher.groups.addGroup")]}),Le&&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:Le})]})})}),s.jsx("div",{className:"shrink-0 px-4 sm:px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-2xl flex items-center justify-end gap-2",children:[!je&&L!==null?s.jsxs("div",{className:"mr-auto flex min-w-0 items-center gap-1.5 typography-micro text-muted-foreground",children:[s.jsx(I,{name:"information",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:o("multirun.launcher.project.gitRequired")})]}):null,s.jsx(Ve,{type:"button",variant:"ghost",size:"sm",onClick:n,children:o("multirun.launcher.actions.cancel")}),s.jsx(Ve,{type:"submit",size:"sm",disabled:!de||y,children:y?o("multirun.launcher.actions.creating"):s.jsx(s.Fragment,{children:o("multirun.launcher.actions.startWithRunCount",{count:xe})})})]})})]})},Pk=t=>{const e=ft.c(99),{group:n,groupIndex:r,canRemove:o,onUpdate:a,onRemove:c}=t,{t:l}=Nt(),[d,f]=i.useState(!1),[m,u]=i.useState(""),[p,y]=i.useState(!1),[g,b]=i.useState(""),[x,h]=i.useState(!1),[C,w]=i.useState(""),v=i.useRef(null),S=i.useRef(null),k=i.useRef(null),j=i.useRef(null);let A;e[0]!==n.id||e[1]!==n.models||e[2]!==a?(A=W=>{n.models.length>=Bl||a(n.id,{models:[...n.models,W]})},e[0]=n.id,e[1]=n.models,e[2]=a,e[3]=A):A=e[3];const D=A;let N;e[4]!==n.id||e[5]!==n.models||e[6]!==a?(N=W=>{a(n.id,{models:n.models.filter((ge,we)=>we!==W)})},e[4]=n.id,e[5]=n.models,e[6]=a,e[7]=N):N=e[7];const B=N;let T;e[8]!==n.id||e[9]!==n.models||e[10]!==a?(T=(W,ge)=>{a(n.id,{models:n.models.map((we,G)=>G===W?ge:we)})},e[8]=n.id,e[9]=n.models,e[10]=a,e[11]=T):T=e[11];const E=T;let _;e[12]===Symbol.for("react.memo_cache_sentinel")?(_=(W,ge)=>{if(W.startsWith("/")){const Oe=W.indexOf(" "),Ae=W.indexOf(`
|
|
233
|
-
`),J=Math.min(Oe===-1?W.length:Oe,Ae===-1?W.length:Ae);if(ge<=J&&Oe===-1){b(W.substring(1,J)),y(!0),f(!1),h(!1);return}}y(!1);const we=W.substring(0,ge),G=we.lastIndexOf("#");if(G!==-1){const Oe=G>0?we[G-1]:null,Ae=we.substring(G+1);if((!Oe||/\s/.test(Oe))&&!Ae.includes(" ")&&!Ae.includes(`
|
|
234
|
-
`)){w(Ae),h(!0),f(!1);return}}h(!1);const Se=we.lastIndexOf("@");if(Se!==-1){const Oe=Se>0?we[Se-1]:null,Ae=we.substring(Se+1);(!Oe||/\s/.test(Oe))&&!Ae.includes(" ")&&!Ae.includes(`
|
|
235
|
-
`)?(u(Ae),f(!0)):f(!1);return}f(!1)},e[12]=_):_=e[12];const R=_;let z;e[13]!==n.id||e[14]!==a?(z=W=>{a(n.id,{prompt:W})},e[13]=n.id,e[14]=a,e[15]=z):z=e[15];const V=z;let $;e[16]!==n.prompt||e[17]!==V?($=W=>{const ge=n.prompt,G=v.current?.selectionStart??ge.length,Oe=ge.substring(0,G).lastIndexOf("@"),Ae=W.relativePath&&W.relativePath.trim().length>0?W.relativePath.trim():W.path||W.name,J=Oe!==-1?Oe:G,O=`${ge.substring(0,J)}@${Ae} ${ge.substring(G)}`,ae=J+Ae.length+2;V(O),f(!1),u(""),requestAnimationFrame(()=>{const ne=v.current;ne&&(ne.selectionStart=ae,ne.selectionEnd=ae,ne.focus()),R(O,ae)})},e[16]=n.prompt,e[17]=V,e[18]=$):$=e[18];const M=$;let te;e[19]!==n.prompt||e[20]!==V?(te=W=>{const ge=n.prompt,G=v.current?.selectionStart??ge.length,Oe=ge.substring(0,G).lastIndexOf("@"),Ae=Oe!==-1?Oe:G,J=`${ge.substring(0,Ae)}@${W} ${ge.substring(G)}`,O=Ae+W.length+2;V(J),f(!1),u(""),requestAnimationFrame(()=>{const ae=v.current;ae&&(ae.selectionStart=O,ae.selectionEnd=O,ae.focus()),R(J,O)})},e[19]=n.prompt,e[20]=V,e[21]=te):te=e[21];const re=te;let Q;e[22]!==V?(Q=W=>{const ge=`/${W.name} `;V(ge),y(!1),b(""),h(!1),requestAnimationFrame(()=>{const we=v.current;we&&(we.focus(),we.selectionStart=we.value.length,we.selectionEnd=we.value.length),R(ge,ge.length)})},e[22]=V,e[23]=Q):Q=e[23];const H=Q;let X;e[24]!==n.prompt||e[25]!==V?(X=(W,ge)=>{const we=n.prompt,Se=v.current?.selectionStart??we.length,Ae=we.substring(0,Se).lastIndexOf("#"),J=Ae!==-1?Ae:Se,O=`${we.substring(0,J)}#${ge} ${we.substring(Se)}`,ae=J+ge.length+2;V(O),h(!1),w(""),requestAnimationFrame(()=>{const ne=v.current;ne&&(ne.selectionStart=ae,ne.selectionEnd=ae,ne.focus()),R(O,ae)})},e[24]=n.prompt,e[25]=V,e[26]=X):X=e[26];const oe=X;let fe;e[27]!==p||e[28]!==d||e[29]!==x?(fe=W=>{if(p&&k.current&&(W.key==="Enter"||W.key==="ArrowUp"||W.key==="ArrowDown"||W.key==="Escape"||W.key==="Tab")){W.preventDefault(),k.current.handleKeyDown(W.key);return}d&&S.current&&(W.key==="Enter"||W.key==="ArrowUp"||W.key==="ArrowDown"||W.key==="Escape"||W.key==="Tab")&&(W.preventDefault(),S.current.handleKeyDown(W.key)),x&&j.current&&(W.key==="Enter"||W.key==="ArrowUp"||W.key==="ArrowDown"||W.key==="Escape"||W.key==="Tab")&&(W.preventDefault(),j.current.handleKeyDown(W.key))},e[27]=p,e[28]=d,e[29]=x,e[30]=fe):fe=e[30];const ve=fe,ie=r+1;let Ne;e[31]!==l||e[32]!==ie?(Ne=l("multirun.launcher.groups.groupLabel",{index:ie}),e[31]=l,e[32]=ie,e[33]=Ne):Ne=e[33];let K;e[34]!==Ne?(K=s.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ne}),e[34]=Ne,e[35]=K):K=e[35];let pe;e[36]!==o||e[37]!==n.id||e[38]!==c||e[39]!==l?(pe=o&&s.jsx("button",{type:"button",onClick:()=>c(n.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10","aria-label":l("multirun.launcher.groups.removeGroup"),children:s.jsx(I,{name:"close",className:"h-3.5 w-3.5"})}),e[36]=o,e[37]=n.id,e[38]=c,e[39]=l,e[40]=pe):pe=e[40];let L;e[41]!==K||e[42]!==pe?(L=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[K,pe]}),e[41]=K,e[42]=pe,e[43]=L):L=e[43];let se;e[44]!==l?(se=l("multirun.launcher.groups.prompt.label"),e[44]=l,e[45]=se):se=e[45];let Z;e[46]!==se?(Z=s.jsx(Di,{required:!0,children:se}),e[46]=se,e[47]=Z):Z=e[47];const je=n.prompt;let De;e[48]!==V?(De=W=>{const ge=W.target.value;V(ge);const we=W.target.selectionStart??ge.length;R(ge,we)},e[48]=V,e[49]=De):De=e[49];let Le;e[50]!==l?(Le=l("multirun.launcher.groups.prompt.placeholder"),e[50]=l,e[51]=Le):Le=e[51];let Me;e[52]!==n.prompt||e[53]!==ve||e[54]!==De||e[55]!==Le?(Me=s.jsx(Ii,{ref:v,value:je,onChange:De,onKeyDown:ve,placeholder:Le,className:"typography-meta min-h-[80px] max-h-[200px] resize-none overflow-y-auto field-sizing-content",required:!0}),e[52]=n.prompt,e[53]=ve,e[54]=De,e[55]=Le,e[56]=Me):Me=e[56];let Fe;e[57]!==g||e[58]!==H||e[59]!==p?(Fe=p?s.jsx(fm,{ref:k,searchQuery:g,onCommandSelect:H,onClose:()=>y(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[57]=g,e[58]=H,e[59]=p,e[60]=Fe):Fe=e[60];let he;e[61]!==re||e[62]!==M||e[63]!==m||e[64]!==d?(he=d?s.jsx(mm,{ref:S,searchQuery:m,onFileSelect:M,onAgentSelect:re,onClose:()=>f(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[61]=re,e[62]=M,e[63]=m,e[64]=d,e[65]=he):he=e[65];let Ie;e[66]!==oe||e[67]!==x||e[68]!==C?(Ie=x?s.jsx(hm,{ref:j,searchQuery:C,onSnippetSelect:oe,onClose:()=>h(!1),style:{left:0,top:"auto",bottom:"calc(100% + 6px)",marginBottom:0,maxWidth:"100%"}}):null,e[66]=oe,e[67]=x,e[68]=C,e[69]=Ie):Ie=e[69];let me;e[70]!==Me||e[71]!==Fe||e[72]!==he||e[73]!==Ie?(me=s.jsxs("div",{className:"relative",children:[Me,Fe,he,Ie]}),e[70]=Me,e[71]=Fe,e[72]=he,e[73]=Ie,e[74]=me):me=e[74];let ce;e[75]!==Z||e[76]!==me?(ce=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Z,me]}),e[75]=Z,e[76]=me,e[77]=ce):ce=e[77];let xe;e[78]!==l?(xe=l("multirun.launcher.models.info",{max:Bl}),e[78]=l,e[79]=xe):xe=e[79];let ke;e[80]!==xe?(ke=s.jsx(xa,{children:xe}),e[80]=xe,e[81]=ke):ke=e[81];let de;e[82]!==l?(de=l("multirun.launcher.models.label"),e[82]=l,e[83]=de):de=e[83];let P;e[84]!==ke||e[85]!==de?(P=s.jsx(Di,{required:!0,info:ke,children:de}),e[84]=ke,e[85]=de,e[86]=P):P=e[86];let F;e[87]!==n.models||e[88]!==D||e[89]!==B||e[90]!==E?(F=s.jsx(kh,{selectedModels:n.models,onAdd:D,onRemove:B,onUpdate:E,minModels:1,maxModels:Bl}),e[87]=n.models,e[88]=D,e[89]=B,e[90]=E,e[91]=F):F=e[91];let ue;e[92]!==P||e[93]!==F?(ue=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[P,F]}),e[92]=P,e[93]=F,e[94]=ue):ue=e[94];let be;return e[95]!==L||e[96]!==ce||e[97]!==ue?(be=s.jsxs("div",{className:"rounded-lg border border-border p-3 space-y-3",children:[L,ce,ue]}),e[95]=L,e[96]=ce,e[97]=ue,e[98]=be):be=e[98],be},Tk=i.createContext(null),Rk=t=>{const e=ft.c(3),{children:n,value:r}=t;let o;return e[0]!==n||e[1]!==r?(o=s.jsx(Tk.Provider,{value:r,children:n}),e[0]=n,e[1]=r,e[2]=o):o=e[2],o},Df=co(()=>lo(()=>import("./TerminalView-fTYjnQkh.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(t=>({default:t.TerminalView}))),Ek=co(()=>lo(()=>import("./DiagramView-Cb58svCq.js"),__vite__mapDeps([8,1,3,4,2,5,6,7])).then(t=>({default:t.DiagramView}))),Mk=co(()=>lo(()=>import("./runtimeEndpointReset-By39StyB.js").then(t=>t.a9),__vite__mapDeps([5,1,2,3,4,6])).then(t=>({default:t.SettingsView}))),Fk=co(()=>lo(()=>import("./SettingsWindow-CY8q4msv.js"),__vite__mapDeps([9,1,2,3,4,5,6])).then(t=>({default:t.SettingsWindow}))),Ok=co(()=>lo(()=>import("./MultiRunWindow-BPSxV_B7.js"),__vite__mapDeps([10,1,2,3,4,5,6,7])).then(t=>({default:t.MultiRunWindow}))),Lk=()=>{const o=Ee(X=>X.isSidebarOpen),a=Ee(X=>X.isRightSidebarOpen),c=Ee(X=>X.isBottomTerminalOpen),l=Ee(X=>X.setRightSidebarOpen),d=Ee(X=>X.setBottomTerminalOpen),f=Ee(X=>X.activeMainTab),m=Ee(X=>X.setIsMobile),u=Ee(X=>X.isSessionSwitcherOpen),p=Ee(X=>X.isSettingsDialogOpen),y=Ee(X=>X.setSettingsDialogOpen),g=Ee(X=>X.isMultiRunLauncherOpen),b=Ee(X=>X.setMultiRunLauncherOpen),x=Ee(X=>X.multiRunLauncherPrefillPrompt),{isMobile:h,isTablet:C}=Or(),w=i.useRef(!1),v=i.useRef(!1),S=i.useRef(!1),[k,j]=i.useState(!1),[A,D]=i.useState(!1),[N,B]=i.useState(!1),[T,E]=i.useState(!1),_=i.useCallback(X=>{j(X),Ee.getState().setSessionSwitcherOpen(X)},[]),R=i.useRef(!1),z=i.useRef(typeof window>"u"?0:window.innerWidth),V=gd(-z.current),$=tt.useRef(0),M=gd(z.current),te=tt.useRef(0);tt.useEffect(()=>{h&&($.current=window.innerWidth,te.current=window.innerWidth)},[h]),tt.useEffect(()=>{if(!h){B(!1);return}k&&B(!0),xd(V,k?0:-$.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[k,h,V]),tt.useEffect(()=>{if(!h){E(!1);return}R.current=A,A&&E(!0),xd(M,A?0:te.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[h,A,M]),tt.useEffect(()=>{if(h)return V.on("change",X=>{const oe=$.current||z.current,fe=k||X>-oe+.5;B(ve=>ve===fe?ve:fe)})},[h,V,k]),tt.useEffect(()=>{if(h)return M.on("change",X=>{const oe=te.current||z.current,fe=A||X<oe-.5;E(ve=>ve===fe?ve:fe)})},[h,A,M]),tt.useEffect(()=>{h&&!u&&k&&_(!1)},[u,h,k,_]),tt.useEffect(()=>{if(!h){S.current=!1;return}S.current||(S.current=!0,_(!1),D(!1),Ee.getState().isRightSidebarOpen&&l(!1))},[h,_,l]),tt.useEffect(()=>{if(!h||f!=="chat"||k||A||p)return;let X=!1,oe;const fe=ve=>{oe=window.setTimeout(()=>{if(X)return;const ie=ut.getState(),Ne=Ee.getState();if(!(Ne.activeMainTab!=="chat"||Ne.isSettingsDialogOpen||ie.currentSessionId||ie.newSessionDraft?.open)){if(ie.isLoading){fe(250);return}ie.openNewSessionDraft()}},ve)};return fe(500),()=>{X=!0,oe!==void 0&&window.clearTimeout(oe)}},[f,h,p,k,A]),tt.useEffect(()=>{!h||!p||(_(!1),D(!1),a&&l(!1))},[h,p,a,_,l]),Zx(),i.useEffect(()=>{Ee.getState().isMobile!==h&&m(h)},[h,m]),i.useEffect(()=>{if(typeof window>"u")return;let X;const oe=()=>{X===void 0&&(X=window.requestAnimationFrame(()=>{X=void 0,Ee.getState().updateProportionalSidebarWidths()}))};return window.addEventListener("resize",oe),()=>{window.removeEventListener("resize",oe),X!==void 0&&window.cancelAnimationFrame(X)}},[]),i.useEffect(()=>{if(typeof window>"u")return;let X;const oe=()=>{const ve=Ee.getState(),ie=window.innerWidth,Ne=window.innerHeight;if(!h&&!C){const K=ie<1140,pe=ie>=1220;K?ve.isRightSidebarOpen&&(l(!1),w.current=!0):pe&&w.current&&(l(!0),w.current=!1);const L=Ne<640,se=Ne>=700;L?ve.isBottomTerminalOpen&&(d(!1),v.current=!0):se&&v.current&&(d(!0),v.current=!1)}},fe=()=>{X===void 0&&(X=window.requestAnimationFrame(()=>{X=void 0,oe()}))};return oe(),window.addEventListener("resize",fe),()=>{window.removeEventListener("resize",fe),X!==void 0&&window.cancelAnimationFrame(X)}},[h,C,d,l]),i.useEffect(()=>{if(typeof window>"u")return;const X=Ee.subscribe((oe,fe)=>{const ve=window.innerWidth,ie=window.innerHeight,Ne=ve>=1220,K=ie>=700;oe.isRightSidebarOpen!==fe.isRightSidebarOpen&&Ne&&(w.current=!1),oe.isBottomTerminalOpen!==fe.isBottomTerminalOpen&&K&&(v.current=!1)});return()=>{X()}},[h,C,d,l]);const re=i.useCallback(()=>{k&&_(!1),D(!A)},[k,A,_]),Q=i.useMemo(()=>{switch(f){case"plan":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(sh,{})});case"git":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(tc,{isActive:!A})});case"diff":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Jm,{})});case"terminal":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Df,{})});case"files":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(th,{})});case"context":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Km,{})});case"diagram":return s.jsx(i.Suspense,{fallback:null,children:s.jsx(Ek,{})});default:return null}},[f,A]),H=f==="chat";return s.jsx(eb,{children:s.jsxs("div",{"data-page-scroll-lock":"true",className:Te("main-content-safe-area",h?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[s.jsx(tj,{}),s.jsx(zj,{}),s.jsx(Gj,{}),s.jsx(xk,{}),h?s.jsxs(Rk,{value:{leftDrawerOpen:k,rightDrawerOpen:A,toggleLeftDrawer:()=>{const X=!k;A&&D(!1),_(X)},toggleRightDrawer:re,leftDrawerX:V,rightDrawerX:M,leftDrawerWidth:$,rightDrawerWidth:te,setMobileLeftDrawerOpen:_,setRightSidebarOpen:D},children:[!p&&s.jsx(nu,{onToggleLeftDrawer:()=>{const X=!k;A&&D(!1),_(X)},onToggleRightDrawer:()=>{re()},leftDrawerOpen:k,rightDrawerOpen:A}),s.jsx("div",{"data-page-scroll-lock":"true",className:Te("flex flex-1 overflow-hidden relative",p&&"hidden"),children:s.jsxs("main",{className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[s.jsx("div",{className:Te("absolute inset-0",!H&&"invisible"),children:s.jsx(Xs,{children:s.jsx(Ql,{})})}),Q&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Xs,{children:Q})}),g&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",children:s.jsx(Xs,{children:s.jsx(Ik,{initialPrompt:x,onCreated:()=>b(!1),onCancel:()=>b(!1)})})}),N&&s.jsx(bd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:V},"aria-hidden":!k,children:s.jsx(Xs,{children:s.jsx(kf,{mobileVariant:!0})})}),T&&s.jsx(bd.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:M},"aria-hidden":!A,children:s.jsx(Xs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(tc,{isActive:A})})})})]})}),p&&s.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:s.jsx(Xs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Mk,{onClose:()=>y(!1)})})})})]}):s.jsxs(s.Fragment,{children:[s.jsx(dy,{}),s.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[s.jsx(ay,{isOpen:o,isMobile:h,className:"border-border/50",topBar:s.jsx(ly,{}),children:s.jsx(kf,{})}),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(nu,{}),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:Te("absolute inset-0",!H&&"invisible"),children:s.jsx(Xs,{children:s.jsx(Ql,{})})}),Q&&s.jsx("div",{className:"absolute inset-0",children:s.jsx(Xs,{children:Q})})]}),s.jsx(ej,{})]})}),s.jsx(sy,{isOpen:c,isMobile:h,children:c?s.jsx(Xs,{children:s.jsx(i.Suspense,{fallback:null,children:s.jsx(Df,{})})}):null})]}),s.jsx(gy,{isOpen:a,className:"bg-background border-t border-border/50",children:s.jsx(Xs,{children:s.jsx(Lv,{})})})]})]})]}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(Fk,{open:p,onOpenChange:y})}),s.jsx(i.Suspense,{fallback:null,children:s.jsx(Ok,{open:g,onOpenChange:b,initialPrompt:x})})]})]})})},Bk=t=>{if(t<1e3)return`${Math.round(t)}ms`;const e=t/1e3;if(e<60)return`${e.toFixed(1)}s`;const n=Math.floor(e/60),r=Math.round(e%60);return`${n}m ${r}s`},$n=t=>{const e=ft.c(8),{label:n,value:r}=t;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[0]=o):o=e[0];let a;e[1]!==n?(a=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:n}),e[1]=n,e[2]=a):a=e[2];let c;e[3]!==r?(c=s.jsx("div",{className:"typography-markdown font-semibold text-[var(--surface-foreground)]",children:r}),e[3]=r,e[4]=c):c=e[4];let l;return e[5]!==a||e[6]!==c?(l=s.jsxs("div",{className:"rounded-md p-2",style:o,children:[a,c]}),e[5]=a,e[6]=c,e[7]=l):l=e[7],l},If=t=>{const e=ft.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($k,0),e[8]=r.entries,e[9]=d):d=e[9];const f=d;let m;e[10]!==n?(m=s.jsx("div",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:n}),e[10]=n,e[11]=m):m=e[11];let u;e[12]!==r.durationMs||e[13]!==r.startedAt||e[14]!==a?(u=r.startedAt?Bk(r.durationMs):a("memoryDebugPanel.common.idle"),e[12]=r.durationMs,e[13]=r.startedAt,e[14]=a,e[15]=u):u=e[15];let p;e[16]!==u?(p=s.jsx("div",{className:"typography-meta text-[var(--surface-muted-foreground)]",children:u}),e[16]=u,e[17]=p):p=e[17];let y;e[18]!==m||e[19]!==p?(y=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[m,p]}),e[18]=m,e[19]=p,e[20]=y):y=e[20];let g;e[21]!==a?(g=a("memoryDebugPanel.metric.metrics"),e[21]=a,e[22]=g):g=e[22];let b;e[23]!==r.entries.length||e[24]!==g?(b=s.jsx($n,{label:g,value:r.entries.length}),e[23]=r.entries.length,e[24]=g,e[25]=b):b=e[25];let x;e[26]!==a?(x=a("memoryDebugPanel.metric.samples"),e[26]=a,e[27]=x):x=e[27];let h;e[28]!==x||e[29]!==f?(h=s.jsx($n,{label:x,value:f}),e[28]=x,e[29]=f,e[30]=h):h=e[30];let C;e[31]!==a?(C=a("memoryDebugPanel.metric.lastUpdate"),e[31]=a,e[32]=C):C=e[32];let w;e[33]!==r.lastUpdatedAt||e[34]!==a?(w=r.lastUpdatedAt?a("memoryDebugPanel.common.live"):a("memoryDebugPanel.common.notAvailable"),e[33]=r.lastUpdatedAt,e[34]=a,e[35]=w):w=e[35];let v;e[36]!==C||e[37]!==w?(v=s.jsx($n,{label:C,value:w}),e[36]=C,e[37]=w,e[38]=v):v=e[38];let S;e[39]!==h||e[40]!==v||e[41]!==b?(S=s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[b,h,v]}),e[39]=h,e[40]=v,e[41]=b,e[42]=S):S=e[42],c=s.jsxs("div",{className:"space-y-2 border-t border-[var(--interactive-border)] pt-2 first:border-t-0 first:pt-0",children:[y,S,l.length===0?s.jsx("div",{className:"rounded-md p-3 typography-meta text-[var(--surface-muted-foreground)]",style:{backgroundColor:"color-mix(in srgb, var(--surface-muted) 45%, transparent)"},children:o}):s.jsx(Wn,{outerClassName:"max-h-64",className:"pr-1",children:s.jsx("div",{className:"space-y-1",children:l.map(k=>s.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] p-2",style:{backgroundColor:"color-mix(in srgb, var(--surface-elevated) 88%, transparent)"},children:[s.jsx("div",{className:"typography-meta font-medium text-[var(--surface-foreground)] break-all",children:k.metric}),s.jsxs("div",{className:"mt-1 grid grid-cols-4 gap-2 typography-meta text-[var(--surface-muted-foreground)]",children:[s.jsx("span",{children:a("memoryDebugPanel.metric.countValue",{value:k.count})}),s.jsx("span",{children:a("memoryDebugPanel.metric.avgValue",{value:k.avg})}),s.jsx("span",{children:a("memoryDebugPanel.metric.maxValue",{value:k.max})}),s.jsx("span",{children:a("memoryDebugPanel.metric.totalValue",{value:k.total})})]})]},k.metric))})})]}),e[0]=o,e[1]=r.durationMs,e[2]=r.entries,e[3]=r.lastUpdatedAt,e[4]=r.startedAt,e[5]=a,e[6]=n,e[7]=c}else c=e[7];return c},_k=t=>{const e=ft.c(99),{onClose:n}=t,{t:r}=Nt(),[o,a]=i.useState("memory"),[c,l]=i.useState("idle"),d=ut(zk),f=pm(Wk),m=Ic(),u=px(Uk),p=sr(Hk),[y,g]=i.useState(Gk),[b,x]=i.useState(Kk);let h;e[0]!==y.entries?(h=new Map,y.entries.forEach(de=>{h.set(de.metric,de.count)}),e[0]=y.entries,e[1]=h):h=e[1];let C;e[2]!==h?(C=h.get("ui.message_list.render")??0,e[2]=h,e[3]=C):C=e[3];let w;e[4]!==h?(w=h.get("ui.message_list.render.streaming")??0,e[4]=h,e[5]=w):w=e[5];let v;e[6]!==h?(v=h.get("ui.chat_message.render")??0,e[6]=h,e[7]=v):v=e[7];let S;e[8]!==h?(S=h.get("ui.chat_message.render.streaming")??0,e[8]=h,e[9]=S):S=e[9];let k;e[10]!==h?(k=h.get("ui.chat_message.render.static_during_stream")??0,e[10]=h,e[11]=k):k=e[11];let j;e[12]!==h?(j=h.get("ui.chat_message.render.static_outside_active_turn_during_stream")??0,e[12]=h,e[13]=j):j=e[13];let A;e[14]!==C||e[15]!==w||e[16]!==v||e[17]!==S||e[18]!==k||e[19]!==j?(A={messageListRender:C,messageListRenderStreaming:w,chatMessageRender:v,chatMessageRenderStreaming:S,chatMessageRenderStaticDuringStream:k,chatMessageRenderStaticOutsideActiveTurnDuringStream:j},e[14]=C,e[15]=w,e[16]=v,e[17]=S,e[18]=k,e[19]=j,e[20]=A):A=e[20];const D=A;let N,B;e[21]===Symbol.for("react.memo_cache_sentinel")?(N=()=>{const de=()=>{g(ra()),x(ia())};de();const P=window.setInterval(de,500);return()=>window.clearInterval(P)},B=[],e[21]=N,e[22]=B):(N=e[21],B=e[22]),i.useEffect(N,B);let T,E;e[23]!==c?(T=()=>{if(c==="idle")return;const de=window.setTimeout(()=>{l("idle")},1500);return()=>window.clearTimeout(de)},E=[c],e[23]=c,e[24]=T,e[25]=E):(T=e[24],E=e[25]),i.useEffect(T,E);let _=0,R=0,z=0;for(const de of Object.keys(u)){const P=u[de]??[];R=R+P.length;for(const F of P)F.role==="user"?z=z+1:F.role==="assistant"&&(_=_+1)}let V;e[26]!==_||e[27]!==R||e[28]!==z?(V={assistant:_,total:R,user:z},e[26]=_,e[27]=R,e[28]=z,e[29]=V):V=e[29];const $=V;let M;if(e[30]!==d||e[31]!==u||e[32]!==f||e[33]!==m||e[34]!==r){let de;e[36]!==d||e[37]!==u||e[38]!==f||e[39]!==r?(de=P=>{const F=u[P.id]??[];let ue=0,be=0;for(const ge of F)ge.role==="user"?be=be+1:ge.role==="assistant"&&(ue=ue+1);const W=f.get(P.id);return{id:P.id,title:P.title||r("memoryDebugPanel.common.untitled"),assistantMessageCount:ue,messageCount:F.length,userMessageCount:be,isStreaming:W?.isStreaming||!1,isZombie:W?.isZombie||!1,backgroundCount:W?.backgroundMessageCount||0,lastAccessed:W?.lastAccessedAt||0,isCurrent:P.id===d}},e[36]=d,e[37]=u,e[38]=f,e[39]=r,e[40]=de):de=e[40],M=m.map(de).sort(qk),e[30]=d,e[31]=u,e[32]=f,e[33]=m,e[34]=r,e[35]=M}else M=e[35];const te=M;let re;e[41]!==u?(re=Object.keys(u),e[41]=u,e[42]=re):re=e[42];const Q=re.length;let H;e[43]===Symbol.for("react.memo_cache_sentinel")?(H=async()=>{try{const de={generatedAt:new Date().toISOString(),ui:ra(),vscode:ia()};await navigator.clipboard.writeText(JSON.stringify(de,null,2)),l("copied")}catch{l("error")}},e[43]=H):H=e[43];const X=H;let oe;e[44]===Symbol.for("react.memo_cache_sentinel")?(oe={backgroundColor:"color-mix(in srgb, var(--surface-background) 94%, transparent)"},e[44]=oe):oe=e[44];let fe;e[45]!==o?(fe=o==="memory"?s.jsx(I,{name:"database-2",className:"h-4 w-4 text-[var(--surface-foreground)]"}):s.jsx(I,{name:"bar-chart-box",className:"h-4 w-4 text-[var(--surface-foreground)]"}),e[45]=o,e[46]=fe):fe=e[46];let ve;e[47]!==r?(ve=r("memoryDebugPanel.title"),e[47]=r,e[48]=ve):ve=e[48];let ie;e[49]!==ve?(ie=s.jsx("h3",{className:"typography-ui-label font-semibold text-[var(--surface-foreground)]",children:ve}),e[49]=ve,e[50]=ie):ie=e[50];let Ne;e[51]!==fe||e[52]!==ie?(Ne=s.jsxs("div",{className:"flex items-center gap-2",children:[fe,ie]}),e[51]=fe,e[52]=ie,e[53]=Ne):Ne=e[53];let K;e[54]!==o?(K=o==="streaming"?s.jsxs(s.Fragment,{children:[s.jsx(Ve,{size:"xs",variant:"ghost",onClick:X,children:s.jsx(I,{name:"file-copy",className:"h-3.5 w-3.5"})}),s.jsx(Ve,{size:"xs",variant:"ghost",onClick:()=>{Sp(),g(ra()),x(ia())},children:s.jsx(I,{name:"refresh",className:"h-3.5 w-3.5"})})]}):null,e[54]=o,e[55]=K):K=e[55];let pe;e[56]!==n?(pe=n?s.jsx(Ve,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:s.jsx(I,{name:"close",className:"h-4 w-4"})}):null,e[56]=n,e[57]=pe):pe=e[57];let L;e[58]!==K||e[59]!==pe?(L=s.jsxs("div",{className:"flex items-center gap-1",children:[K,pe]}),e[58]=K,e[59]=pe,e[60]=L):L=e[60];let se;e[61]!==Ne||e[62]!==L?(se=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[Ne,L]}),e[61]=Ne,e[62]=L,e[63]=se):se=e[63];let Z;e[64]===Symbol.for("react.memo_cache_sentinel")?(Z={backgroundColor:"color-mix(in srgb, var(--surface-muted) 55%, transparent)"},e[64]=Z):Z=e[64];const je=o==="memory"?"secondary":"ghost";let De;e[65]===Symbol.for("react.memo_cache_sentinel")?(De=()=>a("memory"),e[65]=De):De=e[65];let Le;e[66]!==r?(Le=r("memoryDebugPanel.tabs.memory"),e[66]=r,e[67]=Le):Le=e[67];let Me;e[68]!==je||e[69]!==Le?(Me=s.jsx(Ve,{size:"sm",variant:je,className:"flex-1",onClick:De,children:Le}),e[68]=je,e[69]=Le,e[70]=Me):Me=e[70];const Fe=o==="streaming"?"secondary":"ghost";let he;e[71]===Symbol.for("react.memo_cache_sentinel")?(he=()=>a("streaming"),e[71]=he):he=e[71];let Ie;e[72]!==r?(Ie=r("memoryDebugPanel.tabs.streaming"),e[72]=r,e[73]=Ie):Ie=e[73];let me;e[74]!==Fe||e[75]!==Ie?(me=s.jsx(Ve,{size:"sm",variant:Fe,className:"flex-1",onClick:he,children:Ie}),e[74]=Fe,e[75]=Ie,e[76]=me):me=e[76];let ce;e[77]!==Me||e[78]!==me?(ce=s.jsxs("div",{className:"mb-3 flex gap-1 rounded-md p-1",style:Z,children:[Me,me]}),e[77]=Me,e[78]=me,e[79]=ce):ce=e[79];let xe;e[80]!==o||e[81]!==Q||e[82]!==c||e[83]!==d||e[84]!==u||e[85]!==$||e[86]!==f||e[87]!==te||e[88]!==m||e[89]!==D||e[90]!==y||e[91]!==r||e[92]!==p||e[93]!==b?(xe=o==="memory"?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[s.jsx($n,{label:r("memoryDebugPanel.metric.totalMessages"),value:$.total}),s.jsx($n,{label:r("memoryDebugPanel.metric.cachedSessions"),value:`${Q} / ${Ud.MAX_SESSIONS}`}),s.jsx($n,{label:r("memoryDebugPanel.metric.userMessages"),value:$.user}),s.jsx($n,{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:gx()})})]}),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:Ud.ZOMBIE_TIMEOUT/1e3/60})})]}),s.jsxs("div",{className:"flex justify-between gap-2",children:[s.jsx("span",{className:"text-[var(--surface-muted-foreground)]",children:r("memoryDebugPanel.metric.githubTotalRequests")}),s.jsx("span",{className:"text-[var(--surface-foreground)]",children:p})]})]}),s.jsxs("div",{className:"border-t border-[var(--interactive-border)] pt-2",children:[s.jsx("div",{className:"mb-1 typography-meta font-semibold text-[var(--surface-foreground)]",children:r("memoryDebugPanel.section.sessionsInMemory")}),s.jsx(Wn,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:te.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(I,{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(Ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[DebugPanel] Session store state:",{sessions:m.map(Yk),currentSessionId:d,cachedSessions:Object.keys(u),messageRoleCounts:$,sessionMessageRoleCounts:te.map(Qk),memoryStates:Object.fromEntries(f)})},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(Ve,{size:"xs",variant:"outline",onClick:X,children:r("memoryDebugPanel.actions.copyJson")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx($n,{label:r("memoryDebugPanel.metric.uiMetrics"),value:y.entries.length}),s.jsx($n,{label:r("memoryDebugPanel.metric.vscodeMetrics"),value:b.entries.length}),s.jsx($n,{label:r("memoryDebugPanel.metric.messageListRenders"),value:D.messageListRender}),s.jsx($n,{label:r("memoryDebugPanel.metric.messageListStreamRenders"),value:D.messageListRenderStreaming}),s.jsx($n,{label:r("memoryDebugPanel.metric.chatMessageRenders"),value:D.chatMessageRender}),s.jsx($n,{label:r("memoryDebugPanel.metric.chatMessageStreamRenders"),value:D.chatMessageRenderStreaming}),s.jsx($n,{label:r("memoryDebugPanel.metric.chatMessageStaticDuringStream"),value:D.chatMessageRenderStaticDuringStream}),s.jsx($n,{label:r("memoryDebugPanel.metric.chatMessageStaticOutsideActiveTurn"),value:D.chatMessageRenderStaticOutsideActiveTurnDuringStream})]}),s.jsx(If,{title:r("memoryDebugPanel.section.uiStreamingMetrics"),snapshot:y,emptyLabel:r("memoryDebugPanel.section.noUiSamples")}),b.entries.length>0?s.jsx(If,{title:r("memoryDebugPanel.section.vscodeBridgeMetrics"),snapshot:b,emptyLabel:r("memoryDebugPanel.section.noVscodeSamples")}):null]}),e[80]=o,e[81]=Q,e[82]=c,e[83]=d,e[84]=u,e[85]=$,e[86]=f,e[87]=te,e[88]=m,e[89]=D,e[90]=y,e[91]=r,e[92]=p,e[93]=b,e[94]=xe):xe=e[94];let ke;return e[95]!==se||e[96]!==ce||e[97]!==xe?(ke=s.jsxs(xx,{className:"fixed bottom-4 right-4 z-50 w-[28rem] p-4 shadow-none bottom-safe-area",style:oe,children:[se,ce,xe]}),e[95]=se,e[96]=ce,e[97]=xe,e[98]=ke):ke=e[98],ke},Vk=_k;function $k(t,e){return t+e.count}function zk(t){return t.currentSessionId}function Wk(t){return t.sessionMemoryState}function Uk(t){return t.message}function Hk(t){return t.totalRequestCount}function Gk(){return ra()}function Kk(){return ia()}function qk(t,e){return e.lastAccessed-t.lastAccessed}function Yk(t){return{id:t.id,title:t.title}}function Qk(t){return{id:t.id,title:t.title,total:t.messageCount,user:t.userMessageCount,assistant:t.assistantMessageCount}}const Jk=()=>{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()??"":""},Xk=async()=>{const t=Jk()||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")},Pf="openchamber:menu-action",_l="openchamber:check-for-updates",Zk=t=>{const e=ut(j=>j.openNewSessionDraft),n=Ee(j=>j.toggleCommandPalette),r=Ee(j=>j.setCommandPaletteOpen),o=Ee(j=>j.toggleHelpDialog),a=Ee(j=>j.toggleSidebar),c=Ee(j=>j.setSessionSwitcherOpen),l=Ee(j=>j.setActiveMainTab),d=Ee(j=>j.setSettingsDialogOpen),f=Ee(j=>j.setAboutDialogOpen),m=Ee(j=>j.toggleRightSidebar),u=Ee(j=>j.setRightSidebarOpen),p=Ee(j=>j.setRightSidebarTab),y=Ee(j=>j.toggleBottomTerminal),g=Ee(j=>j.setBottomTerminalExpanded),b=jo(j=>j.checkForUpdates),{setThemeMode:x}=Qr(),h=i.useRef(!1),C=i.useCallback(()=>{h.current||(h.current=!0,b().then(()=>{const{available:j,error:A}=jo.getState();if(A){le.error("Failed to check for updates",{description:A});return}j||le.success("You are on the latest version")}).finally(()=>{h.current=!1}))},[b]),w=i.useCallback(()=>{Er.requestDirectoryDialog()},[]),v=i.useCallback(j=>{const A=bx();if(A.length===0)return;const D=ut.getState().currentSessionId,N=A.findIndex(E=>E.id===D);let B=j>0?0:A.length-1;N>=0&&(B=(N+j+A.length)%A.length);const T=A[B];T&&(l("chat"),c(!1),ut.getState().setCurrentSession(T.id))},[l,c]),S=i.useCallback(j=>{const{activeProjectId:A,projects:D,setActiveProject:N}=Ss.getState();if(D.length===0)return;const B=D.findIndex(_=>_.id===A);let T=j>0?0:D.length-1;B>=0&&(T=(B+j+D.length)%D.length);const E=D[T];E&&N(E.id)},[]),k=i.useCallback(j=>{switch(j){case"about":f(!0);break;case"settings":d(!0);break;case"command-palette":n();break;case"quick-open":r(!0);break;case"new-session":l("chat"),c(!1),e();break;case"new-worktree-session":l("chat"),c(!1),um();break;case"change-workspace":w();break;case"toggle-right-sidebar":m();break;case"open-right-sidebar-git":u(!0),p("git");break;case"open-right-sidebar-files":u(!0),p("files");break;case"toggle-terminal":y();break;case"toggle-terminal-expanded":g(!Ee.getState().isBottomTerminalExpanded);break;case"copy":{const A=new Event("openchamber:copy",{cancelable:!0});!window.dispatchEvent(A)||Xk();break}case"theme-light":x("light");break;case"theme-dark":x("dark");break;case"theme-system":x("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":t?.();break;case"go-back":Ys.getState().goBack();break;case"go-forward":Ys.getState().goForward();break;case"previous-session":v(-1);break;case"next-session":v(1);break;case"previous-project":S(-1);break;case"next-project":S(1);break;case"help-dialog":o();break;case"download-logs":{yx().catch(()=>{le.error("Failed to collect OpenCode status")});break}}},[w,S,v,t,e,f,l,c,r,d,g,u,p,x,y,n,o,m,a]);i.useEffect(()=>{const j=D=>{const N=D.detail;N&&k(N)},A=()=>{C()};return window.addEventListener(Pf,j),window.addEventListener(_l,A),()=>{window.removeEventListener(Pf,j),window.removeEventListener(_l,A)}},[k,C]),i.useEffect(()=>{if(typeof window>"u")return;const A=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof A!="function")return;let D=null,N=null;return A("openchamber:menu-action",B=>{const T=B?.payload;typeof T=="string"&&k(T)}).then(B=>{D=B}).catch(()=>{}),A("openchamber:check-for-updates",()=>{window.dispatchEvent(new Event(_l))}).then(B=>{N=B}).catch(()=>{}),()=>{(async()=>{try{const T=D?.();T instanceof Promise&&await T}catch{}try{const T=N?.();T instanceof Promise&&await T}catch{}})()}},[k])},eC="openchamber:tray-action",Tf=5e3,tC=120,sC=45e3,Dh=20,Rf=()=>typeof window>"u"?!1:window.__OPENCHAMBER_PLATFORM__==="darwin",nC=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},rC=t=>{const e=Array.isArray(t.questions)?t.questions[0]:void 0;return e?.header||e?.question||"Question"},Ba=t=>t.time?.updated??t.time?.created??0,iC=t=>{const e=t.replace(/\\/g,"/").replace(/\/+$/,""),n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},oC=(t,e,n,r,o)=>{if(!t)return"";const a=Sx(n,r,t),c=e.project?.name,l=a?.label?.trim()||c?.trim()||iC(t),d=aa(t);let f=d&&o.get(d)||"";if(!f){for(const[m,u]of wn.getState().directories)if(aa(m)===d){f=u.status?.current??"";break}}if(!f)for(const m of r.values()){const u=m.find(p=>aa(p.path)===d);if(u?.branch){f=u.branch;break}}return f?`${l} · ${f}`:l},aC=()=>{const{results:t,dropdownProviderIds:e,displayMode:n}=mn.getState(),r=n==="remaining"?"remaining":"usage";if(!e.length)return{mode:r,groups:[]};const o=new Map(t.map(c=>[c.providerId,c])),a=[];for(const c of Sm){if(!e.includes(c.id))continue;const l=o.get(c.id);if(!l||l.configured!==!0)continue;const d=[];for(const[m,u]of Object.entries(l.usage?.windows??{})){const p=r==="remaining"?u.remainingPercent:u.usedPercent;d.push({label:yc(m),value:To(u.valueLabel,p)})}const f=!l.ok&&l.error?l.error:d.length===0?"No rate limits reported":null;a.push({provider:c.name,rows:d,status:f})}return{mode:r,groups:a}},lC=async()=>{try{if(eo())return"Local OpenChamber";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,e=Hr();if(e&&Na(e,t))return"Local OpenChamber";const r=(await qf()).hosts.find(o=>e?Na(e,Yf(o)):!1);return r?.label?.trim()?Qf(r.label.trim()):"Instance"}catch{return""}},cC=()=>{const t=new Map,e=new Map,n=[],r=new Map;let o;try{o=Aa()}catch{return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}}for(const[a,c]of o.children.entries()){const l=c.getState();l.vcs?.branch&&e.set(aa(a)??a,l.vcs.branch);for(const d of l.session)d?.id&&r.set(d.id,d.title);for(const[d,f]of Object.entries(l.session_status??{})){const m=f?.type,u=m==="busy"?"busy":m==="retry"?"retry":"idle",p=t.get(d);(!p||p==="idle")&&t.set(d,u)}for(const[d,f]of Object.entries(l.permission??{}))for(const m of f??[]){if(!m?.id)continue;const u=m.sessionID||d;n.push({kind:"permission",id:m.id,sessionId:u,sessionTitle:"",label:nC(m),directory:a})}for(const[d,f]of Object.entries(l.question??{}))for(const m of f??[]){if(!m?.id)continue;const u=m.sessionID||d;n.push({kind:"question",id:m.id,sessionId:u,sessionTitle:"",label:rC(m),directory:a})}}return{statusById:t,branchByDirectory:e,approvals:n,titleById:r}},dC=()=>{const t=jr.getState().activeSessions,e=new Set;t.filter(r=>r?.id&&!r.parentID).slice().sort((r,o)=>Ba(o)-Ba(r)).slice(0,Dh).forEach(r=>{const o=Mr(r);o&&e.add(o)});const n=new Map;for(const r of t){if(!r?.id)continue;const o=Mr(r);if(!o||!e.has(o))continue;const a=n.get(o)??[];a.push(r.id),n.set(o,a)}return n},uC=t=>{const e=cC(),n=xm.getState().index.session,r=jr.getState().activeSessions,o=new Map(e.titleById),a=new Map;for(const x of r)if(x?.id&&(x.title&&o.set(x.id,x.title),x.parentID)){const h=a.get(x.parentID)??[];h.push(x.id),a.set(x.parentID,h)}const c=x=>{const h=[],C=[...a.get(x)??[]],w=new Set;for(;C.length;){const v=C.pop();w.has(v)||(w.add(v),h.push(v),C.push(...a.get(v)??[]))}return h},l=bm.getState().statusById,d=x=>{const h=e.statusById.get(x);return h&&h!=="idle"?h:l.get(x)?.status??h??"idle"},f=x=>{const h=x.map(C=>d(C));return h.includes("busy")?"busy":h.includes("retry")?"retry":"idle"},m=Ss.getState().projects,u=ut.getState().availableWorktreesByProject,p=r.filter(x=>x?.id&&!x.parentID).slice().sort((x,h)=>Ba(h)-Ba(x)).slice(0,Dh).map(x=>{const h=[x.id,...c(x.id)],C=Mr(x)??"";return{id:x.id,title:x.title||"Untitled session",status:f(h),branch:C?e.branchByDirectory.get(C)??"":"",unseen:h.reduce((w,v)=>w+(n.unseenCount[v]??0),0),hasError:h.some(w=>n.unseenHasError[w]??!1),directory:C,subtitle:oC(C,x,m,u,e.branchByDirectory)}}),y=e.approvals.map(x=>({...x,sessionTitle:o.get(x.sessionId)||""})),g=Ee.getState();let b=0;if(g.dockBadgeEnabled)for(const x of r){if(!x?.id||x.parentID)continue;let h=n.unseenCount[x.id]??0;h===0&&g.notifyOnSubtasks&&(h=c(x.id).reduce((C,w)=>C+(n.unseenCount[w]??0),0)),h>0&&(b+=1)}return{sessions:p,approvals:y,instanceName:t,usage:aC(),dockBadgeCount:b}},fC=()=>{i.useEffect(()=>{if(!Rf()||!_a())return;let t=!1,e="",n=null,r="";const o=()=>{if(t)return;const k=uC(r),j=JSON.stringify(k);j!==e&&(e=j,Gr("desktop_tray_update",k))};lC().then(k=>{t||(r=k,o())});const a=async()=>{const k=dC();await Promise.all([...k.entries()].map(async([j,A])=>{const D=await Jn.getSessionStatusForDirectory(j).catch(()=>null);t||D===null||vx(j,D,A)}))},c=()=>{t||n!==null||(n=window.setTimeout(()=>{n=null,o()},tC))},l=new Map,d=()=>{if(t)return;let k;try{k=Aa()}catch{return}const j=new Set;for(const[A,D]of k.children.entries())j.add(A),l.has(A)||l.set(A,D.subscribe(()=>c()));for(const[A,D]of l)j.has(A)||(D(),l.delete(A))};let f=null;try{f=Aa().subscribeRegistry(()=>{d(),c()})}catch{}d();const m=xm.subscribe(()=>c()),u=jr.subscribe(()=>c()),p=Ss.subscribe(()=>c()),y=ut.subscribe(()=>c()),g=wn.subscribe(()=>c()),b=Ee.subscribe(()=>c()),x=bm.subscribe(()=>c());wx(Jf());const h=window.setInterval(()=>{ka()},sC);a();const C=window.setInterval(()=>{a()},Tf),w=mn.subscribe(()=>c());mn.getState().loadSettings().then(()=>{if(t)return;const{dropdownProviderIds:k,results:j}=mn.getState();k.length>0&&k.some(D=>!j.some(N=>N.providerId===D))&&mn.getState().fetchAllQuotas()});const v=window.setInterval(()=>{const k=mn.getState();k.autoRefresh&&k.dropdownProviderIds.length>0&&k.fetchAllQuotas()},Math.max(3e4,mn.getState().refreshIntervalMs||6e4)),S=window.setInterval(()=>{d(),o()},Tf);return o(),()=>{t=!0,n!==null&&window.clearTimeout(n),window.clearInterval(S),window.clearInterval(h),window.clearInterval(C),window.clearInterval(v),m(),u(),p(),y(),g(),b(),x(),w(),f?.();for(const k of l.values())k();l.clear()}},[]),i.useEffect(()=>{if(!Rf()||typeof window>"u")return;const e=window.__OPENCHAMBER_DESKTOP__?.listen;if(typeof e!="function")return;const n=o=>{o.type==="respond-permission"&&jx(o.sessionId,o.id,o.response).catch(()=>{le.error("Failed to respond to permission request")})};let r=null;return e(eC,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{}}},[])},mC="/api/notifications/stream",hC=()=>typeof document>"u"?!0:document.visibilityState==="visible"&&document.hasFocus(),pC=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}},gC=t=>{const e=ft.c(3),n=t?.enabled??!0;let r,o;e[0]!==n?(r=()=>{if(!n||dr()||!bc()||typeof window>"u"||typeof EventSource>"u")return;const a=new EventSource(Pi().sse(mC));return a.onmessage=xC,()=>{a.close()}},o=[n],e[0]=n,e[1]=r,e[2]=o):(r=e[1],o=e[2]),i.useEffect(r,o)};function xC(t){let e;try{e=JSON.parse(t.data)}catch{return}const n=Ee.getState();if(!n.nativeNotificationsEnabled||n.notificationMode!=="always"&&hC())return;const r=pC(e);if(!r)return;Lo()?.notifications?.notifyAgentCompletion(r)}const Ef="pwa-install-toast-shown",Mf="pwa-install-toast-dismissed",bC=()=>{const t=ft.c(6),{browserTab:e}=tb(),{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"||!bc()||!e)return;let d=null,f=null;const m=()=>{f!==null&&(le.dismiss(f),f=null)},u=async()=>{if(!d)return;const g=d;d=null,m(),await g.prompt();const{outcome:b}=await g.userChoice;b==="accepted"&&le.success(r.current("pwa.installPrompt.started"))},p=g=>{const b=g;if(typeof b.prompt!="function")return;b.preventDefault(),d=b;const x=Hi(),h=Vf();sb({dismissed:x.getItem(Mf),sessionShown:h.getItem(Ef),hasActiveToast:f!==null})&&(h.setItem(Ef,"true"),f=le.info(r.current("pwa.installPrompt.description"),{duration:1/0,action:{label:r.current("pwa.installPrompt.action"),onClick:()=>{u()}},cancel:{label:r.current("pwa.installPrompt.dismiss"),onClick:()=>{Hi().setItem(Mf,"true"),m()}}}))},y=()=>{d=null,m(),le.success(r.current("pwa.installPrompt.installed"))};return window.addEventListener("beforeinstallprompt",p),window.addEventListener("appinstalled",y),()=>{m(),window.removeEventListener("beforeinstallprompt",p),window.removeEventListener("appinstalled",y)}},l=[e],t[3]=e,t[4]=c,t[5]=l):(c=t[4],l=t[5]),i.useEffect(c,l)},yC=({open:t,onOpenChange:e})=>{const{t:n}=Nt(),r=!1,[o,a]=i.useState(null),[c,l]=i.useState(null),[d,f]=i.useState(!1),[m,u]=i.useState(!1),[p,y]=i.useState(null),[g,b]=i.useState(!1);i.useCallback(async()=>{},[p,d,r,n]),i.useEffect(()=>{if(!t)return;(async()=>{try{const C=await Cs("/api/system/info");if(C.ok){const w=await C.json();if(typeof w.openchamberVersion=="string"&&w.openchamberVersion.trim()){a(w.openchamberVersion);return}}}catch{}a(await Nx())})()},[t]),i.useEffect(()=>{if(!t)return;let h=!1;return(async()=>{try{const w=await Cs("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!w.ok)return;const v=await w.json().catch(()=>null),S=typeof v?.currentVersion=="string"?v.currentVersion.trim():"";!h&&S&&l(S)}catch{}})(),()=>{h=!0}},[t]),i.useEffect(()=>{{y(null),b(!1);return}},[t,r]);const x=o;return s.jsx(Ms,{open:t,onOpenChange:e,children:s.jsx(Es,{className:"max-w-xs p-6",children:s.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[s.jsx(Tc,{width:64,height:64}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),s.jsxs("div",{className:"space-y-0.5 typography-meta text-muted-foreground",children:[x&&s.jsx("p",{children:n("aboutDialog.openChamberVersionLabel",{version:x})}),c&&s.jsx("p",{children:n("aboutDialog.openCodeVersionLabel",{version:c})})]})]}),r,s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsxs("div",{className:"flex items-center justify-center gap-4",children:[s.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(I,{name:"github-fill",className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(I,{name:"discord-fill",className:"h-4 w-4"}),s.jsx("span",{children:"Discord"})]})]}),s.jsxs("a",{href:"https://x.com/openchamber_dev",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[s.jsx(I,{name:"twitter-xfill",className:"h-4 w-4"}),s.jsx("span",{children:"@openchamber_dev"})]})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:n("aboutDialog.footerNote")})]})})})},Vl=(t,e)=>{const n=t.get(e);return typeof n!="string"?null:n.trim()||null},wC=(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},vC=()=>{const t=nb(a=>a.completeAuth),[e,n]=i.useState("working"),[r,o]=i.useState("Completing MCP authorization...");return i.useEffect(()=>{if(typeof window>"u"){n("error"),o("Browser context unavailable.");return}const a=new URLSearchParams(window.location.search),c=Vl(a,"code"),l=rb(a),d=ib(a),f=Vl(a,"error"),m=Vl(a,"error_description");if(f){d&&Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(m??f);return}(async()=>{try{if(!c)throw new Error("Missing OAuth authorization code. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");let u=l;if(!u&&d){const p=await Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`);if(p.ok){const y=await p.json().catch(()=>null);y?.name?.trim()&&(u={name:y.name.trim(),directory:typeof y.directory=="string"&&y.directory.trim()?y.directory.trim():null})}}if(!u?.name)throw new Error("Authorization session details were not available. Start authorization again from MCP Settings or paste the returned code into OpenChamber manually.");await t(u.name,c,u.directory),d&&await Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("success"),o("Authorization completed. You can close this tab and return to OpenChamber.")}catch(u){d&&await Cs(`/api/mcp/auth/pending?state=${encodeURIComponent(d)}`,{method:"DELETE"}).catch(()=>{}),n("error"),o(wC(u,"Failed to complete MCP authorization."))}})()},[t]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-6 py-12 text-foreground",children:s.jsxs("div",{className:"w-full max-w-xl rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-8 shadow-sm",children:[s.jsxs("div",{className:"space-y-3 text-center",children:[s.jsx("div",{className:e==="error"?"text-[var(--status-error)]":e==="success"?"text-[var(--status-success)]":"text-[var(--status-info)]",children:s.jsx("h1",{className:"typography-hero font-semibold",children:e==="working"?"Completing Authorization":e==="success"?"Authorization Complete":"Authorization Failed"})}),s.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}),e!=="working"&&s.jsx("div",{className:"mt-8 flex justify-center",children:s.jsx(Ve,{type:"button",onClick:()=>{typeof window>"u"||window.location.replace("/")},children:"Return to OpenChamber"})})]})})},Ff=co(()=>lo(()=>import("./OnboardingScreen-Sl-6JgaP.js"),__vite__mapDeps([11,1,3,4,2])).then(t=>({default:t.OnboardingScreen}))),jC=()=>{const t=ft.c(3),e=Ee(DC),n=Ee(IC);let r;return t[0]!==e||t[1]!==n?(r=s.jsx(yC,{open:e,onOpenChange:n}),t[0]=e,t[1]=n,t[2]=r):r=t[2],r},SC=t=>{const e=ft.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 f;e[8]!==c||e[9]!==d?(f=s.jsxs("div",{className:"flex flex-col gap-2",children:[c,d]}),e[8]=c,e[9]=d,e[10]=f):f=e[10];let m;e[11]!==r||e[12]!==o?(m=o(r?"startup.initRecovery.retrying":"startup.initRecovery.retry"),e[11]=r,e[12]=o,e[13]=m):m=e[13];let u;e[14]!==r||e[15]!==n||e[16]!==m?(u=s.jsx(Ve,{type:"button",onClick:n,disabled:r,children:m}),e[14]=r,e[15]=n,e[16]=m,e[17]=u):u=e[17];let p;return e[18]!==f||e[19]!==u?(p=s.jsx("div",{className:"flex h-full items-center justify-center bg-background px-6 text-foreground",children:s.jsxs("div",{className:"flex max-w-md flex-col items-center gap-4 text-center",children:[f,u]})}),e[18]=f,e[19]=u,e[20]=p):p=e[20],p},Of=t=>t?t.replace(/\\/g,"/").replace(/\/+$/g,""):"",NC=()=>{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"}},kC=()=>typeof window>"u"?!1:window.location.pathname===cb,CC=t=>{const e=ft.c(23),{embeddedSessionChat:n,isVSCodeRuntime:r,embeddedBackgroundWorkEnabled:o}=t,a=Ys(PC),c=ut(TC),l=ut(RC),d=Ec(),f=i.useRef(null);let m;e[0]!==n.directory?(m=Of(n.directory),e[0]=n.directory,e[1]=m):m=e[1];const u=m;let p;e[2]!==a?(p=Of(a),e[2]=a,e[3]=p):p=e[3];const y=p;let g,b;if(e[4]!==y||e[5]!==c||e[6]!==n.directory||e[7]!==n.sessionId||e[8]!==u||e[9]!==r||e[10]!==l||e[11]!==d?(g=()=>{if(r||u&&y!==u)return;const S=`${u}
|
|
236
|
-
${n.sessionId}`;f.current===S&&c===n.sessionId||(f.current=S,l(n.sessionId,n.directory),d.ensureSessionRenderable(n.sessionId,!0))},b=[y,c,n.directory,n.sessionId,u,r,l,d],e[4]=y,e[5]=c,e[6]=n.directory,e[7]=n.sessionId,e[8]=u,e[9]=r,e[10]=l,e[11]=d,e[12]=g,e[13]=b):(g=e[12],b=e[13]),i.useEffect(g,b),u&&y!==u)return null;let x;e[14]!==o?(x=s.jsx(ym,{embeddedBackgroundWorkEnabled:o}),e[14]=o,e[15]=x):x=e[15];let h;e[16]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(Pm,{}),e[16]=h):h=e[16];let C;e[17]!==n.readOnly?(C=s.jsx(Ql,{readOnly:n.readOnly}),e[17]=n.readOnly,e[18]=C):C=e[18];let w;e[19]===Symbol.for("react.memo_cache_sentinel")?(w=s.jsx(wm,{}),e[19]=w):w=e[19];let v;return e[20]!==x||e[21]!==C?(v=s.jsxs(s.Fragment,{children:[x,h,C,w]}),e[20]=x,e[21]=C,e[22]=v):v=e[22],v};function AC({apis:t}){i.useEffect(()=>{Np("App:mounted"),kp()&&console.info("[startup-trace] enabled. Run console.table(window.__OPENCHAMBER_STARTUP_TRACE__) after startup.")},[]);const e=ss(L=>L.initializeApp),n=ss(L=>L.isInitialized),r=ss(L=>L.isConnected),o=ss(L=>L.providers.length),a=ss(L=>L.agents.length),c=ss(L=>L.loadProviders),l=ss(L=>L.loadAgents),d=ut(L=>L.error),f=ut(L=>L.clearError),m=Ys(L=>L.currentDirectory),u=Ys(L=>L.setDirectory),p=Ys(L=>L.isSwitchingDirectory),[y,g]=i.useState(!1),b=Mi(L=>L.refreshStatus),[x,h]=i.useState(()=>t.runtime.isVSCode),[C,w]=i.useState(!0),[v,S]=i.useState(!1),[k,j]=i.useState(0),[A,D]=i.useState(0),[N,B]=i.useState(!1),T=Ee(L=>L.wideChatLayoutEnabled),E=Ee(L=>L.mobileKeyboardMode),_=i.useMemo(()=>dr(),[]),R=vc(L=>L.setPlanModeEnabled),[z,V]=i.useState(()=>jd()),[$,M]=i.useState(()=>{const L=Sd();return L!==null?Nd({isDesktopShell:!0,bootOutcome:L}):null}),te=i.useRef(!1),re=i.useMemo(()=>NC(),[]),Q=!re||C,H=i.useMemo(()=>kC(),[]);i.useEffect(()=>(kd(y),()=>{kd(!1)}),[y]),i.useEffect(()=>{Cp(E)},[E]),i.useEffect(()=>{h(t.runtime.isVSCode)},[t.runtime.isVSCode]),i.useEffect(()=>Wf(L=>{ob(L),D(se=>se+1),S(!1),j(se=>se+1)}),[]);const X=Hd(L=>{const se=Cd();return Object.values(L.runsByOriginalSessionID).filter(Z=>Z.status==="running"&&Z.runtimeKey===se).map(Z=>`${Z.originalSessionID}:${Z.phase}:${Z.lastForwardedMessageID??""}:${Z.expectedAssistantParentID??""}`).sort().join("|")});i.useEffect(()=>{if(re)return;const L=Cd(),se=Object.values(Hd.getState().runsByOriginalSessionID).filter(Z=>Z.status==="running"&&Z.runtimeKey===L);for(const Z of se)kx(Z.originalSessionID)},[X,re,A]),i.useEffect(()=>(document.documentElement.classList.toggle("wide-chat-layout",T),()=>{document.documentElement.classList.remove("wide-chat-layout")}),[T]),i.useEffect(()=>(Ad(t),()=>Ad(null)),[t]),i.useEffect(()=>{re||b(t.github,{force:!0})},[t.github,re,b]),Cx();const oe=z==="valid",fe=$?.screen==="main";i.useEffect(()=>{if(!Ap({isDesktopShell:_,isInitialized:n,bootOutcomeKnown:oe,bootViewIsMain:fe}))return;const L=setTimeout(()=>{const se=document.getElementById("initial-loading");se&&(se.classList.add("fade-out"),setTimeout(()=>{se.remove()},300))},150);return()=>clearTimeout(L)},[_,n,oe,fe]),i.useEffect(()=>{if(!_||z!=="malformed")return;const L=document.getElementById("initial-loading");L&&(L.textContent="Desktop startup failed — please restart the app.")},[_,z]),i.useEffect(()=>{if(_)return;const L=setTimeout(()=>{const se=document.getElementById("initial-loading");se&&!n&&(se.classList.add("fade-out"),setTimeout(()=>{se.remove()},300))},5e3);return()=>clearTimeout(L)},[_,n]),i.useEffect(()=>{let L=!1;return(async()=>{const Z=await Cs("/health",{method:"GET"}).catch(()=>null);if(!Z||!Z.ok||L)return;const je=await Z.json().catch(()=>null);if(!je||L)return;const De=je.planModeExperimentalEnabled;R(De===!0||De===1||De==="1"||De==="true")})(),()=>{L=!0}},[R]),i.useEffect(()=>{x||e()},[e,x]),i.useEffect(()=>{if(x||n)return;let L=!0,se,Z=0;const je=10,De=1e3,Le=async()=>{if(!L)return;if(Z>=je){S(!0);return}const Me=ss.getState();if(Me.isInitialized){S(!1);return}Z+=1,await Me.initializeApp();const Fe=ss.getState();if(!L)return;if(Fe.isInitialized){S(!1);return}if(Z>=je){S(!0);return}const he=Math.min(De*Math.pow(2,Z-1),16e3);se=setTimeout(Le,he)};return se=setTimeout(Le,De),()=>{L=!1,se&&clearTimeout(se)}},[k,n,x]),i.useEffect(()=>{n&&S(!1)},[n]),i.useEffect(()=>{if(!v)return;const L=document.getElementById("initial-loading");L&&(L.classList.add("fade-out"),setTimeout(()=>{L.remove()},300))},[v]),i.useEffect(()=>{if(x||!r||o>0&&a>0)return;let L=!0,se=0;const Z=15,je=async()=>{const Le=ss.getState();if(!(Le.providers.length>0&&Le.agents.length>0))try{Le.providers.length===0&&await c({source:"startupRecovery"}),ss.getState().agents.length===0&&await l({source:"startupRecovery"})}catch{}};je();const De=setInterval(()=>{if(L){if(++se>=Z){clearInterval(De);return}je()}},2e3);return()=>{L=!1,clearInterval(De)}},[r,x,l,c,o,a]),i.useEffect(()=>{p||x||r&&Jn.setDirectory(m)},[m,p,r,x]),i.useEffect(()=>{if(!re||typeof window>"u")return;const L=je=>{const De=je?.visible===!0;w(De)},se=je=>{if(je.origin!==window.location.origin)return;const De=je.data;De?.type==="openchamber:embedded-visibility"&&L(De.payload)},Z=window;return Z.__openchamberSetEmbeddedVisibility=L,window.addEventListener("message",se),()=>{window.removeEventListener("message",se),Z.__openchamberSetEmbeddedVisibility===L&&delete Z.__openchamberSetEmbeddedVisibility}},[re]),i.useEffect(()=>{!re?.directory||x||m!==re.directory&&u(re.directory,{showOverlay:!1})},[m,re,x,u]),i.useEffect(()=>{if(!re||typeof window>"u")return;const L=se=>{se.storageArea===window.localStorage&&se.key==="ui-store"&&Ee.persist.rehydrate()};return window.addEventListener("storage",L),()=>{window.removeEventListener("storage",L)}},[re]),i.useEffect(()=>{if(typeof window>"u")return;const L=se=>{const Z=se.detail,je=typeof Z?.sessionId=="string"?Z.sessionId.trim():"";if(!je)return;const De=typeof Z?.directory=="string"&&Z.directory.trim().length>0?Z.directory.trim():null;Ee.getState().setActiveMainTab("chat"),ut.getState().setCurrentSession(je,De)};return window.addEventListener("openchamber:open-session",L),()=>window.removeEventListener("openchamber:open-session",L)},[]),i.useEffect(()=>{if(typeof window>"u")return;const L=()=>{const se=Ys.getState().currentDirectory,{activeProjectId:Z,projects:je}=Ss.getState(),De=je.find(Le=>Le.id===Z)??null;Gr("desktop_open_draft_mini_chat_window",{directory:se||De?.path||"",projectId:De?.id??null})};return window.addEventListener("openchamber:open-mini-chat",L),()=>window.removeEventListener("openchamber:open-mini-chat",L)},[]),i.useEffect(()=>{if(typeof window>"u")return;const L=()=>{const se=ut.getState().currentSessionId;se&&cm(se)};return window.addEventListener("focus",L),()=>window.removeEventListener("focus",L)},[]),i.useEffect(()=>{if(typeof window>"u")return;const L=se=>{const Z=se.detail,je=typeof Z?.directory=="string"&&Z.directory.trim().length>0?Z.directory.trim():null,De=typeof Z?.projectId=="string"&&Z.projectId.trim().length>0?Z.projectId.trim():null;Ee.getState().setActiveMainTab("chat"),Ee.getState().setSessionSwitcherOpen(!1),ut.getState().openNewSessionDraft({selectedProjectId:De,directoryOverride:je,preserveDirectoryOverride:!!je})};return window.addEventListener("openchamber:open-draft-session",L),()=>window.removeEventListener("openchamber:open-draft-session",L)},[]),i.useEffect(()=>{if(typeof window>"u")return;const L=se=>{const Z=se.detail,je=typeof Z?.projectPath=="string"?Z.projectPath.trim():"";if(!je)return;const De=Ss.getState(),Le=De.projects.find(Me=>Me.path===je);Le?De.setActiveProject(Le.id):De.addProject(je)};return window.addEventListener("openchamber:open-project",L),()=>window.removeEventListener("openchamber:open-project",L)},[]),i.useEffect(()=>{typeof window>"u"||!n||p||te.current||(te.current=!0,window.__openchamberAppReady=!0,window.dispatchEvent(new Event("openchamber:app-ready")))},[n,p]),Ax({enabled:Q}),gC({enabled:Q}),bC(),Dx(),ab();const ve=i.useCallback(()=>{g(L=>!L)},[]);Zk(ve),fC(),i.useEffect(()=>{if(re)return;const L=se=>{jc(se)&&se.shiftKey&&!se.altKey&&(se.code==="KeyD"||se.key.toLowerCase()==="d")&&(se.preventDefault(),g(je=>!je))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[re]),i.useEffect(()=>{re||d&&setTimeout(()=>f(),5e3)},[f,re,d]),i.useEffect(()=>{if(!_||z!=="not-injected")return;let L=!1,se=0;const Z=200,je=2e3,De=50,Le=()=>{if(L)return;se++;const Me=jd();if(Me!=="not-injected"){if(L=!0,V(Me),Me==="valid"){const he=Sd();he&&M(Nd({isDesktopShell:!0,bootOutcome:he}))}return}const Fe=Math.min(Z*Math.pow(1.1,se),je);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(Le,Fe)};return window.setTimeout(Le,Z),()=>{L=!0}},[_,z]);const ie=i.useCallback(async()=>{if(Dp({isDesktopShell:dr(),isDesktopLocalOriginActive:eo()})){await Ip();return}window.location.reload()},[]),Ne=i.useCallback(async()=>{if(!N){S(!1),B(!0);try{await ss.getState().initializeApp()}finally{B(!1)}ss.getState().isInitialized||j(L=>L+1)}},[N]),K=L=>{if(L.screen==="recovery")return L.variant};if(_&&$&&$.screen!=="main"){if($.screen==="chooser")return s.jsx(Xs,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-full"}),children:s.jsx(Ff,{mode:"first-launch",onCliAvailable:ie,onChooseRemote:()=>{}})})})});const L=K($),se=$.screen==="recovery"&&"url"in $?$.url:void 0;return s.jsx(Xs,{children:s.jsx("div",{className:"h-full text-foreground bg-transparent",children:s.jsx(i.Suspense,{fallback:s.jsx("div",{className:"h-full"}),children:s.jsx(Ff,{mode:"recovery",recoveryVariant:L,recoveryHostUrl:se,recoveryHostLabel:void 0,onCliAvailable:ie})})})})}if(re)return s.jsx(Xs,{children:s.jsx(Gd,{sdk:Jn.getSdkClient(),directory:m||"",children:s.jsx(Kd,{apis:t,children:s.jsx(qd,{delayDuration:300,skipDelayDuration:150,children:s.jsx("div",{className:"h-full text-foreground bg-background",children:s.jsx(CC,{embeddedSessionChat:re,isVSCodeRuntime:x,embeddedBackgroundWorkEnabled:Q})})})})},A)});if(H)return s.jsx(Xs,{children:s.jsx(vC,{})});if(v&&!n&&!x&&!re)return s.jsx(Xs,{children:s.jsx(SC,{onRetry:()=>{Ne()},isRetrying:N})});const pe=!n&&!_;return s.jsx(Xs,{children:s.jsx(Gd,{sdk:Jn.getSdkClient(),directory:m||"",children:s.jsx(Kd,{apis:t,children:s.jsx(_y,{children:s.jsx(qd,{delayDuration:300,skipDelayDuration:150,children:s.jsxs("div",{className:_?"h-full text-foreground bg-transparent":"h-full text-foreground bg-background",children:[s.jsx(ym,{embeddedBackgroundWorkEnabled:Q}),s.jsx(Pm,{}),s.jsx(Lk,{}),s.jsx(wm,{}),!pe&&s.jsxs(s.Fragment,{children:[s.jsx(lb,{}),s.jsx(jC,{}),y&&s.jsx(Vk,{onClose:()=>g(!1)})]})]})})})})},A)})}function DC(t){return t.isAboutDialogOpen}function IC(t){return t.setAboutDialogOpen}function PC(t){return t.currentDirectory}function TC(t){return t.currentSessionId}function RC(t){return t.setCurrentSession}const EC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();Ix();Pp().then(()=>{Promise.all([Tp(),Px()]).catch(t=>{console.error("[main] settings init failed:",t)}),Tx(),Rx(),Ex()}).catch(t=>{console.error("[main] appearance init failed:",t)});const Ih=document.getElementById("root");if(!Ih)throw new Error("Root element not found");dp.createRoot(Ih).render(s.jsx(tt.StrictMode,{children:s.jsx(Mx,{children:s.jsx(Fx,{children:s.jsx(Ox,{children:s.jsx(Lx,{children:s.jsx(AC,{apis:EC})})})})})}));const zC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{b1 as D,Ik as M,zC as m,_s as u};
|