@openchamber/web 1.18.0 → 1.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/assets/{DiagramView-1-LZVuzn.js → DiagramView-DZmf30ko.js} +1 -1
  2. package/dist/assets/{FilesView-BDRX8vU2.js → FilesView-cJPeFhDe.js} +6 -6
  3. package/dist/assets/{MarkdownRendererImpl-fZSdR7PD.js → MarkdownRendererImpl-DZezL90a.js} +1 -1
  4. package/dist/assets/{OnboardingScreen-D81UrlA4.js → OnboardingScreen-ChYr0xqs.js} +1 -1
  5. package/dist/assets/{SessionSwitcherDropdown-cSK3t3TR.js → SessionSwitcherDropdown-BV7FfPbT.js} +1 -1
  6. package/dist/assets/{SettingsWindow-CozowJLm.js → SettingsWindow-UybkBD1p.js} +1 -1
  7. package/dist/assets/{contextPanelEmbeddedChat-CQYNvKbk.js → contextPanelEmbeddedChat-DW3atb4h.js} +1 -1
  8. package/dist/assets/{de-C2n4oo1Z.js → de-rVJ-hXrd.js} +3 -3
  9. package/dist/assets/es-D7ZyOToq.js +15 -0
  10. package/dist/assets/{fr-DDFUp5jS.js → fr-hl5i-ZI0.js} +2 -2
  11. package/dist/assets/{index-BCCcokur.css → index-CL9MYe8V.css} +1 -1
  12. package/dist/assets/{ja-B7SxobKm.js → ja-DqakdvOp.js} +2 -2
  13. package/dist/assets/{ko-CWGq93SO.js → ko-dNl8A3Xf.js} +2 -2
  14. package/dist/assets/main-B5TIsU2y.js +209 -0
  15. package/dist/assets/{main-Cts0BwVk.js → main-_m6HD9-a.js} +2 -2
  16. package/dist/assets/{markdownCore-BqzEkymd.js → markdownCore-DpT1vbbv.js} +2 -2
  17. package/dist/assets/{miniChat-ChuQD2KK.js → miniChat-wYb8p9vG.js} +2 -2
  18. package/dist/assets/{mobile-c-CRD1Cz.js → mobile-ExXAVUcv.js} +2 -2
  19. package/dist/assets/{pl-DZmyxLo7.js → pl-C5HQx1Hf.js} +3 -3
  20. package/dist/assets/pt-BR-CNCoBDAM.js +15 -0
  21. package/dist/assets/{renderElectronMiniChatApp-9uaZAJjw.js → renderElectronMiniChatApp-DPDzIT8W.js} +2 -2
  22. package/dist/assets/{renderMobileApp-Dm1tmU2a.js → renderMobileApp-CzWvxR9e.js} +3 -3
  23. package/dist/assets/runtimeEndpointReset-DKzVWH1w.js +180 -0
  24. package/dist/assets/uk-Bn-3AMpk.js +15 -0
  25. package/dist/assets/{useAppFontEffects-pyTMaGQu.js → useAppFontEffects-DdvGxoPX.js} +133 -133
  26. package/dist/assets/zh-CN-BCwvQpZm.js +15 -0
  27. package/dist/assets/zh-TW-TRHrkN9l.js +15 -0
  28. package/dist/index.html +4 -4
  29. package/dist/mini-chat.html +3 -3
  30. package/dist/mobile.html +3 -3
  31. package/package.json +2 -2
  32. package/server/lib/openchamber-control/DOCUMENTATION.md +9 -1
  33. package/server/lib/openchamber-sessions/routes.js +117 -4
  34. package/server/lib/openchamber-sessions/routes.test.js +129 -16
  35. package/server/lib/opencode/DOCUMENTATION.md +2 -0
  36. package/server/lib/opencode/proxy.js +21 -3
  37. package/server/lib/small-model/DOCUMENTATION.md +11 -4
  38. package/server/lib/small-model/call.js +19 -3
  39. package/server/lib/small-model/call.test.js +9 -2
  40. package/server/lib/small-model/index.js +10 -1
  41. package/server/lib/small-model/index.test.js +20 -1
  42. package/server/lib/walkthrough/DOCUMENTATION.md +23 -0
  43. package/server/lib/walkthrough/index.js +17 -0
  44. package/server/lib/walkthrough/reproduce-2607.test.js +148 -0
  45. package/server/opencode-proxy.test.js +83 -0
  46. package/dist/assets/es-DP7jRKkr.js +0 -15
  47. package/dist/assets/main-Cqfcxvqq.js +0 -209
  48. package/dist/assets/pt-BR-BKR5oHQ7.js +0 -15
  49. package/dist/assets/runtimeEndpointReset-DL5z84w2.js +0 -180
  50. package/dist/assets/uk-D7oAI_Wc.js +0 -15
  51. package/dist/assets/zh-CN-Ddjz1_9w.js +0 -15
  52. package/dist/assets/zh-TW-D3X01YXj.js +0 -15
  53. /package/dist/assets/{index-ChZvuURI.js → index-DjZ4W8hy.js} +0 -0
@@ -1,180 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
2
- import{f as tt,j as s,r as we,R as l,c as Xi}from"./vendor-react-BUCujlKS.js";import{dX as wr,dY as cr,ay as Dm,f as lt,o as Tn,bg as Kt,bh as Bt,bj as _t,I as K,bA as Os,cj as dr,g as fe,B as ee,aU as jr,aJ as Vn,aR as xs,aS as ks,aQ as bs,bG as Ao,c6 as an,dZ as kr,aO as Vs,t as J,O as Jd,d_ as _n,d$ as Rm,e0 as Mm,dL as Lm,e1 as Fm,e2 as Om,e3 as zm,v as es,e4 as Km,d7 as Bm,d8 as _m,d9 as Um,aK as gs,aI as as,aN as fs,aM as hs,ci as Ns,Y as il,cg as ci,e5 as $m,e6 as kl,e7 as Vm,i as pt,e8 as $a,ck as oa,e9 as Hm,dn as rl,cU as Wm,bi as Ut,cm as Yd,ag as Gm,b as is,a0 as Nr,R as Va,G as Ha,ea as qm,eb as Jm,a6 as Eo,ec as Do,ed as ur,bE as Un,ee as Qd,ef as Xd,j as ol,eg as Ym,a8 as vn,eh as Zi,ei as er,ej as tr,by as Qm,bz as Xm,ek as Zm,el as Fa,bk as Yt,bl as rs,L as at,em as hi,en as Nl,c0 as Lt,c1 as Ft,c2 as Wt,c3 as Ot,c4 as kt,eo as Hn,ds as Rs,ep,eq as Zd,er as tp,es as sp,et as Sr,eu as Cn,ev as Ka,ew as np,ex as ap,ey as ip,ez as rp,eA as op,eB as lp,eC as Nn,bu as eu,J as cp,H as tu,K as su,W as Sl,dk as dp,dG as nu,dv as au,dx as up,eD as mp,u as Ro,cF as pp,eE as Cl,eF as gp,eG as fp,eH as Il,eI as hp,eJ as xp,eK as bp,eL as yp,aP as vp,eM as wp,N as jp,Q as kp,eN as Np,eO as Sp,bU as Cp,P as ia,n as iu,m as Ip,eP as Pp,eQ as Pl,q as Tp,s as Ap,k as Ep,b2 as Dp,b3 as Rp,b4 as ru,eR as $r,eS as Tl,eT as Mp,eU as Lp,eV as Fp,eW as Op,dy as Cr,af as Sn,eX as zp,eY as Kp,eZ as Bp,e_ as _p,e$ as Up,f0 as Vr,f1 as Al,f2 as $p,f3 as Vp,f4 as Hp,f5 as Wp,f6 as Gp,f7 as Hr,f8 as qp,bf as El,f9 as Ra,be as Jp,fa as Yp,fb as Dl,fc as Rl,fd as Qp,bH as Mo,bI as Lo,bJ as Fo,bK as Oo,bL as kn,bM as en,c7 as Oa,M as mi,fe as Ml,cl as Xp,ff as ou,c9 as Zp,dC as eg,fg as Wr,cd as tg,fh as sg,fi as ng,dw as ag,fj as ig,fk as rg,bF as og,fl as lg,fm as cg,fn as Ei,fo as dg,fp as Ll,fq as Fl,fr as ug,cI as mg,ad as pg,a9 as gg,V as fg,fs as hg,cK as xg,ft as lu,dV as bg,de as yg,fu as vg,fv as wg,cN as jg}from"./useAppFontEffects-pyTMaGQu.js";import{ad as mr,ae as kg,af as Ol,ag as Ng,i as ll,ah as Sg,B as ds,Z as In,r as ht,u as ke,x as Wa,b as cu,o as cl,a as mn,d as zl,L as It,k as Cs,m as nn,ai as Ir,q as Ps,aj as Cg,ak as Kl,al as qs,e as Ga,w as ls,H as Bl,am as _l,an as Ul,K as Za,p as Ig,ao as Pg,j as Tg,ap as Ma,aq as Ag,J as Eg,ar as Dg,as as Rg,at as Mg,s as Lg,au as Fg,av as du,S as Og,aw as zg,R as Kg,ax as $l,ay as Bg,az as _g,M as Ug,aA as Vl,aB as Hl,aC as Wl,aD as pi,aE as $g,aF as Vg,aG as Gl,aH as dl,aI as uu,aJ as Hg,aK as Wg,aL as Gg,aM as qg,aN as Jg,aO as Yg,ac as Qg,aP as Xg,aQ as Zg,aR as ef,a2 as tf,aS as ei,aT as mu,T as sf,l as nf,v as af}from"./index-ChZvuURI.js";import{s as rf,d as of,E as tn,e as lf,f as ql,k as Gr,V as pu,D as Pr,W as cf}from"./vendor-codemirror-view-DSzLbZiS.js";import{c as gn,u as Hs,d as qa,p as bi,a as df}from"./vendor-zustand-BAGL70zf.js";import{s as uf,p as mf}from"./vendor-yaml-3778uTud.js";import{E as pf,o as pa,k as ul,i as gu,S as gf}from"./vendor-codemirror-state-CNWM3Q8V.js";import{h as ff,j as hf,k as xf,l as bf}from"./vendor-codemirror-commands-eyb3xW_0.js";import{i as yf,x as vf,H as Jl,y as Di,z as wf}from"./vendor-codemirror-language-CTJVwiVf.js";import{a as Yl,g as pr,b as Ql,c as Xl,o as jf,d as kf}from"./vendor-codemirror-search-8kyQdB3f.js";import{v as Nf,g as Sf}from"./vendor-replit-codemirror-vim-D0xSkRWg.js";import{a as $e,c as Cf}from"./vendor-lezer-highlight-CDMHUZ74.js";import{Q as fu}from"./vendor-qrcode-DTJ12-WC.js";import{c as If,s as Pf,i as hu}from"./contextPanelEmbeddedChat-CQYNvKbk.js";import{C as Tf,c as Af,b as Ef,d as Df,S as Rf,M as Mf,a as Lf,g as Ff,h as Of,i as zf,j as Kf,k as Bf}from"./vendor-base-ui-BuzaMvKv.js";import{f as xu,h as bu,P as yu,k as _f,D as vu,j as wu}from"./vendor-dnd-kit-core-BZknOX2w.js";import{u as ju,S as ku,h as Uf,a as $f,v as Vf}from"./vendor-dnd-kit-sortable-CsEagZ81.js";import{C as Nu}from"./vendor-dnd-kit-utilities-B_MdXhJC.js";import{_ as Zl}from"./vendor-vite-runtime-DD1OZmLC.js";import{I as Hf,D as Wf,q as Gf}from"./vendor-ghostty-web-CfpAcbEe.js";import{u as qf}from"./vendor-tanstack-react-virtual-g05Cx3z9.js";import{W as Jf,c as Yf,d as ec,e as Qf,V as Xf,F as Zf,f as eh}from"./vendor-pierre-diffs-B1TeaSIY.js";function th(){return new Worker(Jf,{type:"module"})}const sh=["typescript","javascript","tsx","jsx","json","markdown"],zo={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let tc,sc;const nc=t=>{const e=zo[t],n=new Yf({workerFactory:th,poolSize:e.poolSize,totalASTLRUCacheSize:e.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:sh,lineDiffType:e.lineDiffType,preferredHighlighter:"shiki-wasm"});return n.initialize(),n},nh=t=>{if(!(typeof window>"u"))return t==="split"?(sc??=nc("split"),sc):(tc??=nc("unified"),tc)},ah=t=>{const e=tt.c(7),{children:n,renderTheme:a}=t,i=Ko("unified"),r=Ko("split");let o,d;e[0]!==a||e[1]!==r||e[2]!==i?(o=()=>{i&&i.setRenderOptions({theme:a,lineDiffType:zo.unified.lineDiffType}),r&&r.setRenderOptions({theme:a,lineDiffType:zo.split.lineDiffType})},d=[a,r,i],e[0]=a,e[1]=r,e[2]=i,e[3]=o,e[4]=d):(o=e[3],d=e[4]),we.useEffect(o,d);let c;return e[5]!==n?(c=s.jsx(s.Fragment,{children:n}),e[5]=n,e[6]=c):c=e[6],c},$N=t=>{const e=tt.c(11),{children:n}=t,a=wr();let i,r;if(e[0]!==a?.availableThemes||e[1]!==a?.darkThemeId||e[2]!==a?.lightThemeId){const p=mr(!1),u=mr(!0),f=a?.lightThemeId??p.metadata.id,m=a?.darkThemeId??u.metadata.id;r=a?.availableThemes.find(w=>w.metadata.id===f)??p,i=a?.availableThemes.find(w=>w.metadata.id===m)??u,cr(r),cr(i),e[0]=a?.availableThemes,e[1]=a?.darkThemeId,e[2]=a?.lightThemeId,e[3]=i,e[4]=r}else i=e[3],r=e[4];let o;e[5]!==i.metadata.id||e[6]!==r.metadata.id?(o={light:r.metadata.id,dark:i.metadata.id},e[5]=i.metadata.id,e[6]=r.metadata.id,e[7]=o):o=e[7];const d=o;let c;return e[8]!==n||e[9]!==d?(c=s.jsx(ah,{renderTheme:d,children:n}),e[8]=n,e[9]=d,e[10]=c):c=e[10],c},Ko=t=>{const e=tt.c(2),n=t===void 0?"unified":t;let a;return e[0]!==n?(a=nh(n),e[0]=n,e[1]=a):a=e[1],a},ac="openchamber.update-install-id";function ih(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const t=window.localStorage.getItem(ac)?.trim();if(t)return t;const e=crypto.randomUUID();return window.localStorage.setItem(ac,e),e}catch{return}}function rh(){if(typeof window>"u")return"unknown";try{const{deviceType:t}=Dm();return t}catch{return"unknown"}}function oh(){const t=typeof window<"u"?window.__OPENCHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(t==="arm64"||t==="aarch64")return"arm64";if(t==="x64"||t==="amd64"||t==="x86_64")return"x64";const e=typeof window<"u"?window.__VSCODE_CONFIG__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const a=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(a==="arm"||a==="arm64"||a==="aarch64")return"arm64";if(a==="x86"||a==="x64"||a==="amd64")return"x64";const i=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return i.includes("aarch64")||i.includes("arm64")||i.includes("armv")?"arm64":i.includes("x86_64")||i.includes("x64")||i.includes("amd64")||i.includes("win64")?"x64":"unknown"}function lh(){const t=cu();if(t==="android"||t==="ios")return t;if(typeof navigator>"u")return"web";const e=(navigator.platform||"").toLowerCase();return e.includes("mac")?"macos":e.includes("win")?"windows":e.includes("linux")?"linux":"web"}function ch(t){const e=ke.getState().reportUsage,n=new URLSearchParams({reportUsage:e?"true":"false"});if(n.set("deviceClass",rh()),n.set("arch",oh()),n.set("platform",lh()),e&&(t==="desktop"||t==="mobile")){const a=ih();a&&n.set("installId",a)}return t==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",Wa()?"local":"remote"),n):t==="vscode"?(n.set("appType","vscode"),n.set("instanceMode","local"),n):t==="mobile"?(n.set("appType","mobile-capacitor"),n.set("instanceMode","remote"),n):(n.set("appType","web"),n.set("instanceMode","unknown"),n)}async function Ri(t,e){try{const n=ch(t),a=typeof window<"u"?window.__VSCODE_CONFIG__?.extensionVersion:void 0;e?n.set("currentVersion",e):t==="vscode"&&a&&n.set("currentVersion",a);const i=await ht(`/api/openchamber/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!i.ok)throw new Error(`Server responded with ${i.status}`);const r=await i.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,releaseUrl:r.releaseUrl,downloadUrl:r.downloadUrl,nextSuggestedCheckInSec:typeof r.nextSuggestedCheckInSec=="number"&&Number.isFinite(r.nextSuggestedCheckInSec)?r.nextSuggestedCheckInSec:void 0,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function dh(){return ll()?"mobile":Sg()?"desktop":ds()?"vscode":In()?"web":null}const ic={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Su=gn()((t,e)=>({...ic,checkForUpdates:async()=>{const n=dh();if(!n)return null;t({checking:!0,error:null,runtimeType:n});try{let a=null,i=null;if(n==="desktop"){const r="1.18.0",[o,d]=await Promise.allSettled([Ol(),Ri("desktop",r)]),c=o.status==="fulfilled"?o.value:null;return i=d.status==="fulfilled"?d.value?.nextSuggestedCheckInSec??null:null,t({checking:!1,available:c?.available??!1,info:c,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(a=await Ri("web"),i=a?.nextSuggestedCheckInSec??null):n==="vscode"?i=(await Ri("vscode"))?.nextSuggestedCheckInSec??null:n==="mobile"&&(a=await Ri("mobile","1.18.0"),i=a?.nextSuggestedCheckInSec??null);return t({checking:!1,available:n==="vscode"?!1:a?.available??!1,info:n==="vscode"?null:a,lastChecked:Date.now(),nextCheckInSec:i}),i}catch(a){return t({checking:!1,error:a instanceof Error?a.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:a}=e();if(!(a!=="desktop"||!n)){t({downloading:!0,error:null,progress:null});try{const i=await Ol();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(t(o=>({info:o.info?{...o.info,...i,body:o.info.body||i.body,available:o.info.available}:i})),!await Ng(o=>{t({progress:o})}))throw new Error("Desktop update only works on Local instance");t({downloading:!1,downloaded:!0})}catch(i){t({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:a}=e();if(!(a!=="desktop"||!n))try{if(!await kg())throw new Error("Desktop restart only works on Local instance")}catch(i){t({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(ic)}})),rc="https://github.com/openchamber/openchamber/releases";function uh(t){const e=new Date(`${t}T00:00:00`);return Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(jr(),{year:"numeric",month:"short",day:"numeric"}).format(e)}function mh(t){return t.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function oc(t){return t.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function ph(t,e){const n=t.split(".").map(i=>Number.parseInt(i,10)),a=e.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const r=Number.isFinite(n[i])?n[i]:0,o=Number.isFinite(a[i])?a[i]:0;if(r!==o)return o-r}return 0}function gh(t){const e=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let a;for(;(a=e.exec(t))!==null;)n.push({version:a[1]??"",date:a[2]??"",start:a.index});return n.length===0?[]:n.map((i,r)=>{const o=n[r+1]?.start??t.length,d=t.slice(i.start,o).trim();return{version:i.version,date:i.date,start:i.start,end:o,raw:d}})}const lc=2e3,fh=600*1e3;async function hh(){try{const t=await ht("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return t.ok?{success:!0,autoRestart:(await t.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await t.json().catch(()=>({}))).error||`Server error: ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:void 0}}}async function xh(){try{return(await ht("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function bh(t,e=Math.ceil(fh/lc),n=lc){for(let a=0;a<e;a++){try{const i=await ht("/api/openchamber/update-check?reportUsage=false",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const r=await i.json().catch(()=>null);if(r&&r.available===!1||r&&typeof r.currentVersion=="string"&&typeof t=="string"&&r.currentVersion!==t)return!0}else if((i.status===401||i.status===403)&&await xh())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const cc=({open:t,onOpenChange:e,info:n,downloading:a,downloaded:i,progress:r,error:o,onDownload:d,onRestart:c,runtimeType:p="desktop"})=>{const{t:u}=lt(),[f,m]=we.useState(!1),[w,b]=we.useState("idle"),[g,x]=we.useState(null),k=n?.version?n.releaseUrl||`${rc}/tag/v${n.version}`:rc,y=n?.downloadUrl||k,C=r?.total?Math.round(r.downloaded/r.total*100):0,z=p==="web",j=p==="mobile",N=n?.updateCommand||"openchamber update";we.useEffect(()=>{t||(b("idle"),x(null))},[t]);const v=async()=>{(await Vn(N)).ok&&(m(!0),setTimeout(()=>m(!1),2e3))},P=we.useCallback(async F=>{await Tn(F)},[]),$=we.useCallback(async()=>{b("updating"),x(null);const F=await hh();if(!F.success){b("error"),x(F.error||u("updateDialog.error.updateFailed"));return}F.autoRestart&&(b("restarting"),await new Promise(D=>setTimeout(D,2e3))),b("reconnecting"),await bh(n?.currentVersion)?window.location.reload():(b("error"),x(u("updateDialog.error.takingLonger")))},[n?.currentVersion,u]),O=we.useCallback(()=>{P(y)},[P,y]),M=w!=="idle"&&w!=="error",S=we.useMemo(()=>{if(!n?.body)return null;const F=n.body.trim();if(!F)return null;const E=gh(F);if(E.length===0)return{kind:"raw",title:u("updateDialog.changelog.title"),content:oc(F)};const D=[...E].sort((W,H)=>ph(W.version,H.version));return{kind:"sections",title:u("updateDialog.changelog.title"),sections:D.map(W=>({version:W.version,dateLabel:uh(W.date),content:oc(mh(W.raw)||F)}))}},[n?.body,u]);return s.jsx(Kt,{open:t,onOpenChange:M?void 0:e,children:s.jsxs(Bt,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"flex items-center mb-1",children:[s.jsxs(_t,{className:"flex items-center gap-2.5",children:[s.jsx(K,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:u(w==="restarting"||w==="reconnecting"?"updateDialog.header.updating":"updateDialog.header.updateAvailable")})]}),(n?.currentVersion||n?.version)&&s.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&s.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),s.jsxs("div",{className:"space-y-2",children:[z&&M&&s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(K,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[w==="updating"&&u("updateDialog.status.installingUpdate"),w==="restarting"&&u("updateDialog.status.serverRestarting"),w==="reconnecting"&&u("updateDialog.status.waitingForServer")]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:u("updateDialog.status.autoReloadHint")})]}),S&&!M&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Os,{className:"max-h-[400px] p-0",fillContainer:!1,children:S.kind==="raw"?s.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:F=>{const D=F.target.closest("a");D&&D.href&&(F.preventDefault(),F.stopPropagation(),P(D.href))},children:s.jsx(dr,{content:S.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:S.sections.map(F=>s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",F.version]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:F.dateLabel})]}),s.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:E=>{const W=E.target.closest("a");W&&W.href&&(E.preventDefault(),E.stopPropagation(),P(W.href))},children:s.jsx(dr,{content:F.content,disableLinkSafety:!0,enableFileReferences:!1})})]},F.version))})})}),z&&w==="error"&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(K,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:u("updateDialog.fallback.updateViaTerminal")})]}),s.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[s.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:N}),s.jsx("button",{onClick:v,className:fe("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:u(f?"updateDialog.actions.copied":"updateDialog.actions.copyCommand"),children:f?s.jsx(K,{name:"check",className:"h-4 w-4"}):s.jsx(K,{name:"clipboard",className:"h-4 w-4"})})]})]}),!z&&!j&&a&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:u("updateDialog.status.downloadingPayload")}),s.jsxs("span",{className:"font-mono text-foreground",children:[C,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${C}%`}})})]}),(o||g)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:o||g})})]}),s.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[s.jsxs("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[s.jsx(K,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!z&&!j&&!i&&!a&&s.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[s.jsx(K,{name:"download",className:"h-4 w-4"}),u("updateDialog.actions.downloadUpdate")]}),!z&&!j&&a&&s.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[s.jsx(K,{name:"loader",className:"h-4 w-4 animate-spin"}),u("updateDialog.status.downloading")]}),!z&&!j&&i&&s.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[s.jsx(K,{name:"restart",className:"h-4 w-4"}),u("updateDialog.actions.restartToUpdate")]}),j&&s.jsxs(ee,{onClick:O,size:"default",children:[s.jsx(K,{name:"external-link",className:"h-4 w-4"}),u("updateDialog.actions.openMobileUpdate")]}),z&&!M&&s.jsxs("button",{onClick:$,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[s.jsx(K,{name:"download",className:"h-4 w-4"}),u("updateDialog.actions.updateNow")]}),z&&M&&s.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[s.jsx(K,{name:"loader",className:"h-4 w-4 animate-spin"}),u("updateDialog.status.updating")]})]})]})]})})},$t=t=>{const e=tt.c(22),{children:n,className:a,contentClassName:i}=t,{t:r}=lt(),[o,d]=l.useState(!1),c=l.useRef(null);let p,u;e[0]!==o?(p=()=>{if(!o)return;const C=z=>{const j=c.current;j&&z.target instanceof Node&&j.contains(z.target)||d(!1)};return document.addEventListener("pointerdown",C,!0),()=>document.removeEventListener("pointerdown",C,!0)},u=[o],e[0]=o,e[1]=p,e[2]=u):(p=e[1],u=e[2]),l.useEffect(p,u);let f;e[3]!==r?(f=r("settings.common.infoAria"),e[3]=r,e[4]=f):f=e[4];let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=C=>{C.preventDefault(),C.stopPropagation(),d(yh)},e[5]=m):m=e[5];let w;e[6]!==a?(w=fe("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",a),e[6]=a,e[7]=w):w=e[7];let b;e[8]===Symbol.for("react.memo_cache_sentinel")?(b=s.jsx(K,{name:"information",className:"h-3.5 w-3.5"}),e[8]=b):b=e[8];let g;e[9]!==o||e[10]!==f||e[11]!==w?(g=s.jsx(xs,{asChild:!0,children:s.jsx("button",{ref:c,type:"button","aria-label":f,"aria-expanded":o,onClick:m,className:w,children:b})}),e[9]=o,e[10]=f,e[11]=w,e[12]=g):g=e[12];let x;e[13]!==i?(x=fe("max-w-sm",i),e[13]=i,e[14]=x):x=e[14];let k;e[15]!==n||e[16]!==x?(k=s.jsx(ks,{sideOffset:8,className:x,children:n}),e[15]=n,e[16]=x,e[17]=k):k=e[17];let y;return e[18]!==o||e[19]!==g||e[20]!==k?(y=s.jsxs(bs,{open:o,onOpenChange:d,children:[g,k]}),e[18]=o,e[19]=g,e[20]=k,e[21]=y):y=e[21],y};function yh(t){return!t}const wn="w-full min-w-40 max-w-48",Jt="settings",ra="w-full min-w-40 max-w-48",Is="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",$n=fe(Ao(),"w-full min-w-40 max-w-48"),Us="w-full max-w-[24rem]",dc="min-w-0 flex-1",ti="flex w-full min-w-0 items-center gap-2",si="typography-meta shrink-0 text-muted-foreground tabular-nums",Bn="space-y-4",Ds="space-y-1.5",Bo="typography-settings-page-title text-muted-foreground",ml="typography-settings-section-title text-foreground",fn=ml,vh="typography-settings-group-title text-foreground",zt="typography-settings-field-label text-foreground",Cu="typography-settings-description text-muted-foreground",Js="typography-meta text-muted-foreground",uc="typography-meta font-medium text-foreground",wh="typography-settings-section-title text-foreground",dt=t=>{const e=tt.c(20),{title:n,description:a,titleAccessory:i,info:r,headerAction:o,children:d,divider:c,className:p,contentClassName:u,settingsItem:f}=t,m=c===void 0?!0:c,w=n!=null||a!=null||o!=null||r!=null,b=m?"border-t border-border/60 py-8":"pb-8";let g;e[0]!==p||e[1]!==b?(g=fe("space-y-5",b,p),e[0]=p,e[1]=b,e[2]=g):g=e[2];let x;e[3]!==a||e[4]!==w||e[5]!==o||e[6]!==r||e[7]!==n||e[8]!==i?(x=w?s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[n!=null?s.jsxs("div",{className:"flex items-center gap-2",children:[typeof n=="string"||typeof n=="number"?s.jsx("h2",{className:ml,children:n}):n,i,r!=null?s.jsx($t,{children:r}):null]}):null,a!=null?s.jsx("div",{className:Cu,children:a}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,e[3]=a,e[4]=w,e[5]=o,e[6]=r,e[7]=n,e[8]=i,e[9]=x):x=e[9];let k;e[10]!==u?(k=fe(u),e[10]=u,e[11]=k):k=e[11];let y;e[12]!==d||e[13]!==k?(y=s.jsx("div",{className:k,children:d}),e[12]=d,e[13]=k,e[14]=y):y=e[14];let C;return e[15]!==f||e[16]!==g||e[17]!==x||e[18]!==y?(C=s.jsxs("section",{"data-settings-item":f,className:g,children:[x,y]}),e[15]=f,e[16]=g,e[17]=x,e[18]=y,e[19]=C):C=e[19],C},On=t=>{const e=tt.c(5),{children:n,className:a}=t;let i;e[0]!==a?(i=fe("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",a),e[0]=a,e[1]=i):i=e[1];let r;return e[2]!==n||e[3]!==i?(r=s.jsx("div",{className:i,children:n}),e[2]=n,e[3]=i,e[4]=r):r=e[4],r},pn=t=>{const e=tt.c(6),{children:n,className:a,as:i}=t,r=i===void 0?"h3":i;let o;e[0]!==a?(o=fe(vh,a),e[0]=a,e[1]=o):o=e[1];let d;return e[2]!==r||e[3]!==n||e[4]!==o?(d=s.jsx(r,{className:o,children:n}),e[2]=r,e[3]=n,e[4]=o,e[5]=d):d=e[5],d},Zs=t=>{const e=tt.c(16),{title:n,description:a,info:i,children:r,className:o,contentClassName:d,settingsItem:c}=t;let p;e[0]!==o?(p=fe("space-y-2",o),e[0]=o,e[1]=p):p=e[1];let u;e[2]!==a||e[3]!==i||e[4]!==n?(u=n!=null||a!=null||i!=null?s.jsxs("div",{className:"space-y-0.5",children:[n!=null?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(pn,{children:n}),i!=null?s.jsx($t,{children:i}):null]}):null,a!=null?s.jsx("p",{className:Js,children:a}):null]}):null,e[2]=a,e[3]=i,e[4]=n,e[5]=u):u=e[5];let f;e[6]!==d?(f=fe(d),e[6]=d,e[7]=f):f=e[7];let m;e[8]!==r||e[9]!==f?(m=s.jsx("div",{className:f,children:r}),e[8]=r,e[9]=f,e[10]=m):m=e[10];let w;return e[11]!==c||e[12]!==p||e[13]!==u||e[14]!==m?(w=s.jsxs("div",{"data-settings-item":c,className:p,children:[u,m]}),e[11]=c,e[12]=p,e[13]=u,e[14]=m,e[15]=w):w=e[15],w},ns=t=>{const e=tt.c(25),{label:n,description:a,info:i,descriptionPlacement:r,children:o,settingsItem:d,className:c,controlClassName:p}=t,u=r===void 0?"before":r;let f;e[0]!==a?(f=a!=null?s.jsx("p",{className:Js,children:a}):null,e[0]=a,e[1]=f):f=e[1];const m=f;let w;e[2]!==c?(w=fe("space-y-2",c),e[2]=c,e[3]=w):w=e[3];let b;e[4]!==n?(b=s.jsx("div",{className:zt,children:n}),e[4]=n,e[5]=b):b=e[5];let g;e[6]!==i?(g=i!=null?s.jsx($t,{children:i}):null,e[6]=i,e[7]=g):g=e[7];let x;e[8]!==b||e[9]!==g?(x=s.jsxs("div",{className:"flex items-center gap-1.5",children:[b,g]}),e[8]=b,e[9]=g,e[10]=x):x=e[10];const k=u==="before"?m:null;let y;e[11]!==x||e[12]!==k?(y=s.jsxs("div",{className:"space-y-0.5",children:[x,k]}),e[11]=x,e[12]=k,e[13]=y):y=e[13];let C;e[14]!==p?(C=fe("flex min-w-0 max-w-[24rem] items-center gap-2",p),e[14]=p,e[15]=C):C=e[15];let z;e[16]!==o||e[17]!==C?(z=s.jsx("div",{className:C,children:o}),e[16]=o,e[17]=C,e[18]=z):z=e[18];const j=u==="after"?m:null;let N;return e[19]!==d||e[20]!==z||e[21]!==j||e[22]!==w||e[23]!==y?(N=s.jsxs("div",{"data-settings-item":d,className:w,children:[y,z,j]}),e[19]=d,e[20]=z,e[21]=j,e[22]=w,e[23]=y,e[24]=N):N=e[24],N},Xt=t=>{const e=tt.c(25),{label:n,description:a,info:i,children:r,settingsItem:o,className:d,controlClassName:c,alignEnd:p}=t,u=p===void 0?!0:p;let f;e[0]!==d?(f=fe("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",d),e[0]=d,e[1]=f):f=e[1];let m;e[2]!==n?(m=s.jsx("div",{className:zt,children:n}),e[2]=n,e[3]=m):m=e[3];let w;e[4]!==i?(w=i!=null?s.jsx($t,{children:i}):null,e[4]=i,e[5]=w):w=e[5];let b;e[6]!==m||e[7]!==w?(b=s.jsxs("div",{className:"flex items-center gap-1.5",children:[m,w]}),e[6]=m,e[7]=w,e[8]=b):b=e[8];let g;e[9]!==a?(g=a!=null?s.jsx("p",{className:fe(Js,"mt-0.5"),children:a}):null,e[9]=a,e[10]=g):g=e[10];let x;e[11]!==b||e[12]!==g?(x=s.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[b,g]}),e[11]=b,e[12]=g,e[13]=x):x=e[13];const k=u&&"@xl:justify-end";let y;e[14]!==c||e[15]!==k?(y=fe("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",k,c),e[14]=c,e[15]=k,e[16]=y):y=e[16];let C;e[17]!==r||e[18]!==y?(C=s.jsx("div",{className:y,children:r}),e[17]=r,e[18]=y,e[19]=C):C=e[19];let z;return e[20]!==o||e[21]!==C||e[22]!==f||e[23]!==x?(z=s.jsxs("div",{"data-settings-item":o,className:f,children:[x,C]}),e[20]=o,e[21]=C,e[22]=f,e[23]=x,e[24]=z):z=e[24],z},la=t=>{const e=tt.c(6),{children:n,className:a,settingsItem:i}=t;let r;e[0]!==a?(r=fe("pt-4",a),e[0]=a,e[1]=r):r=e[1];let o;return e[2]!==n||e[3]!==i||e[4]!==r?(o=s.jsx("div",{"data-settings-item":i,className:r,children:n}),e[2]=n,e[3]=i,e[4]=r,e[5]=o):o=e[5],o},Ct=t=>{const e=tt.c(39),{checked:n,onChange:a,label:i,description:r,disabled:o,ariaLabel:d,settingsItem:c,className:p,labelAccessory:u,info:f}=t,m=o===void 0?!1:o;let w;e[0]!==n||e[1]!==m||e[2]!==a?(w=()=>{m||a(!n)},e[0]=n,e[1]=m,e[2]=a,e[3]=w):w=e[3];const b=w,g=r!=null,x=g?"items-start":"items-center",k=m&&"cursor-not-allowed opacity-60";let y;e[4]!==p||e[5]!==x||e[6]!==k?(y=fe("group flex cursor-pointer gap-2 py-0.5",x,k,p),e[4]=p,e[5]=x,e[6]=k,e[7]=y):y=e[7];const C=m?-1:0,z=m||void 0;let j;e[8]!==b?(j=F=>{(F.key===" "||F.key==="Enter")&&(F.preventDefault(),b())},e[8]=b,e[9]=j):j=e[9];let N;e[10]!==d||e[11]!==n||e[12]!==m||e[13]!==a?(N=s.jsx(an,{checked:n,onChange:a,disabled:m,ariaLabel:d}),e[10]=d,e[11]=n,e[12]=m,e[13]=a,e[14]=N):N=e[14];let v;e[15]!==i?(v=s.jsx("span",{className:zt,children:i}),e[15]=i,e[16]=v):v=e[16];let P;e[17]!==f?(P=f!=null?s.jsx($t,{children:f}):null,e[17]=f,e[18]=P):P=e[18];let $;e[19]!==u||e[20]!==v||e[21]!==P?($=s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[v,u,P]}),e[19]=u,e[20]=v,e[21]=P,e[22]=$):$=e[22];let O;e[23]!==r||e[24]!==g?(O=g?s.jsx("span",{className:Js,children:r}):null,e[23]=r,e[24]=g,e[25]=O):O=e[25];let M;e[26]!==$||e[27]!==O?(M=s.jsxs("div",{className:"flex min-w-0 flex-col",children:[$,O]}),e[26]=$,e[27]=O,e[28]=M):M=e[28];let S;return e[29]!==n||e[30]!==c||e[31]!==M||e[32]!==y||e[33]!==C||e[34]!==z||e[35]!==j||e[36]!==N||e[37]!==b?(S=s.jsxs("div",{"data-settings-item":c,className:y,role:"button",tabIndex:C,"aria-pressed":n,"aria-disabled":z,onClick:b,onKeyDown:j,children:[N,M]}),e[29]=n,e[30]=c,e[31]=M,e[32]=y,e[33]=C,e[34]=z,e[35]=j,e[36]=N,e[37]=b,e[38]=S):S=e[38],S},zn=t=>{const e=tt.c(33),{selected:n,onSelect:a,label:i,description:r,ariaLabel:o,disabled:d,className:c}=t,p=d===void 0?!1:d,u=r!=null?"items-start":"items-center",f=p&&"cursor-not-allowed opacity-60";let m;e[0]!==c||e[1]!==u||e[2]!==f?(m=fe("flex cursor-pointer gap-2 py-0.5",u,f,c),e[0]=c,e[1]=u,e[2]=f,e[3]=m):m=e[3];const w=p?-1:0,b=p||void 0;let g,x;e[4]!==p||e[5]!==a?(g=()=>{p||a()},x=$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),p||a())},e[4]=p,e[5]=a,e[6]=g,e[7]=x):(g=e[6],x=e[7]);const k=r!=null?"mt-0.5":void 0;let y;e[8]!==o||e[9]!==p||e[10]!==a||e[11]!==n||e[12]!==k?(y=s.jsx(kr,{checked:n,onChange:a,disabled:p,ariaLabel:o,className:k}),e[8]=o,e[9]=p,e[10]=a,e[11]=n,e[12]=k,e[13]=y):y=e[13];const C=n?"text-foreground":"text-foreground/50";let z;e[14]!==C?(z=fe("typography-settings-field-label font-normal",C),e[14]=C,e[15]=z):z=e[15];let j;e[16]!==i||e[17]!==z?(j=s.jsx("span",{className:z,children:i}),e[16]=i,e[17]=z,e[18]=j):j=e[18];let N;e[19]!==r?(N=r!=null?s.jsx("span",{className:Js,children:r}):null,e[19]=r,e[20]=N):N=e[20];let v;e[21]!==j||e[22]!==N?(v=s.jsxs("div",{className:"flex min-w-0 flex-col",children:[j,N]}),e[21]=j,e[22]=N,e[23]=v):v=e[23];let P;return e[24]!==n||e[25]!==y||e[26]!==v||e[27]!==m||e[28]!==w||e[29]!==b||e[30]!==g||e[31]!==x?(P=s.jsxs("div",{className:m,role:"button",tabIndex:w,"aria-pressed":n,"aria-disabled":b,onClick:g,onKeyDown:x,children:[y,v]}),e[24]=n,e[25]=y,e[26]=v,e[27]=m,e[28]=w,e[29]=b,e[30]=g,e[31]=x,e[32]=P):P=e[32],P},Kn=t=>{const e=tt.c(6),{"aria-label":n,children:a,className:i}=t;let r;e[0]!==i?(r=fe(Ds,i),e[0]=i,e[1]=r):r=e[1];let o;return e[2]!==n||e[3]!==a||e[4]!==r?(o=s.jsx("div",{role:"radiogroup","aria-label":n,className:r,children:a}),e[2]=n,e[3]=a,e[4]=r,e[5]=o):o=e[5],o};function Ys(t){const e=tt.c(13),{value:n,options:a,onChange:i,className:r,"aria-label":o}=t;let d;e[0]!==r?(d=fe("flex flex-wrap items-center gap-1",r),e[0]=r,e[1]=d):d=e[1];let c;if(e[2]!==i||e[3]!==a||e[4]!==n){let u;e[6]!==i||e[7]!==n?(u=f=>s.jsx(ee,{type:"button",variant:"chip",size:"xs",disabled:f.disabled,"aria-pressed":n===f.value,className:"!font-normal",onClick:()=>i(f.value),children:f.label},f.value),e[6]=i,e[7]=n,e[8]=u):u=e[8],c=a.map(u),e[2]=i,e[3]=a,e[4]=n,e[5]=c}else c=e[5];let p;return e[9]!==o||e[10]!==d||e[11]!==c?(p=s.jsx("div",{role:"group","aria-label":o,className:d,children:c}),e[9]=o,e[10]=d,e[11]=c,e[12]=p):p=e[12],p}const mc="https://github.com/openchamber/openchamber",jh="https://discord.gg/ZYRSdnwwKA",pc="https://x.com/openchamber_dev",kh=800,Iu=({initialUpdateDialogOpen:t=!1})=>{const{t:e}=lt(),[n,a]=l.useState(t),[i,r]=l.useState(!1),[o,d]=l.useState(null),[c,p]=l.useState(null),u=Su(Hs(g=>({info:g.info,checking:g.checking,available:g.available,error:g.error,downloading:g.downloading,downloaded:g.downloaded,progress:g.progress,runtimeType:g.runtimeType,checkForUpdates:g.checkForUpdates,downloadUpdate:g.downloadUpdate,restartToUpdate:g.restartToUpdate}))),{isMobile:f}=Vs(),m=o||u.info?.currentVersion||"unknown";l.useEffect(()=>{let g=!1;return(async()=>{try{const k=await ht("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!k.ok)return;const y=await k.json().catch(()=>null),C=typeof y?.openchamberVersion=="string"&&y.openchamberVersion.trim().length>0?y.openchamberVersion.trim():null;g||d(C)}catch{g||d(null)}})(),()=>{g=!0}},[]),l.useEffect(()=>{let g=!1;return(async()=>{try{const k=await ht("/api/opencode/upgrade-status",{method:"GET",headers:{Accept:"application/json"}});if(!k.ok)return;const y=await k.json().catch(()=>null),C=typeof y?.currentVersion=="string"&&y.currentVersion.trim().length>0?y.currentVersion.trim():null;g||p(C)}catch{g||p(null)}})(),()=>{g=!0}},[]);const w=l.useRef(!1);l.useEffect(()=>{if(u.checking)r(!0),w.current=!0;else if(i){const g=setTimeout(()=>{r(!1),w.current&&!u.available&&!u.error&&(J.success(e("settings.openchamber.about.toast.latestVersion")),w.current=!1)},kh);return()=>clearTimeout(g)}},[e,u.checking,i,u.available,u.error]);const b=u.checking||i;return f?s.jsxs("div",{className:"w-full space-y-6 pb-2",children:[s.jsxs("div",{className:"flex flex-col items-center text-center",children:[s.jsx(Jd,{width:72,height:72}),s.jsx("h2",{className:`mt-4 ${wh}`,children:"OpenChamber"}),s.jsxs("div",{className:"mt-2 space-y-1 typography-ui text-muted-foreground",children:[s.jsx("p",{children:e("aboutDialog.openChamberVersionLabel",{version:m})}),s.jsx("p",{children:e("aboutDialog.openCodeVersionLabel",{version:c||e("settings.openchamber.about.state.unknown")})})]})]}),s.jsxs("div",{className:"flex justify-center",children:[!u.available&&!u.error&&s.jsxs(ee,{type:"button",variant:"outline",size:"sm",onClick:()=>u.checkForUpdates(),disabled:b,className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[b?s.jsx(K,{name:"loader",className:"size-4 animate-spin"}):s.jsx(K,{name:"refresh",className:"size-4"}),e(b?"settings.openchamber.about.state.checking":"settings.openchamber.about.actions.checkForUpdates")]}),!b&&u.available&&s.jsxs(ee,{type:"button",variant:"default",size:"sm",onClick:()=>a(!0),className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[s.jsx(K,{name:"download",className:"size-4"}),e("settings.openchamber.about.actions.updateToVersion",{version:u.info?.version||""})]})]}),u.error&&s.jsx("p",{className:"rounded-xl border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 typography-meta text-[var(--status-error)]",children:u.error}),s.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-5",children:[s.jsxs("a",{href:mc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground",children:[s.jsx(K,{name:"github-fill",className:"size-5"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:jh,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground",children:[s.jsx(K,{name:"discord-fill",className:"size-5"}),s.jsx("span",{children:"Discord"})]})]}),s.jsxs("a",{href:pc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground",children:[s.jsx(K,{name:"twitter-xfill",className:"size-5"}),s.jsx("span",{children:"@openchamber_dev"})]})]}),s.jsx("p",{className:"text-center typography-ui text-muted-foreground/60",children:e("aboutDialog.footerNote")}),s.jsx(cc,{open:n,onOpenChange:a,info:u.info,downloading:u.downloading,downloaded:u.downloaded,progress:u.progress,error:u.error,onDownload:u.downloadUpdate,onRestart:u.restartToUpdate,runtimeType:u.runtimeType})]}):s.jsxs(dt,{divider:!1,children:[s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex flex-col @xl:flex-row @xl:items-center justify-between gap-4 px-4 py-3 border-b border-border/40",children:[s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:zt,children:e("settings.openchamber.about.field.version")}),s.jsx("span",{className:"typography-meta text-muted-foreground font-mono",children:m})]}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:zt,children:e("settings.openchamber.about.field.openCodeVersion")}),s.jsx("span",{className:"typography-meta text-muted-foreground font-mono",children:c||e("settings.openchamber.about.state.unknown")})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[u.checking&&s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[s.jsx(K,{name:"loader",className:"h-4 w-4 animate-spin"}),s.jsx("span",{className:"typography-meta",children:e("settings.openchamber.about.state.checking")})]}),!u.checking&&u.available&&s.jsxs(ee,{size:"sm",variant:"default",onClick:()=>a(!0),children:[s.jsx(K,{name:"download",className:"h-4 w-4 mr-1"}),e("settings.openchamber.about.actions.updateToVersion",{version:u.info?.version||""})]}),!u.checking&&!u.available&&!u.error&&s.jsx("span",{className:"typography-meta text-muted-foreground",children:e("settings.openchamber.about.state.upToDate")}),s.jsx(ee,{size:"sm",variant:"outline",onClick:()=>u.checkForUpdates(),disabled:u.checking,children:e("settings.openchamber.about.actions.checkForUpdates")})]})]}),u.error&&s.jsx("div",{className:"px-3 py-2 border-b border-border/40",children:s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:u.error})}),s.jsxs("div",{className:"flex items-center gap-4 px-4 py-4",children:[s.jsxs("a",{href:mc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground typography-meta transition-colors",children:[s.jsx(K,{name:"github-fill",className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:pc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground typography-meta transition-colors",children:[s.jsx(K,{name:"twitter-xfill",className:"h-4 w-4"}),s.jsx("span",{children:"@openchamber_dev"})]})]})]}),s.jsx(cc,{open:n,onOpenChange:a,info:u.info,downloading:u.downloading,downloaded:u.downloaded,progress:u.progress,error:u.error,onDownload:u.downloadUpdate,onRestart:u.restartToUpdate,runtimeType:u.runtimeType})]})},VN=t=>!(t.dismissed==="true"||t.sessionShown==="true"||t.hasActiveToast),Nh=t=>!(!t.version||t.seenVersions.has(t.version)||t.dismissedVersion!==null&&t.dismissedVersion===t.version),Sh=t=>{if(t===null||typeof t!="object")return"";const e=t.version;return typeof e!="string"?"":e.trim()},Ch=t=>!t||t.upgrade?.supported!==!0||t.available!==!0||typeof t.latestVersion!="string"?"":t.latestVersion.trim(),Ca="opencode-update-available",Mi="opencode-upgrade-progress",Ih=5e3,Ph=[1e4,6e4],gc="opencode-update-toast-dismissed-version",HN=()=>{const{t}=lt(),e=ke(o=>o.showOpenCodeUpdateNotifications),n=we.useRef(new Set),a=we.useRef(!1);we.useEffect(()=>{e||J.dismiss(Ca)},[e]);const i=we.useCallback(()=>{J.dismiss(Mi),_n({message:t("opencodeUpdate.toast.reload.message"),mode:"projects",scopes:["all"]}).catch(()=>{})},[t]),r=we.useCallback(async()=>{if(!a.current){a.current=!0,J.dismiss(Ca),J.message(t("opencodeUpdate.toast.upgrading.title"),{id:Mi,description:t("opencodeUpdate.toast.upgrading.description"),duration:1/0,icon:s.jsx(K,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})});try{const o=await ht("/api/opencode/upgrade",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),d=await o.json().catch(()=>null);if(!o.ok||d?.success===!1)throw new Error(d?.error||o.statusText||t("opencodeUpdate.toast.failed.description"));J.success(t("opencodeUpdate.toast.updated.title"),{id:Mi,description:d?.version?t("opencodeUpdate.toast.updated.descriptionWithVersion",{version:d.version}):t("opencodeUpdate.toast.updated.description"),duration:1/0,icon:s.jsx(K,{name:"check",className:"h-4 w-4 text-[var(--status-success)]"}),action:{label:t("opencodeUpdate.toast.actions.reload"),onClick:i}})}catch(o){J.error(t("opencodeUpdate.toast.failed.title"),{id:Mi,description:o instanceof Error?o.message:t("opencodeUpdate.toast.failed.description"),duration:1/0})}finally{a.current=!1}}},[i,t]);return we.useEffect(()=>{const o=m=>{if(!ke.getState().showOpenCodeUpdateNotifications){J.dismiss(Ca);return}Nh({version:m,dismissedVersion:zl().getItem(gc),seenVersions:n.current})&&(n.current.add(m),J.info(t("opencodeUpdate.toast.available.title"),{id:Ca,description:t("opencodeUpdate.toast.available.description",{version:m}),duration:1/0,action:{label:t("opencodeUpdate.toast.actions.update"),onClick:r},cancel:{label:t("opencodeUpdate.toast.actions.dismiss"),onClick:()=>{zl().setItem(gc,m),It({openCodeUpdateToastDismissedVersion:m}),J.dismiss(Ca)}}}))};let d=!1;const c=[],p=async(m,w=mn())=>{try{const b=await ht("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!b.ok)throw new Error(b.statusText||"OpenCode upgrade status check failed");const g=await b.json().catch(()=>null),x=Ch(g);!d&&w===mn()&&x&&o(x)}catch{const b=Ph[m];!d&&w===mn()&&b!==void 0&&c.push(setTimeout(()=>{p(m+1,w)},b))}},u=m=>{Sh(m.detail)&&p(0)};e&&c.push(setTimeout(()=>{p(0)},Ih));const f=cl(({runtimeKey:m})=>{n.current.clear(),J.dismiss(Ca),ke.getState().showOpenCodeUpdateNotifications&&p(0,m)});return window.addEventListener("openchamber:opencode-update-available",u),()=>{d=!0;for(const m of c)clearTimeout(m);f(),window.removeEventListener("openchamber:opencode-update-available",u)}},[r,e,t]),null},WN=()=>{const t=tt.c(3),[e,n]=l.useState(Th),{isUpdating:a}=e;let i,r;if(t[0]===Symbol.for("react.memo_cache_sentinel")?(i=()=>Mm(n),r=[],t[0]=i,t[1]=r):(i=t[0],r=t[1]),l.useEffect(i,r),!a)return null;let o;return t[2]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-background/90",children:s.jsx(Jd,{width:80,height:80,isAnimated:!0})}),t[2]=o):o=t[2],o};function Th(){return Rm()}class Ah extends l.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){this.setState({error:e,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?s.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:s.jsxs(Lm,{className:"w-full max-w-md",children:[s.jsx(Fm,{className:"text-center",children:s.jsxs(Om,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(K,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(zm,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&s.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&s.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[s.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),s.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(ee,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(K,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),s.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Eh(t){const e=tt.c(22),{t:n}=lt();let a;e[0]!==n?(a=n("chat.errorBoundary.title"),e[0]=n,e[1]=a):a=e[1];let i;e[2]!==n?(i=n("chat.errorBoundary.description"),e[2]=n,e[3]=i):i=e[3];let r;e[4]!==n?(r=n("chat.errorBoundary.sessionLabel"),e[4]=n,e[5]=r):r=e[5];let o;e[6]!==n?(o=n("chat.errorBoundary.detailsSummary"),e[6]=n,e[7]=o):o=e[7];let d;e[8]!==n?(d=n("chat.errorBoundary.resetAction"),e[8]=n,e[9]=d):d=e[9];let c;e[10]!==n?(c=n("chat.errorBoundary.persistentHint"),e[10]=n,e[11]=c):c=e[11];let p;e[12]!==a||e[13]!==i||e[14]!==r||e[15]!==o||e[16]!==d||e[17]!==c?(p={title:a,description:i,sessionLabel:r,detailsSummary:o,resetAction:d,persistentHint:c},e[12]=a,e[13]=i,e[14]=r,e[15]=o,e[16]=d,e[17]=c,e[18]=p):p=e[18];let u;return e[19]!==t||e[20]!==p?(u=s.jsx(Ah,{...t,texts:p}),e[19]=t,e[20]=p,e[21]=u):u=e[21],u}const GN=t=>{const e=tt.c(6),{active:n,readOnly:a}=t,i=n===void 0?!0:n,r=a===void 0?!1:a,d=es(Dh)||void 0;let c;e[0]!==i||e[1]!==r?(c=s.jsx(Km,{active:i,readOnly:r}),e[0]=i,e[1]=r,e[2]=c):c=e[2];let p;return e[3]!==d||e[4]!==c?(p=s.jsx(Eh,{sessionId:d,children:c}),e[3]=d,e[4]=c,e[5]=p):p=e[5],p};function Dh(t){return t.currentSessionId}const Rh=t=>t!==null&&typeof t=="object"&&"updateStatus"in t&&typeof t.updateStatus=="function",Mh=t=>{const e=document.createElement("div");e.className="cm-vim-panel";const n=Sf(t);if(!n)return{top:!1,dom:e};n.state.statusbar=e;const a=n.state.vimPlugin;return Rh(a)&&a.updateStatus(),{top:!1,dom:e,destroy(){n.state.statusbar===e&&(n.state.statusbar=null)}}};function fc(t){return t?[Nf(),rf.of(Mh),of()]:[]}const Lh={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},Fh={case:"Match case",re:"Regular expression",word:"Match whole word"};function Oh(t){const e=t.querySelector(".cm-search");if(e){for(const[n,a]of Object.entries(Lh)){const i=e.querySelector(`button[name="${n}"]`);i&&!i.title&&(i.title=a)}for(const[n,a]of Object.entries(Fh)){const r=e.querySelector(`input[name="${n}"]`)?.parentElement;r&&!r.title&&(r.title=a)}}}const qr=new WeakMap;function zh(t,e){const n=pr(t.state);if(!n.valid)return qr.delete(t),0;const a=qr.get(t);if(!e&&a?.doc===t.state.doc&&a.query.eq(n))return a.total;const i=n.getCursor(t.state);let r=0;for(let o=i.next();!o.done;o=i.next())r+=1;return qr.set(t,{query:n,doc:t.state.doc,total:r}),r}function Kh(t){const e=pr(t.state);if(!e.valid)return 0;const n=t.state.selection.main,a=e.getCursor(t.state);let i=0,r=0;for(let o=a.next();!o.done;o=a.next()){const d=o.value;if(i+=1,r===0&&(r=i),n.from===d.from&&n.to===d.to||n.from<d.to&&n.to>d.from||d.from>=n.head)return i}return r}function hc(t,e,n=!1){const a=t.querySelector(".cm-search");if(!a)return;let i=a.querySelector(".cm-search-message");if(!i){i=document.createElement("span"),i.className="cm-search-message",i.setAttribute("aria-live","polite");const d=a.querySelector('button[name="next"]'),c=d?.parentNode===a?d:a.firstChild;a.insertBefore(i,c)}const r=zh(e,n),o=r===0?0:Kh(e);i.textContent=r===0?"":`${o}/${r}`}const xc=new pa,bc=new pa,yc=new pa,vc=new pa,wc=new pa,jc=new pa,kc=new pa,Nc=t=>t,Jr=vf,Bh=jf,_h=kf;class Uh extends cf{constructor(e,n){super(),this.id=e,this.containerMap=n}toDOM(){let e=this.containerMap.get(this.id);return e||(e=document.createElement("div"),e.className="oc-block-widget",e.dataset.widgetId=this.id,this.containerMap.set(this.id,e)),e}eq(e){return e.id===this.id}destroy(){}}const Sc=(t,e)=>!t||t.length===0?[]:gu.define({create(n){const a=new ul,i=[...t].sort((r,o)=>r.afterLine-o.afterLine);for(const r of i){const o=n.doc.lines;if(r.afterLine>o)continue;const d=n.doc.line(r.afterLine);a.add(d.to,d.to,Pr.widget({widget:new Uh(r.id,e),block:!0,side:1}))}return a.finish()},update(n,a){return n.map(a.changes)},provide:n=>tn.decorations.from(n)}),Cc=t=>{if(!t)return[];const e=Math.max(1,t.start),n=Math.max(e,t.end);return pu.fromClass(class{decorations;constructor(a){this.decorations=this.build(a)}update(a){(a.docChanged||a.viewportChanged)&&(this.decorations=this.build(a.view))}build(a){const i=new ul;for(let r=e;r<=n&&r<=a.state.doc.lines;r+=1){const o=a.state.doc.line(r);i.add(o.from,o.from,Pr.line({class:"oc-cm-selected-line"}))}return i.finish()}},{decorations:a=>a.decorations})};function _o({value:t,onChange:e,extensions:n,className:a,readOnly:i,lineNumbersConfig:r,highlightLines:o,onViewReady:d,onViewDestroy:c,blockWidgets:p,enableSearch:u,searchOpen:f,onSearchOpenChange:m,vimMode:w}){const b=l.useRef(null),g=l.useRef(null),x=l.useRef(t),k=l.useRef(e),y=l.useRef(d),C=l.useRef(c),z=l.useRef(m),j=l.useRef(p),N=l.useRef(w),v=l.useRef(new Map),[P,$]=l.useState([]),O=l.useCallback(S=>{const F=(S??[]).map(E=>{const D=v.current.get(E.id);return D?{id:E.id,content:E.content,container:D}:null}).filter(E=>E!==null);$(E=>E.length===F.length&&E.every((D,W)=>{const H=F[W];return D.id===H.id&&D.content===H.content&&D.container===H.container})?E:F)},[]),M=l.useCallback(S=>{const F=b.current,E=S??g.current;if(!F||!E)return;const D=E.dom.querySelector(".cm-gutters"),W=D instanceof HTMLElement?D.getBoundingClientRect().width:0;F.style.setProperty("--oc-editor-gutter-width",`${W}px`)},[]);return l.useEffect(()=>{x.current=t},[t]),l.useEffect(()=>{k.current=e},[e]),l.useEffect(()=>{y.current=d,C.current=c},[d,c]),l.useEffect(()=>{z.current=m},[m]),l.useEffect(()=>{j.current=p,O(p)},[p,O]),l.useEffect(()=>{if(!b.current)return;const S=(()=>{if(typeof document>"u")return null;const E=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(E)return E;const D=window.__OPENCHAMBER_CSP_NONCE__;return typeof D=="string"&&D.length>0?D:null})(),F=pf.create({doc:x.current,extensions:[...S?[tn.cspNonce.of(S)]:[],lf({fixed:!0}),xc.of(ql(r)),ff(),yf.of(" "),kc.of(fc(w)),Gr.of([hf,...xf,...bf]),tn.updateListener.of(E=>{M(E.view),(E.viewportChanged||E.geometryChanged)&&O(j.current);const D=Yl(E.startState),W=Yl(E.state);D!==W&&z.current?.(W);const H=!pr(E.startState).eq(pr(E.state));if(W&&(D!==W||H||E.docChanged||E.selectionSet)&&hc(E.view.dom,E.view,D!==W||H||E.docChanged),!E.docChanged)return;const Z=E.state.doc.toString();x.current=Z,k.current(Z),O(j.current)}),bc.of(tn.editable.of(!i)),yc.of(n??[]),vc.of(Cc(o)),wc.of(Sc(p,v.current)),jc.of(u?[Ql({top:!0}),Gr.of(Nc(Xl))]:[])]});return g.current=new tn({state:F,parent:b.current}),Jr(g.current,g.current.state.doc.length,200),g.current.requestMeasure(),requestAnimationFrame(()=>{M(g.current),O(j.current)}),g.current&&y.current?.(g.current),()=>{C.current?.(),g.current?.destroy(),g.current=null,$([])}},[j,M,O]),l.useEffect(()=>{const S=g.current;S&&(S.dispatch({effects:[xc.reconfigure(ql(r)),bc.reconfigure(tn.editable.of(!i)),yc.reconfigure(n??[]),vc.reconfigure(Cc(o)),wc.reconfigure(Sc(p,v.current)),jc.reconfigure(u?[Ql({top:!0}),Gr.of(Nc(Xl))]:[])]}),Jr(S,S.state.doc.length,200),S.requestMeasure(),requestAnimationFrame(()=>{M(S),O(j.current)}))},[n,o,r,i,p,u,M,O]),l.useEffect(()=>{const S=g.current;if(!S){N.current=w;return}N.current!==w&&(N.current=w,S.dispatch({effects:kc.reconfigure(fc(w))}))},[w]),l.useEffect(()=>{const S=g.current;!S||u===!1||(f?(Bh(S),requestAnimationFrame(()=>{Oh(S.dom),hc(S.dom,S,!0)})):_h(S))},[f,u]),l.useEffect(()=>{const S=g.current;if(!S)return;const F=S.state.doc.toString();F!==t&&(S.dispatch({changes:{from:0,to:F.length,insert:t}}),Jr(S,S.state.doc.length,300),S.requestMeasure(),requestAnimationFrame(()=>M(S)))},[t,M]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:b,className:fe("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6","[&_.cm-lineNumbers]:text-[var(--tools-edit-line-number)]",a)}),P.map(S=>Xi.createPortal(S.content,S.container,S.id))]})}const Pu=t=>{const e=tt.c(11),{currentMode:n,onToggle:a}=t,i=n==="preview",r=i?"Switch to edit mode":"Switch to preview mode",o=i?"Edit":"Preview";let d;e[0]!==i?(d=i?s.jsx(K,{name:"eye",className:"size-4","aria-hidden":"true"}):s.jsx(K,{name:"eye-off",className:"size-4","aria-hidden":"true"}),e[0]=i,e[1]=d):d=e[1];let c;e[2]!==r||e[3]!==a||e[4]!==d?(c=s.jsx(xs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"sm",onClick:a,"aria-label":r,className:"h-5 w-5 p-0",children:d})}),e[2]=r,e[3]=a,e[4]=d,e[5]=c):c=e[5];let p;e[6]!==o?(p=s.jsx(ks,{sideOffset:8,children:o}),e[6]=o,e[7]=p):p=e[7];let u;return e[8]!==c||e[9]!==p?(u=s.jsxs(bs,{children:[c,p]}),e[8]=c,e[9]=p,e[10]=u):u=e[10],u};function Wn(t){const e=tt.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let a;return e[2]!==n?(a=s.jsx(Tf,{...n}),e[2]=n,e[3]=a):a=e[3],a}function Gn(t){const e=tt.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let a;return e[2]!==n?(a=s.jsx(Af,{...n}),e[2]=n,e[3]=a):a=e[3],a}function qn(t){const e=tt.c(20);let n,a,i,r,o;e[0]!==t?({className:a,positionerClassName:i,children:n,style:o,...r}=t,e[0]=t,e[1]=n,e[2]=a,e[3]=i,e[4]=r,e[5]=o):(n=e[1],a=e[2],i=e[3],r=e[4],o=e[5]);let d;e[6]!==i?(d=fe("app-region-no-drag z-50",i),e[6]=i,e[7]=d):d=e[7];let c;e[8]!==o?(c={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)",...o},e[8]=o,e[9]=c):c=e[9];let p;e[10]!==a?(p=fe(Bm,a),e[10]=a,e[11]=p):p=e[11];let u;e[12]!==n||e[13]!==r||e[14]!==c||e[15]!==p?(u=s.jsx(Ef,{"data-slot":"dropdown-menu-content",style:c,className:p,...r,children:n}),e[12]=n,e[13]=r,e[14]=c,e[15]=p,e[16]=u):u=e[16];let f;return e[17]!==d||e[18]!==u?(f=s.jsx(Mf,{children:s.jsx(Lf,{className:d,children:u})}),e[17]=d,e[18]=u,e[19]=f):f=e[19],f}function An(t){const e=tt.c(8);let n,a;e[0]!==t?({className:n,...a}=t,e[0]=t,e[1]=n,e[2]=a):(n=e[1],a=e[2]);let i;e[3]!==n?(i=fe(_m,n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx(Df,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r}function qN(t){const e=tt.c(8);let n,a;e[0]!==t?({className:n,...a}=t,e[0]=t,e[1]=n,e[2]=a):(n=e[1],a=e[2]);let i;e[3]!==n?(i=fe(Um,n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx(Rf,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r}const ca=Of,da=t=>{const e=tt.c(14);let n,a,i,r;e[0]!==t?({className:i,asChild:n,children:a,...r}=t,e[0]=t,e[1]=n,e[2]=a,e[3]=i,e[4]=r):(n=e[1],a=e[2],i=e[3],r=e[4]);let o;e[5]!==n||e[6]!==a?(o=n&&we.isValidElement(a)?{render:a}:{children:a},e[5]=n,e[6]=a,e[7]=o):o=e[7];const d=o;let c;e[8]!==i?(c=fe("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",i),e[8]=i,e[9]=c):c=e[9];let p;return e[10]!==r||e[11]!==d||e[12]!==c?(p=s.jsx(Ff,{className:c,...r,...d}),e[10]=r,e[11]=d,e[12]=c,e[13]=p):p=e[13],p},ua=t=>{const e=tt.c(8);let n,a;e[0]!==t?({className:n,...a}=t,e[0]=t,e[1]=n,e[2]=a):(n=e[1],a=e[2]);let i;e[3]!==n?(i=fe("overflow-hidden data-[closed]:animate-collapsible-up data-[open]:animate-collapsible-down",n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx(zf,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r};function Tu(t){const e=tt.c(85),{draft:n,onEdit:a,onDelete:i,className:r,maxWidth:o}=t,{t:d}=lt(),p=wr()?.currentTheme,[u,f]=we.useState(!1),[m,w]=we.useState(!1),b=typeof n.text=="string"?n.text:"";let g;e[0]!==b?(g=b.length>150||b.split(`
3
- `).length>3,e[0]=b,e[1]=g):g=e[1];const x=g;let k;e[2]!==r?(k=fe("rounded-lg border shadow-none w-full max-w-[min(100%,calc(var(--oc-context-panel-width,100vw)-var(--oc-editor-gutter-width,0px)))] overflow-hidden transition-all duration-200",r),e[2]=r,e[3]=k):k=e[3];const y=p?.colors?.surface?.elevated,C=p?.colors?.interactive?.border,z=o?`${Math.max(200,Math.floor(o))}px`:void 0;let j;e[4]!==y||e[5]!==C||e[6]!==z?(j={backgroundColor:y,borderColor:C,maxWidth:z},e[4]=y,e[5]=C,e[6]=z,e[7]=j):j=e[7];let N;e[8]===Symbol.for("react.memo_cache_sentinel")?(N=ie=>{ie.preventDefault(),w(!0)},e[8]=N):N=e[8];let v;e[9]!==k||e[10]!==j?(v=s.jsx("div",{className:k,style:j,"data-comment-card":"true",onContextMenu:N}),e[9]=k,e[10]=j,e[11]=v):v=e[11];let P;e[12]!==n.fileLabel?(P=s.jsx("span",{className:"truncate max-w-[200px]",title:n.fileLabel,children:n.fileLabel}),e[12]=n.fileLabel,e[13]=P):P=e[13];let $;e[14]===Symbol.for("react.memo_cache_sentinel")?($=s.jsx("span",{children:"•"}),e[14]=$):$=e[14];let O;e[15]!==n.endLine||e[16]!==n.startLine||e[17]!==d?(O=d("inlineComment.range.lines",{start:n.startLine,end:n.endLine}),e[15]=n.endLine,e[16]=n.startLine,e[17]=d,e[18]=O):O=e[18];let M;e[19]!==O?(M=s.jsx("span",{children:O}),e[19]=O,e[20]=M):M=e[20];let S;e[21]!==n.side?(S=n.side&&s.jsxs("span",{children:["(",n.side,")"]}),e[21]=n.side,e[22]=S):S=e[22];let F;e[23]!==M||e[24]!==S||e[25]!==P?(F=s.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1.5",children:[P,$,M,S]}),e[23]=M,e[24]=S,e[25]=P,e[26]=F):F=e[26];const E=u||!x,D=!u&&x&&"line-clamp-3";let W;e[27]!==D?(W=fe("text-sm whitespace-pre-wrap break-words leading-relaxed",D),e[27]=D,e[28]=W):W=e[28];let H;e[29]!==b||e[30]!==W?(H=s.jsx("div",{className:W,children:b}),e[29]=b,e[30]=W,e[31]=H):H=e[31];let Z;e[32]!==x||e[33]!==u||e[34]!==d?(Z=x&&s.jsx(da,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"sm",className:"h-6 px-0 mt-1 text-xs text-muted-foreground hover:text-foreground w-full justify-start",children:u?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"arrow-up-s",className:"size-3 mr-1"}),d("inlineComment.actions.showLess")]}):s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"arrow-down-s",className:"size-3 mr-1"}),d("inlineComment.actions.showMore")]})})}),e[32]=x,e[33]=u,e[34]=d,e[35]=Z):Z=e[35];let Y;e[36]===Symbol.for("react.memo_cache_sentinel")?(Y=s.jsx(ua,{}),e[36]=Y):Y=e[36];let A;e[37]!==E||e[38]!==H||e[39]!==Z?(A=s.jsxs(ca,{open:E,onOpenChange:f,children:[H,Z,Y]}),e[37]=E,e[38]=H,e[39]=Z,e[40]=A):A=e[40];let X;e[41]!==F||e[42]!==A?(X=s.jsxs("div",{className:"flex-1 min-w-0",children:[F,A]}),e[41]=F,e[42]=A,e[43]=X):X=e[43];let te;e[44]===Symbol.for("react.memo_cache_sentinel")?(te=s.jsx(gs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1 text-muted-foreground hover:text-foreground",children:s.jsx(K,{name:"more",className:"size-4"})})}),e[44]=te):te=e[44];let T;e[45]===Symbol.for("react.memo_cache_sentinel")?(T=s.jsx(K,{name:"edit",className:"size-4 mr-2"}),e[45]=T):T=e[45];let I;e[46]!==d?(I=d("inlineComment.actions.editComment"),e[46]=d,e[47]=I):I=e[47];let B;e[48]!==a||e[49]!==I?(B=s.jsxs(as,{onClick:a,children:[T,I]}),e[48]=a,e[49]=I,e[50]=B):B=e[50];let L;e[51]===Symbol.for("react.memo_cache_sentinel")?(L=s.jsx(K,{name:"delete-bin",className:"size-4 mr-2"}),e[51]=L):L=e[51];let V;e[52]!==d?(V=d("inlineComment.actions.deleteComment"),e[52]=d,e[53]=V):V=e[53];let Q;e[54]!==i||e[55]!==V?(Q=s.jsxs(as,{onClick:i,className:"text-destructive",children:[L,V]}),e[54]=i,e[55]=V,e[56]=Q):Q=e[56];let G;e[57]!==B||e[58]!==Q?(G=s.jsxs(fs,{children:[te,s.jsxs(hs,{align:"end",children:[B,Q]})]}),e[57]=B,e[58]=Q,e[59]=G):G=e[59];let ue;e[60]!==X||e[61]!==G?(ue=s.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[X,G]}),e[60]=X,e[61]=G,e[62]=ue):ue=e[62];let ne;e[63]!==ue||e[64]!==v?(ne=s.jsx(Gn,{render:v,children:ue}),e[63]=ue,e[64]=v,e[65]=ne):ne=e[65];let xe;e[66]===Symbol.for("react.memo_cache_sentinel")?(xe=s.jsx(K,{name:"edit",className:"size-4 mr-2"}),e[66]=xe):xe=e[66];let ve;e[67]!==d?(ve=d("inlineComment.actions.editComment"),e[67]=d,e[68]=ve):ve=e[68];let me;e[69]!==a||e[70]!==ve?(me=s.jsxs(An,{onClick:a,children:[xe,ve]}),e[69]=a,e[70]=ve,e[71]=me):me=e[71];let ge;e[72]===Symbol.for("react.memo_cache_sentinel")?(ge=s.jsx(K,{name:"delete-bin",className:"size-4 mr-2"}),e[72]=ge):ge=e[72];let Ie;e[73]!==d?(Ie=d("inlineComment.actions.deleteComment"),e[73]=d,e[74]=Ie):Ie=e[74];let oe;e[75]!==i||e[76]!==Ie?(oe=s.jsxs(An,{onClick:i,className:"text-destructive focus:text-destructive",children:[ge,Ie]}),e[75]=i,e[76]=Ie,e[77]=oe):oe=e[77];let ce;e[78]!==me||e[79]!==oe?(ce=s.jsxs(qn,{children:[me,oe]}),e[78]=me,e[79]=oe,e[80]=ce):ce=e[80];let pe;return e[81]!==m||e[82]!==ne||e[83]!==ce?(pe=s.jsxs(Wn,{open:m,onOpenChange:w,children:[ne,ce]}),e[81]=m,e[82]=ne,e[83]=ce,e[84]=pe):pe=e[84],pe}function gr(t){const e=tt.c(62),{initialText:n,onTextChange:a,onSave:i,onCancel:r,fileLabel:o,lineRange:d,isEditing:c,className:p,maxWidth:u}=t,f=n===void 0?"":n,m=c===void 0?!1:c,{t:w}=lt(),g=wr()?.currentTheme,{isMobile:x}=Vs(),[k,y]=l.useState(f),C=we.useRef(null);let z;e[0]!==a?(z=de=>{y(de),a?.(de)},e[0]=a,e[1]=z):z=e[1];const j=z,N=we.useRef(d);let v,P;e[2]!==d?(v=()=>{d&&(N.current=d)},P=[d],e[2]=d,e[3]=v,e[4]=P):(v=e[3],P=e[4]),we.useEffect(v,P);const $=Jh,O=$(d);let M,S;e[5]!==x?(M=()=>{const de=C.current;if(!de)return;const he=de.closest(".overlay-scrollbar-container"),Me=he?.scrollTop??window.scrollY,Le=he?.scrollLeft??window.scrollX;if(x){de.scrollIntoView({behavior:"auto",block:"nearest"});try{de.focus({preventScroll:!0})}catch{de.focus()}return}try{de.focus({preventScroll:!0})}catch{de.focus()}const Be=de.value.length;try{de.setSelectionRange(Be,Be)}catch{}requestAnimationFrame(()=>{he?(he.scrollTop=Me,he.scrollLeft=Le):window.scrollTo({top:Me,left:Le})})},S=[x],e[5]=x,e[6]=M,e[7]=S):(M=e[6],S=e[7]),we.useEffect(M,S);let F;e[8]!==r||e[9]!==i||e[10]!==k?(F=de=>{(de.metaKey||de.ctrlKey)&&de.key==="Enter"?(de.preventDefault(),k.trim()&&i(k,$(N.current))):de.key==="Escape"&&(de.preventDefault(),r())},e[8]=r,e[9]=i,e[10]=k,e[11]=F):F=e[11];const E=F;let D;e[12]!==i||e[13]!==k?(D=de=>{de.stopPropagation(),k.trim()&&i(k,$(N.current))},e[12]=i,e[13]=k,e[14]=D):D=e[14];const W=D;let H;e[15]!==p?(H=fe("rounded-lg border shadow-none w-full max-w-[min(100%,calc(var(--oc-context-panel-width,100vw)-var(--oc-editor-gutter-width,0px)))] overflow-hidden animate-in fade-in zoom-in-95 duration-200",p),e[15]=p,e[16]=H):H=e[16];const Z=g?.colors?.surface?.elevated,Y=g?.colors?.interactive?.border,A=u?`${Math.max(200,Math.floor(u))}px`:void 0;let X;e[17]!==Z||e[18]!==Y||e[19]!==A?(X={backgroundColor:Z,borderColor:Y,maxWidth:A},e[17]=Z,e[18]=Y,e[19]=A,e[20]=X):X=e[20];const te="true",T=qh,I=Gh,B="p-3",L=(o||d)&&s.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground mb-2",children:[o&&s.jsx("span",{className:"truncate max-w-[200px]",children:o}),o&&d&&s.jsx("span",{children:"•"}),O&&s.jsx("span",{children:w("inlineComment.range.lines",{start:O.start,end:O.end})})]});let V;e[21]!==j?(V=de=>j(de.target.value),e[21]=j,e[22]=V):V=e[22];let Q;e[23]!==x||e[24]!==w?(Q=w(x?"inlineComment.input.placeholderShort":"inlineComment.input.placeholder"),e[23]=x,e[24]=w,e[25]=Q):Q=e[25];let G;e[26]!==E||e[27]!==V||e[28]!==Q||e[29]!==k?(G=s.jsx(Ns,{simple:!0,ref:C,value:k,onChange:V,onKeyDown:E,placeholder:Q,outerClassName:"rounded-[var(--radius-xl)] bg-[var(--surface-subtle)] ring-1 ring-inset ring-border/60 focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]",className:"min-h-[80px] px-3 py-2.5 text-sm resize-y"}),e[26]=E,e[27]=V,e[28]=Q,e[29]=k,e[30]=G):G=e[30];let ue;e[31]!==w?(ue=w("inlineComment.actions.cancel"),e[31]=w,e[32]=ue):ue=e[32];let ne;e[33]!==r||e[34]!==ue?(ne=s.jsx(ee,{variant:"ghost",size:"sm",onClick:r,onPointerDown:Wh,onTouchStart:Hh,className:"h-8 text-muted-foreground hover:text-foreground",children:ue}),e[33]=r,e[34]=ue,e[35]=ne):ne=e[35];let xe;e[36]!==k?(xe=k.trim(),e[36]=k,e[37]=xe):xe=e[37];const ve=!xe,me=g?.colors?.status?.success,ge=g?.colors?.status?.successForeground;let Ie;e[38]!==me||e[39]!==ge?(Ie={backgroundColor:me,color:ge},e[38]=me,e[39]=ge,e[40]=Ie):Ie=e[40];let oe;e[41]!==m||e[42]!==w?(oe=w(m?"inlineComment.actions.save":"inlineComment.actions.comment"),e[41]=m,e[42]=w,e[43]=oe):oe=e[43];let ce;e[44]!==W||e[45]!==ve||e[46]!==Ie||e[47]!==oe?(ce=s.jsx(ee,{size:"sm",onClick:W,onPointerDown:Vh,onTouchStart:$h,disabled:ve,className:"h-8 min-w-[80px]",style:Ie,children:oe}),e[44]=W,e[45]=ve,e[46]=Ie,e[47]=oe,e[48]=ce):ce=e[48];let pe;e[49]!==ne||e[50]!==ce?(pe=s.jsxs("div",{className:"flex items-center justify-end gap-2 mt-3",children:[ne,ce]}),e[49]=ne,e[50]=ce,e[51]=pe):pe=e[51];let ie;e[52]!==L||e[53]!==G||e[54]!==pe?(ie=s.jsxs("div",{className:B,children:[L,G,pe]}),e[52]=L,e[53]=G,e[54]=pe,e[55]=ie):ie=e[55];let le;return e[56]!==H||e[57]!==X||e[58]!==T||e[59]!==I||e[60]!==ie?(le=s.jsx("div",{className:H,style:X,"data-comment-input":te,onPointerDown:T,onTouchStart:I,children:ie}),e[56]=H,e[57]=X,e[58]=T,e[59]=I,e[60]=ie,e[61]=le):le=e[61],le}function $h(t){return t.stopPropagation()}function Vh(t){return t.stopPropagation()}function Hh(t){return t.stopPropagation()}function Wh(t){return t.stopPropagation()}function Gh(t){return t.stopPropagation()}function qh(t){return t.stopPropagation()}function Jh(t){if(!t)return;const e=Math.min(t.start,t.end),n=Math.max(t.start,t.end);return{...t,start:e,end:n}}const Yh=t=>{const e=Math.min(t.startLine,t.endLine),n=Math.max(t.startLine,t.endLine);return{...t,startLine:e,endLine:n}},Uo=t=>{const e=Math.min(t.start,t.end),n=Math.max(t.start,t.end);return{...t,start:e,end:n}};function Au(t){const e=tt.c(47),{t:n}=lt(),{source:a,fileLabel:i,language:r,getCodeForRange:o,toStoreRange:d,fromDraftRange:c}=t,p=es(tx),u=es(ex),f=il();let m;e[0]!==p?(m=Q=>p?Q.getDirectoryForSession(p):null,e[0]=p,e[1]=m):m=e[1];const w=es(m),b=ci(Zh),g=ci(Xh),x=ci(Qh),[k,y]=l.useState(null),[C,z]=l.useState(""),[j,N]=l.useState(null),v=p??(u?"draft":null),P=w??f;let $;e:{if(!v||!P){$=null;break e}let Q;e[2]!==P||e[3]!==v?(Q={directory:P,sessionKey:v},e[2]=P,e[3]=v,e[4]=Q):Q=e[4],$=Q}const O=$;let M;e[5]!==O?(M=O?$m(mn(),O.directory,O.sessionKey):null,e[5]=O,e[6]=M):M=e[6];const S=M;let F;e[7]!==S?(F=Q=>S?Q.drafts[S]??kl:kl,e[7]=S,e[8]=F):F=e[8];const E=ci(F);let D;e:{if(!O||!i){let G;e[9]===Symbol.for("react.memo_cache_sentinel")?(G=[],e[9]=G):G=e[9],D=G;break e}let Q;if(e[10]!==i||e[11]!==E||e[12]!==a){let G;e[14]!==i||e[15]!==a?(G=ue=>ue.source===a&&ue.fileLabel===i,e[14]=i,e[15]=a,e[16]=G):G=e[16],Q=E.filter(G),e[10]=i,e[11]=E,e[12]=a,e[13]=Q}else Q=e[13];D=Q}const W=D;let H;e[17]===Symbol.for("react.memo_cache_sentinel")?(H=()=>{y(null),z(""),N(null)},e[17]=H):H=e[17];const Z=H;let Y;e[18]===Symbol.for("react.memo_cache_sentinel")?(Y=()=>{Z()},e[18]=Y):Y=e[18];const A=Y;let X;e[19]!==c?(X=Q=>{const G=Uo(c(Q));y(G),z(Q.text),N(Q.id)},e[19]=c,e[20]=X):X=e[20];const te=X;let T;e[21]!==j||e[22]!==x||e[23]!==O?(T=Q=>{O&&(x(O,Q.id),j===Q.id&&Z())},e[21]=j,e[22]=x,e[23]=O,e[24]=T):T=e[24];const I=T;let B;e[25]!==b||e[26]!==j||e[27]!==i||e[28]!==o||e[29]!==r||e[30]!==k||e[31]!==a||e[32]!==n||e[33]!==O||e[34]!==d||e[35]!==g?(B=(Q,G)=>{const ue=G??k,ne=Q.trim();if(!ue||!ne||!i)return;if(!O){J.error(n("inlineComment.toast.selectSessionToSave"));return}const xe=Uo(ue),ve=Yh(d(xe)),me=o(xe);j?g(O,j,{fileLabel:i,startLine:ve.startLine,endLine:ve.endLine,side:ve.side,code:me,language:r,text:ne}):b(O,{source:a,fileLabel:i,startLine:ve.startLine,endLine:ve.endLine,side:ve.side,code:me,language:r,text:ne}),Z()},e[25]=b,e[26]=j,e[27]=i,e[28]=o,e[29]=r,e[30]=k,e[31]=a,e[32]=n,e[33]=O,e[34]=d,e[35]=g,e[36]=B):B=e[36];const L=B;let V;return e[37]!==C||e[38]!==I||e[39]!==W||e[40]!==j||e[41]!==c||e[42]!==L||e[43]!==k||e[44]!==v||e[45]!==te?(V={sessionKey:v,drafts:W,selection:k,setSelection:y,commentText:C,setCommentText:z,editingDraftId:j,setEditingDraftId:N,reset:Z,cancel:A,startEdit:te,deleteDraft:I,saveComment:L,fromDraftRange:c},e[37]=C,e[38]=I,e[39]=W,e[40]=j,e[41]=c,e[42]=L,e[43]=k,e[44]=v,e[45]=te,e[46]=V):V=e[46],V}function Qh(t){return t.removeDraft}function Xh(t){return t.updateDraft}function Zh(t){return t.addDraft}function ex(t){return t.newSessionDraft?.open}function tx(t){return t.currentSessionId}function sx(t){const{drafts:e,editingDraftId:n,commentText:a,onTextChange:i,selection:r,isDragging:o,fileLabel:d,newWidgetId:c,mapDraftToRange:p,onSave:u,onCancel:f,onEdit:m,onDelete:w}=t,b=[];for(const g of e){const x=p(g);if(g.id===n){b.push({afterLine:x.end,id:`edit-${g.id}`,content:s.jsx(gr,{initialText:a,onTextChange:i,fileLabel:d,lineRange:x,isEditing:!0,onSave:u,onCancel:f},`edit-${g.id}`)});continue}b.push({afterLine:x.end,id:`card-${g.id}`,content:s.jsx(Tu,{draft:g,onEdit:()=>m(g),onDelete:()=>w(g)},`card-${g.id}`)})}if(r&&!n&&!o){const g={...r,start:Math.min(r.start,r.end),end:Math.max(r.start,r.end)};b.push({afterLine:g.end,id:c,content:s.jsx(gr,{initialText:a,onTextChange:i,fileLabel:d,lineRange:g,isEditing:!1,onSave:u,onCancel:f},c)})}return b}const sr=t=>{if(t.type==="new"){const e=Math.min(t.selection.start,t.selection.end),n=Math.max(t.selection.start,t.selection.end);return`new-comment-${t.selection.side??"additions"}-${e}-${n}`}return`draft-${t.draft.id}`},nx=t=>{const{drafts:e,editingDraftId:n,selection:a}=t,i=[];for(const r of e){if(!Number.isFinite(r.endLine))continue;const o=Math.max(1,Math.floor(r.endLine)),d=r.side==="original"?"deletions":"additions";i.push({lineNumber:o,side:d,metadata:{type:r.id===n?"edit":"saved",draft:r}})}return a&&!n&&i.push({lineNumber:Math.max(a.start,a.end),side:a.side??"additions",metadata:{type:"new",selection:a}}),i};function ax(t){const e=t.trim();if(!e)return null;if(/^-?\d+(\.\d+)?$/.test(e)){const n=Number.parseFloat(e);return Number.isFinite(n)?n:null}if(e.endsWith("px")){const n=Number.parseFloat(e.slice(0,-2));return Number.isFinite(n)?n:null}return null}function Ic(t){if(!(!t||t<=0))return Math.max(200,Math.floor(t))}function ix(t){const{diffRootRef:e,drafts:n,selection:a,editingDraftId:i,commentText:r,onTextChange:o,fileLabel:d,onSave:c,onCancel:p,onEdit:u,onDelete:f}=t,[m,w]=l.useState(0),[b,g]=l.useState(null),x=l.useMemo(()=>!a||i?null:sr({type:"new",selection:a}),[i,a]),k=l.useMemo(()=>{const z=n.map(j=>sr({type:j.id===i?"edit":"saved",draft:j}));return x&&z.push(x),z},[n,i,x]),y=l.useCallback(z=>{const j=e.current;if(!j)return null;const N=j.querySelector("diffs-container");if(!(N instanceof HTMLElement))return null;const v=N.querySelector(`[data-annotation-id="${z}"]`);if(v instanceof HTMLElement)return v;const P=N.shadowRoot;return P?P.querySelector(`[data-annotation-id="${z}"]`):null},[e]);l.useEffect(()=>{if(k.length===0)return;let z=!1,j=0;const N=12,v=()=>{z||k.every($=>!!y($))||j>=N||(j+=1,requestAnimationFrame(()=>{z||(w($=>$+1),v())}))};return v(),()=>{z=!0}},[k,y]),l.useEffect(()=>{const z=e.current;if(!z)return;const j=()=>{const v=getComputedStyle(z),P=ax(v.getPropertyValue("--oc-context-panel-width")),$=z.getBoundingClientRect(),O=P??$.width;g(O>0?O:null)};j();const N=new ResizeObserver(()=>{j()});return N.observe(z),window.addEventListener("resize",j),()=>{N.disconnect(),window.removeEventListener("resize",j)}},[e]);const C=l.useCallback(z=>{const N=e.current?.getBoundingClientRect(),v=z.closest("[data-annotation-content]"),P=v instanceof HTMLElement?v.getBoundingClientRect():z.getBoundingClientRect(),$=[P.width];N&&$.push(N.right-P.left);const O=$.filter(M=>Number.isFinite(M)&&M>0);return O.length>0?Ic(Math.min(...O)):Ic(b)},[e,b]);return s.jsxs(s.Fragment,{children:[n.map(z=>{const j=sr({type:z.id===i?"edit":"saved",draft:z}),N=y(j);if(!N)return null;const v=C(N);return z.id===i?Xi.createPortal(s.jsx(gr,{initialText:r,onTextChange:o,fileLabel:d,lineRange:{start:z.startLine,end:z.endLine,side:z.side==="original"?"deletions":"additions"},isEditing:!0,onSave:c,onCancel:p,maxWidth:v}),N,`draft-edit-${z.id}`):Xi.createPortal(s.jsx(Tu,{draft:z,onEdit:()=>u(z),onDelete:()=>f(z),maxWidth:v}),N,`draft-card-${z.id}`)}),a&&!i&&x&&(()=>{const z=y(x);if(!z)return null;const j=C(z);return Xi.createPortal(s.jsx(gr,{initialText:r,onTextChange:o,fileLabel:d,lineRange:a,isEditing:!1,onSave:c,onCancel:p,maxWidth:j}),z,x)})()]})}function $o(t,e){const n=t.metadata.variant==="dark",a=t.config?.fonts?.mono||"monospace",i=t.colors.syntax.highlights||{},r=t.colors.syntax.tokens||{},o=e?.fontSize?`${e.fontSize}px`:"var(--text-code)",d=tn.theme({"&":{backgroundColor:"var(--background)",color:t.colors.syntax.base.foreground,fontSize:o,lineHeight:"1.5",position:"relative"},".cm-scroller":{fontFamily:a,backgroundColor:"var(--background)"},".cm-comment":{color:t.colors.syntax.base.comment},".cm-keyword":{color:t.colors.syntax.base.keyword},".cm-string":{color:t.colors.syntax.base.string},".cm-string-2":{color:r.stringEscape||t.colors.syntax.base.string},".cm-number":{color:t.colors.syntax.base.number},".cm-operator":{color:t.colors.syntax.base.operator},".cm-punctuation":{color:r.punctuation||t.colors.syntax.base.comment},".cm-atom":{color:r.boolean||t.colors.syntax.base.number},".cm-builtin":{color:r.functionCall||t.colors.syntax.base.function},".cm-def":{color:r.variableGlobal||t.colors.syntax.base.variable},".cm-attribute":{color:r.variableOther||r.variableProperty||t.colors.syntax.base.operator},".cm-meta":{color:t.colors.syntax.base.comment},".cm-property":{color:r.variableProperty||t.colors.syntax.base.keyword},".cm-variable":{color:t.colors.syntax.base.variable},".cm-variable-2":{color:r.variableOther||t.colors.syntax.base.function},".cm-variable-3":{color:r.variableGlobal||t.colors.syntax.base.type},".cm-tag":{color:r.tag||t.colors.syntax.base.keyword},".cm-link":{color:r.url||t.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:t.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:t.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:t.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:i.lineNumber||t.colors.syntax.base.comment,borderRight:`1px solid ${t.colors.interactive.border}`,position:"sticky",paddingRight:"8px",left:0,zIndex:2,boxShadow:"0 0 0 var(--background)"},".cm-gutter":{backgroundColor:"var(--background)"},".cm-gutterElement":{backgroundColor:"var(--background)"},".cm-lineNumbers":{backgroundColor:"var(--background)"},".cm-lineNumbers .cm-gutterElement":{paddingLeft:"8px",paddingRight:"8px",minWidth:"42px"},".cm-activeLineGutter":{color:i.lineNumberActive||t.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:t.colors.surface.overlay},".cm-panels":{backgroundColor:"transparent",color:t.colors.surface.foreground,position:"absolute",top:"0",right:"0",left:"auto",width:"auto",zIndex:10,pointerEvents:"none"},".cm-panels-top":{borderBottom:"none",position:"absolute",top:"6px",right:"14px",left:"auto",width:"auto"},".cm-panels-bottom":{position:"static",width:"100%",pointerEvents:"auto"},".cm-panels-bottom .cm-vim-panel":{borderTop:`1px solid ${t.colors.interactive.border}`,backgroundColor:t.colors.surface.elevated,color:t.colors.surface.mutedForeground,fontFamily:"var(--font-mono)",fontSize:"12px",minHeight:"22px",padding:"2px 8px"},".cm-panel.cm-search":{pointerEvents:"auto",padding:"4px",backgroundColor:`color-mix(in srgb, ${t.colors.surface.elevated} 85%, transparent)`,border:`1px solid ${t.colors.interactive.border}`,borderRadius:"10px",boxShadow:`0 2px 8px color-mix(in srgb, ${t.colors.surface.background} 60%, transparent)`,width:"auto",minWidth:"360px",maxWidth:"480px"},".cm-search":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"0",width:"100%",color:t.colors.surface.foreground,fontFamily:"inherit",fontSize:"13px",lineHeight:"1"},".cm-search br":{display:"none"},".cm-search .cm-textfield":{appearance:"none",height:"26px",margin:0,padding:"0 8px",borderRadius:"6px !important",border:`1px solid ${t.colors.interactive.border}`,backgroundColor:t.colors.surface.background,color:t.colors.surface.foreground,fontFamily:"inherit",fontSize:"12px",lineHeight:"1",outline:"none",transition:"border-color 150ms ease"},".cm-search .cm-textfield::placeholder":{color:t.colors.surface.mutedForeground,opacity:1},".cm-search .cm-textfield:focus":{borderColor:t.colors.primary.base},'.cm-search .cm-textfield[name="search"]':{order:1,flex:"1 1 120px",maxWidth:"calc(100% - 142px)",minWidth:"100px"},".cm-search label":{order:2,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:0,marginLeft:"1px",padding:0,borderRadius:"4px",border:"1px solid transparent",backgroundColor:"transparent",color:"transparent",cursor:"pointer",userSelect:"none",fontSize:"1px",lineHeight:"0",overflow:"hidden",position:"relative",transition:"background-color 120ms ease, border-color 120ms ease"},".cm-search label:hover":{backgroundColor:t.colors.interactive.hover},'.cm-search label:has(input[type="checkbox"]:checked)':{backgroundColor:t.colors.interactive.hover,borderColor:t.colors.interactive.border},'.cm-search [type="checkbox"]':{appearance:"none",WebkitAppearance:"none",width:"0",height:"0",margin:"0",padding:"0",border:"none",position:"absolute",opacity:"0",pointerEvents:"none"},".cm-search label::after":{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"13px",fontWeight:"600",lineHeight:"1",fontFamily:"inherit",color:t.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search label:hover::after":{color:t.colors.surface.foreground},'.cm-search label:has(input[type="checkbox"]:checked)::after':{color:t.colors.surface.foreground},'.cm-search label:has(input[name="case"])::after':{content:'"Aa"',fontSize:"12px",letterSpacing:"-0.5px"},'.cm-search label:has(input[name="re"])::after':{content:'".*"',fontSize:"13px",fontFamily:"monospace"},'.cm-search label:has(input[name="word"])::after':{content:'"ab"',fontSize:"12px",textDecoration:"underline",textUnderlineOffset:"2px"},".cm-search .cm-search-message":{order:3,color:t.colors.surface.mutedForeground,backgroundColor:"transparent",border:"none",borderRadius:"0",padding:"0 6px",fontSize:"11px",whiteSpace:"nowrap",lineHeight:"26px"},".cm-search .cm-button":{appearance:"none",WebkitAppearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:0,marginLeft:"1px",padding:0,borderRadius:"4px",border:"none",backgroundColor:"transparent",backgroundImage:"none",color:"transparent",cursor:"pointer",fontSize:"1px",fontWeight:"400",lineHeight:"0",overflow:"hidden",position:"relative",boxShadow:"none",transition:"background-color 120ms ease"},".cm-search .cm-button::after":{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",fontSize:"15px",lineHeight:"1",color:t.colors.surface.mutedForeground,pointerEvents:"none"},".cm-search .cm-button:hover":{backgroundColor:t.colors.interactive.hover},".cm-search .cm-button:hover::after":{color:t.colors.surface.foreground},".cm-search .cm-button:active":{backgroundColor:t.colors.interactive.active},".cm-search .cm-button:focus-visible":{outline:"none",boxShadow:`0 0 0 1px ${t.colors.interactive.focusRing}`},".cm-search .cm-button:disabled":{opacity:.4,cursor:"default",pointerEvents:"none"},'.cm-search .cm-button[name="prev"]':{order:21,marginTop:"2px"},'.cm-search .cm-button[name="prev"]::after':{content:'"↑"'},'.cm-search .cm-button[name="next"]':{order:22,marginTop:"2px"},'.cm-search .cm-button[name="next"]::after':{content:'"↓"'},'.cm-search .cm-button[name="select"]':{order:23,marginTop:"2px"},'.cm-search .cm-button[name="select"]::after':{content:'"≡"',fontSize:"17px"},'.cm-panel.cm-search button[name="close"]':{order:5,appearance:"none",WebkitAppearance:"none",display:"inline-flex",alignItems:"center",justifyContent:"center",width:"26px",height:"26px",minWidth:"26px",flexShrink:"0",margin:"0 0 0 auto",padding:"0",borderRadius:"4px",border:"none",backgroundColor:"transparent",backgroundImage:"none",color:t.colors.surface.mutedForeground,cursor:"pointer",fontSize:"16px",lineHeight:"1",boxShadow:"none",position:"relative",overflow:"visible",transition:"background-color 120ms ease, color 120ms ease"},'.cm-panel.cm-search button[name="close"]:hover':{backgroundColor:t.colors.interactive.hover,color:t.colors.surface.foreground},'.cm-search .cm-button[name="replace"]':{order:24,marginTop:"2px"},'.cm-search .cm-button[name="replace"]::after':{content:'"⇄"'},'.cm-search .cm-button[name="replaceAll"], .cm-search .cm-button[name="replace-all"]':{order:25,marginTop:"2px"},'.cm-search .cm-button[name="replaceAll"]::after, .cm-search .cm-button[name="replace-all"]::after':{content:'"⇉"'},'.cm-search .cm-textfield[name="replace"]':{order:20,flex:"1 1 100%",maxWidth:"calc(100% - 142px)",minWidth:"80px",marginTop:"2px"},".cm-searchMatch":{backgroundColor:t.colors.status.infoBackground,boxShadow:`inset 0 0 0 1px ${t.colors.status.infoBorder}`,borderRadius:"2px"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:t.colors.interactive.selection,color:t.colors.interactive.selectionForeground,boxShadow:`inset 0 0 0 1px ${t.colors.interactive.borderFocus}`},"&.cm-focused":{outline:"none"}},{dark:n}),c=Jl.define([{tag:[$e.comment,$e.docComment,$e.meta,$e.documentMeta],class:"cm-comment"},{tag:[$e.keyword,$e.controlKeyword,$e.moduleKeyword,$e.definitionKeyword,$e.modifier],class:"cm-keyword"},{tag:[$e.operatorKeyword,$e.operator,$e.derefOperator,$e.updateOperator,$e.definitionOperator,$e.typeOperator,$e.controlOperator,$e.logicOperator,$e.bitwiseOperator,$e.arithmeticOperator,$e.compareOperator],class:"cm-operator"},{tag:[$e.punctuation,$e.separator,$e.bracket,$e.paren,$e.brace,$e.squareBracket,$e.angleBracket],class:"cm-punctuation"},{tag:[$e.string,$e.regexp,$e.attributeValue,$e.special($e.string),$e.monospace],class:"cm-string"},{tag:$e.escape,class:"cm-string-2"},{tag:[$e.number,$e.bool,$e.atom,$e.null,$e.self],class:"cm-number"},{tag:[$e.function($e.variableName),$e.function($e.definition($e.variableName)),$e.function($e.propertyName),$e.standard($e.variableName),$e.special($e.variableName)],class:"cm-builtin"},{tag:$e.definition($e.variableName),class:"cm-def"},{tag:[$e.variableName,$e.local($e.variableName),$e.constant($e.variableName),$e.literal],class:"cm-variable"},{tag:$e.propertyName,class:"cm-property"},{tag:$e.attributeName,class:"cm-attribute"},{tag:[$e.className,$e.typeName,$e.namespace],class:"cm-variable-3"},{tag:[$e.tagName,$e.labelName,$e.annotation,$e.macroName],class:"cm-tag"},{tag:$e.link,class:"cm-link"},{tag:[$e.heading,$e.heading1,$e.heading2,$e.heading3,$e.heading4,$e.heading5,$e.heading6],class:"cm-keyword"}]),p=Jl.define([{tag:[$e.comment,$e.docComment,$e.meta,$e.documentMeta],color:t.colors.syntax.base.comment},{tag:[$e.keyword,$e.controlKeyword,$e.moduleKeyword,$e.definitionKeyword,$e.modifier],color:t.colors.syntax.base.keyword},{tag:[$e.operatorKeyword,$e.operator,$e.derefOperator,$e.updateOperator,$e.definitionOperator,$e.typeOperator,$e.controlOperator,$e.logicOperator,$e.bitwiseOperator,$e.arithmeticOperator,$e.compareOperator],color:t.colors.syntax.base.operator},{tag:[$e.string,$e.regexp,$e.attributeValue,$e.special($e.string),$e.monospace],color:t.colors.syntax.base.string},{tag:$e.escape,color:r.stringEscape||t.colors.syntax.base.string},{tag:[$e.number,$e.bool,$e.atom,$e.null,$e.self],color:t.colors.syntax.base.number},{tag:[$e.function($e.variableName),$e.function($e.definition($e.variableName)),$e.function($e.propertyName),$e.standard($e.variableName),$e.special($e.variableName)],color:t.colors.syntax.base.function},{tag:$e.definition($e.variableName),color:r.variableGlobal||t.colors.syntax.base.variable},{tag:[$e.variableName,$e.local($e.variableName),$e.constant($e.variableName),$e.literal],color:t.colors.syntax.base.variable},{tag:$e.propertyName,color:r.variableProperty||t.colors.syntax.base.variable},{tag:$e.attributeName,color:r.variableOther||t.colors.syntax.base.variable},{tag:[$e.className,$e.typeName,$e.namespace],color:t.colors.syntax.base.type},{tag:[$e.tagName,$e.labelName,$e.annotation,$e.macroName],color:r.tag||t.colors.syntax.base.keyword},{tag:$e.link,color:r.url||t.colors.syntax.base.function,textDecoration:"underline"},{tag:[$e.punctuation,$e.separator,$e.bracket,$e.paren,$e.brace,$e.squareBracket,$e.angleBracket],color:r.punctuation||t.colors.syntax.base.comment}]);return e?.syntaxColors===!1?[d]:[d,Di(wf,{fallback:!0}),Di(Cf),Di(c),Di(p)]}const rx=180,Eu=gf.define(),ox=1,lx=2,cx=4,Pc=new Map,dx=(t,e)=>{const n=`${t}|${e}`,a=Pc.get(n);if(a)return a;let i="";t&&(i+=`color:${t};`),e&ox&&(i+="font-style:italic;"),e&lx&&(i+="font-weight:bold;"),e&cx&&(i+="text-decoration:underline;");const r=Pr.mark({attributes:{style:i}});return Pc.set(n,r),r},ux=(t,e)=>{const n=new ul,a=t.state.doc,i=Math.min(e.length,a.lines);for(let r=0;r<i;r+=1){const o=e[r];if(!o||o.length===0)continue;const d=a.line(r+1);let c=d.from;for(const[p,u,f]of o){if(p<=0)continue;const m=c,w=Math.min(c+p,d.to);c+=p,!(w<=m)&&(!u&&!f||n.add(m,w,dx(u,f)))}}return n.finish()},mx=gu.define({create(){return Pr.none},update(t,e){let n=t.map(e.changes);for(const a of e.effects)a.is(Eu)&&(n=a.value);return n},provide:t=>tn.decorations.from(t)}),px=t=>pu.fromClass(class{timer;generation=0;constructor(e){this.tokenize(e)}update(e){e.docChanged&&this.schedule(e.view)}schedule(e){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.tokenize(e)},rx)}async tokenize(e){const n=++this.generation,a=e.state.doc.toString(),i=await Vm(a,t.language,t.themeName,t.theme);i&&n===this.generation&&e.state.doc.length===a.length&&e.dispatch({effects:Eu.of(ux(e,i))})}destroy(){this.timer&&clearTimeout(this.timer)}}),Du=t=>[mx,px(t)],Tc=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function Ru(t){const e=tt.c(131),{t:n}=lt(),{open:a,onOpenChange:i,target:r,projectDirectory:o,submitting:d,allowRunAsGoal:c,onConfirm:p}=t,u=d===void 0?!1:d,f=c===void 0?!1:c;let m;e[0]!==f?(m=f&&!ds(),e[0]=f,e[1]=m):m=e[1];const w=m,b=pt(Nx),g=pt(kx),x=$a(jx),k=pt(wx),y=pt(vx),C=pt(yx),z=pt(bx),j=pt(xx);let N;e[2]!==j||e[3]!==C||e[4]!==y||e[5]!==z?(N=()=>Tc({providerID:y,modelID:C,variant:z,agent:j}),e[2]=j,e[3]=C,e[4]=y,e[5]=z,e[6]=N):N=e[6];const[v,P]=l.useState(N);let $,O;e[7]!==x||e[8]!==g||e[9]!==b||e[10]!==a||e[11]!==o?($=()=>{a&&(b({directory:o,source:"todoSendDialog"}),g({directory:o}),x())},O=[a,b,g,x,o],e[7]=x,e[8]=g,e[9]=b,e[10]=a,e[11]=o,e[12]=$,e[13]=O):($=e[12],O=e[13]),l.useEffect($,O);let M,S;e[14]!==j||e[15]!==C||e[16]!==y||e[17]!==z||e[18]!==a?(M=()=>{a&&P(Tc({providerID:y,modelID:C,variant:z,agent:j}))},S=[a,y,C,z,j],e[14]=j,e[15]=C,e[16]=y,e[17]=z,e[18]=a,e[19]=M,e[20]=S):(M=e[19],S=e[20]),l.useEffect(M,S);let F,E;e[21]!==v.modelID||e[22]!==v.providerID||e[23]!==a||e[24]!==k?(F=()=>{if(!a||k.length===0)return;const U=k.find(be=>be.id===v.providerID)??k[0],h=Array.isArray(U?.models)?U.models:[],ae=h.some(be=>be.id===v.modelID),ye=h[0]?.id??"";U?.id===v.providerID&&ae||P(be=>({...be,providerID:U?.id??"",modelID:ae?be.modelID:ye,variant:""}))},E=[a,k,v.providerID,v.modelID],e[21]=v.modelID,e[22]=v.providerID,e[23]=a,e[24]=k,e[25]=F,e[26]=E):(F=e[25],E=e[26]),l.useEffect(F,E);const D=hx;let W;if(e[27]!==v.modelID||e[28]!==v.providerID||e[29]!==k){let U;e[31]!==v.providerID?(U=ae=>ae.id===v.providerID,e[31]=v.providerID,e[32]=U):U=e[32],W=k.find(U)?.models?.find(ae=>ae.id===v.modelID),e[27]=v.modelID,e[28]=v.providerID,e[29]=k,e[30]=W}else W=e[30];const H=W;let Z;e[33]!==H?(Z=H?.variants?Object.keys(H.variants):[],e[33]=H,e[34]=Z):Z=e[34];const Y=Z,A=Y.length>0;let X,te;e[35]!==v.variant||e[36]!==A?(X=()=>{A||!v.variant||P(fx)},te=[A,v.variant],e[35]=v.variant,e[36]=A,e[37]=X,e[38]=te):(X=e[37],te=e[38]),l.useEffect(X,te);let T;e[39]!==v.modelID||e[40]!==v.providerID?(T=v.providerID.trim().length>0&&v.modelID.trim().length>0,e[39]=v.modelID,e[40]=v.providerID,e[41]=T):T=e[41];const I=T;let B;e[42]!==I||e[43]!==v||e[44]!==p||e[45]!==u?(B=()=>{!I||u||p(v)},e[42]=I,e[43]=v,e[44]=p,e[45]=u,e[46]=B):B=e[46];const L=B;let V,Q;e[47]!==L||e[48]!==a?(V=()=>{if(!a)return;const U=h=>{(h.metaKey||h.ctrlKey)&&h.key==="Enter"&&(h.preventDefault(),L())};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},Q=[a,L],e[47]=L,e[48]=a,e[49]=V,e[50]=Q):(V=e[49],Q=e[50]),l.useEffect(V,Q);let G;e[51]!==n||e[52]!==r?(G=n(r==="worktree"?"rightSidebar.contextNotesTodo.sendDialog.title.newWorktree":"rightSidebar.contextNotesTodo.sendDialog.title.newSession"),e[51]=n,e[52]=r,e[53]=G):G=e[53];const ue=G;let ne;e[54]!==i||e[55]!==u?(ne=U=>{u||i(U)},e[54]=i,e[55]=u,e[56]=ne):ne=e[56];let xe;e[57]!==ue?(xe=s.jsx(Ut,{children:s.jsx(_t,{children:ue})}),e[57]=ue,e[58]=xe):xe=e[58];let ve;e[59]!==n?(ve=n("chat.modelControls.model"),e[59]=n,e[60]=ve):ve=e[60];let me;e[61]!==ve?(me=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ve}),e[61]=ve,e[62]=me):me=e[62];let ge;e[63]===Symbol.for("react.memo_cache_sentinel")?(ge=(U,h)=>{P(ae=>({...ae,providerID:U,modelID:h,variant:""}))},e[63]=ge):ge=e[63];let Ie;e[64]!==v.modelID||e[65]!==v.providerID?(Ie=s.jsx(oa,{providerId:v.providerID,modelId:v.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:ge}),e[64]=v.modelID,e[65]=v.providerID,e[66]=Ie):Ie=e[66];let oe;e[67]!==me||e[68]!==Ie?(oe=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[me,Ie]}),e[67]=me,e[68]=Ie,e[69]=oe):oe=e[69];let ce;e[70]!==n?(ce=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[70]=n,e[71]=ce):ce=e[71];let pe;e[72]!==ce?(pe=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ce}),e[72]=ce,e[73]=pe):pe=e[73];const ie=!A;let le;e[74]===Symbol.for("react.memo_cache_sentinel")?(le=U=>P(h=>({...h,variant:U})),e[74]=le):le=e[74];let de;e[75]!==v.variant||e[76]!==ie||e[77]!==Y?(de=s.jsx(Hm,{value:v.variant,options:Y,disabled:ie,onChange:le}),e[75]=v.variant,e[76]=ie,e[77]=Y,e[78]=de):de=e[78];let he;e[79]!==pe||e[80]!==de?(he=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[pe,de]}),e[79]=pe,e[80]=de,e[81]=he):he=e[81];let Me;e[82]!==n?(Me=n("sessions.scheduledTasks.editor.agent.label"),e[82]=n,e[83]=Me):Me=e[83];let Le;e[84]!==Me?(Le=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:Me}),e[84]=Me,e[85]=Le):Le=e[85];let Be;e[86]===Symbol.for("react.memo_cache_sentinel")?(Be=U=>P(h=>({...h,agent:U})),e[86]=Be):Be=e[86];let Fe;e[87]!==v.agent?(Fe=s.jsx(rl,{agentName:v.agent,filter:D,dropdownPortalToBody:!0,onChange:Be}),e[87]=v.agent,e[88]=Fe):Fe=e[88];let De;e[89]!==Le||e[90]!==Fe?(De=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Le,Fe]}),e[89]=Le,e[90]=Fe,e[91]=De):De=e[91];let ze;e[92]!==oe||e[93]!==he||e[94]!==De?(ze=s.jsxs("div",{className:"flex flex-col gap-4",children:[oe,he,De]}),e[92]=oe,e[93]=he,e[94]=De,e[95]=ze):ze=e[95];const Ve=`flex items-center gap-3 ${w?"justify-between":"justify-end"}`;let We;e[96]!==v.runAsGoal||e[97]!==w||e[98]!==u||e[99]!==n?(We=w?s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(an,{checked:v.runAsGoal===!0,onChange:U=>P(h=>({...h,runAsGoal:U})),disabled:u,ariaLabel:n("sessions.scheduledTasks.editor.goal.aria")}),s.jsx("button",{type:"button",className:"truncate typography-ui-label text-muted-foreground transition-colors hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:u,onClick:()=>P(gx),children:n("sessions.scheduledTasks.editor.goal.label")})]}):null,e[96]=v.runAsGoal,e[97]=w,e[98]=u,e[99]=n,e[100]=We):We=e[100];let _e;e[101]!==i?(_e=()=>i(!1),e[101]=i,e[102]=_e):_e=e[102];let He;e[103]!==n?(He=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[103]=n,e[104]=He):He=e[104];let Ke;e[105]!==u||e[106]!==_e||e[107]!==He?(Ke=s.jsx(ee,{variant:"ghost",size:"sm",onClick:_e,disabled:u,children:He}),e[105]=u,e[106]=_e,e[107]=He,e[108]=Ke):Ke=e[108];const Oe=!I||u;let je;e[109]!==u||e[110]!==n?(je=n(u?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[109]=u,e[110]=n,e[111]=je):je=e[111];let Te;e[112]!==L||e[113]!==Oe||e[114]!==je?(Te=s.jsx(ee,{size:"sm",onClick:L,disabled:Oe,children:je}),e[112]=L,e[113]=Oe,e[114]=je,e[115]=Te):Te=e[115];let Ue;e[116]!==Ke||e[117]!==Te?(Ue=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Ke,Te]}),e[116]=Ke,e[117]=Te,e[118]=Ue):Ue=e[118];let Ye;e[119]!==Ve||e[120]!==We||e[121]!==Ue?(Ye=s.jsxs("div",{className:Ve,children:[We,Ue]}),e[119]=Ve,e[120]=We,e[121]=Ue,e[122]=Ye):Ye=e[122];let q;e[123]!==xe||e[124]!==ze||e[125]!==Ye?(q=s.jsxs(Bt,{className:"max-w-md overflow-visible",children:[xe,ze,Ye]}),e[123]=xe,e[124]=ze,e[125]=Ye,e[126]=q):q=e[126];let re;return e[127]!==a||e[128]!==ne||e[129]!==q?(re=s.jsx(Kt,{open:a,onOpenChange:ne,children:q}),e[127]=a,e[128]=ne,e[129]=q,e[130]=re):re=e[130],re}function gx(t){return{...t,runAsGoal:t.runAsGoal!==!0}}function fx(t){return{...t,variant:""}}function hx(t){return Wm(t.mode)}function xx(t){return t.currentAgentName||""}function bx(t){return t.currentVariant||""}function yx(t){return t.currentModelId}function vx(t){return t.currentProviderId}function wx(t){return t.providers}function jx(t){return t.loadAgents}function kx(t){return t.loadAgents}function Nx(t){return t.loadProviders}const sn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Yr=(t,e)=>{const n=sn(t),a=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${a}`:`${n}/${a}`},Sx=(t,e,n)=>Yr(Yr(Yr(t,".opencode"),"plans"),`${e}-${n}.md`),Cx=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,Ix=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},Px=(t,e)=>{const n=sn(e.currentDirectory),a=sn(e.homeDirectory),i=sn(t);return n&&i.startsWith(n+"/")?i.slice(n.length+1):a&&i===a?"~":a&&i.startsWith(a+"/")?`~${i.slice(a.length)}`:i},Tx=(t,e,n)=>{const a=sn(t.trim());if(!a)return null;const i=n?e.find(o=>o.id===n)??null:null;if(i?.path){const o=sn(i.path);if(a===o||a.startsWith(`${o}/`))return{id:i.id,path:i.path}}const r=e.filter(o=>{const d=sn(o.path);return a===d||a.startsWith(`${d}/`)}).sort((o,d)=>sn(d.path).length-sn(o.path).length)[0];return r?{id:r.id,path:r.path}:null},JN=({targetPath:t=null,onNavigatedToChat:e})=>{const{t:n}=lt(),a=es(h=>h.currentSessionId),i=es(h=>h.createSession),r=es(h=>h.initializeNewOpenChamberSession),o=es(h=>h.sendMessage),d=es(h=>h.setCurrentSession),c=Yd(),p=Cs(h=>h.homeDirectory),u=Gm(h=>h.planModeEnabled),f=is(h=>h.projects),m=is(h=>h.activeProjectId),w=Nr(h=>h.directories),b=il()??"",g=ke(h=>h.setActiveMainTab),x=ke(h=>h.setSessionSwitcherOpen),k=Va(),{isMobile:y}=Vs(),{currentTheme:C}=Ha(),z=l.useMemo(()=>a?c.find(h=>h.id===a)??null:null,[a,c]),j=l.useMemo(()=>{const h=typeof z?.directory=="string"?z.directory:"";return sn(h||"")},[z?.directory]),N=l.useMemo(()=>sn(b||j),[b,j]),v=l.useMemo(()=>Tx(N,f,m),[m,N,f]),P=l.useMemo(()=>v?w.get(v.path)?.isGitRepo===!0:!1,[v,w]),[$,O]=l.useState(null),[M,S]=l.useState(!1),[F,E]=l.useState(null),D=l.useMemo(()=>!F||!j||!p?F:Px(F,{currentDirectory:j,homeDirectory:p}),[F,j,p]),[W,H]=l.useState(""),{isPlaying:Z,play:Y,stop:A}=qm(),X=pt(h=>h.showMessageTTSButtons),[te,T]=l.useState(null),I=l.useMemo(()=>D&&D.split("/").pop()||n("planView.file.defaultName"),[D,n]),B=l.useMemo(()=>W.trim()&&Jm(W).title||n("planView.title.default"),[W,n]),L=l.useMemo(()=>B.trim()||n("planView.title.default"),[B,n]),[V,Q]=l.useState(!1),[G,ue]=l.useState(!1),[ne,xe]=l.useState("edit"),ve=l.useRef(null),[me,ge]=l.useState(null),Ie=l.useRef(null),oe=l.useRef(null),ce="openchamber:plan:md-viewer-mode";l.useEffect(()=>{try{const h=localStorage.getItem(ce);if(!h)return;const ae=JSON.parse(h);(ae==="preview"||ae==="edit")&&xe(ae)}catch{}},[]);const pe=l.useCallback(h=>{xe(h);try{localStorage.setItem(ce,JSON.stringify(h))}catch{}},[]),ie=l.useRef(!1),le=l.useRef(null),[de,he]=l.useState(!1);l.useEffect(()=>{const h=()=>{ie.current=!1,le.current=null,he(!1)};return document.addEventListener("mouseup",h),()=>document.removeEventListener("mouseup",h)},[]);const Me=l.useCallback((h,ae)=>{const ye=h.split(`
4
- `),be=Math.max(1,ae.start),Ee=Math.min(ye.length,ae.end);return be>Ee?"":ye.slice(be-1,Ee).join(`
5
- `)},[]),Le=Au({source:"plan",fileLabel:I,language:F&&Eo(F)||"markdown",getCodeForRange:h=>Me(W,Uo(h)),toStoreRange:h=>({startLine:h.start,endLine:h.end}),fromDraftRange:h=>({start:h.startLine,end:h.endLine})}),{drafts:Be,commentText:Fe,setCommentText:De,editingDraftId:ze,setSelection:Ve,saveComment:We,cancel:_e,reset:He,startEdit:Ke,deleteDraft:Oe}=Le;l.useEffect(()=>{ge(null),He()},[W,He]),l.useEffect(()=>{Ve(me)},[me,Ve]);const je=l.useCallback(()=>{ge(null),_e()},[_e]),Te=l.useCallback((h,ae)=>{ae&&ge(ae),We(h,ae??me??void 0),ge(null)},[me,We]);l.useEffect(()=>{if(!me)return;const h=ye=>{const be=ye.target;be.closest('[data-comment-card="true"]')||be.closest('[data-comment-input="true"]')||be.closest(".oc-block-widget")||be.closest(".cm-gutterElement")||be.closest("[data-sonner-toast]")||be.closest("[data-sonner-toaster]")||Fe.trim()||(ge(null),_e())},ae=window.setTimeout(()=>{document.addEventListener("click",h)},100);return()=>{window.clearTimeout(ae),document.removeEventListener("click",h)}},[_e,Fe,ze,y,me]);const Ue=ke(h=>h.editorFontSize),Ye=l.useMemo(()=>{const h=F?Eo(F):null,ae=!!h&&h!=="markdown",ye=[$o(C,ae?{syntaxColors:!1,fontSize:Ue}:{fontSize:Ue})],be=Do(F||"plan.md");return be&&ye.push(be),ae&&h&&ye.push(Du({language:h,themeName:C.metadata.id,theme:ur(C)})),ye.push(tn.lineWrapping),ye},[C,F,Ue]);l.useEffect(()=>{if(!u&&!t){E(null),H(""),Q(!1);return}let h=!1;const ae=async be=>{if(k.files?.readFile)return(await k.files.readFile(be))?.content??"";const Ee=nn()?.files;if(Ee?.readFile)return(await Ee.readFile(be,{optional:!0}))?.content??"";const et=await ht(`/api/fs/read?path=${encodeURIComponent(be)}&optional=true`,{cache:"no-store"});if(!et.ok)throw new Error(`Failed to read plan file (${et.status})`);return et.text()};return(async()=>{if(E(null),H(""),T(null),t){Q(!0);try{const be=await ae(t);if(h)return;E(t),H(be)}catch{if(h)return;E(null),H("")}finally{h||Q(!1)}return}if(!z?.slug||!z?.time?.created||!j){E(null),H("");return}Q(!0);try{const be=Sx(j,z.time.created,z.slug),Ee=Ix(Cx(z.time.created,z.slug),p||null);let et=null,Ze=null;try{Ze=await ae(be),et=be}catch{}if(!et)try{Ze=await ae(Ee),et=Ee}catch{}if(h)return;if(!et||Ze===null){E(null),H("");return}E(et),H(Ze)}catch{if(h)return;E(null),H("")}finally{h||Q(!1)}})(),()=>{h=!0}},[p,u,k.files,j,z?.slug,z?.time?.created,t]),l.useEffect(()=>{if(!F){T(null);return}const h=window.setTimeout(async()=>{T(null);try{if(k.files?.writeFile){if(!(await k.files.writeFile(F,W))?.success)throw new Error(n("planView.error.writeFailed"))}else{const ae=await ht("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:F,content:W})});if(!ae.ok)throw new Error(n("planView.error.writePlanFileFailed",{status:ae.status}))}}catch(ae){T(ae instanceof Error?ae.message:n("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(h)}},[W,F,k.files,n]),l.useEffect(()=>()=>{ve.current!==null&&window.clearTimeout(ve.current)},[]);const q=l.useCallback(()=>{g("chat"),x(!1),e?.()},[e,g,x]),re=l.useCallback(async h=>{if(!v||!$)return;const ae=await Un($.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:L}),be=[{synthetic:!0,text:await Un($.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:L,plan_path:F??""})}];S(!0);try{q();let Ee=null,et=v.path;if($.target==="worktree"){if(!P)return;const ot=await Qd(v.path,Xd());if(!ot?.id)return;Ee=ot.id,et=ot.path}else{const ot=await i(void 0,v.path,null);if(!ot?.id)return;Ee=ot.id,et=ot.directory??v.path,r(ot.id,pt.getState().agents??[])}if(!Ee)return;const Ze=ol.getState();Ze.saveSessionModelSelection(Ee,h.providerID,h.modelID),h.agent.trim()&&(Ze.saveSessionAgentSelection(Ee,h.agent),Ze.saveAgentModelForSession(Ee,h.agent,h.providerID,h.modelID),Ze.saveAgentModelVariantForSession(Ee,h.agent,h.providerID,h.modelID,h.variant||void 0)),d(Ee,et);const it=h.runAsGoal===!0?[`Implement the plan "${L}" end-to-end${F?` (plan file: ${F})`:""}.`,"Re-read that file for full details — it is the source of truth.","",W].join(`
6
- `):null;Ym.getState().setArmed(h.runAsGoal===!0,it),await o(ae,h.providerID,h.modelID,h.agent.trim()||void 0,void 0,void 0,be,h.variant||void 0),O(null)}finally{S(!1)}},[P,W,i,v,r,$,F,q,o,L,d]),U=l.useMemo(()=>sx({drafts:Be,editingDraftId:ze,commentText:Fe,onTextChange:De,selection:me,isDragging:de,fileLabel:I,newWidgetId:"plan-new-comment-input",mapDraftToRange:h=>({start:h.startLine,end:h.endLine}),onSave:Te,onCancel:je,onEdit:h=>{Ke(h),ge({start:h.startLine,end:h.endLine})},onDelete:Oe}),[Fe,Oe,ze,je,Te,de,me,Be,I,De,Ke]);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:B}),te?s.jsx("div",{className:"typography-micro text-[color:var(--status-error)] truncate",title:te,children:n("planView.error.saveFailed")}):null]}),F?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(fs,{children:[s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(gs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":n("planView.actions.improvePlanAria"),disabled:!W.trim(),children:s.jsx(K,{name:"loop-right-ai",className:"size-4"})})})}),s.jsx(ks,{sideOffset:8,children:n("planView.actions.improve")})]}),s.jsxs(hs,{align:"end",children:[s.jsx(as,{onClick:()=>O({action:"improve",target:"session"}),children:n("planView.actions.sendToNewSession")}),s.jsx(as,{onClick:()=>O({action:"improve",target:"worktree"}),disabled:!P,children:n("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsxs(fs,{children:[s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(gs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":n("planView.actions.implementPlanAria"),disabled:!W.trim(),children:s.jsx(K,{name:"code-ai",className:"size-4"})})})}),s.jsx(ks,{sideOffset:8,children:n("planView.actions.implement")})]}),s.jsxs(hs,{align:"end",children:[s.jsx(as,{onClick:()=>O({action:"implement",target:"session"}),children:n("planView.actions.sendToNewSession")}),s.jsx(as,{onClick:()=>O({action:"implement",target:"worktree"}),disabled:!P,children:n("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(Pu,{currentMode:ne,onToggle:()=>pe(ne==="preview"?"edit":"preview")}),ne==="preview"&&X&&s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0","aria-label":n(Z?"planView.tts.stopSpeaking":"planView.tts.readAloud"),onClick:()=>{Z?A():W.trim()&&Y(W)},children:Z?s.jsx(K,{name:"stop",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(K,{name:"volume-up",className:"h-4 w-4"})})}),s.jsx(ks,{sideOffset:8,children:n(Z?"planView.tts.stopSpeaking":"planView.tts.readAloud")})]}),s.jsx(ee,{variant:"ghost",size:"sm",onClick:async()=>{(await Vn(W)).ok&&(ue(!0),ve.current!==null&&window.clearTimeout(ve.current),ve.current=window.setTimeout(()=>{ue(!1)},1200))},className:"h-5 w-5 p-0",title:n("planView.actions.copyPlanContents"),"aria-label":n("planView.actions.copyPlanContents"),children:G?s.jsx(K,{name:"check",className:"h-4 w-4 text-[color:var(--status-success)]"}):s.jsx(K,{name:"clipboard",className:"h-4 w-4"})})]}):null]}),s.jsx(Ru,{open:$!==null,onOpenChange:h=>{!h&&!M&&O(null)},target:$?.target??"session",projectDirectory:v?.path??null,submitting:M,allowRunAsGoal:!0,onConfirm:re}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(Os,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:V?s.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:n("planView.state.loading")}):s.jsx("div",{className:"relative h-full",children:s.jsx("div",{className:"h-full",children:ne==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(vn,{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:n("planView.error.previewUnavailable")}),s.jsx("div",{className:"text-sm text-muted-foreground",children:n("planView.error.switchToEditMode")})]}),children:s.jsx(dr,{content:W,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:oe,children:s.jsx(_o,{value:W,onChange:H,readOnly:!1,className:"h-full",extensions:Ye,onViewReady:h=>{Ie.current=h},onViewDestroy:()=>{Ie.current=null},blockWidgets:U,highlightLines:me?{start:Math.min(me.start,me.end),end:Math.max(me.start,me.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(h,ae,ye)=>{if(!(ye instanceof MouseEvent)||ye.button!==0)return!1;ye.preventDefault();const be=h.state.doc.lineAt(ae.from).number;if(me&&!ye.shiftKey&&Math.min(me.start,me.end)===be&&Math.max(me.start,me.end)===be)return ge(null),_e(),ie.current=!1,le.current=null,he(!1),!0;if(y&&me&&!ye.shiftKey){const Ee=Math.min(me.start,me.end,be),et=Math.max(me.start,me.end,be);return ge({start:Ee,end:et}),ie.current=!1,le.current=null,he(!1),!0}if(ie.current=!0,le.current=be,he(!0),me&&ye.shiftKey){const Ee=Math.min(me.start,be),et=Math.max(me.end,be);ge({start:Ee,end:et})}else ge({start:be,end:be});return!0},mouseover:(h,ae,ye)=>{if(!(ye instanceof MouseEvent)||ye.buttons!==1||!ie.current||le.current===null)return!1;const be=h.state.doc.lineAt(ae.from).number,Ee=Math.min(le.current,be),et=Math.max(le.current,be);return ge({start:Ee,end:et}),he(!0),!1},mouseup:()=>(ie.current=!1,le.current=null,he(!1),!1)}}})})})})})})]})},Li=()=>{try{const e=is.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=Ps.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[McpConfigStore] Error resolving config directory:",t)}return null},Ac=t=>t?Object.entries(t).map(([e,n])=>({key:e,value:n})):[],Ec=t=>{const e=t.filter(n=>n.key.trim());if(e.length!==0)return Object.fromEntries(e.map(n=>[n.key.trim(),n.value]))},Fi=t=>typeof t!="string"?void 0:t.trim()||void 0,Qr=800,Ax=5e3,Ex="__default__",Vo=new Map,Xr=new Map,Mu=t=>t?.trim()||Ex,Zr=t=>{Vo.delete(Mu(t))},_a=gn()(qa(bi((t,e)=>({mcpServers:[],selectedMcpName:null,isLoading:!1,mcpDraft:null,setSelectedMcp:n=>t({selectedMcpName:n}),setMcpDraft:n=>t({mcpDraft:n}),loadMcpConfigs:async n=>{const a=Li(),i=Mu(a),r=Date.now(),o=Vo.get(i)??0,d=e().mcpServers.length>0;if(!n?.force&&d&&r-o<Ax)return!0;const c=Xr.get(i);if(!n?.force&&c)return c;const p=(async()=>{t({isLoading:!0});try{const u=a?`?directory=${encodeURIComponent(a)}`:"",f=await ht(`/api/config/mcp${u}`,{headers:a?{"x-opencode-directory":a}:void 0});if(!f.ok)throw new Error("Failed to load MCP configs");const m=await f.json();return t({mcpServers:m,isLoading:!1}),Vo.set(i,Date.now()),!0}catch(u){return console.error("[McpConfigStore] Failed to load MCP configs:",u),t({isLoading:!1}),!1}})();Xr.set(i,p);try{return await p}finally{Xr.delete(i)}},createMcp:async n=>{Zi("Creating MCP server configuration…");let a=!1;try{const i=Dc(n),r=Li(),o=r?`?directory=${encodeURIComponent(r)}`:"",d=await ht(`/api/config/mcp/${encodeURIComponent(n.name)}${o}`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-opencode-directory":r}:{}},body:JSON.stringify(i)}),c=await d.json().catch(()=>null);if(!d.ok)throw new Error(c?.error||"Failed to create MCP server");return Zr(r),c?.requiresReload?(a=!0,await er({message:c.message,delayMs:c.reloadDelayMs??Qr,scopes:["all"]}),await e().loadMcpConfigs({force:!0}),{ok:!0,reloadFailed:c?.reloadFailed===!0,message:c?.message,warning:c?.warning}):(await e().loadMcpConfigs({force:!0}),{ok:!0,reloadFailed:c?.reloadFailed===!0,message:c?.message,warning:c?.warning})}catch(i){return console.error("[McpConfigStore] Failed to create MCP:",i),{ok:!1}}finally{a||tr()}},updateMcp:async(n,a)=>{Zi("Updating MCP server configuration…");let i=!1;try{const r=Dc(a),o=Li(),d=o?`?directory=${encodeURIComponent(o)}`:"",c=await ht(`/api/config/mcp/${encodeURIComponent(n)}${d}`,{method:"PATCH",headers:{"Content-Type":"application/json",...o?{"x-opencode-directory":o}:{}},body:JSON.stringify(r)}),p=await c.json().catch(()=>null);if(!c.ok)throw new Error(p?.error||"Failed to update MCP server");return Zr(o),p?.requiresReload?(i=!0,await er({message:p.message,delayMs:p.reloadDelayMs??Qr,scopes:["all"]}),await e().loadMcpConfigs({force:!0}),{ok:!0,reloadFailed:p?.reloadFailed===!0,message:p?.message,warning:p?.warning}):(await e().loadMcpConfigs({force:!0}),{ok:!0,reloadFailed:p?.reloadFailed===!0,message:p?.message,warning:p?.warning})}catch(r){throw console.error("[McpConfigStore] Failed to update MCP:",r),r}finally{i||tr()}},deleteMcp:async n=>{Zi("Deleting MCP server configuration…");let a=!1;try{const i=Li(),r=i?`?directory=${encodeURIComponent(i)}`:"",o=await ht(`/api/config/mcp/${encodeURIComponent(n)}${r}`,{method:"DELETE",headers:i?{"x-opencode-directory":i}:void 0}),d=await o.json().catch(()=>null);if(!o.ok)throw new Error(d?.error||"Failed to delete MCP server");return Zr(i),d?.requiresReload&&(a=!0,await er({message:d.message,delayMs:d.reloadDelayMs??Qr,scopes:["all"]})),e().selectedMcpName===n&&t({selectedMcpName:null}),await e().loadMcpConfigs({force:!0}),{ok:!0,reloadFailed:d?.reloadFailed===!0,message:d?.message,warning:d?.warning}}catch(i){return console.error("[McpConfigStore] Failed to delete MCP:",i),{ok:!1}}finally{a||tr()}},getMcpByName:n=>e().mcpServers.find(a=>a.name===n)}),{name:"mcp-config-store",storage:Ir(),partialize:t=>({selectedMcpName:t.selectedMcpName})}),{name:"mcp-config-store"}));function Dc(t){const e={};if(t.scope!==void 0&&(e.scope=t.scope),t.type!==void 0&&(e.type=t.type),(t.type==="local"||t.command!==void 0)&&(e.command=(t.command??[]).filter(n=>n.trim())),(t.type==="remote"||t.url!==void 0)&&(e.url=t.url?.trim()??""),t.environment!==void 0&&(e.environment=Ec(t.environment)??{}),t.headers!==void 0&&(e.headers=Ec(t.headers)??{}),t.oauthEnabled!==void 0||t.oauthClientId!==void 0||t.oauthClientSecret!==void 0||t.oauthScope!==void 0||t.oauthRedirectUri!==void 0)if(t.oauthEnabled===!1)e.oauth=!1;else{const n={clientId:Fi(t.oauthClientId),clientSecret:Fi(t.oauthClientSecret),scope:Fi(t.oauthScope),redirectUri:Fi(t.oauthRedirectUri)};n.clientId||n.clientSecret||n.scope||n.redirectUri?e.oauth=n:t.oauthEnabled?e.oauth={}:e.oauth=!1}if(t.timeout!==void 0){const n=Number(t.timeout);Number.isFinite(n)&&n>0?e.timeout=n:e.timeout=null}return t.enabled!==void 0&&(e.enabled=t.enabled),e}const Lu=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),yi=t=>{const e=tt.c(39),{className:n}=t,{t:a}=lt(),i=is(Dx),r=is(Rx),o=is(Mx),d=ds();let c;e[0]!==i?(c=[...i].sort(Lx),e[0]=i,e[1]=c):c=e[1];const p=c;let u;e:{if(p.length===0){u=null;break e}let E;e[2]!==r||e[3]!==p?(E=p.find(D=>D.id===r)??p[0],e[2]=r,e[3]=p,e[4]=E):E=e[4],u=E}const f=u;if(d||p.length===0)return null;let m;e[5]!==f||e[6]!==a?(m=f?.label&&f.label.trim().length>0?f.label:f?.path.split("/").filter(Boolean).pop()||f?.path||a("settings.shared.projectSelector.fallbackProject"),e[5]=f,e[6]=a,e[7]=m):m=e[7];const w=m;let b;e[8]!==w?(b=Lu(w),e[8]=w,e[9]=b):b=e[9];const g=b;let x;e[10]!==n?(x=fe(n),e[10]=n,e[11]=x):x=e[11];let k;e[12]!==a?(k=a("settings.shared.projectSelector.switchProjectAria"),e[12]=a,e[13]=k):k=e[13];let y;e[14]!==a?(y=a("settings.shared.projectSelector.switchProjectTitle"),e[14]=a,e[15]=y):y=e[15];let C,z;e[16]===Symbol.for("react.memo_cache_sentinel")?(C=fe("text-foreground border border-border/80 appearance-none flex h-8 w-full min-w-0 rounded-lg bg-transparent px-3 py-1 outline-none","hover:border-input focus-visible:ring-1 focus-visible:ring-primary/50 focus-visible:border-primary/70","flex items-center gap-1.5 text-left"),z=s.jsx(K,{name:"folder",className:"h-4 w-4 opacity-70"}),e[16]=C,e[17]=z):(C=e[16],z=e[17]);let j;e[18]!==g?(j=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:g}),e[18]=g,e[19]=j):j=e[19];let N;e[20]===Symbol.for("react.memo_cache_sentinel")?(N=s.jsx(K,{name:"arrow-down-s",className:"size-4 opacity-50"}),e[20]=N):N=e[20];let v;e[21]!==j||e[22]!==k||e[23]!==y?(v=s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":k,title:y,className:C,children:[z,j,N]})}),e[21]=j,e[22]=k,e[23]=y,e[24]=v):v=e[24];const P=f?.id??"";let $;e[25]!==o?($=E=>{E&&o(E)},e[25]=o,e[26]=$):$=e[26];let O;e[27]!==p?(O=p.map(Fx),e[27]=p,e[28]=O):O=e[28];let M;e[29]!==P||e[30]!==$||e[31]!==O?(M=s.jsx(hs,{align:"start",className:"w-auto",children:s.jsx(Xm,{value:P,onValueChange:$,children:O})}),e[29]=P,e[30]=$,e[31]=O,e[32]=M):M=e[32];let S;e[33]!==v||e[34]!==M?(S=s.jsxs(fs,{children:[v,M]}),e[33]=v,e[34]=M,e[35]=S):S=e[35];let F;return e[36]!==S||e[37]!==x?(F=s.jsx("div",{className:x,children:S}),e[36]=S,e[37]=x,e[38]=F):F=e[38],F};function Dx(t){return t.projects}function Rx(t){return t.activeProjectId}function Mx(t){return t.setActiveProject}function Lx(t,e){return(t.label||t.path).localeCompare(e.label||e.path)}function Fx(t){const e=t.label?.trim()?t.label.trim():t.path.split("/").filter(Boolean).pop()||t.path,n=Lu(e);return s.jsx(Qm,{value:t.id,children:s.jsx("span",{className:"min-w-0 truncate typography-ui",children:n})},t.id)}function Ox(t,e){return`opencode:sidebar-group:${t}:${e}`}const Ho=t=>{const e=tt.c(33),{label:n,count:a,storageKey:i,defaultExpanded:r,children:o}=t,d=r===void 0?!0:r;let c;e[0]!==n||e[1]!==i?(c=Ox(i,n),e[0]=n,e[1]=i,e[2]=c):c=e[2];const p=c,u=l.useId();let f;e[3]!==d||e[4]!==p?(f=()=>{try{const M=localStorage.getItem(p);if(M!==null)return M==="true"}catch{}return d},e[3]=d,e[4]=p,e[5]=f):f=e[5];const[m,w]=we.useState(f);let b,g;e[6]!==m||e[7]!==p?(b=()=>{try{localStorage.setItem(p,String(m))}catch{}},g=[p,m],e[6]=m,e[7]=p,e[8]=b,e[9]=g):(b=e[8],g=e[9]),we.useEffect(b,g);let x;e[10]===Symbol.for("react.memo_cache_sentinel")?(x=()=>w(zx),e[10]=x):x=e[10];let k;e[11]===Symbol.for("react.memo_cache_sentinel")?(k=fe("flex w-full items-center gap-1 rounded-md px-2 py-1 text-left","text-xs font-semibold uppercase tracking-wide text-muted-foreground","hover:bg-[var(--interactive-hover)] transition-colors duration-150","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"),e[11]=k):k=e[11];const y=!m&&"-rotate-90";let C;e[12]!==y?(C=fe("h-3.5 w-3.5 flex-shrink-0 transition-transform duration-200",y),e[12]=y,e[13]=C):C=e[13];let z;e[14]!==C?(z=s.jsx(K,{name:"arrow-down-s",className:C}),e[14]=C,e[15]=z):z=e[15];let j;e[16]!==n?(j=s.jsx("span",{className:"flex-1 truncate",children:n}),e[16]=n,e[17]=j):j=e[17];let N;e[18]!==a?(N=s.jsx("span",{className:"ml-1 tabular-nums opacity-60",children:a}),e[18]=a,e[19]=N):N=e[19];let v;e[20]!==u||e[21]!==m||e[22]!==z||e[23]!==j||e[24]!==N?(v=s.jsxs("button",{type:"button",onClick:x,"aria-expanded":m,"aria-controls":u,className:k,children:[z,j,N]}),e[20]=u,e[21]=m,e[22]=z,e[23]=j,e[24]=N,e[25]=v):v=e[25];const P=!m;let $;e[26]!==o||e[27]!==u||e[28]!==P?($=s.jsx("div",{id:u,hidden:P,className:"mt-0.5 space-y-0.5 ml-2 pl-3 border-l-2 border-[var(--interactive-border)]",children:o}),e[26]=o,e[27]=u,e[28]=P,e[29]=$):$=e[29];let O;return e[30]!==v||e[31]!==$?(O=s.jsxs("div",{children:[v,$]}),e[30]=v,e[31]=$,e[32]=O):O=e[32],O};function zx(t){return!t}const Kx=t=>{if(!Array.isArray(t))return[];const e=[];for(const n of t){if(!n||typeof n!="object")continue;const a=n;typeof a.permission!="string"||typeof a.pattern!="string"||typeof a.action!="string"||a.action!=="allow"&&a.action!=="ask"&&a.action!=="deny"||e.push({permission:a.permission,pattern:a.pattern,action:a.action})}return e},Bx=t=>{const e=new Map;for(const n of t)!n.permission||n.permission==="invalid"||n.pattern&&e.set(`${n.permission}::${n.pattern}`,n);return Array.from(e.values())},Rc=t=>{const e=Bx(Kx(t));if(e.length===0)return;const n={};for(const i of e)i.permission&&((n[i.permission]||={})[i.pattern]=i.action);const a={};for(const[i,r]of Object.entries(n)){const o=Object.keys(r);if(o.length===1&&o[0]==="*"){a[i]=r["*"];continue}a[i]=r}return Object.keys(a).length>0?a:void 0},_x=({onItemSelect:t})=>{const{t:e}=lt(),[n,a]=l.useState(null),[i,r]=l.useState(""),[o,d]=l.useState(null),[c,p]=l.useState(null),[u,f]=l.useState(!1),[m,w]=l.useState(null),{selectedAgentName:b,agents:g,setSelectedAgent:x,setAgentDraft:k,createAgent:y,deleteAgent:C,loadAgents:z}=$a(Hs(A=>({selectedAgentName:A.selectedAgentName,agents:A.agents,setSelectedAgent:A.setSelectedAgent,setAgentDraft:A.setAgentDraft,createAgent:A.createAgent,deleteAgent:A.deleteAgent,loadAgents:A.loadAgents})));l.useEffect(()=>{z()},[z]);const j="bg-background",N=()=>{const A="new-agent";let X=A,te=1;for(;g.some(T=>T.name===X);)X=`${A}-${te}`,te++;k({name:X,scope:"user"}),x(X),t?.()},v=async A=>{if(Fa(A)){J.error(e("settings.agents.sidebar.toast.builtInCannotDelete"));return}d(A),p("delete")},P=async A=>{Fa(A)&&(d(A),p("reset"))},$=()=>{d(null),p(null)},O=async()=>{if(!(!o||!c)){f(!0);try{const A=await C(o.name,o.scope);A.ok?(A.requiresManualRestart?J.warning(e("settings.agents.page.toast.savedManualRestart")):c==="delete"?J.success(e("settings.agents.sidebar.toast.agentDeleted",{name:o.name})):J.success(e("settings.agents.sidebar.toast.agentReset",{name:o.name})),$()):c==="delete"?J.error(e("settings.agents.sidebar.toast.deleteFailed")):J.error(e("settings.agents.sidebar.toast.resetFailed"))}catch(A){const X=A instanceof Error?A.message:"",te=/built-in|not deletable|not found/i.test(X);c==="delete"?J.error(e(te?"settings.agents.sidebar.toast.definitionNotFound":"settings.agents.sidebar.toast.deleteFailed")):J.error(e("settings.agents.sidebar.toast.resetFailed"))}f(!1)}},M=A=>{const X=A.name;let te=1,T=`${X}-copy`;for(;g.some(V=>V.name===T);)te++,T=`${X}-copy-${te}`;const I=A,B=A.model?.providerID&&A.model?.modelID?`${A.model.providerID}/${A.model.modelID}`:null,L=A;k({name:T,scope:I.scope||"user",description:A.description,model:B,variant:A.variant,temperature:A.temperature,top_p:A.topP,prompt:A.prompt,mode:A.mode,permission:Rc(A.permission),disable:L.disable}),x(T)},S=A=>{r(A.name),a(A)},F=async()=>{if(!n)return;const A=i.trim().replace(/\s+/g,"-");if(!A){J.error(e("settings.agents.sidebar.toast.agentNameRequired"));return}if(A===n.name){a(null);return}if(g.some(I=>I.name===A)){J.error(e("settings.agents.sidebar.toast.agentExists"));return}const X=n.model?.providerID&&n.model?.modelID?`${n.model.providerID}/${n.model.modelID}`:null,te=n,T=await y({name:A,description:n.description,model:X,variant:n.variant,temperature:n.temperature,top_p:n.topP,prompt:n.prompt,mode:n.mode,permission:Rc(n.permission),disable:te.disable,scope:te.scope});if(T.ok){const I=await C(n.name,te.scope);I.ok?(T.requiresManualRestart||I.requiresManualRestart?J.warning(e("settings.agents.page.toast.savedManualRestart")):J.success(e("settings.agents.sidebar.toast.agentRenamed",{name:A})),x(A)):J.error(e("settings.agents.sidebar.toast.removeOldAfterRenameFailed"))}else J.error(e("settings.agents.sidebar.toast.renameFailed"));a(null)},E=A=>{switch(A){case"primary":return s.jsx(K,{name:"ai-agent",className:"h-3 w-3 text-primary"});case"all":return s.jsx(K,{name:"ai-agent-fill",className:"h-3 w-3 text-primary"});case"subagent":return s.jsx(K,{name:"robot",className:"h-3 w-3 text-primary"});default:return null}},D=g.filter(A=>!Zm(A)),W=D.filter(Fa),H=D.filter(A=>!Fa(A)),{groupedCustomAgents:Z,ungroupedCustomAgents:Y}=we.useMemo(()=>{const A={},X=[];for(const T of H){const I=T;I.group?(A[I.group]||(A[I.group]=[]),A[I.group].push(T)):X.push(T)}return{groupedCustomAgents:Object.keys(A).sort((T,I)=>T.localeCompare(I)).map(T=>({name:T,agents:A[T]})),ungroupedCustomAgents:X}},[H]);return s.jsxs("div",{className:fe("flex h-full flex-col",j),children:[s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[s.jsx("h2",{className:`${fn} mb-3`,children:e("settings.agents.sidebar.title")}),s.jsx(yi,{className:"mb-3"}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:e("settings.agents.sidebar.total",{count:D.length})}),s.jsx(ee,{size:"sm","data-settings-item":"agents.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:N,children:s.jsx(K,{name:"add",className:"h-3.5 w-3.5"})})]})]}),s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:D.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"robot-2",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:e("settings.agents.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:e("settings.agents.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[W.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:e("settings.agents.sidebar.section.builtIn")}),W.map(A=>s.jsx(eo,{agent:A,isSelected:b===A.name,onSelect:()=>{x(A.name),t?.()},onReset:()=>P(A),onDuplicate:()=>M(A),getAgentModeIcon:E,isMenuOpen:m===A.name,onMenuOpenChange:X=>w(X?A.name:null)},A.name))]}),H.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:e("settings.agents.sidebar.section.custom")}),Z.map(({name:A,agents:X})=>s.jsx(Ho,{label:A,count:X.length,storageKey:"agents",children:X.map(te=>s.jsx(eo,{agent:te,isSelected:b===te.name,onSelect:()=>{x(te.name),t?.()},onRename:()=>S(te),onDelete:()=>v(te),onDuplicate:()=>M(te),getAgentModeIcon:E,isMenuOpen:m===te.name,onMenuOpenChange:T=>w(T?te.name:null)},te.name))},A)),Y.map(A=>s.jsx(eo,{agent:A,isSelected:b===A.name,onSelect:()=>{x(A.name),t?.()},onRename:()=>S(A),onDelete:()=>v(A),onDuplicate:()=>M(A),getAgentModeIcon:E,isMenuOpen:m===A.name,onMenuOpenChange:X=>w(X?A.name:null)},A.name))]})]})}),s.jsx(Kt,{open:o!==null&&c!==null,onOpenChange:A=>{!A&&!u&&$()},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:e(c==="delete"?"settings.agents.sidebar.dialog.deleteTitle":"settings.agents.sidebar.dialog.resetTitle")}),s.jsx(Yt,{children:c==="delete"?e("settings.agents.sidebar.dialog.deleteDescription",{name:o?.name??""}):e("settings.agents.sidebar.dialog.resetDescription",{name:o?.name??""})})]}),s.jsxs(rs,{children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:$,disabled:u,children:e("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",onClick:O,disabled:u,children:e(c==="delete"?"settings.common.actions.delete":"settings.common.actions.reset")})]})]})}),s.jsx(Kt,{open:n!==null,onOpenChange:A=>!A&&a(null),children:s.jsxs(Bt,{children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:e("settings.agents.sidebar.renameDialog.title")}),s.jsx(Yt,{children:e("settings.agents.sidebar.renameDialog.description",{name:n?.name??""})})]}),s.jsx(at,{value:i,onChange:A=>r(A.target.value),placeholder:e("settings.agents.sidebar.renameDialog.placeholder"),className:"text-foreground placeholder:text-muted-foreground",onKeyDown:A=>{A.key==="Enter"&&F()}}),s.jsxs(rs,{children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>a(null),children:e("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",onClick:F,children:e("settings.common.actions.rename")})]})]})})]})},eo=t=>{const e=tt.c(52),{agent:n,isSelected:a,onSelect:i,onDelete:r,onReset:o,onRename:d,onDuplicate:c,getAgentModeIcon:p,isMenuOpen:u,onMenuOpenChange:f}=t,{t:m}=lt(),w=n;let b;e[0]===Symbol.for("react.memo_cache_sentinel")?(b=hi(),e[0]=b):b=e[0];const g=b,[x,k]=l.useState(!1);let y;e[1]!==r||e[2]!==c||e[3]!==d||e[4]!==o||e[5]!==m?(y=te=>s.jsxs(s.Fragment,{children:[d&&s.jsxs(te,{onClick:T=>{T.stopPropagation(),d()},children:[s.jsx(K,{name:"edit",className:"h-4 w-4 mr-px"}),m("settings.common.actions.rename")]}),s.jsxs(te,{onClick:T=>{T.stopPropagation(),c()},children:[s.jsx(K,{name:"file-copy",className:"h-4 w-4 mr-px"}),m("settings.common.actions.duplicate")]}),o&&s.jsxs(te,{onClick:T=>{T.stopPropagation(),o()},children:[s.jsx(K,{name:"restart",className:"h-4 w-4 mr-px"}),m("settings.common.actions.reset")]}),r&&s.jsxs(te,{onClick:T=>{T.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),m("settings.common.actions.delete")]})]}),e[1]=r,e[2]=c,e[3]=d,e[4]=o,e[5]=m,e[6]=y):y=e[6];const C=y,z=a?"bg-interactive-selection":"hover:bg-interactive-hover";let j;e[7]!==z?(j=fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",z),e[7]=z,e[8]=j):j=e[8];let N;e[9]===Symbol.for("react.memo_cache_sentinel")?(N=g?void 0:te=>{te.preventDefault(),k(!0)},e[9]=N):N=e[9];let v;e[10]!==j?(v=s.jsx("div",{className:j,onContextMenu:N}),e[10]=j,e[11]=v):v=e[11];let P;e[12]!==n.name?(P=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n.name}),e[12]=n.name,e[13]=P):P=e[13];let $;e[14]!==n.mode||e[15]!==p?($=p(n.mode),e[14]=n.mode,e[15]=p,e[16]=$):$=e[16];let O;e[17]!==n||e[18]!==w.scope||e[19]!==m?(O=(w.scope||Fa(n))&&s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:Fa(n)?m("settings.agents.sidebar.badge.system"):w.scope}),e[17]=n,e[18]=w.scope,e[19]=m,e[20]=O):O=e[20];let M;e[21]!==P||e[22]!==$||e[23]!==O?(M=s.jsxs("div",{className:"flex items-center gap-1.5",children:[P,$,O]}),e[21]=P,e[22]=$,e[23]=O,e[24]=M):M=e[24];let S;e[25]!==n.description?(S=n.description&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n.description}),e[25]=n.description,e[26]=S):S=e[26];let F;e[27]!==i||e[28]!==M||e[29]!==S?(F=s.jsxs("button",{onClick:i,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[M,S]}),e[27]=i,e[28]=M,e[29]=S,e[30]=F):F=e[30];let E;e[31]!==f?(E=te=>{te&&k(!1),f(te)},e[31]=f,e[32]=E):E=e[32];let D;e[33]===Symbol.for("react.memo_cache_sentinel")?(D=s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"sm",variant:"ghost",className:"h-6 w-6 px-0 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[33]=D):D=e[33];let W;e[34]!==C?(W=s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:C(as)}),e[34]=C,e[35]=W):W=e[35];let H;e[36]!==u||e[37]!==E||e[38]!==W?(H=s.jsxs(fs,{open:u,onOpenChange:E,children:[D,W]}),e[36]=u,e[37]=E,e[38]=W,e[39]=H):H=e[39];let Z;e[40]!==F||e[41]!==H?(Z=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[F,H]}),e[40]=F,e[41]=H,e[42]=Z):Z=e[42];let Y;e[43]!==Z||e[44]!==v?(Y=s.jsx(Gn,{render:v,children:Z}),e[43]=Z,e[44]=v,e[45]=Y):Y=e[45];let A;e[46]!==C?(A=s.jsx(qn,{className:"w-fit min-w-20",children:C(An)}),e[46]=C,e[47]=A):A=e[47];let X;return e[48]!==x||e[49]!==Y||e[50]!==A?(X=s.jsxs(Wn,{open:x,onOpenChange:k,children:[Y,A]}),e[48]=x,e[49]=Y,e[50]=A,e[51]=X):X=e[51],X},ps=t=>{const e=tt.c(21),{children:n,className:a,outerClassName:i,title:r,titleLeading:o,titleAccessory:d,description:c,headerEnd:p,showSaveStatus:u}=t,f=u===void 0?!1:u,m=r!=null||c!=null||p!=null||f,w=typeof r=="string"||typeof r=="number",b=o!=null||d!=null;let g;e[0]!==i?(g=fe("h-full",i),e[0]=i,e[1]=g):g=e[1];let x;e[2]!==a?(x=fe("mx-auto max-w-[840px] space-y-0 px-6 py-6 @3xl:px-12 @3xl:py-8","[&>section:first-of-type]:border-t-0 [&>section:first-of-type]:pt-0",a),e[2]=a,e[3]=x):x=e[3];let k;e[4]!==c||e[5]!==m||e[6]!==b||e[7]!==p||e[8]!==w||e[9]!==f||e[10]!==r||e[11]!==d||e[12]!==o?(k=m&&s.jsxs("div",{className:"mb-2 flex items-start justify-between gap-4 pb-6",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[r!=null?w?b?s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o,s.jsx("h1",{className:fe(Bo,"min-w-0 truncate"),children:r}),d]}):s.jsx("h1",{className:Bo,children:r}):r:null,c!=null?typeof c=="string"||typeof c=="number"?s.jsx("p",{className:Cu,children:c}):c:null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[p,f&&s.jsx($x,{})]})]}),e[4]=c,e[5]=m,e[6]=b,e[7]=p,e[8]=w,e[9]=f,e[10]=r,e[11]=d,e[12]=o,e[13]=k):k=e[13];let y;e[14]!==n||e[15]!==x||e[16]!==k?(y=s.jsxs("div",{className:x,children:[k,n]}),e[14]=n,e[15]=x,e[16]=k,e[17]=y):y=e[17];let C;return e[18]!==g||e[19]!==y?(C=s.jsx(Os,{outerClassName:g,className:"w-full @container",children:y}),e[18]=g,e[19]=y,e[20]=C):C=e[20],C},Ux=500,$x=()=>{const t=tt.c(13),{t:e}=lt(),n=l.useSyncExternalStore(Cg,Kl,Kl),[a,i]=l.useState(!1);let r,o;if(t[0]!==n?(r=()=>{if(n!=="saving"){i(!1);return}const u=setTimeout(()=>i(!0),Ux);return()=>clearTimeout(u)},o=[n],t[0]=n,t[1]=r,t[2]=o):(r=t[1],o=t[2]),l.useEffect(r,o),n==="error"){let u;t[3]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(K,{name:"error-warning",className:"size-3.5"}),t[3]=u):u=t[3];let f;t[4]!==e?(f=e("settings.common.status.saveFailed"),t[4]=e,t[5]=f):f=t[5];let m;return t[6]!==f?(m=s.jsxs("div",{"aria-live":"assertive",className:"flex shrink-0 items-center gap-1.5 typography-meta text-[var(--status-error)]",children:[u,s.jsx("span",{children:f})]}),t[6]=f,t[7]=m):m=t[7],m}if(n!=="saving"||!a)return null;let d;t[8]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"}),t[8]=d):d=t[8];let c;t[9]!==e?(c=e("settings.common.actions.saving"),t[9]=e,t[10]=c):c=t[10];let p;return t[11]!==c?(p=s.jsxs("div",{"aria-live":"polite",className:"flex shrink-0 items-center gap-1.5 typography-meta text-muted-foreground",children:[d,s.jsx("span",{children:c})]}),t[11]=c,t[12]=p):p=t[12],p},Vx=["allow","ask","deny"],di=t=>t==="allow"||t==="ask"||t==="deny",Wo=()=>({global:null,keys:{}}),Hx=t=>{const e=Wo();if(t==null)return e;if(typeof t=="string")return di(t)&&(e.global=t),e;if(typeof t!="object"||Array.isArray(t))return e;for(const[n,a]of Object.entries(t)){if(n==="*"){di(a)&&(e.global=a);continue}const i={action:null,patterns:[]};if(di(a))i.action=a;else if(a&&typeof a=="object"&&!Array.isArray(a))for(const[r,o]of Object.entries(a))di(o)&&(r==="*"?i.action=o:i.patterns.push({pattern:r,action:o}));else continue;e.keys[n]=i}return e},Go=t=>{const e={};t.global!==null&&(e["*"]=t.global);for(const[n,a]of Object.entries(t.keys)){const i=a.patterns.filter(r=>r.pattern.trim().length>0);if(a.action!==null&&i.length===0)e[n]=a.action;else if(i.length>0){const r={};a.action!==null&&(r["*"]=a.action);for(const o of i)r[o.pattern]=o.action;e[n]=r}}return Object.keys(e).length>0?e:null},Wx=(t,e)=>JSON.stringify(Go(t))===JSON.stringify(Go(e)),Mn=t=>JSON.parse(JSON.stringify(t)),Gx=["edit","external_directory","doom_loop","plan_enter","plan_exit"],qx=new Set(["read","edit","glob","grep","list","bash","task","external_directory","lsp","skill"]),Mc=new Set(["write","patch","apply_patch","multiedit","invalid"]),Jx=t=>t.split(/[_-]/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),Yx=({agent:t})=>{const{t:e}=lt(),n=$a(I=>I.updateAgent),[a,i]=l.useState(Wo),[r,o]=l.useState(Wo),[d,c]=l.useState(!0),[p,u]=l.useState(!1),[f,m]=l.useState(!1),[w,b]=l.useState({}),[g,x]=l.useState([]),[k,y]=l.useState(""),[C,z]=l.useState(0),j=t.name;l.useEffect(()=>{let I=!1;return c(!0),u(!1),(async()=>{try{const B=Nl(),L=B?`?directory=${encodeURIComponent(B)}`:"",V=await ht(`/api/config/agents/${encodeURIComponent(j)}/config${L}`,{headers:{"Cache-Control":"no-cache",...B?{"x-opencode-directory":B}:{}}});if(!V.ok)throw new Error(String(V.status));const Q=await V.json().catch(()=>null);if(I)return;const G=Hx(Q?.config?.permission);i(Mn(G)),o(G)}catch{I||u(!0)}finally{I||c(!1)}})(),()=>{I=!0}},[j,C]),l.useEffect(()=>{let I=!1;return(async()=>{try{const B=await Ps.listToolIds({directory:Nl()});!I&&Array.isArray(B)&&x(B.filter(L=>typeof L=="string"&&!Mc.has(L)))}catch{}})(),()=>{I=!0}},[j]);const N=l.useMemo(()=>{const I=t.permission;if(!Array.isArray(I))return[];const B=[];for(const L of I){if(!L||typeof L!="object")continue;const{permission:V,pattern:Q,action:G}=L;typeof V=="string"&&typeof Q=="string"&&di(G)&&B.push({permission:V,pattern:Q,action:G})}return B},[t]),v=l.useCallback(I=>{const B=N.find(V=>V.permission===I&&V.pattern==="*");if(B)return B.action;const L=N.find(V=>V.permission==="*"&&V.pattern==="*");return L?L.action:null},[N]),P=l.useCallback(I=>{const B=r.keys[I]?.patterns??[],L=new Set(B.map(V=>V.pattern));return N.filter(V=>V.permission===I&&V.pattern!=="*"&&!L.has(V.pattern))},[N,r.keys]),$=l.useMemo(()=>{const I=new Set;for(const B of g)I.add(B);for(const B of Gx)I.add(B);for(const B of Object.keys(r.keys))I.add(B);for(const B of Mc)I.delete(B);return Array.from(I).sort((B,L)=>B.localeCompare(L))},[g,r.keys]),O=l.useMemo(()=>!Wx(r,a),[r,a]),M=I=>{o(B=>({...B,global:I}))},S=(I,B)=>{o(L=>{const V=Mn(L),Q=V.keys[I]??{action:null,patterns:[]};return Q.action=B,Q.action===null&&Q.patterns.length===0?delete V.keys[I]:V.keys[I]=Q,V})},F=(I,B,L,V)=>{o(Q=>{const G=Mn(Q),ue=G.keys[I]??{action:null,patterns:[]};return ue.patterns[B]={pattern:L,action:V},G.keys[I]=ue,G})},E=I=>{o(B=>{const L=Mn(B),V=L.keys[I]??{action:null,patterns:[]};return V.patterns.push({pattern:"",action:"allow"}),L.keys[I]=V,L}),b(B=>({...B,[I]:!0}))},D=(I,B)=>{o(L=>{const V=Mn(L),Q=V.keys[I];return Q?(Q.patterns.splice(B,1),Q.action===null&&Q.patterns.length===0&&delete V.keys[I],V):L})},W=()=>{const I=k.trim();!I||I==="*"||(o(B=>{if(B.keys[I])return B;const L=Mn(B);return L.keys[I]={action:"ask",patterns:[]},L}),b(B=>({...B,[I]:!0})),y(""))},H=async()=>{m(!0);try{const I=Go(r),B=await n(j,{permission:I});B.ok?(i(Mn(r)),J.success(B.requiresManualRestart?e("settings.agents.page.permissionsEditor.toast.savedRestartRequired"):e("settings.agents.page.permissionsEditor.toast.saved"))):J.error(e("settings.agents.page.permissionsEditor.toast.saveFailed"))}finally{m(!1)}},Z=()=>{o(Mn(a))},Y=I=>e(I==="allow"?"settings.agents.page.permissionsEditor.action.allow":I==="ask"?"settings.agents.page.permissionsEditor.action.ask":"settings.agents.page.permissionsEditor.action.deny"),A=e("settings.agents.page.permissionsEditor.action.inherit"),X=e("settings.agents.page.permissionsEditor.action.default"),te=I=>[...I?[{value:"inherit",label:I}]:[],...Vx.map(B=>({value:B,label:Y(B)}))],T=(I,B,L,V=A)=>s.jsx(Ys,{value:I??"inherit",options:te(V),onChange:Q=>B(Q==="inherit"?null:Q),"aria-label":L});return d?s.jsx(dt,{title:e("settings.agents.page.section.toolPermissions"),children:s.jsx("p",{className:Js,children:e("common.loading")})}):p?s.jsx(dt,{title:e("settings.agents.page.section.toolPermissions"),children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:e("settings.agents.page.permissionsEditor.state.loadFailed")}),s.jsx(ee,{variant:"outline",size:"xs",onClick:()=>z(I=>I+1),children:e("settings.agents.page.permissionsEditor.actions.retry")})]})}):s.jsxs(dt,{title:e("settings.agents.page.section.toolPermissions"),settingsItem:"agents.permissions",info:e("settings.agents.page.permissionsEditor.sectionInfo"),headerAction:O?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:Z,disabled:f,children:e("settings.agents.page.permissionsEditor.actions.discard")}),s.jsx(ee,{size:"xs",className:"!font-normal",onClick:()=>{H()},disabled:f,children:e(f?"settings.common.actions.saving":"settings.agents.page.permissionsEditor.actions.save")})]}):void 0,contentClassName:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col gap-2 pb-2 @xl:flex-row @xl:items-center @xl:justify-between",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:zt,children:e("settings.agents.page.permissionsEditor.defaultLabel")}),s.jsx($t,{children:e("settings.agents.page.permissionsEditor.defaultInfo")}),r.global===null&&s.jsx("span",{className:"typography-micro text-muted-foreground",children:e("settings.agents.page.permissionsEditor.effectiveHint",{action:Y(v("*")??"allow")})})]}),T(r.global,M,e("settings.agents.page.permissionsEditor.defaultAria"),X)]}),s.jsx("div",{children:$.map(I=>{const B=r.keys[I]??{action:null,patterns:[]},L=P(I),V=qx.has(I)||B.patterns.length>0,Q=V||L.length>0,G=w[I]===!0,ue=v(I);return s.jsxs("div",{className:"border-t border-border/40 py-2",children:[s.jsxs("div",{className:"flex flex-col gap-2 @xl:flex-row @xl:items-center @xl:justify-between",children:[s.jsxs("button",{type:"button",onClick:Q?()=>b(ne=>({...ne,[I]:!G})):void 0,className:fe("flex min-w-0 items-center gap-1.5 text-left",!Q&&"cursor-default"),"aria-expanded":Q?G:void 0,children:[s.jsx(K,{name:G&&Q?"arrow-down-s":"arrow-right-s",className:fe("h-3.5 w-3.5 shrink-0 text-muted-foreground",!Q&&"opacity-0")}),s.jsx("span",{className:zt,children:Jx(I)}),s.jsx("span",{className:"typography-micro font-mono text-muted-foreground/70",children:I}),B.action===null&&ue!==null&&s.jsx("span",{className:"typography-micro text-muted-foreground",children:e("settings.agents.page.permissionsEditor.effectiveHint",{action:Y(ue)})}),B.patterns.length>0&&s.jsx("span",{className:"typography-micro rounded bg-muted px-1 text-muted-foreground",children:e("settings.agents.page.permissionsEditor.ruleCount",{count:String(B.patterns.length)})})]}),T(B.action,ne=>S(I,ne),e("settings.agents.page.permissionsEditor.keyAria",{key:I}))]}),G&&Q&&s.jsxs("div",{className:"mt-2 space-y-2 pl-5",children:[B.patterns.map((ne,xe)=>s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(at,{value:ne.pattern,onChange:ve=>F(I,xe,ve.target.value,ne.action),placeholder:e("settings.agents.page.permissionsEditor.patternPlaceholder"),className:"h-8 w-full max-w-[24rem] min-w-0 flex-1 font-mono text-xs"}),s.jsx(Ys,{value:ne.action,options:te(),onChange:ve=>F(I,xe,ne.pattern,ve),"aria-label":e("settings.agents.page.permissionsEditor.patternActionAria",{key:I})}),s.jsx(ee,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive",onClick:()=>D(I,xe),"aria-label":e("settings.agents.page.permissionsEditor.actions.removeRuleAria"),children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]},xe)),V&&s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>E(I),children:[s.jsx(K,{name:"add",className:"mr-1 h-3.5 w-3.5"}),e("settings.agents.page.permissionsEditor.actions.addRule")]}),L.length>0&&s.jsxs("div",{className:"space-y-1 pt-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"typography-micro font-medium text-muted-foreground",children:e("settings.agents.page.permissionsEditor.sessionRulesTitle")}),s.jsx($t,{children:e("settings.agents.page.permissionsEditor.sessionRulesInfo")})]}),L.map(ne=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-micro min-w-0 flex-1 truncate font-mono text-muted-foreground/70",children:ne.pattern}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:Y(ne.action)})]},`${ne.pattern}-${ne.action}`))]})]})]},I)})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t border-border/40 pt-3",children:[s.jsx(at,{value:k,onChange:I=>y(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),W())},placeholder:e("settings.agents.page.permissionsEditor.customKeyPlaceholder"),className:"h-8 w-full max-w-[16rem] font-mono text-xs"}),s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:W,disabled:!k.trim(),children:[s.jsx(K,{name:"add",className:"mr-1 h-3.5 w-3.5"}),e("settings.agents.page.permissionsEditor.actions.addKey")]})]})]})},Qx=(t,e)=>{const n=Hn(e);if(!n)return[];const i=t.find(r=>r.id===n.providerId)?.models?.find(r=>r.id===n.modelId);return i?.variants?Object.keys(i.variants):[]},Xx=()=>{const{t}=lt(),e=pt(T=>T.providers),{selectedAgentName:n,getAgentByName:a,createAgent:i,updateAgent:r,agents:o,agentDraft:d,setAgentDraft:c}=$a(Hs(T=>({selectedAgentName:T.selectedAgentName,getAgentByName:T.getAgentByName,createAgent:T.createAgent,updateAgent:T.updateAgent,agents:T.agents,agentDraft:T.agentDraft,setAgentDraft:T.setAgentDraft}))),p=n?a(n):null,u=!!(d&&d.name===n&&!p),[f,m]=l.useState(""),[w,b]=l.useState("user"),[g,x]=l.useState(""),[k,y]=l.useState("subagent"),[C,z]=l.useState(""),[j,N]=l.useState(""),[v,P]=l.useState(void 0),[$,O]=l.useState(void 0),[M,S]=l.useState(""),[F,E]=l.useState(!1),D=l.useRef(null),W=l.useMemo(()=>Qx(e,C),[C,e]),H=W.length>0,Z=j||"__default",Y=H,A=l.useMemo(()=>j&&!W.includes(j)?[j,...W]:W,[j,W]);l.useEffect(()=>{if(u&&d){const T=d.name||"",I=d.scope||"user",B=d.description||"",L=d.mode||"subagent",V=d.model||"",Q=d.variant||"",G=d.temperature??void 0,ue=d.top_p??void 0,ne=d.prompt||"";m(T),b(I),x(B),y(L),z(V),N(Q),P(G),O(ue),S(ne),D.current={draftName:T,draftScope:I,description:B,mode:L,model:V,variant:Q,temperature:G,topP:ue,prompt:ne};return}if(p&&n===p.name){const T=p.description||"",I=p.mode||"subagent",B=p.model?.providerID&&p.model?.modelID?`${p.model.providerID}/${p.model.modelID}`:"",L=p.variant||"",V=p.temperature??void 0,Q=p.topP??void 0,G=p.prompt||"";x(T),y(I),z(B),N(L),P(V),O(Q),S(G),D.current={draftName:"",draftScope:"user",description:T,mode:I,model:B,variant:L,temperature:V,topP:Q,prompt:G}}},[d,u,p,n]);const X=l.useMemo(()=>{const T=D.current;return T?!!(u&&(f!==T.draftName||w!==T.draftScope)||g!==T.description||k!==T.mode||C!==T.model||j!==T.variant||v!==T.temperature||$!==T.topP||M!==T.prompt):!1},[g,f,w,u,k,C,M,v,$,j]),te=async()=>{const T=u?f.trim().replace(/\s+/g,"-"):n?.trim();if(!T){J.error(t("settings.agents.sidebar.toast.agentNameRequired"));return}if(u&&o.some(I=>I.name===T)){J.error(t("settings.agents.sidebar.toast.agentExists"));return}E(!0);try{const I=C.trim(),B=j.trim(),L=M.trim(),V={name:T,...g.trim()?{description:g.trim()}:{},mode:k,model:I===""?null:I,variant:B===""?null:B||void 0,temperature:v??null,top_p:$??null,prompt:L||(u?void 0:null),...u&&w?{scope:w}:{}};let Q;u?(Q=await i(V),Q.ok&&c(null)):Q=await r(T,V),Q.ok?Q.requiresManualRestart?J.warning(t("settings.agents.page.toast.savedManualRestart")):J.success(t(u?"settings.agents.page.toast.created":"settings.agents.page.toast.updated")):J.error(t(u?"settings.agents.page.toast.createFailed":"settings.agents.page.toast.updateFailed"))}catch(I){console.error("Error saving agent:",I);const B=I instanceof Error&&I.message?I.message:t("settings.agents.page.toast.saveUnexpectedError");J.error(B)}finally{E(!1)}};return n?s.jsxs(ps,{title:u?t("settings.agents.page.title.new"):n,description:t(u?"settings.agents.page.subtitle.new":"settings.agents.page.subtitle.edit"),showSaveStatus:!1,children:[s.jsxs(dt,{title:t("settings.agents.page.section.identityRole"),divider:!1,contentClassName:"space-y-0",children:[u&&s.jsxs(Xt,{settingsItem:"agents.name",label:t("settings.agents.page.field.agentName"),children:[s.jsxs("div",{className:"flex items-center",children:[s.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),s.jsx(at,{value:f,onChange:T=>m(T.target.value),placeholder:t("settings.agents.page.field.agentNamePlaceholder"),className:"h-7 w-40 px-2"})]}),s.jsxs(Lt,{value:w,onValueChange:T=>b(T),children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[100px]",children:s.jsx(Wt,{placeholder:t("settings.agents.page.field.scopePlaceholder")})}),s.jsxs(Ot,{align:"end",children:[s.jsx(kt,{value:"user",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.global")})]})}),s.jsx(kt,{value:"project",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.project")})]})})]})]})]}),s.jsx(ns,{label:t("settings.common.field.description"),controlClassName:"w-full max-w-none",children:s.jsx(Ns,{value:g,onChange:T=>x(T.target.value),placeholder:t("settings.agents.page.field.descriptionPlaceholder"),rows:2,className:"w-full resize-none min-h-[60px] bg-transparent"})}),s.jsx(ns,{settingsItem:"agents.mode",label:t("settings.agents.page.field.mode"),info:t("settings.agents.page.field.modeTooltip"),children:s.jsx(Ys,{"aria-label":t("settings.agents.page.field.mode"),value:k,onChange:y,options:[{value:"primary",label:t("settings.agents.page.mode.primary")},{value:"subagent",label:t("settings.agents.page.mode.subagent")},{value:"all",label:t("settings.agents.page.mode.all")}]})})]}),s.jsxs(dt,{title:t("settings.agents.page.section.modelParameters"),contentClassName:"space-y-3",children:[s.jsx(Xt,{settingsItem:"agents.model",label:t("settings.agents.page.field.overrideModel"),children:s.jsx(oa,{providerId:Hn(C)?.providerId??"",modelId:Hn(C)?.modelId??"",onChange:(T,I)=>{z(T&&I?`${T}/${I}`:""),N("")},className:$n})}),s.jsx(Xt,{settingsItem:"agents.variant",label:t("settings.agents.page.field.variant"),info:s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{children:t("settings.agents.page.field.variantTooltip")}),s.jsx("p",{children:t("settings.agents.page.field.variantHint")})]}),children:Y?s.jsxs(Lt,{value:Z,onValueChange:T=>N(T==="__default"?"":T),children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{placeholder:t("settings.agents.page.field.variantPlaceholder"),children:T=>T==="__default"?t("chat.modelControls.default"):T})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"__default",children:t("chat.modelControls.default")}),A.map(T=>s.jsx(kt,{value:T,children:T},T))]})]}):s.jsxs(s.Fragment,{children:[s.jsx(at,{value:j,onChange:T=>N(T.target.value),placeholder:t("settings.agents.page.field.variantPlaceholder"),disabled:!C&&!j,className:"h-8 w-40 rounded-md px-3"}),j&&s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>N(""),className:Is,"aria-label":t("settings.common.actions.clear"),title:t("settings.common.actions.clear"),children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]})}),s.jsxs(Xt,{settingsItem:"agents.temperature",label:t("settings.agents.page.field.temperature"),info:s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{children:t("settings.agents.page.field.temperatureTooltip")}),s.jsx("p",{children:t("settings.agents.page.field.temperatureRange")})]}),children:[s.jsx(Rs,{value:v,fallbackValue:.7,onValueChange:P,onClear:()=>P(void 0),min:0,max:2,step:.1,inputMode:"decimal",placeholder:"—",emptyLabel:"—",className:"w-16"}),v!==void 0&&s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>P(void 0),className:Is,"aria-label":t("settings.agents.page.field.clearTemperatureAria"),title:t("settings.common.actions.clear"),children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]}),s.jsxs(Xt,{settingsItem:"agents.top-p",label:t("settings.agents.page.field.topP"),info:s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{children:t("settings.agents.page.field.topPTooltip")}),s.jsx("p",{children:t("settings.agents.page.field.topPRange")})]}),children:[s.jsx(Rs,{value:$,fallbackValue:.9,onValueChange:O,onClear:()=>O(void 0),min:0,max:1,step:.1,inputMode:"decimal",placeholder:"—",emptyLabel:"—",className:"w-16"}),$!==void 0&&s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>O(void 0),className:Is,"aria-label":t("settings.agents.page.field.clearTopPAria"),title:t("settings.common.actions.clear"),children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]})]}),s.jsx(dt,{title:t("settings.agents.page.section.systemPrompt"),settingsItem:"agents.system-prompt",children:s.jsx(Ns,{value:M,onChange:T=>S(T.target.value),placeholder:t("settings.agents.page.field.systemPromptPlaceholder"),rows:8,className:"w-full font-mono typography-meta min-h-[120px] max-h-[60vh] bg-transparent resize-y"})}),!u&&p&&s.jsx(Yx,{agent:p}),s.jsx("div",{className:"pb-8",children:s.jsx(ee,{onClick:te,disabled:F||!X,size:"xs",className:"!font-normal",children:t(F?"settings.common.actions.saving":"settings.common.actions.saveChanges")})})]}):s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"robot-2",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.agents.page.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.agents.page.empty.description")})]})})},Zx="~/.config/opencode/AGENTS.md",Fu=async(t,e)=>{const n=await t.json().catch(()=>null);return typeof n?.error=="string"&&n.error.trim()?n.error:e},eb=t=>t.length>0&&!t.endsWith(`
7
- `)?`${t}
8
- `:t,Oi={prompt:"",optimizeSystemPrompt:!1,responseStyleEnabled:!1,responseStylePreset:"concise",responseStyleCustomInstructions:""},tb=(t,e)=>t==="custom"?e:sp(t),sb=t=>t==="custom"?"custom":Zd(t)?t:"concise",Lc={concise:"settings.behavior.page.responseStyle.option.concise",detailed:"settings.behavior.page.responseStyle.option.detailed",mentor:"settings.behavior.page.responseStyle.option.mentor",pushback:"settings.behavior.page.responseStyle.option.pushback",noFiller:"settings.behavior.page.responseStyle.option.noFiller",matchEnergy:"settings.behavior.page.responseStyle.option.matchEnergy",warmPeer:"settings.behavior.page.responseStyle.option.warmPeer"},to=async(t,e)=>{qs("saving");try{const n=await ht("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(await Fu(n,e));qs("saved")}catch(n){throw qs("error"),n}},nb=()=>{const{t}=lt(),e=ep(),[n,a]=l.useState(""),[i,r]=l.useState(!1),[o,d]=l.useState(Oi.responseStyleEnabled),[c,p]=l.useState(Oi.responseStylePreset),[u,f]=l.useState(Oi.responseStyleCustomInstructions),[m,w]=l.useState(!0),[b,g]=l.useState(!1),[x,k]=l.useState(!1),[y,C]=l.useState(""),[z,j]=l.useState(!1),N=l.useRef(null);l.useEffect(()=>{const S=new AbortController;return(async()=>{try{const[E,D]=await Promise.all([ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"},signal:S.signal}),ht("/api/behavior/agents-md",{method:"GET",headers:{Accept:"application/json"},signal:S.signal})]);let W=Oi;if(E.ok){const H=await E.json();W={...W,optimizeSystemPrompt:H.optimizeSystemPrompt===!0,responseStyleEnabled:H.responseStyleEnabled===!0,responseStylePreset:sb(H.responseStylePreset),responseStyleCustomInstructions:typeof H.responseStyleCustomInstructions=="string"?H.responseStyleCustomInstructions:""},typeof H.globalBehaviorPrompt=="string"&&(W={...W,prompt:H.globalBehaviorPrompt})}if(!W.prompt.trim()&&D.ok){const H=await D.json();typeof H.content=="string"&&(W={...W,prompt:H.content})}a(W.prompt),r(W.optimizeSystemPrompt),j(W.optimizeSystemPrompt),d(W.responseStyleEnabled),p(W.responseStylePreset),f(W.responseStyleCustomInstructions),C(W.prompt),N.current={enabled:W.responseStyleEnabled,preset:W.responseStylePreset,custom:W.responseStyleCustomInstructions}}catch(E){E.name!=="AbortError"&&console.warn("Failed to load behavior settings:",E)}finally{w(!1)}})(),()=>S.abort()},[]),l.useEffect(()=>{if(m)return;const S=N.current;if(S&&S.enabled===o&&S.preset===c&&S.custom===u)return;const F={enabled:o,preset:c,custom:u},E=setTimeout(async()=>{try{await to({responseStyleEnabled:F.enabled,responseStylePreset:F.preset,responseStyleCustomInstructions:F.custom},t("settings.behavior.page.toast.saveFailed")),N.current=F}catch(D){const W=D instanceof Error?D.message:t("settings.behavior.page.toast.saveFailed");J.error(W)}},400);return()=>clearTimeout(E)},[o,c,u,m,t]);const v=tb(c,u),P=n!==y,$=i!==z,O=async()=>{g(!0);try{const S=eb(n),F=await ht("/api/behavior/agents-md",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({content:S})});if(!F.ok)throw new Error(await Fu(F,t("settings.behavior.page.toast.saveFailed")));await to({globalBehaviorPrompt:S},t("settings.behavior.page.toast.saveFailed")),a(S),C(S),J.success(t("settings.behavior.page.toast.saved"))}catch(S){console.error("Failed to save behavior:",S);const F=S instanceof Error?S.message:t("settings.behavior.page.toast.saveFailed");J.error(F)}finally{g(!1)}},M=async()=>{k(!0);try{await to({optimizeSystemPrompt:i},t("settings.behavior.page.toast.saveFailed")),j(i)}catch(S){const F=S instanceof Error?S.message:t("settings.behavior.page.toast.saveFailed");J.error(F),k(!1);return}try{await _n({message:t("settings.behavior.page.systemPromptOptimization.restarting"),mode:"projects",scopes:["all"]})}catch(S){const F=S instanceof Error?S.message:t("settings.behavior.page.toast.saveFailed");J.error(F)}finally{k(!1)}};return s.jsxs(ps,{title:t("settings.behavior.page.title"),description:t("settings.page.behavior.description"),showSaveStatus:!0,children:[!e&&s.jsxs(dt,{title:t("settings.behavior.page.section.systemPromptOptimization"),divider:!1,settingsItem:"behavior.system-prompt-optimization",contentClassName:"space-y-3",children:[s.jsx(Ct,{checked:i,onChange:r,disabled:m||x,label:t("settings.behavior.page.systemPromptOptimization.enable"),ariaLabel:t("settings.behavior.page.systemPromptOptimization.enableAria"),info:t("settings.behavior.page.systemPromptOptimization.info")}),s.jsx(ee,{type:"button",size:"xs",onClick:()=>{M()},disabled:m||x||!$,className:"!font-normal",children:t(x?"settings.common.actions.saving":"settings.openchamber.opencodeCli.actions.saveAndReload")})]}),s.jsxs(dt,{title:t("settings.behavior.page.section.systemPrompt"),info:s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{className:"font-medium text-foreground",children:t("settings.behavior.page.warning.title")}),s.jsx("p",{children:t("settings.behavior.page.warning.description",{path:Zx})})]}),settingsItem:"behavior.system-prompt",contentClassName:"space-y-3",children:[s.jsx(Ns,{value:n,onChange:S=>a(S.target.value),placeholder:t("settings.behavior.page.field.systemPromptPlaceholder"),rows:12,disabled:m,outerClassName:"min-h-[160px] max-h-[70vh]",className:"w-full font-mono typography-meta bg-transparent"}),s.jsx(ee,{onClick:O,disabled:b||!P||m,size:"xs",className:"!font-normal",children:t(b?"settings.common.actions.saving":"settings.common.actions.saveChanges")})]}),s.jsxs(dt,{title:t("settings.behavior.page.section.responseStyle"),info:t("settings.behavior.page.responseStyle.tooltip"),settingsItem:"behavior.response-style",contentClassName:"space-y-3",children:[s.jsx(Ct,{checked:o,onChange:d,disabled:m,label:t("settings.behavior.page.responseStyle.enable"),ariaLabel:t("settings.behavior.page.responseStyle.enableAria")}),s.jsx(Xt,{label:t("settings.behavior.page.responseStyle.preset"),alignEnd:!1,children:s.jsxs(Lt,{value:c,onValueChange:S=>p(S),disabled:m||!o,children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{children:S=>S==="custom"?t("settings.behavior.page.responseStyle.option.custom"):Zd(S)?t(Lc[S]):null})}),s.jsxs(Ot,{children:[tp.map(S=>s.jsx(kt,{value:S,children:t(Lc[S])},S)),s.jsx(kt,{value:"custom",children:t("settings.behavior.page.responseStyle.option.custom")})]})]})}),s.jsx(Ns,{value:v,onChange:S=>f(S.target.value),placeholder:t("settings.behavior.page.responseStyle.customPlaceholder"),rows:5,disabled:m||!o||c!=="custom",outerClassName:"min-h-[120px]",className:"w-full font-mono typography-meta bg-transparent"})]})]})},ab=t=>{const e=tt.c(169),{onItemSelect:n}=t,{t:a}=lt(),[i,r]=l.useState(null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,f]=l.useState(null),[m,w]=l.useState(!1),[b,g]=l.useState(null),{selectedCommandName:x,commands:k,setSelectedCommand:y,setCommandDraft:C,createCommand:z,deleteCommand:j,loadCommands:N}=Sr(Hs(ib)),v=Cn(rb),P=Cn(ob);let $,O;e[0]!==N||e[1]!==P?($=()=>{N(),P()},O=[N,P],e[0]=N,e[1]=P,e[2]=$,e[3]=O):($=e[2],O=e[3]),l.useEffect($,O);let M;e[4]!==v?(M=new Set(v.map(lb)),e[4]=v,e[5]=M):M=e[5];const S=M;let F;if(e[6]!==k||e[7]!==S){let Se;e[9]!==S?(Se=Qe=>!S.has(Qe.name),e[9]=S,e[10]=Se):Se=e[10],F=k.filter(Se),e[6]=k,e[7]=S,e[8]=F}else F=e[8];const E=F;let D,W;e[11]!==x||e[12]!==y||e[13]!==S?(D=()=>{x&&S.has(x)&&y(null)},W=[x,y,S],e[11]=x,e[12]=y,e[13]=S,e[14]=D,e[15]=W):(D=e[14],W=e[15]),l.useEffect(D,W);let H;e[16]!==k||e[17]!==n||e[18]!==C||e[19]!==y?(H=()=>{let Se="new-command",Qe=1;for(;k.some(nt=>nt.name===Se);)Se=`new-command-${Qe}`,Qe++;C({name:Se,scope:"user"}),y(Se),n?.()},e[16]=k,e[17]=n,e[18]=C,e[19]=y,e[20]=H):H=e[20];const Z=H;let Y;e[21]!==a?(Y=async Se=>{if(Ka(Se)){J.error(a("settings.commands.sidebar.toast.builtInCannotDelete"));return}p(Se),f("delete")},e[21]=a,e[22]=Y):Y=e[22];const A=Y;let X;e[23]===Symbol.for("react.memo_cache_sentinel")?(X=async Se=>{Ka(Se)&&(p(Se),f("reset"))},e[23]=X):X=e[23];const te=X;let T;e[24]===Symbol.for("react.memo_cache_sentinel")?(T=()=>{p(null),f(null)},e[24]=T):T=e[24];const I=T;let B;e[25]!==c||e[26]!==u||e[27]!==j||e[28]!==a?(B=async()=>{if(!c||!u)return;w(!0),await j(c.name)?(u==="delete"?J.success(a("settings.commands.sidebar.toast.commandDeleted",{name:c.name})):J.success(a("settings.commands.sidebar.toast.commandReset",{name:c.name})),I()):u==="delete"?J.error(a("settings.commands.sidebar.toast.deleteFailed")):J.error(a("settings.commands.sidebar.toast.resetFailed")),w(!1)},e[25]=c,e[26]=u,e[27]=j,e[28]=a,e[29]=B):B=e[29];const L=B;let V;e[30]!==k||e[31]!==C||e[32]!==y?(V=Se=>{const Qe=Se.name;let nt=1,rt=`${Qe}-copy`;for(;k.some(gt=>gt.name===rt);)nt++,rt=`${Qe}-copy-${nt}`;C({name:rt,scope:Se.scope||"user",description:Se.description,template:Se.template,agent:Se.agent,model:Se.model}),y(rt)},e[30]=k,e[31]=C,e[32]=y,e[33]=V):V=e[33];const Q=V;let G;e[34]===Symbol.for("react.memo_cache_sentinel")?(G=Se=>{d(Se.name),r(Se)},e[34]=G):G=e[34];const ue=G;let ne;e[35]!==k||e[36]!==z||e[37]!==j||e[38]!==i||e[39]!==o||e[40]!==y||e[41]!==a?(ne=async()=>{if(!i)return;const Se=o.trim().replace(/\s+/g,"-");if(!Se){J.error(a("settings.commands.sidebar.toast.commandNameRequired"));return}if(Se===i.name){r(null);return}if(k.some(nt=>nt.name===Se)){J.error(a("settings.commands.sidebar.toast.commandExists"));return}await z({name:Se,description:i.description,template:i.template,agent:i.agent,model:i.model})?await j(i.name)?(J.success(`Command renamed to "${Se}"`),y(Se)):J.error(a("settings.commands.sidebar.toast.removeOldAfterRenameFailed")):J.error(a("settings.commands.sidebar.toast.renameFailed")),r(null)},e[35]=k,e[36]=z,e[37]=j,e[38]=i,e[39]=o,e[40]=y,e[41]=a,e[42]=ne):ne=e[42];const xe=ne;let ve,me,ge,Ie,oe,ce;if(e[43]!==E||e[44]!==Z||e[45]!==A||e[46]!==Q||e[47]!==n||e[48]!==b||e[49]!==x||e[50]!==y||e[51]!==a){const Se=E.filter(Ka),Qe=E.filter(cb);e[58]===Symbol.for("react.memo_cache_sentinel")?(oe=fe("flex h-full flex-col","bg-background"),e[58]=oe):oe=e[58];let nt;e[59]!==a?(nt=a("settings.commands.sidebar.title"),e[59]=a,e[60]=nt):nt=e[60];let rt;e[61]!==nt?(rt=s.jsx("h2",{className:`${fn} mb-3`,children:nt}),e[61]=nt,e[62]=rt):rt=e[62];let gt;e[63]===Symbol.for("react.memo_cache_sentinel")?(gt=s.jsx(yi,{className:"mb-3"}),e[63]=gt):gt=e[63];let wt;e[64]!==E.length||e[65]!==a?(wt=a("settings.commands.sidebar.total",{count:E.length}),e[64]=E.length,e[65]=a,e[66]=wt):wt=e[66];let Pe;e[67]!==wt?(Pe=s.jsx("span",{className:"typography-meta text-muted-foreground",children:wt}),e[67]=wt,e[68]=Pe):Pe=e[68];let se;e[69]===Symbol.for("react.memo_cache_sentinel")?(se=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[69]=se):se=e[69];let Ce;e[70]!==Z?(Ce=s.jsx(ee,{size:"sm","data-settings-item":"commands.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:Z,children:se}),e[70]=Z,e[71]=Ce):Ce=e[71];let Xe;e[72]!==Pe||e[73]!==Ce?(Xe=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Pe,Ce]}),e[72]=Pe,e[73]=Ce,e[74]=Xe):Xe=e[74],e[75]!==rt||e[76]!==Xe?(ce=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[rt,gt,Xe]}),e[75]=rt,e[76]=Xe,e[77]=ce):ce=e[77],ve=Os,me="flex-1 min-h-0",ge="space-y-1 px-3 py-2",Ie=E.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"terminal-box",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:a("settings.commands.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:a("settings.commands.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[Se.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.commands.sidebar.section.builtIn")}),[...Se].sort(db).map(Re=>s.jsx(Fc,{command:Re,isSelected:x===Re.name,onSelect:()=>{y(Re.name),n?.()},onReset:()=>te(Re),onDuplicate:()=>Q(Re),isMenuOpen:b===Re.name,onMenuOpenChange:Je=>g(Je?Re.name:null)},Re.name))]}),Qe.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.commands.sidebar.section.custom")}),[...Qe].sort(ub).map(Re=>s.jsx(Fc,{command:Re,isSelected:x===Re.name,onSelect:()=>{y(Re.name),n?.()},onRename:()=>ue(Re),onDelete:()=>A(Re),onDuplicate:()=>Q(Re),isMenuOpen:b===Re.name,onMenuOpenChange:Je=>g(Je?Re.name:null)},Re.name))]})]}),e[43]=E,e[44]=Z,e[45]=A,e[46]=Q,e[47]=n,e[48]=b,e[49]=x,e[50]=y,e[51]=a,e[52]=ve,e[53]=me,e[54]=ge,e[55]=Ie,e[56]=oe,e[57]=ce}else ve=e[52],me=e[53],ge=e[54],Ie=e[55],oe=e[56],ce=e[57];let pe;e[78]!==ve||e[79]!==me||e[80]!==ge||e[81]!==Ie?(pe=s.jsx(ve,{outerClassName:me,className:ge,children:Ie}),e[78]=ve,e[79]=me,e[80]=ge,e[81]=Ie,e[82]=pe):pe=e[82];const ie=c!==null&&u!==null;let le;e[83]!==m?(le=Se=>{!Se&&!m&&I()},e[83]=m,e[84]=le):le=e[84];let de;e[85]!==u||e[86]!==a?(de=a(u==="delete"?"settings.commands.sidebar.dialog.deleteTitle":"settings.commands.sidebar.dialog.resetTitle"),e[85]=u,e[86]=a,e[87]=de):de=e[87];let he;e[88]!==de?(he=s.jsx(_t,{children:de}),e[88]=de,e[89]=he):he=e[89];let Me;e[90]!==c?.name||e[91]!==u||e[92]!==a?(Me=u==="delete"?a("settings.commands.sidebar.dialog.deleteDescription",{name:c?.name??""}):a("settings.commands.sidebar.dialog.resetDescription",{name:c?.name??""}),e[90]=c?.name,e[91]=u,e[92]=a,e[93]=Me):Me=e[93];let Le;e[94]!==Me?(Le=s.jsx(Yt,{children:Me}),e[94]=Me,e[95]=Le):Le=e[95];let Be;e[96]!==he||e[97]!==Le?(Be=s.jsxs(Ut,{children:[he,Le]}),e[96]=he,e[97]=Le,e[98]=Be):Be=e[98];let Fe;e[99]!==a?(Fe=a("settings.common.actions.cancel"),e[99]=a,e[100]=Fe):Fe=e[100];let De;e[101]!==m||e[102]!==Fe?(De=s.jsx(ee,{size:"sm",variant:"ghost",onClick:I,disabled:m,children:Fe}),e[101]=m,e[102]=Fe,e[103]=De):De=e[103];let ze;e[104]!==u||e[105]!==a?(ze=a(u==="delete"?"settings.common.actions.delete":"settings.common.actions.reset"),e[104]=u,e[105]=a,e[106]=ze):ze=e[106];let Ve;e[107]!==L||e[108]!==m||e[109]!==ze?(Ve=s.jsx(ee,{size:"sm",onClick:L,disabled:m,children:ze}),e[107]=L,e[108]=m,e[109]=ze,e[110]=Ve):Ve=e[110];let We;e[111]!==De||e[112]!==Ve?(We=s.jsxs(rs,{children:[De,Ve]}),e[111]=De,e[112]=Ve,e[113]=We):We=e[113];let _e;e[114]!==Be||e[115]!==We?(_e=s.jsxs(Bt,{className:"max-w-md",children:[Be,We]}),e[114]=Be,e[115]=We,e[116]=_e):_e=e[116];let He;e[117]!==ie||e[118]!==le||e[119]!==_e?(He=s.jsx(Kt,{open:ie,onOpenChange:le,children:_e}),e[117]=ie,e[118]=le,e[119]=_e,e[120]=He):He=e[120];const Ke=i!==null;let Oe;e[121]===Symbol.for("react.memo_cache_sentinel")?(Oe=Se=>!Se&&r(null),e[121]=Oe):Oe=e[121];let je;e[122]!==a?(je=a("settings.commands.sidebar.renameDialog.title"),e[122]=a,e[123]=je):je=e[123];let Te;e[124]!==je?(Te=s.jsx(_t,{children:je}),e[124]=je,e[125]=Te):Te=e[125];const Ue=i?.name??"";let Ye;e[126]!==a||e[127]!==Ue?(Ye=a("settings.commands.sidebar.renameDialog.description",{name:Ue}),e[126]=a,e[127]=Ue,e[128]=Ye):Ye=e[128];let q;e[129]!==Ye?(q=s.jsx(Yt,{children:Ye}),e[129]=Ye,e[130]=q):q=e[130];let re;e[131]!==Te||e[132]!==q?(re=s.jsxs(Ut,{children:[Te,q]}),e[131]=Te,e[132]=q,e[133]=re):re=e[133];let U;e[134]===Symbol.for("react.memo_cache_sentinel")?(U=Se=>d(Se.target.value),e[134]=U):U=e[134];let h;e[135]!==a?(h=a("settings.commands.sidebar.renameDialog.placeholder"),e[135]=a,e[136]=h):h=e[136];let ae;e[137]!==xe?(ae=Se=>{Se.key==="Enter"&&xe()},e[137]=xe,e[138]=ae):ae=e[138];let ye;e[139]!==o||e[140]!==h||e[141]!==ae?(ye=s.jsx(at,{value:o,onChange:U,placeholder:h,className:"text-foreground placeholder:text-muted-foreground",onKeyDown:ae}),e[139]=o,e[140]=h,e[141]=ae,e[142]=ye):ye=e[142];let be;e[143]===Symbol.for("react.memo_cache_sentinel")?(be=()=>r(null),e[143]=be):be=e[143];let Ee;e[144]!==a?(Ee=a("settings.common.actions.cancel"),e[144]=a,e[145]=Ee):Ee=e[145];let et;e[146]!==Ee?(et=s.jsx(ee,{size:"sm",variant:"ghost",onClick:be,children:Ee}),e[146]=Ee,e[147]=et):et=e[147];let Ze;e[148]!==a?(Ze=a("settings.common.actions.rename"),e[148]=a,e[149]=Ze):Ze=e[149];let it;e[150]!==xe||e[151]!==Ze?(it=s.jsx(ee,{size:"sm",onClick:xe,children:Ze}),e[150]=xe,e[151]=Ze,e[152]=it):it=e[152];let ot;e[153]!==et||e[154]!==it?(ot=s.jsxs(rs,{children:[et,it]}),e[153]=et,e[154]=it,e[155]=ot):ot=e[155];let xt;e[156]!==re||e[157]!==ye||e[158]!==ot?(xt=s.jsxs(Bt,{children:[re,ye,ot]}),e[156]=re,e[157]=ye,e[158]=ot,e[159]=xt):xt=e[159];let bt;e[160]!==Ke||e[161]!==xt?(bt=s.jsx(Kt,{open:Ke,onOpenChange:Oe,children:xt}),e[160]=Ke,e[161]=xt,e[162]=bt):bt=e[162];let Nt;return e[163]!==oe||e[164]!==ce||e[165]!==pe||e[166]!==He||e[167]!==bt?(Nt=s.jsxs("div",{className:oe,children:[ce,pe,He,bt]}),e[163]=oe,e[164]=ce,e[165]=pe,e[166]=He,e[167]=bt,e[168]=Nt):Nt=e[168],Nt},Fc=t=>{const e=tt.c(47),{command:n,isSelected:a,onSelect:i,onDelete:r,onReset:o,onRename:d,onDuplicate:c,isMenuOpen:p,onMenuOpenChange:u}=t,{t:f}=lt();let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m=hi(),e[0]=m):m=e[0];const w=m,[b,g]=l.useState(!1);let x;e[1]!==r||e[2]!==c||e[3]!==d||e[4]!==o||e[5]!==f?(x=Y=>s.jsxs(s.Fragment,{children:[d&&s.jsxs(Y,{onClick:A=>{A.stopPropagation(),d()},children:[s.jsx(K,{name:"edit",className:"h-4 w-4 mr-px"}),f("settings.common.actions.rename")]}),s.jsxs(Y,{onClick:A=>{A.stopPropagation(),c()},children:[s.jsx(K,{name:"file-copy",className:"h-4 w-4 mr-px"}),f("settings.common.actions.duplicate")]}),o&&s.jsxs(Y,{onClick:A=>{A.stopPropagation(),o()},children:[s.jsx(K,{name:"restart",className:"h-4 w-4 mr-px"}),f("settings.common.actions.reset")]}),r&&s.jsxs(Y,{onClick:A=>{A.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),f("settings.common.actions.delete")]})]}),e[1]=r,e[2]=c,e[3]=d,e[4]=o,e[5]=f,e[6]=x):x=e[6];const k=x,y=a?"bg-interactive-selection":"hover:bg-interactive-hover";let C;e[7]!==y?(C=fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",y),e[7]=y,e[8]=C):C=e[8];let z;e[9]===Symbol.for("react.memo_cache_sentinel")?(z=w?void 0:Y=>{Y.preventDefault(),g(!0)},e[9]=z):z=e[9];let j;e[10]!==C?(j=s.jsx("div",{className:C,onContextMenu:z}),e[10]=C,e[11]=j):j=e[11];let N;e[12]!==n.name?(N=s.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",n.name]}),e[12]=n.name,e[13]=N):N=e[13];let v;e[14]!==n||e[15]!==f?(v=(n.scope||Ka(n))&&s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:Ka(n)?f("settings.agents.sidebar.badge.system"):n.scope}),e[14]=n,e[15]=f,e[16]=v):v=e[16];let P;e[17]!==N||e[18]!==v?(P=s.jsxs("div",{className:"flex items-center gap-2",children:[N,v]}),e[17]=N,e[18]=v,e[19]=P):P=e[19];let $;e[20]!==n.description?($=n.description&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n.description}),e[20]=n.description,e[21]=$):$=e[21];let O;e[22]!==i||e[23]!==$||e[24]!==P?(O=s.jsxs("button",{onClick:i,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[P,$]}),e[22]=i,e[23]=$,e[24]=P,e[25]=O):O=e[25];let M;e[26]!==u?(M=Y=>{Y&&g(!1),u(Y)},e[26]=u,e[27]=M):M=e[27];let S;e[28]===Symbol.for("react.memo_cache_sentinel")?(S=s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"sm",variant:"ghost",className:"h-6 w-6 px-0 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[28]=S):S=e[28];let F;e[29]!==k?(F=s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:k(as)}),e[29]=k,e[30]=F):F=e[30];let E;e[31]!==p||e[32]!==M||e[33]!==F?(E=s.jsxs(fs,{open:p,onOpenChange:M,children:[S,F]}),e[31]=p,e[32]=M,e[33]=F,e[34]=E):E=e[34];let D;e[35]!==O||e[36]!==E?(D=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[O,E]}),e[35]=O,e[36]=E,e[37]=D):D=e[37];let W;e[38]!==D||e[39]!==j?(W=s.jsx(Gn,{render:j,children:D}),e[38]=D,e[39]=j,e[40]=W):W=e[40];let H;e[41]!==k?(H=s.jsx(qn,{className:"w-fit min-w-20",children:k(An)}),e[41]=k,e[42]=H):H=e[42];let Z;return e[43]!==b||e[44]!==W||e[45]!==H?(Z=s.jsxs(Wn,{open:b,onOpenChange:g,children:[W,H]}),e[43]=b,e[44]=W,e[45]=H,e[46]=Z):Z=e[46],Z};function ib(t){return{selectedCommandName:t.selectedCommandName,commands:t.commands,setSelectedCommand:t.setSelectedCommand,setCommandDraft:t.setCommandDraft,createCommand:t.createCommand,deleteCommand:t.deleteCommand,loadCommands:t.loadCommands}}function rb(t){return t.skills}function ob(t){return t.loadSkills}function lb(t){return t.name}function cb(t){return!Ka(t)}function db(t,e){return t.name.localeCompare(e.name)}function ub(t,e){return t.name.localeCompare(e.name)}const mb=()=>{const{t}=lt(),{selectedCommandName:e,getCommandByName:n,createCommand:a,updateCommand:i,commands:r,commandDraft:o,setCommandDraft:d}=Sr(Hs(M=>({selectedCommandName:M.selectedCommandName,getCommandByName:M.getCommandByName,createCommand:M.createCommand,updateCommand:M.updateCommand,commands:M.commands,commandDraft:M.commandDraft,setCommandDraft:M.setCommandDraft}))),c=e?n(e):null,p=!!(o&&o.name===e&&!c),[u,f]=l.useState(""),[m,w]=l.useState("user"),[b,g]=l.useState(""),[x,k]=l.useState(""),[y,C]=l.useState(""),[z,j]=l.useState(""),[N,v]=l.useState(!1),P=l.useRef(null);l.useEffect(()=>{if(p&&o){const M=o.name||"",S=o.scope||"user",F=o.description||"",E=o.agent||"",D=o.model||"",W=o.template||"";f(M),w(S),g(F),k(E),C(D),j(W),P.current={draftName:M,draftScope:S,description:F,agent:E,model:D,template:W}}else if(c){const M=c.description||"",S=c.agent||"",F=c.model||"",E=c.template||"";g(M),k(S),C(F),j(E),P.current={draftName:"",draftScope:"user",description:M,agent:S,model:F,template:E}}},[c,p,e,r,o]);const $=l.useMemo(()=>{const M=P.current;return M?!!(p&&(u!==M.draftName||m!==M.draftScope)||b!==M.description||x!==M.agent||y!==M.model||z!==M.template):!1},[x,b,u,m,p,y,z]),O=async()=>{const M=p?u.trim().replace(/\s+/g,"-"):e?.trim();if(!M){J.error(t("settings.commands.sidebar.toast.commandNameRequired"));return}if(!z.trim()){J.error(t("settings.commands.page.toast.templateRequired"));return}if(p&&r.some(S=>S.name===M)){J.error(t("settings.commands.sidebar.toast.commandExists"));return}v(!0);try{const S=x.trim(),F=y.trim(),E=z.trim(),D={name:M,description:b.trim()||void 0,agent:S===""?null:S,model:F===""?null:F,template:E,scope:p?m:void 0};let W;p?(W=await a(D),W&&d(null)):W=await i(M,D),W?J.success(t(p?"settings.commands.page.toast.created":"settings.commands.page.toast.updated")):J.error(t(p?"settings.commands.page.toast.createFailed":"settings.commands.page.toast.updateFailed"))}catch(S){console.error("Error saving command:",S),J.error(t("settings.commands.page.toast.saveUnexpectedError"))}finally{v(!1)}};return e?s.jsxs(ps,{title:p?t("settings.commands.page.title.new"):`/${e}`,description:t(p?"settings.commands.page.subtitle.new":"settings.commands.page.subtitle.edit"),showSaveStatus:!1,children:[s.jsxs(dt,{title:t("settings.commands.page.section.identity"),divider:!1,contentClassName:"space-y-0",children:[p&&s.jsxs(Xt,{settingsItem:"commands.name",label:t("settings.commands.page.field.commandName"),children:[s.jsxs("div",{className:"flex items-center",children:[s.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),s.jsx(at,{value:u,onChange:M=>f(M.target.value),placeholder:t("settings.commands.page.field.commandNamePlaceholder"),className:"h-7 w-40 px-2"})]}),s.jsxs(Lt,{value:m,onValueChange:M=>w(M),children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[100px]",children:s.jsx(Wt,{placeholder:t("settings.agents.page.field.scopePlaceholder")})}),s.jsxs(Ot,{align:"end",children:[s.jsx(kt,{value:"user",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.global")})]})}),s.jsx(kt,{value:"project",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.project")})]})})]})]})]}),s.jsxs("div",{className:"py-1.5",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:t("settings.common.field.description")}),s.jsx("div",{className:"mt-1.5",children:s.jsx(Ns,{value:b,onChange:M=>g(M.target.value),placeholder:t("settings.commands.page.field.descriptionPlaceholder"),rows:2,className:"w-full resize-none min-h-[60px] bg-transparent"})})]})]}),s.jsxs(dt,{title:t("settings.commands.page.section.executionContext"),contentClassName:"space-y-0",children:[s.jsx(Xt,{settingsItem:"commands.agent",label:t("settings.commands.page.field.overrideAgent"),children:s.jsx(rl,{agentName:x,onChange:M=>k(M),className:$n})}),s.jsx(Xt,{settingsItem:"commands.model",label:t("settings.agents.page.field.overrideModel"),children:s.jsx(oa,{providerId:Hn(y)?.providerId??"",modelId:Hn(y)?.modelId??"",onChange:(M,S)=>{C(M&&S?`${M}/${S}`:"")},className:$n})})]}),s.jsxs(dt,{title:t("settings.commands.page.section.template"),settingsItem:"commands.template",children:[s.jsx(Ns,{value:z,onChange:M=>j(M.target.value),placeholder:t("settings.commands.page.field.templatePlaceholder"),rows:12,className:"w-full font-mono typography-meta min-h-[160px] max-h-[60vh] bg-transparent resize-y"}),s.jsxs("p",{className:"mt-2 typography-meta text-muted-foreground",children:[s.jsx("code",{className:"text-foreground",children:"$ARGUMENTS"})," ",t("settings.commands.page.templateHint.userInput")," ·"," ",s.jsx("code",{className:"text-foreground",children:"!`cmd`"})," ",t("settings.commands.page.templateHint.shellOutput")," ·"," ",s.jsx("code",{className:"text-foreground",children:"@file"})," ",t("settings.commands.page.templateHint.fileContents")]}),s.jsx("div",{className:"pt-3",children:s.jsx(ee,{onClick:O,disabled:N||!$,size:"xs",className:"!font-normal",children:t(N?"settings.common.actions.saving":"settings.common.actions.saveChanges")})})]})]}):s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"terminal-box",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.commands.page.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.commands.page.empty.description")})]})})},pb={},gb={},jn=t=>{if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const n=e.replace(/\\/g,"/");return n.length>1?n.replace(/\/+$/,""):n},Ia=t=>jn(t)??"__global__",sa=t=>{const e=jn(t);return e?Ps.getScopedApiClient(e):Ps.getApiClient()},ws=gn()(qa((t,e)=>({byDirectory:{},diagnosticsByDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:n=>{const a=Ia(n??Cs.getState().currentDirectory);return e().byDirectory[a]??pb},getDiagnosticForDirectory:n=>{const a=Ia(n??Cs.getState().currentDirectory);return e().diagnosticsByDirectory[a]??gb},getErrorForDirectory:n=>{const a=Ia(n??Cs.getState().currentDirectory);return e().lastErrorKeys[a]??null},refresh:async n=>{const a=jn(n?.directory??Cs.getState().currentDirectory),i=Ia(a);n?.silent||t(r=>({loadingKeys:{...r.loadingKeys,[i]:!0},lastErrorKeys:{...r.lastErrorKeys,[i]:null}}));try{const d=(await sa(a).mcp.status()).data??{};t(c=>({byDirectory:{...c.byDirectory,[i]:d},diagnosticsByDirectory:{...c.diagnosticsByDirectory,[i]:Object.fromEntries(Object.entries(c.diagnosticsByDirectory[i]??{}).filter(([p])=>!d[p]))},loadingKeys:{...c.loadingKeys,[i]:!1},lastErrorKeys:{...c.lastErrorKeys,[i]:null}}))}catch(r){const o=r instanceof Error?r.message:"Failed to load MCP status";t(d=>({loadingKeys:{...d.loadingKeys,[i]:!1},lastErrorKeys:{...d.lastErrorKeys,[i]:o}}))}},connect:async(n,a)=>{const i=jn(a??Cs.getState().currentDirectory),r=Ia(i),o=sa(i);try{await o.mcp.connect({name:n},{throwOnError:!0})}catch(d){const c=d instanceof Error?d.message:"Connection failed";throw t(p=>({diagnosticsByDirectory:{...p.diagnosticsByDirectory,[r]:{...p.diagnosticsByDirectory[r]??{},[n]:{status:"failed",error:c}}}})),d}await e().refresh({directory:i,silent:!0})},disconnect:async(n,a)=>{const i=jn(a??Cs.getState().currentDirectory);await sa(i).mcp.disconnect({name:n},{throwOnError:!0}),await e().refresh({directory:i,silent:!0})},startAuth:async(n,a)=>{const i=jn(a??Cs.getState().currentDirectory),d=(await sa(i).mcp.auth.start({name:n},{throwOnError:!0})).data?.authorizationUrl;if(!d)throw new Error("Authorization URL was not returned");return d},completeAuth:async(n,a,i)=>{const r=jn(i??Cs.getState().currentDirectory);await sa(r).mcp.auth.callback({name:n,code:a},{throwOnError:!0}),await e().refresh({directory:r,silent:!0})},clearAuth:async(n,a)=>{const i=jn(a??Cs.getState().currentDirectory);await sa(i).mcp.auth.remove({name:n},{throwOnError:!0}),await e().refresh({directory:i,silent:!0})},testConnection:async(n,a)=>{const i=jn(a??Cs.getState().currentDirectory),r=Ia(i),o=sa(i),c=e().getStatusForDirectory(i)[n]?.status==="connected";let p,u;try{await o.mcp.connect({name:n},{throwOnError:!0})}catch(w){p=w instanceof Error?w.message:"Connection failed",t(b=>({diagnosticsByDirectory:{...b.diagnosticsByDirectory,[r]:{...b.diagnosticsByDirectory[r]??{},[n]:{status:"failed",error:p??"Connection failed"}}}}))}await e().refresh({directory:i,silent:!0});const f=e().getStatusForDirectory(i)[n],m=f;if(!c&&f?.status==="connected"){try{await o.mcp.disconnect({name:n},{throwOnError:!0})}catch(w){u=`Connection test succeeded, but cleanup disconnect failed: ${w instanceof Error?w.message:"Disconnect failed"}`}await e().refresh({directory:i,silent:!0})}return{status:m??e().getStatusForDirectory(i)[n],error:p,warning:u}}}))),Oc=t=>{switch(t){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"idle"}},zc=t=>{const e=tt.c(5),{tone:n,enabled:a}=t;if(!a){let o;return e[0]===Symbol.for("react.memo_cache_sentinel")?(o=s.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-muted-foreground/30 flex-shrink-0"}),e[0]=o):o=e[0],o}let i;e[1]!==n?(i=fe("inline-block h-2 w-2 rounded-full flex-shrink-0",{success:"bg-[var(--status-success)]",error:"bg-[var(--status-error)]",warning:"bg-[var(--status-warning)]",idle:"bg-muted-foreground/40"}[n]),e[1]=n,e[2]=i):i=e[2];let r;return e[3]!==i?(r=s.jsx("span",{className:i}),e[3]=i,e[4]=r):r=e[4],r},fb=t=>{const e=tt.c(120),{onItemSelect:n}=t,{t:a}=lt(),{mcpServers:i,selectedMcpName:r,setSelectedMcp:o,setMcpDraft:d,loadMcpConfigs:c,deleteMcp:p}=_a(Hs(hb)),u=Cs(xb);let f;e[0]!==u?(f=q=>q.getStatusForDirectory(u??null),e[0]=u,e[1]=f):f=e[1];const m=ws(f),w=ws(bb),b=ws(yb),[g,x]=l.useState(null),[k,y]=l.useState(!1),[C,z]=l.useState(null),[j,N]=l.useState(null),[v,P]=l.useState(!1);let $;e[2]!==i?($=i.filter(vb),e[2]=i,e[3]=$):$=e[3];const O=$;let M;e[4]!==i?(M=i.filter(wb),e[4]=i,e[5]=M):M=e[5];const S=M;let F,E;e[6]!==c?(F=()=>{c()},E=[c],e[6]=c,e[7]=F,e[8]=E):(F=e[7],E=e[8]),l.useEffect(F,E);let D;e[9]!==u||e[10]!==b||e[11]!==v||e[12]!==w?(D=()=>{if(v)return;P(!0);const q=new Promise(jb);Promise.all([w({directory:u,silent:!0}),q]).then(()=>{const re=b(u);re&&J.error(re)}).finally(()=>{P(!1)})},e[9]=u,e[10]=b,e[11]=v,e[12]=w,e[13]=D):D=e[13];const W=D;let H;e[14]!==i||e[15]!==n||e[16]!==d||e[17]!==o?(H=()=>{let q="new-mcp-server",re=1;for(;i.some(h=>h.name===q);)q=`new-mcp-server-${re}`,re++;d({name:q,scope:"user",type:"local",command:[],url:"",environment:[],headers:[],oauthEnabled:!0,oauthClientId:"",oauthClientSecret:"",oauthScope:"",oauthRedirectUri:"",timeout:"",enabled:!0}),o(q),n?.()},e[14]=i,e[15]=n,e[16]=d,e[17]=o,e[18]=H):H=e[18];const Z=H;let Y;e[19]!==p||e[20]!==g||e[21]!==a?(Y=async()=>{if(!g)return;y(!0);const q=await p(g.name);q.ok?q.reloadFailed?J.warning(q.message||`MCP server "${g.name}" deleted, but OpenCode reload failed`,{description:q.warning||a("settings.mcp.sidebar.toast.refreshListIfStale")}):J.success(q.message||a("settings.mcp.sidebar.toast.serverDeleted",{name:g.name})):J.error(a("settings.mcp.sidebar.toast.deleteFailed")),x(null),y(!1)},e[19]=p,e[20]=g,e[21]=a,e[22]=Y):Y=e[22];const A=Y;let X;e[23]!==a?(X=(q,re)=>s.jsxs(re,{onClick:U=>{U.stopPropagation(),x(q)},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),a("settings.common.actions.delete")]}),e[23]=a,e[24]=X):X=e[24];const te=X;let T;e[25]===Symbol.for("react.memo_cache_sentinel")?(T=fe("flex h-full flex-col","bg-background"),e[25]=T):T=e[25];let I;e[26]!==a?(I=a("settings.mcp.sidebar.title"),e[26]=a,e[27]=I):I=e[27];let B;e[28]!==I?(B=s.jsx("h2",{className:fn,children:I}),e[28]=I,e[29]=B):B=e[29];let L;e[30]!==a?(L=a("settings.mcp.sidebar.actions.refreshStatusAria"),e[30]=a,e[31]=L):L=e[31];let V;e[32]!==a?(V=a("settings.mcp.sidebar.actions.refreshStatusTitle"),e[32]=a,e[33]=V):V=e[33];const Q=v&&"animate-spin";let G;e[34]!==Q?(G=fe("h-4 w-4",Q),e[34]=Q,e[35]=G):G=e[35];let ue;e[36]!==G?(ue=s.jsx(K,{name:"refresh",className:G}),e[36]=G,e[37]=ue):ue=e[37];let ne;e[38]!==W||e[39]!==v||e[40]!==L||e[41]!==V||e[42]!==ue?(ne=s.jsx("button",{type:"button",className:"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",disabled:v,onClick:W,"aria-label":L,title:V,children:ue}),e[38]=W,e[39]=v,e[40]=L,e[41]=V,e[42]=ue,e[43]=ne):ne=e[43];let xe;e[44]!==B||e[45]!==ne?(xe=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[B,ne]}),e[44]=B,e[45]=ne,e[46]=xe):xe=e[46];let ve;e[47]===Symbol.for("react.memo_cache_sentinel")?(ve=s.jsx(yi,{className:"mb-3"}),e[47]=ve):ve=e[47];let me;e[48]!==i.length||e[49]!==a?(me=a("settings.mcp.sidebar.total",{count:i.length}),e[48]=i.length,e[49]=a,e[50]=me):me=e[50];let ge;e[51]!==me?(ge=s.jsx("span",{className:"typography-meta text-muted-foreground",children:me}),e[51]=me,e[52]=ge):ge=e[52];let Ie;e[53]!==a?(Ie=a("settings.mcp.sidebar.actions.addServerTitle"),e[53]=a,e[54]=Ie):Ie=e[54];let oe;e[55]===Symbol.for("react.memo_cache_sentinel")?(oe=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[55]=oe):oe=e[55];let ce;e[56]!==Z||e[57]!==Ie?(ce=s.jsx(ee,{size:"sm","data-settings-item":"mcp.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:Z,title:Ie,children:oe}),e[56]=Z,e[57]=Ie,e[58]=ce):ce=e[58];let pe;e[59]!==ge||e[60]!==ce?(pe=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[ge,ce]}),e[59]=ge,e[60]=ce,e[61]=pe):pe=e[61];let ie;e[62]!==xe||e[63]!==pe?(ie=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[xe,ve,pe]}),e[62]=xe,e[63]=pe,e[64]=ie):ie=e[64];let le;e[65]!==i.length||e[66]!==m||e[67]!==n||e[68]!==C||e[69]!==O||e[70]!==te||e[71]!==j||e[72]!==r||e[73]!==d||e[74]!==o||e[75]!==a||e[76]!==S?(le=s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:i.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"plug",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:a("settings.mcp.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:a("settings.mcp.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[O.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.mcp.sidebar.group.projectServers")}),O.map(q=>{const re=m[q.name],U=Oc(re?.status),h=r===q.name,ae=hi();return s.jsxs(Wn,{open:j===q.name,onOpenChange:ye=>N(ye?q.name:null),children:[s.jsxs(Gn,{render:s.jsx("div",{className:fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",h?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:ae?void 0:ye=>{ye.preventDefault(),N(q.name)}}),children:[s.jsxs("button",{onClick:()=>{o(q.name),d(null),n?.()},className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(zc,{tone:U,enabled:q.enabled}),s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:q.name}),s.jsx("span",{title:q.type==="local"?a("settings.mcp.sidebar.serverType.localTitle"):a("settings.mcp.sidebar.serverType.remoteTitle"),children:q.type==="local"?s.jsx(K,{name:"server",className:"h-3 w-3 text-muted-foreground/60 flex-shrink-0"}):s.jsx(K,{name:"global",className:"h-3 w-3 text-muted-foreground/60 flex-shrink-0"})})]}),s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight pl-4",children:q.type==="local"?q.command?.join(" ")??"":q.url??""})]}),s.jsxs(fs,{open:C===q.name,onOpenChange:ye=>{ye&&N(null),z(ye?q.name:null)},children:[s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"xs",variant:"ghost",className:"flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:te(q,as)})]})]}),s.jsx(qn,{className:"w-fit min-w-20",children:te(q,An)})]},q.name)})]}),S.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.mcp.sidebar.group.userServers")}),S.map(q=>{const re=m[q.name],U=Oc(re?.status),h=r===q.name,ae=hi();return s.jsxs(Wn,{open:j===q.name,onOpenChange:ye=>N(ye?q.name:null),children:[s.jsxs(Gn,{render:s.jsx("div",{className:fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",h?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:ae?void 0:ye=>{ye.preventDefault(),N(q.name)}}),children:[s.jsxs("button",{onClick:()=>{o(q.name),d(null),n?.()},className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(zc,{tone:U,enabled:q.enabled}),s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:q.name}),s.jsx("span",{title:q.type==="local"?a("settings.mcp.sidebar.serverType.localTitle"):a("settings.mcp.sidebar.serverType.remoteTitle"),children:q.type==="local"?s.jsx(K,{name:"server",className:"h-3 w-3 text-muted-foreground/60 flex-shrink-0"}):s.jsx(K,{name:"global",className:"h-3 w-3 text-muted-foreground/60 flex-shrink-0"})})]}),s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight pl-4",children:q.type==="local"?q.command?.join(" ")??"":q.url??""})]}),s.jsxs(fs,{open:C===q.name,onOpenChange:ye=>{ye&&N(null),z(ye?q.name:null)},children:[s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"xs",variant:"ghost",className:"flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:te(q,as)})]})]}),s.jsx(qn,{className:"w-fit min-w-20",children:te(q,An)})]},q.name)})]})]})}),e[65]=i.length,e[66]=m,e[67]=n,e[68]=C,e[69]=O,e[70]=te,e[71]=j,e[72]=r,e[73]=d,e[74]=o,e[75]=a,e[76]=S,e[77]=le):le=e[77];const de=g!==null;let he;e[78]!==k?(he=q=>{!q&&!k&&x(null)},e[78]=k,e[79]=he):he=e[79];let Me;e[80]!==a?(Me=a("settings.mcp.sidebar.deleteDialog.title"),e[80]=a,e[81]=Me):Me=e[81];let Le;e[82]!==Me?(Le=s.jsx(_t,{children:Me}),e[82]=Me,e[83]=Le):Le=e[83];const Be=g?.name||"";let Fe;e[84]!==a||e[85]!==Be?(Fe=a("settings.mcp.sidebar.deleteDialog.descriptionPrefix",{name:Be}),e[84]=a,e[85]=Be,e[86]=Fe):Fe=e[86];let De;e[87]===Symbol.for("react.memo_cache_sentinel")?(De=s.jsx("code",{className:"text-foreground",children:"opencode.json"}),e[87]=De):De=e[87];let ze;e[88]!==Fe?(ze=s.jsxs(Yt,{children:[Fe," ",De,"."]}),e[88]=Fe,e[89]=ze):ze=e[89];let Ve;e[90]!==Le||e[91]!==ze?(Ve=s.jsxs(Ut,{children:[Le,ze]}),e[90]=Le,e[91]=ze,e[92]=Ve):Ve=e[92];let We;e[93]===Symbol.for("react.memo_cache_sentinel")?(We=()=>x(null),e[93]=We):We=e[93];let _e;e[94]!==a?(_e=a("settings.common.actions.cancel"),e[94]=a,e[95]=_e):_e=e[95];let He;e[96]!==k||e[97]!==_e?(He=s.jsx(ee,{size:"sm",variant:"ghost",onClick:We,disabled:k,children:_e}),e[96]=k,e[97]=_e,e[98]=He):He=e[98];let Ke;e[99]!==k||e[100]!==a?(Ke=a(k?"settings.mcp.sidebar.actions.deleting":"settings.common.actions.delete"),e[99]=k,e[100]=a,e[101]=Ke):Ke=e[101];let Oe;e[102]!==A||e[103]!==k||e[104]!==Ke?(Oe=s.jsx(ee,{size:"sm",onClick:A,disabled:k,children:Ke}),e[102]=A,e[103]=k,e[104]=Ke,e[105]=Oe):Oe=e[105];let je;e[106]!==He||e[107]!==Oe?(je=s.jsxs(rs,{children:[He,Oe]}),e[106]=He,e[107]=Oe,e[108]=je):je=e[108];let Te;e[109]!==Ve||e[110]!==je?(Te=s.jsxs(Bt,{className:"max-w-md",children:[Ve,je]}),e[109]=Ve,e[110]=je,e[111]=Te):Te=e[111];let Ue;e[112]!==de||e[113]!==he||e[114]!==Te?(Ue=s.jsx(Kt,{open:de,onOpenChange:he,children:Te}),e[112]=de,e[113]=he,e[114]=Te,e[115]=Ue):Ue=e[115];let Ye;return e[116]!==ie||e[117]!==le||e[118]!==Ue?(Ye=s.jsxs("div",{className:T,children:[ie,le,Ue]}),e[116]=ie,e[117]=le,e[118]=Ue,e[119]=Ye):Ye=e[119],Ye};function hb(t){return{mcpServers:t.mcpServers,selectedMcpName:t.selectedMcpName,setSelectedMcp:t.setSelectedMcp,setMcpDraft:t.setMcpDraft,loadMcpConfigs:t.loadMcpConfigs,deleteMcp:t.deleteMcp}}function xb(t){return t.currentDirectory}function bb(t){return t.refresh}function yb(t){return t.getErrorForDirectory}function vb(t){return t.scope==="project"}function wb(t){return t.scope!=="project"}function jb(t){return setTimeout(t,500)}function un(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ni(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function cn(t,e){return e!==void 0?{ok:!1,error:t,parsed:e}:{ok:!1,error:t}}function zi(t,e,n){const a=kb(n),i=typeof n.url=="string"?n.url.trim():"",r=Kc(n,"env","environment"),o=Kc(n,"headers"),d=Nb(n),c=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.clientId??"").trim():"",p=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.clientSecret??"").trim():"",u=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.scope??"").trim():"",f=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.redirectUri??"").trim():"",m=Sb(n),w=Cb(n);return{ok:!0,name:t,type:e,command:a,url:i,environment:r,headers:o,oauthEnabled:d,oauthClientId:c,oauthClientSecret:p,oauthScope:u,oauthRedirectUri:f,timeout:m,enabled:w}}function kb(t){const e=t.command,n=t.args;if(ni(e)&&ni(n))return[...e,...n];if(ni(e))return e;if(typeof e=="string"&&e.trim()){const a=e.trim().split(/\s+/);return ni(n)?[...a,...n]:a}return ni(n)?n:[]}function Kc(t,...e){for(const n of e){const a=t[n];if(!un(a))continue;const i=Object.entries(a).filter(([r,o])=>r&&typeof o=="string");if(i.length>0)return i.map(([r,o])=>({key:r,value:String(o)}))}return[]}function Nb(t){if(t.oauth===!1||t.oauth===null||t.oauth===void 0||!un(t.oauth))return!1;const e=t.oauth;return!!(typeof e.clientId=="string"&&e.clientId.trim()||typeof e.clientSecret=="string"&&e.clientSecret.trim()||typeof e.scope=="string"&&e.scope.trim()||typeof e.redirectUri=="string"&&e.redirectUri.trim())}function Sb(t){const e=t.timeout;if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(Math.floor(e));if(typeof e=="string"&&e.trim()){const n=Number(e);if(Number.isFinite(n)&&n>0)return String(Math.floor(n))}return""}function Cb(t){return"disabled"in t&&t.disabled===!0?!1:"enabled"in t?!!t.enabled:!0}function Ib(t){const e=t.mcpServers;if(un(e)){const a=Object.keys(e);if(a.length===1){const i=a[0],r=e[i];if(un(r))return{name:i,entry:r}}if(a.length>1)return null}const n=Object.keys(t).filter(a=>{const i=t[a];return a!=="mcpServers"&&un(i)});if(n.length===1){const a=n[0],i=t[a];if(Ou(i))return{name:a,entry:i}}return null}function Ou(t){return t.type==="local"||t.type==="remote"||Array.isArray(t.command)||typeof t.url=="string"||Array.isArray(t.args)}function Pb(t,e){let n;try{const d=t.trim();if(!d)return cn("No JSON content provided");n=JSON.parse(d)}catch(d){return cn(d instanceof Error?`Invalid JSON: ${d.message}`:"Invalid JSON")}if(!un(n))return cn("Expected a JSON object, not an array or primitive");const a=n,i=a.mcpServers;if(un(i)){const d=Object.keys(i);if(d.length===0)return cn("mcpServers object is empty",n);if(d.length>1)return cn("Paste one server at a time. Found "+d.length+" servers in mcpServers",n);const c=d[0],p=i[c];return un(p)?zi(c,Ki(p),p):cn("Server entry is not a valid object",n)}const r=a.mcp;if(un(r)){const d=Object.keys(r);if(d.length===0)return cn("mcp object is empty",n);if(d.length>1)return cn("Paste one server at a time. Found "+d.length+" servers in mcp",n);const c=d[0],p=r[c];return un(p)?zi(c,Ki(p),p):cn("Server entry in mcp is not a valid object",n)}const o=Ib(a);if(o)return zi(o.name,Ki(o.entry),o.entry);if(Ou(a)){const d=Ki(a),c=typeof a.name=="string"&&a.name.trim()?a.name.trim():e?.fallbackName;return zi(c,d,a)}return cn("No recognizable MCP server configuration found in JSON",n)}function Ki(t){return t.type==="remote"?"remote":t.type==="local"?"local":typeof t.url=="string"&&t.url.trim()?"remote":(Array.isArray(t.command)||typeof t.command=="string"||Array.isArray(t.args),"local")}function Tb(t,e,n){const a=n?.isNewServer??!1,i=t.name,r=a&&i?i:e.name??"";return{...e,name:r,type:t.type,command:t.type==="local"?t.command:[],url:t.type==="remote"?t.url:"",environment:t.environment,headers:t.type==="remote"?t.headers:[],oauthEnabled:t.type==="remote"?t.oauthEnabled:!1,oauthClientId:t.type==="remote"?t.oauthClientId:"",oauthClientSecret:t.type==="remote"?t.oauthClientSecret:"",oauthScope:t.type==="remote"?t.oauthScope:"",oauthRedirectUri:t.type==="remote"?t.oauthRedirectUri:"",timeout:t.type==="remote"?t.timeout:"",enabled:t.enabled}}const Ab="/mcp/oauth/callback",Eb=t=>{if(typeof window>"u")return null;try{const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=e.length%4===0?"":"=".repeat(4-e.length%4),a=window.atob(e+n),i=Uint8Array.from(a,r=>r.charCodeAt(0));return new TextDecoder().decode(i)}catch{return null}},Db=t=>{const e=Rb(t.get("state"));if(e)return e;const n=t.get("server");if(typeof n!="string"||!n.trim())return null;const a=t.get("directory");return{name:n.trim(),directory:typeof a=="string"&&a.trim()?a.trim():null}},zu=t=>{const e=t.get("state");return typeof e!="string"?null:e.trim()||null},Rb=t=>{if(typeof t!="string"||!t.trim())return null;const e=Eb(t.trim());if(!e)return null;try{const n=JSON.parse(e);return n?.v!==1||typeof n.n!="string"||!n.n.trim()?null:{name:n.n.trim(),directory:typeof n.d=="string"&&n.d.trim()?n.d.trim():null}}catch{return null}};function Mb(t){const e=[];let n="",a=!1,i=!1;for(let r=0;r<t.length;r++){const o=t[r];if(o==="'"&&!i){a=!a;continue}if(o==='"'&&!a){i=!i;continue}if((o===" "||o===" ")&&!a&&!i){n&&(e.push(n),n="");continue}n+=o}return n&&e.push(n),e}function Lb(t){const e=t.trim();if(!e)return{code:null,context:null,stateKey:null};try{const n=new URL(e),a=n.searchParams.get("code");if(typeof a=="string"&&a.trim())return{code:a.trim(),context:Db(n.searchParams),stateKey:zu(n.searchParams)}}catch{}return{code:e,context:null,stateKey:null}}const Fb=({value:t,onChange:e,pasteCommandTitle:n,pasteCommandLabel:a,pasteSuccess:i,clipboardReadFailed:r,preview:o})=>{const[d,c]=l.useState(()=>t.join(`
9
- `)),p=l.useRef(t);l.useEffect(()=>{JSON.stringify(p.current)!==JSON.stringify(t)&&(p.current=t,c(t.join(`
10
- `)))},[t]);const u=m=>{const w=m.split(`
11
- `).filter(b=>b.trim().length>0);e(w)},f=async()=>{try{const w=(await navigator.clipboard.readText()).trim(),b=w.includes(`
12
- `)?w.split(`
13
- `).filter(g=>g.trim()):Mb(w);c(b.join(`
14
- `)),e(b),J.success(i(b.length))}catch{J.error(r)}};return s.jsxs("div",{className:"space-y-2","data-bwignore":"true","data-1p-ignore":"true","data-lpignore":"true",children:[s.jsx("div",{className:"flex items-center justify-end gap-2",children:s.jsxs(ee,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:f,type:"button",title:n,children:[s.jsx(K,{name:"clipboard",className:"h-3 w-3"}),a]})}),s.jsx(Ns,{value:d,onChange:m=>{c(m.target.value),u(m.target.value)},onBlur:()=>{const m=d.split(`
15
- `).map(w=>w.trimEnd()).join(`
16
- `);c(m),u(m)},placeholder:`npx
17
- -y
18
- @modelcontextprotocol/server-postgres
19
- postgresql://user:pass@host/db`,rows:Math.max(4,t.length+1),className:"font-mono typography-meta resize-y min-h-[80px]",spellCheck:!1}),t.length>0&&s.jsxs("details",{className:"group",children:[s.jsx("summary",{className:"typography-micro text-muted-foreground/60 cursor-pointer select-none hover:text-muted-foreground",children:o(t.length)}),s.jsx("div",{className:"mt-1 rounded-md bg-[var(--surface-elevated)] px-3 py-2 overflow-x-auto",children:s.jsx("code",{className:"typography-micro text-foreground/80 whitespace-pre",children:t.map((m,w)=>s.jsxs("span",{className:"block",children:[s.jsxs("span",{className:"text-muted-foreground select-none mr-2",children:["[",w,"]"]}),m]},w))})})]})]})},Ob=t=>t.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),Bc=({value:t,onChange:e,keyTransform:n=Ob,keyPlaceholder:a="API_KEY",keyInputClassName:i="w-36 shrink-0 font-mono typography-meta uppercase",pasteLabel:r="Paste .env",pasteTitle:o="Paste KEY=VALUE lines from clipboard",noPairsFoundError:d,importSuccess:c,clipboardReadFailed:p,keyLabel:u,valueLabel:f,valuePlaceholder:m,hideValueTitle:w,showValueTitle:b,addVariable:g,plainTextWarning:x,removeVariableAria:k})=>{const[y,C]=l.useState(new Set),z=()=>e([...t,{key:"",value:""}]),j=O=>{e(t.filter((M,S)=>S!==O)),C(M=>{const S=new Set(M);return S.delete(O),S})},N=(O,M,S)=>{const F=[...t];F[O]={...F[O],[M]:S},e(F)},v=O=>{C(M=>{const S=new Set(M);return S.has(O)?S.delete(O):S.add(O),S})},P=async()=>{try{const O=await navigator.clipboard.readText(),M=[];for(const F of O.split(`
20
- `)){const E=F.trim();if(!E||E.startsWith("#"))continue;const D=E.indexOf("=");if(D===-1)continue;const W=E.slice(0,D).trim();let H=E.slice(D+1).trim();(H.startsWith('"')&&H.endsWith('"')||H.startsWith("'")&&H.endsWith("'"))&&(H=H.slice(1,-1)),W&&M.push({key:W,value:H})}if(M.length===0){J.error(d);return}const S=[...t];for(const F of M){const E=S.findIndex(D=>D.key===F.key);E!==-1?S[E]=F:S.push(F)}e(S),J.success(c(M.length))}catch{J.error(p)}},$=t.some(O=>O.value.length>0);return 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-3",children:[s.jsx("span",{className:"typography-micro text-muted-foreground w-32 shrink-0",children:u}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:f})]}),s.jsxs(ee,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:P,type:"button",title:o,children:[s.jsx(K,{name:"clipboard",className:"h-3 w-3"}),r]})]}),s.jsx("div",{className:"space-y-1.5",children:t.map((O,M)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(at,{value:O.key,onChange:S=>N(M,"key",n(S.target.value)),placeholder:a,className:i,"data-bwignore":"true","data-1p-ignore":"true","data-lpignore":"true",spellCheck:!1}),s.jsxs("div",{className:"relative flex-1 flex items-center",children:[s.jsx(at,{type:y.has(M)?"text":"password",value:O.value,onChange:S=>N(M,"value",S.target.value),placeholder:m,className:"font-mono typography-meta pr-8 w-full",autoComplete:"new-password","data-bwignore":"true","data-1p-ignore":"true","data-lpignore":"true",spellCheck:!1}),s.jsx("button",{type:"button",onClick:()=>v(M),className:"absolute right-2 text-muted-foreground/60 hover:text-muted-foreground",title:y.has(M)?w:b,children:y.has(M)?s.jsx(K,{name:"eye-off",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"eye",className:"h-3.5 w-3.5"})})]}),s.jsx(ee,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 shrink-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>j(M),"aria-label":k,children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},M))}),s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:z,type:"button",children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),g]}),$&&s.jsx("p",{className:"typography-micro text-muted-foreground/60",children:x})]})},_c=t=>{const e=tt.c(14),{status:n,enabled:a,getStatusLabel:i,variant:r}=t,o=r===void 0?"compact":r;if(!a||!n)return null;let d,c;if(e[0]!==i||e[1]!==n||e[2]!==o){c=Symbol.for("react.early_return_sentinel");e:{const m={connected:{text:"text-[var(--status-success)]",bg:"bg-[var(--status-success)]/10"},failed:{text:"text-[var(--status-error)]",bg:"bg-[var(--status-error)]/10"},needs_auth:{text:"text-[var(--status-warning)]",bg:"bg-[var(--status-warning)]/10"},needs_client_registration:{text:"text-[var(--status-warning)]",bg:"bg-[var(--status-warning)]/10"}}[n]??{text:"text-muted-foreground",bg:""};if(o==="pill"){const w=fe("typography-micro font-medium rounded-full px-2 py-0.5",m.text,m.bg);let b;e[5]!==i||e[6]!==n?(b=i(n),e[5]=i,e[6]=n,e[7]=b):b=e[7],c=s.jsxs("span",{className:w,children:["● ",b]});break e}d=fe("typography-micro font-medium",m.text)}e[0]=i,e[1]=n,e[2]=o,e[3]=d,e[4]=c}else d=e[3],c=e[4];if(c!==Symbol.for("react.early_return_sentinel"))return c;let p;e[8]!==i||e[9]!==n?(p=i(n),e[8]=i,e[9]=n,e[10]=p):p=e[10];let u;return e[11]!==d||e[12]!==p?(u=s.jsxs("span",{className:d,children:["● ",p]}),e[11]=d,e[12]=p,e[13]=u):u=e[13],u},zb=(t,e,n)=>{switch(t){case"connected":return e("settings.mcp.page.status.description.connected");case"failed":return n?.trim()||e("settings.mcp.page.status.description.failedDefault");case"needs_auth":return e("settings.mcp.page.status.description.needsAuth");case"needs_client_registration":return n?.trim()||e("settings.mcp.page.status.description.needsClientRegistrationDefault");case"disabled":return e("settings.mcp.page.status.description.disabled");default:return e("settings.mcp.page.status.description.default")}},Kb=t=>{switch(t){case"failed":return"border-[var(--status-error-border)] bg-[var(--status-error-background)]";case"needs_auth":case"needs_client_registration":return"border-[var(--status-warning-border)] bg-[var(--status-warning-background)]";default:return"border-[var(--interactive-border)] bg-[var(--surface-elevated)]"}},Bb=(t,e,n,a)=>!!(t==="failed"||t==="needs_auth"||t==="needs_client_registration"||e||n||a),Uc=(t,e)=>{if(typeof window>"u")return null;const n=new URL(Ab,Ga()||window.location.origin);return typeof t=="string"&&t.trim()&&n.searchParams.set("server",t.trim()),typeof e=="string"&&e.trim()&&n.searchParams.set("directory",e.trim()),n.toString()},_b=async t=>{const e=await ht("/api/mcp/auth/pending",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:t.state,name:t.name,directory:typeof t.directory=="string"&&t.directory.trim()?t.directory.trim():null})});if(!e.ok){const n=await e.json().catch(()=>null);throw new Error(n?.error||"Failed to prepare MCP authorization callback")}},Ub=async t=>{const e=await ht(`/api/mcp/auth/pending?state=${encodeURIComponent(t)}`);if(!e.ok)return null;const n=await e.json().catch(()=>null);return n?.name?.trim()?{name:n.name.trim(),directory:typeof n.directory=="string"&&n.directory.trim()?n.directory.trim():null}:null},ai=async t=>{typeof t!="string"||!t.trim()||await ht(`/api/mcp/auth/pending?state=${encodeURIComponent(t.trim())}`,{method:"DELETE"}).catch(()=>{})},so=(t,e,n)=>{const a=t instanceof Error?t.message:e;return/oauth state required/i.test(a)?n("settings.mcp.page.toast.authSessionExpired"):a},$b=(t,e)=>{const n=typeof e=="string"&&e.trim()?e.trim():"__global__";return`${t??"__none__"}::${n}`},Vb=()=>{const{t}=lt(),e=l.useCallback((Ne,ut)=>t(Ne,ut),[t]),{selectedMcpName:n,mcpServers:a,mcpDraft:i,setMcpDraft:r,setSelectedMcp:o,getMcpByName:d,createMcp:c,updateMcp:p,deleteMcp:u}=_a(Hs(Ne=>({selectedMcpName:Ne.selectedMcpName,mcpServers:Ne.mcpServers,mcpDraft:Ne.mcpDraft,setMcpDraft:Ne.setMcpDraft,setSelectedMcp:Ne.setSelectedMcp,getMcpByName:Ne.getMcpByName,createMcp:Ne.createMcp,updateMcp:Ne.updateMcp,deleteMcp:Ne.deleteMcp}))),f=Cs(Ne=>Ne.currentDirectory),m=l.useMemo(()=>ds(),[]),w=ws(Ne=>Ne.getStatusForDirectory(f??null)),b=ws(Ne=>Ne.getDiagnosticForDirectory(f??null)),g=ws(Ne=>Ne.refresh),x=ws(Ne=>Ne.connect),k=ws(Ne=>Ne.disconnect),y=ws(Ne=>Ne.startAuth),C=ws(Ne=>Ne.completeAuth),z=ws(Ne=>Ne.clearAuth),j=ws(Ne=>Ne.testConnection),N=n?d(n):null,v=!!(i&&i.name===n&&!N),[P,$]=l.useState(""),[O,M]=l.useState("user"),[S,F]=l.useState("local"),[E,D]=l.useState([]),[W,H]=l.useState(""),[Z,Y]=l.useState([]),[A,X]=l.useState([]),[te,T]=l.useState(!0),[I,B]=l.useState(""),[L,V]=l.useState(""),[Q,G]=l.useState(""),[ue,ne]=l.useState(""),[xe,ve]=l.useState(""),[me,ge]=l.useState(!0),[Ie,oe]=l.useState(!1),[ce,pe]=l.useState(!1),[ie,le]=l.useState(!1),[de,he]=l.useState(!1),[Me,Le]=l.useState(!1),[Be,Fe]=l.useState(!1),[De,ze]=l.useState(!1),[Ve,We]=l.useState(!1),[_e,He]=l.useState(null),[Ke,Oe]=l.useState(null),[je,Te]=l.useState(""),[Ue,Ye]=l.useState(!1),q=l.useRef(0),re=l.useRef(!1),[U,h]=l.useState(!1),[ae,ye]=l.useState(!1),[be,Ee]=l.useState(""),[et,Ze]=l.useState(null),it=l.useMemo(()=>$b(n,f),[f,n]),ot=l.useRef(it),xt=l.useRef(null),bt=l.useCallback(()=>{He(null),Oe(null),Te(""),Ye(!1),q.current=0,We(!1),Le(!1),Fe(!1),re.current=!1},[]),Nt=l.useCallback(()=>{Ee(""),Ze(null),ye(!0)},[]),Se=l.useCallback(async()=>{try{const Ne=await navigator.clipboard.readText();Ee(Ne),Ze(null)}catch{J.error(t("settings.mcp.page.toast.clipboardReadFailed"))}},[t]),Qe=l.useCallback(()=>{const Ne=Pb(be,{fallbackName:P});if(!Ne.ok){Ze(Ne.error);return}const mt=Tb(Ne,{name:P,scope:O,type:S,command:E,url:W,environment:Z,headers:A,oauthEnabled:te,oauthClientId:I,oauthClientSecret:L,oauthScope:Q,oauthRedirectUri:ue,timeout:xe,enabled:me},{isNewServer:v});$(mt.name),F(mt.type),D(mt.command??[]),H(mt.url??""),Y(mt.environment??[]),X(mt.headers??[]),T(mt.oauthEnabled??!1),B(mt.oauthClientId??""),V(mt.oauthClientSecret??""),G(mt.oauthScope??""),ne(mt.oauthRedirectUri??""),ve(mt.timeout??""),ge(mt.enabled??!0),ye(!1),Ee(""),Ze(null),J.success(t("settings.mcp.page.toast.configImported"))},[be,P,O,S,E,W,Z,A,te,I,L,Q,ue,xe,me,v,t]);l.useEffect(()=>{if(v&&i){$(i.name),M(i.scope||"user"),F(i.type),D(i.command),H(i.url),Y(i.environment),X(i.headers),T(i.oauthEnabled),B(i.oauthClientId),V(i.oauthClientSecret),G(i.oauthScope),ne(i.oauthRedirectUri),ve(i.timeout),ge(i.enabled),h(!1),xt.current={mcpType:i.type,command:i.command,url:i.url,envEntries:i.environment,headerEntries:i.headers,oauthEnabled:i.oauthEnabled,oauthClientId:i.oauthClientId,oauthClientSecret:i.oauthClientSecret,oauthScope:i.oauthScope,oauthRedirectUri:i.oauthRedirectUri,timeout:i.timeout,enabled:i.enabled};return}if(N){M(N.scope==="project"?"project":"user");const Ne=Ac(N.environment),ut=N.type==="remote"?N:null,mt=Ac(ut?.headers),At=ut?.oauth,ft=At&&typeof At=="object"?At:null,vt=At!==!1,Dt=N.type,Vt=Dt==="local"?N.command??[]:[],ts=Dt==="remote"?N.url??"":"",os=typeof ut?.timeout=="number"&&Number.isFinite(ut.timeout)?String(ut.timeout):"";F(Dt),D(Vt),H(ts),Y(Ne),X(mt),T(vt),B(vt?ft?.clientId??"":""),V(vt?ft?.clientSecret??"":""),G(vt?ft?.scope??"":""),ne(vt?ft?.redirectUri??"":""),ve(os),ge(N.enabled),h(!1),xt.current={mcpType:Dt,command:Vt,url:ts,envEntries:Ne,headerEntries:mt,oauthEnabled:vt,oauthClientId:vt?ft?.clientId??"":"",oauthClientSecret:vt?ft?.clientSecret??"":"",oauthScope:vt?ft?.scope??"":"",oauthRedirectUri:vt?ft?.redirectUri??"":"",timeout:os,enabled:N.enabled}}},[N,v,i]);const nt=l.useMemo(()=>{const Ne=xt.current;return Ne?S!==Ne.mcpType||me!==Ne.enabled||JSON.stringify(E)!==JSON.stringify(Ne.command)||W!==Ne.url||JSON.stringify(Z)!==JSON.stringify(Ne.envEntries)||JSON.stringify(A)!==JSON.stringify(Ne.headerEntries)||te!==Ne.oauthEnabled||I!==Ne.oauthClientId||L!==Ne.oauthClientSecret||Q!==Ne.oauthScope||ue!==Ne.oauthRedirectUri||xe!==Ne.timeout:!1},[S,E,W,Z,A,te,I,L,Q,ue,xe,me]),rt=async()=>{const Ne=v?P.trim():n??"";if(!Ne){J.error(t("settings.mcp.page.toast.nameRequired"));return}if(v&&a.some(mt=>mt.name===Ne)){J.error(t("settings.mcp.page.toast.serverNameExists"));return}if(S==="local"&&E.filter(Boolean).length===0){J.error(t("settings.mcp.page.toast.localCommandRequired"));return}if(S==="remote"&&!W.trim()){J.error(t("settings.mcp.page.toast.remoteUrlRequired"));return}const ut={name:Ne,scope:O,type:S,command:E,url:W,environment:Z,headers:A,oauthEnabled:te,oauthClientId:I,oauthClientSecret:L,oauthScope:Q,oauthRedirectUri:ue,timeout:xe,enabled:me};oe(!0);try{const mt=v?await c(ut):await p(Ne,ut);mt.ok?(await ai(Ke),bt(),v&&(r(null),o(Ne)),await g({directory:f,silent:!0}),mt.reloadFailed?J.warning(mt.message||t(v?"settings.mcp.page.toast.serverCreatedReloadFailed":"settings.mcp.page.toast.savedReloadFailed"),{description:mt.warning||t("settings.mcp.page.toast.retryRefreshHint")}):J.success(mt.message||t(v?"settings.mcp.page.toast.serverCreatedReloading":"settings.mcp.page.toast.savedReloading"))):J.error(t("settings.mcp.page.toast.saveFailed"))}catch(mt){J.error(mt instanceof Error?mt.message:t("settings.mcp.page.toast.unexpectedError"))}finally{oe(!1)}},gt=async()=>{if(!n)return;le(!0);const Ne=await u(n);Ne.ok?(await ai(Ke),bt(),Ne.reloadFailed?J.warning(Ne.message||t("settings.mcp.page.toast.serverDeletedReloadFailed",{name:n}),{description:Ne.warning||t("settings.mcp.page.toast.refreshListIfStale")}):J.success(Ne.message||t("settings.mcp.page.toast.serverDeleted",{name:n})),pe(!1)):J.error(t("settings.mcp.page.toast.deleteFailed")),le(!1)},wt=async()=>{if(n){he(!0);try{if(w[n]?.status==="connected")await k(n,f),J.success(t("settings.mcp.page.toast.disconnected"));else{await x(n,f),await g({directory:f,silent:!0});const ut=ws.getState().getStatusForDirectory(f??null)[n];ut?.status==="connected"?J.success(t("settings.mcp.page.toast.connected")):ut?.status==="needs_auth"?J.message(t("settings.mcp.page.toast.connectionNeedsAuthorization")):ut?.status==="needs_client_registration"?J.message(t("settings.mcp.page.toast.connectionNeedsClientRegistration")):ut?.status==="failed"?J.error(ut.error||t("settings.mcp.page.toast.connectionFailed")):J.message(t("settings.mcp.page.toast.connectionAttemptFinished"));return}await g({directory:f,silent:!0})}catch(Ne){J.error(Ne instanceof Error?Ne.message:t("settings.mcp.page.toast.connectionFailed"))}finally{he(!1)}}},Pe=l.useCallback(()=>v?(J.error(t("settings.mcp.page.toast.createServerBeforeLiveActions")),!1):nt?(J.error(t("settings.mcp.page.toast.saveBeforeLiveActions")),!1):!0,[nt,v,t]),se=l.useCallback(async(Ne=!1)=>{try{await g({directory:f,silent:Ne})}catch(ut){Ne||J.error(ut instanceof Error?ut.message:t("settings.mcp.page.toast.refreshStatusFailed"))}},[f,g,t]);l.useEffect(()=>{se(!0)},[se]),l.useEffect(()=>{ot.current=it,he(!1),ze(!1),bt()},[bt,it]);const Ce=l.useCallback(async()=>{if(!n||S!=="remote"||!Pe())return;Le(!0);const Ne=it;let ut=null;try{const mt=ws.getState().getStatusForDirectory(f??null)[n]?.status;re.current=mt==="needs_auth"||mt==="needs_client_registration";const At=Uc(n,f);if(!At)throw new Error(t("settings.mcp.page.toast.oauthRedirectUrlBuildFailed"));if(!ue.trim()&&!m){const Vt=await p(n,{oauthEnabled:te,oauthClientId:I,oauthClientSecret:L,oauthScope:Q,oauthRedirectUri:At});if(!Vt.ok)throw new Error(t("settings.mcp.page.toast.oauthBrowserCallbackSaveFailed"));if(Vt.reloadFailed)throw new Error(Vt.warning||Vt.message||t("settings.mcp.page.toast.openCodeReloadFailedAfterCallbackSave"));if(ot.current!==Ne)return;ne(At),xt.current=xt.current?{...xt.current,oauthRedirectUri:At}:xt.current}const ft=await y(n,f),vt=zu(new URL(ft).searchParams);if(vt&&(ut=vt,await _b({state:vt,name:n,directory:f})),ot.current!==Ne)return;He(ft),Oe(vt??null),Ye(!0),q.current=0;const Dt=await Tn(ft);if(ot.current!==Ne)return;Dt?J.message(t(m?"settings.mcp.page.toast.completeAuthorizationInBrowserWithPaste":"settings.mcp.page.toast.completeAuthorizationInBrowser")):J.error(t("settings.mcp.page.toast.openAuthorizationUrlFailed"))}catch(mt){await ai(ut),ot.current===Ne&&J.error(so(mt,t("settings.mcp.page.toast.authorizationStartFailed"),e))}finally{ot.current===Ne&&Le(!1)}},[f,m,S,I,L,te,ue,Q,Pe,it,n,y,t,e,p]),Xe=l.useCallback(async()=>{if(!n||!Pe())return;Fe(!0);const Ne=it;try{if(await z(n,f),ot.current!==Ne)return;He(null),Oe(null),Te(""),Ye(!1),q.current=0,await ai(Ke),J.success(t("settings.mcp.page.toast.savedAuthorizationRemoved"))}catch(ut){ot.current===Ne&&J.error(so(ut,t("settings.mcp.page.toast.clearAuthorizationFailed"),e))}finally{ot.current===Ne&&Fe(!1)}},[Ke,z,f,Pe,it,n,t,e]),Re=l.useCallback(async()=>{if(!_e)return;if((await Vn(_e)).ok){J.success(t("settings.mcp.page.toast.authorizationUrlCopied"));return}J.error(t("settings.mcp.page.toast.authorizationUrlCopyFailed"))},[_e,t]),Je=l.useCallback(async()=>{const Ne=Lb(je);if(!Ne.code){J.error(t("settings.mcp.page.toast.pasteCallbackOrCodeFirst"));return}const ut=Ne.stateKey?await Ub(Ne.stateKey):null,mt=Ne.context??ut,At=mt?.name??n,ft=mt?.directory??f;if(!At){J.error(t("settings.mcp.page.toast.missingServerDetails"));return}if(!mt&&!Pe())return;We(!0);const vt=it;try{if(await C(At,Ne.code,ft),await ai(Ne.stateKey??Ke),ot.current!==vt)return;Te(""),He(null),Oe(null),Ye(!1),q.current=0,J.success(At===n?t("settings.mcp.page.toast.authorizationCompleted"):t("settings.mcp.page.toast.authorizationCompletedFor",{name:At}))}catch(Dt){ot.current===vt&&J.error(so(Dt,t("settings.mcp.page.toast.authorizationCompleteFailed"),e))}finally{ot.current===vt&&We(!1)}},[je,Ke,C,f,Pe,it,n,t,e]),Ge=l.useCallback(async()=>{if(!(!n||!Pe())){if(!me){J.error(t("settings.mcp.page.toast.enableServerBeforeTest"));return}ze(!0);try{const Ne=await j(n,f),ut=Ne.status?.status;Ne.warning?J.warning(Ne.warning):ut==="connected"?J.success(t("settings.mcp.page.toast.connectionTestSucceeded")):ut==="needs_auth"?J.message(t("settings.mcp.page.toast.connectionNeedsAuthorization")):ut==="needs_client_registration"?J.message(t("settings.mcp.page.toast.connectionNeedsClientRegistration")):ut==="failed"?J.error(Ne.status?.error||Ne.error||t("settings.mcp.page.toast.connectionTestFailed")):Ne.error?J.error(Ne.error):J.message(t("settings.mcp.page.toast.connectionTestFinished"))}catch(Ne){J.error(Ne instanceof Error?Ne.message:t("settings.mcp.page.toast.connectionTestFailed"))}finally{ze(!1)}}},[f,me,Pe,n,t,j]);if(l.useEffect(()=>{if(!Ue||!n)return;const Ne=window.setInterval(()=>{(async()=>{q.current+=1,await g({directory:f,silent:!0});const ut=ws.getState().getStatusForDirectory(f??null)[n];if(ut){if(re.current&&ut.status!=="needs_auth"&&ut.status!=="needs_client_registration"){Ye(!1),q.current=0,re.current=!1,He(null),Te(""),ut.status==="connected"&&J.success(t("settings.mcp.page.toast.authorizationCompleted"));return}if(!re.current&&ut.status==="failed"){Ye(!1),q.current=0,re.current=!1,J.error(ut.error||t("settings.mcp.page.toast.authorizationFailed"));return}q.current>=30&&(Ye(!1),q.current=0,re.current=!1,J.message(t("settings.mcp.page.toast.authorizationStillInProgress")))}})()},2e3);return()=>{window.clearInterval(Ne)}},[f,Ue,g,n,t]),!n)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"plug",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.mcp.page.empty.selectServer")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.mcp.page.empty.addNewOne")})]})});const st=w[n],jt=n?b[n]:void 0,Et=st??jt,Mt=st?.status==="connected",Zt=st?.status==="needs_auth"||st?.status==="needs_client_registration",Qt=m?null:Uc(n,f),St=zb(Et?.status,e,Et&&"error"in Et?Et.error:void 0),Pt=Ne=>{switch(Ne){case"connected":return t("settings.mcp.page.status.label.connected");case"failed":return t("settings.mcp.page.status.label.failed");case"needs_auth":return t("settings.mcp.page.status.label.needsAuth");case"needs_client_registration":return t("settings.mcp.page.status.label.needsRegistration");default:return Ne}};return s.jsxs(s.Fragment,{children:[s.jsxs(ps,{title:v?t("settings.mcp.page.header.newServer"):n,titleAccessory:v?void 0:s.jsx(_c,{status:Et?.status,enabled:me,getStatusLabel:Pt,variant:"pill"}),description:v?t("settings.mcp.page.header.configureNewServer"):t("settings.mcp.page.header.transport",{type:t(S==="local"?"settings.mcp.page.transport.local":"settings.mcp.page.transport.remote")}),headerEnd:v?void 0:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(ee,{variant:Mt?"outline":"default",size:"xs",className:"!font-normal",onClick:wt,disabled:de||!me,children:t(de?"settings.mcp.page.actions.working":Mt?"settings.mcp.page.actions.disconnect":"settings.mcp.page.actions.connect")}),S==="remote"&&s.jsxs(s.Fragment,{children:[s.jsx(ee,{variant:Zt?"default":"outline",size:"xs",className:"!font-normal",onClick:()=>{Ce()},disabled:Me||!me,children:t(Me?"settings.mcp.page.actions.starting":Zt?"settings.mcp.page.actions.authorize":"settings.mcp.page.actions.reauthorize")}),s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:()=>{Xe()},disabled:Be||!me,children:t(Be?"settings.mcp.page.actions.clearing":"settings.mcp.page.actions.clearAuth")})]}),Mt&&s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:()=>{Ge()},disabled:De||!me,children:t(De?"settings.mcp.page.actions.testing":"settings.mcp.page.actions.test")})]}),showSaveStatus:!1,children:[!v&&Bb(Et?.status,_e,Zt,Ue)&&s.jsx(dt,{divider:!1,children:s.jsxs("div",{className:fe("rounded-lg border p-3",Kb(Et?.status)),children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[s.jsx("span",{className:zt,children:t("settings.mcp.page.status.runtimeStatus")}),s.jsx(_c,{status:Et?.status,enabled:me,getStatusLabel:Pt})]}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:St}),s.jsx("p",{className:"typography-micro text-muted-foreground/80",children:O==="project"?t("settings.mcp.page.status.projectScopedTo",{directory:f??t("settings.mcp.page.status.activeProject")}):t("settings.mcp.page.status.userScoped")})]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:!Mt&&s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Ge()},disabled:De||!me,children:t(De?"settings.mcp.page.actions.testing":"settings.mcp.page.actions.testConnection")})}),_e&&s.jsx("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--surface-background)] px-3 py-2",children:s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-micro text-muted-foreground",children:t("settings.mcp.page.auth.authorizationUrl")}),s.jsx("div",{className:"break-all typography-micro text-foreground font-mono",children:_e}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Tn(_e)},children:[s.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"}),t("settings.mcp.page.actions.openInBrowser")]}),s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Re()},children:[s.jsx(K,{name:"clipboard",className:"h-3.5 w-3.5"}),t("settings.mcp.page.actions.copyLink")]})]})]})}),S==="remote"&&(Zt||Ue||_e)&&s.jsx("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--surface-background)] px-3 py-3",children:s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{children:[s.jsx(pn,{as:"div",children:t("settings.mcp.page.auth.manualFallbackTitle")}),s.jsx("p",{className:"mt-1 typography-micro text-muted-foreground",children:t("settings.mcp.page.auth.manualFallbackDescription")})]}),s.jsx(Ns,{value:je,onChange:Ne=>Te(Ne.target.value),placeholder:t("settings.mcp.page.auth.callbackInputPlaceholder"),rows:3,className:"font-mono typography-meta resize-y","data-bwignore":"true","data-1p-ignore":"true",spellCheck:!1}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Je()},disabled:Ve,children:t(Ve?"settings.mcp.page.actions.completing":"settings.mcp.page.actions.completeAuthorization")})})]})})]}),Ue&&s.jsx("p",{className:"mt-4 typography-micro text-muted-foreground",children:t("settings.mcp.page.auth.waitingForOpenCode")})]})}),s.jsxs(dt,{title:t("settings.mcp.page.server.title"),divider:!1,settingsItem:"mcp.server",contentClassName:"space-y-0",children:[v&&s.jsxs(Xt,{label:t("settings.mcp.page.server.name"),children:[s.jsx(at,{value:P,onChange:Ne=>$(Ne.target.value.toLowerCase().replace(/[^a-z0-9_-]/g,"-")),placeholder:t("settings.mcp.page.server.namePlaceholder"),className:"h-7 w-48 font-mono px-2",autoFocus:!0}),s.jsxs(Lt,{value:O,onValueChange:Ne=>M(Ne),children:[s.jsx(Ft,{size:Jt,className:"!h-7 !w-7 !min-w-0 !px-0 !py-0 justify-center [&>svg:last-child]:hidden",title:t(O==="user"?"settings.common.scope.global":"settings.common.scope.project"),children:O==="user"?s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"})}),s.jsxs(Ot,{align:"end",children:[s.jsx(kt,{value:"user",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.global")})]})}),s.jsx(kt,{value:"project",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.project")})]})})]})]})]}),v&&s.jsx("div",{className:"py-1.5",children:s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:Nt,type:"button",title:t("settings.mcp.page.server.importJsonTitle"),children:[s.jsx(K,{name:"file-code",className:"h-3.5 w-3.5"}),t("settings.mcp.page.server.importJson")]})}),s.jsx(Ct,{checked:me,onChange:ge,label:t("settings.mcp.page.server.enable"),ariaLabel:t("settings.mcp.page.server.enableAria")}),s.jsx(ns,{label:t("settings.mcp.page.server.transportMode"),children:s.jsx(Ys,{"aria-label":t("settings.mcp.page.server.transportMode"),value:S,onChange:F,options:[{value:"local",label:t("settings.mcp.page.transport.local")},{value:"remote",label:t("settings.mcp.page.transport.remote")}]})})]}),s.jsx(dt,{title:t(S==="local"?"settings.mcp.page.connection.command":"settings.mcp.page.connection.serverUrl"),settingsItem:"mcp.command",children:S==="local"?s.jsx(Fb,{value:E,onChange:D,pasteCommandTitle:t("settings.mcp.page.connection.pasteCommandTitle"),pasteCommandLabel:t("settings.mcp.page.connection.pasteCommand"),pasteSuccess:Ne=>t("settings.mcp.page.toast.pastedArgumentsCount",{count:Ne}),clipboardReadFailed:t("settings.mcp.page.toast.clipboardReadFailed"),preview:Ne=>t("settings.mcp.page.connection.previewArgs",{count:Ne})}):s.jsx(at,{value:W,onChange:Ne=>H(Ne.target.value),placeholder:t("settings.mcp.page.connection.serverUrlPlaceholder"),className:"font-mono typography-meta"})}),S==="remote"&&s.jsx(dt,{title:t("settings.mcp.page.advanced.title"),settingsItem:"mcp.advanced",children:s.jsxs(ca,{open:U,onOpenChange:h,children:[s.jsxs(da,{className:"flex w-full items-center justify-between py-0.5 group",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-left",children:[s.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:t("settings.mcp.page.advanced.configure")}),s.jsxs("span",{className:"typography-micro text-muted-foreground",children:["(",t(te?"settings.mcp.page.advanced.autoDetect":"settings.mcp.page.advanced.custom")," · ",A.length," ",t("settings.mcp.page.advanced.headers"),xe?` · ${xe}ms`:"",")"]})]}),U?s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"}):s.jsx(K,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]}),s.jsx(ua,{className:"pt-2",children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"space-y-2",children:s.jsxs("div",{className:"flex flex-col gap-2 @xl:flex-row @xl:items-center @xl:gap-8",children:[s.jsxs("div",{className:"flex min-w-0 flex-row items-center gap-1 @xl:w-56 shrink-0",children:[s.jsx("span",{className:zt,children:t("settings.mcp.page.advanced.timeoutMs")}),s.jsx($t,{children:t("settings.mcp.page.advanced.timeoutHint")})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx(at,{type:"number",min:"1",step:"1",value:xe,onChange:Ne=>ve(Ne.target.value),placeholder:"5000",className:"h-7 w-32 font-mono px-2","data-bwignore":"true","data-1p-ignore":"true"})})]})}),s.jsxs("div",{children:[s.jsxs(pn,{as:"div",className:"mb-2",children:[t("settings.mcp.page.advanced.requestHeaders"),A.length>0&&s.jsxs("span",{className:"ml-1.5 typography-micro text-muted-foreground font-normal",children:["(",A.length,")"]})]}),s.jsx(Bc,{value:A,onChange:X,keyTransform:Ne=>Ne.trimStart(),keyPlaceholder:t("settings.mcp.page.advanced.headerNamePlaceholder"),keyInputClassName:"w-36 shrink-0 font-mono typography-meta",pasteLabel:t("settings.mcp.page.advanced.pasteHeaders"),pasteTitle:t("settings.mcp.page.advanced.pasteHeadersTitle"),noPairsFoundError:t("settings.mcp.page.toast.noKeyValuePairsFound"),importSuccess:Ne=>t("settings.mcp.page.toast.importedVariablesCount",{count:Ne}),clipboardReadFailed:t("settings.mcp.page.toast.clipboardReadFailed"),keyLabel:t("settings.mcp.page.env.key"),valueLabel:t("settings.mcp.page.env.value"),valuePlaceholder:t("settings.mcp.page.env.valuePlaceholder"),hideValueTitle:t("settings.mcp.page.env.hide"),showValueTitle:t("settings.mcp.page.env.show"),addVariable:t("settings.mcp.page.env.addVariable"),plainTextWarning:t("settings.mcp.page.env.plainTextWarning"),removeVariableAria:t("settings.mcp.page.env.removeVariableAria")})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ct,{checked:te,onChange:T,label:t("settings.mcp.page.advanced.oauthAutoDetection"),ariaLabel:t("settings.mcp.page.advanced.oauthAutoDetectionAria"),info:t("settings.mcp.page.advanced.oauthHint")}),s.jsxs("div",{className:"grid gap-3 @xl:grid-cols-2",children:[s.jsx(at,{value:I,onChange:Ne=>B(Ne.target.value),placeholder:t("settings.mcp.page.advanced.oauthClientIdPlaceholder"),className:"font-mono typography-meta",disabled:!te,"data-bwignore":"true","data-1p-ignore":"true"}),s.jsx(at,{value:L,onChange:Ne=>V(Ne.target.value),placeholder:t("settings.mcp.page.advanced.oauthClientSecretPlaceholder"),className:"font-mono typography-meta",disabled:!te,"data-bwignore":"true","data-1p-ignore":"true"}),s.jsx(at,{value:Q,onChange:Ne=>G(Ne.target.value),placeholder:t("settings.mcp.page.advanced.oauthScopesPlaceholder"),className:"font-mono typography-meta",disabled:!te,"data-bwignore":"true","data-1p-ignore":"true"}),s.jsx(at,{value:ue,onChange:Ne=>ne(Ne.target.value),placeholder:t("settings.mcp.page.advanced.oauthRedirectUriPlaceholder"),className:"font-mono typography-meta",disabled:!te,"data-bwignore":"true","data-1p-ignore":"true"})]}),Qt&&s.jsxs("p",{className:"typography-micro text-muted-foreground",children:[t("settings.mcp.page.advanced.oauthCallbackHint"),s.jsx("span",{className:"mt-1 block break-all font-mono text-foreground/80",children:Qt})]})]})]})})]})}),s.jsx(dt,{title:t("settings.mcp.page.env.title"),titleAccessory:Z.length>0?s.jsxs("span",{className:"typography-micro text-muted-foreground font-normal",children:["(",Z.length,")"]}):null,settingsItem:"mcp.environment",children:Z.length===0?s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:()=>Y([{key:"",value:""}]),children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.mcp.page.env.addEnvironmentVariable")]}):s.jsx(Bc,{value:Z,onChange:Y,keyPlaceholder:t("settings.mcp.page.env.keyPlaceholder"),pasteLabel:t("settings.mcp.page.env.pasteEnv"),pasteTitle:t("settings.mcp.page.env.pasteEnvTitle"),noPairsFoundError:t("settings.mcp.page.toast.noKeyValuePairsFound"),importSuccess:Ne=>t("settings.mcp.page.toast.importedVariablesCount",{count:Ne}),clipboardReadFailed:t("settings.mcp.page.toast.clipboardReadFailed"),keyLabel:t("settings.mcp.page.env.key"),valueLabel:t("settings.mcp.page.env.value"),valuePlaceholder:t("settings.mcp.page.env.valuePlaceholder"),hideValueTitle:t("settings.mcp.page.env.hide"),showValueTitle:t("settings.mcp.page.env.show"),addVariable:t("settings.mcp.page.env.addVariable"),plainTextWarning:t("settings.mcp.page.env.plainTextWarning"),removeVariableAria:t("settings.mcp.page.env.removeVariableAria")})}),s.jsxs("div",{className:"flex items-center gap-2 pb-8",children:[s.jsx(ee,{onClick:rt,disabled:Ie||!nt&&!v,size:"xs",className:"!font-normal",children:t(Ie?"settings.common.actions.saving":v?"settings.common.actions.create":"settings.common.actions.saveChanges")}),!v&&s.jsx(ee,{variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>pe(!0),children:t("settings.common.actions.delete")})]})," "]}),s.jsx(Kt,{open:ae,onOpenChange:Ne=>{Ne||(ye(!1),Ee(""),Ze(null))},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.mcp.page.importDialog.title")}),s.jsx(Yt,{children:t("settings.mcp.page.importDialog.description")})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ns,{value:be,onChange:Ne=>{Ee(Ne.target.value),Ze(null)},placeholder:`{
21
- "mcpServers": {
22
- "postgres": {
23
- "command": "npx",
24
- "args": ["-y", "@modelcontextprotocol/server-postgres"]
25
- }
26
- }
27
- }`,rows:8,className:"font-mono typography-meta resize-y",spellCheck:!1,"data-bwignore":"true","data-1p-ignore":"true"}),et&&s.jsx("p",{className:"typography-micro text-[var(--status-error)]",children:et}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal gap-1",onClick:Se,type:"button",children:[s.jsx(K,{name:"clipboard",className:"h-3.5 w-3.5"}),t("settings.mcp.page.importDialog.pasteFromClipboard")]})})]}),s.jsxs(rs,{children:[s.jsx(ee,{variant:"outline",onClick:()=>{ye(!1),Ee(""),Ze(null)},className:"text-foreground",children:t("settings.common.actions.cancel")}),s.jsx(ee,{onClick:Qe,disabled:!be.trim(),size:"sm",children:t("settings.common.actions.import")})]})]})}),s.jsx(Kt,{open:ce,onOpenChange:Ne=>{!Ne&&!ie&&pe(!1)},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.mcp.page.deleteDialog.title",{name:n??""})}),s.jsxs(Yt,{children:[t("settings.mcp.page.deleteDialog.descriptionPrefix")," ",s.jsx("code",{className:"text-foreground",children:"opencode.json"}),"."," ",t("settings.mcp.page.deleteDialog.descriptionSuffix")]})]}),s.jsxs(rs,{children:[s.jsx(ee,{variant:"outline",onClick:()=>pe(!1),disabled:ie,className:"text-foreground",children:t("settings.common.actions.cancel")}),s.jsx(ee,{variant:"destructive",size:"sm",onClick:gt,disabled:ie,children:t(ie?"settings.mcp.page.actions.deleting":"settings.common.actions.delete")})]})]})})]})},Hb=280,$c=4,Wb=({transform:t})=>({...t,y:0}),Gb=t=>{const e=tt.c(18),{id:n,children:a,className:i}=t;let r;e[0]!==n?(r={id:n},e[0]=n,e[1]=r):r=e[1];const{attributes:o,listeners:d,setNodeRef:c,transform:p,transition:u,isDragging:f}=ju(r);let m;e[2]!==p?(m=Nu.Transform.toString(p),e[2]=p,e[3]=m):m=e[3];let w;e[4]!==m||e[5]!==u?(w={transform:m,transition:u},e[4]=m,e[5]=u,e[6]=w):w=e[6];const b=f&&"opacity-50";let g;e[7]!==i||e[8]!==b?(g=fe("h-full rounded-md",i,b),e[7]=i,e[8]=b,e[9]=g):g=e[9];let x;return e[10]!==o||e[11]!==a||e[12]!==n||e[13]!==d||e[14]!==c||e[15]!==w||e[16]!==g?(x=s.jsx("div",{ref:c,"data-sortable-tab-id":n,style:w,className:g,...o,...d,children:a}),e[10]=o,e[11]=a,e[12]=n,e[13]=d,e[14]=c,e[15]=w,e[16]=g,e[17]=x):x=e[17],x},qb=t=>{const e=tt.c(6),{id:n,children:a,className:i}=t;let r;e[0]!==i?(r=fe("h-full",i),e[0]=i,e[1]=r):r=e[1];let o;return e[2]!==a||e[3]!==n||e[4]!==r?(o=s.jsx("div",{className:r,"data-sortable-tab-id":n,children:a}),e[2]=a,e[3]=n,e[4]=r,e[5]=o):o=e[5],o},ma=t=>{const e=tt.c(133),{items:n,activeId:a,onSelect:i,onClose:r,onReorder:o,layoutMode:d,variant:c,activePillInsetClassName:p,activePillButtonClassName:u,inactiveTabsIconOnly:f,animateActivePill:m,activePillLowercase:w,nonCompositedIndicator:b,className:g}=t,x=d===void 0?"scrollable":d,k=c===void 0?"default":c,y=f===void 0?!1:f,C=w===void 0?!0:w,z=b===void 0?!1:b,{t:j}=lt(),N=ke(Jb),{isTablet:v}=Vs(),P=N||v,$=l.useRef(null);let O;e[0]===Symbol.for("react.memo_cache_sentinel")?(O={left:!1,right:!1},e[0]=O):O=e[0];const[M,S]=l.useState(O);let F;e[1]!==n?(F=n.map(Yb),e[1]=n,e[2]=F):F=e[2];const E=F,D=x==="scrollable",W=k==="default",H=k==="active-pill",Y=H||k==="animated",A=W,X=Y||A,te=H&&D,T=Y,I=m??Y,B=typeof o=="function",L=B?Gb:qb;let V;e[3]===Symbol.for("react.memo_cache_sentinel")?(V=new Map,e[3]=V):V=e[3];const Q=l.useRef(V),[G,ue]=l.useState(null),[ne,xe]=l.useState(!1),[ve,me]=l.useState(null),ge=l.useRef(!1),Ie=l.useRef(0),oe=l.useRef(a),ce=l.useRef(null);let pe;e:{if(!X||!ve||!a||ve===a){pe=0;break e}const Je=n.findIndex(st=>st.id===ve),Ge=n.findIndex(st=>st.id===a);if(Je<0||Ge<0){pe=0;break e}pe=Je>Ge?$c:-$c}const ie=pe;let le;e[4]===Symbol.for("react.memo_cache_sentinel")?(le={activationConstraint:{distance:8}},e[4]=le):le=e[4];const de=xu(bu(yu,le)),he=Qb;let Me;e[5]===Symbol.for("react.memo_cache_sentinel")?(Me=(Je,Ge)=>{if(Ge){Q.current.set(Je,Ge);return}Q.current.delete(Je)},e[5]=Me):Me=e[5];const Le=Me;let Be;e[6]!==a||e[7]!==X?(Be=()=>{if(!X||!a){ue(Xb);return}const Je=$.current,Ge=Q.current.get(a);if(!Je||!Ge){ue(Zb);return}let st=0,jt=0,Et=Ge;for(;Et&&Et!==Je;)st=st+Et.offsetLeft,jt=jt+Et.offsetTop,Et=Et.offsetParent;const Mt={left:st,top:jt,width:Ge.offsetWidth,height:Ge.offsetHeight};ue(Zt=>he(Zt,Mt)?Zt:Mt)},e[6]=a,e[7]=X,e[8]=Be):Be=e[8];const Fe=Be;let De;e[9]!==D?(De=()=>{if(!D){S({left:!1,right:!1});return}const Je=$.current;if(!Je){S({left:!1,right:!1});return}S({left:Je.scrollLeft>2,right:Je.scrollLeft+Je.clientWidth<Je.scrollWidth-2})},e[9]=D,e[10]=De):De=e[10];const ze=De;let Ve;e[11]!==D||e[12]!==ze?(Ve=()=>{if(!D){S({left:!1,right:!1});return}const Je=$.current;if(!Je)return;ze(),Je.addEventListener("scroll",ze,{passive:!0});const Ge=new ResizeObserver(ze);return Ge.observe(Je),()=>{Je.removeEventListener("scroll",ze),Ge.disconnect()}},e[11]=D,e[12]=ze,e[13]=Ve):Ve=e[13];let We;e[14]!==D||e[15]!==n.length||e[16]!==ze?(We=[D,n.length,ze],e[14]=D,e[15]=n.length,e[16]=ze,e[17]=We):We=e[17],l.useEffect(Ve,We);let _e;e[18]!==a||e[19]!==Fe||e[20]!==X?(_e=()=>{if(!X){ue(null);return}Fe();const Je=$.current;if(!Je)return;const Ge=new ResizeObserver(()=>{performance.now()-Ie.current>Hb&&xe(!1),Fe()});if(Ge.observe(Je),a){const st=Q.current.get(a);st&&Ge.observe(st)}return()=>{Ge.disconnect()}},e[18]=a,e[19]=Fe,e[20]=X,e[21]=_e):_e=e[21];let He;e[22]!==a||e[23]!==n.length||e[24]!==Fe||e[25]!==X?(He=[a,n.length,Fe,X],e[22]=a,e[23]=n.length,e[24]=Fe,e[25]=X,e[26]=He):He=e[26],l.useEffect(_e,He);let Ke;e[27]!==Fe?(Ke=()=>{Fe()},e[27]=Fe,e[28]=Ke):Ke=e[28],l.useLayoutEffect(Ke);let Oe;e[29]!==E?(Oe=E.join("\0"),e[29]=E,e[30]=Oe):Oe=e[30];const je=Oe;let Te,Ue;e[31]!==a||e[32]!==je||e[33]!==X?(Te=()=>{if(!X){ge.current=!1,xe(!1);return}const Je=ce.current!==je;if(ce.current=je,!ge.current){ge.current=!0,oe.current=a;return}const Ge=oe.current!==a;if(oe.current=a,!Ge||Je){xe(!1);return}Ie.current=performance.now(),xe(!0)},Ue=[a,je,X],e[31]=a,e[32]=je,e[33]=X,e[34]=Te,e[35]=Ue):(Te=e[34],Ue=e[35]),l.useLayoutEffect(Te,Ue);let Ye;e[36]!==a||e[37]!==D||e[38]!==ze?(Ye=()=>{if(!D||!a)return;const Je=$.current;if(!Je)return;const Ge=window.requestAnimationFrame(()=>{const st=typeof window.CSS?.escape=="function"?window.CSS.escape(a):a.replace(/"/g,'\\"'),jt=Je.querySelector(`[data-sortable-tab-id="${st}"]`);jt&&(jt.scrollIntoView({block:"nearest",inline:"nearest"}),ze())});return()=>{window.cancelAnimationFrame(Ge)}},e[36]=a,e[37]=D,e[38]=ze,e[39]=Ye):Ye=e[39];let q;e[40]!==a||e[41]!==D||e[42]!==n.length||e[43]!==ze?(q=[a,D,n.length,ze],e[40]=a,e[41]=D,e[42]=n.length,e[43]=ze,e[44]=q):q=e[44],l.useEffect(Ye,q);let re;e[45]!==o?(re=Je=>{if(!o)return;const{active:Ge,over:st}=Je;!st||Ge.id===st.id||o(String(Ge.id),String(st.id))},e[45]=o,e[46]=re):re=e[46];const U=re;let h;e[47]!==g?(h=fe("relative flex h-full min-w-0 flex-1",g),e[47]=g,e[48]=h):h=e[48];let ae;e[49]!==D||e[50]!==M||e[51]!==Y?(ae=D&&M.left?s.jsx("div",{className:fe("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",Y?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e[49]=D,e[50]=M,e[51]=Y,e[52]=ae):ae=e[52];let ye;e[53]!==D||e[54]!==M||e[55]!==Y?(ye=D&&M.right?s.jsx("div",{className:fe("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",Y?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e[53]=D,e[54]=M,e[55]=Y,e[56]=ye):ye=e[56];const be=Y?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",Ee=Y&&"@container/pill-tabs",et=Y&&"pill-tabs__track",Ze=Y&&(p??"gap-0.5 py-0.5"),it=A&&"items-center overflow-y-hidden",ot=T&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",xt=D?"overflow-x-auto scrollbar-none":"overflow-x-hidden";let bt;e[57]!==be||e[58]!==Ee||e[59]!==et||e[60]!==Ze||e[61]!==it||e[62]!==ot||e[63]!==xt?(bt=fe("relative flex h-full min-w-0 flex-1",be,Ee,et,Ze,it,ot,xt),e[57]=be,e[58]=Ee,e[59]=et,e[60]=Ze,e[61]=it,e[62]=ot,e[63]=xt,e[64]=bt):bt=e[64];let Nt;e[65]!==D?(Nt=D?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,e[65]=D,e[66]=Nt):Nt=e[66];let Se;e[67]!==j?(Se=j("sortableTabsStrip.aria.tabs"),e[67]=j,e[68]=Se):Se=e[68];let Qe;e[69]!==z||e[70]!==ie||e[71]!==G||e[72]!==ne||e[73]!==I||e[74]!==Y?(Qe=Y&&G?s.jsx("div",{className:fe("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",I&&ne&&(z?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:z?{left:`${G.left+ie}px`,top:`${G.top}px`,width:`${G.width}px`,height:`${G.height}px`}:{transform:`translate3d(${G.left+ie}px, ${G.top}px, 0)`,width:`${G.width}px`,height:`${G.height}px`}}):null,e[69]=z,e[70]=ie,e[71]=G,e[72]=ne,e[73]=I,e[74]=Y,e[75]=Qe):Qe=e[75];let nt;e[76]!==ie||e[77]!==G||e[78]!==ne||e[79]!==A?(nt=A&&G?s.jsx("div",{className:fe("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",ne&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${G.left+ie}px, 0, 0)`,width:`${G.width}px`},"aria-hidden":!0}):null,e[76]=ie,e[77]=G,e[78]=ne,e[79]=A,e[80]=nt):nt=e[80];let rt;if(e[81]!==L||e[82]!==a||e[83]!==u||e[84]!==C||e[85]!==P||e[86]!==y||e[87]!==H||e[88]!==N||e[89]!==D||e[90]!==n||e[91]!==r||e[92]!==i||e[93]!==te||e[94]!==Y||e[95]!==X){let Je;e[97]!==L||e[98]!==a||e[99]!==u||e[100]!==C||e[101]!==P||e[102]!==y||e[103]!==H||e[104]!==N||e[105]!==D||e[106]!==r||e[107]!==i||e[108]!==te||e[109]!==Y||e[110]!==X?(Je=Ge=>{const st=Ge.id===a,jt=y&&Y&&!st&&!!Ge.icon,Et=!jt,Mt=!!Ge.icon,Zt=y&&Y&&st&&!D&&!te,Qt=Ge.closable!==!1&&!!r,St=Qt&&!!Ge.icon,Pt=D||te?void 0:Y?Zt?"flex-none basis-auto":N?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",Ne=Qt?mt=>{mt.button===1&&(mt.preventDefault(),mt.stopPropagation(),r?.(Ge.id))}:void 0,ut=Qt?ey:void 0;return s.jsx(L,{id:Ge.id,className:Pt,children:s.jsxs("div",{ref:mt=>Le(Ge.id,mt),onAuxClick:Ne,onMouseDown:ut,className:fe("group flex h-full min-w-0 flex-nowrap items-center",D||te?"shrink-0":Y?"w-full":"w-full min-w-0",Y?"relative z-10 bg-transparent":st?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[s.jsx("button",{type:"button",role:"tab","aria-selected":st,"aria-label":jt?Ge.title??Ge.label:void 0,onClick:()=>i(Ge.id),onPointerDown:X?()=>{xe(!0),me(Ge.id)}:void 0,onPointerUp:X?()=>me(null):void 0,onPointerLeave:X?()=>me(null):void 0,onPointerCancel:X?()=>me(null):void 0,className:fe(Y?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",Y&&C?"lowercase":null,Y&&(jt?"gap-0":"gap-1.5"),Y?te?"shrink-0 whitespace-nowrap px-3 text-center":D?"max-w-56 shrink-0 px-3 text-center":jt?"px-2 !min-w-0 text-center":Zt?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":D?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",Y?u??(H?N?"h-[38px]":"h-[31px]":"h-7"):null,Y?st?"text-foreground":"text-muted-foreground hover:text-foreground":null,Y?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:Ge.title??Ge.label,children:Y?s.jsxs(s.Fragment,{children:[Mt?s.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[s.jsx("span",{className:fe("flex items-center justify-center transition-opacity",St&&(P?"opacity-0":"group-hover:opacity-0")),children:Ge.icon}),St?s.jsx("span",{role:"button",tabIndex:-1,className:fe("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",P?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:ty,onClick:mt=>{mt.stopPropagation(),r?.(Ge.id)},"aria-label":Ge.closeLabel??`Close ${Ge.label} tab`,title:Ge.closeLabel??`Close ${Ge.label} tab`,children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,Et?s.jsx("span",{className:"animated-tabs__label truncate",children:Ge.label}):null]}):s.jsxs("span",{className:fe("flex min-w-0 flex-nowrap items-center gap-1.5",!D&&"justify-center"),children:[Mt?s.jsxs("span",{className:fe("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",st?"text-[var(--primary-base)]":"text-muted-foreground"),children:[s.jsx("span",{className:fe("flex items-center justify-center transition-opacity",St&&(P?"opacity-0":"group-hover:opacity-0")),children:Ge.icon}),St?s.jsx("span",{role:"button",tabIndex:-1,className:fe("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",P?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:sy,onClick:mt=>{mt.stopPropagation(),r?.(Ge.id)},"aria-label":Ge.closeLabel??`Close ${Ge.label} tab`,title:Ge.closeLabel??`Close ${Ge.label} tab`,children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,s.jsx("span",{className:"truncate leading-[1.2]",children:Ge.label})]})}),Qt&&!St?s.jsx("button",{type:"button",onPointerDown:ny,onClick:mt=>{mt.stopPropagation(),r?.(Ge.id)},className:fe("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",Y?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",Y?st?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":st?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":Ge.closeLabel??`Close ${Ge.label} tab`,title:Ge.closeLabel??`Close ${Ge.label} tab`,children:s.jsx(K,{name:"close",className:"h-3 w-3"})}):null]})},Ge.id)},e[97]=L,e[98]=a,e[99]=u,e[100]=C,e[101]=P,e[102]=y,e[103]=H,e[104]=N,e[105]=D,e[106]=r,e[107]=i,e[108]=te,e[109]=Y,e[110]=X,e[111]=Je):Je=e[111],rt=n.map(Je),e[81]=L,e[82]=a,e[83]=u,e[84]=C,e[85]=P,e[86]=y,e[87]=H,e[88]=N,e[89]=D,e[90]=n,e[91]=r,e[92]=i,e[93]=te,e[94]=Y,e[95]=X,e[96]=rt}else rt=e[96];let gt;e[112]!==bt||e[113]!==Nt||e[114]!==Se||e[115]!==Qe||e[116]!==nt||e[117]!==rt?(gt=s.jsxs("div",{ref:$,className:bt,style:Nt,role:"tablist","aria-label":Se,children:[Qe,nt,rt]}),e[112]=bt,e[113]=Nt,e[114]=Se,e[115]=Qe,e[116]=nt,e[117]=rt,e[118]=gt):gt=e[118];let wt;e[119]!==h||e[120]!==ae||e[121]!==ye||e[122]!==gt?(wt=s.jsxs("div",{className:h,children:[ae,ye,gt]}),e[119]=h,e[120]=ae,e[121]=ye,e[122]=gt,e[123]=wt):wt=e[123];const Pe=wt;if(!B)return Pe;let se;e[124]===Symbol.for("react.memo_cache_sentinel")?(se=[Wb],e[124]=se):se=e[124];let Ce;e[125]!==E||e[126]!==Pe?(Ce=s.jsx(ku,{items:E,strategy:Uf,children:Pe}),e[125]=E,e[126]=Pe,e[127]=Ce):Ce=e[127];let Xe;e[128]===Symbol.for("react.memo_cache_sentinel")?(Xe=s.jsx(_f,{dropAnimation:null}),e[128]=Xe):Xe=e[128];let Re;return e[129]!==U||e[130]!==de||e[131]!==Ce?(Re=s.jsxs(vu,{sensors:de,collisionDetection:wu,onDragEnd:U,modifiers:se,children:[Ce,Xe]}),e[129]=U,e[130]=de,e[131]=Ce,e[132]=Re):Re=e[132],Re};function Jb(t){return t.isMobile}function Yb(t){return t.id}function Qb(t,e){return!t||!e?t===e:Math.abs(t.left-e.left)<.5&&Math.abs(t.top-e.top)<.5&&Math.abs(t.width-e.width)<.5&&Math.abs(t.height-e.height)<.5}function Xb(t){return t===null?t:null}function Zb(t){return t===null?t:null}function ey(t){t.button===1&&t.preventDefault()}function ty(t){t.stopPropagation()}function sy(t){t.stopPropagation()}function ny(t){t.stopPropagation()}const nr=()=>{try{const e=is.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=Ps.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[PluginsStore] Error resolving config directory:",t)}return null},ay=800,iy=5e3,ry="__default__",qo=new Map,no=new Map,oy=1500,Ku=t=>t?.trim()||ry,ly=t=>{qo.delete(Ku(t))},js=gn()(qa(bi((t,e)=>({entries:[],files:[],selectedId:null,isLoading:!1,registryInfo:{},isLoadingRegistry:!1,draft:null,setSelected:n=>t({selectedId:n}),setDraft:n=>t({draft:n}),loadPlugins:async n=>{const a=nr(),i=Ku(a),r=Date.now(),o=qo.get(i)??0,d=e().entries.length>0||e().files.length>0;if(!n?.force&&d&&r-o<iy)return!0;const c=no.get(i);if(!n?.force&&c)return c;const p=(async()=>{t({isLoading:!0});try{const u=await ht(Ln("/api/config/plugins",a),{headers:ii(a)});if(!u.ok)throw new Error("Failed to load plugins");const f=await ar(u);return t({entries:f.entries??[],files:f.files??[],isLoading:!1}),qo.set(i,Date.now()),n?.force||e().loadRegistryInfo(),!0}catch(u){return console.error("[PluginsStore] Failed to load plugins:",u),t({isLoading:!1}),!1}})();no.set(i,p);try{return await p}finally{no.delete(i)}},loadRegistryInfo:async n=>{const a=dy(n?.specs??e().entries.map(i=>i.spec));if(a.length===0){t({isLoadingRegistry:!1});return}t({isLoadingRegistry:!0});try{const i=nr(),r={...e().registryInfo};for(const o of uy(a)){const d=await ht(cy(o,n?.force===!0,i),{headers:ii(i)});if(!d.ok)throw new Error("Failed to load plugin registry info");const c=await ar(d);for(const p of c.results??[])r[p.spec]=p}t({registryInfo:r,isLoadingRegistry:!1})}catch(i){console.error("[PluginsStore] Failed to load plugin registry info:",i),t({isLoadingRegistry:!1})}},updateToLatest:async n=>{const a=e().entries.find(r=>r.id===n);if(!a)return{ok:!1};const i=e().registryInfo[a.spec];return!i||i.kind!=="npm-ok"||!i.hasUpdate||!i.latestVersion?{ok:!1}:await e().updateEntry(n,{spec:`${i.name}@${i.latestVersion}`})},createEntry:async n=>{const a=await Pa("Creating plugin entry…",async i=>await ht(Ln("/api/config/plugins/entry",i),{method:"POST",headers:Bi(i),body:JSON.stringify(Vc(n))}),e);return a.ok&&e().loadRegistryInfo({specs:[n.spec],force:!0}),a},updateEntry:async(n,a)=>{const i=e().entries.find(d=>d.id===n)?.spec,r=a.spec??i,o=await Pa("Updating plugin entry…",async d=>await ht(Ln(`/api/config/plugins/entry/${encodeURIComponent(n)}`,d),{method:"PATCH",headers:Bi(d),body:JSON.stringify(Vc(a))}),e);return o.ok&&r&&e().loadRegistryInfo({specs:[r],force:!0}),o},deleteEntry:async n=>{const a=e().entries.find(r=>r.id===n),i=await Pa("Deleting plugin entry…",async r=>await ht(Ln(`/api/config/plugins/entry/${encodeURIComponent(n)}`,r),{method:"DELETE",headers:ii(r)}),e);if(i.ok&&e().selectedId===n&&t({selectedId:null}),i.ok&&a){const r={...e().registryInfo};delete r[a.spec],t({registryInfo:r})}return i},readFile:async n=>{try{const a=nr(),i=await ht(Ln(`/api/config/plugins/file/${encodeURIComponent(n)}`,a),{headers:ii(a)});if(!i.ok)throw new Error("Failed to read plugin file");return await ar(i)}catch(a){return console.error("[PluginsStore] Failed to read plugin file:",a),null}},createFile:async n=>Pa("Creating plugin file…",async a=>await ht(Ln("/api/config/plugins/file",a),{method:"POST",headers:Bi(a),body:JSON.stringify(n)}),e),updateFile:async(n,a)=>Pa("Updating plugin file…",async i=>await ht(Ln(`/api/config/plugins/file/${encodeURIComponent(n)}`,i),{method:"PUT",headers:Bi(i),body:JSON.stringify(a)}),e),deleteFile:async n=>{const a=await Pa("Deleting plugin file…",async i=>await ht(Ln(`/api/config/plugins/file/${encodeURIComponent(n)}`,i),{method:"DELETE",headers:ii(i)}),e);return a.ok&&e().selectedId===n&&t({selectedId:null}),a},getById:n=>e().entries.find(a=>a.id===n)??e().files.find(a=>a.id===n)}),{name:"plugins-store",storage:Ir(),partialize:t=>({selectedId:t.selectedId})}),{name:"plugins-store"}));function Ln(t,e){const n=e?`?directory=${encodeURIComponent(e)}`:"";return`${t}${n}`}function cy(t,e,n){const a=new URLSearchParams;e&&a.set("refresh","true"),n&&a.set("directory",n);const i=a.toString();return`/api/config/plugins/registry?${`specs=${t.map(encodeURIComponent).join(",")}`}${i?`&${i}`:""}`}function dy(t){return Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))}function uy(t){const e=[];let n=[],a=0;for(const i of t){const r=encodeURIComponent(i),o=n.length===0?r.length:a+1+r.length;n.length>0&&o>oy?(e.push(n),n=[i],a=r.length):(n.push(i),a=o)}return n.length>0&&e.push(n),e}function ii(t){return t?{"x-opencode-directory":t}:void 0}function Bi(t){return{"Content-Type":"application/json",...t?{"x-opencode-directory":t}:{}}}function Vc(t){const e={};return t.spec!==void 0&&(e.spec=t.spec),t.options!==void 0&&(e.options=t.options),t.scope!==void 0&&(e.scope=t.scope),e}async function Pa(t,e,n){Zi(t);let a=!1;try{const i=nr(),r=await e(i),o=await ar(r).catch(()=>null);if(!r.ok)throw new Error(o?.error||"Failed to update plugin configuration");return ly(i),o?.requiresReload&&(a=!0,await er({message:o.message,delayMs:o.reloadDelayMs??ay,scopes:["all"]})),await n().loadPlugins({force:!0}),{ok:!0,reloadFailed:o?.reloadFailed===!0,message:o?.message,warning:o?.warning}}catch(i){return console.error("[PluginsStore] Failed to update plugin configuration:",i),{ok:!1}}finally{a||tr()}}async function ar(t){return await t.json()}const my=/^[a-z0-9][a-z0-9-_.]*\.(js|ts|mjs|cjs)$/;function py(t){const e=t.trim();if(e==="")return{ok:!0,value:void 0};try{const n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)?{ok:!1}:{ok:!0,value:n}}catch{return{ok:!1}}}const gy=({open:t,onOpenChange:e,defaultScope:n="user"})=>{const{t:a}=lt(),i=js(D=>D.createEntry),r=js(D=>D.createFile),[o,d]=l.useState("npm"),[c,p]=l.useState(""),[u,f]=l.useState(""),[m,w]=l.useState(""),[b,g]=l.useState(""),[x,k]=l.useState(n),[y,C]=l.useState(!1),z=l.useCallback(()=>{p(""),f(""),w(""),g(""),k(n)},[n]);l.useEffect(()=>{t&&(d("npm"),z())},[t,z]);const j=D=>{D!==o&&(d(D),z())},N=l.useMemo(()=>py(u),[u]),v=!N.ok,P=o==="file"&&m.trim()!==""&&!my.test(m.trim()),$=(o==="npm"||o==="path")&&c.trim()==="",O=o==="file"&&b.trim()==="",M=o==="file"&&m.trim()==="",S=y||v||o==="npm"&&$||o==="path"&&$||o==="file"&&(M||P||O),F=async()=>{if(!S){C(!0);try{let D;o==="file"?D=await r({fileName:m.trim(),content:b,scope:x}):D=await i({spec:c.trim(),options:N.ok?N.value:void 0,scope:x}),D.ok?(J.success(D.message||a("settings.plugins.toast.created")),D.reloadFailed&&J.warning(a("settings.plugins.toast.reloadFailed")),e(!1)):J.error(D.message||a("settings.plugins.sidebar.toast.deleteFailed"))}finally{C(!1)}}},E=l.useMemo(()=>[{id:"npm",label:a("settings.plugins.dialog.add.tab.npm")},{id:"path",label:a("settings.plugins.dialog.add.tab.path")},{id:"file",label:a("settings.plugins.dialog.add.tab.file")}],[a]);return s.jsx(Kt,{open:t,onOpenChange:D=>{!D&&y||e(D)},children:s.jsxs(Bt,{className:"max-w-xl",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:a("settings.plugins.dialog.add.title")}),s.jsx(Yt,{children:a("settings.plugins.sidebar.empty.description")})]}),s.jsx(ma,{items:E,activeId:o,onSelect:D=>j(D),layoutMode:"fit",variant:"active-pill",activePillLowercase:!1,className:"h-10"}),s.jsxs("div",{className:"flex flex-col gap-4",children:[(o==="npm"||o==="path")&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{"data-settings-item":"plugins.spec",className:"flex flex-col gap-1.5",children:[s.jsx("label",{htmlFor:"plugin-spec",className:"typography-ui-label text-foreground",children:a("settings.plugins.page.field.spec")}),s.jsx(at,{id:"plugin-spec",value:c,onChange:D=>p(D.target.value),placeholder:a("settings.plugins.page.field.spec.placeholder"),"aria-invalid":$?!1:void 0,disabled:y}),$&&s.jsx("p",{className:"typography-meta text-muted-foreground",children:a("settings.plugins.validation.specRequired")})]}),s.jsxs("div",{"data-settings-item":"plugins.options",className:"flex flex-col gap-1.5",children:[s.jsx("label",{htmlFor:"plugin-options",className:"typography-ui-label text-foreground",children:a("settings.plugins.page.field.options")}),s.jsx(Ns,{id:"plugin-options",value:u,onChange:D=>f(D.target.value),rows:5,className:"font-mono",hasError:v,disabled:y}),v&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:a("settings.plugins.page.field.options.invalidJson")})]})]}),o==="file"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{"data-settings-item":"plugins.content",className:"flex flex-col gap-1.5",children:[s.jsx("label",{htmlFor:"plugin-filename",className:"typography-ui-label text-foreground",children:a("settings.plugins.page.field.fileName")}),s.jsx(at,{id:"plugin-filename",value:m,onChange:D=>w(D.target.value),placeholder:"my-plugin.ts","aria-invalid":P||void 0,disabled:y}),P&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:a("settings.plugins.validation.fileName")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx("label",{htmlFor:"plugin-content",className:"typography-ui-label text-foreground",children:a("settings.plugins.page.field.content")}),s.jsx(Ns,{id:"plugin-content",value:b,onChange:D=>g(D.target.value),rows:16,className:"font-mono",disabled:y})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:a("settings.plugins.page.field.scope")}),s.jsx("div",{className:"flex items-center gap-4",children:["user","project"].map(D=>{const W=x===D,H=a(D==="user"?"settings.plugins.scope.user":"settings.plugins.scope.project");return s.jsxs("button",{type:"button",onClick:()=>k(D),disabled:y,className:"flex items-center gap-2 py-1 text-left disabled:opacity-50",children:[s.jsx(kr,{checked:W,onChange:()=>k(D),ariaLabel:H}),s.jsx("span",{className:fe("typography-ui-label font-normal",W?"text-foreground":"text-foreground/60"),children:H})]},D)})})]})]}),s.jsxs(rs,{children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>e(!1),disabled:y,children:a("settings.plugins.dialog.add.action.cancel")}),s.jsxs(ee,{size:"sm",onClick:()=>{F()},disabled:S,children:[y?s.jsx(K,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}):null,a("settings.plugins.dialog.add.action.submit")]})]})]})})},fy=t=>{const e=tt.c(33),{spec:n}=t;let a;e[0]!==n?(a=d=>d.registryInfo[n],e[0]=n,e[1]=a):a=e[1];const i=js(a),{t:r}=lt();if(!i)return null;const o=hy;switch(i.kind){case"npm-ok":{if(!i.hasUpdate||!i.latestVersion)return null;let d;e[2]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"arrow-up-s",className:"h-3 w-3"}),e[2]=d):d=e[2];let c;e[3]!==i.latestVersion?(c=s.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[var(--status-success)]",children:[d,i.latestVersion]}),e[3]=i.latestVersion,e[4]=c):c=e[4];let p;return e[5]!==i.currentVersion||e[6]!==i.latestVersion||e[7]!==r||e[8]!==c?(p=o(c,r("settings.plugins.registry.badge.update.tooltip",{current:i.currentVersion??"",latest:i.latestVersion})),e[5]=i.currentVersion,e[6]=i.latestVersion,e[7]=r,e[8]=c,e[9]=p):p=e[9],p}case"npm-missing-version":{let d;e[10]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"error-warning",className:"h-3 w-3 text-[var(--status-warning)]"}),e[10]=d):d=e[10];let c;return e[11]!==i.currentVersion||e[12]!==i.name||e[13]!==r?(c=o(d,r("settings.plugins.registry.badge.missingVersion.tooltip",{version:i.currentVersion,name:i.name})),e[11]=i.currentVersion,e[12]=i.name,e[13]=r,e[14]=c):c=e[14],c}case"npm-missing-package":{let d;e[15]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"error-warning",className:"h-3 w-3 text-[var(--status-error)]"}),e[15]=d):d=e[15];let c;return e[16]!==i.name||e[17]!==r?(c=o(d,r("settings.plugins.registry.badge.missingPackage.tooltip",{name:i.name})),e[16]=i.name,e[17]=r,e[18]=c):c=e[18],c}case"npm-malformed":{let d;e[19]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"error-warning",className:"h-3 w-3 text-[var(--status-error)]"}),e[19]=d):d=e[19];let c;return e[20]!==r?(c=o(d,r("settings.plugins.registry.badge.malformed.tooltip")),e[20]=r,e[21]=c):c=e[21],c}case"npm-network":{let d;e[22]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"cloud-off",className:"h-3 w-3 text-muted-foreground"}),e[22]=d):d=e[22];let c;return e[23]!==r?(c=o(d,r("settings.plugins.registry.badge.network.tooltip")),e[23]=r,e[24]=c):c=e[24],c}case"path-missing":{let d;e[25]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"error-warning",className:"h-3 w-3 text-[var(--status-error)]"}),e[25]=d):d=e[25];let c;return e[26]!==i.absolutePath||e[27]!==r?(c=o(d,r("settings.plugins.registry.badge.pathMissing.tooltip",{path:i.absolutePath})),e[26]=i.absolutePath,e[27]=r,e[28]=c):c=e[28],c}case"path-unreadable":{let d;e[29]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(K,{name:"error-warning",className:"h-3 w-3 text-[var(--status-warning)]"}),e[29]=d):d=e[29];let c;return e[30]!==i.absolutePath||e[31]!==r?(c=o(d,r("settings.plugins.registry.badge.pathUnreadable.tooltip",{path:i.absolutePath})),e[30]=i.absolutePath,e[31]=r,e[32]=c):c=e[32],c}case"path-ok":return null;default:return null}};function hy(t,e){return s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-xs",children:t})}),s.jsx(ks,{children:e})]})}const Bu=t=>{const e=tt.c(26),{header:n,footer:a,children:i,className:r,variant:o}=t,d=o===void 0?"sidebar":o,c=ds(),p=l.useRef(null),[u,f]=l.useState(!1),[m,w]=l.useState(!1),b=d==="background"||c?"bg-background":"bg-sidebar",g=b==="bg-background"?"var(--surface-background)":"var(--surface-muted)";let x;e[0]===Symbol.for("react.memo_cache_sentinel")?(x=()=>{const S=p.current;if(!S){f(!1),w(!1);return}if(!(S.scrollHeight>S.clientHeight+1)){f(!1),w(!1);return}f(S.scrollTop>1),w(S.scrollTop+S.clientHeight<S.scrollHeight-1)},e[0]=x):x=e[0];const k=x;let y;e[1]===Symbol.for("react.memo_cache_sentinel")?(y=()=>{k()},e[1]=y):y=e[1];let C;e[2]!==i?(C=[i,k],e[2]=i,e[3]=C):C=e[3],l.useEffect(y,C);let z,j;e[4]===Symbol.for("react.memo_cache_sentinel")?(z=()=>{const S=p.current;if(!S)return;const F=()=>k();return S.addEventListener("scroll",F,{passive:!0}),()=>S.removeEventListener("scroll",F)},j=[k],e[4]=z,e[5]=j):(z=e[4],j=e[5]),l.useEffect(z,j);let N;e[6]!==b||e[7]!==r?(N=fe("flex h-full flex-col",b,r),e[6]=b,e[7]=r,e[8]=N):N=e[8];let v;e[9]!==i?(v=s.jsx(Os,{ref:p,outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-3 py-2 overflow-x-hidden",children:i}),e[9]=i,e[10]=v):v=e[10];let P;e[11]!==g||e[12]!==u?(P=u&&s.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-4",style:{background:`linear-gradient(to bottom, ${g} 0%, transparent 100%)`}}),e[11]=g,e[12]=u,e[13]=P):P=e[13];let $;e[14]!==g||e[15]!==m?($=m&&s.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-6",style:{background:`linear-gradient(to top, ${g} 0%, transparent 100%)`}}),e[14]=g,e[15]=m,e[16]=$):$=e[16];let O;e[17]!==$||e[18]!==v||e[19]!==P?(O=s.jsxs("div",{className:"relative flex flex-1 min-h-0 flex-col",children:[v,P,$]}),e[17]=$,e[18]=v,e[19]=P,e[20]=O):O=e[20];let M;return e[21]!==a||e[22]!==n||e[23]!==O||e[24]!==N?(M=s.jsxs("div",{className:N,children:[n,O,a]}),e[21]=a,e[22]=n,e[23]=O,e[24]=N,e[25]=M):M=e[25],M},Jo=t=>{const e=tt.c(23),{title:n,metadata:a,selected:i,onSelect:r,icon:o,actions:d,className:c}=t,p=i===void 0?!1:i,u=d&&d.length>0,f=p?"bg-interactive-selection":"hover:bg-interactive-hover";let m;e[0]!==c||e[1]!==f?(m=fe("group relative flex items-center rounded-md px-1.5 py-0.5 transition-all duration-200",f,c),e[0]=c,e[1]=f,e[2]=m):m=e[2];let w;e[3]!==n?(w=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n}),e[3]=n,e[4]=w):w=e[4];let b;e[5]!==o||e[6]!==w?(b=s.jsxs("div",{className:"flex items-center gap-1.5",children:[o,w]}),e[5]=o,e[6]=w,e[7]=b):b=e[7];let g;e[8]!==a?(g=a&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:a}),e[8]=a,e[9]=g):g=e[9];let x;e[10]!==r||e[11]!==b||e[12]!==g?(x=s.jsxs("button",{onClick:r,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[b,g]}),e[10]=r,e[11]=b,e[12]=g,e[13]=x):x=e[13];let k;e[14]!==d||e[15]!==u?(k=u&&s.jsxs(fs,{children:[s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:d.map(xy)})]}),e[14]=d,e[15]=u,e[16]=k):k=e[16];let y;e[17]!==x||e[18]!==k?(y=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[x,k]}),e[17]=x,e[18]=k,e[19]=y):y=e[19];let C;return e[20]!==m||e[21]!==y?(C=s.jsx("div",{className:m,children:y}),e[20]=m,e[21]=y,e[22]=C):C=e[22],C};function xy(t){const e=t.icon;return s.jsxs(as,{onClick:n=>{n.stopPropagation(),t.onClick()},className:fe(t.destructive&&"text-destructive focus:text-destructive"),children:[e&&s.jsx(K,{name:e,className:"h-4 w-4 mr-px"}),t.label]},t.label)}const by=t=>t.parsedKind==="npm"?"code-box":"folder",yy=t=>{const e=tt.c(144),{onItemSelect:n,onAddClick:a}=t,{t:i}=lt(),{entries:r,files:o,selectedId:d,setSelected:c,deleteEntry:p,deleteFile:u,loadPlugins:f}=js(Hs(vy)),m=js(wy),w=js(jy),b=js(ky),g=js(Ny),[x,k]=l.useState(null),[y,C]=l.useState(!1),[z,j]=l.useState(!1);let N,v;e[0]!==f?(N=()=>{f()},v=[f],e[0]=f,e[1]=N,e[2]=v):(N=e[1],v=e[2]),l.useEffect(N,v);let P,$;e[3]===Symbol.for("react.memo_cache_sentinel")?(P=()=>{const Se=()=>j(!0);return window.addEventListener("openchamber:settings-open-plugin-add",Se),()=>window.removeEventListener("openchamber:settings-open-plugin-add",Se)},$=[],e[3]=P,e[4]=$):(P=e[3],$=e[4]),l.useEffect(P,$);let O;if(e[5]!==r||e[6]!==m){O={userEntries:0,projectEntries:0};for(const Se of r){const Qe=m[Se.spec];Qe?.kind==="npm-ok"&&Qe.hasUpdate&&(Se.scope==="user"?O.userEntries=O.userEntries+1:Se.scope==="project"&&(O.projectEntries=O.projectEntries+1))}e[5]=r,e[6]=m,e[7]=O}else O=e[7];const M=O;let S;e[8]!==r?(S=r.filter(Sy),e[8]=r,e[9]=S):S=e[9];const F=S;let E;e[10]!==r?(E=r.filter(Cy),e[10]=r,e[11]=E):E=e[11];const D=E;let W;e[12]!==o?(W=o.filter(Iy),e[12]=o,e[13]=W):W=e[13];const H=W;let Z;e[14]!==o?(Z=o.filter(Py),e[14]=o,e[15]=Z):Z=e[15];const Y=Z,A=r.length+o.length,X=A===0;let te;e[16]!==a?(te=()=>{a?a():j(!0)},e[16]=a,e[17]=te):te=e[17];const T=te;let I;e[18]!==n||e[19]!==c?(I=Se=>{c(Se),n?.()},e[18]=n,e[19]=c,e[20]=I):I=e[20];const B=I;let L;e[21]!==r||e[22]!==m||e[23]!==i||e[24]!==g?(L=async Se=>{const Qe=r.find(wt=>wt.id===Se);if(!Qe)return;const nt=m[Qe.spec];if(!nt||nt.kind!=="npm-ok"||!nt.hasUpdate||!nt.latestVersion)return;const rt=nt.latestVersion;(await g(Se)).ok?J.success(i("settings.plugins.toast.updatedToLatest",{version:rt})):J.error(i("settings.plugins.toast.refreshFailed"))},e[21]=r,e[22]=m,e[23]=i,e[24]=g,e[25]=L):L=e[25];const V=L;let Q;e[26]!==b||e[27]!==i?(Q=async()=>{J.info(i("settings.plugins.toast.refreshing"));try{await b({force:!0})}catch{J.error(i("settings.plugins.toast.refreshFailed"))}},e[26]=b,e[27]=i,e[28]=Q):Q=e[28];const G=Q;let ue;e[29]!==p||e[30]!==u||e[31]!==x||e[32]!==i?(ue=async()=>{if(!x)return;C(!0);const Se=x.kind==="entry"?await p(x.id):await u(x.id);Se.ok?J.success(Se.message||i("settings.plugins.sidebar.toast.deleted",{name:x.label})):J.error(i("settings.plugins.sidebar.toast.deleteFailed")),k(null),C(!1)},e[29]=p,e[30]=u,e[31]=x,e[32]=i,e[33]=ue):ue=e[33];const ne=ue;let xe;e[34]!==B||e[35]!==V||e[36]!==m||e[37]!==d||e[38]!==i?(xe=Se=>{const Qe=m[Se.spec],nt=Qe?.kind==="npm-ok"&&Qe.hasUpdate&&!!Qe.latestVersion,rt=[];return nt&&rt.push({label:i("settings.plugins.sidebar.actions.updateToLatest"),icon:"arrow-up-s",onClick:()=>{V(Se.id)}}),rt.push({label:i("settings.common.actions.delete"),icon:"delete-bin",destructive:!0,onClick:()=>k({kind:"entry",id:Se.id,label:Se.spec})}),s.jsx(Jo,{title:s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Se.spec}),s.jsx(fy,{spec:Se.spec})]}),metadata:Se.parsedKind==="npm"?i("settings.plugins.sidebar.kind.npm"):i("settings.plugins.sidebar.kind.path"),selected:d===Se.id,onSelect:()=>B(Se.id),icon:s.jsx(K,{name:by(Se),className:"h-4 w-4 flex-shrink-0 text-muted-foreground/70"}),actions:rt},Se.id)},e[34]=B,e[35]=V,e[36]=m,e[37]=d,e[38]=i,e[39]=xe):xe=e[39];const ve=xe;let me;e[40]!==B||e[41]!==d||e[42]!==i?(me=Se=>s.jsx(Jo,{title:Se.fileName,metadata:i("settings.plugins.sidebar.kind.file"),selected:d===Se.id,onSelect:()=>B(Se.id),icon:s.jsx(K,{name:"file-text",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/70"}),actions:[{label:i("settings.common.actions.delete"),icon:"delete-bin",destructive:!0,onClick:()=>k({kind:"file",id:Se.id,label:Se.fileName})}]},Se.id),e[40]=B,e[41]=d,e[42]=i,e[43]=me):me=e[43];const ge=me;let Ie;e[44]!==i?(Ie=(Se,Qe,nt)=>{const rt=nt===void 0?0:nt;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[Se,rt>0&&s.jsx("span",{className:"ml-2 normal-case font-normal text-[var(--status-success)]",children:i(rt===1?"settings.plugins.sidebar.group.updatesAvailable_one":"settings.plugins.sidebar.group.updatesAvailable_other",{count:rt})})]}),Qe]})},e[44]=i,e[45]=Ie):Ie=e[45];const oe=Ie;let ce;e[46]!==i?(ce=i("settings.plugins.sidebar.title"),e[46]=i,e[47]=ce):ce=e[47];let pe;e[48]!==ce?(pe=s.jsx("div",{className:"mb-3 flex items-center justify-between gap-3",children:s.jsx("h2",{className:fn,children:ce})}),e[48]=ce,e[49]=pe):pe=e[49];let ie;e[50]!==i||e[51]!==A?(ie=i("settings.plugins.sidebar.total",{count:A}),e[50]=i,e[51]=A,e[52]=ie):ie=e[52];let le;e[53]!==ie?(le=s.jsx("span",{className:"typography-meta text-muted-foreground",children:ie}),e[53]=ie,e[54]=le):le=e[54];let de;e[55]!==G?(de=()=>{G()},e[55]=G,e[56]=de):de=e[56];let he;e[57]!==i?(he=i("settings.plugins.sidebar.actions.refresh"),e[57]=i,e[58]=he):he=e[58];let Me;e[59]!==i?(Me=i("settings.plugins.sidebar.actions.refresh"),e[59]=i,e[60]=Me):Me=e[60];const Le=w?"size-4 animate-spin":"size-4";let Be;e[61]!==Le?(Be=s.jsx(K,{name:"refresh",className:Le}),e[61]=Le,e[62]=Be):Be=e[62];let Fe;e[63]!==w||e[64]!==de||e[65]!==he||e[66]!==Me||e[67]!==Be?(Fe=s.jsx(ee,{type:"button","data-settings-item":"plugins.create",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:de,disabled:w,"aria-label":he,title:Me,children:Be}),e[63]=w,e[64]=de,e[65]=he,e[66]=Me,e[67]=Be,e[68]=Fe):Fe=e[68];let De;e[69]!==i?(De=i("settings.plugins.sidebar.actions.addTitle"),e[69]=i,e[70]=De):De=e[70];let ze;e[71]!==i?(ze=i("settings.plugins.sidebar.actions.addTitle"),e[71]=i,e[72]=ze):ze=e[72];let Ve;e[73]===Symbol.for("react.memo_cache_sentinel")?(Ve=s.jsx(K,{name:"add",className:"size-4"}),e[73]=Ve):Ve=e[73];let We;e[74]!==T||e[75]!==De||e[76]!==ze?(We=s.jsx(ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:T,"aria-label":De,title:ze,children:Ve}),e[74]=T,e[75]=De,e[76]=ze,e[77]=We):We=e[77];let _e;e[78]!==Fe||e[79]!==We?(_e=s.jsxs("div",{className:"flex items-center gap-1",children:[Fe,We]}),e[78]=Fe,e[79]=We,e[80]=_e):_e=e[80];let He;e[81]!==le||e[82]!==_e?(He=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[le,_e]}),e[81]=le,e[82]=_e,e[83]=He):He=e[83];let Ke;e[84]!==pe||e[85]!==He?(Ke=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[pe,He]}),e[84]=pe,e[85]=He,e[86]=Ke):Ke=e[86];let Oe;e[87]!==X||e[88]!==D||e[89]!==Y||e[90]!==ve||e[91]!==ge||e[92]!==oe||e[93]!==i||e[94]!==M||e[95]!==F||e[96]!==H?(Oe=X?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"plug",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:i("settings.plugins.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:i("settings.plugins.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[F.length>0&&oe(i("settings.plugins.sidebar.group.userEntries"),F.map(ve),M.userEntries),H.length>0&&oe(i("settings.plugins.sidebar.group.userFiles"),H.map(ge)),D.length>0&&oe(i("settings.plugins.sidebar.group.projectEntries"),D.map(ve),M.projectEntries),Y.length>0&&oe(i("settings.plugins.sidebar.group.projectFiles"),Y.map(ge))]}),e[87]=X,e[88]=D,e[89]=Y,e[90]=ve,e[91]=ge,e[92]=oe,e[93]=i,e[94]=M,e[95]=F,e[96]=H,e[97]=Oe):Oe=e[97];let je;e[98]!==Ke||e[99]!==Oe?(je=s.jsx(Bu,{variant:"background",header:Ke,children:Oe}),e[98]=Ke,e[99]=Oe,e[100]=je):je=e[100];let Te;e[101]!==z?(Te=s.jsx(gy,{open:z,onOpenChange:j}),e[101]=z,e[102]=Te):Te=e[102];const Ue=x!==null;let Ye;e[103]!==y?(Ye=Se=>{!Se&&!y&&k(null)},e[103]=y,e[104]=Ye):Ye=e[104];let q;e[105]!==i?(q=i("settings.plugins.sidebar.deleteDialog.title"),e[105]=i,e[106]=q):q=e[106];let re;e[107]!==q?(re=s.jsx(_t,{children:q}),e[107]=q,e[108]=re):re=e[108];const U=x?.label??"";let h;e[109]!==i||e[110]!==U?(h=i("settings.plugins.sidebar.deleteDialog.description",{name:U}),e[109]=i,e[110]=U,e[111]=h):h=e[111];let ae;e[112]!==h?(ae=s.jsx(Yt,{children:h}),e[112]=h,e[113]=ae):ae=e[113];let ye;e[114]!==re||e[115]!==ae?(ye=s.jsxs(Ut,{children:[re,ae]}),e[114]=re,e[115]=ae,e[116]=ye):ye=e[116];let be;e[117]===Symbol.for("react.memo_cache_sentinel")?(be=()=>k(null),e[117]=be):be=e[117];let Ee;e[118]!==i?(Ee=i("settings.common.actions.cancel"),e[118]=i,e[119]=Ee):Ee=e[119];let et;e[120]!==y||e[121]!==Ee?(et=s.jsx(ee,{size:"sm",variant:"ghost",onClick:be,disabled:y,children:Ee}),e[120]=y,e[121]=Ee,e[122]=et):et=e[122];let Ze;e[123]!==y||e[124]!==i?(Ze=i(y?"settings.plugins.sidebar.actions.deleting":"settings.common.actions.delete"),e[123]=y,e[124]=i,e[125]=Ze):Ze=e[125];let it;e[126]!==ne||e[127]!==y||e[128]!==Ze?(it=s.jsx(ee,{size:"sm",variant:"destructive",onClick:ne,disabled:y,children:Ze}),e[126]=ne,e[127]=y,e[128]=Ze,e[129]=it):it=e[129];let ot;e[130]!==et||e[131]!==it?(ot=s.jsxs(rs,{children:[et,it]}),e[130]=et,e[131]=it,e[132]=ot):ot=e[132];let xt;e[133]!==ye||e[134]!==ot?(xt=s.jsxs(Bt,{className:"max-w-md",children:[ye,ot]}),e[133]=ye,e[134]=ot,e[135]=xt):xt=e[135];let bt;e[136]!==Ue||e[137]!==Ye||e[138]!==xt?(bt=s.jsx(Kt,{open:Ue,onOpenChange:Ye,children:xt}),e[136]=Ue,e[137]=Ye,e[138]=xt,e[139]=bt):bt=e[139];let Nt;return e[140]!==je||e[141]!==Te||e[142]!==bt?(Nt=s.jsxs(s.Fragment,{children:[je,Te,bt]}),e[140]=je,e[141]=Te,e[142]=bt,e[143]=Nt):Nt=e[143],Nt};function vy(t){return{entries:t.entries,files:t.files,selectedId:t.selectedId,setSelected:t.setSelected,deleteEntry:t.deleteEntry,deleteFile:t.deleteFile,loadPlugins:t.loadPlugins}}function wy(t){return t.registryInfo}function jy(t){return t.isLoadingRegistry}function ky(t){return t.loadRegistryInfo}function Ny(t){return t.updateToLatest}function Sy(t){return t.scope==="user"}function Cy(t){return t.scope==="project"}function Iy(t){return t.scope==="user"}function Py(t){return t.scope==="project"}const Ty=({entryId:t,spec:e})=>{const{t:n}=lt(),a=js(f=>f.registryInfo[e]),i=js(f=>f.updateToLatest),[r,o]=l.useState(!1);if(!a)return null;if(a.kind==="npm-ok"){if(!a.hasUpdate||!a.latestVersion)return null;const f=a.latestVersion,m=a.currentVersion??"",w=async()=>{o(!0);try{(await i(t)).ok?J.success(n("settings.plugins.toast.updatedToLatest",{version:f})):J.error(n("settings.plugins.toast.refreshFailed"))}finally{o(!1)}};return s.jsxs("div",{className:"rounded-md border border-border bg-card p-3 flex items-start gap-3",children:[s.jsx(K,{name:"arrow-up",className:"h-5 w-5 text-[var(--status-success)] shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"typography-label text-[var(--status-success)]",children:n("settings.plugins.registry.banner.updateAvailable.title")}),s.jsx("p",{className:"typography-micro text-muted-foreground mt-0.5",children:n("settings.plugins.registry.banner.updateAvailable.description",{current:m,latest:f})})]}),s.jsx(ee,{variant:"default",size:"sm",onClick:()=>{w()},disabled:r,children:n("settings.plugins.registry.banner.updateAvailable.action",{latest:f})})]})}if(a.kind==="path-ok")return null;if(a.kind==="npm-network")return s.jsxs("div",{className:"rounded-md border border-border bg-card p-3 flex items-start gap-3",children:[s.jsx(K,{name:"cloud-off",className:"h-5 w-5 text-muted-foreground shrink-0 mt-0.5"}),s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx("p",{className:"typography-micro text-muted-foreground",children:n("settings.plugins.registry.badge.network.tooltip")})})]});const d=a.kind==="path-unreadable",c=d?"var(--status-warning)":"var(--status-error)",p=d?"alert":"error-warning",u=(()=>{switch(a.kind){case"npm-missing-version":return n("settings.plugins.registry.banner.invalid.missingVersion");case"npm-missing-package":return n("settings.plugins.registry.banner.invalid.missingPackage");case"npm-malformed":return n("settings.plugins.registry.banner.invalid.malformed");case"path-missing":return n("settings.plugins.registry.banner.invalid.pathMissing");case"path-unreadable":return n("settings.plugins.registry.banner.invalid.pathUnreadable")}})();return s.jsxs("div",{className:"rounded-md border border-border bg-card p-3 flex items-start gap-3",children:[s.jsx(K,{name:p,className:"h-5 w-5 shrink-0 mt-0.5",style:{color:c}}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"typography-label",style:{color:c},children:n("settings.plugins.registry.banner.invalid.title")}),s.jsx("p",{className:"typography-micro text-muted-foreground mt-0.5",children:u})]})]})};function Ay(t){const e=t.trim();if(e.length===0)return{ok:!0,value:void 0};try{const n=JSON.parse(e);return n===null||typeof n!="object"||Array.isArray(n)?{ok:!1}:{ok:!0,value:n}}catch{return{ok:!1}}}function _u(t){return!t||Object.keys(t).length===0?"":JSON.stringify(t,null,2)}function Hc(t){return{mode:"entry",scope:t.scope,spec:t.spec,optionsJson:_u(t.options),fileName:"",content:""}}function Wc(t,e){return{mode:"file",scope:t.scope,spec:"",optionsJson:"",fileName:t.fileName,content:e}}const Gc=t=>{const e=tt.c(4),{scope:n,label:a}=t;let i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i=fe("typography-micro font-medium rounded-full px-2 py-0.5","bg-[var(--surface-elevated)] text-muted-foreground","border border-[var(--interactive-border)]"),e[0]=i):i=e[0];let r;return e[1]!==a||e[2]!==n?(r=s.jsx("span",{className:i,"data-scope":n,children:a}),e[1]=a,e[2]=n,e[3]=r):r=e[3],r},Ey=()=>{const{t}=lt(),e=js(x=>x.selectedId),n=js(x=>x.entries),a=js(x=>x.files),i=js(x=>x.draft),r=js(x=>x.setDraft),o=js(x=>x.updateEntry),d=js(x=>x.updateFile),c=js(x=>x.readFile),p=l.useMemo(()=>e?n.find(x=>x.id===e)??null:null,[n,e]),u=l.useMemo(()=>e?a.find(x=>x.id===e)??null:null,[a,e]),[f,m]=l.useState(!1),[w,b]=l.useState(!1),g=l.useRef(new Map);if(l.useEffect(()=>{let x=!1;return p?(r(Hc(p)),()=>{x=!0}):u?(b(!0),(async()=>{const k=await c(u.id);if(x)return;b(!1);const y=k?.content??"";g.current.set(u.id,y),r(Wc(u,y))})(),()=>{x=!0}):(r(null),()=>{x=!0})},[p,u,c,r]),!e)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"plug",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.plugins.page.empty.select")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.plugins.page.empty.add")})]})});if(p&&i&&i.mode==="entry"){const x=Ay(i.optionsJson),k=x.ok,y=i.spec!==p.spec||i.optionsJson!==_u(p.options),C=()=>{r(Hc(p))},z=async()=>{if(!k)return;const j=i.spec.trim();if(!j){J.error(t("settings.plugins.validation.specRequired"));return}m(!0);try{const N=await o(p.id,{spec:j,options:x.value});N.ok?N.reloadFailed?J.warning(N.message||t("settings.plugins.toast.reloadFailed"),{description:N.warning}):J.success(N.message||t("settings.plugins.toast.updated")):J.error(N.message||t("settings.plugins.toast.reloadFailed"))}finally{m(!1)}};return s.jsxs(ps,{title:t("settings.plugins.page.header.entry"),titleAccessory:s.jsx(Gc,{scope:p.scope,label:p.scope==="project"?t("settings.plugins.sidebar.group.projectEntries"):t("settings.plugins.sidebar.group.userEntries")}),showSaveStatus:!1,children:[s.jsx(dt,{divider:!1,children:s.jsx(Ty,{entryId:p.id,spec:p.spec})}),s.jsx(dt,{title:t("settings.plugins.page.field.spec"),settingsItem:"plugins.spec",children:s.jsx(at,{value:i.spec,onChange:j=>r({...i,spec:j.target.value}),placeholder:t("settings.plugins.page.field.spec.placeholder"),className:"font-mono typography-meta",spellCheck:!1})}),s.jsxs(dt,{title:t("settings.plugins.page.field.options"),settingsItem:"plugins.options",children:[s.jsx(Ns,{value:i.optionsJson,onChange:j=>r({...i,optionsJson:j.target.value}),rows:10,className:fe("font-mono typography-meta min-h-[200px]",!k&&"border-[var(--status-error-border)]"),spellCheck:!1,placeholder:"{ }"}),!k&&s.jsx("p",{className:"typography-micro text-[var(--status-error)]",children:t("settings.plugins.page.field.options.invalidJson")}),s.jsxs("div",{className:"flex items-center gap-2 pt-3",children:[s.jsx(ee,{variant:"default",size:"sm",onClick:()=>{z()},disabled:!y||!k||f,children:t("settings.plugins.page.action.save")}),s.jsx(ee,{variant:"outline",size:"sm",onClick:C,disabled:!y||f,children:t("settings.plugins.page.action.discard")})]})]})]})}if(u&&i&&i.mode==="file"){const x=g.current.get(u.id)??"",k=i.content!==x||i.fileName!==u.fileName,y=()=>{(async()=>{b(!0);const j=(await c(u.id))?.content??"";b(!1),g.current.set(u.id,j),r(Wc(u,j))})()},C=async()=>{m(!0);try{const z=await d(u.id,{content:i.content});z.ok?(g.current.set(u.id,i.content),z.reloadFailed?J.warning(z.message||t("settings.plugins.toast.reloadFailed"),{description:z.warning}):J.success(z.message||t("settings.plugins.toast.updated"))):J.error(z.message||t("settings.plugins.toast.reloadFailed"))}finally{m(!1)}};return s.jsx(ps,{title:t("settings.plugins.page.header.file"),titleAccessory:s.jsxs(s.Fragment,{children:[s.jsx(Gc,{scope:u.scope,label:u.scope==="project"?t("settings.plugins.sidebar.group.projectFiles"):t("settings.plugins.sidebar.group.userFiles")}),s.jsx("span",{className:fe("typography-micro font-mono rounded-full px-2 py-0.5","bg-[var(--surface-elevated)] text-foreground","border border-[var(--interactive-border)]"),children:u.fileName})]}),showSaveStatus:!1,children:s.jsxs(dt,{title:t("settings.plugins.page.field.content"),divider:!1,settingsItem:"plugins.content",children:[s.jsx(Ns,{value:i.content,onChange:z=>r({...i,content:z.target.value}),rows:16,className:"font-mono typography-meta min-h-[320px]",spellCheck:!1,disabled:w}),s.jsxs("div",{className:"flex items-center gap-2 pt-3",children:[s.jsx(ee,{variant:"default",size:"sm",onClick:()=>{C()},disabled:!k||f||w,children:t("settings.plugins.page.action.save")}),s.jsx(ee,{variant:"outline",size:"sm",onClick:y,disabled:f||w,children:t("settings.plugins.page.action.discard")})]})]})})}return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsx("div",{className:"text-center text-muted-foreground",children:s.jsx(K,{name:"loader-4",className:"mx-auto mb-3 h-6 w-6 animate-spin opacity-50"})})})},Dy="<built-in>",gi=t=>t?.path===Dy,Yo=t=>!!t&&!gi(t)&&t.renamable===!0,Ry=t=>{const e=tt.c(148),{onItemSelect:n}=t,{t:a}=lt(),[i,r]=l.useState(null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,f]=l.useState(!1),[m,w]=l.useState(null),{selectedSkillName:b,skills:g,setSelectedSkill:x,setSkillDraft:k,deleteSkill:y,renameSkill:C,getSkillDetail:z}=Cn(Hs(My));let j;e[0]!==n||e[1]!==x||e[2]!==k||e[3]!==g?(j=()=>{let Se="new-skill",Qe=1;for(;g.some(nt=>nt.name===Se);)Se=`new-skill-${Qe}`,Qe++;k({name:Se,scope:"user",source:"opencode",description:""}),x(Se),n?.()},e[0]=n,e[1]=x,e[2]=k,e[3]=g,e[4]=j):j=e[4];const N=j;let v;e[5]===Symbol.for("react.memo_cache_sentinel")?(v=async Se=>{gi(Se)||p(Se)},e[5]=v):v=e[5];const P=v;let $;e[6]!==c||e[7]!==y||e[8]!==a?($=async()=>{if(!c)return;if(gi(c)){p(null);return}f(!0),await y(c.name)?(J.success(a("settings.skills.sidebar.toast.skillDeleted",{name:c.name})),p(null)):J.error(a("settings.skills.sidebar.toast.deleteSkillFailed")),f(!1)},e[6]=c,e[7]=y,e[8]=a,e[9]=$):$=e[9];const O=$;let M;e[10]!==z||e[11]!==x||e[12]!==k||e[13]!==g||e[14]!==a?(M=async Se=>{if(gi(Se))return;const Qe=Se.name;let nt=1,rt=`${Qe}-copy`;for(;g.some(wt=>wt.name===rt);)nt++,rt=`${Qe}-copy-${nt}`;const gt=await z(Se.name);if(!gt){J.error(a("settings.skills.sidebar.toast.duplicateLoadFailed"));return}k({name:rt,scope:Se.scope||"user",source:Se.source||"opencode",description:(gt.sources.md.fields.includes("description"),""),instructions:""}),x(rt)},e[10]=z,e[11]=x,e[12]=k,e[13]=g,e[14]=a,e[15]=M):M=e[15];const S=M;let F;e[16]===Symbol.for("react.memo_cache_sentinel")?(F=Se=>{Yo(Se)&&(d(Se.name),r(Se))},e[16]=F):F=e[16];const E=F;let D;e[17]!==i||e[18]!==o||e[19]!==C||e[20]!==x||e[21]!==g||e[22]!==a?(D=async()=>{if(!i)return;if(!Yo(i)){r(null);return}const Se=o.trim().replace(/\s+/g,"-").toLowerCase();if(!Se){J.error(a("settings.skills.page.toast.skillNameRequired"));return}if(Se===i.name){r(null);return}if(g.some(nt=>nt.name===Se)){J.error(a("settings.skills.page.toast.skillExists"));return}await C(i.name,Se)?(J.success(a("settings.skills.sidebar.toast.skillRenamed",{name:Se})),x(Se)):J.error(a("settings.skills.sidebar.toast.renameFailed")),r(null)},e[17]=i,e[18]=o,e[19]=C,e[20]=x,e[21]=g,e[22]=a,e[23]=D):D=e[23];const W=D;let H;e[24]!==g?(H=g.filter(Ly),e[24]=g,e[25]=H):H=e[25];const Z=H;let Y;e[26]!==g?(Y=g.filter(Fy),e[26]=g,e[27]=Y):Y=e[27];const A=Y;let X;e[28]===Symbol.for("react.memo_cache_sentinel")?(X=function(Qe){const nt={},rt=[];for(const wt of Qe)wt.group?(nt[wt.group]||(nt[wt.group]=[]),nt[wt.group].push(wt)):rt.push(wt);const gt=Object.keys(nt).sort(Oy).map(wt=>({name:wt,skills:[...nt[wt]].sort(zy)}));return rt.sort(Ky),{sortedGroups:gt,ungrouped:rt}},e[28]=X):X=e[28];const te=X;let T;e[29]!==Z?(T=te(Z),e[29]=Z,e[30]=T):T=e[30];const I=T;let B;e[31]!==A?(B=te(A),e[31]=A,e[32]=B):B=e[32];const L=B;let V;e[33]===Symbol.for("react.memo_cache_sentinel")?(V=fe("flex h-full flex-col","bg-background"),e[33]=V):V=e[33];let Q;e[34]!==a?(Q=a("settings.skills.sidebar.title"),e[34]=a,e[35]=Q):Q=e[35];let G;e[36]!==Q?(G=s.jsx("h2",{className:`${fn} mb-3`,children:Q}),e[36]=Q,e[37]=G):G=e[37];let ue;e[38]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(yi,{className:"mb-3"}),e[38]=ue):ue=e[38];let ne;e[39]!==g.length||e[40]!==a?(ne=a("settings.skills.sidebar.total",{count:g.length}),e[39]=g.length,e[40]=a,e[41]=ne):ne=e[41];let xe;e[42]!==ne?(xe=s.jsx("span",{className:"typography-meta text-muted-foreground",children:ne}),e[42]=ne,e[43]=xe):xe=e[43];let ve;e[44]===Symbol.for("react.memo_cache_sentinel")?(ve=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[44]=ve):ve=e[44];let me;e[45]!==N?(me=s.jsx(ee,{size:"sm","data-settings-item":"skills.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:N,children:ve}),e[45]=N,e[46]=me):me=e[46];let ge;e[47]!==xe||e[48]!==me?(ge=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[xe,me]}),e[47]=xe,e[48]=me,e[49]=ge):ge=e[49];let Ie;e[50]!==G||e[51]!==ge?(Ie=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[G,ue,ge]}),e[50]=G,e[51]=ge,e[52]=Ie):Ie=e[52];let oe;e[53]!==I||e[54]!==L||e[55]!==S||e[56]!==n||e[57]!==m||e[58]!==Z||e[59]!==b||e[60]!==x||e[61]!==g.length||e[62]!==a||e[63]!==A?(oe=s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:g.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"book-open",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:a("settings.skills.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:a("settings.skills.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[Z.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.skills.sidebar.section.project")}),I.sortedGroups.map(Se=>{const{name:Qe,skills:nt}=Se;return s.jsx(Ho,{label:Qe,count:nt.length,storageKey:"project-skills",children:nt.map(rt=>s.jsx(_i,{skill:rt,isSelected:b===rt.name,onSelect:()=>{x(rt.name),n?.()},onRename:()=>E(rt),onDelete:()=>P(rt),onDuplicate:()=>S(rt),isMenuOpen:m===rt.name,onMenuOpenChange:gt=>w(gt?rt.name:null)},rt.name))},Qe)}),I.ungrouped.map(Se=>s.jsx(_i,{skill:Se,isSelected:b===Se.name,onSelect:()=>{x(Se.name),n?.()},onRename:()=>E(Se),onDelete:()=>P(Se),onDuplicate:()=>S(Se),isMenuOpen:m===Se.name,onMenuOpenChange:Qe=>w(Qe?Se.name:null)},Se.name))]}),A.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.skills.sidebar.section.user")}),L.sortedGroups.map(Se=>{const{name:Qe,skills:nt}=Se;return s.jsx(Ho,{label:Qe,count:nt.length,storageKey:"user-skills",children:nt.map(rt=>s.jsx(_i,{skill:rt,isSelected:b===rt.name,onSelect:()=>{x(rt.name),n?.()},onRename:()=>E(rt),onDelete:()=>P(rt),onDuplicate:()=>S(rt),isMenuOpen:m===rt.name,onMenuOpenChange:gt=>w(gt?rt.name:null)},rt.name))},Qe)}),L.ungrouped.map(Se=>s.jsx(_i,{skill:Se,isSelected:b===Se.name,onSelect:()=>{x(Se.name),n?.()},onRename:()=>E(Se),onDelete:()=>P(Se),onDuplicate:()=>S(Se),isMenuOpen:m===Se.name,onMenuOpenChange:Qe=>w(Qe?Se.name:null)},Se.name))]})]})}),e[53]=I,e[54]=L,e[55]=S,e[56]=n,e[57]=m,e[58]=Z,e[59]=b,e[60]=x,e[61]=g.length,e[62]=a,e[63]=A,e[64]=oe):oe=e[64];const ce=c!==null;let pe;e[65]!==u?(pe=Se=>{!Se&&!u&&p(null)},e[65]=u,e[66]=pe):pe=e[66];let ie;e[67]!==a?(ie=a("settings.skills.sidebar.deleteDialog.title"),e[67]=a,e[68]=ie):ie=e[68];let le;e[69]!==ie?(le=s.jsx(_t,{children:ie}),e[69]=ie,e[70]=le):le=e[70];const de=c?.name??"";let he;e[71]!==a||e[72]!==de?(he=a("settings.skills.sidebar.deleteDialog.description",{name:de}),e[71]=a,e[72]=de,e[73]=he):he=e[73];let Me;e[74]!==he?(Me=s.jsx(Yt,{children:he}),e[74]=he,e[75]=Me):Me=e[75];let Le;e[76]!==le||e[77]!==Me?(Le=s.jsxs(Ut,{children:[le,Me]}),e[76]=le,e[77]=Me,e[78]=Le):Le=e[78];let Be;e[79]===Symbol.for("react.memo_cache_sentinel")?(Be=()=>p(null),e[79]=Be):Be=e[79];let Fe;e[80]!==a?(Fe=a("settings.common.actions.cancel"),e[80]=a,e[81]=Fe):Fe=e[81];let De;e[82]!==u||e[83]!==Fe?(De=s.jsx(ee,{size:"sm",className:"text-foreground hover:bg-interactive-hover hover:text-foreground",variant:"ghost",onClick:Be,disabled:u,children:Fe}),e[82]=u,e[83]=Fe,e[84]=De):De=e[84];let ze;e[85]!==a?(ze=a("settings.common.actions.delete"),e[85]=a,e[86]=ze):ze=e[86];let Ve;e[87]!==O||e[88]!==u||e[89]!==ze?(Ve=s.jsx(ee,{size:"sm",onClick:O,disabled:u,children:ze}),e[87]=O,e[88]=u,e[89]=ze,e[90]=Ve):Ve=e[90];let We;e[91]!==De||e[92]!==Ve?(We=s.jsxs(rs,{children:[De,Ve]}),e[91]=De,e[92]=Ve,e[93]=We):We=e[93];let _e;e[94]!==Le||e[95]!==We?(_e=s.jsxs(Bt,{className:"max-w-md",children:[Le,We]}),e[94]=Le,e[95]=We,e[96]=_e):_e=e[96];let He;e[97]!==ce||e[98]!==pe||e[99]!==_e?(He=s.jsx(Kt,{open:ce,onOpenChange:pe,children:_e}),e[97]=ce,e[98]=pe,e[99]=_e,e[100]=He):He=e[100];const Ke=i!==null;let Oe;e[101]===Symbol.for("react.memo_cache_sentinel")?(Oe=Se=>!Se&&r(null),e[101]=Oe):Oe=e[101];let je;e[102]!==a?(je=a("settings.skills.sidebar.renameDialog.title"),e[102]=a,e[103]=je):je=e[103];let Te;e[104]!==je?(Te=s.jsx(_t,{children:je}),e[104]=je,e[105]=Te):Te=e[105];const Ue=i?.name??"";let Ye;e[106]!==a||e[107]!==Ue?(Ye=a("settings.skills.sidebar.renameDialog.description",{name:Ue}),e[106]=a,e[107]=Ue,e[108]=Ye):Ye=e[108];let q;e[109]!==Ye?(q=s.jsx(Yt,{children:Ye}),e[109]=Ye,e[110]=q):q=e[110];let re;e[111]!==Te||e[112]!==q?(re=s.jsxs(Ut,{children:[Te,q]}),e[111]=Te,e[112]=q,e[113]=re):re=e[113];let U;e[114]===Symbol.for("react.memo_cache_sentinel")?(U=Se=>d(Se.target.value),e[114]=U):U=e[114];let h;e[115]!==a?(h=a("settings.skills.sidebar.renameDialog.placeholder"),e[115]=a,e[116]=h):h=e[116];let ae;e[117]!==W?(ae=Se=>{Se.key==="Enter"&&W()},e[117]=W,e[118]=ae):ae=e[118];let ye;e[119]!==o||e[120]!==h||e[121]!==ae?(ye=s.jsx(at,{value:o,onChange:U,placeholder:h,className:"text-foreground placeholder:text-muted-foreground",onKeyDown:ae}),e[119]=o,e[120]=h,e[121]=ae,e[122]=ye):ye=e[122];let be;e[123]===Symbol.for("react.memo_cache_sentinel")?(be=()=>r(null),e[123]=be):be=e[123];let Ee;e[124]!==a?(Ee=a("settings.common.actions.cancel"),e[124]=a,e[125]=Ee):Ee=e[125];let et;e[126]!==Ee?(et=s.jsx(ee,{size:"sm",className:"text-foreground hover:bg-interactive-hover hover:text-foreground",variant:"ghost",onClick:be,children:Ee}),e[126]=Ee,e[127]=et):et=e[127];let Ze;e[128]!==a?(Ze=a("settings.common.actions.rename"),e[128]=a,e[129]=Ze):Ze=e[129];let it;e[130]!==W||e[131]!==Ze?(it=s.jsx(ee,{size:"sm",onClick:W,children:Ze}),e[130]=W,e[131]=Ze,e[132]=it):it=e[132];let ot;e[133]!==et||e[134]!==it?(ot=s.jsxs(rs,{children:[et,it]}),e[133]=et,e[134]=it,e[135]=ot):ot=e[135];let xt;e[136]!==re||e[137]!==ye||e[138]!==ot?(xt=s.jsxs(Bt,{children:[re,ye,ot]}),e[136]=re,e[137]=ye,e[138]=ot,e[139]=xt):xt=e[139];let bt;e[140]!==Ke||e[141]!==xt?(bt=s.jsx(Kt,{open:Ke,onOpenChange:Oe,children:xt}),e[140]=Ke,e[141]=xt,e[142]=bt):bt=e[142];let Nt;return e[143]!==Ie||e[144]!==oe||e[145]!==He||e[146]!==bt?(Nt=s.jsxs("div",{className:V,children:[Ie,oe,He,bt]}),e[143]=Ie,e[144]=oe,e[145]=He,e[146]=bt,e[147]=Nt):Nt=e[147],Nt},_i=t=>{const e=tt.c(52),{skill:n,isSelected:a,onSelect:i,onDelete:r,onRename:o,onDuplicate:d,isMenuOpen:c,onMenuOpenChange:p}=t,{t:u}=lt();let f;e[0]===Symbol.for("react.memo_cache_sentinel")?(f=hi(),e[0]=f):f=e[0];const m=f;let w;e[1]!==n.source||e[2]!==u?(w=n.source==="claude"?u("settings.skills.sidebar.badge.claude"):n.source==="agents"?u("settings.skills.sidebar.badge.agents"):u("settings.skills.sidebar.badge.opencode"),e[1]=n.source,e[2]=u,e[3]=w):w=e[3];const b=w;let g;e[4]!==n?(g=gi(n),e[4]=n,e[5]=g):g=e[5];const x=g;let k;e[6]!==n?(k=Yo(n),e[6]=n,e[7]=k):k=e[7];const y=k,[C,z]=l.useState(!1);let j;e[8]!==y||e[9]!==r||e[10]!==d||e[11]!==o||e[12]!==u?(j=te=>s.jsxs(s.Fragment,{children:[y?s.jsxs(te,{onClick:T=>{T.stopPropagation(),o()},children:[s.jsx(K,{name:"edit",className:"h-4 w-4 mr-px"}),u("settings.common.actions.rename")]}):null,s.jsxs(te,{onClick:T=>{T.stopPropagation(),d()},children:[s.jsx(K,{name:"file-copy",className:"h-4 w-4 mr-px"}),u("settings.common.actions.duplicate")]}),s.jsxs(te,{onClick:T=>{T.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),u("settings.common.actions.delete")]})]}),e[8]=y,e[9]=r,e[10]=d,e[11]=o,e[12]=u,e[13]=j):j=e[13];const N=j,v=!x&&C,P=a?"bg-interactive-selection":"hover:bg-interactive-hover";let $;e[14]!==P?($=fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",P),e[14]=P,e[15]=$):$=e[15];let O;e[16]!==x?(O=!m&&!x?te=>{te.preventDefault(),z(!0)}:void 0,e[16]=x,e[17]=O):O=e[17];let M;e[18]!==$||e[19]!==O?(M=s.jsx("div",{className:$,onContextMenu:O}),e[18]=$,e[19]=O,e[20]=M):M=e[20];let S;e[21]!==n.name?(S=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n.name}),e[21]=n.name,e[22]=S):S=e[22];let F;e[23]!==n.scope?(F=s.jsx("span",{className:"typography-micro text-muted-foreground bg-[var(--surface-muted)] px-1 rounded flex-shrink-0 leading-none pb-px border border-[var(--interactive-border)]/50",children:n.scope}),e[23]=n.scope,e[24]=F):F=e[24];let E;e[25]!==b?(E=s.jsx("span",{className:"typography-micro text-muted-foreground bg-[var(--surface-muted)] px-1 rounded flex-shrink-0 leading-none pb-px border border-[var(--interactive-border)]/50",children:b}),e[25]=b,e[26]=E):E=e[26];let D;e[27]!==S||e[28]!==F||e[29]!==E?(D=s.jsxs("div",{className:"flex items-center gap-1.5",children:[S,F,E]}),e[27]=S,e[28]=F,e[29]=E,e[30]=D):D=e[30];let W;e[31]!==i||e[32]!==D?(W=s.jsx("button",{onClick:i,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:D}),e[31]=i,e[32]=D,e[33]=W):W=e[33];let H;e[34]!==x||e[35]!==c||e[36]!==p||e[37]!==N?(H=x?null:s.jsxs(fs,{open:c,onOpenChange:te=>{te&&z(!1),p(te)},children:[s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"sm",variant:"ghost",className:"h-6 w-6 px-0 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:N(as)})]}),e[34]=x,e[35]=c,e[36]=p,e[37]=N,e[38]=H):H=e[38];let Z;e[39]!==W||e[40]!==H?(Z=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[W,H]}),e[39]=W,e[40]=H,e[41]=Z):Z=e[41];let Y;e[42]!==M||e[43]!==Z?(Y=s.jsx(Gn,{render:M,children:Z}),e[42]=M,e[43]=Z,e[44]=Y):Y=e[44];let A;e[45]!==x||e[46]!==N?(A=x?null:s.jsx(qn,{className:"w-fit min-w-20",children:N(An)}),e[45]=x,e[46]=N,e[47]=A):A=e[47];let X;return e[48]!==Y||e[49]!==A||e[50]!==v?(X=s.jsxs(Wn,{open:v,onOpenChange:z,children:[Y,A]}),e[48]=Y,e[49]=A,e[50]=v,e[51]=X):X=e[51],X};function My(t){return{selectedSkillName:t.selectedSkillName,skills:t.skills,setSelectedSkill:t.setSelectedSkill,setSkillDraft:t.setSkillDraft,deleteSkill:t.deleteSkill,renameSkill:t.renameSkill,getSkillDetail:t.getSkillDetail}}function Ly(t){return t.scope==="project"}function Fy(t){return t.scope==="user"}function Oy(t,e){return t.localeCompare(e)}function zy(t,e){return t.name.localeCompare(e.name)}function Ky(t,e){return t.name.localeCompare(e.name)}const $s=gn()(qa(bi((t,e)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{t({selectedProfileId:n})},loadProfiles:async()=>{t({isLoading:!0});const n=e().profiles;try{const a=await lp();return t({profiles:a,isLoading:!1}),!0}catch(a){return console.error("Failed to load git identity profiles:",a),t({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await op();if(n&&n.userName&&n.userEmail){const a={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};t({globalIdentity:a})}else t({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),t({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await rp();return t({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),t({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=a=>{if(typeof a!="string")return null;const i=a.trim();return i.length>0?i:null};try{let a=null;if(a===null){const i=nn()?.settings;if(i)try{const o=(await i.load())?.settings||{};a=n(o.defaultGitIdentityId)}catch{}}if(a===null)try{const i=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const r=await i.json().catch(()=>null);a=n(r?.defaultGitIdentityId)}}catch{}return t({defaultGitIdentityId:a}),!0}catch(a){return console.error("Failed to load default git identity setting:",a),!1}},setDefaultGitIdentityId:async n=>{try{const a=typeof n=="string"?n.trim():"",i=a.length>0?a:"";return await It({defaultGitIdentityId:i}),t({defaultGitIdentityId:i.length>0?i:null}),!0}catch(a){return console.error("Failed to save default git identity setting:",a),!1}},createProfile:async n=>{try{const a={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return qs("saving"),await ip(a),qs("saved"),await e().loadProfiles(),!0}catch(a){return qs("error"),console.error("Failed to create git identity profile:",a),!1}},updateProfile:async(n,a)=>{try{const i=e().profiles.find(o=>o.id===n);if(!i)throw new Error("Profile not found");const r={...i,...a};return qs("saving"),await ap(n,r),qs("saved"),await e().loadProfiles(),!0}catch(i){return qs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return qs("saving"),await np(n),qs("saved"),e().selectedProfileId===n&&t({selectedProfileId:null}),await e().loadProfiles(),!0}catch(a){return qs("error"),console.error("Failed to delete git identity profile:",a),!1}},getProfileById:n=>{const{profiles:a,globalIdentity:i}=e();return n==="global"?i||void 0:a.find(r=>r.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:a}=e();return a.filter(i=>!n.some(r=>r.authType==="token"&&r.host===i.host))}}),{name:"git-identities-store",storage:Ir(),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=$s);const By=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,_y=t=>{const e=t.trim(),n=e.startsWith("https://")?"https":e.startsWith("git@")?"ssh":"shorthand";if(n==="ssh")return`${e.split(":")[1].replace(/\.git$/i,"")}`;if(n==="https")return e.split("/").slice(3).filter(Boolean).join("/").replace(/\.git$/i,"");const a=e.match(/^([^/\s]+)\/([^/\s]+)(?:\/.+)?$/);return a?`${a[1]}/${a[2].replace(/\.git$/i,"")}`:e},Uy=async()=>{try{const t=nn()?.settings;if(t)return(await t.load())?.settings||{};const e=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return e.ok?await e.json().catch(()=>null):null}catch{return null}},$y=t=>{const e=tt.c(162),{open:n,onOpenChange:a}=t,{t:i}=lt(),r=Nn(Vy),o=Nn(Hy),d=Nn(Wy),c=Nn(Gy),p=Nn(qy),u=$s(Jy),f=$s(Yy),[m,w]=l.useState(""),[b,g]=l.useState(""),[x,k]=l.useState("");let y;e[0]===Symbol.for("react.memo_cache_sentinel")?(y=[],e[0]=y):y=e[0];const[C,z]=l.useState(y),[j,N]=l.useState(null),[v,P]=l.useState(!1);let $;e[1]===Symbol.for("react.memo_cache_sentinel")?($=[],e[1]=$):$=e[1];const[O,M]=l.useState($),[S,F]=l.useState(null),E=l.useRef(0);let D;e[2]===Symbol.for("react.memo_cache_sentinel")?(D=Qe=>{E.current=E.current+1,P(!1),N(null),Qe?.clearIdentity&&(M([]),F(null))},e[2]=D):D=e[2];const W=D;let H,Z;e[3]!==f||e[4]!==n?(H=()=>{n&&(E.current=E.current+1,w(""),g(""),k(""),N(null),P(!1),M([]),F(null),f(),(async()=>{const Qe=await Uy(),nt=Array.isArray(Qe?.skillCatalogs)?Qe?.skillCatalogs:[];z(nt||[])})())},Z=[n,f],e[3]=f,e[4]=n,e[5]=H,e[6]=Z):(H=e[5],Z=e[6]),l.useEffect(H,Z);let Y;e[7]!==b?(Y=b.trim(),e[7]=b,e[8]=Y):Y=e[8];const A=Y;let X;e[9]!==x?(X=x.trim(),e[9]=x,e[10]=X):X=e[10];const te=X;let T;if(e[11]!==C||e[12]!==A||e[13]!==te){let Qe;e[15]!==A||e[16]!==te?(Qe=nt=>{const rt=(nt.source||"").trim(),gt=(nt.subpath||"").trim();return rt===A&&gt===te},e[15]=A,e[16]=te,e[17]=Qe):Qe=e[17],T=C.some(Qe),e[11]=C,e[12]=A,e[13]=te,e[14]=T}else T=e[14];const I=T;let B;e[18]!==u||e[19]!==S||e[20]!==m||e[21]!==r||e[22]!==b||e[23]!==x||e[24]!==i?(B=async()=>{const Qe=b.trim();if(!Qe){J.error(i("settings.skills.catalog.add.toast.repositoryRequired"));return}m.trim()||w(_y(Qe)),P(!1),N(null);const nt=E.current+1;E.current=nt;const rt=await r({source:Qe,subpath:x.trim()||void 0,gitIdentityId:S||void 0});if(E.current!==nt)return;if(!rt.ok){if(rt.error?.kind==="authRequired"){if(ds()){J.error(i("settings.skills.catalog.shared.toast.privateRepoNotSupportedVsCode"));return}const wt=rt.error.identities||[];if(M(wt),!S&&wt.length>0){const Pe=u&&u!=="global"&&wt.some(se=>se.id===u)?u:wt[0].id;F(Pe)}J.error(i("settings.skills.catalog.add.toast.authenticationRequiredScan"));return}J.error(rt.error?.message||i("settings.skills.catalog.add.toast.scanFailed"));return}const gt=rt.items?.length||0;if(N(gt),gt===0){J.error(i("settings.skills.catalog.add.toast.noSkillsFound")),P(!1);return}M([]),P(!0),J.success(i("settings.skills.catalog.shared.toast.foundSkills",{count:gt}))},e[18]=u,e[19]=S,e[20]=m,e[21]=r,e[22]=b,e[23]=x,e[24]=i,e[25]=B):B=e[25];const L=B;let V;e[26]!==C||e[27]!==S||e[28]!==I||e[29]!==m||e[30]!==o||e[31]!==d||e[32]!==a||e[33]!==v||e[34]!==c||e[35]!==b||e[36]!==x||e[37]!==i?(V=async()=>{const Qe=m.trim(),nt=b.trim(),rt=x.trim();if(!Qe){J.error(i("settings.skills.catalog.add.toast.catalogNameRequired"));return}if(!nt){J.error(i("settings.skills.catalog.add.toast.repositoryRequired"));return}if(!v){J.error(i("settings.skills.catalog.add.toast.scanBeforeAdd"));return}if(I){J.error(i("settings.skills.catalog.add.toast.catalogAlreadyExists"));return}const gt={id:By(),label:Qe,source:nt,...rt?{subpath:rt}:{},...S?{gitIdentityId:S}:{}},wt=[...C,gt];try{await It({skillCatalogs:wt}),z(wt),J.success(i("settings.skills.catalog.add.toast.catalogAdded")),await o({refresh:!0}),await d(gt.id,{refresh:!0}),c(gt.id),a(!1)}catch(Pe){const se=Pe;J.error(se instanceof Error?se.message:i("settings.skills.catalog.add.toast.saveFailed"))}},e[26]=C,e[27]=S,e[28]=I,e[29]=m,e[30]=o,e[31]=d,e[32]=a,e[33]=v,e[34]=c,e[35]=b,e[36]=x,e[37]=i,e[38]=V):V=e[38];const Q=V;let G;e[39]!==i?(G=i("settings.skills.catalog.add.title"),e[39]=i,e[40]=G):G=e[40];let ue;e[41]!==G?(ue=s.jsx(_t,{children:G}),e[41]=G,e[42]=ue):ue=e[42];let ne;e[43]!==i?(ne=i("settings.skills.catalog.add.descriptionPrefix"),e[43]=i,e[44]=ne):ne=e[44];let xe;e[45]===Symbol.for("react.memo_cache_sentinel")?(xe=s.jsx("code",{className:"font-mono",children:"SKILL.md"}),e[45]=xe):xe=e[45];let ve;e[46]!==i?(ve=i("settings.skills.catalog.add.descriptionSuffix"),e[46]=i,e[47]=ve):ve=e[47];let me;e[48]!==ne||e[49]!==ve?(me=s.jsxs(Yt,{children:[ne," ",xe,ve]}),e[48]=ne,e[49]=ve,e[50]=me):me=e[50];let ge;e[51]!==ue||e[52]!==me?(ge=s.jsxs(Ut,{children:[ue,me]}),e[51]=ue,e[52]=me,e[53]=ge):ge=e[53];let Ie;e[54]!==i?(Ie=i("settings.skills.catalog.add.field.catalogName"),e[54]=i,e[55]=Ie):Ie=e[55];let oe;e[56]!==Ie?(oe=s.jsx("label",{className:"typography-ui-label text-foreground",children:Ie}),e[56]=Ie,e[57]=oe):oe=e[57];let ce;e[58]===Symbol.for("react.memo_cache_sentinel")?(ce=Qe=>w(Qe.target.value),e[58]=ce):ce=e[58];let pe;e[59]!==i?(pe=i("settings.skills.catalog.add.field.catalogNamePlaceholder"),e[59]=i,e[60]=pe):pe=e[60];let ie;e[61]!==m||e[62]!==pe?(ie=s.jsx(at,{value:m,onChange:ce,placeholder:pe}),e[61]=m,e[62]=pe,e[63]=ie):ie=e[63];let le;e[64]!==oe||e[65]!==ie?(le=s.jsxs("div",{className:"space-y-2",children:[oe,ie]}),e[64]=oe,e[65]=ie,e[66]=le):le=e[66];let de;e[67]!==i?(de=i("settings.skills.catalog.add.field.repository"),e[67]=i,e[68]=de):de=e[68];let he;e[69]!==de?(he=s.jsx("label",{className:"typography-ui-label text-foreground",children:de}),e[69]=de,e[70]=he):he=e[70];let Me;e[71]!==i?(Me=i("settings.skills.catalog.add.field.repositoryHint"),e[71]=i,e[72]=Me):Me=e[72];let Le;e[73]!==Me?(Le=s.jsx($t,{children:Me}),e[73]=Me,e[74]=Le):Le=e[74];let Be;e[75]!==he||e[76]!==Le?(Be=s.jsxs("div",{className:"flex items-center gap-1",children:[he,Le]}),e[75]=he,e[76]=Le,e[77]=Be):Be=e[77];let Fe;e[78]===Symbol.for("react.memo_cache_sentinel")?(Fe=Qe=>{g(Qe.target.value),W({clearIdentity:!0})},e[78]=Fe):Fe=e[78];let De;e[79]!==i?(De=i("settings.skills.catalog.shared.field.repositoryPlaceholder"),e[79]=i,e[80]=De):De=e[80];let ze;e[81]!==b||e[82]!==De?(ze=s.jsx(at,{value:b,onChange:Fe,placeholder:De}),e[81]=b,e[82]=De,e[83]=ze):ze=e[83];let Ve;e[84]!==Be||e[85]!==ze?(Ve=s.jsxs("div",{className:"space-y-2",children:[Be,ze]}),e[84]=Be,e[85]=ze,e[86]=Ve):Ve=e[86];let We;e[87]!==i?(We=i("settings.skills.catalog.add.field.optionalSubpath"),e[87]=i,e[88]=We):We=e[88];let _e;e[89]!==We?(_e=s.jsx("label",{className:"typography-ui-label text-foreground",children:We}),e[89]=We,e[90]=_e):_e=e[90];let He;e[91]===Symbol.for("react.memo_cache_sentinel")?(He=Qe=>{k(Qe.target.value),W({clearIdentity:!0})},e[91]=He):He=e[91];let Ke;e[92]!==i?(Ke=i("settings.skills.catalog.shared.field.subpathPlaceholder"),e[92]=i,e[93]=Ke):Ke=e[93];let Oe;e[94]!==x||e[95]!==Ke?(Oe=s.jsx(at,{value:x,onChange:He,placeholder:Ke}),e[94]=x,e[95]=Ke,e[96]=Oe):Oe=e[96];let je;e[97]!==_e||e[98]!==Oe?(je=s.jsxs("div",{className:"space-y-2",children:[_e,Oe]}),e[97]=_e,e[98]=Oe,e[99]=je):je=e[99];let Te;e[100]!==S||e[101]!==O||e[102]!==i?(Te=O.length>0&&!ds()?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center",children:[s.jsx("span",{className:"typography-ui-label text-[var(--status-warning)]",children:i("settings.skills.catalog.shared.auth.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground ml-2",children:i("settings.skills.catalog.shared.auth.description")}),s.jsx($t,{className:"ml-1",children:i("settings.skills.catalog.shared.auth.footerHint")})]}),s.jsxs(Lt,{value:S||"",onValueChange:Qe=>{F(Qe),W()},children:[s.jsx(Ft,{className:"w-fit",children:s.jsx("span",{children:O.find(Qe=>Qe.id===S)?.name||i("settings.skills.catalog.shared.auth.chooseIdentity")})}),s.jsx(Ot,{align:"start",children:O.map(Qy)})]})]}):null,e[100]=S,e[101]=O,e[102]=i,e[103]=Te):Te=e[103];let Ue;e[104]!==j||e[105]!==i?(Ue=j!==null?s.jsx("div",{className:"typography-meta text-muted-foreground",children:i("settings.skills.catalog.add.scanResult",{count:j})}):null,e[104]=j,e[105]=i,e[106]=Ue):Ue=e[106];let Ye;e[107]!==I||e[108]!==i?(Ye=I?s.jsx("div",{className:"typography-meta text-muted-foreground",children:i("settings.skills.catalog.add.duplicateMessage")}):null,e[107]=I,e[108]=i,e[109]=Ye):Ye=e[109];let q;e[110]!==le||e[111]!==Ve||e[112]!==je||e[113]!==Te||e[114]!==Ue||e[115]!==Ye?(q=s.jsxs("div",{className:"space-y-4",children:[le,Ve,je,Te,Ue,Ye]}),e[110]=le,e[111]=Ve,e[112]=je,e[113]=Te,e[114]=Ue,e[115]=Ye,e[116]=q):q=e[116];let re;e[117]!==a?(re=()=>a(!1),e[117]=a,e[118]=re):re=e[118];let U;e[119]!==i?(U=i("settings.common.actions.cancel"),e[119]=i,e[120]=U):U=e[120];let h;e[121]!==re||e[122]!==U?(h=s.jsx(ee,{size:"sm",variant:"ghost",onClick:re,children:U}),e[121]=re,e[122]=U,e[123]=h):h=e[123];let ae;e[124]!==L?(ae=()=>{L()},e[124]=L,e[125]=ae):ae=e[125];let ye;e[126]!==p||e[127]!==b?(ye=p||!b.trim(),e[126]=p,e[127]=b,e[128]=ye):ye=e[128];let be;e[129]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx(K,{name:"git-repository",className:"h-4 w-4"}),e[129]=be):be=e[129];let Ee;e[130]!==p||e[131]!==i?(Ee=i(p?"settings.skills.catalog.shared.actions.scanning":"settings.skills.catalog.shared.actions.scan"),e[130]=p,e[131]=i,e[132]=Ee):Ee=e[132];let et;e[133]!==ae||e[134]!==ye||e[135]!==Ee?(et=s.jsxs(ee,{size:"sm",className:"gap-2",variant:"ghost",onClick:ae,disabled:ye,children:[be,Ee]}),e[133]=ae,e[134]=ye,e[135]=Ee,e[136]=et):et=e[136];let Ze;e[137]!==Q?(Ze=()=>{Q()},e[137]=Q,e[138]=Ze):Ze=e[138];let it;e[139]!==I||e[140]!==m||e[141]!==v||e[142]!==b?(it=!v||I||!m.trim()||!b.trim(),e[139]=I,e[140]=m,e[141]=v,e[142]=b,e[143]=it):it=e[143];let ot;e[144]!==i?(ot=i("settings.skills.catalog.add.actions.addCatalog"),e[144]=i,e[145]=ot):ot=e[145];let xt;e[146]!==Ze||e[147]!==it||e[148]!==ot?(xt=s.jsx(ee,{size:"sm",onClick:Ze,disabled:it,children:ot}),e[146]=Ze,e[147]=it,e[148]=ot,e[149]=xt):xt=e[149];let bt;e[150]!==h||e[151]!==et||e[152]!==xt?(bt=s.jsxs(rs,{children:[h,et,xt]}),e[150]=h,e[151]=et,e[152]=xt,e[153]=bt):bt=e[153];let Nt;e[154]!==ge||e[155]!==q||e[156]!==bt?(Nt=s.jsxs(Bt,{className:"max-w-xl",children:[ge,q,bt]}),e[154]=ge,e[155]=q,e[156]=bt,e[157]=Nt):Nt=e[157];let Se;return e[158]!==a||e[159]!==n||e[160]!==Nt?(Se=s.jsx(Kt,{open:n,onOpenChange:a,children:Nt}),e[158]=a,e[159]=n,e[160]=Nt,e[161]=Se):Se=e[161],Se};function Vy(t){return t.scanRepo}function Hy(t){return t.loadCatalog}function Wy(t){return t.loadSource}function Gy(t){return t.setSelectedSource}function qy(t){return t.isScanning}function Jy(t){return t.defaultGitIdentityId}function Yy(t){return t.loadDefaultGitIdentityId}function Qy(t){return s.jsx(kt,{value:t.id,children:t.name},t.id)}const Xy=t=>{const e=tt.c(85),{open:n,onOpenChange:a,conflicts:i,onConfirm:r}=t,{t:o}=lt();let d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d={},e[0]=d):d=e[0];const[c,p]=l.useState(d);let u,f;e[1]!==i||e[2]!==n?(u=()=>{if(!n)return;const Q={};for(const G of i)Q[G.skillName]="skip";p(Q)},f=[n,i],e[1]=i,e[2]=n,e[3]=u,e[4]=f):(u=e[3],f=e[4]),l.useEffect(u,f);let m;e[5]!==i?(m=Q=>{const G={};for(const ue of i)G[ue.skillName]=Q;p(G)},e[5]=i,e[6]=m):m=e[6];const w=m;let b;e[7]!==i||e[8]!==c?(b=i.length>0&&i.every(Q=>c[Q.skillName]),e[7]=i,e[8]=c,e[9]=b):b=e[9];const g=b;let x;e[10]!==o?(x=o("settings.skills.catalog.conflicts.title"),e[10]=o,e[11]=x):x=e[11];let k;e[12]!==x?(k=s.jsx(_t,{children:x}),e[12]=x,e[13]=k):k=e[13];let y;e[14]!==o?(y=o("settings.skills.catalog.conflicts.description"),e[14]=o,e[15]=y):y=e[15];let C;e[16]!==y?(C=s.jsx(Yt,{children:y}),e[16]=y,e[17]=C):C=e[17];let z;e[18]!==k||e[19]!==C?(z=s.jsxs(Ut,{children:[k,C]}),e[18]=k,e[19]=C,e[20]=z):z=e[20];let j;e[21]!==i.length||e[22]!==o?(j=o("settings.skills.catalog.conflicts.count",{count:i.length}),e[21]=i.length,e[22]=o,e[23]=j):j=e[23];let N;e[24]!==j?(N=s.jsx("span",{className:"typography-meta text-muted-foreground",children:j}),e[24]=j,e[25]=N):N=e[25];let v;e[26]!==w?(v=()=>w("skip"),e[26]=w,e[27]=v):v=e[27];let P;e[28]!==o?(P=o("settings.skills.catalog.conflicts.actions.skipAll"),e[28]=o,e[29]=P):P=e[29];let $;e[30]!==v||e[31]!==P?($=s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:v,children:P}),e[30]=v,e[31]=P,e[32]=$):$=e[32];let O;e[33]!==w?(O=()=>w("overwrite"),e[33]=w,e[34]=O):O=e[34];let M;e[35]!==o?(M=o("settings.skills.catalog.conflicts.actions.overwriteAll"),e[35]=o,e[36]=M):M=e[36];let S;e[37]!==O||e[38]!==M?(S=s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:O,children:M}),e[37]=O,e[38]=M,e[39]=S):S=e[39];let F;e[40]!==$||e[41]!==S?(F=s.jsxs("div",{className:"flex items-center gap-2",children:[$,S]}),e[40]=$,e[41]=S,e[42]=F):F=e[42];let E;e[43]!==N||e[44]!==F?(E=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[N,F]}),e[43]=N,e[44]=F,e[45]=E):E=e[45];let D;if(e[46]!==i||e[47]!==c||e[48]!==o){let Q;e[50]!==c||e[51]!==o?(Q=G=>s.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label truncate",children:G.skillName}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:o("settings.skills.catalog.conflicts.installedIn",{scope:G.scope==="project"?o("settings.skills.catalog.conflicts.scope.project"):o("settings.skills.catalog.conflicts.scope.user"),source:G.source==="agents"?o("settings.skills.catalog.conflicts.source.agents"):o("settings.skills.catalog.conflicts.source.opencode")})})]}),s.jsxs(Lt,{value:c[G.skillName]||"skip",onValueChange:ue=>p(ne=>({...ne,[G.skillName]:ue})),children:[s.jsx(Ft,{className:"w-fit",children:s.jsx("span",{className:"capitalize",children:(c[G.skillName]||"skip")==="overwrite"?o("settings.skills.catalog.conflicts.decision.overwrite"):o("settings.skills.catalog.conflicts.decision.skip")})}),s.jsxs(Ot,{align:"end",children:[s.jsx(kt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:o("settings.skills.catalog.conflicts.decision.skip")}),s.jsx(kt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:o("settings.skills.catalog.conflicts.decision.overwrite")})]})]})]},G.skillName),e[50]=c,e[51]=o,e[52]=Q):Q=e[52],D=i.map(Q),e[46]=i,e[47]=c,e[48]=o,e[49]=D}else D=e[49];let W;e[53]!==D?(W=s.jsx("div",{className:"space-y-2",children:D}),e[53]=D,e[54]=W):W=e[54];let H;e[55]!==E||e[56]!==W?(H=s.jsxs("div",{className:"space-y-3",children:[E,W]}),e[55]=E,e[56]=W,e[57]=H):H=e[57];let Z;e[58]!==a?(Z=()=>a(!1),e[58]=a,e[59]=Z):Z=e[59];let Y;e[60]!==o?(Y=o("settings.common.actions.cancel"),e[60]=o,e[61]=Y):Y=e[61];let A;e[62]!==Z||e[63]!==Y?(A=s.jsx(ee,{size:"sm",variant:"ghost",onClick:Z,children:Y}),e[62]=Z,e[63]=Y,e[64]=A):A=e[64];let X;e[65]!==c||e[66]!==r?(X=()=>r(c),e[65]=c,e[66]=r,e[67]=X):X=e[67];const te=!g;let T;e[68]!==o?(T=o("settings.skills.catalog.conflicts.actions.continue"),e[68]=o,e[69]=T):T=e[69];let I;e[70]!==X||e[71]!==te||e[72]!==T?(I=s.jsx(ee,{size:"sm",onClick:X,disabled:te,children:T}),e[70]=X,e[71]=te,e[72]=T,e[73]=I):I=e[73];let B;e[74]!==A||e[75]!==I?(B=s.jsxs(rs,{children:[A,I]}),e[74]=A,e[75]=I,e[76]=B):B=e[76];let L;e[77]!==z||e[78]!==H||e[79]!==B?(L=s.jsxs(Bt,{className:"max-w-2xl",children:[z,H,B]}),e[77]=z,e[78]=H,e[79]=B,e[80]=L):L=e[80];let V;return e[81]!==a||e[82]!==n||e[83]!==L?(V=s.jsx(Kt,{open:n,onOpenChange:a,children:L}),e[81]=a,e[82]=n,e[83]=L,e[84]=V):V=e[84],V},pl=[{value:"user-opencode",scope:"user",source:"opencode",label:"User / OpenCode",description:"Global OpenCode config location"},{value:"project-opencode",scope:"project",source:"opencode",label:"Project / OpenCode",description:"Current project .opencode location"},{value:"user-agents",scope:"user",source:"agents",label:"User / Agents",description:"Global .agents compatibility location"},{value:"project-agents",scope:"project",source:"agents",label:"Project / Agents",description:"Current project .agents compatibility location"}];function fi(t,e){return t==="project"&&e==="claude"?"project-claude":t==="project"&&e==="agents"?"project-agents":e==="claude"?"user-claude":t==="project"?"project-opencode":e==="agents"?"user-agents":"user-opencode"}function Uu(t){if(t==="user-claude")return{scope:"user",source:"claude"};if(t==="project-claude")return{scope:"project",source:"claude"};const e=pl.find(n=>n.value===t);return e?{scope:e.scope,source:e.source}:{scope:"user",source:"opencode"}}const Zy=t=>{const e=tt.c(124),{open:n,onOpenChange:a,item:i}=t,{t:r}=lt(),o=Nn(ev),d=Nn(tv),[c,p]=l.useState("user"),[u,f]=l.useState("opencode"),m=is(sv),w=is(nv),[b,g]=l.useState(null),[x,k]=l.useState(!1);let y;e[0]===Symbol.for("react.memo_cache_sentinel")?(y=[],e[0]=y):y=e[0];const[C,z]=l.useState(y),[j,N]=l.useState(null);let v,P;e[1]!==w||e[2]!==n?(v=()=>{n&&(p("user"),f("opencode"),g(w),k(!1),z([]),N(null))},P=[n,w],e[1]=w,e[2]=n,e[3]=v,e[4]=P):(v=e[3],P=e[4]),l.useEffect(v,P);let $;e[5]!==r?($=Oe=>{switch(Oe){case"project-opencode":return r("settings.skills.location.option.projectOpencode.label");case"user-agents":return r("settings.skills.location.option.userAgents.label");case"project-agents":return r("settings.skills.location.option.projectAgents.label");default:return r("settings.skills.location.option.userOpencode.label")}},e[5]=r,e[6]=$):$=e[6];const O=$;let M;e[7]!==r?(M=Oe=>{switch(Oe){case"project-opencode":return r("settings.skills.location.option.projectOpencode.description");case"user-agents":return r("settings.skills.location.option.userAgents.description");case"project-agents":return r("settings.skills.location.option.projectAgents.description");default:return r("settings.skills.location.option.userOpencode.description")}},e[7]=r,e[8]=M):M=e[8];const S=M;let F;e:{if(m.length===0){F=null;break e}if(b&&m.some(Oe=>Oe.id===b)){F=b;break e}if(w&&m.some(Oe=>Oe.id===w)){F=w;break e}F=m[0]?.id??null}const E=F;let D;e:{if(c!=="project"){D=null;break e}const Oe=E;if(!Oe){D=null;break e}let je;if(e[9]!==Oe||e[10]!==m){let Ue;e[12]!==Oe?(Ue=Ye=>Ye.id===Oe,e[12]=Oe,e[13]=Ue):Ue=e[13],je=m.find(Ue),e[9]=Oe,e[10]=m,e[11]=je}else je=e[11];D=je?.path??null}const W=D;let H;e[14]!==o||e[15]!==i||e[16]!==a||e[17]!==r?(H=async Oe=>{const je={skillDir:Oe.skillDir};i?.clawdhub&&(je.clawdhub={slug:i.clawdhub.slug,version:i.clawdhub.version});const Te=await o({source:Oe.source,subpath:Oe.subpath,gitIdentityId:i?.gitIdentityId,scope:Oe.scope,targetSource:Oe.targetSource,selections:[je],conflictPolicy:"prompt",conflictDecisions:Oe.conflictDecisions},{directory:Oe.directoryOverride??null});if(Te.ok){J.success(r("settings.skills.catalog.installSkill.toast.installed")),a(!1);return}if(Te.error?.kind==="conflicts"){N({source:Oe.source,subpath:Oe.subpath,scope:Oe.scope,targetSource:Oe.targetSource,skillDir:Oe.skillDir,directoryOverride:Oe.directoryOverride??null}),z(Te.error.conflicts),k(!0);return}if(Te.error?.kind==="authRequired"){J.error(Te.error.message||r("settings.skills.catalog.installSkill.toast.authRequired"));return}J.error(Te.error?.message||r("settings.skills.catalog.installSkill.toast.installFailed"))},e[14]=o,e[15]=i,e[16]=a,e[17]=r,e[18]=H):H=e[18];const Z=H;if(!i)return null;let Y;e[19]!==r?(Y=r("settings.skills.catalog.installSkill.title"),e[19]=r,e[20]=Y):Y=e[20];let A;e[21]!==Y?(A=s.jsx(_t,{children:Y}),e[21]=Y,e[22]=A):A=e[22];let X;e[23]!==r?(X=r("settings.skills.catalog.installSkill.descriptionPrefix"),e[23]=r,e[24]=X):X=e[24];let te;e[25]!==i.skillName?(te=s.jsx("span",{className:"font-semibold text-foreground",children:i.skillName}),e[25]=i.skillName,e[26]=te):te=e[26];let T;e[27]!==r?(T=r("settings.skills.catalog.installSkill.descriptionSuffix"),e[27]=r,e[28]=T):T=e[28];let I;e[29]!==X||e[30]!==te||e[31]!==T?(I=s.jsxs(Yt,{children:[X," ",te," ",T]}),e[29]=X,e[30]=te,e[31]=T,e[32]=I):I=e[32];let B;e[33]!==A||e[34]!==I?(B=s.jsxs(Ut,{children:[A,I]}),e[33]=A,e[34]=I,e[35]=B):B=e[35];let L;e[36]!==r?(L=r("settings.skills.catalog.installSkill.field.destination"),e[36]=r,e[37]=L):L=e[37];let V;e[38]!==L?(V=s.jsx("span",{className:"typography-ui-label text-foreground",children:L}),e[38]=L,e[39]=V):V=e[39];let Q;e[40]!==c||e[41]!==u?(Q=fi(c,u),e[40]=c,e[41]=u,e[42]=Q):Q=e[42];let G;e[43]===Symbol.for("react.memo_cache_sentinel")?(G=Oe=>{const je=Uu(Oe);p(je.scope),f(je.source==="agents"?"agents":"opencode")},e[43]=G):G=e[43];let ue;e[44]!==c?(ue=c==="user"?s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),e[44]=c,e[45]=ue):ue=e[45];let ne;e[46]!==u?(ne=u==="agents"?s.jsx(K,{name:"robot-2",className:"h-3.5 w-3.5"}):null,e[46]=u,e[47]=ne):ne=e[47];let xe;e[48]!==O||e[49]!==c||e[50]!==u?(xe=O(fi(c,u)),e[48]=O,e[49]=c,e[50]=u,e[51]=xe):xe=e[51];let ve;e[52]!==xe?(ve=s.jsx("span",{children:xe}),e[52]=xe,e[53]=ve):ve=e[53];let me;e[54]!==ue||e[55]!==ne||e[56]!==ve?(me=s.jsxs(Ft,{className:"w-fit gap-1.5",children:[ue,ne,ve]}),e[54]=ue,e[55]=ne,e[56]=ve,e[57]=me):me=e[57];let ge;e[58]!==S||e[59]!==O?(ge=pl.map(Oe=>s.jsx(kt,{value:Oe.value,className:"pr-2 [&>span:first-child]:hidden",children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[Oe.scope==="user"?s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),Oe.source==="agents"?s.jsx(K,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:O(Oe.value)})]}),s.jsx("span",{className:"typography-micro text-muted-foreground ml-5",children:S(Oe.value)})]})},Oe.value)),e[58]=S,e[59]=O,e[60]=ge):ge=e[60];let Ie;e[61]!==ge?(Ie=s.jsx(Ot,{align:"start",children:ge}),e[61]=ge,e[62]=Ie):Ie=e[62];let oe;e[63]!==Q||e[64]!==me||e[65]!==Ie?(oe=s.jsxs(Lt,{value:Q,onValueChange:G,children:[me,Ie]}),e[63]=Q,e[64]=me,e[65]=Ie,e[66]=oe):oe=e[66];let ce;e[67]!==V||e[68]!==oe?(ce=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[V,oe]}),e[67]=V,e[68]=oe,e[69]=ce):ce=e[69];let pe;e[70]!==m||e[71]!==E||e[72]!==c||e[73]!==r?(pe=c==="project"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:r("settings.skills.catalog.installSkill.field.project")}),m.length===0?s.jsx("span",{className:"typography-meta text-muted-foreground",children:r("settings.skills.catalog.installSkill.field.noProjects")}):s.jsxs(Lt,{value:E??"",onValueChange:Oe=>g(Oe),disabled:m.length===1,children:[s.jsx(Ft,{className:"w-fit",children:s.jsx(Wt,{placeholder:r("settings.skills.catalog.installSkill.field.chooseProjectPlaceholder")})}),s.jsx(Ot,{align:"start",children:m.map(av)})]})]}),e[70]=m,e[71]=E,e[72]=c,e[73]=r,e[74]=pe):pe=e[74];let ie;e[75]!==i.warnings?(ie=i.warnings?.length?s.jsx("div",{className:"typography-micro text-[var(--status-warning)] bg-[var(--status-warning)]/10 px-2 py-1.5 rounded",children:i.warnings.join(" · ")}):null,e[75]=i.warnings,e[76]=ie):ie=e[76];let le;e[77]!==ce||e[78]!==pe||e[79]!==ie?(le=s.jsxs("div",{className:"mt-2 space-y-3",children:[ce,pe,ie]}),e[77]=ce,e[78]=pe,e[79]=ie,e[80]=le):le=e[80];let de;e[81]!==a?(de=()=>a(!1),e[81]=a,e[82]=de):de=e[82];let he;e[83]!==r?(he=r("settings.common.actions.cancel"),e[83]=r,e[84]=he):he=e[84];let Me;e[85]!==de||e[86]!==he?(Me=s.jsx(ee,{size:"sm",variant:"ghost",onClick:de,children:he}),e[85]=de,e[86]=he,e[87]=Me):Me=e[87];const Le=d||!i.installable||c==="project"&&!W;let Be;e[88]!==W||e[89]!==Z||e[90]!==i.repoSource||e[91]!==i.repoSubpath||e[92]!==i.skillDir||e[93]!==c||e[94]!==u?(Be=()=>{Z({source:i.repoSource,subpath:i.repoSubpath,scope:c,targetSource:u,skillDir:i.skillDir,directoryOverride:W})},e[88]=W,e[89]=Z,e[90]=i.repoSource,e[91]=i.repoSubpath,e[92]=i.skillDir,e[93]=c,e[94]=u,e[95]=Be):Be=e[95];let Fe;e[96]!==d||e[97]!==r?(Fe=r(d?"settings.skills.catalog.installSkill.actions.installing":"settings.skills.catalog.installSkill.actions.install"),e[96]=d,e[97]=r,e[98]=Fe):Fe=e[98];let De;e[99]!==Le||e[100]!==Be||e[101]!==Fe?(De=s.jsx(ee,{size:"sm",disabled:Le,onClick:Be,children:Fe}),e[99]=Le,e[100]=Be,e[101]=Fe,e[102]=De):De=e[102];let ze;e[103]!==Me||e[104]!==De?(ze=s.jsxs(rs,{children:[Me,De]}),e[103]=Me,e[104]=De,e[105]=ze):ze=e[105];let Ve;e[106]!==B||e[107]!==le||e[108]!==ze?(Ve=s.jsxs(Bt,{className:"max-w-md",children:[B,le,ze]}),e[106]=B,e[107]=le,e[108]=ze,e[109]=Ve):Ve=e[109];let We;e[110]!==a||e[111]!==n||e[112]!==Ve?(We=s.jsx(Kt,{open:n,onOpenChange:a,children:Ve}),e[110]=a,e[111]=n,e[112]=Ve,e[113]=We):We=e[113];let _e;e[114]!==j||e[115]!==Z?(_e=Oe=>{j&&(Z({source:j.source,subpath:j.subpath,scope:j.scope,targetSource:j.targetSource,skillDir:j.skillDir,conflictDecisions:Oe,directoryOverride:j.directoryOverride??null}),k(!1))},e[114]=j,e[115]=Z,e[116]=_e):_e=e[116];let He;e[117]!==C||e[118]!==x||e[119]!==_e?(He=s.jsx(Xy,{open:x,onOpenChange:k,conflicts:C,onConfirm:_e}),e[117]=C,e[118]=x,e[119]=_e,e[120]=He):He=e[120];let Ke;return e[121]!==We||e[122]!==He?(Ke=s.jsxs(s.Fragment,{children:[We,He]}),e[121]=We,e[122]=He,e[123]=Ke):Ke=e[123],Ke};function ev(t){return t.installSkills}function tv(t){return t.isInstalling}function sv(t){return t.projects}function nv(t){return t.activeProjectId}function av(t){return s.jsx(kt,{value:t.id,children:t.label||t.path},t.id)}const iv=async()=>{try{const t=nn()?.settings;if(t)return(await t.load())?.settings||{};const e=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return e.ok?await e.json().catch(()=>null):null}catch{return null}},rv=({mode:t,onModeChange:e,showModeTabs:n=!0})=>{const{t:a}=lt(),{sources:i,itemsBySource:r,selectedSourceId:o,setSelectedSource:d,loadCatalog:c,loadSource:p,loadMoreClawdHub:u,isLoadingCatalog:f,isLoadingSource:m,isLoadingMore:w,loadedSourceIds:b,clawdhubHasMoreBySource:g,lastCatalogError:x}=Nn(Hs(A=>({sources:A.sources,itemsBySource:A.itemsBySource,selectedSourceId:A.selectedSourceId,setSelectedSource:A.setSelectedSource,loadCatalog:A.loadCatalog,loadSource:A.loadSource,loadMoreClawdHub:A.loadMoreClawdHub,isLoadingCatalog:A.isLoadingCatalog,isLoadingSource:A.isLoadingSource,isLoadingMore:A.isLoadingMore,loadedSourceIds:A.loadedSourceIds,clawdhubHasMoreBySource:A.clawdhubHasMoreBySource,lastCatalogError:A.lastCatalogError}))),[k,y]=l.useState(""),[C,z]=l.useState(!1),[j,N]=l.useState(!1),[v,P]=l.useState(null),[$,O]=l.useState(!1),[M,S]=l.useState(!1);l.useEffect(()=>{c()},[c]),l.useEffect(()=>{o&&(b[o]||p(o))},[o,b,p]);const F=l.useMemo(()=>o?r[o]||[]:[],[r,o]),E=l.useMemo(()=>{const A=k.trim().toLowerCase();return A?F.filter(X=>{const te=X.skillName.toLowerCase(),T=(X.description||"").toLowerCase(),I=(X.frontmatterName||"").toLowerCase();return te.includes(A)||T.includes(A)||I.includes(A)}):F},[F,k]),D=l.useMemo(()=>i.find(A=>A.id===o)||null,[i,o]),W=!!(o&&o.startsWith("custom:")),H=D?.source==="clawdhub:registry"||D?.sourceType==="clawdhub",Z=!!(o&&(g[o]??!0)),Y=async()=>{if(!(!o||!W)){O(!0);try{const A=await iv(),te=(Array.isArray(A?.skillCatalogs)?A?.skillCatalogs:[]).filter(T=>T.id!==o);await It({skillCatalogs:te}),await c({refresh:!0}),S(!1)}finally{O(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsxs(ps,{title:a("settings.skills.catalog.page.title"),showSaveStatus:!1,children:[n&&s.jsx("div",{className:"mb-4",children:s.jsx("div",{className:"h-10",children:s.jsx(ma,{items:[{id:"manual",label:a("settings.skills.catalog.page.mode.manual")},{id:"external",label:a("settings.skills.catalog.page.mode.external")}],activeId:t,onSelect:A=>e(A),layoutMode:"fit",variant:"animated",animateActivePill:!1,className:"h-full"})})}),s.jsxs(dt,{title:a("settings.skills.catalog.page.section.sourceRepository"),divider:!1,settingsItem:"skills.catalog.source",contentClassName:"space-y-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-1.5",children:[s.jsxs(Lt,{value:o||"",onValueChange:A=>d(A),children:[s.jsx(Ft,{size:Jt,className:fe(wn,"w-fit"),children:s.jsx(Wt,{placeholder:a("settings.skills.catalog.page.field.selectSourcePlaceholder"),children:D?.label})}),s.jsx(Ot,{align:"start",children:i.map(A=>s.jsx(kt,{value:A.id,children:A.label},A.id))})]}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal h-6 w-6 px-0",onClick:()=>{o?p(o,{refresh:!0}):c({refresh:!0})},disabled:f||m,title:a("settings.skills.catalog.page.actions.refreshTitle"),children:s.jsx(K,{name:"refresh",className:fe("h-3.5 w-3.5",(f||m)&&"animate-spin")})}),W&&s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal h-6 w-6 px-0 text-[var(--status-error)] hover:text-[var(--status-error)]",onClick:()=>S(!0),disabled:$,title:a("settings.skills.catalog.page.actions.removeCatalogTitle"),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(ee,{"data-settings-item":"skills.catalog.add-catalog",size:"xs",className:"!font-normal gap-1",onClick:()=>z(!0),children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"})," ",a("settings.skills.catalog.page.actions.addCatalog")]})]}),s.jsxs("div",{"data-settings-item":"skills.catalog.search",className:"py-1.5",children:[s.jsxs("div",{className:"relative",children:[s.jsx(K,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),s.jsx(at,{value:k,onChange:A=>y(A.target.value),placeholder:a("settings.skills.catalog.shared.field.searchSkillsPlaceholder"),className:"h-7 pl-8 w-full sm:w-64"})]}),s.jsx("span",{className:"typography-meta text-muted-foreground mt-1 block",children:f?a("settings.skills.catalog.page.loading.catalog"):a("settings.skills.catalog.page.foundCount",{count:E.length})})]})]}),x&&s.jsx(dt,{children:s.jsxs("div",{className:"rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-4 py-3",children:[s.jsx("div",{className:"typography-ui-label font-medium text-[var(--status-error)]",children:a("settings.skills.catalog.page.error.catalogTitle")}),s.jsx("div",{className:"typography-meta text-[var(--status-error)]/80 mt-1",children:x.message})]})}),s.jsxs(dt,{children:[E.length===0&&!m?s.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-body",children:a("settings.skills.catalog.page.empty.noSkillsTitle")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:a("settings.skills.catalog.page.empty.noSkillsDescription")})]}):m?s.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[s.jsx(K,{name:"refresh",className:"mx-auto mb-3 h-5 w-5 animate-spin opacity-50"}),s.jsx("p",{className:"typography-meta",children:a("settings.skills.catalog.page.loading.skills")})]}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:E.map(A=>{const X=A.installed?.isInstalled,te=A.installed?.scope;return s.jsx("div",{className:"py-2",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-ui-label font-medium text-foreground truncate",children:A.skillName}),X&&s.jsx("span",{className:"typography-micro text-[var(--status-success)] bg-[var(--status-success)]/10 px-1.5 py-0.5 rounded flex-shrink-0",children:a("settings.skills.catalog.page.badge.installed",{scope:te||a("settings.skills.catalog.page.badge.unknown")})}),!A.installable&&s.jsx("span",{className:"typography-micro text-[var(--status-warning)] bg-[var(--status-warning)]/10 px-1.5 py-0.5 rounded flex-shrink-0",children:a("settings.skills.catalog.page.badge.notInstallable")})]}),A.description?s.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:A.description}):s.jsx("div",{className:"typography-meta text-muted-foreground/50 mt-0.5 italic",children:a("settings.skills.catalog.shared.noDescription")}),A.clawdhub&&s.jsxs("div",{className:"typography-micro text-muted-foreground mt-1.5 flex items-center gap-3",children:[A.clawdhub.owner&&s.jsxs("span",{children:[a("settings.skills.catalog.page.byOwnerPrefix")," ",s.jsx("span",{className:"font-medium text-foreground/80",children:A.clawdhub.owner})]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(K,{name:"download",className:"h-3 w-3"}),A.clawdhub.downloads?.toLocaleString()??0]}),(A.clawdhub.stars??0)>0&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(K,{name:"star",className:"h-3 w-3"}),A.clawdhub.stars]}),s.jsxs("span",{className:"bg-[var(--surface-muted)] px-1.5 py-0.5 rounded",children:["v",A.clawdhub.version]})]}),A.warnings?.length?s.jsx("div",{className:"typography-micro text-[var(--status-warning)] mt-1.5 bg-[var(--status-warning)]/10 px-2 py-1 rounded w-fit",children:A.warnings.join(" · ")}):null]}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal shrink-0",disabled:!A.installable,onClick:()=>{P(A),N(!0)},children:a("settings.skills.catalog.shared.actions.install")})]})},`${A.sourceId}:${A.skillDir}`)})}),H&&Z&&!m&&E.length>0&&s.jsx("div",{className:"flex justify-center mt-2",children:s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{u()},disabled:w,children:a(w?"settings.skills.catalog.page.loading.more":"settings.skills.catalog.page.actions.loadMoreSkills")})})]})]}),s.jsx($y,{open:C,onOpenChange:z}),s.jsx(Zy,{open:j,onOpenChange:N,item:v}),s.jsx(Kt,{open:M,onOpenChange:A=>{$||S(A)},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:a("settings.skills.catalog.page.removeDialog.title")}),s.jsx(Yt,{children:a("settings.skills.catalog.page.removeDialog.description")})]}),s.jsxs(rs,{children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>S(!1),disabled:$,children:a("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",variant:"destructive",onClick:()=>{Y()},disabled:$,children:a("settings.skills.catalog.page.actions.removeCatalog")})]})]})})]})},ov=()=>{const t=tt.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(rv,{mode:"external",onModeChange:pv,showModeTabs:!1}),t[0]=e):e=t[0],e},lv="SKILL.md",cv="h-[clamp(320px,58dvh,680px)] min-h-[260px] max-h-[calc(100dvh-220px)]",ir=(t,e)=>{const n=uf({description:t}).trimEnd(),a=e.trimStart();return`---
28
- ${n}
29
- ---${a?`
30
-
31
- ${a}`:`
32
- `}`},dv=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$u=t=>{const e=t.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/);if(!e)return{description:null,instructions:t};let n=null;try{const a=mf(e[1]);if(dv(a)){const i=a.description;typeof i=="string"&&(n=i)}}catch{n=null}return{description:n,instructions:e[2].replace(/^\r?\n/,"")}},uv=(t,e)=>{const n=$u(t);return ir(e,n.instructions)},mv=()=>{const{t}=lt(),{currentTheme:e}=Ha(),{selectedSkillName:n,getSkillByName:a,getSkillDetail:i,createSkill:r,updateSkill:o,skills:d,skillDraft:c,setSkillDraft:p,setSelectedSkill:u}=Cn(Hs(je=>({selectedSkillName:je.selectedSkillName,getSkillByName:je.getSkillByName,getSkillDetail:je.getSkillDetail,createSkill:je.createSkill,updateSkill:je.updateSkill,skills:je.skills,skillDraft:je.skillDraft,setSkillDraft:je.setSkillDraft,setSelectedSkill:je.setSelectedSkill}))),f=n?a(n):null,m=!!(c&&c.name===n&&!f),w=!!(n&&!f&&!c),b=f?.path==="<built-in>";l.useEffect(()=>{w&&u(null)},[w,u]);const[g,x]=l.useState(""),[k,y]=l.useState("user"),[C,z]=l.useState("opencode"),[j,N]=l.useState(""),[v,P]=l.useState(""),[$,O]=l.useState(()=>ir("","")),[M,S]=l.useState("edit"),[F,E]=l.useState([]),[D,W]=l.useState([]),[H,Z]=l.useState(!1),[Y,A]=l.useState(!1),[X,te]=l.useState(""),[T,I]=l.useState(""),[B,L]=l.useState(!1),[V,Q]=l.useState(""),[G,ue]=l.useState(""),[ne,xe]=l.useState(null),[ve,me]=l.useState(!1),[ge,Ie]=l.useState(""),[oe,ce]=l.useState(null),[pe,ie]=l.useState(!1),le=m?g.trim()!==""||j.trim()!==""||v.trim()!==""||D.length>0:j!==X||v!==T,de=ne?G!==ge:V.trim()!=="",he=l.useCallback(je=>{switch(je){case"project-opencode":return t("settings.skills.location.option.projectOpencode.label");case"user-claude":return t("settings.skills.location.option.userClaude.label");case"project-claude":return t("settings.skills.location.option.projectClaude.label");case"user-agents":return t("settings.skills.location.option.userAgents.label");case"project-agents":return t("settings.skills.location.option.projectAgents.label");default:return t("settings.skills.location.option.userOpencode.label")}},[t]),Me=l.useCallback(je=>{switch(je){case"project-opencode":return t("settings.skills.location.option.projectOpencode.description");case"user-claude":return t("settings.skills.location.option.userClaude.description");case"project-claude":return t("settings.skills.location.option.projectClaude.description");case"user-agents":return t("settings.skills.location.option.userAgents.description");case"project-agents":return t("settings.skills.location.option.projectAgents.description");default:return t("settings.skills.location.option.userOpencode.description")}},[t]);l.useEffect(()=>{(async()=>{if(m&&c){const Te=c.description||"",Ue=c.instructions||"";x(c.name||""),y(c.scope||"user"),z(c.source==="agents"?"agents":"opencode"),N(Te),P(Ue),O(ir(Te,Ue)),te(""),I(""),E([]),W(c.pendingFiles||[])}else if(n&&f){A(!0);try{const Te=await i(n);if(Te){const Ue=Te.sources.md,Ye=Ue.description||"",q=Ue.instructions||"";N(Ye),P(q),O(ir(Ye,q)),te(Ye),I(q),E(Ue.supportingFiles||[])}}catch(Te){console.error("Failed to load skill details:",Te)}finally{A(!1)}}})()},[f,m,n,d,c,i]);const Le=ke(je=>je.editorFontSize),Be=l.useMemo(()=>{const je=[$o(e,{fontSize:Le})],Te=Do(lv);return Te&&je.push(Te),je.push(tn.lineWrapping),je},[e,Le]),Fe=l.useMemo(()=>{const je=V.trim()||"supporting-file.md",Te=Eo(je),Ue=!!Te&&Te!=="markdown",Ye=[$o(e,Ue?{syntaxColors:!1,fontSize:Le}:{fontSize:Le})],q=Do(je);return q&&Ye.push(q),Ue&&Te&&Ye.push(Du({language:Te,themeName:e.metadata.id,theme:ur(e)})),Ye.push(tn.lineWrapping),Ye},[e,V,Le]),De=l.useCallback(je=>{N(je),O(Te=>uv(Te,je))},[]),ze=l.useCallback(je=>{O(je);const Te=$u(je);N(Te.description??""),P(Te.instructions)},[]),Ve=async()=>{const je=m?g.trim().replace(/\s+/g,"-").toLowerCase():n?.trim();if(!je){J.error(t("settings.skills.page.toast.skillNameRequired"));return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(je)||je.length>64){J.error(t("settings.skills.page.toast.invalidSkillName"));return}if(!j.trim()){J.error(t("settings.skills.page.toast.descriptionRequired"));return}if(m&&d.some(Te=>Te.name===je)){J.error(t("settings.skills.page.toast.skillExists"));return}Z(!0);try{const Te={name:je,description:j.trim(),instructions:v.trim()||void 0,scope:m?k:void 0,source:m?C:void 0,targetPath:m?void 0:f?.path,supportingFiles:m&&D.length>0?D:void 0};let Ue;m?(Ue=await r(Te),Ue&&(p(null),W([]),u(je))):(Ue=await o(je,Te),Ue&&(te(j.trim()),I(v.trim()))),Ue?J.success(t(m?"settings.skills.page.toast.skillCreated":"settings.skills.page.toast.skillUpdated")):J.error(t(m?"settings.skills.page.toast.createSkillFailed":"settings.skills.page.toast.updateSkillFailed"))}catch(Te){console.error("Error saving skill:",Te),J.error(t("settings.skills.page.toast.saveUnexpectedError"))}finally{Z(!1)}},We=()=>{xe(null),Q(""),ue(""),Ie(""),L(!0)},_e=async je=>{if(xe(je),Q(je),m){const Ue=D.find(Ye=>Ye.path===je)?.content||"";ue(Ue),Ie(Ue),L(!0);return}if(n){me(!0),L(!0);try{const{readSupportingFile:Te}=Cn.getState(),Ue=await Te(n,je);ue(Ue||""),Ie(Ue||"")}catch{J.error(t("settings.skills.page.toast.loadFileContentFailed")),ue(""),Ie("")}finally{me(!1)}}},He=async()=>{if(!V.trim()){J.error(t("settings.skills.page.toast.fileNameRequired"));return}const je=V.trim(),Te=ne!==null;if(m){if(Te)W(q=>q.map(re=>re.path===ne?{path:je,content:G}:re)),J.success(t("settings.skills.page.toast.fileUpdated",{path:je}));else{if(D.some(q=>q.path===je)){J.error(t("settings.skills.page.toast.fileExists"));return}W(q=>[...q,{path:je,content:G}]),J.success(t("settings.skills.page.toast.fileAdded",{path:je}))}L(!1),xe(null);return}if(!n){J.error(t("settings.skills.page.toast.noSkillSelected"));return}const{writeSupportingFile:Ue}=Cn.getState();if(await Ue(n,je,G)){J.success(Te?t("settings.skills.page.toast.fileUpdated",{path:je}):t("settings.skills.page.toast.fileCreated",{path:je})),L(!1),xe(null);const q=await i(n);q&&E(q.sources.md.supportingFiles||[])}else J.error(t(Te?"settings.skills.page.toast.updateFileFailed":"settings.skills.page.toast.createFileFailed"))},Ke=je=>{if(m){W(Te=>Te.filter(Ue=>Ue.path!==je)),J.success(t("settings.skills.page.toast.fileRemoved",{path:je}));return}n&&ce(je)},Oe=async()=>{if(!oe||!n)return;ie(!0);const{deleteSupportingFile:je}=Cn.getState();if(await je(n,oe)){J.success(t("settings.skills.page.toast.fileDeleted",{path:oe}));const Ue=await i(n);Ue&&E(Ue.sources.md.supportingFiles||[]),ce(null)}else J.error(t("settings.skills.page.toast.deleteFileFailed"));ie(!1)};return!n&&!c||w?s.jsx("div",{className:"flex h-full items-center justify-center px-4",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"book-open",className:"mx-auto mb-3 h-10 w-10 sm:h-12 sm:w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.skills.page.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.skills.page.empty.description")})]})}):Y?s.jsx("div",{className:"flex h-full items-center justify-center px-4",children:s.jsx("div",{className:"text-center text-muted-foreground",children:s.jsx("p",{className:"typography-body",children:t("settings.skills.page.loading.details")})})}):s.jsxs(s.Fragment,{children:[s.jsxs(ps,{title:m?t("settings.skills.page.title.newSkill"):n,description:f?t("settings.skills.page.subtitle.skillLocation",{location:he(fi(f.scope,f.source))}):t("settings.skills.page.subtitle.newSkill"),showSaveStatus:!1,children:[s.jsxs(dt,{title:t("settings.skills.page.section.basicInformation"),divider:!1,settingsItem:"skills.basic-information",contentClassName:"space-y-0",children:[m&&s.jsxs(Xt,{label:t("settings.skills.page.field.skillNameLocation"),info:t("settings.skills.page.field.skillNameHint"),children:[s.jsx(at,{value:g,onChange:je=>x(je.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:t("settings.skills.page.field.skillNamePlaceholder"),className:"h-7 w-40 px-2"}),s.jsxs(Lt,{value:fi(k,C),onValueChange:je=>{const Te=Uu(je);y(Te.scope),z(Te.source==="agents"?"agents":"opencode")},children:[s.jsxs(Ft,{size:Jt,className:"w-fit gap-1.5",children:[k==="user"?s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),C==="agents"?s.jsx(K,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:he(fi(k,C))})]}),s.jsx(Ot,{align:"start",children:pl.map(je=>s.jsx(kt,{value:je.value,children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[je.scope==="user"?s.jsx(K,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"folder",className:"h-3.5 w-3.5"}),je.source==="agents"?s.jsx(K,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:he(je.value)})]}),s.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:Me(je.value)})]})},je.value))})]})]}),s.jsx(ns,{label:s.jsxs(s.Fragment,{children:[t("settings.common.field.description")," ",s.jsx("span",{className:"text-[var(--status-error)]",children:"*"})]}),info:t("settings.skills.page.field.descriptionHint"),controlClassName:"w-full max-w-none",children:s.jsx(Ns,{value:j,onChange:je=>De(je.target.value),placeholder:t("settings.skills.page.field.descriptionPlaceholder"),rows:2,className:"w-full resize-none min-h-[60px] max-h-32 bg-transparent",disabled:b})})]}),s.jsx(dt,{title:t("settings.skills.page.section.instructions"),headerAction:s.jsx(Pu,{currentMode:M==="preview"?"preview":"edit",onToggle:()=>S(je=>je==="preview"?"edit":"preview")}),settingsItem:"skills.instructions",children:s.jsx("div",{className:fe("overflow-hidden rounded-md border border-[var(--surface-subtle)] bg-background",cv),children:M==="preview"?s.jsx(Os,{outerClassName:"h-full",className:"h-full",children:s.jsx("div",{className:"min-h-full px-4 py-3",children:s.jsx(dr,{content:$,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})}):s.jsx(_o,{value:$,onChange:ze,readOnly:b,extensions:Be,className:"h-full",enableSearch:!0})})}),s.jsx(dt,{title:t("settings.skills.page.section.supportingFiles"),headerAction:s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal gap-1",onClick:We,disabled:b,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"})," ",t("settings.skills.page.actions.addFile")]}),settingsItem:"skills.supporting-files",children:(()=>{const je=m?D:F;return je.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground py-1.5",children:t("settings.skills.page.supportingFiles.empty")}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:je.map(Te=>s.jsxs("div",{className:"flex items-center gap-2 py-1.5 cursor-pointer group",onClick:()=>_e(Te.path),children:[s.jsx(K,{name:"file",className:"h-3.5 w-3.5 text-muted-foreground flex-shrink-0"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Te.path}),m&&s.jsx("span",{className:"typography-micro text-[var(--status-warning)] bg-[var(--status-warning)]/10 px-1.5 py-0.5 rounded flex-shrink-0",children:t("settings.skills.page.badge.pending")}),!b&&s.jsx(ee,{size:"sm",variant:"ghost",className:"h-5 w-5 px-0 flex-shrink-0 text-muted-foreground hover:text-[var(--status-error)] opacity-0 group-hover:opacity-100 transition-opacity",onClick:Ue=>{Ue.stopPropagation(),Ke(Te.path)},children:s.jsx(K,{name:"delete-bin",className:"h-3 w-3"})})]},Te.path))})})()}),s.jsx(dt,{children:s.jsx(ee,{onClick:Ve,disabled:b||H||!le,size:"xs",className:"!font-normal",children:t(H?"settings.common.actions.saving":m?"settings.skills.page.actions.createSkill":"settings.common.actions.saveChanges")})})]}),s.jsx(Kt,{open:oe!==null,onOpenChange:je=>{!je&&!pe&&ce(null)},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.skills.page.deleteFileDialog.title")}),s.jsx(Yt,{children:t("settings.skills.page.deleteFileDialog.description",{path:oe??""})})]}),s.jsxs(rs,{children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>ce(null),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",variant:"destructive",onClick:Oe,disabled:pe,children:t("settings.common.actions.delete")})]})]})}),s.jsx(Kt,{open:B,onOpenChange:je=>{L(je),je||xe(null)},children:s.jsxs(Bt,{className:"max-w-3xl max-h-[85vh] flex flex-col",children:[s.jsxs(Ut,{className:"flex-shrink-0",children:[s.jsx(_t,{children:t(ne?"settings.skills.page.fileDialog.titleEdit":"settings.skills.page.fileDialog.titleAdd")}),s.jsx(Yt,{children:t(ne?"settings.skills.page.fileDialog.descriptionEdit":"settings.skills.page.fileDialog.descriptionAdd")})]}),ve?s.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("settings.skills.page.loading.fileContent")})}):s.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col pt-2",children:[s.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("label",{className:zt,children:t("settings.skills.page.fileDialog.field.filePath")}),!ne&&s.jsx($t,{children:t("settings.skills.page.fileDialog.field.filePathHint")})]}),s.jsx(at,{value:V,onChange:je=>Q(je.target.value),placeholder:t("settings.skills.page.fileDialog.field.filePathPlaceholder"),className:"text-foreground placeholder:text-muted-foreground focus-visible:ring-[var(--primary-base)]",disabled:ne!==null})]}),s.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[s.jsx("label",{className:`${zt} flex-shrink-0`,children:t("settings.skills.page.fileDialog.field.content")}),s.jsx("div",{className:"h-[45vh] min-h-[250px] max-h-[55vh] overflow-hidden rounded-md border border-[var(--surface-subtle)] bg-background",children:s.jsx(_o,{value:G,onChange:ue,extensions:Fe,className:"h-full",enableSearch:!0})})]})]}),s.jsxs(rs,{className:"mt-4",children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>{L(!1),xe(null)},children:t("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",onClick:He,disabled:ve||!de,children:t(ne?"settings.common.actions.saveChanges":"settings.skills.page.actions.createFile")})]})]})})]})},qc=t=>{const e=tt.c(2),{view:n}=t,a=n===void 0?"installed":n;let i;return e[0]!==a?(i=a==="catalog"?s.jsx(ov,{}):s.jsx(mv,{}),e[0]=a,e[1]=i):i=e[1],i};function pv(){}const gv=t=>{const e=tt.c(38),{onItemSelect:n}=t,{t:a}=lt(),i=is(fv),r=ke(hv),o=ke(xv),{currentTheme:d}=Ha();let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=ds(),e[0]=c):c=e[0];const p=c,u=bv;let f,m;e[1]!==i||e[2]!==r||e[3]!==o?(f=()=>{if(i.length===0){r!==null&&o(null);return}r&&i.some(v=>v.id===r)||o(i[0].id)},m=[i,r,o],e[1]=i,e[2]=r,e[3]=o,e[4]=f,e[5]=m):(f=e[4],m=e[5]),l.useEffect(f,m);let w;e[6]===Symbol.for("react.memo_cache_sentinel")?(w=fe("border-b px-3","pt-4 pb-3"),e[6]=w):w=e[6];let b;e[7]!==a?(b=a("settings.page.projects.title"),e[7]=a,e[8]=b):b=e[8];let g;e[9]!==b?(g=s.jsx("h2",{className:`${fn} mb-3`,children:b}),e[9]=b,e[10]=g):g=e[10];let x;e[11]!==i.length||e[12]!==a?(x=a("settings.projects.sidebar.total",{count:i.length}),e[11]=i.length,e[12]=a,e[13]=x):x=e[13];let k;e[14]!==x?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:x}),e[14]=x,e[15]=k):k=e[15];let y;e[16]!==a?(y=!p&&s.jsx(ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:u,"aria-label":a("settings.projects.sidebar.actions.addProject"),children:s.jsx(K,{name:"add",className:"size-4"})}),e[16]=a,e[17]=y):y=e[17];let C;e[18]!==k||e[19]!==y?(C=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[k,y]}),e[18]=k,e[19]=y,e[20]=C):C=e[20];let z;e[21]!==C||e[22]!==g?(z=s.jsxs("div",{className:w,children:[g,C]}),e[21]=C,e[22]=g,e[23]=z):z=e[23];let j;if(e[24]!==d||e[25]!==n||e[26]!==i||e[27]!==r||e[28]!==o){let v;e[30]!==d||e[31]!==n||e[32]!==r||e[33]!==o?(v=P=>{const $=P.id===r,O=P.icon?cp[P.icon]:null,M=P.color?tu[P.color]??null:null,S=O?s.jsx(K,{name:O,className:fe("h-4 w-4",$?"text-foreground":"text-muted-foreground/70"),style:M?{color:M}:void 0}):s.jsx(K,{name:"folder",className:fe("h-4 w-4",$?"text-foreground":"text-muted-foreground/70"),style:M?{color:M}:void 0}),F=P.iconImage?s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:P.iconBackground?{backgroundColor:P.iconBackground}:void 0,children:s.jsx(su,{project:P,options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:S})}):S;return s.jsx(Jo,{title:P.label||P.path,icon:F,selected:$,onSelect:()=>{o(P.id),n?.()}},P.id)},e[30]=d,e[31]=n,e[32]=r,e[33]=o,e[34]=v):v=e[34],j=i.map(v),e[24]=d,e[25]=n,e[26]=i,e[27]=r,e[28]=o,e[29]=j}else j=e[29];let N;return e[35]!==z||e[36]!==j?(N=s.jsx(Bu,{variant:"background",header:z,children:j}),e[35]=z,e[36]=j,e[37]=N):N=e[37],N};function fv(t){return t.projects}function hv(t){return t.settingsProjectsSelectedId}function xv(t){return t.setSettingsProjectsSelectedId}function bv(){eu.requestDirectoryDialog()}const xi=Us,Pn=t=>{const e=tt.c(11),{title:n,description:a,info:i,settingsItem:r,titleAccessory:o,headerAction:d,children:c,className:p,contentClassName:u,divider:f}=t,m=f===void 0?!0:f;let w;return e[0]!==c||e[1]!==p||e[2]!==u||e[3]!==a||e[4]!==m||e[5]!==d||e[6]!==i||e[7]!==r||e[8]!==n||e[9]!==o?(w=s.jsx(dt,{title:n,description:a,info:i,settingsItem:r,titleAccessory:o,headerAction:d,divider:m,className:p,contentClassName:u,children:c}),e[0]=c,e[1]=p,e[2]=u,e[3]=a,e[4]=m,e[5]=d,e[6]=i,e[7]=r,e[8]=n,e[9]=o,e[10]=w):w=e[10],w},yv=450,vv=({projectRef:t=null,sections:e="all"})=>{const{t:n}=lt(),{isMobile:a,isTablet:i}=Vs(),r=a||i,o=is(T=>T.getActiveProject()),d=t?.path??o?.path??null,c=es(T=>T.getWorktreeMetadata),p=Yd(),u=Cs(T=>T.homeDirectory),[f,m]=l.useState([]),[w,b]=l.useState(!1),[g,x]=l.useState(!1),[k,y]=l.useState(null),[C,z]=l.useState(null),[j,N]=l.useState([]),[v,P]=l.useState(!1),$=l.useRef(!1),O=l.useMemo(()=>t?.id&&t?.path?{id:t.id,path:t.path}:!o?.id||!d?null:{id:o.id,path:d},[o?.id,d,t?.id,t?.path]),M=l.useCallback(async()=>{if(!(!O||C===!1))try{const T=await Sl(O);N(T)}catch{}},[O,C]);l.useEffect(()=>{if(!d)return;let T=!1;return z(null),(async()=>{try{const I=await dp(d);if(T)return;z(I)}catch{}})(),()=>{T=!0}},[d]),l.useEffect(()=>{if(!O){N([]),P(!1);return}if(C===!1){N([]),P(!1);return}let T=!1;return P(!0),N([]),(async()=>{try{const I=await Sl(O);if(T)return;N(I)}catch{}finally{T||P(!1)}})(),()=>{T=!0}},[O,C]),l.useEffect(()=>{if(!O)return;let T=!1;return x(!0),(async()=>{try{const[I,B]=await Promise.all([nu(O),au(O)]);if(!T){const L=I.length>0?I:[""];m(L),y(JSON.stringify(L)),b(B)}}catch{T||(m([""]),y(JSON.stringify([""])),b(!1))}finally{T||x(!1)}})(),()=>{T=!0}},[O]);const S=l.useCallback(async T=>{if(!O)return!1;const I=T.filter(B=>B.trim().length>0);try{return await up(O,I)?(y(JSON.stringify(T)),!0):(J.error(n("settings.openchamber.worktrees.setup.toast.saveFailed")),!1)}catch{return J.error(n("settings.openchamber.worktrees.setup.toast.saveFailed")),!1}},[O,n]),F=l.useMemo(()=>k===null?!1:k!==JSON.stringify(f),[k,f]);l.useEffect(()=>{if(!F||g||$.current)return;const T=window.setTimeout(()=>{$.current||($.current=!0,(async()=>{try{await S(f)}finally{$.current=!1}})())},yv);return()=>{window.clearTimeout(T)}},[F,g,S,f]);const E=l.useCallback((T,I)=>{m(B=>{const L=[...B];return L[T]=I,L})},[]),D=l.useCallback(()=>{m(T=>[...T,""])},[]),W=l.useCallback(T=>{m(I=>{const B=I.filter((L,V)=>V!==T);return B.length>0?B:[""]})},[]),H=l.useCallback(()=>{!F||$.current||($.current=!0,(async()=>{try{await S(f)}finally{$.current=!1}})())},[F,S,f]),Z=l.useCallback(T=>{b(T),O&&mp(O,T)},[O]),Y=l.useCallback(T=>{const I=ve=>ve.replace(/\\/g,"/").replace(/\/+$/,""),B=I(T.path),L=p.filter(ve=>{const me=c(ve.id);if(me?.path&&I(me.path)===B)return!0;const ge=ve.directory;return!!(ge&&I(ge)===B)}),V=new Set(L.map(ve=>ve.id)),Q=[...Ro.getState().activeSessions,...Ro.getState().archivedSessions],G=ve=>{const me=Q.filter(Ie=>{const oe=Ie.parentID;return oe&&ve.has(oe)});if(me.length===0)return[];const ge=new Set(me.map(Ie=>Ie.id));return[...me,...G(ge)]},ue=G(V),ne=new Set,xe=[...L,...ue].filter(ve=>ne.has(ve.id)?!1:(ne.add(ve.id),!0));eu.requestDelete({sessions:xe,mode:"worktree",worktree:T})},[p,c]),A=l.useMemo(()=>p.map(T=>T.id).join(","),[p]);l.useEffect(()=>{C&&d&&M()},[A,C,d,M]);const X=s.jsxs($t,{children:[n("settings.openchamber.worktrees.setup.tooltipPrefix")," ",s.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_PROJECT_PATH"})," ",n("settings.openchamber.worktrees.setup.tooltipSuffix")]}),te=s.jsx($t,{children:n("settings.openchamber.worktrees.list.tooltip")});return d?C===!1?s.jsx(Pn,{title:n("settings.projects.page.section.worktree"),settingsItem:"projects.worktree",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.state.gitOnly")})}):s.jsxs(s.Fragment,{children:[e==="all"?s.jsx(Pn,{title:n("settings.projects.page.section.worktree"),settingsItem:"projects.worktree",titleAccessory:X,children:g?s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.setup.loading")}):s.jsxs("div",{className:fe("space-y-2",xi),children:[f.map((T,I)=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(at,{value:T,onChange:B=>E(I,B.target.value),onBlur:H,placeholder:n("settings.openchamber.worktrees.setup.commandPlaceholder"),className:"h-7 min-w-0 flex-1 font-mono text-xs"}),s.jsx(ee,{type:"button",variant:"ghost",size:"icon",onClick:()=>W(I),className:"h-7 w-7 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive","aria-label":n("settings.openchamber.worktrees.setup.removeCommandAria"),children:s.jsx(K,{name:"close",className:"h-4 w-4"})})]},I)),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:D,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),n("settings.openchamber.worktrees.setup.addCommand")]}),s.jsxs("label",{"data-settings-item":"projects.worktree.setup.wait",className:"flex cursor-pointer items-center gap-2 py-1",children:[s.jsx(an,{checked:w,onChange:Z,ariaLabel:n("settings.openchamber.worktrees.setup.waitForCommandsAria")}),s.jsx("span",{className:fe("typography-ui-label font-normal",w?"text-foreground":"text-foreground/60"),children:n("settings.openchamber.worktrees.setup.waitForCommands")})]})]})}):null,s.jsx(Pn,{title:n("settings.openchamber.worktrees.list.title"),titleAccessory:te,children:v?s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.list.loading")}):j.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:n("settings.openchamber.worktrees.list.empty")}):s.jsx("div",{className:fe("space-y-1",e==="all"&&xi),children:j.map(T=>s.jsxs("div",{className:"group flex w-full items-center gap-2 py-1.5",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"flex min-w-0 items-center gap-2",children:s.jsx("p",{className:"typography-meta min-w-0 truncate text-foreground",children:T.label||T.branch||n("settings.openchamber.worktrees.list.detachedHead")})}),s.jsx("p",{className:"typography-micro truncate text-muted-foreground/60",children:pp(T.path,u)})]}),s.jsx("button",{type:"button",onClick:()=>Y(T),className:fe("flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground/50 transition-opacity hover:bg-destructive/10 hover:text-destructive focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",r?"opacity-100":"opacity-0 group-hover:opacity-100"),"aria-label":n("settings.openchamber.worktrees.list.deleteWorktreeAria",{name:T.branch||T.label||T.path}),children:s.jsx(K,{name:"delete-bin",className:"h-4 w-4"})})]},T.path))})})]}):s.jsx(Pn,{title:n("settings.projects.page.section.worktree"),settingsItem:"projects.worktree",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.state.selectProject")})})},Jc=(t,e)=>e.updatedAtMs-t.updatedAtMs,Ss=gn((t,e)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!e().isLoading){t({isLoading:!0,error:null});try{const[n,a]=await Promise.all([xp(),Il()]),i={};for(const r of a.sort(Jc))i[r.id]=r;e().listenerReady||await bp(r=>{t(o=>({statusesById:{...o.statusesById,[r.id]:r}}))}),t({instances:n.instances,statusesById:i,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){t({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!e().isImportsLoading){t({isImportsLoading:!0,error:null});try{const n=await hp();t({importCandidates:n,isImportsLoading:!1})}catch(n){t({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Il(),a={};for(const i of n.sort(Jc))a[i.id]=i;t({statusesById:a})}catch(n){t({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{t({isSaving:!0,error:null});try{await fp({instances:n}),t({instances:n,isSaving:!1}),await e().refreshStatuses()}catch(a){throw t({isSaving:!1,error:a instanceof Error?a.message:String(a)}),a}},upsertInstance:async n=>{const a=e().instances,i=a.some(r=>r.id===n.id)?a.map(r=>r.id===n.id?n:r):[n,...a];await e().setInstances(i)},createFromCommand:async(n,a,i)=>{const r=yp(n,a);i&&i.trim()&&(r.nickname=i.trim()),await e().upsertInstance(r)},removeInstance:async n=>{await Cl(n).catch(()=>{});const a=e().instances.filter(i=>i.id!==n);await e().setInstances(a),t(i=>{const r={...i.statusesById};return delete r[n],{statusesById:r}})},connect:async n=>{t({error:null});try{await gp(n),await e().refreshStatuses()}catch(a){throw t({error:a instanceof Error?a.message:String(a)}),a}},disconnect:async n=>{t({error:null});try{await Cl(n),await e().refreshStatuses()}catch(a){throw t({error:a instanceof Error?a.message:String(a)}),a}},retry:async n=>{await e().connect(n)},getStatus:n=>e().statusesById[n]||null,clearError:()=>t({error:null})})),Vu=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],Hu=Object.fromEntries(Vu.map(t=>[t.key,t.Icon])),wv="openchamber:project-actions-updated",jv=t=>{const e=(t||"").trim().replace(/\\/g,"/");return e?e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e:""},YN=(t,e)=>`${jv(t)}::${e}`,kv=t=>{const e=t.trim();return!e||e==="0.0.0.0"||e==="::"?"127.0.0.1":e},Yc=t=>{if(typeof t!="number"||!Number.isFinite(t))return null;const e=Math.round(t);return e<1||e>65535?null:e},Nv=(t,e)=>{if(!e.enabled||e.type!=="local")return null;const n=Yc(e.localPort),a=Yc(e.remotePort);if(!n||!a)return null;const i=kv(e.localHost||t.localForward.bindHost||"127.0.0.1"),r=(e.remoteHost||"127.0.0.1").trim(),o=(t.nickname||t.id||"instance").trim();return{id:`${t.id}::${e.id}`,label:`${o} - ${i}:${n} -> ${r}:${a}`,url:`http://${i}:${n}`}},Wu=t=>{const e=[];for(const n of t)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const a of n.portForwards){const i=Nv(n,a);i&&e.push(i)}return e},QN=(t,e)=>{const n=(t||"").trim();return n&&Wu(e).find(r=>r.id===n)?.url||null},Sv=450,Cv=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Iv=()=>({id:Cv(),name:"",command:"",icon:"play"}),Pv=({projectRef:t})=>{const{t:e}=lt(),n=l.useMemo(()=>ls(),[]),a=Ss(N=>N.instances),i=Ss(N=>N.load),[r,o]=l.useState([]),[d,c]=l.useState(!1),[p,u]=l.useState(null),[f,m]=l.useState({}),w=l.useRef(!1),b=l.useRef(null);l.useEffect(()=>{n&&i().catch(()=>{})},[n,i]),l.useEffect(()=>{let N=!1;return c(!0),(async()=>{try{const v=await vp(t);if(N)return;o(v.actions),u(JSON.stringify({actions:v.actions}))}catch{if(N)return;o([]),u(JSON.stringify({actions:[]}))}finally{N||c(!1)}})(),()=>{N=!0}},[t]);const g=l.useMemo(()=>n?Wu(a):[],[a,n]),x=l.useMemo(()=>r.some(v=>v.name.trim().length===0||v.command.trim().length===0)?e("settings.projects.actions.validation.fillNameAndCommand"):null,[r,e]),k=l.useMemo(()=>p===null?!1:p!==JSON.stringify({actions:r}),[r,p]),y=l.useCallback(async N=>await wp(t,{actions:N,primaryActionId:null})?(u(JSON.stringify({actions:N})),typeof window<"u"&&window.dispatchEvent(new CustomEvent(wv,{detail:{projectId:t.id}})),!0):(J.error(e("settings.projects.actions.toast.saveFailed")),!1),[t,e]);l.useEffect(()=>{if(!k||d||x||w.current)return;const N=window.setTimeout(()=>{w.current||(w.current=!0,(async()=>{try{await y(r)}finally{w.current=!1}})())},Sv);return()=>{window.clearTimeout(N)}},[r,k,d,y,x]),l.useEffect(()=>{if(!k||!x||d){x||(b.current=null);return}const N=window.setTimeout(()=>{b.current!==x&&(b.current=x,J.error(x))},1e3);return()=>{window.clearTimeout(N)}},[k,d,x]);const C=l.useCallback(()=>{const N=Iv();o(v=>[...v,N]),m(v=>({...v,[N.id]:!0}))},[]),z=l.useCallback(N=>{o(v=>v.filter(P=>P.id!==N)),m(v=>{const P={...v};return delete P[N],P})},[]),j=l.useCallback((N,v)=>{o(P=>P.map($=>$.id===N?v($):$))},[]);return s.jsxs(Pn,{title:e("settings.projects.actions.title"),info:e("settings.projects.actions.description"),settingsItem:"projects.actions",headerAction:s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:C,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e("settings.projects.actions.actions.add")]}),contentClassName:"space-y-0",children:[d?s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("settings.projects.actions.state.loading")}):r.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("settings.projects.actions.state.empty")}):s.jsx("div",{className:fe("space-y-0",xi),children:r.map(N=>{const v=N.icon||"play",P=Hu[v]||"play",$=f[N.id]??!1,O=N.name.trim()||e("settings.projects.actions.state.untitled");return s.jsxs(ca,{open:$,onOpenChange:M=>{m(S=>({...S,[N.id]:M}))},className:"py-1.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs(da,{className:"group flex-1 justify-start gap-2 rounded-md px-0 pr-1 py-1 hover:bg-[var(--interactive-hover)] focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",children:[$?s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(K,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"}),s.jsx(K,{name:P,className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O})})]}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal h-7 w-7 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>z(N.id),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsx(ua,{className:"pt-1.5",children:s.jsxs("div",{className:"space-y-2 pb-4 pl-3 pr-1",children:[s.jsxs("div",{className:"flex items-center gap-2 py-1",children:[s.jsxs(fs,{children:[s.jsx(gs,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":e("settings.projects.actions.field.selectIconAria"),children:s.jsx(K,{name:P,className:"h-4 w-4"})})}),s.jsx(hs,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Vu.map(M=>{const S=M.Icon,F=(N.icon||"play")===M.key;return s.jsx("button",{type:"button",onClick:()=>j(N.id,E=>({...E,icon:M.key})),className:fe("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",F&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":e("settings.projects.actions.field.iconAria",{icon:M.label}),children:s.jsx(K,{name:S,className:"h-4 w-4"})},M.key)})})})]}),s.jsx(at,{value:N.name,onChange:M=>j(N.id,S=>({...S,name:M.target.value})),placeholder:e("settings.projects.actions.field.actionNamePlaceholder"),className:"h-7 flex-1 min-w-0"})]}),s.jsxs("div",{className:"py-1",children:[s.jsx("p",{className:"typography-meta mb-0.5 text-muted-foreground",children:e("settings.projects.actions.field.command")}),s.jsx(Ns,{value:N.command,onChange:M=>j(N.id,S=>({...S,command:M.target.value})),placeholder:e("settings.projects.actions.field.commandPlaceholder"),className:"min-h-[88px] w-full font-mono text-xs"})]}),s.jsxs("div",{className:"py-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:e("settings.projects.actions.field.autoOpenUrl")}),s.jsxs("div",{className:"group flex cursor-pointer items-center gap-2",role:"button",tabIndex:0,"aria-pressed":N.autoOpenUrl===!0,onClick:()=>j(N.id,M=>({...M,...M.autoOpenUrl===!0?{autoOpenUrl:void 0}:{autoOpenUrl:!0}})),onKeyDown:M=>{(M.key===" "||M.key==="Enter")&&(M.preventDefault(),j(N.id,S=>({...S,...S.autoOpenUrl===!0?{autoOpenUrl:void 0}:{autoOpenUrl:!0}})))},children:[s.jsx(an,{checked:N.autoOpenUrl===!0,onChange:M=>j(N.id,S=>({...S,...M?{autoOpenUrl:!0}:{autoOpenUrl:void 0}})),ariaLabel:e("settings.projects.actions.field.autoOpenUrlForAria",{title:O})}),s.jsx("span",{className:"typography-ui-label font-normal text-foreground/80",children:e("settings.projects.actions.field.autoOpenUrlDescription")})]})]}),N.autoOpenUrl===!0?s.jsxs("div",{className:"mt-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(at,{value:N.openUrl||"",onChange:M=>j(N.id,S=>({...S,openUrl:M.target.value})),placeholder:e("settings.projects.actions.field.overrideUrlPlaceholder"),className:"h-7 w-full max-w-[24rem]"}),s.jsx($t,{contentClassName:"max-w-xs",children:e("settings.projects.actions.field.overrideUrlTooltip")})]}),n?s.jsxs("div",{className:"mt-2",children:[s.jsx("p",{className:"typography-meta mb-0.5 text-muted-foreground",children:e("settings.projects.actions.field.desktopSshForward")}),g.length>0?s.jsxs(Lt,{value:N.desktopOpenSshForward&&g.some(M=>M.id===N.desktopOpenSshForward)?N.desktopOpenSshForward:"__none__",onValueChange:M=>{j(N.id,S=>({...S,...M==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:M}}))},children:[s.jsx(Ft,{size:Jt,className:"w-full",children:s.jsx(Wt,{placeholder:e("settings.projects.actions.field.useOutputManualUrl")})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"__none__",children:e("settings.projects.actions.field.useOutputManualUrl")}),g.map(M=>s.jsx(kt,{value:M.id,children:M.label},M.id))]})]}):s.jsx("p",{className:"typography-meta text-muted-foreground",children:e("settings.projects.actions.state.noDesktopSshForwards")})]}):null]}):null]})]})})]},N.id)})}),x&&r.length>0?s.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:x}):null]})},Tv=t=>{const e=tt.c(123),{form:n}=t,{t:a}=lt(),{currentTheme:i}=Ha(),{name:r,setName:o,icon:d,setIcon:c,color:p,setColor:u,iconBackground:f,setIconBackground:m,parsedDefaultModel:w,handleDefaultModelChange:b,isUploadingIcon:g,isRemovingCustomIcon:x,isDiscoveringIcon:k,pendingRemoveImageIcon:y,setPendingRemoveImageIcon:C,pendingUploadIconPreviewUrl:z,setPreviewImageFailed:j,hasPendingUploadImageIcon:N,hasCustomIcon:v,effectiveHasImageIcon:P,hasRemovableImageIcon:$,showImagePreview:O,fileInputRef:M,handleUploadIcon:S,handleRemoveImageIcon:F,handleDiscoverIcon:E,currentIconImage:D,project:W}=n;if(!W)return null;const H=p?tu[p]??null:null;let Z;e[0]!==a?(Z=a("settings.projects.page.field.projectName"),e[0]=a,e[1]=Z):Z=e[1];let Y;e[2]!==o?(Y=q=>o(q.target.value),e[2]=o,e[3]=Y):Y=e[3];let A;e[4]!==a?(A=a("settings.projects.page.field.projectNamePlaceholder"),e[4]=a,e[5]=A):A=e[5];let X;e[6]===Symbol.for("react.memo_cache_sentinel")?(X=fe("h-8 rounded-md px-3",xi),e[6]=X):X=e[6];let te;e[7]!==r||e[8]!==Y||e[9]!==A?(te=s.jsx(at,{value:r,onChange:Y,placeholder:A,className:X}),e[7]=r,e[8]=Y,e[9]=A,e[10]=te):te=e[10];let T;e[11]!==Z||e[12]!==te?(T=s.jsx(Pn,{title:Z,settingsItem:"projects.name",divider:!1,children:te}),e[11]=Z,e[12]=te,e[13]=T):T=e[13];let I;e[14]!==a?(I=a("settings.projects.page.field.defaultModel"),e[14]=a,e[15]=I):I=e[15];let B;e[16]!==a?(B=a("settings.projects.page.field.defaultModelDescription"),e[16]=a,e[17]=B):B=e[17];const L=w.providerId,V=w.modelId;let Q;e[18]===Symbol.for("react.memo_cache_sentinel")?(Q=fe("h-8 min-h-8 rounded-md px-3 max-w-48",xi),e[18]=Q):Q=e[18];let G;e[19]!==b||e[20]!==w.modelId||e[21]!==w.providerId?(G=s.jsx(oa,{providerId:L,modelId:V,onChange:b,className:Q}),e[19]=b,e[20]=w.modelId,e[21]=w.providerId,e[22]=G):G=e[22];let ue;e[23]!==G||e[24]!==I||e[25]!==B?(ue=s.jsx(Pn,{title:I,info:B,settingsItem:"projects.default-model",children:G}),e[23]=G,e[24]=I,e[25]=B,e[26]=ue):ue=e[26];let ne;e[27]!==a?(ne=a("settings.projects.page.field.accentColor"),e[27]=a,e[28]=ne):ne=e[28];let xe;e[29]!==u?(xe=()=>u(null),e[29]=u,e[30]=xe):xe=e[30];const ve=p===null?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-border/40 hover:border-border hover:bg-[var(--surface-muted)]";let me;e[31]!==ve?(me=fe("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",ve),e[31]=ve,e[32]=me):me=e[32];let ge;e[33]!==a?(ge=a("settings.projects.page.field.none"),e[33]=a,e[34]=ge):ge=e[34];let Ie;e[35]===Symbol.for("react.memo_cache_sentinel")?(Ie=s.jsx(K,{name:"close",className:"h-4 w-4 text-muted-foreground"}),e[35]=Ie):Ie=e[35];let oe;e[36]!==xe||e[37]!==me||e[38]!==ge?(oe=s.jsx("button",{type:"button",onClick:xe,className:me,title:ge,children:Ie}),e[36]=xe,e[37]=me,e[38]=ge,e[39]=oe):oe=e[39];let ce;e[40]!==p||e[41]!==u?(ce=jp.map(q=>s.jsx("button",{type:"button",onClick:()=>u(q.key),className:fe("h-7 w-7 rounded-md border transition-colors",p===q.key?"border-2 border-foreground ring-1 ring-[var(--primary-base)]/40":"border-transparent hover:border-border/70"),style:{backgroundColor:q.cssVar},title:q.label},q.key)),e[40]=p,e[41]=u,e[42]=ce):ce=e[42];let pe;e[43]!==oe||e[44]!==ce?(pe=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[oe,ce]}),e[43]=oe,e[44]=ce,e[45]=pe):pe=e[45];let ie;e[46]!==ne||e[47]!==pe?(ie=s.jsx(Pn,{title:ne,settingsItem:"projects.accent-color",children:pe}),e[46]=ne,e[47]=pe,e[48]=ie):ie=e[48];let le;e[49]!==a?(le=a("settings.projects.page.field.projectIcon"),e[49]=a,e[50]=le):le=e[50];let de;e[51]!==S?(de=q=>{const re=q.target.files?.[0]??null;S(re),q.currentTarget.value=""},e[51]=S,e[52]=de):de=e[52];let he;e[53]!==M||e[54]!==de?(he=s.jsx("input",{ref:M,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:de}),e[53]=M,e[54]=de,e[55]=he):he=e[55];let Me;e[56]!==c?(Me=()=>c(null),e[56]=c,e[57]=Me):Me=e[57];const Le=d===null?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-border/40 hover:border-border hover:bg-[var(--surface-muted)]";let Be;e[58]!==Le?(Be=fe("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",Le),e[58]=Le,e[59]=Be):Be=e[59];let Fe;e[60]!==a?(Fe=a("settings.projects.page.field.none"),e[60]=a,e[61]=Fe):Fe=e[61];let De;e[62]===Symbol.for("react.memo_cache_sentinel")?(De=s.jsx(K,{name:"close",className:"h-4 w-4 text-muted-foreground"}),e[62]=De):De=e[62];let ze;e[63]!==Me||e[64]!==Be||e[65]!==Fe?(ze=s.jsx("button",{type:"button",onClick:Me,className:Be,title:Fe,children:De}),e[63]=Me,e[64]=Be,e[65]=Fe,e[66]=ze):ze=e[66];let Ve;e[67]!==H||e[68]!==d||e[69]!==c?(Ve=kp.map(q=>{const re=q.Icon;return s.jsx("button",{type:"button",onClick:()=>c(q.key),className:fe("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",d===q.key?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-transparent hover:border-border hover:bg-[var(--surface-muted)]"),title:q.label,children:s.jsx(K,{name:re,className:"w-4 h-4",style:H&&d===q.key?{color:H}:void 0})},q.key)}),e[67]=H,e[68]=d,e[69]=c,e[70]=Ve):Ve=e[70];let We;e[71]!==ze||e[72]!==Ve?(We=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[ze,Ve]}),e[71]=ze,e[72]=Ve,e[73]=We):We=e[73];let _e;e[74]!==D||e[75]!==i||e[76]!==P||e[77]!==N||e[78]!==f||e[79]!==z||e[80]!==W||e[81]!==j||e[82]!==O||e[83]!==a?(_e=P&&O&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:a("settings.projects.page.field.preview")}),s.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-md 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:f?{backgroundColor:f}:void 0,children:N&&z?s.jsx("img",{src:z,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>j(!0)}):s.jsx(su,{project:{...W,iconImage:D??W.iconImage},options:{themeVariant:i.metadata.variant,iconColor:i.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>j(!0)})})})]}),e[74]=D,e[75]=i,e[76]=P,e[77]=N,e[78]=f,e[79]=z,e[80]=W,e[81]=j,e[82]=O,e[83]=a,e[84]=_e):_e=e[84];let He;e[85]!==P||e[86]!==f||e[87]!==m||e[88]!==a?(He=P&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:f??"#000000",onChange:q=>m(q.target.value),className:"h-7 w-9 cursor-pointer rounded border border-border bg-transparent p-1","aria-label":a("settings.projects.page.field.projectIconBackgroundAria")}),s.jsx(at,{value:f??"",onChange:q=>m(q.target.value),placeholder:"#000000",className:"h-7 w-[8rem]"}),s.jsx(ee,{type:"button",size:"xs",variant:"outline",onClick:()=>m(null),className:"h-7 w-7 p-0","aria-label":a("settings.projects.page.field.clearIconBackgroundAria"),title:a("settings.projects.page.field.clearBackground"),disabled:!f,children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]}),e[85]=P,e[86]=f,e[87]=m,e[88]=a,e[89]=He):He=e[89];let Ke;e[90]!==M||e[91]!==E||e[92]!==v||e[93]!==k||e[94]!==g||e[95]!==a?(Ke=!v&&s.jsxs(s.Fragment,{children:[s.jsx(ee,{size:"xs",className:"h-6 !font-normal",onClick:()=>M.current?.click(),disabled:g,children:a(g?"settings.projects.page.actions.uploading":"settings.projects.page.actions.uploadIcon")}),s.jsx(ee,{size:"xs",className:"h-6 !font-normal",variant:"outline",onClick:()=>{E()},disabled:k,children:a(k?"settings.projects.page.actions.discovering":"settings.projects.page.actions.discoverFavicon")})]}),e[90]=M,e[91]=E,e[92]=v,e[93]=k,e[94]=g,e[95]=a,e[96]=Ke):Ke=e[96];let Oe;e[97]!==F||e[98]!==$||e[99]!==x||e[100]!==a?(Oe=$&&s.jsx(ee,{size:"xs",className:"!font-normal",variant:"outline",onClick:()=>{F()},disabled:x,children:a(x?"settings.projects.page.actions.removing":"settings.projects.page.actions.removeProjectIcon")}),e[97]=F,e[98]=$,e[99]=x,e[100]=a,e[101]=Oe):Oe=e[101];let je;e[102]!==x||e[103]!==y||e[104]!==C||e[105]!==a?(je=y&&s.jsx(ee,{size:"xs",className:"!font-normal",variant:"outline",onClick:()=>C(!1),disabled:x,children:a("settings.projects.page.actions.undoRemove")}),e[102]=x,e[103]=y,e[104]=C,e[105]=a,e[106]=je):je=e[106];let Te;e[107]!==Ke||e[108]!==Oe||e[109]!==je?(Te=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Ke,Oe,je]}),e[107]=Ke,e[108]=Oe,e[109]=je,e[110]=Te):Te=e[110];let Ue;e[111]!==le||e[112]!==he||e[113]!==We||e[114]!==_e||e[115]!==He||e[116]!==Te?(Ue=s.jsxs(Pn,{title:le,settingsItem:"projects.icon",contentClassName:"space-y-3",children:[he,We,_e,He,Te]}),e[111]=le,e[112]=he,e[113]=We,e[114]=_e,e[115]=He,e[116]=Te,e[117]=Ue):Ue=e[117];let Ye;return e[118]!==ue||e[119]!==ie||e[120]!==Ue||e[121]!==T?(Ye=s.jsxs(s.Fragment,{children:[T,ue,ie,Ue]}),e[118]=ue,e[119]=ie,e[120]=Ue,e[121]=T,e[122]=Ye):Ye=e[122],Ye},Av=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Ev=t=>{if(!t)return null;const e=t.trim();return e&&Av.test(e)?e.toLowerCase():null},Dv=t=>{const{t:e}=lt(),n=is(ne=>ne.uploadProjectIcon),a=is(ne=>ne.removeProjectIcon),i=is(ne=>ne.discoverProjectIcon),r=is(ne=>t?ne.projects.find(xe=>xe.id===t.id)?.iconImage??null:null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,f]=l.useState(null),[m,w]=l.useState(null),[b,g]=l.useState(void 0),[x,k]=l.useState(!1),[y,C]=l.useState(!1),[z,j]=l.useState(!1),[N,v]=l.useState(!1),[P,$]=l.useState(null),[O,M]=l.useState(null),[S,F]=l.useState(!1),E=l.useRef(null),D=l.useCallback(()=>{$(null),M(ne=>(ne&&URL.revokeObjectURL(ne),null))},[]),W=t?.id??null;l.useEffect(()=>{if(!t){d(""),p(null),f(null),w(null),g(void 0);return}d(t.label??""),p(t.icon??null),f(t.color??null),w(t.iconBackground??null),g(t.defaultModel),v(!1),D(),F(!1)},[t,D]),l.useEffect(()=>()=>{D()},[D]);const H=l.useMemo(()=>Hn(b)??{providerId:"",modelId:""},[b]),Z=!!t?.iconImage,Y=!!(P&&O),A=t?.iconImage?.source==="custom",X=Z&&!N||Y,te=X,T=!!(t&&Z&&!N),I=!S&&(Y||T),B=!!t&&(o.trim()!==(t?.label??"").trim()||c!==(t?.icon??null)||u!==(t?.color??null)||m!==(t?.iconBackground??null)||(b??void 0)!==(t?.defaultModel??void 0)||N||!!P),L=l.useCallback((ne,xe)=>{g(ne&&xe?`${ne}/${xe}`:void 0)},[]),V=l.useCallback(ne=>{!t||!ne||x||(v(!1),F(!1),$(ne),M(xe=>(xe&&URL.revokeObjectURL(xe),URL.createObjectURL(ne))))},[x,t]),Q=l.useCallback(()=>{!t||!te||y||(Y&&D(),v(!!Z),F(!1))},[D,Y,te,Z,y,t]),G=l.useCallback(async()=>{if(!(!t||z)){D(),v(!1),F(!1),j(!0);try{const ne=await i(t.id);if(!ne.ok){J.error(ne.error||e("settings.projects.page.toast.discoverIconFailed"));return}if(ne.skipped){J.success(e("settings.projects.page.toast.customIconAlreadySet"));return}J.success(e("settings.projects.page.toast.iconDiscovered"))}finally{j(!1)}}},[D,i,z,t,e]),ue=l.useCallback(async ne=>{const xe=ne?.silent===!0;if(!t)return null;const ve=o.trim();if(!ve)return null;if(P){k(!0);const ge=await n(t.id,P);if(k(!1),!ge.ok)return J.error(ge.error||e("settings.projects.page.toast.uploadIconFailed")),null;xe||J.success(e("settings.projects.page.toast.iconUpdated")),D(),v(!1)}const me=N&&!!t.iconImage;if(me){C(!0);const ge=await a(t.id);if(C(!1),!ge.ok)return J.error(ge.error||e("settings.projects.page.toast.removeIconFailed")),null;xe||J.success(e("settings.projects.page.toast.iconRemoved")),v(!1),w(null)}return{label:ve,icon:c,color:u,iconBackground:Ev(me?null:m),defaultModel:b??null}},[D,u,b,c,m,o,N,P,t,a,e,n]);return l.useEffect(()=>{F(!1)},[W,r?.updatedAt]),{name:o,setName:d,icon:c,setIcon:p,color:u,setColor:f,iconBackground:m,setIconBackground:w,defaultModel:b,parsedDefaultModel:H,handleDefaultModelChange:L,isUploadingIcon:x,isRemovingCustomIcon:y,isDiscoveringIcon:z,pendingRemoveImageIcon:N,setPendingRemoveImageIcon:v,pendingUploadIconFile:P,pendingUploadIconPreviewUrl:O,previewImageFailed:S,setPreviewImageFailed:F,hasStoredImageIcon:Z,hasPendingUploadImageIcon:Y,hasCustomIcon:A,effectiveHasImageIcon:X,hasRemovableImageIcon:te,showStoredImagePreview:T,showImagePreview:I,fileInputRef:E,clearPendingUploadIcon:D,handleUploadIcon:V,handleRemoveImageIcon:Q,handleDiscoverIcon:G,hasChanges:B,prepareSaveData:ue,currentIconImage:r,project:t}},Rv=450,Mv=(t,e)=>{const{t:n}=lt(),{hasChanges:a,name:i,icon:r,color:o,iconBackground:d,defaultModel:c,pendingRemoveImageIcon:p,pendingUploadIconFile:u,isUploadingIcon:f,isRemovingCustomIcon:m,prepareSaveData:w}=t,b=l.useRef(!1);l.useEffect(()=>{if(!a||!i.trim()||f||m||b.current)return;const g=window.setTimeout(()=>{b.current||(b.current=!0,(async()=>{try{const x=await w({silent:!0});if(x)try{await e(x)}catch{J.error(n("settings.projects.page.toast.saveFailed"))}}finally{b.current=!1}})())},Rv);return()=>{window.clearTimeout(g)}},[o,c,a,r,d,m,f,i,e,p,u,w,n])},Lv=t=>{const e=tt.c(16),{project:n,onIdentitySave:a,showWorktrees:i}=t,r=i===void 0?!0:i,o=Dv(n);let d;e:{if(!n){d=null;break e}let g;e[0]!==n.id||e[1]!==n.path?(g={id:n.id,path:n.path},e[0]=n.id,e[1]=n.path,e[2]=g):g=e[2],d=g}const c=d;let p;if(e[3]!==a?(p=async g=>{await a(g)},e[3]=a,e[4]=p):p=e[4],Mv(o,p),!n||!c)return null;let f;e[5]!==o?(f=s.jsx(Tv,{form:o}),e[5]=o,e[6]=f):f=e[6];let m;e[7]!==c?(m=s.jsx(Pv,{projectRef:c}),e[7]=c,e[8]=m):m=e[8];let w;e[9]!==c||e[10]!==r?(w=r?s.jsx(vv,{projectRef:c}):null,e[9]=c,e[10]=r,e[11]=w):w=e[11];let b;return e[12]!==f||e[13]!==m||e[14]!==w?(b=s.jsxs("div",{className:"space-y-0",children:[f,m,w]}),e[12]=f,e[13]=m,e[14]=w,e[15]=b):b=e[15],b},Fv=()=>{const t=tt.c(30),{t:e}=lt(),n=is(Ov),a=is(zv),i=ke(Kv),r=ke(Bv);let o;e:{if(!i){o=null;break e}let x;t[0]!==n||t[1]!==i?(x=n.find(k=>k.id===i)??null,t[0]=n,t[1]=i,t[2]=x):x=t[2],o=x}const d=o;let c,p;t[3]!==n||t[4]!==i||t[5]!==r?(c=()=>{if(n.length===0){r(null);return}i&&n.some(x=>x.id===i)||r(n[0].id)},p=[n,i,r],t[3]=n,t[4]=i,t[5]=r,t[6]=c,t[7]=p):(c=t[6],p=t[7]),l.useEffect(c,p);let u;t[8]!==d||t[9]!==a?(u=async x=>{d&&a(d.id,{label:x.label,icon:x.icon,color:x.color,iconBackground:x.iconBackground,defaultModel:x.defaultModel??null})},t[8]=d,t[9]=a,t[10]=u):u=t[10];const f=u;if(!d){let x;t[11]!==e?(x=e("settings.page.projects.title"),t[11]=e,t[12]=x):x=t[12];let k;t[13]!==e?(k=e("settings.projects.page.empty.noProjects"),t[13]=e,t[14]=k):k=t[14];let y;t[15]!==k?(y=s.jsx("p",{className:"typography-meta text-muted-foreground",children:k}),t[15]=k,t[16]=y):y=t[16];let C;return t[17]!==x||t[18]!==y?(C=s.jsx(ps,{title:x,showSaveStatus:!0,children:y}),t[17]=x,t[18]=y,t[19]=C):C=t[19],C}let m;t[20]!==d.label||t[21]!==e?(m=d.label??e("settings.projects.page.title.default"),t[20]=d.label,t[21]=e,t[22]=m):m=t[22];const w=m;let b;t[23]!==f||t[24]!==d?(b=s.jsx(Lv,{project:d,onIdentitySave:f}),t[23]=f,t[24]=d,t[25]=b):b=t[25];let g;return t[26]!==w||t[27]!==d.path||t[28]!==b?(g=s.jsx(ps,{title:w,description:d.path,showSaveStatus:!0,outerClassName:"bg-background",children:b}),t[26]=w,t[27]=d.path,t[28]=b,t[29]=g):g=t[29],g};function Ov(t){return t.projects}function zv(t){return t.updateProjectMeta}function Kv(t){return t.settingsProjectsSelectedId}function Bv(t){return t.setSettingsProjectsSelectedId}const fr=we.forwardRef((t,e)=>{const n=tt.c(11);let a,i;n[0]!==t?({className:a,...i}=t,n[0]=t,n[1]=a,n[2]=i):(a=n[1],i=n[2]);let r;n[3]!==a?(r=fe("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[checked]:bg-primary data-[unchecked]:bg-[var(--interactive-border)]",a),n[3]=a,n[4]=r):r=n[4];let o;n[5]===Symbol.for("react.memo_cache_sentinel")?(o={width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},n[5]=o):o=n[5];let d;n[6]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(Kf,{className:fe("pointer-events-none block rounded-full bg-background shadow-none ring-0 transition-transform data-[checked]:translate-x-4 data-[unchecked]:translate-x-0"),style:{width:"16px",height:"16px",minWidth:"16px",minHeight:"16px"}}),n[6]=d):d=n[6];let c;return n[7]!==i||n[8]!==e||n[9]!==r?(c=s.jsx(Bf,{className:r,style:o,...i,ref:e,children:d}),n[7]=i,n[8]=e,n[9]=r,n[10]=c):c=n[10],c});fr.displayName="Switch";const Qo=()=>Math.floor(2e4+Math.random()*3e4),_v=t=>{const e=(t instanceof Error?t.message:String(t)).toLowerCase();return e.includes("address already in use")||e.includes("eaddrinuse")||e.includes("port already in use")},Uv=()=>{if(typeof navigator>"u")return;const t=(navigator.userAgent||"").toLowerCase();if(t.includes("mac"))return"macos";if(t.includes("win"))return"windows";if(t.includes("linux"))return"linux"},Qc=t=>{switch((t||"").toLowerCase()){case"ios":return"iOS";case"android":return"Android";case"macos":case"darwin":return"macOS";case"windows":case"win32":return"Windows";case"linux":return"Linux";default:return null}},Xc=t=>{switch(t){case"config_resolved":return"settings.remoteInstances.page.phase.resolvingConfiguration";case"auth_check":return"settings.remoteInstances.page.phase.checkingAuth";case"master_connecting":return"settings.remoteInstances.page.phase.establishingSsh";case"remote_probe":return"settings.remoteInstances.page.phase.probingRemote";case"installing":return"settings.remoteInstances.page.phase.installingOpenChamber";case"updating":return"settings.remoteInstances.page.phase.updatingOpenChamber";case"server_detecting":return"settings.remoteInstances.page.phase.detectingServer";case"server_starting":return"settings.remoteInstances.page.phase.startingServer";case"forwarding":return"settings.remoteInstances.page.phase.forwardingPorts";case"ready":return"settings.remoteInstances.sidebar.phase.ready";case"degraded":return"settings.remoteInstances.page.phase.reconnecting";case"error":return"settings.remoteInstances.sidebar.phase.error";default:return"settings.remoteInstances.sidebar.phase.idle"}},$v=new Set(["config_resolved","auth_check","master_connecting","remote_probe","installing","updating","server_detecting","server_starting","forwarding"]),Gu=t=>!!(t&&$v.has(t)),Zc=t=>t==="ready"?"bg-[var(--status-success)] animate-pulse":t==="error"?"bg-[var(--status-error)] animate-pulse":t==="degraded"||Gu(t)?"bg-[var(--status-warning)] animate-pulse":"bg-muted-foreground/40",Vv=t=>t.type==="dynamic"?`${t.localHost||"127.0.0.1"}:${t.localPort||0}`:t.type==="remote"?`${t.remoteHost||"127.0.0.1"}:${t.remotePort||0} -> ${t.localHost||"127.0.0.1"}:${t.localPort||0}`:`${t.localHost||"127.0.0.1"}:${t.localPort||0} -> ${t.remoteHost||"127.0.0.1"}:${t.remotePort||0}`,Hv=()=>({id:`forward-${Date.now()}-${Math.random().toString(16).slice(2)}`,enabled:!0,type:"local",localHost:"127.0.0.1",localPort:Qo(),remoteHost:"127.0.0.1",remotePort:80}),Wv=t=>t.trim().replace(/\*/g,"host").replace(/\?/g,"x")||"user@host",yn=t=>{const e=tt.c(7),{label:n,hint:a}=t;let i;e[0]!==n?(i=s.jsx("span",{children:n}),e[0]=n,e[1]=i):i=e[1];let r;e[2]!==a?(r=s.jsx($t,{contentClassName:"max-w-xs",children:a}),e[2]=a,e[3]=r):r=e[3];let o;return e[4]!==i||e[5]!==r?(o=s.jsxs("span",{className:`inline-flex items-center gap-1 ${zt}`,children:[i,r]}),e[4]=i,e[5]=r,e[6]=o):o=e[6],o},Gv=t=>{switch(t){case"remote":return"settings.remoteInstances.page.forwardTypeDescription.remote";case"dynamic":return"settings.remoteInstances.page.forwardTypeDescription.dynamic";default:return"settings.remoteInstances.page.forwardTypeDescription.local"}},ed=(t,e)=>{const n=(t||"").trim();return`${!n||n==="127.0.0.1"||n==="::1"?"localhost":n}:${e||0}`},qv=t=>{const e=(t||"").trim();return!e||e==="0.0.0.0"||e==="::"?"127.0.0.1":e},Jv=t=>{const e=t.match(/^\[(\d{10,})\]\s*(?:\[([A-Z]+)\]\s*)?(.*)$/);if(!e)return t;const n=Number(e[1]),a=Number.isFinite(n)?new Date(n).toISOString():e[1],i=(e[2]||"INFO").toUpperCase(),r=e[3]||"";return`[${a}] [${i}] ${r}`},Xo=(t="",e="")=>({id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`header-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:t,value:e}),Yv=t=>t.trim().toLowerCase()==="authorization",ao=t=>{const e={};for(const n of t){const a=n.name.trim(),i=n.value.trim();a&&i&&!Yv(a)&&(e[a]=i)}return Object.keys(e).length>0?e:void 0},Qv=t=>Object.entries(t||{}).map(([e,n])=>Xo(e,n)),qu=()=>{if(typeof window>"u")return null;const e=Ga()||window.location.href;try{const n=Number(new URL(e).port||window.location.port);return Number.isFinite(n)&&n>0?n:null}catch{const n=Number(window.location.port);return Number.isFinite(n)&&n>0?n:null}},td=t=>{try{const e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}catch{return!1}},Xv=async()=>{const t=Ma(Ga())||window.location.origin;if(!ls()||!Wa())return t;let e;try{e=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}})}catch{return t}if(!e.ok||(await e.json().catch(()=>null))?.desktopLanAccessActive!==!0)return t;const a=await du(),i=qu();return!a||!i?t:`http://${a}:${i}`},io=t=>{const e=t.trim();if(e)try{window.location.assign(e)}catch{window.location.href=e}},Zv=t=>{const e=t.sshCommand.trim(),n=t.nickname?.trim(),a=t.portForwards.map(i=>({...i,localHost:i.localHost?.trim()||"127.0.0.1",localPort:typeof i.localPort=="number"?Math.max(1,Math.min(65535,Math.round(i.localPort))):void 0,remoteHost:i.remoteHost?.trim(),remotePort:typeof i.remotePort=="number"?Math.max(1,Math.min(65535,Math.round(i.remotePort))):void 0}));return{...t,sshCommand:e,...n?{nickname:n}:{nickname:void 0},connectionTimeoutSec:Math.max(5,Math.min(240,Math.round(t.connectionTimeoutSec||60))),localForward:{...t.localForward,bindHost:t.localForward.bindHost==="localhost"||t.localForward.bindHost==="0.0.0.0"?t.localForward.bindHost:"127.0.0.1",preferredLocalPort:typeof t.localForward.preferredLocalPort=="number"?Math.max(1,Math.min(65535,Math.round(t.localForward.preferredLocalPort))):void 0},remoteOpenchamber:{...t.remoteOpenchamber,preferredPort:typeof t.remoteOpenchamber.preferredPort=="number"?Math.max(1,Math.min(65535,Math.round(t.remoteOpenchamber.preferredPort))):void 0},portForwards:a}},ew=()=>{const{t}=lt(),e=ke(_=>_.timeFormatPreference),{clientAuth:n}=Va(),a=ls(),i=Ss(_=>_.instances),r=Ss(_=>_.statusesById),o=Ss(_=>_.importCandidates),d=Ss(_=>_.isLoading),c=Ss(_=>_.isImportsLoading),p=Ss(_=>_.isSaving),u=Ss(_=>_.error),f=Ss(_=>_.load),m=Ss(_=>_.loadImports),w=Ss(_=>_.refreshStatuses),b=Ss(_=>_.upsertInstance),g=Ss(_=>_.createFromCommand),x=Ss(_=>_.removeInstance),k=Ss(_=>_.connect),y=Ss(_=>_.disconnect),C=Ss(_=>_.retry),z=ke(_=>_.settingsRemoteInstancesSelectedId),j=ke(_=>_.setSettingsRemoteInstancesSelectedId),N=l.useMemo(()=>z&&i.find(_=>_.id===z)||null,[i,z]),[v,P]=l.useState(null),[$,O]=l.useState(!1),[M,S]=l.useState(!1),[F,E]=l.useState(null),[D,W]=l.useState([]),[H,Z]=l.useState(null),[Y,A]=l.useState(""),[X,te]=l.useState(!1),[T,I]=l.useState({}),[B,L]=l.useState(!1),[V,Q]=l.useState(!1),[G,ue]=l.useState(()=>Date.now()),[ne,xe]=l.useState([]),[ve,me]=l.useState({}),[ge,Ie]=l.useState("local"),[oe,ce]=l.useState(!1),[pe,ie]=l.useState(!1),[le,de]=l.useState(""),[he,Me]=l.useState(""),[Le,Be]=l.useState(""),[Fe,De]=l.useState([]),[ze,Ve]=l.useState(""),[We,_e]=l.useState(null),[He,Ke]=l.useState(!1),[Oe,je]=l.useState(!1),[Te,Ue]=l.useState(null),[Ye,q]=l.useState(""),[re,U]=l.useState(""),[h,ae]=l.useState(""),[ye,be]=l.useState([]),[Ee,et]=l.useState([]),[Ze,it]=l.useState([]),[ot,xt]=l.useState(!1),[bt,Nt]=l.useState(""),[Se,Qe]=l.useState(null),[nt,rt]=l.useState(null),[gt,wt]=l.useState(null),[Pe,se]=l.useState(null),[Ce,Xe]=l.useState(!1),[Re,Je]=l.useState(!1),[Ge,st]=l.useState("configure"),[jt,Et]=l.useState(!1),[Mt,Zt]=l.useState("relay"),[Qt,St]=l.useState(!0),[Pt,Ne]=l.useState(null),ut=l.useMemo(()=>Ee.filter(_=>!!_.revokedAt).length,[Ee]),[mt,At]=l.useState(!1),[ft,vt]=l.useState("ssh user@example.com"),[Dt,Vt]=l.useState("");l.useEffect(()=>{f(),m()},[f,m]);const ts=l.useCallback(async()=>{ce(!0),_e(null);try{const _=await Bl();xe(_.hosts||[]),Ie(_.defaultHostId||"local")}catch(_){_e(_ instanceof Error?_.message:String(_))}finally{ce(!1)}},[]);l.useEffect(()=>{ts()},[ts]);const os=l.useCallback(async(_,Ae=ge)=>{ie(!0),_e(null);try{await _l({hosts:_,defaultHostId:Ae,initialHostChoiceCompleted:!0}),xe(_),Ie(Ae)}catch(ct){_e(ct instanceof Error?ct.message:String(ct))}finally{ie(!1)}},[ge]),En=l.useCallback(async()=>{const _=Ul(he);if(!_){_e(t("desktopHostSwitcher.error.invalidUrl"));return}const Ae=_.persistedUrl,yt={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:le.trim()||Za(Ae),url:Ae,apiUrl:Ae,...Le.trim()?{clientToken:Le.trim()}:{},...ao(Fe)?{requestHeaders:ao(Fe)}:{}};await os([yt,...ne],ge),de(""),Me(""),Be(""),De([]),Ke(!1),_.redeemUrl&&io(_.redeemUrl)},[ge,Fe,ne,le,Le,he,os,t]),zs=l.useCallback(async()=>{const _=Ig(ze);if(!_){_e(t("settings.remoteInstances.direct.error.invalidConnectLink"));return}const Ae=await Pg().catch(()=>""),ct=JSON.stringify({pairingId:_.pairingId,secret:_.secret,clientLabel:_.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:Uv(),...Ae?{dedupeKey:`desktop:${Ae}`}:{}}),yt={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:ct},Gt=async Ht=>{if(!Ht.ok)return null;const Ls=await Ht.json().catch(()=>null);return(typeof Ls?.clientToken=="string"?Ls.clientToken.trim():"")||null},Bs=[..._.candidates].sort((Ht,Ls)=>(Ht.type==="relay"?1:0)-(Ls.type==="relay"?1:0));let us=null;for(const Ht of Bs){if(Ht.type==="relay"){const Zn=Tg({relayUrl:Ht.relayUrl,serverId:Ht.serverId,hostEncPubJwk:Ht.hostEncPubJwk,...Ht.grant?{grant:Ht.grant}:{}});try{const ka=await Zn.fetch("/api/client-auth/pairing/redeem",yt),Na=await Gt(ka);if(Na){us={kind:"relay",relay:{relayUrl:Ht.relayUrl,serverId:Ht.serverId,hostEncPubJwk:Ht.hostEncPubJwk},token:Na};break}}catch{}finally{Zn.close()}continue}const Ls=Ma(Ht.url);if(Ls)try{const Zn=await fetch(`${Ls}/api/client-auth/pairing/redeem`,yt),ka=await Gt(Zn);if(ka){us={kind:"direct",url:Ls,token:ka};break}}catch{}}if(!us){_e(t("desktopHostSwitcher.error.invalidUrl"));return}const Gs=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,_s=_.candidates.find(Ht=>Ht.type==="relay"),Ms=us.kind==="relay"?us.relay:_s?{relayUrl:_s.relayUrl,serverId:_s.serverId,hostEncPubJwk:_s.hostEncPubJwk}:void 0,on=_.candidates.filter(Ht=>Ht.type!=="relay").map(Ht=>Ma(Ht.url)).find(Ht=>!!Ht),ln=us.kind==="direct"?us.url:on,{token:Qn}=us,Rt=ln||(Ms?Ag(Ms.serverId):null);if(!Rt){_e(t("desktopHostSwitcher.error.invalidUrl"));return}const cs={url:Rt,apiUrl:ln||void 0,clientToken:Qn,...Ms?{relay:Ms}:{}},Xn=ne.find(Ht=>Ms?Ht.relay?.serverId===Ms.serverId:!Ht.relay&&Ma(Ht.apiUrl||Ht.url)===Rt);if(Xn){const Ht=ne.map(Ls=>Ls.id===Xn.id?{...Ls,label:_.label||Ls.label,...cs}:Ls);await os(Ht,ge)}else await os([{id:Gs(),label:_.label||Za(Rt),...cs},...ne],ge);Ve(""),_e(null),je(!1)},[ze,ge,ne,os,t]),ga=l.useCallback(async _=>{const Ae=ne.filter(yt=>yt.id!==_);await os(Ae,ge===_?"local":ge),Te===_&&Ue(null)},[ge,Te,ne,os]),Yn=l.useCallback(_=>{Ue(_.id),q(_.label),U(_.apiUrl||_.url),ae(_.clientToken||""),be(Qv(_.requestHeaders)),_e(null)},[]),Ar=l.useCallback(async()=>{if(!Te)return;const _=Ul(re);if(!_){_e(t("desktopHostSwitcher.error.invalidUrl"));return}const Ae=_.persistedUrl,ct=ne.map(yt=>yt.id===Te?{...yt,label:Ye.trim()||Za(Ae),url:Ae,apiUrl:Ae,clientToken:h.trim()||void 0,requestHeaders:ao(ye)}:yt);await os(ct,ge),Ue(null),_.redeemUrl&&io(_.redeemUrl)},[ge,ye,Ye,h,re,Te,ne,os,t]),vi=l.useCallback(async()=>{const _=ft.trim();if(!_){J.error(t("settings.remoteInstances.page.toast.sshCommandRequired"));return}const Ae=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{await g(Ae,_,Dt.trim()||t("settings.remoteInstances.sidebar.newSshInstanceName")),j(Ae),At(!1),vt("ssh user@example.com"),Vt(""),J.success(t("settings.remoteInstances.page.toast.instanceCreated"))}catch(ct){J.error(t("settings.remoteInstances.sidebar.toast.createFailed"),{description:ct instanceof Error?ct.message:String(ct)})}},[g,j,ft,Dt,t]),Er=l.useCallback(async _=>{await os(ne,_)},[ne,os]);l.useEffect(()=>{if(!a||ne.length===0)return;let _=!1;return Promise.all(ne.map(async Ae=>{const ct=()=>Fg(Ae.relay,{clientToken:Ae.clientToken||null,requestHeaders:Ae.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Ae.relay&&!Ae.apiUrl)return[Ae.id,await ct()];const yt=Ma(Eg(Ae));if(!yt)return[Ae.id,Ae.relay?await ct():{status:"unreachable",latencyMs:0}];const Gt=await Dg(yt,{clientToken:Ae.clientToken||null,requestHeaders:Ae.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Gt.status==="unreachable"&&Ae.relay){const Bs=await ct();if(Bs.status==="ok")return[Ae.id,Bs]}return[Ae.id,Gt]})).then(Ae=>{_||me(Object.fromEntries(Ae))}),()=>{_=!0}},[ne,a]);const Ws=l.useCallback(async _=>{if(n){_?.silent||xt(!0),_?.silent||Qe(null);try{const[Ae,ct]=await Promise.all([n.listClients(),n.listPendingPairings().catch(()=>null)]);et(Ae),ct&&it(ct)}catch(Ae){_?.silent||Qe(Ae instanceof Error?Ae.message:String(Ae))}finally{_?.silent||xt(!1)}}},[n]),Ja=l.useRef(!1);l.useEffect(()=>{if(!(!Re||Ge!=="result"||!gt)){if(Ze.some(_=>_.id===gt)){Ja.current=!0;return}Ja.current&&(wt(null),Je(!1),Ee.some(_=>_.pairingId===gt)&&J.success(t("settings.remoteInstances.clientAuth.addDevice.connectedToast")))}},[Re,Ge,gt,Ze,Ee,t]);const wi=l.useCallback(async _=>{if(n)try{await n.cancelPairing(_),it(Ae=>Ae.filter(ct=>ct.id!==_)),await Ws({silent:!0})}catch(Ae){Qe(Ae instanceof Error?Ae.message:String(Ae))}},[n,Ws]);l.useEffect(()=>{if(!n)return;Ws();const _=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ws({silent:!0})},5e3);return()=>window.clearInterval(_)},[n,Ws]);const ji=l.useCallback(async()=>{if(n?.getPairingTransports)try{const yt=await n.getPairingTransports();return{localUrl:yt.local,lanUrl:yt.lan,relayAvailable:yt.relayAvailable}}catch{}const _=qu(),Ae=_?`http://127.0.0.1:${_}`:td(window.location.origin)?window.location.origin:null;let ct=null;try{const yt=Ma(await Xv());ct=yt&&!td(yt)?yt:null}catch{}return{localUrl:Ae,lanUrl:ct,relayAvailable:!0}},[n]),Dr=l.useCallback(async()=>{Qe(null),rt(null),se(null),Xe(!1),wt(null),st("configure"),St(!0),Je(!0);const _=await ji();Ne(_),Zt(_.relayAvailable?"relay":_.lanUrl?"lan":"local")},[ji]),Rr=l.useCallback(async()=>{if(!(!n?.createPairingSession||!Pt)){Qe(null),Et(!0);try{const _=bt.trim()||void 0;let Ae,ct,yt=!0;Mt==="local"?(Ae=Pt.localUrl??void 0,ct=!1):Mt==="lan"?(Ae=Pt.lanUrl??void 0,ct=Qt):Qt&&Pt.lanUrl?(Ae=Pt.lanUrl,ct=!0):(yt=!1,ct=!0);const{pairing:Gt,server:Bs}=await n.createPairingSession({label:_,allowedClientKinds:["mobile","desktop"],serverUrl:Ae,includeRelay:ct,includeDirect:yt}),us=Rg({pairingId:Gt.id,secret:Gt.secret,label:Bs.label,fingerprint:Gt.fingerprint??void 0,expiresAt:Gt.expiresAt,candidates:Bs.candidates}),Gs=Mg(us);rt(Gs),se(await fu.toDataURL(Gs,{width:1024,margin:2,errorCorrectionLevel:"L"})),Xe(!1),Ja.current=!1,wt(Gt.id),st("result"),await Ws({silent:!0})}catch(_){Qe(_ instanceof Error?_.message:String(_))}finally{Et(!1)}}},[n,Pt,Mt,Qt,bt,Ws]),ki=l.useCallback(()=>{nt&&Vn(nt).then(_=>{_.ok&&(Xe(!0),window.setTimeout(()=>Xe(!1),2e3))})},[nt]),Mr=l.useCallback(async _=>{if(!n)return;const Ae=_.clientKind==="desktop-local";Qe(null);try{if(await n.revokeClient(_.id),Ae&&ls()){const ct=await Bl();await _l({hosts:ct.hosts,defaultHostId:ct.defaultHostId,initialHostChoiceCompleted:ct.initialHostChoiceCompleted,localClientToken:null}),et(yt=>yt.map(Gt=>Gt.id===_.id?{...Gt,revokedAt:new Date().toISOString()}:Gt)),Lg({apiBaseUrl:Ga(),clientToken:null,runtimeKey:"local"});return}await Ws()}catch(ct){Qe(ct instanceof Error?ct.message:String(ct))}},[n,Ws]),Lr=l.useCallback(async()=>{if(n){Qe(null);try{await n.purgeRevokedClients(),await Ws()}catch(_){Qe(_ instanceof Error?_.message:String(_))}}},[n,Ws]);l.useEffect(()=>{P(N)},[N]),l.useEffect(()=>{if(!z)return;const _=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||w()},2e3);return()=>{window.clearInterval(_)}},[w,z]),l.useEffect(()=>{let _=null,Ae=Date.now();const ct=()=>{const Gt=Date.now();Gt-Ae>=1e3&&(ue(Gt),Ae=Gt),_=requestAnimationFrame(ct)};(typeof document>"u"||document.visibilityState==="visible")&&(_=requestAnimationFrame(ct));const yt=()=>{document.visibilityState==="visible"&&_===null?_=requestAnimationFrame(ct):document.visibilityState!=="visible"&&_!==null&&(cancelAnimationFrame(_),_=null)};return document.addEventListener("visibilitychange",yt),()=>{document.removeEventListener("visibilitychange",yt),_!==null&&cancelAnimationFrame(_)}},[]);const Ks=z?r[z]:null,rn=Ks?.phase,fa=rn==="ready",hn=rn==="degraded",Dn=Gu(rn),Rn=fa||(Dn||hn),Fr=Ks?Math.max(0,G-Ks.updatedAtMs):0,ha=hn&&Fr>12e3,Or=l.useMemo(()=>!v||!N?!1:JSON.stringify(v)!==JSON.stringify(N),[v,N]),ys=l.useCallback(_=>{P(Ae=>Ae&&_(Ae))},[]),zr=l.useCallback(async()=>{if(!v)return;const _=Zv(v);if(!_.sshCommand.trim()){J.error(t("settings.remoteInstances.page.toast.sshCommandRequired"));return}if(!(_.localForward.bindHost==="0.0.0.0"&&!window.confirm(t("settings.remoteInstances.page.confirm.bindAllInterfaces")))){if(_.auth.sshPassword?.enabled&&_.auth.sshPassword.value?.trim()&&_.auth.sshPassword.store!=="settings"){const Ae=window.confirm(t("settings.remoteInstances.page.confirm.storeSshPasswordPlaintext"));_.auth.sshPassword.store=Ae?"settings":"never",Ae||(_.auth.sshPassword.value=void 0)}if(_.auth.openchamberPassword?.enabled&&_.auth.openchamberPassword.value?.trim()&&_.auth.openchamberPassword.store!=="settings"){const Ae=window.confirm(t("settings.remoteInstances.page.confirm.storeUiPasswordPlaintext"));_.auth.openchamberPassword.store=Ae?"settings":"never",Ae||(_.auth.openchamberPassword.value=void 0)}try{await b(_),J.success(t("settings.remoteInstances.page.toast.instanceSaved"))}catch(Ae){J.error(t("settings.remoteInstances.page.toast.saveFailed"),{description:Ae instanceof Error?Ae.message:String(Ae)})}}},[v,t,b]),xa=l.useCallback(async(_,Ae)=>{const ct=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{return await g(ct,`ssh ${Ae}`,_),j(ct),J.success(t("settings.remoteInstances.page.toast.instanceCreated")),!0}catch(yt){return J.error(t("settings.remoteInstances.sidebar.toast.createFailed"),{description:yt instanceof Error?yt.message:String(yt)}),!1}},[g,j,t]),ba=l.useCallback(()=>{X||(Z(null),A(""))},[X]),Kr=l.useCallback((_,Ae)=>{if(Ae){Z(_),A(Wv(_));return}xa(_,_)},[xa]),Ni=l.useCallback(async()=>{const _=H,Ae=Y.trim();if(_){if(!Ae){J.error(t("settings.remoteInstances.page.toast.destinationRequired"));return}te(!0);try{await xa(_,Ae)&&(Z(null),A(""))}finally{te(!1)}}},[xa,Y,H,t]),ya=l.useCallback(async()=>{if(N)try{await k(N.id);return}catch(_){if(!_v(_)||!window.confirm(t("settings.remoteInstances.sidebar.confirm.localPortInUseRetry")))throw _;const ct={...N,localForward:{...N.localForward,preferredLocalPort:Qo()}};await b(ct),await k(ct.id),J.success(t("settings.remoteInstances.sidebar.toast.retriedWithRandomPort"))}},[k,N,t,b]),va=l.useCallback(async _=>(await Np(_,600)).map(ct=>Jv(ct)),[]),wa=l.useCallback(async()=>{if(v){O(!0),S(!0),E(null);try{const _=await va(v.id);W(_)}catch(_){W([]),E(_ instanceof Error?_.message:String(_))}finally{S(!1)}}},[v,va]);l.useEffect(()=>{if(!$||!v)return;let _=!1;const Ae=async()=>{try{const yt=await va(v.id);_||(W(yt),E(null))}catch(yt){_||E(yt instanceof Error?yt.message:String(yt))}};Ae();const ct=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ae()},1e3);return()=>{_=!0,window.clearInterval(ct)}},[v,$,va]);const xn=l.useMemo(()=>D.join(`
33
- `),[D]),Ya=l.useCallback(()=>{if(!xn.trim()){J.error(t("settings.remoteInstances.page.toast.noLogsToCopy"));return}Vn(xn).then(_=>{_.ok&&J.success(t("settings.remoteInstances.page.toast.logsCopied"))})},[xn,t]),Qa=l.useCallback(async()=>{if(v)try{await Sp(v.id),W([]),J.success(t("settings.remoteInstances.page.toast.logsCleared"))}catch(_){J.error(t("settings.remoteInstances.page.toast.clearLogsFailed"),{description:_ instanceof Error?_.message:String(_)})}},[v,t]),ja=l.useCallback(async()=>{if(!Ks?.localUrl){J.error(t("settings.remoteInstances.page.toast.instanceUrlUnavailable"));return}const _=Ks.localUrl.trim();if(!_){J.error(t("settings.remoteInstances.page.toast.instanceUrlUnavailable"));return}io(_)},[Ks?.localUrl,t]),qe=l.useCallback(()=>{if(!v)return;L(!0),(Rn?y(v.id):ya()).catch(Ae=>{const ct=Rn?fa?"settings.remoteInstances.page.toast.disconnectFailed":"settings.remoteInstances.page.toast.cancelConnectionFailed":"settings.remoteInstances.page.toast.connectFailed";J.error(t(ct),{description:Ae instanceof Error?Ae.message:String(Ae)})}).finally(()=>{L(!1)})},[Rn,ya,y,v,fa,t]),ms=l.useCallback(()=>{if(!v||Dn)return;Q(!0),(hn?y(v.id).then(()=>ya()):C(v.id)).catch(Ae=>{J.error(t("settings.remoteInstances.page.toast.retryFailed"),{description:Ae instanceof Error?Ae.message:String(Ae)})}).finally(()=>{Q(!1)})},[ya,y,v,Dn,hn,C,t]),Si=t(Dn?"settings.remoteInstances.page.actions.connecting":hn?ha?"settings.remoteInstances.page.actions.reconnectNow":"settings.remoteInstances.page.actions.reconnecting":"settings.remoteInstances.sidebar.actions.retry"),Ci=!B&&!V&&(rn==="error"||rn==="idle"||!rn||hn&&ha)&&!Dn,Ii=t(fa?"settings.remoteInstances.sidebar.actions.disconnect":Rn?"settings.remoteInstances.page.actions.cancel":"settings.remoteInstances.sidebar.actions.connect");if(!v)return s.jsxs(ps,{title:t("settings.page.remoteInstances.title"),children:[n?s.jsxs(dt,{title:t("settings.remoteInstances.clientAuth.title"),info:t("settings.remoteInstances.clientAuth.description"),divider:!1,settingsItem:"remote-instances.client-auth",contentClassName:"space-y-3",children:[s.jsx("div",{children:s.jsxs(ee,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{Dr()},children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.clientAuth.actions.addDevice")]})}),s.jsxs("div",{className:"space-y-2.5",children:[ut>0?s.jsx("div",{className:"flex justify-end",children:s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Lr()},children:t("settings.remoteInstances.clientAuth.actions.clearRevoked")})}):null,ot&&Ee.length===0&&Ze.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.state.loading")}):Ee.length===0&&Ze.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.state.empty")}):s.jsxs(s.Fragment,{children:[Ze.map(_=>s.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[s.jsxs("div",{className:"min-w-0 space-y-0.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-[var(--status-warning)] animate-pulse"}),s.jsx("p",{className:"typography-ui-label text-foreground truncate",children:_.label||t("settings.remoteInstances.clientAuth.field.labelPlaceholder")}),_.usesRelay?s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded shrink-0 leading-none pb-px border border-border/50",children:t("settings.remoteInstances.clientAuth.state.viaRelay")}):null]}),s.jsx("p",{className:"typography-micro text-muted-foreground truncate",children:t("settings.remoteInstances.clientAuth.state.pending")})]}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{wi(_.id)},children:t("settings.common.actions.cancel")})]},`pending-${_.id}`)),Ee.map(_=>{const Ae=_.clientKind==="desktop-local",ct=_.lastUsedAt?Date.parse(_.lastUsedAt):Number.NaN,yt=!_.revokedAt&&(Ae||Number.isFinite(ct)&&Date.now()-ct<9e4),Gt=_.revokedAt?t("settings.remoteInstances.clientAuth.state.revoked"):yt?_.lastTransport==="relay"&&!Ae?t("settings.remoteInstances.clientAuth.state.connectedRelay"):t("settings.remoteInstances.clientAuth.state.connectedDirect"):Number.isFinite(ct)?t("settings.remoteInstances.clientAuth.lastUsed",{date:Cp(ct,e,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}):t("settings.remoteInstances.clientAuth.neverUsed");return s.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[s.jsx("div",{className:"min-w-0",children:s.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5",children:[s.jsx("span",{className:fe("h-2 w-2 shrink-0 rounded-full",_.revokedAt?"bg-muted-foreground/20":yt?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),s.jsx("p",{className:"typography-ui-label text-foreground truncate",children:_.label}),Qc(_.devicePlatform)?s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded shrink-0 leading-none pb-px border border-border/50",children:Qc(_.devicePlatform)}):null,Ae?s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:t("settings.remoteInstances.clientAuth.state.thisDevice")}):null,s.jsx("span",{className:fe("typography-micro truncate",yt&&!_.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:Gt})]})}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Mr(_)},disabled:!!_.revokedAt,children:t("settings.remoteInstances.clientAuth.actions.revoke")})]},_.id)})]})]}),Se?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Se}):null]}):null,a?s.jsxs(dt,{title:t("settings.remoteInstances.direct.title"),info:t("settings.remoteInstances.direct.description"),settingsItem:"remote-instances.direct-hosts",contentClassName:"space-y-4",headerAction:s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",onClick:()=>je(!0),disabled:pe,children:t("settings.remoteInstances.direct.import.action")}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ke(!0),disabled:pe,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.direct.actions.add")]})]}),children:[s.jsx("div",{className:"space-y-2.5",children:oe?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.direct.state.loading")}):ne.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.direct.state.empty")}):ne.map(_=>{const Ae=ve[_.id],ct=Ae?Ae.status==="ok"?"desktopHostSwitcher.status.connected":Ae.status==="auth"?"desktopHostSwitcher.status.authRequired":Ae.status==="update-recommended"?"desktopHostSwitcher.status.updateRecommended":Ae.status==="incompatible"?"desktopHostSwitcher.status.incompatible":Ae.status==="wrong-service"?"desktopHostSwitcher.status.wrongService":"desktopHostSwitcher.status.unreachable":"desktopHostSwitcher.status.checking",yt=Ae?.status==="ok";return s.jsx("div",{className:"py-1.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-0.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:fe("h-2 w-2 shrink-0 rounded-full",Ae?yt?"bg-[var(--status-success)]":"bg-[var(--status-error)]":"bg-muted-foreground/30 animate-pulse")}),s.jsx("p",{className:"typography-ui-label text-foreground truncate",children:Za(_.label)}),ge===_.id?s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:t("desktopHostSwitcher.header.default")}):null,s.jsxs("span",{className:fe("typography-micro shrink-0",yt?"text-[var(--status-success)]":"text-muted-foreground"),children:[t(ct),yt&&typeof Ae?.latencyMs=="number"?t("desktopHostSwitcher.status.ping",{ms:Math.max(0,Math.round(Ae.latencyMs))}):""]})]}),s.jsx("p",{className:fe("typography-micro text-muted-foreground truncate",_.apiUrl&&"font-mono"),children:_.relay&&!_.apiUrl?t("mobile.connect.relay.badge"):Za(_.apiUrl||_.url)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Er(_.id)},disabled:pe||ge===_.id,"aria-label":t("desktopHostSwitcher.actions.setAsDefaultAria"),children:ge===_.id?s.jsx(K,{name:"star-fill",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"star",className:"h-3.5 w-3.5"})}),_.relay&&!_.apiUrl?null:s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>Yn(_),disabled:pe,children:[s.jsx(K,{name:"pencil",className:"h-3.5 w-3.5"}),t("desktopHostSwitcher.actions.edit")]}),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{ga(_.id)},disabled:pe,children:[s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.delete")]})]})]})},_.id)})}),We?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:We}):null]}):null,a?s.jsx(Kt,{open:He,onOpenChange:Ke,children:s.jsxs(Bt,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.remoteInstances.direct.actions.add")}),s.jsx(Yt,{children:t("settings.remoteInstances.direct.addDialog.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),En()},children:[s.jsx(at,{className:"h-8",value:le,onChange:_=>de(_.target.value),placeholder:t("settings.remoteInstances.direct.field.labelPlaceholder"),disabled:pe}),s.jsx(at,{className:"h-8",value:he,onChange:_=>Me(_.target.value),placeholder:t("settings.remoteInstances.direct.field.urlPlaceholder"),disabled:pe,autoFocus:!0}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(at,{className:"h-8",value:Le,onChange:_=>Be(_.target.value),placeholder:t("settings.remoteInstances.direct.field.tokenPlaceholder"),type:"password",disabled:pe}),s.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:t("settings.remoteInstances.direct.note")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(pn,{children:t("settings.remoteInstances.direct.headers.title")}),s.jsx($t,{children:t("settings.remoteInstances.direct.headers.description")})]}),Fe.map(_=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(at,{className:"h-8 font-mono text-xs",value:_.name,onChange:Ae=>De(ct=>ct.map(yt=>yt.id===_.id?{...yt,name:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.namePlaceholder"),disabled:pe}),s.jsx(at,{className:"h-8 font-mono text-xs",value:_.value,onChange:Ae=>De(ct=>ct.map(yt=>yt.id===_.id?{...yt,value:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.valuePlaceholder"),type:"password",disabled:pe}),s.jsx("button",{type:"button",onClick:()=>De(Ae=>Ae.filter(ct=>ct.id!==_.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":t("settings.remoteInstances.direct.headers.removeAria"),disabled:pe,children:s.jsx(K,{name:"close",className:"h-4 w-4"})})]},_.id)),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>De(_=>[..._,Xo()]),disabled:pe,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.direct.headers.actions.add")]})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ke(!1),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:pe||!he.trim(),children:t("settings.remoteInstances.direct.actions.add")})]})]})]})}):null,a?s.jsx(Kt,{open:!!Te,onOpenChange:_=>{_||Ue(null)},children:s.jsxs(Bt,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("desktopHostSwitcher.actions.edit")}),s.jsx(Yt,{children:t("settings.remoteInstances.direct.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),Ar()},children:[s.jsx(at,{className:"h-8",value:Ye,onChange:_=>q(_.target.value),placeholder:t("settings.remoteInstances.direct.field.labelPlaceholder"),disabled:pe}),s.jsx(at,{className:"h-8",value:re,onChange:_=>U(_.target.value),placeholder:t("settings.remoteInstances.direct.field.urlPlaceholder"),disabled:pe,autoFocus:!0}),s.jsx(at,{className:"h-8",value:h,onChange:_=>ae(_.target.value),placeholder:t("settings.remoteInstances.direct.field.tokenPlaceholder"),type:"password",disabled:pe}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(pn,{children:t("settings.remoteInstances.direct.headers.title")}),s.jsx($t,{children:t("settings.remoteInstances.direct.headers.description")})]}),ye.map(_=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(at,{className:"h-8 font-mono text-xs",value:_.name,onChange:Ae=>be(ct=>ct.map(yt=>yt.id===_.id?{...yt,name:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.namePlaceholder"),disabled:pe}),s.jsx(at,{className:"h-8 font-mono text-xs",value:_.value,onChange:Ae=>be(ct=>ct.map(yt=>yt.id===_.id?{...yt,value:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.valuePlaceholder"),type:"password",disabled:pe}),s.jsx("button",{type:"button",onClick:()=>be(Ae=>Ae.filter(ct=>ct.id!==_.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":t("settings.remoteInstances.direct.headers.removeAria"),disabled:pe,children:s.jsx(K,{name:"close",className:"h-4 w-4"})})]},_.id)),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>be(_=>[..._,Xo()]),disabled:pe,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.direct.headers.actions.add")]})]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ue(null),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:pe,children:t("settings.common.actions.saveChanges")})]})]})]})}):null,a?s.jsx(Kt,{open:Oe,onOpenChange:je,children:s.jsxs(Bt,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.remoteInstances.direct.import.action")}),s.jsx(Yt,{children:t("settings.remoteInstances.direct.import.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),zs()},children:[s.jsx(at,{className:"h-8",value:ze,onChange:_=>Ve(_.target.value),placeholder:t("settings.remoteInstances.direct.import.placeholder"),disabled:pe,autoFocus:!0}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>je(!1),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:pe||!ze.trim(),children:t("settings.remoteInstances.direct.import.action")})]})]})]})}):null,s.jsx(Kt,{open:Re,onOpenChange:Je,children:s.jsxs(Bt,{className:Ge==="result"?"sm:max-w-lg":"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t(Ge==="result"?"settings.remoteInstances.clientAuth.qrDialogTitle":"settings.remoteInstances.clientAuth.actions.addDevice")}),s.jsx(Yt,{children:t(Ge==="result"?"settings.remoteInstances.clientAuth.qrScanHint":"settings.remoteInstances.clientAuth.addDevice.subtitle")})]}),Ge==="configure"?s.jsxs("form",{className:"space-y-4",onSubmit:_=>{_.preventDefault(),Rr()},children:[s.jsx(at,{className:"h-8",value:bt,onChange:_=>Nt(_.target.value),placeholder:t("settings.remoteInstances.clientAuth.field.labelPlaceholder"),autoFocus:!0}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("p",{className:"typography-ui-label text-foreground",children:t("settings.remoteInstances.clientAuth.addDevice.transportLabel")}),s.jsx("div",{role:"radiogroup","aria-label":t("settings.remoteInstances.clientAuth.addDevice.transportLabel"),className:"space-y-1.5",children:[{key:"relay",label:t("settings.remoteInstances.clientAuth.addDevice.transport.relay"),hint:t("settings.remoteInstances.clientAuth.addDevice.transport.relayHint"),available:!!Pt?.relayAvailable},{key:"lan",label:t("settings.remoteInstances.clientAuth.addDevice.transport.lan"),hint:t("settings.remoteInstances.clientAuth.addDevice.transport.lanHint"),available:!!Pt?.lanUrl},{key:"local",label:t("settings.remoteInstances.clientAuth.addDevice.transport.local"),hint:t("settings.remoteInstances.clientAuth.addDevice.transport.localHint"),available:!!Pt?.localUrl}].map(_=>{const Ae=Mt===_.key;return s.jsxs("div",{className:fe("flex items-start gap-2 py-0.5",_.available?"cursor-pointer":"opacity-45"),onClick:()=>{_.available&&Zt(_.key)},role:"presentation",children:[s.jsx(kr,{checked:Ae,disabled:!_.available,onChange:()=>Zt(_.key),ariaLabel:_.label,className:"mt-0.5"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:fe("typography-ui-label font-normal",Ae?"text-foreground":"text-foreground/70"),children:_.label}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:_.hint})]})]},_.key)})}),Mt==="lan"?s.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[s.jsx(an,{checked:Qt,onChange:St,ariaLabel:t("settings.remoteInstances.clientAuth.addDevice.fallback.relay")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.addDevice.fallback.relay")})]}):null,Mt==="relay"&&Pt?.lanUrl?s.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[s.jsx(an,{checked:Qt,onChange:St,ariaLabel:t("settings.remoteInstances.clientAuth.addDevice.fallback.preferLocal")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.addDevice.fallback.preferLocal")})]}):null]}),Se?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Se}):null,s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Je(!1),disabled:jt,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:jt||!Pt,children:t("settings.remoteInstances.clientAuth.addDevice.create")})]})]}):s.jsxs("div",{className:"space-y-3",children:[Pe?s.jsx("div",{className:"flex justify-center",children:s.jsx("img",{src:Pe,alt:t("settings.remoteInstances.clientAuth.qrAlt"),className:"w-full max-w-[420px] rounded-md bg-white p-4"})}):null,nt?s.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-[var(--interactive-border)] p-2",children:[s.jsx("code",{className:"min-w-0 flex-1 truncate typography-code text-muted-foreground",children:nt}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:ki,children:[s.jsx(K,{name:Ce?"check":"file-copy",className:fe("h-3.5 w-3.5",Ce&&"text-[var(--status-success)]")}),t(Ce?"settings.remoteInstances.clientAuth.actions.copied":"settings.common.actions.copyAll")]})]}):null,s.jsx("div",{className:"flex justify-end",children:s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",onClick:()=>Je(!1),children:t("settings.remoteInstances.clientAuth.addDevice.done")})})]})]})}),a?s.jsx(dt,{title:t("settings.remoteInstances.sidebar.title"),description:t("settings.remoteInstances.sidebar.total",{count:i.length}),headerAction:s.jsxs(ee,{type:"button",size:"xs",className:"!font-normal",onClick:()=>At(!0),children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.sidebar.actions.addSshInstance")]}),contentClassName:"space-y-2.5",children:d?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.page.import.loading")}):i.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.page.import.noneFound")}):i.map(_=>{const Ae=r[_.id],ct=_.nickname?.trim()||_.sshParsed?.destination||_.id,yt=Ae?.phase,Gt=yt==="ready";return s.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5",children:[s.jsxs("div",{className:"min-w-0 space-y-0.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:`h-2 w-2 rounded-full ${Zc(yt)}`}),s.jsx("p",{className:"typography-ui-label text-foreground truncate",children:ct})]}),s.jsxs("p",{className:"typography-micro text-muted-foreground truncate",children:[t(Xc(yt)),Ae?.localUrl?` · ${Ae.localUrl}`:""]})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{(Gt?y(_.id):k(_.id)).catch(us=>J.error(t(Gt?"settings.remoteInstances.sidebar.toast.disconnectFailed":"settings.remoteInstances.sidebar.toast.connectFailed"),{description:us instanceof Error?us.message:String(us)}))},children:[Gt?s.jsx(K,{name:"stop",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"plug-2",className:"h-3.5 w-3.5"}),t(Gt?"settings.remoteInstances.sidebar.actions.disconnect":"settings.remoteInstances.sidebar.actions.connect")]}),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>j(_.id),children:[s.jsx(K,{name:"pencil",className:"h-3.5 w-3.5"}),t("desktopHostSwitcher.actions.edit")]}),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{window.confirm(t("settings.remoteInstances.page.confirm.removeInstance"))&&x(_.id).catch(us=>J.error(t("settings.remoteInstances.page.toast.removeInstanceFailed"),{description:us instanceof Error?us.message:String(us)}))},children:[s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.delete")]})]})]},_.id)})}):null,a?s.jsx(Kt,{open:mt,onOpenChange:At,children:s.jsxs(Bt,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.remoteInstances.sidebar.actions.addSshInstance")}),s.jsx(Yt,{children:t("settings.remoteInstances.page.section.instanceDescription")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),vi()},children:[s.jsx(at,{className:"h-8",value:Dt,onChange:_=>Vt(_.target.value),placeholder:t("settings.remoteInstances.page.field.nicknamePlaceholder"),disabled:p}),s.jsx(at,{className:"h-8",value:ft,onChange:_=>vt(_.target.value),placeholder:t("settings.remoteInstances.page.field.sshCommandPlaceholder"),disabled:p,autoFocus:!0}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>At(!1),disabled:p,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:p||!ft.trim(),children:t("settings.common.actions.create")})]})]})]})}):null,a?s.jsx(dt,{title:t("settings.remoteInstances.page.import.sectionTitle"),children:c?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.page.import.loading")}):o.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.page.import.noneFound")}):s.jsx("div",{children:o.map(_=>s.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--surface-subtle)] py-3 last:border-b-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"typography-ui-label font-medium text-foreground truncate",children:[_.host,_.pattern?` ${t("settings.remoteInstances.page.import.patternSuffix")}`:""]}),s.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:_.sshCommand})]}),s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Kr(_.host,_.pattern)},children:t("settings.common.actions.import")})]},`${_.source}:${_.host}`))})}):null,s.jsx(Kt,{open:!!H,onOpenChange:_=>{_||ba()},children:s.jsxs(Bt,{className:"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.remoteInstances.page.patternDialog.title")}),s.jsx(Yt,{children:H?t("settings.remoteInstances.page.patternDialog.descriptionWithHost",{host:H}):t("settings.remoteInstances.page.patternDialog.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),Ni()},children:[s.jsx(at,{value:Y,onChange:_=>A(_.target.value),placeholder:t("settings.remoteInstances.page.patternDialog.destinationPlaceholder"),autoFocus:!0}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:ba,disabled:X,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:X,children:t("settings.remoteInstances.page.actions.create")})]})]})]})})]});const Xa=v.remoteOpenchamber.mode==="managed",Pi=v.nickname?.trim()||v.sshParsed?.destination||v.id;return s.jsx(Kt,{open:!!v,onOpenChange:_=>{_||j(null)},children:s.jsxs(Bt,{className:"sm:max-w-4xl max-h-[90vh] overflow-auto",children:[s.jsxs("div",{className:"mb-6 px-1",children:[s.jsx("h1",{className:`${Bo} truncate`,children:Pi}),s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${Zc(rn)}`}),s.jsx("span",{children:t(Xc(rn))}),Ks?.localUrl?s.jsx("span",{className:"font-mono text-foreground/80",children:Ks.localUrl}):null,ha?s.jsx("span",{children:t("settings.remoteInstances.page.status.reconnectStale")}):null]})]}),s.jsxs(dt,{title:t("settings.remoteInstances.page.section.actions"),info:t("settings.remoteInstances.page.section.actionsDescription"),divider:!1,contentClassName:"space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ee,{type:"button",variant:Rn?"outline":"default",size:"xs",className:"!font-normal",onClick:qe,disabled:B||V,children:[Rn?s.jsx(K,{name:"stop",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"plug-2",className:"h-3.5 w-3.5"}),Ii]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:ms,disabled:!Ci,children:[s.jsx(K,{name:"refresh",className:`h-3.5 w-3.5 ${Dn||hn&&!ha?"animate-spin":""}`}),Si]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{wa()},children:[s.jsx(K,{name:"terminal-window",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.logs")]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal text-[var(--status-error)] border-[var(--status-error)]/30 hover:text-[var(--status-error)]",onClick:()=>{window.confirm(t("settings.remoteInstances.page.confirm.removeInstance"))&&x(v.id).then(()=>{j(null),J.success(t("settings.remoteInstances.page.toast.instanceRemoved"))}).catch(Ae=>{J.error(t("settings.remoteInstances.page.toast.removeInstanceFailed"),{description:Ae instanceof Error?Ae.message:String(Ae)})})},children:[s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.sidebar.actions.remove")]})]}),Ks?.localUrl?s.jsxs("div",{className:"flex flex-wrap items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx("span",{children:t("settings.remoteInstances.page.status.currentLocalUrl")}),s.jsx("span",{className:"font-mono text-foreground/90",children:Ks.localUrl})]}):null]}),s.jsxs(dt,{title:t("settings.remoteInstances.page.section.instance"),info:t("settings.remoteInstances.page.section.instanceDescription"),contentClassName:"space-y-3",children:[s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:t("settings.remoteInstances.page.field.sshCommand")}),s.jsx(at,{className:"h-7 md:max-w-xl",value:v.sshCommand,onChange:_=>ys(Ae=>({...Ae,sshCommand:_.target.value})),placeholder:t("settings.remoteInstances.page.field.sshCommandPlaceholder")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:t("settings.remoteInstances.page.field.nickname")}),s.jsx(at,{className:"h-7 md:max-w-sm",value:v.nickname||"",onChange:_=>ys(Ae=>({...Ae,nickname:_.target.value})),placeholder:t("settings.remoteInstances.page.field.nicknamePlaceholder")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:t("settings.remoteInstances.page.field.connectionTimeoutSeconds")}),s.jsx(Rs,{containerClassName:"w-fit",min:5,max:240,step:1,className:"w-16 tabular-nums",value:v.connectionTimeoutSec,onValueChange:_=>{ys(Ae=>({...Ae,connectionTimeoutSec:Number.isFinite(_)?_:Ae.connectionTimeoutSec}))}})]})]}),s.jsxs(dt,{title:t("settings.remoteInstances.page.section.remoteServer"),info:t("settings.remoteInstances.page.section.remoteServerDescription"),contentClassName:"space-y-3",children:[s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.mode"),hint:t("settings.remoteInstances.page.field.modeHint")})}),s.jsxs(Lt,{value:v.remoteOpenchamber.mode,onValueChange:_=>ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,mode:_==="external"?"external":"managed"}})),children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.modePlaceholder")})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"managed",children:t("settings.remoteInstances.page.field.modeManaged")}),s.jsx(kt,{value:"external",children:t("settings.remoteInstances.page.field.modeExternal")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.preferredRemotePort"),hint:t("settings.remoteInstances.page.field.preferredRemotePortHint")})}),s.jsx(Rs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:v.remoteOpenchamber.preferredPort,onValueChange:_=>{ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,preferredPort:Number.isFinite(_)&&_>0?_:void 0}}))},onClear:()=>{ys(_=>({..._,remoteOpenchamber:{..._.remoteOpenchamber,preferredPort:void 0}}))},emptyLabel:t("settings.remoteInstances.page.field.auto")})]}),Xa?s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.installMethod"),hint:t("settings.remoteInstances.page.field.installMethodHint")})}),s.jsxs(Lt,{value:v.remoteOpenchamber.installMethod,onValueChange:_=>ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,installMethod:_==="npm"||_==="download_release"||_==="upload_bundle"?_:"bun"}})),children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.selectInstallMethodPlaceholder")})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"bun",children:"bun"}),s.jsx(kt,{value:"npm",children:"npm"}),s.jsx(kt,{value:"download_release",children:t("settings.remoteInstances.page.field.installMethodDownloadRelease")}),s.jsx(kt,{value:"upload_bundle",children:t("settings.remoteInstances.page.field.installMethodUploadBundle")})]})]})]}):null,Xa?s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.keepServerRunning"),hint:t("settings.remoteInstances.page.field.keepServerRunningHint")})}),s.jsx("div",{className:"flex w-full items-center gap-2 md:max-w-xs",children:s.jsx(fr,{checked:v.remoteOpenchamber.keepRunning,onCheckedChange:_=>ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,keepRunning:_}}))})})]}):null]}),s.jsxs(dt,{title:t("settings.remoteInstances.page.section.mainTunnel"),info:t("settings.remoteInstances.page.section.mainTunnelDescription"),contentClassName:"space-y-3",children:[s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.bindHost"),hint:t("settings.remoteInstances.page.field.bindHostHint")})}),s.jsxs(Lt,{value:v.localForward.bindHost,onValueChange:_=>{_==="0.0.0.0"&&!window.confirm(t("settings.remoteInstances.page.confirm.bindAllInterfaces"))||ys(Ae=>({...Ae,localForward:{...Ae.localForward,bindHost:_==="localhost"||_==="0.0.0.0"?_:"127.0.0.1"}}))},children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.selectBindHostPlaceholder")})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"127.0.0.1",children:"127.0.0.1"}),s.jsx(kt,{value:"localhost",children:"localhost"}),s.jsx(kt,{value:"0.0.0.0",children:"0.0.0.0"})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.preferredLocalPort"),hint:t("settings.remoteInstances.page.field.preferredLocalPortHint")})}),s.jsxs("div",{className:"flex w-full items-center gap-2 md:max-w-sm",children:[s.jsx(Rs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:v.localForward.preferredLocalPort,onValueChange:_=>{ys(Ae=>({...Ae,localForward:{...Ae.localForward,preferredLocalPort:Number.isFinite(_)&&_>0?_:void 0}}))},onClear:()=>{ys(_=>({..._,localForward:{..._.localForward,preferredLocalPort:void 0}}))},emptyLabel:t("settings.remoteInstances.page.field.auto")}),s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal h-7 w-7 px-0",title:t("settings.remoteInstances.page.actions.pickRandomPort"),onClick:()=>ys(_=>({..._,localForward:{..._.localForward,preferredLocalPort:Qo()}})),children:s.jsx(K,{name:"shuffle",className:"h-3.5 w-3.5"})})]})]})]}),s.jsxs(dt,{title:t("settings.remoteInstances.page.section.authentication"),info:t("settings.remoteInstances.page.section.authenticationDescription"),contentClassName:"space-y-3",children:[s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:t("settings.remoteInstances.page.field.sshPasswordOptional")}),s.jsx(at,{className:"h-7 md:max-w-sm",type:"password",value:v.auth.sshPassword?.value||"",onChange:_=>ys(Ae=>({...Ae,auth:{...Ae.auth,sshPassword:{enabled:_.target.value.trim().length>0,value:_.target.value,store:Ae.auth.sshPassword?.store||"never"}}})),placeholder:t("settings.remoteInstances.page.field.sshPasswordPlaceholder")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("span",{className:"typography-ui-label text-foreground w-56 shrink-0",children:t("settings.remoteInstances.page.field.uiPasswordOptional")}),s.jsx(at,{className:"h-7 md:max-w-sm",type:"password",value:v.auth.openchamberPassword?.value||"",onChange:_=>ys(Ae=>({...Ae,auth:{...Ae.auth,openchamberPassword:{enabled:_.target.value.trim().length>0,value:_.target.value,store:Ae.auth.openchamberPassword?.store||"never"}}})),placeholder:t("settings.remoteInstances.page.field.uiPasswordPlaceholder")})]})]}),s.jsxs(dt,{title:t("settings.remoteInstances.page.section.portForwards"),info:t("settings.remoteInstances.page.section.portForwardsDescription"),contentClassName:"space-y-2",children:[v.portForwards.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground/80",children:t("settings.remoteInstances.page.empty.noExtraForwards")}):null,v.portForwards.map((_,Ae)=>{const ct=Rt=>{ys(cs=>({...cs,portForwards:cs.portForwards.map((Xn,Ht)=>Ht===Ae?Rt(Xn):Xn)}))},yt=_.type==="remote"?"Local target":"Local listen",Gt=_.type==="remote"?"Local host and port on your machine that receives traffic from remote -R listener.":"Local host and port where this forward listens on your machine.",Bs=_.type==="remote"?"Remote listen":"Remote target",us=_.type==="remote"?"Remote host and port where SSH creates the -R listener.":"Remote host and port that receives traffic from local -L listener.",Gs=ed(_.localHost||"localhost",_.localPort),_s=ed(_.remoteHost||"localhost",_.remotePort),Ms=_.type==="local"&&typeof _.localPort=="number"&&_.localPort>0,on=Ms?`http://${qv(_.localHost)}:${_.localPort}`:"",ln=!!T[_.id],Qn=_.type==="local"?t("settings.remoteInstances.page.forwardType.local"):_.type==="remote"?t("settings.remoteInstances.page.forwardType.remote"):t("settings.remoteInstances.page.forwardType.dynamic");return s.jsxs(ca,{open:ln,onOpenChange:Rt=>{I(cs=>({...cs,[_.id]:Rt}))},className:`${Ae>0?"border-t border-[var(--surface-subtle)]":""} py-2`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"min-w-0 flex items-center gap-2",children:s.jsxs(da,{className:"flex items-center gap-2 group",children:[s.jsx(K,{name:"arrow-down-s",className:`h-4 w-4 text-muted-foreground transition-transform ${ln?"rotate-180":""}`}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Vv(_)}),s.jsx("span",{className:"typography-micro text-muted-foreground/70 shrink-0",children:Qn})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fr,{checked:_.enabled,onCheckedChange:Rt=>ct(cs=>({...cs,enabled:Rt})),"aria-label":t("settings.remoteInstances.page.actions.enableForwardAria")}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal h-6 w-6 px-0 text-[var(--status-error)] hover:text-[var(--status-error)]",onClick:()=>ys(Rt=>({...Rt,portForwards:Rt.portForwards.filter(cs=>cs.id!==_.id)})),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})]}),s.jsx(ua,{className:"pt-2",children:s.jsxs("div",{className:"space-y-0 pb-2",children:[s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:t("settings.remoteInstances.page.field.forwardType"),hint:s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{children:t("settings.remoteInstances.page.field.forwardTypeHint")}),s.jsx("p",{children:t(Gv(_.type))})]})})}),s.jsxs(Lt,{value:_.type,onValueChange:Rt=>ct(cs=>({...cs,type:Rt==="dynamic"||Rt==="remote"?Rt:"local"})),children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.typePlaceholder")})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"local",children:t("settings.remoteInstances.page.forwardType.local")}),s.jsx(kt,{value:"remote",children:t("settings.remoteInstances.page.forwardType.remote")}),s.jsx(kt,{value:"dynamic",children:t("settings.remoteInstances.page.forwardType.dynamic")})]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:yt,hint:Gt})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(at,{className:"h-7 w-32",value:_.localHost||"127.0.0.1",onChange:Rt=>ct(cs=>({...cs,localHost:Rt.target.value})),placeholder:t("settings.remoteInstances.page.field.localHostPlaceholder")}),s.jsx("span",{className:"text-muted-foreground",children:":"}),s.jsx(Rs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:_.localPort,onValueChange:Rt=>{ct(cs=>({...cs,localPort:Number.isFinite(Rt)&&Rt>0?Rt:void 0}))},onClear:()=>{ct(Rt=>({...Rt,localPort:void 0}))},emptyLabel:t("settings.remoteInstances.page.field.auto")})]})]}),_.type!=="dynamic"?s.jsxs("div",{className:"flex flex-col gap-1.5 py-1.5 md:flex-row md:items-center md:gap-8",children:[s.jsx("div",{className:"w-56 shrink-0",children:s.jsx(yn,{label:Bs,hint:us})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(at,{className:"h-7 w-32",value:_.remoteHost||"",onChange:Rt=>ct(cs=>({...cs,remoteHost:Rt.target.value})),placeholder:t("settings.remoteInstances.page.field.remoteHostPlaceholder")}),s.jsx("span",{className:"text-muted-foreground",children:":"}),s.jsx(Rs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:_.remotePort,onValueChange:Rt=>{ct(cs=>({...cs,remotePort:Number.isFinite(Rt)&&Rt>0?Rt:void 0}))},onClear:()=>{ct(Rt=>({...Rt,remotePort:void 0}))},emptyLabel:t("settings.remoteInstances.page.field.auto")})]})]}):null,s.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2 rounded-md bg-[var(--surface-subtle)] p-2",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1 typography-micro text-muted-foreground/80",children:_.type==="dynamic"?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"computer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:Gs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.localSocks5")})]}):_.type==="remote"?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"server",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:_s}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.remote")}),s.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"}),s.jsx(K,{name:"computer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:Gs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.local")})]}):s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"computer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:Gs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.local")}),s.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"}),s.jsx(K,{name:"server",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:_s}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.remote")})]})}),Ms?s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Tn(on).then(Rt=>{Rt||J.error(t("settings.remoteInstances.page.toast.openLocalEndpointFailed"))})},children:[s.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.openLocal")]}):null]})]})})]},_.id)}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal mt-1",onClick:()=>{const _=Hv();ys(Ae=>({...Ae,portForwards:[...Ae.portForwards,_]})),I(Ae=>({...Ae,[_.id]:!0}))},children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.addForward")]})]}),s.jsx("div",{className:"mt-8 border-t border-[var(--interactive-border)] pt-3",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{zr()},disabled:!Or||p,children:t("settings.common.actions.saveChanges")}),Ks?.localUrl?s.jsxs(s.Fragment,{children:[s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Vn(Ks.localUrl||"").then(_=>{_.ok&&J.success(t("settings.remoteInstances.page.toast.localUrlCopied"))})},children:[s.jsx(K,{name:"file-copy",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.copyLocalUrl")]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{ja()},children:[s.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.open")]})]}):null,u?s.jsx("div",{className:"ml-auto typography-meta text-[var(--status-error)]",children:u}):null]})}),s.jsx(Kt,{open:$,onOpenChange:O,children:s.jsxs(Bt,{className:"sm:max-w-2xl",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.remoteInstances.page.logsDialog.title")}),s.jsx(Yt,{children:v?.nickname?.trim()||v?.sshParsed?.destination||v?.id||t("settings.remoteInstances.page.logsDialog.selectedInstanceFallback")})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Ya,disabled:M||!xn.trim(),children:[s.jsx(K,{name:"file-copy",className:"h-3.5 w-3.5"}),t("settings.common.actions.copyAll")]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Qa()},disabled:M,children:[s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.clear")]})]}),M?s.jsx("div",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.page.logsDialog.loading")}):F?s.jsx("div",{className:"typography-meta text-[var(--status-error)]",children:F}):s.jsx("pre",{className:"max-h-[55vh] overflow-auto rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3 typography-micro text-foreground whitespace-pre-wrap break-words",children:D.length>0?D.join(`
34
- `):t("settings.remoteInstances.page.logsDialog.empty")})]})}),s.jsx(Kt,{open:!!H,onOpenChange:_=>{_||ba()},children:s.jsxs(Bt,{className:"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t("settings.remoteInstances.page.patternDialog.title")}),s.jsx(Yt,{children:H?t("settings.remoteInstances.page.patternDialog.descriptionWithHost",{host:H}):t("settings.remoteInstances.page.patternDialog.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:_=>{_.preventDefault(),Ni()},children:[s.jsx(at,{value:Y,onChange:_=>A(_.target.value),placeholder:t("settings.remoteInstances.page.patternDialog.destinationPlaceholder"),autoFocus:!0}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:ba,disabled:X,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:X,children:t("settings.common.actions.create")})]})]})]})})]})})},tw="__add_provider__",sw=()=>{const t=Ps.getDirectory();return typeof t=="string"&&t.trim().length>0?t.trim():null},nw=({onItemSelect:t})=>{const{t:e}=lt(),n=pt(m=>m.providers),a=pt(m=>m.selectedProviderId),i=pt(m=>m.setSelectedProvider),r=is(m=>m.activeProjectId),[o,d]=l.useState({}),c=l.useMemo(()=>sw(),[r]);l.useEffect(()=>{if(n.length===0){d({});return}let m=!1;return(async()=>{const b=n.map(async g=>{try{const x=c?`?directory=${encodeURIComponent(c)}`:"",k=await ht(`/api/provider/${encodeURIComponent(g.id)}/source${x}`,{method:"GET",headers:{Accept:"application/json"}});if(!k.ok)return;const y=await k.json().catch(()=>null),C=y?.sources??y?.data?.sources;if(!C||m)return;d(z=>({...z,[g.id]:C}))}catch{}});await Promise.all(b)})(),()=>{m=!0}},[c,n]);const p="bg-background",u=l.useMemo(()=>n.filter(m=>!!o[m.id]?.project?.exists),[n,o]),f=l.useMemo(()=>n.filter(m=>!o[m.id]?.project?.exists),[n,o]);return s.jsxs("div",{className:fe("flex h-full flex-col",p),children:[s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[s.jsx("h2",{className:`${fn} mb-3`,children:e("settings.providers.sidebar.title")}),s.jsx(yi,{className:"mb-3"}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:e("settings.providers.sidebar.total",{count:n.length})}),s.jsx(ee,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:()=>{i(tw),t?.()},"aria-label":e("settings.providers.sidebar.actions.connectProviderAria"),title:e("settings.providers.sidebar.actions.connectProviderTitle"),children:s.jsx(K,{name:"add",className:"h-3.5 w-3.5"})})]})]}),s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:n.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"stack",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:e("settings.providers.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:e("settings.providers.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[f.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:e("settings.providers.sidebar.section.userProviders")}),f.map(m=>s.jsx(sd,{provider:m,selectedProviderId:a,onSelect:()=>{i(m.id),t?.()}},m.id))]}),u.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:fe("px-2 pb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground",f.length>0?"pt-3":"pt-2"),children:e("settings.providers.sidebar.section.projectProviders")}),u.map(m=>s.jsx(sd,{provider:m,selectedProviderId:a,onSelect:()=>{i(m.id),t?.()}},m.id))]})]})})]})},sd=t=>{const e=tt.c(17),{provider:n,selectedProviderId:a,onSelect:i}=t,r=Array.isArray(n.models)?n.models.length:0,o=n.id===a,d=n.id,c=o?"bg-interactive-selection":"hover:bg-interactive-hover";let p;e[0]!==c?(p=fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",c),e[0]=c,e[1]=p):p=e[1];let u;e[2]!==n.id?(u=s.jsx(ia,{providerId:n.id,className:"h-4 w-4 flex-shrink-0"}),e[2]=n.id,e[3]=u):u=e[3];const f=n.name||n.id;let m;e[4]!==f?(m=s.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:f}),e[4]=f,e[5]=m):m=e[5];let w;e[6]!==r?(w=s.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:r}),e[6]=r,e[7]=w):w=e[7];let b;e[8]!==i||e[9]!==u||e[10]!==m||e[11]!==w?(b=s.jsxs("button",{type:"button",onClick:i,className:"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[u,m,w]}),e[8]=i,e[9]=u,e[10]=m,e[11]=w,e[12]=b):b=e[12];let g;return e[13]!==n.id||e[14]!==p||e[15]!==b?(g=s.jsx("div",{className:p,children:b},d),e[13]=n.id,e[14]=p,e[15]=b,e[16]=g):g=e[16],g},aw=t=>t,Ju="@ai-sdk/openai-compatible",na="__custom_provider__",iw=/^[a-z0-9][a-z0-9-_]*$/,Yu=/^https?:\/\//,rw=/^\{env:([^}]+)\}$/;let ow=0;const hr=()=>`row-${ow++}`,gl=()=>({row:hr(),id:"",name:""}),fl=()=>({row:hr(),key:"",value:""}),lw=()=>({providerID:"",name:"",baseURL:"",apiKey:"",models:[gl()],headers:[fl()]});function cw(t){const e=t.trim();if(!e)return{};const a=e.match(rw)?.[1]?.trim();return a?{env:a}:{key:e}}function dw(t){const e=t.options&&typeof t.options=="object"?t.options:null,n=typeof e?.baseURL=="string"?e.baseURL.trim():"";return n&&Yu.test(n)?!0:(Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.values(t.models):[]).some(i=>{if(!i||typeof i!="object")return!1;const r="api"in i&&i.api&&typeof i.api=="object"?i.api:null;return typeof r?.npm=="string"&&r.npm===Ju})}function uw(t,e){return e?!!(e.user?.exists||e.project?.exists||e.custom?.exists)&&dw(t):!1}function nd(t){return t?.custom?.exists?"custom":t?.project?.exists?"project":"user"}function mw(t){const e=t.options&&typeof t.options=="object"?t.options:{},n=typeof e.baseURL=="string"?e.baseURL:"",a=e.headers&&typeof e.headers=="object"&&!Array.isArray(e.headers)?e.headers:{},i=Object.entries(a).filter(c=>typeof c[0]=="string"&&typeof c[1]=="string").map(([c,p])=>({row:hr(),key:c,value:p})),r=Array.isArray(t.models)?t.models:t.models&&typeof t.models=="object"?Object.entries(t.models).map(([c,p])=>({id:c,name:p&&typeof p=="object"&&"name"in p&&typeof p.name=="string"?p.name:c})):[],o=r.length>0?r.map(c=>({row:hr(),id:typeof c?.id=="string"?c.id:"",name:typeof c?.name=="string"?c.name:typeof c?.id=="string"?c.id:""})):[gl()],d=Array.isArray(t.env)?t.env.find(c=>typeof c=="string"&&c.trim().length>0)?.trim():void 0;return{providerID:t.id,name:typeof t.name=="string"&&t.name.trim()?t.name:t.id,baseURL:n,apiKey:d?`{env:${d}}`:"",models:o,headers:i.length>0?i:[fl()]}}function pw(t){const e=t.form.providerID.trim(),n=t.form.name.trim(),a=t.form.baseURL.trim(),{env:i,key:r}=cw(t.form.apiKey),o=t.disabledProviders??[],d=t.editingProviderID?.trim(),c=e?iw.test(e)?void 0:t.t("settings.providers.page.custom.error.providerID.format"):t.t("settings.providers.page.custom.error.providerID.required"),p=n?void 0:t.t("settings.providers.page.custom.error.name.required"),u=a?Yu.test(a)?void 0:t.t("settings.providers.page.custom.error.baseURL.format"):t.t("settings.providers.page.custom.error.baseURL.required"),m=!!(i||r||d&&t.allowExistingAuth&&d===e)?void 0:t.t("settings.providers.page.custom.error.apiKey.required"),w=o.includes(e),g=c||!!(d&&d===e)?void 0:t.existingProviderIDs.has(e)&&!w?t.t("settings.providers.page.custom.error.providerID.exists"):void 0,x=new Set,k=t.form.models.map(O=>{const M=O.id.trim(),S=M?x.has(M)?t.t("settings.providers.page.custom.error.duplicate"):void x.add(M):t.t("settings.providers.page.custom.error.required"),F=O.name.trim()?void 0:t.t("settings.providers.page.custom.error.required");return{id:S,name:F}}),y=k.every(O=>!O.id&&!O.name),C=Object.fromEntries(t.form.models.map(O=>[O.id.trim(),{name:O.name.trim()}])),z=new Set,j=t.form.headers.map(O=>{const M=O.key.trim(),S=O.value.trim();if(!M&&!S)return{};const F=M?z.has(M.toLowerCase())?t.t("settings.providers.page.custom.error.duplicate"):void z.add(M.toLowerCase()):t.t("settings.providers.page.custom.error.required"),E=S?void 0:t.t("settings.providers.page.custom.error.required");return{key:F,value:E}}),N=j.every(O=>!O.key&&!O.value),v=Object.fromEntries(t.form.headers.map(O=>({key:O.key.trim(),value:O.value.trim()})).filter(O=>O.key&&O.value).map(O=>[O.key,O.value])),P={providerID:c??g,name:p,baseURL:u,apiKey:m};return!c&&!g&&!p&&!u&&!m&&y&&N?{err:P,models:k,headers:j,result:{providerID:e,name:n,apiKey:r,config:{npm:Ju,name:n,...i?{env:[i]}:{},options:{baseURL:a,...Object.keys(v).length>0?{headers:v}:{}},models:C}}}:{err:P,models:k,headers:j}}function gw(t){return t.apiKey?{providerID:t.providerID,auth:{type:"api",key:t.apiKey}}:null}function fw(t,e){return{providerID:t.providerID,config:t.config,scope:e?.scope??"user"}}const ad=t=>{const e=tt.c(198),{existingProviderIDs:n,disabledProviders:a,busy:i,mode:r,initialValues:o,allowExistingAuth:d,authFailureHint:c,onSubmit:p,onCancel:u,onDisconnect:f}=t;let m;e[0]!==a?(m=a===void 0?[]:a,e[0]=a,e[1]=m):m=e[1];const w=m,b=i===void 0?!1:i,g=r===void 0?"create":r,x=d===void 0?!1:d,k=c===void 0?null:c,{t:y}=lt(),C=g==="edit";let z;e[2]!==o?(z=()=>o??lw(),e[2]=o,e[3]=z):z=e[3];const[j,N]=l.useState(z);let v;e[4]===Symbol.for("react.memo_cache_sentinel")?(v={},e[4]=v):v=e[4];const[P,$]=l.useState(v);let O;e[5]===Symbol.for("react.memo_cache_sentinel")?(O=[],e[5]=O):O=e[5];const[M,S]=l.useState(O);let F;e[6]===Symbol.for("react.memo_cache_sentinel")?(F=[],e[6]=F):F=e[6];const[E,D]=l.useState(F),W=l.useRef(null);let H,Z;e[7]!==o||e[8]!==C?(H=()=>{o&&(C&&W.current===o.providerID||(W.current=C?o.providerID:null,N(o),$({}),S([]),D([])))},Z=[o,C],e[7]=o,e[8]=C,e[9]=H,e[10]=Z):(H=e[9],Z=e[10]),l.useEffect(H,Z);let Y;e[11]===Symbol.for("react.memo_cache_sentinel")?(Y=(St,Pt)=>{N(Ne=>({...Ne,[St]:Pt})),$(Ne=>({...Ne,[St]:void 0}))},e[11]=Y):Y=e[11];const A=Y;let X;e[12]===Symbol.for("react.memo_cache_sentinel")?(X=(St,Pt,Ne)=>{N(ut=>({...ut,models:ut.models.map((mt,At)=>At===St?{...mt,[Pt]:Ne}:mt)})),S(ut=>{const mt=[...ut];return mt[St]={...mt[St]??{},[Pt]:void 0},mt})},e[12]=X):X=e[12];const te=X;let T;e[13]===Symbol.for("react.memo_cache_sentinel")?(T=(St,Pt,Ne)=>{N(ut=>({...ut,headers:ut.headers.map((mt,At)=>At===St?{...mt,[Pt]:Ne}:mt)})),D(ut=>{const mt=[...ut];return mt[St]={...mt[St]??{},[Pt]:void 0},mt})},e[13]=T):T=e[13];const I=T;let B;e[14]!==x||e[15]!==b||e[16]!==w||e[17]!==n||e[18]!==j||e[19]!==C||e[20]!==p||e[21]!==y?(B=async St=>{if(St.preventDefault(),b)return;const Pt=pw({form:j,t:((Ne,ut)=>y(Ne,ut)),existingProviderIDs:n,disabledProviders:w,editingProviderID:C?j.providerID:void 0,allowExistingAuth:C&&x});$(Pt.err),S(Pt.models),D(Pt.headers),Pt.result&&await p(Pt.result)},e[14]=x,e[15]=b,e[16]=w,e[17]=n,e[18]=j,e[19]=C,e[20]=p,e[21]=y,e[22]=B):B=e[22];const L=B;let V;e[23]!==C||e[24]!==y?(V=y(C?"settings.providers.page.custom.editTitle":"settings.providers.page.custom.title"),e[23]=C,e[24]=y,e[25]=V):V=e[25];let Q;e[26]!==y?(Q=y("settings.providers.page.custom.description"),e[26]=y,e[27]=Q):Q=e[27];let G;e[28]!==Q?(G=s.jsx("p",{className:Js,children:Q}),e[28]=Q,e[29]=G):G=e[29];let ue;e[30]!==k?(ue=k?s.jsx("p",{className:"typography-meta text-[var(--status-warning)]",role:"status",children:k}):null,e[30]=k,e[31]=ue):ue=e[31];let ne;e[32]!==y?(ne=y("settings.providers.page.custom.field.providerID.label"),e[32]=y,e[33]=ne):ne=e[33];let xe;e[34]!==y?(xe=y("settings.providers.page.custom.field.providerID.info"),e[34]=y,e[35]=xe):xe=e[35];const ve=j.providerID;let me;e[36]===Symbol.for("react.memo_cache_sentinel")?(me=St=>A("providerID",St.target.value),e[36]=me):me=e[36];let ge;e[37]!==y?(ge=y("settings.providers.page.custom.field.providerID.placeholder"),e[37]=y,e[38]=ge):ge=e[38];const Ie=!C,oe=C||b,ce=!!P.providerID;let pe;e[39]!==y?(pe=y("settings.providers.page.custom.field.providerID.label"),e[39]=y,e[40]=pe):pe=e[40];let ie;e[41]!==j.providerID||e[42]!==ge||e[43]!==Ie||e[44]!==oe||e[45]!==ce||e[46]!==pe?(ie=s.jsx(at,{value:ve,onChange:me,placeholder:ge,className:"h-8 rounded-md px-3 font-mono text-xs",autoFocus:Ie,disabled:oe,"aria-invalid":ce,"aria-label":pe}),e[41]=j.providerID,e[42]=ge,e[43]=Ie,e[44]=oe,e[45]=ce,e[46]=pe,e[47]=ie):ie=e[47];let le;e[48]!==P.providerID?(le=P.providerID?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.providerID}):null,e[48]=P.providerID,e[49]=le):le=e[49];let de;e[50]!==ne||e[51]!==xe||e[52]!==ie||e[53]!==le?(de=s.jsxs(ns,{label:ne,info:xe,children:[ie,le]}),e[50]=ne,e[51]=xe,e[52]=ie,e[53]=le,e[54]=de):de=e[54];let he;e[55]!==y?(he=y("settings.providers.page.custom.field.name.label"),e[55]=y,e[56]=he):he=e[56];let Me;e[57]!==y?(Me=y("settings.providers.page.custom.field.name.info"),e[57]=y,e[58]=Me):Me=e[58];const Le=j.name;let Be;e[59]===Symbol.for("react.memo_cache_sentinel")?(Be=St=>A("name",St.target.value),e[59]=Be):Be=e[59];let Fe;e[60]!==y?(Fe=y("settings.providers.page.custom.field.name.placeholder"),e[60]=y,e[61]=Fe):Fe=e[61];const De=!!P.name;let ze;e[62]!==y?(ze=y("settings.providers.page.custom.field.name.label"),e[62]=y,e[63]=ze):ze=e[63];let Ve;e[64]!==j.name||e[65]!==Fe||e[66]!==De||e[67]!==ze?(Ve=s.jsx(at,{value:Le,onChange:Be,placeholder:Fe,className:"h-8 rounded-md px-3","aria-invalid":De,"aria-label":ze}),e[64]=j.name,e[65]=Fe,e[66]=De,e[67]=ze,e[68]=Ve):Ve=e[68];let We;e[69]!==P.name?(We=P.name?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.name}):null,e[69]=P.name,e[70]=We):We=e[70];let _e;e[71]!==he||e[72]!==Me||e[73]!==Ve||e[74]!==We?(_e=s.jsxs(ns,{label:he,info:Me,children:[Ve,We]}),e[71]=he,e[72]=Me,e[73]=Ve,e[74]=We,e[75]=_e):_e=e[75];let He;e[76]!==y?(He=y("settings.providers.page.custom.field.baseURL.label"),e[76]=y,e[77]=He):He=e[77];let Ke;e[78]!==y?(Ke=y("settings.providers.page.custom.field.baseURL.info"),e[78]=y,e[79]=Ke):Ke=e[79];const Oe=j.baseURL;let je;e[80]===Symbol.for("react.memo_cache_sentinel")?(je=St=>A("baseURL",St.target.value),e[80]=je):je=e[80];let Te;e[81]!==y?(Te=y("settings.providers.page.custom.field.baseURL.placeholder"),e[81]=y,e[82]=Te):Te=e[82];const Ue=!!P.baseURL;let Ye;e[83]!==y?(Ye=y("settings.providers.page.custom.field.baseURL.label"),e[83]=y,e[84]=Ye):Ye=e[84];let q;e[85]!==j.baseURL||e[86]!==Te||e[87]!==Ue||e[88]!==Ye?(q=s.jsx(at,{value:Oe,onChange:je,placeholder:Te,className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":Ue,"aria-label":Ye}),e[85]=j.baseURL,e[86]=Te,e[87]=Ue,e[88]=Ye,e[89]=q):q=e[89];let re;e[90]!==P.baseURL?(re=P.baseURL?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.baseURL}):null,e[90]=P.baseURL,e[91]=re):re=e[91];let U;e[92]!==He||e[93]!==Ke||e[94]!==q||e[95]!==re?(U=s.jsxs(ns,{label:He,info:Ke,children:[q,re]}),e[92]=He,e[93]=Ke,e[94]=q,e[95]=re,e[96]=U):U=e[96];let h;e[97]!==y?(h=y("settings.providers.page.custom.field.apiKey.label"),e[97]=y,e[98]=h):h=e[98];let ae;e[99]!==x||e[100]!==C||e[101]!==y?(ae=y(C&&x?"settings.providers.page.custom.field.apiKey.editInfo":"settings.providers.page.custom.field.apiKey.info"),e[99]=x,e[100]=C,e[101]=y,e[102]=ae):ae=e[102];const ye=j.apiKey;let be;e[103]===Symbol.for("react.memo_cache_sentinel")?(be=St=>A("apiKey",St.target.value),e[103]=be):be=e[103];let Ee;e[104]!==x||e[105]!==C||e[106]!==y?(Ee=y(C&&x?"settings.providers.page.custom.field.apiKey.editPlaceholder":"settings.providers.page.custom.field.apiKey.placeholder"),e[104]=x,e[105]=C,e[106]=y,e[107]=Ee):Ee=e[107];const et=!!P.apiKey;let Ze;e[108]!==y?(Ze=y("settings.providers.page.custom.field.apiKey.label"),e[108]=y,e[109]=Ze):Ze=e[109];let it;e[110]!==j.apiKey||e[111]!==Ee||e[112]!==et||e[113]!==Ze?(it=s.jsx(at,{type:"password",value:ye,onChange:be,placeholder:Ee,className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":et,"aria-label":Ze}),e[110]=j.apiKey,e[111]=Ee,e[112]=et,e[113]=Ze,e[114]=it):it=e[114];let ot;e[115]!==P.apiKey?(ot=P.apiKey?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:P.apiKey}):null,e[115]=P.apiKey,e[116]=ot):ot=e[116];let xt;e[117]!==h||e[118]!==ae||e[119]!==it||e[120]!==ot?(xt=s.jsxs(ns,{label:h,info:ae,children:[it,ot]}),e[117]=h,e[118]=ae,e[119]=it,e[120]=ot,e[121]=xt):xt=e[121];let bt;e[122]!==V||e[123]!==G||e[124]!==ue||e[125]!==de||e[126]!==_e||e[127]!==U||e[128]!==xt?(bt=s.jsxs(dt,{title:V,divider:!1,settingsItem:"providers.custom",contentClassName:Bn,children:[G,ue,de,_e,U,xt]}),e[122]=V,e[123]=G,e[124]=ue,e[125]=de,e[126]=_e,e[127]=U,e[128]=xt,e[129]=bt):bt=e[129];let Nt;e[130]!==y?(Nt=y("settings.providers.page.custom.models.title"),e[130]=y,e[131]=Nt):Nt=e[131];let Se;if(e[132]!==j.models||e[133]!==M||e[134]!==y){let St;e[136]!==j.models.length||e[137]!==M||e[138]!==y?(St=(Pt,Ne)=>s.jsx("div",{className:`${Us} space-y-2`,children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[s.jsxs("div",{children:[s.jsx("label",{className:zt,children:y("settings.providers.page.custom.models.idLabel")}),s.jsx(at,{value:Pt.id,onChange:ut=>te(Ne,"id",ut.target.value),placeholder:y("settings.providers.page.custom.models.idPlaceholder"),className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":y("settings.providers.page.custom.models.idLabel")}),M[Ne]?.id?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:M[Ne]?.id}):null]}),s.jsxs("div",{children:[s.jsx("label",{className:zt,children:y("settings.providers.page.custom.models.nameLabel")}),s.jsx(at,{value:Pt.name,onChange:ut=>te(Ne,"name",ut.target.value),placeholder:y("settings.providers.page.custom.models.namePlaceholder"),className:"mt-1 h-8 rounded-md px-3","aria-label":y("settings.providers.page.custom.models.nameLabel")}),M[Ne]?.name?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:M[Ne]?.name}):null]})]}),s.jsx(ee,{type:"button",variant:"ghost",size:"icon",className:Is,disabled:j.models.length<=1,onClick:()=>{j.models.length<=1||(N(ut=>({...ut,models:ut.models.filter((mt,At)=>At!==Ne)})),S(ut=>ut.filter((mt,At)=>At!==Ne)))},"aria-label":y("settings.providers.page.custom.models.remove"),children:s.jsx(K,{name:"delete-bin",className:"size-4"})})]})},Pt.row),e[136]=j.models.length,e[137]=M,e[138]=y,e[139]=St):St=e[139],Se=j.models.map(St),e[132]=j.models,e[133]=M,e[134]=y,e[135]=Se}else Se=e[135];let Qe;e[140]===Symbol.for("react.memo_cache_sentinel")?(Qe=()=>{N(hw),S(xw)},e[140]=Qe):Qe=e[140];let nt;e[141]!==y?(nt=y("settings.providers.page.custom.models.add"),e[141]=y,e[142]=nt):nt=e[142];let rt;e[143]!==nt?(rt=s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Qe,children:nt}),e[143]=nt,e[144]=rt):rt=e[144];let gt;e[145]!==Nt||e[146]!==Se||e[147]!==rt?(gt=s.jsxs(dt,{title:Nt,contentClassName:Bn,children:[Se,rt]}),e[145]=Nt,e[146]=Se,e[147]=rt,e[148]=gt):gt=e[148];let wt;e[149]!==y?(wt=y("settings.providers.page.custom.headers.title"),e[149]=y,e[150]=wt):wt=e[150];let Pe;e[151]!==y?(Pe=y("settings.providers.page.custom.headers.description"),e[151]=y,e[152]=Pe):Pe=e[152];let se;e[153]!==Pe?(se=s.jsx("p",{className:Js,children:Pe}),e[153]=Pe,e[154]=se):se=e[154];let Ce;if(e[155]!==j.headers||e[156]!==E||e[157]!==y){let St;e[159]!==j.headers.length||e[160]!==E||e[161]!==y?(St=(Pt,Ne)=>s.jsx("div",{className:`${Us} space-y-2`,children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[s.jsxs("div",{children:[s.jsx("label",{className:zt,children:y("settings.providers.page.custom.headers.keyLabel")}),s.jsx(at,{value:Pt.key,onChange:ut=>I(Ne,"key",ut.target.value),placeholder:y("settings.providers.page.custom.headers.keyPlaceholder"),className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":y("settings.providers.page.custom.headers.keyLabel")}),E[Ne]?.key?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:E[Ne]?.key}):null]}),s.jsxs("div",{children:[s.jsx("label",{className:zt,children:y("settings.providers.page.custom.headers.valueLabel")}),s.jsx(at,{value:Pt.value,onChange:ut=>I(Ne,"value",ut.target.value),placeholder:y("settings.providers.page.custom.headers.valuePlaceholder"),className:"mt-1 h-8 rounded-md px-3 font-mono text-xs","aria-label":y("settings.providers.page.custom.headers.valueLabel")}),E[Ne]?.value?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:E[Ne]?.value}):null]})]}),s.jsx(ee,{type:"button",variant:"ghost",size:"icon",className:Is,disabled:j.headers.length<=1,onClick:()=>{j.headers.length<=1||(N(ut=>({...ut,headers:ut.headers.filter((mt,At)=>At!==Ne)})),D(ut=>ut.filter((mt,At)=>At!==Ne)))},"aria-label":y("settings.providers.page.custom.headers.remove"),children:s.jsx(K,{name:"delete-bin",className:"size-4"})})]})},Pt.row),e[159]=j.headers.length,e[160]=E,e[161]=y,e[162]=St):St=e[162],Ce=j.headers.map(St),e[155]=j.headers,e[156]=E,e[157]=y,e[158]=Ce}else Ce=e[158];let Xe;e[163]===Symbol.for("react.memo_cache_sentinel")?(Xe=()=>{N(bw),D(yw)},e[163]=Xe):Xe=e[163];let Re;e[164]!==y?(Re=y("settings.providers.page.custom.headers.add"),e[164]=y,e[165]=Re):Re=e[165];let Je;e[166]!==Re?(Je=s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Xe,children:Re}),e[166]=Re,e[167]=Je):Je=e[167];let Ge;e[168]!==wt||e[169]!==se||e[170]!==Ce||e[171]!==Je?(Ge=s.jsxs(dt,{title:wt,contentClassName:Bn,children:[se,Ce,Je]}),e[168]=wt,e[169]=se,e[170]=Ce,e[171]=Je,e[172]=Ge):Ge=e[172];let st;e[173]!==b||e[174]!==u||e[175]!==y?(st=u?s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:u,disabled:b,children:y("settings.providers.page.custom.actions.back")}):null,e[173]=b,e[174]=u,e[175]=y,e[176]=st):st=e[176];let jt;e[177]!==b||e[178]!==f||e[179]!==y?(jt=f?s.jsx(ee,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{f()},disabled:b,children:y("settings.providers.page.actions.disconnect")}):null,e[177]=b,e[178]=f,e[179]=y,e[180]=jt):jt=e[180];let Et;e[181]!==b||e[182]!==C||e[183]!==y?(Et=y(b?"settings.providers.page.actions.saving":C?"settings.providers.page.custom.actions.update":"settings.providers.page.custom.actions.save"),e[181]=b,e[182]=C,e[183]=y,e[184]=Et):Et=e[184];let Mt;e[185]!==b||e[186]!==Et?(Mt=s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:b,children:Et}),e[185]=b,e[186]=Et,e[187]=Mt):Mt=e[187];let Zt;e[188]!==st||e[189]!==jt||e[190]!==Mt?(Zt=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-4",children:[st,jt,Mt]}),e[188]=st,e[189]=jt,e[190]=Mt,e[191]=Zt):Zt=e[191];let Qt;return e[192]!==L||e[193]!==bt||e[194]!==gt||e[195]!==Ge||e[196]!==Zt?(Qt=s.jsxs("form",{onSubmit:L,className:"space-y-0",children:[bt,gt,Ge,Zt]}),e[192]=L,e[193]=bt,e[194]=gt,e[195]=Ge,e[196]=Zt,e[197]=Qt):Qt=e[197],Qt};function hw(t){return{...t,models:[...t.models,gl()]}}function xw(t){return[...t,{}]}function bw(t){return{...t,headers:[...t.headers,fl()]}}function yw(t){return[...t,{}]}const vw=t=>new Intl.NumberFormat(jr(),{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(t),id=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const e=vw(t);return e.endsWith(".0")?e.slice(0,-2):e},Ui="__add_provider__",Ua=t=>typeof t=="object"&&t!==null,rd=t=>{const e=typeof t.type=="string"?t.type:"",n=`${t.name??""} ${t.label??""}`.toLowerCase(),a=`${e} ${n}`.toLowerCase();return a.includes("oauth")?"oauth":a.includes("api")?"api":e.toLowerCase()},ww=t=>{if(!Ua(t))return{};const e={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&(e[n]=a.filter(i=>Ua(i)));return e},jw=t=>{if(typeof t=="string")return{id:t};if(!Ua(t))return null;const e=typeof t.id=="string"&&t.id||typeof t.providerID=="string"&&t.providerID||typeof t.slug=="string"&&t.slug||typeof t.name=="string"&&t.name;if(!e)return null;const n=typeof t.name=="string"?t.name:void 0;return{id:e,name:n}},kw=t=>{let e=[];Array.isArray(t)?e=t:Ua(t)&&(Array.isArray(t.all)?e=t.all:Array.isArray(t.providers)&&(e=t.providers));const n=e.map(i=>jw(i)).filter(i=>!!i),a=new Set;return n.filter(i=>a.has(i.id)?!1:(a.add(i.id),!0))},Nw=()=>{const{t}=lt(),e=pt(re=>re.providers),n=pt(re=>re.selectedProviderId),a=pt(re=>re.setSelectedProvider),i=pt(re=>re.getModelMetadata),r=ke(re=>re.hiddenModels),o=ke(re=>re.toggleHiddenModel),d=ke(re=>re.hideAllModels),c=ke(re=>re.showAllModels),[p,u]=l.useState({}),[f,m]=l.useState(!1),[w,b]=l.useState({}),[g,x]=l.useState(null),[k,y]=l.useState(""),[C,z]=l.useState(null),[j,N]=l.useState({}),[v,P]=l.useState({}),[$,O]=l.useState([]),[M,S]=l.useState(!1),[F,E]=l.useState(null),[D,W]=l.useState(""),[H,Z]=l.useState(""),[Y,A]=l.useState(!1),[X,te]=l.useState({}),[T,I]=l.useState(!1),[B,L]=l.useState(null),[V,Q]=l.useState(null),[G,ue]=l.useState(null),[ne,xe]=l.useState(null),[ve,me]=l.useState(null),ge=n===Ui,Ie=ge&&D===na,oe=!!(B&&n&&B===n&&!ge);l.useEffect(()=>{!n&&e.length>0&&a(e[0].id)},[e,n,a]),l.useEffect(()=>{if(!ge)return;let re=!0;return(async()=>{m(!0);try{const h=await Ps.getSdkClient().provider.auth();if(h.error)throw new Error(`provider.auth failed: ${String(h.error)}`);if(!re)return;u(ww(h.data))}catch(h){if(!re)return;console.error("Failed to load provider auth methods:",h),J.error(t("settings.providers.page.toast.authMethodsLoadFailed"))}finally{re&&m(!1)}})(),()=>{re=!1}},[ge,t]),l.useEffect(()=>{if(!aw(ge))return;let re=!0;return(async()=>{S(!0),E(null);try{const h=await Ps.getSdkClient().provider.list();if(h.error)throw new Error(`provider.list failed: ${String(h.error)}`);if(!re)return;O(kw(h.data))}catch(h){if(!re)return;console.error("Failed to load available providers:",h),E(t("settings.providers.page.state.unableToLoadProviderList"))}finally{re&&S(!1)}})(),()=>{re=!1}},[ge,t]);const ce=l.useMemo(()=>new Set(e.map(re=>re.id)),[e]),pe=l.useMemo(()=>$.filter(re=>!ce.has(re.id)).sort((re,U)=>{const h=(re.name||re.id).toLowerCase(),ae=(U.name||U.id).toLowerCase();return h.localeCompare(ae)}),[$,ce]);l.useEffect(()=>{n===Ui&&D&&D!==na&&!pe.some(re=>re.id===D)&&W("")},[n,D,pe]),l.useEffect(()=>{if(n===Ui){I(!0),L(null),Q(null),ue(null),xe(null);return}I(!1),B&&B!==n&&(L(null),Q(null),ue(null),xe(null))},[n,B]),l.useEffect(()=>{if(!n||n===Ui)return;let re=!1;return(async()=>{try{const h=await ht(`/api/provider/${encodeURIComponent(n)}/source`,{method:"GET",headers:{Accept:"application/json"}}),ae=await h.json().catch(()=>null);if(!h.ok)throw new Error(ae?.error||t("settings.providers.page.toast.providerSourcesLoadFailed"));const ye=ae?.sources??ae?.data?.sources;!re&&ye&&te(be=>({...be,[n]:ye}))}catch(h){re||console.error("Failed to load provider sources:",h)}})(),()=>{re=!0}},[n,t]);const ie=e.find(re=>re.id===n),le=n?X[n]:void 0,de=async re=>{const U=w[re]?.trim()??"";if(!U){J.error(t("settings.providers.page.toast.apiKeyRequired"));return}const h=`api:${re}`;x(h);try{if((await Ps.getSdkClient().auth.set({providerID:re,auth:{type:"api",key:U}})).error)throw new Error(t("settings.providers.page.toast.apiKeySaveFailed"));J.success(t("settings.providers.page.toast.apiKeySaved")),b(ye=>({...ye,[re]:""})),await _n({scopes:["providers"],mode:"active"}),a(re)}catch(ae){console.error("Failed to save API key:",ae),J.error(t("settings.providers.page.toast.apiKeySaveFailed"))}finally{x(null)}},he=async re=>{const U=`custom:${re.providerID}`;x(U),me(re.providerID),xe(null);try{const h=gw(re);if(h&&(await Ps.getSdkClient().auth.set(h)).error)throw new Error(t("settings.providers.page.toast.apiKeySaveFailed"));const ae=fw(re,{scope:B?G??nd(X[B]):"user"}),ye=await ht("/api/provider",{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(ae)}),be=await ye.json().catch(()=>null);if(!ye.ok)throw h&&xe(t("settings.providers.page.custom.authFailure.configAfterAuth")),new Error(be?.error||t("settings.providers.page.toast.customProviderSaveFailed"));J.success(t("settings.providers.page.toast.customProviderSaved",{provider:re.name})),W(""),L(null),Q(null),ue(null),xe(null),me(null),await _n({scopes:["providers"],mode:"active"}),a(re.providerID)}catch(h){console.error("Failed to save custom provider:",h),J.error(h instanceof Error&&h.message?h.message:t("settings.providers.page.toast.customProviderSaveFailed"))}finally{x(null)}},Me=async(re,U)=>{const h=`oauth:${re}:${U}`;x(h);try{const ae=await Ps.getSdkClient().provider.oauth.authorize({providerID:re,method:U});if(ae.error)throw new Error(t("settings.providers.page.toast.oauthStartFailed"));const ye=Ua(ae.data)?ae.data:{},be=ye.data,Ee=Ua(be)?be:ye,et=typeof Ee.url=="string"&&Ee.url||typeof Ee.verification_uri_complete=="string"&&Ee.verification_uri_complete||typeof Ee.verification_uri=="string"&&Ee.verification_uri||void 0,Ze=typeof Ee.instructions=="string"&&Ee.instructions||typeof Ee.message=="string"&&Ee.message||void 0,it=typeof Ee.user_code=="string"&&Ee.user_code||typeof Ee.code=="string"&&Ee.code||typeof Ee.userCode=="string"&&Ee.userCode||void 0;if(!et&&!Ze&&!it)throw new Error(t("settings.providers.page.toast.oauthDetailsMissing"));const ot=`${re}:${U}`;P(xt=>({...xt,[ot]:{url:et,instructions:Ze,userCode:it}})),et&&Tn(et),z({providerId:re,methodIndex:U}),J.message(t("settings.providers.page.toast.completeOAuthInBrowser"))}catch(ae){console.error("Failed to start OAuth flow:",ae),J.error(t("settings.providers.page.toast.oauthStartFailed"))}finally{x(null)}},Le=async(re,U)=>{const h=`${re}:${U}`,ae=j[h]?.trim(),ye=`oauth-complete:${re}:${U}`;x(ye);try{const be={method:U};if(ae&&(be.code=ae),(await Ps.getSdkClient().provider.oauth.callback({providerID:re,method:be.method,code:be.code})).error)throw new Error(t("settings.providers.page.toast.oauthCompleteFailed"));J.success(t("settings.providers.page.toast.oauthCompleted")),N(et=>({...et,[h]:""})),z(null),await _n({scopes:["providers"],mode:"active"}),a(re)}catch(be){console.error("Failed to complete OAuth flow:",be),J.error(t("settings.providers.page.toast.oauthCompleteFailed"))}finally{x(null)}},Be=async re=>{const U=await Vn(re);if(U.ok){J.success(t("settings.providers.page.toast.oauthLinkCopied"));return}console.error("Failed to copy OAuth link:",U.error),J.error(t("settings.providers.page.toast.oauthLinkCopyFailed"))},Fe=async re=>{const U=await Vn(re);if(U.ok){J.success(t("settings.providers.page.toast.deviceCodeCopied"));return}console.error("Failed to copy device code:",U.error),J.error(t("settings.providers.page.toast.deviceCodeCopyFailed"))},De=async re=>{const U=`disconnect:${re}`;x(U);try{const h=await ht(`/api/provider/${encodeURIComponent(re)}/auth?scope=all`,{method:"DELETE",headers:{Accept:"application/json"}}),ae=await h.json().catch(()=>null);if(!h.ok)throw new Error(ae?.error||t("settings.providers.page.toast.providerDisconnectFailed"));J.success(t("settings.providers.page.toast.providerDisconnected")),await _n({scopes:["providers"],mode:"active"})}catch(h){console.error("Failed to disconnect provider:",h),J.error(t("settings.providers.page.toast.providerDisconnectFailed"))}finally{x(null)}},ze=async re=>{re&&(await De(re),L(null),Q(null),ue(null),xe(null),me(null),W(""))};if(!ge&&e.length===0)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"stack",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.providers.page.empty.noProvidersDetected")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.providers.page.empty.checkOpenCodeConfiguration")})]})});if(ge)return s.jsxs(ps,{title:t("settings.providers.page.connect.title"),showSaveStatus:!1,children:[s.jsx(dt,{title:t("settings.providers.page.connect.selectProviderTitle"),divider:!1,settingsItem:"providers.connect",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-1.5",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:t("settings.providers.page.connect.providerField")}),M?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.state.loading")}):F?s.jsx("p",{className:"typography-meta text-muted-foreground",children:F}):s.jsxs(fs,{open:Y,onOpenChange:re=>{A(re),re||Z("")},children:[s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button",className:$n,children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[D&&D!==na?s.jsx(ia,{providerId:D,className:"h-3.5 w-3.5 flex-shrink-0"}):null,s.jsx("span",{className:fe("truncate typography-ui-label font-normal",D?"text-foreground":"text-muted-foreground"),children:D===na?t("settings.providers.page.custom.optionLabel"):D?pe.find(re=>re.id===D)?.name||D:t("settings.providers.page.connect.selectProviderPlaceholder")})]}),s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/50"})]})}),s.jsxs(hs,{align:"start",className:"w-[280px] p-0",onCloseAutoFocus:re=>re.preventDefault(),children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-[var(--surface-subtle)] px-3 py-2",onKeyDown:re=>re.stopPropagation(),children:[s.jsx(K,{name:"search",className:"h-4 w-4 text-muted-foreground"}),s.jsx("input",{type:"text",value:H,onChange:re=>Z(re.target.value),onKeyDown:re=>re.stopPropagation(),placeholder:t("settings.providers.page.connect.searchProvidersPlaceholder"),className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),s.jsx(Os,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const re=H.toLowerCase(),U=t("settings.providers.page.custom.optionLabel"),h=!re||U.toLowerCase().includes(re)||"other".includes(re)||"custom".includes(re),ae=pe.filter(ye=>(ye.name||ye.id).toLowerCase().includes(re)||ye.id.toLowerCase().includes(re));return ae.length===0&&!h?s.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:t("settings.providers.page.connect.noProvidersFound")}):s.jsxs(s.Fragment,{children:[ae.map(ye=>s.jsxs(as,{onSelect:()=>{W(ye.id),A(!1),Z("")},className:"flex items-center justify-between",children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(ia,{providerId:ye.id,className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:ye.name||ye.id})]}),D===ye.id&&s.jsx(K,{name:"check",className:"h-4 w-4 text-[var(--primary-base)]"})]},ye.id)),h?s.jsxs(as,{onSelect:()=>{W(na),A(!1),Z("")},className:"flex items-center justify-between",children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(K,{name:"add",className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:U})]}),D===na&&s.jsx(K,{name:"check",className:"h-4 w-4 text-[var(--primary-base)]"})]},na):null]})})()})]})]})]})}),Ie?s.jsx(ad,{mode:"create",existingProviderIDs:ce,busy:g?.startsWith("custom:")??!1,authFailureHint:ne,onCancel:()=>{W(""),xe(null),me(null)},onDisconnect:ne&&ve?()=>{ze(ve)}:void 0,onSubmit:he}):D?s.jsx(dt,{title:t("settings.providers.page.auth.title"),settingsItem:"providers.auth",contentClassName:"space-y-4",children:f?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.auth.loadingMethods")}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"py-1.5",children:[s.jsxs("label",{className:"typography-ui-label text-foreground flex items-center gap-1.5",children:[t("settings.providers.page.auth.apiKeyLabel"),s.jsx($t,{children:t("settings.providers.page.auth.apiKeyTooltip")})]}),s.jsxs("div",{className:"flex flex-col @xl:flex-row @xl:items-center gap-2 mt-1.5",children:[s.jsx(at,{type:"password",value:w[D]??"",onChange:re=>b(U=>({...U,[D]:re.target.value})),placeholder:t("settings.providers.page.auth.apiKeyPlaceholder"),className:"flex-1 font-mono text-xs"}),s.jsx(ee,{size:"xs",className:"!font-normal shrink-0",onClick:()=>de(D),disabled:g===`api:${D}`,children:g===`api:${D}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.saveKey")})]})]}),(()=>{const U=(p[D]??[]).filter(h=>rd(h)==="oauth");return U.length===0?null:s.jsx("div",{className:"space-y-4 border-t border-[var(--surface-subtle)] pt-2",children:U.map((h,ae)=>{const ye=h.label||h.name||t("settings.providers.page.auth.oauthMethodFallback",{index:String(ae+1)}),be=`${D}:${ae}`,Ee=C?.providerId===D&&C?.methodIndex===ae;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:ye}),(h.description||h.help)&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:String(h.description||h.help)})]}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Me(D,ae),disabled:g===`oauth:${D}:${ae}`,children:t("settings.providers.page.actions.connect")})]}),v[be]?.instructions&&s.jsx("p",{className:"typography-meta text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-2 py-1.5 rounded",children:v[be]?.instructions}),v[be]?.userCode&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(at,{value:v[be]?.userCode,readOnly:!0,className:"font-mono text-center tracking-widest"}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Fe(v[be]?.userCode??""),children:t("settings.providers.page.actions.copyCode")})]}),v[be]?.url&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(at,{value:v[be]?.url,readOnly:!0,className:"text-xs text-muted-foreground"}),s.jsxs("div",{className:"flex gap-1 shrink-0",children:[s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Tn(v[be]?.url??""),children:t("settings.providers.page.actions.open")}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Be(v[be]?.url??""),children:t("settings.providers.page.actions.copy")})]})]}),Ee&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(at,{value:j[be]??"",onChange:et=>N(Ze=>({...Ze,[be]:et.target.value})),placeholder:t("settings.providers.page.auth.pasteAuthorizationCodePlaceholder"),className:"font-mono text-xs"}),s.jsx(ee,{size:"xs",className:"!font-normal",onClick:()=>Le(D,ae),disabled:g===`oauth-complete:${D}:${ae}`,children:g===`oauth-complete:${D}:${ae}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.complete")})]})]},`${D}-${ye}`)})})})()]})}):null]});if(!ie)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"stack",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.providers.page.empty.selectProviderFromSidebar")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.providers.page.empty.reviewDetailsAndConfigureAuth")})]})});const Ve=Array.isArray(ie.models)?ie.models:[],_e=(p[ie.id]??[]).filter(re=>rd(re)==="oauth"),He=!!le,Ke=He&&uw(ie,le),Oe=Array.isArray(ie.env)?ie.env.filter(re=>typeof re=="string"&&re.trim().length>0):[],je=!!le?.auth.exists,Te=Oe.length>0,Ue=je||Te,Ye=Ke&&!Ue,q=Ve.filter(re=>{const U=typeof re?.name=="string"?re.name:"",h=typeof re?.id=="string"?re.id:"",ae=k.trim().toLowerCase();return ae?U.toLowerCase().includes(ae)||h.toLowerCase().includes(ae):!0});return oe&&Ke&&V?s.jsx(ps,{title:ie.name||ie.id,titleLeading:s.jsx(ia,{providerId:ie.id,className:"h-5 w-5 shrink-0"}),description:s.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:ie.id}),showSaveStatus:!1,children:s.jsx(ad,{mode:"edit",existingProviderIDs:ce,initialValues:V,allowExistingAuth:Ue||!He,busy:g?.startsWith("custom:")??!1,authFailureHint:ne,onCancel:()=>{L(null),Q(null),ue(null),xe(null),me(null)},onDisconnect:()=>{ze(ie.id)},onSubmit:he})}):s.jsxs(ps,{title:ie.name||ie.id,titleLeading:s.jsx(ia,{providerId:ie.id,className:"h-5 w-5 shrink-0"}),description:s.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:ie.id}),showSaveStatus:!1,children:[s.jsx(dt,{title:t("settings.providers.page.auth.title"),divider:!1,headerAction:s.jsxs("div",{className:"flex items-center gap-1",children:[Ke?s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{xe(null),Q(mw(ie)),ue(nd(le)),L(ie.id)},children:t("settings.providers.page.actions.edit")}):null,s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>I(re=>!re),children:t(T?"settings.providers.page.actions.hide":"settings.providers.page.actions.reconnect")})]}),settingsItem:"providers.auth",children:T?f?s.jsx("div",{className:"py-1.5 typography-meta text-muted-foreground",children:t("settings.providers.page.auth.loadingMethods")}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"py-1.5",children:[s.jsxs("label",{className:"typography-ui-label text-foreground flex items-center gap-1.5",children:[t("settings.providers.page.auth.apiKeyLabel"),s.jsx($t,{children:t("settings.providers.page.auth.apiKeyTooltip")})]}),s.jsxs("div",{className:"flex flex-col @xl:flex-row @xl:items-center gap-2 mt-1.5",children:[s.jsx(at,{type:"password",value:w[ie.id]??"",onChange:re=>b(U=>({...U,[ie.id]:re.target.value})),placeholder:t("settings.providers.page.auth.apiKeyPlaceholder"),className:"flex-1 font-mono text-xs"}),s.jsx(ee,{size:"xs",className:"!font-normal shrink-0",onClick:()=>de(ie.id),disabled:g===`api:${ie.id}`,children:g===`api:${ie.id}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.saveKey")})]})]}),_e.length>0&&s.jsx("div",{className:"space-y-4 border-t border-[var(--surface-subtle)] pt-2",children:_e.map((re,U)=>{const h=re.label||re.name||t("settings.providers.page.auth.oauthMethodFallback",{index:String(U+1)}),ae=`${ie.id}:${U}`,ye=C?.providerId===ie.id&&C?.methodIndex===U;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:h}),(re.description||re.help)&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:String(re.description||re.help)})]}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Me(ie.id,U),disabled:g===`oauth:${ie.id}:${U}`,children:t("settings.providers.page.actions.connect")})]}),v[ae]?.instructions&&s.jsx("p",{className:"typography-meta text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-2 py-1.5 rounded",children:v[ae]?.instructions}),v[ae]?.userCode&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(at,{value:v[ae]?.userCode,readOnly:!0,className:"font-mono text-center tracking-widest"}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Fe(v[ae]?.userCode??""),children:t("settings.providers.page.actions.copyCode")})]}),v[ae]?.url&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(at,{value:v[ae]?.url,readOnly:!0,className:"text-xs text-muted-foreground"}),s.jsxs("div",{className:"flex gap-1 shrink-0",children:[s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Tn(v[ae]?.url??""),children:t("settings.providers.page.actions.open")}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Be(v[ae]?.url??""),children:t("settings.providers.page.actions.copy")})]})]}),ye&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(at,{value:j[ae]??"",onChange:be=>N(Ee=>({...Ee,[ae]:be.target.value})),placeholder:t("settings.providers.page.auth.pasteAuthorizationCodePlaceholder"),className:"font-mono text-xs"}),s.jsx(ee,{size:"xs",className:"!font-normal",onClick:()=>Le(ie.id,U),disabled:g===`oauth-complete:${ie.id}:${U}`,children:g===`oauth-complete:${ie.id}:${U}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.complete")})]})]},`${ie.id}-${h}`)})})]}):Ye?s.jsxs("div",{className:"flex items-center gap-1.5 py-1.5",children:[s.jsx(K,{name:"alert",className:"w-4 h-4 text-[var(--status-warning)] shrink-0"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:t("settings.providers.page.auth.incomplete")}),s.jsx($t,{children:t("settings.providers.page.auth.incompleteHint")})]}):s.jsxs("div",{className:"flex items-center gap-1.5 py-1.5",children:[s.jsx(K,{name:"check",className:"w-4 h-4 text-[var(--status-success)] shrink-0"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:t("settings.providers.page.auth.connected")}),s.jsx($t,{children:t("settings.providers.page.auth.useReconnectHint")})]})}),s.jsx(dt,{title:t("settings.providers.page.connectionDetails.title"),settingsItem:"providers.connection-details",children:s.jsxs("div",{className:"flex flex-col gap-2 py-1.5 @xl:flex-row @xl:items-center @xl:justify-between @xl:gap-8",children:[s.jsx("div",{className:"flex min-w-0 flex-col",children:le&&(le.auth.exists||le.user.exists||le.project.exists||le.custom?.exists)?s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t("settings.providers.page.connectionDetails.configuredIn")," ",[le.auth.exists?t("settings.providers.page.connectionDetails.source.authCredentials"):null,le.user.exists?t("settings.providers.page.connectionDetails.source.userConfig"):null,le.project.exists?t("settings.providers.page.connectionDetails.source.projectConfig"):null,le.custom?.exists?t("settings.providers.page.connectionDetails.source.customConfig"):null].filter(Boolean).join(", ")]}):s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.connectionDetails.noActiveSource")})}),s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal text-[var(--status-error)] hover:text-[var(--status-error)]",onClick:()=>De(ie.id),disabled:g===`disconnect:${ie.id}`,children:g===`disconnect:${ie.id}`?t("settings.providers.page.actions.disconnecting"):t("settings.providers.page.actions.disconnect")})]})}),s.jsxs(dt,{title:t("settings.providers.page.models.title"),titleAccessory:Ve.length>0?s.jsxs("span",{className:"typography-micro text-muted-foreground font-normal",children:["(",Ve.length,")"]}):null,headerAction:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{const re=Ve.map(U=>typeof U?.id=="string"?U.id:"").filter(U=>U.length>0);d(ie.id,re)},children:t("settings.providers.page.actions.hideAll")}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>c(ie.id),children:t("settings.providers.page.actions.showAll")})]}),settingsItem:"providers.models",children:[s.jsxs("div",{className:"relative mb-2",children:[s.jsx(K,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),s.jsx(at,{value:k,onChange:re=>y(re.target.value),placeholder:t("settings.providers.page.models.filterPlaceholder"),className:"h-7 pl-8 w-full"})]}),q.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground py-4 text-center",children:t("settings.providers.page.models.noModelsMatchFilter")}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:q.map(re=>{const U=typeof re?.id=="string"?re.id:"",h=typeof re?.name=="string"?re.name:U,ae=U?i(ie.id,U):void 0,ye=r.some(Ze=>Ze.providerID===ie.id&&Ze.modelID===U),be=id(ae?.limit?.context),Ee=id(ae?.limit?.output),et=[];return ae?.tool_call&&et.push({key:"tools",icon:"tools",label:t("settings.providers.page.models.capability.toolCalling")}),ae?.reasoning&&et.push({key:"reasoning",icon:"brain-ai-3",label:t("settings.providers.page.models.capability.reasoning")}),ae?.attachment&&et.push({key:"image",icon:"file-image",label:t("settings.providers.page.models.capability.imageInput")}),s.jsx("div",{className:"py-1.5",children:s.jsxs("div",{className:fe("flex items-center gap-3",ye&&"opacity-50"),children:[s.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:h}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[(be||Ee)&&s.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0 bg-[var(--surface-muted)] px-1.5 py-0.5 rounded",children:[be?`${be} ${t("settings.providers.page.models.tokenBadge.context")}`:"",be&&Ee?" · ":"",Ee?`${Ee} ${t("settings.providers.page.models.tokenBadge.output")}`:""]}),et.length>0&&s.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:et.map(({key:Ze,icon:it,label:ot})=>s.jsx("span",{className:"flex h-5 w-5 rounded items-center justify-center text-muted-foreground bg-[var(--surface-muted)]",title:ot,"aria-label":ot,children:s.jsx(K,{name:it,className:"h-3 w-3"})},Ze))}),s.jsx("button",{type:"button",onClick:()=>o(ie.id,U),className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]/50",title:t(ye?"settings.providers.page.models.actions.showModelInSelectors":"settings.providers.page.models.actions.hideModelFromSelectors"),"aria-label":t(ye?"settings.providers.page.models.actions.showModel":"settings.providers.page.models.actions.hideModel"),children:ye?s.jsx(K,{name:"eye-off",className:"h-3.5 w-3.5"}):s.jsx(K,{name:"eye",className:"h-3.5 w-3.5"})})]})]})},U)})})]})]})},Jn=[{id:"claude",name:"Claude"},{id:"codex",name:"Codex"},{id:"cursor",name:"Cursor"},{id:"github-copilot",name:"GitHub Copilot"},{id:"google",name:"Google"},{id:"kimi-for-coding",name:"Kimi for Coding"},{id:"nano-gpt",name:"NanoGPT"},{id:"openrouter",name:"OpenRouter"},{id:"zai-coding-plan",name:"z.ai"},{id:"zhipuai-coding-plan",name:"Zhipu AI Coding Plan"},{id:"minimax-cn-coding-plan",name:"MiniMax Coding Plan (minimaxi.com)"},{id:"minimax-coding-plan",name:"MiniMax Coding Plan (minimax.io)"},{id:"ollama-cloud",name:"Ollama Cloud"},{id:"wafer",name:"Wafer.ai"},{id:"opencode-go",name:"OpenCode Go"},{id:"crof",name:"CrofAI"},{id:"deepseek",name:"DeepSeek"},{id:"neuralwatt",name:"NeuralWatt"}];function od(t){const e=t.indexOf("/");if(e!==-1){const n=t.substring(0,e);if(n==="gemini"||n==="antigravity")return t.substring(e+1)}return t}const Sw=[{id:"gemini-auth",label:"Gemini",matcher:t=>t.startsWith("gemini/"),order:1},{id:"antigravity-auth",label:"Antigravity",matcher:t=>t.startsWith("antigravity/"),order:2}],Qu={google:Sw};function Xu(t,e){const n=Qu[e]??[];for(const a of n)if(a.matcher(t))return a;return null}function Cw(t){return Qu[t]??[]}function Iw(t){return[...t].sort((e,n)=>e.order-n.order)}function XN(t,e){const n=new Map;for(const a of Object.keys(t)){const r=Xu(a,e)?.id??null;n.has(r)||n.set(r,[]),n.get(r).push(a)}return n}function Pw(t,e,n){const a=new Map;for(const i of t){const r=e(i),d=Xu(r,n)?.id??null;a.has(d)||a.set(d,[]),a.get(d).push(i)}return a}function Tw(t,e){return e.filter(n=>{const a=n.toLowerCase(),i=a.includes("/")?a.split("/")[1]:a;return!!(i.startsWith("gemini-3-")||i.startsWith("claude-"))})}const hl=6e4,ld=t=>{const e=Jn.map(m=>m.id),n=typeof t?.usageAutoRefresh=="boolean"?t.usageAutoRefresh:!1,a=typeof t?.usageRefreshIntervalMs=="number"&&Number.isFinite(t.usageRefreshIntervalMs)?Math.max(3e4,Math.min(3e5,Math.round(t.usageRefreshIntervalMs))):hl,i=t?.usageDisplayMode==="remaining"?"remaining":"usage",r=typeof t?.usageShowPredValues=="boolean"?t.usageShowPredValues:!1,o=Array.isArray(t?.usageDropdownProviders)?t?.usageDropdownProviders:null,d=o?o.filter(m=>typeof m=="string"&&e.includes(m)):e,c={},p=t?.usageSelectedModels;if(p&&typeof p=="object")for(const[m,w]of Object.entries(p))Array.isArray(w)&&(c[m]=w.filter(b=>typeof b=="string"));const u={},f=t?.usageExpandedFamilies;if(f&&typeof f=="object")for(const[m,w]of Object.entries(f))Array.isArray(w)&&(u[m]=w.filter(b=>typeof b=="string"));return{autoRefresh:n,refreshIntervalMs:a,displayMode:i,showPredValues:r,dropdownProviderIds:d,selectedModels:c,expandedFamilies:u}},Aw=async()=>{const t=nn()?.settings;if(t)try{const n=(await t.load())?.settings;return ld(n??null)}catch{}if(!ds()){const e=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(e.ok){const n=await e.json().catch(()=>null);return ld(n)}}return{autoRefresh:!1,refreshIntervalMs:hl,displayMode:"usage",showPredValues:!1,dropdownProviderIds:Jn.map(e=>e.id),selectedModels:{},expandedFamilies:{}}},qt=gn()(qa((t,e)=>({results:[],selectedProviderId:null,isLoading:!1,isFetchingProvider:{},lastUpdated:null,error:null,autoRefresh:!1,refreshIntervalMs:hl,displayMode:"usage",showPredValues:!1,dropdownProviderIds:Jn.map(n=>n.id),selectedModels:{},expandedFamilies:{},loadSettings:async()=>{try{const n=await Aw();t(n)}catch(n){console.warn("Failed to load usage settings:",n)}},fetchAllQuotas:async()=>{t({isLoading:!0,error:null});const n=Jn.map(a=>a.id);try{await Promise.all(n.map(a=>e().fetchProviderQuota(a))),t({isLoading:!1,lastUpdated:Date.now()})}catch(a){const i=a instanceof Error?a.message:"Failed to fetch quotas";t({isLoading:!1,error:i})}},fetchProviderQuota:async n=>{t(a=>({isFetchingProvider:{...a.isFetchingProvider,[n]:!0}}));try{const a=await ht(`/api/quota/${encodeURIComponent(n)}`),i=await a.json().catch(()=>null);if(!a.ok)throw new Error(i?.error||"Failed to fetch quota");const r=i;t(o=>{const d=o.results.filter(c=>c.providerId!==n);return d.push(r),{results:d,error:null}})}catch(a){const i=a instanceof Error?a.message:"Failed to fetch quota",r={providerId:n,providerName:n,ok:!1,configured:!1,error:i,usage:null,fetchedAt:Date.now()};t(o=>{const d=o.results.filter(c=>c.providerId!==n);return d.push(r),{results:d,error:i}})}finally{t(a=>({isFetchingProvider:{...a.isFetchingProvider,[n]:!1}}))}},setSelectedProvider:n=>t({selectedProviderId:n}),setAutoRefresh:n=>t({autoRefresh:n}),setRefreshInterval:n=>{const a=Math.max(3e4,Math.min(3e5,Math.round(n)));t({refreshIntervalMs:a})},setDisplayMode:n=>t({displayMode:n}),setShowPredValues:n=>t({showPredValues:n}),setDropdownProviderIds:n=>t({dropdownProviderIds:n}),setSelectedModels:(n,a)=>{t(i=>({selectedModels:{...i.selectedModels,[n]:a}}))},toggleModelSelected:(n,a)=>{t(i=>{const r=i.selectedModels[n]??[],d=r.includes(a)?r.filter(c=>c!==a):[...r,a];return{selectedModels:{...i.selectedModels,[n]:d}}})},setExpandedFamilies:(n,a)=>{t(i=>({expandedFamilies:{...i.expandedFamilies,[n]:a}})),It({usageExpandedFamilies:e().expandedFamilies})},toggleFamilyExpanded:(n,a)=>{t(i=>{const r=i.expandedFamilies[n]??[],d=r.includes(a)?r.filter(c=>c!==a):[...r,a];return{expandedFamilies:{...i.expandedFamilies,[n]:d}}}),It({usageExpandedFamilies:e().expandedFamilies})},applyDefaultSelections:(n,a)=>{if((e().selectedModels[n]?.length??0)>0)return;const r=Tw(n,a);r.length!==0&&(t(o=>({selectedModels:{...o.selectedModels,[n]:r}})),It({usageSelectedModels:e().selectedModels}))}}),{name:"quota-store"})),Ew=()=>{const t=tt.c(5),e=qt(Dw),n=qt(Rw),a=qt(Mw);let i,r;t[0]!==e||t[1]!==a||t[2]!==n?(i=()=>{if(!e)return;const o=window.setInterval(()=>{a()},n);return()=>window.clearInterval(o)},r=[e,n,a],t[0]=e,t[1]=a,t[2]=n,t[3]=i,t[4]=r):(i=t[3],r=t[4]),l.useEffect(i,r)};function Dw(t){return t.autoRefresh}function Rw(t){return t.refreshIntervalMs}function Mw(t){return t.fetchAllQuotas}const Lw=t=>{const e=t?.windows??{},n=Object.values(e).map(a=>a.usedPercent).filter(a=>typeof a=="number");return n.length===0?null:Math.max(...n)},Fw=t=>{const e=tt.c(122),{onItemSelect:n}=t,{t:a}=lt(),i=qt(Ow),r=qt(zw),o=qt(Kw),d=qt(Bw),c=qt(_w),p=qt(Uw),u=qt($w),f=qt(Vw),m=qt(Hw),w=qt(Ww),b=qt(Gw),g=qt(qw),x=qt(Jw),k=qt(Yw);let y,C;e[0]!==k?(y=()=>{k()},C=[k],e[0]=k,e[1]=y,e[2]=C):(y=e[1],C=e[2]),l.useEffect(y,C);const z=Qw;let j;e[3]!==m?(j=Ue=>{m(Ue),z({usageAutoRefresh:Ue})},e[3]=m,e[4]=j):j=e[4];const N=j;let v;e[5]!==w?(v=Ue=>{const Ye=Number(Ue);Number.isFinite(Ye)&&(w(Ye),z({usageRefreshIntervalMs:Ye}))},e[5]=w,e[6]=v):v=e[6];const P=v;let $;e[7]!==b?($=Ue=>{Ue!=="usage"&&Ue!=="remaining"||(b(Ue),z({usageDisplayMode:Ue}))},e[7]=b,e[8]=$):$=e[8];const O=$;let M;e[9]!==x?(M=Ue=>{x(Ue),z({usageShowPredValues:Ue})},e[9]=x,e[10]=M):M=e[10];const S=M;let F;e[11]===Symbol.for("react.memo_cache_sentinel")?(F=fe("flex h-full flex-col","bg-background"),e[11]=F):F=e[11];let E;e[12]!==a?(E=a("settings.usage.sidebar.title"),e[12]=a,e[13]=E):E=e[13];let D;e[14]!==E?(D=s.jsx("h2",{className:`${fn} mb-3`,children:E}),e[14]=E,e[15]=D):D=e[15];let W;e[16]!==a?(W=a("settings.usage.sidebar.total",{count:Jn.length}),e[16]=a,e[17]=W):W=e[17];let H;e[18]!==W?(H=s.jsx("span",{className:"typography-meta text-muted-foreground",children:W}),e[18]=W,e[19]=H):H=e[19];let Z;e[20]!==a?(Z=a("settings.usage.sidebar.actions.toggleAutoRefreshAria"),e[20]=a,e[21]=Z):Z=e[21];let Y;e[22]!==N||e[23]!==Z||e[24]!==p?(Y=s.jsx(xs,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(an,{checked:p,onChange:N,ariaLabel:Z})})}),e[22]=N,e[23]=Z,e[24]=p,e[25]=Y):Y=e[25];let A;e[26]!==a?(A=a("settings.usage.sidebar.tooltip.autoRefresh"),e[26]=a,e[27]=A):A=e[27];let X;e[28]!==A?(X=s.jsx(ks,{side:"bottom",children:A}),e[28]=A,e[29]=X):X=e[29];let te;e[30]!==Y||e[31]!==X?(te=s.jsxs(bs,{children:[Y,X]}),e[30]=Y,e[31]=X,e[32]=te):te=e[32];const T=String(u),I=!p;let B;e[33]!==a?(B=a("settings.usage.sidebar.field.intervalPlaceholder"),e[33]=a,e[34]=B):B=e[34];let L;e[35]!==B?(L=s.jsx(Ft,{className:"w-fit",children:s.jsx(Wt,{placeholder:B})}),e[35]=B,e[36]=L):L=e[36];let V;e[37]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsxs(Ot,{children:[s.jsx(kt,{value:"30000",children:"30s"}),s.jsx(kt,{value:"60000",children:"1m"}),s.jsx(kt,{value:"300000",children:"5m"})]}),e[37]=V):V=e[37];let Q;e[38]!==P||e[39]!==T||e[40]!==I||e[41]!==L?(Q=s.jsxs(Lt,{value:T,onValueChange:P,disabled:I,children:[L,V]}),e[38]=P,e[39]=T,e[40]=I,e[41]=L,e[42]=Q):Q=e[42];let G;e[43]!==d?(G=()=>d(),e[43]=d,e[44]=G):G=e[44];let ue;e[45]!==a?(ue=a("settings.usage.sidebar.actions.refreshAria"),e[45]=a,e[46]=ue):ue=e[46];let ne;e[47]!==a?(ne=a("settings.usage.sidebar.actions.refreshTitle"),e[47]=a,e[48]=ne):ne=e[48];const xe=c&&"animate-spin";let ve;e[49]!==xe?(ve=fe("h-3.5 w-3.5",xe),e[49]=xe,e[50]=ve):ve=e[50];let me;e[51]!==ve?(me=s.jsx(K,{name:"refresh",className:ve}),e[51]=ve,e[52]=me):me=e[52];let ge;e[53]!==c||e[54]!==G||e[55]!==ue||e[56]!==ne||e[57]!==me?(ge=s.jsx(ee,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 text-muted-foreground",onClick:G,"aria-label":ue,title:ne,disabled:c,children:me}),e[53]=c,e[54]=G,e[55]=ue,e[56]=ne,e[57]=me,e[58]=ge):ge=e[58];let Ie;e[59]!==te||e[60]!==Q||e[61]!==ge?(Ie=s.jsxs("div",{className:"flex items-center gap-2",children:[te,Q,ge]}),e[59]=te,e[60]=Q,e[61]=ge,e[62]=Ie):Ie=e[62];let oe;e[63]!==H||e[64]!==Ie?(oe=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[H,Ie]}),e[63]=H,e[64]=Ie,e[65]=oe):oe=e[65];let ce;e[66]!==a?(ce=a("settings.usage.sidebar.field.display"),e[66]=a,e[67]=ce):ce=e[67];let pe;e[68]!==ce?(pe=s.jsx("span",{className:"typography-micro text-muted-foreground",children:ce}),e[68]=ce,e[69]=pe):pe=e[69];let ie;e[70]!==a?(ie=a("settings.usage.sidebar.field.displayModePlaceholder"),e[70]=a,e[71]=ie):ie=e[71];let le;e[72]!==ie?(le=s.jsx(Ft,{className:"w-fit",children:s.jsx(Wt,{placeholder:ie})}),e[72]=ie,e[73]=le):le=e[73];let de;e[74]!==a?(de=a("settings.usage.sidebar.field.displayModeUsage"),e[74]=a,e[75]=de):de=e[75];let he;e[76]!==de?(he=s.jsx(kt,{value:"usage",children:de}),e[76]=de,e[77]=he):he=e[77];let Me;e[78]!==a?(Me=a("settings.usage.sidebar.field.displayModeRemaining"),e[78]=a,e[79]=Me):Me=e[79];let Le;e[80]!==Me?(Le=s.jsx(kt,{value:"remaining",children:Me}),e[80]=Me,e[81]=Le):Le=e[81];let Be;e[82]!==he||e[83]!==Le?(Be=s.jsxs(Ot,{children:[he,Le]}),e[82]=he,e[83]=Le,e[84]=Be):Be=e[84];let Fe;e[85]!==O||e[86]!==le||e[87]!==Be||e[88]!==f?(Fe=s.jsxs(Lt,{value:f,onValueChange:O,children:[le,Be]}),e[85]=O,e[86]=le,e[87]=Be,e[88]=f,e[89]=Fe):Fe=e[89];let De;e[90]!==pe||e[91]!==Fe?(De=s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[pe,Fe]}),e[90]=pe,e[91]=Fe,e[92]=De):De=e[92];let ze;e[93]!==a?(ze=a("settings.usage.sidebar.field.showPredictions"),e[93]=a,e[94]=ze):ze=e[94];let Ve;e[95]!==ze?(Ve=s.jsx("span",{className:"typography-micro text-muted-foreground",children:ze}),e[95]=ze,e[96]=Ve):Ve=e[96];let We;e[97]!==a?(We=a("settings.usage.sidebar.field.showPredictions"),e[97]=a,e[98]=We):We=e[98];let _e;e[99]!==S||e[100]!==g||e[101]!==We?(_e=s.jsx(an,{checked:g,onChange:S,ariaLabel:We}),e[99]=S,e[100]=g,e[101]=We,e[102]=_e):_e=e[102];let He;e[103]!==Ve||e[104]!==_e?(He=s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[Ve,_e]}),e[103]=Ve,e[104]=_e,e[105]=He):He=e[105];let Ke;e[106]!==oe||e[107]!==De||e[108]!==He||e[109]!==D?(Ke=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[D,oe,De,He]}),e[106]=oe,e[107]=De,e[108]=He,e[109]=D,e[110]=Ke):Ke=e[110];let Oe;e[111]!==n||e[112]!==i||e[113]!==r||e[114]!==o||e[115]!==a?(Oe=Jn.map(Ue=>{const Ye=i.find(ye=>ye.providerId===Ue.id),q=Lw(Ye?.usage),re=iu(q),U=Ue.id===r,h=Ye?.configured??!1,ae=h?re==="critical"?{backgroundColor:"var(--status-error)"}:re==="warn"?{backgroundColor:"var(--status-warning)"}:{backgroundColor:"var(--status-success)"}:{backgroundColor:"var(--surface-muted-foreground)",opacity:.4};return s.jsx("div",{className:fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",U?"bg-interactive-selection":"hover:bg-interactive-hover"),children:s.jsxs("button",{type:"button",onClick:()=>{o(Ue.id),n?.()},className:"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full flex-shrink-0",style:ae}),s.jsx(ia,{providerId:Ue.id,className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:Ue.name}),!h&&s.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:a("settings.usage.sidebar.status.notSet")})]})},Ue.id)}),e[111]=n,e[112]=i,e[113]=r,e[114]=o,e[115]=a,e[116]=Oe):Oe=e[116];let je;e[117]!==Oe?(je=s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:Oe}),e[117]=Oe,e[118]=je):je=e[118];let Te;return e[119]!==Ke||e[120]!==je?(Te=s.jsxs("div",{className:F,children:[Ke,je]}),e[119]=Ke,e[120]=je,e[121]=Te):Te=e[121],Te};function Ow(t){return t.results}function zw(t){return t.selectedProviderId}function Kw(t){return t.setSelectedProvider}function Bw(t){return t.fetchAllQuotas}function _w(t){return t.isLoading}function Uw(t){return t.autoRefresh}function $w(t){return t.refreshIntervalMs}function Vw(t){return t.displayMode}function Hw(t){return t.setAutoRefresh}function Ww(t){return t.setRefreshInterval}function Gw(t){return t.setDisplayMode}function qw(t){return t.showPredValues}function Jw(t){return t.setShowPredValues}function Yw(t){return t.loadSettings}async function Qw(t){try{await It(t)}catch(e){console.warn("Failed to save usage settings:",e)}}const Xw=t=>{const e=tt.c(20),{percent:n,tonePercent:a,className:i,expectedMarkerPercent:r}=t;let o;e[0]!==n?(o=Ip(n)??0,e[0]=n,e[1]=o):o=e[1];const d=o,c=a??n;let p;e[2]!==c?(p=iu(c),e[2]=c,e[3]=p):p=e[3];const u=p,f=r!=null?Math.max(0,Math.min(100,r)):null;let m;e[4]!==u?(m=u==="critical"?{backgroundColor:"var(--status-error)"}:u==="warn"?{backgroundColor:"var(--status-warning)"}:{backgroundColor:"var(--status-success)"},e[4]=u,e[5]=m):m=e[5];const w=m;let b;e[6]!==i?(b=fe("relative h-2.5 rounded-full bg-[var(--interactive-border)] overflow-hidden",i),e[6]=i,e[7]=b):b=e[7];const g=`${d}%`;let x;e[8]!==w||e[9]!==g?(x={...w,width:g},e[8]=w,e[9]=g,e[10]=x):x=e[10];let k;e[11]!==d||e[12]!==x?(k=s.jsx("div",{className:"h-full transition-all duration-300",style:x,role:"progressbar","aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100}),e[11]=d,e[12]=x,e[13]=k):k=e[13];let y;e[14]!==f?(y=f!=null&&f>0&&f<100&&s.jsx("div",{className:"absolute top-0 h-full w-0.5 bg-foreground",style:{left:`${f}%`},title:`Expected usage if spread evenly: ${Math.round(f)}% of quota`,"aria-hidden":"true"}),e[14]=f,e[15]=y):y=e[15];let C;return e[16]!==b||e[17]!==k||e[18]!==y?(C=s.jsxs("div",{className:b,children:[k,y]}),e[16]=b,e[17]=k,e[18]=y,e[19]=C):C=e[19],C},Zw=t=>{const e=tt.c(67),{paceInfo:n,className:a,compact:i}=t,r=i===void 0?!1:i,{t:o}=lt();let d;e[0]!==n.status?(d=Pp(n.status),e[0]=n.status,e[1]=d):d=e[1];const c=d;let p;e:{switch(n.status){case"on-track":{let v;e[2]!==o?(v=o("settings.usage.pace.status.onTrack"),e[2]=o,e[3]=v):v=e[3],p=v;break e}case"slightly-fast":{let v;e[4]!==o?(v=o("settings.usage.pace.status.slightlyFast"),e[4]=o,e[5]=v):v=e[5],p=v;break e}case"too-fast":{let v;e[6]!==o?(v=o("settings.usage.pace.status.tooFast"),e[6]=o,e[7]=v):v=e[7],p=v;break e}case"exhausted":{let v;e[8]!==o?(v=o("settings.usage.pace.status.usedUp"),e[8]=o,e[9]=v):v=e[9],p=v;break e}}p=void 0}const u=p;let f;e[10]!==n.predictText||e[11]!==o?(f=o("settings.usage.pace.predictionTooltip",{prediction:n.predictText}),e[10]=n.predictText,e[11]=o,e[12]=f):f=e[12];const m=f;if(r){let v;e[13]!==a?(v=fe("flex items-center gap-1.5",a),e[13]=a,e[14]=v):v=e[14];let P;e[15]!==c?(P={backgroundColor:c},e[15]=c,e[16]=P):P=e[16];let $;e[17]!==u||e[18]!==P?($=s.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:P,title:u}),e[17]=u,e[18]=P,e[19]=$):$=e[19];let O;e[20]!==c?(O={color:c},e[20]=c,e[21]=O):O=e[21];const M=n.isExhausted?void 0:m;let S;e[22]!==n.isExhausted||e[23]!==n.predictText||e[24]!==n.remainingSeconds||e[25]!==o?(S=n.isExhausted?s.jsx(s.Fragment,{children:o("settings.usage.pace.wait",{duration:Pl(n.remainingSeconds)})}):s.jsx(s.Fragment,{children:o("settings.usage.pace.prediction",{prediction:n.predictText})}),e[22]=n.isExhausted,e[23]=n.predictText,e[24]=n.remainingSeconds,e[25]=o,e[26]=S):S=e[26];let F;e[27]!==S||e[28]!==O||e[29]!==M?(F=s.jsx("span",{className:"typography-micro tabular-nums",style:O,title:M,children:S}),e[27]=S,e[28]=O,e[29]=M,e[30]=F):F=e[30];let E;return e[31]!==F||e[32]!==v||e[33]!==$?(E=s.jsxs("div",{className:v,children:[$,F]}),e[31]=F,e[32]=v,e[33]=$,e[34]=E):E=e[34],E}let w;e[35]!==a?(w=fe("flex items-center justify-between gap-2",a),e[35]=a,e[36]=w):w=e[36];let b;e[37]!==n.isExhausted||e[38]!==n.paceRateText||e[39]!==o?(b=!n.isExhausted&&s.jsx("span",{className:"typography-micro text-muted-foreground",children:o("settings.usage.pace.rate",{rate:n.paceRateText})}),e[37]=n.isExhausted,e[38]=n.paceRateText,e[39]=o,e[40]=b):b=e[40];let g;e[41]!==b?(g=s.jsx("div",{className:"flex items-center gap-1.5",children:b}),e[41]=b,e[42]=g):g=e[42];let x;e[43]!==c?(x={color:c},e[43]=c,e[44]=x):x=e[44];let k;e[45]!==n.isExhausted||e[46]!==n.predictText||e[47]!==n.remainingSeconds||e[48]!==m||e[49]!==u||e[50]!==o?(k=n.isExhausted?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium",children:u}),s.jsx("span",{className:"text-muted-foreground",children:o("settings.usage.pace.waitSeparator")}),s.jsx("span",{className:"font-medium",children:Pl(n.remainingSeconds)})]}):s.jsxs("span",{title:m,children:[s.jsx("span",{className:"text-muted-foreground",children:o("settings.usage.pace.predictionLabel")}),s.jsx("span",{className:"font-medium",children:n.predictText})]}),e[45]=n.isExhausted,e[46]=n.predictText,e[47]=n.remainingSeconds,e[48]=m,e[49]=u,e[50]=o,e[51]=k):k=e[51];let y;e[52]!==x||e[53]!==k?(y=s.jsx("span",{className:"typography-micro tabular-nums",style:x,children:k}),e[52]=x,e[53]=k,e[54]=y):y=e[54];let C;e[55]!==c?(C={backgroundColor:c},e[55]=c,e[56]=C):C=e[56];let z;e[57]!==u||e[58]!==C?(z=s.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:C,title:u}),e[57]=u,e[58]=C,e[59]=z):z=e[59];let j;e[60]!==y||e[61]!==z?(j=s.jsxs("div",{className:"flex items-center gap-1.5",children:[y,z]}),e[60]=y,e[61]=z,e[62]=j):j=e[62];let N;return e[63]!==j||e[64]!==w||e[65]!==g?(N=s.jsxs("div",{className:w,children:[g,j]}),e[63]=j,e[64]=w,e[65]=g,e[66]=N):N=e[66],N},ro=t=>{const e=tt.c(54),{title:n,window:a,subtitle:i,showToggle:r,toggleEnabled:o,onToggle:d}=t,c=r===void 0?!1:r,p=o===void 0?!1:o,u=qt(e1),f=qt(t1),m=ke(s1),w=u==="remaining"?a.remainingPercent:a.usedPercent,b=u==="remaining"?"remaining":"used";let g;e[0]!==w||e[1]!==a.valueLabel?(g=Tp(a.valueLabel,w),e[0]=w,e[1]=a.valueLabel,e[2]=g):g=e[2];const x=g,k=a.resetAfterFormatted??a.resetAtFormatted;let y;e[3]!==k||e[4]!==m||e[5]!==a.resetAt?(y=Ap(a.resetAt,k,m),e[3]=k,e[4]=m,e[5]=a.resetAt,e[6]=y):y=e[6];const C=y;let z;e[7]!==n?(z=Ep(n),e[7]=n,e[8]=z):z=e[8];const j=z;let N;e[9]!==n||e[10]!==a.resetAt||e[11]!==a.usedPercent||e[12]!==a.windowSeconds?(N=Dp(a.usedPercent,a.resetAt,a.windowSeconds,n),e[9]=n,e[10]=a.resetAt,e[11]=a.usedPercent,e[12]=a.windowSeconds,e[13]=N):N=e[13];const v=N;let P;e:{if(!v||v.dailyAllocationPercent===null){P=null;break e}const L=Rp(v.elapsedRatio);P=u==="remaining"?100-L:L}const $=P;let O;e[14]!==d||e[15]!==c||e[16]!==p?(O=c&&s.jsx(an,{checked:p,onChange:L=>d?.(L),ariaLabel:"Show in dropdown"}),e[14]=d,e[15]=c,e[16]=p,e[17]=O):O=e[17];let M;e[18]!==j?(M=s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j}),e[18]=j,e[19]=M):M=e[19];let S;e[20]!==i?(S=i&&s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:i}),e[20]=i,e[21]=S):S=e[21];let F;e[22]!==M||e[23]!==S?(F=s.jsxs("div",{className:"min-w-0 flex flex-col",children:[M,S]}),e[22]=M,e[23]=S,e[24]=F):F=e[24];let E;e[25]!==F||e[26]!==O?(E=s.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[O,F]}),e[25]=F,e[26]=O,e[27]=E):E=e[27];const D=x==="-"?"":x;let W;e[28]!==D?(W=s.jsx("div",{className:"typography-ui-label text-foreground tabular-nums flex items-center justify-end",children:D}),e[28]=D,e[29]=W):W=e[29];let H;e[30]!==E||e[31]!==W?(H=s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[E,W]}),e[30]=E,e[31]=W,e[32]=H):H=e[32];let Z;e[33]!==w||e[34]!==$||e[35]!==a.usedPercent?(Z=s.jsx(Xw,{percent:w,tonePercent:a.usedPercent,expectedMarkerPercent:$,className:"h-1.5"}),e[33]=w,e[34]=$,e[35]=a.usedPercent,e[36]=Z):Z=e[36];const Y=C?`Resets ${C}`:"";let A;e[37]!==Y?(A=s.jsx("span",{className:"typography-micro text-muted-foreground",children:Y}),e[37]=Y,e[38]=A):A=e[38];let X;e[39]!==b?(X=s.jsx("span",{className:"typography-micro text-muted-foreground",children:b}),e[39]=b,e[40]=X):X=e[40];let te;e[41]!==A||e[42]!==X?(te=s.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[A,X]}),e[41]=A,e[42]=X,e[43]=te):te=e[43];let T;e[44]!==Z||e[45]!==te?(T=s.jsxs("div",{className:"mt-2.5",children:[Z,te]}),e[44]=Z,e[45]=te,e[46]=T):T=e[46];let I;e[47]!==v||e[48]!==f?(I=v&&f&&s.jsx("div",{className:"mt-1.5",children:s.jsx(Zw,{paceInfo:v})}),e[47]=v,e[48]=f,e[49]=I):I=e[49];let B;return e[50]!==H||e[51]!==T||e[52]!==I?(B=s.jsxs("div",{className:"py-3",children:[H,T,I]}),e[50]=H,e[51]=T,e[52]=I,e[53]=B):B=e[53],B};function e1(t){return t.displayMode}function t1(t){return t.showPredValues}function s1(t){return t.timeFormatPreference}const n1=({providerId:t,providerName:e})=>{const{t:n}=lt(),[a,i]=l.useState(null),[r,o]=l.useState({}),[d,c]=l.useState(!1),p=`/api/quota/credentials/${t}`;l.useEffect(()=>{ht(p).then(async m=>{if(!m.ok)throw new Error;const w=await m.json();i(w),o(w.workspaceId?{workspaceId:w.workspaceId}:{})}).catch(()=>i({configured:!1}))},[p]);const u=async(m,w,b)=>{c(!0);try{const g=await ht(m,{method:w,headers:b?{"Content-Type":"application/json"}:void 0,body:b?JSON.stringify(b):void 0}),x=await g.json().catch(()=>null);if(!g.ok)throw new Error(x?.error);x?.configured!==void 0&&i(x),o(k=>k.workspaceId?{workspaceId:k.workspaceId}:{}),J.success(n("settings.providers.page.quotaCredentials.saved",{provider:e}))}catch(g){J.error(g instanceof Error&&g.message?g.message:n("settings.providers.page.openCodeGo.saveFailed"))}finally{c(!1)}},f=(m,w,b)=>s.jsxs("label",{className:"block typography-ui-label text-foreground",children:[w,s.jsx(at,{className:"mt-1 h-7 font-mono text-xs",type:m==="workspaceId"?"text":"password",autoComplete:"off",value:r[m]??"",onChange:g=>o(x=>({...x,[m]:g.target.value})),placeholder:a?.secretMasked??b})]});return s.jsxs("div",{"data-settings-item":`usage.${t}-credentials`,className:"mb-8",children:[s.jsx("div",{className:"mb-1 px-1",children:s.jsx("h3",{className:"typography-ui-header font-medium text-foreground",children:e})}),s.jsxs("section",{className:"space-y-3 px-2 pb-2 pt-0",children:[t==="opencode-go"&&f("workspaceId",n("settings.providers.page.openCodeGo.workspaceId"),"wrk_..."),t==="opencode-go"&&f("authCookie",n("settings.providers.page.openCodeGo.authCookie"),"auth=..."),t==="ollama-cloud"&&f("cookie",n("settings.providers.page.openCodeGo.authCookie"),"session=..."),t==="cursor"&&f("accessToken",n("settings.providers.page.quotaCredentials.accessToken"),n("settings.providers.page.quotaCredentials.tokenPlaceholder")),t==="cursor"&&f("refreshToken",n("settings.providers.page.quotaCredentials.refreshToken"),n("settings.providers.page.quotaCredentials.tokenPlaceholder")),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ee,{size:"xs",disabled:d,onClick:()=>u(p,"PUT",r),children:a?.configured?n("settings.providers.page.openCodeGo.replace"):n("settings.providers.page.openCodeGo.save")}),a?.configured&&s.jsx(ee,{variant:"outline",size:"xs",disabled:d,onClick:()=>u(`${p}/validate`,"POST"),children:n("settings.providers.page.openCodeGo.validate")}),t==="cursor"&&s.jsx(ee,{variant:"outline",size:"xs",disabled:d,onClick:()=>u(`${p}/import`,"POST"),children:n("settings.providers.page.actions.connect")}),a?.configured&&s.jsx(ee,{variant:"destructive",size:"xs",disabled:d,onClick:()=>u(p,"DELETE"),children:n("settings.providers.page.openCodeGo.delete")})]})]})]})},a1=(t,e)=>{if(!t)return"-";try{return ru(t,e,{fallback:"-"})}catch{return"-"}},i1=()=>{const{t}=lt(),e=ke(E=>E.timeFormatPreference),n=qt(E=>E.results),a=qt(E=>E.selectedProviderId),i=qt(E=>E.setSelectedProvider),r=qt(E=>E.loadSettings),o=qt(E=>E.fetchAllQuotas),d=qt(E=>E.isLoading),c=qt(E=>E.lastUpdated),p=qt(E=>E.error),u=qt(E=>E.dropdownProviderIds),f=qt(E=>E.setDropdownProviderIds),m=qt(E=>E.selectedModels),w=qt(E=>E.toggleModelSelected),b=qt(E=>E.applyDefaultSelections);Ew(),l.useEffect(()=>{r(),o()},[r,o]),l.useEffect(()=>{if(a||n.length===0)return;const E=n.find(D=>D.configured)?.providerId;i(E??Jn[0]?.id??null)},[n,a,i]);const g=n.find(E=>E.providerId===a)??null,k=Jn.find(E=>E.id===a)?.name??a??t("settings.usage.sidebar.title"),y=g?.usage,C=a?u.includes(a):!1,z=a==="opencode-go"||a==="ollama-cloud"||a==="cursor",j=l.useCallback(E=>{if(!a)return;const D=E?Array.from(new Set([...u,a])):u.filter(W=>W!==a);f(D),It({usageDropdownProviders:D})},[u,a,f]),N=l.useMemo(()=>y?.models?Object.entries(y.models).map(([E,D])=>({name:E,windows:D})).filter(E=>Object.keys(E.windows.windows).length>0):[],[y?.models]);l.useEffect(()=>{a&&N.length>0&&b(a,N.map(E=>E.name))},[a,N,b]);const v=l.useMemo(()=>!a||N.length===0?new Map:Pw(N,E=>E.name,a),[N,a]),P=l.useMemo(()=>{if(!a)return[];const E=Cw(a);return Iw(E)},[a]),[$,O]=l.useState(()=>({})),M=l.useCallback(E=>{O(D=>({...D,[E]:!D[E]}))},[]),S=l.useCallback(E=>{if(!a)return;w(a,E);const D=m[a]??[],H=D.includes(E)?D.filter(Y=>Y!==E):[...D,E],Z={...m,[a]:H};It({usageSelectedModels:Z})},[a,m,w]),F=a?m[a]??[]:[];return a?s.jsxs(ps,{title:t("settings.usage.page.header.providerUsage",{provider:k}),titleLeading:s.jsx(ia,{providerId:a,className:"h-5 w-5 shrink-0"}),description:d?s.jsx("span",{className:"animate-pulse typography-settings-description text-muted-foreground",children:t("settings.usage.page.header.refreshing")}):t("settings.usage.page.header.lastUpdated",{time:a1(c,e)}),showSaveStatus:!0,children:[s.jsx(dt,{divider:!1,settingsItem:"usage.header-menu",children:s.jsx(Ct,{checked:C,onChange:j,label:t("settings.usage.page.options.showInHeader"),ariaLabel:t("settings.usage.page.options.showInHeaderAria"),info:t("settings.usage.page.options.showInHeaderTooltip")})}),!g&&s.jsx("p",{className:"typography-ui-label text-foreground pb-8",children:t("settings.usage.page.state.noData")}),p&&s.jsxs("div",{className:"mb-8 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-4 py-3",children:[s.jsx("p",{className:"typography-ui-label font-medium text-[var(--status-error)]",children:t("settings.usage.page.state.refreshFailedTitle")}),s.jsx("p",{className:"typography-meta text-[var(--status-error)]/80 mt-1",children:p})]}),g&&!g.configured&&!z&&s.jsxs("div",{className:"mb-8 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] px-4 py-3",children:[s.jsx("p",{className:"typography-ui-label font-medium text-[var(--status-warning)]",children:t("settings.usage.page.state.providerNotConfiguredTitle")}),s.jsx("p",{className:"typography-meta text-[var(--status-warning)]/80 mt-1",children:t("settings.usage.page.state.providerNotConfiguredDescription")})]}),(a==="opencode-go"||a==="ollama-cloud"||a==="cursor")&&s.jsx(n1,{providerId:a,providerName:k}),y?.windows&&Object.keys(y.windows).length>0&&s.jsx(dt,{settingsItem:"usage.model-quotas",children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:Object.entries(y.windows).map(([E,D])=>s.jsx(ro,{title:E,window:D},E))})}),N.length>0&&s.jsxs(dt,{title:t("settings.usage.page.section.modelQuotas"),contentClassName:"space-y-3",children:[P.map(E=>{const D=v.get(E.id)??[];if(D.length===0)return null;const W=$[E.id]??!1;return s.jsx("section",{className:"p-2",children:s.jsxs(ca,{open:!W,onOpenChange:()=>M(E.id),children:[s.jsxs(da,{className:"flex w-full items-center justify-between py-0.5 group",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-left",children:[s.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:E.label}),s.jsxs("span",{className:"typography-micro text-muted-foreground",children:["(",D.length,")"]})]}),W?s.jsx(K,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"}):s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]}),s.jsx(ua,{children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)] mt-1",children:D.map(H=>{const Z=Object.entries(H.windows.windows);if(Z.length===0)return null;const[Y,A]=Z[0],X=F.includes(H.name);return s.jsx(ro,{title:Y,subtitle:od(H.name),window:A,showToggle:!0,toggleEnabled:X,onToggle:()=>S(H.name)},H.name)})})})]})},E.id)}),(()=>{const E=v.get(null)??[];if(E.length===0)return null;const D=$.other??!1;return s.jsx("section",{className:"p-2",children:s.jsxs(ca,{open:!D,onOpenChange:()=>M("other"),children:[s.jsxs(da,{className:"flex w-full items-center justify-between py-0.5 group",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-left",children:[s.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:t("settings.usage.page.section.otherModels")}),s.jsxs("span",{className:"typography-micro text-muted-foreground",children:["(",E.length,")"]})]}),D?s.jsx(K,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"}):s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]}),s.jsx(ua,{children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)] mt-1",children:E.map(W=>{const H=Object.entries(W.windows.windows);if(H.length===0)return null;const[Z,Y]=H[0],A=F.includes(W.name);return s.jsx(ro,{title:Z,subtitle:od(W.name),window:Y,showToggle:!0,toggleEnabled:A,onToggle:()=>S(W.name)},W.name)})})})]})})})()]}),g?.configured&&y&&Object.keys(y.windows??{}).length===0&&N.length===0&&s.jsxs("div",{className:"pb-8",children:[s.jsx("p",{className:"typography-ui-label text-foreground",children:t("settings.usage.page.state.noQuotaWindowsTitle")}),s.jsx("p",{className:"typography-meta text-muted-foreground mt-1",children:t("settings.usage.page.state.noQuotaWindowsDescription")})]})]}):s.jsx("div",{className:"flex h-full items-center justify-center text-muted-foreground",children:s.jsx("p",{className:"typography-body",children:t("settings.usage.page.empty.selectProvider")})})},r1="git.commit.generate",Zo=gn(t=>({selectedPromptId:r1,setSelectedPromptId:e=>{t(n=>n.selectedPromptId===e?n:{selectedPromptId:e})}})),o1=t=>{const e=tt.c(23),{onItemSelect:n}=t,{t:a}=lt(),i=Zo(l1),r=Zo(c1);let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={groupKey:"settings.magicPrompts.sidebar.group.git",items:[{id:"git.commit.generate",titleKey:"settings.magicPrompts.sidebar.item.gitCommitGenerate"},{id:"git.pr.generate",titleKey:"settings.magicPrompts.sidebar.item.gitPrGenerate"},{id:"git.conflict.resolve",titleKey:"settings.magicPrompts.sidebar.item.gitConflictResolve"},{id:"git.integrate.cherrypick.resolve",titleKey:"settings.magicPrompts.sidebar.item.gitCherrypickConflictResolve"}]},e[0]=o):o=e[0];let d;e[1]===Symbol.for("react.memo_cache_sentinel")?(d={groupKey:"settings.magicPrompts.sidebar.group.github",items:[{id:"github.pr.review",titleKey:"settings.magicPrompts.sidebar.item.githubPrReview"},{id:"github.issue.review",titleKey:"settings.magicPrompts.sidebar.item.githubIssueReview"},{id:"github.pr.checks.review",titleKey:"settings.magicPrompts.sidebar.item.githubPrFailedChecksReview"},{id:"github.pr.comments.review",titleKey:"settings.magicPrompts.sidebar.item.githubPrCommentsReview"},{id:"github.pr.comment.single",titleKey:"settings.magicPrompts.sidebar.item.githubSinglePrCommentReview"}]},e[1]=d):d=e[1];let c;e[2]===Symbol.for("react.memo_cache_sentinel")?(c={groupKey:"settings.magicPrompts.sidebar.group.planning",items:[{id:"plan.todo",titleKey:"settings.magicPrompts.sidebar.item.planTodo"},{id:"plan.improve",titleKey:"settings.magicPrompts.sidebar.item.planImprove"},{id:"plan.implement",titleKey:"settings.magicPrompts.sidebar.item.planImplement"}]},e[2]=c):c=e[2];let p;e[3]===Symbol.for("react.memo_cache_sentinel")?(p=[o,d,c,{groupKey:"settings.magicPrompts.sidebar.group.session",items:[{id:"session.explore",titleKey:"settings.magicPrompts.sidebar.item.sessionExplore"},{id:"session.summary",titleKey:"settings.magicPrompts.sidebar.item.sessionSummary"},{id:"session.review",titleKey:"settings.magicPrompts.sidebar.item.sessionWorkspaceReview"},{id:"session.plan",titleKey:"settings.magicPrompts.sidebar.item.sessionFeaturePlan"},{id:"session.craftGoal",titleKey:"settings.magicPrompts.sidebar.item.sessionCraftGoal"},{id:"session.catchup",titleKey:"settings.magicPrompts.sidebar.item.sessionCatchUp"},{id:"session.debug",titleKey:"settings.magicPrompts.sidebar.item.sessionDebug"},{id:"session.weigh",titleKey:"settings.magicPrompts.sidebar.item.sessionWeigh"},{id:"session.fusion",titleKey:"settings.magicPrompts.sidebar.item.sessionFusion"}]}],e[3]=p):p=e[3];const u=p;let f;e[4]!==a?(f=a("settings.magicPrompts.sidebar.title"),e[4]=a,e[5]=f):f=e[5];let m;e[6]!==f?(m=s.jsx("h2",{className:fn,children:f}),e[6]=f,e[7]=m):m=e[7];let w;e[8]!==a?(w=a("settings.magicPrompts.sidebar.description"),e[8]=a,e[9]=w):w=e[9];let b;e[10]!==w?(b=s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:w}),e[10]=w,e[11]=b):b=e[11];let g;e[12]!==m||e[13]!==b?(g=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[m,b]}),e[12]=m,e[13]=b,e[14]=g):g=e[14];let x;e[15]!==n||e[16]!==i||e[17]!==r||e[18]!==a?(x=s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-3 px-3 py-2 overflow-x-hidden",children:u.map(y=>s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro px-1 text-muted-foreground",children:a(y.groupKey)}),y.items.map(C=>{const z=i===C.id;return s.jsx("button",{type:"button",onClick:()=>{r(C.id),n?.()},className:fe("flex w-full items-center rounded-md px-2 py-1.5 text-left transition-colors",z?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-ui-label truncate font-normal",children:a(C.titleKey)})},C.id)})]},y.groupKey))}),e[15]=n,e[16]=i,e[17]=r,e[18]=a,e[19]=x):x=e[19];let k;return e[20]!==x||e[21]!==g?(k=s.jsxs("div",{className:"flex h-full flex-col bg-background",children:[g,x]}),e[20]=x,e[21]=g,e[22]=k):k=e[22],k};function l1(t){return t.selectedPromptId}function c1(t){return t.setSelectedPromptId}const cd={"git.commit.generate":{titleKey:"settings.magicPrompts.page.group.gitCommitGenerate.title",descriptionKey:"settings.magicPrompts.page.group.gitCommitGenerate.description",blocks:[{id:"git.commit.generate.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"git.commit.generate.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"git.pr.generate":{titleKey:"settings.magicPrompts.page.group.gitPrGenerate.title",descriptionKey:"settings.magicPrompts.page.group.gitPrGenerate.description",blocks:[{id:"git.pr.generate.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"git.pr.generate.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"github.pr.review":{titleKey:"settings.magicPrompts.page.group.githubPrReview.title",descriptionKey:"settings.magicPrompts.page.group.githubPrReview.description",blocks:[{id:"github.pr.review.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"github.pr.review.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"github.issue.review":{titleKey:"settings.magicPrompts.page.group.githubIssueReview.title",descriptionKey:"settings.magicPrompts.page.group.githubIssueReview.description",blocks:[{id:"github.issue.review.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"github.issue.review.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"github.pr.checks.review":{titleKey:"settings.magicPrompts.page.group.githubPrFailedChecksReview.title",descriptionKey:"settings.magicPrompts.page.group.githubPrFailedChecksReview.description",blocks:[{id:"github.pr.checks.review.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"github.pr.checks.review.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"github.pr.comments.review":{titleKey:"settings.magicPrompts.page.group.githubPrCommentsReview.title",descriptionKey:"settings.magicPrompts.page.group.githubPrCommentsReview.description",blocks:[{id:"github.pr.comments.review.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"github.pr.comments.review.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"github.pr.comment.single":{titleKey:"settings.magicPrompts.page.group.githubSinglePrCommentReview.title",descriptionKey:"settings.magicPrompts.page.group.githubSinglePrCommentReview.description",blocks:[{id:"github.pr.comment.single.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"github.pr.comment.single.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"git.conflict.resolve":{titleKey:"settings.magicPrompts.page.group.gitConflictResolve.title",descriptionKey:"settings.magicPrompts.page.group.gitConflictResolve.description",blocks:[{id:"git.conflict.resolve.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"git.conflict.resolve.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"git.integrate.cherrypick.resolve":{titleKey:"settings.magicPrompts.page.group.gitCherrypickConflictResolve.title",descriptionKey:"settings.magicPrompts.page.group.gitCherrypickConflictResolve.description",blocks:[{id:"git.integrate.cherrypick.resolve.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"git.integrate.cherrypick.resolve.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"plan.improve":{titleKey:"settings.magicPrompts.page.group.planImprove.title",descriptionKey:"settings.magicPrompts.page.group.planImprove.description",blocks:[{id:"plan.improve.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"plan.improve.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"plan.todo":{titleKey:"settings.magicPrompts.page.group.planTodo.title",descriptionKey:"settings.magicPrompts.page.group.planTodo.description",blocks:[{id:"plan.todo.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"plan.todo.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"plan.implement":{titleKey:"settings.magicPrompts.page.group.planImplement.title",descriptionKey:"settings.magicPrompts.page.group.planImplement.description",blocks:[{id:"plan.implement.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"plan.implement.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.summary":{titleKey:"settings.magicPrompts.page.group.sessionSummary.title",descriptionKey:"settings.magicPrompts.page.group.sessionSummary.description",blocks:[{id:"session.summary.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.summary.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.review":{titleKey:"settings.magicPrompts.page.group.sessionWorkspaceReview.title",descriptionKey:"settings.magicPrompts.page.group.sessionWorkspaceReview.description",blocks:[{id:"session.review.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.review.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.plan":{titleKey:"settings.magicPrompts.page.group.sessionFeaturePlan.title",descriptionKey:"settings.magicPrompts.page.group.sessionFeaturePlan.description",blocks:[{id:"session.plan.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.plan.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.craftGoal":{titleKey:"settings.magicPrompts.page.group.sessionCraftGoal.title",descriptionKey:"settings.magicPrompts.page.group.sessionCraftGoal.description",blocks:[{id:"session.craftGoal.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.craftGoal.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.catchup":{titleKey:"settings.magicPrompts.page.group.sessionCatchUp.title",descriptionKey:"settings.magicPrompts.page.group.sessionCatchUp.description",blocks:[{id:"session.catchup.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.catchup.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.debug":{titleKey:"settings.magicPrompts.page.group.sessionDebug.title",descriptionKey:"settings.magicPrompts.page.group.sessionDebug.description",blocks:[{id:"session.debug.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.debug.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.weigh":{titleKey:"settings.magicPrompts.page.group.sessionWeigh.title",descriptionKey:"settings.magicPrompts.page.group.sessionWeigh.description",blocks:[{id:"session.weigh.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.weigh.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.explore":{titleKey:"settings.magicPrompts.page.group.sessionExplore.title",descriptionKey:"settings.magicPrompts.page.group.sessionExplore.description",blocks:[{id:"session.explore.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.explore.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]},"session.fusion":{titleKey:"settings.magicPrompts.page.group.sessionFusion.title",descriptionKey:"settings.magicPrompts.page.group.sessionFusion.description",blocks:[{id:"session.fusion.visible",titleKey:"settings.magicPrompts.page.block.visiblePrompt"},{id:"session.fusion.instructions",titleKey:"settings.magicPrompts.page.block.instructions"}]}},dd=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),oo=t=>t.endsWith(".visible"),d1=()=>{const{t}=lt(),e=l.useCallback(N=>t(N),[t]),n=Zo(N=>N.selectedPromptId),[a,i]=l.useState(!0),[r,o]=l.useState({}),[d,c]=l.useState({}),[p,u]=l.useState({}),[f,m]=l.useState({}),[w,b]=l.useState(!1);l.useEffect(()=>{let N=!0;return(async()=>{i(!0);try{const P=await Op();if(!N)return;o(P)}catch(P){console.warn("Failed to load magic prompts:",P),J.error(t("settings.magicPrompts.page.toast.loadFailed"))}finally{N&&i(!1)}})(),()=>{N=!1}},[t]);const g=cd[n]??cd["git.commit.generate"],x=l.useCallback(N=>dd(r,N)?r[N]:$r(N),[r]),k=l.useCallback(N=>d[N]??x(N),[d,x]),y=l.useCallback((N,v)=>{c(P=>P[N]===v?P:{...P,[N]:v})},[]),C=l.useCallback(async N=>{const v=k(N);if(oo(N)&&v.trim().length===0){J.error(t("settings.magicPrompts.page.toast.visiblePromptRequired"));return}u(P=>({...P,[N]:!0}));try{const P=v===$r(N)?await Tl(N):await Mp(N,v);o(P.overrides),J.success(t("settings.magicPrompts.page.toast.saved"))}catch(P){const $=P instanceof Error?P.message:String(P);J.error(t("settings.magicPrompts.page.toast.saveFailed"),{description:$})}finally{u(P=>({...P,[N]:!1}))}},[k,t]),z=l.useCallback(async N=>{m(v=>({...v,[N]:!0}));try{const v=await Tl(N);o(v.overrides),c(P=>({...P,[N]:$r(N)})),J.success(t("settings.magicPrompts.page.toast.resetSuccess"))}catch(v){const P=v instanceof Error?v.message:String(v);J.error(t("settings.magicPrompts.page.toast.resetFailed"),{description:P})}finally{m(v=>({...v,[N]:!1}))}},[t]),j=l.useCallback(async()=>{b(!0);try{const N=await Lp();o(N.overrides),c({}),J.success(t("settings.magicPrompts.page.toast.resetAllSuccess"))}catch(N){const v=N instanceof Error?N.message:String(N);J.error(t("settings.magicPrompts.page.toast.resetAllFailed"),{description:v})}finally{b(!1)}},[t]);return a?s.jsxs("div",{className:"py-6 px-6 flex items-center gap-2 text-muted-foreground",children:[s.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-current animate-busy-pulse","aria-label":t("settings.magicPrompts.page.loading.aria")}),s.jsx("span",{className:"typography-ui",children:t("settings.magicPrompts.page.loading.text")})]}):s.jsx(ps,{title:e(g.titleKey),titleAccessory:s.jsx($t,{contentClassName:"max-w-xs",children:e(g.descriptionKey)}),headerEnd:s.jsx(ee,{"data-settings-item":"magic-prompts.reset-overrides",variant:"outline",size:"sm",onClick:()=>{j()},disabled:w||Object.keys(r).length===0,children:t(w?"settings.magicPrompts.page.actions.resetting":"settings.magicPrompts.page.actions.resetAllOverrides")}),showSaveStatus:!1,children:g.blocks.map((N,v)=>{const P=Fp(N.id),$=x(N.id),O=k(N.id),M=dd(r,N.id),S=O!==$,F=oo(N.id)&&O.trim().length===0,E=p[N.id]===!0,D=f[N.id]===!0;return s.jsxs(dt,{title:e(N.titleKey),info:P.description,description:P.placeholders&&P.placeholders.length>0?`${t("settings.magicPrompts.page.placeholdersLabel")} ${P.placeholders.map(W=>`{{${W.key}}}`).join(", ")}`:void 0,divider:v>0,settingsItem:oo(N.id)?"magic-prompts.visible-prompt":"magic-prompts.instructions",contentClassName:"space-y-3",children:[s.jsx(Ns,{value:O,onChange:W=>y(N.id,W.target.value),className:"min-h-[220px] font-mono text-sm"}),F&&s.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:t("settings.magicPrompts.page.validation.visiblePromptRequired")}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"typography-micro text-muted-foreground",children:t(S?"settings.magicPrompts.page.status.unsavedChanges":M?"settings.magicPrompts.page.status.usingSavedOverride":"settings.magicPrompts.page.status.usingBuiltinDefault")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{variant:"outline",size:"sm",onClick:()=>{z(N.id)},disabled:!M||E||D,children:t(D?"settings.magicPrompts.page.actions.resetting":"settings.magicPrompts.page.actions.resetToDefault")}),s.jsx(ee,{size:"sm",onClick:()=>{C(N.id)},disabled:!S||E||D||F,children:t(E?"settings.common.actions.saving":"settings.magicPrompts.page.actions.save")})]})]})]},N.id)})})},u1=t=>{const e=tt.c(89),{onItemSelect:n}=t,{t:a}=lt(),[i,r]=l.useState(null),[o,d]=l.useState(null),[c,p]=l.useState(null),{selectedSnippetName:u,snippets:f,setSelectedSnippet:m,setSnippetDraft:w,deleteSnippet:b,loadSnippets:g}=Cr(Hs(m1));let x,k;e[0]!==g?(x=()=>{g()},k=[g],e[0]=g,e[1]=x,e[2]=k):(x=e[1],k=e[2]),l.useEffect(x,k);let y;e[3]!==n||e[4]!==m||e[5]!==w||e[6]!==f?(y=async()=>{const oe=new Set(f.map(p1));let ce="new-snippet",pe=1;for(;oe.has(ce);)ce=`new-snippet-${pe++}`;w({name:ce,scope:"global"}),m(ce),n?.()},e[3]=n,e[4]=m,e[5]=w,e[6]=f,e[7]=y):y=e[7];const C=y;let z;e[8]!==i||e[9]!==b||e[10]!==a?(z=async()=>{if(!i)return;await b(i.name)?(J.success(a("settings.snippets.sidebar.toast.deleted")),r(null)):J.error(a("settings.snippets.sidebar.toast.deleteFailed"))},e[8]=i,e[9]=b,e[10]=a,e[11]=z):z=e[11];const j=z;let N;e[12]!==f?(N=[...f].sort(g1),e[12]=f,e[13]=N):N=e[13];const v=N;let P;e[14]===Symbol.for("react.memo_cache_sentinel")?(P=fe("flex h-full flex-col","bg-background"),e[14]=P):P=e[14];let $;e[15]!==a?($=a("settings.snippets.sidebar.title"),e[15]=a,e[16]=$):$=e[16];let O;e[17]!==$?(O=s.jsx("h2",{className:`${fn} mb-3`,children:$}),e[17]=$,e[18]=O):O=e[18];let M;e[19]!==f.length||e[20]!==a?(M=a("settings.snippets.sidebar.total",{count:f.length}),e[19]=f.length,e[20]=a,e[21]=M):M=e[21];let S;e[22]!==M?(S=s.jsx("span",{className:"typography-meta text-muted-foreground",children:M}),e[22]=M,e[23]=S):S=e[23];let F;e[24]!==a?(F=a("settings.snippets.sidebar.actions.create"),e[24]=a,e[25]=F):F=e[25];let E;e[26]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[26]=E):E=e[26];let D;e[27]!==C||e[28]!==F?(D=s.jsx(ee,{size:"sm","data-settings-item":"snippets.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:C,"aria-label":F,children:E}),e[27]=C,e[28]=F,e[29]=D):D=e[29];let W;e[30]!==S||e[31]!==D?(W=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[S,D]}),e[30]=S,e[31]=D,e[32]=W):W=e[32];let H;e[33]!==W||e[34]!==O?(H=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[O,W]}),e[33]=W,e[34]=O,e[35]=H):H=e[35];let Z;if(e[36]!==n||e[37]!==o||e[38]!==c||e[39]!==u||e[40]!==m||e[41]!==v||e[42]!==a){let oe;e[44]!==n||e[45]!==o||e[46]!==c||e[47]!==u||e[48]!==m||e[49]!==a?(oe=ce=>s.jsxs(Wn,{open:c===ce.name,onOpenChange:pe=>p(pe?ce.name:null),children:[s.jsxs(Gn,{render:s.jsx("div",{className:fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",u===ce.name?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:pe=>{pe.preventDefault(),p(ce.name)}}),children:[s.jsxs("button",{onClick:()=>{m(ce.name),n?.()},className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["#",ce.name]}),s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:a(`snippets.source.${ce.source}`)})]}),s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:ce.description||ce.content.replace(/\s+/g," ").substring(0,80)})]}),s.jsxs(fs,{open:o===ce.name,onOpenChange:pe=>{pe&&p(null),d(pe?ce.name:null)},children:[s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"sm",variant:"ghost",className:"h-6 w-6 px-0 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100","aria-label":a("settings.snippets.sidebar.actions.more",{name:ce.name}),children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:s.jsxs(as,{onClick:pe=>{pe.stopPropagation(),r(ce)},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),a("settings.common.actions.delete")]})})]})]}),s.jsx(qn,{className:"w-fit min-w-20",children:s.jsxs(An,{onClick:pe=>{pe.stopPropagation(),r(ce)},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),a("settings.common.actions.delete")]})})]},`${ce.source}:${ce.filePath}`),e[44]=n,e[45]=o,e[46]=c,e[47]=u,e[48]=m,e[49]=a,e[50]=oe):oe=e[50],Z=v.map(oe),e[36]=n,e[37]=o,e[38]=c,e[39]=u,e[40]=m,e[41]=v,e[42]=a,e[43]=Z}else Z=e[43];let Y;e[51]!==Z?(Y=s.jsx(Os,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:Z}),e[51]=Z,e[52]=Y):Y=e[52];const A=i!==null;let X;e[53]===Symbol.for("react.memo_cache_sentinel")?(X=oe=>{oe||r(null)},e[53]=X):X=e[53];let te;e[54]!==a?(te=a("settings.snippets.sidebar.dialog.deleteTitle"),e[54]=a,e[55]=te):te=e[55];let T;e[56]!==te?(T=s.jsx(_t,{children:te}),e[56]=te,e[57]=T):T=e[57];const I=i?.name??"";let B;e[58]!==a||e[59]!==I?(B=a("settings.snippets.sidebar.dialog.deleteDescription",{name:I}),e[58]=a,e[59]=I,e[60]=B):B=e[60];let L;e[61]!==B?(L=s.jsx(Yt,{children:B}),e[61]=B,e[62]=L):L=e[62];let V;e[63]!==T||e[64]!==L?(V=s.jsxs(Ut,{children:[T,L]}),e[63]=T,e[64]=L,e[65]=V):V=e[65];let Q;e[66]===Symbol.for("react.memo_cache_sentinel")?(Q=()=>r(null),e[66]=Q):Q=e[66];let G;e[67]!==a?(G=a("settings.common.actions.cancel"),e[67]=a,e[68]=G):G=e[68];let ue;e[69]!==G?(ue=s.jsx(ee,{size:"sm",variant:"ghost",onClick:Q,children:G}),e[69]=G,e[70]=ue):ue=e[70];let ne;e[71]!==a?(ne=a("settings.common.actions.delete"),e[71]=a,e[72]=ne):ne=e[72];let xe;e[73]!==j||e[74]!==ne?(xe=s.jsx(ee,{size:"sm",onClick:j,children:ne}),e[73]=j,e[74]=ne,e[75]=xe):xe=e[75];let ve;e[76]!==ue||e[77]!==xe?(ve=s.jsxs(rs,{children:[ue,xe]}),e[76]=ue,e[77]=xe,e[78]=ve):ve=e[78];let me;e[79]!==V||e[80]!==ve?(me=s.jsxs(Bt,{className:"max-w-md",children:[V,ve]}),e[79]=V,e[80]=ve,e[81]=me):me=e[81];let ge;e[82]!==A||e[83]!==me?(ge=s.jsx(Kt,{open:A,onOpenChange:X,children:me}),e[82]=A,e[83]=me,e[84]=ge):ge=e[84];let Ie;return e[85]!==H||e[86]!==Y||e[87]!==ge?(Ie=s.jsxs("div",{className:P,children:[H,Y,ge]}),e[85]=H,e[86]=Y,e[87]=ge,e[88]=Ie):Ie=e[88],Ie};function m1(t){return{selectedSnippetName:t.selectedSnippetName,snippets:t.snippets,setSelectedSnippet:t.setSelectedSnippet,setSnippetDraft:t.setSnippetDraft,deleteSnippet:t.deleteSnippet,loadSnippets:t.loadSnippets}}function p1(t){return t.name}function g1(t,e){return t.name.localeCompare(e.name)}const f1=()=>{const{t}=lt(),{selectedSnippetName:e,snippets:n,snippetDraft:a,setSnippetDraft:i,updateSnippet:r,createSnippet:o}=Cr(Hs(P=>({selectedSnippetName:P.selectedSnippetName,snippets:P.snippets,snippetDraft:P.snippetDraft,setSnippetDraft:P.setSnippetDraft,updateSnippet:P.updateSnippet,createSnippet:P.createSnippet}))),d=l.useMemo(()=>e?n.find(P=>P.name===e||P.aliases.includes(e))??null:null,[e,n]),c=!!(a&&a.name===e&&!d),[p,u]=l.useState(""),[f,m]=l.useState("global"),[w,b]=l.useState(""),[g,x]=l.useState(""),[k,y]=l.useState(""),[C,z]=l.useState(!1),j=l.useRef(null);l.useEffect(()=>{if(c&&a){const P={draftName:a.name||"",draftScope:a.scope||"global",description:a.description||"",aliases:(a.aliases||[]).join(", "),content:a.content||""};u(P.draftName),m(P.draftScope),b(P.description),x(P.aliases),y(P.content),j.current=P}else if(d){const P={draftName:"",draftScope:"global",description:d.description??"",aliases:d.aliases.join(", "),content:d.content};b(P.description),x(P.aliases),y(P.content),j.current=P}},[d,c,e,a]);const N=l.useMemo(()=>{const P=j.current;return P?c&&p!==P.draftName||c&&f!==P.draftScope?!0:w!==P.description||g!==P.aliases||k!==P.content:!1},[g,k,w,p,f,c]),v=async()=>{const P=c?p.trim().replace(/\s+/g,"-"):e?.trim();if(!P){J.error(t("settings.snippets.page.toast.nameRequired"));return}if(!k.trim()){J.error(t("settings.snippets.page.toast.contentRequired"));return}const $=g.split(",").map(O=>O.trim()).filter(Boolean);z(!0);try{if(!(c?await o(P,k,{aliases:$,description:w,scope:f}):await r(P,{content:k,aliases:$,description:w}))){J.error(t("settings.snippets.page.toast.saveFailed"));return}J.success(t("settings.snippets.page.toast.saved")),c&&i(null)}finally{z(!1)}};return e?s.jsxs(ps,{title:c?t("settings.snippets.page.title.new"):`#${e}`,description:d?d.filePath:void 0,showSaveStatus:!1,children:[s.jsxs(dt,{divider:!1,contentClassName:"space-y-0",children:[c?s.jsxs(Xt,{label:"#",children:[s.jsx(at,{value:p,onChange:P=>u(P.target.value),placeholder:t("settings.snippets.page.field.namePlaceholder"),className:"h-7 w-44 px-2"}),s.jsxs(Lt,{value:f,onValueChange:P=>m(P),children:[s.jsx(Ft,{size:Jt,className:"w-fit min-w-[100px]",children:s.jsx(Wt,{})}),s.jsxs(Ot,{align:"end",children:[s.jsx(kt,{value:"global",children:t("settings.common.scope.global")}),s.jsx(kt,{value:"project",children:t("settings.common.scope.project")})]})]})]}):null,s.jsx(ns,{label:t("settings.common.field.description"),children:s.jsx(at,{value:w,onChange:P=>b(P.target.value),placeholder:t("settings.snippets.page.field.descriptionPlaceholder"),className:"h-7 w-full max-w-sm px-2"})}),s.jsx(ns,{label:t("settings.snippets.page.field.aliases"),children:s.jsx(at,{value:g,onChange:P=>x(P.target.value),placeholder:t("settings.snippets.page.field.aliasesPlaceholder"),className:"h-7 w-full max-w-sm px-2"})})]}),s.jsxs(dt,{settingsItem:"snippets.content",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:t("settings.snippets.page.field.content")}),s.jsx($t,{children:t("settings.snippets.page.hint")})]}),s.jsx(Ns,{value:k,onChange:P=>y(P.target.value),placeholder:t("settings.snippets.page.field.contentPlaceholder"),rows:12,className:"mt-1.5 w-full font-mono typography-meta min-h-[160px] max-h-[60vh] bg-transparent"}),s.jsx("div",{className:"pt-3",children:s.jsx(ee,{onClick:v,disabled:C||!N,size:"xs",className:"!font-normal",children:t(C?"settings.common.actions.saving":"settings.common.actions.saveChanges")})})]})]}):s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(K,{name:"file-text",className:"mx-auto mb-3 h-12 w-12 opacity-50"}),s.jsx("p",{className:"typography-body",children:t("settings.snippets.page.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:t("settings.snippets.page.empty.description")})]})})},Zu=()=>{const{t}=lt(),e=pt(f=>f.settingsGitmojiEnabled),n=pt(f=>f.setSettingsGitmojiEnabled),a=Og(),i=ke(f=>f.gitChangesViewMode),r=ke(f=>f.setGitChangesViewMode),[o,d]=l.useState(!0),c=l.useMemo(()=>[{id:"flat",label:t("settings.openchamber.git.option.flatList")},{id:"tree",label:t("settings.openchamber.git.option.treeView")}],[t]);l.useEffect(()=>{(async()=>{try{let m=null;if(!m){const w=nn()?.settings;if(w)try{const g=(await w.load())?.settings;g&&(m={gitmojiEnabled:typeof g.gitmojiEnabled=="boolean"?g.gitmojiEnabled:void 0,gitChangesViewMode:g.gitChangesViewMode==="flat"||g.gitChangesViewMode==="tree"?g.gitChangesViewMode:void 0})}catch{}}if(!m){const w=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});w.ok&&(m=await w.json())}m&&(typeof m.gitmojiEnabled=="boolean"&&n(m.gitmojiEnabled),(m.gitChangesViewMode==="flat"||m.gitChangesViewMode==="tree")&&r(m.gitChangesViewMode))}catch(m){console.warn("Failed to load git settings:",m)}finally{d(!1)}})()},[r,n]);const p=l.useCallback(async f=>{n(f);try{await It({gitmojiEnabled:f})}catch(m){console.warn("Failed to save gitmoji setting:",m)}},[n]),u=l.useCallback(f=>{f!==i&&(r(f),It({gitChangesViewMode:f}))},[i,r]);return o?null:s.jsx(dt,{title:t("settings.openchamber.git.title"),children:s.jsxs("div",{className:Ds,children:[s.jsx(Zs,{settingsItem:"git.changes-view",title:t("settings.openchamber.git.changesViewTitle"),children:s.jsx(Kn,{"aria-label":t("settings.openchamber.git.changesViewAria"),children:c.map(f=>s.jsx(zn,{selected:i===f.id,onSelect:()=>{u(f.id)},label:f.label,ariaLabel:t("settings.openchamber.git.optionAria",{option:f.label})},f.id))})}),s.jsx(Ct,{settingsItem:"git.gitmoji",checked:e,onChange:f=>{p(f)},label:t("settings.openchamber.git.enableGitmoji"),ariaLabel:t("settings.openchamber.git.enableGitmojiAria")}),s.jsx(Ct,{settingsItem:"git.gitignored-files",checked:a,onChange:zg,label:t("settings.openchamber.git.showGitignored"),ariaLabel:t("settings.openchamber.git.showGitignoredAria")})]})})},em=()=>{const{t}=lt(),{isMobile:e}=Vs(),n=nn()?.github,a=Sn(S=>S.status),i=Sn(S=>S.isLoading),r=Sn(S=>S.hasChecked),o=Sn(S=>S.refreshStatus),d=Sn(S=>S.setStatus),c=l.useCallback(async S=>{await Tn(S)},[]),[p,u]=l.useState(!1),[f,m]=l.useState(null),[w,b]=l.useState(null),g=l.useRef(null),x=l.useCallback(()=>{g.current!=null&&(window.clearInterval(g.current),g.current=null),b(null)},[]);l.useEffect(()=>((async()=>{try{r||await o(n)}catch(S){console.warn("Failed to load GitHub auth status:",S)}})(),()=>{x()}),[r,o,n,x]);const k=l.useCallback(async()=>{u(!0);try{const S=n?await n.authStart():await(async()=>{const E=await ht("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),D=await E.json().catch(()=>null);if(!E.ok||!D||!("deviceCode"in D))throw new Error(D?.error||E.statusText);return D})();m(S),b(Math.max(1,S.interval)*1e3);const F=S.verificationUriComplete||S.verificationUri;c(F)}catch(S){console.error("Failed to start GitHub connect:",S),J.error(t("settings.github.page.toast.startConnectFailed"))}finally{u(!1)}},[c,n,t]),y=l.useCallback(async S=>{if(n)return n.authComplete(S);const F=await ht("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:S})}),E=await F.json().catch(()=>null);if(!F.ok||!E)throw new Error(E?.error||F.statusText);return E},[n]);l.useEffect(()=>{if(!(!f?.deviceCode||!w)&&g.current==null)return g.current=window.setInterval(()=>{(async()=>{try{const S=await y(f.deviceCode);if(S.connected){J.success(t("settings.github.page.toast.connected")),m(null),x(),await o(n,{force:!0});return}S.status==="slow_down"&&b(F=>F?F+5e3:5e3),(S.status==="expired_token"||S.status==="access_denied")&&(J.error(S.error||t("settings.github.page.toast.authorizationFailed")),m(null),x())}catch(S){console.warn("GitHub polling failed:",S)}})()},w),()=>{g.current!=null&&(window.clearInterval(g.current),g.current=null)}},[f,w,y,o,n,x,t]);const C=l.useCallback(async S=>{u(!0);try{if(n)await n.authSetGhCliDisabled(S);else{const F=await ht("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:S})}),E=await F.json().catch(()=>null);if(!F.ok)throw new Error(E?.error||F.statusText)}J.success(t(S?"settings.github.page.toast.ghCliDisabled":"settings.github.page.toast.ghCliEnabled")),await o(n,{force:!0})}catch(F){console.error("Failed to update gh CLI setting:",F),J.error(t("settings.github.page.toast.ghCliUpdateFailed"))}finally{u(!1)}},[o,n,t]),z=l.useCallback(async()=>{u(!0);try{if(x(),m(null),n)await n.authDisconnect();else{const S=await ht("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!S.ok)throw new Error(S.statusText)}J.success(t("settings.github.page.toast.disconnected")),await o(n,{force:!0})}catch(S){console.error("Failed to disconnect GitHub:",S),J.error(t("settings.github.page.toast.disconnectFailed"))}finally{u(!1)}},[o,n,x,t]),j=l.useCallback(async S=>{if(S){u(!0);try{const F=n?await n.authActivate(S):await(async()=>{const E=await ht("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:S})}),D=await E.json().catch(()=>null);if(!E.ok||!D)throw new Error(D?.error||E.statusText);return D})();d(F),J.success(t("settings.github.page.toast.accountSwitched"))}catch(F){console.error("Failed to switch GitHub account:",F),J.error(t("settings.github.page.toast.accountSwitchFailed"))}finally{u(!1)}}},[n,d,t]);if(i)return null;const N=!!a?.connected,v=a?.user,$=(a?.accounts??[]).filter(S=>!S.current),O=a?.ghCli??null,M=O?.active?t("settings.github.page.accountSource.cli"):t("settings.github.page.accountSource.oauth");return s.jsxs(s.Fragment,{children:[s.jsxs(dt,{title:t("settings.github.page.oauth.title"),divider:!1,settingsItem:"git.github-account",info:t("settings.github.page.tooltip.connectAccount"),children:[s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",children:[N?s.jsxs("div",{className:fe("px-4 py-3",e?"flex flex-col gap-3":"flex items-center justify-between gap-4"),children:[s.jsxs("div",{className:fe("flex min-w-0 items-center gap-4",e?"w-full":void 0),children:[v?.avatarUrl?s.jsx("img",{src:v.avatarUrl,alt:v.login?t("settings.github.page.avatarAlt.withLogin",{login:v.login}):t("settings.github.page.avatarAlt.fallback"),className:"h-10 w-10 shrink-0 rounded-full border border-[var(--interactive-border)] bg-[var(--surface-muted)] object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"h-10 w-10 shrink-0 rounded-full border border-[var(--interactive-border)] bg-[var(--surface-muted)]"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:v?.name?.trim()||v?.login||"GitHub"}),s.jsxs("div",{className:fe("flex items-center gap-2 typography-meta text-muted-foreground mt-0.5",e?"flex-wrap":"truncate"),children:[s.jsx(K,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"font-mono",children:v?.login||t("settings.github.page.label.unknownUser")}),v?.email&&s.jsx("span",{className:"opacity-50",children:"•"}),v?.email&&s.jsx("span",{children:v.email}),s.jsx("span",{className:"opacity-50",children:"•"}),s.jsx("span",{children:M})]}),a?.scope&&s.jsx("div",{className:"typography-micro text-muted-foreground/70 mt-0.5",children:t("settings.github.page.label.scopes",{value:a.scope})}),O?.active&&s.jsx("div",{className:"typography-micro text-muted-foreground/70 mt-0.5",children:t("settings.github.page.ghCli.activeDescription")})]})]}),O?.active?s.jsx(ee,{size:"sm",variant:"outline",onClick:()=>C(!0),disabled:p,className:fe(e?"w-full":void 0),children:t("settings.github.page.ghCli.actions.disable")}):s.jsx(ee,{size:"sm",variant:"outline",onClick:z,disabled:p,className:fe("text-[var(--status-error)] hover:text-[var(--status-error)]",e?"w-full":void 0),children:t("settings.github.page.actions.disconnect")})]}):s.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-4",children:[s.jsx("div",{className:"flex min-w-0 flex-col",children:s.jsx("span",{className:"typography-ui-label text-foreground",children:t("settings.github.page.status.notConnected")})}),s.jsx(ee,{size:"sm",variant:"default",onClick:k,disabled:p,children:t("settings.github.page.actions.connect")})]}),$.length>0&&s.jsxs("div",{className:"mt-2 border-t border-[var(--surface-subtle)] pt-2 px-2 pb-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground mb-2 px-1",children:t("settings.github.page.label.otherAccounts")}),s.jsx("div",{className:"space-y-1",children:$.map(S=>{const F=S.user,E=S.source==="gh-cli"?t("settings.github.page.accountSource.cli"):t("settings.github.page.accountSource.oauth");return s.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-[var(--surface-subtle)] bg-[var(--surface-muted)] px-3 py-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[F?.avatarUrl?s.jsx("img",{src:F.avatarUrl,alt:F.login?t("settings.github.page.avatarAlt.withLogin",{login:F.login}):t("settings.github.page.avatarAlt.fallback"),className:"h-6 w-6 shrink-0 rounded-full border border-[var(--interactive-border)] bg-[var(--surface-muted)] object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-[var(--interactive-border)] bg-[var(--surface-muted)]",children:s.jsx(K,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),s.jsxs("div",{className:"min-w-0 flex flex-col",children:[s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:F?.name?.trim()||F?.login||"GitHub"}),F?.login&&s.jsxs("span",{className:"typography-micro text-muted-foreground truncate",children:[s.jsx("span",{className:"font-mono",children:F.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:E})]})]})]}),s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>j(S.id),disabled:p,children:t("settings.github.page.actions.switchTo")})]},S.id)})})]})]}),N&&s.jsx("div",{className:"mt-2 px-2 pb-2",children:s.jsx(ee,{size:"sm",variant:"outline",onClick:k,disabled:p,className:fe(e?"w-full":void 0),children:t("settings.github.page.actions.addAccount")})}),f&&s.jsxs("div",{className:"mt-4 rounded-lg bg-[var(--surface-elevated)]/70 p-4 border border-[var(--interactive-border)]",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(pn,{children:t("settings.github.page.flow.title")}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.github.page.flow.description")})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3 mt-4",children:[s.jsx("div",{className:"font-mono text-xl tracking-widest text-foreground bg-[var(--surface-muted)] px-3 py-1.5 rounded-md border border-[var(--interactive-border)]",children:f.userCode}),s.jsx(ee,{size:"sm",asChild:!0,children:s.jsx("a",{href:f.verificationUriComplete||f.verificationUri,target:"_blank",rel:"noopener noreferrer",children:t("settings.github.page.actions.openGithub")})})]}),s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsx("span",{className:"typography-micro text-muted-foreground animate-pulse",children:t("settings.github.page.flow.waiting")}),s.jsx(ee,{size:"sm",variant:"ghost",disabled:p,onClick:()=>{x(),m(null)},children:t("settings.common.actions.cancel")})]})]})]}),O?.available&&!O?.active&&(!O.user||O.disabled)&&s.jsx(dt,{title:t("settings.github.page.ghCli.title"),children:s.jsx("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden",children:s.jsxs("div",{className:fe("px-4 py-3",e?"flex flex-col gap-3":"flex items-center justify-between gap-4"),children:[s.jsxs("div",{className:fe("flex min-w-0 items-center gap-4",e?"w-full":void 0),children:[O.user?.avatarUrl?s.jsx("img",{src:O.user.avatarUrl,alt:O.user.login?t("settings.github.page.avatarAlt.withLogin",{login:O.user.login}):t("settings.github.page.avatarAlt.fallback"),className:"h-10 w-10 shrink-0 rounded-full border border-[var(--interactive-border)] bg-[var(--surface-muted)] object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):s.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-[var(--interactive-border)] bg-[var(--surface-muted)]",children:s.jsx(K,{name:"github-fill",className:"h-4 w-4 text-muted-foreground"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[!O.disabled&&O.user&&s.jsx("div",{className:"typography-ui-label text-foreground truncate",children:O.user.name?.trim()||O.user.login||"GitHub"}),!O.disabled&&O.user?.login&&s.jsxs("div",{className:fe("flex items-center gap-2 typography-meta text-muted-foreground mt-0.5",e?"flex-wrap":"truncate"),children:[s.jsx(K,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"font-mono",children:O.user.login}),O.user.email&&s.jsx("span",{className:"opacity-50",children:"•"}),O.user.email&&s.jsx("span",{children:O.user.email})]}),s.jsx("div",{className:fe("typography-meta text-muted-foreground",O.disabled?"opacity-60":void 0),children:O.disabled?t("settings.github.page.ghCli.disabledDescription"):t("settings.github.page.ghCli.fallbackDescription")})]})]}),s.jsx(ee,{size:"sm",variant:"outline",onClick:()=>C(!O.disabled),disabled:p,className:fe(e?"w-full":void 0),children:O.disabled?t("settings.github.page.ghCli.actions.enable"):t("settings.github.page.ghCli.actions.disable")})]})})})]})},ud=[{key:"keyword",label:"Green",cssVar:"var(--syntax-keyword)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"string",label:"Cyan",cssVar:"var(--syntax-string)"},{key:"function",label:"Orange",cssVar:"var(--syntax-function)"},{key:"type",label:"Yellow",cssVar:"var(--syntax-type)"}],h1=[{key:"branch",Icon:"git-branch",label:"Branch"},{key:"briefcase",Icon:"briefcase",label:"Work"},{key:"house",Icon:"home",label:"Personal"},{key:"graduation",Icon:"graduation-cap",label:"School"},{key:"code",Icon:"code",label:"Code"}],x1=({open:t,onOpenChange:e,profileId:n,importData:a})=>{const{t:i}=lt(),r=$s(L=>L.getProfileById),o=$s(L=>L.createProfile),d=$s(L=>L.updateProfile),c=$s(L=>L.deleteProfile),p=l.useMemo(()=>n&&n!=="new"&&!a?r(n):null,[n,r,a]),u=n==="new"||a!=null,f=n==="global",[m,w]=l.useState(""),[b,g]=l.useState(""),[x,k]=l.useState(""),[y,C]=l.useState("ssh"),[z,j]=l.useState(""),[N,v]=l.useState(!1),[P,$]=l.useState(""),[O,M]=l.useState(""),[S,F]=l.useState("keyword"),[E,D]=l.useState("branch"),[W,H]=l.useState(!1),[Z,Y]=l.useState(!1),[A,X]=l.useState(!1);l.useEffect(()=>{if(t){if(a){const L=a.host.split("/"),V=L.length>=3?L[L.length-1]:a.host;w(V),g(a.username),k(""),C("token"),j(""),v(!1),$(""),M(a.host),F("string"),D("code")}else if(u)w(""),g(""),k(""),C("ssh"),j(""),v(!1),$(""),M(""),F("keyword"),D("branch");else if(p)w(p.name),g(p.userName),k(p.userEmail),C(p.authType||"ssh"),j(p.sshKey||""),v(p.signCommits===!0),$(p.signingKey||""),M(p.host||""),F(p.color||"keyword"),D(p.icon||"branch");else if(f){const L=r("global");L&&(w(L.name),g(L.userName),k(L.userEmail),C(L.authType||"ssh"),j(L.sshKey||""),v(!1),$(""),M(L.host||""),F(L.color||"keyword"),D(L.icon||"branch"))}}},[t,n,p,u,a,f,r]);const te=async()=>{if(!b.trim()||!x.trim()){J.error(i("settings.gitIdentities.editor.toast.userNameEmailRequired"));return}if(y==="token"&&!O.trim()){J.error(i("settings.gitIdentities.editor.toast.hostRequiredForToken"));return}if(N&&!P.trim()){J.error(i("settings.gitIdentities.editor.toast.signingKeyRequired"));return}H(!0);try{const L={name:m.trim()||b.trim(),userName:b.trim(),userEmail:x.trim(),authType:y,sshKey:y==="ssh"&&z.trim()||null,signCommits:N,signingKey:P.trim()||null,host:y==="token"&&O.trim()||null,color:S,icon:E};let V;if(u)V=await o(L);else if(n)V=await d(n,L);else return;V?(J.success(i(u?"settings.gitIdentities.editor.toast.profileCreated":"settings.gitIdentities.editor.toast.profileUpdated")),e(!1)):J.error(i(u?"settings.gitIdentities.editor.toast.createProfileFailed":"settings.gitIdentities.editor.toast.updateProfileFailed"))}catch(L){console.error("Error saving profile:",L),J.error(i("settings.gitIdentities.editor.toast.saveUnexpectedError"))}finally{H(!1)}},T=async()=>{if(!(!n||u)){X(!0);try{await c(n)?(J.success(i("settings.gitIdentities.editor.toast.profileDeleted")),Y(!1),e(!1)):J.error(i("settings.gitIdentities.editor.toast.deleteProfileFailed"))}catch(L){console.error("Error deleting profile:",L),J.error(i("settings.gitIdentities.editor.toast.deleteUnexpectedError"))}finally{X(!1)}}},I=l.useMemo(()=>ud.find(V=>V.key===S)?.cssVar||"var(--syntax-keyword)",[S]),B=a?i("settings.gitIdentities.editor.title.importCredential"):u?i("settings.gitIdentities.editor.title.newIdentity"):f?i("settings.gitIdentities.editor.title.globalIdentity"):p?.name||i("settings.gitIdentities.editor.title.editIdentity");return s.jsxs(s.Fragment,{children:[s.jsx(Kt,{open:t,onOpenChange:e,children:s.jsxs(Bt,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:B}),s.jsx(Yt,{children:i(f?"settings.gitIdentities.editor.description.globalReadOnly":u?"settings.gitIdentities.editor.description.newProfile":"settings.gitIdentities.editor.description.editProfile")})]}),s.jsxs("div",{className:"space-y-5 py-2",children:[!f&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:`${zt} block mb-1.5`,children:i("settings.gitIdentities.editor.field.profileName")}),s.jsx(at,{value:m,onChange:L=>w(L.target.value),placeholder:i("settings.gitIdentities.editor.field.profileNamePlaceholder"),className:"h-8"})]}),s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:i("settings.gitIdentities.editor.field.color")}),s.jsx("div",{className:"flex gap-1.5",children:ud.map(L=>s.jsx("button",{type:"button",onClick:()=>F(L.key),className:fe("w-6 h-6 rounded-md border-2 transition-all cursor-pointer",S===L.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:L.cssVar},title:L.label},L.key))})]}),s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:i("settings.gitIdentities.editor.field.icon")}),s.jsx("div",{className:"flex gap-1.5",children:h1.map(L=>{const V=L.Icon;return s.jsx("button",{type:"button",onClick:()=>D(L.key),className:fe("w-7 h-7 rounded-md border-2 transition-all flex items-center justify-center cursor-pointer",E===L.key?"border-[var(--interactive-border)] bg-[var(--surface-muted)]":"border-transparent hover:border-[var(--interactive-border)] hover:bg-[var(--surface-muted)]/50"),title:L.label,children:s.jsx(K,{name:V,className:"w-3.5 h-3.5",style:{color:E===L.key?I:"var(--surface-muted-foreground)"}})},L.key)})})]})]}),!f&&s.jsx("div",{className:"border-t border-border/40"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:zt,children:i("settings.gitIdentities.editor.field.userName")}),!f&&s.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),s.jsx($t,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.userNameTooltip")})]}),s.jsx(at,{value:b,onChange:L=>g(L.target.value),placeholder:i("settings.gitIdentities.editor.field.userNamePlaceholder"),required:!f,readOnly:f,disabled:f,className:"h-8"})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:zt,children:i("settings.gitIdentities.editor.field.emailAddress")}),!f&&s.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),s.jsx($t,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.emailAddressTooltip")})]}),s.jsx(at,{type:"email",value:x,onChange:L=>k(L.target.value),placeholder:i("settings.gitIdentities.editor.field.emailAddressPlaceholder"),required:!f,readOnly:f,disabled:f,className:"h-8"})]})]}),!f&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"border-t border-border/40"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:i("settings.gitIdentities.editor.field.authMethod")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(ee,{size:"sm",type:"button",variant:"chip","aria-pressed":y==="ssh",onClick:()=>C("ssh"),children:[s.jsx(K,{name:"lock-2",className:"w-3.5 h-3.5 mr-1"})," SSH"]}),s.jsxs(ee,{size:"sm",type:"button",variant:"chip","aria-pressed":y==="token",onClick:()=>C("token"),children:[s.jsx(K,{name:"key",className:"w-3.5 h-3.5 mr-1"})," ",i("settings.gitIdentities.editor.field.authToken")]})]})]}),y==="ssh"&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:zt,children:i("settings.gitIdentities.editor.field.sshKeyPath")}),s.jsx($t,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.sshKeyPathTooltip")})]}),s.jsx(at,{value:z,onChange:L=>j(L.target.value),placeholder:i("settings.gitIdentities.editor.field.sshKeyPathPlaceholder"),className:"h-8 font-mono text-xs"})]}),s.jsxs("div",{className:"border-t border-border/40 pt-3 space-y-3",children:[s.jsx(Ct,{checked:N,onChange:v,label:i("settings.gitIdentities.editor.field.signCommits"),info:i("settings.gitIdentities.editor.section.commitSigning"),ariaLabel:i("settings.gitIdentities.editor.field.signCommits")}),s.jsxs("div",{children:[s.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:s.jsx("label",{className:zt,children:i("settings.gitIdentities.editor.field.signingKey")})}),s.jsx(at,{value:P,onChange:L=>$(L.target.value),placeholder:i("settings.gitIdentities.editor.field.signingKeyPlaceholder"),disabled:!N,className:"h-8 font-mono text-xs"})]})]}),y==="token"&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:zt,children:i("settings.gitIdentities.editor.field.host")}),s.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),s.jsx($t,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.hostTooltip")})]}),s.jsx(at,{value:O,onChange:L=>M(L.target.value),placeholder:i("settings.gitIdentities.editor.field.hostPlaceholder"),required:!0,className:"h-8 font-mono text-xs"})]})]})]})]}),s.jsxs(rs,{className:"gap-2",children:[!f&&!u&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>Y(!0),className:"text-[var(--status-error)] hover:text-[var(--status-error)] border-[var(--status-error)]/30 hover:bg-[var(--status-error)]/10 mr-auto",children:[s.jsx(K,{name:"delete-bin",className:"w-3.5 h-3.5 mr-1"})," ",i("settings.common.actions.delete")]}),s.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>e(!1),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:i(f?"settings.gitIdentities.editor.actions.close":"settings.common.actions.cancel")}),!f&&s.jsx(ee,{size:"sm",onClick:te,disabled:W,children:i(W?"settings.common.actions.saving":u?"settings.gitIdentities.editor.actions.create":"settings.gitIdentities.editor.actions.save")})]})]})}),s.jsx(Kt,{open:Z,onOpenChange:L=>{A||Y(L)},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:i("settings.gitIdentities.page.deleteDialog.title")}),s.jsx(Yt,{children:i("settings.gitIdentities.page.deleteDialog.description",{name:p?.name||m})})]}),s.jsxs(rs,{children:[s.jsx(ee,{variant:"ghost",onClick:()=>Y(!1),disabled:A,children:i("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",variant:"destructive",onClick:()=>{T()},disabled:A,children:i("settings.common.actions.delete")})]})]})})]})},b1={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart"},y1={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},v1=()=>{const t=tt.c(113),{t:e}=lt(),{profiles:n,globalIdentity:a,defaultGitIdentityId:i,deleteProfile:r,loadProfiles:o,loadGlobalIdentity:d,loadDiscoveredCredentials:c,loadDefaultGitIdentityId:p,setDefaultGitIdentityId:u,getUnimportedCredentials:f}=$s(Hs(j1)),[m,w]=l.useState(!1),[b,g]=l.useState(null),[x,k]=l.useState(null),[y,C]=l.useState(null),[z,j]=l.useState(!1);let N,v;t[0]!==p||t[1]!==c||t[2]!==d||t[3]!==o?(N=()=>{o(),d(),c(),p()},v=[o,d,c,p],t[0]=p,t[1]=c,t[2]=d,t[3]=o,t[4]=N,t[5]=v):(N=t[4],v=t[5]),l.useEffect(N,v);let P,$,O,M,S,F,E,D,W,H,Z,Y,A,X;if(t[6]!==i||t[7]!==y||t[8]!==r||t[9]!==f||t[10]!==a||t[11]!==n||t[12]!==u||t[13]!==e){const Le=f();let Be;t[28]===Symbol.for("react.memo_cache_sentinel")?(Be=(Ke,Oe)=>{g(Ke),k(Oe??null),w(!0)},t[28]=Be):Be=t[28];const Fe=Be;let De;t[29]!==i||t[30]!==u||t[31]!==e?(De=async Ke=>{const Oe=i===Ke?null:Ke;if(!await u(Oe)){J.error(e("settings.gitIdentities.page.toast.updateDefaultFailed"));return}J.success(e(Oe?"settings.gitIdentities.page.toast.defaultUpdated":"settings.gitIdentities.page.toast.defaultUnset"))},t[29]=i,t[30]=u,t[31]=e,t[32]=De):De=t[32];const ze=De;let Ve;t[33]!==y||t[34]!==r||t[35]!==e?(Ve=async()=>{if(!y)return;j(!0),await r(y.id)?(J.success(e("settings.gitIdentities.page.toast.profileDeleted",{name:y.name})),C(null)):J.error(e("settings.gitIdentities.page.toast.deleteProfileFailed")),j(!1)},t[33]=y,t[34]=r,t[35]=e,t[36]=Ve):Ve=t[36],O=Ve,$=ps,t[37]!==e?(M=e("settings.page.git.title"),t[37]=e,t[38]=M):M=t[38],S=!0,t[39]===Symbol.for("react.memo_cache_sentinel")?(F=s.jsx(em,{}),t[39]=F):F=t[39],P=dt,t[40]!==e?(Y=e("settings.gitIdentities.page.section.title"),t[40]=e,t[41]=Y):Y=t[41];let We,_e;t[42]===Symbol.for("react.memo_cache_sentinel")?(We=()=>Fe("new"),_e=s.jsx(K,{name:"add",className:"w-3.5 h-3.5 mr-1"}),t[42]=We,t[43]=_e):(We=t[42],_e=t[43]);let He;t[44]!==e?(He=e("settings.common.badge.new"),t[44]=e,t[45]=He):He=t[45],t[46]!==He?(A=s.jsxs(ee,{size:"sm",variant:"outline",onClick:We,children:[_e," ",He]}),t[46]=He,t[47]=A):A=t[47],X="git.identities",E="rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",D=a&&s.jsx(md,{profile:a,isDefault:i==="global",onEdit:()=>Fe("global"),onToggleDefault:()=>ze("global"),isReadOnly:!0,hasBorder:n.length>0||Le.length>0}),W=n.map((Ke,Oe)=>s.jsx(md,{profile:Ke,isDefault:i===Ke.id,onEdit:()=>Fe(Ke.id),onToggleDefault:()=>ze(Ke.id),onDelete:()=>C(Ke),hasBorder:Oe<n.length-1||Le.length>0},Ke.id)),H=!a&&n.length===0&&Le.length===0&&s.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground",children:[s.jsx(K,{name:"shield-keyhole",className:"mx-auto mb-2 h-8 w-8 opacity-40"}),s.jsx("p",{className:"typography-ui-label",children:e("settings.gitIdentities.page.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:e("settings.gitIdentities.page.empty.description")})]}),Z=Le.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-4 py-2 border-t border-[var(--surface-subtle)]",children:s.jsx("span",{className:"typography-micro text-muted-foreground",children:e("settings.gitIdentities.page.discoveredCredentials.title")})}),Le.map((Ke,Oe)=>s.jsx(w1,{credential:Ke,onImport:()=>Fe("new",{host:Ke.host,username:Ke.username}),hasBorder:Oe<Le.length-1},`${Ke.host}-${Ke.username}`))]}),t[6]=i,t[7]=y,t[8]=r,t[9]=f,t[10]=a,t[11]=n,t[12]=u,t[13]=e,t[14]=P,t[15]=$,t[16]=O,t[17]=M,t[18]=S,t[19]=F,t[20]=E,t[21]=D,t[22]=W,t[23]=H,t[24]=Z,t[25]=Y,t[26]=A,t[27]=X}else P=t[14],$=t[15],O=t[16],M=t[17],S=t[18],F=t[19],E=t[20],D=t[21],W=t[22],H=t[23],Z=t[24],Y=t[25],A=t[26],X=t[27];let te;t[48]!==E||t[49]!==D||t[50]!==W||t[51]!==H||t[52]!==Z?(te=s.jsxs("div",{className:E,children:[D,W,H,Z]}),t[48]=E,t[49]=D,t[50]=W,t[51]=H,t[52]=Z,t[53]=te):te=t[53];let T;t[54]!==P||t[55]!==te||t[56]!==Y||t[57]!==A||t[58]!==X?(T=s.jsx(P,{title:Y,headerAction:A,settingsItem:X,children:te}),t[54]=P,t[55]=te,t[56]=Y,t[57]=A,t[58]=X,t[59]=T):T=t[59];let I;t[60]===Symbol.for("react.memo_cache_sentinel")?(I=s.jsx(Zu,{}),t[60]=I):I=t[60];let B;t[61]!==$||t[62]!==M||t[63]!==S||t[64]!==F||t[65]!==T?(B=s.jsxs($,{title:M,showSaveStatus:S,children:[F,T,I]}),t[61]=$,t[62]=M,t[63]=S,t[64]=F,t[65]=T,t[66]=B):B=t[66];let L;t[67]!==x||t[68]!==m||t[69]!==b?(L=s.jsx(x1,{open:m,onOpenChange:w,profileId:b,importData:x}),t[67]=x,t[68]=m,t[69]=b,t[70]=L):L=t[70];const V=y!==null;let Q;t[71]!==z?(Q=Le=>{z||Le||C(null)},t[71]=z,t[72]=Q):Q=t[72];let G;t[73]!==e?(G=e("settings.gitIdentities.page.deleteDialog.title"),t[73]=e,t[74]=G):G=t[74];let ue;t[75]!==G?(ue=s.jsx(_t,{children:G}),t[75]=G,t[76]=ue):ue=t[76];const ne=y?.name??"";let xe;t[77]!==e||t[78]!==ne?(xe=e("settings.gitIdentities.page.deleteDialog.description",{name:ne}),t[77]=e,t[78]=ne,t[79]=xe):xe=t[79];let ve;t[80]!==xe?(ve=s.jsx(Yt,{children:xe}),t[80]=xe,t[81]=ve):ve=t[81];let me;t[82]!==ue||t[83]!==ve?(me=s.jsxs(Ut,{children:[ue,ve]}),t[82]=ue,t[83]=ve,t[84]=me):me=t[84];let ge;t[85]===Symbol.for("react.memo_cache_sentinel")?(ge=()=>C(null),t[85]=ge):ge=t[85];let Ie;t[86]!==e?(Ie=e("settings.common.actions.cancel"),t[86]=e,t[87]=Ie):Ie=t[87];let oe;t[88]!==z||t[89]!==Ie?(oe=s.jsx(ee,{variant:"ghost",onClick:ge,disabled:z,children:Ie}),t[88]=z,t[89]=Ie,t[90]=oe):oe=t[90];let ce;t[91]!==O?(ce=()=>{O()},t[91]=O,t[92]=ce):ce=t[92];let pe;t[93]!==e?(pe=e("settings.common.actions.delete"),t[93]=e,t[94]=pe):pe=t[94];let ie;t[95]!==z||t[96]!==ce||t[97]!==pe?(ie=s.jsx(ee,{size:"sm",variant:"destructive",onClick:ce,disabled:z,children:pe}),t[95]=z,t[96]=ce,t[97]=pe,t[98]=ie):ie=t[98];let le;t[99]!==oe||t[100]!==ie?(le=s.jsxs(rs,{children:[oe,ie]}),t[99]=oe,t[100]=ie,t[101]=le):le=t[101];let de;t[102]!==me||t[103]!==le?(de=s.jsxs(Bt,{className:"max-w-md",children:[me,le]}),t[102]=me,t[103]=le,t[104]=de):de=t[104];let he;t[105]!==V||t[106]!==Q||t[107]!==de?(he=s.jsx(Kt,{open:V,onOpenChange:Q,children:de}),t[105]=V,t[106]=Q,t[107]=de,t[108]=he):he=t[108];let Me;return t[109]!==B||t[110]!==L||t[111]!==he?(Me=s.jsxs(s.Fragment,{children:[B,L,he]}),t[109]=B,t[110]=L,t[111]=he,t[112]=Me):Me=t[112],Me},md=t=>{const e=tt.c(56),{profile:n,isDefault:a,onEdit:i,onToggleDefault:r,onDelete:o,isReadOnly:d,hasBorder:c}=t,{t:p}=lt(),[u,f]=l.useState(!1),m=b1[n.icon||"branch"]||"git-branch",w=y1[n.color||""],b=n.authType||"ssh";let g;e[0]!==i?(g=T=>{T.currentTarget===T.target&&(T.key!=="Enter"&&T.key!==" "||(T.preventDefault(),i()))},e[0]=i,e[1]=g):g=e[1];const x=g;let k;e[2]!==a||e[3]!==d||e[4]!==o||e[5]!==r||e[6]!==p?(k=T=>s.jsxs(s.Fragment,{children:[s.jsx(T,{onClick:I=>{I.stopPropagation(),r()},children:p(a?"settings.gitIdentities.page.actions.unsetDefault":"settings.gitIdentities.page.actions.setAsDefault")}),!d&&o&&s.jsxs(T,{onClick:I=>{I.stopPropagation(),o()},className:"text-destructive focus:text-destructive",children:[s.jsx(K,{name:"delete-bin",className:"h-4 w-4 mr-px"}),p("settings.common.actions.delete")]})]}),e[2]=a,e[3]=d,e[4]=o,e[5]=r,e[6]=p,e[7]=k):k=e[7];const y=k,C=c&&"border-b border-[var(--surface-subtle)]";let z;e[8]!==C?(z=fe("group flex items-center justify-between gap-3 px-4 py-2.5 transition-colors hover:bg-[var(--interactive-hover)]/30 cursor-pointer",C),e[8]=C,e[9]=z):z=e[9];let j;e[10]===Symbol.for("react.memo_cache_sentinel")?(j=T=>{T.preventDefault(),f(!0)},e[10]=j):j=e[10];let N;e[11]!==x||e[12]!==i||e[13]!==z?(N=s.jsx("div",{className:z,onClick:i,role:"button",tabIndex:0,onKeyDown:x,onContextMenu:j}),e[11]=x,e[12]=i,e[13]=z,e[14]=N):N=e[14];let v;e[15]!==w?(v={color:w},e[15]=w,e[16]=v):v=e[16];let P;e[17]!==m||e[18]!==v?(P=s.jsx(K,{name:m,className:"w-4 h-4 shrink-0",style:v}),e[17]=m,e[18]=v,e[19]=P):P=e[19];let $;e[20]!==n.name?($=s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:n.name}),e[20]=n.name,e[21]=$):$=e[21];let O;e[22]!==b?(O=s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:b}),e[22]=b,e[23]=O):O=e[23];let M;e[24]!==a||e[25]!==p?(M=a&&s.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:p("settings.gitIdentities.page.badge.default")}),e[24]=a,e[25]=p,e[26]=M):M=e[26];let S;e[27]!==d||e[28]!==p?(S=d&&s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:p("settings.agents.sidebar.badge.system")}),e[27]=d,e[28]=p,e[29]=S):S=e[29];let F;e[30]!==O||e[31]!==M||e[32]!==S||e[33]!==$?(F=s.jsxs("div",{className:"flex items-center gap-1.5",children:[$,O,M,S]}),e[30]=O,e[31]=M,e[32]=S,e[33]=$,e[34]=F):F=e[34];const E=b==="token"&&n.host?n.host:n.userEmail;let D;e[35]!==E?(D=s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:E}),e[35]=E,e[36]=D):D=e[36];let W;e[37]!==F||e[38]!==D?(W=s.jsxs("div",{className:"min-w-0",children:[F,D]}),e[37]=F,e[38]=D,e[39]=W):W=e[39];let H;e[40]!==W||e[41]!==P?(H=s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[P,W]}),e[40]=W,e[41]=P,e[42]=H):H=e[42];let Z;e[43]===Symbol.for("react.memo_cache_sentinel")?(Z=s.jsx(gs,{asChild:!0,children:s.jsx(ee,{size:"icon",variant:"ghost",className:"h-6 w-6 shrink-0 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",onClick:k1,children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[43]=Z):Z=e[43];let Y;e[44]!==y?(Y=s.jsxs(fs,{children:[Z,s.jsx(hs,{align:"end",className:"w-fit min-w-28",children:y(as)})]}),e[44]=y,e[45]=Y):Y=e[45];let A;e[46]!==H||e[47]!==Y||e[48]!==N?(A=s.jsxs(Gn,{render:N,children:[H,Y]}),e[46]=H,e[47]=Y,e[48]=N,e[49]=A):A=e[49];let X;e[50]!==y?(X=s.jsx(qn,{className:"w-fit min-w-28",children:y(An)}),e[50]=y,e[51]=X):X=e[51];let te;return e[52]!==u||e[53]!==A||e[54]!==X?(te=s.jsxs(Wn,{open:u,onOpenChange:f,children:[A,X]}),e[52]=u,e[53]=A,e[54]=X,e[55]=te):te=e[55],te},w1=t=>{const e=tt.c(21),{credential:n,onImport:a,hasBorder:i}=t,{t:r}=lt();let o;e[0]!==n.host?(o=n.host.split("/"),e[0]=n.host,e[1]=o):o=e[1];const d=o,c=d.length>=3?d[d.length-1]:n.host,p=n.host.includes("/"),u=i&&"border-b border-[var(--surface-subtle)]";let f;e[2]!==u?(f=fe("flex items-center justify-between gap-3 px-4 py-2.5 transition-colors hover:bg-[var(--interactive-hover)]/30",u),e[2]=u,e[3]=f):f=e[3];let m;e[4]!==c?(m=s.jsx("span",{className:"typography-ui-label text-foreground truncate block",children:c}),e[4]=c,e[5]=m):m=e[5];const w=p?n.host:n.username;let b;e[6]!==w?(b=s.jsx("span",{className:"typography-micro text-muted-foreground/60 truncate block leading-tight",children:w}),e[6]=w,e[7]=b):b=e[7];let g;e[8]!==m||e[9]!==b?(g=s.jsxs("div",{className:"min-w-0",children:[m,b]}),e[8]=m,e[9]=b,e[10]=g):g=e[10];let x;e[11]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx(K,{name:"download",className:"h-3 w-3"}),e[11]=x):x=e[11];let k;e[12]!==r?(k=r("settings.gitIdentities.page.actions.import"),e[12]=r,e[13]=k):k=e[13];let y;e[14]!==a||e[15]!==k?(y=s.jsxs(ee,{size:"sm",variant:"ghost",onClick:a,className:"gap-1 shrink-0",children:[x,k]}),e[14]=a,e[15]=k,e[16]=y):y=e[16];let C;return e[17]!==y||e[18]!==f||e[19]!==g?(C=s.jsxs("div",{className:f,children:[g,y]}),e[17]=y,e[18]=f,e[19]=g,e[20]=C):C=e[20],C};function j1(t){return{profiles:t.profiles,globalIdentity:t.globalIdentity,defaultGitIdentityId:t.defaultGitIdentityId,deleteProfile:t.deleteProfile,loadProfiles:t.loadProfiles,loadGlobalIdentity:t.loadGlobalIdentity,loadDiscoveredCredentials:t.loadDiscoveredCredentials,loadDefaultGitIdentityId:t.loadDefaultGitIdentityId,setDefaultGitIdentityId:t.setDefaultGitIdentityId,getUnimportedCredentials:t.getUnimportedCredentials}}function k1(t){return t.stopPropagation()}const tm=()=>{const t=zp();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},N1=()=>{const t=tt.c(2),[e,n]=l.useState(S1);let a,i;return t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=[window.matchMedia("(display-mode: standalone)"),window.matchMedia("(display-mode: minimal-ui)"),window.matchMedia("(display-mode: fullscreen)"),window.matchMedia("(display-mode: window-controls-overlay)")],o=()=>{n(tm())};o();for(const d of r)typeof d.addEventListener=="function"?d.addEventListener("change",o):typeof d.addListener=="function"&&d.addListener(o);return window.addEventListener("appinstalled",o),window.addEventListener("focus",o),()=>{for(const d of r)typeof d.removeEventListener=="function"?d.removeEventListener("change",o):typeof d.removeListener=="function"&&d.removeListener(o);window.removeEventListener("appinstalled",o),window.removeEventListener("focus",o)}},i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),l.useEffect(a,i),e};function S1(){return tm()}const C1=[{value:"system",labelKey:"settings.openchamber.visual.option.themeMode.system",descriptionKey:"settings.openchamber.visual.option.themeMode.system.description"},{value:"light",labelKey:"settings.openchamber.visual.option.themeMode.light",descriptionKey:"settings.openchamber.visual.option.themeMode.light.description"},{value:"dark",labelKey:"settings.openchamber.visual.option.themeMode.dark",descriptionKey:"settings.openchamber.visual.option.themeMode.dark.description"}],I1=[{id:"dynamic",labelKey:"settings.openchamber.visual.option.diffLayout.dynamic.label",descriptionKey:"settings.openchamber.visual.option.diffLayout.dynamic.description"},{id:"inline",labelKey:"settings.openchamber.visual.option.diffLayout.inline.label",descriptionKey:"settings.openchamber.visual.option.diffLayout.inline.description"},{id:"side-by-side",labelKey:"settings.openchamber.visual.option.diffLayout.sideBySide.label",descriptionKey:"settings.openchamber.visual.option.diffLayout.sideBySide.description"}],P1=[{id:"svg",labelKey:"settings.openchamber.visual.option.mermaidRendering.svg.label",descriptionKey:"settings.openchamber.visual.option.mermaidRendering.svg.description"},{id:"ascii",labelKey:"settings.openchamber.visual.option.mermaidRendering.ascii.label",descriptionKey:"settings.openchamber.visual.option.mermaidRendering.ascii.description"}],ri="OpenChamber - AI Coding Assistant",pd=[{id:"system",labelKey:"settings.openchamber.visual.option.pwaOrientation.system.label",descriptionKey:"settings.openchamber.visual.option.pwaOrientation.system.description"},{id:"portrait",labelKey:"settings.openchamber.visual.option.pwaOrientation.portrait.label",descriptionKey:"settings.openchamber.visual.option.pwaOrientation.portrait.description"},{id:"landscape",labelKey:"settings.openchamber.visual.option.pwaOrientation.landscape.label",descriptionKey:"settings.openchamber.visual.option.pwaOrientation.landscape.description"}],gd=[{id:"native",labelKey:"settings.openchamber.visual.option.mobileKeyboardMode.native.label",descriptionKey:"settings.openchamber.visual.option.mobileKeyboardMode.native.description"},{id:"resize-content",labelKey:"settings.openchamber.visual.option.mobileKeyboardMode.resizeContent.label",descriptionKey:"settings.openchamber.visual.option.mobileKeyboardMode.resizeContent.description"}],T1=[{value:"default",labelKey:"settings.openchamber.visual.option.mobileLayout.default"},{value:"new",labelKey:"settings.openchamber.visual.option.mobileLayout.new"}],lo=t=>t==="portrait"||t==="landscape"?t:"system",A1=[{id:"markdown",labelKey:"settings.openchamber.visual.option.userMessageRendering.markdown.label",descriptionKey:"settings.openchamber.visual.option.userMessageRendering.markdown.description"},{id:"plain",labelKey:"settings.openchamber.visual.option.userMessageRendering.plain.label",descriptionKey:"settings.openchamber.visual.option.userMessageRendering.plain.description"}],E1=[{id:"sorted",labelKey:"settings.openchamber.visual.option.chatRenderMode.sorted.label",descriptionKey:"settings.openchamber.visual.option.chatRenderMode.sorted.description"},{id:"live",labelKey:"settings.openchamber.visual.option.chatRenderMode.live.label",descriptionKey:"settings.openchamber.visual.option.chatRenderMode.live.description"}],fd=[{id:"auto",labelKey:"settings.openchamber.visual.option.messageTransport.auto.label",descriptionKey:"settings.openchamber.visual.option.messageTransport.auto.description"},{id:"ws",labelKey:"settings.openchamber.visual.option.messageTransport.ws.label",descriptionKey:"settings.openchamber.visual.option.messageTransport.ws.description"},{id:"sse",labelKey:"settings.openchamber.visual.option.messageTransport.sse.label",descriptionKey:"settings.openchamber.visual.option.messageTransport.sse.description"}],D1=[{id:"collapsed",labelKey:"settings.openchamber.visual.option.activityRenderMode.collapsed.label",descriptionKey:"settings.openchamber.visual.option.activityRenderMode.collapsed.description"},{id:"summary",labelKey:"settings.openchamber.visual.option.activityRenderMode.summary.label",descriptionKey:"settings.openchamber.visual.option.activityRenderMode.summary.description"}],hd=[{id:"auto",labelKey:"settings.openchamber.visual.option.timeFormat.auto.label",descriptionKey:"settings.openchamber.visual.option.timeFormat.auto.description"},{id:"24h",labelKey:"settings.openchamber.visual.option.timeFormat.24h.label",descriptionKey:"settings.openchamber.visual.option.timeFormat.24h.description"},{id:"12h",labelKey:"settings.openchamber.visual.option.timeFormat.12h.label",descriptionKey:"settings.openchamber.visual.option.timeFormat.12h.description"}],xd=[{id:"auto",labelKey:"settings.openchamber.visual.option.weekStart.auto.label",descriptionKey:"settings.openchamber.visual.option.weekStart.auto.description"},{id:"monday",labelKey:"settings.openchamber.visual.option.weekStart.monday.label"},{id:"sunday",labelKey:"settings.openchamber.visual.option.weekStart.sunday.label"}],R1=[{id:"steer",labelKey:"settings.openchamber.visual.option.followUpBehavior.steer.label"},{id:"queue",labelKey:"settings.openchamber.visual.option.followUpBehavior.queue.label"}],M1=t=>t==="markdown"?"markdown":"plain",L1=[{id:"left",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsLeft"},{id:"right",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsRight"}],F1=[{id:"classic",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsClassic"},{id:"traffic-lights",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsTrafficLights"}],Tr=({visibleSettings:t})=>{const{locale:e,locales:n,setLocale:a,label:i,t:r}=lt(),o=l.useCallback(R=>r(R),[r]),{isMobile:d}=Vs(),{terminal:c}=Va(),{browserTab:p}=N1(),u=Kg(),f=ke(R=>R.showReasoningTraces),m=ke(R=>R.sessionRecapEnabled),w=ke(R=>R.sessionSuggestionEnabled),b=ke(R=>R.setSessionRecapEnabled),g=ke(R=>R.setSessionSuggestionEnabled),x=ke(R=>R.sessionGoalEnabled),k=ke(R=>R.setSessionGoalEnabled),y=ke(R=>R.sessionGoalDefaultBudgetEnabled),C=ke(R=>R.setSessionGoalDefaultBudgetEnabled),z=ke(R=>R.sessionGoalDefaultBudget),j=ke(R=>R.setSessionGoalDefaultBudget),N=ke(R=>R.setShowReasoningTraces),v=ke(R=>R.collapsibleThinkingBlocks),P=ke(R=>R.setCollapsibleThinkingBlocks),$=ke(R=>R.mermaidRenderingMode),O=ke(R=>R.setMermaidRenderingMode),M=ke(R=>R.userMessageRenderingMode),S=ke(R=>R.setUserMessageRenderingMode),F=ke(R=>R.collapsibleUserMessages),E=ke(R=>R.setCollapsibleUserMessages),D=ke(R=>R.stickyUserHeader),W=ke(R=>R.promptNavigatorEnabled),H=ke(R=>R.setStickyUserHeader),Z=ke(R=>R.setPromptNavigatorEnabled),Y=ke(R=>R.expandedEditorToolbar),A=ke(R=>R.setExpandedEditorToolbar),X=ke(R=>R.autoSaveEnabled),te=ke(R=>R.setAutoSaveEnabled),T=ke(R=>R.wideChatLayoutEnabled),I=ke(R=>R.setWideChatLayoutEnabled),B=ke(R=>R.codeBlockLineWrap),L=ke(R=>R.setCodeBlockLineWrap),V=ke(R=>R.chatRenderMode),Q=ke(R=>R.setChatRenderMode),G=ke(R=>R.activityRenderMode),ue=ke(R=>R.setActivityRenderMode),ne=ke(R=>R.fontSize),xe=ke(R=>R.setFontSize),ve=ke(R=>R.terminalFontSize),me=ke(R=>R.setTerminalFontSize),ge=ke(R=>R.terminalShell),Ie=ke(R=>R.setTerminalShell),oe=ke(R=>R.terminalLoginShells),ce=ke(R=>R.setTerminalLoginShells),pe=ke(R=>R.editorFontSize),ie=ke(R=>R.setEditorFontSize),le=ke(R=>R.uiFont),de=ke(R=>R.setUiFont),he=ke(R=>R.monoFont),Me=ke(R=>R.setMonoFont),Le=ke(R=>R.padding),Be=ke(R=>R.setPadding),Fe=ke(R=>R.inputBarOffset),De=ke(R=>R.setInputBarOffset),ze=ke(R=>R.mobileKeyboardMode),Ve=ke(R=>R.setMobileKeyboardMode),We=ke(R=>R.diffLayoutPreference),_e=ke(R=>R.setDiffLayoutPreference),He=ke(R=>R.showTerminalQuickKeysOnDesktop),Ke=ke(R=>R.setShowTerminalQuickKeysOnDesktop),Oe=ke(R=>R.fileEditorKeymap),je=ke(R=>R.setFileEditorKeymap),Te=$l(R=>R.followUpBehavior),Ue=$l(R=>R.setFollowUpBehavior),Ye=ke(R=>R.persistChatDraft),q=ke(R=>R.setPersistChatDraft),re=ke(R=>R.inputSpellcheckEnabled),U=ke(R=>R.setInputSpellcheckEnabled),h=ke(R=>R.showToolFileIcons),ae=ke(R=>R.setShowToolFileIcons),ye=ke(R=>R.showTurnChangedFiles),be=ke(R=>R.setShowTurnChangedFiles),Ee=ke(R=>R.showExpandedBashTools),et=ke(R=>R.setShowExpandedBashTools),Ze=ke(R=>R.showExpandedEditTools),it=ke(R=>R.setShowExpandedEditTools),ot=ke(R=>R.timeFormatPreference),xt=ke(R=>R.setTimeFormatPreference),bt=ke(R=>R.weekStartPreference),Nt=ke(R=>R.setWeekStartPreference),Se=ke(R=>R.showSplitAssistantMessageActions),Qe=ke(R=>R.setShowSplitAssistantMessageActions),nt=ke(R=>R.allowPromptingSubagentSessions),rt=ke(R=>R.setAllowPromptingSubagentSessions),gt=ke(R=>R.draftStartersVisible),wt=ke(R=>R.setDraftStartersVisible),Pe=pt(R=>R.settingsMessageStreamTransport),se=pt(R=>R.setSettingsMessageStreamTransport),Ce=Pe,Xe=pt(R=>R.settingsDefaultFileViewerPreview),Re=pt(R=>R.setSettingsDefaultFileViewerPreview),Je=ke(R=>R.isSettingsDialogOpen),{themeMode:Ge,setThemeMode:st,availableThemes:jt,customThemesLoading:Et,reloadCustomThemes:Mt,lightThemeId:Zt,darkThemeId:Qt,setLightThemePreference:St,setDarkThemePreference:Pt}=Ha(),[Ne,ut]=l.useState(!1),mt=l.useMemo(()=>ls()&&typeof window<"u"&&window.__OPENCHAMBER_ELECTRON__?.macVibrancySupported===!0,[]),At=typeof window<"u"&&window.__OPENCHAMBER_ELECTRON__?.macVibrancy===!0,[ft,vt]=l.useState(At),[Dt,Vt]=l.useState(!1),ts=l.useMemo(()=>ls()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",[]),os=ke(R=>R.dockBadgeEnabled),En=ke(R=>R.setDockBadgeEnabled),zs=Bg(),ga=ke(R=>R.desktopWindowControlsPosition),Yn=ke(R=>R.setDesktopWindowControlsPosition),Ar=ke(R=>R.desktopWindowControlsStyle),vi=ke(R=>R.setDesktopWindowControlsStyle),[Er,Ws]=l.useState(0),Ja=ke(R=>R.reportUsage),wi=ke(R=>R.setReportUsage),ji=l.useCallback(R=>{wi(R),It({reportUsage:R})},[wi]),Dr=l.useCallback(R=>{Yn(R),It({desktopWindowControlsPosition:R})},[Yn]),Rr=l.useCallback(R=>{vi(R),It({desktopWindowControlsStyle:R})},[vi]),ki=(Je||d||ds())&&(t?t.includes("chatRenderMode"):!0);l.useEffect(()=>{if(!ki)return;let R=null,Tt=Date.now();const Ts=()=>{const bn=Date.now();bn-Tt>=420&&(Ws(ta=>(ta+1)%24),Tt=bn),R=requestAnimationFrame(Ts)};(typeof document>"u"||document.visibilityState==="visible")&&(R=requestAnimationFrame(Ts));const vs=()=>{document.visibilityState==="visible"&&R===null?R=requestAnimationFrame(Ts):document.visibilityState!=="visible"&&R!==null&&(cancelAnimationFrame(R),R=null)};return document.addEventListener("visibilitychange",vs),()=>{document.removeEventListener("visibilitychange",vs),R!==null&&cancelAnimationFrame(R)}},[ki]);const Mr=l.useCallback(R=>{S(R),It({userMessageRenderingMode:R})},[S]),Lr=l.useCallback(R=>{H(R),It({stickyUserHeader:R})},[H]),Ks=l.useCallback(R=>{Z(R),It({promptNavigatorEnabled:R})},[Z]),rn=l.useCallback(R=>{wt(R),It({draftStartersVisible:R})},[wt]),fa=l.useCallback(R=>{A(R),It({expandedEditorToolbar:R})},[A]),hn=l.useCallback(R=>{E(R),It({collapsibleUserMessages:R})},[E]),Dn=l.useCallback(R=>{I(R),It({wideChatLayoutEnabled:R})},[I]),wl=l.useCallback(R=>{Qe(R),It({showSplitAssistantMessageActions:R})},[Qe]),Rn=l.useCallback(R=>{U(R),It({inputSpellcheckEnabled:R})},[U]),Fr=l.useCallback(R=>{Q(R),It({chatRenderMode:R})},[Q]),ha=l.useCallback(R=>{se(R),It({messageStreamTransport:R})},[se]),Or=l.useCallback(R=>{ue(R),It({activityRenderMode:R})},[ue]),ys=l.useCallback(R=>{O(R),It({mermaidRenderingMode:R})},[O]),zr=l.useCallback(R=>{ae(R),It({showToolFileIcons:R})},[ae]),xa=l.useCallback(R=>{be(R),It({showTurnChangedFiles:R})},[be]),ba=l.useCallback(R=>{Re(R),It({defaultFileViewerPreview:R}),window.dispatchEvent(new CustomEvent("openchamber:file-viewer-preview-mode-changed",{detail:{enabled:R}}))},[Re]),Kr=l.useCallback(R=>{et(R),It({showExpandedBashTools:R})},[et]),Ni=l.useCallback(R=>{it(R),It({showExpandedEditTools:R})},[it]),ya=l.useCallback(R=>{xt(R),It({timeFormatPreference:R})},[xt]),va=l.useCallback(R=>{Nt(R),It({weekStartPreference:R})},[Nt]),wa=l.useMemo(()=>jt.filter(R=>R.metadata.variant==="light").sort((R,Tt)=>R.metadata.name.localeCompare(Tt.metadata.name)),[jt]),xn=l.useMemo(()=>jt.filter(R=>R.metadata.variant==="dark").sort((R,Tt)=>R.metadata.name.localeCompare(Tt.metadata.name)),[jt]),Ya=l.useMemo(()=>wa.find(R=>R.metadata.id===Zt)??wa[0],[wa,Zt]),Qa=l.useMemo(()=>xn.find(R=>R.metadata.id===Qt)??xn[0],[xn,Qt]),ja=l.useCallback((R,Tt)=>{const Ts=Tt==="dark"?" Dark":" Light";return R.endsWith(Ts)?R.slice(0,-Ts.length):R},[]),qe=R=>t?t.includes(R):!0,ms=ds(),Si=qe("theme")&&!ms,Ci=qe("windowControlsPosition")&&zs,Ii=qe("theme")||qe("timeFormat")||qe("weekStart"),Xa=d&&In()&&!ls()&&!ms,Pi=ms?Ii:qe("theme")||Ci||Xa||qe("pwaInstallName")||qe("pwaOrientation")||qe("timeFormat")||qe("weekStart"),_=qe("fontSize")||qe("terminalFontSize")||qe("editorFontSize")||qe("spacing")||qe("inputBarOffset")&&d,Ae=qe("terminalQuickKeys")&&!d||(qe("terminalShell")||qe("terminalLoginShell"))&&!ms||qe("fileEditorKeymap")||qe("autoSaveEnabled")||qe("expandedEditorToolbar")&&!ms,ct=qe("mermaidRendering")||qe("sessionGoal")&&!ms||qe("userMessageRendering")||qe("chatRenderMode")||qe("messageTransport")||qe("activityRenderMode")&&V==="sorted"||qe("collapsibleUserMessages")||qe("stickyUserHeader")||qe("promptNavigatorEnabled")&&!ms||qe("wideChatLayout")||qe("codeBlockLineWrap")||qe("splitAssistantMessageActions")||qe("subagentReadOnlyBanner")||qe("diffLayout")||qe("dotfiles")||qe("fileViewerPreview")||qe("reasoning")||qe("followUpBehavior")||qe("persistDraft")||qe("showToolFileIcons")||qe("expandedTools")||!d&&qe("inputSpellcheck"),yt=qe("chatRenderMode")||qe("activityRenderMode")&&V==="sorted",Gt=qe("messageTransport"),Bs=qe("userMessageRendering")||qe("mermaidRendering")||qe("diffLayout")&&!ms||qe("followUpBehavior"),us=qe("sessionAssist")||qe("sessionGoal")&&!ms||qe("subagentReadOnlyBanner")||qe("collapsibleUserMessages")||qe("stickyUserHeader")||qe("promptNavigatorEnabled")&&!ms||qe("wideChatLayout")||qe("codeBlockLineWrap")||qe("splitAssistantMessageActions")||qe("dotfiles")||qe("fileViewerPreview")||qe("persistDraft")||qe("showToolFileIcons")||qe("showTurnChangedFiles")||!d&&qe("inputSpellcheck")||qe("reasoning")||qe("expandedTools"),Gs=Pi||_||Ae,_s=qe("pwaInstallName")&&In()&&p&&!ls()&&!ms,Ms=qe("pwaOrientation")&&In()&&!ls()&&!ms,on=qe("mobileKeyboardMode")&&In()&&!ls()&&!ms&&_g(),ln=(qe("terminalShell")||qe("terminalLoginShell"))&&!ms,[Qn,Rt]=l.useState([]),[cs,Xn]=l.useState(0);l.useEffect(()=>cl(()=>{Rt([]),Xn(R=>R+1)}),[]),l.useEffect(()=>{let R=!1;if(!(!ln||!c.listShells))return c.listShells().then(Tt=>{R||Rt(Tt)}).catch(()=>{R||Rt([])}),()=>{R=!0}},[ln,c,cs]);const Ht=l.useMemo(()=>{const R=Qn.filter(Tt=>Tt.id!=="auto");return ge==="auto"||R.some(Tt=>Tt.id===ge)?R:[{id:ge,name:ge,supportsLogin:!1},...R]},[Qn,ge]),Ls=Qn.find(R=>R.id===ge)?.supportsLogin===!0,Zn=oe.includes(ge),ka=R=>{ce(R?[...oe.filter(Tt=>Tt!==ge),ge]:oe.filter(Tt=>Tt!==ge))},[Na,Cm]=l.useState(()=>If()),[Br,ea]=l.useState(""),[Ti,Sa]=l.useState("system"),Im=l.useMemo(()=>{const R=hd.find(Tt=>Tt.id===ot);return o(R?.labelKey??"settings.openchamber.visual.option.timeFormat.auto.label")},[ot,o]),Pm=l.useMemo(()=>{const R=xd.find(Tt=>Tt.id===bt);return o(R?.labelKey??"settings.openchamber.visual.option.weekStart.auto.label")},[bt,o]),Tm=l.useMemo(()=>{const R=pd.find(Tt=>Tt.id===Ti);return R?o(R.labelKey):void 0},[Ti,o]),Am=l.useMemo(()=>{const R=gd.find(Tt=>Tt.id===ze);return R?o(R.labelKey):void 0},[ze,o]),Em=l.useCallback(R=>{R!==Na&&(Cm(R),Pf(R),window.location.reload())},[Na]),_r=l.useCallback(async R=>{if(typeof window>"u")return;const Tt=window,vs=R.trim().replace(/\s+/g," ").slice(0,64);if(await It({pwaAppName:vs}),typeof Tt.__OPENCHAMBER_SET_PWA_INSTALL_NAME__=="function"){const bn=Tt.__OPENCHAMBER_SET_PWA_INSTALL_NAME__(vs);ea(bn);return}ea(vs||ri),Tt.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),jl=l.useCallback(async R=>{if(typeof window>"u")return;const Tt=window,Ts=lo(R);if(await It({pwaOrientation:Ts}),typeof Tt.__OPENCHAMBER_SET_PWA_ORIENTATION__=="function"){const vs=Tt.__OPENCHAMBER_SET_PWA_ORIENTATION__(Ts);Sa(vs);return}Sa(Ts),Tt.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return l.useEffect(()=>{if(typeof window>"u"||!_s&&!Ms&&!on)return;let R=!1;return(async()=>{try{const Ts=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!Ts.ok){R||ea(ri);return}const vs=await Ts.json().catch(()=>({})),ta=(typeof vs?.pwaAppName=="string"?vs.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),Ai=lo(vs?.pwaOrientation),Ur=Gl(vs?.mobileKeyboardMode);R||(_s&&ea(ta||ri),Ms&&Sa(Ai),on&&Ve(Ur))}catch{R||(_s&&ea(ri),Ms&&Sa("system"),on&&Ve("native"))}})(),()=>{R=!0}},[Ve,on,_s,Ms]),s.jsxs("div",{className:"space-y-0",children:[Pi&&s.jsxs("div",{className:"space-y-0",children:[Si&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.colorModeAndTheme"),divider:!1,children:[s.jsxs(On,{children:[s.jsxs("div",{className:Bn,children:[s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.colorMode"),children:C1.map(R=>s.jsx(zn,{selected:Ge===R.value,onSelect:()=>st(R.value),label:o(R.labelKey),ariaLabel:o(R.labelKey)},R.value))}),Xa&&s.jsx(la,{children:s.jsx(ns,{label:r("settings.openchamber.visual.section.mobileLayout"),children:s.jsx(Ys,{value:Na,options:T1.map(R=>({value:R.value,label:o(R.labelKey)})),onChange:Em,"aria-label":r("settings.openchamber.visual.section.mobileLayout")})})})]}),s.jsxs("div",{className:Bn,children:[s.jsx(ns,{label:r("settings.openchamber.visual.field.lightTheme"),settingsItem:"appearance.light-theme",children:s.jsxs(Lt,{value:Ya?.metadata.id??"",onValueChange:St,children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.selectLightThemeAria"),size:Jt,className:wn,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectThemePlaceholder"),children:Ya?ja(Ya.metadata.name,"light"):void 0})}),s.jsx(Ot,{children:wa.map(R=>s.jsx(kt,{value:R.metadata.id,children:ja(R.metadata.name,"light")},R.metadata.id))})]})}),s.jsx(ns,{label:r("settings.openchamber.visual.field.darkTheme"),settingsItem:"appearance.dark-theme",children:s.jsxs(Lt,{value:Qa?.metadata.id??"",onValueChange:Pt,children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.selectDarkThemeAria"),size:Jt,className:wn,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectThemePlaceholder"),children:Qa?ja(Qa.metadata.name,"dark"):void 0})}),s.jsx(Ot,{children:xn.map(R=>s.jsx(kt,{value:R.metadata.id,children:ja(R.metadata.name,"dark")},R.metadata.id))})]})}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsxs("button",{type:"button",disabled:Et||Ne,onClick:()=>{const R=Date.now();ut(!0),Mt().finally(()=>{const Tt=Date.now()-R;if(Tt<500){window.setTimeout(()=>{ut(!1)},500-Tt);return}ut(!1)})},className:"typography-settings-link inline-flex items-center gap-1.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:no-underline",children:[s.jsx(K,{name:"restart",className:fe("h-3.5 w-3.5",Ne&&"animate-spin")}),r(Ne?"settings.openchamber.visual.actions.reloadingThemes":"settings.openchamber.visual.actions.reloadThemes")]}),s.jsx($t,{children:r("settings.openchamber.visual.field.themeImportInfoTooltip")})]})]})]}),mt&&s.jsxs(la,{settingsItem:"appearance.window-transparency",className:"flex flex-col gap-1.5",children:[s.jsx(Ct,{checked:ft,onChange:vt,disabled:Dt,label:r("settings.openchamber.visual.field.macVibrancy"),info:r("settings.openchamber.visual.field.macVibrancyHint"),ariaLabel:r("settings.openchamber.visual.field.macVibrancy")}),ft!==At&&s.jsx("div",{className:"pl-6",children:s.jsx(ee,{variant:"outline",size:"sm",disabled:Dt,onClick:()=>{Vt(!0),Ug("desktop_set_vibrancy",{enabled:ft})},children:r(Dt?"settings.openchamber.visual.actions.restarting":"settings.openchamber.visual.actions.saveAndRestart")})})]}),ts&&s.jsx(la,{settingsItem:"appearance.dock-badge",children:s.jsx(Ct,{checked:os,onChange:En,label:r("settings.openchamber.visual.field.dockBadge"),info:r("settings.openchamber.visual.field.dockBadgeHint"),ariaLabel:r("settings.openchamber.visual.field.dockBadge")})})]}),Ci&&s.jsx(dt,{title:r("settings.openchamber.desktopNetwork.field.windowControls"),info:r("settings.openchamber.desktopNetwork.field.windowControlsPositionDescription"),divider:Si,children:s.jsxs(On,{children:[s.jsx(ns,{label:r("settings.openchamber.desktopNetwork.field.windowControlsPosition"),settingsItem:"sessions.desktop-window-controls-position",children:s.jsx(Ys,{value:ga,options:L1.map(R=>({value:R.id,label:o(R.labelKey)})),onChange:Dr,"aria-label":r("settings.openchamber.desktopNetwork.field.windowControlsPositionAria")})}),s.jsx(ns,{label:r("settings.openchamber.desktopNetwork.field.windowControlsStyle"),settingsItem:"sessions.desktop-window-controls-style",children:s.jsx(Ys,{value:Ar,options:F1.map(R=>({value:R.id,label:o(R.labelKey)})),onChange:Rr,"aria-label":r("settings.openchamber.desktopNetwork.field.windowControlsStyleAria")})})]})}),Ii&&s.jsx(dt,{title:r("settings.openchamber.visual.section.localization"),children:s.jsxs(On,{children:[s.jsx(ns,{label:r("settings.appearance.language.label"),info:r("settings.appearance.language.description"),settingsItem:"appearance.language",children:s.jsxs(Lt,{value:e,onValueChange:R=>a(R),children:[s.jsx(Ft,{"aria-label":r("settings.appearance.language.select"),size:Jt,className:wn,children:s.jsx(Wt,{children:i(e)})}),s.jsx(Ot,{children:n.map(R=>s.jsx(kt,{value:R,children:i(R)},R))})]})}),(qe("timeFormat")||qe("weekStart"))&&s.jsxs("div",{className:Bn,children:[qe("timeFormat")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.timeFormat"),settingsItem:"appearance.time-format",children:s.jsxs(Lt,{value:ot,onValueChange:R=>ya(R),children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.selectTimeFormatAria"),size:Jt,className:wn,children:s.jsx(Wt,{children:Im})}),s.jsx(Ot,{children:hd.map(R=>s.jsx(kt,{value:R.id,children:o(R.labelKey)},R.id))})]})}),qe("weekStart")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.weekStartsOn"),settingsItem:"appearance.week-start",children:s.jsxs(Lt,{value:bt,onValueChange:R=>va(R),children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.selectWeekStartAria"),size:Jt,className:wn,children:s.jsx(Wt,{children:Pm})}),s.jsx(Ot,{children:xd.map(R=>s.jsx(kt,{value:R.id,children:o(R.labelKey)},R.id))})]})})]})]})}),(_s||Ms||on)&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.appInstall"),contentClassName:Bn,children:[_s&&s.jsxs(Xt,{label:r("settings.openchamber.visual.field.installAppName"),info:r("settings.openchamber.visual.field.installAppNameHint"),settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:Us,children:[s.jsx(at,{value:Br,onChange:R=>{ea(R.target.value)},onBlur:()=>{_r(Br)},onKeyDown:R=>{R.key==="Enter"&&(R.preventDefault(),_r(Br))},className:"min-w-0 flex-1",maxLength:64,"aria-label":r("settings.openchamber.visual.field.pwaInstallAppNameAria")}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>{ea(ri),_r("")},className:Is,"aria-label":r("settings.openchamber.visual.actions.resetInstallAppNameAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]}),Ms&&s.jsxs(Xt,{label:r("settings.openchamber.visual.field.installOrientation"),description:r("settings.openchamber.visual.field.installOrientationHint"),settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:Us,children:[s.jsxs(Lt,{value:Ti,onValueChange:R=>{const Tt=lo(R);Sa(Tt),jl(Tt)},children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.pwaInstallOrientationAria"),size:Jt,className:dc,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectOrientationPlaceholder"),children:Tm})}),s.jsx(Ot,{children:pd.map(R=>s.jsx(kt,{value:R.id,children:o(R.labelKey)},R.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Sa("system"),jl("system")},disabled:Ti==="system",className:Is,"aria-label":r("settings.openchamber.visual.actions.resetInstallOrientationAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]}),on&&s.jsxs(Xt,{label:r("settings.openchamber.visual.field.mobileKeyboardMode"),info:r("settings.openchamber.visual.field.mobileKeyboardModeHint"),settingsItem:"appearance.mobile-keyboard-mode",alignEnd:!1,controlClassName:Us,children:[s.jsxs(Lt,{value:ze,onValueChange:R=>{const Tt=Gl(R);Ve(Tt),It({mobileKeyboardMode:Tt})},children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.mobileKeyboardModeAria"),size:Jt,className:dc,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectMobileKeyboardModePlaceholder"),children:Am})}),s.jsx(Ot,{children:gd.map(R=>s.jsx(kt,{value:R.id,children:o(R.labelKey)},R.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Ve("native"),It({mobileKeyboardMode:"native"})},disabled:ze==="native",className:Is,"aria-label":r("settings.openchamber.visual.actions.resetMobileKeyboardModeAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})]})]}),_&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.densityAndType"),contentClassName:Bn,children:[qe("fontSize")&&!d||qe("terminalFontSize")?s.jsxs(On,{children:[qe("fontSize")&&!d&&s.jsxs(ns,{label:r("settings.openchamber.visual.field.interfaceFont"),settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[s.jsxs(Lt,{value:le,onValueChange:R=>de(R),children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.selectInterfaceFontAria"),size:Jt,className:wn,children:s.jsx(Wt,{children:Vl.find(R=>R.id===le)?.label})}),s.jsx(Ot,{children:Vl.map(R=>s.jsx(kt,{value:R.id,children:s.jsx("span",{style:{fontFamily:R.stack},children:R.label})},R.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>de(Hl),disabled:le===Hl,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetInterfaceFontAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]}),qe("terminalFontSize")&&s.jsxs(ns,{label:r("settings.openchamber.visual.field.codeFont"),controlClassName:"w-full",children:[s.jsxs(Lt,{value:he,onValueChange:R=>Me(R),children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.selectCodeFontAria"),size:Jt,className:wn,children:s.jsx(Wt,{children:Wl.find(R=>R.id===he)?.label})}),s.jsx(Ot,{children:Wl.map(R=>s.jsx(kt,{value:R.id,children:s.jsx("span",{style:{fontFamily:R.stack},children:R.label})},R.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>Me(pi),disabled:he===pi,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetCodeFontAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,qe("fontSize")&&!d||qe("terminalFontSize")||qe("editorFontSize")?s.jsxs(On,{children:[qe("fontSize")&&!d&&s.jsx(ns,{label:r("settings.openchamber.visual.field.interfaceFontSize"),controlClassName:"w-full",children:s.jsxs("div",{className:ti,children:[s.jsx(Rs,{value:ne,onValueChange:xe,min:50,max:200,step:5,"aria-label":r("settings.openchamber.visual.field.fontSizePercentageAria")}),s.jsx("span",{className:si,children:"%"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>xe(100),disabled:ne===100,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetFontSizeAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})}),qe("terminalFontSize")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.terminalFontSize"),settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:s.jsxs("div",{className:ti,children:[s.jsx(Rs,{value:ve,onValueChange:me,min:9,max:52,step:1}),s.jsx("span",{className:si,children:"px"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>me(13),disabled:ve===13,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetTerminalFontSizeAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})}),qe("editorFontSize")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.editorFontSize"),settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:s.jsxs("div",{className:ti,children:[s.jsx(Rs,{value:pe,onValueChange:ie,min:9,max:32,step:1}),s.jsx("span",{className:si,children:"px"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>ie(13),disabled:pe===13,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetEditorFontSizeAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,qe("spacing")||qe("inputBarOffset")&&d?s.jsxs(On,{children:[qe("spacing")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.spacingDensity"),settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:s.jsxs("div",{className:ti,children:[s.jsx(Rs,{value:Le,onValueChange:Be,min:50,max:200,step:5}),s.jsx("span",{className:si,children:"%"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>Be(100),disabled:Le===100,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetSpacingAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})}),qe("inputBarOffset")&&d&&s.jsx(ns,{label:r("settings.openchamber.visual.field.inputBarOffset"),info:r("settings.openchamber.visual.field.inputBarOffsetTooltip"),settingsItem:"appearance.input-bar-offset",controlClassName:"w-full",children:s.jsxs("div",{className:ti,children:[s.jsx(Rs,{value:Fe,onValueChange:De,min:0,max:100,step:5}),s.jsx("span",{className:si,children:"px"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>De(0),disabled:Fe===0,className:Is,"aria-label":r("settings.openchamber.visual.actions.resetInputBarOffsetAria"),title:r("settings.common.actions.reset"),children:s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),Ae&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.navigation"),contentClassName:"space-y-4",children:[qe("fileEditorKeymap")&&s.jsx(Zs,{title:r("settings.openchamber.visual.field.fileEditorKeymap"),settingsItem:"appearance.file-editor-keymap",children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.field.fileEditorKeymap"),children:["default","vim"].map(R=>s.jsx(zn,{selected:Oe===R,onSelect:()=>je(R),label:r(`settings.openchamber.visual.option.fileEditorKeymap.${R}`),ariaLabel:r(`settings.openchamber.visual.option.fileEditorKeymap.${R}`)},R))})}),s.jsxs("div",{className:Ds,children:[qe("autoSaveEnabled")&&s.jsx(Ct,{checked:X,onChange:te,label:r("settings.openchamber.visual.field.autoSaveEnabled"),ariaLabel:r("settings.openchamber.visual.field.autoSaveEnabledAria"),info:r("settings.openchamber.visual.field.autoSaveEnabledInfo"),settingsItem:"appearance.auto-save-enabled"}),qe("expandedEditorToolbar")&&!ms&&s.jsx(Ct,{checked:Y,onChange:fa,label:r("settings.openchamber.visual.field.expandedEditorToolbar"),ariaLabel:r("settings.openchamber.visual.field.expandedEditorToolbarAria"),settingsItem:"appearance.expanded-editor-toolbar"}),qe("terminalQuickKeys")&&!d&&s.jsx(Ct,{checked:He,onChange:Ke,label:r("settings.openchamber.visual.field.terminalQuickKeys"),ariaLabel:r("settings.openchamber.visual.field.terminalQuickKeysAria"),settingsItem:"appearance.terminal-quick-keys",info:r("settings.openchamber.visual.field.terminalQuickKeysTooltip")}),ln&&s.jsx(ns,{label:r("settings.openchamber.visual.field.terminalShell"),info:r("settings.openchamber.visual.field.terminalShellHint"),settingsItem:"appearance.terminal-shell",className:"pt-2",children:s.jsxs(Lt,{value:ge,onValueChange:R=>{$g(R)&&Ie(R)},children:[s.jsx(Ft,{"aria-label":r("settings.openchamber.visual.field.terminalShellAria"),size:Jt,className:wn,children:s.jsx(Wt,{})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"auto",children:r("settings.openchamber.visual.option.terminalShell.auto")}),Ht.map(R=>s.jsx(kt,{value:R.id,children:R.name},R.id))]})]})}),ln&&Ls&&s.jsx(Ct,{checked:Zn,onChange:ka,label:r("settings.openchamber.visual.field.terminalLoginShell"),ariaLabel:r("settings.openchamber.visual.field.terminalLoginShell"),settingsItem:"appearance.terminal-login-shell"})]})]}),ct&&s.jsxs(s.Fragment,{children:[yt&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.chatDisplay"),divider:Gs,contentClassName:"space-y-6",children:[qe("chatRenderMode")&&s.jsx(Zs,{title:r("settings.openchamber.visual.section.chatRenderMode"),settingsItem:"chat.render-mode",children:s.jsx("div",{role:"radiogroup","aria-label":r("settings.openchamber.visual.section.chatRenderModeAria"),className:"grid w-full max-w-[26rem] grid-cols-1 gap-3 @xl:grid-cols-2",children:E1.map(R=>{const Tt=V===R.id,Ts=Er%12;return s.jsxs("button",{type:"button",onClick:()=>Fr(R.id),"aria-pressed":Tt,className:fe("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",Tt?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsx("span",{className:fe("typography-ui-label",Tt?"text-foreground":"text-muted-foreground"),children:o(R.labelKey)}),s.jsx("div",{className:"mt-2 w-full rounded-md border border-border/60 bg-muted/30 p-2",children:R.id==="live"?s.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(vs=>{const bn=vs*3+1,ta=Ts-bn+1,Ai=ta<=0?0:ta===1?42:ta===2?68:92,Ur=Ai>0;return s.jsxs("div",{className:fe("flex items-center gap-1.5 transition-all duration-300 motion-reduce:transition-none",Ur?"translate-y-0 opacity-100":"translate-y-1 opacity-0"),children:[s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-muted-foreground/55"}),s.jsx("span",{className:"h-1.5 rounded bg-muted-foreground/30 transition-all duration-300 motion-reduce:transition-none",style:{width:`${Ai}%`}})]},vs)})}):s.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(vs=>{const bn=Ts>=(vs+1)*3;return s.jsxs("div",{className:fe("flex items-center gap-1.5 transition-all duration-300 motion-reduce:transition-none",bn?"translate-y-0 opacity-100":"translate-y-1 opacity-0"),children:[s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-muted-foreground/55"}),s.jsx("span",{className:"h-1.5 rounded bg-muted-foreground/30",style:{width:"92%"}})]},vs)})})})]},R.id)})})}),qe("activityRenderMode")&&V==="sorted"&&s.jsx(Zs,{title:r("settings.openchamber.visual.section.activityDefault"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.activityDefaultAria"),children:D1.map(R=>s.jsx(zn,{selected:G===R.id,onSelect:()=>Or(R.id),label:o(R.labelKey),ariaLabel:r("settings.openchamber.visual.field.activityDefaultModeAria",{option:o(R.labelKey)})},R.id))})})]}),Gt&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.messageStreamTransport"),divider:yt||Gs,settingsItem:"chat.message-transport",contentClassName:"space-y-2",children:[s.jsx(Ys,{value:Ce,options:fd.map(R=>({value:R.id,label:o(R.labelKey)})),onChange:ha,"aria-label":r("settings.openchamber.visual.section.messageStreamTransport")}),(()=>{const R=fd.find(Tt=>Tt.id===Ce);return R?.descriptionKey?s.jsx("span",{className:"typography-meta text-muted-foreground",children:o(R.descriptionKey)}):null})()]}),Bs&&s.jsx(dt,{title:r("settings.openchamber.visual.section.chatMessageOptions"),divider:yt||Gt||Gs,children:s.jsxs(On,{className:"lg:gap-y-6",children:[qe("userMessageRendering")&&s.jsx(Zs,{title:r("settings.openchamber.visual.section.userMessageRendering"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.userMessageRenderingAria"),children:A1.map(R=>s.jsx(zn,{selected:M1(M)===R.id,onSelect:()=>Mr(R.id),label:o(R.labelKey),ariaLabel:r("settings.openchamber.visual.field.userMessageRenderingAria",{option:o(R.labelKey)})},R.id))})}),qe("mermaidRendering")&&s.jsx(Zs,{title:r("settings.openchamber.visual.section.mermaidRendering"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.mermaidRenderingAria"),children:P1.map(R=>s.jsx(zn,{selected:$===R.id,onSelect:()=>ys(R.id),label:o(R.labelKey),ariaLabel:r("settings.openchamber.visual.field.mermaidRenderingAria",{option:o(R.labelKey)})},R.id))})}),qe("diffLayout")&&!ms&&s.jsx(Zs,{title:r("settings.openchamber.visual.section.diffLayout"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.diffLayoutAria"),children:I1.map(R=>s.jsx(zn,{selected:We===R.id,onSelect:()=>_e(R.id),label:o(R.labelKey),ariaLabel:r("settings.openchamber.visual.field.diffLayoutAria",{option:o(R.labelKey)})},R.id))})}),qe("followUpBehavior")&&s.jsx(Zs,{title:r("settings.openchamber.visual.section.followUpBehavior"),settingsItem:"chat.follow-up-behavior",children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.followUpBehaviorAria"),children:R1.map(R=>s.jsx(zn,{selected:Te===R.id,onSelect:()=>Ue(R.id),label:o(R.labelKey),ariaLabel:r("settings.openchamber.visual.field.followUpBehaviorAria",{option:o(R.labelKey)})},R.id))})})]})}),us&&s.jsxs(s.Fragment,{children:[qe("expandedTools")&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.showToolsOpenedByDefault"),divider:yt||Gt||Bs||Gs,contentClassName:Ds,children:[s.jsx(Ct,{checked:Ee,onChange:Kr,label:r("settings.openchamber.visual.field.bash"),ariaLabel:r("settings.openchamber.visual.field.showExpandedBashToolsAria")}),s.jsx(Ct,{checked:Ze,onChange:Ni,label:r("settings.openchamber.visual.field.editTools"),ariaLabel:r("settings.openchamber.visual.field.showExpandedEditToolsAria")})]}),s.jsxs(dt,{title:r("settings.openchamber.visual.section.sessionAssistance"),settingsItem:"chat.session-assistance",contentClassName:Ds,children:[s.jsx(Ct,{checked:gt,onChange:rn,label:r("settings.openchamber.visual.field.draftStartersVisible"),ariaLabel:r("settings.openchamber.visual.field.draftStartersVisibleAria"),settingsItem:"chat.draft-starters-visible"}),qe("sessionAssist")&&s.jsxs(s.Fragment,{children:[s.jsx(Ct,{checked:m,onChange:b,label:r("settings.openchamber.visual.field.sessionRecap"),ariaLabel:r("settings.openchamber.visual.field.sessionRecapAria"),settingsItem:"chat.session-recap"}),s.jsx(Ct,{checked:w,onChange:g,label:r("settings.openchamber.visual.field.sessionSuggestion"),ariaLabel:r("settings.openchamber.visual.field.sessionSuggestionAria"),settingsItem:"chat.session-suggestion"})]}),qe("subagentReadOnlyBanner")&&s.jsx(Ct,{checked:nt,onChange:rt,label:r("settings.openchamber.visual.field.allowPromptingSubagentSessions"),ariaLabel:r("settings.openchamber.visual.field.allowPromptingSubagentSessionsAria"),settingsItem:"chat.subagent-read-only-banner"})]}),qe("sessionGoal")&&!ms&&s.jsxs(dt,{title:r("settings.openchamber.visual.goal.sectionTitle"),info:r("settings.openchamber.visual.goal.description"),contentClassName:Ds,children:[s.jsx(Ct,{checked:x,onChange:k,label:r("settings.openchamber.visual.field.sessionGoal"),ariaLabel:r("settings.openchamber.visual.field.sessionGoalAria"),settingsItem:"chat.session-goal"}),s.jsxs("div",{"data-settings-item":"chat.session-goal-budget",className:"flex items-center gap-2",children:[s.jsx(Ct,{checked:y,onChange:C,disabled:!x,label:r("settings.openchamber.visual.goal.budgetLabel"),ariaLabel:r("settings.openchamber.visual.goal.budgetAria")}),x&&y?s.jsx(Rs,{value:z,onValueChange:R=>{typeof R=="number"&&Number.isFinite(R)&&R>0&&j(Math.floor(R))},min:1e3,max:1e8,step:5e4}):null]})]}),qe("reasoning")&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.reasoning"),settingsItem:"chat.reasoning",contentClassName:Ds,children:[s.jsx(Ct,{checked:f,onChange:N,label:r("settings.openchamber.visual.field.showReasoningTraces"),ariaLabel:r("settings.openchamber.visual.field.showReasoningTracesAria"),settingsItem:"chat.reasoning-traces"}),f&&s.jsx(Ct,{checked:v,onChange:P,label:r("settings.openchamber.visual.field.collapsibleThinkingBlocks"),ariaLabel:r("settings.openchamber.visual.field.collapsibleThinkingBlocksAria")})]}),(qe("collapsibleUserMessages")||qe("stickyUserHeader")||qe("promptNavigatorEnabled")&&!ms||qe("wideChatLayout")||qe("splitAssistantMessageActions")||qe("codeBlockLineWrap"))&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.messageAppearance"),settingsItem:"chat.message-appearance",contentClassName:Ds,children:[qe("collapsibleUserMessages")&&s.jsx(Ct,{checked:F,onChange:hn,label:r("settings.openchamber.visual.field.collapsibleUserMessages"),ariaLabel:r("settings.openchamber.visual.field.collapsibleUserMessagesAria"),settingsItem:"chat.collapsible-user-messages"}),qe("stickyUserHeader")&&s.jsx(Ct,{checked:D,onChange:Lr,label:r("settings.openchamber.visual.field.stickyUserHeader"),ariaLabel:r("settings.openchamber.visual.field.stickyUserHeaderAria"),settingsItem:"chat.sticky-user-header"}),qe("promptNavigatorEnabled")&&!ms&&s.jsx(Ct,{checked:W,onChange:Ks,label:r("settings.openchamber.visual.field.promptNavigatorEnabled"),ariaLabel:r("settings.openchamber.visual.field.promptNavigatorEnabledAria"),settingsItem:"chat.prompt-navigator"}),qe("wideChatLayout")&&s.jsx(Ct,{checked:T,onChange:Dn,label:r("settings.openchamber.visual.field.wideChatLayout"),ariaLabel:r("settings.openchamber.visual.field.wideChatLayoutAria"),settingsItem:"chat.wide-layout"}),qe("splitAssistantMessageActions")&&s.jsx(Ct,{checked:Se,onChange:wl,label:r("settings.openchamber.visual.field.showSplitAssistantMessageActions"),ariaLabel:r("settings.openchamber.visual.field.showSplitAssistantMessageActionsAria"),settingsItem:"chat.inline-assistant-actions",info:r("settings.openchamber.visual.field.showSplitAssistantMessageActionsTooltip")}),qe("codeBlockLineWrap")&&s.jsx(Ct,{checked:B,onChange:L,label:r("settings.openchamber.visual.field.codeBlockLineWrap"),ariaLabel:r("settings.openchamber.visual.field.codeBlockLineWrapAria"),settingsItem:"chat.code-block-line-wrap"})]}),(qe("showToolFileIcons")||qe("showTurnChangedFiles")||qe("dotfiles")&&!ds()||qe("fileViewerPreview"))&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.toolsAndFiles"),settingsItem:"chat.tools-and-files",contentClassName:Ds,children:[qe("showToolFileIcons")&&s.jsx(Ct,{checked:h,onChange:zr,label:r("settings.openchamber.visual.field.showToolFileIcons"),ariaLabel:r("settings.openchamber.visual.field.showToolFileIconsAria"),settingsItem:"chat.tool-file-icons"}),qe("showTurnChangedFiles")&&s.jsx(Ct,{checked:ye,onChange:xa,label:r("settings.openchamber.visual.field.showTurnChangedFiles"),ariaLabel:r("settings.openchamber.visual.field.showTurnChangedFilesAria"),settingsItem:"chat.changed-files"}),qe("dotfiles")&&!ds()&&s.jsx(Ct,{checked:u,onChange:Vg,label:r("settings.openchamber.visual.field.showDotfiles"),ariaLabel:r("settings.openchamber.visual.field.showDotfilesAria"),settingsItem:"chat.dotfiles"}),qe("fileViewerPreview")&&s.jsx(Ct,{checked:Xe,onChange:ba,label:r("settings.openchamber.defaults.field.openFilesPreview"),ariaLabel:r("settings.openchamber.defaults.field.openFilesPreviewAria")})]}),(qe("persistDraft")||!d&&qe("inputSpellcheck"))&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.composer"),settingsItem:"chat.composer",contentClassName:Ds,children:[qe("persistDraft")&&s.jsx(Ct,{checked:Ye,onChange:q,label:r("settings.openchamber.visual.field.persistDraftMessages"),ariaLabel:r("settings.openchamber.visual.field.persistDraftMessagesAria"),settingsItem:"chat.persist-drafts"}),!d&&qe("inputSpellcheck")&&s.jsx(Ct,{checked:re,onChange:Rn,label:r("settings.openchamber.visual.field.enableSpellcheckInTextInputs"),ariaLabel:r("settings.openchamber.visual.field.enableSpellcheckInTextInputsAria"),settingsItem:"chat.spellcheck"})]})]})]}),qe("reportUsage")&&s.jsx(dt,{title:r("settings.openchamber.visual.section.privacy"),children:s.jsx(Ct,{checked:Ja,onChange:ji,label:r("settings.openchamber.visual.field.sendAnonymousUsageReports"),info:r("settings.openchamber.visual.field.sendAnonymousUsageReportsHint"),ariaLabel:r("settings.openchamber.visual.field.sendAnonymousUsageReportsAria"),settingsItem:"appearance.usage-reports"})})]})},O1=1,z1=365,bd=30,K1=[{value:"archive",labelKey:"settings.openchamber.sessionRetention.action.archive"},{value:"delete",labelKey:"settings.openchamber.sessionRetention.action.delete"}],sm=()=>{const t=tt.c(87),{t:e}=lt(),n=ke(B1),a=ke(_1),i=ke(U1),r=ke($1),o=ke(V1),d=ke(H1);let c;t[0]===Symbol.for("react.memo_cache_sentinel")?(c={autoRun:!1},t[0]=c):c=t[0];const{candidates:p,isRunning:u,runCleanup:f,action:m}=Kp(c),w=p.length;let b;t[1]!==f||t[2]!==e?(b=async()=>{const ue=await f({force:!0});if(ue.completedIds.length===0&&ue.failedIds.length===0){J.message(ue.action==="archive"?e("settings.openchamber.sessionRetention.toast.noneEligibleArchive"):e("settings.openchamber.sessionRetention.toast.noneEligibleDelete"));return}ue.completedIds.length>0&&J.success(ue.action==="archive"?e("settings.openchamber.sessionRetention.toast.archivedCount",{count:ue.completedIds.length}):e("settings.openchamber.sessionRetention.toast.deletedCount",{count:ue.completedIds.length})),ue.failedIds.length>0&&J.error(ue.action==="archive"?e("settings.openchamber.sessionRetention.toast.failedArchiveCount",{count:ue.failedIds.length}):e("settings.openchamber.sessionRetention.toast.failedDeleteCount",{count:ue.failedIds.length}))},t[1]=f,t[2]=e,t[3]=b):b=t[3];const g=b;let x;t[4]!==e?(x=e("settings.openchamber.sessionRetention.title"),t[4]=e,t[5]=x):x=t[5];let k;t[6]!==e?(k=e("settings.openchamber.sessionRetention.tooltip"),t[6]=e,t[7]=k):k=t[7];let y;t[8]!==e?(y=e("settings.openchamber.sessionRetention.field.enableAutoCleanup"),t[8]=e,t[9]=y):y=t[9];let C;t[10]!==e?(C=e("settings.openchamber.sessionRetention.field.enableAutoCleanupAria"),t[10]=e,t[11]=C):C=t[11];let z;t[12]!==n||t[13]!==r||t[14]!==y||t[15]!==C?(z=s.jsx(Ct,{settingsItem:"sessions.auto-cleanup",checked:n,onChange:r,label:y,ariaLabel:C}),t[12]=n,t[13]=r,t[14]=y,t[15]=C,t[16]=z):z=t[16];let j;t[17]!==e?(j=e("settings.openchamber.sessionRetention.field.retentionPeriod"),t[17]=e,t[18]=j):j=t[18];let N;t[19]!==e?(N=e("settings.openchamber.sessionRetention.field.retentionPeriodAria"),t[19]=e,t[20]=N):N=t[20];let v;t[21]!==a||t[22]!==o||t[23]!==N?(v=s.jsx(Rs,{value:a,onValueChange:o,min:O1,max:z1,step:1,"aria-label":N,className:"w-20 tabular-nums"}),t[21]=a,t[22]=o,t[23]=N,t[24]=v):v=t[24];let P;t[25]!==e?(P=e("settings.openchamber.sessionRetention.field.days"),t[25]=e,t[26]=P):P=t[26];let $;t[27]!==P?($=s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:P}),t[27]=P,t[28]=$):$=t[28];let O;t[29]!==o?(O=()=>o(bd),t[29]=o,t[30]=O):O=t[30];const M=a===bd;let S;t[31]!==e?(S=e("settings.openchamber.sessionRetention.actions.resetRetentionAria"),t[31]=e,t[32]=S):S=t[32];let F;t[33]!==e?(F=e("settings.common.actions.reset"),t[33]=e,t[34]=F):F=t[34];let E;t[35]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"}),t[35]=E):E=t[35];let D;t[36]!==O||t[37]!==M||t[38]!==S||t[39]!==F?(D=s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:O,disabled:M,className:Is,"aria-label":S,title:F,children:E}),t[36]=O,t[37]=M,t[38]=S,t[39]=F,t[40]=D):D=t[40];let W;t[41]!==$||t[42]!==D||t[43]!==j||t[44]!==v?(W=s.jsxs(Xt,{settingsItem:"sessions.retention-period",label:j,children:[v,$,D]}),t[41]=$,t[42]=D,t[43]=j,t[44]=v,t[45]=W):W=t[45];let H;t[46]!==e?(H=e("settings.openchamber.sessionRetention.field.whenSessionsExpire"),t[46]=e,t[47]=H):H=t[47];let Z;t[48]!==e?(Z=K1.map(ue=>({value:ue.value,label:e(ue.labelKey)})),t[48]=e,t[49]=Z):Z=t[49];let Y;t[50]!==i||t[51]!==d||t[52]!==Z?(Y=s.jsx(Ys,{value:i,onChange:d,options:Z}),t[50]=i,t[51]=d,t[52]=Z,t[53]=Y):Y=t[53];let A;t[54]!==H||t[55]!==Y?(A=s.jsx(Xt,{settingsItem:"sessions.retention-action",label:H,children:Y}),t[54]=H,t[55]=Y,t[56]=A):A=t[56];let X;t[57]!==W||t[58]!==A?(X=s.jsxs(la,{className:"space-y-0",children:[W,A]}),t[57]=W,t[58]=A,t[59]=X):X=t[59];let te;t[60]!==e?(te=e("settings.openchamber.sessionRetention.manualCleanup.title"),t[60]=e,t[61]=te):te=t[61];let T;t[62]!==u||t[63]!==e?(T=e(u?"settings.openchamber.sessionRetention.actions.cleaningUp":"settings.openchamber.sessionRetention.actions.runCleanupNow"),t[62]=u,t[63]=e,t[64]=T):T=t[64];let I;t[65]!==g||t[66]!==u||t[67]!==T?(I=s.jsx(ee,{type:"button",variant:"outline",size:"xs",onClick:g,disabled:u,className:"!font-normal",children:T}),t[65]=g,t[66]=u,t[67]=T,t[68]=I):I=t[68];let B;t[69]!==te||t[70]!==I?(B=s.jsx(Xt,{label:te,children:I}),t[69]=te,t[70]=I,t[71]=B):B=t[71];let L;t[72]!==m||t[73]!==w||t[74]!==e?(L=m==="archive"?e("settings.openchamber.sessionRetention.manualCleanup.eligibleArchiveNow",{count:w}):e("settings.openchamber.sessionRetention.manualCleanup.eligibleDeleteNow",{count:w}),t[72]=m,t[73]=w,t[74]=e,t[75]=L):L=t[75];let V;t[76]!==L?(V=s.jsx("p",{className:"typography-meta text-muted-foreground",children:L}),t[76]=L,t[77]=V):V=t[77];let Q;t[78]!==B||t[79]!==V?(Q=s.jsxs("div",{className:"mt-1 py-1.5 space-y-1",children:[B,V]}),t[78]=B,t[79]=V,t[80]=Q):Q=t[80];let G;return t[81]!==x||t[82]!==X||t[83]!==k||t[84]!==Q||t[85]!==z?(G=s.jsxs(dt,{title:x,info:k,children:[z,X,Q]}),t[81]=x,t[82]=X,t[83]=k,t[84]=Q,t[85]=z,t[86]=G):G=t[86],G};function B1(t){return t.autoDeleteEnabled}function _1(t){return t.autoDeleteAfterDays}function U1(t){return t.sessionRetentionAction}function $1(t){return t.setAutoDeleteEnabled}function V1(t){return t.setAutoDeleteAfterDays}function H1(t){return t.setSessionRetentionAction}const yd=(t,e,n)=>!t||!Number.isFinite(t)?e:new Intl.DateTimeFormat(jr(),{dateStyle:"medium",timeStyle:"short",hour12:n==="auto"?void 0:n==="12h"}).format(t),nm=()=>{const{t}=lt(),e=ke(v=>v.timeFormatPreference),[n,a]=l.useState(!1),[i,r]=l.useState(!0),[o,d]=l.useState(!1),[c,p]=l.useState(null),[u,f]=l.useState(!1),[m,w]=l.useState([]),[b,g]=l.useState(Bp),[x,k]=l.useState(""),y=l.useMemo(()=>_p(),[]),C=l.useCallback(async()=>{r(!0),k("");try{const v=await Up();w(v)}catch(v){const P=v instanceof Error?v.message:t("settings.openchamber.passkeys.toast.loadFailed");k(P)}finally{r(!1)}},[t]);l.useEffect(()=>{let v=!1;return(async()=>{try{if(!y.supported){v||(a(!1),r(!1));return}v||a(!0)}catch{v||a(!1)}if(!v){const P=await Vr();if(g(P),!P.enabled){w([]),r(!1);return}await C()}})(),()=>{v=!0,Al()}},[C,y.supported]);const z=l.useCallback(async()=>{if(!b.enabled){const v=t("settings.openchamber.passkeys.toast.enableUiPasswordFirst");k(v),J.message(v);return}if(!n){k(y.reason),J.message(y.reason);return}if(o){Al(),d(!1);return}k(""),d(!0);try{await $p(),g(await Vr()),await C(),J.success(t("settings.openchamber.passkeys.toast.added"))}catch(v){if(Vp(v)){J.message(t("settings.openchamber.passkeys.toast.setupCanceled"));return}const P=v instanceof Error?v.message:t("settings.openchamber.passkeys.toast.addFailed");k(P),J.error(P)}finally{d(!1)}},[o,C,b.enabled,y.reason,n,t]),j=l.useCallback(async v=>{p(v),k("");try{await Hp(v),g(await Vr()),await C(),J.success(t("settings.openchamber.passkeys.toast.removed"))}catch(P){const $=P instanceof Error?P.message:t("settings.openchamber.passkeys.toast.removeFailed");k($),J.error($)}finally{p(null)}},[C,t]),N=l.useCallback(async()=>{f(!0),k("");try{await Wp(),window.location.reload()}catch(v){const P=v instanceof Error?v.message:t("settings.openchamber.passkeys.toast.clearAuthFailed");k(P),J.error(P),f(!1)}},[t]);return s.jsxs(dt,{title:t("settings.openchamber.passkeys.title"),children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Xt,{label:t("settings.openchamber.passkeys.field.currentDevice"),children:[s.jsx(ee,{type:"button",variant:o?"secondary":"outline",size:"xs",onClick:()=>{z()},disabled:i||u,className:"!font-normal",children:t(o?"settings.openchamber.passkeys.actions.cancelSetup":"settings.openchamber.passkeys.actions.add")}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>{N()},disabled:i||o||u,className:"!font-normal text-muted-foreground hover:text-foreground",children:t(u?"settings.openchamber.passkeys.actions.signingOut":"settings.openchamber.passkeys.actions.signOutEverywhere")})]}),!b.enabled&&s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.openchamber.passkeys.state.uiPasswordRequired")}),b.enabled&&!n&&s.jsx("p",{className:"typography-meta text-muted-foreground",children:y.reason}),i?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.openchamber.passkeys.state.loading")}):m.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.openchamber.passkeys.state.noneSaved")}):s.jsx("div",{className:"space-y-1 pt-1",children:m.map(v=>s.jsxs(Xt,{label:s.jsx("span",{className:"truncate",children:v.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:v.lastUsedAt?t("settings.openchamber.passkeys.item.lastUsed",{time:yd(v.lastUsedAt,t("settings.openchamber.passkeys.time.neverUsed"),e)}):t("settings.openchamber.passkeys.item.added",{time:yd(v.createdAt,t("settings.openchamber.passkeys.time.neverUsed"),e)})}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>{j(v.id)},disabled:c===v.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:c===v.id?t("settings.openchamber.passkeys.actions.removing"):t("settings.common.actions.delete")})]},v.id))})]}),x&&s.jsx("div",{className:"mt-1 py-1.5",children:s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:x})})]})},co=t=>{const e=Hn(t);return e||{providerId:"",modelId:""}},am=()=>{const{t}=lt(),e=pt(L=>L.setProvider),n=pt(L=>L.setModel),a=pt(L=>L.setAgent),i=pt(L=>L.setCurrentVariant),r=pt(L=>L.setSettingsDefaultModel),o=pt(L=>L.setSettingsDefaultVariant),d=pt(L=>L.setSettingsDefaultAgent),c=ke(L=>L.showDeletionDialog),p=ke(L=>L.setShowDeletionDialog),u=pt(L=>L.providers),f=pt(L=>L.modelsMetadata),[m,w]=l.useState(),[b,g]=l.useState(),[x,k]=l.useState(),[y,C]=l.useState(!0),[z,j]=l.useState(),[N,v]=l.useState(),[P,$]=l.useState(),[O,M]=l.useState(!0),S=l.useMemo(()=>co(m),[m]);l.useEffect(()=>{(async()=>{try{let V=null;if(!V){const Q=nn()?.settings;if(Q)try{const ue=(await Q.load())?.settings;if(ue){const ne=ue;V={defaultModel:typeof ue.defaultModel=="string"?ue.defaultModel:void 0,defaultVariant:typeof ne.defaultVariant=="string"?ne.defaultVariant:void 0,defaultAgent:typeof ue.defaultAgent=="string"?ue.defaultAgent:void 0,smallModelUseDefault:typeof ne.smallModelUseDefault=="boolean"?ne.smallModelUseDefault:void 0,smallModelOverride:typeof ne.smallModelOverride=="string"?ne.smallModelOverride:void 0,walkthroughModelOverride:typeof ne.walkthroughModelOverride=="string"?ne.walkthroughModelOverride:void 0}}}catch{}}if(!V){const Q=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});Q.ok&&(V=await Q.json())}if(V){const Q=typeof V.defaultModel=="string"&&V.defaultModel.trim().length>0?V.defaultModel.trim():void 0,G=typeof V.defaultVariant=="string"&&V.defaultVariant.trim().length>0?V.defaultVariant.trim():void 0,ue=typeof V.defaultAgent=="string"&&V.defaultAgent.trim().length>0?V.defaultAgent.trim():void 0;Q!==void 0&&w(Q),G!==void 0&&g(G),ue!==void 0&&k(ue),typeof V.smallModelUseDefault=="boolean"&&C(V.smallModelUseDefault),typeof V.smallModelOverride=="string"&&V.smallModelOverride.trim()&&j(V.smallModelOverride.trim()),typeof V.walkthroughModelOverride=="string"&&V.walkthroughModelOverride.trim()&&$(V.walkthroughModelOverride.trim())}}catch(V){console.warn("Failed to load defaults settings:",V)}finally{M(!1)}})()},[]);const F=l.useCallback(async(L,V)=>{const Q=L&&V?`${L}/${V}`:void 0;w(Q),g(void 0),o(void 0),i(void 0),r(Q),L&&V&&u.find(ue=>ue.id===L)&&(e(L),n(V));try{await It({defaultModel:Q??"",defaultVariant:""});const G=await ht("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:Q})});G.ok||console.warn("Failed to save default model to server:",G.status,G.statusText)}catch(G){console.warn("Failed to save default model:",G)}},[u,i,n,e,r,o]),E="__default__",D=l.useCallback(L=>L===E?t("settings.openchamber.defaults.option.default"):L.charAt(0).toUpperCase()+L.slice(1),[t]),W=l.useCallback(async L=>{const V=L===E?void 0:L||void 0;g(V),o(V),i(V);try{await It({defaultVariant:V??""})}catch(Q){console.warn("Failed to save default variant:",Q)}},[i,o]),H=l.useCallback(async L=>{const V=L||void 0;k(V),d(V),L&&a(L);try{await It({defaultAgent:V??""})}catch(Q){console.warn("Failed to save default agent:",Q)}},[a,d]),Z=l.useCallback(async L=>{C(L);try{await It({smallModelUseDefault:L})}catch(V){console.warn("Failed to save small model preference:",V)}},[]),Y=l.useCallback(async(L,V)=>{const Q=L&&V?`${L}/${V}`:void 0;j(Q);try{await It({smallModelOverride:Q??""})}catch(G){console.warn("Failed to save small model override:",G)}},[]),A=l.useCallback(async(L,V)=>{const Q=L&&V?`${L}/${V}`:void 0;$(Q);try{await It({walkthroughModelOverride:Q??""})}catch(G){console.warn("Failed to save walkthrough model override:",G)}},[]),X=l.useCallback((L,V)=>f.get(`${L}/${V}`)?.structured_output!==!1,[f]),te=l.useMemo(()=>co(z),[z]),T=l.useMemo(()=>co(P),[P]);l.useEffect(()=>{if(N!==void 0)return;let L=!1;return(async()=>{try{const V=await ht("/api/small-model",{method:"GET",headers:{Accept:"application/json"}});if(!V.ok)return;const Q=await V.json().catch(()=>null);!L&&Array.isArray(Q?.authenticatedProviders)&&v(Q.authenticatedProviders.filter(G=>typeof G=="string"))}catch{}})(),()=>{L=!0}},[N]);const I=l.useMemo(()=>{if(!S.providerId||!S.modelId)return[];const Q=u.find(G=>G.id===S.providerId)?.models.find(G=>G.id===S.modelId)?.variants;return Q?Object.keys(Q):[]},[S.modelId,S.providerId,u]),B=I.length>0;return l.useEffect(()=>{!B&&b&&(g(void 0),o(void 0),i(void 0),It({defaultVariant:""}).catch(()=>{}))},[b,i,o,B]),O?null:s.jsx(s.Fragment,{children:s.jsx(dt,{title:t("settings.openchamber.defaults.title"),divider:!1,children:s.jsxs("div",{className:"space-y-0",children:[s.jsxs("div",{className:"mt-0 mb-1 typography-meta text-muted-foreground",children:[t("settings.openchamber.defaults.summaryPrefix")," ",S.providerId?s.jsxs("span",{className:"text-foreground",children:[S.providerId,"/",S.modelId,B?` (${b??t("settings.openchamber.defaults.option.defaultLowercase")})`:""]}):s.jsx("span",{className:"text-foreground",children:t("settings.openchamber.defaults.summaryOpenCodeDefault")}),x&&s.jsxs(s.Fragment,{children:[" / ",s.jsx("span",{className:"text-foreground",children:x})]})]}),s.jsxs("div",{children:[s.jsx(Xt,{settingsItem:"sessions.default-model",label:t("settings.openchamber.defaults.field.defaultModel"),children:s.jsx(oa,{providerId:S.providerId,modelId:S.modelId,onChange:F,className:$n})}),s.jsx(Xt,{settingsItem:"sessions.default-thinking",label:t("settings.openchamber.defaults.field.defaultThinking"),children:s.jsxs(Lt,{value:b??E,onValueChange:W,disabled:!B,children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{placeholder:t("settings.openchamber.defaults.field.thinkingPlaceholder"),children:D(b??E)})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:E,children:t("settings.openchamber.defaults.option.default")}),I.map(L=>s.jsx(kt,{value:L,children:D(L)},L))]})]})}),s.jsx(Xt,{settingsItem:"sessions.default-agent",label:t("settings.openchamber.defaults.field.defaultAgent"),children:s.jsx(rl,{agentName:x||"",onChange:H,className:$n})})]}),s.jsx(la,{className:Ds,children:s.jsx(Ct,{settingsItem:"sessions.deletion-dialog",checked:c,onChange:p,label:t("settings.openchamber.defaults.field.showDeletionDialog"),ariaLabel:t("settings.openchamber.defaults.field.showDeletionDialogAria")})}),s.jsxs("div",{className:"space-y-3 pt-6",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(pn,{children:t("settings.openchamber.defaults.smallModel.title")}),s.jsx($t,{children:t("settings.openchamber.defaults.smallModel.description")})]}),s.jsx(Ct,{settingsItem:"sessions.small-model",checked:y,onChange:L=>{Z(L)},label:t("settings.openchamber.defaults.smallModel.useDefault"),ariaLabel:t("settings.openchamber.defaults.smallModel.useDefaultAria")}),y?null:s.jsx(Xt,{label:t("settings.openchamber.defaults.smallModel.overrideModel"),children:s.jsx(oa,{providerId:te.providerId,modelId:te.modelId,onChange:Y,allowedProviderIds:N,className:$n})}),s.jsxs(la,{className:Ds,children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(pn,{children:t("settings.openchamber.defaults.walkthroughModel.title")}),s.jsx($t,{children:t("settings.openchamber.defaults.walkthroughModel.description")})]}),s.jsx(Xt,{settingsItem:"sessions.walkthrough-model",label:t("settings.openchamber.defaults.walkthroughModel.overrideModel"),children:s.jsx(oa,{providerId:T.providerId,modelId:T.modelId,onChange:A,allowedProviderIds:N,isModelAllowed:X,placeholder:t("settings.openchamber.defaults.walkthroughModel.usesSmallModel"),className:$n})})]})]})]})})})},vd={completion:{titleKey:"settings.notifications.page.template.defaults.completion.title",messageKey:"settings.notifications.page.template.defaults.completion.message"},error:{titleKey:"settings.notifications.page.template.defaults.error.title",messageKey:"settings.notifications.page.template.defaults.error.message"},question:{titleKey:"settings.notifications.page.template.defaults.question.title",messageKey:"settings.notifications.page.template.defaults.question.message"},subtask:{titleKey:"settings.notifications.page.template.defaults.subtask.title",messageKey:"settings.notifications.page.template.defaults.subtask.message"}},W1={completion:"settings.notifications.page.template.event.completion",subtask:"settings.notifications.page.template.event.subtask",error:"settings.notifications.page.template.event.error",question:"settings.notifications.page.template.event.question"},G1=()=>{const{t}=lt(),e=l.useMemo(()=>ls(),[]),n=l.useMemo(()=>ds(),[]),a=l.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),i=!e&&!n&&!a,r=ke(T=>T.nativeNotificationsEnabled),o=ke(T=>T.setNativeNotificationsEnabled),d=ke(T=>T.notificationMode),c=ke(T=>T.setNotificationMode),p=ke(T=>T.notifyOnSubtasks),u=ke(T=>T.setNotifyOnSubtasks),f=ke(T=>T.notifyOnCompletion),m=ke(T=>T.setNotifyOnCompletion),w=ke(T=>T.notifyOnError),b=ke(T=>T.setNotifyOnError),g=ke(T=>T.notifyOnQuestion),x=ke(T=>T.setNotifyOnQuestion),k=ke(T=>T.notificationTemplates),y=ke(T=>T.setNotificationTemplates),[C,z]=l.useState("default"),[j,N]=l.useState(!1),[v,P]=l.useState(!1),[$,O]=l.useState(!1);l.useEffect(()=>{if(!i){N(!1),P(!1);return}typeof Notification<"u"&&z(Notification.permission);const T=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;N(T),(async()=>{if(!T){P(!1);return}try{const B=await navigator.serviceWorker.getRegistration();if(!B){P(!1);return}const L=await B.pushManager.getSubscription();P(!!L)}catch{P(!1)}})()},[i]);const M=async T=>{if(e){o(T);return}if(!i){o(T);return}if(T&&typeof Notification<"u"&&Notification.permission==="default")try{const I=await Notification.requestPermission();z(I),I==="granted"?o(!0):J.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.description")})}catch(I){console.error("Failed to request notification permission:",I),J.error(t("settings.notifications.page.toast.requestPermissionFailed"))}else o(!!(T&&C==="granted"))},S=e||n||a||i&&typeof Notification<"u"&&Notification.permission==="granted",F=(T,I,B)=>{y({...k,[T]:{...k[T],[I]:B}})},E=T=>{const I="=".repeat((4-T.length%4)%4),B=(T+I).replace(/-/g,"+").replace(/_/g,"/"),L=atob(B),V=new Uint8Array(L.length);for(let Q=0;Q<L.length;Q+=1)V[Q]=L.charCodeAt(Q);return V},D=async(T,I,B)=>{let L=null;const V=new Promise((Q,G)=>{L=setTimeout(()=>{G(new Error(B))},I)});try{return await Promise.race([T,V])}finally{L&&clearTimeout(L)}},W=async T=>{if(T.active)return;const I=T.installing||T.waiting;I&&I.state!=="activated"&&await D(new Promise(B=>{const L=()=>{I.state==="activated"&&(I.removeEventListener("statechange",L),B())};I.addEventListener("statechange",L),L()}),15e3,"Service worker activation timed out")},H=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const T=[{label:"no-options",opts:null},{label:"scope-root",opts:{scope:"/"}},{label:"type-classic",opts:{type:"classic"}},{label:"type-classic-scope",opts:{type:"classic",scope:"/"}},{label:"updateViaCache-none",opts:{type:"classic",updateViaCache:"none",scope:"/"}}];let I=null;for(const B of T)try{const L=B.opts?navigator.serviceWorker.register("/sw.js",B.opts):navigator.serviceWorker.register("/sw.js");return await D(L,1e4,`Service worker registration timed out (${B.label})`)}catch(L){I=L}throw I instanceof Error?I:new Error("Service worker registration failed")},Z=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const T=await navigator.serviceWorker.getRegistration();if(T)return T;const I=await H();try{await I.update()}catch{}return await W(I),I},Y=T=>{const I=T,B=[`type=${typeof T}`,`toString=${String(T)}`,`name=${String(I?.name??"")}`,`message=${String(I?.message??"")}`];let L="";try{L=JSON.stringify(T)}catch{}return{summary:B.filter(Boolean).join(" | "),json:L,stack:typeof I?.stack=="string"?I.stack:""}},A=async()=>{const T=nn();if(!T?.notifications){J.error(t("settings.notifications.page.toast.notificationsApiUnavailable"));return}try{await T.notifications.notifyAgentCompletion({title:t("settings.notifications.page.testNotification.title"),body:t("settings.notifications.page.testNotification.body"),tag:"openchamber-test"})?J.success(t("settings.notifications.page.toast.testNotificationSent")):J.error(t("settings.notifications.page.toast.testNotificationFailed"))}catch(I){console.error("Test notification failed:",I),J.error(t("settings.notifications.page.toast.testNotificationFailed"))}},X=async()=>{if(!j){J.error(t("settings.notifications.page.toast.pushUnsupported"));return}const T=nn();if(!T?.push){J.error(t("settings.notifications.page.toast.pushApiUnavailable"));return}O(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const ne=await Notification.requestPermission();if(z(ne),ne!=="granted"){J.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.enableInBrowser")});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){J.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.enableInBrowser")});return}const I=await T.push.getVapidPublicKey();if(!I?.publicKey){J.error(t("settings.notifications.page.toast.pushKeyLoadFailed"));return}const B=await Z();await W(B);const L=await B.pushManager.getSubscription();if(!("pushManager"in B)||!B.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const Q=(L??await D(B.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:E(I.publicKey)}),15e3,"Push subscription timed out")).toJSON(),G=Q.keys;if(!Q.endpoint||!G?.p256dh||!G.auth)throw new Error("Push subscription missing keys");if(!(await D(T.push.subscribe({endpoint:Q.endpoint,keys:{p256dh:G.p256dh,auth:G.auth},origin:typeof window<"u"?window.location.origin:void 0,platform:cu()}),15e3,"Push subscribe request timed out"))?.ok){J.error(t("settings.notifications.page.toast.enableBackgroundFailed"));return}P(!0),J.success(t("settings.notifications.page.toast.backgroundEnabled"))}catch(I){console.error("[Push] Enable failed:",I);const B=Y(I);J.error(t("settings.notifications.page.toast.enableBackgroundFailed"),{description:B.summary})}finally{O(!1)}},te=async()=>{if(!j){P(!1);return}const T=nn();if(!T?.push){J.error(t("settings.notifications.page.toast.pushApiUnavailable"));return}O(!0);try{const B=await(await Z()).pushManager.getSubscription();if(!B){P(!1);return}const L=B.endpoint;await B.unsubscribe(),await T.push.unsubscribe({endpoint:L}),P(!1),J.success(t("settings.notifications.page.toast.backgroundDisabled"))}finally{O(!1)}};return s.jsxs(s.Fragment,{children:[s.jsxs(dt,{settingsItem:"notifications.delivery",title:t("settings.notifications.page.delivery.title"),divider:!1,children:[s.jsxs("div",{className:Ds,children:[s.jsx(Ct,{checked:r&&S,onChange:T=>{M(T)},label:t("settings.notifications.page.delivery.enableLabel"),info:i?t("settings.notifications.page.delivery.browserPermissionHint"):n?t("settings.notifications.page.delivery.vscodeHint"):void 0,ariaLabel:t("settings.notifications.page.delivery.enableAria")}),r&&S&&!a&&s.jsxs(s.Fragment,{children:[s.jsx(Ct,{checked:d==="always",onChange:T=>c(T?"always":"hidden-only"),label:t("settings.notifications.page.delivery.focusedLabel"),ariaLabel:t("settings.notifications.page.delivery.focusedAria")}),s.jsx("div",{className:"py-2",children:s.jsx(ee,{type:"button",variant:"outline",size:"sm",onClick:()=>{A()},children:t("settings.notifications.page.delivery.testAction")})})]})]}),i&&s.jsxs("div",{className:"mt-1",children:[C==="denied"&&s.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:t("settings.notifications.page.delivery.permissionDenied")}),C==="granted"&&!r&&s.jsx("p",{className:"typography-meta text-muted-foreground/70 mt-1",children:t("settings.notifications.page.delivery.permissionGrantedButDisabled")})]})]}),r&&S&&s.jsxs(s.Fragment,{children:[s.jsx(dt,{settingsItem:"notifications.events",title:t("settings.notifications.page.events.title"),children:s.jsxs("div",{className:Ds,children:[s.jsx(Ct,{checked:f,onChange:m,label:t("settings.notifications.page.events.completionLabel"),ariaLabel:t("settings.notifications.page.events.completionAria")}),s.jsx(Ct,{checked:p,onChange:u,label:t("settings.notifications.page.events.subtaskLabel"),ariaLabel:t("settings.notifications.page.events.subtaskAria")}),s.jsx(Ct,{checked:w,onChange:b,label:t("settings.notifications.page.events.errorLabel"),ariaLabel:t("settings.notifications.page.events.errorAria")}),s.jsx(Ct,{checked:g,onChange:x,label:t("settings.notifications.page.events.questionLabel"),ariaLabel:t("settings.notifications.page.events.questionAria")})]})}),!a&&s.jsx(dt,{title:t("settings.notifications.page.template.title"),description:s.jsxs(s.Fragment,{children:[t("settings.notifications.page.template.variablesLabel")," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{project_name}"})," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{worktree}"})," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{branch}"})," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{session_name}"})," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{agent_name}"})," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{model_name}"})," ",s.jsx("code",{className:"text-[var(--primary-base)]",children:"{last_message}"})]}),children:s.jsx(On,{className:"gap-2 md:grid-cols-2 md:gap-3 lg:gap-3",children:["completion","subtask","error","question"].map(T=>s.jsxs("section",{className:"p-2",children:[s.jsx(pn,{className:"capitalize",children:t(W1[T])}),s.jsxs("div",{className:"mt-1.5 space-y-2",children:[s.jsxs("div",{children:[s.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:t("settings.notifications.page.template.field.title")}),s.jsx(at,{value:k[T].title,onChange:I=>F(T,"title",I.target.value),className:"h-7",placeholder:t(vd[T].titleKey)})]}),s.jsxs("div",{children:[s.jsx("label",{className:"typography-micro text-muted-foreground block mb-1",children:t("settings.notifications.page.template.field.message")}),s.jsx(at,{value:k[T].message,onChange:I=>F(T,"message",I.target.value),className:"h-7",placeholder:t(vd[T].messageKey)})]})]})]},T))})})]}),i&&s.jsx(dt,{settingsItem:"notifications.push",title:t("settings.notifications.page.push.title"),children:s.jsx(Ct,{checked:j?v:!1,disabled:!j||$,onChange:T=>{T?X():te()},label:t("settings.notifications.page.push.enableLabel"),description:j?void 0:t("settings.notifications.page.push.unsupportedHint"),info:j?t("settings.notifications.page.push.supportedHint"):void 0,ariaLabel:t("settings.notifications.page.push.enableAria"),labelAccessory:$?s.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-current text-muted-foreground animate-busy-pulse","aria-label":t("settings.notifications.page.push.loadingAria")}):null})})]})},Fs=t=>{if(!t)return;t.pause();const{src:e}=t;e.startsWith("blob:")&&URL.revokeObjectURL(e),t.removeAttribute("src"),t.load()},q1=[{id:"parakeet-tdt-0.6b-v2-int8",labelKey:"settings.voice.page.stt.model.parakeetV2",badgeKey:"settings.voice.page.stt.badge.bestForEnglish",accuracy:5,speed:5,size:"460 MB"},{id:"parakeet-tdt-0.6b-v3-int8",labelKey:"settings.voice.page.stt.model.parakeetV3",badgeKey:"settings.voice.page.stt.badge.bestForMultilingual",accuracy:5,speed:4,size:"465 MB"},{id:"whisper-base-int8",labelKey:"settings.voice.page.stt.model.whisperBase",badgeKey:null,accuracy:3,speed:3,size:"200 MB"},{id:"whisper-tiny-int8",labelKey:"settings.voice.page.stt.model.whisperTiny",badgeKey:null,accuracy:2,speed:4,size:"115 MB"}],wd=t=>{const e=tt.c(8),{value:n,label:a}=t,i=`${a}: ${n}/5`,r=`${n/5*100}%`;let o;e[0]!==r?(o=s.jsx("span",{className:"h-1.5 w-12 flex-shrink-0 overflow-hidden rounded-full bg-[var(--interactive-border)]","aria-hidden":"true",children:s.jsx("span",{className:"block h-full rounded-full bg-[var(--primary-base)]",style:{width:r}})}),e[0]=r,e[1]=o):o=e[1];let d;e[2]!==a?(d=s.jsx("span",{className:"typography-ui-compact text-muted-foreground",children:a}),e[2]=a,e[3]=d):d=e[3];let c;return e[4]!==i||e[5]!==o||e[6]!==d?(c=s.jsxs("span",{className:"flex items-center gap-1.5",title:i,children:[o,d]}),e[4]=i,e[5]=o,e[6]=d,e[7]=c):c=e[7],c},J1=({selectedModelId:t,onSelect:e})=>{const{t:n}=lt(),a=we.useCallback(m=>n(m),[n]),[i,r]=we.useState(new Map),[o,d]=we.useState(null),c=we.useCallback(async()=>{try{const m=await ht("/api/dictation/status",{query:{provider:"local"}});if(!m.ok)return;const w=await m.json();Array.isArray(w?.models)&&r(new Map(w.models.map(b=>[b.id,b])))}catch{}},[]);we.useEffect(()=>{c()},[c]);const p=Array.from(i.values()).some(m=>m.downloading);we.useEffect(()=>{if(!p)return;const m=setInterval(()=>{c()},2e3);return()=>clearInterval(m)},[p,c]);const u=async m=>{d(m);try{await ht(`/api/dictation/models/${encodeURIComponent(m)}/download`,{method:"POST"}),await c()}catch{}finally{d(null)}},f=async m=>{d(m);try{await ht(`/api/dictation/models/${encodeURIComponent(m)}`,{method:"DELETE"}),await c()}catch{}finally{d(null)}};return s.jsx("div",{role:"radiogroup","aria-label":n("settings.voice.page.field.model"),className:"mt-1.5 grid w-full grid-cols-1 gap-3 @xl:grid-cols-2",children:q1.map(m=>{const w=t===m.id,b=i.get(m.id)??null;return s.jsx("div",{className:fe("rounded-lg border border-[var(--interactive-border)] p-3",w&&"border-[var(--primary-base)] bg-[var(--primary-base)]/5"),children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 cursor-pointer items-start gap-2",role:"button",tabIndex:0,onClick:()=>e(m.id),onKeyDown:g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),e(m.id))},children:[s.jsx("div",{className:"pt-0.5",children:s.jsx(kr,{checked:w,onChange:()=>e(m.id),ariaLabel:a(m.labelKey)})}),s.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:fe("typography-ui-label font-normal",w?"text-foreground":"text-foreground/50"),children:a(m.labelKey)}),m.badgeKey?s.jsx("span",{className:"rounded border border-[var(--status-success-border)] bg-[var(--status-success-background)] px-1 text-[9px] font-medium uppercase leading-[14px] tracking-wide text-[var(--status-success)]",children:a(m.badgeKey)}):null]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(wd,{value:m.accuracy,label:n("settings.voice.page.stt.meta.accuracy")}),s.jsx(wd,{value:m.speed,label:n("settings.voice.page.stt.meta.speed")}),s.jsx("span",{className:"typography-ui-compact tabular-nums text-muted-foreground",children:m.size})]}),b?.downloadError?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:b.downloadError}):null]})]}),s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:b?.installed?s.jsxs(s.Fragment,{children:[s.jsx(ee,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0 text-muted-foreground hover:text-[var(--status-error)]",disabled:o===m.id,onClick:()=>{f(m.id)},title:n("settings.voice.page.stt.modelDelete"),"aria-label":n("settings.voice.page.stt.modelDelete"),children:s.jsx(K,{name:"delete-bin",className:"h-4 w-4"})}),s.jsx(K,{name:"checkbox-circle",className:"h-4 w-4 flex-shrink-0 text-[var(--status-success)]","aria-label":n("settings.voice.page.stt.modelInstalled")})]}):b?.downloading?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(K,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-ui-compact tabular-nums text-muted-foreground",children:typeof b.downloadProgress=="number"?`${b.downloadProgress}%`:""})]}):s.jsx(ee,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0",disabled:o===m.id,onClick:()=>{u(m.id)},title:n("settings.voice.page.stt.modelDownload"),"aria-label":n("settings.voice.page.stt.modelDownload"),children:s.jsx(K,{name:"download",className:"h-4 w-4"})})})]})},m.id)})})},uo=[{id:0,label:"Alloy (af)"},{id:1,label:"Bella (af)"},{id:2,label:"Nicole (af)"},{id:3,label:"Sarah (af)"},{id:4,label:"Sky (af)"},{id:5,label:"Adam (am)"},{id:6,label:"Michael (am)"},{id:7,label:"Emma (bf)"},{id:8,label:"Isabella (bf)"},{id:9,label:"George (bm)"},{id:10,label:"Lewis (bm)"}],mo="kokoro-en-v0_19",Y1=()=>{const{t}=lt(),[e,n]=we.useState(null),[a,i]=we.useState(!1),r=we.useCallback(async()=>{try{const d=await ht("/api/dictation/status",{query:{provider:"local"}});if(!d.ok)return;const c=await d.json(),p=Array.isArray(c?.ttsModels)?c.ttsModels.find(u=>u.id===mo):null;p&&n(p)}catch{}},[]);we.useEffect(()=>{r()},[r]),we.useEffect(()=>{if(!e?.downloading)return;const d=setInterval(()=>{r()},2e3);return()=>clearInterval(d)},[e?.downloading,r]);const o=async d=>{i(!0);try{const c=d==="POST"?`/api/dictation/models/${mo}/download`:`/api/dictation/models/${mo}`;await ht(c,{method:d}),await r()}catch{}finally{i(!1)}};return e?s.jsxs("div",{className:"flex items-center gap-2 py-1.5",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:"Kokoro"}),s.jsx("span",{className:"typography-ui-compact tabular-nums text-muted-foreground",children:"305 MB"}),e.installed?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"checkbox-circle",className:"h-4 w-4 text-[var(--status-success)]","aria-label":t("settings.voice.page.stt.modelInstalled")}),s.jsx(ee,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0 text-muted-foreground hover:text-[var(--status-error)]",disabled:a,onClick:()=>{o("DELETE")},title:t("settings.voice.page.stt.modelDelete"),"aria-label":t("settings.voice.page.stt.modelDelete"),children:s.jsx(K,{name:"delete-bin",className:"h-4 w-4"})})]}):e.downloading?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(K,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),s.jsx("span",{className:"typography-ui-compact tabular-nums text-muted-foreground",children:typeof e.downloadProgress=="number"?`${e.downloadProgress}%`:""})]}):s.jsx(ee,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0",disabled:a,onClick:()=>{o("POST")},title:t("settings.voice.page.stt.modelDownload"),"aria-label":t("settings.voice.page.stt.modelDownload"),children:s.jsx(K,{name:"download",className:"h-4 w-4"})}),e.downloadError?s.jsx("span",{className:"typography-meta text-[var(--status-error)]",children:e.downloadError}):null]}):null},Q1=[{value:"alloy",label:"Alloy"},{value:"ash",label:"Ash"},{value:"ballad",label:"Ballad"},{value:"coral",label:"Coral"},{value:"echo",label:"Echo"},{value:"fable",label:"Fable"},{value:"nova",label:"Nova"},{value:"onyx",label:"Onyx"},{value:"sage",label:"Sage"},{value:"shimmer",label:"Shimmer"},{value:"verse",label:"Verse"},{value:"marin",label:"Marin"},{value:"cedar",label:"Cedar"}],X1=()=>{const{t}=lt(),{isMobile:e}=Vs(),n=pt(h=>h.voiceProvider),a=pt(h=>h.setVoiceProvider),i=pt(h=>h.speechRate),r=pt(h=>h.setSpeechRate),o=pt(h=>h.speechPitch),d=pt(h=>h.setSpeechPitch),c=pt(h=>h.speechVolume),p=pt(h=>h.setSpeechVolume),u=pt(h=>h.sayVoice),f=pt(h=>h.setSayVoice),m=pt(h=>h.localTtsVoiceId),w=pt(h=>h.setLocalTtsVoiceId),{speak:b,stop:g,isPlaying:x,error:k}=Gp(),y=we.useCallback(()=>{if(x){g();return}const h=uo.find(ae=>ae.id===m)?.label??String(m);b(t("settings.voice.page.preview.voiceLine",{voiceName:h}),{speakerId:m,speed:pt.getState().speechRate})},[x,m,b,g,t]),C=pt(h=>h.browserVoice),z=pt(h=>h.setBrowserVoice),j=pt(h=>h.openaiVoice),N=pt(h=>h.setOpenaiVoice),v=pt(h=>h.openaiApiKey),P=pt(h=>h.setOpenaiApiKey),$=pt(h=>h.openaiCompatibleUrl),O=pt(h=>h.setOpenaiCompatibleUrl),M=pt(h=>h.openaiCompatibleApiKey),S=pt(h=>h.setOpenaiCompatibleApiKey),F=pt(h=>h.openaiCompatibleVoice),E=pt(h=>h.setOpenaiCompatibleVoice),D=pt(h=>h.openaiCompatibleTtsModel),W=pt(h=>h.setOpenaiCompatibleTtsModel),H=pt(h=>h.showMessageTTSButtons),Z=pt(h=>h.ttsInputMode),Y=pt(h=>h.setTtsInputMode),A=pt(h=>h.sttProvider),X=pt(h=>h.setSttProvider),te=pt(h=>h.sttServerUrl),T=pt(h=>h.setSttServerUrl),I=pt(h=>h.sttApiKey),B=pt(h=>h.setSttApiKey),L=pt(h=>h.sttModel),V=pt(h=>h.setSttModel),Q=pt(h=>h.sttLocalModel),G=pt(h=>h.setSttLocalModel),ue=pt(h=>h.sttLanguage),ne=pt(h=>h.setSttLanguage),xe=pt(h=>h.setShowMessageTTSButtons),ve=pt(h=>h.dictationEnabled),me=pt(h=>h.setDictationEnabled),[ge,Ie]=we.useState(!1),[oe,ce]=we.useState([]),[pe,ie]=we.useState(!1),[le,de]=we.useState(null),[he,Me]=we.useState(!1),[Le,Be]=we.useState(!1),[Fe,De]=we.useState(null),[ze,Ve]=we.useState(!1),[We,_e]=we.useState(null),[He,Ke]=we.useState([]),[Oe,je]=we.useState(!1);we.useEffect(()=>((async()=>{const ae=await Hr.waitForVoices();Ke(ae)})(),"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=()=>{Ke(window.speechSynthesis.getVoices())}),()=>{"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=null)}),[]);const Te=we.useMemo(()=>He.filter(h=>h.lang).sort((h,ae)=>{const ye=h.lang.startsWith("en"),be=ae.lang.startsWith("en");if(ye&&!be)return-1;if(!ye&&be)return 1;const Ee=h.lang.localeCompare(ae.lang);return Ee!==0?Ee:h.name.localeCompare(ae.name)}),[He]),Ue=we.useCallback(()=>{if(Oe){Hr.cancelSpeech(),je(!1);return}const h=He.find(Ee=>Ee.name===C),ae=h?.name??t("settings.voice.page.preview.browserVoiceFallback"),ye=t("settings.voice.page.preview.voiceLine",{voiceName:ae});je(!0);const be=new SpeechSynthesisUtterance(ye);be.rate=i,be.pitch=o,be.volume=c,h&&(be.voice=h,be.lang=h.lang),be.onend=()=>je(!1),be.onerror=()=>je(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(be)},[C,He,i,o,c,Oe,t]);we.useEffect(()=>()=>{Oe&&Hr.cancelSpeech()},[Oe]),we.useEffect(()=>{if(!H||n!=="openai"&&n!=="openai-compatible"){Me(v.trim().length>0);return}(async()=>{try{const be=(await(await ht("/api/tts/status")).json()).available,Ee=v.trim().length>0;Me(be||Ee)}catch{Me(v.trim().length>0)}})()},[v,H,n]),we.useEffect(()=>{if(!H){Ie(!1),ce([]);return}ht("/api/tts/say/status").then(h=>h.json()).then(h=>{if(Ie(h.available),h.voices){const ae=h.voices.filter((ye,be,Ee)=>Ee.findIndex(et=>et.name===ye.name)===be).sort((ye,be)=>ye.name.localeCompare(be.name));ce(ae)}}).catch(()=>{Ie(!1)})},[H]);const Ye=we.useCallback(async()=>{if(le){Fs(le),de(null),ie(!1);return}ie(!0);let h=null;try{const ae=await ht("/api/tts/say/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t("settings.voice.page.preview.voiceLine",{voiceName:u}),voice:u,rate:Math.round(100+(i-.5)*200)})});if(!ae.ok)throw new Error("Preview failed");const ye=await ae.blob(),be=URL.createObjectURL(ye);h=new Audio(be),h.onended=()=>{Fs(h),de(null),ie(!1)},h.onerror=()=>{Fs(h),de(null),ie(!1)},de(h),await h.play()}catch{Fs(h),de(null),ie(!1)}},[u,i,le,t]);we.useEffect(()=>()=>{Fs(le)},[le]);const q=we.useCallback(async()=>{if(Fe){Fs(Fe),De(null),Be(!1);return}Be(!0);let h=null;try{const ae=await ht("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t("settings.voice.page.preview.voiceLine",{voiceName:j}),voice:j,speed:i,apiKey:v||void 0})});if(!ae.ok){const Ee=await ae.json().catch(()=>({error:"Unknown error"}));throw new Error(Ee.error||`HTTP ${ae.status}`)}const ye=await ae.blob(),be=URL.createObjectURL(ye);h=new Audio(be),h.onended=()=>{Fs(h),De(null),Be(!1)},h.onerror=()=>{Fs(h),De(null),Be(!1)},De(h),await h.play()}catch{Fs(h),De(null),Be(!1)}},[j,i,Fe,v,t]);we.useEffect(()=>()=>{Fs(Fe)},[Fe]);const re=we.useCallback(async()=>{if(We){Fs(We),_e(null),Ve(!1);return}if(!$.trim())return;Ve(!0);let h=null;try{const ae=await ht("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t("settings.voice.page.preview.customServerLine"),voice:F,model:D||void 0,speed:i,baseURL:$,apiKey:M||void 0})});if(!ae.ok){const Ee=await ae.json().catch(()=>({error:"Unknown error"}));throw new Error(Ee.error||`HTTP ${ae.status}`)}const ye=await ae.blob(),be=URL.createObjectURL(ye);h=new Audio(be),h.onended=()=>{Fs(h),_e(null),Ve(!1)},h.onerror=()=>{Fs(h),_e(null),Ve(!1)},_e(h),await h.play()}catch{Fs(h),_e(null),Ve(!1)}},[$,F,D,M,i,We,t]);we.useEffect(()=>()=>{Fs(We)},[We]);const U="flex-1 min-w-0 h-1.5 bg-[var(--interactive-border)] rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-[var(--primary-base)] [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-[var(--primary-base)] [&::-moz-range-thumb]:border-0 disabled:opacity-50";return s.jsxs(s.Fragment,{children:[s.jsxs(dt,{settingsItem:"voice.playback",title:t("settings.voice.page.section.playbackAndSummary"),divider:!1,contentClassName:"space-y-4",children:[s.jsx(Ct,{checked:H,onChange:xe,label:t("settings.voice.page.field.messageReadAloudButton"),ariaLabel:t("settings.voice.page.field.messageReadAloudButtonAria")}),H&&s.jsxs(s.Fragment,{children:[s.jsx(Zs,{title:t("settings.voice.page.field.provider"),info:s.jsxs("ul",{className:"space-y-1",children:[s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.browser")})," ",t("settings.voice.page.tooltip.browser")]}),s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.local")})," ",t("settings.voice.page.tooltip.localTts")]}),s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.openai")})," ",t("settings.voice.page.tooltip.openai")]}),s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.custom")})," ",t("settings.voice.page.tooltip.custom")]}),s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.say")})," ",t("settings.voice.page.tooltip.say")]})]}),children:s.jsx(Ys,{value:n,onChange:a,"aria-label":t("settings.voice.page.field.provider"),className:"w-full gap-1.5 sm:gap-2",options:[{value:"browser",label:t("settings.voice.page.provider.browser")},{value:"local",label:t("settings.voice.page.provider.local")},{value:"openai",label:t("settings.voice.page.provider.openai")},{value:"openai-compatible",label:t("settings.voice.page.provider.custom")},...ge?[{value:"say",label:s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"apple",className:"mr-0.5 h-3.5 w-3.5"}),t("settings.voice.page.provider.say")]})}]:[]]})}),n==="openai"&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:fe(zt,!he&&"text-[var(--status-error)]"),children:t("settings.voice.page.field.apiKey")}),s.jsx("span",{className:fe(Js,!he&&"text-[var(--status-error)]/80"),children:t(he&&!v?"settings.voice.page.field.apiKeyHintUsingConfig":he?"settings.voice.page.field.apiKeyHintProvide":"settings.voice.page.field.apiKeyHintRequired")}),s.jsxs("div",{className:fe("relative",Us),children:[s.jsx("input",{type:"password",value:v,onChange:h=>P(h.target.value),placeholder:"sk-...",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"}),v&&s.jsx("button",{type:"button",onClick:()=>P(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(K,{name:"close",className:"w-3.5 h-3.5"})})]})]}),n==="openai-compatible"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:fe(zt,!$.trim()&&"text-[var(--status-error)]"),children:t("settings.voice.page.field.serverUrl")}),s.jsx($t,{children:t("settings.voice.page.field.serverUrlHint")})]}),s.jsxs("div",{className:fe("relative",Us),children:[s.jsx("input",{type:"text",value:$,onChange:h=>O(h.target.value),placeholder:"http://localhost:8880/v1",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"}),$&&s.jsx("button",{type:"button",onClick:()=>O(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(K,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:zt,children:"API Key"}),s.jsx("span",{className:Js,children:"Optional"}),s.jsxs("div",{className:fe("relative",Us),children:[s.jsx("input",{type:"password",value:M,onChange:h=>S(h.target.value),placeholder:"sk-...",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"}),M&&s.jsx("button",{type:"button",onClick:()=>S(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(K,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:zt,children:t("settings.voice.page.field.model")}),s.jsx("div",{className:fe("relative",Us),children:s.jsx("input",{type:"text",value:D,onChange:h=>W(h.target.value),placeholder:"speaches-ai/Kokoro-82M-v1.0-ONNX",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"})})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:zt,children:t("settings.voice.page.field.voice")}),s.jsx($t,{children:t("settings.voice.page.field.voiceIdentifierHint")})]}),s.jsxs("div",{className:fe("flex items-center gap-2",Us),children:[s.jsx("div",{className:"relative min-w-0 flex-1",children:s.jsx("input",{type:"text",value:F,onChange:h=>E(h.target.value),placeholder:"af_sky",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"})}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:re,title:t("settings.voice.page.actions.preview"),disabled:!$.trim(),children:ze?s.jsx(K,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(K,{name:"play",className:"w-3.5 h-3.5"})})]})]})]}),n==="local"&&s.jsx(Y1,{}),s.jsxs(Xt,{label:t("settings.voice.page.field.voice"),children:[n==="local"&&s.jsxs(s.Fragment,{children:[s.jsxs(Lt,{value:String(m),onValueChange:h=>w(Number.parseInt(h,10)||0),children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder"),children:h=>uo.find(ae=>String(ae.id)===h)?.label??h})}),s.jsx(Ot,{children:uo.map(h=>s.jsx(kt,{value:String(h.id),children:h.label},h.id))})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:y,title:t("settings.voice.page.actions.preview"),children:x?s.jsx(K,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(K,{name:"play",className:"w-3.5 h-3.5"})}),k?s.jsx("span",{className:"typography-meta text-[var(--status-error)]",children:k}):null]}),n==="openai"&&he&&s.jsxs(s.Fragment,{children:[s.jsxs(Lt,{value:j,onValueChange:N,children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder")})}),s.jsx(Ot,{children:Q1.map(h=>s.jsx(kt,{value:h.value,children:h.label},h.value))})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:q,title:t("settings.voice.page.actions.preview"),children:Le?s.jsx(K,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(K,{name:"play",className:"w-3.5 h-3.5"})})]}),n==="openai-compatible"&&s.jsx("span",{className:Js,children:t("settings.voice.page.field.configuredAbove")}),n==="say"&&ge&&oe.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs(Lt,{value:u,onValueChange:f,children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder")})}),s.jsx(Ot,{children:oe.map(h=>s.jsx(kt,{value:h.name,children:h.name},h.name))})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:Ye,title:t("settings.voice.page.actions.preview"),children:pe?s.jsx(K,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(K,{name:"play",className:"w-3.5 h-3.5"})})]}),n==="browser"&&Te.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs(Lt,{value:C||"$auto",onValueChange:h=>z(h==="$auto"?"":h),children:[s.jsx(Ft,{size:Jt,className:ra,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.auto")})}),s.jsxs(Ot,{children:[s.jsx(kt,{value:"$auto",children:t("settings.voice.page.field.auto")}),Te.map(h=>s.jsxs(kt,{value:h.name,children:[h.name," (",h.lang,")"]},h.name))]})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:Ue,title:t("settings.voice.page.actions.preview"),children:Oe?s.jsx(K,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(K,{name:"play",className:"w-3.5 h-3.5"})})]})]}),s.jsxs(Xt,{label:t("settings.voice.page.field.speechRate"),children:[!e&&s.jsx("input",{type:"range",min:.5,max:2,step:.1,value:i,onChange:h=>r(Number(h.target.value)),className:U}),s.jsx(Rs,{value:i,onValueChange:r,min:.5,max:2,step:.1,className:"w-16 tabular-nums"})]}),s.jsxs(Xt,{label:t("settings.voice.page.field.speechPitch"),children:[!e&&s.jsx("input",{type:"range",min:.5,max:2,step:.1,value:o,onChange:h=>d(Number(h.target.value)),className:U}),s.jsx(Rs,{value:o,onValueChange:d,min:.5,max:2,step:.1,className:"w-16 tabular-nums"})]}),s.jsxs(Xt,{label:t("settings.voice.page.field.speechVolume"),children:[!e&&s.jsx("input",{type:"range",min:0,max:1,step:.1,value:c,onChange:h=>p(Number(h.target.value)),className:U}),e?s.jsx(Rs,{value:Math.round(c*100),onValueChange:h=>p(h/100),min:0,max:100,step:10,className:"w-16 tabular-nums"}):s.jsxs("span",{className:"typography-ui-label text-foreground tabular-nums min-w-[3rem] text-right",children:[Math.round(c*100),"%"]})]}),s.jsx(Zs,{title:t("settings.voice.page.field.ttsInputMode"),children:s.jsx(Ys,{value:Z,onChange:Y,"aria-label":t("settings.voice.page.field.ttsInputMode"),className:"w-full gap-1.5 sm:gap-2",options:[{value:"sanitized",label:t("settings.voice.page.field.ttsInputModeSanitized")},{value:"raw",label:t("settings.voice.page.field.ttsInputModeRaw")},{value:"summarized",label:t("settings.voice.page.field.ttsInputModeSummarized")}]})})]})]}),s.jsxs(dt,{settingsItem:"voice.speech-recognition",title:t("settings.voice.page.section.speechRecognition"),contentClassName:"space-y-4",children:[s.jsx(Ct,{checked:ve,onChange:me,label:t("settings.voice.page.field.enableVoiceInput"),ariaLabel:t("settings.voice.page.field.enableVoiceInputAria")}),ve&&s.jsxs(s.Fragment,{children:[s.jsx(Zs,{title:t("settings.voice.page.field.provider"),info:s.jsxs("ul",{className:"space-y-1",children:[s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.local")})," ",t("settings.voice.page.tooltip.sttLocal")]}),s.jsxs("li",{children:[s.jsx("strong",{children:t("settings.voice.page.provider.server")})," ",t("settings.voice.page.tooltip.sttServer")]})]}),children:s.jsx(Ys,{value:A,onChange:X,"aria-label":t("settings.voice.page.field.provider"),className:"w-full gap-1.5 sm:gap-2",options:[{value:"local",label:t("settings.voice.page.provider.local")},{value:"openai-compatible",label:t("settings.voice.page.provider.server")}]})}),A==="local"&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:zt,children:t("settings.voice.page.field.model")}),s.jsx(J1,{selectedModelId:Q,onSelect:G})]}),A==="openai-compatible"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:fe(zt,!te.trim()&&"text-[var(--status-error)]"),children:t("settings.voice.page.field.serverUrl")}),s.jsx($t,{children:t("settings.voice.page.field.sttServerUrlHint")})]}),s.jsxs("div",{className:fe("relative",Us),children:[s.jsx("input",{type:"text",value:te,onChange:h=>T(h.target.value),placeholder:"http://localhost:8001/v1",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"}),te&&s.jsx("button",{type:"button",onClick:()=>T(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(K,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:zt,children:"API Key"}),s.jsx("span",{className:Js,children:"Optional"}),s.jsxs("div",{className:fe("relative",Us),children:[s.jsx("input",{type:"password",value:I,onChange:h=>B(h.target.value),placeholder:"sk-...",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"}),I&&s.jsx("button",{type:"button",onClick:()=>B(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(K,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:zt,children:t("settings.voice.page.field.model")}),s.jsx("div",{className:fe("relative",Us),children:s.jsx("input",{type:"text",value:L,onChange:h=>V(h.target.value),placeholder:"deepdml/faster-whisper-large-v3-turbo-ct2",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"})})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:zt,children:t("settings.voice.page.field.language")}),s.jsx($t,{children:t("settings.voice.page.field.sttLanguageHint")})]}),s.jsx("div",{className:"relative max-w-[8rem]",children:s.jsx("input",{type:"text",value:ue,onChange:h=>ne(h.target.value),placeholder:"auto",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"})})]})]})]})]})]})},$i=[{value:"1800000",label:"30m",ms:1800*1e3},{value:"180000",label:"3m",ms:180*1e3},{value:"7200000",label:"2h",ms:7200*1e3},{value:"28800000",label:"8h",ms:480*60*1e3},{value:"86400000",label:"24h",ms:1440*60*1e3}],Vi=[{value:"3600000",label:"1h",ms:3600*1e3},{value:"28800000",label:"8h",ms:480*60*1e3},{value:"43200000",label:"12h",ms:720*60*1e3},{value:"86400000",label:"24h",ms:1440*60*1e3},{value:"604800000",label:"1w",ms:10080*60*1e3},{value:"2592000000",label:"30d",ms:720*60*60*1e3}],Z1="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",ej="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",po=[{value:"quick",labelKey:"settings.openchamber.tunnel.option.mode.quick.label",tooltipKey:"settings.openchamber.tunnel.option.mode.quick.tooltip"},{value:"managed-remote",labelKey:"settings.openchamber.tunnel.option.mode.managedRemote.label",tooltipKey:"settings.openchamber.tunnel.option.mode.managedRemote.tooltip"},{value:"managed-local",labelKey:"settings.openchamber.tunnel.option.mode.managedLocal.label",tooltipKey:"settings.openchamber.tunnel.option.mode.managedLocal.tooltip"}],tj=[".yml",".yaml",".json"],sj="settings.openchamber.tunnel.error.invalidConfigExtension",oi=t=>{const e=t.trim().toLowerCase();return tj.some(n=>e.endsWith(n))},nj=t=>t==="ngrok"?"ngrok":"cloudflared",im=()=>{if(typeof window<"u"&&typeof window.__OPENCHAMBER_PLATFORM__=="string"){const e=window.__OPENCHAMBER_PLATFORM__;if(e==="win32"||e==="darwin"||e==="linux")return e}const t=typeof navigator<"u"?`${navigator.platform||""} ${navigator.userAgent||""}`.toLowerCase():"";return t.includes("win")?"win32":t.includes("mac")?"darwin":"linux"},aj=(t,e=im())=>t==="ngrok"?e==="win32"?"winget install ngrok -s msstore":e==="darwin"?"brew install ngrok":"https://ngrok.com/download":e==="win32"?"winget install --id Cloudflare.cloudflared":e==="darwin"?"brew install cloudflared":"https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflared/downloads/",go=(t,e)=>{const n=typeof e?.provider=="string"&&e.provider.trim().length>0?e.provider.trim().toLowerCase():t,a=typeof e?.dependency=="string"&&e.dependency.trim().length>0?e.dependency.trim():nj(n),i=typeof e?.platform=="string"&&e.platform.trim().length>0?e.platform.trim():im(),r=typeof e?.installCommand=="string"&&e.installCommand.trim().length>0?e.installCommand.trim():aj(n,i);return{provider:n,dependency:a,installCommand:r}},rm=t=>t==="cloudflare"?"Cloudflare":t==="ngrok"?"Ngrok":t,jd=t=>{const e=tt.c(11),{provider:n}=t;let a;e[0]!==n?(a=rm(n),e[0]=n,e[1]=a):a=e[1];const i=a,d=n==="cloudflare"||n==="ngrok"?"text-[var(--status-warning)]":"text-muted-foreground";let c;e[2]!==d?(c=fe("size-4 shrink-0",d),e[2]=d,e[3]=c):c=e[3];let p;e[4]!==c?(p=s.jsx(K,{name:"cloud",className:c}),e[4]=c,e[5]=p):p=e[5];let u;e[6]!==i?(u=s.jsx("span",{children:i}),e[6]=i,e[7]=u):u=e[7];let f;return e[8]!==p||e[9]!==u?(f=s.jsxs("span",{className:"flex items-center gap-2",children:[p,u]}),e[8]=p,e[9]=u,e[10]=f):f=e[10],f},Fn=t=>t==="quick"?"quick":t==="managed-remote"?"managed-remote":t==="managed-local"?"managed-local":"quick",el=(t,e,n)=>t.find(i=>i.ms===e)?.value||n,kd=(t,e,n)=>{const a=el(t,e,n);return t.find(i=>i.value===a)?.label||a},Nd=t=>{const e=Math.max(0,t),n=Math.floor(e/1e3),a=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60;return a>0?`${a}h ${i}m`:i>0?`${i}m ${r}s`:`${r}s`},ij=(t,e)=>ru(t,e,{hour:"2-digit",precision:"second"}),rr=t=>{const e=t.trim();if(!e)return"";try{return(e.includes("://")?new URL(e):new URL(`https://${e}`)).hostname.trim().toLowerCase()}catch{return e.toLowerCase()}},rj=t=>{if(!Array.isArray(t))return[];const e=new Set,n=new Set,a=[];for(const i of t){if(!i||typeof i!="object")continue;const r=i,o=typeof r.id=="string"?r.id.trim():"",d=typeof r.name=="string"?r.name.trim():"",c=rr(typeof r.hostname=="string"?r.hostname:"");!o||!d||!c||e.has(o)||n.has(c)||(e.add(o),n.add(c),a.push({id:o,name:d,hostname:c}))}return a},oj=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,lj=()=>{const{t}=lt(),e=ke(se=>se.timeFormatPreference),n=l.useCallback(se=>t(se),[t]),[a,i]=l.useState("checking"),[r,o]=l.useState(null),[d,c]=l.useState(null),[p,u]=l.useState(null),[f,m]=l.useState(null),[w,b]=l.useState(null),[g,x]=l.useState(!1),[k,y]=l.useState(!1),[C,z]=l.useState(!1),[j,N]=l.useState("cloudflare"),[v,P]=l.useState(()=>go("cloudflare")),[$,O]=l.useState([]),[M,S]=l.useState("quick"),[F,E]=l.useState(null),[D,W]=l.useState([]),[H,Z]=l.useState({}),[Y,A]=l.useState(""),[X,te]=l.useState({}),[T,I]=l.useState(new Set),[B,L]=l.useState(!1),[V,Q]=l.useState(""),[G,ue]=l.useState(""),[ne,xe]=l.useState(""),[ve,me]=l.useState(1800*1e3),[ge,Ie]=l.useState(480*60*1e3),[oe,ce]=l.useState(""),[pe,ie]=l.useState([]),[le,de]=l.useState(()=>Date.now()),[he,Me]=l.useState(null),Le=t(sj),Be=l.useRef(null),Fe=l.useMemo(()=>F?!oi(F):!1,[F]),De=l.useMemo(()=>D.find(se=>se.id===Y)||D[0]||null,[D,Y]),ze=l.useMemo(()=>pe.map(se=>{const Ce=se.expiresAt<=le,Xe=se.status==="active"&&!Ce,Re=Xe?Nd(se.expiresAt-le):se.inactiveReason==="expired"||Ce?"expired":"inactive",Je=Re==="expired"?t("settings.openchamber.tunnel.state.expired"):se.inactiveReason==="tunnel-revoked"?t("settings.openchamber.tunnel.state.revoked"):t("settings.openchamber.tunnel.state.inactive"),Ge=Fn(se.mode);return{...se,isActive:Xe,mode:Ge,remainingTextForSession:Re,inactiveLabel:Je}}),[le,pe,t]),Ve=l.useMemo(()=>r?.connectUrl?r.bootstrapExpiresAt===null?!0:r.bootstrapExpiresAt>le:!1,[le,r?.bootstrapExpiresAt,r?.connectUrl]),We=l.useMemo(()=>!r||a!=="active"&&a!=="stopping"?!1:d===M,[d,a,r,M]),_e=l.useMemo(()=>!r||a!=="active"||!d?!1:d!==M,[d,a,r,M]),He=l.useMemo(()=>{if(typeof he=="number"&&Number.isFinite(he)&&he>0)return he;if(typeof window>"u")return null;const Ce=Ga()||window.location.href;let Xe=0;try{Xe=Number(new URL(Ce).port)}catch{Xe=Number(window.location.port)}return Number.isFinite(Xe)&&Xe>0?Xe:null},[he]),Ke=l.useMemo(()=>$.find(se=>se.provider===j)??null,[$,j]),Oe=l.useMemo(()=>{const se=new Set(Ke?.modes?.map(Ce=>Ce.key).filter(Ce=>Ce==="quick"||Ce==="managed-remote"||Ce==="managed-local"));return se.size===0?po:po.filter(Ce=>se.has(Ce.value))},[Ke]),je=l.useMemo(()=>Oe.some(se=>se.value==="managed-remote"||se.value==="managed-local"),[Oe]),Te=l.useMemo(()=>v.provider===j?v:go(j),[v,j]),Ue=l.useCallback(async se=>{await Tn(se)},[]),Ye=l.useCallback((se,Ce)=>(P(go(Ce,se)),se.available===!0),[]),q=l.useCallback(async(se,Ce)=>{try{const Xe=await ht("/api/openchamber/tunnel/check",{query:{provider:se},...Ce?{signal:Ce}:{}});if(!Xe.ok)return null;const Re=await Xe.json();if(Ce?.aborted)return null;const Je=Ye(Re,se);return i(Ge=>Ge==="checking"||Ge==="starting"||Ge==="active"||Ge==="stopping"?Ge:Je?"idle":"not-available"),Je}catch{return null}},[Ye]),re=l.useCallback(async se=>{try{const[Ce,Xe,Re,Je]=await Promise.all([ht("/api/openchamber/tunnel/check",{signal:se}),ht("/api/openchamber/tunnel/status",{signal:se}),ht("/api/config/settings",{signal:se,headers:{Accept:"application/json"}}),ht("/api/openchamber/tunnel/providers",{signal:se})]),Ge=await Ce.json(),st=await Xe.json(),jt=Re.ok?await Re.json():{},Et=Je.ok?await Je.json():{},Mt=st.ttlConfig?.bootstrapTtlMs??(jt?.tunnelBootstrapTtlMs===null?null:typeof jt?.tunnelBootstrapTtlMs=="number"?jt.tunnelBootstrapTtlMs:1800*1e3),Zt=typeof st.ttlConfig?.sessionTtlMs=="number"?st.ttlConfig.sessionTtlMs:typeof jt?.tunnelSessionTtlMs=="number"?jt.tunnelSessionTtlMs:480*60*1e3,Qt=Fn(st.mode??jt?.tunnelMode),St=typeof jt?.tunnelProvider=="string"&&jt.tunnelProvider.trim().length>0?jt.tunnelProvider.trim().toLowerCase():"cloudflare",Pt=typeof jt?.managedLocalTunnelConfigPath=="string"&&jt.managedLocalTunnelConfigPath.trim()||null,Ne=Ye(Ge,St),ut=rj(st?.managedRemoteTunnelPresets),mt=typeof st.managedRemoteTunnelHostname=="string"?st.managedRemoteTunnelHostname:"",At=ut.length>0?ut:mt?[{id:`legacy-${rr(mt)}`,name:mt,hostname:rr(mt)}]:[],ft=At[0]?.id||"";if(me(Mt),Ie(Zt),N(St),O(Array.isArray(Et?.providers)?Et.providers:[]),S(Qt),E(Pt),W(At),A(ft),ie(Array.isArray(st.activeSessions)?st.activeSessions:[]),c(st.activeTunnelMode?Fn(st.activeTunnelMode):st.active&&st.mode?Fn(st.mode):null),I(new Set(Array.isArray(st.managedRemoteTunnelTokenPresetIds)?st.managedRemoteTunnelTokenPresetIds:[])),Me(typeof st.localPort=="number"?st.localPort:null),st.active&&st.url){o({url:st.url,connectUrl:null,bootstrapExpiresAt:typeof st.bootstrapExpiresAt=="number"?st.bootstrapExpiresAt:null}),i("active");return}i(Ne?"idle":"not-available")}catch{se.aborted||(i("error"),m(t("settings.openchamber.tunnel.toast.checkAvailabilityFailed")))}},[Ye,t]);l.useEffect(()=>{const se=new AbortController;return re(se.signal),()=>se.abort()},[re]),l.useEffect(()=>{if(!r?.connectUrl){u(null);return}let se=!1;return fu.toDataURL(r.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(Ce=>{se||u(Ce)}).catch(()=>{se||u(null)}),()=>{se=!0}},[r?.connectUrl]),l.useEffect(()=>{if(!r?.bootstrapExpiresAt){ce(t("settings.openchamber.tunnel.state.noExpiry"));return}let se=null,Ce=Date.now();const Xe=()=>{const Ge=r.bootstrapExpiresAt?r.bootstrapExpiresAt-Date.now():0;Ge<=0?ce(t("settings.openchamber.tunnel.state.expired")):ce(Nd(Ge))},Re=()=>{const Ge=Date.now();Ge-Ce>=1e3&&(Xe(),Ce=Ge),se=requestAnimationFrame(Re)};Xe(),(typeof document>"u"||document.visibilityState==="visible")&&(se=requestAnimationFrame(Re));const Je=()=>{document.visibilityState==="visible"&&se===null?se=requestAnimationFrame(Re):document.visibilityState!=="visible"&&se!==null&&(cancelAnimationFrame(se),se=null)};return document.addEventListener("visibilitychange",Je),()=>{document.removeEventListener("visibilitychange",Je),se!==null&&cancelAnimationFrame(se)}},[t,r?.bootstrapExpiresAt]),l.useEffect(()=>{let se=null,Ce=Date.now();const Xe=()=>{const Je=Date.now();Je-Ce>=1e3&&(de(Je),Ce=Je),se=requestAnimationFrame(Xe)};(typeof document>"u"||document.visibilityState==="visible")&&(se=requestAnimationFrame(Xe));const Re=()=>{document.visibilityState==="visible"&&se===null?se=requestAnimationFrame(Xe):document.visibilityState!=="visible"&&se!==null&&(cancelAnimationFrame(se),se=null)};return document.addEventListener("visibilitychange",Re),()=>{document.removeEventListener("visibilitychange",Re),se!==null&&cancelAnimationFrame(se)}},[]),l.useEffect(()=>{if(a==="starting"||a==="stopping"||a==="checking")return;let se=!1;const Ce=async()=>{try{const Re=await ht("/api/openchamber/tunnel/status");if(!Re.ok||se)return;const Je=await Re.json();if(se)return;ie(Array.isArray(Je.activeSessions)?Je.activeSessions:[]),I(new Set(Array.isArray(Je.managedRemoteTunnelTokenPresetIds)?Je.managedRemoteTunnelTokenPresetIds:[])),Me(typeof Je.localPort=="number"?Je.localPort:null)}catch{}},Xe=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ce()},5e3);return()=>{se=!0,window.clearInterval(Xe)}},[a]);const U=l.useCallback(async se=>{z(!0);try{await It(se),Object.prototype.hasOwnProperty.call(se,"tunnelMode")&&se.tunnelMode&&S(se.tunnelMode),Object.prototype.hasOwnProperty.call(se,"tunnelProvider")&&typeof se.tunnelProvider=="string"&&N(se.tunnelProvider),Object.prototype.hasOwnProperty.call(se,"managedLocalTunnelConfigPath")&&E(se.managedLocalTunnelConfigPath??null),Object.prototype.hasOwnProperty.call(se,"managedRemoteTunnelPresets")&&se.managedRemoteTunnelPresets&&W(se.managedRemoteTunnelPresets)}catch{J.error(t("settings.openchamber.tunnel.toast.saveSettingsFailed"))}finally{z(!1)}},[t]),h=l.useCallback(async(se,Ce)=>{y(!0);try{await It({tunnelBootstrapTtlMs:se,tunnelSessionTtlMs:Ce})}catch{J.error(t("settings.openchamber.tunnel.toast.saveTtlFailed"))}finally{y(!1)}},[t]),ae=l.useCallback(async se=>{const Ce=se.token.trim();if(Ce)try{const Xe={...X,[se.presetId]:Ce};await It({managedRemoteTunnelPresetTokens:Xe}),I(Re=>{const Je=new Set(Re);return Je.add(se.presetId),Je})}catch{J.error(t("settings.openchamber.tunnel.toast.saveTokenFailed"))}},[X,t]),ye=l.useCallback(async se=>{b(null),m(null);const Ce=$.find(Re=>Re.provider===se),Xe=Ce?.modes?.some(Re=>Re.key===M)?M:Fn(Ce?.modes?.[0]?.key);await U({tunnelProvider:se,tunnelMode:Xe}),q(se)},[$,q,U,M]),be=l.useCallback(async()=>{const se=await dl({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(se.success&&typeof se.path=="string"&&se.path.trim().length>0){const Ce=se.path.trim();if(!oi(Ce)){J.error(Le);return}E(Ce),await U({managedLocalTunnelConfigPath:Ce});return}Be.current?.click()},[Le,U]),Ee=l.useCallback(se=>{const Ce=se.trim();E(Ce.length>0?Ce:null)},[]),et=l.useCallback(async()=>{if(F&&!oi(F)){J.error(Le);return}await U({managedLocalTunnelConfigPath:F})},[Le,F,U]),Ze=l.useCallback(async()=>{E(null),await U({managedLocalTunnelConfigPath:null})},[U]),it=l.useCallback(async se=>{const Ce=se.target.files?.[0];if(!Ce)return;const Xe=Ce.name.trim();if(Xe.length!==0){if(!oi(Xe)){J.error(Le);return}E(Xe),await U({managedLocalTunnelConfigPath:Xe}),se.target.value=""}},[Le,U]),ot=l.useCallback(async()=>{if(m(null),b(null),M==="managed-local"&&F&&!oi(F)){m(Le),J.error(Le);return}i("starting");try{let se="",Ce="";if(M==="managed-remote"){if(!De){i("idle"),b(t("settings.openchamber.tunnel.toast.selectOrAddManagedRemoteFirst")),J.error(t("settings.openchamber.tunnel.toast.selectOrAddManagedRemoteFirst"));return}se=De.hostname,Ce=(X[De.id]||"").trim(),await U({tunnelMode:"managed-remote",managedRemoteTunnelPresets:D})}const Xe=await ht("/api/openchamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:j,mode:M,...M==="managed-remote"&&De?{managedRemoteTunnelPresetId:De.id,managedRemoteTunnelPresetName:De.name}:{},...M==="managed-remote"&&se?{managedRemoteTunnelHostname:se}:{},...M==="managed-remote"&&Ce?{managedRemoteTunnelToken:Ce}:{},...M==="managed-local"&&F?{configPath:F}:{}})}),Re=await Xe.json();if(!Xe.ok||!Re.ok){if(M==="managed-remote"&&typeof Re.error=="string"&&Re.error.includes("Managed remote tunnel token is required")){i("idle"),b(t("settings.openchamber.tunnel.toast.managedRemoteTokenRequiredBeforeStarting")),J.error(t("settings.openchamber.tunnel.toast.addManagedRemoteTokenBeforeStarting"));return}i("error"),m(Re.error||t("settings.openchamber.tunnel.toast.startFailed")),J.error(Re.error||t("settings.openchamber.tunnel.toast.startFailed"));return}const Je=typeof Re.url=="string"?Re.url:"";if(!Je){i("error"),m(t("settings.openchamber.tunnel.toast.startedButNoPublicUrl")),J.error(t("settings.openchamber.tunnel.toast.startedButNoPublicUrl"));return}if(o({url:Je,connectUrl:typeof Re.connectUrl=="string"?Re.connectUrl:null,bootstrapExpiresAt:typeof Re.bootstrapExpiresAt=="number"?Re.bootstrapExpiresAt:null}),c(Re.activeTunnelMode?Fn(Re.activeTunnelMode):Re.mode?Fn(Re.mode):M),ie(Array.isArray(Re.activeSessions)?Re.activeSessions:[]),Array.isArray(Re.managedRemoteTunnelTokenPresetIds)&&I(new Set(Re.managedRemoteTunnelTokenPresetIds)),typeof Re.localPort=="number"&&Me(Re.localPort),typeof Re.mode=="string"&&S(Fn(Re.mode)),i("active"),Re.replacedTunnel){const Ge=typeof Re.revokedBootstrapCount=="number"?Re.revokedBootstrapCount:0,st=typeof Re.invalidatedSessionCount=="number"?Re.invalidatedSessionCount:0;Ge===1&&st===1?J.warning(t("settings.openchamber.tunnel.toast.replacedTunnelSingleSingle")):Ge===1?J.warning(t("settings.openchamber.tunnel.toast.replacedTunnelSingleManySessions",{invalidatedSessionCount:st})):st===1?J.warning(t("settings.openchamber.tunnel.toast.replacedTunnelManyLinksSingleSession",{revokedBootstrapCount:Ge})):J.warning(t("settings.openchamber.tunnel.toast.replacedTunnelManyMany",{revokedBootstrapCount:Ge,invalidatedSessionCount:st}))}else J.success(t("settings.openchamber.tunnel.toast.linkReady"))}catch{i("error"),m(t("settings.openchamber.tunnel.toast.startFailed")),J.error(t("settings.openchamber.tunnel.toast.startFailed"))}},[Le,D,U,De,X,t,j,M,F]),xt=l.useCallback(async()=>{i("stopping");try{await ht("/api/openchamber/tunnel/stop",{method:"POST"});const se=await ht("/api/openchamber/tunnel/status");if(se.ok){const Ce=await se.json();ie(Array.isArray(Ce.activeSessions)?Ce.activeSessions:[]),I(new Set(Array.isArray(Ce.managedRemoteTunnelTokenPresetIds)?Ce.managedRemoteTunnelTokenPresetIds:[])),Me(typeof Ce.localPort=="number"?Ce.localPort:null)}o(null),c(null),u(null),i("idle"),J.success(t("settings.openchamber.tunnel.toast.stopped"))}catch{i("error"),m(t("settings.openchamber.tunnel.toast.stopFailed")),J.error(t("settings.openchamber.tunnel.toast.stopFailed"))}},[t]),bt=l.useCallback(async()=>{if(r?.connectUrl)try{await navigator.clipboard.writeText(r.connectUrl),x(!0),J.success(t("settings.openchamber.tunnel.toast.connectLinkCopied")),setTimeout(()=>x(!1),2e3)}catch{J.error(t("settings.openchamber.tunnel.toast.copyUrlFailed"))}},[t,r?.connectUrl]),Nt=l.useCallback(async se=>{const Ce=$i.find(Xe=>Xe.value===se);Ce&&(me(Ce.ms),await h(Ce.ms,ge))},[h,ge]),Se=l.useCallback(async se=>{const Ce=Vi.find(Xe=>Xe.value===se);!Ce||Ce.ms===null||(Ie(Ce.ms),await h(ve,Ce.ms))},[ve,h]),Qe=l.useCallback(async se=>{b(null),m(null),a!=="active"&&a!=="stopping"&&a!=="starting"&&i("idle"),await U({tunnelMode:se,managedRemoteTunnelPresets:D})},[D,U,a]),nt=l.useCallback(async(se,Ce)=>{try{await It({managedRemoteTunnelPresets:Ce})}catch{J.error(t("settings.openchamber.tunnel.toast.saveSelectedManagedRemoteFailed"))}},[t]),rt=l.useCallback(se=>{const Ce=D.find(Xe=>Xe.id===se);Ce&&(A(Ce.id),b(null),nt(Ce,D))},[D,nt]),gt=l.useCallback(async()=>{const se=V.trim(),Ce=rr(G),Xe=ne.trim();if(!se){J.error(t("settings.openchamber.tunnel.toast.tunnelNameRequired"));return}if(!Ce){J.error(t("settings.openchamber.tunnel.toast.managedRemoteHostnameRequired"));return}if(!Xe){J.error(t("settings.openchamber.tunnel.toast.managedRemoteTokenRequired"));return}if(D.some(Ge=>Ge.hostname===Ce)){J.error(t("settings.openchamber.tunnel.toast.hostnameAlreadyExists"));return}const Re={id:oj(),name:se,hostname:Ce},Je=[...D,Re];W(Je),A(Re.id),Z(Ge=>({...Ge,[Re.id]:!0})),te(Ge=>({...Ge,[Re.id]:Xe})),b(null),L(!1),Q(""),ue(""),xe(""),await U({tunnelMode:"managed-remote",managedRemoteTunnelPresets:Je,managedRemoteTunnelPresetTokens:{...X,[Re.id]:Xe}}),await ae({presetId:Re.id,presetName:Re.name,hostname:Re.hostname,token:Xe}),J.success(t("settings.openchamber.tunnel.toast.managedRemoteSaved"))},[D,G,V,ne,ae,U,X,t]),wt=l.useCallback(async se=>{const Ce=D.find(st=>st.id===se);if(!Ce)return;const Xe=D.filter(st=>st.id!==Ce.id),Re=Xe[0]?.id||"",Je=Y===Ce.id?Re:Y,Ge=Object.fromEntries(Object.entries(X).filter(([st,jt])=>st!==Ce.id&&jt.trim().length>0));W(Xe),A(Je),Z(st=>{const jt={...st};return delete jt[Ce.id],jt}),te(st=>{const jt={...st};return delete jt[Ce.id],jt}),I(st=>{const jt=new Set(st);return jt.delete(Ce.id),jt}),b(null),await U({managedRemoteTunnelPresets:Xe,managedRemoteTunnelPresetTokens:Ge}),J.success(t("settings.openchamber.tunnel.toast.managedRemoteRemoved"))},[D,U,Y,X,t]),Pe="gap-2 border-[var(--primary-base)] bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:bg-[var(--primary-hover)] hover:text-[var(--primary-foreground)]";return a==="checking"?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current animate-busy-pulse","aria-label":t("settings.openchamber.tunnel.state.loading")})}):s.jsx(dt,{title:t("settings.openchamber.tunnel.title"),info:s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{children:t("settings.openchamber.tunnel.description")}),s.jsx("p",{children:t("settings.openchamber.tunnel.note.serverSideEnforced")}),s.jsx("p",{children:t("settings.openchamber.tunnel.note.connectLinksOneTime")})]}),divider:!1,children:s.jsxs("div",{className:"space-y-6",children:[ze.length>0&&s.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:s.jsxs("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)]/30 p-3",children:[s.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[s.jsx(K,{name:"information",className:"size-4 text-[var(--status-info)]"}),s.jsx("p",{className:uc,children:t("settings.openchamber.tunnel.section.redeemedAccessLinks")})]}),s.jsx("div",{className:"space-y-1",children:ze.map(se=>{const Ce=se.mode==="quick",Xe=se.mode==="managed-remote",Re=Ce?"border-[var(--status-warning-border)] bg-[var(--status-warning-background)] text-[var(--status-warning)]":Xe?"border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)]":"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",Je=se.isActive?Ce?"text-[var(--status-warning)]":Xe?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-muted-foreground/50",Ge=t(Ce?"settings.openchamber.tunnel.badge.quick":Xe?"settings.openchamber.tunnel.badge.remote":"settings.openchamber.tunnel.badge.local");return s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 rounded border border-[var(--surface-subtle)] bg-[var(--surface-elevated)] px-2 py-1.5",children:[s.jsx(K,{name:"checkbox-blank-circle-fill",className:fe("size-2.5 shrink-0",Je)}),s.jsx("span",{className:fe("typography-micro rounded border px-1.5 py-0.5 uppercase",Re),children:Ge}),s.jsx("span",{className:"typography-meta text-muted-foreground/80",children:t("settings.openchamber.tunnel.session.redeemedAt",{time:ij(se.createdAt,e)})}),s.jsx("span",{className:"typography-meta text-foreground",children:se.isActive?t("settings.openchamber.tunnel.session.expiresIn",{remaining:se.remainingTextForSession}):se.inactiveLabel===t("settings.openchamber.tunnel.state.inactive")?t("settings.openchamber.tunnel.state.inactive"):t("settings.openchamber.tunnel.session.inactiveWithReason",{reason:se.inactiveLabel})})]},se.sessionId)})})]})}),a==="not-available"&&s.jsx("section",{className:"space-y-2 px-2 pb-2 pt-0",children:s.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning)]/30 bg-[var(--status-warning)]/5 p-3",children:[s.jsx(K,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("p",{className:uc,children:t("settings.openchamber.tunnel.notAvailable.dependencyNotFound",{dependency:Te.dependency})}),s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t("settings.openchamber.tunnel.notAvailable.installHint")}),s.jsx("code",{className:"typography-code block rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:Te.installCommand})]})]})}),s.jsxs("section",{className:"space-y-4 px-2 pb-2 pt-0",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{"data-settings-item":"tunnel.provider",className:"space-y-1.5",children:[s.jsx("p",{className:zt,children:t("settings.openchamber.tunnel.field.provider")}),s.jsxs(Lt,{value:j,onValueChange:se=>{ye(se)},disabled:C||a==="starting"||a==="stopping",children:[s.jsx(Ft,{size:Jt,className:"max-w-[16rem]",children:s.jsx(Wt,{placeholder:t("settings.openchamber.tunnel.field.providerPlaceholder"),children:rm(j)})}),s.jsxs(Ot,{children:[$.length>0?$.map(se=>s.jsx(kt,{value:se.provider,children:s.jsx(jd,{provider:se.provider})},se.provider)):s.jsx(kt,{value:"cloudflare",children:s.jsx(jd,{provider:"cloudflare"})}),s.jsx(kt,{value:"__more-soon",disabled:!0,children:t("settings.openchamber.tunnel.option.moreProvidersSoon")})]})]})]}),s.jsxs("div",{"data-settings-item":"tunnel.type",className:"space-y-1.5",children:[s.jsx("p",{className:zt,children:t("settings.openchamber.tunnel.field.tunnelType")}),s.jsx("div",{className:"flex flex-wrap items-center gap-1",children:Oe.map(se=>s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(ee,{variant:"chip",size:"xs","aria-pressed":M===se.value,className:"!font-normal",onClick:()=>{Qe(se.value)},disabled:C||a==="starting"||a==="stopping",children:n(se.labelKey)})}),s.jsx(ks,{sideOffset:8,className:"max-w-xs",children:n(se.tooltipKey)})]},se.value))})]})]}),s.jsxs("div",{"data-settings-item":"tunnel.ttl",className:"mt-2 grid grid-cols-1 gap-2 py-1.5 md:grid-cols-[14rem_auto] md:gap-x-8 md:gap-y-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:fe(zt,"shrink-0"),children:t("settings.openchamber.tunnel.field.connectLinkTtl")}),s.jsxs(Lt,{value:el($i,ve,"1800000"),onValueChange:se=>{Nt(se)},disabled:k||C||a==="starting"||a==="stopping",children:[s.jsx(Ft,{size:Jt,className:"max-w-[11rem] min-w-0",children:s.jsx(Wt,{className:"truncate",children:kd($i,ve,"1800000")})}),s.jsx(Ot,{children:$i.map(se=>s.jsx(kt,{value:se.value,children:se.label},se.value))})]})]}),s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:fe(zt,"shrink-0"),children:t("settings.openchamber.tunnel.field.tunnelSessionTtl")}),s.jsxs(Lt,{value:el(Vi,ge,"28800000"),onValueChange:se=>{Se(se)},disabled:k||C||a==="starting"||a==="stopping",children:[s.jsx(Ft,{size:Jt,className:"max-w-[11rem] min-w-0",children:s.jsx(Wt,{className:"truncate",children:kd(Vi,ge,"28800000")})}),s.jsx(Ot,{children:Vi.map(se=>s.jsx(kt,{value:se.value,children:se.label},se.value))})]})]})]}),M==="quick"&&s.jsx("div",{className:"rounded-lg border border-[var(--status-warning)]/35 bg-[var(--status-warning)]/10 p-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(K,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsxs("div",{children:[s.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:t("settings.openchamber.tunnel.option.mode.quick.tooltip")}),je&&s.jsx("p",{className:"typography-meta mt-1 text-[var(--status-warning)]",children:t("settings.openchamber.tunnel.warning.quickModeReliability")})]})]})}),M==="managed-remote"&&s.jsxs("div",{"data-settings-item":"tunnel.managed-remote",className:"space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:[typeof He=="number"&&s.jsx("div",{className:"rounded-md border border-[var(--status-info-border)] bg-[var(--status-info-background)]/35 px-2 py-1.5",children:s.jsxs("p",{className:"typography-meta text-[var(--status-info)]",children:[t("settings.openchamber.tunnel.note.cloudflareConnectorTarget")," ",s.jsxs("code",{children:["http://localhost:",He]})]})}),s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx(pn,{children:t("settings.openchamber.tunnel.section.savedManagedRemoteTunnels")}),s.jsxs(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>L(se=>!se),disabled:a==="starting"||a==="stopping"||C,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.common.actions.create")]})]}),D.length>0?s.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:D.map((se,Ce)=>{const Xe=X[se.id]||"",Re=T.has(se.id),Je=H[se.id]??!1;return s.jsx("div",{className:fe(Ce<D.length-1&&"border-b border-[var(--surface-subtle)]"),children:s.jsxs(ca,{open:Je,onOpenChange:Ge=>{Z(st=>({...st,[se.id]:Ge})),Ge&&rt(se.id)},className:"py-1.5",children:[s.jsxs("div",{className:"flex items-start gap-2 px-3",children:[s.jsxs(da,{type:"button",className:"group flex-1 justify-start gap-2 rounded-md px-0 py-1 pr-1 text-left hover:bg-[var(--interactive-hover)]",disabled:a==="starting"||a==="stopping"||C,children:[Je?s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(K,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"}),s.jsx("span",{className:"typography-ui-label min-w-0 flex-1 truncate text-foreground",children:se.name})]}),s.jsx(ee,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0 text-muted-foreground hover:text-[var(--status-error)]","aria-label":t("settings.openchamber.tunnel.actions.removePresetAria",{name:se.name}),onClick:()=>{wt(se.id)},disabled:a==="starting"||a==="stopping"||C,children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsx(ua,{className:"pt-1.5",children:s.jsxs("div",{className:"space-y-1 px-3 pb-2",children:[s.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:[t("settings.openchamber.tunnel.field.hostnameLabel")," ",s.jsx("code",{children:se.hostname})]}),s.jsx(at,{type:"password",value:Xe,onChange:Ge=>{const st=Ge.target.value;b(null),te(jt=>({...jt,[se.id]:st}))},onBlur:Ge=>{const st=Ge.currentTarget.value.trim();st&&ae({presetId:se.id,presetName:se.name,hostname:se.hostname,token:st})},placeholder:t(Re?"settings.openchamber.tunnel.field.savedTokenAvailablePlaceholder":"settings.openchamber.tunnel.field.pasteTokenPlaceholder"),className:"h-7",disabled:a==="starting"||a==="stopping"}),s.jsx("div",{className:"flex items-center justify-end",children:s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal",disabled:a==="starting"||a==="stopping"||Xe.trim().length===0,onClick:()=>{ae({presetId:se.id,presetName:se.name,hostname:se.hostname,token:Xe})},children:t("settings.openchamber.tunnel.actions.saveToken")})})]})})]})},se.id)})}):s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t("settings.openchamber.tunnel.empty.noManagedRemoteTunnels")}),B&&s.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[s.jsx(at,{value:V,onChange:se=>Q(se.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetNamePlaceholder"),className:"h-7",disabled:C||a==="starting"||a==="stopping"}),s.jsx(at,{value:G,onChange:se=>ue(se.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetHostnamePlaceholder"),className:"h-7",disabled:C||a==="starting"||a==="stopping"}),s.jsx(at,{type:"password",value:ne,onChange:se=>xe(se.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetTokenPlaceholder"),className:"h-7",disabled:C||a==="starting"||a==="stopping"}),typeof He=="number"&&s.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:[t("settings.openchamber.tunnel.note.cloudflareConnectorTargetUse")," ",s.jsxs("code",{children:["http://localhost:",He]}),"."]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{gt()},disabled:C||a==="starting"||a==="stopping",children:t("settings.common.actions.saveChanges")}),s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{L(!1),Q(""),ue(""),xe("")},disabled:C||a==="starting"||a==="stopping",children:t("settings.common.actions.cancel")})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:t("settings.openchamber.tunnel.note.tokensSavedPerTunnel")}),s.jsx($t,{children:t("settings.openchamber.tunnel.tooltip.tokensSavedPath")})]}),!De&&w&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:w})]}),M==="managed-local"&&s.jsx("div",{"data-settings-item":"tunnel.managed-local-config",className:"space-y-2 rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] p-3",children:s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("p",{className:zt,children:t("settings.openchamber.tunnel.field.configurationFile")}),s.jsx("input",{ref:Be,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:se=>{it(se)}}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(at,{value:F||"",onChange:se=>{Ee(se.target.value)},onBlur:()=>{et()},placeholder:t("settings.openchamber.tunnel.field.configurationFilePlaceholder"),className:"h-7",disabled:a==="starting"||a==="stopping"||C}),s.jsx(ee,{variant:"outline",size:"xs",className:"h-7 w-7 p-0","aria-label":t("settings.openchamber.tunnel.actions.browseConfigFileAria"),onClick:()=>{be()},disabled:a==="starting"||a==="stopping"||C,children:s.jsx(K,{name:"folder",className:"size-3.5"})}),F&&s.jsx(ee,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0","aria-label":t("settings.openchamber.tunnel.actions.clearConfigFileAria"),onClick:()=>{Ze()},disabled:a==="starting"||a==="stopping"||C,children:s.jsx(K,{name:"close",className:"size-3.5"})})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t(F?"settings.openchamber.tunnel.note.customConfigUsed":"settings.openchamber.tunnel.note.defaultConfigUsed")}),Fe&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Le})]})}),!We&&s.jsxs("div",{"data-settings-item":"tunnel.start",className:"space-y-6",children:[s.jsx("div",{className:"rounded-lg border border-[var(--status-info-border)] bg-[var(--status-info-background)] p-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(K,{name:"information",className:"mt-0.5 size-4 shrink-0 text-[var(--status-info)]"}),s.jsxs("div",{className:"space-y-1",children:[M==="managed-remote"&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:t("settings.openchamber.tunnel.note.managedRemoteRequiresDomain")}),s.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{Ue(Z1)},children:[t("settings.openchamber.tunnel.actions.openManagedRemoteDocs"),s.jsx(K,{name:"external-link",className:"size-3.5"})]})]}),M==="managed-local"&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:t("settings.openchamber.tunnel.note.managedLocalUsesConfig")}),s.jsxs("button",{type:"button",className:"typography-meta inline-flex items-center gap-1 text-[var(--status-info)] underline underline-offset-2 hover:opacity-90",onClick:()=>{Ue(ej)},children:[t("settings.openchamber.tunnel.actions.openManagedLocalDocs"),s.jsx(K,{name:"external-link",className:"size-3.5"})]})]}),s.jsx("p",{className:"typography-meta text-[var(--status-info)]",children:t("settings.openchamber.tunnel.note.startModeAndGenerateLink",{mode:n(po.find(se=>se.value===M)?.labelKey??"settings.openchamber.tunnel.option.mode.quick.label")})})]})]})}),M==="managed-remote"&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("p",{className:zt,children:t("settings.openchamber.tunnel.field.managedRemoteTunnelToConnect")}),s.jsxs(Lt,{value:Y||(D[0]?.id??""),onValueChange:se=>{rt(se)},disabled:C||a==="starting"||a==="stopping"||D.length<=1,children:[s.jsx(Ft,{size:Jt,children:s.jsx(Wt,{placeholder:t("settings.openchamber.tunnel.field.selectSavedTunnelPlaceholder"),children:De?.name})}),s.jsx(Ot,{fitContent:!0,children:D.map(se=>s.jsx(kt,{value:se.id,children:se.name},se.id))})]})]}),_e&&s.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(K,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:t("settings.openchamber.tunnel.warning.replacesActiveTunnel")})]})}),s.jsx(ee,{size:"sm",variant:"outline",onClick:ot,disabled:a==="starting"||C||M==="managed-remote"&&!De||M==="managed-local"&&Fe,className:fe(Pe,a==="starting"&&"opacity-70"),children:a==="starting"?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"})," ",t("settings.openchamber.tunnel.actions.startingTunnel")]}):t("settings.openchamber.tunnel.actions.startTunnel")})]})]}),We&&r&&s.jsxs("section",{"data-settings-item":"tunnel.start",className:"space-y-4 px-2 pb-2 pt-0",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"size-2 shrink-0 rounded-full bg-[var(--status-success)]"}),s.jsx("p",{className:"typography-meta font-medium text-foreground",children:t("settings.openchamber.tunnel.state.tunnelReady")})]}),s.jsxs("div",{children:[s.jsx("p",{className:"typography-meta mb-1 text-muted-foreground/70",children:t("settings.openchamber.tunnel.field.publicUrlHint")}),s.jsx("code",{className:"typography-code block truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:r.url})]}),Ve&&r.connectUrl&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("p",{className:"typography-meta mb-1 text-muted-foreground/70",children:t("settings.openchamber.tunnel.field.connectLink")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"typography-code flex-1 truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:r.connectUrl}),s.jsxs(ee,{size:"sm",variant:"ghost",onClick:bt,className:"shrink-0 gap-1.5",children:[g?s.jsx(K,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):s.jsx(K,{name:"file-copy",className:"size-3.5"}),t(g?"settings.openchamber.tunnel.actions.copied":"settings.common.actions.copyAll")]})]}),s.jsxs("p",{className:"typography-meta mt-1 text-muted-foreground/70",children:[t("settings.openchamber.tunnel.field.expires"),": ",r.bootstrapExpiresAt?oe:t("settings.openchamber.tunnel.state.never")]})]}),s.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-lg border border-border/50 bg-[var(--surface-elevated)] p-4",children:[p?s.jsx("img",{src:p,alt:t("settings.openchamber.tunnel.field.connectQrAlt"),className:"size-48"}):s.jsx("div",{className:"size-48 rounded bg-muted/30"}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.openchamber.tunnel.note.scanQrToConnect")})]})]})]}),s.jsx("div",{className:"pt-1",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ee,{size:"sm",variant:"outline",onClick:ot,disabled:a==="stopping"||C||M==="managed-local"&&Fe,className:Pe,children:[s.jsx(K,{name:"restart",className:"size-3.5"}),t("settings.openchamber.tunnel.actions.newConnectLink")]}),s.jsx(ee,{size:"sm",variant:"ghost",onClick:xt,disabled:a==="stopping"||C,className:"gap-2 text-[var(--status-error)]",children:a==="stopping"?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"})," ",t("settings.openchamber.tunnel.actions.stopping")]}):t("settings.openchamber.tunnel.actions.stopTunnel")})]})})]}),a==="error"&&f&&s.jsxs("section",{className:"space-y-3 px-2 pb-2 pt-0",children:[s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:f}),s.jsx(ee,{size:"sm",variant:"ghost",onClick:ot,children:t("settings.openchamber.tunnel.actions.retry")})]})]})})},om=()=>{const{t}=lt(),[e,n]=we.useState(""),[a,i]=we.useState(!0),[r,o]=we.useState(!1),d=ke(g=>g.showOpenCodeUpdateNotifications),c=ke(g=>g.setShowOpenCodeUpdateNotifications),p=ke(g=>g.agentControlToolEnabled),u=ke(g=>g.setAgentControlToolEnabled);we.useEffect(()=>{let g=!1;return(async()=>{try{const x=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!x.ok)return;const k=await x.json().catch(()=>null);if(g||!k)return;const y=typeof k.opencodeBinary=="string"?k.opencodeBinary.trim():"";n(y)}catch{}finally{g||i(!1)}})(),()=>{g=!0}},[]);const f=we.useCallback(async()=>{if(!(typeof window>"u")&&ls())try{const g=await dl();g.success&&g.path&&g.path.trim().length>0&&n(g.path.trim())}catch{}},[]),m=we.useCallback(async()=>{o(!0);try{const g=e.trim(),x=g.length>=2&&(g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'"))?g.slice(1,-1).trim():g;await It({opencodeBinary:x}),await _n({message:t("settings.openchamber.opencodeCli.actions.restartingOpenCode"),mode:"projects",scopes:["all"]})}finally{o(!1)}},[t,e]),w=we.useCallback(g=>{c(g),It({showOpenCodeUpdateNotifications:g})},[c]),b=we.useCallback(g=>{u(g),It({agentControlToolEnabled:g})},[u]);return s.jsx(dt,{title:t("settings.openchamber.opencodeCli.title"),children:s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs(Xt,{settingsItem:"sessions.opencode-binary",label:t("settings.openchamber.opencodeCli.field.binaryPath"),info:s.jsxs(s.Fragment,{children:[t("settings.openchamber.opencodeCli.tipPrefix")," ",s.jsx("span",{className:"font-mono",children:"OPENCODE_BINARY"})," ",t("settings.openchamber.opencodeCli.tipMiddle")," ",s.jsx("span",{className:"font-mono",children:"~/.config/openchamber/settings.json"}),"."]}),alignEnd:!1,controlClassName:"@xl:w-[20rem]",children:[s.jsx(at,{value:e,onChange:g=>n(g.target.value),placeholder:t("settings.openchamber.opencodeCli.field.binaryPathPlaceholder"),disabled:a||r,className:"h-8 min-w-0 flex-1 font-mono text-xs"}),s.jsx(ee,{type:"button",variant:"outline",size:"xs",onClick:f,disabled:a||r||!ls(),className:Is,"aria-label":t("settings.openchamber.opencodeCli.actions.browseAria"),title:t("settings.openchamber.opencodeCli.actions.browse"),children:s.jsx(K,{name:"folder",className:"h-4 w-4"})})]}),s.jsxs(la,{className:Ds,children:[!uu()&&s.jsx(Ct,{settingsItem:"sessions.opencode-update-notifications",checked:d,onChange:w,label:t("settings.openchamber.opencodeCli.field.showUpdateNotifications"),ariaLabel:t("settings.openchamber.opencodeCli.field.showUpdateNotificationsAria")}),s.jsx(Ct,{settingsItem:"sessions.agent-control-tool",checked:p,onChange:b,label:t("settings.openchamber.opencodeCli.field.agentControlTool"),ariaLabel:t("settings.openchamber.opencodeCli.field.agentControlToolAria"),info:t("settings.openchamber.opencodeCli.field.agentControlToolInfo")}),s.jsx("div",{className:"flex justify-start py-1.5",children:s.jsx(ee,{type:"button",size:"xs",onClick:m,disabled:a||r,className:"shrink-0 !font-normal",children:t(r?"settings.common.actions.saving":"settings.openchamber.opencodeCli.actions.saveAndReload")})})]})]})})},lm=()=>{const{t}=lt(),e=ls()&&Wa(),n=e&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",[a,i]=we.useState(!1),[r,o]=we.useState(!1),[d,c]=we.useState(""),[p,u]=we.useState(""),[f,m]=we.useState(!1),[w,b]=we.useState(!1),[g,x]=we.useState(null),[k,y]=we.useState(!0),[C,z]=we.useState(!1),[j,N]=we.useState(!1),[v,P]=we.useState(!1),[$,O]=we.useState(!1),[M,S]=we.useState(!1),[F,E]=we.useState(!1),[D,W]=we.useState(!1),[H,Z]=we.useState(!0),[Y,A]=we.useState(!0),[X,te]=we.useState(!1),[T,I]=we.useState(!1),[B,L]=we.useState(!1),[V,Q]=we.useState(null),[G,ue]=we.useState(null);we.useEffect(()=>{if(!e){y(!1);return}let de=!1;return(async()=>{try{const he=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!he.ok)throw new Error(t("settings.openchamber.desktopNetwork.error.loadFailed"));const Me=await he.json().catch(()=>null);if(de)return;const Le=Me?.desktopLanAccessEnabled===!0,Be=typeof Me?.desktopUiPassword=="string"?Me.desktopUiPassword:"";i(Le),o(Le),c(Be),u(Be),b(Me?.desktopLanAccessActive===!0),x(typeof Me?.desktopLanAccessBlockedReason=="string"?Me.desktopLanAccessBlockedReason:null);const Fe=Me?.desktopMacMenuBarEnabled!==!1;Z(Fe),A(Fe),Q(null)}catch(he){de||Q(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.loadFailed"))}finally{de||y(!1)}})(),()=>{de=!0}},[e,t]),we.useEffect(()=>{if(!e){N(!1);return}let de=!1;return(async()=>{const he=await Hg();de||(N(he?.supported===!0),P(he?.enabled===!0))})(),()=>{de=!0}},[e]),we.useEffect(()=>{if(!e){S(!1);return}let de=!1;return(async()=>{const he=await Wg();de||(S(he?.supported===!0),E(he?.enabled===!0))})(),()=>{de=!0}},[e]),we.useEffect(()=>{if(!e){te(!1);return}let de=!1;return(async()=>{const he=await Gg();de||(te(he?.supported===!0),I(he?.enabled===!0))})(),()=>{de=!0}},[e]),we.useEffect(()=>{if(!e||!r){ue(null);return}let de=!1;return(async()=>{const he=await du();de||ue(he)})(),()=>{de=!0}},[r,e]);const ne=r!==a||p!==d||Y!==H,xe=we.useMemo(()=>{if(typeof window>"u")return null;const he=Ga()||window.location.href;let Me=0;try{Me=Number(new URL(he).port)}catch{Me=Number(window.location.port)}return Number.isFinite(Me)&&Me>0?Me:null},[]),ve=r&&w&&G&&xe?`http://${G}:${xe}`:null,me=r&&!p.trim(),ge=a&&!w&&g==="missing-password",Ie=k||C||!ne||me,oe=we.useCallback(de=>{u(de),de.trim()||o(!1)},[]),ce=we.useCallback(async()=>{if(!j||$)return;const de=!v;P(de),O(!0),Q(null);try{const he=await qg(de);if(!he?.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.launchAtLoginUnsupported"));P(he.enabled)}catch(he){P(!de),Q(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.launchAtLoginSaveFailed"))}finally{O(!1)}},[$,v,j,t]),pe=we.useCallback(async()=>{if(!M||D)return;const de=!F;E(de),W(!0),Q(null);try{const he=await Jg(de);if(!he)throw new Error(t("settings.openchamber.desktopNetwork.error.minimizeToTraySaveFailed"));if(!he.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.minimizeToTrayUnsupported"));E(he.enabled)}catch(he){E(!de),Q(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.minimizeToTraySaveFailed"))}finally{W(!1)}},[D,F,M,t]),ie=we.useCallback(async()=>{if(!X||B)return;const de=!T;I(de),L(!0),Q(null);try{const he=await Yg(de);if(!he?.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.keepAwakeUnsupported"));I(he.enabled)}catch(he){I(!de),Q(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.keepAwakeSaveFailed"))}finally{L(!1)}},[B,T,X,t]),le=we.useCallback(async()=>{if(ne){z(!0),Q(null);try{if(!(await ht("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:r,desktopUiPassword:p,desktopMacMenuBarEnabled:Y})})).ok)throw new Error(t("settings.openchamber.desktopNetwork.error.saveFailed"));if(i(r),c(p),Z(Y),!await Qg())throw new Error(t("settings.openchamber.desktopNetwork.error.savedRestartFailed"))}catch(de){Q(de instanceof Error?de.message:t("settings.openchamber.desktopNetwork.error.saveFailed")),z(!1)}}},[Y,p,r,ne,t]);return e?s.jsx(dt,{title:t("settings.openchamber.desktopNetwork.title"),children:s.jsxs("div",{className:"space-y-3",children:[j||n||M||X?s.jsxs("div",{className:Ds,children:[j?s.jsx(Ct,{settingsItem:"sessions.desktop-launch-at-login",checked:v,onChange:de=>{de!==v&&ce()},disabled:$,label:t("settings.openchamber.desktopNetwork.field.launchAtLogin"),info:t("settings.openchamber.desktopNetwork.field.launchAtLoginDescription"),ariaLabel:t("settings.openchamber.desktopNetwork.field.launchAtLoginAria")}):null,n?s.jsx(Ct,{settingsItem:"sessions.desktop-mac-menu-bar",checked:Y,onChange:A,disabled:k||C,label:t("settings.openchamber.desktopNetwork.field.macMenuBar"),info:t("settings.openchamber.desktopNetwork.field.macMenuBarDescription"),ariaLabel:t("settings.openchamber.desktopNetwork.field.macMenuBarAria")}):null,M?s.jsx(Ct,{settingsItem:"sessions.desktop-minimize-to-tray",checked:F,onChange:de=>{de!==F&&pe()},disabled:D,label:t("settings.openchamber.desktopNetwork.field.minimizeToTray"),info:t("settings.openchamber.desktopNetwork.field.minimizeToTrayDescription"),ariaLabel:t("settings.openchamber.desktopNetwork.field.minimizeToTrayAria")}):null,X?s.jsx(Ct,{settingsItem:"sessions.desktop-keep-awake",checked:T,onChange:de=>{de!==T&&ie()},disabled:B,label:t("settings.openchamber.desktopNetwork.field.keepAwake"),info:t("settings.openchamber.desktopNetwork.field.keepAwakeDescription"),ariaLabel:t("settings.openchamber.desktopNetwork.field.keepAwakeAria")}):null]}):null,s.jsxs(ns,{settingsItem:"sessions.desktop-ui-password",label:s.jsx("label",{htmlFor:"desktop-ui-password",children:t("settings.openchamber.desktopPassword.field.password")}),info:t("settings.openchamber.desktopPassword.field.passwordDescription"),children:[s.jsx(at,{id:"desktop-ui-password",type:f?"text":"password",className:"h-8 min-w-0 flex-1",value:p,onChange:de=>oe(de.target.value),placeholder:t("settings.openchamber.desktopPassword.field.passwordPlaceholder"),disabled:k||C,required:r,"aria-invalid":me}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>m(de=>!de),className:Is,"aria-label":t(f?"settings.openchamber.desktopPassword.actions.hidePassword":"settings.openchamber.desktopPassword.actions.showPassword"),"aria-pressed":f,children:s.jsx(K,{name:f?"eye-off":"eye",className:"h-4 w-4"})})]}),s.jsx("div",{className:Ds,children:s.jsx(Ct,{settingsItem:"sessions.desktop-lan-access",checked:r,onChange:o,disabled:k||C,label:t("settings.openchamber.desktopNetwork.field.allowLanAccess"),info:t("settings.openchamber.desktopNetwork.field.allowLanAccessDescription"),description:s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"block text-[var(--status-warning)]/85",children:t("settings.openchamber.desktopNetwork.field.warning")}),me||ge?s.jsx("span",{className:"block text-[var(--status-warning)]/85",children:t("settings.openchamber.desktopNetwork.field.passwordRequiredWarning")}):null]}),ariaLabel:t("settings.openchamber.desktopNetwork.field.allowLanAccessAria")})}),V?s.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:V}):null,ve?s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[t(ne&&!a?"settings.openchamber.desktopNetwork.hint.openAfterRestart":"settings.openchamber.desktopNetwork.hint.openNow"),s.jsx("span",{className:"font-mono text-foreground",children:ve})]}):null,s.jsx("div",{className:"flex justify-start py-1.5",children:s.jsx(ee,{type:"button",size:"xs",onClick:le,disabled:Ie,className:"shrink-0 !font-normal",children:t(C?"settings.common.actions.saving":"settings.openchamber.desktopNetwork.actions.saveAndRestart")})})]})}):null},cj=new Set(["shift","control","alt","meta"]),dj=t=>{if(cj.has(t.key.toLowerCase()))return null;const e=[];(t.metaKey||t.ctrlKey)&&e.push("mod"),t.shiftKey&&e.push("shift"),t.altKey&&e.push("alt");const n=Yp(t.key);return n?(e.push(n),Ra(e.join("+"))):null},uj=()=>{const t=tt.c(54),{t:e}=lt();let n;t[0]!==e?(n=B=>e(B),t[0]=e,t[1]=n):n=t[1];const a=n,i=ke(mj),r=ke(pj),o=ke(gj),d=ke(fj);let c;if(t[2]===Symbol.for("react.memo_cache_sentinel")){e:{const B=qp();if(!ds()){c=B;break e}c=B.filter(hj)}t[2]=c}else c=t[2];const p=c;let u;t[3]!==a?(u=(B,L)=>{const V=`settings.openchamber.keyboardShortcuts.action.${B}.label`,Q=a(V);return Q===V?L:Q},t[3]=a,t[4]=u):u=t[4];const f=u,[m,w]=l.useState(null);let b;t[5]===Symbol.for("react.memo_cache_sentinel")?(b={},t[5]=b):b=t[5];const[g,x]=l.useState(b),[k,y]=l.useState(""),[C,z]=l.useState(""),[j,N]=l.useState(null),v=xj;let P;t[6]!==i?(P=(B,L)=>{const V=Ra(L);for(const Q of p){if(Q.id===B)continue;const G=El(Q.id,i);if(Ra(G)===V)return Q.id}return null},t[6]=i,t[7]=P):P=t[7];const $=P;let O;t[8]!==$||t[9]!==r||t[10]!==i||t[11]!==e?(O=(B,L)=>{const V=Ra(L),Q=$(B,V);if(Q){N({actionId:B,combo:V,conflictActionId:Q}),y("");return}const G={...i,[B]:V};r(B,V),v(G),N(null),y(""),z(Dl(V)?e("settings.openchamber.keyboardShortcuts.warning.riskyBrowserShortcut"):""),x(ue=>{const ne={...ue};return delete ne[B],ne})},t[8]=$,t[9]=r,t[10]=i,t[11]=e,t[12]=O):O=t[12];const M=O;let S;t[13]!==j||t[14]!==r||t[15]!==i||t[16]!==e?(S=()=>{if(!j)return;const B={...i,[j.conflictActionId]:Rl,[j.actionId]:j.combo};r(j.conflictActionId,Rl),r(j.actionId,j.combo),v(B),N(null),y(""),z(Dl(j.combo)?e("settings.openchamber.keyboardShortcuts.warning.riskyBrowserShortcut"):""),x(L=>{const V={...L};return delete V[j.actionId],V})},t[13]=j,t[14]=r,t[15]=i,t[16]=e,t[17]=S):S=t[17];const F=S;let E;t[18]!==o||t[19]!==i?(E=B=>{const L={...i};delete L[B],o(B),v(L),x(V=>{const Q={...V};return delete Q[B],Q}),N(null),y(""),z("")},t[18]=o,t[19]=i,t[20]=E):E=t[20];const D=E;let W;t[21]!==e?(W=e("settings.openchamber.keyboardShortcuts.title"),t[21]=e,t[22]=W):W=t[22];let H;t[23]!==e?(H=e("settings.openchamber.keyboardShortcuts.tooltip"),t[23]=e,t[24]=H):H=t[24];let Z;t[25]!==d?(Z=()=>{d(),v({}),x({}),N(null),y(""),z("")},t[25]=d,t[26]=Z):Z=t[26];let Y;t[27]!==e?(Y=e("settings.openchamber.keyboardShortcuts.actions.resetAll"),t[27]=e,t[28]=Y):Y=t[28];let A;t[29]!==Z||t[30]!==Y?(A=s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Z,children:Y}),t[29]=Z,t[30]=Y,t[31]=A):A=t[31];let X;t[32]!==F||t[33]!==k||t[34]!==j||t[35]!==e||t[36]!==C?(X=(k||C||j)&&s.jsxs("div",{className:"mb-2 space-y-2",children:[j&&s.jsxs("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 flex flex-col @xl:flex-row @xl:items-center justify-between gap-3",children:[s.jsx("span",{className:"typography-meta text-foreground",children:e("settings.openchamber.keyboardShortcuts.overwritePrompt")}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",onClick:F,children:e("settings.openchamber.keyboardShortcuts.actions.overwrite")}),s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>N(null),children:e("settings.common.actions.cancel")})]})]}),k&&s.jsx("div",{className:"rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3 typography-meta text-foreground",children:k}),C&&s.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 typography-meta text-foreground",children:C})]}),t[32]=F,t[33]=k,t[34]=j,t[35]=e,t[36]=C,t[37]=X):X=t[37];let te;t[38]!==f||t[39]!==m||t[40]!==g||t[41]!==D||t[42]!==M||t[43]!==i||t[44]!==e?(te=p.map((B,L)=>{const V=El(B.id,i),Q=g[B.id],G=Q??V,ue=typeof Q=="string"&&Ra(Q)!==Ra(V);return s.jsx("div",{className:fe("py-1.5",L>0&&"border-t border-border/40"),children:s.jsxs(Xt,{label:f(B.id,B.label),alignEnd:!1,children:[s.jsx(at,{readOnly:!0,value:m===B.id?e("settings.openchamber.keyboardShortcuts.field.pressKeys"):Jp(G),onFocus:()=>{w(B.id),y("")},onBlur:()=>{m===B.id&&w(null)},onKeyDown:ne=>{if(ne.preventDefault(),ne.stopPropagation(),ne.key==="Escape"){w(null);return}const xe=dj(ne);xe&&(x(ve=>({...ve,[B.id]:xe})),w(null),N(null),y(""))},className:"h-7 w-40 min-w-0 typography-ui-label text-center"}),s.jsx(ee,{type:"button",variant:"secondary",size:"xs",className:"!font-normal",onClick:()=>{const ne=g[B.id];if(!ne){y(e("settings.openchamber.keyboardShortcuts.error.captureFirst"));return}M(B.id,ne)},disabled:!ue,children:e("settings.common.actions.saveChanges")}),s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>D(B.id),children:e("settings.common.actions.reset")})]})},B.id)}),t[38]=f,t[39]=m,t[40]=g,t[41]=D,t[42]=M,t[43]=i,t[44]=e,t[45]=te):te=t[45];let T;t[46]!==te?(T=s.jsx("div",{children:te}),t[46]=te,t[47]=T):T=t[47];let I;return t[48]!==A||t[49]!==X||t[50]!==T||t[51]!==W||t[52]!==H?(I=s.jsxs(dt,{settingsItem:"shortcuts.keyboard-shortcuts",title:W,divider:!1,info:H,headerAction:A,children:[X,T]}),t[48]=A,t[49]=X,t[50]=T,t[51]=W,t[52]=H,t[53]=I):I=t[53],I};function mj(t){return t.shortcutOverrides}function pj(t){return t.setShortcutOverride}function gj(t){return t.clearShortcutOverride}function fj(t){return t.resetAllShortcutOverrides}function hj(t){return t.id!=="toggle_prompt_navigator"}function xj(t){It({shortcutOverrides:t})}const cm=()=>{const t=tt.c(2),[e,n]=l.useState(0);let a,i;return t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>cl(()=>n(Tj)),i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),l.useEffect(a,i),e},bj=t=>{const e=tt.c(78),{section:n}=t,{t:a}=lt(),{isMobile:i}=Vs();cm();let r;e[0]!==i?(r=i&&In(),e[0]=i,e[1]=r):r=e[1];const o=r;let d;e[2]===Symbol.for("react.memo_cache_sentinel")?(d=ds(),e[2]=d):d=e[2];const c=d;let p;e[3]===Symbol.for("react.memo_cache_sentinel")?(p=ls()&&Wa(),e[3]=p):p=e[3];const u=p;if(!n){let X,te,T,I,B,L;e[4]===Symbol.for("react.memo_cache_sentinel")?(X=s.jsx(Tr,{}),te=s.jsx(am,{}),T=u&&s.jsx(lm,{}),I=!c&&s.jsx(om,{}),B=s.jsx(sm,{}),L=In()&&!ls()&&!c&&!ll()&&s.jsx(nm,{}),e[4]=X,e[5]=te,e[6]=T,e[7]=I,e[8]=B,e[9]=L):(X=e[4],te=e[5],T=e[6],I=e[7],B=e[8],L=e[9]);let V;e[10]!==o?(V=o&&s.jsx(Iu,{}),e[10]=o,e[11]=V):V=e[11];let Q;return e[12]!==V?(Q=s.jsxs(ps,{showSaveStatus:!0,className:"openchamber-page-body space-y-3 sm:space-y-6",children:[X,te,T,I,B,L,V]}),e[12]=V,e[13]=Q):Q=e[13],Q}let f;e[14]!==n?(f=()=>{switch(n){case"general":return s.jsx(vj,{});case"visual":return s.jsx(wj,{});case"chat":return s.jsx(jj,{});case"sessions":return s.jsx(kj,{});case"shortcuts":return s.jsx(yj,{});case"git":return s.jsx(Nj,{});case"github":return s.jsx(Sj,{});case"notifications":return s.jsx(Cj,{});case"voice":return s.jsx(Ij,{});case"tunnel":return s.jsx(Pj,{});default:return null}},e[14]=n,e[15]=f):f=e[15];const m=f;let w;e[16]!==a?(w=a("settings.page.general.title"),e[16]=a,e[17]=w):w=e[17];let b;e[18]!==a?(b=a("settings.page.appearance.title"),e[18]=a,e[19]=b):b=e[19];let g;e[20]!==a?(g=a("settings.page.chat.title"),e[20]=a,e[21]=g):g=e[21];let x;e[22]!==a?(x=a("settings.page.sessions.title"),e[22]=a,e[23]=x):x=e[23];let k;e[24]!==a?(k=a("settings.page.shortcuts.title"),e[24]=a,e[25]=k):k=e[25];let y;e[26]!==a?(y=a("settings.page.git.title"),e[26]=a,e[27]=y):y=e[27];let C;e[28]!==a?(C=a("settings.page.git.title"),e[28]=a,e[29]=C):C=e[29];let z;e[30]!==a?(z=a("settings.page.notifications.title"),e[30]=a,e[31]=z):z=e[31];let j;e[32]!==a?(j=a("settings.page.voice.title"),e[32]=a,e[33]=j):j=e[33];let N;e[34]!==a?(N=a("settings.page.tunnel.title"),e[34]=a,e[35]=N):N=e[35];let v;e[36]!==y||e[37]!==C||e[38]!==z||e[39]!==j||e[40]!==N||e[41]!==w||e[42]!==b||e[43]!==g||e[44]!==x||e[45]!==k?(v={general:w,visual:b,chat:g,sessions:x,shortcuts:k,git:y,github:C,notifications:z,voice:j,tunnel:N},e[36]=y,e[37]=C,e[38]=z,e[39]=j,e[40]=N,e[41]=w,e[42]=b,e[43]=g,e[44]=x,e[45]=k,e[46]=v):v=e[46];const P=v[n];let $;e[47]!==a?($=a("settings.page.general.description"),e[47]=a,e[48]=$):$=e[48];let O;e[49]!==a?(O=a("settings.page.appearance.description"),e[49]=a,e[50]=O):O=e[50];let M;e[51]!==a?(M=a("settings.page.chat.description"),e[51]=a,e[52]=M):M=e[52];let S;e[53]!==a?(S=a("settings.page.sessions.description"),e[53]=a,e[54]=S):S=e[54];let F;e[55]!==a?(F=a("settings.page.shortcuts.description"),e[55]=a,e[56]=F):F=e[56];let E;e[57]!==a?(E=a("settings.page.notifications.description"),e[57]=a,e[58]=E):E=e[58];let D;e[59]!==a?(D=a("settings.page.voice.description"),e[59]=a,e[60]=D):D=e[60];let W;e[61]!==a?(W=a("settings.page.tunnel.description"),e[61]=a,e[62]=W):W=e[62];let H;e[63]!==$||e[64]!==O||e[65]!==M||e[66]!==S||e[67]!==F||e[68]!==E||e[69]!==D||e[70]!==W?(H={general:$,visual:O,chat:M,sessions:S,shortcuts:F,git:void 0,github:void 0,notifications:E,voice:D,tunnel:W},e[63]=$,e[64]=O,e[65]=M,e[66]=S,e[67]=F,e[68]=E,e[69]=D,e[70]=W,e[71]=H):H=e[71];const Z=H[n];let Y;e[72]!==m?(Y=m(),e[72]=m,e[73]=Y):Y=e[73];let A;return e[74]!==Z||e[75]!==P||e[76]!==Y?(A=s.jsx(ps,{title:P,description:Z,showSaveStatus:!0,className:"openchamber-page-body",children:Y}),e[74]=Z,e[75]=P,e[76]=Y,e[77]=A):A=e[77],A},yj=()=>{const t=tt.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(uj,{}),t[0]=e):e=t[0],e},vj=()=>{const t=tt.c(7);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=ds(),t[0]=e):e=t[0];const n=e;cm();let a;t[1]===Symbol.for("react.memo_cache_sentinel")?(a=ls()&&Wa(),t[1]=a):a=t[1];const i=a;let r;t[2]===Symbol.for("react.memo_cache_sentinel")?(r=In()&&!ls()&&!n&&!ll(),t[2]=r):r=t[2];const o=r;let d,c,p;t[3]===Symbol.for("react.memo_cache_sentinel")?(d=i&&s.jsx(lm,{}),c=o&&s.jsx(nm,{}),p=!n&&s.jsx(om,{}),t[3]=d,t[4]=c,t[5]=p):(d=t[3],c=t[4],p=t[5]);let u;return t[6]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsxs(s.Fragment,{children:[d,c,p,s.jsx(Tr,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar",...n?[]:["terminalQuickKeys"],...n?[]:["terminalShell"],...n?[]:["terminalLoginShell"],"messageTransport","reportUsage"]})]}),t[6]=u):u=t[6],u},wj=()=>{const t=tt.c(2);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=ds(),t[0]=e):e=t[0];const n=e;let a;return t[1]===Symbol.for("react.memo_cache_sentinel")?(a=s.jsx(Tr,{visibleSettings:["theme","windowControlsPosition","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat",...n?[]:["weekStart"],"fontSize","terminalFontSize","editorFontSize","spacing","inputBarOffset"]}),t[1]=a):a=t[1],a},jj=()=>{const t=tt.c(2);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=ds(),t[0]=e):e=t[0];const n=e;let a;return t[1]===Symbol.for("react.memo_cache_sentinel")?(a=s.jsx(Tr,{visibleSettings:["sessionGoal","sessionAssist","chatRenderMode","activityRenderMode","userMessageRendering","mermaidRendering","reasoning","showToolFileIcons","showTurnChangedFiles","expandedTools","collapsibleUserMessages","stickyUserHeader",...n?[]:["promptNavigatorEnabled"],"wideChatLayout","codeBlockLineWrap","splitAssistantMessageActions","subagentReadOnlyBanner","diffLayout","dotfiles","fileViewerPreview","followUpBehavior","persistDraft","inputSpellcheck"]}),t[1]=a):a=t[1],a},kj=()=>{const t=tt.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsxs(s.Fragment,{children:[s.jsx(am,{}),s.jsx(sm,{})]}),t[0]=e):e=t[0],e},Nj=()=>{const t=tt.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(Zu,{}),t[0]=e):e=t[0],e},Sj=()=>{const t=tt.c(1);if(ds())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(em,{}),t[0]=e):e=t[0],e},Cj=()=>{const t=tt.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(G1,{}),t[0]=e):e=t[0],e},Ij=()=>{const t=tt.c(1);if(ds())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(X1,{}),t[0]=e):e=t[0],e},Pj=()=>{const t=tt.c(1);if(ds())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(lj,{}),t[0]=e):e=t[0],e};function Tj(t){return t+1}function Aj(t){const e=tt.c(4);let n,a;e[0]===Symbol.for("react.memo_cache_sentinel")?(n=s.jsx("path",{d:"M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"}),a=s.jsx("path",{d:"M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"}),e[0]=n,e[1]=a):(n=e[0],a=e[1]);let i;return e[2]!==t?(i=s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",fillRule:"evenodd",viewBox:"-0.5 -0.5 25 25",...t,children:[n,a]}),e[2]=t,e[3]=i):i=e[3],i}const dm=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli"]},{slug:"projects",title:"Projects",group:"projects",kind:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"],isAvailable:t=>!t.isVSCode},{slug:"providers",title:"Providers",group:"opencode",kind:"split",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"usage",title:"Usage",group:"general",kind:"split",keywords:["quota","billing","tokens","usage","limits"]},{slug:"agents",title:"Agents",group:"opencode",kind:"split",keywords:["agent","agents","prompts","tools","permissions"]},{slug:"behavior",title:"Behavior",group:"opencode",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"commands",title:"Commands",group:"opencode",kind:"split",keywords:["command","commands","slash","macros","automation"]},{slug:"mcp",title:"MCP",group:"opencode",kind:"split",keywords:["mcp","model context protocol","servers","tools","remote","stdio"]},{slug:"plugins",title:"Plugins",group:"opencode",kind:"split",keywords:["plugin","plugins","extensions","addons","npm","opencode-wakatime"]},{slug:"skills.installed",title:"Skills",group:"content",kind:"split",keywords:["skill","skills","instructions","install","catalog"]},{slug:"skills.catalog",title:"Skills Catalog",group:"content",kind:"single",keywords:["install","catalog","external","repository","skills catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"],isAvailable:t=>!t.isVSCode},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"],isAvailable:t=>!t.isVSCode},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"Magic Prompts",group:"content",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request"],isAvailable:t=>!t.isVSCode},{slug:"snippets",title:"Snippets",group:"content",kind:"split",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"voice",title:"Voice",group:"general",kind:"single",keywords:["tts","speech","voice"],isAvailable:t=>!t.isVSCode},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:t=>!t.isVSCode},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog"],isAvailable:t=>t.isMobile&&!t.isVSCode}],Ej={sessions:"sessions",agents:"agents",commands:"commands",mcp:"mcp",skills:"skills.installed",providers:"providers",usage:"usage","git-identities":"git",settings:"home"};function za(t){const e=t.trim().toLowerCase();return dm.find(n=>n.slug===e)??null}function xl(t){const e=(t??"").trim().toLowerCase();if(!e)return"home";const n=Ej[e];if(n)return n;const a=za(e);return a?a.slug:"home"}const Dj=[{id:"appearance.language",page:"appearance",titleKey:"settings.appearance.language.label",descriptionKey:"settings.appearance.language.description",keywords:["locale","translation","ui language"]},{id:"appearance.time-format",page:"appearance",titleKey:"settings.openchamber.visual.field.timeFormat",keywords:["clock","12h","24h"]},{id:"appearance.week-start",page:"appearance",titleKey:"settings.openchamber.visual.field.weekStartsOn",keywords:["calendar","monday","sunday"],isAvailable:t=>!t.isVSCode},{id:"appearance.light-theme",page:"appearance",titleKey:"settings.openchamber.visual.field.lightTheme",keywords:["theme","color","light mode"],isAvailable:t=>!t.isVSCode},{id:"appearance.dark-theme",page:"appearance",titleKey:"settings.openchamber.visual.field.darkTheme",keywords:["theme","color","dark mode"],isAvailable:t=>!t.isVSCode},{id:"appearance.window-transparency",page:"appearance",titleKey:"settings.openchamber.visual.field.macVibrancy",descriptionKey:"settings.openchamber.visual.field.macVibrancyHint",keywords:["transparent","transparency","vibrancy","blur","macos","opaque"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"appearance.dock-badge",page:"appearance",titleKey:"settings.openchamber.visual.field.dockBadge",descriptionKey:"settings.openchamber.visual.field.dockBadgeHint",keywords:["dock","badge","unread","unseen","counter","count","notification","macos"],isAvailable:t=>t.isMac},{id:"appearance.pwa-install-name",page:"appearance",titleKey:"settings.openchamber.visual.field.installAppName",descriptionKey:"settings.openchamber.visual.field.installAppNameHint",keywords:["pwa","installed app"],isAvailable:t=>t.isWeb&&!t.isDesktop&&!t.isVSCode},{id:"appearance.pwa-orientation",page:"appearance",titleKey:"settings.openchamber.visual.field.installOrientation",descriptionKey:"settings.openchamber.visual.field.installOrientationHint",keywords:["pwa","portrait","landscape"],isAvailable:t=>t.isWeb&&!t.isDesktop&&!t.isVSCode},{id:"appearance.mobile-keyboard-mode",page:"appearance",titleKey:"settings.openchamber.visual.field.mobileKeyboardMode",descriptionKey:"settings.openchamber.visual.field.mobileKeyboardModeHint",keywords:["mobile","keyboard","resize"],isAvailable:t=>t.isMobile&&t.isWeb&&!t.isDesktop&&!t.isVSCode},{id:"appearance.interface-font-size",page:"appearance",titleKey:"settings.openchamber.visual.field.interfaceFontSize",keywords:["font","text size","ui scale"],isAvailable:t=>!t.isMobile},{id:"appearance.terminal-font-size",page:"appearance",titleKey:"settings.openchamber.visual.field.terminalFontSize",keywords:["terminal","font","text size"]},{id:"appearance.terminal-shell",page:"general",titleKey:"settings.openchamber.visual.field.terminalShell",descriptionKey:"settings.openchamber.visual.field.terminalShellHint",keywords:["terminal","shell","bash","zsh","fish","pwsh","powershell"],isAvailable:t=>!t.isVSCode},{id:"appearance.editor-font-size",page:"appearance",titleKey:"settings.openchamber.visual.field.editorFontSize",keywords:["editor","font","text size","code"]},{id:"appearance.spacing-density",page:"appearance",titleKey:"settings.openchamber.visual.field.spacingDensity",keywords:["density","compact","comfortable","spacing"]},{id:"appearance.input-bar-offset",page:"appearance",titleKey:"settings.openchamber.visual.field.inputBarOffset",descriptionKey:"settings.openchamber.visual.field.inputBarOffsetTooltip",keywords:["input","home bar","offset"],isAvailable:t=>t.isMobile},{id:"appearance.auto-save-enabled",page:"general",titleKey:"settings.openchamber.visual.field.autoSaveEnabled",descriptionKey:"settings.openchamber.visual.field.autoSaveEnabledInfo",keywords:["editor","autosave","auto-save","files","save"]},{id:"appearance.expanded-editor-toolbar",page:"general",titleKey:"settings.openchamber.visual.field.expandedEditorToolbar",keywords:["editor","toolbar","tabs","docked","files"],isAvailable:t=>!t.isVSCode},{id:"appearance.file-editor-keymap",page:"general",titleKey:"settings.openchamber.visual.field.fileEditorKeymap",keywords:["editor","vim","keymap"]},{id:"appearance.terminal-quick-keys",page:"general",titleKey:"settings.openchamber.visual.field.terminalQuickKeys",descriptionKey:"settings.openchamber.visual.field.terminalQuickKeysTooltip",keywords:["terminal","keyboard","esc","ctrl","arrows"],isAvailable:t=>!t.isMobile&&!t.isVSCode},{id:"appearance.usage-reports",page:"general",titleKey:"settings.openchamber.visual.field.sendAnonymousUsageReports",descriptionKey:"settings.openchamber.visual.field.sendAnonymousUsageReportsHint",keywords:["telemetry","analytics"]},{id:"chat.render-mode",page:"chat",titleKey:"settings.openchamber.visual.section.chatRenderMode",keywords:["messages","conversation","rendering"]},{id:"chat.message-transport",page:"general",titleKey:"settings.openchamber.visual.section.messageStreamTransport",keywords:["streaming","sse","websocket"]},{id:"chat.session-recap",page:"chat",titleKey:"settings.openchamber.visual.field.sessionRecap",keywords:["recap","assist","small model","summary"]},{id:"chat.session-assistance",page:"chat",titleKey:"settings.openchamber.visual.section.sessionAssistance",keywords:["recap","suggestion","subagent"]},{id:"chat.session-suggestion",page:"chat",titleKey:"settings.openchamber.visual.field.sessionSuggestion",keywords:["suggestion","assist","small model","follow up"]},{id:"chat.session-goal",page:"chat",titleKey:"settings.openchamber.visual.field.sessionGoal",keywords:["goal","objective","auto continue","small model"],isAvailable:t=>!t.isVSCode},{id:"chat.session-goal-budget",page:"chat",titleKey:"settings.openchamber.visual.goal.budgetLabel",keywords:["goal","budget","tokens","limit"],isAvailable:t=>!t.isVSCode},{id:"chat.reasoning-traces",page:"chat",titleKey:"settings.openchamber.visual.field.showReasoningTraces",keywords:["thinking","reasoning"]},{id:"chat.reasoning",page:"chat",titleKey:"settings.openchamber.visual.section.reasoning",keywords:["thinking","traces"]},{id:"chat.sticky-user-header",page:"chat",titleKey:"settings.openchamber.visual.field.stickyUserHeader",keywords:["messages","header"]},{id:"chat.prompt-navigator",page:"chat",titleKey:"settings.openchamber.visual.field.promptNavigatorEnabled",keywords:["prompt","navigator","navigation","timeline","scroll"],isAvailable:t=>!t.isVSCode},{id:"chat.collapsible-user-messages",page:"chat",titleKey:"settings.openchamber.visual.field.collapsibleUserMessages",keywords:["collapse","expand","clamp","long messages","user messages"]},{id:"chat.wide-layout",page:"chat",titleKey:"settings.openchamber.visual.field.wideChatLayout",keywords:["layout","wide","messages"]},{id:"chat.message-appearance",page:"chat",titleKey:"settings.openchamber.visual.section.messageAppearance",keywords:["layout","messages","appearance"]},{id:"chat.code-block-line-wrap",page:"chat",titleKey:"settings.openchamber.visual.field.codeBlockLineWrap",keywords:["code","wrap","line wrap","markdown"]},{id:"chat.inline-assistant-actions",page:"chat",titleKey:"settings.openchamber.visual.field.showSplitAssistantMessageActions",descriptionKey:"settings.openchamber.visual.field.showSplitAssistantMessageActionsTooltip",keywords:["copy","save image","read aloud"]},{id:"chat.draft-starters-visible",page:"chat",titleKey:"settings.openchamber.visual.field.draftStartersVisible",keywords:["starter","starters","new session","welcome","suggestions"]},{id:"chat.subagent-read-only-banner",page:"chat",titleKey:"settings.openchamber.visual.field.allowPromptingSubagentSessions",keywords:["subagent","read only","prompt","banner"]},{id:"chat.tool-file-icons",page:"chat",titleKey:"settings.openchamber.visual.field.showToolFileIcons",keywords:["tools","files","icons"]},{id:"chat.tools-and-files",page:"chat",titleKey:"settings.openchamber.visual.section.toolsAndFiles",keywords:["tools","files","dotfiles"]},{id:"chat.changed-files",page:"chat",titleKey:"settings.openchamber.visual.field.showTurnChangedFiles",keywords:["changed files","turns"]},{id:"chat.dotfiles",page:"chat",titleKey:"settings.openchamber.visual.field.showDotfiles",keywords:["hidden files"],isAvailable:t=>!t.isVSCode},{id:"chat.follow-up-behavior",page:"chat",titleKey:"settings.openchamber.visual.section.followUpBehavior",descriptionKey:"settings.openchamber.visual.field.followUpBehaviorDescription",keywords:["follow up","queue","steer","send immediately"]},{id:"chat.persist-drafts",page:"chat",titleKey:"settings.openchamber.visual.field.persistDraftMessages",keywords:["draft","message"]},{id:"chat.composer",page:"chat",titleKey:"settings.openchamber.visual.section.composer",keywords:["input","draft","spellcheck"]},{id:"chat.spellcheck",page:"chat",titleKey:"settings.openchamber.visual.field.enableSpellcheckInTextInputs",keywords:["spelling","input"],isAvailable:t=>!t.isMobile},{id:"sessions.default-model",page:"sessions",titleKey:"settings.openchamber.defaults.field.defaultModel",keywords:["model","provider","new sessions"]},{id:"sessions.default-thinking",page:"sessions",titleKey:"settings.openchamber.defaults.field.defaultThinking",keywords:["thinking","reasoning","variant"]},{id:"sessions.default-agent",page:"sessions",titleKey:"settings.openchamber.defaults.field.defaultAgent",keywords:["agent","new sessions"]},{id:"sessions.deletion-dialog",page:"sessions",titleKey:"settings.openchamber.defaults.field.showDeletionDialog",keywords:["delete","confirmation"]},{id:"sessions.small-model",page:"sessions",titleKey:"settings.openchamber.defaults.smallModel.title",descriptionKey:"settings.openchamber.defaults.smallModel.description",keywords:["small model","utility","summary","recap","cheap","override"]},{id:"sessions.walkthrough-model",page:"sessions",titleKey:"settings.openchamber.defaults.walkthroughModel.title",descriptionKey:"settings.openchamber.defaults.walkthroughModel.description",keywords:["walkthrough","diff","review","changes","structured output","model","override"]},{id:"sessions.auto-cleanup",page:"sessions",titleKey:"settings.openchamber.sessionRetention.field.enableAutoCleanup",descriptionKey:"settings.openchamber.sessionRetention.tooltip",keywords:["retention","archive","delete"]},{id:"sessions.retention-period",page:"sessions",titleKey:"settings.openchamber.sessionRetention.field.retentionPeriod",keywords:["days","cleanup","retention"]},{id:"sessions.retention-action",page:"sessions",titleKey:"settings.openchamber.sessionRetention.field.whenSessionsExpire",keywords:["archive","delete","expire"]},{id:"sessions.desktop-launch-at-login",page:"general",titleKey:"settings.openchamber.desktopNetwork.field.launchAtLogin",descriptionKey:"settings.openchamber.desktopNetwork.field.launchAtLoginDescription",keywords:["desktop","startup","login","launch","background","autostart"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.desktop-window-controls-position",page:"appearance",titleKey:"settings.openchamber.desktopNetwork.field.windowControlsPosition",descriptionKey:"settings.openchamber.desktopNetwork.field.windowControlsPositionDescription",keywords:["desktop","window","controls","minimize","maximize","close","titlebar","linux","windows"],isAvailable:t=>t.isDesktop&&(t.isWindows||!t.isMac)},{id:"sessions.desktop-window-controls-style",page:"appearance",titleKey:"settings.openchamber.desktopNetwork.field.windowControlsStyle",keywords:["desktop","window","controls","style","traffic","lights","classic","macos","titlebar"],isAvailable:t=>t.isDesktop&&(t.isWindows||!t.isMac)},{id:"sessions.desktop-mac-menu-bar",page:"general",titleKey:"settings.openchamber.desktopNetwork.field.macMenuBar",descriptionKey:"settings.openchamber.desktopNetwork.field.macMenuBarDescription",keywords:["desktop","menu bar","tray","status item","macos","background"],isAvailable:t=>t.isDesktopLocalOrigin&&t.isMac},{id:"sessions.desktop-minimize-to-tray",page:"general",titleKey:"settings.openchamber.desktopNetwork.field.minimizeToTray",descriptionKey:"settings.openchamber.desktopNetwork.field.minimizeToTrayDescription",keywords:["desktop","tray","system tray","minimize","close","background","windows","linux"],isAvailable:t=>t.isDesktopLocalOrigin&&(t.isWindows||t.isLinux)},{id:"sessions.desktop-keep-awake",page:"general",titleKey:"settings.openchamber.desktopNetwork.field.keepAwake",descriptionKey:"settings.openchamber.desktopNetwork.field.keepAwakeDescription",keywords:["desktop","sleep","awake","server","mobile","phone"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.desktop-ui-password",page:"general",titleKey:"settings.openchamber.desktopPassword.field.password",descriptionKey:"settings.openchamber.desktopPassword.field.passwordDescription",keywords:["desktop","password","auth","login"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.desktop-lan-access",page:"general",titleKey:"settings.openchamber.desktopNetwork.field.allowLanAccess",descriptionKey:"settings.openchamber.desktopNetwork.field.allowLanAccessDescription",keywords:["desktop","lan","network","phone","tablet"],isAvailable:t=>t.isDesktopLocalOrigin},{id:"sessions.opencode-binary",page:"general",titleKey:"settings.openchamber.opencodeCli.field.binaryPath",keywords:["opencode","cli","binary","path"],isAvailable:t=>!t.isVSCode},{id:"sessions.opencode-update-notifications",page:"general",titleKey:"settings.openchamber.opencodeCli.field.showUpdateNotifications",keywords:["opencode","cli","updates"],isAvailable:t=>!t.isVSCode&&!t.isWindowsArm64},{id:"sessions.agent-control-tool",page:"general",titleKey:"settings.openchamber.opencodeCli.field.agentControlTool",descriptionKey:"settings.openchamber.opencodeCli.field.agentControlToolInfo",keywords:["agent","tool","orchestration","openchamber","sessions","schedule","control"],isAvailable:t=>!t.isVSCode},{id:"git.github-account",page:"git",titleKey:"settings.github.page.actions.connect",keywords:["github","account","oauth","prs","issues"]},{id:"git.identities",page:"git",titleKey:"settings.gitIdentities.page.section.title",descriptionKey:"settings.gitIdentities.page.empty.description",keywords:["identity","profile","author","email","credentials","signing","commit signing","ssh signing","gpg"]},{id:"git.changes-view",page:"git",titleKey:"settings.openchamber.git.changesViewTitle",keywords:["changes","flat list","tree view"]},{id:"git.gitmoji",page:"git",titleKey:"settings.openchamber.git.enableGitmoji",keywords:["commit","emoji"]},{id:"git.gitignored-files",page:"git",titleKey:"settings.openchamber.git.showGitignored",keywords:["ignored","files","gitignore"]},{id:"usage.header-menu",page:"usage",titleKey:"settings.usage.page.options.showInHeader",descriptionKey:"settings.usage.page.options.showInHeaderTooltip",keywords:["quota","header","dropdown"]},{id:"usage.model-quotas",page:"usage",titleKey:"settings.usage.page.section.modelQuotas",keywords:["models","quota","limits","tokens"]},{id:"projects.name",page:"projects",titleKey:"settings.projects.page.field.projectName",keywords:["label","display name","project metadata"]},{id:"projects.accent-color",page:"projects",titleKey:"settings.projects.page.field.accentColor",keywords:["color","appearance","project metadata"]},{id:"projects.icon",page:"projects",titleKey:"settings.projects.page.field.projectIcon",keywords:["icon","favicon","upload","project metadata"]},{id:"projects.worktree",page:"projects",titleKey:"settings.projects.page.section.worktree",keywords:["worktree","branch","repository"]},{id:"projects.worktree.setup.wait",page:"projects",titleKey:"settings.openchamber.worktrees.setup.waitForCommands",keywords:["worktree","setup commands","bootstrap","wait"]},{id:"remote-instances.client-auth",page:"remote-instances",titleKey:"settings.remoteInstances.clientAuth.title",descriptionKey:"settings.remoteInstances.clientAuth.description",keywords:["pairing link","client token","connect desktop","remote access","relay","devices","connect from anywhere"],isAvailable:t=>!t.isVSCode},{id:"remote-instances.direct-hosts",page:"remote-instances",titleKey:"settings.remoteInstances.direct.title",descriptionKey:"settings.remoteInstances.direct.description",keywords:["server url","connection token","import link","host switcher","additional headers","request headers","cloudflare access","service token"],isAvailable:t=>t.isDesktop},{id:"behavior.system-prompt-optimization",page:"behavior",titleKey:"settings.behavior.page.section.systemPromptOptimization",descriptionKey:"settings.behavior.page.systemPromptOptimization.info",keywords:["system prompt","tokens","context","optimize","minimal"],isAvailable:t=>!t.isVSCode},{id:"behavior.system-prompt",page:"behavior",titleKey:"settings.behavior.page.section.systemPrompt",descriptionKey:"settings.behavior.page.warning.title",keywords:["agents.md","global instructions","system prompt"]},{id:"behavior.response-style",page:"behavior",titleKey:"settings.behavior.page.section.responseStyle",descriptionKey:"settings.behavior.page.responseStyle.tooltip",keywords:["tone","concise","detailed","custom instructions"]},{id:"agents.create",page:"agents",titleKey:"settings.agents.page.title.new",keywords:["create","add","new agent"]},{id:"agents.name",page:"agents",titleKey:"settings.agents.page.field.agentName",keywords:["agent","name"]},{id:"agents.mode",page:"agents",titleKey:"settings.agents.page.field.mode",descriptionKey:"settings.agents.page.field.modeTooltip",keywords:["primary","subagent","visibility"]},{id:"agents.model",page:"agents",titleKey:"settings.agents.page.field.overrideModel",keywords:["model","provider"]},{id:"agents.variant",page:"agents",titleKey:"settings.agents.page.field.variant",descriptionKey:"settings.agents.page.field.variantTooltip",keywords:["thinking","reasoning","variant","depth"]},{id:"agents.temperature",page:"agents",titleKey:"settings.agents.page.field.temperature",descriptionKey:"settings.agents.page.field.temperatureTooltip",keywords:["randomness","creative"]},{id:"agents.top-p",page:"agents",titleKey:"settings.agents.page.field.topP",descriptionKey:"settings.agents.page.field.topPTooltip",keywords:["sampling","nucleus"]},{id:"agents.system-prompt",page:"agents",titleKey:"settings.agents.page.section.systemPrompt",keywords:["prompt","instructions"]},{id:"agents.permissions",page:"agents",titleKey:"settings.agents.page.section.toolPermissions",keywords:["tools","permissions","allow","ask","deny"]},{id:"commands.create",page:"commands",titleKey:"settings.commands.page.title.new",keywords:["create","add","new command"]},{id:"commands.name",page:"commands",titleKey:"settings.commands.page.field.commandName",keywords:["slash command","name"]},{id:"commands.agent",page:"commands",titleKey:"settings.commands.page.field.overrideAgent",keywords:["agent","execution"]},{id:"commands.model",page:"commands",titleKey:"settings.agents.page.field.overrideModel",keywords:["model","provider"]},{id:"commands.template",page:"commands",titleKey:"settings.commands.page.section.template",keywords:["prompt","template","arguments","shell","file"]},{id:"mcp.create",page:"mcp",titleKey:"settings.mcp.sidebar.actions.addServerTitle",keywords:["create","add","server"]},{id:"mcp.server",page:"mcp",titleKey:"settings.mcp.page.server.title",keywords:["server","name","transport"]},{id:"mcp.command",page:"mcp",titleKey:"settings.mcp.page.connection.command",keywords:["stdio","local","command"]},{id:"mcp.environment",page:"mcp",titleKey:"settings.mcp.page.env.title",keywords:["env","variables","api key"]},{id:"mcp.advanced",page:"mcp",titleKey:"settings.mcp.page.advanced.title",keywords:["oauth","headers","timeout"]},{id:"plugins.create",page:"plugins",titleKey:"settings.plugins.sidebar.actions.addTitle",keywords:["add","plugin","npm","path","file"]},{id:"plugins.spec",page:"plugins",titleKey:"settings.plugins.page.field.spec",keywords:["npm","package","path"]},{id:"plugins.options",page:"plugins",titleKey:"settings.plugins.page.field.options",keywords:["json","configuration"]},{id:"plugins.content",page:"plugins",titleKey:"settings.plugins.page.field.content",keywords:["file","code"]},{id:"snippets.create",page:"snippets",titleKey:"settings.snippets.sidebar.actions.create",keywords:["add","new snippet"]},{id:"snippets.content",page:"snippets",titleKey:"settings.snippets.page.field.content",keywords:["markdown","prompt","template"]},{id:"providers.connect",page:"providers",titleKey:"settings.providers.page.connect.title",keywords:["add provider","connect provider","credentials"]},{id:"providers.custom",page:"providers",titleKey:"settings.providers.page.custom.title",descriptionKey:"settings.providers.page.custom.description",keywords:["other","custom","openai-compatible","base url","api key"]},{id:"providers.auth",page:"providers",titleKey:"settings.providers.page.auth.title",keywords:["api key","oauth","credentials"]},{id:"providers.connection-details",page:"providers",titleKey:"settings.providers.page.connectionDetails.title",keywords:["config","source","disconnect"]},{id:"providers.models",page:"providers",titleKey:"settings.providers.page.models.title",keywords:["models","hide","show"]},{id:"skills.create",page:"skills.installed",titleKey:"settings.skills.page.title.newSkill",keywords:["create","add","new skill"]},{id:"skills.basic-information",page:"skills.installed",titleKey:"settings.skills.page.section.basicInformation",keywords:["name","location","description"]},{id:"skills.instructions",page:"skills.installed",titleKey:"settings.skills.page.section.instructions",keywords:["markdown","skill.md","content"]},{id:"skills.supporting-files",page:"skills.installed",titleKey:"settings.skills.page.section.supportingFiles",keywords:["files","resources"]},{id:"skills.catalog.source",page:"skills.catalog",titleKey:"settings.skills.catalog.page.section.sourceRepository",keywords:["catalog","repository","source","refresh"]},{id:"skills.catalog.search",page:"skills.catalog",titleKey:"settings.skills.catalog.shared.field.searchSkillsPlaceholder",keywords:["find skills","install skills","catalog search"]},{id:"skills.catalog.add-catalog",page:"skills.catalog",titleKey:"settings.skills.catalog.page.actions.addCatalog",keywords:["external repository","add source","catalog"]},{id:"magic-prompts.visible-prompt",page:"magic-prompts",titleKey:"settings.magicPrompts.page.block.visiblePrompt",keywords:["prompt text","user message","template"],isAvailable:t=>!t.isVSCode},{id:"magic-prompts.instructions",page:"magic-prompts",titleKey:"settings.magicPrompts.page.block.instructions",keywords:["hidden prompt","instructions","template"],isAvailable:t=>!t.isVSCode},{id:"magic-prompts.reset-overrides",page:"magic-prompts",titleKey:"settings.magicPrompts.page.actions.resetAllOverrides",keywords:["reset","default prompts","overrides"],isAvailable:t=>!t.isVSCode},{id:"shortcuts.keyboard-shortcuts",page:"shortcuts",titleKey:"settings.openchamber.keyboardShortcuts.title",descriptionKey:"settings.openchamber.keyboardShortcuts.tooltip",keywords:["keyboard","hotkeys","bindings"]},{id:"voice.playback",page:"voice",titleKey:"settings.voice.page.section.playbackAndSummary",keywords:["tts","read aloud","voice","provider","speech rate","speech pitch","speech volume","tts input mode","markdown"]},{id:"voice.speech-recognition",page:"voice",titleKey:"settings.voice.page.section.speechRecognition",keywords:["stt","dictation","voice input","transcribe","whisper","parakeet","microphone"]},{id:"tunnel.provider",page:"tunnel",titleKey:"settings.openchamber.tunnel.field.provider",descriptionKey:"settings.openchamber.tunnel.description",keywords:["remote access","cloudflare","ngrok"],isAvailable:t=>!t.isVSCode},{id:"tunnel.type",page:"tunnel",titleKey:"settings.openchamber.tunnel.field.tunnelType",keywords:["quick","managed remote","managed local"],isAvailable:t=>!t.isVSCode},{id:"tunnel.ttl",page:"tunnel",titleKey:"settings.openchamber.tunnel.field.connectLinkTtl",descriptionKey:"settings.openchamber.tunnel.field.tunnelSessionTtl",keywords:["expiry","expiration","session ttl","connect link ttl"],isAvailable:t=>!t.isVSCode},{id:"tunnel.managed-remote",page:"tunnel",titleKey:"settings.openchamber.tunnel.section.savedManagedRemoteTunnels",keywords:["cloudflare","hostname","token","managed remote"],isAvailable:t=>!t.isVSCode},{id:"tunnel.managed-local-config",page:"tunnel",titleKey:"settings.openchamber.tunnel.field.configurationFile",descriptionKey:"settings.openchamber.tunnel.note.managedLocalUsesConfig",keywords:["cloudflared","config","yaml","json","managed local"],isAvailable:t=>!t.isVSCode},{id:"tunnel.start",page:"tunnel",titleKey:"settings.openchamber.tunnel.actions.startTunnel",descriptionKey:"settings.openchamber.tunnel.note.connectLinksOneTime",keywords:["connect link","qr code","public url","remote access"],isAvailable:t=>!t.isVSCode},{id:"notifications.delivery",page:"notifications",titleKey:"settings.notifications.page.delivery.title",keywords:["desktop notifications","system notifications"]},{id:"notifications.events",page:"notifications",titleKey:"settings.notifications.page.events.title",keywords:["completion","subtasks","errors","questions"]},{id:"notifications.push",page:"notifications",titleKey:"settings.notifications.page.push.title",keywords:["background","push"],isAvailable:t=>t.isWeb&&!t.isDesktop&&!t.isVSCode}];function Sd(t){return t.trim().toLocaleLowerCase()}function Rj({query:t,runtimeCtx:e,visiblePageSlugs:n,t:a,getPageTitle:i}){const r=Sd(t);if(!r)return[];const o=n?new Set(n):null,d=r.split(/\s+/).filter(Boolean);return Dj.flatMap(c=>{if(o&&!o.has(c.page))return[];const p=za(c.page);if(!p||p.isAvailable&&!p.isAvailable(e)||c.isAvailable&&!c.isAvailable(e))return[];const u=a(c.titleKey),f=c.descriptionKey?a(c.descriptionKey):null,m=Sd([u,f,i(c.page),...c.keywords??[]].filter(Boolean).join(" "));return d.every(w=>m.includes(w))?[{...c,title:u,description:f,pageTitle:i(c.page)}]:[]})}const Cd=256,Id=280,um="__openchamberSettingsDetail",Mj=["general","appearance","chat","notifications","sessions","shortcuts","voice","usage","about","projects","remote-instances","tunnel","git","providers","agents","behavior","commands","mcp","plugins","magic-prompts","snippets","skills.installed","skills.catalog"],Lj=["general","projects","opencode","content"],Fj={icon:"chat-thread"},Oj="__add_provider__";function zj(t,e){const n=ds(),a=!t&&In();return{isVSCode:n,isWeb:a,isDesktop:t,isMobile:e}}function Pd(t,e){return t.isAvailable?t.isAvailable(e):!0}function tl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function li(t,e){const n=new Set(e);let a=t,i=1;for(;n.has(a);)a=`${t}-${i}`,i+=1;return a}function fo(t){if(!tl(t))return null;const e=t[um];if(!tl(e))return null;const n=e.page,a=e.stage;return typeof n!="string"||a!=="page-content"?null:{page:xl(n),stage:a}}function Kj(){return typeof window>"u"||!tl(window.history.state)?{}:window.history.state}function mm(t){switch(t){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"magic-prompts":return"ai-generate-2";case"snippets":return Fj.icon;case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"agents":return"ai-agent";case"behavior":return"brain";case"commands":return"slash-commands-2";case"mcp":return null;case"plugins":return"plug-2";case"skills.installed":return"book-open";case"skills.catalog":return"book";case"git":return"git-branch";case"usage":return"bar-chart-2";case"voice":return"mic";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const Bj=t=>{const e=tt.c(124),{onClose:n,forceMobile:a,isWindowed:i,visiblePageSlugs:r,initialMobileStage:o}=t,d=o===void 0?"nav":o,{t:c}=lt(),p=Vs(),u=a??p.isMobile,f=ke(_j),m=ke(Uj),w=ke($j);let b;e[0]!==f?(b=xl(f),e[0]=f,e[1]=b):b=e[1];const g=b,[x,k]=l.useState(d),y=l.useRef(d==="nav"?g:null);let C,z;e[2]!==u||e[3]!==w||e[4]!==g?(C=()=>{!u&&g==="home"&&w("general")},z=[u,w,g],e[2]=u,e[3]=w,e[4]=g,e[5]=C,e[6]=z):(C=e[5],z=e[6]),l.useEffect(C,z);const[j,N]=l.useState(""),[v,P]=l.useState(null),[$,O]=l.useState(0),M=l.useRef(null);let S;e[7]===Symbol.for("react.memo_cache_sentinel")?(S=[],e[7]=S):S=e[7];const F=l.useRef(S),E=l.useRef(0),D=l.useRef(!1);let W;e[8]===Symbol.for("react.memo_cache_sentinel")?(W=ls(),e[8]=W):W=e[8];const H=W;let Z;e[9]===Symbol.for("react.memo_cache_sentinel")?(Z=ls()&&Wa(),e[9]=Z):Z=e[9];const Y=Z;let A;e[10]===Symbol.for("react.memo_cache_sentinel")?(A=ls()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",e[10]=A):A=e[10];const X=A;let te;e[11]===Symbol.for("react.memo_cache_sentinel")?(te=ls()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32",e[11]=te):te=e[11];const T=te;let I;e[12]===Symbol.for("react.memo_cache_sentinel")?(I=ls()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="linux",e[12]=I):I=e[12];const B=I;let L;e[13]===Symbol.for("react.memo_cache_sentinel")?(L=uu(),e[13]=L):L=e[13];const V=L;let Q;e[14]!==u?(Q=zj(H,u),e[14]=u,e[15]=Q):Q=e[15];const G=Q;let ue;if(e[16]!==u||e[17]!==G||e[18]!==r){const ft=r?new Set(r):null;let vt;e[20]!==G?(vt=ts=>Pd(ts,G),e[20]=G,e[21]=vt):vt=e[21];let Dt;e[22]!==G.isVSCode?(Dt=ts=>!(G.isVSCode&&ts.slug==="projects"),e[22]=G.isVSCode,e[23]=Dt):Dt=e[23];let Vt;e[24]!==u?(Vt=ts=>!(u&&ts.slug==="shortcuts"),e[24]=u,e[25]=Vt):Vt=e[25],ue=dm.filter(Vj).filter(ts=>!ft||ft.has(ts.slug)).filter(vt).filter(Dt).filter(Vt),e[16]=u,e[17]=G,e[18]=r,e[19]=ue}else ue=e[19];const ne=ue;let xe;e[26]===Symbol.for("react.memo_cache_sentinel")?(xe=new Map(Mj.map(Hj)),e[26]=xe):xe=e[26];const ve=xe;let me;if(e[27]!==ne){let ft;e[29]===Symbol.for("react.memo_cache_sentinel")?(ft=(vt,Dt)=>(ve.get(vt.slug)??999)-(ve.get(Dt.slug)??999),e[29]=ft):ft=e[29],me=ne.slice().sort(ft),e[27]=ne,e[28]=me}else me=e[28];const ge=me,Ie=is(Wj);let oe;e[30]!==m||e[31]!==i||e[32]!==G.isVSCode||e[33]!==g?(oe=()=>{if(!(!m&&!G.isVSCode&&!i)){if(g==="agents"){$a.getState().loadAgents();return}if(g==="commands"){Sr.getState().loadCommands();return}if(g==="mcp"){_a.getState().loadMcpConfigs();return}if(g==="plugins"){js.getState().loadPlugins();return}(g==="skills.installed"||g==="skills.catalog")&&(Cn.getState().loadSkills(),Nn.getState().loadCatalog()),g==="snippets"&&Cr.getState().loadSnippets()}},e[30]=m,e[31]=i,e[32]=G.isVSCode,e[33]=g,e[34]=oe):oe=e[34];let ce;e[35]!==Ie||e[36]!==m||e[37]!==i||e[38]!==G.isVSCode||e[39]!==g?(ce=[Ie,m,i,G.isVSCode,g],e[35]=Ie,e[36]=m,e[37]=i,e[38]=G.isVSCode,e[39]=g,e[40]=ce):ce=e[40],l.useEffect(oe,ce);let pe;e[41]!==u||e[42]!==w?(pe=ft=>{if(w(ft),y.current=ft,!u)return;const vt=za(ft);if(!vt||vt.slug==="home"){k("nav");return}k(vt.kind==="split"?"page-sidebar":"page-content")},e[41]=u,e[42]=w,e[43]=pe):pe=e[43];const ie=pe;let le;e[44]!==g?(le=za(g),e[44]=g,e[45]=le):le=e[45];const de=le;let he;e[46]===Symbol.for("react.memo_cache_sentinel")?(he={general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",voice:"voice",tunnel:"tunnel"},e[46]=he):he=e[46];const Me=he;let Le;e[47]!==c?(Le=ft=>{switch(ft){case"general":return c("settings.page.general.title");case"projects":return c("settings.page.projects.title");case"remote-instances":return c("settings.page.remoteInstances.title");case"providers":return c("settings.page.providers.title");case"usage":return c("settings.page.usage.title");case"agents":return c("settings.page.agents.title");case"behavior":return c("settings.page.behavior.title");case"commands":return c("settings.page.commands.title");case"mcp":return c("settings.page.mcp.title");case"plugins":return c("settings.page.plugins.title");case"skills.installed":return c("settings.page.skills.title");case"skills.catalog":return c("settings.page.skillsCatalog.title");case"git":return c("settings.page.git.title");case"appearance":return c("settings.page.appearance.title");case"chat":return c("settings.page.chat.title");case"shortcuts":return c("settings.page.shortcuts.title");case"sessions":return c("settings.page.sessions.title");case"magic-prompts":return c("settings.page.magicPrompts.title");case"snippets":return c("settings.page.snippets.title");case"notifications":return c("settings.page.notifications.title");case"voice":return c("settings.page.voice.title");case"tunnel":return c("settings.page.tunnel.title");case"about":return c("settings.page.about.title");default:return c("settings.view.home.title")}},e[47]=c,e[48]=Le):Le=e[48];const Be=Le;let Fe;e[49]!==Be||e[50]!==G||e[51]!==j||e[52]!==c||e[53]!==r?(Fe=Rj({query:j,runtimeCtx:{...G,isDesktopLocalOrigin:Y,isMac:X,isWindows:T,isLinux:B,isWindowsArm64:V},visiblePageSlugs:r,t:c,getPageTitle:Be}),e[49]=Be,e[50]=G,e[51]=j,e[52]=c,e[53]=r,e[54]=Fe):Fe=e[54];const De=Fe,ze=Xj;let Ve;if(e[55]!==De){Ve=[];const ft=new Map;for(const vt of De){let Dt=ft.get(vt.page);Dt||(Dt={page:vt.page,pageTitle:vt.pageTitle,results:[]},ft.set(vt.page,Dt),Ve.push(Dt)),Dt.results.push(vt)}e[55]=De,e[56]=Ve}else Ve=e[56];const We=Ve;let _e;e[57]===Symbol.for("react.memo_cache_sentinel")?(_e=()=>{O(0),E.current=0,D.current=!1},e[57]=_e):_e=e[57];let He;e[58]!==j?(He=[j],e[58]=j,e[59]=He):He=e[59],l.useEffect(_e,He);let Ke,Oe;e[60]!==$?(Ke=()=>{E.current=$},Oe=[$],e[60]=$,e[61]=Ke,e[62]=Oe):(Ke=e[61],Oe=e[62]),l.useEffect(Ke,Oe);let je,Te;e[63]!==$?(je=()=>{F.current[$]?.scrollIntoView({block:"nearest"})},Te=[$],e[63]=$,e[64]=je,e[65]=Te):(je=e[64],Te=e[65]),l.useEffect(je,Te);let Ue,Ye;e[66]!==$||e[67]!==De.length?(Ue=()=>{$>=De.length&&O(Math.max(0,De.length-1)),F.current.length=De.length},Ye=[$,De.length],e[66]=$,e[67]=De.length,e[68]=Ue,e[69]=Ye):(Ue=e[68],Ye=e[69]),l.useEffect(Ue,Ye);let q;e[70]!==u||e[71]!==ie?(q=ft=>{const vt=ze(ft);P(vt),ie(ft.page),u&&k("page-content"),ft.id==="plugins.create"&&typeof window<"u"&&window.setTimeout(Zj,50)},e[70]=u,e[71]=ie,e[72]=q):q=e[72];const re=q;let U;e[73]!==re||e[74]!==j||e[75]!==De?(U=ft=>{if(j.trim()){if(ft.key==="Escape"){ft.preventDefault(),N("");return}if(De.length!==0){if(ft.key==="ArrowDown"){ft.preventDefault(),D.current=!0,O(vt=>(vt+1)%De.length);return}if(ft.key==="ArrowUp"){ft.preventDefault(),D.current=!0,O(vt=>(vt-1+De.length)%De.length);return}if(ft.key==="Enter"){ft.preventDefault();const vt=(E.current%De.length+De.length)%De.length,Dt=De[vt]??De[0];Dt&&re(Dt)}}}},e[73]=re,e[74]=j,e[75]=De,e[76]=U):U=e[76];const h=U;let ae;e[77]!==v?(ae=()=>{const ft=v;if(!ft)return;let vt=!1;const Dt=window.requestAnimationFrame(()=>{if(vt)return;const Vt=typeof CSS<"u"&&CSS.escape?CSS.escape(ft):ft.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),ts=M.current?.querySelector(`[data-settings-item="${Vt}"]`);ts&&(P(null),ts.scrollIntoView({block:"center",behavior:"smooth"}),ts.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{ts.removeAttribute("data-settings-search-highlight")},1600))});return()=>{vt=!0,window.cancelAnimationFrame(Dt)}},e[77]=v,e[78]=ae):ae=e[78];let ye;e[79]!==v||e[80]!==g?(ye=[v,g],e[79]=v,e[80]=g,e[81]=ye):ye=e[81],l.useEffect(ae,ye);let be;e[82]!==c?(be=()=>s.jsx("div",{className:"flex h-full items-center justify-center px-6",children:s.jsxs("div",{className:"max-w-md text-center",children:[s.jsx("div",{className:ml,children:c("settings.view.unavailable.title")}),s.jsx("p",{className:"typography-ui text-muted-foreground mt-1",children:c("settings.view.unavailable.description")})]})}),e[82]=c,e[83]=be):be=e[83];const Ee=be,et=ek;let Ze;e[84]!==Ee||e[85]!==G||e[86]!==c?(Ze=ft=>{const vt=za(ft);if(vt&&!Pd(vt,G))return Ee();switch(ft){case"projects":return s.jsx(Fv,{});case"remote-instances":return s.jsx(ew,{});case"agents":return s.jsx(Xx,{});case"behavior":return s.jsx(nb,{});case"commands":return s.jsx(mb,{});case"mcp":return s.jsx(Vb,{});case"plugins":return s.jsx(Ey,{});case"skills.installed":return s.jsx(qc,{view:"installed"});case"skills.catalog":return s.jsx(qc,{view:"catalog"});case"providers":return s.jsx(Nw,{});case"usage":return s.jsx(i1,{});case"about":return s.jsx(ps,{title:c("settings.page.about.title"),showSaveStatus:!1,children:s.jsx(Iu,{})});case"magic-prompts":return s.jsx(d1,{});case"snippets":return s.jsx(f1,{});case"git":return s.jsx(v1,{});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"voice":case"tunnel":{const Dt=Me[ft]??"visual";return s.jsx(bj,{section:Dt})}default:return null}},e[84]=Ee,e[85]=G,e[86]=c,e[87]=Ze):Ze=e[87];const it=Ze;let ot,xt;e[88]!==u||e[89]!==x||e[90]!==g?(ot=()=>{if(!u||x!=="nav"||g==="home"||y.current===g)return;const ft=za(g);!ft||ft.slug==="home"||(y.current=g,k(ft.kind==="split"?"page-sidebar":"page-content"))},xt=[u,x,g],e[88]=u,e[89]=x,e[90]=g,e[91]=ot,e[92]=xt):(ot=e[91],xt=e[92]),l.useEffect(ot,xt);const bt=u&&x!=="nav",Nt=u&&x==="page-content"&&g==="skills.installed",Se=x==="page-content"&&de?.kind==="split"&&!Nt;let Qe;e[93]!==Nt||e[94]!==bt||e[95]!==c?(Qe=c(Nt?"settings.view.actions.back":bt?"settings.view.actions.backToSettings":"settings.view.actions.closeSettings"),e[93]=Nt,e[94]=bt,e[95]=c,e[96]=Qe):Qe=e[96];const nt=Qe,rt=Qp();let gt;e[97]!==G.isVSCode?(gt=ft=>{if(typeof window>"u"||G.isVSCode)return;const vt=fo(window.history.state);vt?.page===ft&&vt.stage==="page-content"||window.history.pushState({...Kj(),[um]:{page:ft,stage:"page-content"}},"",window.location.href)},e[97]=G.isVSCode,e[98]=gt):gt=e[98];const wt=gt;let Pe;e[99]!==wt||e[100]!==g?(Pe=()=>{k("page-content"),g==="skills.installed"&&wt(g)},e[99]=wt,e[100]=g,e[101]=Pe):Pe=e[101];const se=Pe;let Ce;e[102]!==Nt||e[103]!==G.isVSCode||e[104]!==g?(Ce=()=>{if(Nt){if((typeof window<"u"?fo(window.history.state):null)?.page===g&&!G.isVSCode){window.history.back();return}k("page-sidebar");return}k("nav")},e[102]=Nt,e[103]=G.isVSCode,e[104]=g,e[105]=Ce):Ce=e[105];const Xe=Ce;let Re,Je;e[106]!==u||e[107]!==G.isVSCode||e[108]!==g?(Re=()=>{if(!u||G.isVSCode)return;const ft=vt=>{if(g!=="skills.installed")return;if(fo(vt.state)?.page==="skills.installed"){k("page-content");return}k(tk)};return window.addEventListener("popstate",ft),()=>{window.removeEventListener("popstate",ft)}},Je=[u,G.isVSCode,g],e[106]=u,e[107]=G.isVSCode,e[108]=g,e[109]=Re,e[110]=Je):(Re=e[109],Je=e[110]),l.useEffect(Re,Je);let Ge;e[111]===Symbol.for("react.memo_cache_sentinel")?(Ge=()=>{k("page-sidebar")},e[111]=Ge):Ge=e[111];const st=Ge,jt=()=>{const ft=j.trim().length>0;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[s.jsx("div",{className:"px-4 pt-3",children:s.jsxs("div",{className:"flex h-10 items-center gap-1.5 rounded-md border border-border bg-background/70 px-2 text-muted-foreground focus-within:ring-2 focus-within:ring-primary/40 sm:h-8",children:[s.jsx(K,{name:"search",className:"h-4 w-4 shrink-0"}),s.jsx("input",{value:j,onChange:vt=>N(vt.target.value),onKeyDown:h,placeholder:c("settings.view.search.placeholder"),"aria-label":c("settings.view.search.aria"),className:"typography-ui min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground/70"}),ft&&s.jsx("button",{type:"button",onClick:()=>N(""),"aria-label":c("settings.view.search.clear"),className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground sm:h-5 sm:w-5",children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]})}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overflow-x-hidden",children:s.jsx("div",{className:"flex flex-col gap-0.5 px-4 pt-4 pb-2",children:ft?De.length>0?(()=>{let vt=0;return We.map(Dt=>s.jsxs("div",{className:"space-y-0.5",children:[s.jsx("div",{className:"px-2 pb-0.5 pt-2 typography-micro font-medium text-muted-foreground/70",children:Dt.pageTitle}),Dt.results.map(Vt=>{const ts=vt;vt=vt+1;const os=ts===$,En=!!Vt.description;return s.jsxs("button",{type:"button",ref:zs=>{F.current[ts]=zs},onMouseMove:()=>{D.current=!1,O(ts)},onClick:()=>re(Vt),className:fe("flex w-full flex-col rounded-md px-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",En?"min-h-11 py-1.5":"py-2",os?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Vt.title}),En&&s.jsx("span",{className:"typography-micro text-muted-foreground/70 line-clamp-2",children:Vt.description})]},Vt.id)})]},Dt.page))})():s.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:c("settings.view.search.noResults")}):(()=>{const vt=new Map;for(const Vt of ge){const ts=Vt.group,os=vt.get(ts);os?os.push(Vt):vt.set(ts,[Vt])}return Lj.map(Vt=>({group:Vt,pages:vt.get(Vt)??[]})).filter(sk).map((Vt,ts)=>{const{group:os,pages:En}=Vt;return s.jsxs("div",{className:"space-y-0.5",children:[s.jsx("div",{className:fe("px-3 pb-1 typography-micro font-semibold uppercase tracking-wide text-muted-foreground sm:px-2 sm:pb-0.5",ts===0?"pt-1":"pt-4 sm:pt-3"),children:c(`settings.view.nav.group.${os}`)}),En.map(zs=>{const ga=g===zs.slug&&!(u&&x==="nav"),Yn=mm(zs.slug);return!Yn&&zs.slug!=="mcp"?null:s.jsx(bs,{children:s.jsx(xs,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>ie(zs.slug),"aria-current":ga?"page":void 0,className:fe("flex h-11 w-full items-center gap-2.5 rounded-md px-3 overflow-hidden sm:h-8 sm:gap-2 sm:px-2",ga?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[zs.slug==="mcp"?s.jsx(Aj,{className:"h-[18px] w-[18px] shrink-0 sm:h-4 sm:w-4"}):s.jsx(K,{name:Yn,className:"h-[18px] w-[18px] shrink-0 sm:h-4 sm:w-4"}),s.jsxs("span",{className:"flex items-center gap-1.5 whitespace-nowrap overflow-hidden transition-opacity duration-150 opacity-100",children:[s.jsx("span",{className:"typography-ui-label font-normal truncate",children:Be(zs.slug)}),zs.slug==="tunnel"&&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:c("settings.view.badge.beta")})]})]})})},zs.slug)})]},os)})})()})}),s.jsx("div",{className:"overflow-hidden transition-opacity duration-150 opacity-100",children:s.jsx("div",{className:"border-t border-border bg-background px-4 py-1 space-y-0.5 sm:bg-sidebar",children:!G.isVSCode&&s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsxs("button",{type:"button",className:fe("flex h-11 w-full items-center gap-2 rounded-md px-3 overflow-hidden whitespace-nowrap sm:h-7 sm:px-2","text-sm font-semibold text-sidebar-foreground/90","hover:text-sidebar-foreground hover:bg-interactive-hover"),onClick:ak,children:[s.jsx(K,{name:"restart",className:"h-4 w-4 shrink-0"}),s.jsx("span",{children:c("settings.view.actions.reloadOpenCode")})]})}),s.jsx(ks,{children:c("settings.view.actions.reloadOpenCodeTooltip")})]})})})]})},Et=()=>{if(x==="nav")return s.jsx("div",{className:"flex-1 min-h-0 overflow-hidden bg-background",children:s.jsx("div",{className:"flex h-full min-h-0 flex-col",children:s.jsx(vn,{children:jt()})})});if(!de)return s.jsx("div",{className:"flex-1 bg-background"});if(x==="page-sidebar"){if(de.kind!=="split"){const vt=it(g);return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(vn,{children:vt})})}return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(vn,{children:et(g,{onItemSelect:se})})})}const ft=it(g);return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(vn,{children:ft})})};let Mt;e[112]!==de||e[113]!==it||e[114]!==G.isVSCode||e[115]!==g?(Mt=()=>!de||g==="home"?null:de.kind==="split"?s.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden",children:[s.jsx("div",{className:fe("border-r",G.isVSCode?"bg-background":"bg-sidebar"),style:{width:Id,minWidth:Id,borderColor:"var(--interactive-border)"},children:s.jsx(vn,{children:et(g,{})})}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(vn,{children:it(g)})})]}):s.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(vn,{children:it(g)})}),e[112]=de,e[113]=it,e[114]=G.isVSCode,e[115]=g,e[116]=Mt):Mt=e[116];const Zt=Mt,Qt="true";let St;e[117]===Symbol.for("react.memo_cache_sentinel")?(St=fe("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),e[117]=St):St=e[117];const Pt=u?s.jsxs("div",{className:fe("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",x!=="nav"&&"border-b","bg-background"),style:x!=="nav"?{borderColor:"var(--interactive-border)"}:void 0,children:[bt?s.jsx("button",{type:"button",onClick:Xe,"aria-label":nt,className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(K,{name:"arrow-left-s",className:"h-5 w-5"})}):null,s.jsx("div",{className:"min-w-0 flex-1 px-2 typography-ui-label font-medium text-foreground truncate",children:x==="nav"?c("settings.view.home.title"):de?Be(de.slug):c("settings.view.home.title")}),Se&&s.jsx("button",{type:"button",onClick:st,"aria-label":c("settings.view.actions.openSectionList"),className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(K,{name:"list-unordered",className:"h-5 w-5"})}),n&&s.jsx("button",{type:"button",onClick:n,"aria-label":c("settings.view.actions.closeSettings"),title:c("settings.view.actions.closeSettingsWithShortcut",{shortcut:rt}),className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(K,{name:"close",className:"h-5 w-5"})})]}):s.jsxs(s.Fragment,{children:[bt&&s.jsx("div",{className:fe("absolute left-3 z-50",i?"top-2":"top-3"),children:s.jsx("button",{type:"button",onClick:Xe,"aria-label":c("settings.view.actions.back"),className:"inline-flex h-9 w-9 items-center justify-center rounded-lg p-2 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(K,{name:"arrow-left-s",className:"h-5 w-5"})})}),n&&s.jsx("div",{className:fe("absolute right-0.5 z-50",i?"top-0.5":"top-1"),children:s.jsx("button",{type:"button",onClick:n,"aria-label":c("settings.view.actions.closeSettings"),title:c("settings.view.actions.closeSettingsWithShortcut",{shortcut:rt}),className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0.5 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s.jsx(K,{name:"close",className:"h-5 w-5"})})})]}),Ne="flex flex-1 min-h-0 overflow-hidden",ut=u?Et():s.jsxs(s.Fragment,{children:[s.jsx("div",{className:fe("relative flex h-full min-h-0 flex-col overflow-hidden border-r",H?"bg-sidebar":G.isVSCode?"bg-background":"bg-sidebar"),style:{width:`${Cd}px`,minWidth:`${Cd}px`,borderColor:"var(--interactive-border)"},children:s.jsx(vn,{children:jt()})}),s.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:Zt()})]});let mt;e[118]!==ut?(mt=s.jsx("div",{className:Ne,children:ut}),e[118]=ut,e[119]=mt):mt=e[119];let At;return e[120]!==St||e[121]!==Pt||e[122]!==mt?(At=s.jsxs("div",{ref:M,"data-settings-view":Qt,className:St,children:[Pt,mt]}),e[120]=St,e[121]=Pt,e[122]=mt,e[123]=At):At=e[123],At};function _j(t){return t.settingsPage}function Uj(t){return t.isSettingsDialogOpen}function $j(t){return t.setSettingsPage}function Vj(t){return t.slug!=="home"}function Hj(t,e){return[t,e]}function Wj(t){return t.activeProjectId}function Gj(t){return t.name}function qj(t){return t.name}function Jj(t){return t.name}function Yj(t){return t.name}function Qj(t){return t.name}function Xj(t){if(t.id.startsWith("agents.")){const e=$a.getState(),n=li("new-agent",e.agents.map(Gj));return e.setAgentDraft({name:n,scope:"user"}),e.setSelectedAgent(n),t.id==="agents.create"?"agents.name":t.id}if(t.id.startsWith("commands.")){const e=Sr.getState(),n=li("new-command",e.commands.map(qj));return e.setCommandDraft({name:n,scope:"user"}),e.setSelectedCommand(n),t.id==="commands.create"?"commands.name":t.id}if(t.id.startsWith("mcp.")){const e=_a.getState(),n=li("new-mcp-server",e.mcpServers.map(Jj));return e.setMcpDraft({name:n,scope:"user",type:"local",command:[],url:"",environment:[],headers:[],oauthEnabled:!0,oauthClientId:"",oauthClientSecret:"",oauthScope:"",oauthRedirectUri:"",timeout:"",enabled:!0}),e.setSelectedMcp(n),t.id==="mcp.create"?"mcp.server":t.id}if(t.id.startsWith("snippets.")){const e=Cr.getState(),n=li("new-snippet",e.snippets.map(Yj));return e.setSnippetDraft({name:n,scope:"global"}),e.setSelectedSnippet(n),t.id==="snippets.create"?"snippets.content":t.id}if(t.id.startsWith("skills.")){const e=Cn.getState(),n=li("new-skill",e.skills.map(Qj));return e.setSkillDraft({name:n,scope:"user",source:"opencode",description:"",instructions:""}),e.setSelectedSkill(n),t.id==="skills.create"?"skills.basic-information":t.id}return t.id==="providers.connect"&&pt.getState().setSelectedProvider(Oj),t.id==="plugins.create"?"plugins.spec":t.id}function Zj(){window.dispatchEvent(new CustomEvent("openchamber:settings-open-plugin-add"))}function ek(t,e){switch(t){case"projects":return s.jsx(gv,{onItemSelect:e.onItemSelect});case"agents":return s.jsx(_x,{onItemSelect:e.onItemSelect});case"commands":return s.jsx(ab,{onItemSelect:e.onItemSelect});case"mcp":return s.jsx(fb,{onItemSelect:e.onItemSelect});case"plugins":return s.jsx(yy,{onItemSelect:e.onItemSelect});case"skills.installed":return s.jsx(Ry,{onItemSelect:e.onItemSelect});case"providers":return s.jsx(nw,{onItemSelect:e.onItemSelect});case"usage":return s.jsx(Fw,{onItemSelect:e.onItemSelect});case"magic-prompts":return s.jsx(o1,{onItemSelect:e.onItemSelect});case"snippets":return s.jsx(u1,{onItemSelect:e.onItemSelect});default:return null}}function tk(t){return t==="page-content"?"page-sidebar":t}function sk(t){return t.pages.length>0}function nk(){}function ak(){_n({message:"Restarting OpenCode…",mode:"projects",scopes:["all"]}).catch(nk)}const ZN=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:Bj,getSettingsNavIcon:mm},Symbol.toStringTag,{value:"Module"})),ik=["chat","git","diff","terminal","files","diagram"],rk=["settings","agents","commands","skills","providers","usage","git-identities"],Qs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Td(t){const e=ok();return{sessionId:lk(e),tab:ck(e),settingsPath:dk(e),diffFile:uk(e)}}function ok(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function lk(t){const e=t.get(Qs.SESSION);return!e||e.trim().length===0?null:e.trim()}function ck(t){const e=t.get(Qs.TAB);if(!e)return null;const n=e.toLowerCase().trim();return ik.includes(n)?n:null}function dk(t){const e=t.get(Qs.SETTINGS);if(!e)return null;const n=e.toLowerCase().trim();return n.length===0?null:n==="openchamber"||n==="general"||n==="preferences"?"home":(rk.includes(n),n)}function uk(t){const e=t.get(Qs.FILE);if(!e||e.trim().length===0)return null;try{return decodeURIComponent(e.trim())}catch{return e.trim()}}function Ad(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Qs.SESSION)||t.has(Qs.TAB)||t.has(Qs.SETTINGS)||t.has(Qs.FILE)}catch{return!1}}const mk="chat";function pm(t){const e=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&e.set(Qs.SESSION,t.sessionId),t.isSettingsOpen){const n=t.settingsPath.trim().length>0?t.settingsPath:"home";return e.set(Qs.SETTINGS,n),e}return t.tab!==mk&&e.set(Qs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&e.set(Qs.FILE,t.diffFile),e}function pk(t,e){const n=typeof window<"u"?window.location.pathname:"/",a=t.toString();return a?`${n}?${a}`:n}function gk(t){if(typeof window>"u")return!0;try{const e=new URLSearchParams(window.location.search),n=pm(t),a=[...e.entries()].sort((r,o)=>r[0].localeCompare(o[0])),i=[...n.entries()].sort((r,o)=>r[0].localeCompare(o[0]));if(a.length!==i.length)return!1;for(let r=0;r<a.length;r++)if(a[r][0]!==i[r][0]||a[r][1]!==i[r][1])return!1;return!0}catch{return!0}}function Ed(t,e={}){if(!(typeof window>"u")&&!(fk()||hu())&&!(!e.force&&gk(t)))try{const n=pm(t),a=pk(n);e.replace?window.history.replaceState({...window.history.state,route:t},"",a):window.history.pushState({route:t},"",a)}catch{}}function fk(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function hk(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function eS(){const t=l.useMemo(()=>hk(),[]),e=l.useMemo(()=>hu(),[]),n=l.useRef(!1),a=l.useRef(!1),i=es(m=>m.setCurrentSession),r=ke(m=>m.setActiveMainTab),o=ke(m=>m.setSettingsDialogOpen),d=ke(m=>m.setSettingsPage),c=ke(m=>m.navigateToDiff),p=l.useCallback(async m=>{if(!a.current){a.current=!0;try{if(m.sessionId){const w=es.getState().currentSessionId;if(m.sessionId!==w){const b=es.getState().getDirectoryForSession(m.sessionId);i(m.sessionId,b)}}if(m.settingsPath){d(xl(m.settingsPath)),o(!0);return}ke.getState().isSettingsDialogOpen&&o(!1),m.tab&&r(m.tab),m.diffFile&&(m.tab==="diff"||!m.tab)&&c(m.diffFile)}finally{a.current=!1}}},[i,r,o,d,c]),u=l.useCallback(()=>{const m=es.getState(),w=ke.getState();return{sessionId:m.currentSessionId,tab:w.activeMainTab,isSettingsOpen:w.isSettingsDialogOpen,settingsPath:w.settingsPage,diffFile:w.pendingDiffFile}},[]),f=l.useCallback((m={})=>{if(t||e||a.current)return;const w=u();Ed(w,m)},[t,e,u]);l.useEffect(()=>{if(n.current||(n.current=!0,!Ad()))return;const m=Td();(async()=>(await p(m),!t&&!e&&Ed({...u(),sessionId:m.sessionId??es.getState().currentSessionId,tab:m.tab??ke.getState().activeMainTab,settingsPath:m.settingsPath??ke.getState().settingsPage,diffFile:m.diffFile??ke.getState().pendingDiffFile},{replace:!0,force:!0})))()},[p,u,t,e]),l.useEffect(()=>{if(t||e)return;let m=es.getState().currentSessionId;return es.subscribe(b=>{const g=b.currentSessionId;g===m||a.current||(m=g,f())})},[t,e,f]),l.useEffect(()=>{if(t||e)return;let m=ke.getState().activeMainTab,w=ke.getState().isSettingsDialogOpen,b=ke.getState().settingsPage,g=ke.getState().pendingDiffFile;return ke.subscribe(k=>{if(a.current)return;const y=k.activeMainTab!==m,C=k.isSettingsDialogOpen!==w,z=k.settingsPage!==b,j=k.pendingDiffFile!==g&&k.activeMainTab==="diff";m=k.activeMainTab,w=k.isSettingsDialogOpen,b=k.settingsPage,g=k.pendingDiffFile,(y||C||z||j)&&f()})},[t,e,f]),l.useEffect(()=>{if(typeof window>"u"||t||e)return;const m=()=>{const w=Td();if(Ad())p(w);else{const b=ke.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[p,t,e,r,o])}function tS(){const t=tt.c(5),e=Su(bk),n=l.useRef(e);let a,i;t[0]!==e?(a=()=>{n.current=e},i=[e],t[0]=e,t[1]=a,t[2]=i):(a=t[1],i=t[2]),l.useEffect(a,i);let r,o;t[3]===Symbol.for("react.memo_cache_sentinel")?(r=()=>{let d=!1,c=null;const p=xk,u=f=>{d||(c=window.setTimeout(async()=>{const m=await n.current(),w=typeof m=="number"&&Number.isFinite(m)?p(m):36e5;u(w)},f))};return u(3e3),()=>{d=!0,c!==null&&window.clearTimeout(c)}},o=[],t[3]=r,t[4]=o):(r=t[3],o=t[4]),l.useEffect(r,o)}function xk(t){const e=Math.round(t*1e3);return Math.max(3e5,Math.min(864e5,e))}function bk(t){return t.checkForUpdates}const yk=()=>{const t=tt.c(13),[e,n]=we.useState(!1);let a,i;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>{n(ls())},i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),we.useEffect(a,i);let r;t[2]!==e?(r=async m=>e?await Xg(m):{success:!0,path:m},t[2]=e,t[3]=r):r=t[3];const o=r;let d;t[4]!==e?(d=async m=>e?await Zg():{success:!0},t[4]=e,t[5]=d):d=t[5];const c=d;let p;t[6]!==e?(p=async m=>e?await ef():{success:!0},t[6]=e,t[7]=p):p=t[7];const u=p;let f;return t[8]!==e||t[9]!==o||t[10]!==c||t[11]!==u?(f={isDesktop:e,requestAccess:o,startAccessing:c,stopAccessing:u},t[8]=e,t[9]=o,t[10]=c,t[11]=u,t[12]=f):f=t[12],f},vk=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),wk=({currentBranch:t,localBranches:e,remoteBranches:n,branchInfo:a,onCheckout:i,onCreate:r,remotes:o=[],disabled:d=!1})=>{const{t:c}=lt(),[p,u]=l.useState(!1),[f,m]=l.useState(""),[w,b]=l.useState(!1),[g,x]=l.useState(!1),[k,y]=l.useState(""),[C,z]=l.useState(!1),j=l.useRef(null),N=l.useCallback(H=>{H.stopPropagation()},[]),v=o.length>1,P=l.useMemo(()=>vk(k),[k]),$=l.useMemo(()=>{const H=f.toLowerCase();return H?e.filter(Z=>Z.toLowerCase().includes(H)):e},[f,e]),O=l.useMemo(()=>{const H=f.toLowerCase();return H?n.filter(Z=>Z.toLowerCase().includes(H)):n},[f,n]),M=H=>{if(H===t){u(!1);return}i(H),u(!1),m("")},S=()=>{b(!0),setTimeout(()=>j.current?.focus(),50)},F=async()=>{if(!(!P||C)){if(v){x(!0);return}z(!0);try{await r(P,o[0]),y(""),b(!1),u(!1)}finally{z(!1)}}},E=async H=>{if(!(!P||C)){z(!0);try{await r(P,H),y(""),b(!1),x(!1),u(!1)}finally{z(!1)}}},D=()=>{x(!1)},W=()=>{y(""),b(!1),x(!1)};return l.useEffect(()=>{p||(m(""),b(!1),x(!1),y(""))},[p]),s.jsxs(fs,{open:p,onOpenChange:u,children:[s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(gs,{asChild:!0,children:s.jsxs(ee,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:d,children:[s.jsx(K,{name:"git-branch",className:"size-4 text-primary"}),s.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:t||c("gitView.branch.detachedHead")}),s.jsx(K,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),s.jsx(ks,{sideOffset:8,children:c("gitView.branch.currentBranchTooltip")})]}),s.jsx(hs,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:s.jsxs(Mo,{className:"h-full min-h-0",children:[s.jsx(Lo,{placeholder:c("gitView.branch.searchPlaceholder"),value:f,onValueChange:m,onKeyDown:N}),s.jsxs(Fo,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(Oo,{children:c("gitView.branch.empty")}),s.jsx(kn,{children:g?s.jsxs("div",{className:"px-2 py-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("button",{type:"button",onClick:D,disabled:C,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:s.jsx(K,{name:"arrow-left",className:"size-4"})}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[c("gitView.branch.pushToPrefix")," ",s.jsx("span",{className:"text-foreground font-medium",children:P})," ",c("gitView.branch.pushToSuffix")]})]}),s.jsx("div",{className:"flex flex-col gap-1",children:o.map(H=>s.jsxs("button",{type:"button",onClick:()=>E(H),disabled:C,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[s.jsxs("span",{className:"typography-ui-label text-foreground",children:[C?s.jsx(K,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,H.name]}),s.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:H.pushUrl})]},H.name))})]}):w?s.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[s.jsx("input",{ref:j,placeholder:c("gitView.branch.newBranchPlaceholder"),value:k,onChange:H=>y(H.target.value),onClick:H=>H.stopPropagation(),onKeyDown:H=>{N(H),H.key==="Enter"?(H.preventDefault(),F()):H.key==="Escape"&&(H.preventDefault(),W())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:F,disabled:!P||C,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:C?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"add",className:"size-4"})}),s.jsx("button",{type:"button",onClick:W,disabled:C,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:s.jsx(K,{name:"close",className:"size-4"})})]}):s.jsxs(en,{onSelect:S,children:[s.jsx(K,{name:"add",className:"size-4"}),s.jsx("span",{children:c("gitView.branch.create")})]})}),s.jsx(Oa,{}),s.jsxs(kn,{heading:c("gitView.branch.localBranches"),children:[$.map(H=>s.jsxs(en,{onSelect:()=>M(H),children:[s.jsxs("span",{className:"flex flex-1 flex-col",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:H}),(a?.[H]?.ahead||a?.[H]?.behind)&&s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[a[H].ahead||0," ahead ·"," ",a[H].behind||0," behind"]})]}),t===H&&s.jsx("span",{className:"typography-micro text-primary",children:c("gitView.branch.currentBadge")})]},`local-${H}`)),$.length===0&&s.jsx(en,{disabled:!0,className:"justify-center",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:c("gitView.branch.noLocalBranches")})})]}),s.jsx(Oa,{}),s.jsxs(kn,{heading:c("gitView.branch.remoteBranches"),children:[O.map(H=>s.jsx(en,{onSelect:()=>M(H),children:s.jsx("span",{className:"typography-ui-label text-foreground",children:H})},`remote-${H}`)),O.length===0&&s.jsx(en,{disabled:!0,className:"justify-center",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:c("gitView.branch.noRemoteBranches")})})]})]})]})})]})},jk=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),kk=({currentBranch:t,onRename:e,showEditButton:n=!0})=>{const{t:a}=lt(),[i,r]=l.useState(!1),[o,d]=l.useState(t||""),[c,p]=l.useState(!1),u=l.useRef(null),f=()=>{!t||!e||(d(t),r(!0),setTimeout(()=>u.current?.focus(),0))},m=async()=>{if(!t||!e||!o.trim())return;const g=jk(o);if(g===t){r(!1);return}p(!0);try{await e(t,g),r(!1),d("")}finally{p(!1)}},w=()=>{r(!1),d("")},b=g=>{g.key==="Enter"?(g.preventDefault(),m()):g.key==="Escape"&&(g.preventDefault(),w())};return i?s.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:s.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:g=>{g.preventDefault(),m()},children:[s.jsx(K,{name:"git-branch",className:"size-4 text-primary"}),s.jsx("input",{ref:u,value:o,onChange:g=>d(g.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:a("gitView.branch.namePlaceholder"),onKeyDown:b,autoFocus:!0}),s.jsx("button",{type:"submit",disabled:c,"aria-label":a(c?"gitView.branch.renameSaving":"gitView.branch.renameSave"),title:a(c?"gitView.branch.renameSaving":"gitView.branch.renameSave"),className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:w,disabled:c,"aria-label":a("gitView.branch.renameCancel"),title:a("gitView.branch.renameCancel"),className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:s.jsx(K,{name:"close",className:"size-4"})})]})}):s.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[s.jsx(K,{name:"git-branch",className:"size-4 text-primary shrink-0"}),s.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:t||a("gitView.branch.detachedHead")}),n&&e&&t&&s.jsx(ee,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:a("gitView.branch.renameTitle"),children:s.jsx(K,{name:"edit",className:"size-4"})})]})]})},Nk=t=>{const e=tt.c(44),{syncAction:n,remotes:a,onFetch:i,onSync:r,onRemoveRemote:o,disabled:d,removingRemoteName:c,aheadCount:p,behindCount:u,trackingRemoteName:f,hasUncommittedChanges:m}=t,w=a===void 0?[]:a,b=c===void 0?null:c,g=p===void 0?0:p,x=u===void 0?0:u,k=m===void 0?!1:m,{t:y}=lt(),C=l.useRef(!1),z=!!b,j=w.find(ie=>ie.name===f)??w[0],N=x>0&&k,v=d||n!==null||z||!j||N,P=d||n!==null||z||w.length===0,$=g>0||x>0;let O;e[0]!==y?(O=y("gitView.sync.sync"),e[0]=y,e[1]=O):O=e[1];const M=x>0?`↓${x}`:null,S=g>0?`↑${g}`:null;let F;e[2]!==O||e[3]!==M||e[4]!==S?(F=[O,M,S].filter(Boolean),e[2]=O,e[3]=M,e[4]=S,e[5]=F):F=e[5];const E=F.join(" "),D=N?y("gitView.sync.commitOrStashTooltip"):j?$?y("gitView.sync.syncChangesTooltip",{ahead:g,behind:x}):y("gitView.sync.syncChanges"):y("gitView.sync.noRemoteTooltip"),W=()=>{j&&r(j)},H="inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",Z=N?0:void 0;let Y;e[6]===Symbol.for("react.memo_cache_sentinel")?(Y=fe("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),e[6]=Y):Y=e[6];let A;e[7]!==y?(A=y("gitView.sync.syncChanges"),e[7]=y,e[8]=A):A=e[8];let X;e[9]!==n?(X=n==="sync"?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"refresh",className:"size-4"}),e[9]=n,e[10]=X):X=e[10];let te;e[11]!==E?(te=s.jsx("span",{className:"whitespace-nowrap tabular-nums",children:E}),e[11]=E,e[12]=te):te=e[12];let T;e[13]!==W||e[14]!==v||e[15]!==A||e[16]!==X||e[17]!==te?(T=s.jsxs("button",{type:"button",onClick:W,disabled:v,className:Y,"aria-label":A,children:[X,te]}),e[13]=W,e[14]=v,e[15]=A,e[16]=X,e[17]=te,e[18]=T):T=e[18];let I;e[19]!==Z||e[20]!==T?(I=s.jsx(xs,{asChild:!0,children:s.jsx("span",{className:"inline-flex",tabIndex:Z,children:T})}),e[19]=Z,e[20]=T,e[21]=I):I=e[21];let B;e[22]!==D?(B=s.jsx(ks,{sideOffset:8,children:D}),e[22]=D,e[23]=B):B=e[23];let L;e[24]!==I||e[25]!==B?(L=s.jsxs(bs,{children:[I,B]}),e[24]=I,e[25]=B,e[26]=L):L=e[26];const V=fs;let Q;e[27]===Symbol.for("react.memo_cache_sentinel")?(Q=fe("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),e[27]=Q):Q=e[27];let G;e[28]!==y?(G=y("gitView.sync.moreActionsAria"),e[28]=y,e[29]=G):G=e[29];let ue;e[30]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(K,{name:"arrow-down-s",className:"size-4"}),e[30]=ue):ue=e[30];let ne;e[31]!==P||e[32]!==G?(ne=s.jsx(gs,{asChild:!0,children:s.jsx("button",{type:"button",className:Q,disabled:P,"aria-label":G,children:ue})}),e[31]=P,e[32]=G,e[33]=ne):ne=e[33];const xe=hs,ve="start",me=-40,ge="w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",Ie=w.map(ie=>s.jsx(as,{onSelect:le=>{if(C.current){le.preventDefault(),C.current=!1;return}i(ie)},children:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx(K,{name:"refresh",className:"size-4 text-muted-foreground"}),s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex flex-col",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:y("gitView.sync.fetchFromRemote",{name:ie.name})}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:ie.fetchUrl})]})}),o&&ie.name!==f?s.jsx(ee,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:n!==null||z,onPointerDown:le=>{C.current=!0,le.preventDefault(),le.stopPropagation()},onClick:le=>{C.current=!0,le.preventDefault(),le.stopPropagation(),o(ie)},"aria-label":y("gitView.header.removeRemoteAria",{name:ie.name}),title:y("gitView.header.removeRemoteTitle",{name:ie.name}),children:b===ie.name?s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(K,{name:"close",className:"size-3.5"})}):null]})},ie.name));let oe;e[34]!==xe||e[35]!==Ie?(oe=s.jsx(xe,{align:ve,alignOffset:me,className:ge,children:Ie}),e[34]=xe,e[35]=Ie,e[36]=oe):oe=e[36];let ce;e[37]!==V||e[38]!==ne||e[39]!==oe?(ce=s.jsxs(V,{children:[ne,oe]}),e[37]=V,e[38]=ne,e[39]=oe,e[40]=ce):ce=e[40];let pe;return e[41]!==L||e[42]!==ce?(pe=s.jsxs("div",{className:H,children:[L,ce]}),e[41]=L,e[42]=ce,e[43]=pe):pe=e[43],pe},Sk={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Ck={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function gm(t){return t&&Ck[t]||"var(--primary)"}const Dd=t=>{const e=tt.c(8),{icon:n,className:a,colorToken:i}=t,r=Sk[n??"branch"]??"user-3";let o;e[0]!==i?(o=gm(i),e[0]=i,e[1]=o):o=e[1];let d;e[2]!==o?(d={color:o},e[2]=o,e[3]=d):d=e[3];let c;return e[4]!==a||e[5]!==r||e[6]!==d?(c=s.jsx(K,{name:r,className:a,style:d}),e[4]=a,e[5]=r,e[6]=d,e[7]=c):c=e[7],c},fm=t=>{const e=tt.c(35),{activeProfile:n,identities:a,onSelect:i,isApplying:r,iconOnly:o}=t,d=o===void 0?!1:o,{t:c}=lt(),p=r||a.length===0,u=n?.color;let f;e[0]!==u?(f=gm(u),e[0]=u,e[1]=f):f=e[1];let m;e[2]!==f?(m={color:f},e[2]=f,e[3]=m):m=e[3];let w;e[4]!==n?.color||e[5]!==n?.icon||e[6]!==r?(w=r?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(Dd,{icon:n?.icon,colorToken:n?.color,className:"size-4"}),e[4]=n?.color,e[5]=n?.icon,e[6]=r,e[7]=w):w=e[7];let b;e[8]!==n?.name||e[9]!==d||e[10]!==c?(b=!d&&s.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:n?.name||c("gitView.header.noIdentity")}),e[8]=n?.name,e[9]=d,e[10]=c,e[11]=b):b=e[11];let g;e[12]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(K,{name:"arrow-down-s",className:"size-4 opacity-60"}),e[12]=g):g=e[12];let x;e[13]!==p||e[14]!==m||e[15]!==w||e[16]!==b?(x=s.jsx(xs,{asChild:!0,children:s.jsx(gs,{asChild:!0,children:s.jsxs(ee,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:m,disabled:p,children:[w,b,g]})})}),e[13]=p,e[14]=m,e[15]=w,e[16]=b,e[17]=x):x=e[17];let k;e[18]!==c?(k=c("gitView.header.identityTooltip"),e[18]=c,e[19]=k):k=e[19];let y;e[20]!==k?(y=s.jsx(ks,{sideOffset:8,children:k}),e[20]=k,e[21]=y):y=e[21];let C;e[22]!==y||e[23]!==x?(C=s.jsxs(bs,{children:[x,y]}),e[22]=y,e[23]=x,e[24]=C):C=e[24];let z;e[25]!==n?.id||e[26]!==a||e[27]!==i||e[28]!==c?(z=a.length===0?s.jsx("div",{className:"px-2 py-1.5",children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:c("gitView.header.noProfiles")})}):a.map(v=>{const P=n?.id===v.id;return s.jsx(as,{onSelect:()=>i(v),children:s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(Dd,{icon:v.icon,colorToken:v.color,className:"size-4"}),s.jsxs("span",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:v.name}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:v.userEmail})]}),P?s.jsx(K,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},v.id)}),e[25]=n?.id,e[26]=a,e[27]=i,e[28]=c,e[29]=z):z=e[29];let j;e[30]!==z?(j=s.jsx(hs,{align:"end",className:"w-64",children:z}),e[30]=z,e[31]=j):j=e[31];let N;return e[32]!==C||e[33]!==j?(N=s.jsxs(fs,{children:[C,j]}),e[32]=C,e[33]=j,e[34]=N):N=e[34],N},Ik=t=>{const e=tt.c(21),{comparison:n,trackingBranch:a,tooltipDelayMs:i}=t,r=i===void 0?1e3:i,{t:o}=lt(),d=`${n.remote}/${n.branch}`,c=n.ahead===0&&n.behind===0;let p;e[0]!==o||e[1]!==d||e[2]!==a?(p=a?o("gitView.header.upstreamTooltipTracking",{target:d,tracking:a}):o("gitView.header.upstreamTooltip",{target:d}),e[0]=o,e[1]=d,e[2]=a,e[3]=p):p=e[3];const u=p;let f;e[4]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(K,{name:"git-branch",className:"size-3.5 shrink-0"}),e[4]=f):f=e[4];let m;e[5]!==d?(m=s.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:d}),e[5]=d,e[6]=m):m=e[6];let w;e[7]!==n.ahead||e[8]!==n.behind||e[9]!==c||e[10]!==o?(w=c?s.jsx("span",{className:"tabular-nums text-muted-foreground",children:o("gitView.header.upstreamSynced")}):s.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[n.ahead>0?s.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",n.ahead]}):null,n.behind>0?s.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",n.behind]}):null]}),e[7]=n.ahead,e[8]=n.behind,e[9]=c,e[10]=o,e[11]=w):w=e[11];let b;e[12]!==m||e[13]!==w?(b=s.jsx(xs,{asChild:!0,children:s.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[f,m,w]})}),e[12]=m,e[13]=w,e[14]=b):b=e[14];let g;e[15]!==u?(g=s.jsx(ks,{sideOffset:8,children:u}),e[15]=u,e[16]=g):g=e[16];let x;return e[17]!==b||e[18]!==g||e[19]!==r?(x=s.jsxs(bs,{delayDuration:r,children:[b,g]}),e[17]=b,e[18]=g,e[19]=r,e[20]=x):x=e[20],x},sS=t=>{const e=tt.c(67),{status:n,localBranches:a,remoteBranches:i,branchInfo:r,syncAction:o,remotes:d,onFetch:c,onSync:p,onRemoveRemote:u,removingRemoteName:f,onCheckoutBranch:m,onCreateBranch:w,onRenameBranch:b,activeIdentityProfile:g,availableIdentities:x,onSelectIdentity:k,isApplyingIdentity:y,isWorktreeMode:C,onOpenHistory:z,onOpenGraph:j,onOpenStashes:N,onOpenUpdateBranch:v,onOpenReintegrateCommits:P,pullRequest:$,prChecks:O,onOpenPullRequest:M}=t,{t:S}=lt();if(!n)return null;let F;e[0]!==j||e[1]!==z||e[2]!==P||e[3]!==N||e[4]!==v||e[5]!==S?(F=z||j||N||v?s.jsxs(fs,{children:[s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(gs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":S("gitView.header.repositoryViews"),children:s.jsx(K,{name:"more-fill",className:"size-4"})})})}),s.jsx(ks,{sideOffset:8,children:S("gitView.header.repositoryViews")})]}),s.jsxs(hs,{align:"end",children:[z?s.jsxs(as,{onSelect:z,children:[s.jsx(K,{name:"history",className:"size-4"}),S("gitView.history.title")]}):null,j?s.jsxs(as,{onSelect:j,children:[s.jsx(K,{name:"git-branch",className:"size-4"}),S("gitView.graph.title")]}):null,N?s.jsxs(as,{onSelect:N,children:[s.jsx(K,{name:"archive-stack",className:"size-4"}),S("gitView.stashes.title")]}):null,v?s.jsxs(as,{onSelect:v,children:[s.jsx(K,{name:"git-merge",className:"size-4"}),S("gitView.header.updateBranch")]}):null,P?s.jsxs(as,{onSelect:P,children:[s.jsx(K,{name:"split-cells-horizontal",className:"size-4"}),S("gitView.integrate.title")]}):null]})]}):null,e[0]=j,e[1]=z,e[2]=P,e[3]=N,e[4]=v,e[5]=S,e[6]=F):F=e[6];let E;e[7]!==F?(E=s.jsx("div",{className:"flex items-center gap-1 shrink-0",children:F}),e[7]=F,e[8]=E):E=e[8];const D=E,W=O?O.state==="success"?"var(--status-success)":O.state==="failure"?"var(--status-error)":"var(--status-warning)":null,H=$?$.state==="merged"?"merged":$.state==="closed"?"closed":$.draft?"draft":O?.state==="failure"||$.mergeable===!1||$.mergeableState==="blocked"||$.mergeableState==="dirty"?"blocked":"open":null;let Z;e[9]!==M||e[10]!==W||e[11]!==H||e[12]!==$||e[13]!==S?(Z=$&&M?s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsxs(ee,{variant:"ghost",size:"sm",onClick:M,className:"h-8 gap-1.5 px-2 typography-micro",children:[s.jsx(K,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${H})`}}),s.jsx("span",{className:"tabular-nums text-foreground/80",children:S("gitView.pr.numberLabel",{number:$.number})}),W?s.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:W}}):null]})}),s.jsx(ks,{sideOffset:8,children:S("gitView.header.openPullRequest")})]}):null,e[9]=M,e[10]=W,e[11]=H,e[12]=$,e[13]=S,e[14]=Z):Z=e[14];const Y=Z,A=!n;let X;e[15]!==n.tracking?(X=n.tracking?.split("/")[0],e[15]=n.tracking,e[16]=X):X=e[16];const te=(n.files?.length??0)>0;let T;e[17]!==c||e[18]!==u||e[19]!==p||e[20]!==d||e[21]!==f||e[22]!==n.ahead||e[23]!==n.behind||e[24]!==o||e[25]!==A||e[26]!==X||e[27]!==te?(T=s.jsx(Nk,{syncAction:o,remotes:d,onFetch:c,onSync:p,onRemoveRemote:u,removingRemoteName:f,disabled:A,iconOnly:!0,aheadCount:n.ahead,behindCount:n.behind,trackingRemoteName:X,hasUncommittedChanges:te}),e[17]=c,e[18]=u,e[19]=p,e[20]=d,e[21]=f,e[22]=n.ahead,e[23]=n.behind,e[24]=o,e[25]=A,e[26]=X,e[27]=te,e[28]=T):T=e[28];const I=T;let B;e[29]!==n.tracking||e[30]!==n.upstreamComparison?(B=n.upstreamComparison?s.jsx(Ik,{comparison:n.upstreamComparison,trackingBranch:n.tracking,tooltipDelayMs:1e3}):null,e[29]=n.tracking,e[30]=n.upstreamComparison,e[31]=B):B=e[31];const L=B;let V;e[32]!==g||e[33]!==x||e[34]!==y||e[35]!==k?(V=s.jsx(fm,{activeProfile:g,identities:x,onSelect:k,isApplying:y,iconOnly:!0}),e[32]=g,e[33]=x,e[34]=y,e[35]=k,e[36]=V):V=e[36];const Q=V;let G;e[37]!==r||e[38]!==C||e[39]!==a||e[40]!==m||e[41]!==w||e[42]!==b||e[43]!==i||e[44]!==d||e[45]!==n.current?(G=s.jsx("div",{className:"min-w-0 flex-1",children:C?s.jsx(kk,{currentBranch:n.current,onRename:b}):s.jsx(wk,{currentBranch:n.current,localBranches:a,remoteBranches:i,branchInfo:r,onCheckout:m,onCreate:w,remotes:d})}),e[37]=r,e[38]=C,e[39]=a,e[40]=m,e[41]=w,e[42]=b,e[43]=i,e[44]=d,e[45]=n.current,e[46]=G):G=e[46];let ue;e[47]!==Q?(ue=s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:Q}),e[47]=Q,e[48]=ue):ue=e[48];let ne;e[49]!==G||e[50]!==ue?(ne=s.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[G,ue]}),e[49]=G,e[50]=ue,e[51]=ne):ne=e[51];let xe;e[52]!==Y?(xe=Y?s.jsx("div",{className:"shrink-0",children:Y}):null,e[52]=Y,e[53]=xe):xe=e[53];let ve;e[54]===Symbol.for("react.memo_cache_sentinel")?(ve=s.jsx("div",{className:"min-w-0 flex-1"}),e[54]=ve):ve=e[54];let me;e[55]!==L?(me=L?s.jsx("div",{className:"min-w-0 shrink",children:L}):null,e[55]=L,e[56]=me):me=e[56];let ge;e[57]!==I?(ge=s.jsx("div",{className:"shrink-0",children:I}),e[57]=I,e[58]=ge):ge=e[58];let Ie;e[59]!==D||e[60]!==xe||e[61]!==me||e[62]!==ge?(Ie=s.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[xe,ve,me,D,ge]}),e[59]=D,e[60]=xe,e[61]=me,e[62]=ge,e[63]=Ie):Ie=e[63];let oe;return e[64]!==ne||e[65]!==Ie?(oe=s.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[ne,Ie]}),e[64]=ne,e[65]=Ie,e[66]=oe):oe=e[66],oe},Pk=t=>t==="/",xr=t=>t.replace(/\\/g,"/"),bl=t=>{if(!t||Pk(t))return t;let e=t;for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e},Ba=t=>t.endsWith("/"),Tk=t=>{const e=t.trim();return!e||Ba(e)?e:`${e}/`},yl=t=>t.lastIndexOf("/"),hm=t=>{if(Ba(t))return t;const e=yl(t);return e<0?t:t.slice(0,e+1)},Ak=t=>{const e=yl(t);return t.slice(e+1)},xm=t=>{const e=bl(t.trim());if(!e||e==="~"||e==="~/"||e==="/")return null;const n=yl(e);return n<0?null:e.startsWith("~/")&&n<=1?"~/":n===0?"/":`${e.slice(0,n)}/`},Ek=t=>Ba(t)&&xm(t)!==null,Dk=(t,e)=>`${hm(t)}${e}/`,aa=t=>{if(!t)return null;const e=bl(xr(t.trim()));return e?e.toLowerCase():null},Rd=(t,e)=>{const n=t.trim();return n==="~"?e:n.startsWith("~/")?`${e}${n.slice(1)}`:n},Rk=t=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?t.metaKey&&!t.ctrlKey:t.ctrlKey&&!t.metaKey,ho=t=>{if(!t)return;t.focus({preventScroll:!0});const e=t.value.length;t.setSelectionRange(e,e),t.scrollLeft=t.scrollWidth},Mk=async()=>{try{const t=await ht("/api/fs/home",{method:"GET",headers:{Accept:"application/json"}});if(t.ok){const e=await t.json();if(typeof e.home=="string"&&e.home.trim().length>0)return xr(e.home.trim())}}catch{}return Ps.getFilesystemHome().catch(()=>null)},nS=({open:t,onOpenChange:e})=>{const{t:n}=lt(),a=Cs(h=>h.homeDirectory),i=is(h=>h.projects),r=is(h=>h.addProject),o=$s(h=>h.profiles),d=$s(h=>h.globalIdentity),c=$s(h=>h.defaultGitIdentityId),p=$s(h=>h.loadProfiles),u=$s(h=>h.loadGlobalIdentity),f=$s(h=>h.loadDefaultGitIdentityId),{isDesktop:m,requestAccess:w,startAccessing:b}=yk(),{isMobile:g}=Vs(),x=l.useRef(null),k=l.useRef(null),y=l.useRef(new Map),[C,z]=l.useState(""),[j,N]=l.useState("~/"),[v,P]=l.useState([]),[$,O]=l.useState(!1),[M,S]=l.useState(!1),[F,E]=l.useState(0),[D,W]=l.useState(!1),[H,Z]=l.useState(!1),[Y,A]=l.useState(0),[X,te]=l.useState(!1),[T,I]=l.useState(""),[B,L]=l.useState(null),[V,Q]=l.useState(!1),G=C||a,ue=l.useMemo(()=>new Set(i.map(h=>aa(h.path)).filter(h=>!!h)),[i]);l.useEffect(()=>{if(!t)return;N("~/"),P([]),E(0),W(!1),Z(!1),te(!1),I(""),L(null),Q(!1),requestAnimationFrame(()=>ho(x.current));let h=!1;return(async()=>{const ye=await Mk();h||(z(ye||a||""),requestAnimationFrame(()=>ho(x.current)))})(),()=>{h=!0}},[a,t]),l.useEffect(()=>{t&&(p(),u(),f())},[f,p,u,t]);const ne=l.useMemo(()=>{const h=new Map;d&&h.set(d.id,d);for(const ae of o)h.set(ae.id,ae);return Array.from(h.values())},[o,d]);l.useEffect(()=>{if(!t||!X||B!==null)return;const h=typeof c=="string"?c.trim():"";if(h&&ne.some(ye=>ye.id===h)){L(h);return}const ae=ne.find(ye=>ye.authType==="ssh"||ye.sshKey);ae&&L(ae.id)},[ne,c,X,t,B]);const xe=l.useMemo(()=>ne.find(h=>h.id===B)??null,[ne,B]),ve=l.useMemo(()=>hm(j),[j]),me=l.useMemo(()=>Ba(j)?"":Ak(j),[j]),ge=l.useMemo(()=>G?Rd(ve,G):"",[ve,G]);l.useEffect(()=>{if(!t||!ge){P([]);return}let h=!1;return O(!0),S(!1),Ps.listLocalDirectory(ge).then(ae=>{if(h)return;S(!1);const ye=ae.filter(be=>be.isDirectory).map(be=>({name:be.name,path:xr(be.path)})).sort((be,Ee)=>be.name.localeCompare(Ee.name));P(ye)}).catch(()=>{h||(P([]),S(!0))}).finally(()=>{h||O(!1)}),()=>{h=!0}},[ge,t]);const Ie=l.useMemo(()=>{const h=me.toLowerCase(),ae=V||me.startsWith(".");return v.filter(ye=>ye.name.toLowerCase().startsWith(h)&&(ae||!ye.name.startsWith(".")))},[me,v,V]),oe=l.useMemo(()=>{const h=[];Ek(j)&&h.push({type:"up",value:"browse:up",name:"..",path:xm(j)});for(const ae of Ie){const ye=aa(ae.path);h.push({type:"directory",value:`browse:${ae.path}`,name:ae.name,path:ae.path,disabled:!!(ye&&ue.has(ye))})}return h},[ue,Ie,j]);l.useEffect(()=>{E(0)},[j,oe.length]);const ce=l.useMemo(()=>G?bl(Rd(j,G)):"",[G,j]),pe=aa(ce),ie=!!(pe&&ue.has(pe)),le=l.useMemo(()=>me?Ie.find(h=>h.name===me)??null:null,[me,Ie]),de=!!(ce&&!ie&&(Ba(j)&&M||!Ba(j)&&me.trim().length>0&&le===null)),he=!D&&!H&&!ie&&!!ce,Me=he&&T.trim().length>0,Le=oe[F]??null,Be=!!(Le&&(Le.type==="up"||Le.type==="directory"&&!Le.disabled)),Fe=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",De=n(ie?"directoryExplorerDialog.actions.alreadyAdded":X?D?"directoryExplorerDialog.actions.cloning":"directoryExplorerDialog.actions.cloneAndAdd":D?"directoryExplorerDialog.actions.adding":de?"directoryExplorerDialog.actions.createAndAdd":"directoryExplorerDialog.actions.addProject");l.useLayoutEffect(()=>{const h=k.current;if(!h)return;const ae=()=>A(Math.ceil(h.getBoundingClientRect().width));if(ae(),typeof ResizeObserver>"u")return;const ye=new ResizeObserver(ae);return ye.observe(h),()=>ye.disconnect()},[De]),l.useLayoutEffect(()=>{const h=x.current;h&&(h.scrollLeft=h.scrollWidth)},[Y,j]),l.useLayoutEffect(()=>{t&&ho(x.current)},[t]),l.useLayoutEffect(()=>{const h=oe[F];h&&y.current.get(h.value)?.scrollIntoView({block:"nearest"})},[F,oe]);const ze=l.useCallback(()=>{e(!1)},[e]),Ve=l.useCallback((h,ae)=>{h.stopPropagation();const ye=aa(ae);if(ye&&ue.has(ye))return;r(ae)||J.error(n("directoryExplorerDialog.toast.failedToAddProject"),{description:n("directoryExplorerDialog.toast.selectValidDirectoryPath")})},[r,ue,n]),We=l.useCallback(async h=>{if(!h||D)return;const ae=aa(h);if(ae&&ue.has(ae))return;let ye=h;W(!0);try{const be=!X&&de&&aa(h)===aa(ce);if(X){const et=T.trim();if(!et){J.error(n("directoryExplorerDialog.toast.cloneUrlRequired"));return}ye=(await Ps.cloneRepository({remoteUrl:et,destinationPath:h,gitIdentityId:xe?.id??null})).path}else be&&await Ps.createDirectory(h);if(!r(ye)){J.error(n("directoryExplorerDialog.toast.failedToAddProject"),{description:n("directoryExplorerDialog.toast.selectValidDirectoryPath")});return}ze()}catch(be){J.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:be instanceof Error?be.message:n("directoryExplorerDialog.toast.unknownError")})}finally{W(!1)}},[r,ue,T,ze,X,D,xe?.id,de,ce,n]),_e=l.useCallback(h=>{N(Tk(h))},[]),He=l.useCallback(h=>{N(Dk(j,h.name))},[j]),Ke=l.useCallback(h=>{if(h){if(h.type==="up"){h.path&&_e(h.path);return}h.disabled||He(h)}},[_e,He]),Oe=l.useCallback(async()=>{if(!(!m||H)){Z(!0);try{const h=await w(ce);if(!h.success||!h.path){h.error&&h.error!=="Directory selection cancelled"&&J.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:h.error});return}const ae=await b(h.path);if(!ae.success){J.error(n("directoryExplorerDialog.toast.failedToOpenDirectory"),{description:ae.error||n("directoryExplorerDialog.toast.desktopCouldNotGrantAccess")});return}await We(h.path)}catch(h){J.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:h instanceof Error?h.message:n("directoryExplorerDialog.toast.unknownError")})}finally{Z(!1)}}},[We,m,H,w,b,n,ce]),je=l.useCallback(h=>{if(h.key==="ArrowDown"){h.preventDefault(),E(ae=>Math.min(oe.length-1,ae+1));return}if(h.key==="ArrowUp"){h.preventDefault(),E(ae=>Math.max(0,ae-1));return}if(h.key==="Enter"){if(h.preventDefault(),Rk(h)){We(ce);return}Be&&Ke(Le);return}h.key==="Backspace"&&j===""&&(h.preventDefault(),ze())},[Ke,We,ze,Be,Le,j,oe.length,ce]),Te=s.jsxs("button",{type:"button",onClick:()=>Q(h=>!h),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[V?s.jsx(K,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(K,{name:"checkbox-blank",className:"h-4 w-4"}),n("directoryExplorerDialog.toggle.showHidden")]}),Ue=s.jsxs("div",{className:"px-2.5 py-1.5",children:[X?s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[s.jsx(at,{value:T,onChange:h=>I(h.target.value),placeholder:n("directoryExplorerDialog.clone.remoteUrlPlaceholder"),className:"min-w-0 flex-1 border-border/60 bg-[var(--surface-elevated)] font-mono typography-ui-label shadow-none",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),s.jsx(fm,{activeProfile:xe,identities:ne,onSelect:h=>L(h.id),isApplying:D,iconOnly:!0})]}):null,s.jsxs("div",{className:"relative",children:[s.jsx(K,{name:"folder-add",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),s.jsx(at,{ref:x,value:j,onChange:h=>N(xr(h.target.value)),onKeyDown:je,placeholder:n("directoryExplorerDialog.pathInput.placeholder"),className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",style:!g&&Y>0?{paddingRight:`${Y+24}px`}:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),g?null:s.jsx(ee,{ref:k,variant:"outline",size:"xs",tabIndex:-1,className:"absolute right-1.5 top-1/2 h-7 -translate-y-1/2 gap-1 px-2 typography-meta",disabled:X?!Me:!he,onMouseDown:h=>h.preventDefault(),onClick:()=>{We(ce)},title:De,children:De})]})]}),Ye=s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:s.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[s.jsx("div",{className:"px-2 pb-1 pt-0.5 typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:n("directoryExplorerDialog.browse.directories")}),$?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:n("directoryExplorerDialog.browse.loading")}):oe.length===0?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:n("directoryExplorerDialog.browse.empty")}):s.jsx("div",{className:"space-y-0.5",children:oe.map((h,ae)=>{const ye=ae===F;return s.jsxs("button",{ref:be=>{be?y.current.set(h.value,be):y.current.delete(h.value)},type:"button",disabled:h.type==="directory"&&h.disabled,onMouseEnter:()=>E(ae),onMouseDown:be=>be.preventDefault(),onClick:()=>Ke(h),className:fe("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",ye&&"bg-interactive-selection text-interactive-selection-foreground",!ye&&"hover:bg-interactive-hover/50",h.type==="directory"&&h.disabled&&"cursor-not-allowed opacity-45 hover:bg-transparent"),children:[h.type==="up"?s.jsx(K,{name:"arrow-left-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(K,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:h.name})}),h.type==="directory"&&h.disabled?s.jsx("span",{className:"rounded-full border border-border/60 px-2 py-0.5 typography-meta text-muted-foreground",children:n("directoryExplorerDialog.browse.addedBadge")}):h.type==="directory"?s.jsx("button",{type:"button",onMouseDown:be=>be.stopPropagation(),onClick:be=>Ve(be,h.path),className:"flex-shrink-0 rounded-full p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",title:n("directoryExplorerDialog.browse.quickAdd"),children:s.jsx(K,{name:"add",className:"h-3.5 w-3.5"})}):null]},h.value)})})]})}),q=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Ue,Ye]}),re=s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(K,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(K,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),n("directoryExplorerDialog.footer.navigate")]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(K,{name:"corner-down-left",className:"h-3.5 w-3.5"}),n("directoryExplorerDialog.footer.select")]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{children:Fe}),s.jsx(K,{name:"corner-down-left",className:"h-3.5 w-3.5"}),n("directoryExplorerDialog.footer.add")]})]}),U=()=>s.jsxs(s.Fragment,{children:[g?null:re,s.jsxs("div",{className:fe("flex w-full flex-row justify-end gap-2 sm:w-auto",g&&"justify-stretch"),children:[m?s.jsx(ee,{variant:"ghost",size:"xs",onClick:Oe,disabled:D||H||X,children:n(H?"directoryExplorerDialog.actions.openingFinder":"directoryExplorerDialog.actions.openInFinder")}):null,s.jsx(ee,{variant:"ghost",size:"xs",onClick:()=>te(h=>!h),disabled:D||H,className:fe(g&&"flex-1"),children:n(X?"directoryExplorerDialog.actions.addLocalProject":"directoryExplorerDialog.actions.cloneRepository")}),g?s.jsx(ee,{size:"xs",onClick:()=>{We(ce)},disabled:X?!Me:!he,className:"flex-1",children:De}):null]})]});return g?s.jsx(mi,{open:t,onClose:ze,title:n("directoryExplorerDialog.title"),className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:U()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Te}),q]})}):s.jsx(Kt,{open:t,onOpenChange:e,children:s.jsxs(Bt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(Ut,{className:"px-5 pb-2 pt-5",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx(_t,{children:n("directoryExplorerDialog.title")}),s.jsx(Yt,{className:"mt-2",children:n("directoryExplorerDialog.description")})]}),Te]})}),s.jsx("div",{className:"min-h-0 flex-1 px-2 pb-0",children:q}),s.jsx(rs,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:U()})]})})};function Md(t){const{localBranches:e,remoteBranches:n,query:a}=t,i=a.trim();if(!i)return{matching:[],otherLocal:e,otherRemote:n};const r=Ml(e,i,u=>u),o=Ml(n,i,u=>u),d=[],c=r.other,p=o.other;for(const u of r.matching)d.push({label:u,value:u,source:"local"});for(const u of o.matching)d.push({label:u,value:`remotes/${u}`,source:"remote"});return d.sort((u,f)=>{const m=u.label.localeCompare(f.label,void 0,{sensitivity:"accent"});return m!==0?m:u.source!==f.source?u.source.localeCompare(f.source):u.value.localeCompare(f.value)}),{matching:d,otherLocal:c,otherRemote:p}}const xo="oc:lastWorktreeSourceBranch",Lk=({mode:t,sourceBranch:e,linkedPr:n,selectedBranch:a})=>t==="existing-branch"?a||null:n?null:e||null,Fk=({branches:t,savedSourceBranch:e,rootBranch:n})=>!!(e&&t.includes(e))&&e?{sourceBranch:e,shouldClearSavedSourceBranch:!1}:{sourceBranch:n&&t.includes(n)?n:t.includes("main")?"main":t.includes("master")?"master":t[0]??"",shouldClearSavedSourceBranch:!!e};function Ok({open:t,onOpenChange:e,onSelect:n}){const{t:a}=lt(),i=ke(oe=>oe.isMobile),{github:r}=Va(),o=Sn(oe=>oe.status),d=Sn(oe=>oe.hasChecked),c=ke(oe=>oe.setSettingsDialogOpen),p=ke(oe=>oe.setSettingsPage),u=is(oe=>oe.getActiveProject()),f=u?.path??null,m=we.useMemo(()=>f&&u?{id:u.id,path:f}:null,[u,f]),[w,b]=we.useState("issues"),[g,x]=we.useState(""),[k,y]=we.useState([]),[C,z]=we.useState([]),[j,N]=we.useState(!1),[v,P]=we.useState(!1),[$,O]=we.useState(null),[M,S]=we.useState(null),[F,E]=we.useState(null),[D,W]=we.useState(!1),[H,Z]=we.useState(new Map),[Y,A]=we.useState(1),[X,te]=we.useState(!1),T=Xp(g,350),I=we.useCallback(async oe=>{if(!(!f||!r)&&!(d&&o?.connected===!1)){N(!0),O(null),A(1),te(!1);try{if(w==="issues"&&r.issuesList){const ce=await r.issuesList(f,{page:1,query:oe});ce.connected===!1?(O(a("session.githubIntegration.error.notConnected")),y([])):(y(ce.issues??[]),A(ce.page??1),te(!!ce.hasMore))}else if(w==="prs"&&r.prsList){const ce=await r.prsList(f,{page:1,query:oe});ce.connected===!1?(O(a("session.githubIntegration.error.notConnected")),z([])):(z(ce.prs??[]),A(ce.page??1),te(!!ce.hasMore))}}catch(ce){O(ce instanceof Error?ce.message:a("session.githubIntegration.error.loadDataFailed"))}finally{N(!1)}}},[f,r,d,o,w,a]);we.useEffect(()=>{if(!t||!f||d&&o?.connected===!1||!r)return;if(!T.trim()){I();return}const oe=new AbortController;N(!0),O(null),A(1),te(!1);const ce=w==="issues"&&r.issuesList?r.issuesList(f,{page:1,query:T.trim()}):w==="prs"&&r.prsList?r.prsList(f,{page:1,query:T.trim()}):null;if(!ce){N(!1);return}return ce.then(pe=>{oe.signal.aborted||("issues"in pe?pe.connected===!1?(O(a("session.githubIntegration.error.notConnected")),y([])):(y(pe.issues??[]),A(pe.page??1),te(!!pe.hasMore)):"prs"in pe&&(pe.connected===!1?(O(a("session.githubIntegration.error.notConnected")),z([])):(z(pe.prs??[]),A(pe.page??1),te(!!pe.hasMore))))}).catch(pe=>{oe.signal.aborted||O(pe instanceof Error?pe.message:a("session.githubIntegration.error.loadDataFailed"))}).finally(()=>{oe.signal.aborted||N(!1)}),()=>oe.abort()},[t,f,r,d,o,w,T,I,a]);const B=we.useCallback(async()=>{if(!(!f||!r)&&!(j||v)&&X){P(!0);try{const oe=Y+1;if(w==="issues"&&r.issuesList){const ce=T.trim()?await r.issuesList(f,{page:oe,query:T.trim()}):await r.issuesList(f,{page:oe});ce.connected!==!1&&(y(pe=>[...pe,...ce.issues??[]]),A(ce.page??oe),te(!!ce.hasMore))}else if(w==="prs"&&r.prsList){const ce=T.trim()?await r.prsList(f,{page:oe,query:T.trim()}):await r.prsList(f,{page:oe});ce.connected!==!1&&(z(pe=>[...pe,...ce.prs??[]]),A(ce.page??oe),te(!!ce.hasMore))}}catch{}finally{P(!1)}}},[f,r,w,Y,X,j,v,T]);we.useEffect(()=>{if(!t){b("issues"),x(""),y([]),z([]),S(null),E(null),W(!1),O(null),Z(new Map),A(1),te(!1);return}I()},[t,I]);const L=we.useCallback(async oe=>{if(!(!m||!oe)&&!H.has(oe))try{const pe=(await ou(m,{mode:"new",branchName:oe,worktreeName:oe})).errors.find(ie=>ie.code==="branch_in_use");Z(ie=>new Map(ie).set(oe,{isValid:!pe,error:pe?a(pe.code==="branch_exists"?"session.githubIntegration.validation.branchAlreadyExists":"session.githubIntegration.validation.branchAlreadyCheckedOut"):null}))}catch{Z(ce=>new Map(ce).set(oe,{isValid:!1,error:a("session.githubIntegration.validation.failed")}))}},[m,H,a]);we.useEffect(()=>{!t||w!=="prs"||C.forEach(oe=>{oe.head&&L(oe.head)})},[t,w,C,L]);const V=d&&o?.connected===!0,Q=()=>{p("github"),c(!0)},G=oe=>{S(oe),E(null)},ue=oe=>{E(oe),S(null)},ne=()=>{M?n({type:"issue",item:M}):F&&n({type:"pr",item:F,includeDiff:D}),e(!1)},xe=()=>{S(null),E(null),W(!1)},ve=M||F&&H.get(F.head??"")?.isValid!==!1,me=oe=>oe.head?H.get(oe.head)?.isValid===!1:!0,ge=s.jsx(s.Fragment,{children:V?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"relative mt-2",children:[s.jsx(K,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(at,{value:g,onChange:oe=>x(oe.target.value),placeholder:a(w==="issues"?"session.githubIntegration.search.issuesPlaceholder":"session.githubIntegration.search.prsPlaceholder"),className:"h-8 pl-9"})]}),s.jsx("div",{className:"mt-2 h-[300px] overflow-hidden",children:s.jsxs("div",{className:"h-full overflow-y-auto",children:[j&&s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsx(K,{name:"loader-4",className:"h-5 w-5 animate-spin text-muted-foreground"})}),$&&s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-destructive/10 text-destructive",children:[s.jsx(K,{name:"error-warning",className:"h-4 w-4"}),s.jsx("span",{className:"typography-small",children:$})]})}),!j&&!$&&w==="issues"&&s.jsxs("div",{className:"space-y-0.5 min-h-full",children:[k.length>0?k.map(oe=>s.jsx("button",{onClick:()=>G(oe),className:fe("w-full text-left px-2 py-1.5 rounded transition-colors",M?.number===oe.number?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("span",{className:"text-muted-foreground shrink-0 typography-micro",children:["#",oe.number]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"typography-small line-clamp-2",children:oe.title}),oe.sourceRepo?.source==="upstream"?s.jsxs("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info mt-0.5 inline-block",children:[oe.sourceRepo.owner,"/",oe.sourceRepo.repo]}):null]})]})},`${oe.sourceRepo?.owner??""}-${oe.sourceRepo?.repo??""}-${oe.number}`)):s.jsx("div",{className:"flex items-center justify-center h-[300px] text-center typography-small text-muted-foreground",children:a("session.githubIntegration.empty.noIssuesFound")}),X&&!v&&s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{B()},className:"h-7 text-xs",children:a("session.githubIntegration.actions.loadMore")})}),v&&s.jsx("div",{className:"flex items-center justify-center py-2",children:s.jsx(K,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground"})})]}),!j&&!$&&w==="prs"&&s.jsxs("div",{className:"space-y-0.5 min-h-full",children:[C.length>0?C.map(oe=>{const ce=me(oe),pe=oe.head?H.get(oe.head):void 0;return s.jsx("button",{onClick:()=>!ce&&ue(oe),disabled:ce,className:fe("w-full text-left px-2 py-1.5 rounded transition-colors",F?.number===oe.number?"bg-interactive-selection text-interactive-selection-foreground":ce?"opacity-50 cursor-not-allowed":"hover:bg-interactive-hover"),children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("span",{className:"text-muted-foreground shrink-0 typography-micro",children:["#",oe.number]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"typography-small line-clamp-1",children:oe.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[oe.head," → ",oe.base]}),oe.sourceRepo?.source==="upstream"?s.jsxs("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info",children:[oe.sourceRepo.owner,"/",oe.sourceRepo.repo]}):null,ce&&pe?.error&&s.jsx("span",{className:"typography-micro text-destructive",children:pe.error})]})]})]})},`${oe.sourceRepo?.owner??""}-${oe.sourceRepo?.repo??""}-${oe.number}`)}):s.jsx("div",{className:"flex items-center justify-center h-[300px] text-center typography-small text-muted-foreground",children:a("session.githubIntegration.empty.noPullRequestsFound")}),X&&!v&&s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{B()},className:"h-7 text-xs",children:a("session.githubIntegration.actions.loadMore")})}),v&&s.jsx("div",{className:"flex items-center justify-center py-2",children:s.jsx(K,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground"})})]})]})})]}):s.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 gap-4",children:[s.jsx(K,{name:"github",className:"h-12 w-12 text-muted-foreground"}),s.jsxs("div",{className:"text-center",children:[s.jsx("p",{className:"typography-ui-label text-foreground",children:a("session.githubIntegration.connect.title")}),s.jsx("p",{className:"typography-small text-muted-foreground mt-1",children:a("session.githubIntegration.connect.description")})]}),s.jsx(ee,{onClick:Q,size:"sm",children:a("session.githubIntegration.connect.action")})]})}),Ie=s.jsxs("div",{className:fe("w-full",i?"flex flex-col gap-2":"flex flex-row items-center"),children:[s.jsxs("div",{className:fe("flex items-center gap-4",i?"w-full justify-center order-1":"flex-1"),children:[!i&&(M||F)&&s.jsxs("div",{className:"flex items-center gap-2 px-2 h-8 rounded-md bg-muted/50 border border-border/50",children:[s.jsx(K,{name:"check",className:"h-3.5 w-3.5 text-status-success shrink-0"}),s.jsx("span",{className:"typography-small truncate max-w-[150px]",children:M?a("session.githubIntegration.selected.issueNumber",{number:M.number}):a("session.githubIntegration.selected.prNumber",{number:F?.number??""})}),s.jsx("button",{onClick:xe,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]}),w==="prs"&&F&&s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer h-8",children:[s.jsx(an,{checked:D,onChange:oe=>W(oe),ariaLabel:a("session.githubIntegration.includeDiffAria")}),s.jsx("span",{className:"typography-small text-foreground",children:a("session.githubIntegration.includeDiff")})]})]}),s.jsxs("div",{className:fe("flex gap-2",i?"w-full order-2":"justify-end"),children:[s.jsx(ee,{variant:"outline",size:"sm",onClick:()=>e(!1),className:fe(i&&"flex-1"),children:a("session.githubIntegration.actions.cancel")}),s.jsx(ee,{size:"sm",onClick:ne,disabled:!ve,className:fe(i&&"flex-1"),children:a("session.githubIntegration.actions.select")})]})]});return s.jsx(s.Fragment,{children:i?s.jsx(mi,{open:t,title:a("session.githubIntegration.title"),onClose:()=>e(!1),footer:V?Ie:void 0,renderHeader:oe=>s.jsxs("div",{className:"flex flex-col gap-2 px-3 py-2 border-b border-border/40",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:a("session.githubIntegration.title")}),oe]}),s.jsx("div",{className:"w-full",children:s.jsx(ma,{items:[{id:"issues",label:a("session.githubIntegration.tabs.issues"),icon:s.jsx(K,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"prs",label:a("session.githubIntegration.tabs.pullRequests"),icon:s.jsx(K,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],activeId:w,onSelect:ce=>{b(ce),x("")},variant:"active-pill",layoutMode:"fit"})}),(M||F)&&s.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md bg-muted/50 border border-border/50",children:[s.jsx(K,{name:"check",className:"h-3.5 w-3.5 text-status-success shrink-0"}),s.jsx("span",{className:"typography-small truncate flex-1",children:M?a("session.githubIntegration.selected.issueNumber",{number:M.number}):a("session.githubIntegration.selected.prNumber",{number:F?.number??""})}),s.jsx("button",{onClick:xe,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]})]}),children:ge}):s.jsx(Kt,{open:t,onOpenChange:e,children:s.jsxs(Bt,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[s.jsx(Ut,{className:"flex flex-row items-center justify-between",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs(_t,{className:"flex items-center gap-2 shrink-0",children:[s.jsx(K,{name:"github",className:"h-5 w-5"}),a("session.githubIntegration.title")]}),s.jsx("div",{className:"w-[220px]",children:s.jsx(ma,{items:[{id:"issues",label:a("session.githubIntegration.tabs.issues"),icon:s.jsx(K,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"prs",label:a("session.githubIntegration.tabs.pullRequests"),icon:s.jsx(K,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],activeId:w,onSelect:oe=>{b(oe),x("")},variant:"active-pill",layoutMode:"fit"})})]})}),ge,s.jsx(rs,{className:"mt-1",children:Ie})]})})})}const ui=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,""),As=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,"").split("/").join("-").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"").slice(0,80),zk=t=>String(t).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"pr-head",Ld=(t,e,n)=>{const a=ui(t.head||"");if(!a)throw new Error("PR head branch is missing");if(e.includes(a))return{existingBranch:a,setUpstream:void 0,upstreamRemote:void 0,upstreamBranch:void 0,ensureRemoteName:void 0,ensureRemoteUrl:void 0,sourceLabel:a};const i=n.find(p=>{const u=p.indexOf("/");return u<=0||u>=p.length-1?!1:p.slice(u+1)===a});if(i){const p=i.indexOf("/"),u=i.slice(0,p);return{existingBranch:`remotes/${i}`,setUpstream:!0,upstreamRemote:u,upstreamBranch:a,ensureRemoteName:void 0,ensureRemoteUrl:void 0,sourceLabel:`${u}/${a}`}}const r=String(t.headLabel||"").split(":")[0]?.trim(),o=t.headRepo?.owner||r||"pr-head",d=`pr-${zk(o)}`,c=t.headRepo?.sshUrl||t.headRepo?.cloneUrl||"";if(!c)throw new Error("PR head repository URL is unavailable");return{existingBranch:`remotes/${d}/${a}`,setUpstream:!0,upstreamRemote:d,upstreamBranch:a,ensureRemoteName:d,ensureRemoteUrl:c,sourceLabel:`${d}/${a}`}},Kk=t=>{const e={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
35
- ${JSON.stringify(e,null,2)}`},Bk=t=>`GitHub pull request context (JSON)
36
- ${JSON.stringify(t,null,2)}`;function aS({open:t,onOpenChange:e,onWorktreeCreated:n}){const{t:a}=lt(),{github:i,git:r}=Va(),o=ke(U=>U.isMobile),d=Sn(U=>U.status),c=Sn(U=>U.hasChecked),p=is(U=>U.getActiveProject()),u=p?.path??null,f=we.useMemo(()=>u&&p?{id:p.id,path:u}:null,[p,u]),[m,w]=we.useState("new-branch"),[b,g]=we.useState({branchName:"",worktreeName:"",isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1}),[x,k]=we.useState({selectedBranch:"",worktreeName:""}),y=Zp(u),C=eg(u),z=Nr(U=>U.fetchBranches),j=we.useMemo(()=>y?.all?y.all.filter(U=>!U.startsWith("remotes/")).sort():[],[y]),N=we.useMemo(()=>y?.all?y.all.filter(U=>U.startsWith("remotes/")).map(U=>U.replace(/^remotes\//,"")).sort():[],[y]),v=es(U=>U.availableWorktreesByProject),P=we.useMemo(()=>{if(!u)return new Set;const U=v.get(u)??[];return new Set(U.map(h=>h.name))},[v,u]),$=we.useCallback((U=10)=>{for(let h=0;h<U;h++){const ae=Wr();if(!P.has(ae))return ae}return`${Wr()}-${Date.now().toString(36).slice(-4)}`},[P]),[O,M]=we.useState(!1),[S,F]=we.useState(!1),[E,D]=we.useState(!1),[W,H]=we.useState(!1),[Z,Y]=we.useState(!1),[A,X]=we.useState(""),[te,T]=we.useState(""),I=we.useRef(null),B=we.useRef(null),L=we.useRef(null),V=we.useRef(null),Q=we.useCallback(U=>{U.stopPropagation()},[]),G=we.useCallback(U=>{let h=U;for(;h&&h!==document.body;){const{overflowY:ae}=window.getComputedStyle(h);if((ae==="auto"||ae==="scroll")&&h.scrollHeight>h.clientHeight)return h;h=h.parentElement}return null},[]),ue=we.useCallback(U=>{U&&(U.scrollTop=0)},[]),ne=we.useCallback(U=>{const h=U.current?.querySelector('[data-slot="command-list"]')??null;ue(h)},[ue]),xe=we.useCallback(U=>{const h=G(U.current);ue(h)},[G,ue]),ve=we.useMemo(()=>Md({localBranches:j,remoteBranches:N,query:A}),[j,N,A]),me=we.useMemo(()=>Md({localBranches:j,remoteBranches:N,query:te}),[j,N,te]),ge=A.trim().length>0,Ie=te.trim().length>0,oe=ve.matching.length>0,ce=me.matching.length>0,pe=!!(u&&r),ie=we.useCallback(()=>{!u||!r||z(u,r)},[u,r,z]);we.useEffect(()=>{!t||!u||!r||y?.all||z(u,r)},[t,u,r,y?.all,z]),we.useEffect(()=>{!S&&!W&&X("")},[S,W]),we.useEffect(()=>{!E&&!Z&&T("")},[E,Z]),we.useEffect(()=>{S&&ne(I),W&&xe(L)},[S,W,A,ne,xe]),we.useEffect(()=>{E&&ne(B),Z&&xe(V)},[E,Z,te,ne,xe]);const[le,de]=we.useState({isValidating:!1,branchError:null,worktreeError:null,touched:!1}),[he,Me]=we.useState(!1),[Le,Be]=we.useState(null),Fe=we.useCallback(()=>{const U=pt.getState(),h=U.getVisibleAgents();if(U.settingsDefaultAgent){const ae=h.find(ye=>ye.name===U.settingsDefaultAgent);if(ae)return ae.name}return h.find(ae=>ae.name==="build")?.name||h[0]?.name},[]),De=we.useCallback(()=>{const U=pt.getState(),h=U.settingsDefaultModel;if(!h)return null;const ae=Hn(h);if(!ae)return null;const{providerId:ye,modelId:be}=ae;return U.getModelMetadata(ye,be)?{providerID:ye,modelID:be}:null},[]),ze=we.useCallback((U,h)=>{const ae=pt.getState(),ye=ae.settingsDefaultVariant,be=ae.currentProviderId===U&&ae.currentModelId===h?ae.currentVariant:void 0,Ze=ae.providers.find(it=>it.id===U)?.models.find(it=>it.id===h)?.variants;if(!Ze)return ye||be||void 0;if(ye&&Object.prototype.hasOwnProperty.call(Ze,ye))return ye;if(be&&Object.prototype.hasOwnProperty.call(Ze,be))return be},[]),Ve=we.useCallback(async U=>{if(!u||!i)return;const h=pt.getState(),ae=ol.getState().lastUsedProvider,ye=De(),be=ye?.providerID||h.currentProviderId||ae?.providerID,Ee=ye?.modelID||h.currentModelId||ae?.modelID,et=Fe()||h.currentAgentName||void 0;if(!be||!Ee){J.error(a("session.newWorktree.error.noModelSelected"));return}const Ze=ze(be,Ee);if(U.issue){if(!i.issueGet||!i.issueComments)return;const it=await i.issueGet(u,U.issue.number,{sourceRepo:U.issue.sourceRepo??null});if(it.connected===!1||!it.repo||!it.issue)throw new Error("Failed to load issue context");const ot=await i.issueComments(u,U.issue.number,{sourceRepo:U.issue.sourceRepo??null});if(ot.connected===!1)throw new Error("Failed to load issue comments");const xt=await Un("github.issue.review.visible",{issue_number:String(U.issue.number)}),bt=await Un("github.issue.review.instructions"),Nt=Kk({repo:it.repo,issue:it.issue,comments:ot.comments??[]});await es.getState().sendMessage(xt,be,Ee,et,void 0,void 0,[{text:bt,synthetic:!0},{text:Nt,synthetic:!0}],Ze,void 0,{sessionId:U.sessionId}),J.success(a("session.newWorktree.toast.sessionFromIssue"));return}if(U.pr){if(!i.prContext)return;const it=await i.prContext(u,U.pr.number,{sourceRepo:U.pr.sourceRepo??null,includeDiff:U.includeDiff,includeCheckDetails:!1});if(it.connected===!1||!it.repo||!it.pr)throw new Error("Failed to load PR context");const ot=await Un("github.pr.review.visible",{pr_number:String(U.pr.number)}),xt=await Un("github.pr.review.instructions"),bt=Bk(it);await es.getState().sendMessage(ot,be,Ee,et,void 0,void 0,[{text:xt,synthetic:!0},{text:bt,synthetic:!0}],Ze,void 0,{sessionId:U.sessionId}),J.success(a("session.newWorktree.toast.sessionFromPr"))}},[i,u,Fe,De,ze,a]),We=m==="new-branch"?b:x;we.useEffect(()=>{if(!t||!y?.all||!u||b.sourceBranch)return;const U=b.sourceBranch;let h=!1;return(async()=>{try{const ye=await tg(u).catch(()=>null);if(h)return;const be=localStorage.getItem(xo),{sourceBranch:Ee,shouldClearSavedSourceBranch:et}=Fk({branches:y.all,savedSourceBranch:be,rootBranch:ye});if(et&&localStorage.removeItem(xo),h||U)return;Ee&&g(Ze=>({...Ze,sourceBranch:Ee}))}catch{}})(),()=>{h=!0}},[t,y?.all,u,b.sourceBranch]),we.useLayoutEffect(()=>{if(!t)return;w("new-branch"),k({selectedBranch:"",worktreeName:""}),F(!1),D(!1),H(!1),Y(!1),X(""),T(""),de({isValidating:!1,branchError:null,worktreeError:null,touched:!1});const U=$();g({branchName:U,worktreeName:U,isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1})},[t,$]),we.useEffect(()=>{if(m!=="new-branch"||!b.isSyncingWorktreeName)return;const U=ui(b.branchName),h=As(U);g(ae=>({...ae,worktreeName:h}))},[m,b.branchName,b.isSyncingWorktreeName]);const _e=we.useCallback(async()=>{if(!f||!le.touched||he)return;Le&&Le.abort();const U=new AbortController;Be(U),de(h=>({...h,isValidating:!0}));try{const h=m==="new-branch"?b.branchName:x.selectedBranch,ae=We.worktreeName,ye=ui(h),be=As(ae);let Ee=null,et=null;if(ye||(Ee=a("session.newWorktree.error.branchNameRequired")),be||(et=a("session.newWorktree.error.worktreeDirectoryRequired")),ye&&be){const Ze=m==="new-branch"?b.linkedPr:null,it=Ze?Ld(Ze,j,N):null,ot=await ou(f,{mode:m==="existing-branch"||it?"existing":"new",branchName:ye,worktreeName:be,existingBranch:it?.existingBranch??(m==="existing-branch"?ye:void 0),...it?.ensureRemoteName?{ensureRemoteName:it.ensureRemoteName}:{},...it?.ensureRemoteUrl?{ensureRemoteUrl:it.ensureRemoteUrl}:{}});if(U.signal.aborted)return;ot.ok||ot.errors.forEach(xt=>{if(xt.code==="worktree_exists"){et=et??xt.message;return}xt.code.startsWith("branch_")&&(Ee=Ee??xt.message)})}U.signal.aborted||de(Ze=>({...Ze,isValidating:!1,branchError:Ee,worktreeError:et}))}catch{U.signal.aborted||de(h=>({...h,isValidating:!1}))}},[f,m,b.branchName,b.linkedPr,x.selectedBranch,We.worktreeName,j,N,le.touched,Le,he,a]),He=m==="new-branch"?b.branchName:x.selectedBranch;we.useEffect(()=>{if(!t||!f||!le.touched||he)return;const U=setTimeout(()=>{_e()},300);return()=>clearTimeout(U)},[We.worktreeName,He,t,f,_e,le.touched,he]);const Ke=async()=>{if(!f||!u){J.error(a("session.newWorktree.error.noActiveProject"));return}de(be=>({...be,touched:!0}));const U=m==="new-branch"?b.branchName:x.selectedBranch,h=We.worktreeName,ae=ui(U),ye=As(h);if(!ae){J.error(a("session.newWorktree.error.branchNameRequired"));return}if(!ye){J.error(a("session.newWorktree.error.worktreeDirectoryRequired"));return}Le&&(Le.abort(),Be(null)),de(be=>({...be,isValidating:!1,branchError:null,worktreeError:null})),Me(!0);try{const be=m==="new-branch"?b.linkedPr:null,Ee=m==="new-branch"?b.linkedIssue:null,et=m==="new-branch"?b.linkedPr:null,Ze=m==="new-branch"?b.includePrDiff:!1,it=!!(Ee||et),ot=await nu(f),xt=b.sourceBranch;let bt="";const Nt=(()=>{if(be){const gt=Ld(be,j,N);return bt=gt.sourceLabel,{preferredName:ae||ye,mode:"existing",branchName:ae,worktreeName:ye,existingBranch:gt.existingBranch,setupCommands:ot,setUpstream:gt.setUpstream,upstreamRemote:gt.upstreamRemote,upstreamBranch:gt.upstreamBranch,returnAfterDirectoryCreated:!0,...gt.ensureRemoteName?{ensureRemoteName:gt.ensureRemoteName}:{},...gt.ensureRemoteUrl?{ensureRemoteUrl:gt.ensureRemoteUrl}:{}}}return bt=m==="new-branch"?xt:"",{preferredName:ae||ye,mode:m==="existing-branch"?"existing":"new",branchName:m==="existing-branch"?void 0:ae,worktreeName:ye,existingBranch:m==="existing-branch"?ae:void 0,setupCommands:ot,returnAfterDirectoryCreated:!0,...xt&&m==="new-branch"?{startRef:xt}:{}}})(),Se=await sg(u,Nt),Qe=await ng(f,Se);let nt=null;if(it){await au(f)&&await ag(Qe.path);const gt=Ee?`#${Ee.number} ${Ee.title}`.trim():et?`#${et.number} ${et.title}`.trim():a("session.newWorktree.newSessionTitle"),wt=await ig(gt,Qe.path,null);if(!wt?.id)throw new Error("Failed to create session");nt=wt.id,n?.(Qe.path,{sessionId:nt}),e(!1),Me(!1),rg(wt.id,gt).catch(()=>{});try{es.getState().initializeNewOpenChamberSession(wt.id,pt.getState().agents)}catch{}}else e(!1),Me(!1);const rt=Lk({mode:m,sourceBranch:b.sourceBranch,linkedPr:!!b.linkedPr,selectedBranch:x.selectedBranch});rt&&localStorage.setItem(xo,rt),J.success(a("session.newWorktree.toast.worktreeCreated"),{description:a("session.newWorktree.toast.worktreeCreatedDescription",{target:`${Qe.branch||Qe.name}${bt?` ${a("session.newWorktree.fromSource",{source:bt})}`:""}`})}),nt?Ve({sessionId:nt,directory:Qe.path,issue:Ee,pr:et,includeDiff:Ze}).catch(gt=>{const wt=gt instanceof Error?gt.message:a("session.newWorktree.error.sendGitHubContextFailed");J.error(a("session.newWorktree.error.sendGitHubContextFailed"),{description:wt})}):n?.(Qe.path)}catch(be){const Ee=be instanceof Error?be.message:a("session.newWorktree.error.createWorktreeFailed");J.error(a("session.newWorktree.error.createWorktreeFailed"),{description:Ee})}finally{Me(!1)}},Oe=U=>{w(U),de(h=>({...h,touched:!1,branchError:null,worktreeError:null}))},je=U=>{if(!U){g(h=>({...h,linkedIssue:null,linkedPr:null,includePrDiff:!1,branchName:""}));return}if(U.type==="issue"){const h=U.item,ae=`issue-${h.number}-${Wr()}`;g(ye=>({...ye,linkedIssue:h,linkedPr:null,includePrDiff:!1,branchName:ae,worktreeName:As(ae),isSyncingWorktreeName:!0}))}else if(U.type==="pr"){const h=U.item;g(ae=>({...ae,linkedPr:h,linkedIssue:null,includePrDiff:U.includeDiff??!1,branchName:h.head,worktreeName:As(h.head),isSyncingWorktreeName:!0}))}},Te=c&&d?.connected===!0,Ye=(m==="existing-branch"?!!x.selectedBranch&&!!x.worktreeName&&!le.branchError&&!le.worktreeError:!!ui(b.branchName)&&!!b.worktreeName&&!le.branchError&&!le.worktreeError)&&!he,q=()=>{g(U=>({...U,linkedIssue:null,linkedPr:null,branchName:"",includePrDiff:!1,isSyncingWorktreeName:!0}))},re=s.jsxs("div",{className:fe("flex gap-2",o?"flex-col w-full":"flex-row items-center"),children:[s.jsx("div",{className:fe("flex items-center gap-1.5 text-destructive",o?"w-full justify-center order-first":"mr-auto"),children:le.touched&&(le.branchError||le.worktreeError)&&s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"error-warning",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"typography-micro",children:le.branchError||le.worktreeError})]})}),s.jsxs("div",{className:fe("flex gap-2",o&&"w-full"),children:[s.jsx(ee,{variant:"outline",size:"sm",onClick:()=>e(!1),disabled:he,className:fe(o&&"flex-1"),children:a("session.newWorktree.actions.cancel")}),s.jsxs(ee,{size:"sm",onClick:Ke,disabled:!Ye||he,className:fe("gap-1.5",o&&"flex-1"),children:[he&&s.jsx(K,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),a(he?"session.newWorktree.actions.creating":"session.newWorktree.actions.createWorktree")]})]})]});return s.jsxs(s.Fragment,{children:[o?s.jsxs(mi,{open:t,title:a("session.newWorktree.title"),onClose:()=>e(!1),footer:re,children:[s.jsx("div",{className:"w-full mb-4",children:s.jsx(ma,{items:[{id:"new-branch",label:a("session.newWorktree.mode.newBranch"),icon:s.jsx(K,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"existing-branch",label:a("session.newWorktree.mode.existingBranch"),icon:s.jsx(K,{name:"git-repository",className:"h-3.5 w-3.5"})}],activeId:m,onSelect:U=>Oe(U),variant:"active-pill",layoutMode:"fit",className:"w-full"})}),s.jsxs("div",{className:"space-y-6",children:[m==="existing-branch"?s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:a("session.newWorktree.selectBranch")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>H(!0),className:"flex-1 justify-between h-9",children:[s.jsx("span",{className:x.selectedBranch?"text-foreground":"text-muted-foreground",children:x.selectedBranch||a("session.newWorktree.chooseBranch")}),s.jsx(K,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(ee,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0 shrink-0",onClick:ie,disabled:!pe||C,title:a("session.newWorktree.fetchBranches"),children:C?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"refresh",className:"size-4"})})]}),s.jsx(mi,{open:W,title:a("session.newWorktree.selectBranch"),onClose:()=>H(!1),children:s.jsxs("div",{className:"space-y-4",ref:L,children:[s.jsx(at,{value:A,onChange:U=>X(U.target.value),placeholder:a("session.newWorktree.searchBranches"),className:"h-8"}),C?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):j.length===0&&N.length===0?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noBranchesFound")}):s.jsxs("div",{className:"space-y-4",children:[ge&&oe&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:a("session.newWorktree.matchingBranches")}),s.jsx("div",{className:"space-y-1",children:ve.matching.map(U=>s.jsx("button",{onClick:()=>{k(h=>({...h,selectedBranch:U.value,worktreeName:As(U.label)})),de(h=>({...h,touched:!0})),H(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===U.value?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:U.label})},`${U.source}-${U.value}`))})]}),ge&&!oe&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),ve.otherLocal.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:a(ge?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches")}),s.jsx("div",{className:"space-y-1",children:ve.otherLocal.map(U=>s.jsx("button",{onClick:()=>{k(h=>({...h,selectedBranch:U,worktreeName:As(U)})),de(h=>({...h,touched:!0})),H(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===U?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:U})},U))})]}),ve.otherRemote.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:a(ge?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches")}),s.jsx("div",{className:"space-y-1",children:ve.otherRemote.map(U=>s.jsx("button",{onClick:()=>{k(h=>({...h,selectedBranch:`remotes/${U}`,worktreeName:As(U)})),de(h=>({...h,touched:!0})),H(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===`remotes/${U}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:U})},`remotes/${U}`))})]})]})]})})]}):s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex flex-col items-start gap-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:a("session.newWorktree.branchName")}),m==="new-branch"&&Te&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>M(!0),className:"gap-1.5 h-7",children:[s.jsx(K,{name:"github",className:"size-4 text-status-success"}),b.linkedIssue||b.linkedPr?a("session.newWorktree.actions.change"):a("session.newWorktree.actions.startFromGitHubIssuePr")]})]}),s.jsx(at,{value:b.branchName,onChange:U=>{g(h=>({...h,branchName:U.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>de(U=>({...U,touched:!0})),placeholder:a("session.newWorktree.branchNamePlaceholder"),disabled:!!b.linkedPr,className:fe("h-8",le.touched&&le.branchError&&"border-destructive",b.linkedPr&&"bg-muted text-muted-foreground")}),b.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(K,{name:"check",className:"h-3.5 w-3.5 text-status-success"}),s.jsx("span",{className:"typography-micro",children:a("session.newWorktree.usingPrBranch",{branch:b.linkedPr.head})})]}),b.linkedIssue&&!b.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(K,{name:"check",className:"h-3.5 w-3.5 text-status-success"}),s.jsx("span",{className:"typography-micro",children:a("session.newWorktree.fromIssue",{number:b.linkedIssue.number,title:b.linkedIssue.title})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"typography-ui-label text-foreground font-semibold",children:a("session.newWorktree.worktreeDirectory")}),m!=="existing-branch"&&s.jsxs("button",{onClick:()=>{const U=As(m==="new-branch"?b.branchName:"");g(h=>({...h,worktreeName:U,isSyncingWorktreeName:!0}))},disabled:!b.branchName||b.worktreeName===As(b.branchName),className:fe("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",b.worktreeName===As(b.branchName)||!b.branchName?"text-muted-foreground/40 cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-muted"),title:a("session.newWorktree.resetToMatchBranchName"),children:[s.jsx(K,{name:"refresh",className:"h-3 w-3"}),s.jsx("span",{children:a("session.newWorktree.actions.reset")})]})]}),s.jsx(at,{value:We.worktreeName,onChange:U=>{m==="new-branch"?g(h=>({...h,worktreeName:U.target.value,isSyncingWorktreeName:!1})):k(h=>({...h,worktreeName:U.target.value}))},onBlur:()=>de(U=>({...U,touched:!0})),placeholder:a("session.newWorktree.worktreeDirectoryPlaceholder"),className:fe("h-8",le.touched&&le.worktreeError&&"border-destructive")})]}),m==="new-branch"&&!b.linkedPr&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:a("session.newWorktree.sourceBranch")}),s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>Y(!0),className:"w-full justify-between h-9",children:[s.jsx("span",{className:b.sourceBranch?"text-foreground":"text-muted-foreground",children:b.sourceBranch||a("session.newWorktree.selectSourceBranchPlaceholder")}),s.jsx(K,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"})]}),b.sourceBranch&&s.jsx("div",{className:"typography-micro text-muted-foreground",children:a("session.newWorktree.newBranchFromSource",{source:b.sourceBranch})}),s.jsx(mi,{open:Z,title:a("session.newWorktree.selectSourceBranch"),onClose:()=>Y(!1),children:s.jsxs("div",{className:"space-y-4",ref:V,children:[s.jsx(at,{value:te,onChange:U=>T(U.target.value),placeholder:a("session.newWorktree.searchBranches"),className:"h-8"}),C?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):j.length===0&&N.length===0?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noBranchesFound")}):s.jsxs("div",{className:"space-y-4",children:[Ie&&ce&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:a("session.newWorktree.matchingBranches")}),s.jsx("div",{className:"space-y-1",children:me.matching.map(U=>s.jsx("button",{onClick:()=>{g(h=>({...h,sourceBranch:U.value})),Y(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",b.sourceBranch===U.value?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:U.label})},`${U.source}-${U.value}`))})]}),Ie&&!ce&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),me.otherLocal.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:a(Ie?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches")}),s.jsx("div",{className:"space-y-1",children:me.otherLocal.map(U=>s.jsx("button",{onClick:()=>{g(h=>({...h,sourceBranch:U})),Y(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",b.sourceBranch===U?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:U})},U))})]}),me.otherRemote.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"typography-small font-semibold text-foreground px-2",children:a(Ie?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches")}),s.jsx("div",{className:"space-y-1",children:me.otherRemote.map(U=>s.jsx("button",{onClick:()=>{g(h=>({...h,sourceBranch:`remotes/${U}`})),Y(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",b.sourceBranch===`remotes/${U}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:U})},`remotes/${U}`))})]})]})]})})]}),(b.linkedIssue||b.linkedPr)&&m==="new-branch"&&s.jsxs("div",{className:"mt-2 px-2 py-1.5 rounded bg-muted/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"github",className:"h-3.5 w-3.5 text-status-success shrink-0"}),b.linkedIssue&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.issueNumber",{number:b.linkedIssue.number})}),b.linkedPr&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.prNumber",{number:b.linkedPr.number})}),s.jsx("span",{className:"typography-micro text-foreground truncate flex-1",children:b.linkedIssue?.title||b.linkedPr?.title}),s.jsx("a",{href:b.linkedIssue?.url||b.linkedPr?.url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",onClick:U=>U.stopPropagation(),children:s.jsx(K,{name:"external-link",className:"h-3 w-3"})}),s.jsx("button",{onClick:q,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]}),b.linkedPr&&s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 pl-5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[b.linkedPr.head," → ",b.linkedPr.base]}),b.includePrDiff&&s.jsx("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success",children:a("session.newWorktree.includeDiffBadge")})]})]})]})]}):s.jsx(Kt,{open:t,onOpenChange:e,children:s.jsxs(Bt,{className:"max-w-lg max-h-[80vh] flex flex-col",children:[s.jsx(Ut,{className:"flex flex-row items-center justify-between",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs(_t,{className:"flex items-center gap-2 shrink-0",children:[s.jsx(K,{name:"git-branch",className:"h-5 w-5"}),a("session.newWorktree.title")]}),s.jsx("div",{className:"w-[280px] shrink-0",children:s.jsx(ma,{items:[{id:"new-branch",label:a("session.newWorktree.mode.newBranch"),icon:s.jsx(K,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"existing-branch",label:a("session.newWorktree.mode.existingBranch"),icon:s.jsx(K,{name:"git-repository",className:"h-3.5 w-3.5"})}],activeId:m,onSelect:U=>Oe(U),variant:"active-pill",layoutMode:"fit",className:"w-full"})})]})}),s.jsxs("div",{className:"flex-1 overflow-y-auto mt-2 space-y-6",children:[m==="existing-branch"?s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:a("session.newWorktree.selectBranch")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(fs,{open:S,onOpenChange:F,children:[s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button",className:fe(Ao({size:"default"}),"min-w-[220px] max-w-full"),children:[s.jsx("span",{className:fe("truncate",x.selectedBranch?"text-foreground":"text-muted-foreground"),children:x.selectedBranch||a("session.newWorktree.chooseBranch")}),s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),s.jsx(hs,{align:"start",sideOffset:6,portalToBody:!0,className:"w-[min(42rem,calc(100vw-2rem))] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",ref:I,children:s.jsxs(Mo,{shouldFilter:!1,children:[s.jsx(Lo,{placeholder:a("session.newWorktree.searchBranches"),value:A,onValueChange:X,onKeyDown:Q}),s.jsx(Fo,{disableHorizontal:!0,children:C?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):j.length===0&&N.length===0?s.jsx(Oo,{children:a("session.newWorktree.noBranchesFound")}):s.jsxs(s.Fragment,{children:[ge&&oe&&s.jsx(kn,{heading:a("session.newWorktree.matchingBranches"),children:ve.matching.map(U=>s.jsx(en,{value:U.value,onSelect:()=>{k(h=>({...h,selectedBranch:U.value,worktreeName:As(U.label)})),de(h=>({...h,touched:!0})),F(!1)},children:s.jsx("span",{className:"typography-small break-all",children:U.label})},`${U.source}-${U.value}`))}),ge&&!oe&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),ve.otherLocal.length>0&&s.jsxs(s.Fragment,{children:[ge&&s.jsx(Oa,{}),s.jsx(kn,{heading:a(ge?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches"),children:ve.otherLocal.map(U=>s.jsx(en,{value:U,onSelect:()=>{k(h=>({...h,selectedBranch:U,worktreeName:As(U)})),de(h=>({...h,touched:!0})),F(!1)},children:s.jsx("span",{className:"typography-small break-all",children:U})},`local-${U}`))})]}),ve.otherRemote.length>0&&s.jsxs(s.Fragment,{children:[(ve.otherLocal.length>0||ge)&&s.jsx(Oa,{}),s.jsx(kn,{heading:a(ge?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches"),children:ve.otherRemote.map(U=>s.jsx(en,{value:`remotes/${U}`,onSelect:()=>{k(h=>({...h,selectedBranch:`remotes/${U}`,worktreeName:As(U)})),de(h=>({...h,touched:!0})),F(!1)},children:s.jsx("span",{className:"typography-small break-all",children:U})},`remote-${U}`))})]})]})})]})})]}),s.jsx(ee,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0 shrink-0",onClick:ie,disabled:!pe||C,title:a("session.newWorktree.fetchBranches"),children:C?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"refresh",className:"size-4"})})]})]}):s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:a("session.newWorktree.branchName")}),m==="new-branch"&&Te&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>M(!0),className:"gap-1.5 h-7",children:[s.jsx(K,{name:"github",className:"size-4 text-status-success"}),b.linkedIssue||b.linkedPr?a("session.newWorktree.actions.change"):a("session.newWorktree.actions.startFromGitHubIssuePr")]})]}),s.jsx(at,{value:b.branchName,onChange:U=>{g(h=>({...h,branchName:U.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>de(U=>({...U,touched:!0})),placeholder:a("session.newWorktree.branchNamePlaceholder"),disabled:!!b.linkedPr,className:fe("h-8",le.touched&&le.branchError&&"border-destructive",b.linkedPr&&"bg-muted text-muted-foreground")}),b.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(K,{name:"check",className:"h-3.5 w-3.5 text-status-success"}),s.jsx("span",{className:"typography-micro",children:a("session.newWorktree.usingPrBranch",{branch:b.linkedPr.head})})]}),b.linkedIssue&&!b.linkedPr&&s.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s.jsx(K,{name:"check",className:"h-3.5 w-3.5 text-status-success"}),s.jsx("span",{className:"typography-micro",children:a("session.newWorktree.fromIssue",{number:b.linkedIssue.number,title:b.linkedIssue.title})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"typography-ui-label text-foreground font-semibold",children:a("session.newWorktree.worktreeDirectory")}),m!=="existing-branch"&&s.jsxs("button",{onClick:()=>{const U=As(m==="new-branch"?b.branchName:"");g(h=>({...h,worktreeName:U,isSyncingWorktreeName:!0}))},disabled:!b.branchName||b.worktreeName===As(b.branchName),className:fe("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",b.worktreeName===As(b.branchName)||!b.branchName?"text-muted-foreground/40 cursor-not-allowed":"text-muted-foreground hover:text-foreground hover:bg-muted"),title:a("session.newWorktree.resetToMatchBranchName"),children:[s.jsx(K,{name:"refresh",className:"h-3 w-3"}),s.jsx("span",{children:a("session.newWorktree.actions.reset")})]})]}),s.jsx(at,{value:We.worktreeName,onChange:U=>{m==="new-branch"?g(h=>({...h,worktreeName:U.target.value,isSyncingWorktreeName:!1})):k(h=>({...h,worktreeName:U.target.value}))},onBlur:()=>de(U=>({...U,touched:!0})),placeholder:a("session.newWorktree.worktreeDirectoryPlaceholder"),className:fe("h-8",le.touched&&le.worktreeError&&"border-destructive")})]}),m==="new-branch"&&!b.linkedPr&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground block font-semibold",children:a("session.newWorktree.sourceBranch")}),s.jsxs(fs,{open:E,onOpenChange:D,children:[s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button",className:fe(Ao({size:"default"}),"min-w-[220px] max-w-full"),children:[s.jsx("span",{className:fe("truncate",b.sourceBranch?"text-foreground":"text-muted-foreground"),children:b.sourceBranch||a("session.newWorktree.selectSourceBranchPlaceholder")}),s.jsx(K,{name:"arrow-down-s",className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),s.jsx(hs,{align:"start",portalToBody:!0,className:"w-[min(42rem,calc(100vw-2rem))] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",ref:B,children:s.jsxs(Mo,{shouldFilter:!1,children:[s.jsx(Lo,{placeholder:a("session.newWorktree.searchBranches"),value:te,onValueChange:T,onKeyDown:Q}),s.jsx(Fo,{disableHorizontal:!0,children:C?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):j.length===0&&N.length===0?s.jsx(Oo,{children:a("session.newWorktree.noBranchesFound")}):s.jsxs(s.Fragment,{children:[Ie&&ce&&s.jsx(kn,{heading:a("session.newWorktree.matchingBranches"),children:me.matching.map(U=>s.jsx(en,{value:U.value,onSelect:()=>{g(h=>({...h,sourceBranch:U.value})),D(!1)},children:s.jsx("span",{className:"typography-small break-all",children:U.label})},`${U.source}-${U.value}`))}),Ie&&!ce&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),me.otherLocal.length>0&&s.jsxs(s.Fragment,{children:[Ie&&s.jsx(Oa,{}),s.jsx(kn,{heading:a(Ie?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches"),children:me.otherLocal.map(U=>s.jsx(en,{value:U,onSelect:()=>{g(h=>({...h,sourceBranch:U})),D(!1)},children:s.jsx("span",{className:"typography-small break-all",children:U})},`local-${U}`))})]}),me.otherRemote.length>0&&s.jsxs(s.Fragment,{children:[(me.otherLocal.length>0||Ie)&&s.jsx(Oa,{}),s.jsx(kn,{heading:a(Ie?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches"),children:me.otherRemote.map(U=>s.jsx(en,{value:`remotes/${U}`,onSelect:()=>{g(h=>({...h,sourceBranch:`remotes/${U}`})),D(!1)},children:s.jsx("span",{className:"typography-small break-all",children:U})},`remote-${U}`))})]})]})})]})})]}),b.sourceBranch&&s.jsx("div",{className:"typography-micro text-muted-foreground",children:a("session.newWorktree.newBranchFromSource",{source:b.sourceBranch})})]}),(b.linkedIssue||b.linkedPr)&&m==="new-branch"&&s.jsxs("div",{className:"mt-2 px-2 py-1.5 rounded bg-muted/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(K,{name:"github",className:"h-3.5 w-3.5 text-status-success shrink-0"}),b.linkedIssue&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.issueNumber",{number:b.linkedIssue.number})}),b.linkedPr&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.prNumber",{number:b.linkedPr.number})}),s.jsx("span",{className:"typography-micro text-foreground truncate flex-1",children:b.linkedIssue?.title||b.linkedPr?.title}),s.jsx("a",{href:b.linkedIssue?.url||b.linkedPr?.url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",onClick:U=>U.stopPropagation(),children:s.jsx(K,{name:"external-link",className:"h-3 w-3"})}),s.jsx("button",{onClick:q,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]}),b.linkedPr&&s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 pl-5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[b.linkedPr.head," → ",b.linkedPr.base]}),b.includePrDiff&&s.jsx("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success",children:a("session.newWorktree.includeDiffBadge")})]})]})]}),s.jsxs(rs,{className:"mt-1 flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center gap-1.5 text-destructive",children:le.touched&&(le.branchError||le.worktreeError)&&s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"error-warning",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"typography-micro",children:le.branchError||le.worktreeError})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{variant:"outline",size:"sm",onClick:()=>e(!1),disabled:he,children:a("session.newWorktree.actions.cancel")}),s.jsxs(ee,{size:"sm",onClick:Ke,disabled:!Ye||he,className:"gap-1.5",children:[he&&s.jsx(K,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),a(he?"session.newWorktree.actions.creating":"session.newWorktree.actions.createWorktree")]})]})]})]})}),s.jsx(Ok,{open:O,onOpenChange:M,onSelect:je})]})}const _k=(t,e)=>{if(!t)return e("mcpDropdown.status.unknown");switch(t.status){case"connected":return e("mcpDropdown.status.connected");case"failed":return e("mcpDropdown.status.failed",{error:t.error||e("mcpDropdown.status.unknownError")});case"needs_auth":return e("mcpDropdown.status.needsAuth");case"needs_client_registration":return e("mcpDropdown.status.needsRegistration",{error:t.error||""});default:return t.status}},Uk=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},iS=({active:t,className:e,headerAction:n,listClassName:a,hideHeader:i=!1,mobileListDensity:r=!1})=>{const{t:o}=lt(),c=Cs(j=>j.currentDirectory)??null,p=ws(j=>j.getStatusForDirectory(c)),u=ws(j=>j.refresh),f=ws(j=>j.connect),m=ws(j=>j.disconnect),w=_a(j=>j.mcpServers),b=_a(j=>j.loadMcpConfigs),[g,x]=l.useState(!1),[k,y]=l.useState(null);l.useEffect(()=>{u({directory:c,silent:!0})},[u,c]),l.useEffect(()=>{b({force:!0})},[b]),l.useEffect(()=>{t&&Promise.all([u({directory:c,silent:!0}),b({force:!0})])},[t,u,c,b]);const C=l.useMemo(()=>{const j=new Set(Object.keys(p));for(const N of w)N?.name&&j.add(N.name);return Array.from(j).sort((N,v)=>N.localeCompare(v))},[w,p]),z=l.useCallback(j=>{if(j?.preventDefault(),g)return;x(!0);const N=new Promise(v=>setTimeout(v,500));Promise.all([u({directory:c}),N]).finally(()=>{x(!1)})},[g,u,c]);return s.jsxs("div",{className:fe("w-full",e),children:[i?null: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-2.5",children:[s.jsxs("div",{className:"min-w-0 flex items-baseline gap-2",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:o("mcpDropdown.title")}),c&&s.jsx("div",{className:"truncate typography-micro text-muted-foreground",children:c.split("/").pop()||c})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n,s.jsx("button",{type:"button",className:"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",disabled:g,onClick:z,"aria-label":o("mcpDropdown.actions.refreshAria"),children:s.jsx(K,{name:"refresh",className:fe("h-4 w-4",g&&"animate-spin")})})]})]})}),s.jsx("div",{className:fe("max-h-64 overflow-y-auto",r?"space-y-1 py-3":"px-3 py-2.5",a),children:s.jsxs("div",{className:fe(!r&&C.length>0&&"rounded-xl bg-[var(--surface-muted)] p-1.5"),children:[C.map(j=>{const N=p[j],v=Uk(N),P=N?.status==="connected",$=k===j,O=_k(N,o);return s.jsxs("div",{className:fe("flex items-center justify-between rounded-lg hover:bg-interactive-hover/50",r?"gap-3 px-4 py-3":"gap-2 px-2.5 py-2"),children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx("span",{className:fe("rounded-full flex-shrink-0",r?"h-2.5 w-2.5":"h-2 w-2",v==="success"&&"bg-status-success",v==="error"&&"bg-status-error",v==="warning"&&"bg-status-warning",v==="default"&&"bg-muted-foreground/40"),"aria-label":O})}),s.jsx(ks,{side:"left",children:s.jsx("p",{children:O})})]}),s.jsx("span",{className:fe("truncate",r?"text-[17px] leading-6 font-medium":"typography-ui-label"),children:j})]})}),s.jsx(fr,{checked:P,disabled:$,className:"data-[checked]:bg-status-info",onCheckedChange:async M=>{y(j);try{M?await f(j,c):await m(j,c)}finally{y(null)}}})]},j)}),C.length===0&&s.jsx("div",{className:"px-4 py-5 typography-ui-label text-muted-foreground text-center",children:o("mcpDropdown.empty.configureInConfig")})]})})]})},sl=5,bm=15,Hi=new Map,or=t=>{const e=Math.sqrt(t/100),n=12*e,a=24*e;return Math.ceil(n+a+1)},$k=(t,e)=>{const n=or(e);return Math.max(n*sl,Math.min(n*bm,n*t))},Vk=async(t,e)=>{const n=await ug(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},Hk=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Fd=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],Od=(t,e)=>{const n=t.findIndex(a=>a.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},Wk=t=>{const e=tt.c(20),{id:n,children:a}=t;let i;e[0]!==n?(i={id:n},e[0]=n,e[1]=i):i=e[1];const{attributes:r,listeners:o,setNodeRef:d,setActivatorNodeRef:c,transform:p,transition:u,isDragging:f}=ju(i);let m;e[2]!==p?(m=Nu.Transform.toString(p),e[2]=p,e[3]=m):m=e[3];let w;e[4]!==m||e[5]!==u?(w={transform:m,transition:u},e[4]=m,e[5]=u,e[6]=w):w=e[6];const b=f&&"opacity-60";let g;e[7]!==b?(g=fe(b),e[7]=b,e[8]=g):g=e[8];let x;e[9]!==r||e[10]!==a||e[11]!==f||e[12]!==o||e[13]!==c?(x=a({attributes:r,listeners:o,setActivatorNodeRef:c,isDragging:f}),e[9]=r,e[10]=a,e[11]=f,e[12]=o,e[13]=c,e[14]=x):x=e[14];let k;return e[15]!==d||e[16]!==w||e[17]!==g||e[18]!==x?(k=s.jsx("li",{ref:d,style:w,className:g,children:x}),e[15]=d,e[16]=w,e[17]=g,e[18]=x,e[19]=k):k=e[19],k},Gk=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:a,onOpenPlan:i,className:r})=>{const{t:o}=lt(),[d,c]=l.useState(!1),[p,u]=l.useState(""),[f,m]=l.useState([]),[w,b]=l.useState(""),[g,x]=l.useState(null),[k,y]=l.useState(()=>new Set),[C,z]=l.useState([]),[j,N]=l.useState(null),[v,P]=l.useState(!1),[$,O]=l.useState(0),M=l.useRef(!1),S=l.useRef(""),F=l.useRef(null),E=ke(q=>q.todoPanelHeight),D=ke(q=>q.setTodoPanelHeight),W=ke(q=>q.notesPanelHeight),H=ke(q=>q.setNotesPanelHeight),[Z,Y]=l.useState(!1),A=l.useRef(0),X=l.useRef(E),te=es(q=>q.currentSessionId),T=es(q=>q.createSession),I=es(q=>q.initializeNewOpenChamberSession),B=es(q=>q.sendMessage),L=es(q=>q.setCurrentSession),V=og(q=>q.setPendingInputText),Q=Cs(q=>q.currentDirectory),G=ke(q=>q.openContextPanelTab),ue=ke(q=>q.setActiveMainTab),ne=ke(q=>q.setSessionSwitcherOpen),xe=ke(q=>q.padding),ve=l.useCallback(async(q,re)=>{if(!t)return!1;const U=t.id,ae=(Hi.get(U)??Promise.resolve()).catch(()=>{}).then(()=>lg(t,{notes:q,todos:re}));Hi.set(U,ae);try{const ye=await ae;return ye||J.error(o("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),ye}finally{Hi.get(U)===ae&&Hi.delete(U)}},[t,o]);l.useEffect(()=>{if(!t){u(""),m([]),z([]),b(""),y(new Set);return}let q=!1;return c(!0),(async()=>{try{const re=await cg(t),U=await Promise.all(re.plans.map(h=>Vk(h,o("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if(q)return;u(re.notes),m(Fd(re.todos)),z(U),S.current=re.notes,M.current=!0,b(""),y(new Set)}catch{q||(J.error(o("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),u(""),m([]),z([]),S.current="",M.current=!0)}finally{q||c(!1)}})(),()=>{q=!0}},[$,t,o]),l.useEffect(()=>{if(!t)return;const q=re=>{const U=re.detail;U?.projectId&&U.projectId!==t.id||O(h=>h+1)};return window.addEventListener("openchamber:project-plan-saved",q),window.addEventListener("openchamber:project-notes-updated",q),()=>{window.removeEventListener("openchamber:project-plan-saved",q),window.removeEventListener("openchamber:project-notes-updated",q)}},[t]),l.useEffect(()=>{if(f.length<7)return;const q=$k(f.length,xe),re=or(xe)*sl;E!==q&&(E<re||E>q)&&D(q)},[f.length,xe,E,D]),l.useEffect(()=>{if(!Z)return;const q=U=>{const h=U.clientY-A.current,ae=Math.min(or(xe)*bm,Math.max(or(xe)*sl,X.current+h));D(ae)},re=()=>{Y(!1)};return window.addEventListener("pointermove",q),window.addEventListener("pointerup",re,{once:!0}),window.addEventListener("pointercancel",re,{once:!0}),()=>{window.removeEventListener("pointermove",q),window.removeEventListener("pointerup",re),window.removeEventListener("pointercancel",re)}},[Z,xe,D]);const me=l.useCallback(q=>{Y(!0),A.current=q.clientY,X.current=E,q.preventDefault()},[E]),ge=l.useCallback(()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),Ie=l.useCallback(()=>{ge(),S.current=p,ve(p,f)},[ge,p,ve,f]);l.useEffect(()=>{if(!(!t||!M.current)&&p!==S.current)return F.current=window.setTimeout(()=>{F.current=null,S.current=p,ve(p,f)},400),()=>{ge()}},[ge,p,ve,t,f]),l.useEffect(()=>()=>ge(),[ge]);const oe=l.useCallback(()=>{const q=w.trim();if(!q)return;const re=Od(f,{id:Hk(),text:q.slice(0,Ei),completed:!1,createdAt:Date.now()});m(re),b(""),ve(p,re)},[w,p,ve,f]),ce=l.useCallback(q=>{y(re=>{const U=new Set(re);return U.has(q)?U.delete(q):U.add(q),U})},[]),pe=l.useCallback((q,re)=>{const U=f.find(be=>be.id===q);if(!U||U.completed===re)return;const h=f.filter(be=>be.id!==q),ae={...U,completed:re},ye=re?[...h,ae]:Od(h,ae);m(ye),ve(p,ye)},[p,ve,f]),ie=l.useCallback(q=>{const re=f.filter(U=>U.id!==q);m(re),ve(p,re)},[p,ve,f]),le=l.useCallback(()=>{const q=f.filter(re=>!re.completed);q.length!==f.length&&(m(q),ve(p,q))},[p,ve,f]),de=l.useCallback(q=>{const{active:re,over:U}=q;if(!U||re.id===U.id)return;const h=f.findIndex(be=>be.id===re.id),ae=f.findIndex(be=>be.id===U.id);if(h===-1||ae===-1)return;const ye=Fd($f(f,h,ae));m(ye),ve(p,ye)},[p,ve,f]),he=xu(bu(yu,{activationConstraint:{distance:8}})),Me=w.slice(0,Ei),Le=f.reduce((q,re)=>q+(re.completed?1:0),0),Be=l.useCallback(()=>{ue("chat"),ne(!1)},[ue,ne]),Fe=l.useCallback((q,re)=>{!t||g||N({kind:"session",todoId:q,todoText:re})},[t,g]),De=l.useCallback(q=>{if(!te){J.error(o("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}Be();const re=`\`\`\`md
37
- ${q}
38
- \`\`\``;V(re,"append"),J.success(o("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),a?.()},[te,a,Be,V,o]),ze=l.useCallback((q,re)=>{if(!(!t||g)){if(!n){J.error(o("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}N({kind:"worktree",todoId:q,todoText:re})}},[n,t,g,o]),Ve=l.useCallback(async q=>{if(!t||!j)return;const re=await Un("plan.todo.visible",{todo_text:j.todoText}),h=[{synthetic:!0,text:await Un("plan.todo.instructions",{todo_text:j.todoText})}];P(!0),x(j.todoId);try{Be();let ae=null,ye=t.path;if(j.kind==="worktree"){if(!n){J.error(o("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const Ee=await Qd(t.path,Xd());if(!Ee?.id)return;ae=Ee.id,ye=Ee.path}else{const Ee=await T(void 0,t.path,null);if(!Ee?.id){J.error(o("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}ae=Ee.id,ye=Ee.directory??t.path,I(Ee.id,pt.getState().agents??[])}if(!ae)return;const be=ol.getState();be.saveSessionModelSelection(ae,q.providerID,q.modelID),q.agent.trim()&&(be.saveSessionAgentSelection(ae,q.agent),be.saveAgentModelForSession(ae,q.agent,q.providerID,q.modelID),be.saveAgentModelVariantForSession(ae,q.agent,q.providerID,q.modelID,q.variant||void 0)),L(ae,ye),await B(re,q.providerID,q.modelID,q.agent.trim()||void 0,void 0,void 0,h,q.variant||void 0),J.success(j.kind==="worktree"?o("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):o("rightSidebar.contextNotesTodo.toast.sentToNewSession")),N(null),a?.()}catch(ae){const ye=ae instanceof Error?ae.message:void 0;J.error(o("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),ye?{description:ye}:void 0)}finally{P(!1),x(null)}},[n,T,I,a,j,t,Be,B,L,o]),We=l.useRef(null),[_e,He]=l.useState(!1),[Ke,Oe]=l.useState(null),je=l.useCallback(async q=>{if(!(!t||Ke)){Oe(q);try{if(!await dg(t,q)){J.error(o("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}z(U=>U.filter(h=>h.id!==q)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{Oe(null)}}},[Ke,t,o]),Te=l.useCallback(async()=>{if(!t||_e)return;const q=await dl({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(q.success&&q.path){He(!0);try{const re=new URLSearchParams({path:q.path,allowOutsideWorkspace:"true"});q.outsideFileGrant&&re.set("outsideFileGrant",q.outsideFileGrant);const U=await ht(`/api/fs/read?${re.toString()}`,{cache:"no-store"});if(!U.ok){J.error(o("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const h=await U.text();if(!h.trim()){J.error(o("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const ae=q.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Ll(t,h,ae)){J.error(o("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),J.success(o("rightSidebar.contextNotesTodo.toast.planImported"))}catch(re){const U=re instanceof Error?re.message:void 0;J.error(o("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),U?{description:U}:void 0)}finally{He(!1)}}else q.error==="Native file picker not available"&&We.current?.click()},[_e,t,o]),Ue=l.useCallback(async q=>{if(!(!t||!q)){He(!0);try{const re=await q.text();if(!re.trim()){J.error(o("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const U=q.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Ll(t,re,U)){J.error(o("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),J.success(o("rightSidebar.contextNotesTodo.toast.planImported"))}catch(re){const U=re instanceof Error?re.message:void 0;J.error(o("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),U?{description:U}:void 0)}finally{He(!1)}}},[t,o]),Ye=l.useCallback(q=>{if(i){i({path:q.path,title:q.title});return}const re=t?.path?.trim(),U=Q?.trim()||re;U&&G(U,{mode:"plan",targetPath:q.path,dedupeKey:q.path,label:q.title})},[Q,i,G,t]);return t?s.jsxs("div",{className:fe("w-full min-w-0 space-y-3 p-3",r),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:o("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:[p.length,"/",Fl]})]}),s.jsx(Ns,{value:p,onChange:q=>u(q.target.value.slice(0,Fl)),onBlur:Ie,placeholder:o("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:W,onResizeHeightChange:H,useScrollShadow:!0,scrollShadowSize:56,disabled:d})]}),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:o("rightSidebar.contextNotesTodo.todo.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:f.length===1?o("rightSidebar.contextNotesTodo.todo.itemsSingle",{count:f.length}):o("rightSidebar.contextNotesTodo.todo.itemsPlural",{count:f.length})}),s.jsx("button",{type:"button",onClick:le,disabled:d||Le===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:o("rightSidebar.contextNotesTodo.todo.clearCompleted")})]}),s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[Me.length,"/",Ei]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(at,{value:Me,onChange:q=>b(q.target.value.slice(0,Ei)),onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),oe())},placeholder:o("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:d,className:"h-8"}),s.jsx("button",{type:"button",onClick:oe,disabled:d||Me.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":o("rightSidebar.contextNotesTodo.todo.addAria"),title:o("rightSidebar.contextNotesTodo.todo.addAria"),children:s.jsx(K,{name:"add",className:"h-4 w-4"})})]}),s.jsx("div",{className:fe("overflow-y-auto rounded-lg border border-border/60 bg-background/40",Z&&"transition-none"),style:f.length<7?void 0:{height:`${E}px`,maxHeight:`${E}px`},children:f.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:o("rightSidebar.contextNotesTodo.todo.empty")}):s.jsx(vu,{sensors:he,collisionDetection:wu,onDragEnd:de,children:s.jsx(ku,{items:f.map(q=>q.id),strategy:Vf,children:s.jsx("ul",{className:"divide-y divide-border/50",children:f.map(q=>{const re=k.has(q.id);return s.jsx(Wk,{id:q.id,children:U=>s.jsxs("div",{className:fe("flex gap-1.5 px-2.5 py-1.5",re?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:U.setActivatorNodeRef,...U.attributes,...U.listeners,onClick:h=>{h.preventDefault(),h.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":o("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:q.text}),title:o("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:q.text}),children:s.jsx(K,{name:"draggable",className:"h-3.5 w-3.5"})}),s.jsx("div",{className:"flex h-6 items-center",children:s.jsx(an,{checked:q.completed,onChange:h=>pe(q.id,h),ariaLabel:o("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:q.text})})}),s.jsx("button",{type:"button",onClick:()=>ce(q.id),className:fe("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",re?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",q.completed&&"text-muted-foreground line-through"),title:re?void 0:q.text,"aria-label":re?o("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:q.text}):o("rightSidebar.contextNotesTodo.todo.actions.expand",{text:q.text}),children:q.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>ie(q.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":o("rightSidebar.contextNotesTodo.todo.actions.delete",{text:q.text}),title:o("rightSidebar.contextNotesTodo.todo.actions.delete",{text:q.text}),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(fs,{children:[s.jsx(gs,{asChild:!0,children:s.jsx("button",{type:"button",disabled:g===q.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":o("rightSidebar.contextNotesTodo.todo.actions.send",{text:q.text}),title:o("rightSidebar.contextNotesTodo.todo.actions.send",{text:q.text}),children:s.jsx(K,{name:"send-plane",className:"h-3.5 w-3.5"})})}),s.jsxs(hs,{align:"end",className:"w-56",children:[s.jsx(as,{onClick:()=>De(q.text),children:o("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(as,{onClick:()=>Fe(q.id,q.text),children:o("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(as,{onClick:()=>{ze(q.id,q.text)},disabled:!n,children:o("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},q.id)})})})})}),f.length>=7&&s.jsx("div",{className:fe("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",Z&&"bg-[var(--interactive-border)]"),onPointerDown:me,role:"separator","aria-orientation":"horizontal","aria-label":o("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:o("rightSidebar.contextNotesTodo.plans.title")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:C.length===1?o("rightSidebar.contextNotesTodo.plans.filesSingle",{count:C.length}):o("rightSidebar.contextNotesTodo.plans.filesPlural",{count:C.length})})]}),s.jsx("input",{ref:We,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:q=>{const re=q.target.files?.[0]??null;Ue(re),q.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:Te,disabled:!t||_e,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":o("rightSidebar.contextNotesTodo.plans.importFromFile"),title:o("rightSidebar.contextNotesTodo.plans.importFromFile"),children:s.jsx(K,{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:o("rightSidebar.contextNotesTodo.plans.empty")}):s.jsx("ul",{className:"divide-y divide-border/50",children:C.map(q=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>Ye(q),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:q.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(q.createdAt).toLocaleDateString(jr())})]}),s.jsx("button",{type:"button",onClick:()=>{je(q.id)},disabled:Ke===q.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:o("rightSidebar.contextNotesTodo.plans.deletePlan"),"aria-label":o("rightSidebar.contextNotesTodo.plans.deletePlanWithTitle",{title:q.title}),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},q.id))})})]}),s.jsx(Ru,{open:j!==null,onOpenChange:q=>{!q&&!v&&N(null)},target:j?.kind??"session",projectDirectory:t?.path??null,submitting:v,onConfirm:Ve})]}):s.jsx("div",{className:fe("w-full min-w-0 p-3",r),children:s.jsx("p",{className:"typography-meta text-muted-foreground",children:o("rightSidebar.contextNotesTodo.empty.selectProject")})})},rS=t=>{const e=tt.c(19),{onActionComplete:n,onOpenPlan:a}=t,i=is(qk),r=is(Jk),o=Cs(Yk),d=Nr(Qk);let c;e:{if(i){let k;e[0]!==i||e[1]!==r?(k=r.find(y=>y.id===i)??r[0]??null,e[0]=i,e[1]=r,e[2]=k):k=e[2],c=k;break e}c=r[0]??null}const p=c;let u;e:{if(!p){u=null;break e}let k;e[3]!==p.id||e[4]!==p.path?(k={id:p.id,path:p.path},e[3]=p.id,e[4]=p.path,e[5]=k):k=e[5],u=k}const f=u;let m;e:{if(!p){m=null;break e}let k;e[6]!==p.label||e[7]!==p.path||e[8]!==o?(k=p.label?.trim()||mg(p.path,o)||p.path,e[6]=p.label,e[7]=p.path,e[8]=o,e[9]=k):k=e[9],m=k}const w=m;let b;e:{if(!p){b=!1;break e}let k;e[10]!==p.path||e[11]!==d?(k=d.get(p.path)?.isGitRepo,e[10]=p.path,e[11]=d,e[12]=k):k=e[12],b=k===!0}const g=b;let x;return e[13]!==g||e[14]!==n||e[15]!==a||e[16]!==w||e[17]!==f?(x=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(Gk,{projectRef:f,projectLabel:w,canCreateWorktree:g,onActionComplete:n,onOpenPlan:a})}),e[13]=g,e[14]=n,e[15]=a,e[16]=w,e[17]=f,e[18]=x):x=e[18],x};function qk(t){return t.activeProjectId}function Jk(t){return t.projects}function Yk(t){return t.homeDirectory}function Qk(t){return t.directories}const lr=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),nl=512*1024,Xk=new TextEncoder,Zk=new TextDecoder,bo=t=>{const e=Xk.encode(t);if(e.byteLength<=nl)return{text:t,byteLength:e.byteLength};let n=e.byteLength-nl;for(;n<e.byteLength&&(e[n]&192)===128;)n+=1;const a=e.subarray(n);return{text:Zk.decode(a),byteLength:a.byteLength}},Ta=(t,e)=>`${t}\0${e}`,yo=(t,e)=>{let n=null;for(const a of t.keys())e(a)&&(n??=new Map(t),n.delete(a));return n},e0="terminal-store";let zd=!1,Kd=0;const Wi=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Kd+=1,`tab-${Date.now().toString(36)}-${Kd.toString(36)}`),vo=t=>typeof t=="object"&&t!==null,t0=t=>{const e=/^tab-(\d+)$/.exec(t);if(!e)return null;const n=Number(e[1]);return Number.isFinite(n)?n:null};function Es(t){let e=t.trim();for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e}const wo=(t,e)=>({id:t,terminalSessionId:null,lifecycle:"idle",label:e,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),jo=t=>({tabs:[t],activeTabId:t.id}),Xs=(t,e)=>t.tabs.findIndex(n=>n.id===e);let ko=null,No=null;const s0=t=>{if(No&&ko?.sessions===t.sessions&&ko.nextTabId===t.nextTabId)return No;const e={sessions:Array.from(t.sessions.entries()).map(([n,a])=>[n,{activeTabId:a.activeTabId,tabs:a.tabs.map(i=>({id:i.id,label:i.label,iconKey:i.iconKey,createdAt:i.createdAt}))}]),nextTabId:t.nextTabId};return ko={sessions:t.sessions,nextTabId:t.nextTabId},No=e,e},n0=()=>{const t=df(()=>tf());if(!t)return;let e=null;return{getItem:n=>t.getItem(n),setItem:(n,a)=>{if(a.state!==e)return e=a.state,t.setItem(n,a)},removeItem:n=>(e=null,t.removeItem(n))}},ss=gn()(qa(bi((t,e)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const a=Es(n);a&&t(i=>{if(i.sessions.has(a))return i;const r=new Map(i.sessions),o=Wi(),d=wo(o,"Terminal");return r.set(a,jo(d)),{sessions:r,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const a=Es(n);return e().sessions.get(a)},getActiveTab:n=>{const a=Es(n),i=e().sessions.get(a);if(!i)return;const r=i.activeTabId;return r?i.tabs.find(o=>o.id===r)??i.tabs[0]:i.tabs[0]},getBuffer:(n,a)=>e().buffers.get(Ta(Es(n),a))??lr,createTab:n=>{const a=Es(n);if(!a)return"tab-invalid";const i=Wi();return t(r=>{const o=new Map(r.sessions),d=o.get(a),c=r.nextTabId+1,u=`Terminal ${(d?.tabs.length??0)+1}`,f=wo(i,u);return d?o.set(a,{...d,tabs:[...d.tabs,f]}):o.set(a,jo(f)),{sessions:o,nextTabId:c}}),i},setActiveTab:(n,a)=>{const i=Es(n);t(r=>{const o=new Map(r.sessions),d=o.get(i);return!d||d.activeTabId===a||Xs(d,a)<0?r:(o.set(i,{...d,activeTabId:a}),{sessions:o})})},setTabLabel:(n,a,i)=>{const r=Es(n),o=i.trim();o&&t(d=>{const c=new Map(d.sessions),p=c.get(r);if(!p)return d;const u=Xs(p,a);if(u<0||p.tabs[u]?.label===o)return d;const f=[...p.tabs];return f[u]={...f[u],label:o},c.set(r,{...p,tabs:f}),{sessions:c}})},setTabIconKey:(n,a,i)=>{const r=Es(n);t(o=>{const d=new Map(o.sessions),c=d.get(r);if(!c)return o;const p=Xs(c,a);if(p<0)return o;const u=i?.trim()||null;if(c.tabs[p]?.iconKey===u)return o;const f=[...c.tabs];return f[p]={...f[p],iconKey:u},d.set(r,{...c,tabs:f}),{sessions:d}})},closeTab:(n,a)=>{const i=Es(n);t(r=>{const o=new Map(r.sessions),d=o.get(i);if(!d)return r;const c=Xs(d,a);if(c<0)return r;const p=d.tabs.filter(g=>g.id!==a),u=Object.fromEntries(Object.entries(r.projectActionRuns).filter(([,g])=>!(g.directory===i&&g.tabId===a))),f=Object.keys(u).length!==Object.keys(r.projectActionRuns).length,m=Ta(i,a),w=r.buffers.has(m)?yo(r.buffers,g=>g===m):null;if(p.length===0){const g=Wi(),x=wo(g,"Terminal");return o.set(i,jo(x)),{sessions:o,nextTabId:r.nextTabId+1,...w?{buffers:w}:{},...f?{projectActionRuns:u}:{}}}let b=d.activeTabId;return d.activeTabId===a&&(b=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),o.set(i,{...d,tabs:p,activeTabId:b}),{sessions:o,...w?{buffers:w}:{},...f?{projectActionRuns:u}:{}}})},setTabSessionId:(n,a,i)=>{const r=Es(n);t(o=>{const d=new Map(o.sessions),c=d.get(r);if(!c)return o;const p=Xs(c,a);if(p<0)return o;const u=c.tabs[p],f=i!==null&&u.terminalSessionId!==i,m=i?"running":u.terminalSessionId?"exited":u.lifecycle,w={...u,terminalSessionId:i,lifecycle:m,isConnecting:!1},b=Ta(r,a),g=f&&o.buffers.has(b)?yo(o.buffers,k=>k===b):null,x=[...c.tabs];return x[p]=w,d.set(r,{...c,tabs:x}),{sessions:d,...g?{buffers:g}:{}}})},setTabLifecycle:(n,a,i)=>{const r=Es(n);t(o=>{const d=new Map(o.sessions),c=d.get(r);if(!c)return o;const p=Xs(c,a);if(p<0)return o;const u=[...c.tabs];return u[p]={...u[p],lifecycle:i,isConnecting:!1},d.set(r,{...c,tabs:u}),{sessions:d}})},setConnecting:(n,a,i)=>{const r=Es(n);t(o=>{const d=new Map(o.sessions),c=d.get(r);if(!c)return o;const p=Xs(c,a);if(p<0)return o;const u=[...c.tabs];return u[p]={...u[p],isConnecting:i},d.set(r,{...c,tabs:u}),{sessions:d}})},replaceBuffer:(n,a,i,r)=>{const o=Es(n);t(d=>{const c=d.sessions.get(o);if(!c||Xs(c,a)<0)return d;const p=Ta(o,a),u=d.buffers.get(p)??lr;if(u.lastSequence>r)return d;const f=bo(i);if(u.lastSequence===r&&u.byteLength===f.byteLength&&u.chunks.map(b=>b.data).join("")===f.text)return d;const m=d.nextChunkId,w=new Map(d.buffers);return w.set(p,{chunks:f.text?[{id:m,data:f.text,byteLength:f.byteLength}]:[],byteLength:f.byteLength,lastSequence:r}),{buffers:w,nextChunkId:f.text?m+1:m}})},appendToBuffer:(n,a,i,r,o)=>{if(!i)return;const d=Es(n);t(c=>{const p=c.sessions.get(d);if(!p||Xs(p,a)<0)return c;const u=Ta(d,a),f=c.buffers.get(u)??lr;if(r!==void 0&&r<=f.lastSequence)return c;const m=c.nextChunkId,w=bo(i),b=o!==void 0&&o!==i?bo(o).text:void 0,g={id:m,data:w.text,...b!==void 0?{replayData:b}:{},byteLength:w.byteLength},x=[...f.chunks,g];let k=f.byteLength+g.byteLength;for(;k>nl&&x.length>1;){const C=x.shift();if(!C)break;k-=C.byteLength}const y=new Map(c.buffers);return y.set(u,{chunks:x,byteLength:k,lastSequence:r??f.lastSequence}),{buffers:y,nextChunkId:m+1}})},setTabPreviewUrl:(n,a,i,r={})=>{const o=Es(n);t(d=>{const c=new Map(d.sessions),p=c.get(o);if(!p)return d;const u=Xs(p,a);if(u<0)return d;const f=p.tabs[u],m=r.autoOpened??f.previewAutoOpened,w=r.locked??f.previewUrlLocked;if(f.previewUrl===i&&f.previewAutoOpened===m&&f.previewUrlLocked===w)return d;const b=[...p.tabs];return b[u]={...f,previewUrl:i,previewAutoOpened:m,previewUrlLocked:w},c.set(o,{...p,tabs:b}),{sessions:c}})},markPreviewAutoOpened:(n,a)=>{const i=Es(n);t(r=>{const o=new Map(r.sessions),d=o.get(i);if(!d)return r;const c=Xs(d,a);if(c<0)return r;const p=d.tabs[c];if(!p.previewUrl||p.previewAutoOpened)return r;const u=[...d.tabs];return u[c]={...p,previewAutoOpened:!0},o.set(i,{...d,tabs:u}),{sessions:o}})},setProjectActionRun:n=>{t(a=>{const i=a.projectActionRuns[n.key];return i&&i.directory===n.directory&&i.actionId===n.actionId&&i.tabId===n.tabId&&i.sessionId===n.sessionId&&i.status===n.status?a:{projectActionRuns:{...a.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,a)=>{t(i=>{const r=i.projectActionRuns[n];return!r||r.status===a?i:{projectActionRuns:{...i.projectActionRuns,[n]:{...r,status:a}}}})},removeProjectActionRun:n=>{t(a=>{if(!a.projectActionRuns[n])return a;const i={...a.projectActionRuns};return delete i[n],{projectActionRuns:i}})},removeDirectory:n=>{const a=Es(n);t(i=>{const r=new Map(i.sessions);r.delete(a);const o=Ta(a,""),d=yo(i.buffers,p=>p.startsWith(o)),c=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,p])=>p.directory!==a));return{sessions:r,...d?{buffers:d}:{},projectActionRuns:c}})},clearAll:()=>{t({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:e0,storage:n0(),partialize:s0,merge:(t,e)=>{if(!vo(t))return e;const n=Array.isArray(t.sessions)?t.sessions:[],a=new Map;let i=0;for(const d of n){if(!Array.isArray(d)||d.length!==2)continue;const[c,p]=d;if(typeof c!="string"||!vo(p))continue;const u=Array.isArray(p.tabs)?p.tabs:[],f=[],m=new Map;for(const x of u){if(!vo(x))continue;const k=typeof x.id=="string"?x.id:null;if(!k)continue;const y=t0(k);y!==null&&(i=Math.max(i,y));const C=y===null?k:Wi();m.set(k,C),f.push({id:C,label:typeof x.label=="string"?x.label:"Terminal",iconKey:typeof x.iconKey=="string"?x.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof x.createdAt=="number"?x.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(f.length===0)continue;const w=typeof p.activeTabId=="string"?p.activeTabId:null,b=w?m.get(w)??w:null,g=b?f.some(x=>x.id===b):!1;a.set(c,{tabs:f,activeTabId:g?b:f[0].id})}const r=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,o=Math.max(e.nextTabId,r,i+1);return{...e,sessions:a,buffers:new Map,nextChunkId:1,nextTabId:o,hasHydrated:!0}}})));if(typeof window<"u"&&!zd){zd=!0;const t=ss.persist,e=()=>{ss.getState().hasHydrated||ss.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}function a0(t){const{colors:e}=t,n=e.syntax.base;return{background:e.surface.background,foreground:n.foreground,cursor:e.interactive.cursor,cursorAccent:e.surface.background,selectionBackground:e.interactive.selection,selectionForeground:e.interactive.selectionForeground,selectionInactiveBackground:e.interactive.selection+"50",black:e.surface.muted,red:e.status.error,green:e.status.success,yellow:e.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:e.status.error,brightGreen:e.status.success,brightYellow:e.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:e.surface.elevatedForeground}}function i0(t,e,n,a,i=!1){const o=`${t}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",fontSize:e,fontFamily:o,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:a,disableStdin:i}}const So=["\x1B[0m","\x1B[m"],r0=t=>{const e=t.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(e)?.[1];if(n){const r=n.length<=4?n.slice(0,3).split("").map(o=>o+o).join(""):n.slice(0,6);return[Number.parseInt(r.slice(0,2),16),Number.parseInt(r.slice(2,4),16),Number.parseInt(r.slice(4,6),16)]}const a=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(e);if(!a)return null;const i=a.slice(1,4).map(Number);return i.some(r=>r<0||r>255)?null:i},Bd=t=>{const e=r0(t);return e?`\x1B[0;48;2;${e[0]};${e[1]};${e[2]}m`:null},o0=(t,e,n)=>{const a=e+t;if(!n)return{data:a,carry:""};let i=0;const r=Math.max(...So.map(c=>c.length))-1;for(let c=1;c<=Math.min(r,a.length);c+=1){const p=a.slice(-c);So.some(u=>u.length>p.length&&u.startsWith(p))&&(i=c)}const o=i>0?a.slice(-i):"";let d=i>0?a.slice(0,-i):a;for(const c of So)d=d.replaceAll(c,n);return{data:d,carry:o}},l0=(t,e,n,a,i)=>{if(n.width<=0||n.height<=0||a<=0||i<=0)return null;const r=Math.floor((t-n.left)/n.width*a),o=Math.floor((e-n.top)/n.height*i);return{column:Math.max(0,Math.min(a-1,r)),row:Math.max(0,Math.min(i-1,o))}},c0=(t,e)=>{const n=Math.max(0,Math.min(t.length-1,e)),a=o=>!!(o&&!/^\s+$/u.test(o));if(!a(t[n]))return{startColumn:n,endColumn:n};let i=n,r=n;for(;i>0&&a(t[i-1]);)i-=1;for(;r<t.length-1&&a(t[r+1]);)r+=1;return{startColumn:i,endColumn:r}};let d0=null;const u0=()=>d0??=Gf.load(),m0=(t,e,n)=>{if(typeof window>"u"||typeof document>"u")return null;const a=document.createElement("canvas").getContext("2d");if(!a||t.clientWidth<24||t.clientHeight<24)return null;a.font=`${n}px ${e}`;const i=a.measureText("M"),r=Math.ceil(i.width),o=Math.ceil((i.actualBoundingBoxAscent||n*.8)+(i.actualBoundingBoxDescent||n*.2))+2;if(r<1||o<1)return null;const d=window.getComputedStyle(t),c=(Number.parseInt(d.paddingLeft,10)||0)+(Number.parseInt(d.paddingRight,10)||0),p=(Number.parseInt(d.paddingTop,10)||0)+(Number.parseInt(d.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((t.clientWidth-c-15)/r)),rows:Math.max(1,Math.floor((t.clientHeight-p)/o))}},ym=l.forwardRef(({sessionKey:t,chunks:e,onInput:n,onResize:a,theme:i,fontFamily:r,fontSize:o,className:d,enableTouchScroll:c=!1,autoFocus:p=!0,isVisible:u=!0},f)=>{const m=l.useRef(null),w=l.useRef(null),b=l.useRef(null),g=l.useRef(n),x=l.useRef(a),k=l.useRef(null),y=l.useRef(null),C=l.useRef(null),z=l.useRef(""),j=l.useRef(""),N=l.useRef(Bd(i.background)),v=l.useRef(!1),P=l.useRef(0),$=l.useRef(u),O=l.useRef(!1),[M,S]=l.useState(0),[F,E]=l.useState(0);g.current=n,x.current=a,$.current=u,N.current=Bd(i.background),l.useLayoutEffect(()=>{const Z=m.current;if(!Z)return;const Y=m0(Z,r,o);y.current=Y,Y&&x.current(Y.cols,Y.rows)},[r,o]);const D=l.useCallback(()=>{const Z=m.current,Y=w.current;if(!Z||!Y||!b.current||!$.current)return;const A=Z.getBoundingClientRect();if(!(A.width<24||A.height<24))try{b.current.fit();const X={cols:Y.cols,rows:Y.rows};(!k.current||k.current.cols!==X.cols||k.current.rows!==X.rows)&&(k.current=X,x.current(X.cols,X.rows)),O.current||(O.current=!0,S(te=>te+1))}catch{}},[]),W=l.useCallback(()=>{if(v.current||!z.current||!w.current)return;const Z=w.current,Y=z.current;z.current="";const A=o0(Y,j.current,N.current);if(j.current=A.carry,!A.data){z.current&&W();return}v.current=!0;const X=P.current;Z.write(A.data,()=>{w.current!==Z||P.current!==X||(v.current=!1,z.current&&W())})},[]),H=l.useCallback(()=>{C.current=null,z.current="",j.current="",v.current=!1,P.current+=1;const Z=w.current;if(!Z){E(Y=>Y+1);return}try{Z.reset();const Y=N.current;Y&&Z.write(`${Y}\x1B[2J\x1B[H`)}catch{E(Y=>Y+1)}},[]);return l.useEffect(()=>{const Z=m.current;if(!Z)return;let Y=!1,A=null,X=null,te=null,T=null,I=[];const B=()=>{A&&$.current&&(A.options.cursorBlink=!0)},L=G=>{G.relatedTarget instanceof Node&&Z.contains(G.relatedTarget)||A&&(A.options.cursorBlink=!1)},V=()=>{A&&$.current&&Z.contains(document.activeElement)&&(A.options.cursorBlink=!0)},Q=()=>{A&&(A.options.cursorBlink=!1)};return Z.addEventListener("focusin",B),Z.addEventListener("focusout",L),window.addEventListener("focus",V),window.addEventListener("blur",Q),u0().then(G=>{if(Y)return;A=new Hf({...i0(r,o,i,G,!1),...y.current??{}});const ue=new Wf;A.loadAddon(ue),A.open(Z),w.current=A,b.current=ue,I=[A.onData(xe=>g.current(xe))],X=new ResizeObserver(()=>{te&&clearTimeout(te),te=setTimeout(D,80)}),X.observe(Z),D();const ne=N.current;ne&&A.write(`${ne}\x1B[2J\x1B[H`),T=requestAnimationFrame(D)}),()=>{Y=!0;const G=document.activeElement;G instanceof HTMLElement&&Z.contains(G)&&(G.blur(),window.Capacitor?.getPlatform?.()==="android"&&Zl(async()=>{const{Keyboard:ne}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ne}},__vite__mapDeps([0,1])).then(({Keyboard:ne})=>ne.hide()).catch(()=>{})),X?.disconnect(),te&&clearTimeout(te),T!==null&&cancelAnimationFrame(T),Z.removeEventListener("focusin",B),Z.removeEventListener("focusout",L),window.removeEventListener("focus",V),window.removeEventListener("blur",Q),I.forEach(ue=>ue.dispose()),A?.dispose(),w.current=null,b.current=null,k.current=null,C.current=null,z.current="",j.current="",v.current=!1,P.current+=1,O.current=!1}},[D,r,o,F,i]),l.useEffect(()=>{const Z=w.current,Y=m.current;!Z||!Y||(Z.options.cursorBlink=u&&document.hasFocus()&&Y.contains(document.activeElement))},[u,M]),l.useEffect(()=>{if(!w.current)return;if(e.length===0){C.current!==null&&H();return}const Y=C.current;let A=-1;if(Y!==null){for(let T=e.length-1;T>=0;T-=1){const I=e[T].id;if(I===Y){A=T;break}if(I<Y)break}if(A<0){H();return}}const X=A<0,te=A>=0?e.slice(A+1):e;z.current+=te.map(T=>X?T.replayData??T.data:T.data).join(""),C.current=e.at(-1)?.id??null,W()},[e,W,M,H]),l.useEffect(()=>{if(!p||!u)return;const Z=requestAnimationFrame(()=>w.current?.focus());return()=>cancelAnimationFrame(Z)},[p,u,M,t]),l.useEffect(()=>{const Z=m.current;if(!c||!Z)return;const Y=A=>{const X=A;if(!X.isComposing)switch(X.inputType){case"insertText":X.data&&g.current(X.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return Z.addEventListener("beforeinput",Y),()=>Z.removeEventListener("beforeinput",Y)},[c,M]),l.useEffect(()=>{const Z=m.current,Y=w.current;if(!c||!Z||!Y)return;let A=null,X=null,te="idle",T=0,I=0,B=0,L=0,V=null;const Q=Math.max(12,o+2),G=()=>{window.Capacitor?.getPlatform?.()==="android"&&Zl(async()=>{const{Keyboard:pe}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:pe}},__vite__mapDeps([0,1])).then(({Keyboard:pe})=>pe.show()).catch(()=>{})},ue=()=>{X&&(clearTimeout(X),X=null)},ne=(ce,pe)=>{const ie=Z.querySelector("canvas");return ie?l0(ce,pe,ie.getBoundingClientRect(),Y.cols,Y.rows):null},xe=(ce,pe)=>{const ie=Z.querySelector("canvas");if(!ie)return;const le=ie.getBoundingClientRect(),de=le.left+(pe.column+.5)/Y.cols*le.width,he=le.top+(pe.row+.5)/Y.rows*le.height;ie.dispatchEvent(new MouseEvent(ce,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:de,clientY:he}))},ve=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},me=ce=>{ce.pointerType!=="touch"||A!==null||(A=ce.pointerId,te="pending",T=ce.clientX,I=ce.clientY,B=ce.clientY,L=0,V=null,Z.setPointerCapture(ce.pointerId),X=setTimeout(()=>{if(X=null,A!==ce.pointerId||te!=="pending")return;const pe=ne(T,I);if(!pe)return;const ie=Y.buffer.active,le=Math.max(0,ie.length-Y.rows-ie.viewportY+pe.row),de=ie.getLine(le),he=Array.from({length:Y.cols},(Be,Fe)=>de?.getCell(Fe)?.getChars()??""),Me=c0(he,pe.column),Le={column:Me.startColumn,row:pe.row};V={column:Me.endColumn,row:pe.row},te="selecting",xe("mousedown",Le),xe("mousemove",V)},350))},ge=ce=>{if(A!==ce.pointerId)return;if(te==="selecting"){const le=ne(ce.clientX,ce.clientY);le&&(!V||le.column!==V.column||le.row!==V.row)&&(V=le,xe("mousemove",le)),ce.cancelable&&ce.preventDefault();return}if(te==="pending"){if(Math.hypot(ce.clientX-T,ce.clientY-I)<8)return;ue(),te="scrolling"}if(te!=="scrolling")return;const pe=B-ce.clientY;B=ce.clientY,L+=pe;const ie=Math.trunc(L/Q);ie&&(Y.scrollLines(ie),L-=ie*Q),ce.cancelable&&ce.preventDefault()},Ie=ce=>{if(A!==ce.pointerId)return;const pe=te==="pending",ie=te==="selecting";ue(),Z.hasPointerCapture(ce.pointerId)&&Z.releasePointerCapture(ce.pointerId),A=null,te="idle",ie&&ve(),pe&&(Y.focus(),G())},oe=ce=>{if(A!==ce.pointerId)return;const pe=te==="selecting";ue(),Z.hasPointerCapture(ce.pointerId)&&Z.releasePointerCapture(ce.pointerId),A=null,te="idle",pe&&ve()};return Z.addEventListener("pointerdown",me),Z.addEventListener("pointermove",ge,{passive:!1}),Z.addEventListener("pointerup",Ie),Z.addEventListener("pointercancel",oe),()=>{ue(),Z.removeEventListener("pointerdown",me),Z.removeEventListener("pointermove",ge),Z.removeEventListener("pointerup",Ie),Z.removeEventListener("pointercancel",oe)}},[c,o,M]),l.useImperativeHandle(f,()=>({focus:()=>w.current?.focus(),fit:D,getSelection:()=>{const Z=w.current,Y=Z?.getSelectionPosition(),A=Z?.getSelection()??"";return!Y||!A.trim()?null:{text:A,startLine:Y.start.y+1,endLine:Y.end.y+1}}}),[D]),s.jsx("div",{ref:m,"data-terminal-owner":"main",className:fe("terminal-viewport-container h-full w-full overflow-hidden touch-none",d)})});ym.displayName="TerminalViewport";const p0="\x1B",g0=new RegExp(`${p0}\\[[0-9;?]*[ -/]*[@-~]`,"g"),f0=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,h0=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,x0=/Serving HTTP on .*? port (\d{2,5})/i,b0=new Set([".",",",";",":","!","?"]),y0=t=>{let e=t;for(;e.length>0;){const n=e[e.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const a=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",i=e.slice(0,-1),r=(i.match(new RegExp(`\\${a}`,"g"))||[]).length,o=(i.match(new RegExp(`\\${n}`,"g"))||[]).length;if(r>o)break;e=i;continue}if(b0.has(n)){e=e.slice(0,-1);continue}break}return e},_d=t=>{let e=y0(t);return e=e.replace("0.0.0.0","127.0.0.1"),e=e.replace("[::1]","127.0.0.1"),e=e.replace("[::]","127.0.0.1"),e},v0=t=>{if(!t)return null;const e=t.replace(g0,""),n=e.match(x0);if(n?.[1]){const i=Number.parseInt(n[1],10);if(Number.isFinite(i)&&i>0&&i<=65535)return`http://127.0.0.1:${i}/`}const a=e.split(`
39
- `);for(const i of a){if(!h0.test(i))continue;const r=Array.from(i.matchAll(f0));if(r.length===0)continue;const o=r.find(d=>{try{return!!new URL(_d(d[1])).port}catch{return!1}});return _d((o??r[0])[1])}return null},w0=async(t,e=1500)=>{if(!t||typeof window>"u")return!1;let n;try{n=new URL(t)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const a=n.hostname.toLowerCase();if(a!=="localhost"&&a!=="127.0.0.1"&&a!=="0.0.0.0"&&a!=="::1"&&a!=="::")return!1;const i=new AbortController,r=window.setTimeout(()=>i.abort(),e);try{const o=await ht("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:i.signal});return o.ok?(await o.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(r)}},j0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},k0=(t,e)=>{if(e&&t.startsWith("arrow-")){const n=e==="ctrl"?"5":"3",a={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[t];return`\x1B[1;${n}${a}`}return j0[t]},vm=t=>{const e=t[0]?.toUpperCase();return!e||e<"A"||e>"Z"?null:String.fromCharCode(e.charCodeAt(0)&31)},N0=(t,e)=>t&&(e==="ctrl"?vm(t)??t:t.length===1&&t!=="\x1B"?`\x1B${t}`:t),Ud={cols:80,rows:24},oS=({visible:t})=>{const{t:e}=lt(),{terminal:n,runtime:a}=Va(),{currentTheme:i}=Ha(),r=l.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});r.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:o}=pg(),d=ke(Pe=>Pe.terminalFontSize),c=ke(Pe=>Pe.terminalShell),p=ke(Pe=>Pe.terminalLoginShells.includes(Pe.terminalShell)),{isMobile:u,isTablet:f,hasTouchOnlyPointer:m}=Vs(),w=u||f,b=(w||m)&&a.platform==="web",g=a.platform!=="vscode",x=ke(Pe=>Pe.showTerminalQuickKeysOnDesktop),k=w||x,y=es(Pe=>Pe.currentSessionId),C=es(Pe=>Pe.newSessionDraft),z=y!==null||C?.open===!0,j=il()??null,N=ss(Pe=>j?Pe.sessions.get(j):void 0),v=ss(Pe=>Pe.hasHydrated),P=ss(Pe=>Pe.ensureDirectory),$=ss(Pe=>Pe.createTab),O=ss(Pe=>Pe.setActiveTab),M=ss(Pe=>Pe.closeTab),S=ss(Pe=>Pe.setTabSessionId),F=ss(Pe=>Pe.setTabLifecycle),E=ss(Pe=>Pe.setConnecting),D=ss(Pe=>Pe.appendToBuffer),W=ss(Pe=>Pe.replaceBuffer),H=ss(Pe=>Pe.setTabPreviewUrl),Z=ci(Pe=>Pe.addDraft),Y=ke(Pe=>Pe.openContextPreview),A=l.useMemo(()=>N?g?N.activeTabId??N.tabs[0]?.id??null:N.tabs[0]?.id??null:null,[N,g]),X=l.useMemo(()=>{if(N)return A?N.tabs.find(Pe=>Pe.id===A)??N.tabs[0]:N.tabs[0]},[N,A]),te=l.useMemo(()=>(N?.tabs??[]).map(Pe=>({icon:(()=>{const se=Pe.iconKey?Hu[Pe.iconKey]??"terminal":"terminal";return s.jsx(K,{name:se,className:"h-4 w-4"})})(),id:Pe.id,label:Pe.label,title:Pe.label,closeLabel:e("terminalView.tabs.closeTabTitle")})),[N?.tabs,e]),T=X?.terminalSessionId??null,I=X?.lifecycle??"idle",B=ss(Pe=>j&&A?Pe.getBuffer(j,A).chunks:lr.chunks),L=X?.isConnecting??!1,V=X?.previewUrl??null,[Q,G]=l.useState(null),[ue,ne]=l.useState(!1),[xe,ve]=l.useState(!1),[me,ge]=l.useState(null),[Ie,oe]=l.useState(!1),ce=l.useRef(null),pe=l.useRef(null),ie=l.useRef(A),le=l.useRef(T),de=l.useRef(j),he=l.useRef(null),Me=l.useRef(null),Le=l.useRef(new Set),Be=l.useRef(""),Fe=l.useRef(new Set),De=l.useRef(0),ze=l.useCallback(()=>{Be.current="",Fe.current.clear(),De.current+=1},[]),Ve=l.useCallback(()=>{b||typeof document<"u"&&!document.hasFocus()||he.current?.focus()},[b]),We=l.useCallback(()=>{b||he.current?.focus()},[b]),He=ke(Pe=>Pe.activeMainTab)==="terminal",Ke=t??He,[Oe,je]=l.useState(Ke);l.useEffect(()=>{Ke&&je(!0)},[Ke]),l.useEffect(()=>{le.current=T},[T]),l.useEffect(()=>{!T||!n.updateAppearance||n.updateAppearance(T,r.current).catch(()=>{})},[i.colors.surface.background,i.colors.syntax.base.foreground,i.metadata.variant,n,T]),l.useEffect(()=>{ie.current=A,ze()},[A,ze]),l.useEffect(()=>{de.current=j},[j]),l.useEffect(()=>{!k&&me!==null&&ge(null)},[k,me,ge]),l.useEffect(()=>{!T&&me!==null&&ge(null)},[T,me,ge]);const Te=l.useCallback(()=>{ce.current?.(),ce.current=null,pe.current=null,ve(!1)},[]);l.useEffect(()=>()=>{Te(),le.current=null},[Te]);const Ue=l.useCallback((Pe,se,Ce)=>{if(!Ce)return;const Xe=`${Be.current}${Ce}`.replace(/\r\n|\r/g,`
40
- `),Re=Xe.split(`
41
- `),Je=Xe.endsWith(`
42
- `)?Re.join(`
43
- `):Re.slice(0,-1).join(`
44
- `);if(Be.current=Xe.endsWith(`
45
- `)?"":(Re[Re.length-1]??"").slice(-1024),!Je)return;const Ge=v0(Je);if(!Ge||Fe.current.has(Ge))return;const st=De.current;Fe.current.add(Ge),w0(Ge).then(jt=>{if(Fe.current.delete(Ge),!jt||De.current!==st)return;const Et=ss.getState().getDirectoryState(Pe)?.tabs.find(Mt=>Mt.id===se);!Et||Et.previewUrlLocked||Et.previewUrl===Ge||H(Pe,se,Ge,{locked:!1,autoOpened:!1})})},[H]),Ye=l.useCallback((Pe,se,Ce)=>{if(pe.current===Ce)return;Te(),pe.current=Ce;const Xe=n.connect(Ce,{onEvent:Re=>{if(pe.current===Ce)switch(Re.type){case"snapshot":{E(Pe,se,!1),G(null),ne(!1),ve(!1),Ve(),W(Pe,se,Re.data??"",Re.sequence??0),Ue(Pe,se,Re.data??""),Re.status==="exited"&&F(Pe,se,"exited");break}case"reconnecting":{G(null),ne(!1),ve(!0);break}case"data":{Re.data&&(D(Pe,se,Re.data,Re.sequence,Re.replayData),Ue(Pe,se,Re.data));break}case"exit":{const Je=typeof Re.exitCode=="number"?Re.exitCode:null,Ge=typeof Re.signal=="number"?Re.signal:null,jt=!!ss.getState().getDirectoryState(Pe)?.tabs.find(Et=>Et.id===se)?.label?.startsWith("Action:");D(Pe,se,e("terminalView.stream.processExitedMessage",{exitCodeSegment:Je!==null?e("terminalView.stream.processExitedWithCode",{exitCode:Je}):"",signalSegment:Ge!==null?e("terminalView.stream.processExitedWithSignal",{signal:Ge}):""})),F(Pe,se,"exited"),E(Pe,se,!1),G(jt?null:e("terminalView.error.sessionEnded")),ne(!1),ve(!1),Te();break}}},onError:(Re,Je)=>{if(pe.current===Ce){if(!Je){G(null),ne(!1);return}if(ve(!1),Re.code==="SESSION_NOT_FOUND"&&!ss.getState().getDirectoryState(Pe)?.tabs.find(st=>st.id===se)?.label?.startsWith("Action:")){G(null),ne(!1),E(Pe,se,!1),S(Pe,se,null),F(Pe,se,"idle"),Te();return}G(e("terminalView.error.connectionFailed",{message:Re.message})),ne(!0),E(Pe,se,!1),F(Pe,se,"exited"),S(Pe,se,null),Te()}}});ce.current=()=>{Xe.close(),pe.current=null}},[D,W,Te,Ve,Ue,E,F,S,e,n]);l.useEffect(()=>{let Pe=!1;if(!v||!Oe)return;if(!j){G(e(z?"terminalView.empty.noWorkingDirectory":"terminalView.empty.selectSession")),Te();return}return(async()=>{const Ce=j;if(!de.current||de.current!==Ce)return;if(!ss.getState().getDirectoryState(Ce)){P(Ce);return}const Re=ss.getState().getDirectoryState(Ce);if(!Re||Re.tabs.length===0)return;const Je=g?Re.activeTabId??Re.tabs[0]?.id??null:Re.tabs[0]?.id??null;if(!Je)return;const Ge=Re.tabs.find(Qt=>Qt.id===Je)??Re.tabs[0],st=Ge?.terminalSessionId??null,jt=Ge?.lifecycle??"idle",Et=!!Ge?.label?.startsWith("Action:"),Mt=ss.getState().getBuffer(Ce,Je),Zt=Mt.byteLength>0||Mt.chunks.length>0;if(!st){if(jt==="exited"){E(Ce,Je,!1);return}if(Et&&Zt){E(Ce,Je,!1);return}const Qt=`${Ce}\0${Je}`;if(Le.current.has(Qt))return;const St=Me.current??Ud;Le.current.add(Qt),G(null),ne(!1),ve(!1),E(Ce,Je,!0);try{const Pt=await n.createSession({cwd:Ce,sessionId:Je,cols:St.cols,rows:St.rows,shell:c,loginShell:p,...r.current}),Ne=!Pe&&de.current===Ce&&ie.current===Je;if(!ss.getState().getDirectoryState(Ce)?.tabs.find(At=>At.id===Je)){try{await n.close(Pt.sessionId)}catch{}return}if(S(Ce,Je,Pt.sessionId),!Ne)return;const mt=Me.current;mt&&(mt.cols!==St.cols||mt.rows!==St.rows)&&n.resize({sessionId:Pt.sessionId,...mt}).catch(()=>{});return}catch(Pt){const Ne=ss.getState().getDirectoryState(Ce)?.tabs.find(ut=>ut.id===Je);if(!Ne||Ne.terminalSessionId||(E(Ce,Je,!1),de.current!==Ce||ie.current!==Je))return;G(Pt instanceof Error?Pt.message:e("terminalView.error.startSessionFailed")),ne(!0),ve(!1);return}finally{Le.current.delete(Qt)}}!st||Pe||(le.current=st,Ye(Ce,Je,st))})(),()=>{Pe=!0,le.current=null,Te()}},[z,j,T,I,A,Oe,g,v,P,E,F,S,Ye,Te,e,n,p,c]),l.useEffect(()=>{if(!Ke||b)return;if(typeof window>"u"){Ve();return}const Pe=window.requestAnimationFrame(()=>{Ve()});return()=>{window.cancelAnimationFrame(Pe)}},[A,Ve,Ke,b]);const q=l.useCallback(async()=>{if(!j||Ie)return;const Pe=ss.getState().getDirectoryState(j),se=g?A??Pe?.activeTabId??Pe?.tabs[0]?.id??null:Pe?.tabs[0]?.id??null;if(!se)return;const Ce=Pe?.tabs.find(Xe=>Xe.id===se)?.terminalSessionId??null;if(!(!Ce||!n.restartSession)){oe(!0),G(null),ne(!1),ve(!1),Te(),ze();try{const Xe=Me.current??Ud,Re=await n.restartSession(Ce,{cwd:j,shell:c,loginShell:p,...Xe,...r.current});if(ss.getState().getDirectoryState(j)?.tabs.find(Ge=>Ge.id===se)?.terminalSessionId!==Ce||(S(j,se,Re.sessionId),F(j,se,"running"),de.current!==j||ie.current!==se))return;le.current=Re.sessionId,Ye(j,se,Re.sessionId)}catch(Xe){if(ss.getState().getDirectoryState(j)?.tabs.find(Je=>Je.id===se)?.terminalSessionId!==Ce||de.current!==j||ie.current!==se)return;G(Xe instanceof Error?Xe.message:e("terminalView.error.restartFailed")),ne(!1),ve(!1),le.current=Ce,Ye(j,se,Ce)}finally{oe(!1)}}},[A,Te,j,g,Ie,ze,F,S,Ye,e,n,p,c]),re=l.useCallback(async()=>{await q()},[q]),U=l.useCallback(()=>{if(!j)return;const Pe=$(j);O(j,Pe),G(null),ne(!1),ve(!1),Te()},[$,Te,j,O]),h=l.useCallback(()=>{const Pe=he.current?.getSelection(),se=y??(C?.open?"draft":null);!Pe||!se||!X||!j||Z({directory:j,sessionKey:se},{source:"terminal",fileLabel:X.label,startLine:Pe.startLine,endLine:Pe.endLine,code:Pe.text,language:X.terminalSessionId??X.id,text:""})},[X,Z,y,j,C?.open]),ae=l.useCallback(Pe=>{j&&(O(j,Pe),G(null),ne(!1),ve(!1),Te())},[Te,j,O]),ye=l.useCallback(Pe=>{if(!j)return;Pe===A&&Te(),G(null),ne(!1),ve(!1);const se=ss.getState().getDirectoryState(j)?.tabs.find(Ce=>Ce.id===Pe)?.terminalSessionId;(async()=>{se&&await n.close(se),M(j,Pe)})().catch(Ce=>G(Ce instanceof Error?Ce.message:e("terminalView.error.sessionEnded")))},[A,M,Te,j,e,n]),be=l.useCallback(Pe=>{if(!Pe||xe)return;let se=Pe,Ce=!1;me&&Pe.length>0&&(se=N0(Pe,me),Ce=!0);const Xe=le.current;Xe&&(n.sendInput(Xe,se).catch(Re=>{xe||G(Re instanceof Error?Re.message:e("terminalView.error.sendInputFailed"))}),Ce&&(ge(null),We()))},[me,We,xe,ge,e,n]),Ee=l.useCallback((Pe,se)=>{const Ce=Me.current;if((!Ce||Ce.cols!==Pe||Ce.rows!==se)&&(Me.current={cols:Pe,rows:se}),!Ke)return;const Xe=le.current;Xe&&n.resize({sessionId:Xe,cols:Pe,rows:se}).catch(()=>{})},[Ke,n]),et=l.useCallback(Pe=>{ge(se=>se===Pe?null:Pe),We()},[We,ge]),Ze=l.useCallback(Pe=>{const se=k0(Pe,me);se&&(be(se),ge(null),We())},[me,We,be,ge]),it=l.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),ot=l.useCallback(Pe=>{if(Pe.repeat)return;const se=Pe.key;if(!se||se==="Control"||se==="Meta"||se==="Alt"||se==="Shift")return;const Ce=se.length===1?se.toLowerCase():se;if(Ce in it){Pe.preventDefault(),Pe.stopPropagation(),Ze(it[Ce]);return}if(me!=="ctrl")return;const Xe=Pe.code??"",Re=se.length===1&&/[a-zA-Z]/.test(se)?se.toUpperCase():Xe.startsWith("Key")&&Xe.length===4?Xe.slice(3).toUpperCase():null;if(Re&&Re.length===1&&Re>="A"&&Re<="Z"){const Je=vm(Re);if(!Je)return;Pe.preventDefault(),Pe.stopPropagation(),be(Je),ge(null),We()}},[me,We,Ze,be,it,ge]);l.useEffect(()=>{if(!(!k||!me||!T))return window.addEventListener("keydown",ot),()=>window.removeEventListener("keydown",ot)},[me,ot,k,T]);const xt=l.useMemo(()=>{const Pe=ei[pi].stack;if(typeof window>"u")return(ei[o]??ei[pi]).stack;const Ce=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Ce&&Ce.trim().length>0?Ce.trim():(ei[o]??ei[pi]).stack??Pe},[o]),bt=l.useMemo(()=>a0(i),[i]),Nt=`${j??"no-dir"}::${A??"no-tab"}`;if(l.useEffect(()=>{if(!Ke||b)return;const Pe=he.current;if(!Pe)return;const se=()=>{Pe.fit()};if(typeof window<"u"){const Ce=window.requestAnimationFrame(()=>{se(),Ve()}),Xe=[220,400].map(Re=>window.setTimeout(se,Re));return()=>{window.cancelAnimationFrame(Ce),Xe.forEach(Re=>window.clearTimeout(Re))}}se()},[Ve,Ke,b,Nt,T]),l.useEffect(()=>{if(!Ke||!b)return;let Pe=null;const se=()=>{Pe!==null&&window.cancelAnimationFrame(Pe),Pe=window.requestAnimationFrame(()=>{Pe=null,he.current?.fit()})};return window.addEventListener("oc:keyboard-settled",se),()=>{window.removeEventListener("oc:keyboard-settled",se),Pe!==null&&window.cancelAnimationFrame(Pe)}},[Ke,Nt,b]),!z)return s.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:e("terminalView.empty.selectSession")});if(!j)return s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[s.jsx("p",{children:e("terminalView.empty.noWorkingDirectoryForSession")}),s.jsx("button",{onClick:q,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:e("terminalView.actions.retry")})]});const Se=!T||L||Ie||xe,Qe=Oe,nt=w?"lg":"xs",rt=w?"w-10 p-0":"w-9 p-0",gt=Pe=>{w&&Pe.preventDefault()},wt=s.jsxs(s.Fragment,{children:[s.jsx(ee,{type:"button",size:nt,variant:"outline",onPointerDown:gt,onClick:()=>Ze("esc"),disabled:Se,children:e("terminalView.quickKeys.escape")}),s.jsxs(ee,{type:"button",size:nt,variant:"outline",className:rt,onPointerDown:gt,onClick:()=>Ze("tab"),disabled:Se,children:[s.jsx(K,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.tabAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"chip","aria-pressed":me==="ctrl",className:w?"px-3":"px-2",onPointerDown:gt,onClick:()=>et("ctrl"),disabled:Se,children:[s.jsx("span",{className:"text-xs font-medium",children:e("terminalView.quickKeys.controlLabel")}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.controlModifierAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"chip","aria-pressed":me==="alt",className:w?"px-3":"px-2",onPointerDown:gt,onClick:()=>et("alt"),disabled:Se,children:[s.jsx("span",{className:"text-xs font-medium",children:e("terminalView.quickKeys.altLabel")}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.altModifierAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"outline",className:rt,onPointerDown:gt,onClick:()=>Ze("arrow-up"),disabled:Se,children:[s.jsx(K,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowUpAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"outline",className:rt,onPointerDown:gt,onClick:()=>Ze("arrow-left"),disabled:Se,children:[s.jsx(K,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowLeftAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"outline",className:rt,onPointerDown:gt,onClick:()=>Ze("arrow-down"),disabled:Se,children:[s.jsx(K,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowDownAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"outline",className:rt,onPointerDown:gt,onClick:()=>Ze("arrow-right"),disabled:Se,children:[s.jsx(K,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowRightAria")})]}),s.jsxs(ee,{type:"button",size:nt,variant:"outline",className:rt,onPointerDown:gt,onClick:()=>Ze("enter"),disabled:Se,children:[s.jsx(K,{name:"arrow-go-back"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.enterAria")})]})]});return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[s.jsxs("div",{className:fe("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",w?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[g&&N?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[s.jsx("div",{className:fe("min-w-0 flex-1",w?"h-8":"h-7"),children:s.jsx(ma,{items:te,activeId:A,onSelect:ae,onClose:ye,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),s.jsx(ee,{type:"button",size:"xs",variant:"ghost",className:fe("shrink-0",w?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:U,title:e("terminalView.tabs.newTabTitle"),children:s.jsx(K,{name:"add",className:`${w?"h-[18px] w-[18px]":"h-4 w-4"}`})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(ee,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{q()},disabled:Ie,title:e("terminalView.actions.restart"),"aria-label":e("terminalView.actions.restart"),children:s.jsx(K,{name:"restart",className:"h-4 w-4"})}),s.jsx(ee,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:h,title:e("terminalView.actions.attachSelection"),"aria-label":e("terminalView.actions.attachSelection"),children:s.jsx(K,{name:"attachment-2",className:"h-4 w-4"})}),V?s.jsxs(ee,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{j&&Y(j,V)},title:e("terminalView.preview.openTitle"),children:[s.jsx(K,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:e("terminalView.preview.open")})]}):null]})]}):null,!w&&k&&g&&N?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:wt}):null,!w&&k&&(!g||!N)?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:wt}):null]}),s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:bt.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Qe?s.jsx(ym,{ref:Pe=>{he.current=Pe},sessionKey:Nt,chunks:B,onInput:be,onResize:Ee,theme:bt,fontFamily:xt,fontSize:d,enableTouchScroll:b,autoFocus:Ke,isVisible:Ke},Nt):null}),!xe&&Q&&s.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[s.jsx("span",{children:Q}),ue&&w&&s.jsx(ee,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:re,disabled:Ie,title:e("terminalView.actions.hardRestartTitle"),type:"button",children:e("terminalView.actions.hardRestart")})]})]}),w&&k?s.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:s.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:wt})}):null]})},wm={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},S0=wm.M;function C0(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"}function I0(t){const e=C0(t);return wm[e]??S0}const P0=l.memo(function(e){const n=tt.c(58),{file:a,actionLabel:i,actionSymbol:r,onAction:o,onViewDiff:d,onRevert:c,isReverting:p,stats:u,rowPaddingClassName:f,indentPx:m,actionAtStart:w,showRevert:b}=e,g=m===void 0?0:m,x=w===void 0?!1:w,k=b===void 0?!0:b;let y;n[0]!==a?(y=I0(a),n[0]=a,n[1]=y):y=n[1];const C=y,{t:z}=lt(),j=C.description,N=u?.insertions??0,v=u?.deletions??0;let P;n[2]!==o||n[3]!==d?(P=xe=>{xe.key===" "?(xe.preventDefault(),o()):xe.key==="Enter"&&(xe.preventDefault(),d())},n[2]=o,n[3]=d,n[4]=P):P=n[4];const $=P;let O;n[5]!==o?(O=xe=>{xe.preventDefault(),xe.stopPropagation(),o()},n[5]=o,n[6]=O):O=n[6];const M=O;let S;n[7]!==c?(S=xe=>{xe.preventDefault(),xe.stopPropagation(),c()},n[7]=c,n[8]=S):S=n[8];const F=S;let E;n[9]!==i||n[10]!==r||n[11]!==M?(E=s.jsx("button",{type:"button",onClick:M,className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":i,title:i,children:r}),n[9]=i,n[10]=r,n[11]=M,n[12]=E):E=n[12];const D=E,W=`group flex items-center gap-2 py-1.5 cursor-pointer ${f??"px-3"}`;let H;n[13]!==g?(H=g>0?{paddingLeft:`${g}px`}:void 0,n[13]=g,n[14]=H):H=n[14];const Z=x?D:null;let Y;n[15]!==C.color?(Y={color:C.color},n[15]=C.color,n[16]=Y):Y=n[16];let A;n[17]!==C.code||n[18]!==j||n[19]!==Y?(A=s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:Y,title:j,"aria-label":j,children:C.code}),n[17]=C.code,n[18]=j,n[19]=Y,n[20]=A):A=n[20];let X;n[21]!==a.path?(X=s.jsx(gg,{filePath:a.path,className:"h-3.5 w-3.5 shrink-0"}),n[21]=a.path,n[22]=X):X=n[22];let te;if(n[23]!==a.path){e:{const xe=a.path.lastIndexOf("/");if(xe===-1){let pe;n[25]===Symbol.for("react.memo_cache_sentinel")?(pe={direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},n[25]=pe):pe=n[25],te=s.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:pe,title:a.path,children:a.path});break e}const ve=a.path.slice(0,xe),me=a.path.slice(xe);let ge;n[26]===Symbol.for("react.memo_cache_sentinel")?(ge={direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},n[26]=ge):ge=n[26];let Ie;n[27]===Symbol.for("react.memo_cache_sentinel")?(Ie=s.jsx("span",{className:"text-muted-foreground",children:"/"}),n[27]=Ie):Ie=n[27];const oe=s.jsx("span",{className:"text-foreground",children:me.slice(1)});let ce;n[28]!==oe?(ce=s.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[Ie,oe]}),n[28]=oe,n[29]=ce):ce=n[29],te=s.jsxs("span",{className:"flex-1 min-w-0 flex items-baseline overflow-hidden",title:a.path,children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:ge,children:ve}),ce]})}n[23]=a.path,n[24]=te}else te=n[24];let T;n[30]===Symbol.for("react.memo_cache_sentinel")?(T={color:"var(--status-success)"},n[30]=T):T=n[30];let I;n[31]!==N?(I=s.jsxs("span",{style:T,children:["+",N]}),n[31]=N,n[32]=I):I=n[32];let B,L;n[33]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),L={color:"var(--status-error)"},n[33]=B,n[34]=L):(B=n[33],L=n[34]);let V;n[35]!==v?(V=s.jsxs("span",{style:L,children:["-",v]}),n[35]=v,n[36]=V):V=n[36];let Q;n[37]!==I||n[38]!==V?(Q=s.jsxs("span",{className:"shrink-0 typography-micro",children:[I,B,V]}),n[37]=I,n[38]=V,n[39]=Q):Q=n[39];let G;n[40]!==a.path||n[41]!==F||n[42]!==p||n[43]!==k||n[44]!==z?(G=k?s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx("button",{type:"button",onClick:F,disabled:p,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":z("gitView.changes.revertFileAria",{path:a.path}),children:p?s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(K,{name:"arrow-go-back",className:"size-3.5"})})}),s.jsx(ks,{sideOffset:8,children:z("gitView.changes.revertFileTooltip")})]}):null,n[40]=a.path,n[41]=F,n[42]=p,n[43]=k,n[44]=z,n[45]=G):G=n[45];const ue=x?null:D;let ne;return n[46]!==$||n[47]!==d||n[48]!==H||n[49]!==Z||n[50]!==A||n[51]!==X||n[52]!==te||n[53]!==Q||n[54]!==G||n[55]!==ue||n[56]!==W?(ne=s.jsxs("div",{className:W,role:"button",tabIndex:0,onClick:d,onKeyDown:$,style:H,children:[Z,A,X,te,Q,G,ue]}),n[46]=$,n[47]=d,n[48]=H,n[49]=Z,n[50]=A,n[51]=X,n[52]=te,n[53]=Q,n[54]=G,n[55]=ue,n[56]=W,n[57]=ne):ne=n[57],ne}),$d=14,jm=t=>t.replace(/\\/g,"/").replace(/^\/+/,"").trim(),Vd=(t,e)=>({id:`dir:${t}`,path:t,name:e,children:new Map,directFiles:[],files:[]}),T0=t=>{const e=Vd("","");for(const n of t){const a=jm(n.path);if(!a)continue;const r=a.split("/").filter(Boolean).slice(0,-1);let o=e;if(o.files.push(n),r.length>0){let d="";for(const c of r){d=d?`${d}/${c}`:c;const p=o.children.get(c);if(p){p.files.push(n),o=p;continue}const u=Vd(d,c);u.files.push(n),o.children.set(c,u),o=u}}o.directFiles.push(n)}return e},A0=(t,e)=>{const n=[],a=(i,r)=>{const o=Array.from(i.children.values()).sort((c,p)=>c.path.localeCompare(p.path));for(const c of o)n.push({key:c.id,kind:"directory",depth:r,directory:c}),e.has(c.path)&&a(c,r+1);const d=[...i.directFiles].sort((c,p)=>c.path.localeCompare(p.path));for(const c of d)n.push({key:`file:${jm(c.path)}`,kind:"file",depth:r,file:c})};return a(t,0),n},E0=1e3,Hd=34,Co=30,Gi="pl-0 pr-2",Io=(t,e)=>`${t} ${e}`,lS=({groups:t,diffStats:e,revertingPaths:n,isRevertingAll:a=!1,headerBackgroundClassName:i="bg-sidebar",onVisiblePathsChange:r,onRevertAll:o,onRevertDirectory:d})=>{const{t:c}=lt(),p=l.useRef(null),f=ke(I=>I.gitChangesViewMode)==="tree",m=l.useMemo(()=>t.filter(I=>I.entries.length>0),[t]),[w,b]=l.useState(new Set),[g,x]=l.useState(new Set),[k,y]=l.useState(!1),[C,z]=l.useState(null),j=l.useMemo(()=>m.map(I=>T0(I.entries)),[m]),N=l.useMemo(()=>{const I=[];return m.forEach((B,L)=>{Array.from(j[L]?.children.values()??[]).forEach(V=>{I.push(Io(B.id,V.path))})}),I},[j,m]);l.useEffect(()=>{f&&x(I=>{const B=new Set,L=new Set(N);return I.forEach(V=>{(V.slice(V.indexOf(" ")+1).includes("/")||L.has(V))&&B.add(V)}),N.forEach(V=>B.add(V)),B})},[f,N]);const v=l.useMemo(()=>{const I=[];return m.forEach((B,L)=>{if(I.push({type:"header",key:`header:${B.id}`,groupIndex:L}),!w.has(B.id)){if(f){const V=new Set;g.forEach(G=>{G.startsWith(`${B.id} `)&&V.add(G.slice(B.id.length+1))}),A0(j[L],V).forEach(G=>{G.kind==="file"?I.push({type:"file",key:`${B.id}:${G.key}`,groupIndex:L,file:G.file,depth:G.depth}):I.push({type:"directory",key:`${B.id}:${G.key}`,groupIndex:L,directory:G.directory,depth:G.depth})});return}B.entries.forEach(V=>{I.push({type:"file",key:`${B.id}:file:${V.path}`,groupIndex:L,file:V,depth:0})})}}),o&&m.length>0&&I.push({type:"revert-all",key:"revert-all"}),I},[w,g,f,o,j,m]),P=v.length,$=P>=E0,O=qf({count:P,enabled:$,getScrollElement:()=>p.current,estimateSize:()=>Hd,overscan:12,getItemKey:I=>v[I]?.key??I}),M=O.getVirtualItems(),S=l.useMemo(()=>{if(!$)return 0;const I=p.current?.scrollTop??0;return M.find(L=>L.end>I)?.index??0},[$,M,p]);l.useEffect(()=>{if(!r)return;const I=B=>B&&B.type==="file"?B.file.path:null;if(P===0){r([]);return}if(!$){const B=[];for(const L of v)if(L.type==="file"&&(B.push(L.file.path),B.length>=Co))break;r(B);return}r(v.slice(S,S+Math.ceil((p.current?.clientHeight??0)/Hd)+Co).map(B=>I(B)).filter(B=>!!B).slice(0,Co))},[r,P,v,$,S]);const F=l.useCallback(I=>{b(B=>{const L=new Set(B);return L.has(I)?L.delete(I):L.add(I),L})},[]),E=l.useCallback((I,B)=>{x(L=>{const V=new Set(L),Q=Io(I,B);return V.has(Q)?V.delete(Q):V.add(Q),V})},[]),D=l.useMemo(()=>{const I=new Set;return m.forEach(B=>B.entries.forEach(L=>I.add(L.path))),Array.from(I)},[m]),W=D.length,H=C?a||C.paths.some(I=>n.has(I)):!1,Z=l.useCallback(async()=>{!o||a||D.length===0||(await o(D),y(!1))},[D,a,o]),Y=l.useCallback(async()=>{!d||!C||H||(await d(C.paths),z(null))},[H,d,C]),A=l.useCallback((I,B)=>{const L=w.has(I.id),V=I.entries.length;return s.jsxs("div",{className:fe("sticky top-0 z-10 flex items-center gap-2 py-2",i,Gi,!B&&"mt-1 border-t border-border/40"),children:[s.jsx("button",{type:"button",onClick:()=>I.onActionAll(I.entries.map(Q=>Q.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":I.actionAllLabel,title:I.actionAllLabel,children:I.actionSymbol}),s.jsxs("button",{type:"button",onClick:()=>F(I.id),className:"flex min-w-0 flex-1 items-center gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-expanded":!L,children:[s.jsx("h3",{className:"truncate typography-ui-header font-semibold text-foreground",children:I.title}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:V}),s.jsx(K,{name:"arrow-down-s",className:fe("size-3.5 shrink-0 text-muted-foreground transition-transform",L&&"-rotate-90")})]})]})},[w,i,F]),X=l.useCallback((I,B,L)=>{const V=g.has(Io(I.id,B.path)),Q=B.files.map(ue=>ue.path),G=a||Q.some(ue=>n.has(ue));return s.jsxs("div",{className:fe("group flex items-center gap-2 py-1.5",Gi),style:{paddingLeft:`${L*$d}px`},children:[s.jsxs("button",{type:"button",onClick:()=>E(I.id,B.path),className:"flex min-w-0 flex-1 items-center gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":V?c("gitView.changes.collapseDirectoryAria",{path:B.path}):c("gitView.changes.expandDirectoryAria",{path:B.path}),children:[V?s.jsx(K,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(K,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}),s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:B.path,children:B.name}),s.jsx("span",{className:"ml-auto shrink-0 typography-micro text-muted-foreground",children:B.files.length})]}),I.showRevertActions!==!1&&d?s.jsx("button",{type:"button",onClick:()=>z({path:B.path,paths:Q,count:Q.length}),disabled:G,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50","aria-label":c("gitView.changes.revertDirectoryAria",{path:B.path}),title:c("gitView.changes.revertDirectoryTooltip"),children:G?s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(K,{name:"arrow-go-back",className:"size-3.5"})}):null,s.jsx("button",{type:"button",onClick:()=>I.onActionAll(B.files.map(ue=>ue.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":c(I.actionSymbol==="+"?"gitView.changes.stageDirectoryAria":"gitView.changes.unstageDirectoryAria",{path:B.path}),title:c(I.actionSymbol==="+"?"gitView.changes.stageDirectoryAria":"gitView.changes.unstageDirectoryAria",{path:B.path}),children:I.actionSymbol})]})},[g,a,d,n,c,E]),te=l.useCallback((I,B)=>{if(I.type==="revert-all")return s.jsx("div",{className:fe("flex justify-end py-2",Gi),children:s.jsxs(ee,{variant:"ghost",size:"sm",onClick:()=>y(!0),disabled:a,className:"gap-1.5 text-[var(--status-error)] hover:bg-[var(--status-error)]/10 hover:text-[var(--status-error)]",children:[s.jsx(K,{name:"arrow-go-back",className:"size-3.5"}),c("gitView.changes.revertAll")]})});const L=m[I.groupIndex];if(!L)return null;if(I.type==="header")return A(L,B);if(I.type==="directory")return X(L,I.directory,I.depth);const V=I.file;return s.jsx(P0,{file:V,actionLabel:L.getActionLabel(V.path),actionSymbol:L.actionSymbol,onAction:()=>L.onActionFile(V.path),stats:e?.[V.path],onViewDiff:()=>L.onViewDiff(V.path),onRevert:()=>L.onRevertFile(V.path),isReverting:n.has(V.path)||a,rowPaddingClassName:Gi,indentPx:I.depth*$d,actionAtStart:!f,showRevert:L.showRevertActions!==!1})},[e,a,f,X,A,n,c,m]),T=l.useCallback(I=>{const B=v[I],L=v[I-1];return!B||!L||B.type!=="file"&&B.type!=="directory"||L.type!=="file"&&L.type!=="directory"?!1:L.groupIndex===B.groupIndex},[v]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden",children:[s.jsx(fg,{ref:p,className:"overlay-scrollbar-target overlay-scrollbar-container min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto",children:$?s.jsx("div",{style:{height:O.getTotalSize(),position:"relative"},children:M.map(I=>{const B=v[I.index];return B?s.jsx("div",{"data-index":I.index,ref:O.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${I.start}px)`},className:fe(T(I.index)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:te(B,I.index===0)},B.key):null})}):s.jsx("div",{role:"list","aria-label":c("gitView.changes.changedFilesAria"),children:v.map((I,B)=>s.jsx("div",{className:fe("relative",T(B)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:te(I,B===0)},I.key))})}),s.jsx(hg,{containerRef:p,disableHorizontal:!0})]}),s.jsx(Kt,{open:k,onOpenChange:I=>{!a&&!I&&y(!1)},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:c("gitView.changes.revertAllDialogTitle")}),s.jsx(Yt,{children:W===1?c("gitView.changes.revertAllDescriptionSingle",{count:W}):c("gitView.changes.revertAllDescriptionPlural",{count:W})})]}),s.jsxs(rs,{children:[s.jsx(ee,{variant:"outline",size:"sm",onClick:()=>y(!1),disabled:a,children:c("gitView.common.cancel")}),s.jsx(ee,{variant:"destructive",size:"sm",onClick:()=>{Z()},disabled:a,children:c(a?"gitView.changes.reverting":"gitView.changes.revertAll")})]})]})}),s.jsx(Kt,{open:!!C,onOpenChange:I=>{!H&&!I&&z(null)},children:s.jsxs(Bt,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:c("gitView.changes.revertDirectoryDialogTitle")}),s.jsx(Yt,{children:C?C.count===1?c("gitView.changes.revertDirectoryDescriptionSingle",{count:C.count,path:C.path}):c("gitView.changes.revertDirectoryDescriptionPlural",{count:C.count,path:C.path}):null})]}),s.jsxs(rs,{children:[s.jsx(ee,{variant:"outline",size:"sm",onClick:()=>z(null),disabled:H,children:c("gitView.common.cancel")}),s.jsx(ee,{variant:"destructive",size:"sm",onClick:()=>{Y()},disabled:H||!C,children:c(H?"gitView.changes.reverting":"gitView.changes.revertDirectory")})]})]})})]})},Po=38,qi=200,D0=t=>{const e=tt.c(20),{value:n,onChange:a,placeholder:i,disabled:r,hasTouchInput:o,isMobile:d}=t,c=r===void 0?!1:r,p=o===void 0?!1:o,u=d===void 0?!1:d,{t:f}=lt(),m=l.useRef(null),w=ke(R0);let b;e[0]===Symbol.for("react.memo_cache_sentinel")?(b=()=>{const $=m.current;if(!$)return;const O=document.activeElement===$,M=()=>{$.style.height=`${Po}px`;const F=$.scrollHeight,E=Math.min(Math.max(F,Po),qi);$.style.height=`${E}px`,$.style.overflowY=F>qi?"auto":"hidden",F>qi&&!O&&($.scrollTop=$.scrollHeight)};M();const S=window.requestAnimationFrame(M);return()=>{window.cancelAnimationFrame(S)}},e[0]=b):b=e[0];let g;e[1]!==n?(g=[n],e[1]=n,e[2]=g):g=e[2],l.useLayoutEffect(b,g);let x;e[3]!==a?(x=$=>a($.target.value),e[3]=a,e[4]=x):x=e[4];let k;e[5]!==i||e[6]!==f?(k=i??f("gitView.commit.messagePlaceholder"),e[5]=i,e[6]=f,e[7]=k):k=e[7];const y=p?"on":"off",C=p?"sentences":"off",z=u||w,j=c&&"opacity-50";let N;e[8]!==j?(N=fe("w-full rounded-lg border border-border/60 bg-surface-elevated px-3 py-2 typography-ui-label text-foreground placeholder:text-muted-foreground","resize-none outline-none transition-[border-color,box-shadow] duration-150","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",j),e[8]=j,e[9]=N):N=e[9];let v;e[10]===Symbol.for("react.memo_cache_sentinel")?(v={minHeight:Po,maxHeight:qi},e[10]=v):v=e[10];let P;return e[11]!==c||e[12]!==z||e[13]!==N||e[14]!==x||e[15]!==k||e[16]!==y||e[17]!==C||e[18]!==n?(P=s.jsx("textarea",{ref:m,value:n,onChange:x,placeholder:k,rows:1,disabled:c,autoCorrect:y,autoCapitalize:C,spellCheck:z,className:N,style:v}),e[11]=c,e[12]=z,e[13]=N,e[14]=x,e[15]=k,e[16]=y,e[17]=C,e[18]=n,e[19]=P):P=e[19],P};function R0(t){return t.inputSpellcheckEnabled}const M0=t=>{const e=tt.c(30),{highlights:n,onInsert:a}=t,{t:i}=lt();if(n.length===0)return null;let r;e[0]!==n||e[1]!==a?(r=()=>{a(n)},e[0]=n,e[1]=a,e[2]=r):r=e[2];const o=r;let d;e[3]!==i?(d=i("gitView.commit.aiHighlights.title"),e[3]=i,e[4]=d):d=e[4];let c;e[5]!==d?(c=s.jsx("p",{className:"typography-micro text-muted-foreground",children:d}),e[5]=d,e[6]=c):c=e[6];let p;e[7]!==i?(p=i("gitView.commit.aiHighlights.insertAria"),e[7]=i,e[8]=p):p=e[8];let u;e[9]===Symbol.for("react.memo_cache_sentinel")?(u=s.jsx(K,{name:"arrow-down",className:"size-4"}),e[9]=u):u=e[9];let f;e[10]!==o||e[11]!==p?(f=s.jsx(xs,{asChild:!0,children:s.jsx(ee,{variant:"ghost",size:"icon",className:"size-6",onClick:o,"aria-label":p,children:u})}),e[10]=o,e[11]=p,e[12]=f):f=e[12];let m;e[13]!==i?(m=i("gitView.commit.aiHighlights.insertTooltip"),e[13]=i,e[14]=m):m=e[14];let w;e[15]!==m?(w=s.jsx(ks,{sideOffset:8,children:m}),e[15]=m,e[16]=w):w=e[16];let b;e[17]!==f||e[18]!==w?(b=s.jsxs(bs,{children:[f,w]}),e[17]=f,e[18]=w,e[19]=b):b=e[19];let g;e[20]!==c||e[21]!==b?(g=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c,b]}),e[20]=c,e[21]=b,e[22]=g):g=e[22];let x;e[23]!==n?(x=n.map(L0),e[23]=n,e[24]=x):x=e[24];let k;e[25]!==x?(k=s.jsx("ul",{className:"space-y-1",children:x}),e[25]=x,e[26]=k):k=e[26];let y;return e[27]!==g||e[28]!==k?(y=s.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-transparent px-3 py-2",children:[g,k]}),e[27]=g,e[28]=k,e[29]=y):y=e[29],y};function L0(t,e){return s.jsx("li",{className:"typography-meta text-foreground",children:t},`${t}-${e}`)}const cS=t=>{const e=tt.c(75),{stagedCount:n,commitMessage:a,onCommitMessageChange:i,generatedHighlights:r,onInsertHighlights:o,onGenerateMessage:d,isGeneratingMessage:c,onCommit:p,onCommitAndPush:u,commitAction:f,hasPendingIndexMutation:m,gitmojiEnabled:w,onOpenGitmojiPicker:b}=t,g=m===void 0?!1:m,{t:x}=lt(),k=n>0;let y;e[0]!==f||e[1]!==a||e[2]!==g||e[3]!==k?(y=a.trim()&&k&&f===null&&!g,e[0]=f,e[1]=a,e[2]=g,e[3]=k,e[4]=y):y=e[4];const C=y,{isMobile:z,hasTouchInput:j}=Vs();let N;e[5]!==x?(N=x("gitView.commit.title"),e[5]=x,e[6]=N):N=e[6];let v;e[7]!==N?(v=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:N}),e[7]=N,e[8]=v):v=e[8];let P;e[9]!==k||e[10]!==x?(P=k?null:s.jsx("span",{className:"min-w-0 truncate typography-meta text-muted-foreground",children:x("gitView.commit.stageFilesHint")}),e[9]=k,e[10]=x,e[11]=P):P=e[11];let $;e[12]!==v||e[13]!==P?($=s.jsxs("div",{className:"flex w-full items-baseline gap-2 px-0 pt-2 pb-1",children:[v,P]}),e[12]=v,e[13]=P,e[14]=$):$=e[14];let O;e[15]!==r||e[16]!==o?(O=s.jsx(M0,{highlights:r,onInsert:o}),e[15]=r,e[16]=o,e[17]=O):O=e[17];let M;e[18]!==x?(M=x("gitView.commit.messagePlaceholder"),e[18]=x,e[19]=M):M=e[19];const S=f!==null;let F;e[20]!==a||e[21]!==j||e[22]!==z||e[23]!==i||e[24]!==M||e[25]!==S?(F=s.jsx(D0,{value:a,onChange:i,placeholder:M,disabled:S,hasTouchInput:j,isMobile:z}),e[20]=a,e[21]=j,e[22]=z,e[23]=i,e[24]=M,e[25]=S,e[26]=F):F=e[26];let E;e[27]!==w||e[28]!==b||e[29]!==x?(E=w&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:b,className:"w-fit",type:"button",children:[s.jsx(K,{name:"emotion-happy",className:"size-4"}),x("gitView.commit.addGitmoji")]}),e[27]=w,e[28]=b,e[29]=x,e[30]=E):E=e[30];const D=c||f!==null||g||n===0;let W;e[31]!==x?(W=x("gitView.commit.generateAria"),e[31]=x,e[32]=W):W=e[32];let H;e[33]!==c?(H=c?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"ai-generate-2",className:"size-4 text-primary"}),e[33]=c,e[34]=H):H=e[34];let Z;e[35]!==x?(Z=x("gitView.commit.generate"),e[35]=x,e[36]=Z):Z=e[36];let Y;e[37]!==Z?(Y=s.jsx("span",{className:"commit-actions__label",children:Z}),e[37]=Z,e[38]=Y):Y=e[38];let A;e[39]!==d||e[40]!==D||e[41]!==W||e[42]!==H||e[43]!==Y?(A=s.jsxs(ee,{variant:"outline",size:"sm",onClick:d,disabled:D,type:"button","aria-label":W,className:"commit-actions__btn",children:[H,Y]}),e[39]=d,e[40]=D,e[41]=W,e[42]=H,e[43]=Y,e[44]=A):A=e[44];let X;e[45]===Symbol.for("react.memo_cache_sentinel")?(X=s.jsx("div",{className:"flex-1"}),e[45]=X):X=e[45];const te=!C||c;let T;e[46]!==x?(T=x("gitView.commit.commitAria"),e[46]=x,e[47]=T):T=e[47];let I;e[48]!==f||e[49]!==x?(I=f==="commit"?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"commit-actions__label",children:x("gitView.commit.committing")})]}):s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"git-commit",className:"size-4"}),s.jsx("span",{className:"commit-actions__label",children:x("gitView.commit.commit")})]}),e[48]=f,e[49]=x,e[50]=I):I=e[50];let B;e[51]!==p||e[52]!==te||e[53]!==T||e[54]!==I?(B=s.jsx(ee,{size:"sm",variant:"outline",onClick:p,disabled:te,className:"commit-actions__btn whitespace-nowrap","aria-label":T,children:I}),e[51]=p,e[52]=te,e[53]=T,e[54]=I,e[55]=B):B=e[55];let L;e[56]!==C||e[57]!==f||e[58]!==c||e[59]!==z||e[60]!==u||e[61]!==x?(L=z?s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(ee,{variant:"default",size:"sm",onClick:()=>u(),disabled:!C||c,className:"h-7 w-7 p-0","aria-label":x("gitView.commit.pushAria"),children:f==="commitAndPush"?s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(K,{name:"arrow-up",className:"size-3.5"})})}),s.jsx(ks,{side:"top",children:s.jsx("p",{children:x("gitView.commit.push")})})]}):s.jsx(ee,{size:"sm",variant:"default",onClick:()=>u(),disabled:!C||c,className:"commit-actions__btn","aria-label":x("gitView.commit.pushAria"),children:f==="commitAndPush"?s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}),s.jsx("span",{className:"commit-actions__label commit-actions__label--push",children:x("gitView.commit.pushing")})]}):s.jsxs(s.Fragment,{children:[s.jsx(K,{name:"arrow-up",className:"size-3.5"}),s.jsx("span",{className:"commit-actions__label commit-actions__label--push",children:x("gitView.commit.push")})]})}),e[56]=C,e[57]=f,e[58]=c,e[59]=z,e[60]=u,e[61]=x,e[62]=L):L=e[62];let V;e[63]!==A||e[64]!==B||e[65]!==L?(V=s.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[A,X,B,L]}),e[63]=A,e[64]=B,e[65]=L,e[66]=V):V=e[66];let Q;e[67]!==F||e[68]!==E||e[69]!==V||e[70]!==O?(Q=s.jsxs("div",{className:"flex flex-col gap-3 px-0 pt-1 pb-3",children:[O,F,E,V]}),e[67]=F,e[68]=E,e[69]=V,e[70]=O,e[71]=Q):Q=e[71];let G;return e[72]!==Q||e[73]!==$?(G=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[$,Q]}),e[72]=Q,e[73]=$,e[74]=G):G=e[74],G},Wd=5e5,F0=`
46
- :host {
47
- font-family: var(--font-mono);
48
- font-size: var(--text-code);
49
- }
50
-
51
- pre, [data-code] {
52
- font-family: var(--font-mono);
53
- font-size: var(--text-code);
54
- }
55
-
56
- /* Mobile touch selection support */
57
- [data-line-number] {
58
- touch-action: manipulation;
59
- -webkit-tap-highlight-color: transparent;
60
- cursor: pointer;
61
- }
62
-
63
- /* Ensure interactive line numbers work on touch */
64
- pre[data-interactive-line-numbers] [data-line-number] {
65
- touch-action: manipulation;
66
- }
67
- `,O0=`
68
- ${F0}
69
-
70
- :host {
71
- --diffs-bg-separator-override: var(--surface-elevated);
72
- }
73
-
74
- [data-diff-header],
75
- [data-diff] {
76
- [data-separator] {
77
- height: 24px !important;
78
- }
79
- }
80
-
81
- [data-separator="line-info-basic"] {
82
- height: 24px !important;
83
- background: var(--diffs-bg) !important;
84
- position: relative;
85
- }
86
-
87
- [data-diff-type="single"] [data-gutter],
88
- [data-diff-type="split"] [data-deletions] [data-gutter] {
89
- [data-separator-wrapper] {
90
- position: absolute;
91
- left: 100%;
92
- display: flex;
93
- align-items: center;
94
- gap: unset;
95
- width: max-content;
96
- background: transparent;
97
- color: var(--diffs-fg-number);
98
- font-family: var(--diffs-header-font-family, var(--font-sans));
99
- font-size: 0.75rem;
100
- line-height: 1;
101
- margin-left: calc(-2ch - 2px);
102
- }
103
-
104
- [data-separator-wrapper][data-separator-multi-button] {
105
- margin-left: calc(-3ch - 2px);
106
- }
107
-
108
- [data-expand-button],
109
- [data-separator-content] {
110
- display: block;
111
- align-self: unset;
112
- min-width: unset;
113
- min-height: unset;
114
- padding: 0;
115
- flex-shrink: 0;
116
- grid-column: unset;
117
- border: none;
118
- width: auto;
119
- height: auto;
120
- background-color: transparent;
121
- color: inherit;
122
- font: inherit;
123
- }
124
-
125
- [data-expand-button]:not([data-expand-all-button]) {
126
- &[data-expand-down]::before {
127
- content: '\\2191';
128
- }
129
-
130
- &[data-expand-up]::before {
131
- content: '\\2193';
132
- }
133
-
134
- &[data-expand-both]::before {
135
- content: '\\2195';
136
- }
137
-
138
- svg {
139
- display: none;
140
- }
141
- }
142
-
143
- [data-separator-content] {
144
- background: transparent;
145
- margin-left: calc(2px + 1ch);
146
- }
147
-
148
- [data-expand-all-button] {
149
- position: relative;
150
- margin-left: 14px;
151
- text-transform: lowercase;
152
- }
153
-
154
- [data-expand-all-button]::before {
155
- content: '';
156
- display: block;
157
- position: absolute;
158
- top: 50%;
159
- left: -8px;
160
- margin-top: -1px;
161
- width: 3px;
162
- height: 3px;
163
- border-radius: 2px;
164
- background-color: var(--diffs-fg-number);
165
- pointer-events: none;
166
- }
167
-
168
- [data-separator-content]:hover,
169
- [data-expand-button]:hover,
170
- [data-expand-all-button]:hover {
171
- color: var(--diffs-fg);
172
- }
173
-
174
- [data-expand-all-button]:hover {
175
- text-decoration: underline;
176
- }
177
- }
178
- `;function z0(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=e+((e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24))>>>0;return e.toString(16)}function Gd(t){const e=t.length>400?`${t.slice(0,200)}${t.slice(-200)}`:t;return`${t.length}:${z0(e)}`}const K0=(t,e,n,a)=>{const i=a.side==="deletions",o=(n?(i?n.deletionLines:n.additionLines).join(""):i?t:e).split(`
179
- `),d=Math.min(a.start,a.end),c=Math.max(a.start,a.end),p=Math.max(1,d),u=Math.min(o.length,c);return p>u?"":o.slice(p-1,u).join(`
180
- `)},B0=(t,e)=>t===e?!0:!t||!e?!1:t.start===e.start&&t.end===e.end&&t.side===e.side,_0=t=>t==="auto"||t==="scroll"||t==="overlay",U0=t=>{let e=t?.parentElement??null;for(;e;){const n=window.getComputedStyle(e);if(_0(n.overflowY))return e;e=e.parentElement}return null},$0=(t,e)=>{if(!t||!e||typeof window>"u")return()=>{};const n=U0(t);if(!n)return()=>{};const a=e.getBoundingClientRect().height;if(!a)return()=>{};const i=t.getBoundingClientRect().top-n.getBoundingClientRect().top,r=e.style.minHeight;e.style.minHeight=`${Math.ceil(a)}px`;let o=!1;return()=>{if(o)return;o=!0,e.style.minHeight=r;const c=t.getBoundingClientRect().top-n.getBoundingClientRect().top-i;c&&(n.scrollTop+=c)}},V0=(t,e)=>{if(typeof window>"u")return()=>{};let n=null,a=null,i=!1;const r=()=>{i||(a?.disconnect(),a=null,n=window.requestAnimationFrame(()=>{n=window.requestAnimationFrame(()=>{i||e()})}))},o=()=>t.querySelector("diffs-container")?.shadowRoot??void 0,d=(c=o())=>!!c?.querySelector("[data-line]");return d()?r():typeof MutationObserver<"u"?(a=new MutationObserver(()=>{const c=o();if(c){if(d(c)){r();return}a?.disconnect(),a=new MutationObserver(()=>{d(c)&&r()}),a.observe(c,{childList:!0,subtree:!0})}}),a.observe(t,{childList:!0,subtree:!0})):n=window.requestAnimationFrame(r),()=>{i=!0,a?.disconnect(),n!==null&&window.cancelAnimationFrame(n)}},Ji=new WeakMap,H0={lineHeight:24,hunkSeparatorHeight:24,spacing:0};function W0(t){const e=t.closest("[data-diff-virtual-root]");if(e instanceof HTMLElement){const n=e.querySelector("[data-diff-virtual-content]");return{key:e,root:e,content:n instanceof HTMLElement?n:void 0}}return{key:document,root:document,content:void 0}}function G0(t){if(typeof document>"u")return null;const e=W0(t);let n=Ji.get(e.key);if(!n){const i=new eh;i.setup(e.root,e.content),n={virtualizer:i,refs:0},Ji.set(e.key,n)}n.refs+=1;let a=!1;return{virtualizer:n.virtualizer,root:e.root,release:()=>{if(a)return;a=!0;const i=Ji.get(e.key);i&&(i.refs-=1,!(i.refs>0)&&(i.virtualizer.cleanUp(),Ji.delete(e.key)))}}}const q0=(t,e,n)=>{if(typeof window>"u")return()=>{};const a=[],i=()=>{try{t.rerender()}catch{}const r=e?.root;r instanceof HTMLElement?r.dispatchEvent(new Event("scroll",{bubbles:!1})):document.dispatchEvent(new Event("scroll",{bubbles:!1})),window.dispatchEvent(new Event("resize")),n()};return a.push(window.requestAnimationFrame(i)),a.push(window.requestAnimationFrame(()=>{a.push(window.requestAnimationFrame(i))})),()=>{for(const r of a)window.cancelAnimationFrame(r)}},dS=({original:t,modified:e,fileDiff:n,language:a,fileName:i,renderSideBySide:r,wrapLines:o,layout:d="fill",enableComments:c=!0})=>{const p=wr(),u=p?.currentTheme.metadata.variant==="dark",f=p?.availableThemes.find(ie=>ie.metadata.id===p.lightThemeId)??mr(!1),m=p?.availableThemes.find(ie=>ie.metadata.id===p.darkThemeId)??mr(!0),{isMobile:w}=Vs(),b=Au({source:"diff",fileLabel:i||"unknown",language:a,getCodeForRange:ie=>K0(t,e,n,ie),toStoreRange:ie=>({startLine:ie.start,endLine:ie.end,side:ie.side==="deletions"?"original":"modified"}),fromDraftRange:ie=>({start:ie.startLine,end:ie.endLine,side:ie.side==="original"?"deletions":"additions"})}),{drafts:g,selection:x,setSelection:k,commentText:y,setCommentText:C,editingDraftId:z,saveComment:j,cancel:N,startEdit:v,deleteDraft:P}=b,$=we.useRef(null),O=we.useRef(null),M=we.useRef(""),S=we.useRef(!1),F=we.useRef(null);we.useEffect(()=>{$.current=x},[x]),we.useEffect(()=>{O.current=z},[z]),we.useEffect(()=>{M.current=y},[y]);const E=we.useCallback(ie=>{if(!c||S.current)return;const le=$.current;if(!(!ie&&le&&M.current.trim())){if(w&&le&&ie&&ie.side===le.side){const de=Math.min(le.start,ie.start),he=Math.max(le.end,ie.end);k({...ie,start:de,end:he})}else k(ie);ie&&(O.current||C(""))}},[c,w,C,k]),D=we.useCallback(()=>{N()},[N]),W=we.useCallback(ie=>{const le=document.createElement("div");le.style.position="relative";const de=sr(ie.metadata);return le.dataset.annotationId=de,le.dataset.annotationSide=ie.side,le.dataset.annotationLine=String(ie.lineNumber),le},[]),H=we.useCallback((ie,le)=>{j(ie,le??x??void 0)},[j,x]),Z=we.useCallback(ie=>{k(ie);const le=I.current;if(le)try{S.current=!0,le.setSelectedLines(ie),F.current=ie}catch{}finally{S.current=!1}},[k]),Y=we.useCallback(ie=>{const le=ie.closest("[data-line-type]")?.getAttribute("data-line-type")??ie.getAttribute("data-line-type");if(le==="change-deletion")return"deletions";if(le==="change-addition")return"additions";const de=ie.getAttribute("data-column-side")??ie.getAttribute("data-side")??ie.closest("[data-column-side]")?.getAttribute("data-column-side");if(de==="deletions"||de==="left"||de==="original")return"deletions";if(de==="additions"||de==="right"||de==="modified")return"additions";const he=ie.closest("[data-line-type]");if(he instanceof HTMLElement){const Me=he.getBoundingClientRect(),Le=ie.getBoundingClientRect(),Be=Me.left+Me.width/2;return Le.left+Le.width/2<Be?"deletions":"additions"}return"additions"},[]);cr(f),cr(m);const A=`${f.metadata.id}:${m.metadata.id}:${u?"dark":"light"}`,X=we.useMemo(()=>{if(n){const ie=n.deletionLines.reduce((de,he)=>de+he.length,0),le=n.additionLines.reduce((de,he)=>de+he.length,0);return Math.max(ie,le)>Wd}return Math.max(t.length,e.length)>Wd},[n,e.length,t.length]),te=we.useRef(null),T=we.useRef(null),I=we.useRef(null),B=we.useRef(null),L=we.useRef(null),V=we.useRef(null),Q=we.useRef(void 0),G=we.useRef(void 0),ue=we.useRef(void 0),ne=we.useRef(void 0),[,xe]=l.useReducer(ie=>ie+1,0),ve=Ko(X?"unified":r?"split":"unified"),me=we.useMemo(()=>ur(f),[f]),ge=we.useMemo(()=>ur(m),[m]);l.useLayoutEffect(()=>{const ie=te.current;if(!ie)return;const le=ie.querySelector("diffs-container");if(!le)return;const de=u?ge:me,he=(Ke,Oe)=>Ke.colors?.[Oe],Me=he(me,"terminal.ansiGreen"),Le=he(me,"terminal.ansiRed"),Be=he(me,"terminal.ansiBlue"),Fe=he(ge,"terminal.ansiGreen"),De=he(ge,"terminal.ansiRed"),ze=he(ge,"terminal.ansiBlue");le.style.setProperty("--shiki-light",me.fg),le.style.setProperty("--shiki-light-bg",me.bg),Me&&le.style.setProperty("--shiki-light-addition-color",Me),Le&&le.style.setProperty("--shiki-light-deletion-color",Le),Be&&le.style.setProperty("--shiki-light-modified-color",Be),le.style.setProperty("--shiki-dark",ge.fg),le.style.setProperty("--shiki-dark-bg",ge.bg),Fe&&le.style.setProperty("--shiki-dark-addition-color",Fe),De&&le.style.setProperty("--shiki-dark-deletion-color",De),ze&&le.style.setProperty("--shiki-dark-modified-color",ze),le.style.setProperty("--diffs-bg",de.bg),le.style.setProperty("--diffs-fg",de.fg);const Ve=u?Fe:Me,We=u?De:Le,_e=u?ze:Be;Ve&&le.style.setProperty("--diffs-addition-color-override",Ve),We&&le.style.setProperty("--diffs-deletion-color-override",We),_e&&le.style.setProperty("--diffs-modified-color-override",_e);const He=le.shadowRoot?.querySelector("pre");He&&(He.style.setProperty("--shiki-light",me.fg),He.style.setProperty("--shiki-light-bg",me.bg),Me&&He.style.setProperty("--shiki-light-addition-color",Me),Le&&He.style.setProperty("--shiki-light-deletion-color",Le),Be&&He.style.setProperty("--shiki-light-modified-color",Be),He.style.setProperty("--shiki-dark",ge.fg),He.style.setProperty("--shiki-dark-bg",ge.bg),Fe&&He.style.setProperty("--shiki-dark-addition-color",Fe),De&&He.style.setProperty("--shiki-dark-deletion-color",De),ze&&He.style.setProperty("--shiki-dark-modified-color",ze),He.style.setProperty("--diffs-bg",de.bg),He.style.setProperty("--diffs-fg",de.fg),Ve&&He.style.setProperty("--diffs-addition-color-override",Ve),We&&He.style.setProperty("--diffs-deletion-color-override",We),_e&&He.style.setProperty("--diffs-modified-color-override",_e))},[ge,A,u,me]);const Ie=we.useMemo(()=>({theme:{dark:m.metadata.id,light:f.metadata.id},themeType:u?"dark":"light",diffStyle:r?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info-basic",lineDiffType:"none",maxLineDiffLength:X?0:1e3,maxLineLengthForHighlighting:X?1:1e3,tokenizeMaxLineLength:X?1:1e3,collapsedContextThreshold:0,expansionLineCount:20,overflow:o?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:c,enableHoverUtility:!1,onLineSelected:c?E:void 0,unsafeCSS:O0,renderAnnotation:c?W:void 0}),[m.metadata.id,c,u,X,f.metadata.id,r,o,E,W]),oe=we.useMemo(()=>c?nx({drafts:g,editingDraftId:z,selection:x}):[],[z,c,g,x]),ce=we.useRef(oe);if(we.useEffect(()=>{ce.current=oe},[oe]),we.useEffect(()=>{const ie=T.current;return()=>{I.current?.cleanUp(),I.current=null,B.current?.release(),B.current=null,L.current=null,V.current=null,Q.current=void 0,G.current=void 0,ue.current=void 0,ne.current=void 0,ie&&(ie.innerHTML="")}},[]),we.useEffect(()=>{if(typeof window>"u")return;const ie=T.current,le=te.current;if(!ie||!ve)return;const de=$0(le,ie);let he=B.current;he||(he=G0(ie),B.current=he),B.current=he;const Me=he?.virtualizer??null,Le=n?void 0:{name:i||"",contents:t,lang:a,cacheKey:`old:${A}:${i}:${Gd(t)}`},Be=n?void 0:{name:i||"",contents:e,lang:a,cacheKey:`new:${A}:${i}:${Gd(e)}`},Fe=n?G.current!==n:G.current!==void 0||!Le||!Be||!ue.current||!ne.current||!ec(ue.current,Le)||!ec(ne.current,Be),De=I.current,ze=!!(De&&(L.current!==Me||V.current!==ve||Me&&(Q.current!==Ie.hunkSeparators||Fe)));ze&&(De?.cleanUp(),I.current=null,ie.innerHTML="");let Ve=I.current;const We=!ze&&De?!Qf(De.options,Ie):!1;if(Ve?Ve.setOptions(Ie):(Ve=he?new Xf(Ie,he.virtualizer,H0,ve):new Zf(Ie,ve),I.current=Ve,F.current=null),L.current=Me,V.current=ve,Q.current=Me?Ie.hunkSeparators:void 0,G.current=n,ue.current=Le,ne.current=Be,n)Ve.render({fileDiff:n,forceRender:We,lineAnnotations:ce.current,containerWrapper:ie});else{if(!Le||!Be)return;Ve.render({oldFile:Le,newFile:Be,forceRender:We,lineAnnotations:ce.current,containerWrapper:ie})}const _e=V0(ie,()=>{de(),q0(Ve,he,xe)});return()=>{_e(),de()}},[A,n,i,a,e,Ie,t,ve]),we.useEffect(()=>{const ie=I.current;if(ie){try{ie.setLineAnnotations(oe)}catch(le){console.error("Failed to apply diff line annotations",le);try{ie.setLineAnnotations([])}catch{}}requestAnimationFrame(()=>{if(I.current===ie){try{ie.rerender()}catch{}xe()}})}},[oe]),we.useEffect(()=>{const ie=I.current;if(!ie||x!==null)return;const le=F.current;if(!B0(x,le))try{S.current=!0,ie.setSelectedLines(x),F.current=x}catch{}finally{S.current=!1}},[x]),we.useEffect(()=>{if(!c)return;const ie=T.current;if(!ie)return;let le=null,de=()=>{};const he=()=>{const Le=ie.querySelector("diffs-container")?.shadowRoot;if(!Le){le=requestAnimationFrame(he);return}const Be=Fe=>{if(!(Fe instanceof MouseEvent)||Fe.button!==0||!(Fe.target instanceof Element))return;const De=Fe.target.closest("[data-column-number]");if(!(De instanceof HTMLElement))return;const ze=De.getAttribute("data-column-number"),Ve=ze?parseInt(ze,10):NaN;if(Number.isNaN(Ve))return;const We=Y(De);E({start:Ve,end:Ve,side:We}),Fe.preventDefault(),Fe.stopPropagation()};Le.addEventListener("click",Be,!0),de=()=>{Le.removeEventListener("click",Be,!0)}};return he(),()=>{le!==null&&cancelAnimationFrame(le),de()}},[A,c,i,E,Y]),we.useEffect(()=>{const ie=T.current;if(!ie)return;let le=null,de=null;const Me=setTimeout(()=>{const Le=ie.querySelector("diffs-container");if(!(Le instanceof HTMLElement))return;const Be=Le.shadowRoot;le=new MutationObserver(()=>{de&&cancelAnimationFrame(de),de=requestAnimationFrame(()=>{xe(),de=null})}),le.observe(Le,{childList:!0,subtree:!0}),Be&&le.observe(Be,{childList:!0,subtree:!0})},100);return()=>{clearTimeout(Me),de&&cancelAnimationFrame(de),le?.disconnect()}},[A,i]),typeof window>"u")return null;const pe=c?s.jsx(ix,{diffRootRef:te,drafts:g,selection:x,editingDraftId:z,commentText:y,onTextChange:C,fileLabel:i?.split("/").pop()??"",onSave:H,onCancel:D,onEdit:ie=>{Z({start:ie.startLine,end:ie.endLine,side:ie.side==="original"?"deletions":"additions"}),v(ie)},onDelete:P}):null;return d==="fill"?s.jsx("div",{className:fe("flex flex-col relative","size-full"),"data-diff-virtual-root":!0,children:s.jsxs("div",{className:"flex-1 relative min-h-0",children:[s.jsx(Os,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,"data-diff-virtual-content":!0,children:s.jsx("div",{ref:te,className:"size-full relative",children:s.jsx("div",{ref:T,className:"size-full"})})}),pe]})}):s.jsxs("div",{className:fe("relative","w-full"),children:[s.jsx("div",{ref:te,className:"pierre-diff-wrapper w-full overflow-x-auto overflow-y-visible relative",children:s.jsx("div",{ref:T,className:"w-full"})}),pe]})},J0=9e4,Y0=15e3,Q0=5*6e4,X0=[2e3,5e3],Z0=6e4,eN=2*6e4,tN=5*6e4,sN=4,qd=720*6e4,nN="openchamber.github-pr-status",br=200,aN=t=>t==="closed"||t==="merged",iN=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},rN=t=>iN(t)?Z0:t?.checks&&t.checks.state!=="pending"?tN:eN,oN=(t,e,n)=>JSON.stringify([mn(),t,e,n??"auto"]),Aa=new Map,Ea=new Map,dn=new Map,To=new Map;let Yi=0;const lN=2;let yr=0;const km=[],cN=()=>yr<lN?(yr+=1,Promise.resolve()):new Promise(t=>{km.push(t)}),dN=()=>{const t=km.shift();if(t){t();return}yr=Math.max(0,yr-1)},La=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null,paramsRevision:0}),vr=t=>t?.params?.directory&&t.params.branch?{directory:t.params.directory,branch:t.params.branch,runtimeKey:t.params.runtimeKey??t.identity?.runtimeKey??mn(),remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null}:!t?.identity?.directory||!t.identity.branch?null:t.identity,vl=t=>{const e=vr(t);return!e?.directory||!e.branch?null:JSON.stringify([e.runtimeKey,e.directory,e.branch,e.remoteName??"auto"])},al=t=>{try{const e=JSON.parse(t);if(!Array.isArray(e)||e.length!==4||e.some(o=>typeof o!="string"))return null;const[n,a,i,r]=e;return{runtimeKey:n,directory:a,branch:i,remote:r}}catch{return null}},uN=(t,e)=>{const n=al(e);if(!n)return null;let a=null;for(const[i,r]of Object.entries(t)){if(i===e||!r.isInitialStatusResolved||!r.status)continue;const o=al(i);if(!o||o.runtimeKey!==n.runtimeKey||o.directory!==n.directory||o.branch!==n.branch)continue;const d=r.resolvedRemoteName??r.status.resolvedRemoteName??null;if(!(n.remote!=="auto"&&d&&d!==n.remote)){if(o.remote==="auto")return r;a=a??r}}return a},uS=(t,e,n)=>{const a=mn();let i=null;for(const[r,o]of Object.entries(t)){if(!o.status)continue;const d=al(r);!d||d.runtimeKey!==a||d.directory!==e||d.branch!==n||(!i||o.lastRefreshAt>i.lastRefreshAt)&&(i=o)}return i?.status??null},Nm=(t,e)=>Object.entries(t).filter(([,n])=>vl(n)===e).map(([n])=>n),mN=(t,e)=>{const n=e.runtimeKey??mn(),a=e.remoteName??t.params?.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null,i=!t.params||t.params.runtimeKey!==n||t.params.directory!==e.directory||t.params.branch!==e.branch||t.params.remoteName!==a||t.params.canShow!==e.canShow||t.params.github!==e.github||t.params.githubAuthChecked!==e.githubAuthChecked||t.params.githubConnected!==e.githubConnected;return{...t,paramsRevision:i?t.paramsRevision+1:t.paramsRevision,...i?{isLoading:!1,error:null}:{},params:t.params?{...t.params,...e,runtimeKey:n,remoteName:a}:{...e,runtimeKey:n,remoteName:a},identity:{runtimeKey:n,directory:e.directory,branch:e.branch,remoteName:a}}},Qi=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},pN=(t,e,n)=>{const a=Nm(t,e),i=a.map(c=>Qi(t[c])).filter(c=>!!c);if(i.length===0)return null;const r=Qi(t[n]);if(r&&vl(t[n])===e)return r;const o=a.map(c=>t[c]).find(c=>!!(c?.resolvedRemoteName&&Qi(c)));if(o)return Qi(o);const d=i.find(c=>!!c.remoteName);return d||(i[0]??null)},gN=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:vr(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),fN=t=>({...La(),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}),hN=t=>{const e=Object.entries(t);return e.length<=br?t:Object.fromEntries(e.sort(([,n],[,a])=>{const i=n.watchers>0||n.isLoading,r=a.watchers>0||a.isLoading;return i!==r?i?-1:1:Math.max(a.lastRefreshAt,a.lastDiscoveryPollAt)-Math.max(n.lastRefreshAt,n.lastDiscoveryPollAt)}).slice(0,br))},Sm=gn()(bi((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,resetForRuntimeSwitch:()=>{Yi+=1;for(const n of Aa.values())window.clearInterval(n);for(const n of Ea.values())n.forEach(a=>window.clearTimeout(a));Aa.clear(),Ea.clear(),dn.clear(),To.clear(),t(n=>({activeRequestCount:0,entries:Object.fromEntries(Object.entries(n.entries).map(([a,i])=>[a,{...i,watchers:0,isLoading:!1,params:null,paramsRevision:i.paramsRevision+1}]))}))},ensureEntry:n=>{t(a=>{if(a.entries[n])return a;const i=uN(a.entries,n),r=i?{...La(),status:i.status,isInitialStatusResolved:!0,resolvedRemoteName:i.resolvedRemoteName??i.status?.resolvedRemoteName??null}:La();return{entries:hN({...a.entries,[n]:r})}})},setParams:(n,a)=>{t(i=>{const r=i.entries[n]??La();return{entries:{...i.entries,[n]:mN(r,a)}}})},startWatching:n=>{if(t(r=>{const o=r.entries[n]??La();return{entries:{...r.entries,[n]:{...o,watchers:o.watchers+1}}}}),Aa.has(n))return;const a=r=>{const o=window.setTimeout(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const c=e().entries[n];!c||c.watchers<=0||c.status?.pr||e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0})},r),d=Ea.get(n)??[];d.push(o),Ea.set(n,d)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),X0.forEach(r=>a(r));const i=window.setInterval(()=>{if(typeof document<"u"&&document.visibilityState!=="visible")return;const r=e().entries[n];if(!r||r.watchers<=0)return;if(!!!r.status?.pr){const p=Date.now();if(p-r.lastDiscoveryPollAt<Q0)return;t(u=>{const f=u.entries[n];return f?{entries:{...u.entries,[n]:{...f,lastDiscoveryPollAt:p}}}:u}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(aN(r.status?.pr?.state))return;const d=Date.now()-r.lastRefreshAt,c=rN(r.status);d<c||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},Y0);Aa.set(n,i)},stopWatching:n=>{t(o=>{const d=o.entries[n];if(!d)return o;const c=Math.max(0,d.watchers-1);return{entries:{...o.entries,[n]:{...d,watchers:c}}}});const a=e().entries[n];if(a&&a.watchers>0)return;const i=Aa.get(n);typeof i=="number"&&window.clearInterval(i),Aa.delete(n);const r=Ea.get(n);r&&r.length>0&&r.forEach(o=>{window.clearTimeout(o)}),Ea.delete(n)},refresh:async(n,a)=>{const i=e(),r=i.entries[n],o=vl(r);if(!r||!o)return;const d=Nm(i.entries,o),c=d.some(x=>!!i.entries[x]?.status?.pr);if(a?.onlyExistingPr&&!c)return;const p=To.get(o)??0;if(!a?.force&&Date.now()-p<J0||dn.has(o))return;const u=pN(i.entries,o,n);if(!u)return;const f=Symbol(o),m=Yi,w=r.paramsRevision,b=r.params?.runtimeKey??r.identity?.runtimeKey??mn(),g=()=>m===Yi&&b===mn()&&dn.get(o)===f&&e().entries[n]?.paramsRevision===w;if(dn.set(o,f),t(x=>{const k={...x.entries};return d.forEach(y=>{const C=k[y];C&&(k[y]={...C,isLoading:a?.silent?C.isLoading:!0,error:null})}),{entries:k}}),u.githubAuthChecked&&u.githubConnected===!1){if(!g())return;t(x=>{const k={...x.entries};return d.forEach(y=>{const C=k[y];C&&(k[y]={...C,status:{connected:!1},error:null,isLoading:a?.silent?C.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?C.isInitialStatusResolved:!0})}),{entries:k}}),dn.get(o)===f&&dn.delete(o);return}if(!u.github?.prStatus){if(!g())return;t(x=>{const k={...x.entries};return d.forEach(y=>{const C=k[y];C&&(k[y]={...C,status:null,error:"GitHub runtime API unavailable",isLoading:a?.silent?C.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?C.isInitialStatusResolved:!0})}),{entries:k}}),dn.get(o)===f&&dn.delete(o);return}try{t(k=>({...k,activeRequestCount:k.activeRequestCount+1,totalRequestCount:k.totalRequestCount+1})),await cN();let x;try{if(!g())return;To.set(o,Date.now()),x=await u.github.prStatus(u.directory,u.branch,u.remoteName??void 0,{force:a?.force})}finally{dN()}if(!g())return;t(k=>{const y={...k.entries};return d.forEach(C=>{const z=y[C];if(!z)return;const j=z.status?.fetchedAt,N=x.fetchedAt;if(typeof j=="number"&&typeof N=="number"&&N<j){y[C]={...z,error:null,isLoading:a?.silent?z.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?z.isInitialStatusResolved:!0,lastRefreshAt:Date.now()};return}const v=z.status?.pr,P=x.pr,O=!!(P&&v&&P.number===v.number&&(!P.body||!P.body.trim())&&typeof v.body=="string"&&v.body.trim().length>0)&&P&&v?.body?{...x,pr:{...P,body:v.body}}:x,M=O.resolvedRemoteName??z.resolvedRemoteName??u.remoteName??null,S=vr(z)??{runtimeKey:b,directory:u.directory,branch:u.branch,remoteName:u.remoteName??null};y[C]={...z,status:O,error:null,isLoading:a?.silent?z.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?z.isInitialStatusResolved:!0,lastRefreshAt:Date.now(),resolvedRemoteName:M,identity:{...S,remoteName:M??S.remoteName??null}}}),{entries:y}})}catch(x){if(!g())return;const k=x instanceof Error?x.message:String(x);t(y=>{const C={...y.entries};return d.forEach(z=>{const j=C[z];j&&(C[z]={...j,error:k||"Failed to load PR status",isLoading:a?.silent?j.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?j.isInitialStatusResolved:!0})}),{entries:C}})}finally{dn.get(o)===f&&dn.delete(o),m===Yi&&t(x=>({...x,activeRequestCount:Math.max(0,x.activeRequestCount-1)}))}},refreshTargets:async(n,a)=>{const i=Array.from(new Set(n.map(r=>{const o=r.directory.trim(),d=r.branch.trim();return!o||!d?null:oN(o,d,r.remoteName??null)}).filter(r=>!!r)));await xg(i,sN,r=>e().refresh(r,a))},updateStatus:(n,a)=>{t(i=>{const r=i.entries[n]??La();return{entries:{...i.entries,[n]:{...r,status:a(r.status)}}}})}}),{name:nN,storage:Ir(),version:2,migrate:(t,e)=>e<2?{entries:{}}:t,partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=vr(e);if(!n?.directory||!n.branch)return!1;const a=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return a>0&&Date.now()-a<qd}).sort(([,e],[,n])=>Math.max(n.lastRefreshAt,n.lastDiscoveryPollAt)-Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt)).slice(0,br).map(([e,n])=>[e,gN(n)]))}),merge:(t,e)=>{const n=t?.entries??{};return{...e,entries:Object.fromEntries(Object.entries(n).filter(([,i])=>!!(i.identity?.runtimeKey&&Math.max(i.lastRefreshAt,i.lastDiscoveryPollAt)>0&&Date.now()-Math.max(i.lastRefreshAt,i.lastDiscoveryPollAt)<qd)).slice(0,br).map(([i,r])=>[i,fN(r)]))}}})),xN=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",a=typeof e.mergeableState=="string"?e.mergeableState:"",i=e.mergeable===!1||a==="blocked"||a==="dirty";return n||i?"blocked":"open"},bN=t=>{const e=xN(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}},yN=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??""}`,vN=300,Da=new Map,mS=t=>{const e=tt.c(2);let n;return e[0]!==t?(n=a=>{if(!t)return null;const i=a.entries[t],r=i?bN(i):null;if(!r)return Da.delete(t),null;const o=yN(r),d=Da.get(t);if(d&&d.sig===o)return d.summary;if(!d&&Da.size>=vN){const c=Da.keys().next().value;c!==void 0&&Da.delete(c)}return Da.set(t,{sig:o,summary:r}),r},e[0]=t,e[1]=n):n=e[1],Sm(n)},pS=()=>{mu(),Ps.reconnectToRuntimeBaseUrl(),lu()},gS=t=>{es.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),ke.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),t.previousRuntimeKey&&bg.getState().stopRunningRunsForRuntime(t.previousRuntimeKey),mu(),ss.getState().clearAll(),Ps.reconnectToRuntimeBaseUrl(),pt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),is.getState().resetForRuntimeSwitch(),Ro.getState().resetForRuntimeSwitch(),yg.setState({statusById:new Map}),vg(),wg.getState().reset(),sf.getState().resetForRuntimeSwitch(),Nr.getState().resetForRuntimeSwitch(t.runtimeKey),Sm.getState().resetForRuntimeSwitch(),jg.getState().resetForRuntimeSwitch(t.runtimeKey),nf.getState().resetForRuntimeSwitch(t.runtimeKey),es.getState().restoreForRuntimeSwitch(t.runtimeKey),ke.getState().restoreForRuntimeSwitch(t.runtimeKey),lu(),queueMicrotask(()=>{af()})};export{Gn as $,Iu as A,Zw as B,lS as C,nS as D,ca as E,da as F,ua as G,XN as H,Cw as I,Iw as J,cc as K,$s as L,Aj as M,aS as N,HN as O,dS as P,Jn as Q,Sm as R,Nk as S,oS as T,Xw as U,uS as V,sS as W,oN as X,qn as Y,qN as Z,An as _,qt as a,Wn as a0,dm as a1,mm as a2,Lv as a3,mS as a4,vv as a5,xo as a6,Fk as a7,N1 as a8,VN as a9,Db as aa,zu as ab,Bo as ac,Ab as ad,Au as ae,Uo as af,$o as ag,Du as ah,sx as ai,_o as aj,Pu as ak,ZN as al,Ew as b,cS as c,ma as d,rS as e,ws as f,od as g,_a as h,iS as i,gS as j,tS as k,eS as l,WN as m,GN as n,JN as o,Bj as p,$N as q,pS as r,Ss as s,ss as t,Su as u,jv as v,wv as w,YN as x,QN as y,Hu as z};