@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.
- package/dist/assets/{DiagramView-1-LZVuzn.js → DiagramView-DZmf30ko.js} +1 -1
- package/dist/assets/{FilesView-BDRX8vU2.js → FilesView-cJPeFhDe.js} +6 -6
- package/dist/assets/{MarkdownRendererImpl-fZSdR7PD.js → MarkdownRendererImpl-DZezL90a.js} +1 -1
- package/dist/assets/{OnboardingScreen-D81UrlA4.js → OnboardingScreen-ChYr0xqs.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-cSK3t3TR.js → SessionSwitcherDropdown-BV7FfPbT.js} +1 -1
- package/dist/assets/{SettingsWindow-CozowJLm.js → SettingsWindow-UybkBD1p.js} +1 -1
- package/dist/assets/{contextPanelEmbeddedChat-CQYNvKbk.js → contextPanelEmbeddedChat-DW3atb4h.js} +1 -1
- package/dist/assets/{de-C2n4oo1Z.js → de-rVJ-hXrd.js} +3 -3
- package/dist/assets/es-D7ZyOToq.js +15 -0
- package/dist/assets/{fr-DDFUp5jS.js → fr-hl5i-ZI0.js} +2 -2
- package/dist/assets/{index-BCCcokur.css → index-CL9MYe8V.css} +1 -1
- package/dist/assets/{ja-B7SxobKm.js → ja-DqakdvOp.js} +2 -2
- package/dist/assets/{ko-CWGq93SO.js → ko-dNl8A3Xf.js} +2 -2
- package/dist/assets/main-B5TIsU2y.js +209 -0
- package/dist/assets/{main-Cts0BwVk.js → main-_m6HD9-a.js} +2 -2
- package/dist/assets/{markdownCore-BqzEkymd.js → markdownCore-DpT1vbbv.js} +2 -2
- package/dist/assets/{miniChat-ChuQD2KK.js → miniChat-wYb8p9vG.js} +2 -2
- package/dist/assets/{mobile-c-CRD1Cz.js → mobile-ExXAVUcv.js} +2 -2
- package/dist/assets/{pl-DZmyxLo7.js → pl-C5HQx1Hf.js} +3 -3
- package/dist/assets/pt-BR-CNCoBDAM.js +15 -0
- package/dist/assets/{renderElectronMiniChatApp-9uaZAJjw.js → renderElectronMiniChatApp-DPDzIT8W.js} +2 -2
- package/dist/assets/{renderMobileApp-Dm1tmU2a.js → renderMobileApp-CzWvxR9e.js} +3 -3
- package/dist/assets/runtimeEndpointReset-DKzVWH1w.js +180 -0
- package/dist/assets/uk-Bn-3AMpk.js +15 -0
- package/dist/assets/{useAppFontEffects-pyTMaGQu.js → useAppFontEffects-DdvGxoPX.js} +133 -133
- package/dist/assets/zh-CN-BCwvQpZm.js +15 -0
- package/dist/assets/zh-TW-TRHrkN9l.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -2
- package/server/lib/openchamber-control/DOCUMENTATION.md +9 -1
- package/server/lib/openchamber-sessions/routes.js +117 -4
- package/server/lib/openchamber-sessions/routes.test.js +129 -16
- package/server/lib/opencode/DOCUMENTATION.md +2 -0
- package/server/lib/opencode/proxy.js +21 -3
- package/server/lib/small-model/DOCUMENTATION.md +11 -4
- package/server/lib/small-model/call.js +19 -3
- package/server/lib/small-model/call.test.js +9 -2
- package/server/lib/small-model/index.js +10 -1
- package/server/lib/small-model/index.test.js +20 -1
- package/server/lib/walkthrough/DOCUMENTATION.md +23 -0
- package/server/lib/walkthrough/index.js +17 -0
- package/server/lib/walkthrough/reproduce-2607.test.js +148 -0
- package/server/opencode-proxy.test.js +83 -0
- package/dist/assets/es-DP7jRKkr.js +0 -15
- package/dist/assets/main-Cqfcxvqq.js +0 -209
- package/dist/assets/pt-BR-BKR5oHQ7.js +0 -15
- package/dist/assets/runtimeEndpointReset-DL5z84w2.js +0 -180
- package/dist/assets/uk-D7oAI_Wc.js +0 -15
- package/dist/assets/zh-CN-Ddjz1_9w.js +0 -15
- package/dist/assets/zh-TW-D3X01YXj.js +0 -15
- /package/dist/assets/{index-ChZvuURI.js → index-DjZ4W8hy.js} +0 -0
|
@@ -0,0 +1,180 @@
|
|
|
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 Ze,j as s,r as ve,R as l,c as Zi}from"./vendor-react-BUCujlKS.js";import{dY as jr,dZ as dr,ay as Um,f as ot,o as Hn,bg as Kt,bh as Bt,bj as _t,I as K,bA as zs,cj as ur,g as fe,B as ee,aU as kr,aJ as oa,aR as xs,aS as ks,aQ as bs,bG as Do,c6 as rn,d_ as Nr,aO as Hs,t as Q,O as nu,d$ as _n,e0 as $m,e1 as Vm,dL as Hm,e2 as Wm,e3 as Gm,e4 as qm,v as es,e5 as Jm,d7 as Ym,d8 as Qm,d9 as Xm,aK as gs,aI as as,aN as fs,aM as hs,ci as Ns,Y as ol,cg as ui,e6 as Zm,e7 as Cl,e8 as ep,i as pt,e9 as Va,ck as la,ea as tp,dn as ll,cU as sp,bi as Ut,cm as au,ag as np,b as is,a0 as Sr,R as Ha,G as Wa,eb as ap,ec as ip,a6 as Ro,ed as Mo,ee as mr,bE as Un,ef as iu,eg as ru,j as cl,eh as rp,a8 as wn,ei as er,ej as tr,ek as sr,by as op,bz as lp,el as cp,em as za,bk as Yt,bl as rs,L as nt,en as bi,eo as Il,c0 as Mt,c1 as Lt,c2 as Wt,c3 as Ft,c4 as jt,ep as Wn,ds as Ms,eq as dp,er as ou,es as up,et as mp,eu as Cr,ev as In,ew as _a,ex as pp,ey as gp,ez as fp,eA as hp,eB as xp,eC as bp,eD as Sn,bu as lu,J as yp,H as cu,K as du,W as Pl,dk as vp,dG as uu,dv as mu,dx as wp,eE as jp,u as Lo,cF as kp,eF as Tl,eG as Np,eH as Sp,eI as Al,eJ as Cp,eK as Ip,eL as Pp,eM as Tp,aP as Ap,eN as Ep,N as Dp,Q as Rp,eO as Mp,eP as Lp,bU as Fp,P as ra,n as pu,m as Op,eQ as zp,eR as El,q as Kp,s as Bp,k as _p,b2 as Up,b3 as $p,b4 as gu,eS as Vr,eT as Dl,eU as Vp,eV as Hp,eW as Wp,eX as Gp,dy as Ir,af as Cn,eY as qp,eZ as Jp,e_ as Yp,e$ as Qp,f0 as Xp,f1 as Hr,f2 as Rl,f3 as Zp,f4 as eg,f5 as tg,f6 as sg,f7 as ng,f8 as Wr,f9 as ag,bf as Ml,fa as La,be as ig,fb as rg,fc as Ll,fd as Fl,fe as og,bH as Fo,bI as Oo,bJ as zo,bK as Ko,bL as Nn,bM as tn,c7 as Ka,M as gi,ff as Ol,cl as lg,fg as fu,c9 as cg,dC as dg,fh as Gr,cd as ug,fi as mg,fj as pg,dw as gg,fk as fg,fl as hg,bF as xg,fm as bg,fn as yg,fo as Ri,fp as vg,fq as zl,fr as Kl,fs as wg,cI as jg,ad as kg,a9 as Ng,V as Sg,ft as Cg,cK as Ig,fu as hu,dW as Pg,de as Tg,fv as Ag,fw as Eg,cN as Dg}from"./useAppFontEffects-DdvGxoPX.js";import{ad as pr,ae as Rg,af as Bl,ag as Mg,i as dl,ah as Lg,B as ds,Z as Pn,r as ht,u as je,x as Ga,b as xu,o as ul,a as pn,d as _l,L as It,k as Cs,m as an,ai as Pr,q as Ps,aj as Fg,ak as Ul,al as Js,e as qa,w as ls,H as $l,am as Vl,an as Hl,K as ei,p as Og,ao as zg,j as Kg,ap as Fa,aq as Bg,J as _g,ar as Ug,as as $g,at as Vg,s as Hg,au as Wg,av as bu,S as Gg,aw as qg,R as Jg,ax as Wl,ay as Yg,az as Qg,M as Xg,aA as Gl,aB as ql,aC as Jl,aD as fi,aE as Zg,aF as ef,aG as Yl,aH as ml,aI as yu,aJ as tf,aK as sf,aL as nf,aM as af,aN as rf,aO as of,ac as lf,aP as cf,aQ as df,aR as uf,a2 as mf,aS as ti,aT as vu,T as pf,l as gf,v as ff}from"./index-DjZ4W8hy.js";import{s as hf,d as xf,E as sn,e as bf,f as Ql,k as qr,V as wu,D as Tr,W as yf}from"./vendor-codemirror-view-DSzLbZiS.js";import{c as fn,u as Ws,d as Ja,p as vi,a as vf}from"./vendor-zustand-BAGL70zf.js";import{s as wf,p as jf}from"./vendor-yaml-3778uTud.js";import{E as kf,o as fa,k as pl,i as ju,S as Nf}from"./vendor-codemirror-state-CNWM3Q8V.js";import{h as Sf,j as Cf,k as If,l as Pf}from"./vendor-codemirror-commands-eyb3xW_0.js";import{i as Tf,x as Af,H as Xl,y as Mi,z as Ef}from"./vendor-codemirror-language-CTJVwiVf.js";import{a as Zl,g as gr,b as ec,c as tc,o as Df,d as Rf}from"./vendor-codemirror-search-8kyQdB3f.js";import{v as Mf,g as Lf}from"./vendor-replit-codemirror-vim-D0xSkRWg.js";import{a as $e,c as Ff}from"./vendor-lezer-highlight-CDMHUZ74.js";import{Q as ku}from"./vendor-qrcode-DTJ12-WC.js";import{c as Of,s as zf,i as Nu}from"./contextPanelEmbeddedChat-DW3atb4h.js";import{C as Kf,c as Bf,b as _f,d as Uf,S as $f,M as Vf,a as Hf,g as Wf,h as Gf,i as qf,j as Jf,k as Yf}from"./vendor-base-ui-BuzaMvKv.js";import{f as Su,h as Cu,P as Iu,k as Qf,D as Pu,j as Tu}from"./vendor-dnd-kit-core-BZknOX2w.js";import{u as Au,S as Eu,h as Xf,a as Zf,v as eh}from"./vendor-dnd-kit-sortable-CsEagZ81.js";import{C as Du}from"./vendor-dnd-kit-utilities-B_MdXhJC.js";import{_ as sc}from"./vendor-vite-runtime-DD1OZmLC.js";import{I as th,D as sh,q as nh}from"./vendor-ghostty-web-CfpAcbEe.js";import{u as ah}from"./vendor-tanstack-react-virtual-g05Cx3z9.js";import{W as ih,c as rh,d as nc,e as oh,V as lh,F as ch,f as dh}from"./vendor-pierre-diffs-B1TeaSIY.js";function uh(){return new Worker(ih,{type:"module"})}const mh=["typescript","javascript","tsx","jsx","json","markdown"],Bo={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ac,ic;const rc=t=>{const e=Bo[t],n=new rh({workerFactory:uh,poolSize:e.poolSize,totalASTLRUCacheSize:e.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:mh,lineDiffType:e.lineDiffType,preferredHighlighter:"shiki-wasm"});return n.initialize(),n},ph=t=>{if(!(typeof window>"u"))return t==="split"?(ic??=rc("split"),ic):(ac??=rc("unified"),ac)},gh=t=>{const e=Ze.c(7),{children:n,renderTheme:a}=t,i=_o("unified"),r=_o("split");let o,d;e[0]!==a||e[1]!==r||e[2]!==i?(o=()=>{i&&i.setRenderOptions({theme:a,lineDiffType:Bo.unified.lineDiffType}),r&&r.setRenderOptions({theme:a,lineDiffType:Bo.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]),ve.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},lS=t=>{const e=Ze.c(11),{children:n}=t,a=jr();let i,r;if(e[0]!==a?.availableThemes||e[1]!==a?.darkThemeId||e[2]!==a?.lightThemeId){const p=pr(!1),u=pr(!0),g=a?.lightThemeId??p.metadata.id,m=a?.darkThemeId??u.metadata.id;r=a?.availableThemes.find(w=>w.metadata.id===g)??p,i=a?.availableThemes.find(w=>w.metadata.id===m)??u,dr(r),dr(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(gh,{renderTheme:d,children:n}),e[8]=n,e[9]=d,e[10]=c):c=e[10],c},_o=t=>{const e=Ze.c(2),n=t===void 0?"unified":t;let a;return e[0]!==n?(a=ph(n),e[0]=n,e[1]=a):a=e[1],a},oc="openchamber.update-install-id";function fh(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const t=window.localStorage.getItem(oc)?.trim();if(t)return t;const e=crypto.randomUUID();return window.localStorage.setItem(oc,e),e}catch{return}}function hh(){if(typeof window>"u")return"unknown";try{const{deviceType:t}=Um();return t}catch{return"unknown"}}function xh(){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 bh(){const t=xu();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 yh(t){const e=je.getState().reportUsage,n=new URLSearchParams({reportUsage:e?"true":"false"});if(n.set("deviceClass",hh()),n.set("arch",xh()),n.set("platform",bh()),e&&(t==="desktop"||t==="mobile")){const a=fh();a&&n.set("installId",a)}return t==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",Ga()?"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 Li(t,e){try{const n=yh(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 vh(){return dl()?"mobile":Lg()?"desktop":ds()?"vscode":Pn()?"web":null}const lc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Ru=fn()((t,e)=>({...lc,checkForUpdates:async()=>{const n=vh();if(!n)return null;t({checking:!0,error:null,runtimeType:n});try{let a=null,i=null;if(n==="desktop"){const r="1.18.1",[o,d]=await Promise.allSettled([Bl(),Li("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 Li("web"),i=a?.nextSuggestedCheckInSec??null):n==="vscode"?i=(await Li("vscode"))?.nextSuggestedCheckInSec??null:n==="mobile"&&(a=await Li("mobile","1.18.1"),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 Bl();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 Mg(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 Rg())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(lc)}})),cc="https://github.com/openchamber/openchamber/releases";function wh(t){const e=new Date(`${t}T00:00:00`);return Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(kr(),{year:"numeric",month:"short",day:"numeric"}).format(e)}function jh(t){return t.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function dc(t){return t.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function kh(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 Nh(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 uc=2e3,Sh=600*1e3;async function Ch(){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 Ih(){try{return(await ht("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function Ph(t,e=Math.ceil(Sh/uc),n=uc){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 Ih())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const mc=({open:t,onOpenChange:e,info:n,downloading:a,downloaded:i,progress:r,error:o,onDownload:d,onRestart:c,runtimeType:p="desktop"})=>{const{t:u}=ot(),[g,m]=ve.useState(!1),[w,h]=ve.useState("idle"),[f,x]=ve.useState(null),k=n?.version?n.releaseUrl||`${cc}/tag/v${n.version}`:cc,y=n?.downloadUrl||k,C=r?.total?Math.round(r.downloaded/r.total*100):0,O=p==="web",j=p==="mobile",N=n?.updateCommand||"openchamber update";ve.useEffect(()=>{t||(h("idle"),x(null))},[t]);const b=async()=>{(await oa(N)).ok&&(m(!0),setTimeout(()=>m(!1),2e3))},I=ve.useCallback(async F=>{await Hn(F)},[]),B=ve.useCallback(async()=>{h("updating"),x(null);const F=await Ch();if(!F.success){h("error"),x(F.error||u("updateDialog.error.updateFailed"));return}F.autoRestart&&(h("restarting"),await new Promise(z=>setTimeout(z,2e3))),h("reconnecting"),await Ph(n?.currentVersion)?window.location.reload():(h("error"),x(u("updateDialog.error.takingLonger")))},[n?.currentVersion,u]),T=ve.useCallback(()=>{I(y)},[I,y]),D=w!=="idle"&&w!=="error",S=ve.useMemo(()=>{if(!n?.body)return null;const F=n.body.trim();if(!F)return null;const R=Nh(F);if(R.length===0)return{kind:"raw",title:u("updateDialog.changelog.title"),content:dc(F)};const z=[...R].sort((q,H)=>kh(q.version,H.version));return{kind:"sections",title:u("updateDialog.changelog.title"),sections:z.map(q=>({version:q.version,dateLabel:wh(q.date),content:dc(jh(q.raw)||F)}))}},[n?.body,u]);return s.jsx(Kt,{open:t,onOpenChange:D?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:[O&&D&&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&&!D&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(zs,{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 z=F.target.closest("a");z&&z.href&&(F.preventDefault(),F.stopPropagation(),I(z.href))},children:s.jsx(ur,{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:R=>{const q=R.target.closest("a");q&&q.href&&(R.preventDefault(),R.stopPropagation(),I(q.href))},children:s.jsx(ur,{content:F.content,disableLinkSafety:!0,enableFileReferences:!1})})]},F.version))})})}),O&&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:b,className:fe("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",g&&"text-[var(--status-success)]"),title:u(g?"updateDialog.actions.copied":"updateDialog.actions.copyCommand"),children:g?s.jsx(K,{name:"check",className:"h-4 w-4"}):s.jsx(K,{name:"clipboard",className:"h-4 w-4"})})]})]}),!O&&!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||f)&&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||f})})]}),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:[!O&&!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")]}),!O&&!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")]}),!O&&!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:T,size:"default",children:[s.jsx(K,{name:"external-link",className:"h-4 w-4"}),u("updateDialog.actions.openMobileUpdate")]}),O&&!D&&s.jsxs("button",{onClick:B,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")]}),O&&D&&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=Ze.c(22),{children:n,className:a,contentClassName:i}=t,{t:r}=ot(),[o,d]=l.useState(!1),c=l.useRef(null);let p,u;e[0]!==o?(p=()=>{if(!o)return;const C=O=>{const j=c.current;j&&O.target instanceof Node&&j.contains(O.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 g;e[3]!==r?(g=r("settings.common.infoAria"),e[3]=r,e[4]=g):g=e[4];let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=C=>{C.preventDefault(),C.stopPropagation(),d(Th)},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 h;e[8]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(K,{name:"information",className:"h-3.5 w-3.5"}),e[8]=h):h=e[8];let f;e[9]!==o||e[10]!==g||e[11]!==w?(f=s.jsx(xs,{asChild:!0,children:s.jsx("button",{ref:c,type:"button","aria-label":g,"aria-expanded":o,onClick:m,className:w,children:h})}),e[9]=o,e[10]=g,e[11]=w,e[12]=f):f=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]!==f||e[20]!==k?(y=s.jsxs(bs,{open:o,onOpenChange:d,children:[f,k]}),e[18]=o,e[19]=f,e[20]=k,e[21]=y):y=e[21],y};function Th(t){return!t}const jn="w-full min-w-40 max-w-48",Gt="settings",$n="w-full min-w-40 max-w-48",Is="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Vn=fe(Do(),"w-full min-w-40 max-w-48"),$s="w-full max-w-[24rem]",pc="min-w-0 flex-1",si="flex w-full min-w-0 items-center gap-2",ni="typography-meta shrink-0 text-muted-foreground tabular-nums",Bn="space-y-4",Ds="space-y-1.5",Uo="typography-settings-page-title text-muted-foreground",gl="typography-settings-section-title text-foreground",hn=gl,Ah="typography-settings-group-title text-foreground",zt="typography-settings-field-label text-foreground",Mu="typography-settings-description text-muted-foreground",Ys="typography-meta text-muted-foreground",gc="typography-meta font-medium text-foreground",Eh="typography-settings-section-title text-foreground",dt=t=>{const e=Ze.c(20),{title:n,description:a,titleAccessory:i,info:r,headerAction:o,children:d,divider:c,className:p,contentClassName:u,settingsItem:g}=t,m=c===void 0?!0:c,w=n!=null||a!=null||o!=null||r!=null,h=m?"border-t border-border/60 py-8":"pb-8";let f;e[0]!==p||e[1]!==h?(f=fe("space-y-5",h,p),e[0]=p,e[1]=h,e[2]=f):f=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:gl,children:n}):n,i,r!=null?s.jsx($t,{children:r}):null]}):null,a!=null?s.jsx("div",{className:Mu,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]!==g||e[16]!==f||e[17]!==x||e[18]!==y?(C=s.jsxs("section",{"data-settings-item":g,className:f,children:[x,y]}),e[15]=g,e[16]=f,e[17]=x,e[18]=y,e[19]=C):C=e[19],C},On=t=>{const e=Ze.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},gn=t=>{const e=Ze.c(6),{children:n,className:a,as:i}=t,r=i===void 0?"h3":i;let o;e[0]!==a?(o=fe(Ah,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},en=t=>{const e=Ze.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(gn,{children:n}),i!=null?s.jsx($t,{children:i}):null]}):null,a!=null?s.jsx("p",{className:Ys,children:a}):null]}):null,e[2]=a,e[3]=i,e[4]=n,e[5]=u):u=e[5];let g;e[6]!==d?(g=fe(d),e[6]=d,e[7]=g):g=e[7];let m;e[8]!==r||e[9]!==g?(m=s.jsx("div",{className:g,children:r}),e[8]=r,e[9]=g,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=Ze.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 g;e[0]!==a?(g=a!=null?s.jsx("p",{className:Ys,children:a}):null,e[0]=a,e[1]=g):g=e[1];const m=g;let w;e[2]!==c?(w=fe("space-y-2",c),e[2]=c,e[3]=w):w=e[3];let h;e[4]!==n?(h=s.jsx("div",{className:zt,children:n}),e[4]=n,e[5]=h):h=e[5];let f;e[6]!==i?(f=i!=null?s.jsx($t,{children:i}):null,e[6]=i,e[7]=f):f=e[7];let x;e[8]!==h||e[9]!==f?(x=s.jsxs("div",{className:"flex items-center gap-1.5",children:[h,f]}),e[8]=h,e[9]=f,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 O;e[16]!==o||e[17]!==C?(O=s.jsx("div",{className:C,children:o}),e[16]=o,e[17]=C,e[18]=O):O=e[18];const j=u==="after"?m:null;let N;return e[19]!==d||e[20]!==O||e[21]!==j||e[22]!==w||e[23]!==y?(N=s.jsxs("div",{"data-settings-item":d,className:w,children:[y,O,j]}),e[19]=d,e[20]=O,e[21]=j,e[22]=w,e[23]=y,e[24]=N):N=e[24],N},Xt=t=>{const e=Ze.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 g;e[0]!==d?(g=fe("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",d),e[0]=d,e[1]=g):g=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 h;e[6]!==m||e[7]!==w?(h=s.jsxs("div",{className:"flex items-center gap-1.5",children:[m,w]}),e[6]=m,e[7]=w,e[8]=h):h=e[8];let f;e[9]!==a?(f=a!=null?s.jsx("p",{className:fe(Ys,"mt-0.5"),children:a}):null,e[9]=a,e[10]=f):f=e[10];let x;e[11]!==h||e[12]!==f?(x=s.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[h,f]}),e[11]=h,e[12]=f,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 O;return e[20]!==o||e[21]!==C||e[22]!==g||e[23]!==x?(O=s.jsxs("div",{"data-settings-item":o,className:g,children:[x,C]}),e[20]=o,e[21]=C,e[22]=g,e[23]=x,e[24]=O):O=e[24],O},ca=t=>{const e=Ze.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=Ze.c(39),{checked:n,onChange:a,label:i,description:r,disabled:o,ariaLabel:d,settingsItem:c,className:p,labelAccessory:u,info:g}=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 h=w,f=r!=null,x=f?"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,O=m||void 0;let j;e[8]!==h?(j=F=>{(F.key===" "||F.key==="Enter")&&(F.preventDefault(),h())},e[8]=h,e[9]=j):j=e[9];let N;e[10]!==d||e[11]!==n||e[12]!==m||e[13]!==a?(N=s.jsx(rn,{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 b;e[15]!==i?(b=s.jsx("span",{className:zt,children:i}),e[15]=i,e[16]=b):b=e[16];let I;e[17]!==g?(I=g!=null?s.jsx($t,{children:g}):null,e[17]=g,e[18]=I):I=e[18];let B;e[19]!==u||e[20]!==b||e[21]!==I?(B=s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[b,u,I]}),e[19]=u,e[20]=b,e[21]=I,e[22]=B):B=e[22];let T;e[23]!==r||e[24]!==f?(T=f?s.jsx("span",{className:Ys,children:r}):null,e[23]=r,e[24]=f,e[25]=T):T=e[25];let D;e[26]!==B||e[27]!==T?(D=s.jsxs("div",{className:"flex min-w-0 flex-col",children:[B,T]}),e[26]=B,e[27]=T,e[28]=D):D=e[28];let S;return e[29]!==n||e[30]!==c||e[31]!==D||e[32]!==y||e[33]!==C||e[34]!==O||e[35]!==j||e[36]!==N||e[37]!==h?(S=s.jsxs("div",{"data-settings-item":c,className:y,role:"button",tabIndex:C,"aria-pressed":n,"aria-disabled":O,onClick:h,onKeyDown:j,children:[N,D]}),e[29]=n,e[30]=c,e[31]=D,e[32]=y,e[33]=C,e[34]=O,e[35]=j,e[36]=N,e[37]=h,e[38]=S):S=e[38],S},zn=t=>{const e=Ze.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",g=p&&"cursor-not-allowed opacity-60";let m;e[0]!==c||e[1]!==u||e[2]!==g?(m=fe("flex cursor-pointer gap-2 py-0.5",u,g,c),e[0]=c,e[1]=u,e[2]=g,e[3]=m):m=e[3];const w=p?-1:0,h=p||void 0;let f,x;e[4]!==p||e[5]!==a?(f=()=>{p||a()},x=B=>{(B.key===" "||B.key==="Enter")&&(B.preventDefault(),p||a())},e[4]=p,e[5]=a,e[6]=f,e[7]=x):(f=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(Nr,{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 O;e[14]!==C?(O=fe("typography-settings-field-label font-normal",C),e[14]=C,e[15]=O):O=e[15];let j;e[16]!==i||e[17]!==O?(j=s.jsx("span",{className:O,children:i}),e[16]=i,e[17]=O,e[18]=j):j=e[18];let N;e[19]!==r?(N=r!=null?s.jsx("span",{className:Ys,children:r}):null,e[19]=r,e[20]=N):N=e[20];let b;e[21]!==j||e[22]!==N?(b=s.jsxs("div",{className:"flex min-w-0 flex-col",children:[j,N]}),e[21]=j,e[22]=N,e[23]=b):b=e[23];let I;return e[24]!==n||e[25]!==y||e[26]!==b||e[27]!==m||e[28]!==w||e[29]!==h||e[30]!==f||e[31]!==x?(I=s.jsxs("div",{className:m,role:"button",tabIndex:w,"aria-pressed":n,"aria-disabled":h,onClick:f,onKeyDown:x,children:[y,b]}),e[24]=n,e[25]=y,e[26]=b,e[27]=m,e[28]=w,e[29]=h,e[30]=f,e[31]=x,e[32]=I):I=e[32],I},Kn=t=>{const e=Ze.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 Qs(t){const e=Ze.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=g=>s.jsx(ee,{type:"button",variant:"chip",size:"xs",disabled:g.disabled,"aria-pressed":n===g.value,className:"!font-normal",onClick:()=>i(g.value),children:g.label},g.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 fc="https://github.com/openchamber/openchamber",Dh="https://discord.gg/ZYRSdnwwKA",hc="https://x.com/openchamber_dev",Rh=800,Lu=({initialUpdateDialogOpen:t=!1})=>{const{t:e}=ot(),[n,a]=l.useState(t),[i,r]=l.useState(!1),[o,d]=l.useState(null),[c,p]=l.useState(null),u=Ru(Ws(f=>({info:f.info,checking:f.checking,available:f.available,error:f.error,downloading:f.downloading,downloaded:f.downloaded,progress:f.progress,runtimeType:f.runtimeType,checkForUpdates:f.checkForUpdates,downloadUpdate:f.downloadUpdate,restartToUpdate:f.restartToUpdate}))),{isMobile:g}=Hs(),m=o||u.info?.currentVersion||"unknown";l.useEffect(()=>{let f=!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;f||d(C)}catch{f||d(null)}})(),()=>{f=!0}},[]),l.useEffect(()=>{let f=!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;f||p(C)}catch{f||p(null)}})(),()=>{f=!0}},[]);const w=l.useRef(!1);l.useEffect(()=>{if(u.checking)r(!0),w.current=!0;else if(i){const f=setTimeout(()=>{r(!1),w.current&&!u.available&&!u.error&&(Q.success(e("settings.openchamber.about.toast.latestVersion")),w.current=!1)},Rh);return()=>clearTimeout(f)}},[e,u.checking,i,u.available,u.error]);const h=u.checking||i;return g?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(nu,{width:72,height:72}),s.jsx("h2",{className:`mt-4 ${Eh}`,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:h,className:"h-10 w-auto justify-center gap-2 rounded-xl px-4",children:[h?s.jsx(K,{name:"loader",className:"size-4 animate-spin"}):s.jsx(K,{name:"refresh",className:"size-4"}),e(h?"settings.openchamber.about.state.checking":"settings.openchamber.about.actions.checkForUpdates")]}),!h&&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:fc,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:Dh,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:hc,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(mc,{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:fc,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:hc,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(mc,{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})]})},cS=t=>!(t.dismissed==="true"||t.sessionShown==="true"||t.hasActiveToast),Mh=t=>!(!t.version||t.seenVersions.has(t.version)||t.dismissedVersion!==null&&t.dismissedVersion===t.version),Lh=t=>{if(t===null||typeof t!="object")return"";const e=t.version;return typeof e!="string"?"":e.trim()},Fh=t=>!t||t.upgrade?.supported!==!0||t.available!==!0||typeof t.latestVersion!="string"?"":t.latestVersion.trim(),Pa="opencode-update-available",Fi="opencode-upgrade-progress",Oh=5e3,zh=[1e4,6e4],xc="opencode-update-toast-dismissed-version",dS=()=>{const{t}=ot(),e=je(o=>o.showOpenCodeUpdateNotifications),n=ve.useRef(new Set),a=ve.useRef(!1);ve.useEffect(()=>{e||Q.dismiss(Pa)},[e]);const i=ve.useCallback(()=>{Q.dismiss(Fi),_n({message:t("opencodeUpdate.toast.reload.message"),mode:"projects",scopes:["all"]}).catch(()=>{})},[t]),r=ve.useCallback(async()=>{if(!a.current){a.current=!0,Q.dismiss(Pa),Q.message(t("opencodeUpdate.toast.upgrading.title"),{id:Fi,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"));Q.success(t("opencodeUpdate.toast.updated.title"),{id:Fi,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){Q.error(t("opencodeUpdate.toast.failed.title"),{id:Fi,description:o instanceof Error?o.message:t("opencodeUpdate.toast.failed.description"),duration:1/0})}finally{a.current=!1}}},[i,t]);return ve.useEffect(()=>{const o=m=>{if(!je.getState().showOpenCodeUpdateNotifications){Q.dismiss(Pa);return}Mh({version:m,dismissedVersion:_l().getItem(xc),seenVersions:n.current})&&(n.current.add(m),Q.info(t("opencodeUpdate.toast.available.title"),{id:Pa,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:()=>{_l().setItem(xc,m),It({openCodeUpdateToastDismissedVersion:m}),Q.dismiss(Pa)}}}))};let d=!1;const c=[],p=async(m,w=pn())=>{try{const h=await ht("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!h.ok)throw new Error(h.statusText||"OpenCode upgrade status check failed");const f=await h.json().catch(()=>null),x=Fh(f);!d&&w===pn()&&x&&o(x)}catch{const h=zh[m];!d&&w===pn()&&h!==void 0&&c.push(setTimeout(()=>{p(m+1,w)},h))}},u=m=>{Lh(m.detail)&&p(0)};e&&c.push(setTimeout(()=>{p(0)},Oh));const g=ul(({runtimeKey:m})=>{n.current.clear(),Q.dismiss(Pa),je.getState().showOpenCodeUpdateNotifications&&p(0,m)});return window.addEventListener("openchamber:opencode-update-available",u),()=>{d=!0;for(const m of c)clearTimeout(m);g(),window.removeEventListener("openchamber:opencode-update-available",u)}},[r,e,t]),null},uS=()=>{const t=Ze.c(3),[e,n]=l.useState(Kh),{isUpdating:a}=e;let i,r;if(t[0]===Symbol.for("react.memo_cache_sentinel")?(i=()=>Vm(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(nu,{width:80,height:80,isAnimated:!0})}),t[2]=o):o=t[2],o};function Kh(){return $m()}class Bh 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(Hm,{className:"w-full max-w-md",children:[s.jsx(Wm,{className:"text-center",children:s.jsxs(Gm,{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(qm,{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 _h(t){const e=Ze.c(22),{t:n}=ot();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(Bh,{...t,texts:p}),e[19]=t,e[20]=p,e[21]=u):u=e[21],u}const mS=t=>{const e=Ze.c(6),{active:n,readOnly:a}=t,i=n===void 0?!0:n,r=a===void 0?!1:a,d=es(Uh)||void 0;let c;e[0]!==i||e[1]!==r?(c=s.jsx(Jm,{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(_h,{sessionId:d,children:c}),e[3]=d,e[4]=c,e[5]=p):p=e[5],p};function Uh(t){return t.currentSessionId}const $h=t=>t!==null&&typeof t=="object"&&"updateStatus"in t&&typeof t.updateStatus=="function",Vh=t=>{const e=document.createElement("div");e.className="cm-vim-panel";const n=Lf(t);if(!n)return{top:!1,dom:e};n.state.statusbar=e;const a=n.state.vimPlugin;return $h(a)&&a.updateStatus(),{top:!1,dom:e,destroy(){n.state.statusbar===e&&(n.state.statusbar=null)}}};function bc(t){return t?[Mf(),hf.of(Vh),xf()]:[]}const Hh={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},Wh={case:"Match case",re:"Regular expression",word:"Match whole word"};function Gh(t){const e=t.querySelector(".cm-search");if(e){for(const[n,a]of Object.entries(Hh)){const i=e.querySelector(`button[name="${n}"]`);i&&!i.title&&(i.title=a)}for(const[n,a]of Object.entries(Wh)){const r=e.querySelector(`input[name="${n}"]`)?.parentElement;r&&!r.title&&(r.title=a)}}}const Jr=new WeakMap;function qh(t,e){const n=gr(t.state);if(!n.valid)return Jr.delete(t),0;const a=Jr.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 Jr.set(t,{query:n,doc:t.state.doc,total:r}),r}function Jh(t){const e=gr(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 yc(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=qh(e,n),o=r===0?0:Jh(e);i.textContent=r===0?"":`${o}/${r}`}const vc=new fa,wc=new fa,jc=new fa,kc=new fa,Nc=new fa,Sc=new fa,Cc=new fa,Ic=t=>t,Yr=Af,Yh=Df,Qh=Rf;class Xh extends yf{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 Pc=(t,e)=>!t||t.length===0?[]:ju.define({create(n){const a=new pl,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,Tr.widget({widget:new Xh(r.id,e),block:!0,side:1}))}return a.finish()},update(n,a){return n.map(a.changes)},provide:n=>sn.decorations.from(n)}),Tc=t=>{if(!t)return[];const e=Math.max(1,t.start),n=Math.max(e,t.end);return wu.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 pl;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,Tr.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:g,onSearchOpenChange:m,vimMode:w}){const h=l.useRef(null),f=l.useRef(null),x=l.useRef(t),k=l.useRef(e),y=l.useRef(d),C=l.useRef(c),O=l.useRef(m),j=l.useRef(p),N=l.useRef(w),b=l.useRef(new Map),[I,B]=l.useState([]),T=l.useCallback(S=>{const F=(S??[]).map(R=>{const z=b.current.get(R.id);return z?{id:R.id,content:R.content,container:z}:null}).filter(R=>R!==null);B(R=>R.length===F.length&&R.every((z,q)=>{const H=F[q];return z.id===H.id&&z.content===H.content&&z.container===H.container})?R:F)},[]),D=l.useCallback(S=>{const F=h.current,R=S??f.current;if(!F||!R)return;const z=R.dom.querySelector(".cm-gutters"),q=z instanceof HTMLElement?z.getBoundingClientRect().width:0;F.style.setProperty("--oc-editor-gutter-width",`${q}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(()=>{O.current=m},[m]),l.useEffect(()=>{j.current=p,T(p)},[p,T]),l.useEffect(()=>{if(!h.current)return;const S=(()=>{if(typeof document>"u")return null;const R=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(R)return R;const z=window.__OPENCHAMBER_CSP_NONCE__;return typeof z=="string"&&z.length>0?z:null})(),F=kf.create({doc:x.current,extensions:[...S?[sn.cspNonce.of(S)]:[],bf({fixed:!0}),vc.of(Ql(r)),Sf(),Tf.of(" "),Cc.of(bc(w)),qr.of([Cf,...If,...Pf]),sn.updateListener.of(R=>{D(R.view),(R.viewportChanged||R.geometryChanged)&&T(j.current);const z=Zl(R.startState),q=Zl(R.state);z!==q&&O.current?.(q);const H=!gr(R.startState).eq(gr(R.state));if(q&&(z!==q||H||R.docChanged||R.selectionSet)&&yc(R.view.dom,R.view,z!==q||H||R.docChanged),!R.docChanged)return;const Z=R.state.doc.toString();x.current=Z,k.current(Z),T(j.current)}),wc.of(sn.editable.of(!i)),jc.of(n??[]),kc.of(Tc(o)),Nc.of(Pc(p,b.current)),Sc.of(u?[ec({top:!0}),qr.of(Ic(tc))]:[])]});return f.current=new sn({state:F,parent:h.current}),Yr(f.current,f.current.state.doc.length,200),f.current.requestMeasure(),requestAnimationFrame(()=>{D(f.current),T(j.current)}),f.current&&y.current?.(f.current),()=>{C.current?.(),f.current?.destroy(),f.current=null,B([])}},[j,D,T]),l.useEffect(()=>{const S=f.current;S&&(S.dispatch({effects:[vc.reconfigure(Ql(r)),wc.reconfigure(sn.editable.of(!i)),jc.reconfigure(n??[]),kc.reconfigure(Tc(o)),Nc.reconfigure(Pc(p,b.current)),Sc.reconfigure(u?[ec({top:!0}),qr.of(Ic(tc))]:[])]}),Yr(S,S.state.doc.length,200),S.requestMeasure(),requestAnimationFrame(()=>{D(S),T(j.current)}))},[n,o,r,i,p,u,D,T]),l.useEffect(()=>{const S=f.current;if(!S){N.current=w;return}N.current!==w&&(N.current=w,S.dispatch({effects:Cc.reconfigure(bc(w))}))},[w]),l.useEffect(()=>{const S=f.current;!S||u===!1||(g?(Yh(S),requestAnimationFrame(()=>{Gh(S.dom),yc(S.dom,S,!0)})):Qh(S))},[g,u]),l.useEffect(()=>{const S=f.current;if(!S)return;const F=S.state.doc.toString();F!==t&&(S.dispatch({changes:{from:0,to:F.length,insert:t}}),Yr(S,S.state.doc.length,300),S.requestMeasure(),requestAnimationFrame(()=>D(S)))},[t,D]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:h,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)}),I.map(S=>Zi.createPortal(S.content,S.container,S.id))]})}const Fu=t=>{const e=Ze.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 Gn(t){const e=Ze.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(Kf,{...n}),e[2]=n,e[3]=a):a=e[3],a}function qn(t){const e=Ze.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(Bf,{...n}),e[2]=n,e[3]=a):a=e[3],a}function Jn(t){const e=Ze.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(Ym,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(_f,{"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 g;return e[17]!==d||e[18]!==u?(g=s.jsx(Vf,{children:s.jsx(Hf,{className:d,children:u})}),e[17]=d,e[18]=u,e[19]=g):g=e[19],g}function An(t){const e=Ze.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(Qm,n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx(Uf,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r}function pS(t){const e=Ze.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(Xm,n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx($f,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r}const da=Gf,ua=t=>{const e=Ze.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&&ve.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(Wf,{className:c,...r,...d}),e[10]=r,e[11]=d,e[12]=c,e[13]=p):p=e[13],p},ma=t=>{const e=Ze.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(qf,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r};function Ou(t){const e=Ze.c(85),{draft:n,onEdit:a,onDelete:i,className:r,maxWidth:o}=t,{t:d}=ot(),p=jr()?.currentTheme,[u,g]=ve.useState(!1),[m,w]=ve.useState(!1),h=typeof n.text=="string"?n.text:"";let f;e[0]!==h?(f=h.length>150||h.split(`
|
|
3
|
+
`).length>3,e[0]=h,e[1]=f):f=e[1];const x=f;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,O=o?`${Math.max(200,Math.floor(o))}px`:void 0;let j;e[4]!==y||e[5]!==C||e[6]!==O?(j={backgroundColor:y,borderColor:C,maxWidth:O},e[4]=y,e[5]=C,e[6]=O,e[7]=j):j=e[7];let N;e[8]===Symbol.for("react.memo_cache_sentinel")?(N=oe=>{oe.preventDefault(),w(!0)},e[8]=N):N=e[8];let b;e[9]!==k||e[10]!==j?(b=s.jsx("div",{className:k,style:j,"data-comment-card":"true",onContextMenu:N}),e[9]=k,e[10]=j,e[11]=b):b=e[11];let I;e[12]!==n.fileLabel?(I=s.jsx("span",{className:"truncate max-w-[200px]",title:n.fileLabel,children:n.fileLabel}),e[12]=n.fileLabel,e[13]=I):I=e[13];let B;e[14]===Symbol.for("react.memo_cache_sentinel")?(B=s.jsx("span",{children:"•"}),e[14]=B):B=e[14];let T;e[15]!==n.endLine||e[16]!==n.startLine||e[17]!==d?(T=d("inlineComment.range.lines",{start:n.startLine,end:n.endLine}),e[15]=n.endLine,e[16]=n.startLine,e[17]=d,e[18]=T):T=e[18];let D;e[19]!==T?(D=s.jsx("span",{children:T}),e[19]=T,e[20]=D):D=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]!==D||e[24]!==S||e[25]!==I?(F=s.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1.5",children:[I,B,D,S]}),e[23]=D,e[24]=S,e[25]=I,e[26]=F):F=e[26];const R=u||!x,z=!u&&x&&"line-clamp-3";let q;e[27]!==z?(q=fe("text-sm whitespace-pre-wrap break-words leading-relaxed",z),e[27]=z,e[28]=q):q=e[28];let H;e[29]!==h||e[30]!==q?(H=s.jsx("div",{className:q,children:h}),e[29]=h,e[30]=q,e[31]=H):H=e[31];let Z;e[32]!==x||e[33]!==u||e[34]!==d?(Z=x&&s.jsx(ua,{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 W;e[36]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx(ma,{}),e[36]=W):W=e[36];let A;e[37]!==R||e[38]!==H||e[39]!==Z?(A=s.jsxs(da,{open:R,onOpenChange:g,children:[H,Z,W]}),e[37]=R,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 E;e[45]===Symbol.for("react.memo_cache_sentinel")?(E=s.jsx(K,{name:"edit",className:"size-4 mr-2"}),e[45]=E):E=e[45];let P;e[46]!==d?(P=d("inlineComment.actions.editComment"),e[46]=d,e[47]=P):P=e[47];let _;e[48]!==a||e[49]!==P?(_=s.jsxs(as,{onClick:a,children:[E,P]}),e[48]=a,e[49]=P,e[50]=_):_=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 Y;e[54]!==i||e[55]!==V?(Y=s.jsxs(as,{onClick:i,className:"text-destructive",children:[L,V]}),e[54]=i,e[55]=V,e[56]=Y):Y=e[56];let G;e[57]!==_||e[58]!==Y?(G=s.jsxs(fs,{children:[te,s.jsxs(hs,{align:"end",children:[_,Y]})]}),e[57]=_,e[58]=Y,e[59]=G):G=e[59];let me;e[60]!==X||e[61]!==G?(me=s.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[X,G]}),e[60]=X,e[61]=G,e[62]=me):me=e[62];let ae;e[63]!==me||e[64]!==b?(ae=s.jsx(qn,{render:b,children:me}),e[63]=me,e[64]=b,e[65]=ae):ae=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 be;e[67]!==d?(be=d("inlineComment.actions.editComment"),e[67]=d,e[68]=be):be=e[68];let ie;e[69]!==a||e[70]!==be?(ie=s.jsxs(An,{onClick:a,children:[xe,be]}),e[69]=a,e[70]=be,e[71]=ie):ie=e[71];let pe;e[72]===Symbol.for("react.memo_cache_sentinel")?(pe=s.jsx(K,{name:"delete-bin",className:"size-4 mr-2"}),e[72]=pe):pe=e[72];let Ie;e[73]!==d?(Ie=d("inlineComment.actions.deleteComment"),e[73]=d,e[74]=Ie):Ie=e[74];let re;e[75]!==i||e[76]!==Ie?(re=s.jsxs(An,{onClick:i,className:"text-destructive focus:text-destructive",children:[pe,Ie]}),e[75]=i,e[76]=Ie,e[77]=re):re=e[77];let ce;e[78]!==ie||e[79]!==re?(ce=s.jsxs(Jn,{children:[ie,re]}),e[78]=ie,e[79]=re,e[80]=ce):ce=e[80];let ge;return e[81]!==m||e[82]!==ae||e[83]!==ce?(ge=s.jsxs(Gn,{open:m,onOpenChange:w,children:[ae,ce]}),e[81]=m,e[82]=ae,e[83]=ce,e[84]=ge):ge=e[84],ge}function fr(t){const e=Ze.c(62),{initialText:n,onTextChange:a,onSave:i,onCancel:r,fileLabel:o,lineRange:d,isEditing:c,className:p,maxWidth:u}=t,g=n===void 0?"":n,m=c===void 0?!1:c,{t:w}=ot(),f=jr()?.currentTheme,{isMobile:x}=Hs(),[k,y]=l.useState(g),C=ve.useRef(null);let O;e[0]!==a?(O=le=>{y(le),a?.(le)},e[0]=a,e[1]=O):O=e[1];const j=O,N=ve.useRef(d);let b,I;e[2]!==d?(b=()=>{d&&(N.current=d)},I=[d],e[2]=d,e[3]=b,e[4]=I):(b=e[3],I=e[4]),ve.useEffect(b,I);const B=ix,T=B(d);let D,S;e[5]!==x?(D=()=>{const le=C.current;if(!le)return;const he=le.closest(".overlay-scrollbar-container"),De=he?.scrollTop??window.scrollY,Le=he?.scrollLeft??window.scrollX;if(x){le.scrollIntoView({behavior:"auto",block:"nearest"});try{le.focus({preventScroll:!0})}catch{le.focus()}return}try{le.focus({preventScroll:!0})}catch{le.focus()}const Ke=le.value.length;try{le.setSelectionRange(Ke,Ke)}catch{}requestAnimationFrame(()=>{he?(he.scrollTop=De,he.scrollLeft=Le):window.scrollTo({top:De,left:Le})})},S=[x],e[5]=x,e[6]=D,e[7]=S):(D=e[6],S=e[7]),ve.useEffect(D,S);let F;e[8]!==r||e[9]!==i||e[10]!==k?(F=le=>{(le.metaKey||le.ctrlKey)&&le.key==="Enter"?(le.preventDefault(),k.trim()&&i(k,B(N.current))):le.key==="Escape"&&(le.preventDefault(),r())},e[8]=r,e[9]=i,e[10]=k,e[11]=F):F=e[11];const R=F;let z;e[12]!==i||e[13]!==k?(z=le=>{le.stopPropagation(),k.trim()&&i(k,B(N.current))},e[12]=i,e[13]=k,e[14]=z):z=e[14];const q=z;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=f?.colors?.surface?.elevated,W=f?.colors?.interactive?.border,A=u?`${Math.max(200,Math.floor(u))}px`:void 0;let X;e[17]!==Z||e[18]!==W||e[19]!==A?(X={backgroundColor:Z,borderColor:W,maxWidth:A},e[17]=Z,e[18]=W,e[19]=A,e[20]=X):X=e[20];const te="true",E=ax,P=nx,_="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:"•"}),T&&s.jsx("span",{children:w("inlineComment.range.lines",{start:T.start,end:T.end})})]});let V;e[21]!==j?(V=le=>j(le.target.value),e[21]=j,e[22]=V):V=e[22];let Y;e[23]!==x||e[24]!==w?(Y=w(x?"inlineComment.input.placeholderShort":"inlineComment.input.placeholder"),e[23]=x,e[24]=w,e[25]=Y):Y=e[25];let G;e[26]!==R||e[27]!==V||e[28]!==Y||e[29]!==k?(G=s.jsx(Ns,{simple:!0,ref:C,value:k,onChange:V,onKeyDown:R,placeholder:Y,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]=R,e[27]=V,e[28]=Y,e[29]=k,e[30]=G):G=e[30];let me;e[31]!==w?(me=w("inlineComment.actions.cancel"),e[31]=w,e[32]=me):me=e[32];let ae;e[33]!==r||e[34]!==me?(ae=s.jsx(ee,{variant:"ghost",size:"sm",onClick:r,onPointerDown:sx,onTouchStart:tx,className:"h-8 text-muted-foreground hover:text-foreground",children:me}),e[33]=r,e[34]=me,e[35]=ae):ae=e[35];let xe;e[36]!==k?(xe=k.trim(),e[36]=k,e[37]=xe):xe=e[37];const be=!xe,ie=f?.colors?.status?.success,pe=f?.colors?.status?.successForeground;let Ie;e[38]!==ie||e[39]!==pe?(Ie={backgroundColor:ie,color:pe},e[38]=ie,e[39]=pe,e[40]=Ie):Ie=e[40];let re;e[41]!==m||e[42]!==w?(re=w(m?"inlineComment.actions.save":"inlineComment.actions.comment"),e[41]=m,e[42]=w,e[43]=re):re=e[43];let ce;e[44]!==q||e[45]!==be||e[46]!==Ie||e[47]!==re?(ce=s.jsx(ee,{size:"sm",onClick:q,onPointerDown:ex,onTouchStart:Zh,disabled:be,className:"h-8 min-w-[80px]",style:Ie,children:re}),e[44]=q,e[45]=be,e[46]=Ie,e[47]=re,e[48]=ce):ce=e[48];let ge;e[49]!==ae||e[50]!==ce?(ge=s.jsxs("div",{className:"flex items-center justify-end gap-2 mt-3",children:[ae,ce]}),e[49]=ae,e[50]=ce,e[51]=ge):ge=e[51];let oe;e[52]!==L||e[53]!==G||e[54]!==ge?(oe=s.jsxs("div",{className:_,children:[L,G,ge]}),e[52]=L,e[53]=G,e[54]=ge,e[55]=oe):oe=e[55];let de;return e[56]!==H||e[57]!==X||e[58]!==E||e[59]!==P||e[60]!==oe?(de=s.jsx("div",{className:H,style:X,"data-comment-input":te,onPointerDown:E,onTouchStart:P,children:oe}),e[56]=H,e[57]=X,e[58]=E,e[59]=P,e[60]=oe,e[61]=de):de=e[61],de}function Zh(t){return t.stopPropagation()}function ex(t){return t.stopPropagation()}function tx(t){return t.stopPropagation()}function sx(t){return t.stopPropagation()}function nx(t){return t.stopPropagation()}function ax(t){return t.stopPropagation()}function ix(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 rx=t=>{const e=Math.min(t.startLine,t.endLine),n=Math.max(t.startLine,t.endLine);return{...t,startLine:e,endLine:n}},Vo=t=>{const e=Math.min(t.start,t.end),n=Math.max(t.start,t.end);return{...t,start:e,end:n}};function zu(t){const e=Ze.c(47),{t:n}=ot(),{source:a,fileLabel:i,language:r,getCodeForRange:o,toStoreRange:d,fromDraftRange:c}=t,p=es(ux),u=es(dx),g=ol();let m;e[0]!==p?(m=Y=>p?Y.getDirectoryForSession(p):null,e[0]=p,e[1]=m):m=e[1];const w=es(m),h=ui(cx),f=ui(lx),x=ui(ox),[k,y]=l.useState(null),[C,O]=l.useState(""),[j,N]=l.useState(null),b=p??(u?"draft":null),I=w??g;let B;e:{if(!b||!I){B=null;break e}let Y;e[2]!==I||e[3]!==b?(Y={directory:I,sessionKey:b},e[2]=I,e[3]=b,e[4]=Y):Y=e[4],B=Y}const T=B;let D;e[5]!==T?(D=T?Zm(pn(),T.directory,T.sessionKey):null,e[5]=T,e[6]=D):D=e[6];const S=D;let F;e[7]!==S?(F=Y=>S?Y.drafts[S]??Cl:Cl,e[7]=S,e[8]=F):F=e[8];const R=ui(F);let z;e:{if(!T||!i){let G;e[9]===Symbol.for("react.memo_cache_sentinel")?(G=[],e[9]=G):G=e[9],z=G;break e}let Y;if(e[10]!==i||e[11]!==R||e[12]!==a){let G;e[14]!==i||e[15]!==a?(G=me=>me.source===a&&me.fileLabel===i,e[14]=i,e[15]=a,e[16]=G):G=e[16],Y=R.filter(G),e[10]=i,e[11]=R,e[12]=a,e[13]=Y}else Y=e[13];z=Y}const q=z;let H;e[17]===Symbol.for("react.memo_cache_sentinel")?(H=()=>{y(null),O(""),N(null)},e[17]=H):H=e[17];const Z=H;let W;e[18]===Symbol.for("react.memo_cache_sentinel")?(W=()=>{Z()},e[18]=W):W=e[18];const A=W;let X;e[19]!==c?(X=Y=>{const G=Vo(c(Y));y(G),O(Y.text),N(Y.id)},e[19]=c,e[20]=X):X=e[20];const te=X;let E;e[21]!==j||e[22]!==x||e[23]!==T?(E=Y=>{T&&(x(T,Y.id),j===Y.id&&Z())},e[21]=j,e[22]=x,e[23]=T,e[24]=E):E=e[24];const P=E;let _;e[25]!==h||e[26]!==j||e[27]!==i||e[28]!==o||e[29]!==r||e[30]!==k||e[31]!==a||e[32]!==n||e[33]!==T||e[34]!==d||e[35]!==f?(_=(Y,G)=>{const me=G??k,ae=Y.trim();if(!me||!ae||!i)return;if(!T){Q.error(n("inlineComment.toast.selectSessionToSave"));return}const xe=Vo(me),be=rx(d(xe)),ie=o(xe);j?f(T,j,{fileLabel:i,startLine:be.startLine,endLine:be.endLine,side:be.side,code:ie,language:r,text:ae}):h(T,{source:a,fileLabel:i,startLine:be.startLine,endLine:be.endLine,side:be.side,code:ie,language:r,text:ae}),Z()},e[25]=h,e[26]=j,e[27]=i,e[28]=o,e[29]=r,e[30]=k,e[31]=a,e[32]=n,e[33]=T,e[34]=d,e[35]=f,e[36]=_):_=e[36];const L=_;let V;return e[37]!==C||e[38]!==P||e[39]!==q||e[40]!==j||e[41]!==c||e[42]!==L||e[43]!==k||e[44]!==b||e[45]!==te?(V={sessionKey:b,drafts:q,selection:k,setSelection:y,commentText:C,setCommentText:O,editingDraftId:j,setEditingDraftId:N,reset:Z,cancel:A,startEdit:te,deleteDraft:P,saveComment:L,fromDraftRange:c},e[37]=C,e[38]=P,e[39]=q,e[40]=j,e[41]=c,e[42]=L,e[43]=k,e[44]=b,e[45]=te,e[46]=V):V=e[46],V}function ox(t){return t.removeDraft}function lx(t){return t.updateDraft}function cx(t){return t.addDraft}function dx(t){return t.newSessionDraft?.open}function ux(t){return t.currentSessionId}function mx(t){const{drafts:e,editingDraftId:n,commentText:a,onTextChange:i,selection:r,isDragging:o,fileLabel:d,newWidgetId:c,mapDraftToRange:p,onSave:u,onCancel:g,onEdit:m,onDelete:w}=t,h=[];for(const f of e){const x=p(f);if(f.id===n){h.push({afterLine:x.end,id:`edit-${f.id}`,content:s.jsx(fr,{initialText:a,onTextChange:i,fileLabel:d,lineRange:x,isEditing:!0,onSave:u,onCancel:g},`edit-${f.id}`)});continue}h.push({afterLine:x.end,id:`card-${f.id}`,content:s.jsx(Ou,{draft:f,onEdit:()=>m(f),onDelete:()=>w(f)},`card-${f.id}`)})}if(r&&!n&&!o){const f={...r,start:Math.min(r.start,r.end),end:Math.max(r.start,r.end)};h.push({afterLine:f.end,id:c,content:s.jsx(fr,{initialText:a,onTextChange:i,fileLabel:d,lineRange:f,isEditing:!1,onSave:u,onCancel:g},c)})}return h}const nr=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}`},px=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 gx(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 Ac(t){if(!(!t||t<=0))return Math.max(200,Math.floor(t))}function fx(t){const{diffRootRef:e,drafts:n,selection:a,editingDraftId:i,commentText:r,onTextChange:o,fileLabel:d,onSave:c,onCancel:p,onEdit:u,onDelete:g}=t,[m,w]=l.useState(0),[h,f]=l.useState(null),x=l.useMemo(()=>!a||i?null:nr({type:"new",selection:a}),[i,a]),k=l.useMemo(()=>{const O=n.map(j=>nr({type:j.id===i?"edit":"saved",draft:j}));return x&&O.push(x),O},[n,i,x]),y=l.useCallback(O=>{const j=e.current;if(!j)return null;const N=j.querySelector("diffs-container");if(!(N instanceof HTMLElement))return null;const b=N.querySelector(`[data-annotation-id="${O}"]`);if(b instanceof HTMLElement)return b;const I=N.shadowRoot;return I?I.querySelector(`[data-annotation-id="${O}"]`):null},[e]);l.useEffect(()=>{if(k.length===0)return;let O=!1,j=0;const N=12,b=()=>{O||k.every(B=>!!y(B))||j>=N||(j+=1,requestAnimationFrame(()=>{O||(w(B=>B+1),b())}))};return b(),()=>{O=!0}},[k,y]),l.useEffect(()=>{const O=e.current;if(!O)return;const j=()=>{const b=getComputedStyle(O),I=gx(b.getPropertyValue("--oc-context-panel-width")),B=O.getBoundingClientRect(),T=I??B.width;f(T>0?T:null)};j();const N=new ResizeObserver(()=>{j()});return N.observe(O),window.addEventListener("resize",j),()=>{N.disconnect(),window.removeEventListener("resize",j)}},[e]);const C=l.useCallback(O=>{const N=e.current?.getBoundingClientRect(),b=O.closest("[data-annotation-content]"),I=b instanceof HTMLElement?b.getBoundingClientRect():O.getBoundingClientRect(),B=[I.width];N&&B.push(N.right-I.left);const T=B.filter(D=>Number.isFinite(D)&&D>0);return T.length>0?Ac(Math.min(...T)):Ac(h)},[e,h]);return s.jsxs(s.Fragment,{children:[n.map(O=>{const j=nr({type:O.id===i?"edit":"saved",draft:O}),N=y(j);if(!N)return null;const b=C(N);return O.id===i?Zi.createPortal(s.jsx(fr,{initialText:r,onTextChange:o,fileLabel:d,lineRange:{start:O.startLine,end:O.endLine,side:O.side==="original"?"deletions":"additions"},isEditing:!0,onSave:c,onCancel:p,maxWidth:b}),N,`draft-edit-${O.id}`):Zi.createPortal(s.jsx(Ou,{draft:O,onEdit:()=>u(O),onDelete:()=>g(O),maxWidth:b}),N,`draft-card-${O.id}`)}),a&&!i&&x&&(()=>{const O=y(x);if(!O)return null;const j=C(O);return Zi.createPortal(s.jsx(fr,{initialText:r,onTextChange:o,fileLabel:d,lineRange:a,isEditing:!1,onSave:c,onCancel:p,maxWidth:j}),O,x)})()]})}function Ho(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=sn.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=Xl.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=Xl.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,Mi(Ef,{fallback:!0}),Mi(Ff),Mi(c),Mi(p)]}const hx=180,Ku=Nf.define(),xx=1,bx=2,yx=4,Ec=new Map,vx=(t,e)=>{const n=`${t}|${e}`,a=Ec.get(n);if(a)return a;let i="";t&&(i+=`color:${t};`),e&xx&&(i+="font-style:italic;"),e&bx&&(i+="font-weight:bold;"),e&yx&&(i+="text-decoration:underline;");const r=Tr.mark({attributes:{style:i}});return Ec.set(n,r),r},wx=(t,e)=>{const n=new pl,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,g]of o){if(p<=0)continue;const m=c,w=Math.min(c+p,d.to);c+=p,!(w<=m)&&(!u&&!g||n.add(m,w,vx(u,g)))}}return n.finish()},jx=ju.define({create(){return Tr.none},update(t,e){let n=t.map(e.changes);for(const a of e.effects)a.is(Ku)&&(n=a.value);return n},provide:t=>sn.decorations.from(t)}),kx=t=>wu.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)},hx)}async tokenize(e){const n=++this.generation,a=e.state.doc.toString(),i=await ep(a,t.language,t.themeName,t.theme);i&&n===this.generation&&e.state.doc.length===a.length&&e.dispatch({effects:Ku.of(wx(e,i))})}destroy(){this.timer&&clearTimeout(this.timer)}}),Bu=t=>[jx,kx(t)],Dc=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function _u(t){const e=Ze.c(131),{t:n}=ot(),{open:a,onOpenChange:i,target:r,projectDirectory:o,submitting:d,allowRunAsGoal:c,onConfirm:p}=t,u=d===void 0?!1:d,g=c===void 0?!1:c;let m;e[0]!==g?(m=g&&!ds(),e[0]=g,e[1]=m):m=e[1];const w=m,h=pt(Mx),f=pt(Rx),x=Va(Dx),k=pt(Ex),y=pt(Ax),C=pt(Tx),O=pt(Px),j=pt(Ix);let N;e[2]!==j||e[3]!==C||e[4]!==y||e[5]!==O?(N=()=>Dc({providerID:y,modelID:C,variant:O,agent:j}),e[2]=j,e[3]=C,e[4]=y,e[5]=O,e[6]=N):N=e[6];const[b,I]=l.useState(N);let B,T;e[7]!==x||e[8]!==f||e[9]!==h||e[10]!==a||e[11]!==o?(B=()=>{a&&(h({directory:o,source:"todoSendDialog"}),f({directory:o}),x())},T=[a,h,f,x,o],e[7]=x,e[8]=f,e[9]=h,e[10]=a,e[11]=o,e[12]=B,e[13]=T):(B=e[12],T=e[13]),l.useEffect(B,T);let D,S;e[14]!==j||e[15]!==C||e[16]!==y||e[17]!==O||e[18]!==a?(D=()=>{a&&I(Dc({providerID:y,modelID:C,variant:O,agent:j}))},S=[a,y,C,O,j],e[14]=j,e[15]=C,e[16]=y,e[17]=O,e[18]=a,e[19]=D,e[20]=S):(D=e[19],S=e[20]),l.useEffect(D,S);let F,R;e[21]!==b.modelID||e[22]!==b.providerID||e[23]!==a||e[24]!==k?(F=()=>{if(!a||k.length===0)return;const J=k.find(we=>we.id===b.providerID)??k[0],v=Array.isArray(J?.models)?J.models:[],ue=v.some(we=>we.id===b.modelID),Ne=v[0]?.id??"";J?.id===b.providerID&&ue||I(we=>({...we,providerID:J?.id??"",modelID:ue?we.modelID:Ne,variant:""}))},R=[a,k,b.providerID,b.modelID],e[21]=b.modelID,e[22]=b.providerID,e[23]=a,e[24]=k,e[25]=F,e[26]=R):(F=e[25],R=e[26]),l.useEffect(F,R);const z=Cx;let q;if(e[27]!==b.modelID||e[28]!==b.providerID||e[29]!==k){let J;e[31]!==b.providerID?(J=ue=>ue.id===b.providerID,e[31]=b.providerID,e[32]=J):J=e[32],q=k.find(J)?.models?.find(ue=>ue.id===b.modelID),e[27]=b.modelID,e[28]=b.providerID,e[29]=k,e[30]=q}else q=e[30];const H=q;let Z;e[33]!==H?(Z=H?.variants?Object.keys(H.variants):[],e[33]=H,e[34]=Z):Z=e[34];const W=Z,A=W.length>0;let X,te;e[35]!==b.variant||e[36]!==A?(X=()=>{A||!b.variant||I(Sx)},te=[A,b.variant],e[35]=b.variant,e[36]=A,e[37]=X,e[38]=te):(X=e[37],te=e[38]),l.useEffect(X,te);let E;e[39]!==b.modelID||e[40]!==b.providerID?(E=b.providerID.trim().length>0&&b.modelID.trim().length>0,e[39]=b.modelID,e[40]=b.providerID,e[41]=E):E=e[41];const P=E;let _;e[42]!==P||e[43]!==b||e[44]!==p||e[45]!==u?(_=()=>{!P||u||p(b)},e[42]=P,e[43]=b,e[44]=p,e[45]=u,e[46]=_):_=e[46];const L=_;let V,Y;e[47]!==L||e[48]!==a?(V=()=>{if(!a)return;const J=v=>{(v.metaKey||v.ctrlKey)&&v.key==="Enter"&&(v.preventDefault(),L())};return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},Y=[a,L],e[47]=L,e[48]=a,e[49]=V,e[50]=Y):(V=e[49],Y=e[50]),l.useEffect(V,Y);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 me=G;let ae;e[54]!==i||e[55]!==u?(ae=J=>{u||i(J)},e[54]=i,e[55]=u,e[56]=ae):ae=e[56];let xe;e[57]!==me?(xe=s.jsx(Ut,{children:s.jsx(_t,{children:me})}),e[57]=me,e[58]=xe):xe=e[58];let be;e[59]!==n?(be=n("chat.modelControls.model"),e[59]=n,e[60]=be):be=e[60];let ie;e[61]!==be?(ie=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:be}),e[61]=be,e[62]=ie):ie=e[62];let pe;e[63]===Symbol.for("react.memo_cache_sentinel")?(pe=(J,v)=>{I(ue=>({...ue,providerID:J,modelID:v,variant:""}))},e[63]=pe):pe=e[63];let Ie;e[64]!==b.modelID||e[65]!==b.providerID?(Ie=s.jsx(la,{providerId:b.providerID,modelId:b.modelID,className:"max-w-[320px] justify-between",dropdownPortalToBody:!0,onChange:pe}),e[64]=b.modelID,e[65]=b.providerID,e[66]=Ie):Ie=e[66];let re;e[67]!==ie||e[68]!==Ie?(re=s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[ie,Ie]}),e[67]=ie,e[68]=Ie,e[69]=re):re=e[69];let ce;e[70]!==n?(ce=n("sessions.scheduledTasks.editor.thinkingLevel.label"),e[70]=n,e[71]=ce):ce=e[71];let ge;e[72]!==ce?(ge=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:ce}),e[72]=ce,e[73]=ge):ge=e[73];const oe=!A;let de;e[74]===Symbol.for("react.memo_cache_sentinel")?(de=J=>I(v=>({...v,variant:J})),e[74]=de):de=e[74];let le;e[75]!==b.variant||e[76]!==oe||e[77]!==W?(le=s.jsx(tp,{value:b.variant,options:W,disabled:oe,onChange:de}),e[75]=b.variant,e[76]=oe,e[77]=W,e[78]=le):le=e[78];let he;e[79]!==ge||e[80]!==le?(he=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[ge,le]}),e[79]=ge,e[80]=le,e[81]=he):he=e[81];let De;e[82]!==n?(De=n("sessions.scheduledTasks.editor.agent.label"),e[82]=n,e[83]=De):De=e[83];let Le;e[84]!==De?(Le=s.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:De}),e[84]=De,e[85]=Le):Le=e[85];let Ke;e[86]===Symbol.for("react.memo_cache_sentinel")?(Ke=J=>I(v=>({...v,agent:J})),e[86]=Ke):Ke=e[86];let Fe;e[87]!==b.agent?(Fe=s.jsx(ll,{agentName:b.agent,filter:z,dropdownPortalToBody:!0,onChange:Ke}),e[87]=b.agent,e[88]=Fe):Fe=e[88];let Me;e[89]!==Le||e[90]!==Fe?(Me=s.jsxs("div",{className:"flex flex-col gap-1.5",children:[Le,Fe]}),e[89]=Le,e[90]=Fe,e[91]=Me):Me=e[91];let Be;e[92]!==re||e[93]!==he||e[94]!==Me?(Be=s.jsxs("div",{className:"flex flex-col gap-4",children:[re,he,Me]}),e[92]=re,e[93]=he,e[94]=Me,e[95]=Be):Be=e[95];const Ge=`flex items-center gap-3 ${w?"justify-between":"justify-end"}`;let Ve;e[96]!==b.runAsGoal||e[97]!==w||e[98]!==u||e[99]!==n?(Ve=w?s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(rn,{checked:b.runAsGoal===!0,onChange:J=>I(v=>({...v,runAsGoal:J})),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:()=>I(Nx),children:n("sessions.scheduledTasks.editor.goal.label")})]}):null,e[96]=b.runAsGoal,e[97]=w,e[98]=u,e[99]=n,e[100]=Ve):Ve=e[100];let Ue;e[101]!==i?(Ue=()=>i(!1),e[101]=i,e[102]=Ue):Ue=e[102];let He;e[103]!==n?(He=n("rightSidebar.contextNotesTodo.sendDialog.actions.cancel"),e[103]=n,e[104]=He):He=e[104];let _e;e[105]!==u||e[106]!==Ue||e[107]!==He?(_e=s.jsx(ee,{variant:"ghost",size:"sm",onClick:Ue,disabled:u,children:He}),e[105]=u,e[106]=Ue,e[107]=He,e[108]=_e):_e=e[108];const Oe=!P||u;let se;e[109]!==u||e[110]!==n?(se=n(u?"rightSidebar.contextNotesTodo.sendDialog.actions.sending":"rightSidebar.contextNotesTodo.sendDialog.actions.send"),e[109]=u,e[110]=n,e[111]=se):se=e[111];let ye;e[112]!==L||e[113]!==Oe||e[114]!==se?(ye=s.jsx(ee,{size:"sm",onClick:L,disabled:Oe,children:se}),e[112]=L,e[113]=Oe,e[114]=se,e[115]=ye):ye=e[115];let ke;e[116]!==_e||e[117]!==ye?(ke=s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[_e,ye]}),e[116]=_e,e[117]=ye,e[118]=ke):ke=e[118];let ze;e[119]!==Ge||e[120]!==Ve||e[121]!==ke?(ze=s.jsxs("div",{className:Ge,children:[Ve,ke]}),e[119]=Ge,e[120]=Ve,e[121]=ke,e[122]=ze):ze=e[122];let $;e[123]!==xe||e[124]!==Be||e[125]!==ze?($=s.jsxs(Bt,{className:"max-w-md overflow-visible",children:[xe,Be,ze]}),e[123]=xe,e[124]=Be,e[125]=ze,e[126]=$):$=e[126];let Ee;return e[127]!==a||e[128]!==ae||e[129]!==$?(Ee=s.jsx(Kt,{open:a,onOpenChange:ae,children:$}),e[127]=a,e[128]=ae,e[129]=$,e[130]=Ee):Ee=e[130],Ee}function Nx(t){return{...t,runAsGoal:t.runAsGoal!==!0}}function Sx(t){return{...t,variant:""}}function Cx(t){return sp(t.mode)}function Ix(t){return t.currentAgentName||""}function Px(t){return t.currentVariant||""}function Tx(t){return t.currentModelId}function Ax(t){return t.currentProviderId}function Ex(t){return t.providers}function Dx(t){return t.loadAgents}function Rx(t){return t.loadAgents}function Mx(t){return t.loadProviders}const nn=t=>{if(!t)return"";const e=t.replace(/\\/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")},Qr=(t,e)=>{const n=nn(t),a=e.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!n||n==="/"?`/${a}`:`${n}/${a}`},Lx=(t,e,n)=>Qr(Qr(Qr(t,".opencode"),"plans"),`${e}-${n}.md`),Fx=(t,e)=>`~/.opencode/plans/${t}-${e}.md`,Ox=(t,e)=>{const n=t.trim();return n.startsWith("~")?n==="~"?e||n:(n.startsWith("~/")||n.startsWith("~\\"))&&e?`${e}${n.slice(1)}`:n:n},zx=(t,e)=>{const n=nn(e.currentDirectory),a=nn(e.homeDirectory),i=nn(t);return n&&i.startsWith(n+"/")?i.slice(n.length+1):a&&i===a?"~":a&&i.startsWith(a+"/")?`~${i.slice(a.length)}`:i},Kx=(t,e,n)=>{const a=nn(t.trim());if(!a)return null;const i=n?e.find(o=>o.id===n)??null:null;if(i?.path){const o=nn(i.path);if(a===o||a.startsWith(`${o}/`))return{id:i.id,path:i.path}}const r=e.filter(o=>{const d=nn(o.path);return a===d||a.startsWith(`${d}/`)}).sort((o,d)=>nn(d.path).length-nn(o.path).length)[0];return r?{id:r.id,path:r.path}:null},gS=({targetPath:t=null,onNavigatedToChat:e})=>{const{t:n}=ot(),a=es(v=>v.currentSessionId),i=es(v=>v.createSession),r=es(v=>v.initializeNewOpenChamberSession),o=es(v=>v.sendMessage),d=es(v=>v.setCurrentSession),c=au(),p=Cs(v=>v.homeDirectory),u=np(v=>v.planModeEnabled),g=is(v=>v.projects),m=is(v=>v.activeProjectId),w=Sr(v=>v.directories),h=ol()??"",f=je(v=>v.setActiveMainTab),x=je(v=>v.setSessionSwitcherOpen),k=Ha(),{isMobile:y}=Hs(),{currentTheme:C}=Wa(),O=l.useMemo(()=>a?c.find(v=>v.id===a)??null:null,[a,c]),j=l.useMemo(()=>{const v=typeof O?.directory=="string"?O.directory:"";return nn(v||"")},[O?.directory]),N=l.useMemo(()=>nn(h||j),[h,j]),b=l.useMemo(()=>Kx(N,g,m),[m,N,g]),I=l.useMemo(()=>b?w.get(b.path)?.isGitRepo===!0:!1,[b,w]),[B,T]=l.useState(null),[D,S]=l.useState(!1),[F,R]=l.useState(null),z=l.useMemo(()=>!F||!j||!p?F:zx(F,{currentDirectory:j,homeDirectory:p}),[F,j,p]),[q,H]=l.useState(""),{isPlaying:Z,play:W,stop:A}=ap(),X=pt(v=>v.showMessageTTSButtons),[te,E]=l.useState(null),P=l.useMemo(()=>z&&z.split("/").pop()||n("planView.file.defaultName"),[z,n]),_=l.useMemo(()=>q.trim()&&ip(q).title||n("planView.title.default"),[q,n]),L=l.useMemo(()=>_.trim()||n("planView.title.default"),[_,n]),[V,Y]=l.useState(!1),[G,me]=l.useState(!1),[ae,xe]=l.useState("edit"),be=l.useRef(null),[ie,pe]=l.useState(null),Ie=l.useRef(null),re=l.useRef(null),ce="openchamber:plan:md-viewer-mode";l.useEffect(()=>{try{const v=localStorage.getItem(ce);if(!v)return;const ue=JSON.parse(v);(ue==="preview"||ue==="edit")&&xe(ue)}catch{}},[]);const ge=l.useCallback(v=>{xe(v);try{localStorage.setItem(ce,JSON.stringify(v))}catch{}},[]),oe=l.useRef(!1),de=l.useRef(null),[le,he]=l.useState(!1);l.useEffect(()=>{const v=()=>{oe.current=!1,de.current=null,he(!1)};return document.addEventListener("mouseup",v),()=>document.removeEventListener("mouseup",v)},[]);const De=l.useCallback((v,ue)=>{const Ne=v.split(`
|
|
4
|
+
`),we=Math.max(1,ue.start),qe=Math.min(Ne.length,ue.end);return we>qe?"":Ne.slice(we-1,qe).join(`
|
|
5
|
+
`)},[]),Le=zu({source:"plan",fileLabel:P,language:F&&Ro(F)||"markdown",getCodeForRange:v=>De(q,Vo(v)),toStoreRange:v=>({startLine:v.start,endLine:v.end}),fromDraftRange:v=>({start:v.startLine,end:v.endLine})}),{drafts:Ke,commentText:Fe,setCommentText:Me,editingDraftId:Be,setSelection:Ge,saveComment:Ve,cancel:Ue,reset:He,startEdit:_e,deleteDraft:Oe}=Le;l.useEffect(()=>{pe(null),He()},[q,He]),l.useEffect(()=>{Ge(ie)},[ie,Ge]);const se=l.useCallback(()=>{pe(null),Ue()},[Ue]),ye=l.useCallback((v,ue)=>{ue&&pe(ue),Ve(v,ue??ie??void 0),pe(null)},[ie,Ve]);l.useEffect(()=>{if(!ie)return;const v=Ne=>{const we=Ne.target;we.closest('[data-comment-card="true"]')||we.closest('[data-comment-input="true"]')||we.closest(".oc-block-widget")||we.closest(".cm-gutterElement")||we.closest("[data-sonner-toast]")||we.closest("[data-sonner-toaster]")||Fe.trim()||(pe(null),Ue())},ue=window.setTimeout(()=>{document.addEventListener("click",v)},100);return()=>{window.clearTimeout(ue),document.removeEventListener("click",v)}},[Ue,Fe,Be,y,ie]);const ke=je(v=>v.editorFontSize),ze=l.useMemo(()=>{const v=F?Ro(F):null,ue=!!v&&v!=="markdown",Ne=[Ho(C,ue?{syntaxColors:!1,fontSize:ke}:{fontSize:ke})],we=Mo(F||"plan.md");return we&&Ne.push(we),ue&&v&&Ne.push(Bu({language:v,themeName:C.metadata.id,theme:mr(C)})),Ne.push(sn.lineWrapping),Ne},[C,F,ke]);l.useEffect(()=>{if(!u&&!t){R(null),H(""),Y(!1);return}let v=!1;const ue=async we=>{if(k.files?.readFile)return(await k.files.readFile(we))?.content??"";const qe=an()?.files;if(qe?.readFile)return(await qe.readFile(we,{optional:!0}))?.content??"";const it=await ht(`/api/fs/read?path=${encodeURIComponent(we)}&optional=true`,{cache:"no-store"});if(!it.ok)throw new Error(`Failed to read plan file (${it.status})`);return it.text()};return(async()=>{if(R(null),H(""),E(null),t){Y(!0);try{const we=await ue(t);if(v)return;R(t),H(we)}catch{if(v)return;R(null),H("")}finally{v||Y(!1)}return}if(!O?.slug||!O?.time?.created||!j){R(null),H("");return}Y(!0);try{const we=Lx(j,O.time.created,O.slug),qe=Ox(Fx(O.time.created,O.slug),p||null);let it=null,st=null;try{st=await ue(we),it=we}catch{}if(!it)try{st=await ue(qe),it=qe}catch{}if(v)return;if(!it||st===null){R(null),H("");return}R(it),H(st)}catch{if(v)return;R(null),H("")}finally{v||Y(!1)}})(),()=>{v=!0}},[p,u,k.files,j,O?.slug,O?.time?.created,t]),l.useEffect(()=>{if(!F){E(null);return}const v=window.setTimeout(async()=>{E(null);try{if(k.files?.writeFile){if(!(await k.files.writeFile(F,q))?.success)throw new Error(n("planView.error.writeFailed"))}else{const ue=await ht("/api/fs/write",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:F,content:q})});if(!ue.ok)throw new Error(n("planView.error.writePlanFileFailed",{status:ue.status}))}}catch(ue){E(ue instanceof Error?ue.message:n("planView.error.saveFailed"))}},350);return()=>{window.clearTimeout(v)}},[q,F,k.files,n]),l.useEffect(()=>()=>{be.current!==null&&window.clearTimeout(be.current)},[]);const $=l.useCallback(()=>{f("chat"),x(!1),e?.()},[e,f,x]),Ee=l.useCallback(async v=>{if(!b||!B)return;const ue=await Un(B.action==="improve"?"plan.improve.visible":"plan.implement.visible",{plan_title:L}),we=[{synthetic:!0,text:await Un(B.action==="improve"?"plan.improve.instructions":"plan.implement.instructions",{plan_title:L,plan_path:F??""})}];S(!0);try{$();let qe=null,it=b.path;if(B.target==="worktree"){if(!I)return;const lt=await iu(b.path,ru());if(!lt?.id)return;qe=lt.id,it=lt.path}else{const lt=await i(void 0,b.path,null);if(!lt?.id)return;qe=lt.id,it=lt.directory??b.path,r(lt.id,pt.getState().agents??[])}if(!qe)return;const st=cl.getState();st.saveSessionModelSelection(qe,v.providerID,v.modelID),v.agent.trim()&&(st.saveSessionAgentSelection(qe,v.agent),st.saveAgentModelForSession(qe,v.agent,v.providerID,v.modelID),st.saveAgentModelVariantForSession(qe,v.agent,v.providerID,v.modelID,v.variant||void 0)),d(qe,it);const rt=v.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.","",q].join(`
|
|
6
|
+
`):null;rp.getState().setArmed(v.runAsGoal===!0,rt),await o(ue,v.providerID,v.modelID,v.agent.trim()||void 0,void 0,void 0,we,v.variant||void 0),T(null)}finally{S(!1)}},[I,q,i,b,r,B,F,$,o,L,d]),J=l.useMemo(()=>mx({drafts:Ke,editingDraftId:Be,commentText:Fe,onTextChange:Me,selection:ie,isDragging:le,fileLabel:P,newWidgetId:"plan-new-comment-input",mapDraftToRange:v=>({start:v.startLine,end:v.endLine}),onSave:ye,onCancel:se,onEdit:v=>{_e(v),pe({start:v.startLine,end:v.endLine})},onDelete:Oe}),[Fe,Oe,Be,se,ye,le,ie,Ke,P,Me,_e]);return s.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden bg-background",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"typography-ui-label font-medium truncate",children:_}),te?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:!q.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:()=>T({action:"improve",target:"session"}),children:n("planView.actions.sendToNewSession")}),s.jsx(as,{onClick:()=>T({action:"improve",target:"worktree"}),disabled:!I,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:!q.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:()=>T({action:"implement",target:"session"}),children:n("planView.actions.sendToNewSession")}),s.jsx(as,{onClick:()=>T({action:"implement",target:"worktree"}),disabled:!I,children:n("planView.actions.sendToNewWorktreeSession")})]})]}),s.jsx(Fu,{currentMode:ae,onToggle:()=>ge(ae==="preview"?"edit":"preview")}),ae==="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():q.trim()&&W(q)},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 oa(q)).ok&&(me(!0),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{me(!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(_u,{open:B!==null,onOpenChange:v=>{!v&&!D&&T(null)},target:B?.target??"session",projectDirectory:b?.path??null,submitting:D,allowRunAsGoal:!0,onConfirm:Ee}),s.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:s.jsx(zs,{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:ae==="preview"?s.jsx("div",{className:"h-full overflow-auto p-3",children:s.jsx(wn,{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(ur,{content:q,className:"typography-markdown-body",enableFileReferences:!1})})}):s.jsx("div",{className:"relative h-full",ref:re,children:s.jsx($o,{value:q,onChange:H,readOnly:!1,className:"h-full",extensions:ze,onViewReady:v=>{Ie.current=v},onViewDestroy:()=>{Ie.current=null},blockWidgets:J,highlightLines:ie?{start:Math.min(ie.start,ie.end),end:Math.max(ie.start,ie.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(v,ue,Ne)=>{if(!(Ne instanceof MouseEvent)||Ne.button!==0)return!1;Ne.preventDefault();const we=v.state.doc.lineAt(ue.from).number;if(ie&&!Ne.shiftKey&&Math.min(ie.start,ie.end)===we&&Math.max(ie.start,ie.end)===we)return pe(null),Ue(),oe.current=!1,de.current=null,he(!1),!0;if(y&&ie&&!Ne.shiftKey){const qe=Math.min(ie.start,ie.end,we),it=Math.max(ie.start,ie.end,we);return pe({start:qe,end:it}),oe.current=!1,de.current=null,he(!1),!0}if(oe.current=!0,de.current=we,he(!0),ie&&Ne.shiftKey){const qe=Math.min(ie.start,we),it=Math.max(ie.end,we);pe({start:qe,end:it})}else pe({start:we,end:we});return!0},mouseover:(v,ue,Ne)=>{if(!(Ne instanceof MouseEvent)||Ne.buttons!==1||!oe.current||de.current===null)return!1;const we=v.state.doc.lineAt(ue.from).number,qe=Math.min(de.current,we),it=Math.max(de.current,we);return pe({start:qe,end:it}),he(!0),!1},mouseup:()=>(oe.current=!1,de.current=null,he(!1),!1)}}})})})})})})]})},Oi=()=>{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},Rc=t=>t?Object.entries(t).map(([e,n])=>({key:e,value:n})):[],Mc=t=>{const e=t.filter(n=>n.key.trim());if(e.length!==0)return Object.fromEntries(e.map(n=>[n.key.trim(),n.value]))},zi=t=>typeof t!="string"?void 0:t.trim()||void 0,Xr=800,Bx=5e3,_x="__default__",Wo=new Map,Zr=new Map,Uu=t=>t?.trim()||_x,eo=t=>{Wo.delete(Uu(t))},$a=fn()(Ja(vi((t,e)=>({mcpServers:[],selectedMcpName:null,isLoading:!1,mcpDraft:null,setSelectedMcp:n=>t({selectedMcpName:n}),setMcpDraft:n=>t({mcpDraft:n}),loadMcpConfigs:async n=>{const a=Oi(),i=Uu(a),r=Date.now(),o=Wo.get(i)??0,d=e().mcpServers.length>0;if(!n?.force&&d&&r-o<Bx)return!0;const c=Zr.get(i);if(!n?.force&&c)return c;const p=(async()=>{t({isLoading:!0});try{const u=a?`?directory=${encodeURIComponent(a)}`:"",g=await ht(`/api/config/mcp${u}`,{headers:a?{"x-opencode-directory":a}:void 0});if(!g.ok)throw new Error("Failed to load MCP configs");const m=await g.json();return t({mcpServers:m,isLoading:!1}),Wo.set(i,Date.now()),!0}catch(u){return console.error("[McpConfigStore] Failed to load MCP configs:",u),t({isLoading:!1}),!1}})();Zr.set(i,p);try{return await p}finally{Zr.delete(i)}},createMcp:async n=>{er("Creating MCP server configuration…");let a=!1;try{const i=Lc(n),r=Oi(),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 eo(r),c?.requiresReload?(a=!0,await tr({message:c.message,delayMs:c.reloadDelayMs??Xr,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||sr()}},updateMcp:async(n,a)=>{er("Updating MCP server configuration…");let i=!1;try{const r=Lc(a),o=Oi(),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 eo(o),p?.requiresReload?(i=!0,await tr({message:p.message,delayMs:p.reloadDelayMs??Xr,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||sr()}},deleteMcp:async n=>{er("Deleting MCP server configuration…");let a=!1;try{const i=Oi(),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 eo(i),d?.requiresReload&&(a=!0,await tr({message:d.message,delayMs:d.reloadDelayMs??Xr,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||sr()}},getMcpByName:n=>e().mcpServers.find(a=>a.name===n)}),{name:"mcp-config-store",storage:Pr(),partialize:t=>({selectedMcpName:t.selectedMcpName})}),{name:"mcp-config-store"}));function Lc(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=Mc(t.environment)??{}),t.headers!==void 0&&(e.headers=Mc(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:zi(t.oauthClientId),clientSecret:zi(t.oauthClientSecret),scope:zi(t.oauthScope),redirectUri:zi(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 $u=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),wi=t=>{const e=Ze.c(39),{className:n}=t,{t:a}=ot(),i=is(Ux),r=is($x),o=is(Vx),d=ds();let c;e[0]!==i?(c=[...i].sort(Hx),e[0]=i,e[1]=c):c=e[1];const p=c;let u;e:{if(p.length===0){u=null;break e}let R;e[2]!==r||e[3]!==p?(R=p.find(z=>z.id===r)??p[0],e[2]=r,e[3]=p,e[4]=R):R=e[4],u=R}const g=u;if(d||p.length===0)return null;let m;e[5]!==g||e[6]!==a?(m=g?.label&&g.label.trim().length>0?g.label:g?.path.split("/").filter(Boolean).pop()||g?.path||a("settings.shared.projectSelector.fallbackProject"),e[5]=g,e[6]=a,e[7]=m):m=e[7];const w=m;let h;e[8]!==w?(h=$u(w),e[8]=w,e[9]=h):h=e[9];const f=h;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,O;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"),O=s.jsx(K,{name:"folder",className:"h-4 w-4 opacity-70"}),e[16]=C,e[17]=O):(C=e[16],O=e[17]);let j;e[18]!==f?(j=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:f}),e[18]=f,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 b;e[21]!==j||e[22]!==k||e[23]!==y?(b=s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":k,title:y,className:C,children:[O,j,N]})}),e[21]=j,e[22]=k,e[23]=y,e[24]=b):b=e[24];const I=g?.id??"";let B;e[25]!==o?(B=R=>{R&&o(R)},e[25]=o,e[26]=B):B=e[26];let T;e[27]!==p?(T=p.map(Wx),e[27]=p,e[28]=T):T=e[28];let D;e[29]!==I||e[30]!==B||e[31]!==T?(D=s.jsx(hs,{align:"start",className:"w-auto",children:s.jsx(lp,{value:I,onValueChange:B,children:T})}),e[29]=I,e[30]=B,e[31]=T,e[32]=D):D=e[32];let S;e[33]!==b||e[34]!==D?(S=s.jsxs(fs,{children:[b,D]}),e[33]=b,e[34]=D,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 Ux(t){return t.projects}function $x(t){return t.activeProjectId}function Vx(t){return t.setActiveProject}function Hx(t,e){return(t.label||t.path).localeCompare(e.label||e.path)}function Wx(t){const e=t.label?.trim()?t.label.trim():t.path.split("/").filter(Boolean).pop()||t.path,n=$u(e);return s.jsx(op,{value:t.id,children:s.jsx("span",{className:"min-w-0 truncate typography-ui",children:n})},t.id)}function Gx(t,e){return`opencode:sidebar-group:${t}:${e}`}const Go=t=>{const e=Ze.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=Gx(i,n),e[0]=n,e[1]=i,e[2]=c):c=e[2];const p=c,u=l.useId();let g;e[3]!==d||e[4]!==p?(g=()=>{try{const D=localStorage.getItem(p);if(D!==null)return D==="true"}catch{}return d},e[3]=d,e[4]=p,e[5]=g):g=e[5];const[m,w]=ve.useState(g);let h,f;e[6]!==m||e[7]!==p?(h=()=>{try{localStorage.setItem(p,String(m))}catch{}},f=[p,m],e[6]=m,e[7]=p,e[8]=h,e[9]=f):(h=e[8],f=e[9]),ve.useEffect(h,f);let x;e[10]===Symbol.for("react.memo_cache_sentinel")?(x=()=>w(qx),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 O;e[14]!==C?(O=s.jsx(K,{name:"arrow-down-s",className:C}),e[14]=C,e[15]=O):O=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 b;e[20]!==u||e[21]!==m||e[22]!==O||e[23]!==j||e[24]!==N?(b=s.jsxs("button",{type:"button",onClick:x,"aria-expanded":m,"aria-controls":u,className:k,children:[O,j,N]}),e[20]=u,e[21]=m,e[22]=O,e[23]=j,e[24]=N,e[25]=b):b=e[25];const I=!m;let B;e[26]!==o||e[27]!==u||e[28]!==I?(B=s.jsx("div",{id:u,hidden:I,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]=I,e[29]=B):B=e[29];let T;return e[30]!==b||e[31]!==B?(T=s.jsxs("div",{children:[b,B]}),e[30]=b,e[31]=B,e[32]=T):T=e[32],T};function qx(t){return!t}const Jx=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},Yx=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())},Fc=t=>{const e=Yx(Jx(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},Qx=({onItemSelect:t})=>{const{t:e}=ot(),[n,a]=l.useState(null),[i,r]=l.useState(""),[o,d]=l.useState(null),[c,p]=l.useState(null),[u,g]=l.useState(!1),[m,w]=l.useState(null),{selectedAgentName:h,agents:f,setSelectedAgent:x,setAgentDraft:k,createAgent:y,deleteAgent:C,loadAgents:O}=Va(Ws(A=>({selectedAgentName:A.selectedAgentName,agents:A.agents,setSelectedAgent:A.setSelectedAgent,setAgentDraft:A.setAgentDraft,createAgent:A.createAgent,deleteAgent:A.deleteAgent,loadAgents:A.loadAgents})));l.useEffect(()=>{O()},[O]);const j="bg-background",N=()=>{const A="new-agent";let X=A,te=1;for(;f.some(E=>E.name===X);)X=`${A}-${te}`,te++;k({name:X,scope:"user"}),x(X),t?.()},b=async A=>{if(za(A)){Q.error(e("settings.agents.sidebar.toast.builtInCannotDelete"));return}d(A),p("delete")},I=async A=>{za(A)&&(d(A),p("reset"))},B=()=>{d(null),p(null)},T=async()=>{if(!(!o||!c)){g(!0);try{const A=await C(o.name,o.scope);A.ok?(A.requiresManualRestart?Q.warning(e("settings.agents.page.toast.savedManualRestart")):c==="delete"?Q.success(e("settings.agents.sidebar.toast.agentDeleted",{name:o.name})):Q.success(e("settings.agents.sidebar.toast.agentReset",{name:o.name})),B()):c==="delete"?Q.error(e("settings.agents.sidebar.toast.deleteFailed")):Q.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"?Q.error(e(te?"settings.agents.sidebar.toast.definitionNotFound":"settings.agents.sidebar.toast.deleteFailed")):Q.error(e("settings.agents.sidebar.toast.resetFailed"))}g(!1)}},D=A=>{const X=A.name;let te=1,E=`${X}-copy`;for(;f.some(V=>V.name===E);)te++,E=`${X}-copy-${te}`;const P=A,_=A.model?.providerID&&A.model?.modelID?`${A.model.providerID}/${A.model.modelID}`:null,L=A;k({name:E,scope:P.scope||"user",description:A.description,model:_,variant:A.variant,temperature:A.temperature,top_p:A.topP,prompt:A.prompt,mode:A.mode,permission:Fc(A.permission),disable:L.disable}),x(E)},S=A=>{r(A.name),a(A)},F=async()=>{if(!n)return;const A=i.trim().replace(/\s+/g,"-");if(!A){Q.error(e("settings.agents.sidebar.toast.agentNameRequired"));return}if(A===n.name){a(null);return}if(f.some(P=>P.name===A)){Q.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,E=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:Fc(n.permission),disable:te.disable,scope:te.scope});if(E.ok){const P=await C(n.name,te.scope);P.ok?(E.requiresManualRestart||P.requiresManualRestart?Q.warning(e("settings.agents.page.toast.savedManualRestart")):Q.success(e("settings.agents.sidebar.toast.agentRenamed",{name:A})),x(A)):Q.error(e("settings.agents.sidebar.toast.removeOldAfterRenameFailed"))}else Q.error(e("settings.agents.sidebar.toast.renameFailed"));a(null)},R=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}},z=f.filter(A=>!cp(A)),q=z.filter(za),H=z.filter(A=>!za(A)),{groupedCustomAgents:Z,ungroupedCustomAgents:W}=ve.useMemo(()=>{const A={},X=[];for(const E of H){const P=E;P.group?(A[P.group]||(A[P.group]=[]),A[P.group].push(E)):X.push(E)}return{groupedCustomAgents:Object.keys(A).sort((E,P)=>E.localeCompare(P)).map(E=>({name:E,agents:A[E]})),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:`${hn} mb-3`,children:e("settings.agents.sidebar.title")}),s.jsx(wi,{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:z.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(zs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:z.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:[q.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")}),q.map(A=>s.jsx(to,{agent:A,isSelected:h===A.name,onSelect:()=>{x(A.name),t?.()},onReset:()=>I(A),onDuplicate:()=>D(A),getAgentModeIcon:R,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(Go,{label:A,count:X.length,storageKey:"agents",children:X.map(te=>s.jsx(to,{agent:te,isSelected:h===te.name,onSelect:()=>{x(te.name),t?.()},onRename:()=>S(te),onDelete:()=>b(te),onDuplicate:()=>D(te),getAgentModeIcon:R,isMenuOpen:m===te.name,onMenuOpenChange:E=>w(E?te.name:null)},te.name))},A)),W.map(A=>s.jsx(to,{agent:A,isSelected:h===A.name,onSelect:()=>{x(A.name),t?.()},onRename:()=>S(A),onDelete:()=>b(A),onDuplicate:()=>D(A),getAgentModeIcon:R,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&&B()},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:B,disabled:u,children:e("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",onClick:T,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(nt,{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")})]})]})})]})},to=t=>{const e=Ze.c(52),{agent:n,isSelected:a,onSelect:i,onDelete:r,onReset:o,onRename:d,onDuplicate:c,getAgentModeIcon:p,isMenuOpen:u,onMenuOpenChange:g}=t,{t:m}=ot(),w=n;let h;e[0]===Symbol.for("react.memo_cache_sentinel")?(h=bi(),e[0]=h):h=e[0];const f=h,[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:E=>{E.stopPropagation(),d()},children:[s.jsx(K,{name:"edit",className:"h-4 w-4 mr-px"}),m("settings.common.actions.rename")]}),s.jsxs(te,{onClick:E=>{E.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:E=>{E.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:E=>{E.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,O=a?"bg-interactive-selection":"hover:bg-interactive-hover";let j;e[7]!==O?(j=fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",O),e[7]=O,e[8]=j):j=e[8];let N;e[9]===Symbol.for("react.memo_cache_sentinel")?(N=f?void 0:te=>{te.preventDefault(),k(!0)},e[9]=N):N=e[9];let b;e[10]!==j?(b=s.jsx("div",{className:j,onContextMenu:N}),e[10]=j,e[11]=b):b=e[11];let I;e[12]!==n.name?(I=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n.name}),e[12]=n.name,e[13]=I):I=e[13];let B;e[14]!==n.mode||e[15]!==p?(B=p(n.mode),e[14]=n.mode,e[15]=p,e[16]=B):B=e[16];let T;e[17]!==n||e[18]!==w.scope||e[19]!==m?(T=(w.scope||za(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:za(n)?m("settings.agents.sidebar.badge.system"):w.scope}),e[17]=n,e[18]=w.scope,e[19]=m,e[20]=T):T=e[20];let D;e[21]!==I||e[22]!==B||e[23]!==T?(D=s.jsxs("div",{className:"flex items-center gap-1.5",children:[I,B,T]}),e[21]=I,e[22]=B,e[23]=T,e[24]=D):D=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]!==D||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:[D,S]}),e[27]=i,e[28]=D,e[29]=S,e[30]=F):F=e[30];let R;e[31]!==g?(R=te=>{te&&k(!1),g(te)},e[31]=g,e[32]=R):R=e[32];let z;e[33]===Symbol.for("react.memo_cache_sentinel")?(z=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]=z):z=e[33];let q;e[34]!==C?(q=s.jsx(hs,{align:"end",className:"w-fit min-w-20",children:C(as)}),e[34]=C,e[35]=q):q=e[35];let H;e[36]!==u||e[37]!==R||e[38]!==q?(H=s.jsxs(fs,{open:u,onOpenChange:R,children:[z,q]}),e[36]=u,e[37]=R,e[38]=q,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 W;e[43]!==Z||e[44]!==b?(W=s.jsx(qn,{render:b,children:Z}),e[43]=Z,e[44]=b,e[45]=W):W=e[45];let A;e[46]!==C?(A=s.jsx(Jn,{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]!==W||e[50]!==A?(X=s.jsxs(Gn,{open:x,onOpenChange:k,children:[W,A]}),e[48]=x,e[49]=W,e[50]=A,e[51]=X):X=e[51],X},ps=t=>{const e=Ze.c(21),{children:n,className:a,outerClassName:i,title:r,titleLeading:o,titleAccessory:d,description:c,headerEnd:p,showSaveStatus:u}=t,g=u===void 0?!1:u,m=r!=null||c!=null||p!=null||g,w=typeof r=="string"||typeof r=="number",h=o!=null||d!=null;let f;e[0]!==i?(f=fe("h-full",i),e[0]=i,e[1]=f):f=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]!==h||e[7]!==p||e[8]!==w||e[9]!==g||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?h?s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o,s.jsx("h1",{className:fe(Uo,"min-w-0 truncate"),children:r}),d]}):s.jsx("h1",{className:Uo,children:r}):r:null,c!=null?typeof c=="string"||typeof c=="number"?s.jsx("p",{className:Mu,children:c}):c:null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[p,g&&s.jsx(Zx,{})]})]}),e[4]=c,e[5]=m,e[6]=h,e[7]=p,e[8]=w,e[9]=g,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]!==f||e[19]!==y?(C=s.jsx(zs,{outerClassName:f,className:"w-full @container",children:y}),e[18]=f,e[19]=y,e[20]=C):C=e[20],C},Xx=500,Zx=()=>{const t=Ze.c(13),{t:e}=ot(),n=l.useSyncExternalStore(Fg,Ul,Ul),[a,i]=l.useState(!1);let r,o;if(t[0]!==n?(r=()=>{if(n!=="saving"){i(!1);return}const u=setTimeout(()=>i(!0),Xx);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 g;t[4]!==e?(g=e("settings.common.status.saveFailed"),t[4]=e,t[5]=g):g=t[5];let m;return t[6]!==g?(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:g})]}),t[6]=g,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},eb=["allow","ask","deny"],mi=t=>t==="allow"||t==="ask"||t==="deny",qo=()=>({global:null,keys:{}}),tb=t=>{const e=qo();if(t==null)return e;if(typeof t=="string")return mi(t)&&(e.global=t),e;if(typeof t!="object"||Array.isArray(t))return e;for(const[n,a]of Object.entries(t)){if(n==="*"){mi(a)&&(e.global=a);continue}const i={action:null,patterns:[]};if(mi(a))i.action=a;else if(a&&typeof a=="object"&&!Array.isArray(a))for(const[r,o]of Object.entries(a))mi(o)&&(r==="*"?i.action=o:i.patterns.push({pattern:r,action:o}));else continue;e.keys[n]=i}return e},Jo=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},sb=(t,e)=>JSON.stringify(Jo(t))===JSON.stringify(Jo(e)),Mn=t=>JSON.parse(JSON.stringify(t)),nb=["edit","external_directory","doom_loop","plan_enter","plan_exit"],ab=new Set(["read","edit","glob","grep","list","bash","task","external_directory","lsp","skill"]),Oc=new Set(["write","patch","apply_patch","multiedit","invalid"]),ib=t=>t.split(/[_-]/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),rb=({agent:t})=>{const{t:e}=ot(),n=Va(P=>P.updateAgent),[a,i]=l.useState(qo),[r,o]=l.useState(qo),[d,c]=l.useState(!0),[p,u]=l.useState(!1),[g,m]=l.useState(!1),[w,h]=l.useState({}),[f,x]=l.useState([]),[k,y]=l.useState(""),[C,O]=l.useState(0),j=t.name;l.useEffect(()=>{let P=!1;return c(!0),u(!1),(async()=>{try{const _=Il(),L=_?`?directory=${encodeURIComponent(_)}`:"",V=await ht(`/api/config/agents/${encodeURIComponent(j)}/config${L}`,{headers:{"Cache-Control":"no-cache",..._?{"x-opencode-directory":_}:{}}});if(!V.ok)throw new Error(String(V.status));const Y=await V.json().catch(()=>null);if(P)return;const G=tb(Y?.config?.permission);i(Mn(G)),o(G)}catch{P||u(!0)}finally{P||c(!1)}})(),()=>{P=!0}},[j,C]),l.useEffect(()=>{let P=!1;return(async()=>{try{const _=await Ps.listToolIds({directory:Il()});!P&&Array.isArray(_)&&x(_.filter(L=>typeof L=="string"&&!Oc.has(L)))}catch{}})(),()=>{P=!0}},[j]);const N=l.useMemo(()=>{const P=t.permission;if(!Array.isArray(P))return[];const _=[];for(const L of P){if(!L||typeof L!="object")continue;const{permission:V,pattern:Y,action:G}=L;typeof V=="string"&&typeof Y=="string"&&mi(G)&&_.push({permission:V,pattern:Y,action:G})}return _},[t]),b=l.useCallback(P=>{const _=N.find(V=>V.permission===P&&V.pattern==="*");if(_)return _.action;const L=N.find(V=>V.permission==="*"&&V.pattern==="*");return L?L.action:null},[N]),I=l.useCallback(P=>{const _=r.keys[P]?.patterns??[],L=new Set(_.map(V=>V.pattern));return N.filter(V=>V.permission===P&&V.pattern!=="*"&&!L.has(V.pattern))},[N,r.keys]),B=l.useMemo(()=>{const P=new Set;for(const _ of f)P.add(_);for(const _ of nb)P.add(_);for(const _ of Object.keys(r.keys))P.add(_);for(const _ of Oc)P.delete(_);return Array.from(P).sort((_,L)=>_.localeCompare(L))},[f,r.keys]),T=l.useMemo(()=>!sb(r,a),[r,a]),D=P=>{o(_=>({..._,global:P}))},S=(P,_)=>{o(L=>{const V=Mn(L),Y=V.keys[P]??{action:null,patterns:[]};return Y.action=_,Y.action===null&&Y.patterns.length===0?delete V.keys[P]:V.keys[P]=Y,V})},F=(P,_,L,V)=>{o(Y=>{const G=Mn(Y),me=G.keys[P]??{action:null,patterns:[]};return me.patterns[_]={pattern:L,action:V},G.keys[P]=me,G})},R=P=>{o(_=>{const L=Mn(_),V=L.keys[P]??{action:null,patterns:[]};return V.patterns.push({pattern:"",action:"allow"}),L.keys[P]=V,L}),h(_=>({..._,[P]:!0}))},z=(P,_)=>{o(L=>{const V=Mn(L),Y=V.keys[P];return Y?(Y.patterns.splice(_,1),Y.action===null&&Y.patterns.length===0&&delete V.keys[P],V):L})},q=()=>{const P=k.trim();!P||P==="*"||(o(_=>{if(_.keys[P])return _;const L=Mn(_);return L.keys[P]={action:"ask",patterns:[]},L}),h(_=>({..._,[P]:!0})),y(""))},H=async()=>{m(!0);try{const P=Jo(r),_=await n(j,{permission:P});_.ok?(i(Mn(r)),Q.success(_.requiresManualRestart?e("settings.agents.page.permissionsEditor.toast.savedRestartRequired"):e("settings.agents.page.permissionsEditor.toast.saved"))):Q.error(e("settings.agents.page.permissionsEditor.toast.saveFailed"))}finally{m(!1)}},Z=()=>{o(Mn(a))},W=P=>e(P==="allow"?"settings.agents.page.permissionsEditor.action.allow":P==="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=P=>[...P?[{value:"inherit",label:P}]:[],...eb.map(_=>({value:_,label:W(_)}))],E=(P,_,L,V=A)=>s.jsx(Qs,{value:P??"inherit",options:te(V),onChange:Y=>_(Y==="inherit"?null:Y),"aria-label":L});return d?s.jsx(dt,{title:e("settings.agents.page.section.toolPermissions"),children:s.jsx("p",{className:Ys,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:()=>O(P=>P+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:T?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:Z,disabled:g,children:e("settings.agents.page.permissionsEditor.actions.discard")}),s.jsx(ee,{size:"xs",className:"!font-normal",onClick:()=>{H()},disabled:g,children:e(g?"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:W(b("*")??"allow")})})]}),E(r.global,D,e("settings.agents.page.permissionsEditor.defaultAria"),X)]}),s.jsx("div",{children:B.map(P=>{const _=r.keys[P]??{action:null,patterns:[]},L=I(P),V=ab.has(P)||_.patterns.length>0,Y=V||L.length>0,G=w[P]===!0,me=b(P);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:Y?()=>h(ae=>({...ae,[P]:!G})):void 0,className:fe("flex min-w-0 items-center gap-1.5 text-left",!Y&&"cursor-default"),"aria-expanded":Y?G:void 0,children:[s.jsx(K,{name:G&&Y?"arrow-down-s":"arrow-right-s",className:fe("h-3.5 w-3.5 shrink-0 text-muted-foreground",!Y&&"opacity-0")}),s.jsx("span",{className:zt,children:ib(P)}),s.jsx("span",{className:"typography-micro font-mono text-muted-foreground/70",children:P}),_.action===null&&me!==null&&s.jsx("span",{className:"typography-micro text-muted-foreground",children:e("settings.agents.page.permissionsEditor.effectiveHint",{action:W(me)})}),_.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(_.patterns.length)})})]}),E(_.action,ae=>S(P,ae),e("settings.agents.page.permissionsEditor.keyAria",{key:P}))]}),G&&Y&&s.jsxs("div",{className:"mt-2 space-y-2 pl-5",children:[_.patterns.map((ae,xe)=>s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(nt,{value:ae.pattern,onChange:be=>F(P,xe,be.target.value,ae.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(Qs,{value:ae.action,options:te(),onChange:be=>F(P,xe,ae.pattern,be),"aria-label":e("settings.agents.page.permissionsEditor.patternActionAria",{key:P})}),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:()=>z(P,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:()=>R(P),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(ae=>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:ae.pattern}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:W(ae.action)})]},`${ae.pattern}-${ae.action}`))]})]})]},P)})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t border-border/40 pt-3",children:[s.jsx(nt,{value:k,onChange:P=>y(P.target.value),onKeyDown:P=>{P.key==="Enter"&&(P.preventDefault(),q())},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:q,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")]})]})]})},ob=(t,e)=>{const n=Wn(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):[]},lb=()=>{const{t}=ot(),e=pt(E=>E.providers),{selectedAgentName:n,getAgentByName:a,createAgent:i,updateAgent:r,agents:o,agentDraft:d,setAgentDraft:c}=Va(Ws(E=>({selectedAgentName:E.selectedAgentName,getAgentByName:E.getAgentByName,createAgent:E.createAgent,updateAgent:E.updateAgent,agents:E.agents,agentDraft:E.agentDraft,setAgentDraft:E.setAgentDraft}))),p=n?a(n):null,u=!!(d&&d.name===n&&!p),[g,m]=l.useState(""),[w,h]=l.useState("user"),[f,x]=l.useState(""),[k,y]=l.useState("subagent"),[C,O]=l.useState(""),[j,N]=l.useState(""),[b,I]=l.useState(void 0),[B,T]=l.useState(void 0),[D,S]=l.useState(""),[F,R]=l.useState(!1),z=l.useRef(null),q=l.useMemo(()=>ob(e,C),[C,e]),H=q.length>0,Z=j||"__default",W=H,A=l.useMemo(()=>j&&!q.includes(j)?[j,...q]:q,[j,q]);l.useEffect(()=>{if(u&&d){const E=d.name||"",P=d.scope||"user",_=d.description||"",L=d.mode||"subagent",V=d.model||"",Y=d.variant||"",G=d.temperature??void 0,me=d.top_p??void 0,ae=d.prompt||"";m(E),h(P),x(_),y(L),O(V),N(Y),I(G),T(me),S(ae),z.current={draftName:E,draftScope:P,description:_,mode:L,model:V,variant:Y,temperature:G,topP:me,prompt:ae};return}if(p&&n===p.name){const E=p.description||"",P=p.mode||"subagent",_=p.model?.providerID&&p.model?.modelID?`${p.model.providerID}/${p.model.modelID}`:"",L=p.variant||"",V=p.temperature??void 0,Y=p.topP??void 0,G=p.prompt||"";x(E),y(P),O(_),N(L),I(V),T(Y),S(G),z.current={draftName:"",draftScope:"user",description:E,mode:P,model:_,variant:L,temperature:V,topP:Y,prompt:G}}},[d,u,p,n]);const X=l.useMemo(()=>{const E=z.current;return E?!!(u&&(g!==E.draftName||w!==E.draftScope)||f!==E.description||k!==E.mode||C!==E.model||j!==E.variant||b!==E.temperature||B!==E.topP||D!==E.prompt):!1},[f,g,w,u,k,C,D,b,B,j]),te=async()=>{const E=u?g.trim().replace(/\s+/g,"-"):n?.trim();if(!E){Q.error(t("settings.agents.sidebar.toast.agentNameRequired"));return}if(u&&o.some(P=>P.name===E)){Q.error(t("settings.agents.sidebar.toast.agentExists"));return}R(!0);try{const P=C.trim(),_=j.trim(),L=D.trim(),V={name:E,...f.trim()?{description:f.trim()}:{},mode:k,model:P===""?null:P,variant:_===""?null:_||void 0,temperature:b??null,top_p:B??null,prompt:L||(u?void 0:null),...u&&w?{scope:w}:{}};let Y;u?(Y=await i(V),Y.ok&&c(null)):Y=await r(E,V),Y.ok?Y.requiresManualRestart?Q.warning(t("settings.agents.page.toast.savedManualRestart")):Q.success(t(u?"settings.agents.page.toast.created":"settings.agents.page.toast.updated")):Q.error(t(u?"settings.agents.page.toast.createFailed":"settings.agents.page.toast.updateFailed"))}catch(P){console.error("Error saving agent:",P);const _=P instanceof Error&&P.message?P.message:t("settings.agents.page.toast.saveUnexpectedError");Q.error(_)}finally{R(!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(nt,{value:g,onChange:E=>m(E.target.value),placeholder:t("settings.agents.page.field.agentNamePlaceholder"),className:"h-7 w-40 px-2"})]}),s.jsxs(Mt,{value:w,onValueChange:E=>h(E),children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[100px]",children:s.jsx(Wt,{placeholder:t("settings.agents.page.field.scopePlaceholder")})}),s.jsxs(Ft,{align:"end",children:[s.jsx(jt,{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(jt,{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:f,onChange:E=>x(E.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(Qs,{"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(la,{providerId:Wn(C)?.providerId??"",modelId:Wn(C)?.modelId??"",onChange:(E,P)=>{O(E&&P?`${E}/${P}`:""),N("")},className:Vn})}),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:W?s.jsxs(Mt,{value:Z,onValueChange:E=>N(E==="__default"?"":E),children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{placeholder:t("settings.agents.page.field.variantPlaceholder"),children:E=>E==="__default"?t("chat.modelControls.default"):E})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"__default",children:t("chat.modelControls.default")}),A.map(E=>s.jsx(jt,{value:E,children:E},E))]})]}):s.jsxs(s.Fragment,{children:[s.jsx(nt,{value:j,onChange:E=>N(E.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(Ms,{value:b,fallbackValue:.7,onValueChange:I,onClear:()=>I(void 0),min:0,max:2,step:.1,inputMode:"decimal",placeholder:"—",emptyLabel:"—",className:"w-16"}),b!==void 0&&s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>I(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(Ms,{value:B,fallbackValue:.9,onValueChange:T,onClear:()=>T(void 0),min:0,max:1,step:.1,inputMode:"decimal",placeholder:"—",emptyLabel:"—",className:"w-16"}),B!==void 0&&s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>T(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:D,onChange:E=>S(E.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(rb,{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")})]})})},cb="~/.config/opencode/AGENTS.md",Vu=async(t,e)=>{const n=await t.json().catch(()=>null);return typeof n?.error=="string"&&n.error.trim()?n.error:e},db=t=>t.length>0&&!t.endsWith(`
|
|
7
|
+
`)?`${t}
|
|
8
|
+
`:t,Ki={prompt:"",optimizeSystemPrompt:!1,responseStyleEnabled:!1,responseStylePreset:"concise",responseStyleCustomInstructions:""},ub=(t,e)=>t==="custom"?e:mp(t),mb=t=>t==="custom"?"custom":ou(t)?t:"concise",zc={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"},so=async(t,e)=>{Js("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 Vu(n,e));Js("saved")}catch(n){throw Js("error"),n}},pb=()=>{const{t}=ot(),e=dp(),[n,a]=l.useState(""),[i,r]=l.useState(!1),[o,d]=l.useState(Ki.responseStyleEnabled),[c,p]=l.useState(Ki.responseStylePreset),[u,g]=l.useState(Ki.responseStyleCustomInstructions),[m,w]=l.useState(!0),[h,f]=l.useState(!1),[x,k]=l.useState(!1),[y,C]=l.useState(""),[O,j]=l.useState(!1),N=l.useRef(null);l.useEffect(()=>{const S=new AbortController;return(async()=>{try{const[R,z]=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 q=Ki;if(R.ok){const H=await R.json();q={...q,optimizeSystemPrompt:H.optimizeSystemPrompt===!0,responseStyleEnabled:H.responseStyleEnabled===!0,responseStylePreset:mb(H.responseStylePreset),responseStyleCustomInstructions:typeof H.responseStyleCustomInstructions=="string"?H.responseStyleCustomInstructions:""},typeof H.globalBehaviorPrompt=="string"&&(q={...q,prompt:H.globalBehaviorPrompt})}if(!q.prompt.trim()&&z.ok){const H=await z.json();typeof H.content=="string"&&(q={...q,prompt:H.content})}a(q.prompt),r(q.optimizeSystemPrompt),j(q.optimizeSystemPrompt),d(q.responseStyleEnabled),p(q.responseStylePreset),g(q.responseStyleCustomInstructions),C(q.prompt),N.current={enabled:q.responseStyleEnabled,preset:q.responseStylePreset,custom:q.responseStyleCustomInstructions}}catch(R){R.name!=="AbortError"&&console.warn("Failed to load behavior settings:",R)}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},R=setTimeout(async()=>{try{await so({responseStyleEnabled:F.enabled,responseStylePreset:F.preset,responseStyleCustomInstructions:F.custom},t("settings.behavior.page.toast.saveFailed")),N.current=F}catch(z){const q=z instanceof Error?z.message:t("settings.behavior.page.toast.saveFailed");Q.error(q)}},400);return()=>clearTimeout(R)},[o,c,u,m,t]);const b=ub(c,u),I=n!==y,B=i!==O,T=async()=>{f(!0);try{const S=db(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 Vu(F,t("settings.behavior.page.toast.saveFailed")));await so({globalBehaviorPrompt:S},t("settings.behavior.page.toast.saveFailed")),a(S),C(S),Q.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");Q.error(F)}finally{f(!1)}},D=async()=>{k(!0);try{await so({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");Q.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");Q.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:()=>{D()},disabled:m||x||!B,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:cb})})]}),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:T,disabled:h||!I||m,size:"xs",className:"!font-normal",children:t(h?"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(Mt,{value:c,onValueChange:S=>p(S),disabled:m||!o,children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{children:S=>S==="custom"?t("settings.behavior.page.responseStyle.option.custom"):ou(S)?t(zc[S]):null})}),s.jsxs(Ft,{children:[up.map(S=>s.jsx(jt,{value:S,children:t(zc[S])},S)),s.jsx(jt,{value:"custom",children:t("settings.behavior.page.responseStyle.option.custom")})]})]})}),s.jsx(Ns,{value:b,onChange:S=>g(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"})]})]})},gb=t=>{const e=Ze.c(169),{onItemSelect:n}=t,{t:a}=ot(),[i,r]=l.useState(null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,g]=l.useState(null),[m,w]=l.useState(!1),[h,f]=l.useState(null),{selectedCommandName:x,commands:k,setSelectedCommand:y,setCommandDraft:C,createCommand:O,deleteCommand:j,loadCommands:N}=Cr(Ws(fb)),b=In(hb),I=In(xb);let B,T;e[0]!==N||e[1]!==I?(B=()=>{N(),I()},T=[N,I],e[0]=N,e[1]=I,e[2]=B,e[3]=T):(B=e[2],T=e[3]),l.useEffect(B,T);let D;e[4]!==b?(D=new Set(b.map(bb)),e[4]=b,e[5]=D):D=e[5];const S=D;let F;if(e[6]!==k||e[7]!==S){let Ce;e[9]!==S?(Ce=Qe=>!S.has(Qe.name),e[9]=S,e[10]=Ce):Ce=e[10],F=k.filter(Ce),e[6]=k,e[7]=S,e[8]=F}else F=e[8];const R=F;let z,q;e[11]!==x||e[12]!==y||e[13]!==S?(z=()=>{x&&S.has(x)&&y(null)},q=[x,y,S],e[11]=x,e[12]=y,e[13]=S,e[14]=z,e[15]=q):(z=e[14],q=e[15]),l.useEffect(z,q);let H;e[16]!==k||e[17]!==n||e[18]!==C||e[19]!==y?(H=()=>{let Ce="new-command",Qe=1;for(;k.some(tt=>tt.name===Ce);)Ce=`new-command-${Qe}`,Qe++;C({name:Ce,scope:"user"}),y(Ce),n?.()},e[16]=k,e[17]=n,e[18]=C,e[19]=y,e[20]=H):H=e[20];const Z=H;let W;e[21]!==a?(W=async Ce=>{if(_a(Ce)){Q.error(a("settings.commands.sidebar.toast.builtInCannotDelete"));return}p(Ce),g("delete")},e[21]=a,e[22]=W):W=e[22];const A=W;let X;e[23]===Symbol.for("react.memo_cache_sentinel")?(X=async Ce=>{_a(Ce)&&(p(Ce),g("reset"))},e[23]=X):X=e[23];const te=X;let E;e[24]===Symbol.for("react.memo_cache_sentinel")?(E=()=>{p(null),g(null)},e[24]=E):E=e[24];const P=E;let _;e[25]!==c||e[26]!==u||e[27]!==j||e[28]!==a?(_=async()=>{if(!c||!u)return;w(!0),await j(c.name)?(u==="delete"?Q.success(a("settings.commands.sidebar.toast.commandDeleted",{name:c.name})):Q.success(a("settings.commands.sidebar.toast.commandReset",{name:c.name})),P()):u==="delete"?Q.error(a("settings.commands.sidebar.toast.deleteFailed")):Q.error(a("settings.commands.sidebar.toast.resetFailed")),w(!1)},e[25]=c,e[26]=u,e[27]=j,e[28]=a,e[29]=_):_=e[29];const L=_;let V;e[30]!==k||e[31]!==C||e[32]!==y?(V=Ce=>{const Qe=Ce.name;let tt=1,at=`${Qe}-copy`;for(;k.some(gt=>gt.name===at);)tt++,at=`${Qe}-copy-${tt}`;C({name:at,scope:Ce.scope||"user",description:Ce.description,template:Ce.template,agent:Ce.agent,model:Ce.model}),y(at)},e[30]=k,e[31]=C,e[32]=y,e[33]=V):V=e[33];const Y=V;let G;e[34]===Symbol.for("react.memo_cache_sentinel")?(G=Ce=>{d(Ce.name),r(Ce)},e[34]=G):G=e[34];const me=G;let ae;e[35]!==k||e[36]!==O||e[37]!==j||e[38]!==i||e[39]!==o||e[40]!==y||e[41]!==a?(ae=async()=>{if(!i)return;const Ce=o.trim().replace(/\s+/g,"-");if(!Ce){Q.error(a("settings.commands.sidebar.toast.commandNameRequired"));return}if(Ce===i.name){r(null);return}if(k.some(tt=>tt.name===Ce)){Q.error(a("settings.commands.sidebar.toast.commandExists"));return}await O({name:Ce,description:i.description,template:i.template,agent:i.agent,model:i.model})?await j(i.name)?(Q.success(`Command renamed to "${Ce}"`),y(Ce)):Q.error(a("settings.commands.sidebar.toast.removeOldAfterRenameFailed")):Q.error(a("settings.commands.sidebar.toast.renameFailed")),r(null)},e[35]=k,e[36]=O,e[37]=j,e[38]=i,e[39]=o,e[40]=y,e[41]=a,e[42]=ae):ae=e[42];const xe=ae;let be,ie,pe,Ie,re,ce;if(e[43]!==R||e[44]!==Z||e[45]!==A||e[46]!==Y||e[47]!==n||e[48]!==h||e[49]!==x||e[50]!==y||e[51]!==a){const Ce=R.filter(_a),Qe=R.filter(yb);e[58]===Symbol.for("react.memo_cache_sentinel")?(re=fe("flex h-full flex-col","bg-background"),e[58]=re):re=e[58];let tt;e[59]!==a?(tt=a("settings.commands.sidebar.title"),e[59]=a,e[60]=tt):tt=e[60];let at;e[61]!==tt?(at=s.jsx("h2",{className:`${hn} mb-3`,children:tt}),e[61]=tt,e[62]=at):at=e[62];let gt;e[63]===Symbol.for("react.memo_cache_sentinel")?(gt=s.jsx(wi,{className:"mb-3"}),e[63]=gt):gt=e[63];let wt;e[64]!==R.length||e[65]!==a?(wt=a("settings.commands.sidebar.total",{count:R.length}),e[64]=R.length,e[65]=a,e[66]=wt):wt=e[66];let Te;e[67]!==wt?(Te=s.jsx("span",{className:"typography-meta text-muted-foreground",children:wt}),e[67]=wt,e[68]=Te):Te=e[68];let ne;e[69]===Symbol.for("react.memo_cache_sentinel")?(ne=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[69]=ne):ne=e[69];let Pe;e[70]!==Z?(Pe=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:ne}),e[70]=Z,e[71]=Pe):Pe=e[71];let Xe;e[72]!==Te||e[73]!==Pe?(Xe=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[Te,Pe]}),e[72]=Te,e[73]=Pe,e[74]=Xe):Xe=e[74],e[75]!==at||e[76]!==Xe?(ce=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[at,gt,Xe]}),e[75]=at,e[76]=Xe,e[77]=ce):ce=e[77],be=zs,ie="flex-1 min-h-0",pe="space-y-1 px-3 py-2",Ie=R.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:[Ce.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")}),[...Ce].sort(vb).map(Re=>s.jsx(Kc,{command:Re,isSelected:x===Re.name,onSelect:()=>{y(Re.name),n?.()},onReset:()=>te(Re),onDuplicate:()=>Y(Re),isMenuOpen:h===Re.name,onMenuOpenChange:Ye=>f(Ye?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(wb).map(Re=>s.jsx(Kc,{command:Re,isSelected:x===Re.name,onSelect:()=>{y(Re.name),n?.()},onRename:()=>me(Re),onDelete:()=>A(Re),onDuplicate:()=>Y(Re),isMenuOpen:h===Re.name,onMenuOpenChange:Ye=>f(Ye?Re.name:null)},Re.name))]})]}),e[43]=R,e[44]=Z,e[45]=A,e[46]=Y,e[47]=n,e[48]=h,e[49]=x,e[50]=y,e[51]=a,e[52]=be,e[53]=ie,e[54]=pe,e[55]=Ie,e[56]=re,e[57]=ce}else be=e[52],ie=e[53],pe=e[54],Ie=e[55],re=e[56],ce=e[57];let ge;e[78]!==be||e[79]!==ie||e[80]!==pe||e[81]!==Ie?(ge=s.jsx(be,{outerClassName:ie,className:pe,children:Ie}),e[78]=be,e[79]=ie,e[80]=pe,e[81]=Ie,e[82]=ge):ge=e[82];const oe=c!==null&&u!==null;let de;e[83]!==m?(de=Ce=>{!Ce&&!m&&P()},e[83]=m,e[84]=de):de=e[84];let le;e[85]!==u||e[86]!==a?(le=a(u==="delete"?"settings.commands.sidebar.dialog.deleteTitle":"settings.commands.sidebar.dialog.resetTitle"),e[85]=u,e[86]=a,e[87]=le):le=e[87];let he;e[88]!==le?(he=s.jsx(_t,{children:le}),e[88]=le,e[89]=he):he=e[89];let De;e[90]!==c?.name||e[91]!==u||e[92]!==a?(De=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]=De):De=e[93];let Le;e[94]!==De?(Le=s.jsx(Yt,{children:De}),e[94]=De,e[95]=Le):Le=e[95];let Ke;e[96]!==he||e[97]!==Le?(Ke=s.jsxs(Ut,{children:[he,Le]}),e[96]=he,e[97]=Le,e[98]=Ke):Ke=e[98];let Fe;e[99]!==a?(Fe=a("settings.common.actions.cancel"),e[99]=a,e[100]=Fe):Fe=e[100];let Me;e[101]!==m||e[102]!==Fe?(Me=s.jsx(ee,{size:"sm",variant:"ghost",onClick:P,disabled:m,children:Fe}),e[101]=m,e[102]=Fe,e[103]=Me):Me=e[103];let Be;e[104]!==u||e[105]!==a?(Be=a(u==="delete"?"settings.common.actions.delete":"settings.common.actions.reset"),e[104]=u,e[105]=a,e[106]=Be):Be=e[106];let Ge;e[107]!==L||e[108]!==m||e[109]!==Be?(Ge=s.jsx(ee,{size:"sm",onClick:L,disabled:m,children:Be}),e[107]=L,e[108]=m,e[109]=Be,e[110]=Ge):Ge=e[110];let Ve;e[111]!==Me||e[112]!==Ge?(Ve=s.jsxs(rs,{children:[Me,Ge]}),e[111]=Me,e[112]=Ge,e[113]=Ve):Ve=e[113];let Ue;e[114]!==Ke||e[115]!==Ve?(Ue=s.jsxs(Bt,{className:"max-w-md",children:[Ke,Ve]}),e[114]=Ke,e[115]=Ve,e[116]=Ue):Ue=e[116];let He;e[117]!==oe||e[118]!==de||e[119]!==Ue?(He=s.jsx(Kt,{open:oe,onOpenChange:de,children:Ue}),e[117]=oe,e[118]=de,e[119]=Ue,e[120]=He):He=e[120];const _e=i!==null;let Oe;e[121]===Symbol.for("react.memo_cache_sentinel")?(Oe=Ce=>!Ce&&r(null),e[121]=Oe):Oe=e[121];let se;e[122]!==a?(se=a("settings.commands.sidebar.renameDialog.title"),e[122]=a,e[123]=se):se=e[123];let ye;e[124]!==se?(ye=s.jsx(_t,{children:se}),e[124]=se,e[125]=ye):ye=e[125];const ke=i?.name??"";let ze;e[126]!==a||e[127]!==ke?(ze=a("settings.commands.sidebar.renameDialog.description",{name:ke}),e[126]=a,e[127]=ke,e[128]=ze):ze=e[128];let $;e[129]!==ze?($=s.jsx(Yt,{children:ze}),e[129]=ze,e[130]=$):$=e[130];let Ee;e[131]!==ye||e[132]!==$?(Ee=s.jsxs(Ut,{children:[ye,$]}),e[131]=ye,e[132]=$,e[133]=Ee):Ee=e[133];let J;e[134]===Symbol.for("react.memo_cache_sentinel")?(J=Ce=>d(Ce.target.value),e[134]=J):J=e[134];let v;e[135]!==a?(v=a("settings.commands.sidebar.renameDialog.placeholder"),e[135]=a,e[136]=v):v=e[136];let ue;e[137]!==xe?(ue=Ce=>{Ce.key==="Enter"&&xe()},e[137]=xe,e[138]=ue):ue=e[138];let Ne;e[139]!==o||e[140]!==v||e[141]!==ue?(Ne=s.jsx(nt,{value:o,onChange:J,placeholder:v,className:"text-foreground placeholder:text-muted-foreground",onKeyDown:ue}),e[139]=o,e[140]=v,e[141]=ue,e[142]=Ne):Ne=e[142];let we;e[143]===Symbol.for("react.memo_cache_sentinel")?(we=()=>r(null),e[143]=we):we=e[143];let qe;e[144]!==a?(qe=a("settings.common.actions.cancel"),e[144]=a,e[145]=qe):qe=e[145];let it;e[146]!==qe?(it=s.jsx(ee,{size:"sm",variant:"ghost",onClick:we,children:qe}),e[146]=qe,e[147]=it):it=e[147];let st;e[148]!==a?(st=a("settings.common.actions.rename"),e[148]=a,e[149]=st):st=e[149];let rt;e[150]!==xe||e[151]!==st?(rt=s.jsx(ee,{size:"sm",onClick:xe,children:st}),e[150]=xe,e[151]=st,e[152]=rt):rt=e[152];let lt;e[153]!==it||e[154]!==rt?(lt=s.jsxs(rs,{children:[it,rt]}),e[153]=it,e[154]=rt,e[155]=lt):lt=e[155];let xt;e[156]!==Ee||e[157]!==Ne||e[158]!==lt?(xt=s.jsxs(Bt,{children:[Ee,Ne,lt]}),e[156]=Ee,e[157]=Ne,e[158]=lt,e[159]=xt):xt=e[159];let bt;e[160]!==_e||e[161]!==xt?(bt=s.jsx(Kt,{open:_e,onOpenChange:Oe,children:xt}),e[160]=_e,e[161]=xt,e[162]=bt):bt=e[162];let Nt;return e[163]!==re||e[164]!==ce||e[165]!==ge||e[166]!==He||e[167]!==bt?(Nt=s.jsxs("div",{className:re,children:[ce,ge,He,bt]}),e[163]=re,e[164]=ce,e[165]=ge,e[166]=He,e[167]=bt,e[168]=Nt):Nt=e[168],Nt},Kc=t=>{const e=Ze.c(47),{command:n,isSelected:a,onSelect:i,onDelete:r,onReset:o,onRename:d,onDuplicate:c,isMenuOpen:p,onMenuOpenChange:u}=t,{t:g}=ot();let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m=bi(),e[0]=m):m=e[0];const w=m,[h,f]=l.useState(!1);let x;e[1]!==r||e[2]!==c||e[3]!==d||e[4]!==o||e[5]!==g?(x=W=>s.jsxs(s.Fragment,{children:[d&&s.jsxs(W,{onClick:A=>{A.stopPropagation(),d()},children:[s.jsx(K,{name:"edit",className:"h-4 w-4 mr-px"}),g("settings.common.actions.rename")]}),s.jsxs(W,{onClick:A=>{A.stopPropagation(),c()},children:[s.jsx(K,{name:"file-copy",className:"h-4 w-4 mr-px"}),g("settings.common.actions.duplicate")]}),o&&s.jsxs(W,{onClick:A=>{A.stopPropagation(),o()},children:[s.jsx(K,{name:"restart",className:"h-4 w-4 mr-px"}),g("settings.common.actions.reset")]}),r&&s.jsxs(W,{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"}),g("settings.common.actions.delete")]})]}),e[1]=r,e[2]=c,e[3]=d,e[4]=o,e[5]=g,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 O;e[9]===Symbol.for("react.memo_cache_sentinel")?(O=w?void 0:W=>{W.preventDefault(),f(!0)},e[9]=O):O=e[9];let j;e[10]!==C?(j=s.jsx("div",{className:C,onContextMenu:O}),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 b;e[14]!==n||e[15]!==g?(b=(n.scope||_a(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:_a(n)?g("settings.agents.sidebar.badge.system"):n.scope}),e[14]=n,e[15]=g,e[16]=b):b=e[16];let I;e[17]!==N||e[18]!==b?(I=s.jsxs("div",{className:"flex items-center gap-2",children:[N,b]}),e[17]=N,e[18]=b,e[19]=I):I=e[19];let B;e[20]!==n.description?(B=n.description&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n.description}),e[20]=n.description,e[21]=B):B=e[21];let T;e[22]!==i||e[23]!==B||e[24]!==I?(T=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:[I,B]}),e[22]=i,e[23]=B,e[24]=I,e[25]=T):T=e[25];let D;e[26]!==u?(D=W=>{W&&f(!1),u(W)},e[26]=u,e[27]=D):D=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 R;e[31]!==p||e[32]!==D||e[33]!==F?(R=s.jsxs(fs,{open:p,onOpenChange:D,children:[S,F]}),e[31]=p,e[32]=D,e[33]=F,e[34]=R):R=e[34];let z;e[35]!==T||e[36]!==R?(z=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[T,R]}),e[35]=T,e[36]=R,e[37]=z):z=e[37];let q;e[38]!==z||e[39]!==j?(q=s.jsx(qn,{render:j,children:z}),e[38]=z,e[39]=j,e[40]=q):q=e[40];let H;e[41]!==k?(H=s.jsx(Jn,{className:"w-fit min-w-20",children:k(An)}),e[41]=k,e[42]=H):H=e[42];let Z;return e[43]!==h||e[44]!==q||e[45]!==H?(Z=s.jsxs(Gn,{open:h,onOpenChange:f,children:[q,H]}),e[43]=h,e[44]=q,e[45]=H,e[46]=Z):Z=e[46],Z};function fb(t){return{selectedCommandName:t.selectedCommandName,commands:t.commands,setSelectedCommand:t.setSelectedCommand,setCommandDraft:t.setCommandDraft,createCommand:t.createCommand,deleteCommand:t.deleteCommand,loadCommands:t.loadCommands}}function hb(t){return t.skills}function xb(t){return t.loadSkills}function bb(t){return t.name}function yb(t){return!_a(t)}function vb(t,e){return t.name.localeCompare(e.name)}function wb(t,e){return t.name.localeCompare(e.name)}const jb=()=>{const{t}=ot(),{selectedCommandName:e,getCommandByName:n,createCommand:a,updateCommand:i,commands:r,commandDraft:o,setCommandDraft:d}=Cr(Ws(D=>({selectedCommandName:D.selectedCommandName,getCommandByName:D.getCommandByName,createCommand:D.createCommand,updateCommand:D.updateCommand,commands:D.commands,commandDraft:D.commandDraft,setCommandDraft:D.setCommandDraft}))),c=e?n(e):null,p=!!(o&&o.name===e&&!c),[u,g]=l.useState(""),[m,w]=l.useState("user"),[h,f]=l.useState(""),[x,k]=l.useState(""),[y,C]=l.useState(""),[O,j]=l.useState(""),[N,b]=l.useState(!1),I=l.useRef(null);l.useEffect(()=>{if(p&&o){const D=o.name||"",S=o.scope||"user",F=o.description||"",R=o.agent||"",z=o.model||"",q=o.template||"";g(D),w(S),f(F),k(R),C(z),j(q),I.current={draftName:D,draftScope:S,description:F,agent:R,model:z,template:q}}else if(c){const D=c.description||"",S=c.agent||"",F=c.model||"",R=c.template||"";f(D),k(S),C(F),j(R),I.current={draftName:"",draftScope:"user",description:D,agent:S,model:F,template:R}}},[c,p,e,r,o]);const B=l.useMemo(()=>{const D=I.current;return D?!!(p&&(u!==D.draftName||m!==D.draftScope)||h!==D.description||x!==D.agent||y!==D.model||O!==D.template):!1},[x,h,u,m,p,y,O]),T=async()=>{const D=p?u.trim().replace(/\s+/g,"-"):e?.trim();if(!D){Q.error(t("settings.commands.sidebar.toast.commandNameRequired"));return}if(!O.trim()){Q.error(t("settings.commands.page.toast.templateRequired"));return}if(p&&r.some(S=>S.name===D)){Q.error(t("settings.commands.sidebar.toast.commandExists"));return}b(!0);try{const S=x.trim(),F=y.trim(),R=O.trim(),z={name:D,description:h.trim()||void 0,agent:S===""?null:S,model:F===""?null:F,template:R,scope:p?m:void 0};let q;p?(q=await a(z),q&&d(null)):q=await i(D,z),q?Q.success(t(p?"settings.commands.page.toast.created":"settings.commands.page.toast.updated")):Q.error(t(p?"settings.commands.page.toast.createFailed":"settings.commands.page.toast.updateFailed"))}catch(S){console.error("Error saving command:",S),Q.error(t("settings.commands.page.toast.saveUnexpectedError"))}finally{b(!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(nt,{value:u,onChange:D=>g(D.target.value),placeholder:t("settings.commands.page.field.commandNamePlaceholder"),className:"h-7 w-40 px-2"})]}),s.jsxs(Mt,{value:m,onValueChange:D=>w(D),children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[100px]",children:s.jsx(Wt,{placeholder:t("settings.agents.page.field.scopePlaceholder")})}),s.jsxs(Ft,{align:"end",children:[s.jsx(jt,{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(jt,{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:h,onChange:D=>f(D.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(ll,{agentName:x,onChange:D=>k(D),className:Vn})}),s.jsx(Xt,{settingsItem:"commands.model",label:t("settings.agents.page.field.overrideModel"),children:s.jsx(la,{providerId:Wn(y)?.providerId??"",modelId:Wn(y)?.modelId??"",onChange:(D,S)=>{C(D&&S?`${D}/${S}`:"")},className:Vn})})]}),s.jsxs(dt,{title:t("settings.commands.page.section.template"),settingsItem:"commands.template",children:[s.jsx(Ns,{value:O,onChange:D=>j(D.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:T,disabled:N||!B,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")})]})})},kb={},Nb={},kn=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},Ta=t=>kn(t)??"__global__",na=t=>{const e=kn(t);return e?Ps.getScopedApiClient(e):Ps.getApiClient()},ws=fn()(Ja((t,e)=>({byDirectory:{},diagnosticsByDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:n=>{const a=Ta(n??Cs.getState().currentDirectory);return e().byDirectory[a]??kb},getDiagnosticForDirectory:n=>{const a=Ta(n??Cs.getState().currentDirectory);return e().diagnosticsByDirectory[a]??Nb},getErrorForDirectory:n=>{const a=Ta(n??Cs.getState().currentDirectory);return e().lastErrorKeys[a]??null},refresh:async n=>{const a=kn(n?.directory??Cs.getState().currentDirectory),i=Ta(a);n?.silent||t(r=>({loadingKeys:{...r.loadingKeys,[i]:!0},lastErrorKeys:{...r.lastErrorKeys,[i]:null}}));try{const d=(await na(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=kn(a??Cs.getState().currentDirectory),r=Ta(i),o=na(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=kn(a??Cs.getState().currentDirectory);await na(i).mcp.disconnect({name:n},{throwOnError:!0}),await e().refresh({directory:i,silent:!0})},startAuth:async(n,a)=>{const i=kn(a??Cs.getState().currentDirectory),d=(await na(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=kn(i??Cs.getState().currentDirectory);await na(r).mcp.auth.callback({name:n,code:a},{throwOnError:!0}),await e().refresh({directory:r,silent:!0})},clearAuth:async(n,a)=>{const i=kn(a??Cs.getState().currentDirectory);await na(i).mcp.auth.remove({name:n},{throwOnError:!0}),await e().refresh({directory:i,silent:!0})},testConnection:async(n,a)=>{const i=kn(a??Cs.getState().currentDirectory),r=Ta(i),o=na(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(h=>({diagnosticsByDirectory:{...h.diagnosticsByDirectory,[r]:{...h.diagnosticsByDirectory[r]??{},[n]:{status:"failed",error:p??"Connection failed"}}}}))}await e().refresh({directory:i,silent:!0});const g=e().getStatusForDirectory(i)[n],m=g;if(!c&&g?.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}}}))),Bc=t=>{switch(t){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"idle"}},_c=t=>{const e=Ze.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},Sb=t=>{const e=Ze.c(120),{onItemSelect:n}=t,{t:a}=ot(),{mcpServers:i,selectedMcpName:r,setSelectedMcp:o,setMcpDraft:d,loadMcpConfigs:c,deleteMcp:p}=$a(Ws(Cb)),u=Cs(Ib);let g;e[0]!==u?(g=$=>$.getStatusForDirectory(u??null),e[0]=u,e[1]=g):g=e[1];const m=ws(g),w=ws(Pb),h=ws(Tb),[f,x]=l.useState(null),[k,y]=l.useState(!1),[C,O]=l.useState(null),[j,N]=l.useState(null),[b,I]=l.useState(!1);let B;e[2]!==i?(B=i.filter(Ab),e[2]=i,e[3]=B):B=e[3];const T=B;let D;e[4]!==i?(D=i.filter(Eb),e[4]=i,e[5]=D):D=e[5];const S=D;let F,R;e[6]!==c?(F=()=>{c()},R=[c],e[6]=c,e[7]=F,e[8]=R):(F=e[7],R=e[8]),l.useEffect(F,R);let z;e[9]!==u||e[10]!==h||e[11]!==b||e[12]!==w?(z=()=>{if(b)return;I(!0);const $=new Promise(Db);Promise.all([w({directory:u,silent:!0}),$]).then(()=>{const Ee=h(u);Ee&&Q.error(Ee)}).finally(()=>{I(!1)})},e[9]=u,e[10]=h,e[11]=b,e[12]=w,e[13]=z):z=e[13];const q=z;let H;e[14]!==i||e[15]!==n||e[16]!==d||e[17]!==o?(H=()=>{let $="new-mcp-server",Ee=1;for(;i.some(v=>v.name===$);)$=`new-mcp-server-${Ee}`,Ee++;d({name:$,scope:"user",type:"local",command:[],url:"",environment:[],headers:[],oauthEnabled:!0,oauthClientId:"",oauthClientSecret:"",oauthScope:"",oauthRedirectUri:"",timeout:"",enabled:!0}),o($),n?.()},e[14]=i,e[15]=n,e[16]=d,e[17]=o,e[18]=H):H=e[18];const Z=H;let W;e[19]!==p||e[20]!==f||e[21]!==a?(W=async()=>{if(!f)return;y(!0);const $=await p(f.name);$.ok?$.reloadFailed?Q.warning($.message||`MCP server "${f.name}" deleted, but OpenCode reload failed`,{description:$.warning||a("settings.mcp.sidebar.toast.refreshListIfStale")}):Q.success($.message||a("settings.mcp.sidebar.toast.serverDeleted",{name:f.name})):Q.error(a("settings.mcp.sidebar.toast.deleteFailed")),x(null),y(!1)},e[19]=p,e[20]=f,e[21]=a,e[22]=W):W=e[22];const A=W;let X;e[23]!==a?(X=($,Ee)=>s.jsxs(Ee,{onClick:J=>{J.stopPropagation(),x($)},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 E;e[25]===Symbol.for("react.memo_cache_sentinel")?(E=fe("flex h-full flex-col","bg-background"),e[25]=E):E=e[25];let P;e[26]!==a?(P=a("settings.mcp.sidebar.title"),e[26]=a,e[27]=P):P=e[27];let _;e[28]!==P?(_=s.jsx("h2",{className:hn,children:P}),e[28]=P,e[29]=_):_=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 Y=b&&"animate-spin";let G;e[34]!==Y?(G=fe("h-4 w-4",Y),e[34]=Y,e[35]=G):G=e[35];let me;e[36]!==G?(me=s.jsx(K,{name:"refresh",className:G}),e[36]=G,e[37]=me):me=e[37];let ae;e[38]!==q||e[39]!==b||e[40]!==L||e[41]!==V||e[42]!==me?(ae=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:b,onClick:q,"aria-label":L,title:V,children:me}),e[38]=q,e[39]=b,e[40]=L,e[41]=V,e[42]=me,e[43]=ae):ae=e[43];let xe;e[44]!==_||e[45]!==ae?(xe=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[_,ae]}),e[44]=_,e[45]=ae,e[46]=xe):xe=e[46];let be;e[47]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx(wi,{className:"mb-3"}),e[47]=be):be=e[47];let ie;e[48]!==i.length||e[49]!==a?(ie=a("settings.mcp.sidebar.total",{count:i.length}),e[48]=i.length,e[49]=a,e[50]=ie):ie=e[50];let pe;e[51]!==ie?(pe=s.jsx("span",{className:"typography-meta text-muted-foreground",children:ie}),e[51]=ie,e[52]=pe):pe=e[52];let Ie;e[53]!==a?(Ie=a("settings.mcp.sidebar.actions.addServerTitle"),e[53]=a,e[54]=Ie):Ie=e[54];let re;e[55]===Symbol.for("react.memo_cache_sentinel")?(re=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[55]=re):re=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:re}),e[56]=Z,e[57]=Ie,e[58]=ce):ce=e[58];let ge;e[59]!==pe||e[60]!==ce?(ge=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[pe,ce]}),e[59]=pe,e[60]=ce,e[61]=ge):ge=e[61];let oe;e[62]!==xe||e[63]!==ge?(oe=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[xe,be,ge]}),e[62]=xe,e[63]=ge,e[64]=oe):oe=e[64];let de;e[65]!==i.length||e[66]!==m||e[67]!==n||e[68]!==C||e[69]!==T||e[70]!==te||e[71]!==j||e[72]!==r||e[73]!==d||e[74]!==o||e[75]!==a||e[76]!==S?(de=s.jsx(zs,{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:[T.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")}),T.map($=>{const Ee=m[$.name],J=Bc(Ee?.status),v=r===$.name,ue=bi();return s.jsxs(Gn,{open:j===$.name,onOpenChange:Ne=>N(Ne?$.name:null),children:[s.jsxs(qn,{render:s.jsx("div",{className:fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",v?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:ue?void 0:Ne=>{Ne.preventDefault(),N($.name)}}),children:[s.jsxs("button",{onClick:()=>{o($.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(_c,{tone:J,enabled:$.enabled}),s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:$.name}),s.jsx("span",{title:$.type==="local"?a("settings.mcp.sidebar.serverType.localTitle"):a("settings.mcp.sidebar.serverType.remoteTitle"),children:$.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:$.type==="local"?$.command?.join(" ")??"":$.url??""})]}),s.jsxs(fs,{open:C===$.name,onOpenChange:Ne=>{Ne&&N(null),O(Ne?$.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($,as)})]})]}),s.jsx(Jn,{className:"w-fit min-w-20",children:te($,An)})]},$.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($=>{const Ee=m[$.name],J=Bc(Ee?.status),v=r===$.name,ue=bi();return s.jsxs(Gn,{open:j===$.name,onOpenChange:Ne=>N(Ne?$.name:null),children:[s.jsxs(qn,{render:s.jsx("div",{className:fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",v?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:ue?void 0:Ne=>{Ne.preventDefault(),N($.name)}}),children:[s.jsxs("button",{onClick:()=>{o($.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(_c,{tone:J,enabled:$.enabled}),s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:$.name}),s.jsx("span",{title:$.type==="local"?a("settings.mcp.sidebar.serverType.localTitle"):a("settings.mcp.sidebar.serverType.remoteTitle"),children:$.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:$.type==="local"?$.command?.join(" ")??"":$.url??""})]}),s.jsxs(fs,{open:C===$.name,onOpenChange:Ne=>{Ne&&N(null),O(Ne?$.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($,as)})]})]}),s.jsx(Jn,{className:"w-fit min-w-20",children:te($,An)})]},$.name)})]})]})}),e[65]=i.length,e[66]=m,e[67]=n,e[68]=C,e[69]=T,e[70]=te,e[71]=j,e[72]=r,e[73]=d,e[74]=o,e[75]=a,e[76]=S,e[77]=de):de=e[77];const le=f!==null;let he;e[78]!==k?(he=$=>{!$&&!k&&x(null)},e[78]=k,e[79]=he):he=e[79];let De;e[80]!==a?(De=a("settings.mcp.sidebar.deleteDialog.title"),e[80]=a,e[81]=De):De=e[81];let Le;e[82]!==De?(Le=s.jsx(_t,{children:De}),e[82]=De,e[83]=Le):Le=e[83];const Ke=f?.name||"";let Fe;e[84]!==a||e[85]!==Ke?(Fe=a("settings.mcp.sidebar.deleteDialog.descriptionPrefix",{name:Ke}),e[84]=a,e[85]=Ke,e[86]=Fe):Fe=e[86];let Me;e[87]===Symbol.for("react.memo_cache_sentinel")?(Me=s.jsx("code",{className:"text-foreground",children:"opencode.json"}),e[87]=Me):Me=e[87];let Be;e[88]!==Fe?(Be=s.jsxs(Yt,{children:[Fe," ",Me,"."]}),e[88]=Fe,e[89]=Be):Be=e[89];let Ge;e[90]!==Le||e[91]!==Be?(Ge=s.jsxs(Ut,{children:[Le,Be]}),e[90]=Le,e[91]=Be,e[92]=Ge):Ge=e[92];let Ve;e[93]===Symbol.for("react.memo_cache_sentinel")?(Ve=()=>x(null),e[93]=Ve):Ve=e[93];let Ue;e[94]!==a?(Ue=a("settings.common.actions.cancel"),e[94]=a,e[95]=Ue):Ue=e[95];let He;e[96]!==k||e[97]!==Ue?(He=s.jsx(ee,{size:"sm",variant:"ghost",onClick:Ve,disabled:k,children:Ue}),e[96]=k,e[97]=Ue,e[98]=He):He=e[98];let _e;e[99]!==k||e[100]!==a?(_e=a(k?"settings.mcp.sidebar.actions.deleting":"settings.common.actions.delete"),e[99]=k,e[100]=a,e[101]=_e):_e=e[101];let Oe;e[102]!==A||e[103]!==k||e[104]!==_e?(Oe=s.jsx(ee,{size:"sm",onClick:A,disabled:k,children:_e}),e[102]=A,e[103]=k,e[104]=_e,e[105]=Oe):Oe=e[105];let se;e[106]!==He||e[107]!==Oe?(se=s.jsxs(rs,{children:[He,Oe]}),e[106]=He,e[107]=Oe,e[108]=se):se=e[108];let ye;e[109]!==Ge||e[110]!==se?(ye=s.jsxs(Bt,{className:"max-w-md",children:[Ge,se]}),e[109]=Ge,e[110]=se,e[111]=ye):ye=e[111];let ke;e[112]!==le||e[113]!==he||e[114]!==ye?(ke=s.jsx(Kt,{open:le,onOpenChange:he,children:ye}),e[112]=le,e[113]=he,e[114]=ye,e[115]=ke):ke=e[115];let ze;return e[116]!==oe||e[117]!==de||e[118]!==ke?(ze=s.jsxs("div",{className:E,children:[oe,de,ke]}),e[116]=oe,e[117]=de,e[118]=ke,e[119]=ze):ze=e[119],ze};function Cb(t){return{mcpServers:t.mcpServers,selectedMcpName:t.selectedMcpName,setSelectedMcp:t.setSelectedMcp,setMcpDraft:t.setMcpDraft,loadMcpConfigs:t.loadMcpConfigs,deleteMcp:t.deleteMcp}}function Ib(t){return t.currentDirectory}function Pb(t){return t.refresh}function Tb(t){return t.getErrorForDirectory}function Ab(t){return t.scope==="project"}function Eb(t){return t.scope!=="project"}function Db(t){return setTimeout(t,500)}function mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ai(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function dn(t,e){return e!==void 0?{ok:!1,error:t,parsed:e}:{ok:!1,error:t}}function Bi(t,e,n){const a=Rb(n),i=typeof n.url=="string"?n.url.trim():"",r=Uc(n,"env","environment"),o=Uc(n,"headers"),d=Mb(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():"",g=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.redirectUri??"").trim():"",m=Lb(n),w=Fb(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:g,timeout:m,enabled:w}}function Rb(t){const e=t.command,n=t.args;if(ai(e)&&ai(n))return[...e,...n];if(ai(e))return e;if(typeof e=="string"&&e.trim()){const a=e.trim().split(/\s+/);return ai(n)?[...a,...n]:a}return ai(n)?n:[]}function Uc(t,...e){for(const n of e){const a=t[n];if(!mn(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 Mb(t){if(t.oauth===!1||t.oauth===null||t.oauth===void 0||!mn(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 Lb(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 Fb(t){return"disabled"in t&&t.disabled===!0?!1:"enabled"in t?!!t.enabled:!0}function Ob(t){const e=t.mcpServers;if(mn(e)){const a=Object.keys(e);if(a.length===1){const i=a[0],r=e[i];if(mn(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"&&mn(i)});if(n.length===1){const a=n[0],i=t[a];if(Hu(i))return{name:a,entry:i}}return null}function Hu(t){return t.type==="local"||t.type==="remote"||Array.isArray(t.command)||typeof t.url=="string"||Array.isArray(t.args)}function zb(t,e){let n;try{const d=t.trim();if(!d)return dn("No JSON content provided");n=JSON.parse(d)}catch(d){return dn(d instanceof Error?`Invalid JSON: ${d.message}`:"Invalid JSON")}if(!mn(n))return dn("Expected a JSON object, not an array or primitive");const a=n,i=a.mcpServers;if(mn(i)){const d=Object.keys(i);if(d.length===0)return dn("mcpServers object is empty",n);if(d.length>1)return dn("Paste one server at a time. Found "+d.length+" servers in mcpServers",n);const c=d[0],p=i[c];return mn(p)?Bi(c,_i(p),p):dn("Server entry is not a valid object",n)}const r=a.mcp;if(mn(r)){const d=Object.keys(r);if(d.length===0)return dn("mcp object is empty",n);if(d.length>1)return dn("Paste one server at a time. Found "+d.length+" servers in mcp",n);const c=d[0],p=r[c];return mn(p)?Bi(c,_i(p),p):dn("Server entry in mcp is not a valid object",n)}const o=Ob(a);if(o)return Bi(o.name,_i(o.entry),o.entry);if(Hu(a)){const d=_i(a),c=typeof a.name=="string"&&a.name.trim()?a.name.trim():e?.fallbackName;return Bi(c,d,a)}return dn("No recognizable MCP server configuration found in JSON",n)}function _i(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 Kb(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 Bb="/mcp/oauth/callback",_b=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}},Ub=t=>{const e=$b(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}},Wu=t=>{const e=t.get("state");return typeof e!="string"?null:e.trim()||null},$b=t=>{if(typeof t!="string"||!t.trim())return null;const e=_b(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 Vb(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 Hb(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:Ub(n.searchParams),stateKey:Wu(n.searchParams)}}catch{}return{code:e,context:null,stateKey:null}}const Wb=({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(h=>h.trim().length>0);e(w)},g=async()=>{try{const w=(await navigator.clipboard.readText()).trim(),h=w.includes(`
|
|
12
|
+
`)?w.split(`
|
|
13
|
+
`).filter(f=>f.trim()):Vb(w);c(h.join(`
|
|
14
|
+
`)),e(h),Q.success(i(h.length))}catch{Q.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:g,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))})})]})]})},Gb=t=>t.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),$c=({value:t,onChange:e,keyTransform:n=Gb,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:g,valuePlaceholder:m,hideValueTitle:w,showValueTitle:h,addVariable:f,plainTextWarning:x,removeVariableAria:k})=>{const[y,C]=l.useState(new Set),O=()=>e([...t,{key:"",value:""}]),j=T=>{e(t.filter((D,S)=>S!==T)),C(D=>{const S=new Set(D);return S.delete(T),S})},N=(T,D,S)=>{const F=[...t];F[T]={...F[T],[D]:S},e(F)},b=T=>{C(D=>{const S=new Set(D);return S.has(T)?S.delete(T):S.add(T),S})},I=async()=>{try{const T=await navigator.clipboard.readText(),D=[];for(const F of T.split(`
|
|
20
|
+
`)){const R=F.trim();if(!R||R.startsWith("#"))continue;const z=R.indexOf("=");if(z===-1)continue;const q=R.slice(0,z).trim();let H=R.slice(z+1).trim();(H.startsWith('"')&&H.endsWith('"')||H.startsWith("'")&&H.endsWith("'"))&&(H=H.slice(1,-1)),q&&D.push({key:q,value:H})}if(D.length===0){Q.error(d);return}const S=[...t];for(const F of D){const R=S.findIndex(z=>z.key===F.key);R!==-1?S[R]=F:S.push(F)}e(S),Q.success(c(D.length))}catch{Q.error(p)}},B=t.some(T=>T.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:g})]}),s.jsxs(ee,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:I,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((T,D)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nt,{value:T.key,onChange:S=>N(D,"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(nt,{type:y.has(D)?"text":"password",value:T.value,onChange:S=>N(D,"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:()=>b(D),className:"absolute right-2 text-muted-foreground/60 hover:text-muted-foreground",title:y.has(D)?w:h,children:y.has(D)?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(D),"aria-label":k,children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},D))}),s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:O,type:"button",children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),f]}),B&&s.jsx("p",{className:"typography-micro text-muted-foreground/60",children:x})]})},Vc=t=>{const e=Ze.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 h;e[5]!==i||e[6]!==n?(h=i(n),e[5]=i,e[6]=n,e[7]=h):h=e[7],c=s.jsxs("span",{className:w,children:["● ",h]});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},qb=(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")}},Jb=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)]"}},Yb=(t,e,n,a)=>!!(t==="failed"||t==="needs_auth"||t==="needs_client_registration"||e||n||a),Hc=(t,e)=>{if(typeof window>"u")return null;const n=new URL(Bb,qa()||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()},Qb=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")}},Xb=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},ii=async t=>{typeof t!="string"||!t.trim()||await ht(`/api/mcp/auth/pending?state=${encodeURIComponent(t.trim())}`,{method:"DELETE"}).catch(()=>{})},no=(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},Zb=(t,e)=>{const n=typeof e=="string"&&e.trim()?e.trim():"__global__";return`${t??"__none__"}::${n}`},ey=()=>{const{t}=ot(),e=l.useCallback((Se,ut)=>t(Se,ut),[t]),{selectedMcpName:n,mcpServers:a,mcpDraft:i,setMcpDraft:r,setSelectedMcp:o,getMcpByName:d,createMcp:c,updateMcp:p,deleteMcp:u}=$a(Ws(Se=>({selectedMcpName:Se.selectedMcpName,mcpServers:Se.mcpServers,mcpDraft:Se.mcpDraft,setMcpDraft:Se.setMcpDraft,setSelectedMcp:Se.setSelectedMcp,getMcpByName:Se.getMcpByName,createMcp:Se.createMcp,updateMcp:Se.updateMcp,deleteMcp:Se.deleteMcp}))),g=Cs(Se=>Se.currentDirectory),m=l.useMemo(()=>ds(),[]),w=ws(Se=>Se.getStatusForDirectory(g??null)),h=ws(Se=>Se.getDiagnosticForDirectory(g??null)),f=ws(Se=>Se.refresh),x=ws(Se=>Se.connect),k=ws(Se=>Se.disconnect),y=ws(Se=>Se.startAuth),C=ws(Se=>Se.completeAuth),O=ws(Se=>Se.clearAuth),j=ws(Se=>Se.testConnection),N=n?d(n):null,b=!!(i&&i.name===n&&!N),[I,B]=l.useState(""),[T,D]=l.useState("user"),[S,F]=l.useState("local"),[R,z]=l.useState([]),[q,H]=l.useState(""),[Z,W]=l.useState([]),[A,X]=l.useState([]),[te,E]=l.useState(!0),[P,_]=l.useState(""),[L,V]=l.useState(""),[Y,G]=l.useState(""),[me,ae]=l.useState(""),[xe,be]=l.useState(""),[ie,pe]=l.useState(!0),[Ie,re]=l.useState(!1),[ce,ge]=l.useState(!1),[oe,de]=l.useState(!1),[le,he]=l.useState(!1),[De,Le]=l.useState(!1),[Ke,Fe]=l.useState(!1),[Me,Be]=l.useState(!1),[Ge,Ve]=l.useState(!1),[Ue,He]=l.useState(null),[_e,Oe]=l.useState(null),[se,ye]=l.useState(""),[ke,ze]=l.useState(!1),$=l.useRef(0),Ee=l.useRef(!1),[J,v]=l.useState(!1),[ue,Ne]=l.useState(!1),[we,qe]=l.useState(""),[it,st]=l.useState(null),rt=l.useMemo(()=>Zb(n,g),[g,n]),lt=l.useRef(rt),xt=l.useRef(null),bt=l.useCallback(()=>{He(null),Oe(null),ye(""),ze(!1),$.current=0,Ve(!1),Le(!1),Fe(!1),Ee.current=!1},[]),Nt=l.useCallback(()=>{qe(""),st(null),Ne(!0)},[]),Ce=l.useCallback(async()=>{try{const Se=await navigator.clipboard.readText();qe(Se),st(null)}catch{Q.error(t("settings.mcp.page.toast.clipboardReadFailed"))}},[t]),Qe=l.useCallback(()=>{const Se=zb(we,{fallbackName:I});if(!Se.ok){st(Se.error);return}const mt=Kb(Se,{name:I,scope:T,type:S,command:R,url:q,environment:Z,headers:A,oauthEnabled:te,oauthClientId:P,oauthClientSecret:L,oauthScope:Y,oauthRedirectUri:me,timeout:xe,enabled:ie},{isNewServer:b});B(mt.name),F(mt.type),z(mt.command??[]),H(mt.url??""),W(mt.environment??[]),X(mt.headers??[]),E(mt.oauthEnabled??!1),_(mt.oauthClientId??""),V(mt.oauthClientSecret??""),G(mt.oauthScope??""),ae(mt.oauthRedirectUri??""),be(mt.timeout??""),pe(mt.enabled??!0),Ne(!1),qe(""),st(null),Q.success(t("settings.mcp.page.toast.configImported"))},[we,I,T,S,R,q,Z,A,te,P,L,Y,me,xe,ie,b,t]);l.useEffect(()=>{if(b&&i){B(i.name),D(i.scope||"user"),F(i.type),z(i.command),H(i.url),W(i.environment),X(i.headers),E(i.oauthEnabled),_(i.oauthClientId),V(i.oauthClientSecret),G(i.oauthScope),ae(i.oauthRedirectUri),be(i.timeout),pe(i.enabled),v(!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){D(N.scope==="project"?"project":"user");const Se=Rc(N.environment),ut=N.type==="remote"?N:null,mt=Rc(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),z(Vt),H(ts),W(Se),X(mt),E(vt),_(vt?ft?.clientId??"":""),V(vt?ft?.clientSecret??"":""),G(vt?ft?.scope??"":""),ae(vt?ft?.redirectUri??"":""),be(os),pe(N.enabled),v(!1),xt.current={mcpType:Dt,command:Vt,url:ts,envEntries:Se,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,b,i]);const tt=l.useMemo(()=>{const Se=xt.current;return Se?S!==Se.mcpType||ie!==Se.enabled||JSON.stringify(R)!==JSON.stringify(Se.command)||q!==Se.url||JSON.stringify(Z)!==JSON.stringify(Se.envEntries)||JSON.stringify(A)!==JSON.stringify(Se.headerEntries)||te!==Se.oauthEnabled||P!==Se.oauthClientId||L!==Se.oauthClientSecret||Y!==Se.oauthScope||me!==Se.oauthRedirectUri||xe!==Se.timeout:!1},[S,R,q,Z,A,te,P,L,Y,me,xe,ie]),at=async()=>{const Se=b?I.trim():n??"";if(!Se){Q.error(t("settings.mcp.page.toast.nameRequired"));return}if(b&&a.some(mt=>mt.name===Se)){Q.error(t("settings.mcp.page.toast.serverNameExists"));return}if(S==="local"&&R.filter(Boolean).length===0){Q.error(t("settings.mcp.page.toast.localCommandRequired"));return}if(S==="remote"&&!q.trim()){Q.error(t("settings.mcp.page.toast.remoteUrlRequired"));return}const ut={name:Se,scope:T,type:S,command:R,url:q,environment:Z,headers:A,oauthEnabled:te,oauthClientId:P,oauthClientSecret:L,oauthScope:Y,oauthRedirectUri:me,timeout:xe,enabled:ie};re(!0);try{const mt=b?await c(ut):await p(Se,ut);mt.ok?(await ii(_e),bt(),b&&(r(null),o(Se)),await f({directory:g,silent:!0}),mt.reloadFailed?Q.warning(mt.message||t(b?"settings.mcp.page.toast.serverCreatedReloadFailed":"settings.mcp.page.toast.savedReloadFailed"),{description:mt.warning||t("settings.mcp.page.toast.retryRefreshHint")}):Q.success(mt.message||t(b?"settings.mcp.page.toast.serverCreatedReloading":"settings.mcp.page.toast.savedReloading"))):Q.error(t("settings.mcp.page.toast.saveFailed"))}catch(mt){Q.error(mt instanceof Error?mt.message:t("settings.mcp.page.toast.unexpectedError"))}finally{re(!1)}},gt=async()=>{if(!n)return;de(!0);const Se=await u(n);Se.ok?(await ii(_e),bt(),Se.reloadFailed?Q.warning(Se.message||t("settings.mcp.page.toast.serverDeletedReloadFailed",{name:n}),{description:Se.warning||t("settings.mcp.page.toast.refreshListIfStale")}):Q.success(Se.message||t("settings.mcp.page.toast.serverDeleted",{name:n})),ge(!1)):Q.error(t("settings.mcp.page.toast.deleteFailed")),de(!1)},wt=async()=>{if(n){he(!0);try{if(w[n]?.status==="connected")await k(n,g),Q.success(t("settings.mcp.page.toast.disconnected"));else{await x(n,g),await f({directory:g,silent:!0});const ut=ws.getState().getStatusForDirectory(g??null)[n];ut?.status==="connected"?Q.success(t("settings.mcp.page.toast.connected")):ut?.status==="needs_auth"?Q.message(t("settings.mcp.page.toast.connectionNeedsAuthorization")):ut?.status==="needs_client_registration"?Q.message(t("settings.mcp.page.toast.connectionNeedsClientRegistration")):ut?.status==="failed"?Q.error(ut.error||t("settings.mcp.page.toast.connectionFailed")):Q.message(t("settings.mcp.page.toast.connectionAttemptFinished"));return}await f({directory:g,silent:!0})}catch(Se){Q.error(Se instanceof Error?Se.message:t("settings.mcp.page.toast.connectionFailed"))}finally{he(!1)}}},Te=l.useCallback(()=>b?(Q.error(t("settings.mcp.page.toast.createServerBeforeLiveActions")),!1):tt?(Q.error(t("settings.mcp.page.toast.saveBeforeLiveActions")),!1):!0,[tt,b,t]),ne=l.useCallback(async(Se=!1)=>{try{await f({directory:g,silent:Se})}catch(ut){Se||Q.error(ut instanceof Error?ut.message:t("settings.mcp.page.toast.refreshStatusFailed"))}},[g,f,t]);l.useEffect(()=>{ne(!0)},[ne]),l.useEffect(()=>{lt.current=rt,he(!1),Be(!1),bt()},[bt,rt]);const Pe=l.useCallback(async()=>{if(!n||S!=="remote"||!Te())return;Le(!0);const Se=rt;let ut=null;try{const mt=ws.getState().getStatusForDirectory(g??null)[n]?.status;Ee.current=mt==="needs_auth"||mt==="needs_client_registration";const At=Hc(n,g);if(!At)throw new Error(t("settings.mcp.page.toast.oauthRedirectUrlBuildFailed"));if(!me.trim()&&!m){const Vt=await p(n,{oauthEnabled:te,oauthClientId:P,oauthClientSecret:L,oauthScope:Y,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(lt.current!==Se)return;ae(At),xt.current=xt.current?{...xt.current,oauthRedirectUri:At}:xt.current}const ft=await y(n,g),vt=Wu(new URL(ft).searchParams);if(vt&&(ut=vt,await Qb({state:vt,name:n,directory:g})),lt.current!==Se)return;He(ft),Oe(vt??null),ze(!0),$.current=0;const Dt=await Hn(ft);if(lt.current!==Se)return;Dt?Q.message(t(m?"settings.mcp.page.toast.completeAuthorizationInBrowserWithPaste":"settings.mcp.page.toast.completeAuthorizationInBrowser")):Q.error(t("settings.mcp.page.toast.openAuthorizationUrlFailed"))}catch(mt){await ii(ut),lt.current===Se&&Q.error(no(mt,t("settings.mcp.page.toast.authorizationStartFailed"),e))}finally{lt.current===Se&&Le(!1)}},[g,m,S,P,L,te,me,Y,Te,rt,n,y,t,e,p]),Xe=l.useCallback(async()=>{if(!n||!Te())return;Fe(!0);const Se=rt;try{if(await O(n,g),lt.current!==Se)return;He(null),Oe(null),ye(""),ze(!1),$.current=0,await ii(_e),Q.success(t("settings.mcp.page.toast.savedAuthorizationRemoved"))}catch(ut){lt.current===Se&&Q.error(no(ut,t("settings.mcp.page.toast.clearAuthorizationFailed"),e))}finally{lt.current===Se&&Fe(!1)}},[_e,O,g,Te,rt,n,t,e]),Re=l.useCallback(async()=>{if(!Ue)return;if((await oa(Ue)).ok){Q.success(t("settings.mcp.page.toast.authorizationUrlCopied"));return}Q.error(t("settings.mcp.page.toast.authorizationUrlCopyFailed"))},[Ue,t]),Ye=l.useCallback(async()=>{const Se=Hb(se);if(!Se.code){Q.error(t("settings.mcp.page.toast.pasteCallbackOrCodeFirst"));return}const ut=Se.stateKey?await Xb(Se.stateKey):null,mt=Se.context??ut,At=mt?.name??n,ft=mt?.directory??g;if(!At){Q.error(t("settings.mcp.page.toast.missingServerDetails"));return}if(!mt&&!Te())return;Ve(!0);const vt=rt;try{if(await C(At,Se.code,ft),await ii(Se.stateKey??_e),lt.current!==vt)return;ye(""),He(null),Oe(null),ze(!1),$.current=0,Q.success(At===n?t("settings.mcp.page.toast.authorizationCompleted"):t("settings.mcp.page.toast.authorizationCompletedFor",{name:At}))}catch(Dt){lt.current===vt&&Q.error(no(Dt,t("settings.mcp.page.toast.authorizationCompleteFailed"),e))}finally{lt.current===vt&&Ve(!1)}},[se,_e,C,g,Te,rt,n,t,e]),We=l.useCallback(async()=>{if(!(!n||!Te())){if(!ie){Q.error(t("settings.mcp.page.toast.enableServerBeforeTest"));return}Be(!0);try{const Se=await j(n,g),ut=Se.status?.status;Se.warning?Q.warning(Se.warning):ut==="connected"?Q.success(t("settings.mcp.page.toast.connectionTestSucceeded")):ut==="needs_auth"?Q.message(t("settings.mcp.page.toast.connectionNeedsAuthorization")):ut==="needs_client_registration"?Q.message(t("settings.mcp.page.toast.connectionNeedsClientRegistration")):ut==="failed"?Q.error(Se.status?.error||Se.error||t("settings.mcp.page.toast.connectionTestFailed")):Se.error?Q.error(Se.error):Q.message(t("settings.mcp.page.toast.connectionTestFinished"))}catch(Se){Q.error(Se instanceof Error?Se.message:t("settings.mcp.page.toast.connectionTestFailed"))}finally{Be(!1)}}},[g,ie,Te,n,t,j]);if(l.useEffect(()=>{if(!ke||!n)return;const Se=window.setInterval(()=>{(async()=>{$.current+=1,await f({directory:g,silent:!0});const ut=ws.getState().getStatusForDirectory(g??null)[n];if(ut){if(Ee.current&&ut.status!=="needs_auth"&&ut.status!=="needs_client_registration"){ze(!1),$.current=0,Ee.current=!1,He(null),ye(""),ut.status==="connected"&&Q.success(t("settings.mcp.page.toast.authorizationCompleted"));return}if(!Ee.current&&ut.status==="failed"){ze(!1),$.current=0,Ee.current=!1,Q.error(ut.error||t("settings.mcp.page.toast.authorizationFailed"));return}$.current>=30&&(ze(!1),$.current=0,Ee.current=!1,Q.message(t("settings.mcp.page.toast.authorizationStillInProgress")))}})()},2e3);return()=>{window.clearInterval(Se)}},[g,ke,f,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 et=w[n],kt=n?h[n]:void 0,Et=et??kt,Ot=et?.status==="connected",Zt=et?.status==="needs_auth"||et?.status==="needs_client_registration",Qt=m?null:Hc(n,g),St=qb(Et?.status,e,Et&&"error"in Et?Et.error:void 0),Pt=Se=>{switch(Se){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 Se}};return s.jsxs(s.Fragment,{children:[s.jsxs(ps,{title:b?t("settings.mcp.page.header.newServer"):n,titleAccessory:b?void 0:s.jsx(Vc,{status:Et?.status,enabled:ie,getStatusLabel:Pt,variant:"pill"}),description:b?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:b?void 0:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(ee,{variant:Ot?"outline":"default",size:"xs",className:"!font-normal",onClick:wt,disabled:le||!ie,children:t(le?"settings.mcp.page.actions.working":Ot?"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:()=>{Pe()},disabled:De||!ie,children:t(De?"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:Ke||!ie,children:t(Ke?"settings.mcp.page.actions.clearing":"settings.mcp.page.actions.clearAuth")})]}),Ot&&s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:()=>{We()},disabled:Me||!ie,children:t(Me?"settings.mcp.page.actions.testing":"settings.mcp.page.actions.test")})]}),showSaveStatus:!1,children:[!b&&Yb(Et?.status,Ue,Zt,ke)&&s.jsx(dt,{divider:!1,children:s.jsxs("div",{className:fe("rounded-lg border p-3",Jb(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(Vc,{status:Et?.status,enabled:ie,getStatusLabel:Pt})]}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:St}),s.jsx("p",{className:"typography-micro text-muted-foreground/80",children:T==="project"?t("settings.mcp.page.status.projectScopedTo",{directory:g??t("settings.mcp.page.status.activeProject")}):t("settings.mcp.page.status.userScoped")})]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:!Ot&&s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{We()},disabled:Me||!ie,children:t(Me?"settings.mcp.page.actions.testing":"settings.mcp.page.actions.testConnection")})}),Ue&&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:Ue}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Hn(Ue)},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||ke||Ue)&&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(gn,{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:se,onChange:Se=>ye(Se.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:()=>{Ye()},disabled:Ge,children:t(Ge?"settings.mcp.page.actions.completing":"settings.mcp.page.actions.completeAuthorization")})})]})})]}),ke&&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:[b&&s.jsxs(Xt,{label:t("settings.mcp.page.server.name"),children:[s.jsx(nt,{value:I,onChange:Se=>B(Se.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(Mt,{value:T,onValueChange:Se=>D(Se),children:[s.jsx(Lt,{size:Gt,className:"!h-7 !w-7 !min-w-0 !px-0 !py-0 justify-center [&>svg:last-child]:hidden",title:t(T==="user"?"settings.common.scope.global":"settings.common.scope.project"),children:T==="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(Ft,{align:"end",children:[s.jsx(jt,{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(jt,{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")})]})})]})]})]}),b&&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:ie,onChange:pe,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(Qs,{"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(Wb,{value:R,onChange:z,pasteCommandTitle:t("settings.mcp.page.connection.pasteCommandTitle"),pasteCommandLabel:t("settings.mcp.page.connection.pasteCommand"),pasteSuccess:Se=>t("settings.mcp.page.toast.pastedArgumentsCount",{count:Se}),clipboardReadFailed:t("settings.mcp.page.toast.clipboardReadFailed"),preview:Se=>t("settings.mcp.page.connection.previewArgs",{count:Se})}):s.jsx(nt,{value:q,onChange:Se=>H(Se.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(da,{open:J,onOpenChange:v,children:[s.jsxs(ua,{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`:"",")"]})]}),J?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(ma,{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(nt,{type:"number",min:"1",step:"1",value:xe,onChange:Se=>be(Se.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(gn,{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($c,{value:A,onChange:X,keyTransform:Se=>Se.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:Se=>t("settings.mcp.page.toast.importedVariablesCount",{count:Se}),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:E,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(nt,{value:P,onChange:Se=>_(Se.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(nt,{value:L,onChange:Se=>V(Se.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(nt,{value:Y,onChange:Se=>G(Se.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(nt,{value:me,onChange:Se=>ae(Se.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:()=>W([{key:"",value:""}]),children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.mcp.page.env.addEnvironmentVariable")]}):s.jsx($c,{value:Z,onChange:W,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:Se=>t("settings.mcp.page.toast.importedVariablesCount",{count:Se}),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:at,disabled:Ie||!tt&&!b,size:"xs",className:"!font-normal",children:t(Ie?"settings.common.actions.saving":b?"settings.common.actions.create":"settings.common.actions.saveChanges")}),!b&&s.jsx(ee,{variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>ge(!0),children:t("settings.common.actions.delete")})]})," "]}),s.jsx(Kt,{open:ue,onOpenChange:Se=>{Se||(Ne(!1),qe(""),st(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:we,onChange:Se=>{qe(Se.target.value),st(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"}),it&&s.jsx("p",{className:"typography-micro text-[var(--status-error)]",children:it}),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:Ce,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:()=>{Ne(!1),qe(""),st(null)},className:"text-foreground",children:t("settings.common.actions.cancel")}),s.jsx(ee,{onClick:Qe,disabled:!we.trim(),size:"sm",children:t("settings.common.actions.import")})]})]})}),s.jsx(Kt,{open:ce,onOpenChange:Se=>{!Se&&!oe&&ge(!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:()=>ge(!1),disabled:oe,className:"text-foreground",children:t("settings.common.actions.cancel")}),s.jsx(ee,{variant:"destructive",size:"sm",onClick:gt,disabled:oe,children:t(oe?"settings.mcp.page.actions.deleting":"settings.common.actions.delete")})]})]})})]})},ty=280,Wc=4,sy=({transform:t})=>({...t,y:0}),ny=t=>{const e=Ze.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:g}=Au(r);let m;e[2]!==p?(m=Du.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 h=g&&"opacity-50";let f;e[7]!==i||e[8]!==h?(f=fe("h-full rounded-md",i,h),e[7]=i,e[8]=h,e[9]=f):f=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]!==f?(x=s.jsx("div",{ref:c,"data-sortable-tab-id":n,style:w,className:f,...o,...d,children:a}),e[10]=o,e[11]=a,e[12]=n,e[13]=d,e[14]=c,e[15]=w,e[16]=f,e[17]=x):x=e[17],x},ay=t=>{const e=Ze.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},pa=t=>{const e=Ze.c(133),{items:n,activeId:a,onSelect:i,onClose:r,onReorder:o,layoutMode:d,variant:c,activePillInsetClassName:p,activePillButtonClassName:u,inactiveTabsIconOnly:g,animateActivePill:m,activePillLowercase:w,nonCompositedIndicator:h,className:f}=t,x=d===void 0?"scrollable":d,k=c===void 0?"default":c,y=g===void 0?!1:g,C=w===void 0?!0:w,O=h===void 0?!1:h,{t:j}=ot(),N=je(iy),{isTablet:b}=Hs(),I=N||b,B=l.useRef(null);let T;e[0]===Symbol.for("react.memo_cache_sentinel")?(T={left:!1,right:!1},e[0]=T):T=e[0];const[D,S]=l.useState(T);let F;e[1]!==n?(F=n.map(ry),e[1]=n,e[2]=F):F=e[2];const R=F,z=x==="scrollable",q=k==="default",H=k==="active-pill",W=H||k==="animated",A=q,X=W||A,te=H&&z,E=W,P=m??W,_=typeof o=="function",L=_?ny:ay;let V;e[3]===Symbol.for("react.memo_cache_sentinel")?(V=new Map,e[3]=V):V=e[3];const Y=l.useRef(V),[G,me]=l.useState(null),[ae,xe]=l.useState(!1),[be,ie]=l.useState(null),pe=l.useRef(!1),Ie=l.useRef(0),re=l.useRef(a),ce=l.useRef(null);let ge;e:{if(!X||!be||!a||be===a){ge=0;break e}const Ye=n.findIndex(et=>et.id===be),We=n.findIndex(et=>et.id===a);if(Ye<0||We<0){ge=0;break e}ge=Ye>We?Wc:-Wc}const oe=ge;let de;e[4]===Symbol.for("react.memo_cache_sentinel")?(de={activationConstraint:{distance:8}},e[4]=de):de=e[4];const le=Su(Cu(Iu,de)),he=oy;let De;e[5]===Symbol.for("react.memo_cache_sentinel")?(De=(Ye,We)=>{if(We){Y.current.set(Ye,We);return}Y.current.delete(Ye)},e[5]=De):De=e[5];const Le=De;let Ke;e[6]!==a||e[7]!==X?(Ke=()=>{if(!X||!a){me(ly);return}const Ye=B.current,We=Y.current.get(a);if(!Ye||!We){me(cy);return}let et=0,kt=0,Et=We;for(;Et&&Et!==Ye;)et=et+Et.offsetLeft,kt=kt+Et.offsetTop,Et=Et.offsetParent;const Ot={left:et,top:kt,width:We.offsetWidth,height:We.offsetHeight};me(Zt=>he(Zt,Ot)?Zt:Ot)},e[6]=a,e[7]=X,e[8]=Ke):Ke=e[8];const Fe=Ke;let Me;e[9]!==z?(Me=()=>{if(!z){S({left:!1,right:!1});return}const Ye=B.current;if(!Ye){S({left:!1,right:!1});return}S({left:Ye.scrollLeft>2,right:Ye.scrollLeft+Ye.clientWidth<Ye.scrollWidth-2})},e[9]=z,e[10]=Me):Me=e[10];const Be=Me;let Ge;e[11]!==z||e[12]!==Be?(Ge=()=>{if(!z){S({left:!1,right:!1});return}const Ye=B.current;if(!Ye)return;Be(),Ye.addEventListener("scroll",Be,{passive:!0});const We=new ResizeObserver(Be);return We.observe(Ye),()=>{Ye.removeEventListener("scroll",Be),We.disconnect()}},e[11]=z,e[12]=Be,e[13]=Ge):Ge=e[13];let Ve;e[14]!==z||e[15]!==n.length||e[16]!==Be?(Ve=[z,n.length,Be],e[14]=z,e[15]=n.length,e[16]=Be,e[17]=Ve):Ve=e[17],l.useEffect(Ge,Ve);let Ue;e[18]!==a||e[19]!==Fe||e[20]!==X?(Ue=()=>{if(!X){me(null);return}Fe();const Ye=B.current;if(!Ye)return;const We=new ResizeObserver(()=>{performance.now()-Ie.current>ty&&xe(!1),Fe()});if(We.observe(Ye),a){const et=Y.current.get(a);et&&We.observe(et)}return()=>{We.disconnect()}},e[18]=a,e[19]=Fe,e[20]=X,e[21]=Ue):Ue=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(Ue,He);let _e;e[27]!==Fe?(_e=()=>{Fe()},e[27]=Fe,e[28]=_e):_e=e[28],l.useLayoutEffect(_e);let Oe;e[29]!==R?(Oe=R.join("\0"),e[29]=R,e[30]=Oe):Oe=e[30];const se=Oe;let ye,ke;e[31]!==a||e[32]!==se||e[33]!==X?(ye=()=>{if(!X){pe.current=!1,xe(!1);return}const Ye=ce.current!==se;if(ce.current=se,!pe.current){pe.current=!0,re.current=a;return}const We=re.current!==a;if(re.current=a,!We||Ye){xe(!1);return}Ie.current=performance.now(),xe(!0)},ke=[a,se,X],e[31]=a,e[32]=se,e[33]=X,e[34]=ye,e[35]=ke):(ye=e[34],ke=e[35]),l.useLayoutEffect(ye,ke);let ze;e[36]!==a||e[37]!==z||e[38]!==Be?(ze=()=>{if(!z||!a)return;const Ye=B.current;if(!Ye)return;const We=window.requestAnimationFrame(()=>{const et=typeof window.CSS?.escape=="function"?window.CSS.escape(a):a.replace(/"/g,'\\"'),kt=Ye.querySelector(`[data-sortable-tab-id="${et}"]`);kt&&(kt.scrollIntoView({block:"nearest",inline:"nearest"}),Be())});return()=>{window.cancelAnimationFrame(We)}},e[36]=a,e[37]=z,e[38]=Be,e[39]=ze):ze=e[39];let $;e[40]!==a||e[41]!==z||e[42]!==n.length||e[43]!==Be?($=[a,z,n.length,Be],e[40]=a,e[41]=z,e[42]=n.length,e[43]=Be,e[44]=$):$=e[44],l.useEffect(ze,$);let Ee;e[45]!==o?(Ee=Ye=>{if(!o)return;const{active:We,over:et}=Ye;!et||We.id===et.id||o(String(We.id),String(et.id))},e[45]=o,e[46]=Ee):Ee=e[46];const J=Ee;let v;e[47]!==f?(v=fe("relative flex h-full min-w-0 flex-1",f),e[47]=f,e[48]=v):v=e[48];let ue;e[49]!==z||e[50]!==D||e[51]!==W?(ue=z&&D.left?s.jsx("div",{className:fe("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",W?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e[49]=z,e[50]=D,e[51]=W,e[52]=ue):ue=e[52];let Ne;e[53]!==z||e[54]!==D||e[55]!==W?(Ne=z&&D.right?s.jsx("div",{className:fe("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",W?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e[53]=z,e[54]=D,e[55]=W,e[56]=Ne):Ne=e[56];const we=W?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",qe=W&&"@container/pill-tabs",it=W&&"pill-tabs__track",st=W&&(p??"gap-0.5 py-0.5"),rt=A&&"items-center overflow-y-hidden",lt=E&&"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=z?"overflow-x-auto scrollbar-none":"overflow-x-hidden";let bt;e[57]!==we||e[58]!==qe||e[59]!==it||e[60]!==st||e[61]!==rt||e[62]!==lt||e[63]!==xt?(bt=fe("relative flex h-full min-w-0 flex-1",we,qe,it,st,rt,lt,xt),e[57]=we,e[58]=qe,e[59]=it,e[60]=st,e[61]=rt,e[62]=lt,e[63]=xt,e[64]=bt):bt=e[64];let Nt;e[65]!==z?(Nt=z?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,e[65]=z,e[66]=Nt):Nt=e[66];let Ce;e[67]!==j?(Ce=j("sortableTabsStrip.aria.tabs"),e[67]=j,e[68]=Ce):Ce=e[68];let Qe;e[69]!==O||e[70]!==oe||e[71]!==G||e[72]!==ae||e[73]!==P||e[74]!==W?(Qe=W&&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)]",P&&ae&&(O?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:O?{left:`${G.left+oe}px`,top:`${G.top}px`,width:`${G.width}px`,height:`${G.height}px`}:{transform:`translate3d(${G.left+oe}px, ${G.top}px, 0)`,width:`${G.width}px`,height:`${G.height}px`}}):null,e[69]=O,e[70]=oe,e[71]=G,e[72]=ae,e[73]=P,e[74]=W,e[75]=Qe):Qe=e[75];let tt;e[76]!==oe||e[77]!==G||e[78]!==ae||e[79]!==A?(tt=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)]",ae&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${G.left+oe}px, 0, 0)`,width:`${G.width}px`},"aria-hidden":!0}):null,e[76]=oe,e[77]=G,e[78]=ae,e[79]=A,e[80]=tt):tt=e[80];let at;if(e[81]!==L||e[82]!==a||e[83]!==u||e[84]!==C||e[85]!==I||e[86]!==y||e[87]!==H||e[88]!==N||e[89]!==z||e[90]!==n||e[91]!==r||e[92]!==i||e[93]!==te||e[94]!==W||e[95]!==X){let Ye;e[97]!==L||e[98]!==a||e[99]!==u||e[100]!==C||e[101]!==I||e[102]!==y||e[103]!==H||e[104]!==N||e[105]!==z||e[106]!==r||e[107]!==i||e[108]!==te||e[109]!==W||e[110]!==X?(Ye=We=>{const et=We.id===a,kt=y&&W&&!et&&!!We.icon,Et=!kt,Ot=!!We.icon,Zt=y&&W&&et&&!z&&!te,Qt=We.closable!==!1&&!!r,St=Qt&&!!We.icon,Pt=z||te?void 0:W?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",Se=Qt?mt=>{mt.button===1&&(mt.preventDefault(),mt.stopPropagation(),r?.(We.id))}:void 0,ut=Qt?dy:void 0;return s.jsx(L,{id:We.id,className:Pt,children:s.jsxs("div",{ref:mt=>Le(We.id,mt),onAuxClick:Se,onMouseDown:ut,className:fe("group flex h-full min-w-0 flex-nowrap items-center",z||te?"shrink-0":W?"w-full":"w-full min-w-0",W?"relative z-10 bg-transparent":et?"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":et,"aria-label":kt?We.title??We.label:void 0,onClick:()=>i(We.id),onPointerDown:X?()=>{xe(!0),ie(We.id)}:void 0,onPointerUp:X?()=>ie(null):void 0,onPointerLeave:X?()=>ie(null):void 0,onPointerCancel:X?()=>ie(null):void 0,className:fe(W?"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",W&&C?"lowercase":null,W&&(kt?"gap-0":"gap-1.5"),W?te?"shrink-0 whitespace-nowrap px-3 text-center":z?"max-w-56 shrink-0 px-3 text-center":kt?"px-2 !min-w-0 text-center":Zt?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":z?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",W?u??(H?N?"h-[38px]":"h-[31px]":"h-7"):null,W?et?"text-foreground":"text-muted-foreground hover:text-foreground":null,W?"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:We.title??We.label,children:W?s.jsxs(s.Fragment,{children:[Ot?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&&(I?"opacity-0":"group-hover:opacity-0")),children:We.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",I?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:uy,onClick:mt=>{mt.stopPropagation(),r?.(We.id)},"aria-label":We.closeLabel??`Close ${We.label} tab`,title:We.closeLabel??`Close ${We.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:We.label}):null]}):s.jsxs("span",{className:fe("flex min-w-0 flex-nowrap items-center gap-1.5",!z&&"justify-center"),children:[Ot?s.jsxs("span",{className:fe("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",et?"text-[var(--primary-base)]":"text-muted-foreground"),children:[s.jsx("span",{className:fe("flex items-center justify-center transition-opacity",St&&(I?"opacity-0":"group-hover:opacity-0")),children:We.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",I?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:my,onClick:mt=>{mt.stopPropagation(),r?.(We.id)},"aria-label":We.closeLabel??`Close ${We.label} tab`,title:We.closeLabel??`Close ${We.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:We.label})]})}),Qt&&!St?s.jsx("button",{type:"button",onPointerDown:py,onClick:mt=>{mt.stopPropagation(),r?.(We.id)},className:fe("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",W?"-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",W?et?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":et?"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":We.closeLabel??`Close ${We.label} tab`,title:We.closeLabel??`Close ${We.label} tab`,children:s.jsx(K,{name:"close",className:"h-3 w-3"})}):null]})},We.id)},e[97]=L,e[98]=a,e[99]=u,e[100]=C,e[101]=I,e[102]=y,e[103]=H,e[104]=N,e[105]=z,e[106]=r,e[107]=i,e[108]=te,e[109]=W,e[110]=X,e[111]=Ye):Ye=e[111],at=n.map(Ye),e[81]=L,e[82]=a,e[83]=u,e[84]=C,e[85]=I,e[86]=y,e[87]=H,e[88]=N,e[89]=z,e[90]=n,e[91]=r,e[92]=i,e[93]=te,e[94]=W,e[95]=X,e[96]=at}else at=e[96];let gt;e[112]!==bt||e[113]!==Nt||e[114]!==Ce||e[115]!==Qe||e[116]!==tt||e[117]!==at?(gt=s.jsxs("div",{ref:B,className:bt,style:Nt,role:"tablist","aria-label":Ce,children:[Qe,tt,at]}),e[112]=bt,e[113]=Nt,e[114]=Ce,e[115]=Qe,e[116]=tt,e[117]=at,e[118]=gt):gt=e[118];let wt;e[119]!==v||e[120]!==ue||e[121]!==Ne||e[122]!==gt?(wt=s.jsxs("div",{className:v,children:[ue,Ne,gt]}),e[119]=v,e[120]=ue,e[121]=Ne,e[122]=gt,e[123]=wt):wt=e[123];const Te=wt;if(!_)return Te;let ne;e[124]===Symbol.for("react.memo_cache_sentinel")?(ne=[sy],e[124]=ne):ne=e[124];let Pe;e[125]!==R||e[126]!==Te?(Pe=s.jsx(Eu,{items:R,strategy:Xf,children:Te}),e[125]=R,e[126]=Te,e[127]=Pe):Pe=e[127];let Xe;e[128]===Symbol.for("react.memo_cache_sentinel")?(Xe=s.jsx(Qf,{dropAnimation:null}),e[128]=Xe):Xe=e[128];let Re;return e[129]!==J||e[130]!==le||e[131]!==Pe?(Re=s.jsxs(Pu,{sensors:le,collisionDetection:Tu,onDragEnd:J,modifiers:ne,children:[Pe,Xe]}),e[129]=J,e[130]=le,e[131]=Pe,e[132]=Re):Re=e[132],Re};function iy(t){return t.isMobile}function ry(t){return t.id}function oy(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 ly(t){return t===null?t:null}function cy(t){return t===null?t:null}function dy(t){t.button===1&&t.preventDefault()}function uy(t){t.stopPropagation()}function my(t){t.stopPropagation()}function py(t){t.stopPropagation()}const ar=()=>{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},gy=800,fy=5e3,hy="__default__",Yo=new Map,ao=new Map,xy=1500,Gu=t=>t?.trim()||hy,by=t=>{Yo.delete(Gu(t))},js=fn()(Ja(vi((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=ar(),i=Gu(a),r=Date.now(),o=Yo.get(i)??0,d=e().entries.length>0||e().files.length>0;if(!n?.force&&d&&r-o<fy)return!0;const c=ao.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:ri(a)});if(!u.ok)throw new Error("Failed to load plugins");const g=await ir(u);return t({entries:g.entries??[],files:g.files??[],isLoading:!1}),Yo.set(i,Date.now()),n?.force||e().loadRegistryInfo(),!0}catch(u){return console.error("[PluginsStore] Failed to load plugins:",u),t({isLoading:!1}),!1}})();ao.set(i,p);try{return await p}finally{ao.delete(i)}},loadRegistryInfo:async n=>{const a=vy(n?.specs??e().entries.map(i=>i.spec));if(a.length===0){t({isLoadingRegistry:!1});return}t({isLoadingRegistry:!0});try{const i=ar(),r={...e().registryInfo};for(const o of wy(a)){const d=await ht(yy(o,n?.force===!0,i),{headers:ri(i)});if(!d.ok)throw new Error("Failed to load plugin registry info");const c=await ir(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 Aa("Creating plugin entry…",async i=>await ht(Ln("/api/config/plugins/entry",i),{method:"POST",headers:Ui(i),body:JSON.stringify(Gc(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 Aa("Updating plugin entry…",async d=>await ht(Ln(`/api/config/plugins/entry/${encodeURIComponent(n)}`,d),{method:"PATCH",headers:Ui(d),body:JSON.stringify(Gc(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 Aa("Deleting plugin entry…",async r=>await ht(Ln(`/api/config/plugins/entry/${encodeURIComponent(n)}`,r),{method:"DELETE",headers:ri(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=ar(),i=await ht(Ln(`/api/config/plugins/file/${encodeURIComponent(n)}`,a),{headers:ri(a)});if(!i.ok)throw new Error("Failed to read plugin file");return await ir(i)}catch(a){return console.error("[PluginsStore] Failed to read plugin file:",a),null}},createFile:async n=>Aa("Creating plugin file…",async a=>await ht(Ln("/api/config/plugins/file",a),{method:"POST",headers:Ui(a),body:JSON.stringify(n)}),e),updateFile:async(n,a)=>Aa("Updating plugin file…",async i=>await ht(Ln(`/api/config/plugins/file/${encodeURIComponent(n)}`,i),{method:"PUT",headers:Ui(i),body:JSON.stringify(a)}),e),deleteFile:async n=>{const a=await Aa("Deleting plugin file…",async i=>await ht(Ln(`/api/config/plugins/file/${encodeURIComponent(n)}`,i),{method:"DELETE",headers:ri(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:Pr(),partialize:t=>({selectedId:t.selectedId})}),{name:"plugins-store"}));function Ln(t,e){const n=e?`?directory=${encodeURIComponent(e)}`:"";return`${t}${n}`}function yy(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 vy(t){return Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))}function wy(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>xy?(e.push(n),n=[i],a=r.length):(n.push(i),a=o)}return n.length>0&&e.push(n),e}function ri(t){return t?{"x-opencode-directory":t}:void 0}function Ui(t){return{"Content-Type":"application/json",...t?{"x-opencode-directory":t}:{}}}function Gc(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 Aa(t,e,n){er(t);let a=!1;try{const i=ar(),r=await e(i),o=await ir(r).catch(()=>null);if(!r.ok)throw new Error(o?.error||"Failed to update plugin configuration");return by(i),o?.requiresReload&&(a=!0,await tr({message:o.message,delayMs:o.reloadDelayMs??gy,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||sr()}}async function ir(t){return await t.json()}const jy=/^[a-z0-9][a-z0-9-_.]*\.(js|ts|mjs|cjs)$/;function ky(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 Ny=({open:t,onOpenChange:e,defaultScope:n="user"})=>{const{t:a}=ot(),i=js(z=>z.createEntry),r=js(z=>z.createFile),[o,d]=l.useState("npm"),[c,p]=l.useState(""),[u,g]=l.useState(""),[m,w]=l.useState(""),[h,f]=l.useState(""),[x,k]=l.useState(n),[y,C]=l.useState(!1),O=l.useCallback(()=>{p(""),g(""),w(""),f(""),k(n)},[n]);l.useEffect(()=>{t&&(d("npm"),O())},[t,O]);const j=z=>{z!==o&&(d(z),O())},N=l.useMemo(()=>ky(u),[u]),b=!N.ok,I=o==="file"&&m.trim()!==""&&!jy.test(m.trim()),B=(o==="npm"||o==="path")&&c.trim()==="",T=o==="file"&&h.trim()==="",D=o==="file"&&m.trim()==="",S=y||b||o==="npm"&&B||o==="path"&&B||o==="file"&&(D||I||T),F=async()=>{if(!S){C(!0);try{let z;o==="file"?z=await r({fileName:m.trim(),content:h,scope:x}):z=await i({spec:c.trim(),options:N.ok?N.value:void 0,scope:x}),z.ok?(Q.success(z.message||a("settings.plugins.toast.created")),z.reloadFailed&&Q.warning(a("settings.plugins.toast.reloadFailed")),e(!1)):Q.error(z.message||a("settings.plugins.sidebar.toast.deleteFailed"))}finally{C(!1)}}},R=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:z=>{!z&&y||e(z)},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(pa,{items:R,activeId:o,onSelect:z=>j(z),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(nt,{id:"plugin-spec",value:c,onChange:z=>p(z.target.value),placeholder:a("settings.plugins.page.field.spec.placeholder"),"aria-invalid":B?!1:void 0,disabled:y}),B&&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:z=>g(z.target.value),rows:5,className:"font-mono",hasError:b,disabled:y}),b&&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(nt,{id:"plugin-filename",value:m,onChange:z=>w(z.target.value),placeholder:"my-plugin.ts","aria-invalid":I||void 0,disabled:y}),I&&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:h,onChange:z=>f(z.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(z=>{const q=x===z,H=a(z==="user"?"settings.plugins.scope.user":"settings.plugins.scope.project");return s.jsxs("button",{type:"button",onClick:()=>k(z),disabled:y,className:"flex items-center gap-2 py-1 text-left disabled:opacity-50",children:[s.jsx(Nr,{checked:q,onChange:()=>k(z),ariaLabel:H}),s.jsx("span",{className:fe("typography-ui-label font-normal",q?"text-foreground":"text-foreground/60"),children:H})]},z)})})]})]}),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")]})]})]})})},Sy=t=>{const e=Ze.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}=ot();if(!i)return null;const o=Cy;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 Cy(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 qu=t=>{const e=Ze.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,g]=l.useState(!1),[m,w]=l.useState(!1),h=d==="background"||c?"bg-background":"bg-sidebar",f=h==="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){g(!1),w(!1);return}if(!(S.scrollHeight>S.clientHeight+1)){g(!1),w(!1);return}g(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 O,j;e[4]===Symbol.for("react.memo_cache_sentinel")?(O=()=>{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]=O,e[5]=j):(O=e[4],j=e[5]),l.useEffect(O,j);let N;e[6]!==h||e[7]!==r?(N=fe("flex h-full flex-col",h,r),e[6]=h,e[7]=r,e[8]=N):N=e[8];let b;e[9]!==i?(b=s.jsx(zs,{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]=b):b=e[10];let I;e[11]!==f||e[12]!==u?(I=u&&s.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-4",style:{background:`linear-gradient(to bottom, ${f} 0%, transparent 100%)`}}),e[11]=f,e[12]=u,e[13]=I):I=e[13];let B;e[14]!==f||e[15]!==m?(B=m&&s.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-6",style:{background:`linear-gradient(to top, ${f} 0%, transparent 100%)`}}),e[14]=f,e[15]=m,e[16]=B):B=e[16];let T;e[17]!==B||e[18]!==b||e[19]!==I?(T=s.jsxs("div",{className:"relative flex flex-1 min-h-0 flex-col",children:[b,I,B]}),e[17]=B,e[18]=b,e[19]=I,e[20]=T):T=e[20];let D;return e[21]!==a||e[22]!==n||e[23]!==T||e[24]!==N?(D=s.jsxs("div",{className:N,children:[n,T,a]}),e[21]=a,e[22]=n,e[23]=T,e[24]=N,e[25]=D):D=e[25],D},Qo=t=>{const e=Ze.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,g=p?"bg-interactive-selection":"hover:bg-interactive-hover";let m;e[0]!==c||e[1]!==g?(m=fe("group relative flex items-center rounded-md px-1.5 py-0.5 transition-all duration-200",g,c),e[0]=c,e[1]=g,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 h;e[5]!==o||e[6]!==w?(h=s.jsxs("div",{className:"flex items-center gap-1.5",children:[o,w]}),e[5]=o,e[6]=w,e[7]=h):h=e[7];let f;e[8]!==a?(f=a&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:a}),e[8]=a,e[9]=f):f=e[9];let x;e[10]!==r||e[11]!==h||e[12]!==f?(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:[h,f]}),e[10]=r,e[11]=h,e[12]=f,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(Iy)})]}),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 Iy(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 Py=t=>t.parsedKind==="npm"?"code-box":"folder",Ty=t=>{const e=Ze.c(144),{onItemSelect:n,onAddClick:a}=t,{t:i}=ot(),{entries:r,files:o,selectedId:d,setSelected:c,deleteEntry:p,deleteFile:u,loadPlugins:g}=js(Ws(Ay)),m=js(Ey),w=js(Dy),h=js(Ry),f=js(My),[x,k]=l.useState(null),[y,C]=l.useState(!1),[O,j]=l.useState(!1);let N,b;e[0]!==g?(N=()=>{g()},b=[g],e[0]=g,e[1]=N,e[2]=b):(N=e[1],b=e[2]),l.useEffect(N,b);let I,B;e[3]===Symbol.for("react.memo_cache_sentinel")?(I=()=>{const Ce=()=>j(!0);return window.addEventListener("openchamber:settings-open-plugin-add",Ce),()=>window.removeEventListener("openchamber:settings-open-plugin-add",Ce)},B=[],e[3]=I,e[4]=B):(I=e[3],B=e[4]),l.useEffect(I,B);let T;if(e[5]!==r||e[6]!==m){T={userEntries:0,projectEntries:0};for(const Ce of r){const Qe=m[Ce.spec];Qe?.kind==="npm-ok"&&Qe.hasUpdate&&(Ce.scope==="user"?T.userEntries=T.userEntries+1:Ce.scope==="project"&&(T.projectEntries=T.projectEntries+1))}e[5]=r,e[6]=m,e[7]=T}else T=e[7];const D=T;let S;e[8]!==r?(S=r.filter(Ly),e[8]=r,e[9]=S):S=e[9];const F=S;let R;e[10]!==r?(R=r.filter(Fy),e[10]=r,e[11]=R):R=e[11];const z=R;let q;e[12]!==o?(q=o.filter(Oy),e[12]=o,e[13]=q):q=e[13];const H=q;let Z;e[14]!==o?(Z=o.filter(zy),e[14]=o,e[15]=Z):Z=e[15];const W=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 E=te;let P;e[18]!==n||e[19]!==c?(P=Ce=>{c(Ce),n?.()},e[18]=n,e[19]=c,e[20]=P):P=e[20];const _=P;let L;e[21]!==r||e[22]!==m||e[23]!==i||e[24]!==f?(L=async Ce=>{const Qe=r.find(wt=>wt.id===Ce);if(!Qe)return;const tt=m[Qe.spec];if(!tt||tt.kind!=="npm-ok"||!tt.hasUpdate||!tt.latestVersion)return;const at=tt.latestVersion;(await f(Ce)).ok?Q.success(i("settings.plugins.toast.updatedToLatest",{version:at})):Q.error(i("settings.plugins.toast.refreshFailed"))},e[21]=r,e[22]=m,e[23]=i,e[24]=f,e[25]=L):L=e[25];const V=L;let Y;e[26]!==h||e[27]!==i?(Y=async()=>{Q.info(i("settings.plugins.toast.refreshing"));try{await h({force:!0})}catch{Q.error(i("settings.plugins.toast.refreshFailed"))}},e[26]=h,e[27]=i,e[28]=Y):Y=e[28];const G=Y;let me;e[29]!==p||e[30]!==u||e[31]!==x||e[32]!==i?(me=async()=>{if(!x)return;C(!0);const Ce=x.kind==="entry"?await p(x.id):await u(x.id);Ce.ok?Q.success(Ce.message||i("settings.plugins.sidebar.toast.deleted",{name:x.label})):Q.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]=me):me=e[33];const ae=me;let xe;e[34]!==_||e[35]!==V||e[36]!==m||e[37]!==d||e[38]!==i?(xe=Ce=>{const Qe=m[Ce.spec],tt=Qe?.kind==="npm-ok"&&Qe.hasUpdate&&!!Qe.latestVersion,at=[];return tt&&at.push({label:i("settings.plugins.sidebar.actions.updateToLatest"),icon:"arrow-up-s",onClick:()=>{V(Ce.id)}}),at.push({label:i("settings.common.actions.delete"),icon:"delete-bin",destructive:!0,onClick:()=>k({kind:"entry",id:Ce.id,label:Ce.spec})}),s.jsx(Qo,{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:Ce.spec}),s.jsx(Sy,{spec:Ce.spec})]}),metadata:Ce.parsedKind==="npm"?i("settings.plugins.sidebar.kind.npm"):i("settings.plugins.sidebar.kind.path"),selected:d===Ce.id,onSelect:()=>_(Ce.id),icon:s.jsx(K,{name:Py(Ce),className:"h-4 w-4 flex-shrink-0 text-muted-foreground/70"}),actions:at},Ce.id)},e[34]=_,e[35]=V,e[36]=m,e[37]=d,e[38]=i,e[39]=xe):xe=e[39];const be=xe;let ie;e[40]!==_||e[41]!==d||e[42]!==i?(ie=Ce=>s.jsx(Qo,{title:Ce.fileName,metadata:i("settings.plugins.sidebar.kind.file"),selected:d===Ce.id,onSelect:()=>_(Ce.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:Ce.id,label:Ce.fileName})}]},Ce.id),e[40]=_,e[41]=d,e[42]=i,e[43]=ie):ie=e[43];const pe=ie;let Ie;e[44]!==i?(Ie=(Ce,Qe,tt)=>{const at=tt===void 0?0:tt;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:[Ce,at>0&&s.jsx("span",{className:"ml-2 normal-case font-normal text-[var(--status-success)]",children:i(at===1?"settings.plugins.sidebar.group.updatesAvailable_one":"settings.plugins.sidebar.group.updatesAvailable_other",{count:at})})]}),Qe]})},e[44]=i,e[45]=Ie):Ie=e[45];const re=Ie;let ce;e[46]!==i?(ce=i("settings.plugins.sidebar.title"),e[46]=i,e[47]=ce):ce=e[47];let ge;e[48]!==ce?(ge=s.jsx("div",{className:"mb-3 flex items-center justify-between gap-3",children:s.jsx("h2",{className:hn,children:ce})}),e[48]=ce,e[49]=ge):ge=e[49];let oe;e[50]!==i||e[51]!==A?(oe=i("settings.plugins.sidebar.total",{count:A}),e[50]=i,e[51]=A,e[52]=oe):oe=e[52];let de;e[53]!==oe?(de=s.jsx("span",{className:"typography-meta text-muted-foreground",children:oe}),e[53]=oe,e[54]=de):de=e[54];let le;e[55]!==G?(le=()=>{G()},e[55]=G,e[56]=le):le=e[56];let he;e[57]!==i?(he=i("settings.plugins.sidebar.actions.refresh"),e[57]=i,e[58]=he):he=e[58];let De;e[59]!==i?(De=i("settings.plugins.sidebar.actions.refresh"),e[59]=i,e[60]=De):De=e[60];const Le=w?"size-4 animate-spin":"size-4";let Ke;e[61]!==Le?(Ke=s.jsx(K,{name:"refresh",className:Le}),e[61]=Le,e[62]=Ke):Ke=e[62];let Fe;e[63]!==w||e[64]!==le||e[65]!==he||e[66]!==De||e[67]!==Ke?(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:le,disabled:w,"aria-label":he,title:De,children:Ke}),e[63]=w,e[64]=le,e[65]=he,e[66]=De,e[67]=Ke,e[68]=Fe):Fe=e[68];let Me;e[69]!==i?(Me=i("settings.plugins.sidebar.actions.addTitle"),e[69]=i,e[70]=Me):Me=e[70];let Be;e[71]!==i?(Be=i("settings.plugins.sidebar.actions.addTitle"),e[71]=i,e[72]=Be):Be=e[72];let Ge;e[73]===Symbol.for("react.memo_cache_sentinel")?(Ge=s.jsx(K,{name:"add",className:"size-4"}),e[73]=Ge):Ge=e[73];let Ve;e[74]!==E||e[75]!==Me||e[76]!==Be?(Ve=s.jsx(ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:E,"aria-label":Me,title:Be,children:Ge}),e[74]=E,e[75]=Me,e[76]=Be,e[77]=Ve):Ve=e[77];let Ue;e[78]!==Fe||e[79]!==Ve?(Ue=s.jsxs("div",{className:"flex items-center gap-1",children:[Fe,Ve]}),e[78]=Fe,e[79]=Ve,e[80]=Ue):Ue=e[80];let He;e[81]!==de||e[82]!==Ue?(He=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[de,Ue]}),e[81]=de,e[82]=Ue,e[83]=He):He=e[83];let _e;e[84]!==ge||e[85]!==He?(_e=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[ge,He]}),e[84]=ge,e[85]=He,e[86]=_e):_e=e[86];let Oe;e[87]!==X||e[88]!==z||e[89]!==W||e[90]!==be||e[91]!==pe||e[92]!==re||e[93]!==i||e[94]!==D||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&&re(i("settings.plugins.sidebar.group.userEntries"),F.map(be),D.userEntries),H.length>0&&re(i("settings.plugins.sidebar.group.userFiles"),H.map(pe)),z.length>0&&re(i("settings.plugins.sidebar.group.projectEntries"),z.map(be),D.projectEntries),W.length>0&&re(i("settings.plugins.sidebar.group.projectFiles"),W.map(pe))]}),e[87]=X,e[88]=z,e[89]=W,e[90]=be,e[91]=pe,e[92]=re,e[93]=i,e[94]=D,e[95]=F,e[96]=H,e[97]=Oe):Oe=e[97];let se;e[98]!==_e||e[99]!==Oe?(se=s.jsx(qu,{variant:"background",header:_e,children:Oe}),e[98]=_e,e[99]=Oe,e[100]=se):se=e[100];let ye;e[101]!==O?(ye=s.jsx(Ny,{open:O,onOpenChange:j}),e[101]=O,e[102]=ye):ye=e[102];const ke=x!==null;let ze;e[103]!==y?(ze=Ce=>{!Ce&&!y&&k(null)},e[103]=y,e[104]=ze):ze=e[104];let $;e[105]!==i?($=i("settings.plugins.sidebar.deleteDialog.title"),e[105]=i,e[106]=$):$=e[106];let Ee;e[107]!==$?(Ee=s.jsx(_t,{children:$}),e[107]=$,e[108]=Ee):Ee=e[108];const J=x?.label??"";let v;e[109]!==i||e[110]!==J?(v=i("settings.plugins.sidebar.deleteDialog.description",{name:J}),e[109]=i,e[110]=J,e[111]=v):v=e[111];let ue;e[112]!==v?(ue=s.jsx(Yt,{children:v}),e[112]=v,e[113]=ue):ue=e[113];let Ne;e[114]!==Ee||e[115]!==ue?(Ne=s.jsxs(Ut,{children:[Ee,ue]}),e[114]=Ee,e[115]=ue,e[116]=Ne):Ne=e[116];let we;e[117]===Symbol.for("react.memo_cache_sentinel")?(we=()=>k(null),e[117]=we):we=e[117];let qe;e[118]!==i?(qe=i("settings.common.actions.cancel"),e[118]=i,e[119]=qe):qe=e[119];let it;e[120]!==y||e[121]!==qe?(it=s.jsx(ee,{size:"sm",variant:"ghost",onClick:we,disabled:y,children:qe}),e[120]=y,e[121]=qe,e[122]=it):it=e[122];let st;e[123]!==y||e[124]!==i?(st=i(y?"settings.plugins.sidebar.actions.deleting":"settings.common.actions.delete"),e[123]=y,e[124]=i,e[125]=st):st=e[125];let rt;e[126]!==ae||e[127]!==y||e[128]!==st?(rt=s.jsx(ee,{size:"sm",variant:"destructive",onClick:ae,disabled:y,children:st}),e[126]=ae,e[127]=y,e[128]=st,e[129]=rt):rt=e[129];let lt;e[130]!==it||e[131]!==rt?(lt=s.jsxs(rs,{children:[it,rt]}),e[130]=it,e[131]=rt,e[132]=lt):lt=e[132];let xt;e[133]!==Ne||e[134]!==lt?(xt=s.jsxs(Bt,{className:"max-w-md",children:[Ne,lt]}),e[133]=Ne,e[134]=lt,e[135]=xt):xt=e[135];let bt;e[136]!==ke||e[137]!==ze||e[138]!==xt?(bt=s.jsx(Kt,{open:ke,onOpenChange:ze,children:xt}),e[136]=ke,e[137]=ze,e[138]=xt,e[139]=bt):bt=e[139];let Nt;return e[140]!==se||e[141]!==ye||e[142]!==bt?(Nt=s.jsxs(s.Fragment,{children:[se,ye,bt]}),e[140]=se,e[141]=ye,e[142]=bt,e[143]=Nt):Nt=e[143],Nt};function Ay(t){return{entries:t.entries,files:t.files,selectedId:t.selectedId,setSelected:t.setSelected,deleteEntry:t.deleteEntry,deleteFile:t.deleteFile,loadPlugins:t.loadPlugins}}function Ey(t){return t.registryInfo}function Dy(t){return t.isLoadingRegistry}function Ry(t){return t.loadRegistryInfo}function My(t){return t.updateToLatest}function Ly(t){return t.scope==="user"}function Fy(t){return t.scope==="project"}function Oy(t){return t.scope==="user"}function zy(t){return t.scope==="project"}const Ky=({entryId:t,spec:e})=>{const{t:n}=ot(),a=js(g=>g.registryInfo[e]),i=js(g=>g.updateToLatest),[r,o]=l.useState(!1);if(!a)return null;if(a.kind==="npm-ok"){if(!a.hasUpdate||!a.latestVersion)return null;const g=a.latestVersion,m=a.currentVersion??"",w=async()=>{o(!0);try{(await i(t)).ok?Q.success(n("settings.plugins.toast.updatedToLatest",{version:g})):Q.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:g})})]}),s.jsx(ee,{variant:"default",size:"sm",onClick:()=>{w()},disabled:r,children:n("settings.plugins.registry.banner.updateAvailable.action",{latest:g})})]})}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 By(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 Ju(t){return!t||Object.keys(t).length===0?"":JSON.stringify(t,null,2)}function qc(t){return{mode:"entry",scope:t.scope,spec:t.spec,optionsJson:Ju(t.options),fileName:"",content:""}}function Jc(t,e){return{mode:"file",scope:t.scope,spec:"",optionsJson:"",fileName:t.fileName,content:e}}const Yc=t=>{const e=Ze.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},_y=()=>{const{t}=ot(),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]),[g,m]=l.useState(!1),[w,h]=l.useState(!1),f=l.useRef(new Map);if(l.useEffect(()=>{let x=!1;return p?(r(qc(p)),()=>{x=!0}):u?(h(!0),(async()=>{const k=await c(u.id);if(x)return;h(!1);const y=k?.content??"";f.current.set(u.id,y),r(Jc(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=By(i.optionsJson),k=x.ok,y=i.spec!==p.spec||i.optionsJson!==Ju(p.options),C=()=>{r(qc(p))},O=async()=>{if(!k)return;const j=i.spec.trim();if(!j){Q.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?Q.warning(N.message||t("settings.plugins.toast.reloadFailed"),{description:N.warning}):Q.success(N.message||t("settings.plugins.toast.updated")):Q.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(Yc,{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(Ky,{entryId:p.id,spec:p.spec})}),s.jsx(dt,{title:t("settings.plugins.page.field.spec"),settingsItem:"plugins.spec",children:s.jsx(nt,{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:()=>{O()},disabled:!y||!k||g,children:t("settings.plugins.page.action.save")}),s.jsx(ee,{variant:"outline",size:"sm",onClick:C,disabled:!y||g,children:t("settings.plugins.page.action.discard")})]})]})]})}if(u&&i&&i.mode==="file"){const x=f.current.get(u.id)??"",k=i.content!==x||i.fileName!==u.fileName,y=()=>{(async()=>{h(!0);const j=(await c(u.id))?.content??"";h(!1),f.current.set(u.id,j),r(Jc(u,j))})()},C=async()=>{m(!0);try{const O=await d(u.id,{content:i.content});O.ok?(f.current.set(u.id,i.content),O.reloadFailed?Q.warning(O.message||t("settings.plugins.toast.reloadFailed"),{description:O.warning}):Q.success(O.message||t("settings.plugins.toast.updated"))):Q.error(O.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(Yc,{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:O=>r({...i,content:O.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||g||w,children:t("settings.plugins.page.action.save")}),s.jsx(ee,{variant:"outline",size:"sm",onClick:y,disabled:g||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"})})})},Uy="<built-in>",hi=t=>t?.path===Uy,Xo=t=>!!t&&!hi(t)&&t.renamable===!0,$y=t=>{const e=Ze.c(148),{onItemSelect:n}=t,{t:a}=ot(),[i,r]=l.useState(null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,g]=l.useState(!1),[m,w]=l.useState(null),{selectedSkillName:h,skills:f,setSelectedSkill:x,setSkillDraft:k,deleteSkill:y,renameSkill:C,getSkillDetail:O}=In(Ws(Vy));let j;e[0]!==n||e[1]!==x||e[2]!==k||e[3]!==f?(j=()=>{let Ce="new-skill",Qe=1;for(;f.some(tt=>tt.name===Ce);)Ce=`new-skill-${Qe}`,Qe++;k({name:Ce,scope:"user",source:"opencode",description:""}),x(Ce),n?.()},e[0]=n,e[1]=x,e[2]=k,e[3]=f,e[4]=j):j=e[4];const N=j;let b;e[5]===Symbol.for("react.memo_cache_sentinel")?(b=async Ce=>{hi(Ce)||p(Ce)},e[5]=b):b=e[5];const I=b;let B;e[6]!==c||e[7]!==y||e[8]!==a?(B=async()=>{if(!c)return;if(hi(c)){p(null);return}g(!0),await y(c.name)?(Q.success(a("settings.skills.sidebar.toast.skillDeleted",{name:c.name})),p(null)):Q.error(a("settings.skills.sidebar.toast.deleteSkillFailed")),g(!1)},e[6]=c,e[7]=y,e[8]=a,e[9]=B):B=e[9];const T=B;let D;e[10]!==O||e[11]!==x||e[12]!==k||e[13]!==f||e[14]!==a?(D=async Ce=>{if(hi(Ce))return;const Qe=Ce.name;let tt=1,at=`${Qe}-copy`;for(;f.some(wt=>wt.name===at);)tt++,at=`${Qe}-copy-${tt}`;const gt=await O(Ce.name);if(!gt){Q.error(a("settings.skills.sidebar.toast.duplicateLoadFailed"));return}k({name:at,scope:Ce.scope||"user",source:Ce.source||"opencode",description:(gt.sources.md.fields.includes("description"),""),instructions:""}),x(at)},e[10]=O,e[11]=x,e[12]=k,e[13]=f,e[14]=a,e[15]=D):D=e[15];const S=D;let F;e[16]===Symbol.for("react.memo_cache_sentinel")?(F=Ce=>{Xo(Ce)&&(d(Ce.name),r(Ce))},e[16]=F):F=e[16];const R=F;let z;e[17]!==i||e[18]!==o||e[19]!==C||e[20]!==x||e[21]!==f||e[22]!==a?(z=async()=>{if(!i)return;if(!Xo(i)){r(null);return}const Ce=o.trim().replace(/\s+/g,"-").toLowerCase();if(!Ce){Q.error(a("settings.skills.page.toast.skillNameRequired"));return}if(Ce===i.name){r(null);return}if(f.some(tt=>tt.name===Ce)){Q.error(a("settings.skills.page.toast.skillExists"));return}await C(i.name,Ce)?(Q.success(a("settings.skills.sidebar.toast.skillRenamed",{name:Ce})),x(Ce)):Q.error(a("settings.skills.sidebar.toast.renameFailed")),r(null)},e[17]=i,e[18]=o,e[19]=C,e[20]=x,e[21]=f,e[22]=a,e[23]=z):z=e[23];const q=z;let H;e[24]!==f?(H=f.filter(Hy),e[24]=f,e[25]=H):H=e[25];const Z=H;let W;e[26]!==f?(W=f.filter(Wy),e[26]=f,e[27]=W):W=e[27];const A=W;let X;e[28]===Symbol.for("react.memo_cache_sentinel")?(X=function(Qe){const tt={},at=[];for(const wt of Qe)wt.group?(tt[wt.group]||(tt[wt.group]=[]),tt[wt.group].push(wt)):at.push(wt);const gt=Object.keys(tt).sort(Gy).map(wt=>({name:wt,skills:[...tt[wt]].sort(qy)}));return at.sort(Jy),{sortedGroups:gt,ungrouped:at}},e[28]=X):X=e[28];const te=X;let E;e[29]!==Z?(E=te(Z),e[29]=Z,e[30]=E):E=e[30];const P=E;let _;e[31]!==A?(_=te(A),e[31]=A,e[32]=_):_=e[32];const L=_;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 Y;e[34]!==a?(Y=a("settings.skills.sidebar.title"),e[34]=a,e[35]=Y):Y=e[35];let G;e[36]!==Y?(G=s.jsx("h2",{className:`${hn} mb-3`,children:Y}),e[36]=Y,e[37]=G):G=e[37];let me;e[38]===Symbol.for("react.memo_cache_sentinel")?(me=s.jsx(wi,{className:"mb-3"}),e[38]=me):me=e[38];let ae;e[39]!==f.length||e[40]!==a?(ae=a("settings.skills.sidebar.total",{count:f.length}),e[39]=f.length,e[40]=a,e[41]=ae):ae=e[41];let xe;e[42]!==ae?(xe=s.jsx("span",{className:"typography-meta text-muted-foreground",children:ae}),e[42]=ae,e[43]=xe):xe=e[43];let be;e[44]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[44]=be):be=e[44];let ie;e[45]!==N?(ie=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:be}),e[45]=N,e[46]=ie):ie=e[46];let pe;e[47]!==xe||e[48]!==ie?(pe=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[xe,ie]}),e[47]=xe,e[48]=ie,e[49]=pe):pe=e[49];let Ie;e[50]!==G||e[51]!==pe?(Ie=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[G,me,pe]}),e[50]=G,e[51]=pe,e[52]=Ie):Ie=e[52];let re;e[53]!==P||e[54]!==L||e[55]!==S||e[56]!==n||e[57]!==m||e[58]!==Z||e[59]!==h||e[60]!==x||e[61]!==f.length||e[62]!==a||e[63]!==A?(re=s.jsx(zs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:f.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")}),P.sortedGroups.map(Ce=>{const{name:Qe,skills:tt}=Ce;return s.jsx(Go,{label:Qe,count:tt.length,storageKey:"project-skills",children:tt.map(at=>s.jsx($i,{skill:at,isSelected:h===at.name,onSelect:()=>{x(at.name),n?.()},onRename:()=>R(at),onDelete:()=>I(at),onDuplicate:()=>S(at),isMenuOpen:m===at.name,onMenuOpenChange:gt=>w(gt?at.name:null)},at.name))},Qe)}),P.ungrouped.map(Ce=>s.jsx($i,{skill:Ce,isSelected:h===Ce.name,onSelect:()=>{x(Ce.name),n?.()},onRename:()=>R(Ce),onDelete:()=>I(Ce),onDuplicate:()=>S(Ce),isMenuOpen:m===Ce.name,onMenuOpenChange:Qe=>w(Qe?Ce.name:null)},Ce.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(Ce=>{const{name:Qe,skills:tt}=Ce;return s.jsx(Go,{label:Qe,count:tt.length,storageKey:"user-skills",children:tt.map(at=>s.jsx($i,{skill:at,isSelected:h===at.name,onSelect:()=>{x(at.name),n?.()},onRename:()=>R(at),onDelete:()=>I(at),onDuplicate:()=>S(at),isMenuOpen:m===at.name,onMenuOpenChange:gt=>w(gt?at.name:null)},at.name))},Qe)}),L.ungrouped.map(Ce=>s.jsx($i,{skill:Ce,isSelected:h===Ce.name,onSelect:()=>{x(Ce.name),n?.()},onRename:()=>R(Ce),onDelete:()=>I(Ce),onDuplicate:()=>S(Ce),isMenuOpen:m===Ce.name,onMenuOpenChange:Qe=>w(Qe?Ce.name:null)},Ce.name))]})]})}),e[53]=P,e[54]=L,e[55]=S,e[56]=n,e[57]=m,e[58]=Z,e[59]=h,e[60]=x,e[61]=f.length,e[62]=a,e[63]=A,e[64]=re):re=e[64];const ce=c!==null;let ge;e[65]!==u?(ge=Ce=>{!Ce&&!u&&p(null)},e[65]=u,e[66]=ge):ge=e[66];let oe;e[67]!==a?(oe=a("settings.skills.sidebar.deleteDialog.title"),e[67]=a,e[68]=oe):oe=e[68];let de;e[69]!==oe?(de=s.jsx(_t,{children:oe}),e[69]=oe,e[70]=de):de=e[70];const le=c?.name??"";let he;e[71]!==a||e[72]!==le?(he=a("settings.skills.sidebar.deleteDialog.description",{name:le}),e[71]=a,e[72]=le,e[73]=he):he=e[73];let De;e[74]!==he?(De=s.jsx(Yt,{children:he}),e[74]=he,e[75]=De):De=e[75];let Le;e[76]!==de||e[77]!==De?(Le=s.jsxs(Ut,{children:[de,De]}),e[76]=de,e[77]=De,e[78]=Le):Le=e[78];let Ke;e[79]===Symbol.for("react.memo_cache_sentinel")?(Ke=()=>p(null),e[79]=Ke):Ke=e[79];let Fe;e[80]!==a?(Fe=a("settings.common.actions.cancel"),e[80]=a,e[81]=Fe):Fe=e[81];let Me;e[82]!==u||e[83]!==Fe?(Me=s.jsx(ee,{size:"sm",className:"text-foreground hover:bg-interactive-hover hover:text-foreground",variant:"ghost",onClick:Ke,disabled:u,children:Fe}),e[82]=u,e[83]=Fe,e[84]=Me):Me=e[84];let Be;e[85]!==a?(Be=a("settings.common.actions.delete"),e[85]=a,e[86]=Be):Be=e[86];let Ge;e[87]!==T||e[88]!==u||e[89]!==Be?(Ge=s.jsx(ee,{size:"sm",onClick:T,disabled:u,children:Be}),e[87]=T,e[88]=u,e[89]=Be,e[90]=Ge):Ge=e[90];let Ve;e[91]!==Me||e[92]!==Ge?(Ve=s.jsxs(rs,{children:[Me,Ge]}),e[91]=Me,e[92]=Ge,e[93]=Ve):Ve=e[93];let Ue;e[94]!==Le||e[95]!==Ve?(Ue=s.jsxs(Bt,{className:"max-w-md",children:[Le,Ve]}),e[94]=Le,e[95]=Ve,e[96]=Ue):Ue=e[96];let He;e[97]!==ce||e[98]!==ge||e[99]!==Ue?(He=s.jsx(Kt,{open:ce,onOpenChange:ge,children:Ue}),e[97]=ce,e[98]=ge,e[99]=Ue,e[100]=He):He=e[100];const _e=i!==null;let Oe;e[101]===Symbol.for("react.memo_cache_sentinel")?(Oe=Ce=>!Ce&&r(null),e[101]=Oe):Oe=e[101];let se;e[102]!==a?(se=a("settings.skills.sidebar.renameDialog.title"),e[102]=a,e[103]=se):se=e[103];let ye;e[104]!==se?(ye=s.jsx(_t,{children:se}),e[104]=se,e[105]=ye):ye=e[105];const ke=i?.name??"";let ze;e[106]!==a||e[107]!==ke?(ze=a("settings.skills.sidebar.renameDialog.description",{name:ke}),e[106]=a,e[107]=ke,e[108]=ze):ze=e[108];let $;e[109]!==ze?($=s.jsx(Yt,{children:ze}),e[109]=ze,e[110]=$):$=e[110];let Ee;e[111]!==ye||e[112]!==$?(Ee=s.jsxs(Ut,{children:[ye,$]}),e[111]=ye,e[112]=$,e[113]=Ee):Ee=e[113];let J;e[114]===Symbol.for("react.memo_cache_sentinel")?(J=Ce=>d(Ce.target.value),e[114]=J):J=e[114];let v;e[115]!==a?(v=a("settings.skills.sidebar.renameDialog.placeholder"),e[115]=a,e[116]=v):v=e[116];let ue;e[117]!==q?(ue=Ce=>{Ce.key==="Enter"&&q()},e[117]=q,e[118]=ue):ue=e[118];let Ne;e[119]!==o||e[120]!==v||e[121]!==ue?(Ne=s.jsx(nt,{value:o,onChange:J,placeholder:v,className:"text-foreground placeholder:text-muted-foreground",onKeyDown:ue}),e[119]=o,e[120]=v,e[121]=ue,e[122]=Ne):Ne=e[122];let we;e[123]===Symbol.for("react.memo_cache_sentinel")?(we=()=>r(null),e[123]=we):we=e[123];let qe;e[124]!==a?(qe=a("settings.common.actions.cancel"),e[124]=a,e[125]=qe):qe=e[125];let it;e[126]!==qe?(it=s.jsx(ee,{size:"sm",className:"text-foreground hover:bg-interactive-hover hover:text-foreground",variant:"ghost",onClick:we,children:qe}),e[126]=qe,e[127]=it):it=e[127];let st;e[128]!==a?(st=a("settings.common.actions.rename"),e[128]=a,e[129]=st):st=e[129];let rt;e[130]!==q||e[131]!==st?(rt=s.jsx(ee,{size:"sm",onClick:q,children:st}),e[130]=q,e[131]=st,e[132]=rt):rt=e[132];let lt;e[133]!==it||e[134]!==rt?(lt=s.jsxs(rs,{children:[it,rt]}),e[133]=it,e[134]=rt,e[135]=lt):lt=e[135];let xt;e[136]!==Ee||e[137]!==Ne||e[138]!==lt?(xt=s.jsxs(Bt,{children:[Ee,Ne,lt]}),e[136]=Ee,e[137]=Ne,e[138]=lt,e[139]=xt):xt=e[139];let bt;e[140]!==_e||e[141]!==xt?(bt=s.jsx(Kt,{open:_e,onOpenChange:Oe,children:xt}),e[140]=_e,e[141]=xt,e[142]=bt):bt=e[142];let Nt;return e[143]!==Ie||e[144]!==re||e[145]!==He||e[146]!==bt?(Nt=s.jsxs("div",{className:V,children:[Ie,re,He,bt]}),e[143]=Ie,e[144]=re,e[145]=He,e[146]=bt,e[147]=Nt):Nt=e[147],Nt},$i=t=>{const e=Ze.c(52),{skill:n,isSelected:a,onSelect:i,onDelete:r,onRename:o,onDuplicate:d,isMenuOpen:c,onMenuOpenChange:p}=t,{t:u}=ot();let g;e[0]===Symbol.for("react.memo_cache_sentinel")?(g=bi(),e[0]=g):g=e[0];const m=g;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 h=w;let f;e[4]!==n?(f=hi(n),e[4]=n,e[5]=f):f=e[5];const x=f;let k;e[6]!==n?(k=Xo(n),e[6]=n,e[7]=k):k=e[7];const y=k,[C,O]=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:E=>{E.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:E=>{E.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:E=>{E.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,b=!x&&C,I=a?"bg-interactive-selection":"hover:bg-interactive-hover";let B;e[14]!==I?(B=fe("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",I),e[14]=I,e[15]=B):B=e[15];let T;e[16]!==x?(T=!m&&!x?te=>{te.preventDefault(),O(!0)}:void 0,e[16]=x,e[17]=T):T=e[17];let D;e[18]!==B||e[19]!==T?(D=s.jsx("div",{className:B,onContextMenu:T}),e[18]=B,e[19]=T,e[20]=D):D=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 R;e[25]!==h?(R=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:h}),e[25]=h,e[26]=R):R=e[26];let z;e[27]!==S||e[28]!==F||e[29]!==R?(z=s.jsxs("div",{className:"flex items-center gap-1.5",children:[S,F,R]}),e[27]=S,e[28]=F,e[29]=R,e[30]=z):z=e[30];let q;e[31]!==i||e[32]!==z?(q=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:z}),e[31]=i,e[32]=z,e[33]=q):q=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&&O(!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]!==q||e[40]!==H?(Z=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[q,H]}),e[39]=q,e[40]=H,e[41]=Z):Z=e[41];let W;e[42]!==D||e[43]!==Z?(W=s.jsx(qn,{render:D,children:Z}),e[42]=D,e[43]=Z,e[44]=W):W=e[44];let A;e[45]!==x||e[46]!==N?(A=x?null:s.jsx(Jn,{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]!==W||e[49]!==A||e[50]!==b?(X=s.jsxs(Gn,{open:b,onOpenChange:O,children:[W,A]}),e[48]=W,e[49]=A,e[50]=b,e[51]=X):X=e[51],X};function Vy(t){return{selectedSkillName:t.selectedSkillName,skills:t.skills,setSelectedSkill:t.setSelectedSkill,setSkillDraft:t.setSkillDraft,deleteSkill:t.deleteSkill,renameSkill:t.renameSkill,getSkillDetail:t.getSkillDetail}}function Hy(t){return t.scope==="project"}function Wy(t){return t.scope==="user"}function Gy(t,e){return t.localeCompare(e)}function qy(t,e){return t.name.localeCompare(e.name)}function Jy(t,e){return t.name.localeCompare(e.name)}const Vs=fn()(Ja(vi((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 bp();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 xp();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 hp();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=an()?.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 Js("saving"),await fp(a),Js("saved"),await e().loadProfiles(),!0}catch(a){return Js("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 Js("saving"),await gp(n,r),Js("saved"),await e().loadProfiles(),!0}catch(i){return Js("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return Js("saving"),await pp(n),Js("saved"),e().selectedProfileId===n&&t({selectedProfileId:null}),await e().loadProfiles(),!0}catch(a){return Js("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:Pr(),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Vs);const Yy=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,Qy=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},Xy=async()=>{try{const t=an()?.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}},Zy=t=>{const e=Ze.c(162),{open:n,onOpenChange:a}=t,{t:i}=ot(),r=Sn(ev),o=Sn(tv),d=Sn(sv),c=Sn(nv),p=Sn(av),u=Vs(iv),g=Vs(rv),[m,w]=l.useState(""),[h,f]=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,O]=l.useState(y),[j,N]=l.useState(null),[b,I]=l.useState(!1);let B;e[1]===Symbol.for("react.memo_cache_sentinel")?(B=[],e[1]=B):B=e[1];const[T,D]=l.useState(B),[S,F]=l.useState(null),R=l.useRef(0);let z;e[2]===Symbol.for("react.memo_cache_sentinel")?(z=Qe=>{R.current=R.current+1,I(!1),N(null),Qe?.clearIdentity&&(D([]),F(null))},e[2]=z):z=e[2];const q=z;let H,Z;e[3]!==g||e[4]!==n?(H=()=>{n&&(R.current=R.current+1,w(""),f(""),k(""),N(null),I(!1),D([]),F(null),g(),(async()=>{const Qe=await Xy(),tt=Array.isArray(Qe?.skillCatalogs)?Qe?.skillCatalogs:[];O(tt||[])})())},Z=[n,g],e[3]=g,e[4]=n,e[5]=H,e[6]=Z):(H=e[5],Z=e[6]),l.useEffect(H,Z);let W;e[7]!==h?(W=h.trim(),e[7]=h,e[8]=W):W=e[8];const A=W;let X;e[9]!==x?(X=x.trim(),e[9]=x,e[10]=X):X=e[10];const te=X;let E;if(e[11]!==C||e[12]!==A||e[13]!==te){let Qe;e[15]!==A||e[16]!==te?(Qe=tt=>{const at=(tt.source||"").trim(),gt=(tt.subpath||"").trim();return at===A&>===te},e[15]=A,e[16]=te,e[17]=Qe):Qe=e[17],E=C.some(Qe),e[11]=C,e[12]=A,e[13]=te,e[14]=E}else E=e[14];const P=E;let _;e[18]!==u||e[19]!==S||e[20]!==m||e[21]!==r||e[22]!==h||e[23]!==x||e[24]!==i?(_=async()=>{const Qe=h.trim();if(!Qe){Q.error(i("settings.skills.catalog.add.toast.repositoryRequired"));return}m.trim()||w(Qy(Qe)),I(!1),N(null);const tt=R.current+1;R.current=tt;const at=await r({source:Qe,subpath:x.trim()||void 0,gitIdentityId:S||void 0});if(R.current!==tt)return;if(!at.ok){if(at.error?.kind==="authRequired"){if(ds()){Q.error(i("settings.skills.catalog.shared.toast.privateRepoNotSupportedVsCode"));return}const wt=at.error.identities||[];if(D(wt),!S&&wt.length>0){const Te=u&&u!=="global"&&wt.some(ne=>ne.id===u)?u:wt[0].id;F(Te)}Q.error(i("settings.skills.catalog.add.toast.authenticationRequiredScan"));return}Q.error(at.error?.message||i("settings.skills.catalog.add.toast.scanFailed"));return}const gt=at.items?.length||0;if(N(gt),gt===0){Q.error(i("settings.skills.catalog.add.toast.noSkillsFound")),I(!1);return}D([]),I(!0),Q.success(i("settings.skills.catalog.shared.toast.foundSkills",{count:gt}))},e[18]=u,e[19]=S,e[20]=m,e[21]=r,e[22]=h,e[23]=x,e[24]=i,e[25]=_):_=e[25];const L=_;let V;e[26]!==C||e[27]!==S||e[28]!==P||e[29]!==m||e[30]!==o||e[31]!==d||e[32]!==a||e[33]!==b||e[34]!==c||e[35]!==h||e[36]!==x||e[37]!==i?(V=async()=>{const Qe=m.trim(),tt=h.trim(),at=x.trim();if(!Qe){Q.error(i("settings.skills.catalog.add.toast.catalogNameRequired"));return}if(!tt){Q.error(i("settings.skills.catalog.add.toast.repositoryRequired"));return}if(!b){Q.error(i("settings.skills.catalog.add.toast.scanBeforeAdd"));return}if(P){Q.error(i("settings.skills.catalog.add.toast.catalogAlreadyExists"));return}const gt={id:Yy(),label:Qe,source:tt,...at?{subpath:at}:{},...S?{gitIdentityId:S}:{}},wt=[...C,gt];try{await It({skillCatalogs:wt}),O(wt),Q.success(i("settings.skills.catalog.add.toast.catalogAdded")),await o({refresh:!0}),await d(gt.id,{refresh:!0}),c(gt.id),a(!1)}catch(Te){const ne=Te;Q.error(ne instanceof Error?ne.message:i("settings.skills.catalog.add.toast.saveFailed"))}},e[26]=C,e[27]=S,e[28]=P,e[29]=m,e[30]=o,e[31]=d,e[32]=a,e[33]=b,e[34]=c,e[35]=h,e[36]=x,e[37]=i,e[38]=V):V=e[38];const Y=V;let G;e[39]!==i?(G=i("settings.skills.catalog.add.title"),e[39]=i,e[40]=G):G=e[40];let me;e[41]!==G?(me=s.jsx(_t,{children:G}),e[41]=G,e[42]=me):me=e[42];let ae;e[43]!==i?(ae=i("settings.skills.catalog.add.descriptionPrefix"),e[43]=i,e[44]=ae):ae=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 be;e[46]!==i?(be=i("settings.skills.catalog.add.descriptionSuffix"),e[46]=i,e[47]=be):be=e[47];let ie;e[48]!==ae||e[49]!==be?(ie=s.jsxs(Yt,{children:[ae," ",xe,be]}),e[48]=ae,e[49]=be,e[50]=ie):ie=e[50];let pe;e[51]!==me||e[52]!==ie?(pe=s.jsxs(Ut,{children:[me,ie]}),e[51]=me,e[52]=ie,e[53]=pe):pe=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 re;e[56]!==Ie?(re=s.jsx("label",{className:"typography-ui-label text-foreground",children:Ie}),e[56]=Ie,e[57]=re):re=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 ge;e[59]!==i?(ge=i("settings.skills.catalog.add.field.catalogNamePlaceholder"),e[59]=i,e[60]=ge):ge=e[60];let oe;e[61]!==m||e[62]!==ge?(oe=s.jsx(nt,{value:m,onChange:ce,placeholder:ge}),e[61]=m,e[62]=ge,e[63]=oe):oe=e[63];let de;e[64]!==re||e[65]!==oe?(de=s.jsxs("div",{className:"space-y-2",children:[re,oe]}),e[64]=re,e[65]=oe,e[66]=de):de=e[66];let le;e[67]!==i?(le=i("settings.skills.catalog.add.field.repository"),e[67]=i,e[68]=le):le=e[68];let he;e[69]!==le?(he=s.jsx("label",{className:"typography-ui-label text-foreground",children:le}),e[69]=le,e[70]=he):he=e[70];let De;e[71]!==i?(De=i("settings.skills.catalog.add.field.repositoryHint"),e[71]=i,e[72]=De):De=e[72];let Le;e[73]!==De?(Le=s.jsx($t,{children:De}),e[73]=De,e[74]=Le):Le=e[74];let Ke;e[75]!==he||e[76]!==Le?(Ke=s.jsxs("div",{className:"flex items-center gap-1",children:[he,Le]}),e[75]=he,e[76]=Le,e[77]=Ke):Ke=e[77];let Fe;e[78]===Symbol.for("react.memo_cache_sentinel")?(Fe=Qe=>{f(Qe.target.value),q({clearIdentity:!0})},e[78]=Fe):Fe=e[78];let Me;e[79]!==i?(Me=i("settings.skills.catalog.shared.field.repositoryPlaceholder"),e[79]=i,e[80]=Me):Me=e[80];let Be;e[81]!==h||e[82]!==Me?(Be=s.jsx(nt,{value:h,onChange:Fe,placeholder:Me}),e[81]=h,e[82]=Me,e[83]=Be):Be=e[83];let Ge;e[84]!==Ke||e[85]!==Be?(Ge=s.jsxs("div",{className:"space-y-2",children:[Ke,Be]}),e[84]=Ke,e[85]=Be,e[86]=Ge):Ge=e[86];let Ve;e[87]!==i?(Ve=i("settings.skills.catalog.add.field.optionalSubpath"),e[87]=i,e[88]=Ve):Ve=e[88];let Ue;e[89]!==Ve?(Ue=s.jsx("label",{className:"typography-ui-label text-foreground",children:Ve}),e[89]=Ve,e[90]=Ue):Ue=e[90];let He;e[91]===Symbol.for("react.memo_cache_sentinel")?(He=Qe=>{k(Qe.target.value),q({clearIdentity:!0})},e[91]=He):He=e[91];let _e;e[92]!==i?(_e=i("settings.skills.catalog.shared.field.subpathPlaceholder"),e[92]=i,e[93]=_e):_e=e[93];let Oe;e[94]!==x||e[95]!==_e?(Oe=s.jsx(nt,{value:x,onChange:He,placeholder:_e}),e[94]=x,e[95]=_e,e[96]=Oe):Oe=e[96];let se;e[97]!==Ue||e[98]!==Oe?(se=s.jsxs("div",{className:"space-y-2",children:[Ue,Oe]}),e[97]=Ue,e[98]=Oe,e[99]=se):se=e[99];let ye;e[100]!==S||e[101]!==T||e[102]!==i?(ye=T.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(Mt,{value:S||"",onValueChange:Qe=>{F(Qe),q()},children:[s.jsx(Lt,{className:"w-fit",children:s.jsx("span",{children:T.find(Qe=>Qe.id===S)?.name||i("settings.skills.catalog.shared.auth.chooseIdentity")})}),s.jsx(Ft,{align:"start",children:T.map(ov)})]})]}):null,e[100]=S,e[101]=T,e[102]=i,e[103]=ye):ye=e[103];let ke;e[104]!==j||e[105]!==i?(ke=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]=ke):ke=e[106];let ze;e[107]!==P||e[108]!==i?(ze=P?s.jsx("div",{className:"typography-meta text-muted-foreground",children:i("settings.skills.catalog.add.duplicateMessage")}):null,e[107]=P,e[108]=i,e[109]=ze):ze=e[109];let $;e[110]!==de||e[111]!==Ge||e[112]!==se||e[113]!==ye||e[114]!==ke||e[115]!==ze?($=s.jsxs("div",{className:"space-y-4",children:[de,Ge,se,ye,ke,ze]}),e[110]=de,e[111]=Ge,e[112]=se,e[113]=ye,e[114]=ke,e[115]=ze,e[116]=$):$=e[116];let Ee;e[117]!==a?(Ee=()=>a(!1),e[117]=a,e[118]=Ee):Ee=e[118];let J;e[119]!==i?(J=i("settings.common.actions.cancel"),e[119]=i,e[120]=J):J=e[120];let v;e[121]!==Ee||e[122]!==J?(v=s.jsx(ee,{size:"sm",variant:"ghost",onClick:Ee,children:J}),e[121]=Ee,e[122]=J,e[123]=v):v=e[123];let ue;e[124]!==L?(ue=()=>{L()},e[124]=L,e[125]=ue):ue=e[125];let Ne;e[126]!==p||e[127]!==h?(Ne=p||!h.trim(),e[126]=p,e[127]=h,e[128]=Ne):Ne=e[128];let we;e[129]===Symbol.for("react.memo_cache_sentinel")?(we=s.jsx(K,{name:"git-repository",className:"h-4 w-4"}),e[129]=we):we=e[129];let qe;e[130]!==p||e[131]!==i?(qe=i(p?"settings.skills.catalog.shared.actions.scanning":"settings.skills.catalog.shared.actions.scan"),e[130]=p,e[131]=i,e[132]=qe):qe=e[132];let it;e[133]!==ue||e[134]!==Ne||e[135]!==qe?(it=s.jsxs(ee,{size:"sm",className:"gap-2",variant:"ghost",onClick:ue,disabled:Ne,children:[we,qe]}),e[133]=ue,e[134]=Ne,e[135]=qe,e[136]=it):it=e[136];let st;e[137]!==Y?(st=()=>{Y()},e[137]=Y,e[138]=st):st=e[138];let rt;e[139]!==P||e[140]!==m||e[141]!==b||e[142]!==h?(rt=!b||P||!m.trim()||!h.trim(),e[139]=P,e[140]=m,e[141]=b,e[142]=h,e[143]=rt):rt=e[143];let lt;e[144]!==i?(lt=i("settings.skills.catalog.add.actions.addCatalog"),e[144]=i,e[145]=lt):lt=e[145];let xt;e[146]!==st||e[147]!==rt||e[148]!==lt?(xt=s.jsx(ee,{size:"sm",onClick:st,disabled:rt,children:lt}),e[146]=st,e[147]=rt,e[148]=lt,e[149]=xt):xt=e[149];let bt;e[150]!==v||e[151]!==it||e[152]!==xt?(bt=s.jsxs(rs,{children:[v,it,xt]}),e[150]=v,e[151]=it,e[152]=xt,e[153]=bt):bt=e[153];let Nt;e[154]!==pe||e[155]!==$||e[156]!==bt?(Nt=s.jsxs(Bt,{className:"max-w-xl",children:[pe,$,bt]}),e[154]=pe,e[155]=$,e[156]=bt,e[157]=Nt):Nt=e[157];let Ce;return e[158]!==a||e[159]!==n||e[160]!==Nt?(Ce=s.jsx(Kt,{open:n,onOpenChange:a,children:Nt}),e[158]=a,e[159]=n,e[160]=Nt,e[161]=Ce):Ce=e[161],Ce};function ev(t){return t.scanRepo}function tv(t){return t.loadCatalog}function sv(t){return t.loadSource}function nv(t){return t.setSelectedSource}function av(t){return t.isScanning}function iv(t){return t.defaultGitIdentityId}function rv(t){return t.loadDefaultGitIdentityId}function ov(t){return s.jsx(jt,{value:t.id,children:t.name},t.id)}const lv=t=>{const e=Ze.c(85),{open:n,onOpenChange:a,conflicts:i,onConfirm:r}=t,{t:o}=ot();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,g;e[1]!==i||e[2]!==n?(u=()=>{if(!n)return;const Y={};for(const G of i)Y[G.skillName]="skip";p(Y)},g=[n,i],e[1]=i,e[2]=n,e[3]=u,e[4]=g):(u=e[3],g=e[4]),l.useEffect(u,g);let m;e[5]!==i?(m=Y=>{const G={};for(const me of i)G[me.skillName]=Y;p(G)},e[5]=i,e[6]=m):m=e[6];const w=m;let h;e[7]!==i||e[8]!==c?(h=i.length>0&&i.every(Y=>c[Y.skillName]),e[7]=i,e[8]=c,e[9]=h):h=e[9];const f=h;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 O;e[18]!==k||e[19]!==C?(O=s.jsxs(Ut,{children:[k,C]}),e[18]=k,e[19]=C,e[20]=O):O=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 b;e[26]!==w?(b=()=>w("skip"),e[26]=w,e[27]=b):b=e[27];let I;e[28]!==o?(I=o("settings.skills.catalog.conflicts.actions.skipAll"),e[28]=o,e[29]=I):I=e[29];let B;e[30]!==b||e[31]!==I?(B=s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:b,children:I}),e[30]=b,e[31]=I,e[32]=B):B=e[32];let T;e[33]!==w?(T=()=>w("overwrite"),e[33]=w,e[34]=T):T=e[34];let D;e[35]!==o?(D=o("settings.skills.catalog.conflicts.actions.overwriteAll"),e[35]=o,e[36]=D):D=e[36];let S;e[37]!==T||e[38]!==D?(S=s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:T,children:D}),e[37]=T,e[38]=D,e[39]=S):S=e[39];let F;e[40]!==B||e[41]!==S?(F=s.jsxs("div",{className:"flex items-center gap-2",children:[B,S]}),e[40]=B,e[41]=S,e[42]=F):F=e[42];let R;e[43]!==N||e[44]!==F?(R=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[N,F]}),e[43]=N,e[44]=F,e[45]=R):R=e[45];let z;if(e[46]!==i||e[47]!==c||e[48]!==o){let Y;e[50]!==c||e[51]!==o?(Y=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(Mt,{value:c[G.skillName]||"skip",onValueChange:me=>p(ae=>({...ae,[G.skillName]:me})),children:[s.jsx(Lt,{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(Ft,{align:"end",children:[s.jsx(jt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:o("settings.skills.catalog.conflicts.decision.skip")}),s.jsx(jt,{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]=Y):Y=e[52],z=i.map(Y),e[46]=i,e[47]=c,e[48]=o,e[49]=z}else z=e[49];let q;e[53]!==z?(q=s.jsx("div",{className:"space-y-2",children:z}),e[53]=z,e[54]=q):q=e[54];let H;e[55]!==R||e[56]!==q?(H=s.jsxs("div",{className:"space-y-3",children:[R,q]}),e[55]=R,e[56]=q,e[57]=H):H=e[57];let Z;e[58]!==a?(Z=()=>a(!1),e[58]=a,e[59]=Z):Z=e[59];let W;e[60]!==o?(W=o("settings.common.actions.cancel"),e[60]=o,e[61]=W):W=e[61];let A;e[62]!==Z||e[63]!==W?(A=s.jsx(ee,{size:"sm",variant:"ghost",onClick:Z,children:W}),e[62]=Z,e[63]=W,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=!f;let E;e[68]!==o?(E=o("settings.skills.catalog.conflicts.actions.continue"),e[68]=o,e[69]=E):E=e[69];let P;e[70]!==X||e[71]!==te||e[72]!==E?(P=s.jsx(ee,{size:"sm",onClick:X,disabled:te,children:E}),e[70]=X,e[71]=te,e[72]=E,e[73]=P):P=e[73];let _;e[74]!==A||e[75]!==P?(_=s.jsxs(rs,{children:[A,P]}),e[74]=A,e[75]=P,e[76]=_):_=e[76];let L;e[77]!==O||e[78]!==H||e[79]!==_?(L=s.jsxs(Bt,{className:"max-w-2xl",children:[O,H,_]}),e[77]=O,e[78]=H,e[79]=_,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},fl=[{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 xi(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 Yu(t){if(t==="user-claude")return{scope:"user",source:"claude"};if(t==="project-claude")return{scope:"project",source:"claude"};const e=fl.find(n=>n.value===t);return e?{scope:e.scope,source:e.source}:{scope:"user",source:"opencode"}}const cv=t=>{const e=Ze.c(124),{open:n,onOpenChange:a,item:i}=t,{t:r}=ot(),o=Sn(dv),d=Sn(uv),[c,p]=l.useState("user"),[u,g]=l.useState("opencode"),m=is(mv),w=is(pv),[h,f]=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,O]=l.useState(y),[j,N]=l.useState(null);let b,I;e[1]!==w||e[2]!==n?(b=()=>{n&&(p("user"),g("opencode"),f(w),k(!1),O([]),N(null))},I=[n,w],e[1]=w,e[2]=n,e[3]=b,e[4]=I):(b=e[3],I=e[4]),l.useEffect(b,I);let B;e[5]!==r?(B=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]=B):B=e[6];const T=B;let D;e[7]!==r?(D=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]=D):D=e[8];const S=D;let F;e:{if(m.length===0){F=null;break e}if(h&&m.some(Oe=>Oe.id===h)){F=h;break e}if(w&&m.some(Oe=>Oe.id===w)){F=w;break e}F=m[0]?.id??null}const R=F;let z;e:{if(c!=="project"){z=null;break e}const Oe=R;if(!Oe){z=null;break e}let se;if(e[9]!==Oe||e[10]!==m){let ke;e[12]!==Oe?(ke=ze=>ze.id===Oe,e[12]=Oe,e[13]=ke):ke=e[13],se=m.find(ke),e[9]=Oe,e[10]=m,e[11]=se}else se=e[11];z=se?.path??null}const q=z;let H;e[14]!==o||e[15]!==i||e[16]!==a||e[17]!==r?(H=async Oe=>{const se={skillDir:Oe.skillDir};i?.clawdhub&&(se.clawdhub={slug:i.clawdhub.slug,version:i.clawdhub.version});const ye=await o({source:Oe.source,subpath:Oe.subpath,gitIdentityId:i?.gitIdentityId,scope:Oe.scope,targetSource:Oe.targetSource,selections:[se],conflictPolicy:"prompt",conflictDecisions:Oe.conflictDecisions},{directory:Oe.directoryOverride??null});if(ye.ok){Q.success(r("settings.skills.catalog.installSkill.toast.installed")),a(!1);return}if(ye.error?.kind==="conflicts"){N({source:Oe.source,subpath:Oe.subpath,scope:Oe.scope,targetSource:Oe.targetSource,skillDir:Oe.skillDir,directoryOverride:Oe.directoryOverride??null}),O(ye.error.conflicts),k(!0);return}if(ye.error?.kind==="authRequired"){Q.error(ye.error.message||r("settings.skills.catalog.installSkill.toast.authRequired"));return}Q.error(ye.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 W;e[19]!==r?(W=r("settings.skills.catalog.installSkill.title"),e[19]=r,e[20]=W):W=e[20];let A;e[21]!==W?(A=s.jsx(_t,{children:W}),e[21]=W,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 E;e[27]!==r?(E=r("settings.skills.catalog.installSkill.descriptionSuffix"),e[27]=r,e[28]=E):E=e[28];let P;e[29]!==X||e[30]!==te||e[31]!==E?(P=s.jsxs(Yt,{children:[X," ",te," ",E]}),e[29]=X,e[30]=te,e[31]=E,e[32]=P):P=e[32];let _;e[33]!==A||e[34]!==P?(_=s.jsxs(Ut,{children:[A,P]}),e[33]=A,e[34]=P,e[35]=_):_=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 Y;e[40]!==c||e[41]!==u?(Y=xi(c,u),e[40]=c,e[41]=u,e[42]=Y):Y=e[42];let G;e[43]===Symbol.for("react.memo_cache_sentinel")?(G=Oe=>{const se=Yu(Oe);p(se.scope),g(se.source==="agents"?"agents":"opencode")},e[43]=G):G=e[43];let me;e[44]!==c?(me=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]=me):me=e[45];let ae;e[46]!==u?(ae=u==="agents"?s.jsx(K,{name:"robot-2",className:"h-3.5 w-3.5"}):null,e[46]=u,e[47]=ae):ae=e[47];let xe;e[48]!==T||e[49]!==c||e[50]!==u?(xe=T(xi(c,u)),e[48]=T,e[49]=c,e[50]=u,e[51]=xe):xe=e[51];let be;e[52]!==xe?(be=s.jsx("span",{children:xe}),e[52]=xe,e[53]=be):be=e[53];let ie;e[54]!==me||e[55]!==ae||e[56]!==be?(ie=s.jsxs(Lt,{className:"w-fit gap-1.5",children:[me,ae,be]}),e[54]=me,e[55]=ae,e[56]=be,e[57]=ie):ie=e[57];let pe;e[58]!==S||e[59]!==T?(pe=fl.map(Oe=>s.jsx(jt,{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:T(Oe.value)})]}),s.jsx("span",{className:"typography-micro text-muted-foreground ml-5",children:S(Oe.value)})]})},Oe.value)),e[58]=S,e[59]=T,e[60]=pe):pe=e[60];let Ie;e[61]!==pe?(Ie=s.jsx(Ft,{align:"start",children:pe}),e[61]=pe,e[62]=Ie):Ie=e[62];let re;e[63]!==Y||e[64]!==ie||e[65]!==Ie?(re=s.jsxs(Mt,{value:Y,onValueChange:G,children:[ie,Ie]}),e[63]=Y,e[64]=ie,e[65]=Ie,e[66]=re):re=e[66];let ce;e[67]!==V||e[68]!==re?(ce=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[V,re]}),e[67]=V,e[68]=re,e[69]=ce):ce=e[69];let ge;e[70]!==m||e[71]!==R||e[72]!==c||e[73]!==r?(ge=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(Mt,{value:R??"",onValueChange:Oe=>f(Oe),disabled:m.length===1,children:[s.jsx(Lt,{className:"w-fit",children:s.jsx(Wt,{placeholder:r("settings.skills.catalog.installSkill.field.chooseProjectPlaceholder")})}),s.jsx(Ft,{align:"start",children:m.map(gv)})]})]}),e[70]=m,e[71]=R,e[72]=c,e[73]=r,e[74]=ge):ge=e[74];let oe;e[75]!==i.warnings?(oe=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]=oe):oe=e[76];let de;e[77]!==ce||e[78]!==ge||e[79]!==oe?(de=s.jsxs("div",{className:"mt-2 space-y-3",children:[ce,ge,oe]}),e[77]=ce,e[78]=ge,e[79]=oe,e[80]=de):de=e[80];let le;e[81]!==a?(le=()=>a(!1),e[81]=a,e[82]=le):le=e[82];let he;e[83]!==r?(he=r("settings.common.actions.cancel"),e[83]=r,e[84]=he):he=e[84];let De;e[85]!==le||e[86]!==he?(De=s.jsx(ee,{size:"sm",variant:"ghost",onClick:le,children:he}),e[85]=le,e[86]=he,e[87]=De):De=e[87];const Le=d||!i.installable||c==="project"&&!q;let Ke;e[88]!==q||e[89]!==Z||e[90]!==i.repoSource||e[91]!==i.repoSubpath||e[92]!==i.skillDir||e[93]!==c||e[94]!==u?(Ke=()=>{Z({source:i.repoSource,subpath:i.repoSubpath,scope:c,targetSource:u,skillDir:i.skillDir,directoryOverride:q})},e[88]=q,e[89]=Z,e[90]=i.repoSource,e[91]=i.repoSubpath,e[92]=i.skillDir,e[93]=c,e[94]=u,e[95]=Ke):Ke=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 Me;e[99]!==Le||e[100]!==Ke||e[101]!==Fe?(Me=s.jsx(ee,{size:"sm",disabled:Le,onClick:Ke,children:Fe}),e[99]=Le,e[100]=Ke,e[101]=Fe,e[102]=Me):Me=e[102];let Be;e[103]!==De||e[104]!==Me?(Be=s.jsxs(rs,{children:[De,Me]}),e[103]=De,e[104]=Me,e[105]=Be):Be=e[105];let Ge;e[106]!==_||e[107]!==de||e[108]!==Be?(Ge=s.jsxs(Bt,{className:"max-w-md",children:[_,de,Be]}),e[106]=_,e[107]=de,e[108]=Be,e[109]=Ge):Ge=e[109];let Ve;e[110]!==a||e[111]!==n||e[112]!==Ge?(Ve=s.jsx(Kt,{open:n,onOpenChange:a,children:Ge}),e[110]=a,e[111]=n,e[112]=Ge,e[113]=Ve):Ve=e[113];let Ue;e[114]!==j||e[115]!==Z?(Ue=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]=Ue):Ue=e[116];let He;e[117]!==C||e[118]!==x||e[119]!==Ue?(He=s.jsx(lv,{open:x,onOpenChange:k,conflicts:C,onConfirm:Ue}),e[117]=C,e[118]=x,e[119]=Ue,e[120]=He):He=e[120];let _e;return e[121]!==Ve||e[122]!==He?(_e=s.jsxs(s.Fragment,{children:[Ve,He]}),e[121]=Ve,e[122]=He,e[123]=_e):_e=e[123],_e};function dv(t){return t.installSkills}function uv(t){return t.isInstalling}function mv(t){return t.projects}function pv(t){return t.activeProjectId}function gv(t){return s.jsx(jt,{value:t.id,children:t.label||t.path},t.id)}const fv=async()=>{try{const t=an()?.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}},hv=({mode:t,onModeChange:e,showModeTabs:n=!0})=>{const{t:a}=ot(),{sources:i,itemsBySource:r,selectedSourceId:o,setSelectedSource:d,loadCatalog:c,loadSource:p,loadMoreClawdHub:u,isLoadingCatalog:g,isLoadingSource:m,isLoadingMore:w,loadedSourceIds:h,clawdhubHasMoreBySource:f,lastCatalogError:x}=Sn(Ws(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,O]=l.useState(!1),[j,N]=l.useState(!1),[b,I]=l.useState(null),[B,T]=l.useState(!1),[D,S]=l.useState(!1);l.useEffect(()=>{c()},[c]),l.useEffect(()=>{o&&(h[o]||p(o))},[o,h,p]);const F=l.useMemo(()=>o?r[o]||[]:[],[r,o]),R=l.useMemo(()=>{const A=k.trim().toLowerCase();return A?F.filter(X=>{const te=X.skillName.toLowerCase(),E=(X.description||"").toLowerCase(),P=(X.frontmatterName||"").toLowerCase();return te.includes(A)||E.includes(A)||P.includes(A)}):F},[F,k]),z=l.useMemo(()=>i.find(A=>A.id===o)||null,[i,o]),q=!!(o&&o.startsWith("custom:")),H=z?.source==="clawdhub:registry"||z?.sourceType==="clawdhub",Z=!!(o&&(f[o]??!0)),W=async()=>{if(!(!o||!q)){T(!0);try{const A=await fv(),te=(Array.isArray(A?.skillCatalogs)?A?.skillCatalogs:[]).filter(E=>E.id!==o);await It({skillCatalogs:te}),await c({refresh:!0}),S(!1)}finally{T(!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(pa,{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(Mt,{value:o||"",onValueChange:A=>d(A),children:[s.jsx(Lt,{size:Gt,className:fe(jn,"w-fit"),children:s.jsx(Wt,{placeholder:a("settings.skills.catalog.page.field.selectSourcePlaceholder"),children:z?.label})}),s.jsx(Ft,{align:"start",children:i.map(A=>s.jsx(jt,{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:g||m,title:a("settings.skills.catalog.page.actions.refreshTitle"),children:s.jsx(K,{name:"refresh",className:fe("h-3.5 w-3.5",(g||m)&&"animate-spin")})}),q&&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:B,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:()=>O(!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(nt,{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:g?a("settings.skills.catalog.page.loading.catalog"):a("settings.skills.catalog.page.foundCount",{count:R.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:[R.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:R.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:()=>{I(A),N(!0)},children:a("settings.skills.catalog.shared.actions.install")})]})},`${A.sourceId}:${A.skillDir}`)})}),H&&Z&&!m&&R.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(Zy,{open:C,onOpenChange:O}),s.jsx(cv,{open:j,onOpenChange:N,item:b}),s.jsx(Kt,{open:D,onOpenChange:A=>{B||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:B,children:a("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",variant:"destructive",onClick:()=>{W()},disabled:B,children:a("settings.skills.catalog.page.actions.removeCatalog")})]})]})})]})},xv=()=>{const t=Ze.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(hv,{mode:"external",onModeChange:kv,showModeTabs:!1}),t[0]=e):e=t[0],e},bv="SKILL.md",yv="h-[clamp(320px,58dvh,680px)] min-h-[260px] max-h-[calc(100dvh-220px)]",rr=(t,e)=>{const n=wf({description:t}).trimEnd(),a=e.trimStart();return`---
|
|
28
|
+
${n}
|
|
29
|
+
---${a?`
|
|
30
|
+
|
|
31
|
+
${a}`:`
|
|
32
|
+
`}`},vv=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Qu=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=jf(e[1]);if(vv(a)){const i=a.description;typeof i=="string"&&(n=i)}}catch{n=null}return{description:n,instructions:e[2].replace(/^\r?\n/,"")}},wv=(t,e)=>{const n=Qu(t);return rr(e,n.instructions)},jv=()=>{const{t}=ot(),{currentTheme:e}=Wa(),{selectedSkillName:n,getSkillByName:a,getSkillDetail:i,createSkill:r,updateSkill:o,skills:d,skillDraft:c,setSkillDraft:p,setSelectedSkill:u}=In(Ws(se=>({selectedSkillName:se.selectedSkillName,getSkillByName:se.getSkillByName,getSkillDetail:se.getSkillDetail,createSkill:se.createSkill,updateSkill:se.updateSkill,skills:se.skills,skillDraft:se.skillDraft,setSkillDraft:se.setSkillDraft,setSelectedSkill:se.setSelectedSkill}))),g=n?a(n):null,m=!!(c&&c.name===n&&!g),w=!!(n&&!g&&!c),h=g?.path==="<built-in>";l.useEffect(()=>{w&&u(null)},[w,u]);const[f,x]=l.useState(""),[k,y]=l.useState("user"),[C,O]=l.useState("opencode"),[j,N]=l.useState(""),[b,I]=l.useState(""),[B,T]=l.useState(()=>rr("","")),[D,S]=l.useState("edit"),[F,R]=l.useState([]),[z,q]=l.useState([]),[H,Z]=l.useState(!1),[W,A]=l.useState(!1),[X,te]=l.useState(""),[E,P]=l.useState(""),[_,L]=l.useState(!1),[V,Y]=l.useState(""),[G,me]=l.useState(""),[ae,xe]=l.useState(null),[be,ie]=l.useState(!1),[pe,Ie]=l.useState(""),[re,ce]=l.useState(null),[ge,oe]=l.useState(!1),de=m?f.trim()!==""||j.trim()!==""||b.trim()!==""||z.length>0:j!==X||b!==E,le=ae?G!==pe:V.trim()!=="",he=l.useCallback(se=>{switch(se){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]),De=l.useCallback(se=>{switch(se){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 ye=c.description||"",ke=c.instructions||"";x(c.name||""),y(c.scope||"user"),O(c.source==="agents"?"agents":"opencode"),N(ye),I(ke),T(rr(ye,ke)),te(""),P(""),R([]),q(c.pendingFiles||[])}else if(n&&g){A(!0);try{const ye=await i(n);if(ye){const ke=ye.sources.md,ze=ke.description||"",$=ke.instructions||"";N(ze),I($),T(rr(ze,$)),te(ze),P($),R(ke.supportingFiles||[])}}catch(ye){console.error("Failed to load skill details:",ye)}finally{A(!1)}}})()},[g,m,n,d,c,i]);const Le=je(se=>se.editorFontSize),Ke=l.useMemo(()=>{const se=[Ho(e,{fontSize:Le})],ye=Mo(bv);return ye&&se.push(ye),se.push(sn.lineWrapping),se},[e,Le]),Fe=l.useMemo(()=>{const se=V.trim()||"supporting-file.md",ye=Ro(se),ke=!!ye&&ye!=="markdown",ze=[Ho(e,ke?{syntaxColors:!1,fontSize:Le}:{fontSize:Le})],$=Mo(se);return $&&ze.push($),ke&&ye&&ze.push(Bu({language:ye,themeName:e.metadata.id,theme:mr(e)})),ze.push(sn.lineWrapping),ze},[e,V,Le]),Me=l.useCallback(se=>{N(se),T(ye=>wv(ye,se))},[]),Be=l.useCallback(se=>{T(se);const ye=Qu(se);N(ye.description??""),I(ye.instructions)},[]),Ge=async()=>{const se=m?f.trim().replace(/\s+/g,"-").toLowerCase():n?.trim();if(!se){Q.error(t("settings.skills.page.toast.skillNameRequired"));return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(se)||se.length>64){Q.error(t("settings.skills.page.toast.invalidSkillName"));return}if(!j.trim()){Q.error(t("settings.skills.page.toast.descriptionRequired"));return}if(m&&d.some(ye=>ye.name===se)){Q.error(t("settings.skills.page.toast.skillExists"));return}Z(!0);try{const ye={name:se,description:j.trim(),instructions:b.trim()||void 0,scope:m?k:void 0,source:m?C:void 0,targetPath:m?void 0:g?.path,supportingFiles:m&&z.length>0?z:void 0};let ke;m?(ke=await r(ye),ke&&(p(null),q([]),u(se))):(ke=await o(se,ye),ke&&(te(j.trim()),P(b.trim()))),ke?Q.success(t(m?"settings.skills.page.toast.skillCreated":"settings.skills.page.toast.skillUpdated")):Q.error(t(m?"settings.skills.page.toast.createSkillFailed":"settings.skills.page.toast.updateSkillFailed"))}catch(ye){console.error("Error saving skill:",ye),Q.error(t("settings.skills.page.toast.saveUnexpectedError"))}finally{Z(!1)}},Ve=()=>{xe(null),Y(""),me(""),Ie(""),L(!0)},Ue=async se=>{if(xe(se),Y(se),m){const ke=z.find(ze=>ze.path===se)?.content||"";me(ke),Ie(ke),L(!0);return}if(n){ie(!0),L(!0);try{const{readSupportingFile:ye}=In.getState(),ke=await ye(n,se);me(ke||""),Ie(ke||"")}catch{Q.error(t("settings.skills.page.toast.loadFileContentFailed")),me(""),Ie("")}finally{ie(!1)}}},He=async()=>{if(!V.trim()){Q.error(t("settings.skills.page.toast.fileNameRequired"));return}const se=V.trim(),ye=ae!==null;if(m){if(ye)q($=>$.map(Ee=>Ee.path===ae?{path:se,content:G}:Ee)),Q.success(t("settings.skills.page.toast.fileUpdated",{path:se}));else{if(z.some($=>$.path===se)){Q.error(t("settings.skills.page.toast.fileExists"));return}q($=>[...$,{path:se,content:G}]),Q.success(t("settings.skills.page.toast.fileAdded",{path:se}))}L(!1),xe(null);return}if(!n){Q.error(t("settings.skills.page.toast.noSkillSelected"));return}const{writeSupportingFile:ke}=In.getState();if(await ke(n,se,G)){Q.success(ye?t("settings.skills.page.toast.fileUpdated",{path:se}):t("settings.skills.page.toast.fileCreated",{path:se})),L(!1),xe(null);const $=await i(n);$&&R($.sources.md.supportingFiles||[])}else Q.error(t(ye?"settings.skills.page.toast.updateFileFailed":"settings.skills.page.toast.createFileFailed"))},_e=se=>{if(m){q(ye=>ye.filter(ke=>ke.path!==se)),Q.success(t("settings.skills.page.toast.fileRemoved",{path:se}));return}n&&ce(se)},Oe=async()=>{if(!re||!n)return;oe(!0);const{deleteSupportingFile:se}=In.getState();if(await se(n,re)){Q.success(t("settings.skills.page.toast.fileDeleted",{path:re}));const ke=await i(n);ke&&R(ke.sources.md.supportingFiles||[]),ce(null)}else Q.error(t("settings.skills.page.toast.deleteFileFailed"));oe(!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")})]})}):W?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:g?t("settings.skills.page.subtitle.skillLocation",{location:he(xi(g.scope,g.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(nt,{value:f,onChange:se=>x(se.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:t("settings.skills.page.field.skillNamePlaceholder"),className:"h-7 w-40 px-2"}),s.jsxs(Mt,{value:xi(k,C),onValueChange:se=>{const ye=Yu(se);y(ye.scope),O(ye.source==="agents"?"agents":"opencode")},children:[s.jsxs(Lt,{size:Gt,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(xi(k,C))})]}),s.jsx(Ft,{align:"start",children:fl.map(se=>s.jsx(jt,{value:se.value,children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[se.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"}),se.source==="agents"?s.jsx(K,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:he(se.value)})]}),s.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:De(se.value)})]})},se.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:se=>Me(se.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:h})})]}),s.jsx(dt,{title:t("settings.skills.page.section.instructions"),headerAction:s.jsx(Fu,{currentMode:D==="preview"?"preview":"edit",onToggle:()=>S(se=>se==="preview"?"edit":"preview")}),settingsItem:"skills.instructions",children:s.jsx("div",{className:fe("overflow-hidden rounded-md border border-[var(--surface-subtle)] bg-background",yv),children:D==="preview"?s.jsx(zs,{outerClassName:"h-full",className:"h-full",children:s.jsx("div",{className:"min-h-full px-4 py-3",children:s.jsx(ur,{content:B,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})}):s.jsx($o,{value:B,onChange:Be,readOnly:h,extensions:Ke,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:Ve,disabled:h,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 se=m?z:F;return se.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:se.map(ye=>s.jsxs("div",{className:"flex items-center gap-2 py-1.5 cursor-pointer group",onClick:()=>Ue(ye.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:ye.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")}),!h&&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:ke=>{ke.stopPropagation(),_e(ye.path)},children:s.jsx(K,{name:"delete-bin",className:"h-3 w-3"})})]},ye.path))})})()}),s.jsx(dt,{children:s.jsx(ee,{onClick:Ge,disabled:h||H||!de,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:re!==null,onOpenChange:se=>{!se&&!ge&&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:re??""})})]}),s.jsxs(rs,{children:[s.jsx(ee,{size:"sm",variant:"ghost",onClick:()=>ce(null),disabled:ge,children:t("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",variant:"destructive",onClick:Oe,disabled:ge,children:t("settings.common.actions.delete")})]})]})}),s.jsx(Kt,{open:_,onOpenChange:se=>{L(se),se||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(ae?"settings.skills.page.fileDialog.titleEdit":"settings.skills.page.fileDialog.titleAdd")}),s.jsx(Yt,{children:t(ae?"settings.skills.page.fileDialog.descriptionEdit":"settings.skills.page.fileDialog.descriptionAdd")})]}),be?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")}),!ae&&s.jsx($t,{children:t("settings.skills.page.fileDialog.field.filePathHint")})]}),s.jsx(nt,{value:V,onChange:se=>Y(se.target.value),placeholder:t("settings.skills.page.fileDialog.field.filePathPlaceholder"),className:"text-foreground placeholder:text-muted-foreground focus-visible:ring-[var(--primary-base)]",disabled:ae!==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:me,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:be||!le,children:t(ae?"settings.common.actions.saveChanges":"settings.skills.page.actions.createFile")})]})]})})]})},Qc=t=>{const e=Ze.c(2),{view:n}=t,a=n===void 0?"installed":n;let i;return e[0]!==a?(i=a==="catalog"?s.jsx(xv,{}):s.jsx(jv,{}),e[0]=a,e[1]=i):i=e[1],i};function kv(){}const Nv=t=>{const e=Ze.c(38),{onItemSelect:n}=t,{t:a}=ot(),i=is(Sv),r=je(Cv),o=je(Iv),{currentTheme:d}=Wa();let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=ds(),e[0]=c):c=e[0];const p=c,u=Pv;let g,m;e[1]!==i||e[2]!==r||e[3]!==o?(g=()=>{if(i.length===0){r!==null&&o(null);return}r&&i.some(b=>b.id===r)||o(i[0].id)},m=[i,r,o],e[1]=i,e[2]=r,e[3]=o,e[4]=g,e[5]=m):(g=e[4],m=e[5]),l.useEffect(g,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 h;e[7]!==a?(h=a("settings.page.projects.title"),e[7]=a,e[8]=h):h=e[8];let f;e[9]!==h?(f=s.jsx("h2",{className:`${hn} mb-3`,children:h}),e[9]=h,e[10]=f):f=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 O;e[21]!==C||e[22]!==f?(O=s.jsxs("div",{className:w,children:[f,C]}),e[21]=C,e[22]=f,e[23]=O):O=e[23];let j;if(e[24]!==d||e[25]!==n||e[26]!==i||e[27]!==r||e[28]!==o){let b;e[30]!==d||e[31]!==n||e[32]!==r||e[33]!==o?(b=I=>{const B=I.id===r,T=I.icon?yp[I.icon]:null,D=I.color?cu[I.color]??null:null,S=T?s.jsx(K,{name:T,className:fe("h-4 w-4",B?"text-foreground":"text-muted-foreground/70"),style:D?{color:D}:void 0}):s.jsx(K,{name:"folder",className:fe("h-4 w-4",B?"text-foreground":"text-muted-foreground/70"),style:D?{color:D}:void 0}),F=I.iconImage?s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:I.iconBackground?{backgroundColor:I.iconBackground}:void 0,children:s.jsx(du,{project:I,options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:S})}):S;return s.jsx(Qo,{title:I.label||I.path,icon:F,selected:B,onSelect:()=>{o(I.id),n?.()}},I.id)},e[30]=d,e[31]=n,e[32]=r,e[33]=o,e[34]=b):b=e[34],j=i.map(b),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]!==O||e[36]!==j?(N=s.jsx(qu,{variant:"background",header:O,children:j}),e[35]=O,e[36]=j,e[37]=N):N=e[37],N};function Sv(t){return t.projects}function Cv(t){return t.settingsProjectsSelectedId}function Iv(t){return t.setSettingsProjectsSelectedId}function Pv(){lu.requestDirectoryDialog()}const yi=$s,Tn=t=>{const e=Ze.c(11),{title:n,description:a,info:i,settingsItem:r,titleAccessory:o,headerAction:d,children:c,className:p,contentClassName:u,divider:g}=t,m=g===void 0?!0:g;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},Tv=450,Av=({projectRef:t=null,sections:e="all"})=>{const{t:n}=ot(),{isMobile:a,isTablet:i}=Hs(),r=a||i,o=is(E=>E.getActiveProject()),d=t?.path??o?.path??null,c=es(E=>E.getWorktreeMetadata),p=au(),u=Cs(E=>E.homeDirectory),[g,m]=l.useState([]),[w,h]=l.useState(!1),[f,x]=l.useState(!1),[k,y]=l.useState(null),[C,O]=l.useState(null),[j,N]=l.useState([]),[b,I]=l.useState(!1),B=l.useRef(!1),T=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]),D=l.useCallback(async()=>{if(!(!T||C===!1))try{const E=await Pl(T);N(E)}catch{}},[T,C]);l.useEffect(()=>{if(!d)return;let E=!1;return O(null),(async()=>{try{const P=await vp(d);if(E)return;O(P)}catch{}})(),()=>{E=!0}},[d]),l.useEffect(()=>{if(!T){N([]),I(!1);return}if(C===!1){N([]),I(!1);return}let E=!1;return I(!0),N([]),(async()=>{try{const P=await Pl(T);if(E)return;N(P)}catch{}finally{E||I(!1)}})(),()=>{E=!0}},[T,C]),l.useEffect(()=>{if(!T)return;let E=!1;return x(!0),(async()=>{try{const[P,_]=await Promise.all([uu(T),mu(T)]);if(!E){const L=P.length>0?P:[""];m(L),y(JSON.stringify(L)),h(_)}}catch{E||(m([""]),y(JSON.stringify([""])),h(!1))}finally{E||x(!1)}})(),()=>{E=!0}},[T]);const S=l.useCallback(async E=>{if(!T)return!1;const P=E.filter(_=>_.trim().length>0);try{return await wp(T,P)?(y(JSON.stringify(E)),!0):(Q.error(n("settings.openchamber.worktrees.setup.toast.saveFailed")),!1)}catch{return Q.error(n("settings.openchamber.worktrees.setup.toast.saveFailed")),!1}},[T,n]),F=l.useMemo(()=>k===null?!1:k!==JSON.stringify(g),[k,g]);l.useEffect(()=>{if(!F||f||B.current)return;const E=window.setTimeout(()=>{B.current||(B.current=!0,(async()=>{try{await S(g)}finally{B.current=!1}})())},Tv);return()=>{window.clearTimeout(E)}},[F,f,S,g]);const R=l.useCallback((E,P)=>{m(_=>{const L=[..._];return L[E]=P,L})},[]),z=l.useCallback(()=>{m(E=>[...E,""])},[]),q=l.useCallback(E=>{m(P=>{const _=P.filter((L,V)=>V!==E);return _.length>0?_:[""]})},[]),H=l.useCallback(()=>{!F||B.current||(B.current=!0,(async()=>{try{await S(g)}finally{B.current=!1}})())},[F,S,g]),Z=l.useCallback(E=>{h(E),T&&jp(T,E)},[T]),W=l.useCallback(E=>{const P=be=>be.replace(/\\/g,"/").replace(/\/+$/,""),_=P(E.path),L=p.filter(be=>{const ie=c(be.id);if(ie?.path&&P(ie.path)===_)return!0;const pe=be.directory;return!!(pe&&P(pe)===_)}),V=new Set(L.map(be=>be.id)),Y=[...Lo.getState().activeSessions,...Lo.getState().archivedSessions],G=be=>{const ie=Y.filter(Ie=>{const re=Ie.parentID;return re&&be.has(re)});if(ie.length===0)return[];const pe=new Set(ie.map(Ie=>Ie.id));return[...ie,...G(pe)]},me=G(V),ae=new Set,xe=[...L,...me].filter(be=>ae.has(be.id)?!1:(ae.add(be.id),!0));lu.requestDelete({sessions:xe,mode:"worktree",worktree:E})},[p,c]),A=l.useMemo(()=>p.map(E=>E.id).join(","),[p]);l.useEffect(()=>{C&&d&&D()},[A,C,d,D]);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(Tn,{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(Tn,{title:n("settings.projects.page.section.worktree"),settingsItem:"projects.worktree",titleAccessory:X,children:f?s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.setup.loading")}):s.jsxs("div",{className:fe("space-y-2",yi),children:[g.map((E,P)=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(nt,{value:E,onChange:_=>R(P,_.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:()=>q(P),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"})})]},P)),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:z,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(rn,{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(Tn,{title:n("settings.openchamber.worktrees.list.title"),titleAccessory:te,children:b?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"&&yi),children:j.map(E=>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:E.label||E.branch||n("settings.openchamber.worktrees.list.detachedHead")})}),s.jsx("p",{className:"typography-micro truncate text-muted-foreground/60",children:kp(E.path,u)})]}),s.jsx("button",{type:"button",onClick:()=>W(E),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:E.branch||E.label||E.path}),children:s.jsx(K,{name:"delete-bin",className:"h-4 w-4"})})]},E.path))})})]}):s.jsx(Tn,{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")})})},Xc=(t,e)=>e.updatedAtMs-t.updatedAtMs,Ss=fn((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([Ip(),Al()]),i={};for(const r of a.sort(Xc))i[r.id]=r;e().listenerReady||await Pp(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 Cp();t({importCandidates:n,isImportsLoading:!1})}catch(n){t({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Al(),a={};for(const i of n.sort(Xc))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 Sp({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=Tp(n,a);i&&i.trim()&&(r.nickname=i.trim()),await e().upsertInstance(r)},removeInstance:async n=>{await Tl(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 Np(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 Tl(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})})),Xu=[{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"}],Zu=Object.fromEntries(Xu.map(t=>[t.key,t.Icon])),Ev="openchamber:project-actions-updated",Dv=t=>{const e=(t||"").trim().replace(/\\/g,"/");return e?e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e:""},fS=(t,e)=>`${Dv(t)}::${e}`,Rv=t=>{const e=t.trim();return!e||e==="0.0.0.0"||e==="::"?"127.0.0.1":e},Zc=t=>{if(typeof t!="number"||!Number.isFinite(t))return null;const e=Math.round(t);return e<1||e>65535?null:e},Mv=(t,e)=>{if(!e.enabled||e.type!=="local")return null;const n=Zc(e.localPort),a=Zc(e.remotePort);if(!n||!a)return null;const i=Rv(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}`}},em=t=>{const e=[];for(const n of t)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const a of n.portForwards){const i=Mv(n,a);i&&e.push(i)}return e},hS=(t,e)=>{const n=(t||"").trim();return n&&em(e).find(r=>r.id===n)?.url||null},Lv=450,Fv=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Ov=()=>({id:Fv(),name:"",command:"",icon:"play"}),zv=({projectRef:t})=>{const{t:e}=ot(),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),[g,m]=l.useState({}),w=l.useRef(!1),h=l.useRef(null);l.useEffect(()=>{n&&i().catch(()=>{})},[n,i]),l.useEffect(()=>{let N=!1;return c(!0),(async()=>{try{const b=await Ap(t);if(N)return;o(b.actions),u(JSON.stringify({actions:b.actions}))}catch{if(N)return;o([]),u(JSON.stringify({actions:[]}))}finally{N||c(!1)}})(),()=>{N=!0}},[t]);const f=l.useMemo(()=>n?em(a):[],[a,n]),x=l.useMemo(()=>r.some(b=>b.name.trim().length===0||b.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 Ep(t,{actions:N,primaryActionId:null})?(u(JSON.stringify({actions:N})),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ev,{detail:{projectId:t.id}})),!0):(Q.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}})())},Lv);return()=>{window.clearTimeout(N)}},[r,k,d,y,x]),l.useEffect(()=>{if(!k||!x||d){x||(h.current=null);return}const N=window.setTimeout(()=>{h.current!==x&&(h.current=x,Q.error(x))},1e3);return()=>{window.clearTimeout(N)}},[k,d,x]);const C=l.useCallback(()=>{const N=Ov();o(b=>[...b,N]),m(b=>({...b,[N.id]:!0}))},[]),O=l.useCallback(N=>{o(b=>b.filter(I=>I.id!==N)),m(b=>{const I={...b};return delete I[N],I})},[]),j=l.useCallback((N,b)=>{o(I=>I.map(B=>B.id===N?b(B):B))},[]);return s.jsxs(Tn,{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",yi),children:r.map(N=>{const b=N.icon||"play",I=Zu[b]||"play",B=g[N.id]??!1,T=N.name.trim()||e("settings.projects.actions.state.untitled");return s.jsxs(da,{open:B,onOpenChange:D=>{m(S=>({...S,[N.id]:D}))},className:"py-1.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs(ua,{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:[B?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:I,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:T})})]}),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:()=>O(N.id),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsx(ma,{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:I,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:Xu.map(D=>{const S=D.Icon,F=(N.icon||"play")===D.key;return s.jsx("button",{type:"button",onClick:()=>j(N.id,R=>({...R,icon:D.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:D.label}),children:s.jsx(K,{name:S,className:"h-4 w-4"})},D.key)})})})]}),s.jsx(nt,{value:N.name,onChange:D=>j(N.id,S=>({...S,name:D.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:D=>j(N.id,S=>({...S,command:D.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,D=>({...D,...D.autoOpenUrl===!0?{autoOpenUrl:void 0}:{autoOpenUrl:!0}})),onKeyDown:D=>{(D.key===" "||D.key==="Enter")&&(D.preventDefault(),j(N.id,S=>({...S,...S.autoOpenUrl===!0?{autoOpenUrl:void 0}:{autoOpenUrl:!0}})))},children:[s.jsx(rn,{checked:N.autoOpenUrl===!0,onChange:D=>j(N.id,S=>({...S,...D?{autoOpenUrl:!0}:{autoOpenUrl:void 0}})),ariaLabel:e("settings.projects.actions.field.autoOpenUrlForAria",{title:T})}),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(nt,{value:N.openUrl||"",onChange:D=>j(N.id,S=>({...S,openUrl:D.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")}),f.length>0?s.jsxs(Mt,{value:N.desktopOpenSshForward&&f.some(D=>D.id===N.desktopOpenSshForward)?N.desktopOpenSshForward:"__none__",onValueChange:D=>{j(N.id,S=>({...S,...D==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:D}}))},children:[s.jsx(Lt,{size:Gt,className:"w-full",children:s.jsx(Wt,{placeholder:e("settings.projects.actions.field.useOutputManualUrl")})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"__none__",children:e("settings.projects.actions.field.useOutputManualUrl")}),f.map(D=>s.jsx(jt,{value:D.id,children:D.label},D.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]})},Kv=t=>{const e=Ze.c(123),{form:n}=t,{t:a}=ot(),{currentTheme:i}=Wa(),{name:r,setName:o,icon:d,setIcon:c,color:p,setColor:u,iconBackground:g,setIconBackground:m,parsedDefaultModel:w,handleDefaultModelChange:h,isUploadingIcon:f,isRemovingCustomIcon:x,isDiscoveringIcon:k,pendingRemoveImageIcon:y,setPendingRemoveImageIcon:C,pendingUploadIconPreviewUrl:O,setPreviewImageFailed:j,hasPendingUploadImageIcon:N,hasCustomIcon:b,effectiveHasImageIcon:I,hasRemovableImageIcon:B,showImagePreview:T,fileInputRef:D,handleUploadIcon:S,handleRemoveImageIcon:F,handleDiscoverIcon:R,currentIconImage:z,project:q}=n;if(!q)return null;const H=p?cu[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 W;e[2]!==o?(W=$=>o($.target.value),e[2]=o,e[3]=W):W=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",yi),e[6]=X):X=e[6];let te;e[7]!==r||e[8]!==W||e[9]!==A?(te=s.jsx(nt,{value:r,onChange:W,placeholder:A,className:X}),e[7]=r,e[8]=W,e[9]=A,e[10]=te):te=e[10];let E;e[11]!==Z||e[12]!==te?(E=s.jsx(Tn,{title:Z,settingsItem:"projects.name",divider:!1,children:te}),e[11]=Z,e[12]=te,e[13]=E):E=e[13];let P;e[14]!==a?(P=a("settings.projects.page.field.defaultModel"),e[14]=a,e[15]=P):P=e[15];let _;e[16]!==a?(_=a("settings.projects.page.field.defaultModelDescription"),e[16]=a,e[17]=_):_=e[17];const L=w.providerId,V=w.modelId;let Y;e[18]===Symbol.for("react.memo_cache_sentinel")?(Y=fe("h-8 min-h-8 rounded-md px-3 max-w-48",yi),e[18]=Y):Y=e[18];let G;e[19]!==h||e[20]!==w.modelId||e[21]!==w.providerId?(G=s.jsx(la,{providerId:L,modelId:V,onChange:h,className:Y}),e[19]=h,e[20]=w.modelId,e[21]=w.providerId,e[22]=G):G=e[22];let me;e[23]!==G||e[24]!==P||e[25]!==_?(me=s.jsx(Tn,{title:P,info:_,settingsItem:"projects.default-model",children:G}),e[23]=G,e[24]=P,e[25]=_,e[26]=me):me=e[26];let ae;e[27]!==a?(ae=a("settings.projects.page.field.accentColor"),e[27]=a,e[28]=ae):ae=e[28];let xe;e[29]!==u?(xe=()=>u(null),e[29]=u,e[30]=xe):xe=e[30];const be=p===null?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-border/40 hover:border-border hover:bg-[var(--surface-muted)]";let ie;e[31]!==be?(ie=fe("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",be),e[31]=be,e[32]=ie):ie=e[32];let pe;e[33]!==a?(pe=a("settings.projects.page.field.none"),e[33]=a,e[34]=pe):pe=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 re;e[36]!==xe||e[37]!==ie||e[38]!==pe?(re=s.jsx("button",{type:"button",onClick:xe,className:ie,title:pe,children:Ie}),e[36]=xe,e[37]=ie,e[38]=pe,e[39]=re):re=e[39];let ce;e[40]!==p||e[41]!==u?(ce=Dp.map($=>s.jsx("button",{type:"button",onClick:()=>u($.key),className:fe("h-7 w-7 rounded-md border transition-colors",p===$.key?"border-2 border-foreground ring-1 ring-[var(--primary-base)]/40":"border-transparent hover:border-border/70"),style:{backgroundColor:$.cssVar},title:$.label},$.key)),e[40]=p,e[41]=u,e[42]=ce):ce=e[42];let ge;e[43]!==re||e[44]!==ce?(ge=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[re,ce]}),e[43]=re,e[44]=ce,e[45]=ge):ge=e[45];let oe;e[46]!==ae||e[47]!==ge?(oe=s.jsx(Tn,{title:ae,settingsItem:"projects.accent-color",children:ge}),e[46]=ae,e[47]=ge,e[48]=oe):oe=e[48];let de;e[49]!==a?(de=a("settings.projects.page.field.projectIcon"),e[49]=a,e[50]=de):de=e[50];let le;e[51]!==S?(le=$=>{const Ee=$.target.files?.[0]??null;S(Ee),$.currentTarget.value=""},e[51]=S,e[52]=le):le=e[52];let he;e[53]!==D||e[54]!==le?(he=s.jsx("input",{ref:D,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:le}),e[53]=D,e[54]=le,e[55]=he):he=e[55];let De;e[56]!==c?(De=()=>c(null),e[56]=c,e[57]=De):De=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 Ke;e[58]!==Le?(Ke=fe("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",Le),e[58]=Le,e[59]=Ke):Ke=e[59];let Fe;e[60]!==a?(Fe=a("settings.projects.page.field.none"),e[60]=a,e[61]=Fe):Fe=e[61];let Me;e[62]===Symbol.for("react.memo_cache_sentinel")?(Me=s.jsx(K,{name:"close",className:"h-4 w-4 text-muted-foreground"}),e[62]=Me):Me=e[62];let Be;e[63]!==De||e[64]!==Ke||e[65]!==Fe?(Be=s.jsx("button",{type:"button",onClick:De,className:Ke,title:Fe,children:Me}),e[63]=De,e[64]=Ke,e[65]=Fe,e[66]=Be):Be=e[66];let Ge;e[67]!==H||e[68]!==d||e[69]!==c?(Ge=Rp.map($=>{const Ee=$.Icon;return s.jsx("button",{type:"button",onClick:()=>c($.key),className:fe("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",d===$.key?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-transparent hover:border-border hover:bg-[var(--surface-muted)]"),title:$.label,children:s.jsx(K,{name:Ee,className:"w-4 h-4",style:H&&d===$.key?{color:H}:void 0})},$.key)}),e[67]=H,e[68]=d,e[69]=c,e[70]=Ge):Ge=e[70];let Ve;e[71]!==Be||e[72]!==Ge?(Ve=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Be,Ge]}),e[71]=Be,e[72]=Ge,e[73]=Ve):Ve=e[73];let Ue;e[74]!==z||e[75]!==i||e[76]!==I||e[77]!==N||e[78]!==g||e[79]!==O||e[80]!==q||e[81]!==j||e[82]!==T||e[83]!==a?(Ue=I&&T&&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:g?{backgroundColor:g}:void 0,children:N&&O?s.jsx("img",{src:O,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>j(!0)}):s.jsx(du,{project:{...q,iconImage:z??q.iconImage},options:{themeVariant:i.metadata.variant,iconColor:i.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>j(!0)})})})]}),e[74]=z,e[75]=i,e[76]=I,e[77]=N,e[78]=g,e[79]=O,e[80]=q,e[81]=j,e[82]=T,e[83]=a,e[84]=Ue):Ue=e[84];let He;e[85]!==I||e[86]!==g||e[87]!==m||e[88]!==a?(He=I&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:g??"#000000",onChange:$=>m($.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(nt,{value:g??"",onChange:$=>m($.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:!g,children:s.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]}),e[85]=I,e[86]=g,e[87]=m,e[88]=a,e[89]=He):He=e[89];let _e;e[90]!==D||e[91]!==R||e[92]!==b||e[93]!==k||e[94]!==f||e[95]!==a?(_e=!b&&s.jsxs(s.Fragment,{children:[s.jsx(ee,{size:"xs",className:"h-6 !font-normal",onClick:()=>D.current?.click(),disabled:f,children:a(f?"settings.projects.page.actions.uploading":"settings.projects.page.actions.uploadIcon")}),s.jsx(ee,{size:"xs",className:"h-6 !font-normal",variant:"outline",onClick:()=>{R()},disabled:k,children:a(k?"settings.projects.page.actions.discovering":"settings.projects.page.actions.discoverFavicon")})]}),e[90]=D,e[91]=R,e[92]=b,e[93]=k,e[94]=f,e[95]=a,e[96]=_e):_e=e[96];let Oe;e[97]!==F||e[98]!==B||e[99]!==x||e[100]!==a?(Oe=B&&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]=B,e[99]=x,e[100]=a,e[101]=Oe):Oe=e[101];let se;e[102]!==x||e[103]!==y||e[104]!==C||e[105]!==a?(se=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]=se):se=e[106];let ye;e[107]!==_e||e[108]!==Oe||e[109]!==se?(ye=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[_e,Oe,se]}),e[107]=_e,e[108]=Oe,e[109]=se,e[110]=ye):ye=e[110];let ke;e[111]!==de||e[112]!==he||e[113]!==Ve||e[114]!==Ue||e[115]!==He||e[116]!==ye?(ke=s.jsxs(Tn,{title:de,settingsItem:"projects.icon",contentClassName:"space-y-3",children:[he,Ve,Ue,He,ye]}),e[111]=de,e[112]=he,e[113]=Ve,e[114]=Ue,e[115]=He,e[116]=ye,e[117]=ke):ke=e[117];let ze;return e[118]!==me||e[119]!==oe||e[120]!==ke||e[121]!==E?(ze=s.jsxs(s.Fragment,{children:[E,me,oe,ke]}),e[118]=me,e[119]=oe,e[120]=ke,e[121]=E,e[122]=ze):ze=e[122],ze},Bv=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,_v=t=>{if(!t)return null;const e=t.trim();return e&&Bv.test(e)?e.toLowerCase():null},Uv=t=>{const{t:e}=ot(),n=is(ae=>ae.uploadProjectIcon),a=is(ae=>ae.removeProjectIcon),i=is(ae=>ae.discoverProjectIcon),r=is(ae=>t?ae.projects.find(xe=>xe.id===t.id)?.iconImage??null:null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,g]=l.useState(null),[m,w]=l.useState(null),[h,f]=l.useState(void 0),[x,k]=l.useState(!1),[y,C]=l.useState(!1),[O,j]=l.useState(!1),[N,b]=l.useState(!1),[I,B]=l.useState(null),[T,D]=l.useState(null),[S,F]=l.useState(!1),R=l.useRef(null),z=l.useCallback(()=>{B(null),D(ae=>(ae&&URL.revokeObjectURL(ae),null))},[]),q=t?.id??null;l.useEffect(()=>{if(!t){d(""),p(null),g(null),w(null),f(void 0);return}d(t.label??""),p(t.icon??null),g(t.color??null),w(t.iconBackground??null),f(t.defaultModel),b(!1),z(),F(!1)},[t,z]),l.useEffect(()=>()=>{z()},[z]);const H=l.useMemo(()=>Wn(h)??{providerId:"",modelId:""},[h]),Z=!!t?.iconImage,W=!!(I&&T),A=t?.iconImage?.source==="custom",X=Z&&!N||W,te=X,E=!!(t&&Z&&!N),P=!S&&(W||E),_=!!t&&(o.trim()!==(t?.label??"").trim()||c!==(t?.icon??null)||u!==(t?.color??null)||m!==(t?.iconBackground??null)||(h??void 0)!==(t?.defaultModel??void 0)||N||!!I),L=l.useCallback((ae,xe)=>{f(ae&&xe?`${ae}/${xe}`:void 0)},[]),V=l.useCallback(ae=>{!t||!ae||x||(b(!1),F(!1),B(ae),D(xe=>(xe&&URL.revokeObjectURL(xe),URL.createObjectURL(ae))))},[x,t]),Y=l.useCallback(()=>{!t||!te||y||(W&&z(),b(!!Z),F(!1))},[z,W,te,Z,y,t]),G=l.useCallback(async()=>{if(!(!t||O)){z(),b(!1),F(!1),j(!0);try{const ae=await i(t.id);if(!ae.ok){Q.error(ae.error||e("settings.projects.page.toast.discoverIconFailed"));return}if(ae.skipped){Q.success(e("settings.projects.page.toast.customIconAlreadySet"));return}Q.success(e("settings.projects.page.toast.iconDiscovered"))}finally{j(!1)}}},[z,i,O,t,e]),me=l.useCallback(async ae=>{const xe=ae?.silent===!0;if(!t)return null;const be=o.trim();if(!be)return null;if(I){k(!0);const pe=await n(t.id,I);if(k(!1),!pe.ok)return Q.error(pe.error||e("settings.projects.page.toast.uploadIconFailed")),null;xe||Q.success(e("settings.projects.page.toast.iconUpdated")),z(),b(!1)}const ie=N&&!!t.iconImage;if(ie){C(!0);const pe=await a(t.id);if(C(!1),!pe.ok)return Q.error(pe.error||e("settings.projects.page.toast.removeIconFailed")),null;xe||Q.success(e("settings.projects.page.toast.iconRemoved")),b(!1),w(null)}return{label:be,icon:c,color:u,iconBackground:_v(ie?null:m),defaultModel:h??null}},[z,u,h,c,m,o,N,I,t,a,e,n]);return l.useEffect(()=>{F(!1)},[q,r?.updatedAt]),{name:o,setName:d,icon:c,setIcon:p,color:u,setColor:g,iconBackground:m,setIconBackground:w,defaultModel:h,parsedDefaultModel:H,handleDefaultModelChange:L,isUploadingIcon:x,isRemovingCustomIcon:y,isDiscoveringIcon:O,pendingRemoveImageIcon:N,setPendingRemoveImageIcon:b,pendingUploadIconFile:I,pendingUploadIconPreviewUrl:T,previewImageFailed:S,setPreviewImageFailed:F,hasStoredImageIcon:Z,hasPendingUploadImageIcon:W,hasCustomIcon:A,effectiveHasImageIcon:X,hasRemovableImageIcon:te,showStoredImagePreview:E,showImagePreview:P,fileInputRef:R,clearPendingUploadIcon:z,handleUploadIcon:V,handleRemoveImageIcon:Y,handleDiscoverIcon:G,hasChanges:_,prepareSaveData:me,currentIconImage:r,project:t}},$v=450,Vv=(t,e)=>{const{t:n}=ot(),{hasChanges:a,name:i,icon:r,color:o,iconBackground:d,defaultModel:c,pendingRemoveImageIcon:p,pendingUploadIconFile:u,isUploadingIcon:g,isRemovingCustomIcon:m,prepareSaveData:w}=t,h=l.useRef(!1);l.useEffect(()=>{if(!a||!i.trim()||g||m||h.current)return;const f=window.setTimeout(()=>{h.current||(h.current=!0,(async()=>{try{const x=await w({silent:!0});if(x)try{await e(x)}catch{Q.error(n("settings.projects.page.toast.saveFailed"))}}finally{h.current=!1}})())},$v);return()=>{window.clearTimeout(f)}},[o,c,a,r,d,m,g,i,e,p,u,w,n])},Hv=t=>{const e=Ze.c(16),{project:n,onIdentitySave:a,showWorktrees:i}=t,r=i===void 0?!0:i,o=Uv(n);let d;e:{if(!n){d=null;break e}let f;e[0]!==n.id||e[1]!==n.path?(f={id:n.id,path:n.path},e[0]=n.id,e[1]=n.path,e[2]=f):f=e[2],d=f}const c=d;let p;if(e[3]!==a?(p=async f=>{await a(f)},e[3]=a,e[4]=p):p=e[4],Vv(o,p),!n||!c)return null;let g;e[5]!==o?(g=s.jsx(Kv,{form:o}),e[5]=o,e[6]=g):g=e[6];let m;e[7]!==c?(m=s.jsx(zv,{projectRef:c}),e[7]=c,e[8]=m):m=e[8];let w;e[9]!==c||e[10]!==r?(w=r?s.jsx(Av,{projectRef:c}):null,e[9]=c,e[10]=r,e[11]=w):w=e[11];let h;return e[12]!==g||e[13]!==m||e[14]!==w?(h=s.jsxs("div",{className:"space-y-0",children:[g,m,w]}),e[12]=g,e[13]=m,e[14]=w,e[15]=h):h=e[15],h},Wv=()=>{const t=Ze.c(30),{t:e}=ot(),n=is(Gv),a=is(qv),i=je(Jv),r=je(Yv);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 g=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 h;t[23]!==g||t[24]!==d?(h=s.jsx(Hv,{project:d,onIdentitySave:g}),t[23]=g,t[24]=d,t[25]=h):h=t[25];let f;return t[26]!==w||t[27]!==d.path||t[28]!==h?(f=s.jsx(ps,{title:w,description:d.path,showSaveStatus:!0,outerClassName:"bg-background",children:h}),t[26]=w,t[27]=d.path,t[28]=h,t[29]=f):f=t[29],f};function Gv(t){return t.projects}function qv(t){return t.updateProjectMeta}function Jv(t){return t.settingsProjectsSelectedId}function Yv(t){return t.setSettingsProjectsSelectedId}const hr=ve.forwardRef((t,e)=>{const n=Ze.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(Jf,{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(Yf,{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});hr.displayName="Switch";const Zo=()=>Math.floor(2e4+Math.random()*3e4),Qv=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")},Xv=()=>{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"},ed=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}},td=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"}},Zv=new Set(["config_resolved","auth_check","master_connecting","remote_probe","installing","updating","server_detecting","server_starting","forwarding"]),tm=t=>!!(t&&Zv.has(t)),sd=t=>t==="ready"?"bg-[var(--status-success)] animate-pulse":t==="error"?"bg-[var(--status-error)] animate-pulse":t==="degraded"||tm(t)?"bg-[var(--status-warning)] animate-pulse":"bg-muted-foreground/40",ew=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}`,tw=()=>({id:`forward-${Date.now()}-${Math.random().toString(16).slice(2)}`,enabled:!0,type:"local",localHost:"127.0.0.1",localPort:Zo(),remoteHost:"127.0.0.1",remotePort:80}),sw=t=>t.trim().replace(/\*/g,"host").replace(/\?/g,"x")||"user@host",vn=t=>{const e=Ze.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},nw=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"}},nd=(t,e)=>{const n=(t||"").trim();return`${!n||n==="127.0.0.1"||n==="::1"?"localhost":n}:${e||0}`},aw=t=>{const e=(t||"").trim();return!e||e==="0.0.0.0"||e==="::"?"127.0.0.1":e},iw=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}`},el=(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}),rw=t=>t.trim().toLowerCase()==="authorization",io=t=>{const e={};for(const n of t){const a=n.name.trim(),i=n.value.trim();a&&i&&!rw(a)&&(e[a]=i)}return Object.keys(e).length>0?e:void 0},ow=t=>Object.entries(t||{}).map(([e,n])=>el(e,n)),sm=()=>{if(typeof window>"u")return null;const e=qa()||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}},ad=t=>{try{const e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}catch{return!1}},lw=async()=>{const t=Fa(qa())||window.location.origin;if(!ls()||!Ga())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 bu(),i=sm();return!a||!i?t:`http://${a}:${i}`},ro=t=>{const e=t.trim();if(e)try{window.location.assign(e)}catch{window.location.href=e}},cw=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}},dw=()=>{const{t}=ot(),e=je(U=>U.timeFormatPreference),{clientAuth:n}=Ha(),a=ls(),i=Ss(U=>U.instances),r=Ss(U=>U.statusesById),o=Ss(U=>U.importCandidates),d=Ss(U=>U.isLoading),c=Ss(U=>U.isImportsLoading),p=Ss(U=>U.isSaving),u=Ss(U=>U.error),g=Ss(U=>U.load),m=Ss(U=>U.loadImports),w=Ss(U=>U.refreshStatuses),h=Ss(U=>U.upsertInstance),f=Ss(U=>U.createFromCommand),x=Ss(U=>U.removeInstance),k=Ss(U=>U.connect),y=Ss(U=>U.disconnect),C=Ss(U=>U.retry),O=je(U=>U.settingsRemoteInstancesSelectedId),j=je(U=>U.setSettingsRemoteInstancesSelectedId),N=l.useMemo(()=>O&&i.find(U=>U.id===O)||null,[i,O]),[b,I]=l.useState(null),[B,T]=l.useState(!1),[D,S]=l.useState(!1),[F,R]=l.useState(null),[z,q]=l.useState([]),[H,Z]=l.useState(null),[W,A]=l.useState(""),[X,te]=l.useState(!1),[E,P]=l.useState({}),[_,L]=l.useState(!1),[V,Y]=l.useState(!1),[G,me]=l.useState(()=>Date.now()),[ae,xe]=l.useState([]),[be,ie]=l.useState({}),[pe,Ie]=l.useState("local"),[re,ce]=l.useState(!1),[ge,oe]=l.useState(!1),[de,le]=l.useState(""),[he,De]=l.useState(""),[Le,Ke]=l.useState(""),[Fe,Me]=l.useState([]),[Be,Ge]=l.useState(""),[Ve,Ue]=l.useState(null),[He,_e]=l.useState(!1),[Oe,se]=l.useState(!1),[ye,ke]=l.useState(null),[ze,$]=l.useState(""),[Ee,J]=l.useState(""),[v,ue]=l.useState(""),[Ne,we]=l.useState([]),[qe,it]=l.useState([]),[st,rt]=l.useState([]),[lt,xt]=l.useState(!1),[bt,Nt]=l.useState(""),[Ce,Qe]=l.useState(null),[tt,at]=l.useState(null),[gt,wt]=l.useState(null),[Te,ne]=l.useState(null),[Pe,Xe]=l.useState(!1),[Re,Ye]=l.useState(!1),[We,et]=l.useState("configure"),[kt,Et]=l.useState(!1),[Ot,Zt]=l.useState("relay"),[Qt,St]=l.useState(!0),[Pt,Se]=l.useState(null),ut=l.useMemo(()=>qe.filter(U=>!!U.revokedAt).length,[qe]),[mt,At]=l.useState(!1),[ft,vt]=l.useState("ssh user@example.com"),[Dt,Vt]=l.useState("");l.useEffect(()=>{g(),m()},[g,m]);const ts=l.useCallback(async()=>{ce(!0),Ue(null);try{const U=await $l();xe(U.hosts||[]),Ie(U.defaultHostId||"local")}catch(U){Ue(U instanceof Error?U.message:String(U))}finally{ce(!1)}},[]);l.useEffect(()=>{ts()},[ts]);const os=l.useCallback(async(U,Ae=pe)=>{oe(!0),Ue(null);try{await Vl({hosts:U,defaultHostId:Ae,initialHostChoiceCompleted:!0}),xe(U),Ie(Ae)}catch(ct){Ue(ct instanceof Error?ct.message:String(ct))}finally{oe(!1)}},[pe]),En=l.useCallback(async()=>{const U=Hl(he);if(!U){Ue(t("desktopHostSwitcher.error.invalidUrl"));return}const Ae=U.persistedUrl,yt={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:de.trim()||ei(Ae),url:Ae,apiUrl:Ae,...Le.trim()?{clientToken:Le.trim()}:{},...io(Fe)?{requestHeaders:io(Fe)}:{}};await os([yt,...ae],pe),le(""),De(""),Ke(""),Me([]),_e(!1),U.redeemUrl&&ro(U.redeemUrl)},[pe,Fe,ae,de,Le,he,os,t]),Ks=l.useCallback(async()=>{const U=Og(Be);if(!U){Ue(t("settings.remoteInstances.direct.error.invalidConnectLink"));return}const Ae=await zg().catch(()=>""),ct=JSON.stringify({pairingId:U.pairingId,secret:U.secret,clientLabel:U.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:Xv(),...Ae?{dedupeKey:`desktop:${Ae}`}:{}}),yt={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:ct},qt=async Ht=>{if(!Ht.ok)return null;const Fs=await Ht.json().catch(()=>null);return(typeof Fs?.clientToken=="string"?Fs.clientToken.trim():"")||null},_s=[...U.candidates].sort((Ht,Fs)=>(Ht.type==="relay"?1:0)-(Fs.type==="relay"?1:0));let us=null;for(const Ht of _s){if(Ht.type==="relay"){const ea=Kg({relayUrl:Ht.relayUrl,serverId:Ht.serverId,hostEncPubJwk:Ht.hostEncPubJwk,...Ht.grant?{grant:Ht.grant}:{}});try{const Sa=await ea.fetch("/api/client-auth/pairing/redeem",yt),Ca=await qt(Sa);if(Ca){us={kind:"relay",relay:{relayUrl:Ht.relayUrl,serverId:Ht.serverId,hostEncPubJwk:Ht.hostEncPubJwk},token:Ca};break}}catch{}finally{ea.close()}continue}const Fs=Fa(Ht.url);if(Fs)try{const ea=await fetch(`${Fs}/api/client-auth/pairing/redeem`,yt),Sa=await qt(ea);if(Sa){us={kind:"direct",url:Fs,token:Sa};break}}catch{}}if(!us){Ue(t("desktopHostSwitcher.error.invalidUrl"));return}const qs=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,Us=U.candidates.find(Ht=>Ht.type==="relay"),Ls=us.kind==="relay"?us.relay:Us?{relayUrl:Us.relayUrl,serverId:Us.serverId,hostEncPubJwk:Us.hostEncPubJwk}:void 0,ln=U.candidates.filter(Ht=>Ht.type!=="relay").map(Ht=>Fa(Ht.url)).find(Ht=>!!Ht),cn=us.kind==="direct"?us.url:ln,{token:Xn}=us,Rt=cn||(Ls?Bg(Ls.serverId):null);if(!Rt){Ue(t("desktopHostSwitcher.error.invalidUrl"));return}const cs={url:Rt,apiUrl:cn||void 0,clientToken:Xn,...Ls?{relay:Ls}:{}},Zn=ae.find(Ht=>Ls?Ht.relay?.serverId===Ls.serverId:!Ht.relay&&Fa(Ht.apiUrl||Ht.url)===Rt);if(Zn){const Ht=ae.map(Fs=>Fs.id===Zn.id?{...Fs,label:U.label||Fs.label,...cs}:Fs);await os(Ht,pe)}else await os([{id:qs(),label:U.label||ei(Rt),...cs},...ae],pe);Ge(""),Ue(null),se(!1)},[Be,pe,ae,os,t]),ha=l.useCallback(async U=>{const Ae=ae.filter(yt=>yt.id!==U);await os(Ae,pe===U?"local":pe),ye===U&&ke(null)},[pe,ye,ae,os]),Qn=l.useCallback(U=>{ke(U.id),$(U.label),J(U.apiUrl||U.url),ue(U.clientToken||""),we(ow(U.requestHeaders)),Ue(null)},[]),Er=l.useCallback(async()=>{if(!ye)return;const U=Hl(Ee);if(!U){Ue(t("desktopHostSwitcher.error.invalidUrl"));return}const Ae=U.persistedUrl,ct=ae.map(yt=>yt.id===ye?{...yt,label:ze.trim()||ei(Ae),url:Ae,apiUrl:Ae,clientToken:v.trim()||void 0,requestHeaders:io(Ne)}:yt);await os(ct,pe),ke(null),U.redeemUrl&&ro(U.redeemUrl)},[pe,Ne,ze,v,Ee,ye,ae,os,t]),ji=l.useCallback(async()=>{const U=ft.trim();if(!U){Q.error(t("settings.remoteInstances.page.toast.sshCommandRequired"));return}const Ae=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{await f(Ae,U,Dt.trim()||t("settings.remoteInstances.sidebar.newSshInstanceName")),j(Ae),At(!1),vt("ssh user@example.com"),Vt(""),Q.success(t("settings.remoteInstances.page.toast.instanceCreated"))}catch(ct){Q.error(t("settings.remoteInstances.sidebar.toast.createFailed"),{description:ct instanceof Error?ct.message:String(ct)})}},[f,j,ft,Dt,t]),Dr=l.useCallback(async U=>{await os(ae,U)},[ae,os]);l.useEffect(()=>{if(!a||ae.length===0)return;let U=!1;return Promise.all(ae.map(async Ae=>{const ct=()=>Wg(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=Fa(_g(Ae));if(!yt)return[Ae.id,Ae.relay?await ct():{status:"unreachable",latencyMs:0}];const qt=await Ug(yt,{clientToken:Ae.clientToken||null,requestHeaders:Ae.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(qt.status==="unreachable"&&Ae.relay){const _s=await ct();if(_s.status==="ok")return[Ae.id,_s]}return[Ae.id,qt]})).then(Ae=>{U||ie(Object.fromEntries(Ae))}),()=>{U=!0}},[ae,a]);const Gs=l.useCallback(async U=>{if(n){U?.silent||xt(!0),U?.silent||Qe(null);try{const[Ae,ct]=await Promise.all([n.listClients(),n.listPendingPairings().catch(()=>null)]);it(Ae),ct&&rt(ct)}catch(Ae){U?.silent||Qe(Ae instanceof Error?Ae.message:String(Ae))}finally{U?.silent||xt(!1)}}},[n]),Ya=l.useRef(!1);l.useEffect(()=>{if(!(!Re||We!=="result"||!gt)){if(st.some(U=>U.id===gt)){Ya.current=!0;return}Ya.current&&(wt(null),Ye(!1),qe.some(U=>U.pairingId===gt)&&Q.success(t("settings.remoteInstances.clientAuth.addDevice.connectedToast")))}},[Re,We,gt,st,qe,t]);const ki=l.useCallback(async U=>{if(n)try{await n.cancelPairing(U),rt(Ae=>Ae.filter(ct=>ct.id!==U)),await Gs({silent:!0})}catch(Ae){Qe(Ae instanceof Error?Ae.message:String(Ae))}},[n,Gs]);l.useEffect(()=>{if(!n)return;Gs();const U=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Gs({silent:!0})},5e3);return()=>window.clearInterval(U)},[n,Gs]);const Ni=l.useCallback(async()=>{if(n?.getPairingTransports)try{const yt=await n.getPairingTransports();return{localUrl:yt.local,lanUrl:yt.lan,relayAvailable:yt.relayAvailable}}catch{}const U=sm(),Ae=U?`http://127.0.0.1:${U}`:ad(window.location.origin)?window.location.origin:null;let ct=null;try{const yt=Fa(await lw());ct=yt&&!ad(yt)?yt:null}catch{}return{localUrl:Ae,lanUrl:ct,relayAvailable:!0}},[n]),Rr=l.useCallback(async()=>{Qe(null),at(null),ne(null),Xe(!1),wt(null),et("configure"),St(!0),Ye(!0);const U=await Ni();Se(U),Zt(U.relayAvailable?"relay":U.lanUrl?"lan":"local")},[Ni]),Mr=l.useCallback(async()=>{if(!(!n?.createPairingSession||!Pt)){Qe(null),Et(!0);try{const U=bt.trim()||void 0;let Ae,ct,yt=!0;Ot==="local"?(Ae=Pt.localUrl??void 0,ct=!1):Ot==="lan"?(Ae=Pt.lanUrl??void 0,ct=Qt):Qt&&Pt.lanUrl?(Ae=Pt.lanUrl,ct=!0):(yt=!1,ct=!0);const{pairing:qt,server:_s}=await n.createPairingSession({label:U,allowedClientKinds:["mobile","desktop"],serverUrl:Ae,includeRelay:ct,includeDirect:yt}),us=$g({pairingId:qt.id,secret:qt.secret,label:_s.label,fingerprint:qt.fingerprint??void 0,expiresAt:qt.expiresAt,candidates:_s.candidates}),qs=Vg(us);at(qs),ne(await ku.toDataURL(qs,{width:1024,margin:2,errorCorrectionLevel:"L"})),Xe(!1),Ya.current=!1,wt(qt.id),et("result"),await Gs({silent:!0})}catch(U){Qe(U instanceof Error?U.message:String(U))}finally{Et(!1)}}},[n,Pt,Ot,Qt,bt,Gs]),Si=l.useCallback(()=>{tt&&oa(tt).then(U=>{U.ok&&(Xe(!0),window.setTimeout(()=>Xe(!1),2e3))})},[tt]),Lr=l.useCallback(async U=>{if(!n)return;const Ae=U.clientKind==="desktop-local";Qe(null);try{if(await n.revokeClient(U.id),Ae&&ls()){const ct=await $l();await Vl({hosts:ct.hosts,defaultHostId:ct.defaultHostId,initialHostChoiceCompleted:ct.initialHostChoiceCompleted,localClientToken:null}),it(yt=>yt.map(qt=>qt.id===U.id?{...qt,revokedAt:new Date().toISOString()}:qt)),Hg({apiBaseUrl:qa(),clientToken:null,runtimeKey:"local"});return}await Gs()}catch(ct){Qe(ct instanceof Error?ct.message:String(ct))}},[n,Gs]),Fr=l.useCallback(async()=>{if(n){Qe(null);try{await n.purgeRevokedClients(),await Gs()}catch(U){Qe(U instanceof Error?U.message:String(U))}}},[n,Gs]);l.useEffect(()=>{I(N)},[N]),l.useEffect(()=>{if(!O)return;const U=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||w()},2e3);return()=>{window.clearInterval(U)}},[w,O]),l.useEffect(()=>{let U=null,Ae=Date.now();const ct=()=>{const qt=Date.now();qt-Ae>=1e3&&(me(qt),Ae=qt),U=requestAnimationFrame(ct)};(typeof document>"u"||document.visibilityState==="visible")&&(U=requestAnimationFrame(ct));const yt=()=>{document.visibilityState==="visible"&&U===null?U=requestAnimationFrame(ct):document.visibilityState!=="visible"&&U!==null&&(cancelAnimationFrame(U),U=null)};return document.addEventListener("visibilitychange",yt),()=>{document.removeEventListener("visibilitychange",yt),U!==null&&cancelAnimationFrame(U)}},[]);const Bs=O?r[O]:null,on=Bs?.phase,xa=on==="ready",xn=on==="degraded",Dn=tm(on),Rn=xa||(Dn||xn),Or=Bs?Math.max(0,G-Bs.updatedAtMs):0,ba=xn&&Or>12e3,zr=l.useMemo(()=>!b||!N?!1:JSON.stringify(b)!==JSON.stringify(N),[b,N]),ys=l.useCallback(U=>{I(Ae=>Ae&&U(Ae))},[]),Kr=l.useCallback(async()=>{if(!b)return;const U=cw(b);if(!U.sshCommand.trim()){Q.error(t("settings.remoteInstances.page.toast.sshCommandRequired"));return}if(!(U.localForward.bindHost==="0.0.0.0"&&!window.confirm(t("settings.remoteInstances.page.confirm.bindAllInterfaces")))){if(U.auth.sshPassword?.enabled&&U.auth.sshPassword.value?.trim()&&U.auth.sshPassword.store!=="settings"){const Ae=window.confirm(t("settings.remoteInstances.page.confirm.storeSshPasswordPlaintext"));U.auth.sshPassword.store=Ae?"settings":"never",Ae||(U.auth.sshPassword.value=void 0)}if(U.auth.openchamberPassword?.enabled&&U.auth.openchamberPassword.value?.trim()&&U.auth.openchamberPassword.store!=="settings"){const Ae=window.confirm(t("settings.remoteInstances.page.confirm.storeUiPasswordPlaintext"));U.auth.openchamberPassword.store=Ae?"settings":"never",Ae||(U.auth.openchamberPassword.value=void 0)}try{await h(U),Q.success(t("settings.remoteInstances.page.toast.instanceSaved"))}catch(Ae){Q.error(t("settings.remoteInstances.page.toast.saveFailed"),{description:Ae instanceof Error?Ae.message:String(Ae)})}}},[b,t,h]),ya=l.useCallback(async(U,Ae)=>{const ct=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{return await f(ct,`ssh ${Ae}`,U),j(ct),Q.success(t("settings.remoteInstances.page.toast.instanceCreated")),!0}catch(yt){return Q.error(t("settings.remoteInstances.sidebar.toast.createFailed"),{description:yt instanceof Error?yt.message:String(yt)}),!1}},[f,j,t]),va=l.useCallback(()=>{X||(Z(null),A(""))},[X]),Br=l.useCallback((U,Ae)=>{if(Ae){Z(U),A(sw(U));return}ya(U,U)},[ya]),Ci=l.useCallback(async()=>{const U=H,Ae=W.trim();if(U){if(!Ae){Q.error(t("settings.remoteInstances.page.toast.destinationRequired"));return}te(!0);try{await ya(U,Ae)&&(Z(null),A(""))}finally{te(!1)}}},[ya,W,H,t]),wa=l.useCallback(async()=>{if(N)try{await k(N.id);return}catch(U){if(!Qv(U)||!window.confirm(t("settings.remoteInstances.sidebar.confirm.localPortInUseRetry")))throw U;const ct={...N,localForward:{...N.localForward,preferredLocalPort:Zo()}};await h(ct),await k(ct.id),Q.success(t("settings.remoteInstances.sidebar.toast.retriedWithRandomPort"))}},[k,N,t,h]),ja=l.useCallback(async U=>(await Mp(U,600)).map(ct=>iw(ct)),[]),ka=l.useCallback(async()=>{if(b){T(!0),S(!0),R(null);try{const U=await ja(b.id);q(U)}catch(U){q([]),R(U instanceof Error?U.message:String(U))}finally{S(!1)}}},[b,ja]);l.useEffect(()=>{if(!B||!b)return;let U=!1;const Ae=async()=>{try{const yt=await ja(b.id);U||(q(yt),R(null))}catch(yt){U||R(yt instanceof Error?yt.message:String(yt))}};Ae();const ct=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ae()},1e3);return()=>{U=!0,window.clearInterval(ct)}},[b,B,ja]);const bn=l.useMemo(()=>z.join(`
|
|
33
|
+
`),[z]),Qa=l.useCallback(()=>{if(!bn.trim()){Q.error(t("settings.remoteInstances.page.toast.noLogsToCopy"));return}oa(bn).then(U=>{U.ok&&Q.success(t("settings.remoteInstances.page.toast.logsCopied"))})},[bn,t]),Xa=l.useCallback(async()=>{if(b)try{await Lp(b.id),q([]),Q.success(t("settings.remoteInstances.page.toast.logsCleared"))}catch(U){Q.error(t("settings.remoteInstances.page.toast.clearLogsFailed"),{description:U instanceof Error?U.message:String(U)})}},[b,t]),Na=l.useCallback(async()=>{if(!Bs?.localUrl){Q.error(t("settings.remoteInstances.page.toast.instanceUrlUnavailable"));return}const U=Bs.localUrl.trim();if(!U){Q.error(t("settings.remoteInstances.page.toast.instanceUrlUnavailable"));return}ro(U)},[Bs?.localUrl,t]),Je=l.useCallback(()=>{if(!b)return;L(!0),(Rn?y(b.id):wa()).catch(Ae=>{const ct=Rn?xa?"settings.remoteInstances.page.toast.disconnectFailed":"settings.remoteInstances.page.toast.cancelConnectionFailed":"settings.remoteInstances.page.toast.connectFailed";Q.error(t(ct),{description:Ae instanceof Error?Ae.message:String(Ae)})}).finally(()=>{L(!1)})},[Rn,wa,y,b,xa,t]),ms=l.useCallback(()=>{if(!b||Dn)return;Y(!0),(xn?y(b.id).then(()=>wa()):C(b.id)).catch(Ae=>{Q.error(t("settings.remoteInstances.page.toast.retryFailed"),{description:Ae instanceof Error?Ae.message:String(Ae)})}).finally(()=>{Y(!1)})},[wa,y,b,Dn,xn,C,t]),Ii=t(Dn?"settings.remoteInstances.page.actions.connecting":xn?ba?"settings.remoteInstances.page.actions.reconnectNow":"settings.remoteInstances.page.actions.reconnecting":"settings.remoteInstances.sidebar.actions.retry"),Pi=!_&&!V&&(on==="error"||on==="idle"||!on||xn&&ba)&&!Dn,Ti=t(xa?"settings.remoteInstances.sidebar.actions.disconnect":Rn?"settings.remoteInstances.page.actions.cancel":"settings.remoteInstances.sidebar.actions.connect");if(!b)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:()=>{Rr()},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:()=>{Fr()},children:t("settings.remoteInstances.clientAuth.actions.clearRevoked")})}):null,lt&&qe.length===0&&st.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.state.loading")}):qe.length===0&&st.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.state.empty")}):s.jsxs(s.Fragment,{children:[st.map(U=>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:U.label||t("settings.remoteInstances.clientAuth.field.labelPlaceholder")}),U.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:()=>{ki(U.id)},children:t("settings.common.actions.cancel")})]},`pending-${U.id}`)),qe.map(U=>{const Ae=U.clientKind==="desktop-local",ct=U.lastUsedAt?Date.parse(U.lastUsedAt):Number.NaN,yt=!U.revokedAt&&(Ae||Number.isFinite(ct)&&Date.now()-ct<9e4),qt=U.revokedAt?t("settings.remoteInstances.clientAuth.state.revoked"):yt?U.lastTransport==="relay"&&!Ae?t("settings.remoteInstances.clientAuth.state.connectedRelay"):t("settings.remoteInstances.clientAuth.state.connectedDirect"):Number.isFinite(ct)?t("settings.remoteInstances.clientAuth.lastUsed",{date:Fp(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",U.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:U.label}),ed(U.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:ed(U.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&&!U.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:qt})]})}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{Lr(U)},disabled:!!U.revokedAt,children:t("settings.remoteInstances.clientAuth.actions.revoke")})]},U.id)})]})]}),Ce?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Ce}):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:()=>se(!0),disabled:ge,children:t("settings.remoteInstances.direct.import.action")}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>_e(!0),disabled:ge,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:re?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.direct.state.loading")}):ae.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.direct.state.empty")}):ae.map(U=>{const Ae=be[U.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:ei(U.label)}),pe===U.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",U.apiUrl&&"font-mono"),children:U.relay&&!U.apiUrl?t("mobile.connect.relay.badge"):ei(U.apiUrl||U.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:()=>{Dr(U.id)},disabled:ge||pe===U.id,"aria-label":t("desktopHostSwitcher.actions.setAsDefaultAria"),children:pe===U.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"})}),U.relay&&!U.apiUrl?null:s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>Qn(U),disabled:ge,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:()=>{ha(U.id)},disabled:ge,children:[s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.delete")]})]})]})},U.id)})}),Ve?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Ve}):null]}):null,a?s.jsx(Kt,{open:He,onOpenChange:_e,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:U=>{U.preventDefault(),En()},children:[s.jsx(nt,{className:"h-8",value:de,onChange:U=>le(U.target.value),placeholder:t("settings.remoteInstances.direct.field.labelPlaceholder"),disabled:ge}),s.jsx(nt,{className:"h-8",value:he,onChange:U=>De(U.target.value),placeholder:t("settings.remoteInstances.direct.field.urlPlaceholder"),disabled:ge,autoFocus:!0}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(nt,{className:"h-8",value:Le,onChange:U=>Ke(U.target.value),placeholder:t("settings.remoteInstances.direct.field.tokenPlaceholder"),type:"password",disabled:ge}),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(gn,{children:t("settings.remoteInstances.direct.headers.title")}),s.jsx($t,{children:t("settings.remoteInstances.direct.headers.description")})]}),Fe.map(U=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(nt,{className:"h-8 font-mono text-xs",value:U.name,onChange:Ae=>Me(ct=>ct.map(yt=>yt.id===U.id?{...yt,name:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.namePlaceholder"),disabled:ge}),s.jsx(nt,{className:"h-8 font-mono text-xs",value:U.value,onChange:Ae=>Me(ct=>ct.map(yt=>yt.id===U.id?{...yt,value:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.valuePlaceholder"),type:"password",disabled:ge}),s.jsx("button",{type:"button",onClick:()=>Me(Ae=>Ae.filter(ct=>ct.id!==U.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:ge,children:s.jsx(K,{name:"close",className:"h-4 w-4"})})]},U.id)),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>Me(U=>[...U,el()]),disabled:ge,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:()=>_e(!1),disabled:ge,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:ge||!he.trim(),children:t("settings.remoteInstances.direct.actions.add")})]})]})]})}):null,a?s.jsx(Kt,{open:!!ye,onOpenChange:U=>{U||ke(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:U=>{U.preventDefault(),Er()},children:[s.jsx(nt,{className:"h-8",value:ze,onChange:U=>$(U.target.value),placeholder:t("settings.remoteInstances.direct.field.labelPlaceholder"),disabled:ge}),s.jsx(nt,{className:"h-8",value:Ee,onChange:U=>J(U.target.value),placeholder:t("settings.remoteInstances.direct.field.urlPlaceholder"),disabled:ge,autoFocus:!0}),s.jsx(nt,{className:"h-8",value:v,onChange:U=>ue(U.target.value),placeholder:t("settings.remoteInstances.direct.field.tokenPlaceholder"),type:"password",disabled:ge}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(gn,{children:t("settings.remoteInstances.direct.headers.title")}),s.jsx($t,{children:t("settings.remoteInstances.direct.headers.description")})]}),Ne.map(U=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(nt,{className:"h-8 font-mono text-xs",value:U.name,onChange:Ae=>we(ct=>ct.map(yt=>yt.id===U.id?{...yt,name:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.namePlaceholder"),disabled:ge}),s.jsx(nt,{className:"h-8 font-mono text-xs",value:U.value,onChange:Ae=>we(ct=>ct.map(yt=>yt.id===U.id?{...yt,value:Ae.target.value}:yt)),placeholder:t("settings.remoteInstances.direct.headers.field.valuePlaceholder"),type:"password",disabled:ge}),s.jsx("button",{type:"button",onClick:()=>we(Ae=>Ae.filter(ct=>ct.id!==U.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:ge,children:s.jsx(K,{name:"close",className:"h-4 w-4"})})]},U.id)),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>we(U=>[...U,el()]),disabled:ge,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(null),disabled:ge,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:ge,children:t("settings.common.actions.saveChanges")})]})]})]})}):null,a?s.jsx(Kt,{open:Oe,onOpenChange:se,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:U=>{U.preventDefault(),Ks()},children:[s.jsx(nt,{className:"h-8",value:Be,onChange:U=>Ge(U.target.value),placeholder:t("settings.remoteInstances.direct.import.placeholder"),disabled:ge,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:()=>se(!1),disabled:ge,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:ge||!Be.trim(),children:t("settings.remoteInstances.direct.import.action")})]})]})]})}):null,s.jsx(Kt,{open:Re,onOpenChange:Ye,children:s.jsxs(Bt,{className:We==="result"?"sm:max-w-lg":"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(_t,{children:t(We==="result"?"settings.remoteInstances.clientAuth.qrDialogTitle":"settings.remoteInstances.clientAuth.actions.addDevice")}),s.jsx(Yt,{children:t(We==="result"?"settings.remoteInstances.clientAuth.qrScanHint":"settings.remoteInstances.clientAuth.addDevice.subtitle")})]}),We==="configure"?s.jsxs("form",{className:"space-y-4",onSubmit:U=>{U.preventDefault(),Mr()},children:[s.jsx(nt,{className:"h-8",value:bt,onChange:U=>Nt(U.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(U=>{const Ae=Ot===U.key;return s.jsxs("div",{className:fe("flex items-start gap-2 py-0.5",U.available?"cursor-pointer":"opacity-45"),onClick:()=>{U.available&&Zt(U.key)},role:"presentation",children:[s.jsx(Nr,{checked:Ae,disabled:!U.available,onChange:()=>Zt(U.key),ariaLabel:U.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:U.label}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:U.hint})]})]},U.key)})}),Ot==="lan"?s.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[s.jsx(rn,{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,Ot==="relay"&&Pt?.lanUrl?s.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[s.jsx(rn,{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]}),Ce?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Ce}):null,s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ye(!1),disabled:kt,children:t("settings.common.actions.cancel")}),s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:kt||!Pt,children:t("settings.remoteInstances.clientAuth.addDevice.create")})]})]}):s.jsxs("div",{className:"space-y-3",children:[Te?s.jsx("div",{className:"flex justify-center",children:s.jsx("img",{src:Te,alt:t("settings.remoteInstances.clientAuth.qrAlt"),className:"w-full max-w-[420px] rounded-md bg-white p-4"})}):null,tt?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:tt}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:Si,children:[s.jsx(K,{name:Pe?"check":"file-copy",className:fe("h-3.5 w-3.5",Pe&&"text-[var(--status-success)]")}),t(Pe?"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:()=>Ye(!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(U=>{const Ae=r[U.id],ct=U.nickname?.trim()||U.sshParsed?.destination||U.id,yt=Ae?.phase,qt=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 ${sd(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(td(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:()=>{(qt?y(U.id):k(U.id)).catch(us=>Q.error(t(qt?"settings.remoteInstances.sidebar.toast.disconnectFailed":"settings.remoteInstances.sidebar.toast.connectFailed"),{description:us instanceof Error?us.message:String(us)}))},children:[qt?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(qt?"settings.remoteInstances.sidebar.actions.disconnect":"settings.remoteInstances.sidebar.actions.connect")]}),s.jsxs(ee,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>j(U.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(U.id).catch(us=>Q.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")]})]})]},U.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:U=>{U.preventDefault(),ji()},children:[s.jsx(nt,{className:"h-8",value:Dt,onChange:U=>Vt(U.target.value),placeholder:t("settings.remoteInstances.page.field.nicknamePlaceholder"),disabled:p}),s.jsx(nt,{className:"h-8",value:ft,onChange:U=>vt(U.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(U=>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:[U.host,U.pattern?` ${t("settings.remoteInstances.page.import.patternSuffix")}`:""]}),s.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:U.sshCommand})]}),s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Br(U.host,U.pattern)},children:t("settings.common.actions.import")})]},`${U.source}:${U.host}`))})}):null,s.jsx(Kt,{open:!!H,onOpenChange:U=>{U||va()},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:U=>{U.preventDefault(),Ci()},children:[s.jsx(nt,{value:W,onChange:U=>A(U.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:va,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 Za=b.remoteOpenchamber.mode==="managed",Ai=b.nickname?.trim()||b.sshParsed?.destination||b.id;return s.jsx(Kt,{open:!!b,onOpenChange:U=>{U||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:`${Uo} truncate`,children:Ai}),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 ${sd(on)}`}),s.jsx("span",{children:t(td(on))}),Bs?.localUrl?s.jsx("span",{className:"font-mono text-foreground/80",children:Bs.localUrl}):null,ba?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:Je,disabled:_||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"}),Ti]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:ms,disabled:!Pi,children:[s.jsx(K,{name:"refresh",className:`h-3.5 w-3.5 ${Dn||xn&&!ba?"animate-spin":""}`}),Ii]}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{ka()},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(b.id).then(()=>{j(null),Q.success(t("settings.remoteInstances.page.toast.instanceRemoved"))}).catch(Ae=>{Q.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")]})]}),Bs?.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:Bs.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(nt,{className:"h-7 md:max-w-xl",value:b.sshCommand,onChange:U=>ys(Ae=>({...Ae,sshCommand:U.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(nt,{className:"h-7 md:max-w-sm",value:b.nickname||"",onChange:U=>ys(Ae=>({...Ae,nickname:U.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(Ms,{containerClassName:"w-fit",min:5,max:240,step:1,className:"w-16 tabular-nums",value:b.connectionTimeoutSec,onValueChange:U=>{ys(Ae=>({...Ae,connectionTimeoutSec:Number.isFinite(U)?U: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(vn,{label:t("settings.remoteInstances.page.field.mode"),hint:t("settings.remoteInstances.page.field.modeHint")})}),s.jsxs(Mt,{value:b.remoteOpenchamber.mode,onValueChange:U=>ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,mode:U==="external"?"external":"managed"}})),children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.modePlaceholder")})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"managed",children:t("settings.remoteInstances.page.field.modeManaged")}),s.jsx(jt,{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(vn,{label:t("settings.remoteInstances.page.field.preferredRemotePort"),hint:t("settings.remoteInstances.page.field.preferredRemotePortHint")})}),s.jsx(Ms,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:b.remoteOpenchamber.preferredPort,onValueChange:U=>{ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,preferredPort:Number.isFinite(U)&&U>0?U:void 0}}))},onClear:()=>{ys(U=>({...U,remoteOpenchamber:{...U.remoteOpenchamber,preferredPort:void 0}}))},emptyLabel:t("settings.remoteInstances.page.field.auto")})]}),Za?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(vn,{label:t("settings.remoteInstances.page.field.installMethod"),hint:t("settings.remoteInstances.page.field.installMethodHint")})}),s.jsxs(Mt,{value:b.remoteOpenchamber.installMethod,onValueChange:U=>ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,installMethod:U==="npm"||U==="download_release"||U==="upload_bundle"?U:"bun"}})),children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.selectInstallMethodPlaceholder")})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"bun",children:"bun"}),s.jsx(jt,{value:"npm",children:"npm"}),s.jsx(jt,{value:"download_release",children:t("settings.remoteInstances.page.field.installMethodDownloadRelease")}),s.jsx(jt,{value:"upload_bundle",children:t("settings.remoteInstances.page.field.installMethodUploadBundle")})]})]})]}):null,Za?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(vn,{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(hr,{checked:b.remoteOpenchamber.keepRunning,onCheckedChange:U=>ys(Ae=>({...Ae,remoteOpenchamber:{...Ae.remoteOpenchamber,keepRunning:U}}))})})]}):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(vn,{label:t("settings.remoteInstances.page.field.bindHost"),hint:t("settings.remoteInstances.page.field.bindHostHint")})}),s.jsxs(Mt,{value:b.localForward.bindHost,onValueChange:U=>{U==="0.0.0.0"&&!window.confirm(t("settings.remoteInstances.page.confirm.bindAllInterfaces"))||ys(Ae=>({...Ae,localForward:{...Ae.localForward,bindHost:U==="localhost"||U==="0.0.0.0"?U:"127.0.0.1"}}))},children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.selectBindHostPlaceholder")})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"127.0.0.1",children:"127.0.0.1"}),s.jsx(jt,{value:"localhost",children:"localhost"}),s.jsx(jt,{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(vn,{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(Ms,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:b.localForward.preferredLocalPort,onValueChange:U=>{ys(Ae=>({...Ae,localForward:{...Ae.localForward,preferredLocalPort:Number.isFinite(U)&&U>0?U:void 0}}))},onClear:()=>{ys(U=>({...U,localForward:{...U.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(U=>({...U,localForward:{...U.localForward,preferredLocalPort:Zo()}})),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(nt,{className:"h-7 md:max-w-sm",type:"password",value:b.auth.sshPassword?.value||"",onChange:U=>ys(Ae=>({...Ae,auth:{...Ae.auth,sshPassword:{enabled:U.target.value.trim().length>0,value:U.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(nt,{className:"h-7 md:max-w-sm",type:"password",value:b.auth.openchamberPassword?.value||"",onChange:U=>ys(Ae=>({...Ae,auth:{...Ae.auth,openchamberPassword:{enabled:U.target.value.trim().length>0,value:U.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:[b.portForwards.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground/80",children:t("settings.remoteInstances.page.empty.noExtraForwards")}):null,b.portForwards.map((U,Ae)=>{const ct=Rt=>{ys(cs=>({...cs,portForwards:cs.portForwards.map((Zn,Ht)=>Ht===Ae?Rt(Zn):Zn)}))},yt=U.type==="remote"?"Local target":"Local listen",qt=U.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.",_s=U.type==="remote"?"Remote listen":"Remote target",us=U.type==="remote"?"Remote host and port where SSH creates the -R listener.":"Remote host and port that receives traffic from local -L listener.",qs=nd(U.localHost||"localhost",U.localPort),Us=nd(U.remoteHost||"localhost",U.remotePort),Ls=U.type==="local"&&typeof U.localPort=="number"&&U.localPort>0,ln=Ls?`http://${aw(U.localHost)}:${U.localPort}`:"",cn=!!E[U.id],Xn=U.type==="local"?t("settings.remoteInstances.page.forwardType.local"):U.type==="remote"?t("settings.remoteInstances.page.forwardType.remote"):t("settings.remoteInstances.page.forwardType.dynamic");return s.jsxs(da,{open:cn,onOpenChange:Rt=>{P(cs=>({...cs,[U.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(ua,{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 ${cn?"rotate-180":""}`}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:ew(U)}),s.jsx("span",{className:"typography-micro text-muted-foreground/70 shrink-0",children:Xn})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(hr,{checked:U.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!==U.id)})),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})]}),s.jsx(ma,{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(vn,{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(nw(U.type))})]})})}),s.jsxs(Mt,{value:U.type,onValueChange:Rt=>ct(cs=>({...cs,type:Rt==="dynamic"||Rt==="remote"?Rt:"local"})),children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Wt,{placeholder:t("settings.remoteInstances.page.field.typePlaceholder")})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"local",children:t("settings.remoteInstances.page.forwardType.local")}),s.jsx(jt,{value:"remote",children:t("settings.remoteInstances.page.forwardType.remote")}),s.jsx(jt,{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(vn,{label:yt,hint:qt})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(nt,{className:"h-7 w-32",value:U.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(Ms,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:U.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")})]})]}),U.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(vn,{label:_s,hint:us})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(nt,{className:"h-7 w-32",value:U.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(Ms,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:U.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:U.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:qs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.localSocks5")})]}):U.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:Us}),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:qs}),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:qs}),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:Us}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.remote")})]})}),Ls?s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Hn(ln).then(Rt=>{Rt||Q.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]})]})})]},U.id)}),s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal mt-1",onClick:()=>{const U=tw();ys(Ae=>({...Ae,portForwards:[...Ae.portForwards,U]})),P(Ae=>({...Ae,[U.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:()=>{Kr()},disabled:!zr||p,children:t("settings.common.actions.saveChanges")}),Bs?.localUrl?s.jsxs(s.Fragment,{children:[s.jsxs(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{oa(Bs.localUrl||"").then(U=>{U.ok&&Q.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:()=>{Na()},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:B,onOpenChange:T,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:b?.nickname?.trim()||b?.sshParsed?.destination||b?.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:Qa,disabled:D||!bn.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:()=>{Xa()},disabled:D,children:[s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.clear")]})]}),D?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:z.length>0?z.join(`
|
|
34
|
+
`):t("settings.remoteInstances.page.logsDialog.empty")})]})}),s.jsx(Kt,{open:!!H,onOpenChange:U=>{U||va()},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:U=>{U.preventDefault(),Ci()},children:[s.jsx(nt,{value:W,onChange:U=>A(U.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:va,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")})]})]})]})})]})})},uw="__add_provider__",mw=()=>{const t=Ps.getDirectory();return typeof t=="string"&&t.trim().length>0?t.trim():null},pw=({onItemSelect:t})=>{const{t:e}=ot(),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(()=>mw(),[r]);l.useEffect(()=>{if(n.length===0){d({});return}let m=!1;return(async()=>{const h=n.map(async f=>{try{const x=c?`?directory=${encodeURIComponent(c)}`:"",k=await ht(`/api/provider/${encodeURIComponent(f.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(O=>({...O,[f.id]:C}))}catch{}});await Promise.all(h)})(),()=>{m=!0}},[c,n]);const p="bg-background",u=l.useMemo(()=>n.filter(m=>!!o[m.id]?.project?.exists),[n,o]),g=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:`${hn} mb-3`,children:e("settings.providers.sidebar.title")}),s.jsx(wi,{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(uw),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(zs,{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:[g.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")}),g.map(m=>s.jsx(id,{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",g.length>0?"pt-3":"pt-2"),children:e("settings.providers.sidebar.section.projectProviders")}),u.map(m=>s.jsx(id,{provider:m,selectedProviderId:a,onSelect:()=>{i(m.id),t?.()}},m.id))]})]})})]})},id=t=>{const e=Ze.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(ra,{providerId:n.id,className:"h-4 w-4 flex-shrink-0"}),e[2]=n.id,e[3]=u):u=e[3];const g=n.name||n.id;let m;e[4]!==g?(m=s.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:g}),e[4]=g,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 h;e[8]!==i||e[9]!==u||e[10]!==m||e[11]!==w?(h=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]=h):h=e[12];let f;return e[13]!==n.id||e[14]!==p||e[15]!==h?(f=s.jsx("div",{className:p,children:h},d),e[13]=n.id,e[14]=p,e[15]=h,e[16]=f):f=e[16],f},gw=t=>t,rd=t=>typeof t=="object"&&t!==null,nm=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()},fw=t=>{if(!rd(t))return{};const e={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&(e[n]=a.filter(i=>rd(i)));return e},od=t=>t.length===0?!0:t.some(e=>nm(e)==="api"),ld=t=>t.map((e,n)=>({method:e,methodIndex:n})).filter(({method:e})=>nm(e)==="oauth"),am="@ai-sdk/openai-compatible",aa="__custom_provider__",hw=/^[a-z0-9][a-z0-9-_]*$/,im=/^https?:\/\//,xw=/^\{env:([^}]+)\}$/;let bw=0;const xr=()=>`row-${bw++}`,hl=()=>({row:xr(),id:"",name:""}),xl=()=>({row:xr(),key:"",value:""}),yw=()=>({providerID:"",name:"",baseURL:"",apiKey:"",models:[hl()],headers:[xl()]});function vw(t){const e=t.trim();if(!e)return{};const a=e.match(xw)?.[1]?.trim();return a?{env:a}:{key:e}}function ww(t){const e=t.options&&typeof t.options=="object"?t.options:null,n=typeof e?.baseURL=="string"?e.baseURL.trim():"";return n&&im.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===am})}function jw(t,e){return e?!!(e.user?.exists||e.project?.exists||e.custom?.exists)&&ww(t):!1}function cd(t){return t?.custom?.exists?"custom":t?.project?.exists?"project":"user"}function kw(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:xr(),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:xr(),id:typeof c?.id=="string"?c.id:"",name:typeof c?.name=="string"?c.name:typeof c?.id=="string"?c.id:""})):[hl()],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:[xl()]}}function Nw(t){const e=t.form.providerID.trim(),n=t.form.name.trim(),a=t.form.baseURL.trim(),{env:i,key:r}=vw(t.form.apiKey),o=t.disabledProviders??[],d=t.editingProviderID?.trim(),c=e?hw.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?im.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),f=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(T=>{const D=T.id.trim(),S=D?x.has(D)?t.t("settings.providers.page.custom.error.duplicate"):void x.add(D):t.t("settings.providers.page.custom.error.required"),F=T.name.trim()?void 0:t.t("settings.providers.page.custom.error.required");return{id:S,name:F}}),y=k.every(T=>!T.id&&!T.name),C=Object.fromEntries(t.form.models.map(T=>[T.id.trim(),{name:T.name.trim()}])),O=new Set,j=t.form.headers.map(T=>{const D=T.key.trim(),S=T.value.trim();if(!D&&!S)return{};const F=D?O.has(D.toLowerCase())?t.t("settings.providers.page.custom.error.duplicate"):void O.add(D.toLowerCase()):t.t("settings.providers.page.custom.error.required"),R=S?void 0:t.t("settings.providers.page.custom.error.required");return{key:F,value:R}}),N=j.every(T=>!T.key&&!T.value),b=Object.fromEntries(t.form.headers.map(T=>({key:T.key.trim(),value:T.value.trim()})).filter(T=>T.key&&T.value).map(T=>[T.key,T.value])),I={providerID:c??f,name:p,baseURL:u,apiKey:m};return!c&&!f&&!p&&!u&&!m&&y&&N?{err:I,models:k,headers:j,result:{providerID:e,name:n,apiKey:r,config:{npm:am,name:n,...i?{env:[i]}:{},options:{baseURL:a,...Object.keys(b).length>0?{headers:b}:{}},models:C}}}:{err:I,models:k,headers:j}}function Sw(t){return t.apiKey?{providerID:t.providerID,auth:{type:"api",key:t.apiKey}}:null}function Cw(t,e){return{providerID:t.providerID,config:t.config,scope:e?.scope??"user"}}const dd=t=>{const e=Ze.c(198),{existingProviderIDs:n,disabledProviders:a,busy:i,mode:r,initialValues:o,allowExistingAuth:d,authFailureHint:c,onSubmit:p,onCancel:u,onDisconnect:g}=t;let m;e[0]!==a?(m=a===void 0?[]:a,e[0]=a,e[1]=m):m=e[1];const w=m,h=i===void 0?!1:i,f=r===void 0?"create":r,x=d===void 0?!1:d,k=c===void 0?null:c,{t:y}=ot(),C=f==="edit";let O;e[2]!==o?(O=()=>o??yw(),e[2]=o,e[3]=O):O=e[3];const[j,N]=l.useState(O);let b;e[4]===Symbol.for("react.memo_cache_sentinel")?(b={},e[4]=b):b=e[4];const[I,B]=l.useState(b);let T;e[5]===Symbol.for("react.memo_cache_sentinel")?(T=[],e[5]=T):T=e[5];const[D,S]=l.useState(T);let F;e[6]===Symbol.for("react.memo_cache_sentinel")?(F=[],e[6]=F):F=e[6];const[R,z]=l.useState(F),q=l.useRef(null);let H,Z;e[7]!==o||e[8]!==C?(H=()=>{o&&(C&&q.current===o.providerID||(q.current=C?o.providerID:null,N(o),B({}),S([]),z([])))},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 W;e[11]===Symbol.for("react.memo_cache_sentinel")?(W=(St,Pt)=>{N(Se=>({...Se,[St]:Pt})),B(Se=>({...Se,[St]:void 0}))},e[11]=W):W=e[11];const A=W;let X;e[12]===Symbol.for("react.memo_cache_sentinel")?(X=(St,Pt,Se)=>{N(ut=>({...ut,models:ut.models.map((mt,At)=>At===St?{...mt,[Pt]:Se}: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 E;e[13]===Symbol.for("react.memo_cache_sentinel")?(E=(St,Pt,Se)=>{N(ut=>({...ut,headers:ut.headers.map((mt,At)=>At===St?{...mt,[Pt]:Se}:mt)})),z(ut=>{const mt=[...ut];return mt[St]={...mt[St]??{},[Pt]:void 0},mt})},e[13]=E):E=e[13];const P=E;let _;e[14]!==x||e[15]!==h||e[16]!==w||e[17]!==n||e[18]!==j||e[19]!==C||e[20]!==p||e[21]!==y?(_=async St=>{if(St.preventDefault(),h)return;const Pt=Nw({form:j,t:((Se,ut)=>y(Se,ut)),existingProviderIDs:n,disabledProviders:w,editingProviderID:C?j.providerID:void 0,allowExistingAuth:C&&x});B(Pt.err),S(Pt.models),z(Pt.headers),Pt.result&&await p(Pt.result)},e[14]=x,e[15]=h,e[16]=w,e[17]=n,e[18]=j,e[19]=C,e[20]=p,e[21]=y,e[22]=_):_=e[22];const L=_;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 Y;e[26]!==y?(Y=y("settings.providers.page.custom.description"),e[26]=y,e[27]=Y):Y=e[27];let G;e[28]!==Y?(G=s.jsx("p",{className:Ys,children:Y}),e[28]=Y,e[29]=G):G=e[29];let me;e[30]!==k?(me=k?s.jsx("p",{className:"typography-meta text-[var(--status-warning)]",role:"status",children:k}):null,e[30]=k,e[31]=me):me=e[31];let ae;e[32]!==y?(ae=y("settings.providers.page.custom.field.providerID.label"),e[32]=y,e[33]=ae):ae=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 be=j.providerID;let ie;e[36]===Symbol.for("react.memo_cache_sentinel")?(ie=St=>A("providerID",St.target.value),e[36]=ie):ie=e[36];let pe;e[37]!==y?(pe=y("settings.providers.page.custom.field.providerID.placeholder"),e[37]=y,e[38]=pe):pe=e[38];const Ie=!C,re=C||h,ce=!!I.providerID;let ge;e[39]!==y?(ge=y("settings.providers.page.custom.field.providerID.label"),e[39]=y,e[40]=ge):ge=e[40];let oe;e[41]!==j.providerID||e[42]!==pe||e[43]!==Ie||e[44]!==re||e[45]!==ce||e[46]!==ge?(oe=s.jsx(nt,{value:be,onChange:ie,placeholder:pe,className:"h-8 rounded-md px-3 font-mono text-xs",autoFocus:Ie,disabled:re,"aria-invalid":ce,"aria-label":ge}),e[41]=j.providerID,e[42]=pe,e[43]=Ie,e[44]=re,e[45]=ce,e[46]=ge,e[47]=oe):oe=e[47];let de;e[48]!==I.providerID?(de=I.providerID?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:I.providerID}):null,e[48]=I.providerID,e[49]=de):de=e[49];let le;e[50]!==ae||e[51]!==xe||e[52]!==oe||e[53]!==de?(le=s.jsxs(ns,{label:ae,info:xe,children:[oe,de]}),e[50]=ae,e[51]=xe,e[52]=oe,e[53]=de,e[54]=le):le=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 De;e[57]!==y?(De=y("settings.providers.page.custom.field.name.info"),e[57]=y,e[58]=De):De=e[58];const Le=j.name;let Ke;e[59]===Symbol.for("react.memo_cache_sentinel")?(Ke=St=>A("name",St.target.value),e[59]=Ke):Ke=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 Me=!!I.name;let Be;e[62]!==y?(Be=y("settings.providers.page.custom.field.name.label"),e[62]=y,e[63]=Be):Be=e[63];let Ge;e[64]!==j.name||e[65]!==Fe||e[66]!==Me||e[67]!==Be?(Ge=s.jsx(nt,{value:Le,onChange:Ke,placeholder:Fe,className:"h-8 rounded-md px-3","aria-invalid":Me,"aria-label":Be}),e[64]=j.name,e[65]=Fe,e[66]=Me,e[67]=Be,e[68]=Ge):Ge=e[68];let Ve;e[69]!==I.name?(Ve=I.name?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:I.name}):null,e[69]=I.name,e[70]=Ve):Ve=e[70];let Ue;e[71]!==he||e[72]!==De||e[73]!==Ge||e[74]!==Ve?(Ue=s.jsxs(ns,{label:he,info:De,children:[Ge,Ve]}),e[71]=he,e[72]=De,e[73]=Ge,e[74]=Ve,e[75]=Ue):Ue=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 _e;e[78]!==y?(_e=y("settings.providers.page.custom.field.baseURL.info"),e[78]=y,e[79]=_e):_e=e[79];const Oe=j.baseURL;let se;e[80]===Symbol.for("react.memo_cache_sentinel")?(se=St=>A("baseURL",St.target.value),e[80]=se):se=e[80];let ye;e[81]!==y?(ye=y("settings.providers.page.custom.field.baseURL.placeholder"),e[81]=y,e[82]=ye):ye=e[82];const ke=!!I.baseURL;let ze;e[83]!==y?(ze=y("settings.providers.page.custom.field.baseURL.label"),e[83]=y,e[84]=ze):ze=e[84];let $;e[85]!==j.baseURL||e[86]!==ye||e[87]!==ke||e[88]!==ze?($=s.jsx(nt,{value:Oe,onChange:se,placeholder:ye,className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":ke,"aria-label":ze}),e[85]=j.baseURL,e[86]=ye,e[87]=ke,e[88]=ze,e[89]=$):$=e[89];let Ee;e[90]!==I.baseURL?(Ee=I.baseURL?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:I.baseURL}):null,e[90]=I.baseURL,e[91]=Ee):Ee=e[91];let J;e[92]!==He||e[93]!==_e||e[94]!==$||e[95]!==Ee?(J=s.jsxs(ns,{label:He,info:_e,children:[$,Ee]}),e[92]=He,e[93]=_e,e[94]=$,e[95]=Ee,e[96]=J):J=e[96];let v;e[97]!==y?(v=y("settings.providers.page.custom.field.apiKey.label"),e[97]=y,e[98]=v):v=e[98];let ue;e[99]!==x||e[100]!==C||e[101]!==y?(ue=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]=ue):ue=e[102];const Ne=j.apiKey;let we;e[103]===Symbol.for("react.memo_cache_sentinel")?(we=St=>A("apiKey",St.target.value),e[103]=we):we=e[103];let qe;e[104]!==x||e[105]!==C||e[106]!==y?(qe=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]=qe):qe=e[107];const it=!!I.apiKey;let st;e[108]!==y?(st=y("settings.providers.page.custom.field.apiKey.label"),e[108]=y,e[109]=st):st=e[109];let rt;e[110]!==j.apiKey||e[111]!==qe||e[112]!==it||e[113]!==st?(rt=s.jsx(nt,{type:"password",value:Ne,onChange:we,placeholder:qe,className:"h-8 rounded-md px-3 font-mono text-xs","aria-invalid":it,"aria-label":st}),e[110]=j.apiKey,e[111]=qe,e[112]=it,e[113]=st,e[114]=rt):rt=e[114];let lt;e[115]!==I.apiKey?(lt=I.apiKey?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:I.apiKey}):null,e[115]=I.apiKey,e[116]=lt):lt=e[116];let xt;e[117]!==v||e[118]!==ue||e[119]!==rt||e[120]!==lt?(xt=s.jsxs(ns,{label:v,info:ue,children:[rt,lt]}),e[117]=v,e[118]=ue,e[119]=rt,e[120]=lt,e[121]=xt):xt=e[121];let bt;e[122]!==V||e[123]!==G||e[124]!==me||e[125]!==le||e[126]!==Ue||e[127]!==J||e[128]!==xt?(bt=s.jsxs(dt,{title:V,divider:!1,settingsItem:"providers.custom",contentClassName:Bn,children:[G,me,le,Ue,J,xt]}),e[122]=V,e[123]=G,e[124]=me,e[125]=le,e[126]=Ue,e[127]=J,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 Ce;if(e[132]!==j.models||e[133]!==D||e[134]!==y){let St;e[136]!==j.models.length||e[137]!==D||e[138]!==y?(St=(Pt,Se)=>s.jsx("div",{className:`${$s} 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(nt,{value:Pt.id,onChange:ut=>te(Se,"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")}),D[Se]?.id?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:D[Se]?.id}):null]}),s.jsxs("div",{children:[s.jsx("label",{className:zt,children:y("settings.providers.page.custom.models.nameLabel")}),s.jsx(nt,{value:Pt.name,onChange:ut=>te(Se,"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")}),D[Se]?.name?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:D[Se]?.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!==Se)})),S(ut=>ut.filter((mt,At)=>At!==Se)))},"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]=D,e[138]=y,e[139]=St):St=e[139],Ce=j.models.map(St),e[132]=j.models,e[133]=D,e[134]=y,e[135]=Ce}else Ce=e[135];let Qe;e[140]===Symbol.for("react.memo_cache_sentinel")?(Qe=()=>{N(Iw),S(Pw)},e[140]=Qe):Qe=e[140];let tt;e[141]!==y?(tt=y("settings.providers.page.custom.models.add"),e[141]=y,e[142]=tt):tt=e[142];let at;e[143]!==tt?(at=s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Qe,children:tt}),e[143]=tt,e[144]=at):at=e[144];let gt;e[145]!==Nt||e[146]!==Ce||e[147]!==at?(gt=s.jsxs(dt,{title:Nt,contentClassName:Bn,children:[Ce,at]}),e[145]=Nt,e[146]=Ce,e[147]=at,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 Te;e[151]!==y?(Te=y("settings.providers.page.custom.headers.description"),e[151]=y,e[152]=Te):Te=e[152];let ne;e[153]!==Te?(ne=s.jsx("p",{className:Ys,children:Te}),e[153]=Te,e[154]=ne):ne=e[154];let Pe;if(e[155]!==j.headers||e[156]!==R||e[157]!==y){let St;e[159]!==j.headers.length||e[160]!==R||e[161]!==y?(St=(Pt,Se)=>s.jsx("div",{className:`${$s} 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(nt,{value:Pt.key,onChange:ut=>P(Se,"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")}),R[Se]?.key?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:R[Se]?.key}):null]}),s.jsxs("div",{children:[s.jsx("label",{className:zt,children:y("settings.providers.page.custom.headers.valueLabel")}),s.jsx(nt,{value:Pt.value,onChange:ut=>P(Se,"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")}),R[Se]?.value?s.jsx("p",{className:"mt-1 typography-meta text-[var(--status-error)]",children:R[Se]?.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!==Se)})),z(ut=>ut.filter((mt,At)=>At!==Se)))},"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]=R,e[161]=y,e[162]=St):St=e[162],Pe=j.headers.map(St),e[155]=j.headers,e[156]=R,e[157]=y,e[158]=Pe}else Pe=e[158];let Xe;e[163]===Symbol.for("react.memo_cache_sentinel")?(Xe=()=>{N(Tw),z(Aw)},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 Ye;e[166]!==Re?(Ye=s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Xe,children:Re}),e[166]=Re,e[167]=Ye):Ye=e[167];let We;e[168]!==wt||e[169]!==ne||e[170]!==Pe||e[171]!==Ye?(We=s.jsxs(dt,{title:wt,contentClassName:Bn,children:[ne,Pe,Ye]}),e[168]=wt,e[169]=ne,e[170]=Pe,e[171]=Ye,e[172]=We):We=e[172];let et;e[173]!==h||e[174]!==u||e[175]!==y?(et=u?s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:u,disabled:h,children:y("settings.providers.page.custom.actions.back")}):null,e[173]=h,e[174]=u,e[175]=y,e[176]=et):et=e[176];let kt;e[177]!==h||e[178]!==g||e[179]!==y?(kt=g?s.jsx(ee,{type:"button",variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>{g()},disabled:h,children:y("settings.providers.page.actions.disconnect")}):null,e[177]=h,e[178]=g,e[179]=y,e[180]=kt):kt=e[180];let Et;e[181]!==h||e[182]!==C||e[183]!==y?(Et=y(h?"settings.providers.page.actions.saving":C?"settings.providers.page.custom.actions.update":"settings.providers.page.custom.actions.save"),e[181]=h,e[182]=C,e[183]=y,e[184]=Et):Et=e[184];let Ot;e[185]!==h||e[186]!==Et?(Ot=s.jsx(ee,{type:"submit",size:"xs",className:"!font-normal",disabled:h,children:Et}),e[185]=h,e[186]=Et,e[187]=Ot):Ot=e[187];let Zt;e[188]!==et||e[189]!==kt||e[190]!==Ot?(Zt=s.jsxs("div",{className:"flex flex-wrap items-center gap-2 py-4",children:[et,kt,Ot]}),e[188]=et,e[189]=kt,e[190]=Ot,e[191]=Zt):Zt=e[191];let Qt;return e[192]!==L||e[193]!==bt||e[194]!==gt||e[195]!==We||e[196]!==Zt?(Qt=s.jsxs("form",{onSubmit:L,className:"space-y-0",children:[bt,gt,We,Zt]}),e[192]=L,e[193]=bt,e[194]=gt,e[195]=We,e[196]=Zt,e[197]=Qt):Qt=e[197],Qt};function Iw(t){return{...t,models:[...t.models,hl()]}}function Pw(t){return[...t,{}]}function Tw(t){return{...t,headers:[...t.headers,xl()]}}function Aw(t){return[...t,{}]}const Ew=/[A-Z0-9]{4}-[A-Z0-9]{4,5}/,ga=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Rs=t=>typeof t=="string"&&t.length>0?t:void 0,Dw=t=>{if(!Array.isArray(t))return[];const e=[];for(const n of t){if(!ga(n))continue;const a=Rs(n.value);a!==void 0&&e.push({value:a,label:Rs(n.label)??a,...Rs(n.hint)?{hint:Rs(n.hint)}:{}})}return e},Rw=t=>{if(!ga(t))return;const e=Rs(t.key),n=t.op==="eq"||t.op==="neq"?t.op:void 0;if(!(!e||!n||typeof t.value!="string"))return{key:e,op:n,value:t.value}},Mw=t=>{if(!Array.isArray(t))return[];const e=[];for(const n of t){if(!ga(n))continue;const a=Rs(n.key);if(!a)continue;const i=n.type==="select"?"select":"text",r=i==="select"?Dw(n.options):[];if(i==="select"&&r.length===0)continue;const o=Rw(n.when);e.push({type:i,key:a,message:Rs(n.message)??a,options:r,...Rs(n.placeholder)?{placeholder:Rs(n.placeholder)}:{},...o?{when:o}:{}})}return e},Lw=(t,e)=>{if(!t.when)return!0;const n=e[t.when.key]??"";return t.when.op==="eq"?n===t.when.value:n!==t.when.value},bl=(t,e)=>t.filter(n=>Lw(n,e)),Fw=t=>{const e={};for(const n of t)e[n.key]=n.type==="select"?n.options[0]?.value??"":"";return e},Ow=(t,e)=>bl(t,e).find(n=>(e[n.key]??"").trim().length===0)??null,zw=(t,e)=>{const n={};for(const a of bl(t,e))n[a.key]=(e[a.key]??"").trim();return n},Kw=t=>{const e=ga(t)?t:{},n=ga(e.data)?e.data:e,a=Rs(n.url)??Rs(n.verification_uri_complete)??Rs(n.verification_uri),i=Rs(n.instructions)??Rs(n.message);if(!a&&!i)return null;const r=Rs(n.user_code)??Rs(n.userCode)??(i?Ew.exec(i)?.[0]:void 0);return{method:n.method==="code"?"code":"auto",...a?{url:a}:{},...i?{instructions:i}:{},...r?{userCode:r}:{}}},ud=(t,e,n)=>{const a=ga(t)?t:{},i=ga(a.data)?a.data:{};switch(a.name){case"ProviderAuthOauthMissing":return e("settings.providers.page.auth.oauth.error.sessionExpired");case"ProviderAuthOauthCodeMissing":return e("settings.providers.page.auth.oauth.error.codeRequired");case"ProviderAuthOauthCallbackFailed":return e("settings.providers.page.auth.oauth.error.declined");case"ProviderAuthValidationFailed":return Rs(i.message)??e("settings.providers.page.auth.oauth.error.invalidInput");default:return e(n)}},oo={phase:"idle"},md=({providerId:t,methods:e,onConnected:n,className:a})=>{const{t:i}=ot(),[r,o]=l.useState(oo),[d,c]=l.useState({}),[p,u]=l.useState(""),g=l.useRef(null);l.useEffect(()=>()=>g.current?.abort(),[]);const m=r.phase==="idle"?null:r.methodIndex,w=r.phase==="authorizing"||r.phase==="waiting"||r.phase==="awaitingCode"&&r.submitting,h=async(b,I,B)=>{const T=await oa(b);if(T.ok){Q.success(i(I));return}console.error("Failed to copy OAuth value:",T.error),Q.error(i(B))},f=async(b,I)=>{const B=new AbortController;g.current?.abort(),g.current=B;try{const T=await Ps.getSdkClient().provider.oauth.callback({providerID:t,method:b,...I?{code:I}:{}},{signal:B.signal});if(B.signal.aborted)return;if(T.error)throw T.error;o(oo),Q.success(i("settings.providers.page.toast.oauthCompleted")),await n()}catch(T){if(B.signal.aborted)return;console.error("Failed to complete OAuth flow:",T),o({phase:"failed",methodIndex:b,message:ud(T,i,"settings.providers.page.toast.oauthCompleteFailed")})}finally{g.current===B&&(g.current=null)}},x=async(b,I)=>{o({phase:"authorizing",methodIndex:b});let B;try{const T=await Ps.getSdkClient().provider.oauth.authorize({providerID:t,method:b,...Object.keys(I).length>0?{inputs:I}:{}});if(T.error)throw T.error;const D=Kw(T.data);if(!D){o({phase:"failed",methodIndex:b,message:i("settings.providers.page.toast.oauthDetailsMissing")});return}B=D}catch(T){console.error("Failed to start OAuth flow:",T),o({phase:"failed",methodIndex:b,message:ud(T,i,"settings.providers.page.toast.oauthStartFailed")});return}if(B.url&&Hn(B.url),B.method==="code"){u(""),o({phase:"awaitingCode",methodIndex:b,authorization:B,submitting:!1});return}o({phase:"waiting",methodIndex:b,authorization:B}),await f(b)},k=b=>{const I=Mw(b.prompts);if(I.length===0){x(b.index,{});return}c(Fw(I)),o({phase:"prompting",methodIndex:b.index,prompts:I,error:null})},y=()=>{if(r.phase!=="prompting")return;const b=Ow(r.prompts,d);if(b){o({...r,error:i("settings.providers.page.auth.oauth.promptRequired",{field:b.message})});return}x(r.methodIndex,zw(r.prompts,d))},C=()=>{if(r.phase!=="awaitingCode")return;const b=p.trim();b&&(o({...r,submitting:!0}),f(r.methodIndex,b))},O=()=>{g.current?.abort(),g.current=null,o(oo)},j=b=>{const I=d[b.key]??"",B=T=>c(D=>({...D,[b.key]:T}));return s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("label",{className:"typography-ui-label text-foreground",children:b.message}),b.type==="select"?s.jsxs(Mt,{value:I,onValueChange:B,children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{children:T=>b.options.find(D=>D.value===T)?.label??null})}),s.jsx(Ft,{children:b.options.map(T=>s.jsx(jt,{value:T.value,children:T.hint?`${T.label} · ${T.hint}`:T.label},T.value))})]}):s.jsx(nt,{value:I,onChange:T=>B(T.target.value),placeholder:b.placeholder,className:"max-w-[24rem] text-xs"})]},b.key)},N=b=>s.jsxs(s.Fragment,{children:[b.instructions&&s.jsx("p",{className:"typography-meta text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-2 py-1.5 rounded",children:b.instructions}),b.userCode&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nt,{value:b.userCode,readOnly:!0,"aria-label":i("settings.providers.page.auth.oauth.deviceCodeLabel"),className:"font-mono text-center tracking-widest"}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:()=>{h(b.userCode??"","settings.providers.page.toast.deviceCodeCopied","settings.providers.page.toast.deviceCodeCopyFailed")},children:i("settings.providers.page.actions.copyCode")})]}),b.url&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nt,{value:b.url,readOnly:!0,"aria-label":i("settings.providers.page.auth.oauth.linkLabel"),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:()=>{Hn(b.url??"")},children:i("settings.providers.page.actions.open")}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{h(b.url??"","settings.providers.page.toast.oauthLinkCopied","settings.providers.page.toast.oauthLinkCopyFailed")},children:i("settings.providers.page.actions.copy")})]})]})]});return s.jsx("div",{className:fe("space-y-4",a),children:e.map(b=>{const I=m===b.index;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:b.label}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:()=>k(b),disabled:w,children:i("settings.providers.page.actions.connect")})]}),I&&r.phase==="prompting"&&s.jsxs("div",{className:"space-y-3",children:[bl(r.prompts,d).map(j),r.error&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:r.error}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ee,{size:"xs",className:"!font-normal",onClick:y,children:i("settings.providers.page.actions.continue")}),s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:O,children:i("settings.providers.page.actions.cancel")})]})]}),I&&r.phase==="authorizing"&&s.jsxs("p",{className:"typography-meta text-muted-foreground flex items-center gap-2",children:[s.jsx(K,{name:"loader",className:"h-3.5 w-3.5 animate-spin"}),i("settings.providers.page.auth.oauth.starting")]}),I&&r.phase==="waiting"&&s.jsxs("div",{className:"space-y-3",children:[N(r.authorization),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("p",{className:"typography-meta text-muted-foreground flex items-center gap-2",children:[s.jsx(K,{name:"loader",className:"h-3.5 w-3.5 animate-spin"}),i("settings.providers.page.auth.oauth.waiting")]}),s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal shrink-0",onClick:O,children:i("settings.providers.page.actions.cancel")})]}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:i("settings.providers.page.auth.oauth.waitingHint")})]}),I&&r.phase==="awaitingCode"&&s.jsxs("div",{className:"space-y-3",children:[N(r.authorization),s.jsx("p",{className:"typography-meta text-muted-foreground",children:i("settings.providers.page.auth.oauth.codeHint")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nt,{value:p,onChange:B=>u(B.target.value),placeholder:i("settings.providers.page.auth.pasteAuthorizationCodePlaceholder"),className:"font-mono text-xs",disabled:r.submitting}),s.jsx(ee,{size:"xs",className:"!font-normal shrink-0",onClick:C,disabled:r.submitting||p.trim().length===0,children:r.submitting?i("settings.providers.page.actions.saving"):i("settings.providers.page.actions.complete")}),s.jsx(ee,{variant:"ghost",size:"xs",className:"!font-normal shrink-0",onClick:O,disabled:r.submitting,children:i("settings.providers.page.actions.cancel")})]})]}),I&&r.phase==="failed"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:r.message}),s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>k(b),children:i("settings.providers.page.actions.tryAgain")})]})]},b.index)})})},Bw=t=>new Intl.NumberFormat(kr(),{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(t),pd=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const e=Bw(t);return e.endsWith(".0")?e.slice(0,-2):e},oi="__add_provider__",rm=t=>typeof t=="object"&&t!==null,gd=(t,e)=>t.map(({method:n,methodIndex:a})=>({index:a,label:n.label||n.name||e(a),prompts:n.prompts})),_w=t=>{if(typeof t=="string")return{id:t};if(!rm(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}},Uw=t=>{let e=[];Array.isArray(t)?e=t:rm(t)&&(Array.isArray(t.all)?e=t.all:Array.isArray(t.providers)&&(e=t.providers));const n=e.map(i=>_w(i)).filter(i=>!!i),a=new Set;return n.filter(i=>a.has(i.id)?!1:(a.add(i.id),!0))},$w=()=>{const{t}=ot(),e=pt(se=>se.providers),n=pt(se=>se.selectedProviderId),a=pt(se=>se.setSelectedProvider),i=pt(se=>se.getModelMetadata),r=je(se=>se.hiddenModels),o=je(se=>se.toggleHiddenModel),d=je(se=>se.hideAllModels),c=je(se=>se.showAllModels),[p,u]=l.useState({}),[g,m]=l.useState(!1),[w,h]=l.useState({}),[f,x]=l.useState(null),[k,y]=l.useState(""),[C,O]=l.useState([]),[j,N]=l.useState(!1),[b,I]=l.useState(null),[B,T]=l.useState(""),[D,S]=l.useState(""),[F,R]=l.useState(!1),[z,q]=l.useState({}),[H,Z]=l.useState(!1),[W,A]=l.useState(null),[X,te]=l.useState(null),[E,P]=l.useState(null),[_,L]=l.useState(null),[V,Y]=l.useState(null),G=n===oi,me=G&&B===aa,ae=!!(W&&n&&W===n&&!G);l.useEffect(()=>{!n&&e.length>0&&a(e[0].id)},[e,n,a]),l.useEffect(()=>{if(!n)return;let se=!0;return(async()=>{m(!0);try{const ke=await Ps.getSdkClient().provider.auth();if(ke.error)throw new Error(`provider.auth failed: ${String(ke.error)}`);if(!se)return;u(fw(ke.data))}catch(ke){if(!se)return;console.error("Failed to load provider auth methods:",ke),Q.error(t("settings.providers.page.toast.authMethodsLoadFailed"))}finally{se&&m(!1)}})(),()=>{se=!1}},[n,t]),l.useEffect(()=>{if(!gw(G))return;let se=!0;return(async()=>{N(!0),I(null);try{const ke=await Ps.getSdkClient().provider.list();if(ke.error)throw new Error(`provider.list failed: ${String(ke.error)}`);if(!se)return;O(Uw(ke.data))}catch(ke){if(!se)return;console.error("Failed to load available providers:",ke),I(t("settings.providers.page.state.unableToLoadProviderList"))}finally{se&&N(!1)}})(),()=>{se=!1}},[G,t]);const xe=l.useMemo(()=>new Set(e.map(se=>se.id)),[e]),be=l.useMemo(()=>C.filter(se=>!xe.has(se.id)).sort((se,ye)=>{const ke=(se.name||se.id).toLowerCase(),ze=(ye.name||ye.id).toLowerCase();return ke.localeCompare(ze)}),[C,xe]);l.useEffect(()=>{n===oi&&B&&B!==aa&&!be.some(se=>se.id===B)&&T("")},[n,B,be]),l.useEffect(()=>{if(n===oi){Z(!0),A(null),te(null),P(null),L(null);return}Z(!1),W&&W!==n&&(A(null),te(null),P(null),L(null))},[n,W]),l.useEffect(()=>{if(!n||n===oi)return;const se=z[n];if(!se)return;const ye=e.find($=>$.id===n),ke=Array.isArray(ye?.env)?ye.env.filter($=>typeof $=="string"&&$.trim().length>0):[];se.auth.exists||ke.length>0||Z(!0)},[n,z,e]),l.useEffect(()=>{if(!n||n===oi)return;let se=!1;return(async()=>{try{const ke=await ht(`/api/provider/${encodeURIComponent(n)}/source`,{method:"GET",headers:{Accept:"application/json"}}),ze=await ke.json().catch(()=>null);if(!ke.ok)throw new Error(ze?.error||t("settings.providers.page.toast.providerSourcesLoadFailed"));const $=ze?.sources??ze?.data?.sources;!se&&$&&q(Ee=>({...Ee,[n]:$}))}catch(ke){se||console.error("Failed to load provider sources:",ke)}})(),()=>{se=!0}},[n,t]);const ie=e.find(se=>se.id===n),pe=n?z[n]:void 0,Ie=async se=>{const ye=w[se]?.trim()??"";if(!ye){Q.error(t("settings.providers.page.toast.apiKeyRequired"));return}const ke=`api:${se}`;x(ke);try{if((await Ps.getSdkClient().auth.set({providerID:se,auth:{type:"api",key:ye}})).error)throw new Error(t("settings.providers.page.toast.apiKeySaveFailed"));Q.success(t("settings.providers.page.toast.apiKeySaved")),h($=>({...$,[se]:""})),await _n({scopes:["providers"],mode:"active"}),a(se)}catch(ze){console.error("Failed to save API key:",ze),Q.error(t("settings.providers.page.toast.apiKeySaveFailed"))}finally{x(null)}},re=async se=>{const ye=`custom:${se.providerID}`;x(ye),Y(se.providerID),L(null);try{const ke=Sw(se);if(ke&&(await Ps.getSdkClient().auth.set(ke)).error)throw new Error(t("settings.providers.page.toast.apiKeySaveFailed"));const ze=Cw(se,{scope:W?E??cd(z[W]):"user"}),$=await ht("/api/provider",{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(ze)}),Ee=await $.json().catch(()=>null);if(!$.ok)throw ke&&L(t("settings.providers.page.custom.authFailure.configAfterAuth")),new Error(Ee?.error||t("settings.providers.page.toast.customProviderSaveFailed"));Q.success(t("settings.providers.page.toast.customProviderSaved",{provider:se.name})),T(""),A(null),te(null),P(null),L(null),Y(null),await _n({scopes:["providers"],mode:"active"}),a(se.providerID)}catch(ke){console.error("Failed to save custom provider:",ke),Q.error(ke instanceof Error&&ke.message?ke.message:t("settings.providers.page.toast.customProviderSaveFailed"))}finally{x(null)}},ce=se=>t("settings.providers.page.auth.oauthMethodFallback",{index:String(se+1)}),ge=async se=>{Z(!1),await _n({scopes:["providers"],mode:"active"}),a(se)},oe=async se=>{const ye=`disconnect:${se}`;x(ye);try{const ke=await ht(`/api/provider/${encodeURIComponent(se)}/auth?scope=all`,{method:"DELETE",headers:{Accept:"application/json"}}),ze=await ke.json().catch(()=>null);if(!ke.ok)throw new Error(ze?.error||t("settings.providers.page.toast.providerDisconnectFailed"));Q.success(t("settings.providers.page.toast.providerDisconnected")),await _n({scopes:["providers"],mode:"active"})}catch(ke){console.error("Failed to disconnect provider:",ke),Q.error(t("settings.providers.page.toast.providerDisconnectFailed"))}finally{x(null)}},de=async se=>{se&&(await oe(se),A(null),te(null),P(null),L(null),Y(null),T(""))};if(!G&&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(G)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")}),j?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.state.loading")}):b?s.jsx("p",{className:"typography-meta text-muted-foreground",children:b}):s.jsxs(fs,{open:F,onOpenChange:se=>{R(se),se||S("")},children:[s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button",className:Vn,children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[B&&B!==aa?s.jsx(ra,{providerId:B,className:"h-3.5 w-3.5 flex-shrink-0"}):null,s.jsx("span",{className:fe("truncate typography-ui-label font-normal",B?"text-foreground":"text-muted-foreground"),children:B===aa?t("settings.providers.page.custom.optionLabel"):B?be.find(se=>se.id===B)?.name||B: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:se=>se.preventDefault(),children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-[var(--surface-subtle)] px-3 py-2",onKeyDown:se=>se.stopPropagation(),children:[s.jsx(K,{name:"search",className:"h-4 w-4 text-muted-foreground"}),s.jsx("input",{type:"text",value:D,onChange:se=>S(se.target.value),onKeyDown:se=>se.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(zs,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const se=D.toLowerCase(),ye=t("settings.providers.page.custom.optionLabel"),ke=!se||ye.toLowerCase().includes(se)||"other".includes(se)||"custom".includes(se),ze=be.filter($=>($.name||$.id).toLowerCase().includes(se)||$.id.toLowerCase().includes(se));return ze.length===0&&!ke?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:[ze.map($=>s.jsxs(as,{onSelect:()=>{T($.id),R(!1),S("")},className:"flex items-center justify-between",children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(ra,{providerId:$.id,className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:$.name||$.id})]}),B===$.id&&s.jsx(K,{name:"check",className:"h-4 w-4 text-[var(--primary-base)]"})]},$.id)),ke?s.jsxs(as,{onSelect:()=>{T(aa),R(!1),S("")},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:ye})]}),B===aa&&s.jsx(K,{name:"check",className:"h-4 w-4 text-[var(--primary-base)]"})]},aa):null]})})()})]})]})]})}),me?s.jsx(dd,{mode:"create",existingProviderIDs:xe,busy:f?.startsWith("custom:")??!1,authFailureHint:_,onCancel:()=>{T(""),L(null),Y(null)},onDisconnect:_&&V?()=>{de(V)}:void 0,onSubmit:re}):B?s.jsx(dt,{title:t("settings.providers.page.auth.title"),settingsItem:"providers.auth",contentClassName:"space-y-4",children:g?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.auth.loadingMethods")}):s.jsx(s.Fragment,{children:(()=>{const se=p[B]??[],ye=gd(ld(se),ce),ke=od(se);return s.jsxs(s.Fragment,{children:[ke?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(nt,{type:"password",value:w[B]??"",onChange:ze=>h($=>({...$,[B]:ze.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:()=>Ie(B),disabled:f===`api:${B}`,children:f===`api:${B}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.saveKey")})]})]}):null,ye.length>0?s.jsx(md,{providerId:B,methods:ye,onConnected:()=>ge(B),className:fe(ke&&"border-t border-[var(--surface-subtle)] pt-2")},B):null]})})()})}):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 le=Array.isArray(ie.models)?ie.models:[],he=p[ie.id]??[],De=gd(ld(he),ce),Le=od(he),Ke=!!pe,Fe=Ke&&jw(ie,pe),Me=Array.isArray(ie.env)?ie.env.filter(se=>typeof se=="string"&&se.trim().length>0):[],Be=!!pe?.auth.exists,Ge=Me.length>0,Ve=Be||Ge,Ue=Ke&&!Ve,He=le.length>0&&(!Ke||Ve),_e=!Le&&De.length>0?t("settings.providers.page.auth.useReconnectHint"):t("settings.providers.page.auth.incompleteHint"),Oe=le.filter(se=>{const ye=typeof se?.name=="string"?se.name:"",ke=typeof se?.id=="string"?se.id:"",ze=k.trim().toLowerCase();return ze?ye.toLowerCase().includes(ze)||ke.toLowerCase().includes(ze):!0});return ae&&Fe&&X?s.jsx(ps,{title:ie.name||ie.id,titleLeading:s.jsx(ra,{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(dd,{mode:"edit",existingProviderIDs:xe,initialValues:X,allowExistingAuth:Ve||!Ke,busy:f?.startsWith("custom:")??!1,authFailureHint:_,onCancel:()=>{A(null),te(null),P(null),L(null),Y(null)},onDisconnect:()=>{de(ie.id)},onSubmit:re})}):s.jsxs(ps,{title:ie.name||ie.id,titleLeading:s.jsx(ra,{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:[Fe?s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{L(null),te(kw(ie)),P(cd(pe)),A(ie.id)},children:t("settings.providers.page.actions.edit")}):null,s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Z(se=>!se),children:t(H?"settings.providers.page.actions.hide":"settings.providers.page.actions.reconnect")})]}),settingsItem:"providers.auth",children:H?g?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:[Le?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(nt,{type:"password",value:w[ie.id]??"",onChange:se=>h(ye=>({...ye,[ie.id]:se.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:()=>Ie(ie.id),disabled:f===`api:${ie.id}`,children:f===`api:${ie.id}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.saveKey")})]})]}):null,De.length>0&&s.jsx(md,{providerId:ie.id,methods:De,onConnected:()=>ge(ie.id),className:fe(Le&&"border-t border-[var(--surface-subtle)] pt-2")},ie.id)]}):Ue?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:_e})]}):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:pe&&(pe.auth.exists||pe.user.exists||pe.project.exists||pe.custom?.exists)?s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t("settings.providers.page.connectionDetails.configuredIn")," ",[pe.auth.exists?t("settings.providers.page.connectionDetails.source.authCredentials"):null,pe.user.exists?t("settings.providers.page.connectionDetails.source.userConfig"):null,pe.project.exists?t("settings.providers.page.connectionDetails.source.projectConfig"):null,pe.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:()=>oe(ie.id),disabled:f===`disconnect:${ie.id}`,children:f===`disconnect:${ie.id}`?t("settings.providers.page.actions.disconnecting"):t("settings.providers.page.actions.disconnect")})]})}),He?s.jsxs(dt,{title:t("settings.providers.page.models.title"),titleAccessory:s.jsxs("span",{className:"typography-micro text-muted-foreground font-normal",children:["(",le.length,")"]}),headerAction:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(ee,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{const se=le.map(ye=>typeof ye?.id=="string"?ye.id:"").filter(ye=>ye.length>0);d(ie.id,se)},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(nt,{value:k,onChange:se=>y(se.target.value),placeholder:t("settings.providers.page.models.filterPlaceholder"),className:"h-7 pl-8 w-full"})]}),Oe.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:Oe.map(se=>{const ye=typeof se?.id=="string"?se.id:"",ke=typeof se?.name=="string"?se.name:ye,ze=ye?i(ie.id,ye):void 0,$=r.some(ue=>ue.providerID===ie.id&&ue.modelID===ye),Ee=pd(ze?.limit?.context),J=pd(ze?.limit?.output),v=[];return ze?.tool_call&&v.push({key:"tools",icon:"tools",label:t("settings.providers.page.models.capability.toolCalling")}),ze?.reasoning&&v.push({key:"reasoning",icon:"brain-ai-3",label:t("settings.providers.page.models.capability.reasoning")}),ze?.attachment&&v.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",$&&"opacity-50"),children:[s.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:ke}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[(Ee||J)&&s.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0 bg-[var(--surface-muted)] px-1.5 py-0.5 rounded",children:[Ee?`${Ee} ${t("settings.providers.page.models.tokenBadge.context")}`:"",Ee&&J?" · ":"",J?`${J} ${t("settings.providers.page.models.tokenBadge.output")}`:""]}),v.length>0&&s.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:v.map(({key:ue,icon:Ne,label:we})=>s.jsx("span",{className:"flex h-5 w-5 rounded items-center justify-center text-muted-foreground bg-[var(--surface-muted)]",title:we,"aria-label":we,children:s.jsx(K,{name:Ne,className:"h-3 w-3"})},ue))}),s.jsx("button",{type:"button",onClick:()=>o(ie.id,ye),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($?"settings.providers.page.models.actions.showModelInSelectors":"settings.providers.page.models.actions.hideModelFromSelectors"),"aria-label":t($?"settings.providers.page.models.actions.showModel":"settings.providers.page.models.actions.hideModel"),children:$?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"})})]})]})},ye)})})]}):null]})},Yn=[{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 fd(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 Vw=[{id:"gemini-auth",label:"Gemini",matcher:t=>t.startsWith("gemini/"),order:1},{id:"antigravity-auth",label:"Antigravity",matcher:t=>t.startsWith("antigravity/"),order:2}],om={google:Vw};function lm(t,e){const n=om[e]??[];for(const a of n)if(a.matcher(t))return a;return null}function Hw(t){return om[t]??[]}function Ww(t){return[...t].sort((e,n)=>e.order-n.order)}function xS(t,e){const n=new Map;for(const a of Object.keys(t)){const r=lm(a,e)?.id??null;n.has(r)||n.set(r,[]),n.get(r).push(a)}return n}function Gw(t,e,n){const a=new Map;for(const i of t){const r=e(i),d=lm(r,n)?.id??null;a.has(d)||a.set(d,[]),a.get(d).push(i)}return a}function qw(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 yl=6e4,hd=t=>{const e=Yn.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))):yl,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(h=>typeof h=="string"));const u={},g=t?.usageExpandedFamilies;if(g&&typeof g=="object")for(const[m,w]of Object.entries(g))Array.isArray(w)&&(u[m]=w.filter(h=>typeof h=="string"));return{autoRefresh:n,refreshIntervalMs:a,displayMode:i,showPredValues:r,dropdownProviderIds:d,selectedModels:c,expandedFamilies:u}},Jw=async()=>{const t=an()?.settings;if(t)try{const n=(await t.load())?.settings;return hd(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 hd(n)}}return{autoRefresh:!1,refreshIntervalMs:yl,displayMode:"usage",showPredValues:!1,dropdownProviderIds:Yn.map(e=>e.id),selectedModels:{},expandedFamilies:{}}},Jt=fn()(Ja((t,e)=>({results:[],selectedProviderId:null,isLoading:!1,isFetchingProvider:{},lastUpdated:null,error:null,autoRefresh:!1,refreshIntervalMs:yl,displayMode:"usage",showPredValues:!1,dropdownProviderIds:Yn.map(n=>n.id),selectedModels:{},expandedFamilies:{},loadSettings:async()=>{try{const n=await Jw();t(n)}catch(n){console.warn("Failed to load usage settings:",n)}},fetchAllQuotas:async()=>{t({isLoading:!0,error:null});const n=Yn.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=qw(n,a);r.length!==0&&(t(o=>({selectedModels:{...o.selectedModels,[n]:r}})),It({usageSelectedModels:e().selectedModels}))}}),{name:"quota-store"})),Yw=()=>{const t=Ze.c(5),e=Jt(Qw),n=Jt(Xw),a=Jt(Zw);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 Qw(t){return t.autoRefresh}function Xw(t){return t.refreshIntervalMs}function Zw(t){return t.fetchAllQuotas}const e1=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)},t1=t=>{const e=Ze.c(122),{onItemSelect:n}=t,{t:a}=ot(),i=Jt(s1),r=Jt(n1),o=Jt(a1),d=Jt(i1),c=Jt(r1),p=Jt(o1),u=Jt(l1),g=Jt(c1),m=Jt(d1),w=Jt(u1),h=Jt(m1),f=Jt(p1),x=Jt(g1),k=Jt(f1);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 O=h1;let j;e[3]!==m?(j=ke=>{m(ke),O({usageAutoRefresh:ke})},e[3]=m,e[4]=j):j=e[4];const N=j;let b;e[5]!==w?(b=ke=>{const ze=Number(ke);Number.isFinite(ze)&&(w(ze),O({usageRefreshIntervalMs:ze}))},e[5]=w,e[6]=b):b=e[6];const I=b;let B;e[7]!==h?(B=ke=>{ke!=="usage"&&ke!=="remaining"||(h(ke),O({usageDisplayMode:ke}))},e[7]=h,e[8]=B):B=e[8];const T=B;let D;e[9]!==x?(D=ke=>{x(ke),O({usageShowPredValues:ke})},e[9]=x,e[10]=D):D=e[10];const S=D;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 R;e[12]!==a?(R=a("settings.usage.sidebar.title"),e[12]=a,e[13]=R):R=e[13];let z;e[14]!==R?(z=s.jsx("h2",{className:`${hn} mb-3`,children:R}),e[14]=R,e[15]=z):z=e[15];let q;e[16]!==a?(q=a("settings.usage.sidebar.total",{count:Yn.length}),e[16]=a,e[17]=q):q=e[17];let H;e[18]!==q?(H=s.jsx("span",{className:"typography-meta text-muted-foreground",children:q}),e[18]=q,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 W;e[22]!==N||e[23]!==Z||e[24]!==p?(W=s.jsx(xs,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(rn,{checked:p,onChange:N,ariaLabel:Z})})}),e[22]=N,e[23]=Z,e[24]=p,e[25]=W):W=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]!==W||e[31]!==X?(te=s.jsxs(bs,{children:[W,X]}),e[30]=W,e[31]=X,e[32]=te):te=e[32];const E=String(u),P=!p;let _;e[33]!==a?(_=a("settings.usage.sidebar.field.intervalPlaceholder"),e[33]=a,e[34]=_):_=e[34];let L;e[35]!==_?(L=s.jsx(Lt,{className:"w-fit",children:s.jsx(Wt,{placeholder:_})}),e[35]=_,e[36]=L):L=e[36];let V;e[37]===Symbol.for("react.memo_cache_sentinel")?(V=s.jsxs(Ft,{children:[s.jsx(jt,{value:"30000",children:"30s"}),s.jsx(jt,{value:"60000",children:"1m"}),s.jsx(jt,{value:"300000",children:"5m"})]}),e[37]=V):V=e[37];let Y;e[38]!==I||e[39]!==E||e[40]!==P||e[41]!==L?(Y=s.jsxs(Mt,{value:E,onValueChange:I,disabled:P,children:[L,V]}),e[38]=I,e[39]=E,e[40]=P,e[41]=L,e[42]=Y):Y=e[42];let G;e[43]!==d?(G=()=>d(),e[43]=d,e[44]=G):G=e[44];let me;e[45]!==a?(me=a("settings.usage.sidebar.actions.refreshAria"),e[45]=a,e[46]=me):me=e[46];let ae;e[47]!==a?(ae=a("settings.usage.sidebar.actions.refreshTitle"),e[47]=a,e[48]=ae):ae=e[48];const xe=c&&"animate-spin";let be;e[49]!==xe?(be=fe("h-3.5 w-3.5",xe),e[49]=xe,e[50]=be):be=e[50];let ie;e[51]!==be?(ie=s.jsx(K,{name:"refresh",className:be}),e[51]=be,e[52]=ie):ie=e[52];let pe;e[53]!==c||e[54]!==G||e[55]!==me||e[56]!==ae||e[57]!==ie?(pe=s.jsx(ee,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 text-muted-foreground",onClick:G,"aria-label":me,title:ae,disabled:c,children:ie}),e[53]=c,e[54]=G,e[55]=me,e[56]=ae,e[57]=ie,e[58]=pe):pe=e[58];let Ie;e[59]!==te||e[60]!==Y||e[61]!==pe?(Ie=s.jsxs("div",{className:"flex items-center gap-2",children:[te,Y,pe]}),e[59]=te,e[60]=Y,e[61]=pe,e[62]=Ie):Ie=e[62];let re;e[63]!==H||e[64]!==Ie?(re=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[H,Ie]}),e[63]=H,e[64]=Ie,e[65]=re):re=e[65];let ce;e[66]!==a?(ce=a("settings.usage.sidebar.field.display"),e[66]=a,e[67]=ce):ce=e[67];let ge;e[68]!==ce?(ge=s.jsx("span",{className:"typography-micro text-muted-foreground",children:ce}),e[68]=ce,e[69]=ge):ge=e[69];let oe;e[70]!==a?(oe=a("settings.usage.sidebar.field.displayModePlaceholder"),e[70]=a,e[71]=oe):oe=e[71];let de;e[72]!==oe?(de=s.jsx(Lt,{className:"w-fit",children:s.jsx(Wt,{placeholder:oe})}),e[72]=oe,e[73]=de):de=e[73];let le;e[74]!==a?(le=a("settings.usage.sidebar.field.displayModeUsage"),e[74]=a,e[75]=le):le=e[75];let he;e[76]!==le?(he=s.jsx(jt,{value:"usage",children:le}),e[76]=le,e[77]=he):he=e[77];let De;e[78]!==a?(De=a("settings.usage.sidebar.field.displayModeRemaining"),e[78]=a,e[79]=De):De=e[79];let Le;e[80]!==De?(Le=s.jsx(jt,{value:"remaining",children:De}),e[80]=De,e[81]=Le):Le=e[81];let Ke;e[82]!==he||e[83]!==Le?(Ke=s.jsxs(Ft,{children:[he,Le]}),e[82]=he,e[83]=Le,e[84]=Ke):Ke=e[84];let Fe;e[85]!==T||e[86]!==de||e[87]!==Ke||e[88]!==g?(Fe=s.jsxs(Mt,{value:g,onValueChange:T,children:[de,Ke]}),e[85]=T,e[86]=de,e[87]=Ke,e[88]=g,e[89]=Fe):Fe=e[89];let Me;e[90]!==ge||e[91]!==Fe?(Me=s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[ge,Fe]}),e[90]=ge,e[91]=Fe,e[92]=Me):Me=e[92];let Be;e[93]!==a?(Be=a("settings.usage.sidebar.field.showPredictions"),e[93]=a,e[94]=Be):Be=e[94];let Ge;e[95]!==Be?(Ge=s.jsx("span",{className:"typography-micro text-muted-foreground",children:Be}),e[95]=Be,e[96]=Ge):Ge=e[96];let Ve;e[97]!==a?(Ve=a("settings.usage.sidebar.field.showPredictions"),e[97]=a,e[98]=Ve):Ve=e[98];let Ue;e[99]!==S||e[100]!==f||e[101]!==Ve?(Ue=s.jsx(rn,{checked:f,onChange:S,ariaLabel:Ve}),e[99]=S,e[100]=f,e[101]=Ve,e[102]=Ue):Ue=e[102];let He;e[103]!==Ge||e[104]!==Ue?(He=s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[Ge,Ue]}),e[103]=Ge,e[104]=Ue,e[105]=He):He=e[105];let _e;e[106]!==re||e[107]!==Me||e[108]!==He||e[109]!==z?(_e=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[z,re,Me,He]}),e[106]=re,e[107]=Me,e[108]=He,e[109]=z,e[110]=_e):_e=e[110];let Oe;e[111]!==n||e[112]!==i||e[113]!==r||e[114]!==o||e[115]!==a?(Oe=Yn.map(ke=>{const ze=i.find(Ne=>Ne.providerId===ke.id),$=e1(ze?.usage),Ee=pu($),J=ke.id===r,v=ze?.configured??!1,ue=v?Ee==="critical"?{backgroundColor:"var(--status-error)"}:Ee==="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",J?"bg-interactive-selection":"hover:bg-interactive-hover"),children:s.jsxs("button",{type:"button",onClick:()=>{o(ke.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:ue}),s.jsx(ra,{providerId:ke.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:ke.name}),!v&&s.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:a("settings.usage.sidebar.status.notSet")})]})},ke.id)}),e[111]=n,e[112]=i,e[113]=r,e[114]=o,e[115]=a,e[116]=Oe):Oe=e[116];let se;e[117]!==Oe?(se=s.jsx(zs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:Oe}),e[117]=Oe,e[118]=se):se=e[118];let ye;return e[119]!==_e||e[120]!==se?(ye=s.jsxs("div",{className:F,children:[_e,se]}),e[119]=_e,e[120]=se,e[121]=ye):ye=e[121],ye};function s1(t){return t.results}function n1(t){return t.selectedProviderId}function a1(t){return t.setSelectedProvider}function i1(t){return t.fetchAllQuotas}function r1(t){return t.isLoading}function o1(t){return t.autoRefresh}function l1(t){return t.refreshIntervalMs}function c1(t){return t.displayMode}function d1(t){return t.setAutoRefresh}function u1(t){return t.setRefreshInterval}function m1(t){return t.setDisplayMode}function p1(t){return t.showPredValues}function g1(t){return t.setShowPredValues}function f1(t){return t.loadSettings}async function h1(t){try{await It(t)}catch(e){console.warn("Failed to save usage settings:",e)}}const x1=t=>{const e=Ze.c(20),{percent:n,tonePercent:a,className:i,expectedMarkerPercent:r}=t;let o;e[0]!==n?(o=Op(n)??0,e[0]=n,e[1]=o):o=e[1];const d=o,c=a??n;let p;e[2]!==c?(p=pu(c),e[2]=c,e[3]=p):p=e[3];const u=p,g=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 h;e[6]!==i?(h=fe("relative h-2.5 rounded-full bg-[var(--interactive-border)] overflow-hidden",i),e[6]=i,e[7]=h):h=e[7];const f=`${d}%`;let x;e[8]!==w||e[9]!==f?(x={...w,width:f},e[8]=w,e[9]=f,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]!==g?(y=g!=null&&g>0&&g<100&&s.jsx("div",{className:"absolute top-0 h-full w-0.5 bg-foreground",style:{left:`${g}%`},title:`Expected usage if spread evenly: ${Math.round(g)}% of quota`,"aria-hidden":"true"}),e[14]=g,e[15]=y):y=e[15];let C;return e[16]!==h||e[17]!==k||e[18]!==y?(C=s.jsxs("div",{className:h,children:[k,y]}),e[16]=h,e[17]=k,e[18]=y,e[19]=C):C=e[19],C},b1=t=>{const e=Ze.c(67),{paceInfo:n,className:a,compact:i}=t,r=i===void 0?!1:i,{t:o}=ot();let d;e[0]!==n.status?(d=zp(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 b;e[2]!==o?(b=o("settings.usage.pace.status.onTrack"),e[2]=o,e[3]=b):b=e[3],p=b;break e}case"slightly-fast":{let b;e[4]!==o?(b=o("settings.usage.pace.status.slightlyFast"),e[4]=o,e[5]=b):b=e[5],p=b;break e}case"too-fast":{let b;e[6]!==o?(b=o("settings.usage.pace.status.tooFast"),e[6]=o,e[7]=b):b=e[7],p=b;break e}case"exhausted":{let b;e[8]!==o?(b=o("settings.usage.pace.status.usedUp"),e[8]=o,e[9]=b):b=e[9],p=b;break e}}p=void 0}const u=p;let g;e[10]!==n.predictText||e[11]!==o?(g=o("settings.usage.pace.predictionTooltip",{prediction:n.predictText}),e[10]=n.predictText,e[11]=o,e[12]=g):g=e[12];const m=g;if(r){let b;e[13]!==a?(b=fe("flex items-center gap-1.5",a),e[13]=a,e[14]=b):b=e[14];let I;e[15]!==c?(I={backgroundColor:c},e[15]=c,e[16]=I):I=e[16];let B;e[17]!==u||e[18]!==I?(B=s.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:I,title:u}),e[17]=u,e[18]=I,e[19]=B):B=e[19];let T;e[20]!==c?(T={color:c},e[20]=c,e[21]=T):T=e[21];const D=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:El(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]!==T||e[29]!==D?(F=s.jsx("span",{className:"typography-micro tabular-nums",style:T,title:D,children:S}),e[27]=S,e[28]=T,e[29]=D,e[30]=F):F=e[30];let R;return e[31]!==F||e[32]!==b||e[33]!==B?(R=s.jsxs("div",{className:b,children:[B,F]}),e[31]=F,e[32]=b,e[33]=B,e[34]=R):R=e[34],R}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 h;e[37]!==n.isExhausted||e[38]!==n.paceRateText||e[39]!==o?(h=!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]=h):h=e[40];let f;e[41]!==h?(f=s.jsx("div",{className:"flex items-center gap-1.5",children:h}),e[41]=h,e[42]=f):f=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:El(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 O;e[57]!==u||e[58]!==C?(O=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]=O):O=e[59];let j;e[60]!==y||e[61]!==O?(j=s.jsxs("div",{className:"flex items-center gap-1.5",children:[y,O]}),e[60]=y,e[61]=O,e[62]=j):j=e[62];let N;return e[63]!==j||e[64]!==w||e[65]!==f?(N=s.jsxs("div",{className:w,children:[f,j]}),e[63]=j,e[64]=w,e[65]=f,e[66]=N):N=e[66],N},lo=t=>{const e=Ze.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=Jt(y1),g=Jt(v1),m=je(w1),w=u==="remaining"?a.remainingPercent:a.usedPercent,h=u==="remaining"?"remaining":"used";let f;e[0]!==w||e[1]!==a.valueLabel?(f=Kp(a.valueLabel,w),e[0]=w,e[1]=a.valueLabel,e[2]=f):f=e[2];const x=f,k=a.resetAfterFormatted??a.resetAtFormatted;let y;e[3]!==k||e[4]!==m||e[5]!==a.resetAt?(y=Bp(a.resetAt,k,m),e[3]=k,e[4]=m,e[5]=a.resetAt,e[6]=y):y=e[6];const C=y;let O;e[7]!==n?(O=_p(n),e[7]=n,e[8]=O):O=e[8];const j=O;let N;e[9]!==n||e[10]!==a.resetAt||e[11]!==a.usedPercent||e[12]!==a.windowSeconds?(N=Up(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 b=N;let I;e:{if(!b||b.dailyAllocationPercent===null){I=null;break e}const L=$p(b.elapsedRatio);I=u==="remaining"?100-L:L}const B=I;let T;e[14]!==d||e[15]!==c||e[16]!==p?(T=c&&s.jsx(rn,{checked:p,onChange:L=>d?.(L),ariaLabel:"Show in dropdown"}),e[14]=d,e[15]=c,e[16]=p,e[17]=T):T=e[17];let D;e[18]!==j?(D=s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j}),e[18]=j,e[19]=D):D=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]!==D||e[23]!==S?(F=s.jsxs("div",{className:"min-w-0 flex flex-col",children:[D,S]}),e[22]=D,e[23]=S,e[24]=F):F=e[24];let R;e[25]!==F||e[26]!==T?(R=s.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[T,F]}),e[25]=F,e[26]=T,e[27]=R):R=e[27];const z=x==="-"?"":x;let q;e[28]!==z?(q=s.jsx("div",{className:"typography-ui-label text-foreground tabular-nums flex items-center justify-end",children:z}),e[28]=z,e[29]=q):q=e[29];let H;e[30]!==R||e[31]!==q?(H=s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[R,q]}),e[30]=R,e[31]=q,e[32]=H):H=e[32];let Z;e[33]!==w||e[34]!==B||e[35]!==a.usedPercent?(Z=s.jsx(x1,{percent:w,tonePercent:a.usedPercent,expectedMarkerPercent:B,className:"h-1.5"}),e[33]=w,e[34]=B,e[35]=a.usedPercent,e[36]=Z):Z=e[36];const W=C?`Resets ${C}`:"";let A;e[37]!==W?(A=s.jsx("span",{className:"typography-micro text-muted-foreground",children:W}),e[37]=W,e[38]=A):A=e[38];let X;e[39]!==h?(X=s.jsx("span",{className:"typography-micro text-muted-foreground",children:h}),e[39]=h,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 E;e[44]!==Z||e[45]!==te?(E=s.jsxs("div",{className:"mt-2.5",children:[Z,te]}),e[44]=Z,e[45]=te,e[46]=E):E=e[46];let P;e[47]!==b||e[48]!==g?(P=b&&g&&s.jsx("div",{className:"mt-1.5",children:s.jsx(b1,{paceInfo:b})}),e[47]=b,e[48]=g,e[49]=P):P=e[49];let _;return e[50]!==H||e[51]!==E||e[52]!==P?(_=s.jsxs("div",{className:"py-3",children:[H,E,P]}),e[50]=H,e[51]=E,e[52]=P,e[53]=_):_=e[53],_};function y1(t){return t.displayMode}function v1(t){return t.showPredValues}function w1(t){return t.timeFormatPreference}const j1=({providerId:t,providerName:e})=>{const{t:n}=ot(),[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,h)=>{c(!0);try{const f=await ht(m,{method:w,headers:h?{"Content-Type":"application/json"}:void 0,body:h?JSON.stringify(h):void 0}),x=await f.json().catch(()=>null);if(!f.ok)throw new Error(x?.error);x?.configured!==void 0&&i(x),o(k=>k.workspaceId?{workspaceId:k.workspaceId}:{}),Q.success(n("settings.providers.page.quotaCredentials.saved",{provider:e}))}catch(f){Q.error(f instanceof Error&&f.message?f.message:n("settings.providers.page.openCodeGo.saveFailed"))}finally{c(!1)}},g=(m,w,h)=>s.jsxs("label",{className:"block typography-ui-label text-foreground",children:[w,s.jsx(nt,{className:"mt-1 h-7 font-mono text-xs",type:m==="workspaceId"?"text":"password",autoComplete:"off",value:r[m]??"",onChange:f=>o(x=>({...x,[m]:f.target.value})),placeholder:a?.secretMasked??h})]});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"&&g("workspaceId",n("settings.providers.page.openCodeGo.workspaceId"),"wrk_..."),t==="opencode-go"&&g("authCookie",n("settings.providers.page.openCodeGo.authCookie"),"auth=..."),t==="ollama-cloud"&&g("cookie",n("settings.providers.page.openCodeGo.authCookie"),"session=..."),t==="cursor"&&g("accessToken",n("settings.providers.page.quotaCredentials.accessToken"),n("settings.providers.page.quotaCredentials.tokenPlaceholder")),t==="cursor"&&g("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")})]})]})]})},k1=(t,e)=>{if(!t)return"-";try{return gu(t,e,{fallback:"-"})}catch{return"-"}},N1=()=>{const{t}=ot(),e=je(R=>R.timeFormatPreference),n=Jt(R=>R.results),a=Jt(R=>R.selectedProviderId),i=Jt(R=>R.setSelectedProvider),r=Jt(R=>R.loadSettings),o=Jt(R=>R.fetchAllQuotas),d=Jt(R=>R.isLoading),c=Jt(R=>R.lastUpdated),p=Jt(R=>R.error),u=Jt(R=>R.dropdownProviderIds),g=Jt(R=>R.setDropdownProviderIds),m=Jt(R=>R.selectedModels),w=Jt(R=>R.toggleModelSelected),h=Jt(R=>R.applyDefaultSelections);Yw(),l.useEffect(()=>{r(),o()},[r,o]),l.useEffect(()=>{if(a||n.length===0)return;const R=n.find(z=>z.configured)?.providerId;i(R??Yn[0]?.id??null)},[n,a,i]);const f=n.find(R=>R.providerId===a)??null,k=Yn.find(R=>R.id===a)?.name??a??t("settings.usage.sidebar.title"),y=f?.usage,C=a?u.includes(a):!1,O=a==="opencode-go"||a==="ollama-cloud"||a==="cursor",j=l.useCallback(R=>{if(!a)return;const z=R?Array.from(new Set([...u,a])):u.filter(q=>q!==a);g(z),It({usageDropdownProviders:z})},[u,a,g]),N=l.useMemo(()=>y?.models?Object.entries(y.models).map(([R,z])=>({name:R,windows:z})).filter(R=>Object.keys(R.windows.windows).length>0):[],[y?.models]);l.useEffect(()=>{a&&N.length>0&&h(a,N.map(R=>R.name))},[a,N,h]);const b=l.useMemo(()=>!a||N.length===0?new Map:Gw(N,R=>R.name,a),[N,a]),I=l.useMemo(()=>{if(!a)return[];const R=Hw(a);return Ww(R)},[a]),[B,T]=l.useState(()=>({})),D=l.useCallback(R=>{T(z=>({...z,[R]:!z[R]}))},[]),S=l.useCallback(R=>{if(!a)return;w(a,R);const z=m[a]??[],H=z.includes(R)?z.filter(W=>W!==R):[...z,R],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(ra,{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:k1(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")})}),!f&&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})]}),f&&!f.configured&&!O&&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(j1,{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(([R,z])=>s.jsx(lo,{title:R,window:z},R))})}),N.length>0&&s.jsxs(dt,{title:t("settings.usage.page.section.modelQuotas"),contentClassName:"space-y-3",children:[I.map(R=>{const z=b.get(R.id)??[];if(z.length===0)return null;const q=B[R.id]??!1;return s.jsx("section",{className:"p-2",children:s.jsxs(da,{open:!q,onOpenChange:()=>D(R.id),children:[s.jsxs(ua,{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:R.label}),s.jsxs("span",{className:"typography-micro text-muted-foreground",children:["(",z.length,")"]})]}),q?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(ma,{children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)] mt-1",children:z.map(H=>{const Z=Object.entries(H.windows.windows);if(Z.length===0)return null;const[W,A]=Z[0],X=F.includes(H.name);return s.jsx(lo,{title:W,subtitle:fd(H.name),window:A,showToggle:!0,toggleEnabled:X,onToggle:()=>S(H.name)},H.name)})})})]})},R.id)}),(()=>{const R=b.get(null)??[];if(R.length===0)return null;const z=B.other??!1;return s.jsx("section",{className:"p-2",children:s.jsxs(da,{open:!z,onOpenChange:()=>D("other"),children:[s.jsxs(ua,{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:["(",R.length,")"]})]}),z?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(ma,{children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)] mt-1",children:R.map(q=>{const H=Object.entries(q.windows.windows);if(H.length===0)return null;const[Z,W]=H[0],A=F.includes(q.name);return s.jsx(lo,{title:Z,subtitle:fd(q.name),window:W,showToggle:!0,toggleEnabled:A,onToggle:()=>S(q.name)},q.name)})})})]})})})()]}),f?.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")})})},S1="git.commit.generate",tl=fn(t=>({selectedPromptId:S1,setSelectedPromptId:e=>{t(n=>n.selectedPromptId===e?n:{selectedPromptId:e})}})),C1=t=>{const e=Ze.c(23),{onItemSelect:n}=t,{t:a}=ot(),i=tl(I1),r=tl(P1);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 g;e[4]!==a?(g=a("settings.magicPrompts.sidebar.title"),e[4]=a,e[5]=g):g=e[5];let m;e[6]!==g?(m=s.jsx("h2",{className:hn,children:g}),e[6]=g,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 h;e[10]!==w?(h=s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:w}),e[10]=w,e[11]=h):h=e[11];let f;e[12]!==m||e[13]!==h?(f=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[m,h]}),e[12]=m,e[13]=h,e[14]=f):f=e[14];let x;e[15]!==n||e[16]!==i||e[17]!==r||e[18]!==a?(x=s.jsx(zs,{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 O=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",O?"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]!==f?(k=s.jsxs("div",{className:"flex h-full flex-col bg-background",children:[f,x]}),e[20]=x,e[21]=f,e[22]=k):k=e[22],k};function I1(t){return t.selectedPromptId}function P1(t){return t.setSelectedPromptId}const xd={"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"}]}},bd=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),co=t=>t.endsWith(".visible"),T1=()=>{const{t}=ot(),e=l.useCallback(N=>t(N),[t]),n=tl(N=>N.selectedPromptId),[a,i]=l.useState(!0),[r,o]=l.useState({}),[d,c]=l.useState({}),[p,u]=l.useState({}),[g,m]=l.useState({}),[w,h]=l.useState(!1);l.useEffect(()=>{let N=!0;return(async()=>{i(!0);try{const I=await Gp();if(!N)return;o(I)}catch(I){console.warn("Failed to load magic prompts:",I),Q.error(t("settings.magicPrompts.page.toast.loadFailed"))}finally{N&&i(!1)}})(),()=>{N=!1}},[t]);const f=xd[n]??xd["git.commit.generate"],x=l.useCallback(N=>bd(r,N)?r[N]:Vr(N),[r]),k=l.useCallback(N=>d[N]??x(N),[d,x]),y=l.useCallback((N,b)=>{c(I=>I[N]===b?I:{...I,[N]:b})},[]),C=l.useCallback(async N=>{const b=k(N);if(co(N)&&b.trim().length===0){Q.error(t("settings.magicPrompts.page.toast.visiblePromptRequired"));return}u(I=>({...I,[N]:!0}));try{const I=b===Vr(N)?await Dl(N):await Vp(N,b);o(I.overrides),Q.success(t("settings.magicPrompts.page.toast.saved"))}catch(I){const B=I instanceof Error?I.message:String(I);Q.error(t("settings.magicPrompts.page.toast.saveFailed"),{description:B})}finally{u(I=>({...I,[N]:!1}))}},[k,t]),O=l.useCallback(async N=>{m(b=>({...b,[N]:!0}));try{const b=await Dl(N);o(b.overrides),c(I=>({...I,[N]:Vr(N)})),Q.success(t("settings.magicPrompts.page.toast.resetSuccess"))}catch(b){const I=b instanceof Error?b.message:String(b);Q.error(t("settings.magicPrompts.page.toast.resetFailed"),{description:I})}finally{m(b=>({...b,[N]:!1}))}},[t]),j=l.useCallback(async()=>{h(!0);try{const N=await Hp();o(N.overrides),c({}),Q.success(t("settings.magicPrompts.page.toast.resetAllSuccess"))}catch(N){const b=N instanceof Error?N.message:String(N);Q.error(t("settings.magicPrompts.page.toast.resetAllFailed"),{description:b})}finally{h(!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(f.titleKey),titleAccessory:s.jsx($t,{contentClassName:"max-w-xs",children:e(f.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:f.blocks.map((N,b)=>{const I=Wp(N.id),B=x(N.id),T=k(N.id),D=bd(r,N.id),S=T!==B,F=co(N.id)&&T.trim().length===0,R=p[N.id]===!0,z=g[N.id]===!0;return s.jsxs(dt,{title:e(N.titleKey),info:I.description,description:I.placeholders&&I.placeholders.length>0?`${t("settings.magicPrompts.page.placeholdersLabel")} ${I.placeholders.map(q=>`{{${q.key}}}`).join(", ")}`:void 0,divider:b>0,settingsItem:co(N.id)?"magic-prompts.visible-prompt":"magic-prompts.instructions",contentClassName:"space-y-3",children:[s.jsx(Ns,{value:T,onChange:q=>y(N.id,q.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":D?"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:()=>{O(N.id)},disabled:!D||R||z,children:t(z?"settings.magicPrompts.page.actions.resetting":"settings.magicPrompts.page.actions.resetToDefault")}),s.jsx(ee,{size:"sm",onClick:()=>{C(N.id)},disabled:!S||R||z||F,children:t(R?"settings.common.actions.saving":"settings.magicPrompts.page.actions.save")})]})]})]},N.id)})})},A1=t=>{const e=Ze.c(89),{onItemSelect:n}=t,{t:a}=ot(),[i,r]=l.useState(null),[o,d]=l.useState(null),[c,p]=l.useState(null),{selectedSnippetName:u,snippets:g,setSelectedSnippet:m,setSnippetDraft:w,deleteSnippet:h,loadSnippets:f}=Ir(Ws(E1));let x,k;e[0]!==f?(x=()=>{f()},k=[f],e[0]=f,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]!==g?(y=async()=>{const re=new Set(g.map(D1));let ce="new-snippet",ge=1;for(;re.has(ce);)ce=`new-snippet-${ge++}`;w({name:ce,scope:"global"}),m(ce),n?.()},e[3]=n,e[4]=m,e[5]=w,e[6]=g,e[7]=y):y=e[7];const C=y;let O;e[8]!==i||e[9]!==h||e[10]!==a?(O=async()=>{if(!i)return;await h(i.name)?(Q.success(a("settings.snippets.sidebar.toast.deleted")),r(null)):Q.error(a("settings.snippets.sidebar.toast.deleteFailed"))},e[8]=i,e[9]=h,e[10]=a,e[11]=O):O=e[11];const j=O;let N;e[12]!==g?(N=[...g].sort(R1),e[12]=g,e[13]=N):N=e[13];const b=N;let I;e[14]===Symbol.for("react.memo_cache_sentinel")?(I=fe("flex h-full flex-col","bg-background"),e[14]=I):I=e[14];let B;e[15]!==a?(B=a("settings.snippets.sidebar.title"),e[15]=a,e[16]=B):B=e[16];let T;e[17]!==B?(T=s.jsx("h2",{className:`${hn} mb-3`,children:B}),e[17]=B,e[18]=T):T=e[18];let D;e[19]!==g.length||e[20]!==a?(D=a("settings.snippets.sidebar.total",{count:g.length}),e[19]=g.length,e[20]=a,e[21]=D):D=e[21];let S;e[22]!==D?(S=s.jsx("span",{className:"typography-meta text-muted-foreground",children:D}),e[22]=D,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 R;e[26]===Symbol.for("react.memo_cache_sentinel")?(R=s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),e[26]=R):R=e[26];let z;e[27]!==C||e[28]!==F?(z=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:R}),e[27]=C,e[28]=F,e[29]=z):z=e[29];let q;e[30]!==S||e[31]!==z?(q=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[S,z]}),e[30]=S,e[31]=z,e[32]=q):q=e[32];let H;e[33]!==q||e[34]!==T?(H=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[T,q]}),e[33]=q,e[34]=T,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]!==b||e[42]!==a){let re;e[44]!==n||e[45]!==o||e[46]!==c||e[47]!==u||e[48]!==m||e[49]!==a?(re=ce=>s.jsxs(Gn,{open:c===ce.name,onOpenChange:ge=>p(ge?ce.name:null),children:[s.jsxs(qn,{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:ge=>{ge.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:ge=>{ge&&p(null),d(ge?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:ge=>{ge.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(Jn,{className:"w-fit min-w-20",children:s.jsxs(An,{onClick:ge=>{ge.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]=re):re=e[50],Z=b.map(re),e[36]=n,e[37]=o,e[38]=c,e[39]=u,e[40]=m,e[41]=b,e[42]=a,e[43]=Z}else Z=e[43];let W;e[51]!==Z?(W=s.jsx(zs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:Z}),e[51]=Z,e[52]=W):W=e[52];const A=i!==null;let X;e[53]===Symbol.for("react.memo_cache_sentinel")?(X=re=>{re||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 E;e[56]!==te?(E=s.jsx(_t,{children:te}),e[56]=te,e[57]=E):E=e[57];const P=i?.name??"";let _;e[58]!==a||e[59]!==P?(_=a("settings.snippets.sidebar.dialog.deleteDescription",{name:P}),e[58]=a,e[59]=P,e[60]=_):_=e[60];let L;e[61]!==_?(L=s.jsx(Yt,{children:_}),e[61]=_,e[62]=L):L=e[62];let V;e[63]!==E||e[64]!==L?(V=s.jsxs(Ut,{children:[E,L]}),e[63]=E,e[64]=L,e[65]=V):V=e[65];let Y;e[66]===Symbol.for("react.memo_cache_sentinel")?(Y=()=>r(null),e[66]=Y):Y=e[66];let G;e[67]!==a?(G=a("settings.common.actions.cancel"),e[67]=a,e[68]=G):G=e[68];let me;e[69]!==G?(me=s.jsx(ee,{size:"sm",variant:"ghost",onClick:Y,children:G}),e[69]=G,e[70]=me):me=e[70];let ae;e[71]!==a?(ae=a("settings.common.actions.delete"),e[71]=a,e[72]=ae):ae=e[72];let xe;e[73]!==j||e[74]!==ae?(xe=s.jsx(ee,{size:"sm",onClick:j,children:ae}),e[73]=j,e[74]=ae,e[75]=xe):xe=e[75];let be;e[76]!==me||e[77]!==xe?(be=s.jsxs(rs,{children:[me,xe]}),e[76]=me,e[77]=xe,e[78]=be):be=e[78];let ie;e[79]!==V||e[80]!==be?(ie=s.jsxs(Bt,{className:"max-w-md",children:[V,be]}),e[79]=V,e[80]=be,e[81]=ie):ie=e[81];let pe;e[82]!==A||e[83]!==ie?(pe=s.jsx(Kt,{open:A,onOpenChange:X,children:ie}),e[82]=A,e[83]=ie,e[84]=pe):pe=e[84];let Ie;return e[85]!==H||e[86]!==W||e[87]!==pe?(Ie=s.jsxs("div",{className:I,children:[H,W,pe]}),e[85]=H,e[86]=W,e[87]=pe,e[88]=Ie):Ie=e[88],Ie};function E1(t){return{selectedSnippetName:t.selectedSnippetName,snippets:t.snippets,setSelectedSnippet:t.setSelectedSnippet,setSnippetDraft:t.setSnippetDraft,deleteSnippet:t.deleteSnippet,loadSnippets:t.loadSnippets}}function D1(t){return t.name}function R1(t,e){return t.name.localeCompare(e.name)}const M1=()=>{const{t}=ot(),{selectedSnippetName:e,snippets:n,snippetDraft:a,setSnippetDraft:i,updateSnippet:r,createSnippet:o}=Ir(Ws(I=>({selectedSnippetName:I.selectedSnippetName,snippets:I.snippets,snippetDraft:I.snippetDraft,setSnippetDraft:I.setSnippetDraft,updateSnippet:I.updateSnippet,createSnippet:I.createSnippet}))),d=l.useMemo(()=>e?n.find(I=>I.name===e||I.aliases.includes(e))??null:null,[e,n]),c=!!(a&&a.name===e&&!d),[p,u]=l.useState(""),[g,m]=l.useState("global"),[w,h]=l.useState(""),[f,x]=l.useState(""),[k,y]=l.useState(""),[C,O]=l.useState(!1),j=l.useRef(null);l.useEffect(()=>{if(c&&a){const I={draftName:a.name||"",draftScope:a.scope||"global",description:a.description||"",aliases:(a.aliases||[]).join(", "),content:a.content||""};u(I.draftName),m(I.draftScope),h(I.description),x(I.aliases),y(I.content),j.current=I}else if(d){const I={draftName:"",draftScope:"global",description:d.description??"",aliases:d.aliases.join(", "),content:d.content};h(I.description),x(I.aliases),y(I.content),j.current=I}},[d,c,e,a]);const N=l.useMemo(()=>{const I=j.current;return I?c&&p!==I.draftName||c&&g!==I.draftScope?!0:w!==I.description||f!==I.aliases||k!==I.content:!1},[f,k,w,p,g,c]),b=async()=>{const I=c?p.trim().replace(/\s+/g,"-"):e?.trim();if(!I){Q.error(t("settings.snippets.page.toast.nameRequired"));return}if(!k.trim()){Q.error(t("settings.snippets.page.toast.contentRequired"));return}const B=f.split(",").map(T=>T.trim()).filter(Boolean);O(!0);try{if(!(c?await o(I,k,{aliases:B,description:w,scope:g}):await r(I,{content:k,aliases:B,description:w}))){Q.error(t("settings.snippets.page.toast.saveFailed"));return}Q.success(t("settings.snippets.page.toast.saved")),c&&i(null)}finally{O(!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(nt,{value:p,onChange:I=>u(I.target.value),placeholder:t("settings.snippets.page.field.namePlaceholder"),className:"h-7 w-44 px-2"}),s.jsxs(Mt,{value:g,onValueChange:I=>m(I),children:[s.jsx(Lt,{size:Gt,className:"w-fit min-w-[100px]",children:s.jsx(Wt,{})}),s.jsxs(Ft,{align:"end",children:[s.jsx(jt,{value:"global",children:t("settings.common.scope.global")}),s.jsx(jt,{value:"project",children:t("settings.common.scope.project")})]})]})]}):null,s.jsx(ns,{label:t("settings.common.field.description"),children:s.jsx(nt,{value:w,onChange:I=>h(I.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(nt,{value:f,onChange:I=>x(I.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:I=>y(I.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:b,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")})]})})},cm=()=>{const{t}=ot(),e=pt(g=>g.settingsGitmojiEnabled),n=pt(g=>g.setSettingsGitmojiEnabled),a=Gg(),i=je(g=>g.gitChangesViewMode),r=je(g=>g.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=an()?.settings;if(w)try{const f=(await w.load())?.settings;f&&(m={gitmojiEnabled:typeof f.gitmojiEnabled=="boolean"?f.gitmojiEnabled:void 0,gitChangesViewMode:f.gitChangesViewMode==="flat"||f.gitChangesViewMode==="tree"?f.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 g=>{n(g);try{await It({gitmojiEnabled:g})}catch(m){console.warn("Failed to save gitmoji setting:",m)}},[n]),u=l.useCallback(g=>{g!==i&&(r(g),It({gitChangesViewMode:g}))},[i,r]);return o?null:s.jsx(dt,{title:t("settings.openchamber.git.title"),children:s.jsxs("div",{className:Ds,children:[s.jsx(en,{settingsItem:"git.changes-view",title:t("settings.openchamber.git.changesViewTitle"),children:s.jsx(Kn,{"aria-label":t("settings.openchamber.git.changesViewAria"),children:c.map(g=>s.jsx(zn,{selected:i===g.id,onSelect:()=>{u(g.id)},label:g.label,ariaLabel:t("settings.openchamber.git.optionAria",{option:g.label})},g.id))})}),s.jsx(Ct,{settingsItem:"git.gitmoji",checked:e,onChange:g=>{p(g)},label:t("settings.openchamber.git.enableGitmoji"),ariaLabel:t("settings.openchamber.git.enableGitmojiAria")}),s.jsx(Ct,{settingsItem:"git.gitignored-files",checked:a,onChange:qg,label:t("settings.openchamber.git.showGitignored"),ariaLabel:t("settings.openchamber.git.showGitignoredAria")})]})})},dm=()=>{const{t}=ot(),{isMobile:e}=Hs(),n=an()?.github,a=Cn(S=>S.status),i=Cn(S=>S.isLoading),r=Cn(S=>S.hasChecked),o=Cn(S=>S.refreshStatus),d=Cn(S=>S.setStatus),c=l.useCallback(async S=>{await Hn(S)},[]),[p,u]=l.useState(!1),[g,m]=l.useState(null),[w,h]=l.useState(null),f=l.useRef(null),x=l.useCallback(()=>{f.current!=null&&(window.clearInterval(f.current),f.current=null),h(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 R=await ht("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),z=await R.json().catch(()=>null);if(!R.ok||!z||!("deviceCode"in z))throw new Error(z?.error||R.statusText);return z})();m(S),h(Math.max(1,S.interval)*1e3);const F=S.verificationUriComplete||S.verificationUri;c(F)}catch(S){console.error("Failed to start GitHub connect:",S),Q.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})}),R=await F.json().catch(()=>null);if(!F.ok||!R)throw new Error(R?.error||F.statusText);return R},[n]);l.useEffect(()=>{if(!(!g?.deviceCode||!w)&&f.current==null)return f.current=window.setInterval(()=>{(async()=>{try{const S=await y(g.deviceCode);if(S.connected){Q.success(t("settings.github.page.toast.connected")),m(null),x(),await o(n,{force:!0});return}S.status==="slow_down"&&h(F=>F?F+5e3:5e3),(S.status==="expired_token"||S.status==="access_denied")&&(Q.error(S.error||t("settings.github.page.toast.authorizationFailed")),m(null),x())}catch(S){console.warn("GitHub polling failed:",S)}})()},w),()=>{f.current!=null&&(window.clearInterval(f.current),f.current=null)}},[g,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})}),R=await F.json().catch(()=>null);if(!F.ok)throw new Error(R?.error||F.statusText)}Q.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),Q.error(t("settings.github.page.toast.ghCliUpdateFailed"))}finally{u(!1)}},[o,n,t]),O=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)}Q.success(t("settings.github.page.toast.disconnected")),await o(n,{force:!0})}catch(S){console.error("Failed to disconnect GitHub:",S),Q.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 R=await ht("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:S})}),z=await R.json().catch(()=>null);if(!R.ok||!z)throw new Error(z?.error||R.statusText);return z})();d(F),Q.success(t("settings.github.page.toast.accountSwitched"))}catch(F){console.error("Failed to switch GitHub account:",F),Q.error(t("settings.github.page.toast.accountSwitchFailed"))}finally{u(!1)}}},[n,d,t]);if(i)return null;const N=!!a?.connected,b=a?.user,B=(a?.accounts??[]).filter(S=>!S.current),T=a?.ghCli??null,D=T?.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:[b?.avatarUrl?s.jsx("img",{src:b.avatarUrl,alt:b.login?t("settings.github.page.avatarAlt.withLogin",{login:b.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:b?.name?.trim()||b?.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:b?.login||t("settings.github.page.label.unknownUser")}),b?.email&&s.jsx("span",{className:"opacity-50",children:"•"}),b?.email&&s.jsx("span",{children:b.email}),s.jsx("span",{className:"opacity-50",children:"•"}),s.jsx("span",{children:D})]}),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})}),T?.active&&s.jsx("div",{className:"typography-micro text-muted-foreground/70 mt-0.5",children:t("settings.github.page.ghCli.activeDescription")})]})]}),T?.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:O,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")})]}),B.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:B.map(S=>{const F=S.user,R=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:R})]})]})]}),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")})}),g&&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(gn,{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:g.userCode}),s.jsx(ee,{size:"sm",asChild:!0,children:s.jsx("a",{href:g.verificationUriComplete||g.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")})]})]})]}),T?.available&&!T?.active&&(!T.user||T.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:[T.user?.avatarUrl?s.jsx("img",{src:T.user.avatarUrl,alt:T.user.login?t("settings.github.page.avatarAlt.withLogin",{login:T.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:[!T.disabled&&T.user&&s.jsx("div",{className:"typography-ui-label text-foreground truncate",children:T.user.name?.trim()||T.user.login||"GitHub"}),!T.disabled&&T.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:T.user.login}),T.user.email&&s.jsx("span",{className:"opacity-50",children:"•"}),T.user.email&&s.jsx("span",{children:T.user.email})]}),s.jsx("div",{className:fe("typography-meta text-muted-foreground",T.disabled?"opacity-60":void 0),children:T.disabled?t("settings.github.page.ghCli.disabledDescription"):t("settings.github.page.ghCli.fallbackDescription")})]})]}),s.jsx(ee,{size:"sm",variant:"outline",onClick:()=>C(!T.disabled),disabled:p,className:fe(e?"w-full":void 0),children:T.disabled?t("settings.github.page.ghCli.actions.enable"):t("settings.github.page.ghCli.actions.disable")})]})})})]})},yd=[{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)"}],L1=[{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"}],F1=({open:t,onOpenChange:e,profileId:n,importData:a})=>{const{t:i}=ot(),r=Vs(L=>L.getProfileById),o=Vs(L=>L.createProfile),d=Vs(L=>L.updateProfile),c=Vs(L=>L.deleteProfile),p=l.useMemo(()=>n&&n!=="new"&&!a?r(n):null,[n,r,a]),u=n==="new"||a!=null,g=n==="global",[m,w]=l.useState(""),[h,f]=l.useState(""),[x,k]=l.useState(""),[y,C]=l.useState("ssh"),[O,j]=l.useState(""),[N,b]=l.useState(!1),[I,B]=l.useState(""),[T,D]=l.useState(""),[S,F]=l.useState("keyword"),[R,z]=l.useState("branch"),[q,H]=l.useState(!1),[Z,W]=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),f(a.username),k(""),C("token"),j(""),b(!1),B(""),D(a.host),F("string"),z("code")}else if(u)w(""),f(""),k(""),C("ssh"),j(""),b(!1),B(""),D(""),F("keyword"),z("branch");else if(p)w(p.name),f(p.userName),k(p.userEmail),C(p.authType||"ssh"),j(p.sshKey||""),b(p.signCommits===!0),B(p.signingKey||""),D(p.host||""),F(p.color||"keyword"),z(p.icon||"branch");else if(g){const L=r("global");L&&(w(L.name),f(L.userName),k(L.userEmail),C(L.authType||"ssh"),j(L.sshKey||""),b(!1),B(""),D(L.host||""),F(L.color||"keyword"),z(L.icon||"branch"))}}},[t,n,p,u,a,g,r]);const te=async()=>{if(!h.trim()||!x.trim()){Q.error(i("settings.gitIdentities.editor.toast.userNameEmailRequired"));return}if(y==="token"&&!T.trim()){Q.error(i("settings.gitIdentities.editor.toast.hostRequiredForToken"));return}if(N&&!I.trim()){Q.error(i("settings.gitIdentities.editor.toast.signingKeyRequired"));return}H(!0);try{const L={name:m.trim()||h.trim(),userName:h.trim(),userEmail:x.trim(),authType:y,sshKey:y==="ssh"&&O.trim()||null,signCommits:N,signingKey:I.trim()||null,host:y==="token"&&T.trim()||null,color:S,icon:R};let V;if(u)V=await o(L);else if(n)V=await d(n,L);else return;V?(Q.success(i(u?"settings.gitIdentities.editor.toast.profileCreated":"settings.gitIdentities.editor.toast.profileUpdated")),e(!1)):Q.error(i(u?"settings.gitIdentities.editor.toast.createProfileFailed":"settings.gitIdentities.editor.toast.updateProfileFailed"))}catch(L){console.error("Error saving profile:",L),Q.error(i("settings.gitIdentities.editor.toast.saveUnexpectedError"))}finally{H(!1)}},E=async()=>{if(!(!n||u)){X(!0);try{await c(n)?(Q.success(i("settings.gitIdentities.editor.toast.profileDeleted")),W(!1),e(!1)):Q.error(i("settings.gitIdentities.editor.toast.deleteProfileFailed"))}catch(L){console.error("Error deleting profile:",L),Q.error(i("settings.gitIdentities.editor.toast.deleteUnexpectedError"))}finally{X(!1)}}},P=l.useMemo(()=>yd.find(V=>V.key===S)?.cssVar||"var(--syntax-keyword)",[S]),_=a?i("settings.gitIdentities.editor.title.importCredential"):u?i("settings.gitIdentities.editor.title.newIdentity"):g?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:_}),s.jsx(Yt,{children:i(g?"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:[!g&&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(nt,{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:yd.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:L1.map(L=>{const V=L.Icon;return s.jsx("button",{type:"button",onClick:()=>z(L.key),className:fe("w-7 h-7 rounded-md border-2 transition-all flex items-center justify-center cursor-pointer",R===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:R===L.key?P:"var(--surface-muted-foreground)"}})},L.key)})})]})]}),!g&&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")}),!g&&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(nt,{value:h,onChange:L=>f(L.target.value),placeholder:i("settings.gitIdentities.editor.field.userNamePlaceholder"),required:!g,readOnly:g,disabled:g,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")}),!g&&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(nt,{type:"email",value:x,onChange:L=>k(L.target.value),placeholder:i("settings.gitIdentities.editor.field.emailAddressPlaceholder"),required:!g,readOnly:g,disabled:g,className:"h-8"})]})]}),!g&&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(nt,{value:O,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:b,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(nt,{value:I,onChange:L=>B(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(nt,{value:T,onChange:L=>D(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:[!g&&!u&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>W(!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(g?"settings.gitIdentities.editor.actions.close":"settings.common.actions.cancel")}),!g&&s.jsx(ee,{size:"sm",onClick:te,disabled:q,children:i(q?"settings.common.actions.saving":u?"settings.gitIdentities.editor.actions.create":"settings.gitIdentities.editor.actions.save")})]})]})}),s.jsx(Kt,{open:Z,onOpenChange:L=>{A||W(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:()=>W(!1),disabled:A,children:i("settings.common.actions.cancel")}),s.jsx(ee,{size:"sm",variant:"destructive",onClick:()=>{E()},disabled:A,children:i("settings.common.actions.delete")})]})]})})]})},O1={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart"},z1={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},K1=()=>{const t=Ze.c(113),{t:e}=ot(),{profiles:n,globalIdentity:a,defaultGitIdentityId:i,deleteProfile:r,loadProfiles:o,loadGlobalIdentity:d,loadDiscoveredCredentials:c,loadDefaultGitIdentityId:p,setDefaultGitIdentityId:u,getUnimportedCredentials:g}=Vs(Ws(_1)),[m,w]=l.useState(!1),[h,f]=l.useState(null),[x,k]=l.useState(null),[y,C]=l.useState(null),[O,j]=l.useState(!1);let N,b;t[0]!==p||t[1]!==c||t[2]!==d||t[3]!==o?(N=()=>{o(),d(),c(),p()},b=[o,d,c,p],t[0]=p,t[1]=c,t[2]=d,t[3]=o,t[4]=N,t[5]=b):(N=t[4],b=t[5]),l.useEffect(N,b);let I,B,T,D,S,F,R,z,q,H,Z,W,A,X;if(t[6]!==i||t[7]!==y||t[8]!==r||t[9]!==g||t[10]!==a||t[11]!==n||t[12]!==u||t[13]!==e){const Le=g();let Ke;t[28]===Symbol.for("react.memo_cache_sentinel")?(Ke=(_e,Oe)=>{f(_e),k(Oe??null),w(!0)},t[28]=Ke):Ke=t[28];const Fe=Ke;let Me;t[29]!==i||t[30]!==u||t[31]!==e?(Me=async _e=>{const Oe=i===_e?null:_e;if(!await u(Oe)){Q.error(e("settings.gitIdentities.page.toast.updateDefaultFailed"));return}Q.success(e(Oe?"settings.gitIdentities.page.toast.defaultUpdated":"settings.gitIdentities.page.toast.defaultUnset"))},t[29]=i,t[30]=u,t[31]=e,t[32]=Me):Me=t[32];const Be=Me;let Ge;t[33]!==y||t[34]!==r||t[35]!==e?(Ge=async()=>{if(!y)return;j(!0),await r(y.id)?(Q.success(e("settings.gitIdentities.page.toast.profileDeleted",{name:y.name})),C(null)):Q.error(e("settings.gitIdentities.page.toast.deleteProfileFailed")),j(!1)},t[33]=y,t[34]=r,t[35]=e,t[36]=Ge):Ge=t[36],T=Ge,B=ps,t[37]!==e?(D=e("settings.page.git.title"),t[37]=e,t[38]=D):D=t[38],S=!0,t[39]===Symbol.for("react.memo_cache_sentinel")?(F=s.jsx(dm,{}),t[39]=F):F=t[39],I=dt,t[40]!==e?(W=e("settings.gitIdentities.page.section.title"),t[40]=e,t[41]=W):W=t[41];let Ve,Ue;t[42]===Symbol.for("react.memo_cache_sentinel")?(Ve=()=>Fe("new"),Ue=s.jsx(K,{name:"add",className:"w-3.5 h-3.5 mr-1"}),t[42]=Ve,t[43]=Ue):(Ve=t[42],Ue=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:Ve,children:[Ue," ",He]}),t[46]=He,t[47]=A):A=t[47],X="git.identities",R="rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",z=a&&s.jsx(vd,{profile:a,isDefault:i==="global",onEdit:()=>Fe("global"),onToggleDefault:()=>Be("global"),isReadOnly:!0,hasBorder:n.length>0||Le.length>0}),q=n.map((_e,Oe)=>s.jsx(vd,{profile:_e,isDefault:i===_e.id,onEdit:()=>Fe(_e.id),onToggleDefault:()=>Be(_e.id),onDelete:()=>C(_e),hasBorder:Oe<n.length-1||Le.length>0},_e.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((_e,Oe)=>s.jsx(B1,{credential:_e,onImport:()=>Fe("new",{host:_e.host,username:_e.username}),hasBorder:Oe<Le.length-1},`${_e.host}-${_e.username}`))]}),t[6]=i,t[7]=y,t[8]=r,t[9]=g,t[10]=a,t[11]=n,t[12]=u,t[13]=e,t[14]=I,t[15]=B,t[16]=T,t[17]=D,t[18]=S,t[19]=F,t[20]=R,t[21]=z,t[22]=q,t[23]=H,t[24]=Z,t[25]=W,t[26]=A,t[27]=X}else I=t[14],B=t[15],T=t[16],D=t[17],S=t[18],F=t[19],R=t[20],z=t[21],q=t[22],H=t[23],Z=t[24],W=t[25],A=t[26],X=t[27];let te;t[48]!==R||t[49]!==z||t[50]!==q||t[51]!==H||t[52]!==Z?(te=s.jsxs("div",{className:R,children:[z,q,H,Z]}),t[48]=R,t[49]=z,t[50]=q,t[51]=H,t[52]=Z,t[53]=te):te=t[53];let E;t[54]!==I||t[55]!==te||t[56]!==W||t[57]!==A||t[58]!==X?(E=s.jsx(I,{title:W,headerAction:A,settingsItem:X,children:te}),t[54]=I,t[55]=te,t[56]=W,t[57]=A,t[58]=X,t[59]=E):E=t[59];let P;t[60]===Symbol.for("react.memo_cache_sentinel")?(P=s.jsx(cm,{}),t[60]=P):P=t[60];let _;t[61]!==B||t[62]!==D||t[63]!==S||t[64]!==F||t[65]!==E?(_=s.jsxs(B,{title:D,showSaveStatus:S,children:[F,E,P]}),t[61]=B,t[62]=D,t[63]=S,t[64]=F,t[65]=E,t[66]=_):_=t[66];let L;t[67]!==x||t[68]!==m||t[69]!==h?(L=s.jsx(F1,{open:m,onOpenChange:w,profileId:h,importData:x}),t[67]=x,t[68]=m,t[69]=h,t[70]=L):L=t[70];const V=y!==null;let Y;t[71]!==O?(Y=Le=>{O||Le||C(null)},t[71]=O,t[72]=Y):Y=t[72];let G;t[73]!==e?(G=e("settings.gitIdentities.page.deleteDialog.title"),t[73]=e,t[74]=G):G=t[74];let me;t[75]!==G?(me=s.jsx(_t,{children:G}),t[75]=G,t[76]=me):me=t[76];const ae=y?.name??"";let xe;t[77]!==e||t[78]!==ae?(xe=e("settings.gitIdentities.page.deleteDialog.description",{name:ae}),t[77]=e,t[78]=ae,t[79]=xe):xe=t[79];let be;t[80]!==xe?(be=s.jsx(Yt,{children:xe}),t[80]=xe,t[81]=be):be=t[81];let ie;t[82]!==me||t[83]!==be?(ie=s.jsxs(Ut,{children:[me,be]}),t[82]=me,t[83]=be,t[84]=ie):ie=t[84];let pe;t[85]===Symbol.for("react.memo_cache_sentinel")?(pe=()=>C(null),t[85]=pe):pe=t[85];let Ie;t[86]!==e?(Ie=e("settings.common.actions.cancel"),t[86]=e,t[87]=Ie):Ie=t[87];let re;t[88]!==O||t[89]!==Ie?(re=s.jsx(ee,{variant:"ghost",onClick:pe,disabled:O,children:Ie}),t[88]=O,t[89]=Ie,t[90]=re):re=t[90];let ce;t[91]!==T?(ce=()=>{T()},t[91]=T,t[92]=ce):ce=t[92];let ge;t[93]!==e?(ge=e("settings.common.actions.delete"),t[93]=e,t[94]=ge):ge=t[94];let oe;t[95]!==O||t[96]!==ce||t[97]!==ge?(oe=s.jsx(ee,{size:"sm",variant:"destructive",onClick:ce,disabled:O,children:ge}),t[95]=O,t[96]=ce,t[97]=ge,t[98]=oe):oe=t[98];let de;t[99]!==re||t[100]!==oe?(de=s.jsxs(rs,{children:[re,oe]}),t[99]=re,t[100]=oe,t[101]=de):de=t[101];let le;t[102]!==ie||t[103]!==de?(le=s.jsxs(Bt,{className:"max-w-md",children:[ie,de]}),t[102]=ie,t[103]=de,t[104]=le):le=t[104];let he;t[105]!==V||t[106]!==Y||t[107]!==le?(he=s.jsx(Kt,{open:V,onOpenChange:Y,children:le}),t[105]=V,t[106]=Y,t[107]=le,t[108]=he):he=t[108];let De;return t[109]!==_||t[110]!==L||t[111]!==he?(De=s.jsxs(s.Fragment,{children:[_,L,he]}),t[109]=_,t[110]=L,t[111]=he,t[112]=De):De=t[112],De},vd=t=>{const e=Ze.c(56),{profile:n,isDefault:a,onEdit:i,onToggleDefault:r,onDelete:o,isReadOnly:d,hasBorder:c}=t,{t:p}=ot(),[u,g]=l.useState(!1),m=O1[n.icon||"branch"]||"git-branch",w=z1[n.color||""],h=n.authType||"ssh";let f;e[0]!==i?(f=E=>{E.currentTarget===E.target&&(E.key!=="Enter"&&E.key!==" "||(E.preventDefault(),i()))},e[0]=i,e[1]=f):f=e[1];const x=f;let k;e[2]!==a||e[3]!==d||e[4]!==o||e[5]!==r||e[6]!==p?(k=E=>s.jsxs(s.Fragment,{children:[s.jsx(E,{onClick:P=>{P.stopPropagation(),r()},children:p(a?"settings.gitIdentities.page.actions.unsetDefault":"settings.gitIdentities.page.actions.setAsDefault")}),!d&&o&&s.jsxs(E,{onClick:P=>{P.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 O;e[8]!==C?(O=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]=O):O=e[9];let j;e[10]===Symbol.for("react.memo_cache_sentinel")?(j=E=>{E.preventDefault(),g(!0)},e[10]=j):j=e[10];let N;e[11]!==x||e[12]!==i||e[13]!==O?(N=s.jsx("div",{className:O,onClick:i,role:"button",tabIndex:0,onKeyDown:x,onContextMenu:j}),e[11]=x,e[12]=i,e[13]=O,e[14]=N):N=e[14];let b;e[15]!==w?(b={color:w},e[15]=w,e[16]=b):b=e[16];let I;e[17]!==m||e[18]!==b?(I=s.jsx(K,{name:m,className:"w-4 h-4 shrink-0",style:b}),e[17]=m,e[18]=b,e[19]=I):I=e[19];let B;e[20]!==n.name?(B=s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:n.name}),e[20]=n.name,e[21]=B):B=e[21];let T;e[22]!==h?(T=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:h}),e[22]=h,e[23]=T):T=e[23];let D;e[24]!==a||e[25]!==p?(D=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]=D):D=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]!==T||e[31]!==D||e[32]!==S||e[33]!==B?(F=s.jsxs("div",{className:"flex items-center gap-1.5",children:[B,T,D,S]}),e[30]=T,e[31]=D,e[32]=S,e[33]=B,e[34]=F):F=e[34];const R=h==="token"&&n.host?n.host:n.userEmail;let z;e[35]!==R?(z=s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:R}),e[35]=R,e[36]=z):z=e[36];let q;e[37]!==F||e[38]!==z?(q=s.jsxs("div",{className:"min-w-0",children:[F,z]}),e[37]=F,e[38]=z,e[39]=q):q=e[39];let H;e[40]!==q||e[41]!==I?(H=s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[I,q]}),e[40]=q,e[41]=I,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:U1,children:s.jsx(K,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[43]=Z):Z=e[43];let W;e[44]!==y?(W=s.jsxs(fs,{children:[Z,s.jsx(hs,{align:"end",className:"w-fit min-w-28",children:y(as)})]}),e[44]=y,e[45]=W):W=e[45];let A;e[46]!==H||e[47]!==W||e[48]!==N?(A=s.jsxs(qn,{render:N,children:[H,W]}),e[46]=H,e[47]=W,e[48]=N,e[49]=A):A=e[49];let X;e[50]!==y?(X=s.jsx(Jn,{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(Gn,{open:u,onOpenChange:g,children:[A,X]}),e[52]=u,e[53]=A,e[54]=X,e[55]=te):te=e[55],te},B1=t=>{const e=Ze.c(21),{credential:n,onImport:a,hasBorder:i}=t,{t:r}=ot();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 g;e[2]!==u?(g=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]=g):g=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 h;e[6]!==w?(h=s.jsx("span",{className:"typography-micro text-muted-foreground/60 truncate block leading-tight",children:w}),e[6]=w,e[7]=h):h=e[7];let f;e[8]!==m||e[9]!==h?(f=s.jsxs("div",{className:"min-w-0",children:[m,h]}),e[8]=m,e[9]=h,e[10]=f):f=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]!==g||e[19]!==f?(C=s.jsxs("div",{className:g,children:[f,y]}),e[17]=y,e[18]=g,e[19]=f,e[20]=C):C=e[20],C};function _1(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 U1(t){return t.stopPropagation()}const um=()=>{const t=qp();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},$1=()=>{const t=Ze.c(2),[e,n]=l.useState(V1);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(um())};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 V1(){return um()}const H1=[{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"}],W1=[{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"}],G1=[{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"}],li="OpenChamber - AI Coding Assistant",wd=[{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"}],jd=[{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"}],q1=[{value:"default",labelKey:"settings.openchamber.visual.option.mobileLayout.default"},{value:"new",labelKey:"settings.openchamber.visual.option.mobileLayout.new"}],uo=t=>t==="portrait"||t==="landscape"?t:"system",J1=[{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"}],Y1=[{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"}],kd=[{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"}],Q1=[{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"}],Nd=[{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"}],Sd=[{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"}],X1=[{id:"steer",labelKey:"settings.openchamber.visual.option.followUpBehavior.steer.label"},{id:"queue",labelKey:"settings.openchamber.visual.option.followUpBehavior.queue.label"}],Z1=t=>t==="markdown"?"markdown":"plain",ej=[{id:"left",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsLeft"},{id:"right",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsRight"}],tj=[{id:"classic",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsClassic"},{id:"traffic-lights",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsTrafficLights"}],Ar=({visibleSettings:t})=>{const{locale:e,locales:n,setLocale:a,label:i,t:r}=ot(),o=l.useCallback(M=>r(M),[r]),{isMobile:d}=Hs(),{terminal:c}=Ha(),{browserTab:p}=$1(),u=Jg(),g=je(M=>M.showReasoningTraces),m=je(M=>M.sessionRecapEnabled),w=je(M=>M.sessionSuggestionEnabled),h=je(M=>M.setSessionRecapEnabled),f=je(M=>M.setSessionSuggestionEnabled),x=je(M=>M.sessionGoalEnabled),k=je(M=>M.setSessionGoalEnabled),y=je(M=>M.sessionGoalDefaultBudgetEnabled),C=je(M=>M.setSessionGoalDefaultBudgetEnabled),O=je(M=>M.sessionGoalDefaultBudget),j=je(M=>M.setSessionGoalDefaultBudget),N=je(M=>M.setShowReasoningTraces),b=je(M=>M.collapsibleThinkingBlocks),I=je(M=>M.setCollapsibleThinkingBlocks),B=je(M=>M.mermaidRenderingMode),T=je(M=>M.setMermaidRenderingMode),D=je(M=>M.userMessageRenderingMode),S=je(M=>M.setUserMessageRenderingMode),F=je(M=>M.collapsibleUserMessages),R=je(M=>M.setCollapsibleUserMessages),z=je(M=>M.stickyUserHeader),q=je(M=>M.promptNavigatorEnabled),H=je(M=>M.setStickyUserHeader),Z=je(M=>M.setPromptNavigatorEnabled),W=je(M=>M.expandedEditorToolbar),A=je(M=>M.setExpandedEditorToolbar),X=je(M=>M.autoSaveEnabled),te=je(M=>M.setAutoSaveEnabled),E=je(M=>M.wideChatLayoutEnabled),P=je(M=>M.setWideChatLayoutEnabled),_=je(M=>M.codeBlockLineWrap),L=je(M=>M.setCodeBlockLineWrap),V=je(M=>M.chatRenderMode),Y=je(M=>M.setChatRenderMode),G=je(M=>M.activityRenderMode),me=je(M=>M.setActivityRenderMode),ae=je(M=>M.fontSize),xe=je(M=>M.setFontSize),be=je(M=>M.terminalFontSize),ie=je(M=>M.setTerminalFontSize),pe=je(M=>M.terminalShell),Ie=je(M=>M.setTerminalShell),re=je(M=>M.terminalLoginShells),ce=je(M=>M.setTerminalLoginShells),ge=je(M=>M.editorFontSize),oe=je(M=>M.setEditorFontSize),de=je(M=>M.uiFont),le=je(M=>M.setUiFont),he=je(M=>M.monoFont),De=je(M=>M.setMonoFont),Le=je(M=>M.padding),Ke=je(M=>M.setPadding),Fe=je(M=>M.inputBarOffset),Me=je(M=>M.setInputBarOffset),Be=je(M=>M.mobileKeyboardMode),Ge=je(M=>M.setMobileKeyboardMode),Ve=je(M=>M.diffLayoutPreference),Ue=je(M=>M.setDiffLayoutPreference),He=je(M=>M.showTerminalQuickKeysOnDesktop),_e=je(M=>M.setShowTerminalQuickKeysOnDesktop),Oe=je(M=>M.fileEditorKeymap),se=je(M=>M.setFileEditorKeymap),ye=Wl(M=>M.followUpBehavior),ke=Wl(M=>M.setFollowUpBehavior),ze=je(M=>M.persistChatDraft),$=je(M=>M.setPersistChatDraft),Ee=je(M=>M.inputSpellcheckEnabled),J=je(M=>M.setInputSpellcheckEnabled),v=je(M=>M.showToolFileIcons),ue=je(M=>M.setShowToolFileIcons),Ne=je(M=>M.showTurnChangedFiles),we=je(M=>M.setShowTurnChangedFiles),qe=je(M=>M.showExpandedBashTools),it=je(M=>M.setShowExpandedBashTools),st=je(M=>M.showExpandedEditTools),rt=je(M=>M.setShowExpandedEditTools),lt=je(M=>M.timeFormatPreference),xt=je(M=>M.setTimeFormatPreference),bt=je(M=>M.weekStartPreference),Nt=je(M=>M.setWeekStartPreference),Ce=je(M=>M.showSplitAssistantMessageActions),Qe=je(M=>M.setShowSplitAssistantMessageActions),tt=je(M=>M.allowPromptingSubagentSessions),at=je(M=>M.setAllowPromptingSubagentSessions),gt=je(M=>M.draftStartersVisible),wt=je(M=>M.setDraftStartersVisible),Te=pt(M=>M.settingsMessageStreamTransport),ne=pt(M=>M.setSettingsMessageStreamTransport),Pe=Te,Xe=pt(M=>M.settingsDefaultFileViewerPreview),Re=pt(M=>M.setSettingsDefaultFileViewerPreview),Ye=je(M=>M.isSettingsDialogOpen),{themeMode:We,setThemeMode:et,availableThemes:kt,customThemesLoading:Et,reloadCustomThemes:Ot,lightThemeId:Zt,darkThemeId:Qt,setLightThemePreference:St,setDarkThemePreference:Pt}=Wa(),[Se,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=je(M=>M.dockBadgeEnabled),En=je(M=>M.setDockBadgeEnabled),Ks=Yg(),ha=je(M=>M.desktopWindowControlsPosition),Qn=je(M=>M.setDesktopWindowControlsPosition),Er=je(M=>M.desktopWindowControlsStyle),ji=je(M=>M.setDesktopWindowControlsStyle),[Dr,Gs]=l.useState(0),Ya=je(M=>M.reportUsage),ki=je(M=>M.setReportUsage),Ni=l.useCallback(M=>{ki(M),It({reportUsage:M})},[ki]),Rr=l.useCallback(M=>{Qn(M),It({desktopWindowControlsPosition:M})},[Qn]),Mr=l.useCallback(M=>{ji(M),It({desktopWindowControlsStyle:M})},[ji]),Si=(Ye||d||ds())&&(t?t.includes("chatRenderMode"):!0);l.useEffect(()=>{if(!Si)return;let M=null,Tt=Date.now();const Ts=()=>{const yn=Date.now();yn-Tt>=420&&(Gs(sa=>(sa+1)%24),Tt=yn),M=requestAnimationFrame(Ts)};(typeof document>"u"||document.visibilityState==="visible")&&(M=requestAnimationFrame(Ts));const vs=()=>{document.visibilityState==="visible"&&M===null?M=requestAnimationFrame(Ts):document.visibilityState!=="visible"&&M!==null&&(cancelAnimationFrame(M),M=null)};return document.addEventListener("visibilitychange",vs),()=>{document.removeEventListener("visibilitychange",vs),M!==null&&cancelAnimationFrame(M)}},[Si]);const Lr=l.useCallback(M=>{S(M),It({userMessageRenderingMode:M})},[S]),Fr=l.useCallback(M=>{H(M),It({stickyUserHeader:M})},[H]),Bs=l.useCallback(M=>{Z(M),It({promptNavigatorEnabled:M})},[Z]),on=l.useCallback(M=>{wt(M),It({draftStartersVisible:M})},[wt]),xa=l.useCallback(M=>{A(M),It({expandedEditorToolbar:M})},[A]),xn=l.useCallback(M=>{R(M),It({collapsibleUserMessages:M})},[R]),Dn=l.useCallback(M=>{P(M),It({wideChatLayoutEnabled:M})},[P]),Nl=l.useCallback(M=>{Qe(M),It({showSplitAssistantMessageActions:M})},[Qe]),Rn=l.useCallback(M=>{J(M),It({inputSpellcheckEnabled:M})},[J]),Or=l.useCallback(M=>{Y(M),It({chatRenderMode:M})},[Y]),ba=l.useCallback(M=>{ne(M),It({messageStreamTransport:M})},[ne]),zr=l.useCallback(M=>{me(M),It({activityRenderMode:M})},[me]),ys=l.useCallback(M=>{T(M),It({mermaidRenderingMode:M})},[T]),Kr=l.useCallback(M=>{ue(M),It({showToolFileIcons:M})},[ue]),ya=l.useCallback(M=>{we(M),It({showTurnChangedFiles:M})},[we]),va=l.useCallback(M=>{Re(M),It({defaultFileViewerPreview:M}),window.dispatchEvent(new CustomEvent("openchamber:file-viewer-preview-mode-changed",{detail:{enabled:M}}))},[Re]),Br=l.useCallback(M=>{it(M),It({showExpandedBashTools:M})},[it]),Ci=l.useCallback(M=>{rt(M),It({showExpandedEditTools:M})},[rt]),wa=l.useCallback(M=>{xt(M),It({timeFormatPreference:M})},[xt]),ja=l.useCallback(M=>{Nt(M),It({weekStartPreference:M})},[Nt]),ka=l.useMemo(()=>kt.filter(M=>M.metadata.variant==="light").sort((M,Tt)=>M.metadata.name.localeCompare(Tt.metadata.name)),[kt]),bn=l.useMemo(()=>kt.filter(M=>M.metadata.variant==="dark").sort((M,Tt)=>M.metadata.name.localeCompare(Tt.metadata.name)),[kt]),Qa=l.useMemo(()=>ka.find(M=>M.metadata.id===Zt)??ka[0],[ka,Zt]),Xa=l.useMemo(()=>bn.find(M=>M.metadata.id===Qt)??bn[0],[bn,Qt]),Na=l.useCallback((M,Tt)=>{const Ts=Tt==="dark"?" Dark":" Light";return M.endsWith(Ts)?M.slice(0,-Ts.length):M},[]),Je=M=>t?t.includes(M):!0,ms=ds(),Ii=Je("theme")&&!ms,Pi=Je("windowControlsPosition")&&Ks,Ti=Je("theme")||Je("timeFormat")||Je("weekStart"),Za=d&&Pn()&&!ls()&&!ms,Ai=ms?Ti:Je("theme")||Pi||Za||Je("pwaInstallName")||Je("pwaOrientation")||Je("timeFormat")||Je("weekStart"),U=Je("fontSize")||Je("terminalFontSize")||Je("editorFontSize")||Je("spacing")||Je("inputBarOffset")&&d,Ae=Je("terminalQuickKeys")&&!d||(Je("terminalShell")||Je("terminalLoginShell"))&&!ms||Je("fileEditorKeymap")||Je("autoSaveEnabled")||Je("expandedEditorToolbar")&&!ms,ct=Je("mermaidRendering")||Je("sessionGoal")&&!ms||Je("userMessageRendering")||Je("chatRenderMode")||Je("messageTransport")||Je("activityRenderMode")&&V==="sorted"||Je("collapsibleUserMessages")||Je("stickyUserHeader")||Je("promptNavigatorEnabled")&&!ms||Je("wideChatLayout")||Je("codeBlockLineWrap")||Je("splitAssistantMessageActions")||Je("subagentReadOnlyBanner")||Je("diffLayout")||Je("dotfiles")||Je("fileViewerPreview")||Je("reasoning")||Je("followUpBehavior")||Je("persistDraft")||Je("showToolFileIcons")||Je("expandedTools")||!d&&Je("inputSpellcheck"),yt=Je("chatRenderMode")||Je("activityRenderMode")&&V==="sorted",qt=Je("messageTransport"),_s=Je("userMessageRendering")||Je("mermaidRendering")||Je("diffLayout")&&!ms||Je("followUpBehavior"),us=Je("sessionAssist")||Je("sessionGoal")&&!ms||Je("subagentReadOnlyBanner")||Je("collapsibleUserMessages")||Je("stickyUserHeader")||Je("promptNavigatorEnabled")&&!ms||Je("wideChatLayout")||Je("codeBlockLineWrap")||Je("splitAssistantMessageActions")||Je("dotfiles")||Je("fileViewerPreview")||Je("persistDraft")||Je("showToolFileIcons")||Je("showTurnChangedFiles")||!d&&Je("inputSpellcheck")||Je("reasoning")||Je("expandedTools"),qs=Ai||U||Ae,Us=Je("pwaInstallName")&&Pn()&&p&&!ls()&&!ms,Ls=Je("pwaOrientation")&&Pn()&&!ls()&&!ms,ln=Je("mobileKeyboardMode")&&Pn()&&!ls()&&!ms&&Qg(),cn=(Je("terminalShell")||Je("terminalLoginShell"))&&!ms,[Xn,Rt]=l.useState([]),[cs,Zn]=l.useState(0);l.useEffect(()=>ul(()=>{Rt([]),Zn(M=>M+1)}),[]),l.useEffect(()=>{let M=!1;if(!(!cn||!c.listShells))return c.listShells().then(Tt=>{M||Rt(Tt)}).catch(()=>{M||Rt([])}),()=>{M=!0}},[cn,c,cs]);const Ht=l.useMemo(()=>{const M=Xn.filter(Tt=>Tt.id!=="auto");return pe==="auto"||M.some(Tt=>Tt.id===pe)?M:[{id:pe,name:pe,supportsLogin:!1},...M]},[Xn,pe]),Fs=Xn.find(M=>M.id===pe)?.supportsLogin===!0,ea=re.includes(pe),Sa=M=>{ce(M?[...re.filter(Tt=>Tt!==pe),pe]:re.filter(Tt=>Tt!==pe))},[Ca,Fm]=l.useState(()=>Of()),[_r,ta]=l.useState(""),[Ei,Ia]=l.useState("system"),Om=l.useMemo(()=>{const M=Nd.find(Tt=>Tt.id===lt);return o(M?.labelKey??"settings.openchamber.visual.option.timeFormat.auto.label")},[lt,o]),zm=l.useMemo(()=>{const M=Sd.find(Tt=>Tt.id===bt);return o(M?.labelKey??"settings.openchamber.visual.option.weekStart.auto.label")},[bt,o]),Km=l.useMemo(()=>{const M=wd.find(Tt=>Tt.id===Ei);return M?o(M.labelKey):void 0},[Ei,o]),Bm=l.useMemo(()=>{const M=jd.find(Tt=>Tt.id===Be);return M?o(M.labelKey):void 0},[Be,o]),_m=l.useCallback(M=>{M!==Ca&&(Fm(M),zf(M),window.location.reload())},[Ca]),Ur=l.useCallback(async M=>{if(typeof window>"u")return;const Tt=window,vs=M.trim().replace(/\s+/g," ").slice(0,64);if(await It({pwaAppName:vs}),typeof Tt.__OPENCHAMBER_SET_PWA_INSTALL_NAME__=="function"){const yn=Tt.__OPENCHAMBER_SET_PWA_INSTALL_NAME__(vs);ta(yn);return}ta(vs||li),Tt.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),Sl=l.useCallback(async M=>{if(typeof window>"u")return;const Tt=window,Ts=uo(M);if(await It({pwaOrientation:Ts}),typeof Tt.__OPENCHAMBER_SET_PWA_ORIENTATION__=="function"){const vs=Tt.__OPENCHAMBER_SET_PWA_ORIENTATION__(Ts);Ia(vs);return}Ia(Ts),Tt.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return l.useEffect(()=>{if(typeof window>"u"||!Us&&!Ls&&!ln)return;let M=!1;return(async()=>{try{const Ts=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!Ts.ok){M||ta(li);return}const vs=await Ts.json().catch(()=>({})),sa=(typeof vs?.pwaAppName=="string"?vs.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),Di=uo(vs?.pwaOrientation),$r=Yl(vs?.mobileKeyboardMode);M||(Us&&ta(sa||li),Ls&&Ia(Di),ln&&Ge($r))}catch{M||(Us&&ta(li),Ls&&Ia("system"),ln&&Ge("native"))}})(),()=>{M=!0}},[Ge,ln,Us,Ls]),s.jsxs("div",{className:"space-y-0",children:[Ai&&s.jsxs("div",{className:"space-y-0",children:[Ii&&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:H1.map(M=>s.jsx(zn,{selected:We===M.value,onSelect:()=>et(M.value),label:o(M.labelKey),ariaLabel:o(M.labelKey)},M.value))}),Za&&s.jsx(ca,{children:s.jsx(ns,{label:r("settings.openchamber.visual.section.mobileLayout"),children:s.jsx(Qs,{value:Ca,options:q1.map(M=>({value:M.value,label:o(M.labelKey)})),onChange:_m,"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(Mt,{value:Qa?.metadata.id??"",onValueChange:St,children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.selectLightThemeAria"),size:Gt,className:jn,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectThemePlaceholder"),children:Qa?Na(Qa.metadata.name,"light"):void 0})}),s.jsx(Ft,{children:ka.map(M=>s.jsx(jt,{value:M.metadata.id,children:Na(M.metadata.name,"light")},M.metadata.id))})]})}),s.jsx(ns,{label:r("settings.openchamber.visual.field.darkTheme"),settingsItem:"appearance.dark-theme",children:s.jsxs(Mt,{value:Xa?.metadata.id??"",onValueChange:Pt,children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.selectDarkThemeAria"),size:Gt,className:jn,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectThemePlaceholder"),children:Xa?Na(Xa.metadata.name,"dark"):void 0})}),s.jsx(Ft,{children:bn.map(M=>s.jsx(jt,{value:M.metadata.id,children:Na(M.metadata.name,"dark")},M.metadata.id))})]})}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsxs("button",{type:"button",disabled:Et||Se,onClick:()=>{const M=Date.now();ut(!0),Ot().finally(()=>{const Tt=Date.now()-M;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",Se&&"animate-spin")}),r(Se?"settings.openchamber.visual.actions.reloadingThemes":"settings.openchamber.visual.actions.reloadThemes")]}),s.jsx($t,{children:r("settings.openchamber.visual.field.themeImportInfoTooltip")})]})]})]}),mt&&s.jsxs(ca,{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),Xg("desktop_set_vibrancy",{enabled:ft})},children:r(Dt?"settings.openchamber.visual.actions.restarting":"settings.openchamber.visual.actions.saveAndRestart")})})]}),ts&&s.jsx(ca,{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")})})]}),Pi&&s.jsx(dt,{title:r("settings.openchamber.desktopNetwork.field.windowControls"),info:r("settings.openchamber.desktopNetwork.field.windowControlsPositionDescription"),divider:Ii,children:s.jsxs(On,{children:[s.jsx(ns,{label:r("settings.openchamber.desktopNetwork.field.windowControlsPosition"),settingsItem:"sessions.desktop-window-controls-position",children:s.jsx(Qs,{value:ha,options:ej.map(M=>({value:M.id,label:o(M.labelKey)})),onChange:Rr,"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(Qs,{value:Er,options:tj.map(M=>({value:M.id,label:o(M.labelKey)})),onChange:Mr,"aria-label":r("settings.openchamber.desktopNetwork.field.windowControlsStyleAria")})})]})}),Ti&&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(Mt,{value:e,onValueChange:M=>a(M),children:[s.jsx(Lt,{"aria-label":r("settings.appearance.language.select"),size:Gt,className:jn,children:s.jsx(Wt,{children:i(e)})}),s.jsx(Ft,{children:n.map(M=>s.jsx(jt,{value:M,children:i(M)},M))})]})}),(Je("timeFormat")||Je("weekStart"))&&s.jsxs("div",{className:Bn,children:[Je("timeFormat")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.timeFormat"),settingsItem:"appearance.time-format",children:s.jsxs(Mt,{value:lt,onValueChange:M=>wa(M),children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.selectTimeFormatAria"),size:Gt,className:jn,children:s.jsx(Wt,{children:Om})}),s.jsx(Ft,{children:Nd.map(M=>s.jsx(jt,{value:M.id,children:o(M.labelKey)},M.id))})]})}),Je("weekStart")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.weekStartsOn"),settingsItem:"appearance.week-start",children:s.jsxs(Mt,{value:bt,onValueChange:M=>ja(M),children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.selectWeekStartAria"),size:Gt,className:jn,children:s.jsx(Wt,{children:zm})}),s.jsx(Ft,{children:Sd.map(M=>s.jsx(jt,{value:M.id,children:o(M.labelKey)},M.id))})]})})]})]})}),(Us||Ls||ln)&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.appInstall"),contentClassName:Bn,children:[Us&&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:$s,children:[s.jsx(nt,{value:_r,onChange:M=>{ta(M.target.value)},onBlur:()=>{Ur(_r)},onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),Ur(_r))},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:()=>{ta(li),Ur("")},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"})})]}),Ls&&s.jsxs(Xt,{label:r("settings.openchamber.visual.field.installOrientation"),description:r("settings.openchamber.visual.field.installOrientationHint"),settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:$s,children:[s.jsxs(Mt,{value:Ei,onValueChange:M=>{const Tt=uo(M);Ia(Tt),Sl(Tt)},children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.pwaInstallOrientationAria"),size:Gt,className:pc,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectOrientationPlaceholder"),children:Km})}),s.jsx(Ft,{children:wd.map(M=>s.jsx(jt,{value:M.id,children:o(M.labelKey)},M.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Ia("system"),Sl("system")},disabled:Ei==="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"})})]}),ln&&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:$s,children:[s.jsxs(Mt,{value:Be,onValueChange:M=>{const Tt=Yl(M);Ge(Tt),It({mobileKeyboardMode:Tt})},children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.mobileKeyboardModeAria"),size:Gt,className:pc,children:s.jsx(Wt,{placeholder:r("settings.openchamber.visual.field.selectMobileKeyboardModePlaceholder"),children:Bm})}),s.jsx(Ft,{children:jd.map(M=>s.jsx(jt,{value:M.id,children:o(M.labelKey)},M.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Ge("native"),It({mobileKeyboardMode:"native"})},disabled:Be==="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"})})]})]})]}),U&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.densityAndType"),contentClassName:Bn,children:[Je("fontSize")&&!d||Je("terminalFontSize")?s.jsxs(On,{children:[Je("fontSize")&&!d&&s.jsxs(ns,{label:r("settings.openchamber.visual.field.interfaceFont"),settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[s.jsxs(Mt,{value:de,onValueChange:M=>le(M),children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.selectInterfaceFontAria"),size:Gt,className:jn,children:s.jsx(Wt,{children:Gl.find(M=>M.id===de)?.label})}),s.jsx(Ft,{children:Gl.map(M=>s.jsx(jt,{value:M.id,children:s.jsx("span",{style:{fontFamily:M.stack},children:M.label})},M.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>le(ql),disabled:de===ql,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"})})]}),Je("terminalFontSize")&&s.jsxs(ns,{label:r("settings.openchamber.visual.field.codeFont"),controlClassName:"w-full",children:[s.jsxs(Mt,{value:he,onValueChange:M=>De(M),children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.selectCodeFontAria"),size:Gt,className:jn,children:s.jsx(Wt,{children:Jl.find(M=>M.id===he)?.label})}),s.jsx(Ft,{children:Jl.map(M=>s.jsx(jt,{value:M.id,children:s.jsx("span",{style:{fontFamily:M.stack},children:M.label})},M.id))})]}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>De(fi),disabled:he===fi,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,Je("fontSize")&&!d||Je("terminalFontSize")||Je("editorFontSize")?s.jsxs(On,{children:[Je("fontSize")&&!d&&s.jsx(ns,{label:r("settings.openchamber.visual.field.interfaceFontSize"),controlClassName:"w-full",children:s.jsxs("div",{className:si,children:[s.jsx(Ms,{value:ae,onValueChange:xe,min:50,max:200,step:5,"aria-label":r("settings.openchamber.visual.field.fontSizePercentageAria")}),s.jsx("span",{className:ni,children:"%"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>xe(100),disabled:ae===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"})})]})}),Je("terminalFontSize")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.terminalFontSize"),settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:s.jsxs("div",{className:si,children:[s.jsx(Ms,{value:be,onValueChange:ie,min:9,max:52,step:1}),s.jsx("span",{className:ni,children:"px"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>ie(13),disabled:be===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"})})]})}),Je("editorFontSize")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.editorFontSize"),settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:s.jsxs("div",{className:si,children:[s.jsx(Ms,{value:ge,onValueChange:oe,min:9,max:32,step:1}),s.jsx("span",{className:ni,children:"px"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>oe(13),disabled:ge===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,Je("spacing")||Je("inputBarOffset")&&d?s.jsxs(On,{children:[Je("spacing")&&s.jsx(ns,{label:r("settings.openchamber.visual.field.spacingDensity"),settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:s.jsxs("div",{className:si,children:[s.jsx(Ms,{value:Le,onValueChange:Ke,min:50,max:200,step:5}),s.jsx("span",{className:ni,children:"%"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>Ke(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"})})]})}),Je("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:si,children:[s.jsx(Ms,{value:Fe,onValueChange:Me,min:0,max:100,step:5}),s.jsx("span",{className:ni,children:"px"}),s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:()=>Me(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:[Je("fileEditorKeymap")&&s.jsx(en,{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(M=>s.jsx(zn,{selected:Oe===M,onSelect:()=>se(M),label:r(`settings.openchamber.visual.option.fileEditorKeymap.${M}`),ariaLabel:r(`settings.openchamber.visual.option.fileEditorKeymap.${M}`)},M))})}),s.jsxs("div",{className:Ds,children:[Je("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"}),Je("expandedEditorToolbar")&&!ms&&s.jsx(Ct,{checked:W,onChange:xa,label:r("settings.openchamber.visual.field.expandedEditorToolbar"),ariaLabel:r("settings.openchamber.visual.field.expandedEditorToolbarAria"),settingsItem:"appearance.expanded-editor-toolbar"}),Je("terminalQuickKeys")&&!d&&s.jsx(Ct,{checked:He,onChange:_e,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")}),cn&&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(Mt,{value:pe,onValueChange:M=>{Zg(M)&&Ie(M)},children:[s.jsx(Lt,{"aria-label":r("settings.openchamber.visual.field.terminalShellAria"),size:Gt,className:jn,children:s.jsx(Wt,{})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"auto",children:r("settings.openchamber.visual.option.terminalShell.auto")}),Ht.map(M=>s.jsx(jt,{value:M.id,children:M.name},M.id))]})]})}),cn&&Fs&&s.jsx(Ct,{checked:ea,onChange:Sa,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:qs,contentClassName:"space-y-6",children:[Je("chatRenderMode")&&s.jsx(en,{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:Y1.map(M=>{const Tt=V===M.id,Ts=Dr%12;return s.jsxs("button",{type:"button",onClick:()=>Or(M.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(M.labelKey)}),s.jsx("div",{className:"mt-2 w-full rounded-md border border-border/60 bg-muted/30 p-2",children:M.id==="live"?s.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(vs=>{const yn=vs*3+1,sa=Ts-yn+1,Di=sa<=0?0:sa===1?42:sa===2?68:92,$r=Di>0;return s.jsxs("div",{className:fe("flex items-center gap-1.5 transition-all duration-300 motion-reduce:transition-none",$r?"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:`${Di}%`}})]},vs)})}):s.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(vs=>{const yn=Ts>=(vs+1)*3;return s.jsxs("div",{className:fe("flex items-center gap-1.5 transition-all duration-300 motion-reduce:transition-none",yn?"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)})})})]},M.id)})})}),Je("activityRenderMode")&&V==="sorted"&&s.jsx(en,{title:r("settings.openchamber.visual.section.activityDefault"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.activityDefaultAria"),children:Q1.map(M=>s.jsx(zn,{selected:G===M.id,onSelect:()=>zr(M.id),label:o(M.labelKey),ariaLabel:r("settings.openchamber.visual.field.activityDefaultModeAria",{option:o(M.labelKey)})},M.id))})})]}),qt&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.messageStreamTransport"),divider:yt||qs,settingsItem:"chat.message-transport",contentClassName:"space-y-2",children:[s.jsx(Qs,{value:Pe,options:kd.map(M=>({value:M.id,label:o(M.labelKey)})),onChange:ba,"aria-label":r("settings.openchamber.visual.section.messageStreamTransport")}),(()=>{const M=kd.find(Tt=>Tt.id===Pe);return M?.descriptionKey?s.jsx("span",{className:"typography-meta text-muted-foreground",children:o(M.descriptionKey)}):null})()]}),_s&&s.jsx(dt,{title:r("settings.openchamber.visual.section.chatMessageOptions"),divider:yt||qt||qs,children:s.jsxs(On,{className:"lg:gap-y-6",children:[Je("userMessageRendering")&&s.jsx(en,{title:r("settings.openchamber.visual.section.userMessageRendering"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.userMessageRenderingAria"),children:J1.map(M=>s.jsx(zn,{selected:Z1(D)===M.id,onSelect:()=>Lr(M.id),label:o(M.labelKey),ariaLabel:r("settings.openchamber.visual.field.userMessageRenderingAria",{option:o(M.labelKey)})},M.id))})}),Je("mermaidRendering")&&s.jsx(en,{title:r("settings.openchamber.visual.section.mermaidRendering"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.mermaidRenderingAria"),children:G1.map(M=>s.jsx(zn,{selected:B===M.id,onSelect:()=>ys(M.id),label:o(M.labelKey),ariaLabel:r("settings.openchamber.visual.field.mermaidRenderingAria",{option:o(M.labelKey)})},M.id))})}),Je("diffLayout")&&!ms&&s.jsx(en,{title:r("settings.openchamber.visual.section.diffLayout"),children:s.jsx(Kn,{"aria-label":r("settings.openchamber.visual.section.diffLayoutAria"),children:W1.map(M=>s.jsx(zn,{selected:Ve===M.id,onSelect:()=>Ue(M.id),label:o(M.labelKey),ariaLabel:r("settings.openchamber.visual.field.diffLayoutAria",{option:o(M.labelKey)})},M.id))})}),Je("followUpBehavior")&&s.jsx(en,{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:X1.map(M=>s.jsx(zn,{selected:ye===M.id,onSelect:()=>ke(M.id),label:o(M.labelKey),ariaLabel:r("settings.openchamber.visual.field.followUpBehaviorAria",{option:o(M.labelKey)})},M.id))})})]})}),us&&s.jsxs(s.Fragment,{children:[Je("expandedTools")&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.showToolsOpenedByDefault"),divider:yt||qt||_s||qs,contentClassName:Ds,children:[s.jsx(Ct,{checked:qe,onChange:Br,label:r("settings.openchamber.visual.field.bash"),ariaLabel:r("settings.openchamber.visual.field.showExpandedBashToolsAria")}),s.jsx(Ct,{checked:st,onChange:Ci,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:on,label:r("settings.openchamber.visual.field.draftStartersVisible"),ariaLabel:r("settings.openchamber.visual.field.draftStartersVisibleAria"),settingsItem:"chat.draft-starters-visible"}),Je("sessionAssist")&&s.jsxs(s.Fragment,{children:[s.jsx(Ct,{checked:m,onChange:h,label:r("settings.openchamber.visual.field.sessionRecap"),ariaLabel:r("settings.openchamber.visual.field.sessionRecapAria"),settingsItem:"chat.session-recap"}),s.jsx(Ct,{checked:w,onChange:f,label:r("settings.openchamber.visual.field.sessionSuggestion"),ariaLabel:r("settings.openchamber.visual.field.sessionSuggestionAria"),settingsItem:"chat.session-suggestion"})]}),Je("subagentReadOnlyBanner")&&s.jsx(Ct,{checked:tt,onChange:at,label:r("settings.openchamber.visual.field.allowPromptingSubagentSessions"),ariaLabel:r("settings.openchamber.visual.field.allowPromptingSubagentSessionsAria"),settingsItem:"chat.subagent-read-only-banner"})]}),Je("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(Ms,{value:O,onValueChange:M=>{typeof M=="number"&&Number.isFinite(M)&&M>0&&j(Math.floor(M))},min:1e3,max:1e8,step:5e4}):null]})]}),Je("reasoning")&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.reasoning"),settingsItem:"chat.reasoning",contentClassName:Ds,children:[s.jsx(Ct,{checked:g,onChange:N,label:r("settings.openchamber.visual.field.showReasoningTraces"),ariaLabel:r("settings.openchamber.visual.field.showReasoningTracesAria"),settingsItem:"chat.reasoning-traces"}),g&&s.jsx(Ct,{checked:b,onChange:I,label:r("settings.openchamber.visual.field.collapsibleThinkingBlocks"),ariaLabel:r("settings.openchamber.visual.field.collapsibleThinkingBlocksAria")})]}),(Je("collapsibleUserMessages")||Je("stickyUserHeader")||Je("promptNavigatorEnabled")&&!ms||Je("wideChatLayout")||Je("splitAssistantMessageActions")||Je("codeBlockLineWrap"))&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.messageAppearance"),settingsItem:"chat.message-appearance",contentClassName:Ds,children:[Je("collapsibleUserMessages")&&s.jsx(Ct,{checked:F,onChange:xn,label:r("settings.openchamber.visual.field.collapsibleUserMessages"),ariaLabel:r("settings.openchamber.visual.field.collapsibleUserMessagesAria"),settingsItem:"chat.collapsible-user-messages"}),Je("stickyUserHeader")&&s.jsx(Ct,{checked:z,onChange:Fr,label:r("settings.openchamber.visual.field.stickyUserHeader"),ariaLabel:r("settings.openchamber.visual.field.stickyUserHeaderAria"),settingsItem:"chat.sticky-user-header"}),Je("promptNavigatorEnabled")&&!ms&&s.jsx(Ct,{checked:q,onChange:Bs,label:r("settings.openchamber.visual.field.promptNavigatorEnabled"),ariaLabel:r("settings.openchamber.visual.field.promptNavigatorEnabledAria"),settingsItem:"chat.prompt-navigator"}),Je("wideChatLayout")&&s.jsx(Ct,{checked:E,onChange:Dn,label:r("settings.openchamber.visual.field.wideChatLayout"),ariaLabel:r("settings.openchamber.visual.field.wideChatLayoutAria"),settingsItem:"chat.wide-layout"}),Je("splitAssistantMessageActions")&&s.jsx(Ct,{checked:Ce,onChange:Nl,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")}),Je("codeBlockLineWrap")&&s.jsx(Ct,{checked:_,onChange:L,label:r("settings.openchamber.visual.field.codeBlockLineWrap"),ariaLabel:r("settings.openchamber.visual.field.codeBlockLineWrapAria"),settingsItem:"chat.code-block-line-wrap"})]}),(Je("showToolFileIcons")||Je("showTurnChangedFiles")||Je("dotfiles")&&!ds()||Je("fileViewerPreview"))&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.toolsAndFiles"),settingsItem:"chat.tools-and-files",contentClassName:Ds,children:[Je("showToolFileIcons")&&s.jsx(Ct,{checked:v,onChange:Kr,label:r("settings.openchamber.visual.field.showToolFileIcons"),ariaLabel:r("settings.openchamber.visual.field.showToolFileIconsAria"),settingsItem:"chat.tool-file-icons"}),Je("showTurnChangedFiles")&&s.jsx(Ct,{checked:Ne,onChange:ya,label:r("settings.openchamber.visual.field.showTurnChangedFiles"),ariaLabel:r("settings.openchamber.visual.field.showTurnChangedFilesAria"),settingsItem:"chat.changed-files"}),Je("dotfiles")&&!ds()&&s.jsx(Ct,{checked:u,onChange:ef,label:r("settings.openchamber.visual.field.showDotfiles"),ariaLabel:r("settings.openchamber.visual.field.showDotfilesAria"),settingsItem:"chat.dotfiles"}),Je("fileViewerPreview")&&s.jsx(Ct,{checked:Xe,onChange:va,label:r("settings.openchamber.defaults.field.openFilesPreview"),ariaLabel:r("settings.openchamber.defaults.field.openFilesPreviewAria")})]}),(Je("persistDraft")||!d&&Je("inputSpellcheck"))&&s.jsxs(dt,{title:r("settings.openchamber.visual.section.composer"),settingsItem:"chat.composer",contentClassName:Ds,children:[Je("persistDraft")&&s.jsx(Ct,{checked:ze,onChange:$,label:r("settings.openchamber.visual.field.persistDraftMessages"),ariaLabel:r("settings.openchamber.visual.field.persistDraftMessagesAria"),settingsItem:"chat.persist-drafts"}),!d&&Je("inputSpellcheck")&&s.jsx(Ct,{checked:Ee,onChange:Rn,label:r("settings.openchamber.visual.field.enableSpellcheckInTextInputs"),ariaLabel:r("settings.openchamber.visual.field.enableSpellcheckInTextInputsAria"),settingsItem:"chat.spellcheck"})]})]})]}),Je("reportUsage")&&s.jsx(dt,{title:r("settings.openchamber.visual.section.privacy"),children:s.jsx(Ct,{checked:Ya,onChange:Ni,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"})})]})},sj=1,nj=365,Cd=30,aj=[{value:"archive",labelKey:"settings.openchamber.sessionRetention.action.archive"},{value:"delete",labelKey:"settings.openchamber.sessionRetention.action.delete"}],mm=()=>{const t=Ze.c(87),{t:e}=ot(),n=je(ij),a=je(rj),i=je(oj),r=je(lj),o=je(cj),d=je(dj);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:g,action:m}=Jp(c),w=p.length;let h;t[1]!==g||t[2]!==e?(h=async()=>{const me=await g({force:!0});if(me.completedIds.length===0&&me.failedIds.length===0){Q.message(me.action==="archive"?e("settings.openchamber.sessionRetention.toast.noneEligibleArchive"):e("settings.openchamber.sessionRetention.toast.noneEligibleDelete"));return}me.completedIds.length>0&&Q.success(me.action==="archive"?e("settings.openchamber.sessionRetention.toast.archivedCount",{count:me.completedIds.length}):e("settings.openchamber.sessionRetention.toast.deletedCount",{count:me.completedIds.length})),me.failedIds.length>0&&Q.error(me.action==="archive"?e("settings.openchamber.sessionRetention.toast.failedArchiveCount",{count:me.failedIds.length}):e("settings.openchamber.sessionRetention.toast.failedDeleteCount",{count:me.failedIds.length}))},t[1]=g,t[2]=e,t[3]=h):h=t[3];const f=h;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 O;t[12]!==n||t[13]!==r||t[14]!==y||t[15]!==C?(O=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]=O):O=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 b;t[21]!==a||t[22]!==o||t[23]!==N?(b=s.jsx(Ms,{value:a,onValueChange:o,min:sj,max:nj,step:1,"aria-label":N,className:"w-20 tabular-nums"}),t[21]=a,t[22]=o,t[23]=N,t[24]=b):b=t[24];let I;t[25]!==e?(I=e("settings.openchamber.sessionRetention.field.days"),t[25]=e,t[26]=I):I=t[26];let B;t[27]!==I?(B=s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:I}),t[27]=I,t[28]=B):B=t[28];let T;t[29]!==o?(T=()=>o(Cd),t[29]=o,t[30]=T):T=t[30];const D=a===Cd;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 R;t[35]===Symbol.for("react.memo_cache_sentinel")?(R=s.jsx(K,{name:"restart",className:"h-3.5 w-3.5"}),t[35]=R):R=t[35];let z;t[36]!==T||t[37]!==D||t[38]!==S||t[39]!==F?(z=s.jsx(ee,{size:"sm",type:"button",variant:"ghost",onClick:T,disabled:D,className:Is,"aria-label":S,title:F,children:R}),t[36]=T,t[37]=D,t[38]=S,t[39]=F,t[40]=z):z=t[40];let q;t[41]!==B||t[42]!==z||t[43]!==j||t[44]!==b?(q=s.jsxs(Xt,{settingsItem:"sessions.retention-period",label:j,children:[b,B,z]}),t[41]=B,t[42]=z,t[43]=j,t[44]=b,t[45]=q):q=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=aj.map(me=>({value:me.value,label:e(me.labelKey)})),t[48]=e,t[49]=Z):Z=t[49];let W;t[50]!==i||t[51]!==d||t[52]!==Z?(W=s.jsx(Qs,{value:i,onChange:d,options:Z}),t[50]=i,t[51]=d,t[52]=Z,t[53]=W):W=t[53];let A;t[54]!==H||t[55]!==W?(A=s.jsx(Xt,{settingsItem:"sessions.retention-action",label:H,children:W}),t[54]=H,t[55]=W,t[56]=A):A=t[56];let X;t[57]!==q||t[58]!==A?(X=s.jsxs(ca,{className:"space-y-0",children:[q,A]}),t[57]=q,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 E;t[62]!==u||t[63]!==e?(E=e(u?"settings.openchamber.sessionRetention.actions.cleaningUp":"settings.openchamber.sessionRetention.actions.runCleanupNow"),t[62]=u,t[63]=e,t[64]=E):E=t[64];let P;t[65]!==f||t[66]!==u||t[67]!==E?(P=s.jsx(ee,{type:"button",variant:"outline",size:"xs",onClick:f,disabled:u,className:"!font-normal",children:E}),t[65]=f,t[66]=u,t[67]=E,t[68]=P):P=t[68];let _;t[69]!==te||t[70]!==P?(_=s.jsx(Xt,{label:te,children:P}),t[69]=te,t[70]=P,t[71]=_):_=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 Y;t[78]!==_||t[79]!==V?(Y=s.jsxs("div",{className:"mt-1 py-1.5 space-y-1",children:[_,V]}),t[78]=_,t[79]=V,t[80]=Y):Y=t[80];let G;return t[81]!==x||t[82]!==X||t[83]!==k||t[84]!==Y||t[85]!==O?(G=s.jsxs(dt,{title:x,info:k,children:[O,X,Y]}),t[81]=x,t[82]=X,t[83]=k,t[84]=Y,t[85]=O,t[86]=G):G=t[86],G};function ij(t){return t.autoDeleteEnabled}function rj(t){return t.autoDeleteAfterDays}function oj(t){return t.sessionRetentionAction}function lj(t){return t.setAutoDeleteEnabled}function cj(t){return t.setAutoDeleteAfterDays}function dj(t){return t.setSessionRetentionAction}const Id=(t,e,n)=>!t||!Number.isFinite(t)?e:new Intl.DateTimeFormat(kr(),{dateStyle:"medium",timeStyle:"short",hour12:n==="auto"?void 0:n==="12h"}).format(t),pm=()=>{const{t}=ot(),e=je(b=>b.timeFormatPreference),[n,a]=l.useState(!1),[i,r]=l.useState(!0),[o,d]=l.useState(!1),[c,p]=l.useState(null),[u,g]=l.useState(!1),[m,w]=l.useState([]),[h,f]=l.useState(Yp),[x,k]=l.useState(""),y=l.useMemo(()=>Qp(),[]),C=l.useCallback(async()=>{r(!0),k("");try{const b=await Xp();w(b)}catch(b){const I=b instanceof Error?b.message:t("settings.openchamber.passkeys.toast.loadFailed");k(I)}finally{r(!1)}},[t]);l.useEffect(()=>{let b=!1;return(async()=>{try{if(!y.supported){b||(a(!1),r(!1));return}b||a(!0)}catch{b||a(!1)}if(!b){const I=await Hr();if(f(I),!I.enabled){w([]),r(!1);return}await C()}})(),()=>{b=!0,Rl()}},[C,y.supported]);const O=l.useCallback(async()=>{if(!h.enabled){const b=t("settings.openchamber.passkeys.toast.enableUiPasswordFirst");k(b),Q.message(b);return}if(!n){k(y.reason),Q.message(y.reason);return}if(o){Rl(),d(!1);return}k(""),d(!0);try{await Zp(),f(await Hr()),await C(),Q.success(t("settings.openchamber.passkeys.toast.added"))}catch(b){if(eg(b)){Q.message(t("settings.openchamber.passkeys.toast.setupCanceled"));return}const I=b instanceof Error?b.message:t("settings.openchamber.passkeys.toast.addFailed");k(I),Q.error(I)}finally{d(!1)}},[o,C,h.enabled,y.reason,n,t]),j=l.useCallback(async b=>{p(b),k("");try{await tg(b),f(await Hr()),await C(),Q.success(t("settings.openchamber.passkeys.toast.removed"))}catch(I){const B=I instanceof Error?I.message:t("settings.openchamber.passkeys.toast.removeFailed");k(B),Q.error(B)}finally{p(null)}},[C,t]),N=l.useCallback(async()=>{g(!0),k("");try{await sg(),window.location.reload()}catch(b){const I=b instanceof Error?b.message:t("settings.openchamber.passkeys.toast.clearAuthFailed");k(I),Q.error(I),g(!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:()=>{O()},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")})]}),!h.enabled&&s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.openchamber.passkeys.state.uiPasswordRequired")}),h.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(b=>s.jsxs(Xt,{label:s.jsx("span",{className:"truncate",children:b.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:b.lastUsedAt?t("settings.openchamber.passkeys.item.lastUsed",{time:Id(b.lastUsedAt,t("settings.openchamber.passkeys.time.neverUsed"),e)}):t("settings.openchamber.passkeys.item.added",{time:Id(b.createdAt,t("settings.openchamber.passkeys.time.neverUsed"),e)})}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>{j(b.id)},disabled:c===b.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:c===b.id?t("settings.openchamber.passkeys.actions.removing"):t("settings.common.actions.delete")})]},b.id))})]}),x&&s.jsx("div",{className:"mt-1 py-1.5",children:s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:x})})]})},mo=t=>{const e=Wn(t);return e||{providerId:"",modelId:""}},gm=()=>{const{t}=ot(),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=je(L=>L.showDeletionDialog),p=je(L=>L.setShowDeletionDialog),u=pt(L=>L.providers),g=pt(L=>L.modelsMetadata),[m,w]=l.useState(),[h,f]=l.useState(),[x,k]=l.useState(),[y,C]=l.useState(!0),[O,j]=l.useState(),[N,b]=l.useState(),[I,B]=l.useState(),[T,D]=l.useState(!0),S=l.useMemo(()=>mo(m),[m]);l.useEffect(()=>{(async()=>{try{let V=null;if(!V){const Y=an()?.settings;if(Y)try{const me=(await Y.load())?.settings;if(me){const ae=me;V={defaultModel:typeof me.defaultModel=="string"?me.defaultModel:void 0,defaultVariant:typeof ae.defaultVariant=="string"?ae.defaultVariant:void 0,defaultAgent:typeof me.defaultAgent=="string"?me.defaultAgent:void 0,smallModelUseDefault:typeof ae.smallModelUseDefault=="boolean"?ae.smallModelUseDefault:void 0,smallModelOverride:typeof ae.smallModelOverride=="string"?ae.smallModelOverride:void 0,walkthroughModelOverride:typeof ae.walkthroughModelOverride=="string"?ae.walkthroughModelOverride:void 0}}}catch{}}if(!V){const Y=await ht("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});Y.ok&&(V=await Y.json())}if(V){const Y=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,me=typeof V.defaultAgent=="string"&&V.defaultAgent.trim().length>0?V.defaultAgent.trim():void 0;Y!==void 0&&w(Y),G!==void 0&&f(G),me!==void 0&&k(me),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()&&B(V.walkthroughModelOverride.trim())}}catch(V){console.warn("Failed to load defaults settings:",V)}finally{D(!1)}})()},[]);const F=l.useCallback(async(L,V)=>{const Y=L&&V?`${L}/${V}`:void 0;w(Y),f(void 0),o(void 0),i(void 0),r(Y),L&&V&&u.find(me=>me.id===L)&&(e(L),n(V));try{await It({defaultModel:Y??"",defaultVariant:""});const G=await ht("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:Y})});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]),R="__default__",z=l.useCallback(L=>L===R?t("settings.openchamber.defaults.option.default"):L.charAt(0).toUpperCase()+L.slice(1),[t]),q=l.useCallback(async L=>{const V=L===R?void 0:L||void 0;f(V),o(V),i(V);try{await It({defaultVariant:V??""})}catch(Y){console.warn("Failed to save default variant:",Y)}},[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(Y){console.warn("Failed to save default agent:",Y)}},[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)}},[]),W=l.useCallback(async(L,V)=>{const Y=L&&V?`${L}/${V}`:void 0;j(Y);try{await It({smallModelOverride:Y??""})}catch(G){console.warn("Failed to save small model override:",G)}},[]),A=l.useCallback(async(L,V)=>{const Y=L&&V?`${L}/${V}`:void 0;B(Y);try{await It({walkthroughModelOverride:Y??""})}catch(G){console.warn("Failed to save walkthrough model override:",G)}},[]),X=l.useCallback((L,V)=>g.get(`${L}/${V}`)?.structured_output!==!1,[g]),te=l.useMemo(()=>mo(O),[O]),E=l.useMemo(()=>mo(I),[I]);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 Y=await V.json().catch(()=>null);!L&&Array.isArray(Y?.authenticatedProviders)&&b(Y.authenticatedProviders.filter(G=>typeof G=="string"))}catch{}})(),()=>{L=!0}},[N]);const P=l.useMemo(()=>{if(!S.providerId||!S.modelId)return[];const Y=u.find(G=>G.id===S.providerId)?.models.find(G=>G.id===S.modelId)?.variants;return Y?Object.keys(Y):[]},[S.modelId,S.providerId,u]),_=P.length>0;return l.useEffect(()=>{!_&&h&&(f(void 0),o(void 0),i(void 0),It({defaultVariant:""}).catch(()=>{}))},[h,i,o,_]),T?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,_?` (${h??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(la,{providerId:S.providerId,modelId:S.modelId,onChange:F,className:Vn})}),s.jsx(Xt,{settingsItem:"sessions.default-thinking",label:t("settings.openchamber.defaults.field.defaultThinking"),children:s.jsxs(Mt,{value:h??R,onValueChange:q,disabled:!_,children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{placeholder:t("settings.openchamber.defaults.field.thinkingPlaceholder"),children:z(h??R)})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:R,children:t("settings.openchamber.defaults.option.default")}),P.map(L=>s.jsx(jt,{value:L,children:z(L)},L))]})]})}),s.jsx(Xt,{settingsItem:"sessions.default-agent",label:t("settings.openchamber.defaults.field.defaultAgent"),children:s.jsx(ll,{agentName:x||"",onChange:H,className:Vn})})]}),s.jsx(ca,{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(gn,{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(la,{providerId:te.providerId,modelId:te.modelId,onChange:W,allowedProviderIds:N,className:Vn})}),s.jsxs(ca,{className:Ds,children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(gn,{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(la,{providerId:E.providerId,modelId:E.modelId,onChange:A,allowedProviderIds:N,isModelAllowed:X,placeholder:t("settings.openchamber.defaults.walkthroughModel.usesSmallModel"),className:Vn})})]})]})]})})})},Pd={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"}},uj={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"},mj=()=>{const{t}=ot(),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=je(E=>E.nativeNotificationsEnabled),o=je(E=>E.setNativeNotificationsEnabled),d=je(E=>E.notificationMode),c=je(E=>E.setNotificationMode),p=je(E=>E.notifyOnSubtasks),u=je(E=>E.setNotifyOnSubtasks),g=je(E=>E.notifyOnCompletion),m=je(E=>E.setNotifyOnCompletion),w=je(E=>E.notifyOnError),h=je(E=>E.setNotifyOnError),f=je(E=>E.notifyOnQuestion),x=je(E=>E.setNotifyOnQuestion),k=je(E=>E.notificationTemplates),y=je(E=>E.setNotificationTemplates),[C,O]=l.useState("default"),[j,N]=l.useState(!1),[b,I]=l.useState(!1),[B,T]=l.useState(!1);l.useEffect(()=>{if(!i){N(!1),I(!1);return}typeof Notification<"u"&&O(Notification.permission);const E=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;N(E),(async()=>{if(!E){I(!1);return}try{const _=await navigator.serviceWorker.getRegistration();if(!_){I(!1);return}const L=await _.pushManager.getSubscription();I(!!L)}catch{I(!1)}})()},[i]);const D=async E=>{if(e){o(E);return}if(!i){o(E);return}if(E&&typeof Notification<"u"&&Notification.permission==="default")try{const P=await Notification.requestPermission();O(P),P==="granted"?o(!0):Q.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.description")})}catch(P){console.error("Failed to request notification permission:",P),Q.error(t("settings.notifications.page.toast.requestPermissionFailed"))}else o(!!(E&&C==="granted"))},S=e||n||a||i&&typeof Notification<"u"&&Notification.permission==="granted",F=(E,P,_)=>{y({...k,[E]:{...k[E],[P]:_}})},R=E=>{const P="=".repeat((4-E.length%4)%4),_=(E+P).replace(/-/g,"+").replace(/_/g,"/"),L=atob(_),V=new Uint8Array(L.length);for(let Y=0;Y<L.length;Y+=1)V[Y]=L.charCodeAt(Y);return V},z=async(E,P,_)=>{let L=null;const V=new Promise((Y,G)=>{L=setTimeout(()=>{G(new Error(_))},P)});try{return await Promise.race([E,V])}finally{L&&clearTimeout(L)}},q=async E=>{if(E.active)return;const P=E.installing||E.waiting;P&&P.state!=="activated"&&await z(new Promise(_=>{const L=()=>{P.state==="activated"&&(P.removeEventListener("statechange",L),_())};P.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 E=[{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 P=null;for(const _ of E)try{const L=_.opts?navigator.serviceWorker.register("/sw.js",_.opts):navigator.serviceWorker.register("/sw.js");return await z(L,1e4,`Service worker registration timed out (${_.label})`)}catch(L){P=L}throw P instanceof Error?P:new Error("Service worker registration failed")},Z=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const E=await navigator.serviceWorker.getRegistration();if(E)return E;const P=await H();try{await P.update()}catch{}return await q(P),P},W=E=>{const P=E,_=[`type=${typeof E}`,`toString=${String(E)}`,`name=${String(P?.name??"")}`,`message=${String(P?.message??"")}`];let L="";try{L=JSON.stringify(E)}catch{}return{summary:_.filter(Boolean).join(" | "),json:L,stack:typeof P?.stack=="string"?P.stack:""}},A=async()=>{const E=an();if(!E?.notifications){Q.error(t("settings.notifications.page.toast.notificationsApiUnavailable"));return}try{await E.notifications.notifyAgentCompletion({title:t("settings.notifications.page.testNotification.title"),body:t("settings.notifications.page.testNotification.body"),tag:"openchamber-test"})?Q.success(t("settings.notifications.page.toast.testNotificationSent")):Q.error(t("settings.notifications.page.toast.testNotificationFailed"))}catch(P){console.error("Test notification failed:",P),Q.error(t("settings.notifications.page.toast.testNotificationFailed"))}},X=async()=>{if(!j){Q.error(t("settings.notifications.page.toast.pushUnsupported"));return}const E=an();if(!E?.push){Q.error(t("settings.notifications.page.toast.pushApiUnavailable"));return}T(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const ae=await Notification.requestPermission();if(O(ae),ae!=="granted"){Q.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.enableInBrowser")});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){Q.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.enableInBrowser")});return}const P=await E.push.getVapidPublicKey();if(!P?.publicKey){Q.error(t("settings.notifications.page.toast.pushKeyLoadFailed"));return}const _=await Z();await q(_);const L=await _.pushManager.getSubscription();if(!("pushManager"in _)||!_.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const Y=(L??await z(_.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:R(P.publicKey)}),15e3,"Push subscription timed out")).toJSON(),G=Y.keys;if(!Y.endpoint||!G?.p256dh||!G.auth)throw new Error("Push subscription missing keys");if(!(await z(E.push.subscribe({endpoint:Y.endpoint,keys:{p256dh:G.p256dh,auth:G.auth},origin:typeof window<"u"?window.location.origin:void 0,platform:xu()}),15e3,"Push subscribe request timed out"))?.ok){Q.error(t("settings.notifications.page.toast.enableBackgroundFailed"));return}I(!0),Q.success(t("settings.notifications.page.toast.backgroundEnabled"))}catch(P){console.error("[Push] Enable failed:",P);const _=W(P);Q.error(t("settings.notifications.page.toast.enableBackgroundFailed"),{description:_.summary})}finally{T(!1)}},te=async()=>{if(!j){I(!1);return}const E=an();if(!E?.push){Q.error(t("settings.notifications.page.toast.pushApiUnavailable"));return}T(!0);try{const _=await(await Z()).pushManager.getSubscription();if(!_){I(!1);return}const L=_.endpoint;await _.unsubscribe(),await E.push.unsubscribe({endpoint:L}),I(!1),Q.success(t("settings.notifications.page.toast.backgroundDisabled"))}finally{T(!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:E=>{D(E)},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:E=>c(E?"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:g,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:h,label:t("settings.notifications.page.events.errorLabel"),ariaLabel:t("settings.notifications.page.events.errorAria")}),s.jsx(Ct,{checked:f,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(E=>s.jsxs("section",{className:"p-2",children:[s.jsx(gn,{className:"capitalize",children:t(uj[E])}),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(nt,{value:k[E].title,onChange:P=>F(E,"title",P.target.value),className:"h-7",placeholder:t(Pd[E].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(nt,{value:k[E].message,onChange:P=>F(E,"message",P.target.value),className:"h-7",placeholder:t(Pd[E].messageKey)})]})]})]},E))})})]}),i&&s.jsx(dt,{settingsItem:"notifications.push",title:t("settings.notifications.page.push.title"),children:s.jsx(Ct,{checked:j?b:!1,disabled:!j||B,onChange:E=>{E?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:B?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})})]})},Os=t=>{if(!t)return;t.pause();const{src:e}=t;e.startsWith("blob:")&&URL.revokeObjectURL(e),t.removeAttribute("src"),t.load()},pj=[{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"}],Td=t=>{const e=Ze.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},gj=({selectedModelId:t,onSelect:e})=>{const{t:n}=ot(),a=ve.useCallback(m=>n(m),[n]),[i,r]=ve.useState(new Map),[o,d]=ve.useState(null),c=ve.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(h=>[h.id,h])))}catch{}},[]);ve.useEffect(()=>{c()},[c]);const p=Array.from(i.values()).some(m=>m.downloading);ve.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)}},g=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:pj.map(m=>{const w=t===m.id,h=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:f=>{(f.key===" "||f.key==="Enter")&&(f.preventDefault(),e(m.id))},children:[s.jsx("div",{className:"pt-0.5",children:s.jsx(Nr,{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(Td,{value:m.accuracy,label:n("settings.voice.page.stt.meta.accuracy")}),s.jsx(Td,{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})]}),h?.downloadError?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:h.downloadError}):null]})]}),s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:h?.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:()=>{g(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")})]}):h?.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 h.downloadProgress=="number"?`${h.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)})})},po=[{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)"}],go="kokoro-en-v0_19",fj=()=>{const{t}=ot(),[e,n]=ve.useState(null),[a,i]=ve.useState(!1),r=ve.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===go):null;p&&n(p)}catch{}},[]);ve.useEffect(()=>{r()},[r]),ve.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/${go}/download`:`/api/dictation/models/${go}`;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},hj=[{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"}],xj=()=>{const{t}=ot(),{isMobile:e}=Hs(),n=pt(v=>v.voiceProvider),a=pt(v=>v.setVoiceProvider),i=pt(v=>v.speechRate),r=pt(v=>v.setSpeechRate),o=pt(v=>v.speechPitch),d=pt(v=>v.setSpeechPitch),c=pt(v=>v.speechVolume),p=pt(v=>v.setSpeechVolume),u=pt(v=>v.sayVoice),g=pt(v=>v.setSayVoice),m=pt(v=>v.localTtsVoiceId),w=pt(v=>v.setLocalTtsVoiceId),{speak:h,stop:f,isPlaying:x,error:k}=ng(),y=ve.useCallback(()=>{if(x){f();return}const v=po.find(ue=>ue.id===m)?.label??String(m);h(t("settings.voice.page.preview.voiceLine",{voiceName:v}),{speakerId:m,speed:pt.getState().speechRate})},[x,m,h,f,t]),C=pt(v=>v.browserVoice),O=pt(v=>v.setBrowserVoice),j=pt(v=>v.openaiVoice),N=pt(v=>v.setOpenaiVoice),b=pt(v=>v.openaiApiKey),I=pt(v=>v.setOpenaiApiKey),B=pt(v=>v.openaiCompatibleUrl),T=pt(v=>v.setOpenaiCompatibleUrl),D=pt(v=>v.openaiCompatibleApiKey),S=pt(v=>v.setOpenaiCompatibleApiKey),F=pt(v=>v.openaiCompatibleVoice),R=pt(v=>v.setOpenaiCompatibleVoice),z=pt(v=>v.openaiCompatibleTtsModel),q=pt(v=>v.setOpenaiCompatibleTtsModel),H=pt(v=>v.showMessageTTSButtons),Z=pt(v=>v.ttsInputMode),W=pt(v=>v.setTtsInputMode),A=pt(v=>v.sttProvider),X=pt(v=>v.setSttProvider),te=pt(v=>v.sttServerUrl),E=pt(v=>v.setSttServerUrl),P=pt(v=>v.sttApiKey),_=pt(v=>v.setSttApiKey),L=pt(v=>v.sttModel),V=pt(v=>v.setSttModel),Y=pt(v=>v.sttLocalModel),G=pt(v=>v.setSttLocalModel),me=pt(v=>v.sttLanguage),ae=pt(v=>v.setSttLanguage),xe=pt(v=>v.setShowMessageTTSButtons),be=pt(v=>v.dictationEnabled),ie=pt(v=>v.setDictationEnabled),[pe,Ie]=ve.useState(!1),[re,ce]=ve.useState([]),[ge,oe]=ve.useState(!1),[de,le]=ve.useState(null),[he,De]=ve.useState(!1),[Le,Ke]=ve.useState(!1),[Fe,Me]=ve.useState(null),[Be,Ge]=ve.useState(!1),[Ve,Ue]=ve.useState(null),[He,_e]=ve.useState([]),[Oe,se]=ve.useState(!1);ve.useEffect(()=>((async()=>{const ue=await Wr.waitForVoices();_e(ue)})(),"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=()=>{_e(window.speechSynthesis.getVoices())}),()=>{"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=null)}),[]);const ye=ve.useMemo(()=>He.filter(v=>v.lang).sort((v,ue)=>{const Ne=v.lang.startsWith("en"),we=ue.lang.startsWith("en");if(Ne&&!we)return-1;if(!Ne&&we)return 1;const qe=v.lang.localeCompare(ue.lang);return qe!==0?qe:v.name.localeCompare(ue.name)}),[He]),ke=ve.useCallback(()=>{if(Oe){Wr.cancelSpeech(),se(!1);return}const v=He.find(qe=>qe.name===C),ue=v?.name??t("settings.voice.page.preview.browserVoiceFallback"),Ne=t("settings.voice.page.preview.voiceLine",{voiceName:ue});se(!0);const we=new SpeechSynthesisUtterance(Ne);we.rate=i,we.pitch=o,we.volume=c,v&&(we.voice=v,we.lang=v.lang),we.onend=()=>se(!1),we.onerror=()=>se(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(we)},[C,He,i,o,c,Oe,t]);ve.useEffect(()=>()=>{Oe&&Wr.cancelSpeech()},[Oe]),ve.useEffect(()=>{if(!H||n!=="openai"&&n!=="openai-compatible"){De(b.trim().length>0);return}(async()=>{try{const we=(await(await ht("/api/tts/status")).json()).available,qe=b.trim().length>0;De(we||qe)}catch{De(b.trim().length>0)}})()},[b,H,n]),ve.useEffect(()=>{if(!H){Ie(!1),ce([]);return}ht("/api/tts/say/status").then(v=>v.json()).then(v=>{if(Ie(v.available),v.voices){const ue=v.voices.filter((Ne,we,qe)=>qe.findIndex(it=>it.name===Ne.name)===we).sort((Ne,we)=>Ne.name.localeCompare(we.name));ce(ue)}}).catch(()=>{Ie(!1)})},[H]);const ze=ve.useCallback(async()=>{if(de){Os(de),le(null),oe(!1);return}oe(!0);let v=null;try{const ue=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(!ue.ok)throw new Error("Preview failed");const Ne=await ue.blob(),we=URL.createObjectURL(Ne);v=new Audio(we),v.onended=()=>{Os(v),le(null),oe(!1)},v.onerror=()=>{Os(v),le(null),oe(!1)},le(v),await v.play()}catch{Os(v),le(null),oe(!1)}},[u,i,de,t]);ve.useEffect(()=>()=>{Os(de)},[de]);const $=ve.useCallback(async()=>{if(Fe){Os(Fe),Me(null),Ke(!1);return}Ke(!0);let v=null;try{const ue=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:b||void 0})});if(!ue.ok){const qe=await ue.json().catch(()=>({error:"Unknown error"}));throw new Error(qe.error||`HTTP ${ue.status}`)}const Ne=await ue.blob(),we=URL.createObjectURL(Ne);v=new Audio(we),v.onended=()=>{Os(v),Me(null),Ke(!1)},v.onerror=()=>{Os(v),Me(null),Ke(!1)},Me(v),await v.play()}catch{Os(v),Me(null),Ke(!1)}},[j,i,Fe,b,t]);ve.useEffect(()=>()=>{Os(Fe)},[Fe]);const Ee=ve.useCallback(async()=>{if(Ve){Os(Ve),Ue(null),Ge(!1);return}if(!B.trim())return;Ge(!0);let v=null;try{const ue=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:z||void 0,speed:i,baseURL:B,apiKey:D||void 0})});if(!ue.ok){const qe=await ue.json().catch(()=>({error:"Unknown error"}));throw new Error(qe.error||`HTTP ${ue.status}`)}const Ne=await ue.blob(),we=URL.createObjectURL(Ne);v=new Audio(we),v.onended=()=>{Os(v),Ue(null),Ge(!1)},v.onerror=()=>{Os(v),Ue(null),Ge(!1)},Ue(v),await v.play()}catch{Os(v),Ue(null),Ge(!1)}},[B,F,z,D,i,Ve,t]);ve.useEffect(()=>()=>{Os(Ve)},[Ve]);const J="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(en,{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(Qs,{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")},...pe?[{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(Ys,!he&&"text-[var(--status-error)]/80"),children:t(he&&!b?"settings.voice.page.field.apiKeyHintUsingConfig":he?"settings.voice.page.field.apiKeyHintProvide":"settings.voice.page.field.apiKeyHintRequired")}),s.jsxs("div",{className:fe("relative",$s),children:[s.jsx("input",{type:"password",value:b,onChange:v=>I(v.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"}),b&&s.jsx("button",{type:"button",onClick:()=>I(""),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,!B.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",$s),children:[s.jsx("input",{type:"text",value:B,onChange:v=>T(v.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"}),B&&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:Ys,children:"Optional"}),s.jsxs("div",{className:fe("relative",$s),children:[s.jsx("input",{type:"password",value:D,onChange:v=>S(v.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"}),D&&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",$s),children:s.jsx("input",{type:"text",value:z,onChange:v=>q(v.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",$s),children:[s.jsx("div",{className:"relative min-w-0 flex-1",children:s.jsx("input",{type:"text",value:F,onChange:v=>R(v.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:Ee,title:t("settings.voice.page.actions.preview"),disabled:!B.trim(),children:Be?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(fj,{}),s.jsxs(Xt,{label:t("settings.voice.page.field.voice"),children:[n==="local"&&s.jsxs(s.Fragment,{children:[s.jsxs(Mt,{value:String(m),onValueChange:v=>w(Number.parseInt(v,10)||0),children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder"),children:v=>po.find(ue=>String(ue.id)===v)?.label??v})}),s.jsx(Ft,{children:po.map(v=>s.jsx(jt,{value:String(v.id),children:v.label},v.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(Mt,{value:j,onValueChange:N,children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder")})}),s.jsx(Ft,{children:hj.map(v=>s.jsx(jt,{value:v.value,children:v.label},v.value))})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:$,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:Ys,children:t("settings.voice.page.field.configuredAbove")}),n==="say"&&pe&&re.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs(Mt,{value:u,onValueChange:g,children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder")})}),s.jsx(Ft,{children:re.map(v=>s.jsx(jt,{value:v.name,children:v.name},v.name))})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:ze,title:t("settings.voice.page.actions.preview"),children:ge?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"&&ye.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs(Mt,{value:C||"$auto",onValueChange:v=>O(v==="$auto"?"":v),children:[s.jsx(Lt,{size:Gt,className:$n,children:s.jsx(Wt,{placeholder:t("settings.voice.page.field.auto")})}),s.jsxs(Ft,{children:[s.jsx(jt,{value:"$auto",children:t("settings.voice.page.field.auto")}),ye.map(v=>s.jsxs(jt,{value:v.name,children:[v.name," (",v.lang,")"]},v.name))]})]}),s.jsx(ee,{size:"xs",variant:"ghost",onClick:ke,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:v=>r(Number(v.target.value)),className:J}),s.jsx(Ms,{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:v=>d(Number(v.target.value)),className:J}),s.jsx(Ms,{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:v=>p(Number(v.target.value)),className:J}),e?s.jsx(Ms,{value:Math.round(c*100),onValueChange:v=>p(v/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(en,{title:t("settings.voice.page.field.ttsInputMode"),children:s.jsx(Qs,{value:Z,onChange:W,"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:be,onChange:ie,label:t("settings.voice.page.field.enableVoiceInput"),ariaLabel:t("settings.voice.page.field.enableVoiceInputAria")}),be&&s.jsxs(s.Fragment,{children:[s.jsx(en,{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(Qs,{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(gj,{selectedModelId:Y,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",$s),children:[s.jsx("input",{type:"text",value:te,onChange:v=>E(v.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:()=>E(""),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:Ys,children:"Optional"}),s.jsxs("div",{className:fe("relative",$s),children:[s.jsx("input",{type:"password",value:P,onChange:v=>_(v.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"}),P&&s.jsx("button",{type:"button",onClick:()=>_(""),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",$s),children:s.jsx("input",{type:"text",value:L,onChange:v=>V(v.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:me,onChange:v=>ae(v.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"})})]})]})]})]})]})},Vi=[{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}],Hi=[{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}],bj="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",yj="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",fo=[{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"}],vj=[".yml",".yaml",".json"],wj="settings.openchamber.tunnel.error.invalidConfigExtension",ci=t=>{const e=t.trim().toLowerCase();return vj.some(n=>e.endsWith(n))},jj=t=>t==="ngrok"?"ngrok":"cloudflared",fm=()=>{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"},kj=(t,e=fm())=>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/",ho=(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():jj(n),i=typeof e?.platform=="string"&&e.platform.trim().length>0?e.platform.trim():fm(),r=typeof e?.installCommand=="string"&&e.installCommand.trim().length>0?e.installCommand.trim():kj(n,i);return{provider:n,dependency:a,installCommand:r}},hm=t=>t==="cloudflare"?"Cloudflare":t==="ngrok"?"Ngrok":t,Ad=t=>{const e=Ze.c(11),{provider:n}=t;let a;e[0]!==n?(a=hm(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 g;return e[8]!==p||e[9]!==u?(g=s.jsxs("span",{className:"flex items-center gap-2",children:[p,u]}),e[8]=p,e[9]=u,e[10]=g):g=e[10],g},Fn=t=>t==="quick"?"quick":t==="managed-remote"?"managed-remote":t==="managed-local"?"managed-local":"quick",sl=(t,e,n)=>t.find(i=>i.ms===e)?.value||n,Ed=(t,e,n)=>{const a=sl(t,e,n);return t.find(i=>i.value===a)?.label||a},Dd=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`},Nj=(t,e)=>gu(t,e,{hour:"2-digit",precision:"second"}),or=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()}},Sj=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=or(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},Cj=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,Ij=()=>{const{t}=ot(),e=je(ne=>ne.timeFormatPreference),n=l.useCallback(ne=>t(ne),[t]),[a,i]=l.useState("checking"),[r,o]=l.useState(null),[d,c]=l.useState(null),[p,u]=l.useState(null),[g,m]=l.useState(null),[w,h]=l.useState(null),[f,x]=l.useState(!1),[k,y]=l.useState(!1),[C,O]=l.useState(!1),[j,N]=l.useState("cloudflare"),[b,I]=l.useState(()=>ho("cloudflare")),[B,T]=l.useState([]),[D,S]=l.useState("quick"),[F,R]=l.useState(null),[z,q]=l.useState([]),[H,Z]=l.useState({}),[W,A]=l.useState(""),[X,te]=l.useState({}),[E,P]=l.useState(new Set),[_,L]=l.useState(!1),[V,Y]=l.useState(""),[G,me]=l.useState(""),[ae,xe]=l.useState(""),[be,ie]=l.useState(1800*1e3),[pe,Ie]=l.useState(480*60*1e3),[re,ce]=l.useState(""),[ge,oe]=l.useState([]),[de,le]=l.useState(()=>Date.now()),[he,De]=l.useState(null),Le=t(wj),Ke=l.useRef(null),Fe=l.useMemo(()=>F?!ci(F):!1,[F]),Me=l.useMemo(()=>z.find(ne=>ne.id===W)||z[0]||null,[z,W]),Be=l.useMemo(()=>ge.map(ne=>{const Pe=ne.expiresAt<=de,Xe=ne.status==="active"&&!Pe,Re=Xe?Dd(ne.expiresAt-de):ne.inactiveReason==="expired"||Pe?"expired":"inactive",Ye=Re==="expired"?t("settings.openchamber.tunnel.state.expired"):ne.inactiveReason==="tunnel-revoked"?t("settings.openchamber.tunnel.state.revoked"):t("settings.openchamber.tunnel.state.inactive"),We=Fn(ne.mode);return{...ne,isActive:Xe,mode:We,remainingTextForSession:Re,inactiveLabel:Ye}}),[de,ge,t]),Ge=l.useMemo(()=>r?.connectUrl?r.bootstrapExpiresAt===null?!0:r.bootstrapExpiresAt>de:!1,[de,r?.bootstrapExpiresAt,r?.connectUrl]),Ve=l.useMemo(()=>!r||a!=="active"&&a!=="stopping"?!1:d===D,[d,a,r,D]),Ue=l.useMemo(()=>!r||a!=="active"||!d?!1:d!==D,[d,a,r,D]),He=l.useMemo(()=>{if(typeof he=="number"&&Number.isFinite(he)&&he>0)return he;if(typeof window>"u")return null;const Pe=qa()||window.location.href;let Xe=0;try{Xe=Number(new URL(Pe).port)}catch{Xe=Number(window.location.port)}return Number.isFinite(Xe)&&Xe>0?Xe:null},[he]),_e=l.useMemo(()=>B.find(ne=>ne.provider===j)??null,[B,j]),Oe=l.useMemo(()=>{const ne=new Set(_e?.modes?.map(Pe=>Pe.key).filter(Pe=>Pe==="quick"||Pe==="managed-remote"||Pe==="managed-local"));return ne.size===0?fo:fo.filter(Pe=>ne.has(Pe.value))},[_e]),se=l.useMemo(()=>Oe.some(ne=>ne.value==="managed-remote"||ne.value==="managed-local"),[Oe]),ye=l.useMemo(()=>b.provider===j?b:ho(j),[b,j]),ke=l.useCallback(async ne=>{await Hn(ne)},[]),ze=l.useCallback((ne,Pe)=>(I(ho(Pe,ne)),ne.available===!0),[]),$=l.useCallback(async(ne,Pe)=>{try{const Xe=await ht("/api/openchamber/tunnel/check",{query:{provider:ne},...Pe?{signal:Pe}:{}});if(!Xe.ok)return null;const Re=await Xe.json();if(Pe?.aborted)return null;const Ye=ze(Re,ne);return i(We=>We==="checking"||We==="starting"||We==="active"||We==="stopping"?We:Ye?"idle":"not-available"),Ye}catch{return null}},[ze]),Ee=l.useCallback(async ne=>{try{const[Pe,Xe,Re,Ye]=await Promise.all([ht("/api/openchamber/tunnel/check",{signal:ne}),ht("/api/openchamber/tunnel/status",{signal:ne}),ht("/api/config/settings",{signal:ne,headers:{Accept:"application/json"}}),ht("/api/openchamber/tunnel/providers",{signal:ne})]),We=await Pe.json(),et=await Xe.json(),kt=Re.ok?await Re.json():{},Et=Ye.ok?await Ye.json():{},Ot=et.ttlConfig?.bootstrapTtlMs??(kt?.tunnelBootstrapTtlMs===null?null:typeof kt?.tunnelBootstrapTtlMs=="number"?kt.tunnelBootstrapTtlMs:1800*1e3),Zt=typeof et.ttlConfig?.sessionTtlMs=="number"?et.ttlConfig.sessionTtlMs:typeof kt?.tunnelSessionTtlMs=="number"?kt.tunnelSessionTtlMs:480*60*1e3,Qt=Fn(et.mode??kt?.tunnelMode),St=typeof kt?.tunnelProvider=="string"&&kt.tunnelProvider.trim().length>0?kt.tunnelProvider.trim().toLowerCase():"cloudflare",Pt=typeof kt?.managedLocalTunnelConfigPath=="string"&&kt.managedLocalTunnelConfigPath.trim()||null,Se=ze(We,St),ut=Sj(et?.managedRemoteTunnelPresets),mt=typeof et.managedRemoteTunnelHostname=="string"?et.managedRemoteTunnelHostname:"",At=ut.length>0?ut:mt?[{id:`legacy-${or(mt)}`,name:mt,hostname:or(mt)}]:[],ft=At[0]?.id||"";if(ie(Ot),Ie(Zt),N(St),T(Array.isArray(Et?.providers)?Et.providers:[]),S(Qt),R(Pt),q(At),A(ft),oe(Array.isArray(et.activeSessions)?et.activeSessions:[]),c(et.activeTunnelMode?Fn(et.activeTunnelMode):et.active&&et.mode?Fn(et.mode):null),P(new Set(Array.isArray(et.managedRemoteTunnelTokenPresetIds)?et.managedRemoteTunnelTokenPresetIds:[])),De(typeof et.localPort=="number"?et.localPort:null),et.active&&et.url){o({url:et.url,connectUrl:null,bootstrapExpiresAt:typeof et.bootstrapExpiresAt=="number"?et.bootstrapExpiresAt:null}),i("active");return}i(Se?"idle":"not-available")}catch{ne.aborted||(i("error"),m(t("settings.openchamber.tunnel.toast.checkAvailabilityFailed")))}},[ze,t]);l.useEffect(()=>{const ne=new AbortController;return Ee(ne.signal),()=>ne.abort()},[Ee]),l.useEffect(()=>{if(!r?.connectUrl){u(null);return}let ne=!1;return ku.toDataURL(r.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(Pe=>{ne||u(Pe)}).catch(()=>{ne||u(null)}),()=>{ne=!0}},[r?.connectUrl]),l.useEffect(()=>{if(!r?.bootstrapExpiresAt){ce(t("settings.openchamber.tunnel.state.noExpiry"));return}let ne=null,Pe=Date.now();const Xe=()=>{const We=r.bootstrapExpiresAt?r.bootstrapExpiresAt-Date.now():0;We<=0?ce(t("settings.openchamber.tunnel.state.expired")):ce(Dd(We))},Re=()=>{const We=Date.now();We-Pe>=1e3&&(Xe(),Pe=We),ne=requestAnimationFrame(Re)};Xe(),(typeof document>"u"||document.visibilityState==="visible")&&(ne=requestAnimationFrame(Re));const Ye=()=>{document.visibilityState==="visible"&&ne===null?ne=requestAnimationFrame(Re):document.visibilityState!=="visible"&&ne!==null&&(cancelAnimationFrame(ne),ne=null)};return document.addEventListener("visibilitychange",Ye),()=>{document.removeEventListener("visibilitychange",Ye),ne!==null&&cancelAnimationFrame(ne)}},[t,r?.bootstrapExpiresAt]),l.useEffect(()=>{let ne=null,Pe=Date.now();const Xe=()=>{const Ye=Date.now();Ye-Pe>=1e3&&(le(Ye),Pe=Ye),ne=requestAnimationFrame(Xe)};(typeof document>"u"||document.visibilityState==="visible")&&(ne=requestAnimationFrame(Xe));const Re=()=>{document.visibilityState==="visible"&&ne===null?ne=requestAnimationFrame(Xe):document.visibilityState!=="visible"&&ne!==null&&(cancelAnimationFrame(ne),ne=null)};return document.addEventListener("visibilitychange",Re),()=>{document.removeEventListener("visibilitychange",Re),ne!==null&&cancelAnimationFrame(ne)}},[]),l.useEffect(()=>{if(a==="starting"||a==="stopping"||a==="checking")return;let ne=!1;const Pe=async()=>{try{const Re=await ht("/api/openchamber/tunnel/status");if(!Re.ok||ne)return;const Ye=await Re.json();if(ne)return;oe(Array.isArray(Ye.activeSessions)?Ye.activeSessions:[]),P(new Set(Array.isArray(Ye.managedRemoteTunnelTokenPresetIds)?Ye.managedRemoteTunnelTokenPresetIds:[])),De(typeof Ye.localPort=="number"?Ye.localPort:null)}catch{}},Xe=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Pe()},5e3);return()=>{ne=!0,window.clearInterval(Xe)}},[a]);const J=l.useCallback(async ne=>{O(!0);try{await It(ne),Object.prototype.hasOwnProperty.call(ne,"tunnelMode")&&ne.tunnelMode&&S(ne.tunnelMode),Object.prototype.hasOwnProperty.call(ne,"tunnelProvider")&&typeof ne.tunnelProvider=="string"&&N(ne.tunnelProvider),Object.prototype.hasOwnProperty.call(ne,"managedLocalTunnelConfigPath")&&R(ne.managedLocalTunnelConfigPath??null),Object.prototype.hasOwnProperty.call(ne,"managedRemoteTunnelPresets")&&ne.managedRemoteTunnelPresets&&q(ne.managedRemoteTunnelPresets)}catch{Q.error(t("settings.openchamber.tunnel.toast.saveSettingsFailed"))}finally{O(!1)}},[t]),v=l.useCallback(async(ne,Pe)=>{y(!0);try{await It({tunnelBootstrapTtlMs:ne,tunnelSessionTtlMs:Pe})}catch{Q.error(t("settings.openchamber.tunnel.toast.saveTtlFailed"))}finally{y(!1)}},[t]),ue=l.useCallback(async ne=>{const Pe=ne.token.trim();if(Pe)try{const Xe={...X,[ne.presetId]:Pe};await It({managedRemoteTunnelPresetTokens:Xe}),P(Re=>{const Ye=new Set(Re);return Ye.add(ne.presetId),Ye})}catch{Q.error(t("settings.openchamber.tunnel.toast.saveTokenFailed"))}},[X,t]),Ne=l.useCallback(async ne=>{h(null),m(null);const Pe=B.find(Re=>Re.provider===ne),Xe=Pe?.modes?.some(Re=>Re.key===D)?D:Fn(Pe?.modes?.[0]?.key);await J({tunnelProvider:ne,tunnelMode:Xe}),$(ne)},[B,$,J,D]),we=l.useCallback(async()=>{const ne=await ml({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(ne.success&&typeof ne.path=="string"&&ne.path.trim().length>0){const Pe=ne.path.trim();if(!ci(Pe)){Q.error(Le);return}R(Pe),await J({managedLocalTunnelConfigPath:Pe});return}Ke.current?.click()},[Le,J]),qe=l.useCallback(ne=>{const Pe=ne.trim();R(Pe.length>0?Pe:null)},[]),it=l.useCallback(async()=>{if(F&&!ci(F)){Q.error(Le);return}await J({managedLocalTunnelConfigPath:F})},[Le,F,J]),st=l.useCallback(async()=>{R(null),await J({managedLocalTunnelConfigPath:null})},[J]),rt=l.useCallback(async ne=>{const Pe=ne.target.files?.[0];if(!Pe)return;const Xe=Pe.name.trim();if(Xe.length!==0){if(!ci(Xe)){Q.error(Le);return}R(Xe),await J({managedLocalTunnelConfigPath:Xe}),ne.target.value=""}},[Le,J]),lt=l.useCallback(async()=>{if(m(null),h(null),D==="managed-local"&&F&&!ci(F)){m(Le),Q.error(Le);return}i("starting");try{let ne="",Pe="";if(D==="managed-remote"){if(!Me){i("idle"),h(t("settings.openchamber.tunnel.toast.selectOrAddManagedRemoteFirst")),Q.error(t("settings.openchamber.tunnel.toast.selectOrAddManagedRemoteFirst"));return}ne=Me.hostname,Pe=(X[Me.id]||"").trim(),await J({tunnelMode:"managed-remote",managedRemoteTunnelPresets:z})}const Xe=await ht("/api/openchamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:j,mode:D,...D==="managed-remote"&&Me?{managedRemoteTunnelPresetId:Me.id,managedRemoteTunnelPresetName:Me.name}:{},...D==="managed-remote"&&ne?{managedRemoteTunnelHostname:ne}:{},...D==="managed-remote"&&Pe?{managedRemoteTunnelToken:Pe}:{},...D==="managed-local"&&F?{configPath:F}:{}})}),Re=await Xe.json();if(!Xe.ok||!Re.ok){if(D==="managed-remote"&&typeof Re.error=="string"&&Re.error.includes("Managed remote tunnel token is required")){i("idle"),h(t("settings.openchamber.tunnel.toast.managedRemoteTokenRequiredBeforeStarting")),Q.error(t("settings.openchamber.tunnel.toast.addManagedRemoteTokenBeforeStarting"));return}i("error"),m(Re.error||t("settings.openchamber.tunnel.toast.startFailed")),Q.error(Re.error||t("settings.openchamber.tunnel.toast.startFailed"));return}const Ye=typeof Re.url=="string"?Re.url:"";if(!Ye){i("error"),m(t("settings.openchamber.tunnel.toast.startedButNoPublicUrl")),Q.error(t("settings.openchamber.tunnel.toast.startedButNoPublicUrl"));return}if(o({url:Ye,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):D),oe(Array.isArray(Re.activeSessions)?Re.activeSessions:[]),Array.isArray(Re.managedRemoteTunnelTokenPresetIds)&&P(new Set(Re.managedRemoteTunnelTokenPresetIds)),typeof Re.localPort=="number"&&De(Re.localPort),typeof Re.mode=="string"&&S(Fn(Re.mode)),i("active"),Re.replacedTunnel){const We=typeof Re.revokedBootstrapCount=="number"?Re.revokedBootstrapCount:0,et=typeof Re.invalidatedSessionCount=="number"?Re.invalidatedSessionCount:0;We===1&&et===1?Q.warning(t("settings.openchamber.tunnel.toast.replacedTunnelSingleSingle")):We===1?Q.warning(t("settings.openchamber.tunnel.toast.replacedTunnelSingleManySessions",{invalidatedSessionCount:et})):et===1?Q.warning(t("settings.openchamber.tunnel.toast.replacedTunnelManyLinksSingleSession",{revokedBootstrapCount:We})):Q.warning(t("settings.openchamber.tunnel.toast.replacedTunnelManyMany",{revokedBootstrapCount:We,invalidatedSessionCount:et}))}else Q.success(t("settings.openchamber.tunnel.toast.linkReady"))}catch{i("error"),m(t("settings.openchamber.tunnel.toast.startFailed")),Q.error(t("settings.openchamber.tunnel.toast.startFailed"))}},[Le,z,J,Me,X,t,j,D,F]),xt=l.useCallback(async()=>{i("stopping");try{await ht("/api/openchamber/tunnel/stop",{method:"POST"});const ne=await ht("/api/openchamber/tunnel/status");if(ne.ok){const Pe=await ne.json();oe(Array.isArray(Pe.activeSessions)?Pe.activeSessions:[]),P(new Set(Array.isArray(Pe.managedRemoteTunnelTokenPresetIds)?Pe.managedRemoteTunnelTokenPresetIds:[])),De(typeof Pe.localPort=="number"?Pe.localPort:null)}o(null),c(null),u(null),i("idle"),Q.success(t("settings.openchamber.tunnel.toast.stopped"))}catch{i("error"),m(t("settings.openchamber.tunnel.toast.stopFailed")),Q.error(t("settings.openchamber.tunnel.toast.stopFailed"))}},[t]),bt=l.useCallback(async()=>{if(r?.connectUrl)try{await navigator.clipboard.writeText(r.connectUrl),x(!0),Q.success(t("settings.openchamber.tunnel.toast.connectLinkCopied")),setTimeout(()=>x(!1),2e3)}catch{Q.error(t("settings.openchamber.tunnel.toast.copyUrlFailed"))}},[t,r?.connectUrl]),Nt=l.useCallback(async ne=>{const Pe=Vi.find(Xe=>Xe.value===ne);Pe&&(ie(Pe.ms),await v(Pe.ms,pe))},[v,pe]),Ce=l.useCallback(async ne=>{const Pe=Hi.find(Xe=>Xe.value===ne);!Pe||Pe.ms===null||(Ie(Pe.ms),await v(be,Pe.ms))},[be,v]),Qe=l.useCallback(async ne=>{h(null),m(null),a!=="active"&&a!=="stopping"&&a!=="starting"&&i("idle"),await J({tunnelMode:ne,managedRemoteTunnelPresets:z})},[z,J,a]),tt=l.useCallback(async(ne,Pe)=>{try{await It({managedRemoteTunnelPresets:Pe})}catch{Q.error(t("settings.openchamber.tunnel.toast.saveSelectedManagedRemoteFailed"))}},[t]),at=l.useCallback(ne=>{const Pe=z.find(Xe=>Xe.id===ne);Pe&&(A(Pe.id),h(null),tt(Pe,z))},[z,tt]),gt=l.useCallback(async()=>{const ne=V.trim(),Pe=or(G),Xe=ae.trim();if(!ne){Q.error(t("settings.openchamber.tunnel.toast.tunnelNameRequired"));return}if(!Pe){Q.error(t("settings.openchamber.tunnel.toast.managedRemoteHostnameRequired"));return}if(!Xe){Q.error(t("settings.openchamber.tunnel.toast.managedRemoteTokenRequired"));return}if(z.some(We=>We.hostname===Pe)){Q.error(t("settings.openchamber.tunnel.toast.hostnameAlreadyExists"));return}const Re={id:Cj(),name:ne,hostname:Pe},Ye=[...z,Re];q(Ye),A(Re.id),Z(We=>({...We,[Re.id]:!0})),te(We=>({...We,[Re.id]:Xe})),h(null),L(!1),Y(""),me(""),xe(""),await J({tunnelMode:"managed-remote",managedRemoteTunnelPresets:Ye,managedRemoteTunnelPresetTokens:{...X,[Re.id]:Xe}}),await ue({presetId:Re.id,presetName:Re.name,hostname:Re.hostname,token:Xe}),Q.success(t("settings.openchamber.tunnel.toast.managedRemoteSaved"))},[z,G,V,ae,ue,J,X,t]),wt=l.useCallback(async ne=>{const Pe=z.find(et=>et.id===ne);if(!Pe)return;const Xe=z.filter(et=>et.id!==Pe.id),Re=Xe[0]?.id||"",Ye=W===Pe.id?Re:W,We=Object.fromEntries(Object.entries(X).filter(([et,kt])=>et!==Pe.id&&kt.trim().length>0));q(Xe),A(Ye),Z(et=>{const kt={...et};return delete kt[Pe.id],kt}),te(et=>{const kt={...et};return delete kt[Pe.id],kt}),P(et=>{const kt=new Set(et);return kt.delete(Pe.id),kt}),h(null),await J({managedRemoteTunnelPresets:Xe,managedRemoteTunnelPresetTokens:We}),Q.success(t("settings.openchamber.tunnel.toast.managedRemoteRemoved"))},[z,J,W,X,t]),Te="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:[Be.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:gc,children:t("settings.openchamber.tunnel.section.redeemedAccessLinks")})]}),s.jsx("div",{className:"space-y-1",children:Be.map(ne=>{const Pe=ne.mode==="quick",Xe=ne.mode==="managed-remote",Re=Pe?"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)]",Ye=ne.isActive?Pe?"text-[var(--status-warning)]":Xe?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-muted-foreground/50",We=t(Pe?"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",Ye)}),s.jsx("span",{className:fe("typography-micro rounded border px-1.5 py-0.5 uppercase",Re),children:We}),s.jsx("span",{className:"typography-meta text-muted-foreground/80",children:t("settings.openchamber.tunnel.session.redeemedAt",{time:Nj(ne.createdAt,e)})}),s.jsx("span",{className:"typography-meta text-foreground",children:ne.isActive?t("settings.openchamber.tunnel.session.expiresIn",{remaining:ne.remainingTextForSession}):ne.inactiveLabel===t("settings.openchamber.tunnel.state.inactive")?t("settings.openchamber.tunnel.state.inactive"):t("settings.openchamber.tunnel.session.inactiveWithReason",{reason:ne.inactiveLabel})})]},ne.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:gc,children:t("settings.openchamber.tunnel.notAvailable.dependencyNotFound",{dependency:ye.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:ye.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(Mt,{value:j,onValueChange:ne=>{Ne(ne)},disabled:C||a==="starting"||a==="stopping",children:[s.jsx(Lt,{size:Gt,className:"max-w-[16rem]",children:s.jsx(Wt,{placeholder:t("settings.openchamber.tunnel.field.providerPlaceholder"),children:hm(j)})}),s.jsxs(Ft,{children:[B.length>0?B.map(ne=>s.jsx(jt,{value:ne.provider,children:s.jsx(Ad,{provider:ne.provider})},ne.provider)):s.jsx(jt,{value:"cloudflare",children:s.jsx(Ad,{provider:"cloudflare"})}),s.jsx(jt,{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(ne=>s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsx(ee,{variant:"chip",size:"xs","aria-pressed":D===ne.value,className:"!font-normal",onClick:()=>{Qe(ne.value)},disabled:C||a==="starting"||a==="stopping",children:n(ne.labelKey)})}),s.jsx(ks,{sideOffset:8,className:"max-w-xs",children:n(ne.tooltipKey)})]},ne.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(Mt,{value:sl(Vi,be,"1800000"),onValueChange:ne=>{Nt(ne)},disabled:k||C||a==="starting"||a==="stopping",children:[s.jsx(Lt,{size:Gt,className:"max-w-[11rem] min-w-0",children:s.jsx(Wt,{className:"truncate",children:Ed(Vi,be,"1800000")})}),s.jsx(Ft,{children:Vi.map(ne=>s.jsx(jt,{value:ne.value,children:ne.label},ne.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(Mt,{value:sl(Hi,pe,"28800000"),onValueChange:ne=>{Ce(ne)},disabled:k||C||a==="starting"||a==="stopping",children:[s.jsx(Lt,{size:Gt,className:"max-w-[11rem] min-w-0",children:s.jsx(Wt,{className:"truncate",children:Ed(Hi,pe,"28800000")})}),s.jsx(Ft,{children:Hi.map(ne=>s.jsx(jt,{value:ne.value,children:ne.label},ne.value))})]})]})]}),D==="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")}),se&&s.jsx("p",{className:"typography-meta mt-1 text-[var(--status-warning)]",children:t("settings.openchamber.tunnel.warning.quickModeReliability")})]})]})}),D==="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(gn,{children:t("settings.openchamber.tunnel.section.savedManagedRemoteTunnels")}),s.jsxs(ee,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>L(ne=>!ne),disabled:a==="starting"||a==="stopping"||C,children:[s.jsx(K,{name:"add",className:"h-3.5 w-3.5"}),t("settings.common.actions.create")]})]}),z.length>0?s.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:z.map((ne,Pe)=>{const Xe=X[ne.id]||"",Re=E.has(ne.id),Ye=H[ne.id]??!1;return s.jsx("div",{className:fe(Pe<z.length-1&&"border-b border-[var(--surface-subtle)]"),children:s.jsxs(da,{open:Ye,onOpenChange:We=>{Z(et=>({...et,[ne.id]:We})),We&&at(ne.id)},className:"py-1.5",children:[s.jsxs("div",{className:"flex items-start gap-2 px-3",children:[s.jsxs(ua,{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:[Ye?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:ne.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:ne.name}),onClick:()=>{wt(ne.id)},disabled:a==="starting"||a==="stopping"||C,children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsx(ma,{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:ne.hostname})]}),s.jsx(nt,{type:"password",value:Xe,onChange:We=>{const et=We.target.value;h(null),te(kt=>({...kt,[ne.id]:et}))},onBlur:We=>{const et=We.currentTarget.value.trim();et&&ue({presetId:ne.id,presetName:ne.name,hostname:ne.hostname,token:et})},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:()=>{ue({presetId:ne.id,presetName:ne.name,hostname:ne.hostname,token:Xe})},children:t("settings.openchamber.tunnel.actions.saveToken")})})]})})]})},ne.id)})}):s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t("settings.openchamber.tunnel.empty.noManagedRemoteTunnels")}),_&&s.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[s.jsx(nt,{value:V,onChange:ne=>Y(ne.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetNamePlaceholder"),className:"h-7",disabled:C||a==="starting"||a==="stopping"}),s.jsx(nt,{value:G,onChange:ne=>me(ne.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetHostnamePlaceholder"),className:"h-7",disabled:C||a==="starting"||a==="stopping"}),s.jsx(nt,{type:"password",value:ae,onChange:ne=>xe(ne.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),Y(""),me(""),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")})]}),!Me&&w&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:w})]}),D==="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:Ke,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:ne=>{rt(ne)}}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(nt,{value:F||"",onChange:ne=>{qe(ne.target.value)},onBlur:()=>{it()},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:()=>{we()},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:()=>{st()},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})]})}),!Ve&&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:[D==="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:()=>{ke(bj)},children:[t("settings.openchamber.tunnel.actions.openManagedRemoteDocs"),s.jsx(K,{name:"external-link",className:"size-3.5"})]})]}),D==="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:()=>{ke(yj)},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(fo.find(ne=>ne.value===D)?.labelKey??"settings.openchamber.tunnel.option.mode.quick.label")})})]})]})}),D==="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(Mt,{value:W||(z[0]?.id??""),onValueChange:ne=>{at(ne)},disabled:C||a==="starting"||a==="stopping"||z.length<=1,children:[s.jsx(Lt,{size:Gt,children:s.jsx(Wt,{placeholder:t("settings.openchamber.tunnel.field.selectSavedTunnelPlaceholder"),children:Me?.name})}),s.jsx(Ft,{fitContent:!0,children:z.map(ne=>s.jsx(jt,{value:ne.id,children:ne.name},ne.id))})]})]}),Ue&&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:lt,disabled:a==="starting"||C||D==="managed-remote"&&!Me||D==="managed-local"&&Fe,className:fe(Te,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")})]})]}),Ve&&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})]}),Ge&&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:[f?s.jsx(K,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):s.jsx(K,{name:"file-copy",className:"size-3.5"}),t(f?"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?re: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:lt,disabled:a==="stopping"||C||D==="managed-local"&&Fe,className:Te,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"&&g&&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:g}),s.jsx(ee,{size:"sm",variant:"ghost",onClick:lt,children:t("settings.openchamber.tunnel.actions.retry")})]})]})})},xm=()=>{const{t}=ot(),[e,n]=ve.useState(""),[a,i]=ve.useState(!0),[r,o]=ve.useState(!1),d=je(f=>f.showOpenCodeUpdateNotifications),c=je(f=>f.setShowOpenCodeUpdateNotifications),p=je(f=>f.agentControlToolEnabled),u=je(f=>f.setAgentControlToolEnabled);ve.useEffect(()=>{let f=!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(f||!k)return;const y=typeof k.opencodeBinary=="string"?k.opencodeBinary.trim():"";n(y)}catch{}finally{f||i(!1)}})(),()=>{f=!0}},[]);const g=ve.useCallback(async()=>{if(!(typeof window>"u")&&ls())try{const f=await ml();f.success&&f.path&&f.path.trim().length>0&&n(f.path.trim())}catch{}},[]),m=ve.useCallback(async()=>{o(!0);try{const f=e.trim(),x=f.length>=2&&(f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'"))?f.slice(1,-1).trim():f;await It({opencodeBinary:x}),await _n({message:t("settings.openchamber.opencodeCli.actions.restartingOpenCode"),mode:"projects",scopes:["all"]})}finally{o(!1)}},[t,e]),w=ve.useCallback(f=>{c(f),It({showOpenCodeUpdateNotifications:f})},[c]),h=ve.useCallback(f=>{u(f),It({agentControlToolEnabled:f})},[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(nt,{value:e,onChange:f=>n(f.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:g,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(ca,{className:Ds,children:[!yu()&&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:h,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")})})]})]})})},bm=()=>{const{t}=ot(),e=ls()&&Ga(),n=e&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",[a,i]=ve.useState(!1),[r,o]=ve.useState(!1),[d,c]=ve.useState(""),[p,u]=ve.useState(""),[g,m]=ve.useState(!1),[w,h]=ve.useState(!1),[f,x]=ve.useState(null),[k,y]=ve.useState(!0),[C,O]=ve.useState(!1),[j,N]=ve.useState(!1),[b,I]=ve.useState(!1),[B,T]=ve.useState(!1),[D,S]=ve.useState(!1),[F,R]=ve.useState(!1),[z,q]=ve.useState(!1),[H,Z]=ve.useState(!0),[W,A]=ve.useState(!0),[X,te]=ve.useState(!1),[E,P]=ve.useState(!1),[_,L]=ve.useState(!1),[V,Y]=ve.useState(null),[G,me]=ve.useState(null);ve.useEffect(()=>{if(!e){y(!1);return}let le=!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 De=await he.json().catch(()=>null);if(le)return;const Le=De?.desktopLanAccessEnabled===!0,Ke=typeof De?.desktopUiPassword=="string"?De.desktopUiPassword:"";i(Le),o(Le),c(Ke),u(Ke),h(De?.desktopLanAccessActive===!0),x(typeof De?.desktopLanAccessBlockedReason=="string"?De.desktopLanAccessBlockedReason:null);const Fe=De?.desktopMacMenuBarEnabled!==!1;Z(Fe),A(Fe),Y(null)}catch(he){le||Y(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.loadFailed"))}finally{le||y(!1)}})(),()=>{le=!0}},[e,t]),ve.useEffect(()=>{if(!e){N(!1);return}let le=!1;return(async()=>{const he=await tf();le||(N(he?.supported===!0),I(he?.enabled===!0))})(),()=>{le=!0}},[e]),ve.useEffect(()=>{if(!e){S(!1);return}let le=!1;return(async()=>{const he=await sf();le||(S(he?.supported===!0),R(he?.enabled===!0))})(),()=>{le=!0}},[e]),ve.useEffect(()=>{if(!e){te(!1);return}let le=!1;return(async()=>{const he=await nf();le||(te(he?.supported===!0),P(he?.enabled===!0))})(),()=>{le=!0}},[e]),ve.useEffect(()=>{if(!e||!r){me(null);return}let le=!1;return(async()=>{const he=await bu();le||me(he)})(),()=>{le=!0}},[r,e]);const ae=r!==a||p!==d||W!==H,xe=ve.useMemo(()=>{if(typeof window>"u")return null;const he=qa()||window.location.href;let De=0;try{De=Number(new URL(he).port)}catch{De=Number(window.location.port)}return Number.isFinite(De)&&De>0?De:null},[]),be=r&&w&&G&&xe?`http://${G}:${xe}`:null,ie=r&&!p.trim(),pe=a&&!w&&f==="missing-password",Ie=k||C||!ae||ie,re=ve.useCallback(le=>{u(le),le.trim()||o(!1)},[]),ce=ve.useCallback(async()=>{if(!j||B)return;const le=!b;I(le),T(!0),Y(null);try{const he=await af(le);if(!he?.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.launchAtLoginUnsupported"));I(he.enabled)}catch(he){I(!le),Y(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.launchAtLoginSaveFailed"))}finally{T(!1)}},[B,b,j,t]),ge=ve.useCallback(async()=>{if(!D||z)return;const le=!F;R(le),q(!0),Y(null);try{const he=await rf(le);if(!he)throw new Error(t("settings.openchamber.desktopNetwork.error.minimizeToTraySaveFailed"));if(!he.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.minimizeToTrayUnsupported"));R(he.enabled)}catch(he){R(!le),Y(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.minimizeToTraySaveFailed"))}finally{q(!1)}},[z,F,D,t]),oe=ve.useCallback(async()=>{if(!X||_)return;const le=!E;P(le),L(!0),Y(null);try{const he=await of(le);if(!he?.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.keepAwakeUnsupported"));P(he.enabled)}catch(he){P(!le),Y(he instanceof Error?he.message:t("settings.openchamber.desktopNetwork.error.keepAwakeSaveFailed"))}finally{L(!1)}},[_,E,X,t]),de=ve.useCallback(async()=>{if(ae){O(!0),Y(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:W})})).ok)throw new Error(t("settings.openchamber.desktopNetwork.error.saveFailed"));if(i(r),c(p),Z(W),!await lf())throw new Error(t("settings.openchamber.desktopNetwork.error.savedRestartFailed"))}catch(le){Y(le instanceof Error?le.message:t("settings.openchamber.desktopNetwork.error.saveFailed")),O(!1)}}},[W,p,r,ae,t]);return e?s.jsx(dt,{title:t("settings.openchamber.desktopNetwork.title"),children:s.jsxs("div",{className:"space-y-3",children:[j||n||D||X?s.jsxs("div",{className:Ds,children:[j?s.jsx(Ct,{settingsItem:"sessions.desktop-launch-at-login",checked:b,onChange:le=>{le!==b&&ce()},disabled:B,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:W,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,D?s.jsx(Ct,{settingsItem:"sessions.desktop-minimize-to-tray",checked:F,onChange:le=>{le!==F&&ge()},disabled:z,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:E,onChange:le=>{le!==E&&oe()},disabled:_,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(nt,{id:"desktop-ui-password",type:g?"text":"password",className:"h-8 min-w-0 flex-1",value:p,onChange:le=>re(le.target.value),placeholder:t("settings.openchamber.desktopPassword.field.passwordPlaceholder"),disabled:k||C,required:r,"aria-invalid":ie}),s.jsx(ee,{type:"button",variant:"ghost",size:"xs",onClick:()=>m(le=>!le),className:Is,"aria-label":t(g?"settings.openchamber.desktopPassword.actions.hidePassword":"settings.openchamber.desktopPassword.actions.showPassword"),"aria-pressed":g,children:s.jsx(K,{name:g?"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")}),ie||pe?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,be?s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[t(ae&&!a?"settings.openchamber.desktopNetwork.hint.openAfterRestart":"settings.openchamber.desktopNetwork.hint.openNow"),s.jsx("span",{className:"font-mono text-foreground",children:be})]}):null,s.jsx("div",{className:"flex justify-start py-1.5",children:s.jsx(ee,{type:"button",size:"xs",onClick:de,disabled:Ie,className:"shrink-0 !font-normal",children:t(C?"settings.common.actions.saving":"settings.openchamber.desktopNetwork.actions.saveAndRestart")})})]})}):null},Pj=new Set(["shift","control","alt","meta"]),Tj=t=>{if(Pj.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=rg(t.key);return n?(e.push(n),La(e.join("+"))):null},Aj=()=>{const t=Ze.c(54),{t:e}=ot();let n;t[0]!==e?(n=_=>e(_),t[0]=e,t[1]=n):n=t[1];const a=n,i=je(Ej),r=je(Dj),o=je(Rj),d=je(Mj);let c;if(t[2]===Symbol.for("react.memo_cache_sentinel")){e:{const _=ag();if(!ds()){c=_;break e}c=_.filter(Lj)}t[2]=c}else c=t[2];const p=c;let u;t[3]!==a?(u=(_,L)=>{const V=`settings.openchamber.keyboardShortcuts.action.${_}.label`,Y=a(V);return Y===V?L:Y},t[3]=a,t[4]=u):u=t[4];const g=u,[m,w]=l.useState(null);let h;t[5]===Symbol.for("react.memo_cache_sentinel")?(h={},t[5]=h):h=t[5];const[f,x]=l.useState(h),[k,y]=l.useState(""),[C,O]=l.useState(""),[j,N]=l.useState(null),b=Fj;let I;t[6]!==i?(I=(_,L)=>{const V=La(L);for(const Y of p){if(Y.id===_)continue;const G=Ml(Y.id,i);if(La(G)===V)return Y.id}return null},t[6]=i,t[7]=I):I=t[7];const B=I;let T;t[8]!==B||t[9]!==r||t[10]!==i||t[11]!==e?(T=(_,L)=>{const V=La(L),Y=B(_,V);if(Y){N({actionId:_,combo:V,conflictActionId:Y}),y("");return}const G={...i,[_]:V};r(_,V),b(G),N(null),y(""),O(Ll(V)?e("settings.openchamber.keyboardShortcuts.warning.riskyBrowserShortcut"):""),x(me=>{const ae={...me};return delete ae[_],ae})},t[8]=B,t[9]=r,t[10]=i,t[11]=e,t[12]=T):T=t[12];const D=T;let S;t[13]!==j||t[14]!==r||t[15]!==i||t[16]!==e?(S=()=>{if(!j)return;const _={...i,[j.conflictActionId]:Fl,[j.actionId]:j.combo};r(j.conflictActionId,Fl),r(j.actionId,j.combo),b(_),N(null),y(""),O(Ll(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 R;t[18]!==o||t[19]!==i?(R=_=>{const L={...i};delete L[_],o(_),b(L),x(V=>{const Y={...V};return delete Y[_],Y}),N(null),y(""),O("")},t[18]=o,t[19]=i,t[20]=R):R=t[20];const z=R;let q;t[21]!==e?(q=e("settings.openchamber.keyboardShortcuts.title"),t[21]=e,t[22]=q):q=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(),b({}),x({}),N(null),y(""),O("")},t[25]=d,t[26]=Z):Z=t[26];let W;t[27]!==e?(W=e("settings.openchamber.keyboardShortcuts.actions.resetAll"),t[27]=e,t[28]=W):W=t[28];let A;t[29]!==Z||t[30]!==W?(A=s.jsx(ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Z,children:W}),t[29]=Z,t[30]=W,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]!==g||t[39]!==m||t[40]!==f||t[41]!==z||t[42]!==D||t[43]!==i||t[44]!==e?(te=p.map((_,L)=>{const V=Ml(_.id,i),Y=f[_.id],G=Y??V,me=typeof Y=="string"&&La(Y)!==La(V);return s.jsx("div",{className:fe("py-1.5",L>0&&"border-t border-border/40"),children:s.jsxs(Xt,{label:g(_.id,_.label),alignEnd:!1,children:[s.jsx(nt,{readOnly:!0,value:m===_.id?e("settings.openchamber.keyboardShortcuts.field.pressKeys"):ig(G),onFocus:()=>{w(_.id),y("")},onBlur:()=>{m===_.id&&w(null)},onKeyDown:ae=>{if(ae.preventDefault(),ae.stopPropagation(),ae.key==="Escape"){w(null);return}const xe=Tj(ae);xe&&(x(be=>({...be,[_.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 ae=f[_.id];if(!ae){y(e("settings.openchamber.keyboardShortcuts.error.captureFirst"));return}D(_.id,ae)},disabled:!me,children:e("settings.common.actions.saveChanges")}),s.jsx(ee,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>z(_.id),children:e("settings.common.actions.reset")})]})},_.id)}),t[38]=g,t[39]=m,t[40]=f,t[41]=z,t[42]=D,t[43]=i,t[44]=e,t[45]=te):te=t[45];let E;t[46]!==te?(E=s.jsx("div",{children:te}),t[46]=te,t[47]=E):E=t[47];let P;return t[48]!==A||t[49]!==X||t[50]!==E||t[51]!==q||t[52]!==H?(P=s.jsxs(dt,{settingsItem:"shortcuts.keyboard-shortcuts",title:q,divider:!1,info:H,headerAction:A,children:[X,E]}),t[48]=A,t[49]=X,t[50]=E,t[51]=q,t[52]=H,t[53]=P):P=t[53],P};function Ej(t){return t.shortcutOverrides}function Dj(t){return t.setShortcutOverride}function Rj(t){return t.clearShortcutOverride}function Mj(t){return t.resetAllShortcutOverrides}function Lj(t){return t.id!=="toggle_prompt_navigator"}function Fj(t){It({shortcutOverrides:t})}const ym=()=>{const t=Ze.c(2),[e,n]=l.useState(0);let a,i;return t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>ul(()=>n(qj)),i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),l.useEffect(a,i),e},Oj=t=>{const e=Ze.c(78),{section:n}=t,{t:a}=ot(),{isMobile:i}=Hs();ym();let r;e[0]!==i?(r=i&&Pn(),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()&&Ga(),e[3]=p):p=e[3];const u=p;if(!n){let X,te,E,P,_,L;e[4]===Symbol.for("react.memo_cache_sentinel")?(X=s.jsx(Ar,{}),te=s.jsx(gm,{}),E=u&&s.jsx(bm,{}),P=!c&&s.jsx(xm,{}),_=s.jsx(mm,{}),L=Pn()&&!ls()&&!c&&!dl()&&s.jsx(pm,{}),e[4]=X,e[5]=te,e[6]=E,e[7]=P,e[8]=_,e[9]=L):(X=e[4],te=e[5],E=e[6],P=e[7],_=e[8],L=e[9]);let V;e[10]!==o?(V=o&&s.jsx(Lu,{}),e[10]=o,e[11]=V):V=e[11];let Y;return e[12]!==V?(Y=s.jsxs(ps,{showSaveStatus:!0,className:"openchamber-page-body space-y-3 sm:space-y-6",children:[X,te,E,P,_,L,V]}),e[12]=V,e[13]=Y):Y=e[13],Y}let g;e[14]!==n?(g=()=>{switch(n){case"general":return s.jsx(Kj,{});case"visual":return s.jsx(Bj,{});case"chat":return s.jsx(_j,{});case"sessions":return s.jsx(Uj,{});case"shortcuts":return s.jsx(zj,{});case"git":return s.jsx($j,{});case"github":return s.jsx(Vj,{});case"notifications":return s.jsx(Hj,{});case"voice":return s.jsx(Wj,{});case"tunnel":return s.jsx(Gj,{});default:return null}},e[14]=n,e[15]=g):g=e[15];const m=g;let w;e[16]!==a?(w=a("settings.page.general.title"),e[16]=a,e[17]=w):w=e[17];let h;e[18]!==a?(h=a("settings.page.appearance.title"),e[18]=a,e[19]=h):h=e[19];let f;e[20]!==a?(f=a("settings.page.chat.title"),e[20]=a,e[21]=f):f=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 O;e[30]!==a?(O=a("settings.page.notifications.title"),e[30]=a,e[31]=O):O=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 b;e[36]!==y||e[37]!==C||e[38]!==O||e[39]!==j||e[40]!==N||e[41]!==w||e[42]!==h||e[43]!==f||e[44]!==x||e[45]!==k?(b={general:w,visual:h,chat:f,sessions:x,shortcuts:k,git:y,github:C,notifications:O,voice:j,tunnel:N},e[36]=y,e[37]=C,e[38]=O,e[39]=j,e[40]=N,e[41]=w,e[42]=h,e[43]=f,e[44]=x,e[45]=k,e[46]=b):b=e[46];const I=b[n];let B;e[47]!==a?(B=a("settings.page.general.description"),e[47]=a,e[48]=B):B=e[48];let T;e[49]!==a?(T=a("settings.page.appearance.description"),e[49]=a,e[50]=T):T=e[50];let D;e[51]!==a?(D=a("settings.page.chat.description"),e[51]=a,e[52]=D):D=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 R;e[57]!==a?(R=a("settings.page.notifications.description"),e[57]=a,e[58]=R):R=e[58];let z;e[59]!==a?(z=a("settings.page.voice.description"),e[59]=a,e[60]=z):z=e[60];let q;e[61]!==a?(q=a("settings.page.tunnel.description"),e[61]=a,e[62]=q):q=e[62];let H;e[63]!==B||e[64]!==T||e[65]!==D||e[66]!==S||e[67]!==F||e[68]!==R||e[69]!==z||e[70]!==q?(H={general:B,visual:T,chat:D,sessions:S,shortcuts:F,git:void 0,github:void 0,notifications:R,voice:z,tunnel:q},e[63]=B,e[64]=T,e[65]=D,e[66]=S,e[67]=F,e[68]=R,e[69]=z,e[70]=q,e[71]=H):H=e[71];const Z=H[n];let W;e[72]!==m?(W=m(),e[72]=m,e[73]=W):W=e[73];let A;return e[74]!==Z||e[75]!==I||e[76]!==W?(A=s.jsx(ps,{title:I,description:Z,showSaveStatus:!0,className:"openchamber-page-body",children:W}),e[74]=Z,e[75]=I,e[76]=W,e[77]=A):A=e[77],A},zj=()=>{const t=Ze.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(Aj,{}),t[0]=e):e=t[0],e},Kj=()=>{const t=Ze.c(7);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=ds(),t[0]=e):e=t[0];const n=e;ym();let a;t[1]===Symbol.for("react.memo_cache_sentinel")?(a=ls()&&Ga(),t[1]=a):a=t[1];const i=a;let r;t[2]===Symbol.for("react.memo_cache_sentinel")?(r=Pn()&&!ls()&&!n&&!dl(),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(bm,{}),c=o&&s.jsx(pm,{}),p=!n&&s.jsx(xm,{}),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(Ar,{visibleSettings:["fileEditorKeymap","autoSaveEnabled","expandedEditorToolbar",...n?[]:["terminalQuickKeys"],...n?[]:["terminalShell"],...n?[]:["terminalLoginShell"],"messageTransport","reportUsage"]})]}),t[6]=u):u=t[6],u},Bj=()=>{const t=Ze.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(Ar,{visibleSettings:["theme","windowControlsPosition","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat",...n?[]:["weekStart"],"fontSize","terminalFontSize","editorFontSize","spacing","inputBarOffset"]}),t[1]=a):a=t[1],a},_j=()=>{const t=Ze.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(Ar,{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},Uj=()=>{const t=Ze.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsxs(s.Fragment,{children:[s.jsx(gm,{}),s.jsx(mm,{})]}),t[0]=e):e=t[0],e},$j=()=>{const t=Ze.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(cm,{}),t[0]=e):e=t[0],e},Vj=()=>{const t=Ze.c(1);if(ds())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(dm,{}),t[0]=e):e=t[0],e},Hj=()=>{const t=Ze.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(mj,{}),t[0]=e):e=t[0],e},Wj=()=>{const t=Ze.c(1);if(ds())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(xj,{}),t[0]=e):e=t[0],e},Gj=()=>{const t=Ze.c(1);if(ds())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(Ij,{}),t[0]=e):e=t[0],e};function qj(t){return t+1}function Jj(t){const e=Ze.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 vm=[{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}],Yj={sessions:"sessions",agents:"agents",commands:"commands",mcp:"mcp",skills:"skills.installed",providers:"providers",usage:"usage","git-identities":"git",settings:"home"};function Ba(t){const e=t.trim().toLowerCase();return vm.find(n=>n.slug===e)??null}function vl(t){const e=(t??"").trim().toLowerCase();if(!e)return"home";const n=Yj[e];if(n)return n;const a=Ba(e);return a?a.slug:"home"}const Qj=[{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 Rd(t){return t.trim().toLocaleLowerCase()}function Xj({query:t,runtimeCtx:e,visiblePageSlugs:n,t:a,getPageTitle:i}){const r=Rd(t);if(!r)return[];const o=n?new Set(n):null,d=r.split(/\s+/).filter(Boolean);return Qj.flatMap(c=>{if(o&&!o.has(c.page))return[];const p=Ba(c.page);if(!p||p.isAvailable&&!p.isAvailable(e)||c.isAvailable&&!c.isAvailable(e))return[];const u=a(c.titleKey),g=c.descriptionKey?a(c.descriptionKey):null,m=Rd([u,g,i(c.page),...c.keywords??[]].filter(Boolean).join(" "));return d.every(w=>m.includes(w))?[{...c,title:u,description:g,pageTitle:i(c.page)}]:[]})}const Md=256,Ld=280,wm="__openchamberSettingsDetail",Zj=["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"],ek=["general","projects","opencode","content"],tk={icon:"chat-thread"},sk="__add_provider__";function nk(t,e){const n=ds(),a=!t&&Pn();return{isVSCode:n,isWeb:a,isDesktop:t,isMobile:e}}function Fd(t,e){return t.isAvailable?t.isAvailable(e):!0}function nl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function di(t,e){const n=new Set(e);let a=t,i=1;for(;n.has(a);)a=`${t}-${i}`,i+=1;return a}function xo(t){if(!nl(t))return null;const e=t[wm];if(!nl(e))return null;const n=e.page,a=e.stage;return typeof n!="string"||a!=="page-content"?null:{page:vl(n),stage:a}}function ak(){return typeof window>"u"||!nl(window.history.state)?{}:window.history.state}function jm(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 tk.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 ik=t=>{const e=Ze.c(124),{onClose:n,forceMobile:a,isWindowed:i,visiblePageSlugs:r,initialMobileStage:o}=t,d=o===void 0?"nav":o,{t:c}=ot(),p=Hs(),u=a??p.isMobile,g=je(rk),m=je(ok),w=je(lk);let h;e[0]!==g?(h=vl(g),e[0]=g,e[1]=h):h=e[1];const f=h,[x,k]=l.useState(d),y=l.useRef(d==="nav"?f:null);let C,O;e[2]!==u||e[3]!==w||e[4]!==f?(C=()=>{!u&&f==="home"&&w("general")},O=[u,w,f],e[2]=u,e[3]=w,e[4]=f,e[5]=C,e[6]=O):(C=e[5],O=e[6]),l.useEffect(C,O);const[j,N]=l.useState(""),[b,I]=l.useState(null),[B,T]=l.useState(0),D=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),R=l.useRef(0),z=l.useRef(!1);let q;e[8]===Symbol.for("react.memo_cache_sentinel")?(q=ls(),e[8]=q):q=e[8];const H=q;let Z;e[9]===Symbol.for("react.memo_cache_sentinel")?(Z=ls()&&Ga(),e[9]=Z):Z=e[9];const W=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 E=te;let P;e[12]===Symbol.for("react.memo_cache_sentinel")?(P=ls()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="linux",e[12]=P):P=e[12];const _=P;let L;e[13]===Symbol.for("react.memo_cache_sentinel")?(L=yu(),e[13]=L):L=e[13];const V=L;let Y;e[14]!==u?(Y=nk(H,u),e[14]=u,e[15]=Y):Y=e[15];const G=Y;let me;if(e[16]!==u||e[17]!==G||e[18]!==r){const ft=r?new Set(r):null;let vt;e[20]!==G?(vt=ts=>Fd(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],me=vm.filter(ck).filter(ts=>!ft||ft.has(ts.slug)).filter(vt).filter(Dt).filter(Vt),e[16]=u,e[17]=G,e[18]=r,e[19]=me}else me=e[19];const ae=me;let xe;e[26]===Symbol.for("react.memo_cache_sentinel")?(xe=new Map(Zj.map(dk)),e[26]=xe):xe=e[26];const be=xe;let ie;if(e[27]!==ae){let ft;e[29]===Symbol.for("react.memo_cache_sentinel")?(ft=(vt,Dt)=>(be.get(vt.slug)??999)-(be.get(Dt.slug)??999),e[29]=ft):ft=e[29],ie=ae.slice().sort(ft),e[27]=ae,e[28]=ie}else ie=e[28];const pe=ie,Ie=is(uk);let re;e[30]!==m||e[31]!==i||e[32]!==G.isVSCode||e[33]!==f?(re=()=>{if(!(!m&&!G.isVSCode&&!i)){if(f==="agents"){Va.getState().loadAgents();return}if(f==="commands"){Cr.getState().loadCommands();return}if(f==="mcp"){$a.getState().loadMcpConfigs();return}if(f==="plugins"){js.getState().loadPlugins();return}(f==="skills.installed"||f==="skills.catalog")&&(In.getState().loadSkills(),Sn.getState().loadCatalog()),f==="snippets"&&Ir.getState().loadSnippets()}},e[30]=m,e[31]=i,e[32]=G.isVSCode,e[33]=f,e[34]=re):re=e[34];let ce;e[35]!==Ie||e[36]!==m||e[37]!==i||e[38]!==G.isVSCode||e[39]!==f?(ce=[Ie,m,i,G.isVSCode,f],e[35]=Ie,e[36]=m,e[37]=i,e[38]=G.isVSCode,e[39]=f,e[40]=ce):ce=e[40],l.useEffect(re,ce);let ge;e[41]!==u||e[42]!==w?(ge=ft=>{if(w(ft),y.current=ft,!u)return;const vt=Ba(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]=ge):ge=e[43];const oe=ge;let de;e[44]!==f?(de=Ba(f),e[44]=f,e[45]=de):de=e[45];const le=de;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 De=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 Ke=Le;let Fe;e[49]!==Ke||e[50]!==G||e[51]!==j||e[52]!==c||e[53]!==r?(Fe=Xj({query:j,runtimeCtx:{...G,isDesktopLocalOrigin:W,isMac:X,isWindows:E,isLinux:_,isWindowsArm64:V},visiblePageSlugs:r,t:c,getPageTitle:Ke}),e[49]=Ke,e[50]=G,e[51]=j,e[52]=c,e[53]=r,e[54]=Fe):Fe=e[54];const Me=Fe,Be=xk;let Ge;if(e[55]!==Me){Ge=[];const ft=new Map;for(const vt of Me){let Dt=ft.get(vt.page);Dt||(Dt={page:vt.page,pageTitle:vt.pageTitle,results:[]},ft.set(vt.page,Dt),Ge.push(Dt)),Dt.results.push(vt)}e[55]=Me,e[56]=Ge}else Ge=e[56];const Ve=Ge;let Ue;e[57]===Symbol.for("react.memo_cache_sentinel")?(Ue=()=>{T(0),R.current=0,z.current=!1},e[57]=Ue):Ue=e[57];let He;e[58]!==j?(He=[j],e[58]=j,e[59]=He):He=e[59],l.useEffect(Ue,He);let _e,Oe;e[60]!==B?(_e=()=>{R.current=B},Oe=[B],e[60]=B,e[61]=_e,e[62]=Oe):(_e=e[61],Oe=e[62]),l.useEffect(_e,Oe);let se,ye;e[63]!==B?(se=()=>{F.current[B]?.scrollIntoView({block:"nearest"})},ye=[B],e[63]=B,e[64]=se,e[65]=ye):(se=e[64],ye=e[65]),l.useEffect(se,ye);let ke,ze;e[66]!==B||e[67]!==Me.length?(ke=()=>{B>=Me.length&&T(Math.max(0,Me.length-1)),F.current.length=Me.length},ze=[B,Me.length],e[66]=B,e[67]=Me.length,e[68]=ke,e[69]=ze):(ke=e[68],ze=e[69]),l.useEffect(ke,ze);let $;e[70]!==u||e[71]!==oe?($=ft=>{const vt=Be(ft);I(vt),oe(ft.page),u&&k("page-content"),ft.id==="plugins.create"&&typeof window<"u"&&window.setTimeout(bk,50)},e[70]=u,e[71]=oe,e[72]=$):$=e[72];const Ee=$;let J;e[73]!==Ee||e[74]!==j||e[75]!==Me?(J=ft=>{if(j.trim()){if(ft.key==="Escape"){ft.preventDefault(),N("");return}if(Me.length!==0){if(ft.key==="ArrowDown"){ft.preventDefault(),z.current=!0,T(vt=>(vt+1)%Me.length);return}if(ft.key==="ArrowUp"){ft.preventDefault(),z.current=!0,T(vt=>(vt-1+Me.length)%Me.length);return}if(ft.key==="Enter"){ft.preventDefault();const vt=(R.current%Me.length+Me.length)%Me.length,Dt=Me[vt]??Me[0];Dt&&Ee(Dt)}}}},e[73]=Ee,e[74]=j,e[75]=Me,e[76]=J):J=e[76];const v=J;let ue;e[77]!==b?(ue=()=>{const ft=b;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=D.current?.querySelector(`[data-settings-item="${Vt}"]`);ts&&(I(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]=b,e[78]=ue):ue=e[78];let Ne;e[79]!==b||e[80]!==f?(Ne=[b,f],e[79]=b,e[80]=f,e[81]=Ne):Ne=e[81],l.useEffect(ue,Ne);let we;e[82]!==c?(we=()=>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:gl,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]=we):we=e[83];const qe=we,it=yk;let st;e[84]!==qe||e[85]!==G||e[86]!==c?(st=ft=>{const vt=Ba(ft);if(vt&&!Fd(vt,G))return qe();switch(ft){case"projects":return s.jsx(Wv,{});case"remote-instances":return s.jsx(dw,{});case"agents":return s.jsx(lb,{});case"behavior":return s.jsx(pb,{});case"commands":return s.jsx(jb,{});case"mcp":return s.jsx(ey,{});case"plugins":return s.jsx(_y,{});case"skills.installed":return s.jsx(Qc,{view:"installed"});case"skills.catalog":return s.jsx(Qc,{view:"catalog"});case"providers":return s.jsx($w,{});case"usage":return s.jsx(N1,{});case"about":return s.jsx(ps,{title:c("settings.page.about.title"),showSaveStatus:!1,children:s.jsx(Lu,{})});case"magic-prompts":return s.jsx(T1,{});case"snippets":return s.jsx(M1,{});case"git":return s.jsx(K1,{});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"voice":case"tunnel":{const Dt=De[ft]??"visual";return s.jsx(Oj,{section:Dt})}default:return null}},e[84]=qe,e[85]=G,e[86]=c,e[87]=st):st=e[87];const rt=st;let lt,xt;e[88]!==u||e[89]!==x||e[90]!==f?(lt=()=>{if(!u||x!=="nav"||f==="home"||y.current===f)return;const ft=Ba(f);!ft||ft.slug==="home"||(y.current=f,k(ft.kind==="split"?"page-sidebar":"page-content"))},xt=[u,x,f],e[88]=u,e[89]=x,e[90]=f,e[91]=lt,e[92]=xt):(lt=e[91],xt=e[92]),l.useEffect(lt,xt);const bt=u&&x!=="nav",Nt=u&&x==="page-content"&&f==="skills.installed",Ce=x==="page-content"&&le?.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 tt=Qe,at=og();let gt;e[97]!==G.isVSCode?(gt=ft=>{if(typeof window>"u"||G.isVSCode)return;const vt=xo(window.history.state);vt?.page===ft&&vt.stage==="page-content"||window.history.pushState({...ak(),[wm]:{page:ft,stage:"page-content"}},"",window.location.href)},e[97]=G.isVSCode,e[98]=gt):gt=e[98];const wt=gt;let Te;e[99]!==wt||e[100]!==f?(Te=()=>{k("page-content"),f==="skills.installed"&&wt(f)},e[99]=wt,e[100]=f,e[101]=Te):Te=e[101];const ne=Te;let Pe;e[102]!==Nt||e[103]!==G.isVSCode||e[104]!==f?(Pe=()=>{if(Nt){if((typeof window<"u"?xo(window.history.state):null)?.page===f&&!G.isVSCode){window.history.back();return}k("page-sidebar");return}k("nav")},e[102]=Nt,e[103]=G.isVSCode,e[104]=f,e[105]=Pe):Pe=e[105];const Xe=Pe;let Re,Ye;e[106]!==u||e[107]!==G.isVSCode||e[108]!==f?(Re=()=>{if(!u||G.isVSCode)return;const ft=vt=>{if(f!=="skills.installed")return;if(xo(vt.state)?.page==="skills.installed"){k("page-content");return}k(vk)};return window.addEventListener("popstate",ft),()=>{window.removeEventListener("popstate",ft)}},Ye=[u,G.isVSCode,f],e[106]=u,e[107]=G.isVSCode,e[108]=f,e[109]=Re,e[110]=Ye):(Re=e[109],Ye=e[110]),l.useEffect(Re,Ye);let We;e[111]===Symbol.for("react.memo_cache_sentinel")?(We=()=>{k("page-sidebar")},e[111]=We):We=e[111];const et=We,kt=()=>{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:v,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?Me.length>0?(()=>{let vt=0;return Ve.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===B,En=!!Vt.description;return s.jsxs("button",{type:"button",ref:Ks=>{F.current[ts]=Ks},onMouseMove:()=>{z.current=!1,T(ts)},onClick:()=>Ee(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 pe){const ts=Vt.group,os=vt.get(ts);os?os.push(Vt):vt.set(ts,[Vt])}return ek.map(Vt=>({group:Vt,pages:vt.get(Vt)??[]})).filter(wk).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(Ks=>{const ha=f===Ks.slug&&!(u&&x==="nav"),Qn=jm(Ks.slug);return!Qn&&Ks.slug!=="mcp"?null:s.jsx(bs,{children:s.jsx(xs,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>oe(Ks.slug),"aria-current":ha?"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",ha?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[Ks.slug==="mcp"?s.jsx(Jj,{className:"h-[18px] w-[18px] shrink-0 sm:h-4 sm:w-4"}):s.jsx(K,{name:Qn,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:Ke(Ks.slug)}),Ks.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")})]})]})})},Ks.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:kk,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(wn,{children:kt()})})});if(!le)return s.jsx("div",{className:"flex-1 bg-background"});if(x==="page-sidebar"){if(le.kind!=="split"){const vt=rt(f);return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(wn,{children:vt})})}return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(wn,{children:it(f,{onItemSelect:ne})})})}const ft=rt(f);return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(wn,{children:ft})})};let Ot;e[112]!==le||e[113]!==rt||e[114]!==G.isVSCode||e[115]!==f?(Ot=()=>!le||f==="home"?null:le.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:Ld,minWidth:Ld,borderColor:"var(--interactive-border)"},children:s.jsx(wn,{children:it(f,{})})}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(wn,{children:rt(f)})})]}):s.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(wn,{children:rt(f)})}),e[112]=le,e[113]=rt,e[114]=G.isVSCode,e[115]=f,e[116]=Ot):Ot=e[116];const Zt=Ot,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":tt,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"):le?Ke(le.slug):c("settings.view.home.title")}),Ce&&s.jsx("button",{type:"button",onClick:et,"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:at}),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:at}),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"})})})]}),Se="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:`${Md}px`,minWidth:`${Md}px`,borderColor:"var(--interactive-border)"},children:s.jsx(wn,{children:kt()})}),s.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:Zt()})]});let mt;e[118]!==ut?(mt=s.jsx("div",{className:Se,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:D,"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 rk(t){return t.settingsPage}function ok(t){return t.isSettingsDialogOpen}function lk(t){return t.setSettingsPage}function ck(t){return t.slug!=="home"}function dk(t,e){return[t,e]}function uk(t){return t.activeProjectId}function mk(t){return t.name}function pk(t){return t.name}function gk(t){return t.name}function fk(t){return t.name}function hk(t){return t.name}function xk(t){if(t.id.startsWith("agents.")){const e=Va.getState(),n=di("new-agent",e.agents.map(mk));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=Cr.getState(),n=di("new-command",e.commands.map(pk));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=di("new-mcp-server",e.mcpServers.map(gk));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=Ir.getState(),n=di("new-snippet",e.snippets.map(fk));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=In.getState(),n=di("new-skill",e.skills.map(hk));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(sk),t.id==="plugins.create"?"plugins.spec":t.id}function bk(){window.dispatchEvent(new CustomEvent("openchamber:settings-open-plugin-add"))}function yk(t,e){switch(t){case"projects":return s.jsx(Nv,{onItemSelect:e.onItemSelect});case"agents":return s.jsx(Qx,{onItemSelect:e.onItemSelect});case"commands":return s.jsx(gb,{onItemSelect:e.onItemSelect});case"mcp":return s.jsx(Sb,{onItemSelect:e.onItemSelect});case"plugins":return s.jsx(Ty,{onItemSelect:e.onItemSelect});case"skills.installed":return s.jsx($y,{onItemSelect:e.onItemSelect});case"providers":return s.jsx(pw,{onItemSelect:e.onItemSelect});case"usage":return s.jsx(t1,{onItemSelect:e.onItemSelect});case"magic-prompts":return s.jsx(C1,{onItemSelect:e.onItemSelect});case"snippets":return s.jsx(A1,{onItemSelect:e.onItemSelect});default:return null}}function vk(t){return t==="page-content"?"page-sidebar":t}function wk(t){return t.pages.length>0}function jk(){}function kk(){_n({message:"Restarting OpenCode…",mode:"projects",scopes:["all"]}).catch(jk)}const bS=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:ik,getSettingsNavIcon:jm},Symbol.toStringTag,{value:"Module"})),Nk=["chat","git","diff","terminal","files","diagram"],Sk=["settings","agents","commands","skills","providers","usage","git-identities"],Xs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Od(t){const e=Ck();return{sessionId:Ik(e),tab:Pk(e),settingsPath:Tk(e),diffFile:Ak(e)}}function Ck(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function Ik(t){const e=t.get(Xs.SESSION);return!e||e.trim().length===0?null:e.trim()}function Pk(t){const e=t.get(Xs.TAB);if(!e)return null;const n=e.toLowerCase().trim();return Nk.includes(n)?n:null}function Tk(t){const e=t.get(Xs.SETTINGS);if(!e)return null;const n=e.toLowerCase().trim();return n.length===0?null:n==="openchamber"||n==="general"||n==="preferences"?"home":(Sk.includes(n),n)}function Ak(t){const e=t.get(Xs.FILE);if(!e||e.trim().length===0)return null;try{return decodeURIComponent(e.trim())}catch{return e.trim()}}function zd(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Xs.SESSION)||t.has(Xs.TAB)||t.has(Xs.SETTINGS)||t.has(Xs.FILE)}catch{return!1}}const Ek="chat";function km(t){const e=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&e.set(Xs.SESSION,t.sessionId),t.isSettingsOpen){const n=t.settingsPath.trim().length>0?t.settingsPath:"home";return e.set(Xs.SETTINGS,n),e}return t.tab!==Ek&&e.set(Xs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&e.set(Xs.FILE,t.diffFile),e}function Dk(t,e){const n=typeof window<"u"?window.location.pathname:"/",a=t.toString();return a?`${n}?${a}`:n}function Rk(t){if(typeof window>"u")return!0;try{const e=new URLSearchParams(window.location.search),n=km(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 Kd(t,e={}){if(!(typeof window>"u")&&!(Mk()||Nu())&&!(!e.force&&Rk(t)))try{const n=km(t),a=Dk(n);e.replace?window.history.replaceState({...window.history.state,route:t},"",a):window.history.pushState({route:t},"",a)}catch{}}function Mk(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function Lk(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function yS(){const t=l.useMemo(()=>Lk(),[]),e=l.useMemo(()=>Nu(),[]),n=l.useRef(!1),a=l.useRef(!1),i=es(m=>m.setCurrentSession),r=je(m=>m.setActiveMainTab),o=je(m=>m.setSettingsDialogOpen),d=je(m=>m.setSettingsPage),c=je(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 h=es.getState().getDirectoryForSession(m.sessionId);i(m.sessionId,h)}}if(m.settingsPath){d(vl(m.settingsPath)),o(!0);return}je.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=je.getState();return{sessionId:m.currentSessionId,tab:w.activeMainTab,isSettingsOpen:w.isSettingsDialogOpen,settingsPath:w.settingsPage,diffFile:w.pendingDiffFile}},[]),g=l.useCallback((m={})=>{if(t||e||a.current)return;const w=u();Kd(w,m)},[t,e,u]);l.useEffect(()=>{if(n.current||(n.current=!0,!zd()))return;const m=Od();(async()=>(await p(m),!t&&!e&&Kd({...u(),sessionId:m.sessionId??es.getState().currentSessionId,tab:m.tab??je.getState().activeMainTab,settingsPath:m.settingsPath??je.getState().settingsPage,diffFile:m.diffFile??je.getState().pendingDiffFile},{replace:!0,force:!0})))()},[p,u,t,e]),l.useEffect(()=>{if(t||e)return;let m=es.getState().currentSessionId;return es.subscribe(h=>{const f=h.currentSessionId;f===m||a.current||(m=f,g())})},[t,e,g]),l.useEffect(()=>{if(t||e)return;let m=je.getState().activeMainTab,w=je.getState().isSettingsDialogOpen,h=je.getState().settingsPage,f=je.getState().pendingDiffFile;return je.subscribe(k=>{if(a.current)return;const y=k.activeMainTab!==m,C=k.isSettingsDialogOpen!==w,O=k.settingsPage!==h,j=k.pendingDiffFile!==f&&k.activeMainTab==="diff";m=k.activeMainTab,w=k.isSettingsDialogOpen,h=k.settingsPage,f=k.pendingDiffFile,(y||C||O||j)&&g()})},[t,e,g]),l.useEffect(()=>{if(typeof window>"u"||t||e)return;const m=()=>{const w=Od();if(zd())p(w);else{const h=je.getState();h.isSettingsDialogOpen&&o(!1),h.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[p,t,e,r,o])}function vS(){const t=Ze.c(5),e=Ru(Ok),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=Fk,u=g=>{d||(c=window.setTimeout(async()=>{const m=await n.current(),w=typeof m=="number"&&Number.isFinite(m)?p(m):36e5;u(w)},g))};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 Fk(t){const e=Math.round(t*1e3);return Math.max(3e5,Math.min(864e5,e))}function Ok(t){return t.checkForUpdates}const zk=()=>{const t=Ze.c(13),[e,n]=ve.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]),ve.useEffect(a,i);let r;t[2]!==e?(r=async m=>e?await cf(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 df():{success:!0},t[4]=e,t[5]=d):d=t[5];const c=d;let p;t[6]!==e?(p=async m=>e?await uf():{success:!0},t[6]=e,t[7]=p):p=t[7];const u=p;let g;return t[8]!==e||t[9]!==o||t[10]!==c||t[11]!==u?(g={isDesktop:e,requestAccess:o,startAccessing:c,stopAccessing:u},t[8]=e,t[9]=o,t[10]=c,t[11]=u,t[12]=g):g=t[12],g},Kk=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Bk=({currentBranch:t,localBranches:e,remoteBranches:n,branchInfo:a,onCheckout:i,onCreate:r,remotes:o=[],disabled:d=!1})=>{const{t:c}=ot(),[p,u]=l.useState(!1),[g,m]=l.useState(""),[w,h]=l.useState(!1),[f,x]=l.useState(!1),[k,y]=l.useState(""),[C,O]=l.useState(!1),j=l.useRef(null),N=l.useCallback(H=>{H.stopPropagation()},[]),b=o.length>1,I=l.useMemo(()=>Kk(k),[k]),B=l.useMemo(()=>{const H=g.toLowerCase();return H?e.filter(Z=>Z.toLowerCase().includes(H)):e},[g,e]),T=l.useMemo(()=>{const H=g.toLowerCase();return H?n.filter(Z=>Z.toLowerCase().includes(H)):n},[g,n]),D=H=>{if(H===t){u(!1);return}i(H),u(!1),m("")},S=()=>{h(!0),setTimeout(()=>j.current?.focus(),50)},F=async()=>{if(!(!I||C)){if(b){x(!0);return}O(!0);try{await r(I,o[0]),y(""),h(!1),u(!1)}finally{O(!1)}}},R=async H=>{if(!(!I||C)){O(!0);try{await r(I,H),y(""),h(!1),x(!1),u(!1)}finally{O(!1)}}},z=()=>{x(!1)},q=()=>{y(""),h(!1),x(!1)};return l.useEffect(()=>{p||(m(""),h(!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(Fo,{className:"h-full min-h-0",children:[s.jsx(Oo,{placeholder:c("gitView.branch.searchPlaceholder"),value:g,onValueChange:m,onKeyDown:N}),s.jsxs(zo,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(Ko,{children:c("gitView.branch.empty")}),s.jsx(Nn,{children:f?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:z,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:I})," ",c("gitView.branch.pushToSuffix")]})]}),s.jsx("div",{className:"flex flex-col gap-1",children:o.map(H=>s.jsxs("button",{type:"button",onClick:()=>R(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(),q())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:F,disabled:!I||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:q,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(tn,{onSelect:S,children:[s.jsx(K,{name:"add",className:"size-4"}),s.jsx("span",{children:c("gitView.branch.create")})]})}),s.jsx(Ka,{}),s.jsxs(Nn,{heading:c("gitView.branch.localBranches"),children:[B.map(H=>s.jsxs(tn,{onSelect:()=>D(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}`)),B.length===0&&s.jsx(tn,{disabled:!0,className:"justify-center",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:c("gitView.branch.noLocalBranches")})})]}),s.jsx(Ka,{}),s.jsxs(Nn,{heading:c("gitView.branch.remoteBranches"),children:[T.map(H=>s.jsx(tn,{onSelect:()=>D(H),children:s.jsx("span",{className:"typography-ui-label text-foreground",children:H})},`remote-${H}`)),T.length===0&&s.jsx(tn,{disabled:!0,className:"justify-center",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:c("gitView.branch.noRemoteBranches")})})]})]})]})})]})},_k=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Uk=({currentBranch:t,onRename:e,showEditButton:n=!0})=>{const{t:a}=ot(),[i,r]=l.useState(!1),[o,d]=l.useState(t||""),[c,p]=l.useState(!1),u=l.useRef(null),g=()=>{!t||!e||(d(t),r(!0),setTimeout(()=>u.current?.focus(),0))},m=async()=>{if(!t||!e||!o.trim())return;const f=_k(o);if(f===t){r(!1);return}p(!0);try{await e(t,f),r(!1),d("")}finally{p(!1)}},w=()=>{r(!1),d("")},h=f=>{f.key==="Enter"?(f.preventDefault(),m()):f.key==="Escape"&&(f.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:f=>{f.preventDefault(),m()},children:[s.jsx(K,{name:"git-branch",className:"size-4 text-primary"}),s.jsx("input",{ref:u,value:o,onChange:f=>d(f.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:h,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:g,title:a("gitView.branch.renameTitle"),children:s.jsx(K,{name:"edit",className:"size-4"})})]})]})},$k=t=>{const e=Ze.c(44),{syncAction:n,remotes:a,onFetch:i,onSync:r,onRemoveRemote:o,disabled:d,removingRemoteName:c,aheadCount:p,behindCount:u,trackingRemoteName:g,hasUncommittedChanges:m}=t,w=a===void 0?[]:a,h=c===void 0?null:c,f=p===void 0?0:p,x=u===void 0?0:u,k=m===void 0?!1:m,{t:y}=ot(),C=l.useRef(!1),O=!!h,j=w.find(oe=>oe.name===g)??w[0],N=x>0&&k,b=d||n!==null||O||!j||N,I=d||n!==null||O||w.length===0,B=f>0||x>0;let T;e[0]!==y?(T=y("gitView.sync.sync"),e[0]=y,e[1]=T):T=e[1];const D=x>0?`↓${x}`:null,S=f>0?`↑${f}`:null;let F;e[2]!==T||e[3]!==D||e[4]!==S?(F=[T,D,S].filter(Boolean),e[2]=T,e[3]=D,e[4]=S,e[5]=F):F=e[5];const R=F.join(" "),z=N?y("gitView.sync.commitOrStashTooltip"):j?B?y("gitView.sync.syncChangesTooltip",{ahead:f,behind:x}):y("gitView.sync.syncChanges"):y("gitView.sync.noRemoteTooltip"),q=()=>{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 W;e[6]===Symbol.for("react.memo_cache_sentinel")?(W=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]=W):W=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]!==R?(te=s.jsx("span",{className:"whitespace-nowrap tabular-nums",children:R}),e[11]=R,e[12]=te):te=e[12];let E;e[13]!==q||e[14]!==b||e[15]!==A||e[16]!==X||e[17]!==te?(E=s.jsxs("button",{type:"button",onClick:q,disabled:b,className:W,"aria-label":A,children:[X,te]}),e[13]=q,e[14]=b,e[15]=A,e[16]=X,e[17]=te,e[18]=E):E=e[18];let P;e[19]!==Z||e[20]!==E?(P=s.jsx(xs,{asChild:!0,children:s.jsx("span",{className:"inline-flex",tabIndex:Z,children:E})}),e[19]=Z,e[20]=E,e[21]=P):P=e[21];let _;e[22]!==z?(_=s.jsx(ks,{sideOffset:8,children:z}),e[22]=z,e[23]=_):_=e[23];let L;e[24]!==P||e[25]!==_?(L=s.jsxs(bs,{children:[P,_]}),e[24]=P,e[25]=_,e[26]=L):L=e[26];const V=fs;let Y;e[27]===Symbol.for("react.memo_cache_sentinel")?(Y=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]=Y):Y=e[27];let G;e[28]!==y?(G=y("gitView.sync.moreActionsAria"),e[28]=y,e[29]=G):G=e[29];let me;e[30]===Symbol.for("react.memo_cache_sentinel")?(me=s.jsx(K,{name:"arrow-down-s",className:"size-4"}),e[30]=me):me=e[30];let ae;e[31]!==I||e[32]!==G?(ae=s.jsx(gs,{asChild:!0,children:s.jsx("button",{type:"button",className:Y,disabled:I,"aria-label":G,children:me})}),e[31]=I,e[32]=G,e[33]=ae):ae=e[33];const xe=hs,be="start",ie=-40,pe="w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",Ie=w.map(oe=>s.jsx(as,{onSelect:de=>{if(C.current){de.preventDefault(),C.current=!1;return}i(oe)},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:oe.name})}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:oe.fetchUrl})]})}),o&&oe.name!==g?s.jsx(ee,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:n!==null||O,onPointerDown:de=>{C.current=!0,de.preventDefault(),de.stopPropagation()},onClick:de=>{C.current=!0,de.preventDefault(),de.stopPropagation(),o(oe)},"aria-label":y("gitView.header.removeRemoteAria",{name:oe.name}),title:y("gitView.header.removeRemoteTitle",{name:oe.name}),children:h===oe.name?s.jsx(K,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(K,{name:"close",className:"size-3.5"})}):null]})},oe.name));let re;e[34]!==xe||e[35]!==Ie?(re=s.jsx(xe,{align:be,alignOffset:ie,className:pe,children:Ie}),e[34]=xe,e[35]=Ie,e[36]=re):re=e[36];let ce;e[37]!==V||e[38]!==ae||e[39]!==re?(ce=s.jsxs(V,{children:[ae,re]}),e[37]=V,e[38]=ae,e[39]=re,e[40]=ce):ce=e[40];let ge;return e[41]!==L||e[42]!==ce?(ge=s.jsxs("div",{className:H,children:[L,ce]}),e[41]=L,e[42]=ce,e[43]=ge):ge=e[43],ge},Vk={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Hk={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 Nm(t){return t&&Hk[t]||"var(--primary)"}const Bd=t=>{const e=Ze.c(8),{icon:n,className:a,colorToken:i}=t,r=Vk[n??"branch"]??"user-3";let o;e[0]!==i?(o=Nm(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},Sm=t=>{const e=Ze.c(35),{activeProfile:n,identities:a,onSelect:i,isApplying:r,iconOnly:o}=t,d=o===void 0?!1:o,{t:c}=ot(),p=r||a.length===0,u=n?.color;let g;e[0]!==u?(g=Nm(u),e[0]=u,e[1]=g):g=e[1];let m;e[2]!==g?(m={color:g},e[2]=g,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(Bd,{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 h;e[8]!==n?.name||e[9]!==d||e[10]!==c?(h=!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]=h):h=e[11];let f;e[12]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(K,{name:"arrow-down-s",className:"size-4 opacity-60"}),e[12]=f):f=e[12];let x;e[13]!==p||e[14]!==m||e[15]!==w||e[16]!==h?(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,h,f]})})}),e[13]=p,e[14]=m,e[15]=w,e[16]=h,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 O;e[25]!==n?.id||e[26]!==a||e[27]!==i||e[28]!==c?(O=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(b=>{const I=n?.id===b.id;return s.jsx(as,{onSelect:()=>i(b),children:s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(Bd,{icon:b.icon,colorToken:b.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:b.name}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:b.userEmail})]}),I?s.jsx(K,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},b.id)}),e[25]=n?.id,e[26]=a,e[27]=i,e[28]=c,e[29]=O):O=e[29];let j;e[30]!==O?(j=s.jsx(hs,{align:"end",className:"w-64",children:O}),e[30]=O,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},Wk=t=>{const e=Ze.c(21),{comparison:n,trackingBranch:a,tooltipDelayMs:i}=t,r=i===void 0?1e3:i,{t:o}=ot(),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 g;e[4]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(K,{name:"git-branch",className:"size-3.5 shrink-0"}),e[4]=g):g=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 h;e[12]!==m||e[13]!==w?(h=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:[g,m,w]})}),e[12]=m,e[13]=w,e[14]=h):h=e[14];let f;e[15]!==u?(f=s.jsx(ks,{sideOffset:8,children:u}),e[15]=u,e[16]=f):f=e[16];let x;return e[17]!==h||e[18]!==f||e[19]!==r?(x=s.jsxs(bs,{delayDuration:r,children:[h,f]}),e[17]=h,e[18]=f,e[19]=r,e[20]=x):x=e[20],x},wS=t=>{const e=Ze.c(67),{status:n,localBranches:a,remoteBranches:i,branchInfo:r,syncAction:o,remotes:d,onFetch:c,onSync:p,onRemoveRemote:u,removingRemoteName:g,onCheckoutBranch:m,onCreateBranch:w,onRenameBranch:h,activeIdentityProfile:f,availableIdentities:x,onSelectIdentity:k,isApplyingIdentity:y,isWorktreeMode:C,onOpenHistory:O,onOpenGraph:j,onOpenStashes:N,onOpenUpdateBranch:b,onOpenReintegrateCommits:I,pullRequest:B,prChecks:T,onOpenPullRequest:D}=t,{t:S}=ot();if(!n)return null;let F;e[0]!==j||e[1]!==O||e[2]!==I||e[3]!==N||e[4]!==b||e[5]!==S?(F=O||j||N||b?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:[O?s.jsxs(as,{onSelect:O,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,b?s.jsxs(as,{onSelect:b,children:[s.jsx(K,{name:"git-merge",className:"size-4"}),S("gitView.header.updateBranch")]}):null,I?s.jsxs(as,{onSelect:I,children:[s.jsx(K,{name:"split-cells-horizontal",className:"size-4"}),S("gitView.integrate.title")]}):null]})]}):null,e[0]=j,e[1]=O,e[2]=I,e[3]=N,e[4]=b,e[5]=S,e[6]=F):F=e[6];let R;e[7]!==F?(R=s.jsx("div",{className:"flex items-center gap-1 shrink-0",children:F}),e[7]=F,e[8]=R):R=e[8];const z=R,q=T?T.state==="success"?"var(--status-success)":T.state==="failure"?"var(--status-error)":"var(--status-warning)":null,H=B?B.state==="merged"?"merged":B.state==="closed"?"closed":B.draft?"draft":T?.state==="failure"||B.mergeable===!1||B.mergeableState==="blocked"||B.mergeableState==="dirty"?"blocked":"open":null;let Z;e[9]!==D||e[10]!==q||e[11]!==H||e[12]!==B||e[13]!==S?(Z=B&&D?s.jsxs(bs,{children:[s.jsx(xs,{asChild:!0,children:s.jsxs(ee,{variant:"ghost",size:"sm",onClick:D,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:B.number})}),q?s.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:q}}):null]})}),s.jsx(ks,{sideOffset:8,children:S("gitView.header.openPullRequest")})]}):null,e[9]=D,e[10]=q,e[11]=H,e[12]=B,e[13]=S,e[14]=Z):Z=e[14];const W=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 E;e[17]!==c||e[18]!==u||e[19]!==p||e[20]!==d||e[21]!==g||e[22]!==n.ahead||e[23]!==n.behind||e[24]!==o||e[25]!==A||e[26]!==X||e[27]!==te?(E=s.jsx($k,{syncAction:o,remotes:d,onFetch:c,onSync:p,onRemoveRemote:u,removingRemoteName:g,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]=g,e[22]=n.ahead,e[23]=n.behind,e[24]=o,e[25]=A,e[26]=X,e[27]=te,e[28]=E):E=e[28];const P=E;let _;e[29]!==n.tracking||e[30]!==n.upstreamComparison?(_=n.upstreamComparison?s.jsx(Wk,{comparison:n.upstreamComparison,trackingBranch:n.tracking,tooltipDelayMs:1e3}):null,e[29]=n.tracking,e[30]=n.upstreamComparison,e[31]=_):_=e[31];const L=_;let V;e[32]!==f||e[33]!==x||e[34]!==y||e[35]!==k?(V=s.jsx(Sm,{activeProfile:f,identities:x,onSelect:k,isApplying:y,iconOnly:!0}),e[32]=f,e[33]=x,e[34]=y,e[35]=k,e[36]=V):V=e[36];const Y=V;let G;e[37]!==r||e[38]!==C||e[39]!==a||e[40]!==m||e[41]!==w||e[42]!==h||e[43]!==i||e[44]!==d||e[45]!==n.current?(G=s.jsx("div",{className:"min-w-0 flex-1",children:C?s.jsx(Uk,{currentBranch:n.current,onRename:h}):s.jsx(Bk,{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]=h,e[43]=i,e[44]=d,e[45]=n.current,e[46]=G):G=e[46];let me;e[47]!==Y?(me=s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:Y}),e[47]=Y,e[48]=me):me=e[48];let ae;e[49]!==G||e[50]!==me?(ae=s.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[G,me]}),e[49]=G,e[50]=me,e[51]=ae):ae=e[51];let xe;e[52]!==W?(xe=W?s.jsx("div",{className:"shrink-0",children:W}):null,e[52]=W,e[53]=xe):xe=e[53];let be;e[54]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx("div",{className:"min-w-0 flex-1"}),e[54]=be):be=e[54];let ie;e[55]!==L?(ie=L?s.jsx("div",{className:"min-w-0 shrink",children:L}):null,e[55]=L,e[56]=ie):ie=e[56];let pe;e[57]!==P?(pe=s.jsx("div",{className:"shrink-0",children:P}),e[57]=P,e[58]=pe):pe=e[58];let Ie;e[59]!==z||e[60]!==xe||e[61]!==ie||e[62]!==pe?(Ie=s.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[xe,be,ie,z,pe]}),e[59]=z,e[60]=xe,e[61]=ie,e[62]=pe,e[63]=Ie):Ie=e[63];let re;return e[64]!==ae||e[65]!==Ie?(re=s.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[ae,Ie]}),e[64]=ae,e[65]=Ie,e[66]=re):re=e[66],re},Gk=t=>t==="/",br=t=>t.replace(/\\/g,"/"),wl=t=>{if(!t||Gk(t))return t;let e=t;for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e},Ua=t=>t.endsWith("/"),qk=t=>{const e=t.trim();return!e||Ua(e)?e:`${e}/`},jl=t=>t.lastIndexOf("/"),Cm=t=>{if(Ua(t))return t;const e=jl(t);return e<0?t:t.slice(0,e+1)},Jk=t=>{const e=jl(t);return t.slice(e+1)},Im=t=>{const e=wl(t.trim());if(!e||e==="~"||e==="~/"||e==="/")return null;const n=jl(e);return n<0?null:e.startsWith("~/")&&n<=1?"~/":n===0?"/":`${e.slice(0,n)}/`},Yk=t=>Ua(t)&&Im(t)!==null,Qk=(t,e)=>`${Cm(t)}${e}/`,ia=t=>{if(!t)return null;const e=wl(br(t.trim()));return e?e.toLowerCase():null},_d=(t,e)=>{const n=t.trim();return n==="~"?e:n.startsWith("~/")?`${e}${n.slice(1)}`:n},Xk=t=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?t.metaKey&&!t.ctrlKey:t.ctrlKey&&!t.metaKey,bo=t=>{if(!t)return;t.focus({preventScroll:!0});const e=t.value.length;t.setSelectionRange(e,e),t.scrollLeft=t.scrollWidth},Zk=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 br(e.home.trim())}}catch{}return Ps.getFilesystemHome().catch(()=>null)},jS=({open:t,onOpenChange:e})=>{const{t:n}=ot(),a=Cs(v=>v.homeDirectory),i=is(v=>v.projects),r=is(v=>v.addProject),o=Vs(v=>v.profiles),d=Vs(v=>v.globalIdentity),c=Vs(v=>v.defaultGitIdentityId),p=Vs(v=>v.loadProfiles),u=Vs(v=>v.loadGlobalIdentity),g=Vs(v=>v.loadDefaultGitIdentityId),{isDesktop:m,requestAccess:w,startAccessing:h}=zk(),{isMobile:f}=Hs(),x=l.useRef(null),k=l.useRef(null),y=l.useRef(new Map),[C,O]=l.useState(""),[j,N]=l.useState("~/"),[b,I]=l.useState([]),[B,T]=l.useState(!1),[D,S]=l.useState(!1),[F,R]=l.useState(0),[z,q]=l.useState(!1),[H,Z]=l.useState(!1),[W,A]=l.useState(0),[X,te]=l.useState(!1),[E,P]=l.useState(""),[_,L]=l.useState(null),[V,Y]=l.useState(!1),G=C||a,me=l.useMemo(()=>new Set(i.map(v=>ia(v.path)).filter(v=>!!v)),[i]);l.useEffect(()=>{if(!t)return;N("~/"),I([]),R(0),q(!1),Z(!1),te(!1),P(""),L(null),Y(!1),requestAnimationFrame(()=>bo(x.current));let v=!1;return(async()=>{const Ne=await Zk();v||(O(Ne||a||""),requestAnimationFrame(()=>bo(x.current)))})(),()=>{v=!0}},[a,t]),l.useEffect(()=>{t&&(p(),u(),g())},[g,p,u,t]);const ae=l.useMemo(()=>{const v=new Map;d&&v.set(d.id,d);for(const ue of o)v.set(ue.id,ue);return Array.from(v.values())},[o,d]);l.useEffect(()=>{if(!t||!X||_!==null)return;const v=typeof c=="string"?c.trim():"";if(v&&ae.some(Ne=>Ne.id===v)){L(v);return}const ue=ae.find(Ne=>Ne.authType==="ssh"||Ne.sshKey);ue&&L(ue.id)},[ae,c,X,t,_]);const xe=l.useMemo(()=>ae.find(v=>v.id===_)??null,[ae,_]),be=l.useMemo(()=>Cm(j),[j]),ie=l.useMemo(()=>Ua(j)?"":Jk(j),[j]),pe=l.useMemo(()=>G?_d(be,G):"",[be,G]);l.useEffect(()=>{if(!t||!pe){I([]);return}let v=!1;return T(!0),S(!1),Ps.listLocalDirectory(pe).then(ue=>{if(v)return;S(!1);const Ne=ue.filter(we=>we.isDirectory).map(we=>({name:we.name,path:br(we.path)})).sort((we,qe)=>we.name.localeCompare(qe.name));I(Ne)}).catch(()=>{v||(I([]),S(!0))}).finally(()=>{v||T(!1)}),()=>{v=!0}},[pe,t]);const Ie=l.useMemo(()=>{const v=ie.toLowerCase(),ue=V||ie.startsWith(".");return b.filter(Ne=>Ne.name.toLowerCase().startsWith(v)&&(ue||!Ne.name.startsWith(".")))},[ie,b,V]),re=l.useMemo(()=>{const v=[];Yk(j)&&v.push({type:"up",value:"browse:up",name:"..",path:Im(j)});for(const ue of Ie){const Ne=ia(ue.path);v.push({type:"directory",value:`browse:${ue.path}`,name:ue.name,path:ue.path,disabled:!!(Ne&&me.has(Ne))})}return v},[me,Ie,j]);l.useEffect(()=>{R(0)},[j,re.length]);const ce=l.useMemo(()=>G?wl(_d(j,G)):"",[G,j]),ge=ia(ce),oe=!!(ge&&me.has(ge)),de=l.useMemo(()=>ie?Ie.find(v=>v.name===ie)??null:null,[ie,Ie]),le=!!(ce&&!oe&&(Ua(j)&&D||!Ua(j)&&ie.trim().length>0&&de===null)),he=!z&&!H&&!oe&&!!ce,De=he&&E.trim().length>0,Le=re[F]??null,Ke=!!(Le&&(Le.type==="up"||Le.type==="directory"&&!Le.disabled)),Fe=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Me=n(oe?"directoryExplorerDialog.actions.alreadyAdded":X?z?"directoryExplorerDialog.actions.cloning":"directoryExplorerDialog.actions.cloneAndAdd":z?"directoryExplorerDialog.actions.adding":le?"directoryExplorerDialog.actions.createAndAdd":"directoryExplorerDialog.actions.addProject");l.useLayoutEffect(()=>{const v=k.current;if(!v)return;const ue=()=>A(Math.ceil(v.getBoundingClientRect().width));if(ue(),typeof ResizeObserver>"u")return;const Ne=new ResizeObserver(ue);return Ne.observe(v),()=>Ne.disconnect()},[Me]),l.useLayoutEffect(()=>{const v=x.current;v&&(v.scrollLeft=v.scrollWidth)},[W,j]),l.useLayoutEffect(()=>{t&&bo(x.current)},[t]),l.useLayoutEffect(()=>{const v=re[F];v&&y.current.get(v.value)?.scrollIntoView({block:"nearest"})},[F,re]);const Be=l.useCallback(()=>{e(!1)},[e]),Ge=l.useCallback((v,ue)=>{v.stopPropagation();const Ne=ia(ue);if(Ne&&me.has(Ne))return;r(ue)||Q.error(n("directoryExplorerDialog.toast.failedToAddProject"),{description:n("directoryExplorerDialog.toast.selectValidDirectoryPath")})},[r,me,n]),Ve=l.useCallback(async v=>{if(!v||z)return;const ue=ia(v);if(ue&&me.has(ue))return;let Ne=v;q(!0);try{const we=!X&&le&&ia(v)===ia(ce);if(X){const it=E.trim();if(!it){Q.error(n("directoryExplorerDialog.toast.cloneUrlRequired"));return}Ne=(await Ps.cloneRepository({remoteUrl:it,destinationPath:v,gitIdentityId:xe?.id??null})).path}else we&&await Ps.createDirectory(v);if(!r(Ne)){Q.error(n("directoryExplorerDialog.toast.failedToAddProject"),{description:n("directoryExplorerDialog.toast.selectValidDirectoryPath")});return}Be()}catch(we){Q.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:we instanceof Error?we.message:n("directoryExplorerDialog.toast.unknownError")})}finally{q(!1)}},[r,me,E,Be,X,z,xe?.id,le,ce,n]),Ue=l.useCallback(v=>{N(qk(v))},[]),He=l.useCallback(v=>{N(Qk(j,v.name))},[j]),_e=l.useCallback(v=>{if(v){if(v.type==="up"){v.path&&Ue(v.path);return}v.disabled||He(v)}},[Ue,He]),Oe=l.useCallback(async()=>{if(!(!m||H)){Z(!0);try{const v=await w(ce);if(!v.success||!v.path){v.error&&v.error!=="Directory selection cancelled"&&Q.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:v.error});return}const ue=await h(v.path);if(!ue.success){Q.error(n("directoryExplorerDialog.toast.failedToOpenDirectory"),{description:ue.error||n("directoryExplorerDialog.toast.desktopCouldNotGrantAccess")});return}await Ve(v.path)}catch(v){Q.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:v instanceof Error?v.message:n("directoryExplorerDialog.toast.unknownError")})}finally{Z(!1)}}},[Ve,m,H,w,h,n,ce]),se=l.useCallback(v=>{if(v.key==="ArrowDown"){v.preventDefault(),R(ue=>Math.min(re.length-1,ue+1));return}if(v.key==="ArrowUp"){v.preventDefault(),R(ue=>Math.max(0,ue-1));return}if(v.key==="Enter"){if(v.preventDefault(),Xk(v)){Ve(ce);return}Ke&&_e(Le);return}v.key==="Backspace"&&j===""&&(v.preventDefault(),Be())},[_e,Ve,Be,Ke,Le,j,re.length,ce]),ye=s.jsxs("button",{type:"button",onClick:()=>Y(v=>!v),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")]}),ke=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(nt,{value:E,onChange:v=>P(v.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(Sm,{activeProfile:xe,identities:ae,onSelect:v=>L(v.id),isApplying:z,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(nt,{ref:x,value:j,onChange:v=>N(br(v.target.value)),onKeyDown:se,placeholder:n("directoryExplorerDialog.pathInput.placeholder"),className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",style:!f&&W>0?{paddingRight:`${W+24}px`}:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),f?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?!De:!he,onMouseDown:v=>v.preventDefault(),onClick:()=>{Ve(ce)},title:Me,children:Me})]})]}),ze=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")}),B?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:n("directoryExplorerDialog.browse.loading")}):re.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:re.map((v,ue)=>{const Ne=ue===F;return s.jsxs("button",{ref:we=>{we?y.current.set(v.value,we):y.current.delete(v.value)},type:"button",disabled:v.type==="directory"&&v.disabled,onMouseEnter:()=>R(ue),onMouseDown:we=>we.preventDefault(),onClick:()=>_e(v),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",Ne&&"bg-interactive-selection text-interactive-selection-foreground",!Ne&&"hover:bg-interactive-hover/50",v.type==="directory"&&v.disabled&&"cursor-not-allowed opacity-45 hover:bg-transparent"),children:[v.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:v.name})}),v.type==="directory"&&v.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")}):v.type==="directory"?s.jsx("button",{type:"button",onMouseDown:we=>we.stopPropagation(),onClick:we=>Ge(we,v.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]},v.value)})})]})}),$=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ke,ze]}),Ee=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")]})]}),J=()=>s.jsxs(s.Fragment,{children:[f?null:Ee,s.jsxs("div",{className:fe("flex w-full flex-row justify-end gap-2 sm:w-auto",f&&"justify-stretch"),children:[m?s.jsx(ee,{variant:"ghost",size:"xs",onClick:Oe,disabled:z||H||X,children:n(H?"directoryExplorerDialog.actions.openingFinder":"directoryExplorerDialog.actions.openInFinder")}):null,s.jsx(ee,{variant:"ghost",size:"xs",onClick:()=>te(v=>!v),disabled:z||H,className:fe(f&&"flex-1"),children:n(X?"directoryExplorerDialog.actions.addLocalProject":"directoryExplorerDialog.actions.cloneRepository")}),f?s.jsx(ee,{size:"xs",onClick:()=>{Ve(ce)},disabled:X?!De:!he,className:"flex-1",children:Me}):null]})]});return f?s.jsx(gi,{open:t,onClose:Be,title:n("directoryExplorerDialog.title"),className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:J()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:ye}),$]})}):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")})]}),ye]})}),s.jsx("div",{className:"min-h-0 flex-1 px-2 pb-0",children:$}),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:J()})]})})};function Ud(t){const{localBranches:e,remoteBranches:n,query:a}=t,i=a.trim();if(!i)return{matching:[],otherLocal:e,otherRemote:n};const r=Ol(e,i,u=>u),o=Ol(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,g)=>{const m=u.label.localeCompare(g.label,void 0,{sensitivity:"accent"});return m!==0?m:u.source!==g.source?u.source.localeCompare(g.source):u.value.localeCompare(g.value)}),{matching:d,otherLocal:c,otherRemote:p}}const yo="oc:lastWorktreeSourceBranch",e0=({mode:t,sourceBranch:e,linkedPr:n,selectedBranch:a})=>t==="existing-branch"?a||null:n?null:e||null,t0=({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 s0({open:t,onOpenChange:e,onSelect:n}){const{t:a}=ot(),i=je(re=>re.isMobile),{github:r}=Ha(),o=Cn(re=>re.status),d=Cn(re=>re.hasChecked),c=je(re=>re.setSettingsDialogOpen),p=je(re=>re.setSettingsPage),u=is(re=>re.getActiveProject()),g=u?.path??null,m=ve.useMemo(()=>g&&u?{id:u.id,path:g}:null,[u,g]),[w,h]=ve.useState("issues"),[f,x]=ve.useState(""),[k,y]=ve.useState([]),[C,O]=ve.useState([]),[j,N]=ve.useState(!1),[b,I]=ve.useState(!1),[B,T]=ve.useState(null),[D,S]=ve.useState(null),[F,R]=ve.useState(null),[z,q]=ve.useState(!1),[H,Z]=ve.useState(new Map),[W,A]=ve.useState(1),[X,te]=ve.useState(!1),E=lg(f,350),P=ve.useCallback(async re=>{if(!(!g||!r)&&!(d&&o?.connected===!1)){N(!0),T(null),A(1),te(!1);try{if(w==="issues"&&r.issuesList){const ce=await r.issuesList(g,{page:1,query:re});ce.connected===!1?(T(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(g,{page:1,query:re});ce.connected===!1?(T(a("session.githubIntegration.error.notConnected")),O([])):(O(ce.prs??[]),A(ce.page??1),te(!!ce.hasMore))}}catch(ce){T(ce instanceof Error?ce.message:a("session.githubIntegration.error.loadDataFailed"))}finally{N(!1)}}},[g,r,d,o,w,a]);ve.useEffect(()=>{if(!t||!g||d&&o?.connected===!1||!r)return;if(!E.trim()){P();return}const re=new AbortController;N(!0),T(null),A(1),te(!1);const ce=w==="issues"&&r.issuesList?r.issuesList(g,{page:1,query:E.trim()}):w==="prs"&&r.prsList?r.prsList(g,{page:1,query:E.trim()}):null;if(!ce){N(!1);return}return ce.then(ge=>{re.signal.aborted||("issues"in ge?ge.connected===!1?(T(a("session.githubIntegration.error.notConnected")),y([])):(y(ge.issues??[]),A(ge.page??1),te(!!ge.hasMore)):"prs"in ge&&(ge.connected===!1?(T(a("session.githubIntegration.error.notConnected")),O([])):(O(ge.prs??[]),A(ge.page??1),te(!!ge.hasMore))))}).catch(ge=>{re.signal.aborted||T(ge instanceof Error?ge.message:a("session.githubIntegration.error.loadDataFailed"))}).finally(()=>{re.signal.aborted||N(!1)}),()=>re.abort()},[t,g,r,d,o,w,E,P,a]);const _=ve.useCallback(async()=>{if(!(!g||!r)&&!(j||b)&&X){I(!0);try{const re=W+1;if(w==="issues"&&r.issuesList){const ce=E.trim()?await r.issuesList(g,{page:re,query:E.trim()}):await r.issuesList(g,{page:re});ce.connected!==!1&&(y(ge=>[...ge,...ce.issues??[]]),A(ce.page??re),te(!!ce.hasMore))}else if(w==="prs"&&r.prsList){const ce=E.trim()?await r.prsList(g,{page:re,query:E.trim()}):await r.prsList(g,{page:re});ce.connected!==!1&&(O(ge=>[...ge,...ce.prs??[]]),A(ce.page??re),te(!!ce.hasMore))}}catch{}finally{I(!1)}}},[g,r,w,W,X,j,b,E]);ve.useEffect(()=>{if(!t){h("issues"),x(""),y([]),O([]),S(null),R(null),q(!1),T(null),Z(new Map),A(1),te(!1);return}P()},[t,P]);const L=ve.useCallback(async re=>{if(!(!m||!re)&&!H.has(re))try{const ge=(await fu(m,{mode:"new",branchName:re,worktreeName:re})).errors.find(oe=>oe.code==="branch_in_use");Z(oe=>new Map(oe).set(re,{isValid:!ge,error:ge?a(ge.code==="branch_exists"?"session.githubIntegration.validation.branchAlreadyExists":"session.githubIntegration.validation.branchAlreadyCheckedOut"):null}))}catch{Z(ce=>new Map(ce).set(re,{isValid:!1,error:a("session.githubIntegration.validation.failed")}))}},[m,H,a]);ve.useEffect(()=>{!t||w!=="prs"||C.forEach(re=>{re.head&&L(re.head)})},[t,w,C,L]);const V=d&&o?.connected===!0,Y=()=>{p("github"),c(!0)},G=re=>{S(re),R(null)},me=re=>{R(re),S(null)},ae=()=>{D?n({type:"issue",item:D}):F&&n({type:"pr",item:F,includeDiff:z}),e(!1)},xe=()=>{S(null),R(null),q(!1)},be=D||F&&H.get(F.head??"")?.isValid!==!1,ie=re=>re.head?H.get(re.head)?.isValid===!1:!0,pe=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(nt,{value:f,onChange:re=>x(re.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"})}),B&&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:B})]})}),!j&&!B&&w==="issues"&&s.jsxs("div",{className:"space-y-0.5 min-h-full",children:[k.length>0?k.map(re=>s.jsx("button",{onClick:()=>G(re),className:fe("w-full text-left px-2 py-1.5 rounded transition-colors",D?.number===re.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:["#",re.number]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"typography-small line-clamp-2",children:re.title}),re.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:[re.sourceRepo.owner,"/",re.sourceRepo.repo]}):null]})]})},`${re.sourceRepo?.owner??""}-${re.sourceRepo?.repo??""}-${re.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&&!b&&s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{_()},className:"h-7 text-xs",children:a("session.githubIntegration.actions.loadMore")})}),b&&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&&!B&&w==="prs"&&s.jsxs("div",{className:"space-y-0.5 min-h-full",children:[C.length>0?C.map(re=>{const ce=ie(re),ge=re.head?H.get(re.head):void 0;return s.jsx("button",{onClick:()=>!ce&&me(re),disabled:ce,className:fe("w-full text-left px-2 py-1.5 rounded transition-colors",F?.number===re.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:["#",re.number]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"typography-small line-clamp-1",children:re.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[re.head," → ",re.base]}),re.sourceRepo?.source==="upstream"?s.jsxs("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info",children:[re.sourceRepo.owner,"/",re.sourceRepo.repo]}):null,ce&&ge?.error&&s.jsx("span",{className:"typography-micro text-destructive",children:ge.error})]})]})]})},`${re.sourceRepo?.owner??""}-${re.sourceRepo?.repo??""}-${re.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&&!b&&s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{_()},className:"h-7 text-xs",children:a("session.githubIntegration.actions.loadMore")})}),b&&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:Y,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&&(D||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:D?a("session.githubIntegration.selected.issueNumber",{number:D.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(rn,{checked:z,onChange:re=>q(re),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:ae,disabled:!be,className:fe(i&&"flex-1"),children:a("session.githubIntegration.actions.select")})]})]});return s.jsx(s.Fragment,{children:i?s.jsx(gi,{open:t,title:a("session.githubIntegration.title"),onClose:()=>e(!1),footer:V?Ie:void 0,renderHeader:re=>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")}),re]}),s.jsx("div",{className:"w-full",children:s.jsx(pa,{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=>{h(ce),x("")},variant:"active-pill",layoutMode:"fit"})}),(D||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:D?a("session.githubIntegration.selected.issueNumber",{number:D.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:pe}):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(pa,{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:re=>{h(re),x("")},variant:"active-pill",layoutMode:"fit"})})]})}),pe,s.jsx(rs,{className:"mt-1",children:Ie})]})})})}const pi=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),n0=t=>String(t).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"pr-head",$d=(t,e,n)=>{const a=pi(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-${n0(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}`}},a0=t=>{const e={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
|
|
35
|
+
${JSON.stringify(e,null,2)}`},i0=t=>`GitHub pull request context (JSON)
|
|
36
|
+
${JSON.stringify(t,null,2)}`;function kS({open:t,onOpenChange:e,onWorktreeCreated:n}){const{t:a}=ot(),{github:i,git:r}=Ha(),o=je(J=>J.isMobile),d=Cn(J=>J.status),c=Cn(J=>J.hasChecked),p=is(J=>J.getActiveProject()),u=p?.path??null,g=ve.useMemo(()=>u&&p?{id:p.id,path:u}:null,[p,u]),[m,w]=ve.useState("new-branch"),[h,f]=ve.useState({branchName:"",worktreeName:"",isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1}),[x,k]=ve.useState({selectedBranch:"",worktreeName:""}),y=cg(u),C=dg(u),O=Sr(J=>J.fetchBranches),j=ve.useMemo(()=>y?.all?y.all.filter(J=>!J.startsWith("remotes/")).sort():[],[y]),N=ve.useMemo(()=>y?.all?y.all.filter(J=>J.startsWith("remotes/")).map(J=>J.replace(/^remotes\//,"")).sort():[],[y]),b=es(J=>J.availableWorktreesByProject),I=ve.useMemo(()=>{if(!u)return new Set;const J=b.get(u)??[];return new Set(J.map(v=>v.name))},[b,u]),B=ve.useCallback((J=10)=>{for(let v=0;v<J;v++){const ue=Gr();if(!I.has(ue))return ue}return`${Gr()}-${Date.now().toString(36).slice(-4)}`},[I]),[T,D]=ve.useState(!1),[S,F]=ve.useState(!1),[R,z]=ve.useState(!1),[q,H]=ve.useState(!1),[Z,W]=ve.useState(!1),[A,X]=ve.useState(""),[te,E]=ve.useState(""),P=ve.useRef(null),_=ve.useRef(null),L=ve.useRef(null),V=ve.useRef(null),Y=ve.useCallback(J=>{J.stopPropagation()},[]),G=ve.useCallback(J=>{let v=J;for(;v&&v!==document.body;){const{overflowY:ue}=window.getComputedStyle(v);if((ue==="auto"||ue==="scroll")&&v.scrollHeight>v.clientHeight)return v;v=v.parentElement}return null},[]),me=ve.useCallback(J=>{J&&(J.scrollTop=0)},[]),ae=ve.useCallback(J=>{const v=J.current?.querySelector('[data-slot="command-list"]')??null;me(v)},[me]),xe=ve.useCallback(J=>{const v=G(J.current);me(v)},[G,me]),be=ve.useMemo(()=>Ud({localBranches:j,remoteBranches:N,query:A}),[j,N,A]),ie=ve.useMemo(()=>Ud({localBranches:j,remoteBranches:N,query:te}),[j,N,te]),pe=A.trim().length>0,Ie=te.trim().length>0,re=be.matching.length>0,ce=ie.matching.length>0,ge=!!(u&&r),oe=ve.useCallback(()=>{!u||!r||O(u,r)},[u,r,O]);ve.useEffect(()=>{!t||!u||!r||y?.all||O(u,r)},[t,u,r,y?.all,O]),ve.useEffect(()=>{!S&&!q&&X("")},[S,q]),ve.useEffect(()=>{!R&&!Z&&E("")},[R,Z]),ve.useEffect(()=>{S&&ae(P),q&&xe(L)},[S,q,A,ae,xe]),ve.useEffect(()=>{R&&ae(_),Z&&xe(V)},[R,Z,te,ae,xe]);const[de,le]=ve.useState({isValidating:!1,branchError:null,worktreeError:null,touched:!1}),[he,De]=ve.useState(!1),[Le,Ke]=ve.useState(null),Fe=ve.useCallback(()=>{const J=pt.getState(),v=J.getVisibleAgents();if(J.settingsDefaultAgent){const ue=v.find(Ne=>Ne.name===J.settingsDefaultAgent);if(ue)return ue.name}return v.find(ue=>ue.name==="build")?.name||v[0]?.name},[]),Me=ve.useCallback(()=>{const J=pt.getState(),v=J.settingsDefaultModel;if(!v)return null;const ue=Wn(v);if(!ue)return null;const{providerId:Ne,modelId:we}=ue;return J.getModelMetadata(Ne,we)?{providerID:Ne,modelID:we}:null},[]),Be=ve.useCallback((J,v)=>{const ue=pt.getState(),Ne=ue.settingsDefaultVariant,we=ue.currentProviderId===J&&ue.currentModelId===v?ue.currentVariant:void 0,st=ue.providers.find(rt=>rt.id===J)?.models.find(rt=>rt.id===v)?.variants;if(!st)return Ne||we||void 0;if(Ne&&Object.prototype.hasOwnProperty.call(st,Ne))return Ne;if(we&&Object.prototype.hasOwnProperty.call(st,we))return we},[]),Ge=ve.useCallback(async J=>{if(!u||!i)return;const v=pt.getState(),ue=cl.getState().lastUsedProvider,Ne=Me(),we=Ne?.providerID||v.currentProviderId||ue?.providerID,qe=Ne?.modelID||v.currentModelId||ue?.modelID,it=Fe()||v.currentAgentName||void 0;if(!we||!qe){Q.error(a("session.newWorktree.error.noModelSelected"));return}const st=Be(we,qe);if(J.issue){if(!i.issueGet||!i.issueComments)return;const rt=await i.issueGet(u,J.issue.number,{sourceRepo:J.issue.sourceRepo??null});if(rt.connected===!1||!rt.repo||!rt.issue)throw new Error("Failed to load issue context");const lt=await i.issueComments(u,J.issue.number,{sourceRepo:J.issue.sourceRepo??null});if(lt.connected===!1)throw new Error("Failed to load issue comments");const xt=await Un("github.issue.review.visible",{issue_number:String(J.issue.number)}),bt=await Un("github.issue.review.instructions"),Nt=a0({repo:rt.repo,issue:rt.issue,comments:lt.comments??[]});await es.getState().sendMessage(xt,we,qe,it,void 0,void 0,[{text:bt,synthetic:!0},{text:Nt,synthetic:!0}],st,void 0,{sessionId:J.sessionId}),Q.success(a("session.newWorktree.toast.sessionFromIssue"));return}if(J.pr){if(!i.prContext)return;const rt=await i.prContext(u,J.pr.number,{sourceRepo:J.pr.sourceRepo??null,includeDiff:J.includeDiff,includeCheckDetails:!1});if(rt.connected===!1||!rt.repo||!rt.pr)throw new Error("Failed to load PR context");const lt=await Un("github.pr.review.visible",{pr_number:String(J.pr.number)}),xt=await Un("github.pr.review.instructions"),bt=i0(rt);await es.getState().sendMessage(lt,we,qe,it,void 0,void 0,[{text:xt,synthetic:!0},{text:bt,synthetic:!0}],st,void 0,{sessionId:J.sessionId}),Q.success(a("session.newWorktree.toast.sessionFromPr"))}},[i,u,Fe,Me,Be,a]),Ve=m==="new-branch"?h:x;ve.useEffect(()=>{if(!t||!y?.all||!u||h.sourceBranch)return;const J=h.sourceBranch;let v=!1;return(async()=>{try{const Ne=await ug(u).catch(()=>null);if(v)return;const we=localStorage.getItem(yo),{sourceBranch:qe,shouldClearSavedSourceBranch:it}=t0({branches:y.all,savedSourceBranch:we,rootBranch:Ne});if(it&&localStorage.removeItem(yo),v||J)return;qe&&f(st=>({...st,sourceBranch:qe}))}catch{}})(),()=>{v=!0}},[t,y?.all,u,h.sourceBranch]),ve.useLayoutEffect(()=>{if(!t)return;w("new-branch"),k({selectedBranch:"",worktreeName:""}),F(!1),z(!1),H(!1),W(!1),X(""),E(""),le({isValidating:!1,branchError:null,worktreeError:null,touched:!1});const J=B();f({branchName:J,worktreeName:J,isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1})},[t,B]),ve.useEffect(()=>{if(m!=="new-branch"||!h.isSyncingWorktreeName)return;const J=pi(h.branchName),v=As(J);f(ue=>({...ue,worktreeName:v}))},[m,h.branchName,h.isSyncingWorktreeName]);const Ue=ve.useCallback(async()=>{if(!g||!de.touched||he)return;Le&&Le.abort();const J=new AbortController;Ke(J),le(v=>({...v,isValidating:!0}));try{const v=m==="new-branch"?h.branchName:x.selectedBranch,ue=Ve.worktreeName,Ne=pi(v),we=As(ue);let qe=null,it=null;if(Ne||(qe=a("session.newWorktree.error.branchNameRequired")),we||(it=a("session.newWorktree.error.worktreeDirectoryRequired")),Ne&&we){const st=m==="new-branch"?h.linkedPr:null,rt=st?$d(st,j,N):null,lt=await fu(g,{mode:m==="existing-branch"||rt?"existing":"new",branchName:Ne,worktreeName:we,existingBranch:rt?.existingBranch??(m==="existing-branch"?Ne:void 0),...rt?.ensureRemoteName?{ensureRemoteName:rt.ensureRemoteName}:{},...rt?.ensureRemoteUrl?{ensureRemoteUrl:rt.ensureRemoteUrl}:{}});if(J.signal.aborted)return;lt.ok||lt.errors.forEach(xt=>{if(xt.code==="worktree_exists"){it=it??xt.message;return}xt.code.startsWith("branch_")&&(qe=qe??xt.message)})}J.signal.aborted||le(st=>({...st,isValidating:!1,branchError:qe,worktreeError:it}))}catch{J.signal.aborted||le(v=>({...v,isValidating:!1}))}},[g,m,h.branchName,h.linkedPr,x.selectedBranch,Ve.worktreeName,j,N,de.touched,Le,he,a]),He=m==="new-branch"?h.branchName:x.selectedBranch;ve.useEffect(()=>{if(!t||!g||!de.touched||he)return;const J=setTimeout(()=>{Ue()},300);return()=>clearTimeout(J)},[Ve.worktreeName,He,t,g,Ue,de.touched,he]);const _e=async()=>{if(!g||!u){Q.error(a("session.newWorktree.error.noActiveProject"));return}le(we=>({...we,touched:!0}));const J=m==="new-branch"?h.branchName:x.selectedBranch,v=Ve.worktreeName,ue=pi(J),Ne=As(v);if(!ue){Q.error(a("session.newWorktree.error.branchNameRequired"));return}if(!Ne){Q.error(a("session.newWorktree.error.worktreeDirectoryRequired"));return}Le&&(Le.abort(),Ke(null)),le(we=>({...we,isValidating:!1,branchError:null,worktreeError:null})),De(!0);try{const we=m==="new-branch"?h.linkedPr:null,qe=m==="new-branch"?h.linkedIssue:null,it=m==="new-branch"?h.linkedPr:null,st=m==="new-branch"?h.includePrDiff:!1,rt=!!(qe||it),lt=await uu(g),xt=h.sourceBranch;let bt="";const Nt=(()=>{if(we){const gt=$d(we,j,N);return bt=gt.sourceLabel,{preferredName:ue||Ne,mode:"existing",branchName:ue,worktreeName:Ne,existingBranch:gt.existingBranch,setupCommands:lt,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:ue||Ne,mode:m==="existing-branch"?"existing":"new",branchName:m==="existing-branch"?void 0:ue,worktreeName:Ne,existingBranch:m==="existing-branch"?ue:void 0,setupCommands:lt,returnAfterDirectoryCreated:!0,...xt&&m==="new-branch"?{startRef:xt}:{}}})(),Ce=await mg(u,Nt),Qe=await pg(g,Ce);let tt=null;if(rt){await mu(g)&&await gg(Qe.path);const gt=qe?`#${qe.number} ${qe.title}`.trim():it?`#${it.number} ${it.title}`.trim():a("session.newWorktree.newSessionTitle"),wt=await fg(gt,Qe.path,null);if(!wt?.id)throw new Error("Failed to create session");tt=wt.id,n?.(Qe.path,{sessionId:tt}),e(!1),De(!1),hg(wt.id,gt).catch(()=>{});try{es.getState().initializeNewOpenChamberSession(wt.id,pt.getState().agents)}catch{}}else e(!1),De(!1);const at=e0({mode:m,sourceBranch:h.sourceBranch,linkedPr:!!h.linkedPr,selectedBranch:x.selectedBranch});at&&localStorage.setItem(yo,at),Q.success(a("session.newWorktree.toast.worktreeCreated"),{description:a("session.newWorktree.toast.worktreeCreatedDescription",{target:`${Qe.branch||Qe.name}${bt?` ${a("session.newWorktree.fromSource",{source:bt})}`:""}`})}),tt?Ge({sessionId:tt,directory:Qe.path,issue:qe,pr:it,includeDiff:st}).catch(gt=>{const wt=gt instanceof Error?gt.message:a("session.newWorktree.error.sendGitHubContextFailed");Q.error(a("session.newWorktree.error.sendGitHubContextFailed"),{description:wt})}):n?.(Qe.path)}catch(we){const qe=we instanceof Error?we.message:a("session.newWorktree.error.createWorktreeFailed");Q.error(a("session.newWorktree.error.createWorktreeFailed"),{description:qe})}finally{De(!1)}},Oe=J=>{w(J),le(v=>({...v,touched:!1,branchError:null,worktreeError:null}))},se=J=>{if(!J){f(v=>({...v,linkedIssue:null,linkedPr:null,includePrDiff:!1,branchName:""}));return}if(J.type==="issue"){const v=J.item,ue=`issue-${v.number}-${Gr()}`;f(Ne=>({...Ne,linkedIssue:v,linkedPr:null,includePrDiff:!1,branchName:ue,worktreeName:As(ue),isSyncingWorktreeName:!0}))}else if(J.type==="pr"){const v=J.item;f(ue=>({...ue,linkedPr:v,linkedIssue:null,includePrDiff:J.includeDiff??!1,branchName:v.head,worktreeName:As(v.head),isSyncingWorktreeName:!0}))}},ye=c&&d?.connected===!0,ze=(m==="existing-branch"?!!x.selectedBranch&&!!x.worktreeName&&!de.branchError&&!de.worktreeError:!!pi(h.branchName)&&!!h.worktreeName&&!de.branchError&&!de.worktreeError)&&!he,$=()=>{f(J=>({...J,linkedIssue:null,linkedPr:null,branchName:"",includePrDiff:!1,isSyncingWorktreeName:!0}))},Ee=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:de.touched&&(de.branchError||de.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:de.branchError||de.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:_e,disabled:!ze||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(gi,{open:t,title:a("session.newWorktree.title"),onClose:()=>e(!1),footer:Ee,children:[s.jsx("div",{className:"w-full mb-4",children:s.jsx(pa,{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:J=>Oe(J),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:oe,disabled:!ge||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(gi,{open:q,title:a("session.newWorktree.selectBranch"),onClose:()=>H(!1),children:s.jsxs("div",{className:"space-y-4",ref:L,children:[s.jsx(nt,{value:A,onChange:J=>X(J.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:[pe&&re&&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:be.matching.map(J=>s.jsx("button",{onClick:()=>{k(v=>({...v,selectedBranch:J.value,worktreeName:As(J.label)})),le(v=>({...v,touched:!0})),H(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===J.value?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:J.label})},`${J.source}-${J.value}`))})]}),pe&&!re&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),be.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(pe?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches")}),s.jsx("div",{className:"space-y-1",children:be.otherLocal.map(J=>s.jsx("button",{onClick:()=>{k(v=>({...v,selectedBranch:J,worktreeName:As(J)})),le(v=>({...v,touched:!0})),H(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===J?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:J})},J))})]}),be.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(pe?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches")}),s.jsx("div",{className:"space-y-1",children:be.otherRemote.map(J=>s.jsx("button",{onClick:()=>{k(v=>({...v,selectedBranch:`remotes/${J}`,worktreeName:As(J)})),le(v=>({...v,touched:!0})),H(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===`remotes/${J}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:J})},`remotes/${J}`))})]})]})]})})]}):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"&&ye&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>D(!0),className:"gap-1.5 h-7",children:[s.jsx(K,{name:"github",className:"size-4 text-status-success"}),h.linkedIssue||h.linkedPr?a("session.newWorktree.actions.change"):a("session.newWorktree.actions.startFromGitHubIssuePr")]})]}),s.jsx(nt,{value:h.branchName,onChange:J=>{f(v=>({...v,branchName:J.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>le(J=>({...J,touched:!0})),placeholder:a("session.newWorktree.branchNamePlaceholder"),disabled:!!h.linkedPr,className:fe("h-8",de.touched&&de.branchError&&"border-destructive",h.linkedPr&&"bg-muted text-muted-foreground")}),h.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:h.linkedPr.head})})]}),h.linkedIssue&&!h.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:h.linkedIssue.number,title:h.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 J=As(m==="new-branch"?h.branchName:"");f(v=>({...v,worktreeName:J,isSyncingWorktreeName:!0}))},disabled:!h.branchName||h.worktreeName===As(h.branchName),className:fe("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",h.worktreeName===As(h.branchName)||!h.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(nt,{value:Ve.worktreeName,onChange:J=>{m==="new-branch"?f(v=>({...v,worktreeName:J.target.value,isSyncingWorktreeName:!1})):k(v=>({...v,worktreeName:J.target.value}))},onBlur:()=>le(J=>({...J,touched:!0})),placeholder:a("session.newWorktree.worktreeDirectoryPlaceholder"),className:fe("h-8",de.touched&&de.worktreeError&&"border-destructive")})]}),m==="new-branch"&&!h.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:()=>W(!0),className:"w-full justify-between h-9",children:[s.jsx("span",{className:h.sourceBranch?"text-foreground":"text-muted-foreground",children:h.sourceBranch||a("session.newWorktree.selectSourceBranchPlaceholder")}),s.jsx(K,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"})]}),h.sourceBranch&&s.jsx("div",{className:"typography-micro text-muted-foreground",children:a("session.newWorktree.newBranchFromSource",{source:h.sourceBranch})}),s.jsx(gi,{open:Z,title:a("session.newWorktree.selectSourceBranch"),onClose:()=>W(!1),children:s.jsxs("div",{className:"space-y-4",ref:V,children:[s.jsx(nt,{value:te,onChange:J=>E(J.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:ie.matching.map(J=>s.jsx("button",{onClick:()=>{f(v=>({...v,sourceBranch:J.value})),W(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",h.sourceBranch===J.value?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:J.label})},`${J.source}-${J.value}`))})]}),Ie&&!ce&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),ie.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:ie.otherLocal.map(J=>s.jsx("button",{onClick:()=>{f(v=>({...v,sourceBranch:J})),W(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",h.sourceBranch===J?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:J})},J))})]}),ie.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:ie.otherRemote.map(J=>s.jsx("button",{onClick:()=>{f(v=>({...v,sourceBranch:`remotes/${J}`})),W(!1)},className:fe("w-full text-left px-3 py-2.5 rounded-md transition-colors",h.sourceBranch===`remotes/${J}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:J})},`remotes/${J}`))})]})]})]})})]}),(h.linkedIssue||h.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"}),h.linkedIssue&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.issueNumber",{number:h.linkedIssue.number})}),h.linkedPr&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.prNumber",{number:h.linkedPr.number})}),s.jsx("span",{className:"typography-micro text-foreground truncate flex-1",children:h.linkedIssue?.title||h.linkedPr?.title}),s.jsx("a",{href:h.linkedIssue?.url||h.linkedPr?.url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",onClick:J=>J.stopPropagation(),children:s.jsx(K,{name:"external-link",className:"h-3 w-3"})}),s.jsx("button",{onClick:$,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"})})]}),h.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:[h.linkedPr.head," → ",h.linkedPr.base]}),h.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(pa,{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:J=>Oe(J),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(Do({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:P,children:s.jsxs(Fo,{shouldFilter:!1,children:[s.jsx(Oo,{placeholder:a("session.newWorktree.searchBranches"),value:A,onValueChange:X,onKeyDown:Y}),s.jsx(zo,{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(Ko,{children:a("session.newWorktree.noBranchesFound")}):s.jsxs(s.Fragment,{children:[pe&&re&&s.jsx(Nn,{heading:a("session.newWorktree.matchingBranches"),children:be.matching.map(J=>s.jsx(tn,{value:J.value,onSelect:()=>{k(v=>({...v,selectedBranch:J.value,worktreeName:As(J.label)})),le(v=>({...v,touched:!0})),F(!1)},children:s.jsx("span",{className:"typography-small break-all",children:J.label})},`${J.source}-${J.value}`))}),pe&&!re&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),be.otherLocal.length>0&&s.jsxs(s.Fragment,{children:[pe&&s.jsx(Ka,{}),s.jsx(Nn,{heading:a(pe?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches"),children:be.otherLocal.map(J=>s.jsx(tn,{value:J,onSelect:()=>{k(v=>({...v,selectedBranch:J,worktreeName:As(J)})),le(v=>({...v,touched:!0})),F(!1)},children:s.jsx("span",{className:"typography-small break-all",children:J})},`local-${J}`))})]}),be.otherRemote.length>0&&s.jsxs(s.Fragment,{children:[(be.otherLocal.length>0||pe)&&s.jsx(Ka,{}),s.jsx(Nn,{heading:a(pe?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches"),children:be.otherRemote.map(J=>s.jsx(tn,{value:`remotes/${J}`,onSelect:()=>{k(v=>({...v,selectedBranch:`remotes/${J}`,worktreeName:As(J)})),le(v=>({...v,touched:!0})),F(!1)},children:s.jsx("span",{className:"typography-small break-all",children:J})},`remote-${J}`))})]})]})})]})})]}),s.jsx(ee,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0 shrink-0",onClick:oe,disabled:!ge||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"&&ye&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:()=>D(!0),className:"gap-1.5 h-7",children:[s.jsx(K,{name:"github",className:"size-4 text-status-success"}),h.linkedIssue||h.linkedPr?a("session.newWorktree.actions.change"):a("session.newWorktree.actions.startFromGitHubIssuePr")]})]}),s.jsx(nt,{value:h.branchName,onChange:J=>{f(v=>({...v,branchName:J.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>le(J=>({...J,touched:!0})),placeholder:a("session.newWorktree.branchNamePlaceholder"),disabled:!!h.linkedPr,className:fe("h-8",de.touched&&de.branchError&&"border-destructive",h.linkedPr&&"bg-muted text-muted-foreground")}),h.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:h.linkedPr.head})})]}),h.linkedIssue&&!h.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:h.linkedIssue.number,title:h.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 J=As(m==="new-branch"?h.branchName:"");f(v=>({...v,worktreeName:J,isSyncingWorktreeName:!0}))},disabled:!h.branchName||h.worktreeName===As(h.branchName),className:fe("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",h.worktreeName===As(h.branchName)||!h.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(nt,{value:Ve.worktreeName,onChange:J=>{m==="new-branch"?f(v=>({...v,worktreeName:J.target.value,isSyncingWorktreeName:!1})):k(v=>({...v,worktreeName:J.target.value}))},onBlur:()=>le(J=>({...J,touched:!0})),placeholder:a("session.newWorktree.worktreeDirectoryPlaceholder"),className:fe("h-8",de.touched&&de.worktreeError&&"border-destructive")})]}),m==="new-branch"&&!h.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:R,onOpenChange:z,children:[s.jsx(gs,{asChild:!0,children:s.jsxs("button",{type:"button",className:fe(Do({size:"default"}),"min-w-[220px] max-w-full"),children:[s.jsx("span",{className:fe("truncate",h.sourceBranch?"text-foreground":"text-muted-foreground"),children:h.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:_,children:s.jsxs(Fo,{shouldFilter:!1,children:[s.jsx(Oo,{placeholder:a("session.newWorktree.searchBranches"),value:te,onValueChange:E,onKeyDown:Y}),s.jsx(zo,{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(Ko,{children:a("session.newWorktree.noBranchesFound")}):s.jsxs(s.Fragment,{children:[Ie&&ce&&s.jsx(Nn,{heading:a("session.newWorktree.matchingBranches"),children:ie.matching.map(J=>s.jsx(tn,{value:J.value,onSelect:()=>{f(v=>({...v,sourceBranch:J.value})),z(!1)},children:s.jsx("span",{className:"typography-small break-all",children:J.label})},`${J.source}-${J.value}`))}),Ie&&!ce&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),ie.otherLocal.length>0&&s.jsxs(s.Fragment,{children:[Ie&&s.jsx(Ka,{}),s.jsx(Nn,{heading:a(Ie?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches"),children:ie.otherLocal.map(J=>s.jsx(tn,{value:J,onSelect:()=>{f(v=>({...v,sourceBranch:J})),z(!1)},children:s.jsx("span",{className:"typography-small break-all",children:J})},`local-${J}`))})]}),ie.otherRemote.length>0&&s.jsxs(s.Fragment,{children:[(ie.otherLocal.length>0||Ie)&&s.jsx(Ka,{}),s.jsx(Nn,{heading:a(Ie?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches"),children:ie.otherRemote.map(J=>s.jsx(tn,{value:`remotes/${J}`,onSelect:()=>{f(v=>({...v,sourceBranch:`remotes/${J}`})),z(!1)},children:s.jsx("span",{className:"typography-small break-all",children:J})},`remote-${J}`))})]})]})})]})})]}),h.sourceBranch&&s.jsx("div",{className:"typography-micro text-muted-foreground",children:a("session.newWorktree.newBranchFromSource",{source:h.sourceBranch})})]}),(h.linkedIssue||h.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"}),h.linkedIssue&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.issueNumber",{number:h.linkedIssue.number})}),h.linkedPr&&s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:a("session.newWorktree.prNumber",{number:h.linkedPr.number})}),s.jsx("span",{className:"typography-micro text-foreground truncate flex-1",children:h.linkedIssue?.title||h.linkedPr?.title}),s.jsx("a",{href:h.linkedIssue?.url||h.linkedPr?.url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",onClick:J=>J.stopPropagation(),children:s.jsx(K,{name:"external-link",className:"h-3 w-3"})}),s.jsx("button",{onClick:$,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"})})]}),h.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:[h.linkedPr.head," → ",h.linkedPr.base]}),h.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:de.touched&&(de.branchError||de.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:de.branchError||de.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:_e,disabled:!ze||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(s0,{open:T,onOpenChange:D,onSelect:se})]})}const r0=(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}},o0=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},NS=({active:t,className:e,headerAction:n,listClassName:a,hideHeader:i=!1,mobileListDensity:r=!1})=>{const{t:o}=ot(),c=Cs(j=>j.currentDirectory)??null,p=ws(j=>j.getStatusForDirectory(c)),u=ws(j=>j.refresh),g=ws(j=>j.connect),m=ws(j=>j.disconnect),w=$a(j=>j.mcpServers),h=$a(j=>j.loadMcpConfigs),[f,x]=l.useState(!1),[k,y]=l.useState(null);l.useEffect(()=>{u({directory:c,silent:!0})},[u,c]),l.useEffect(()=>{h({force:!0})},[h]),l.useEffect(()=>{t&&Promise.all([u({directory:c,silent:!0}),h({force:!0})])},[t,u,c,h]);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,b)=>N.localeCompare(b))},[w,p]),O=l.useCallback(j=>{if(j?.preventDefault(),f)return;x(!0);const N=new Promise(b=>setTimeout(b,500));Promise.all([u({directory:c}),N]).finally(()=>{x(!1)})},[f,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:f,onClick:O,"aria-label":o("mcpDropdown.actions.refreshAria"),children:s.jsx(K,{name:"refresh",className:fe("h-4 w-4",f&&"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],b=o0(N),I=N?.status==="connected",B=k===j,T=r0(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",b==="success"&&"bg-status-success",b==="error"&&"bg-status-error",b==="warning"&&"bg-status-warning",b==="default"&&"bg-muted-foreground/40"),"aria-label":T})}),s.jsx(ks,{side:"left",children:s.jsx("p",{children:T})})]}),s.jsx("span",{className:fe("truncate",r?"text-[17px] leading-6 font-medium":"typography-ui-label"),children:j})]})}),s.jsx(hr,{checked:I,disabled:B,className:"data-[checked]:bg-status-info",onCheckedChange:async D=>{y(j);try{D?await g(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")})]})})]})},al=5,Pm=15,Wi=new Map,lr=t=>{const e=Math.sqrt(t/100),n=12*e,a=24*e;return Math.ceil(n+a+1)},l0=(t,e)=>{const n=lr(e);return Math.max(n*al,Math.min(n*Pm,n*t))},c0=async(t,e)=>{const n=await wg(t.path);return{...t,title:n?.title||t.path.split("/").pop()||e}},d0=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Vd=t=>[...t.filter(e=>!e.completed),...t.filter(e=>e.completed)],Hd=(t,e)=>{const n=t.findIndex(a=>a.completed);return n===-1?[...t,e]:[...t.slice(0,n),e,...t.slice(n)]},u0=t=>{const e=Ze.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:g}=Au(i);let m;e[2]!==p?(m=Du.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 h=g&&"opacity-60";let f;e[7]!==h?(f=fe(h),e[7]=h,e[8]=f):f=e[8];let x;e[9]!==r||e[10]!==a||e[11]!==g||e[12]!==o||e[13]!==c?(x=a({attributes:r,listeners:o,setActivatorNodeRef:c,isDragging:g}),e[9]=r,e[10]=a,e[11]=g,e[12]=o,e[13]=c,e[14]=x):x=e[14];let k;return e[15]!==d||e[16]!==w||e[17]!==f||e[18]!==x?(k=s.jsx("li",{ref:d,style:w,className:f,children:x}),e[15]=d,e[16]=w,e[17]=f,e[18]=x,e[19]=k):k=e[19],k},m0=({projectRef:t,projectLabel:e,canCreateWorktree:n=!1,onActionComplete:a,onOpenPlan:i,className:r})=>{const{t:o}=ot(),[d,c]=l.useState(!1),[p,u]=l.useState(""),[g,m]=l.useState([]),[w,h]=l.useState(""),[f,x]=l.useState(null),[k,y]=l.useState(()=>new Set),[C,O]=l.useState([]),[j,N]=l.useState(null),[b,I]=l.useState(!1),[B,T]=l.useState(0),D=l.useRef(!1),S=l.useRef(""),F=l.useRef(null),R=je($=>$.todoPanelHeight),z=je($=>$.setTodoPanelHeight),q=je($=>$.notesPanelHeight),H=je($=>$.setNotesPanelHeight),[Z,W]=l.useState(!1),A=l.useRef(0),X=l.useRef(R),te=es($=>$.currentSessionId),E=es($=>$.createSession),P=es($=>$.initializeNewOpenChamberSession),_=es($=>$.sendMessage),L=es($=>$.setCurrentSession),V=xg($=>$.setPendingInputText),Y=Cs($=>$.currentDirectory),G=je($=>$.openContextPanelTab),me=je($=>$.setActiveMainTab),ae=je($=>$.setSessionSwitcherOpen),xe=je($=>$.padding),be=l.useCallback(async($,Ee)=>{if(!t)return!1;const J=t.id,ue=(Wi.get(J)??Promise.resolve()).catch(()=>{}).then(()=>bg(t,{notes:$,todos:Ee}));Wi.set(J,ue);try{const Ne=await ue;return Ne||Q.error(o("rightSidebar.contextNotesTodo.toast.saveNotesFailed")),Ne}finally{Wi.get(J)===ue&&Wi.delete(J)}},[t,o]);l.useEffect(()=>{if(!t){u(""),m([]),O([]),h(""),y(new Set);return}let $=!1;return c(!0),(async()=>{try{const Ee=await yg(t),J=await Promise.all(Ee.plans.map(v=>c0(v,o("rightSidebar.contextNotesTodo.plan.defaultTitle"))));if($)return;u(Ee.notes),m(Vd(Ee.todos)),O(J),S.current=Ee.notes,D.current=!0,h(""),y(new Set)}catch{$||(Q.error(o("rightSidebar.contextNotesTodo.toast.loadNotesFailed")),u(""),m([]),O([]),S.current="",D.current=!0)}finally{$||c(!1)}})(),()=>{$=!0}},[B,t,o]),l.useEffect(()=>{if(!t)return;const $=Ee=>{const J=Ee.detail;J?.projectId&&J.projectId!==t.id||T(v=>v+1)};return window.addEventListener("openchamber:project-plan-saved",$),window.addEventListener("openchamber:project-notes-updated",$),()=>{window.removeEventListener("openchamber:project-plan-saved",$),window.removeEventListener("openchamber:project-notes-updated",$)}},[t]),l.useEffect(()=>{if(g.length<7)return;const $=l0(g.length,xe),Ee=lr(xe)*al;R!==$&&(R<Ee||R>$)&&z($)},[g.length,xe,R,z]),l.useEffect(()=>{if(!Z)return;const $=J=>{const v=J.clientY-A.current,ue=Math.min(lr(xe)*Pm,Math.max(lr(xe)*al,X.current+v));z(ue)},Ee=()=>{W(!1)};return window.addEventListener("pointermove",$),window.addEventListener("pointerup",Ee,{once:!0}),window.addEventListener("pointercancel",Ee,{once:!0}),()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",Ee),window.removeEventListener("pointercancel",Ee)}},[Z,xe,z]);const ie=l.useCallback($=>{W(!0),A.current=$.clientY,X.current=R,$.preventDefault()},[R]),pe=l.useCallback(()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),Ie=l.useCallback(()=>{pe(),S.current=p,be(p,g)},[pe,p,be,g]);l.useEffect(()=>{if(!(!t||!D.current)&&p!==S.current)return F.current=window.setTimeout(()=>{F.current=null,S.current=p,be(p,g)},400),()=>{pe()}},[pe,p,be,t,g]),l.useEffect(()=>()=>pe(),[pe]);const re=l.useCallback(()=>{const $=w.trim();if(!$)return;const Ee=Hd(g,{id:d0(),text:$.slice(0,Ri),completed:!1,createdAt:Date.now()});m(Ee),h(""),be(p,Ee)},[w,p,be,g]),ce=l.useCallback($=>{y(Ee=>{const J=new Set(Ee);return J.has($)?J.delete($):J.add($),J})},[]),ge=l.useCallback(($,Ee)=>{const J=g.find(we=>we.id===$);if(!J||J.completed===Ee)return;const v=g.filter(we=>we.id!==$),ue={...J,completed:Ee},Ne=Ee?[...v,ue]:Hd(v,ue);m(Ne),be(p,Ne)},[p,be,g]),oe=l.useCallback($=>{const Ee=g.filter(J=>J.id!==$);m(Ee),be(p,Ee)},[p,be,g]),de=l.useCallback(()=>{const $=g.filter(Ee=>!Ee.completed);$.length!==g.length&&(m($),be(p,$))},[p,be,g]),le=l.useCallback($=>{const{active:Ee,over:J}=$;if(!J||Ee.id===J.id)return;const v=g.findIndex(we=>we.id===Ee.id),ue=g.findIndex(we=>we.id===J.id);if(v===-1||ue===-1)return;const Ne=Vd(Zf(g,v,ue));m(Ne),be(p,Ne)},[p,be,g]),he=Su(Cu(Iu,{activationConstraint:{distance:8}})),De=w.slice(0,Ri),Le=g.reduce(($,Ee)=>$+(Ee.completed?1:0),0),Ke=l.useCallback(()=>{me("chat"),ae(!1)},[me,ae]),Fe=l.useCallback(($,Ee)=>{!t||f||N({kind:"session",todoId:$,todoText:Ee})},[t,f]),Me=l.useCallback($=>{if(!te){Q.error(o("rightSidebar.contextNotesTodo.toast.noActiveSession"));return}Ke();const Ee=`\`\`\`md
|
|
37
|
+
${$}
|
|
38
|
+
\`\`\``;V(Ee,"append"),Q.success(o("rightSidebar.contextNotesTodo.toast.sentToCurrentSession")),a?.()},[te,a,Ke,V,o]),Be=l.useCallback(($,Ee)=>{if(!(!t||f)){if(!n){Q.error(o("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}N({kind:"worktree",todoId:$,todoText:Ee})}},[n,t,f,o]),Ge=l.useCallback(async $=>{if(!t||!j)return;const Ee=await Un("plan.todo.visible",{todo_text:j.todoText}),v=[{synthetic:!0,text:await Un("plan.todo.instructions",{todo_text:j.todoText})}];I(!0),x(j.todoId);try{Ke();let ue=null,Ne=t.path;if(j.kind==="worktree"){if(!n){Q.error(o("rightSidebar.contextNotesTodo.toast.worktreeRequiresGitRepo"));return}const qe=await iu(t.path,ru());if(!qe?.id)return;ue=qe.id,Ne=qe.path}else{const qe=await E(void 0,t.path,null);if(!qe?.id){Q.error(o("rightSidebar.contextNotesTodo.toast.createSessionFailed"));return}ue=qe.id,Ne=qe.directory??t.path,P(qe.id,pt.getState().agents??[])}if(!ue)return;const we=cl.getState();we.saveSessionModelSelection(ue,$.providerID,$.modelID),$.agent.trim()&&(we.saveSessionAgentSelection(ue,$.agent),we.saveAgentModelForSession(ue,$.agent,$.providerID,$.modelID),we.saveAgentModelVariantForSession(ue,$.agent,$.providerID,$.modelID,$.variant||void 0)),L(ue,Ne),await _(Ee,$.providerID,$.modelID,$.agent.trim()||void 0,void 0,void 0,v,$.variant||void 0),Q.success(j.kind==="worktree"?o("rightSidebar.contextNotesTodo.toast.sentToNewWorktreeSession"):o("rightSidebar.contextNotesTodo.toast.sentToNewSession")),N(null),a?.()}catch(ue){const Ne=ue instanceof Error?ue.message:void 0;Q.error(o("rightSidebar.contextNotesTodo.toast.sendTodoFailed"),Ne?{description:Ne}:void 0)}finally{I(!1),x(null)}},[n,E,P,a,j,t,Ke,_,L,o]),Ve=l.useRef(null),[Ue,He]=l.useState(!1),[_e,Oe]=l.useState(null),se=l.useCallback(async $=>{if(!(!t||_e)){Oe($);try{if(!await vg(t,$)){Q.error(o("rightSidebar.contextNotesTodo.toast.deletePlanFailed"));return}O(J=>J.filter(v=>v.id!==$)),window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{Oe(null)}}},[_e,t,o]),ye=l.useCallback(async()=>{if(!t||Ue)return;const $=await ml({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if($.success&&$.path){He(!0);try{const Ee=new URLSearchParams({path:$.path,allowOutsideWorkspace:"true"});$.outsideFileGrant&&Ee.set("outsideFileGrant",$.outsideFileGrant);const J=await ht(`/api/fs/read?${Ee.toString()}`,{cache:"no-store"});if(!J.ok){Q.error(o("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"));return}const v=await J.text();if(!v.trim()){Q.error(o("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const ue=$.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await zl(t,v,ue)){Q.error(o("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),Q.success(o("rightSidebar.contextNotesTodo.toast.planImported"))}catch(Ee){const J=Ee instanceof Error?Ee.message:void 0;Q.error(o("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),J?{description:J}:void 0)}finally{He(!1)}}else $.error==="Native file picker not available"&&Ve.current?.click()},[Ue,t,o]),ke=l.useCallback(async $=>{if(!(!t||!$)){He(!0);try{const Ee=await $.text();if(!Ee.trim()){Q.error(o("rightSidebar.contextNotesTodo.toast.planFileEmpty"));return}const J=$.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await zl(t,Ee,J)){Q.error(o("rightSidebar.contextNotesTodo.toast.importPlanFailed"));return}window.dispatchEvent(new CustomEvent("openchamber:project-plan-saved",{detail:{projectId:t.id}})),Q.success(o("rightSidebar.contextNotesTodo.toast.planImported"))}catch(Ee){const J=Ee instanceof Error?Ee.message:void 0;Q.error(o("rightSidebar.contextNotesTodo.toast.readPlanFileFailed"),J?{description:J}:void 0)}finally{He(!1)}}},[t,o]),ze=l.useCallback($=>{if(i){i({path:$.path,title:$.title});return}const Ee=t?.path?.trim(),J=Y?.trim()||Ee;J&&G(J,{mode:"plan",targetPath:$.path,dedupeKey:$.path,label:$.title})},[Y,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,"/",Kl]})]}),s.jsx(Ns,{value:p,onChange:$=>u($.target.value.slice(0,Kl)),onBlur:Ie,placeholder:o("rightSidebar.contextNotesTodo.notes.placeholder"),resizedHeight:q,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:g.length===1?o("rightSidebar.contextNotesTodo.todo.itemsSingle",{count:g.length}):o("rightSidebar.contextNotesTodo.todo.itemsPlural",{count:g.length})}),s.jsx("button",{type:"button",onClick:de,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:[De.length,"/",Ri]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(nt,{value:De,onChange:$=>h($.target.value.slice(0,Ri)),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),re())},placeholder:o("rightSidebar.contextNotesTodo.todo.inputPlaceholder"),disabled:d,className:"h-8"}),s.jsx("button",{type:"button",onClick:re,disabled:d||De.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:g.length<7?void 0:{height:`${R}px`,maxHeight:`${R}px`},children:g.length===0?s.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:o("rightSidebar.contextNotesTodo.todo.empty")}):s.jsx(Pu,{sensors:he,collisionDetection:Tu,onDragEnd:le,children:s.jsx(Eu,{items:g.map($=>$.id),strategy:eh,children:s.jsx("ul",{className:"divide-y divide-border/50",children:g.map($=>{const Ee=k.has($.id);return s.jsx(u0,{id:$.id,children:J=>s.jsxs("div",{className:fe("flex gap-1.5 px-2.5 py-1.5",Ee?"items-start":"items-center"),children:[s.jsx("button",{type:"button",ref:J.setActivatorNodeRef,...J.attributes,...J.listeners,onClick:v=>{v.preventDefault(),v.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:$.text}),title:o("rightSidebar.contextNotesTodo.todo.actions.reorder",{text:$.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(rn,{checked:$.completed,onChange:v=>ge($.id,v),ariaLabel:o("rightSidebar.contextNotesTodo.todo.actions.markComplete",{text:$.text})})}),s.jsx("button",{type:"button",onClick:()=>ce($.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",Ee?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",$.completed&&"text-muted-foreground line-through"),title:Ee?void 0:$.text,"aria-label":Ee?o("rightSidebar.contextNotesTodo.todo.actions.collapse",{text:$.text}):o("rightSidebar.contextNotesTodo.todo.actions.expand",{text:$.text}),children:$.text}),s.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[s.jsx("button",{type:"button",onClick:()=>oe($.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:$.text}),title:o("rightSidebar.contextNotesTodo.todo.actions.delete",{text:$.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:f===$.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":o("rightSidebar.contextNotesTodo.todo.actions.send",{text:$.text}),title:o("rightSidebar.contextNotesTodo.todo.actions.send",{text:$.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:()=>Me($.text),children:o("rightSidebar.contextNotesTodo.todo.sendMenu.currentSession")}),s.jsx(as,{onClick:()=>Fe($.id,$.text),children:o("rightSidebar.contextNotesTodo.todo.sendMenu.newSession")}),s.jsx(as,{onClick:()=>{Be($.id,$.text)},disabled:!n,children:o("rightSidebar.contextNotesTodo.todo.sendMenu.newWorktreeSession")})]})]})]})]})},$.id)})})})})}),g.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:ie,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:Ve,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:$=>{const Ee=$.target.files?.[0]??null;ke(Ee),$.currentTarget.value=""}}),s.jsx("button",{type:"button",onClick:ye,disabled:!t||Ue,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($=>s.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[s.jsxs("button",{type:"button",onClick:()=>ze($),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:$.title}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date($.createdAt).toLocaleDateString(kr())})]}),s.jsx("button",{type:"button",onClick:()=>{se($.id)},disabled:_e===$.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:$.title}),children:s.jsx(K,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},$.id))})})]}),s.jsx(_u,{open:j!==null,onOpenChange:$=>{!$&&!b&&N(null)},target:j?.kind??"session",projectDirectory:t?.path??null,submitting:b,onConfirm:Ge})]}):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")})})},SS=t=>{const e=Ze.c(19),{onActionComplete:n,onOpenPlan:a}=t,i=is(p0),r=is(g0),o=Cs(f0),d=Sr(h0);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 g=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()||jg(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 h;e:{if(!p){h=!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],h=k===!0}const f=h;let x;return e[13]!==f||e[14]!==n||e[15]!==a||e[16]!==w||e[17]!==g?(x=s.jsx("div",{className:"h-full min-h-0 overflow-auto bg-background",children:s.jsx(m0,{projectRef:g,projectLabel:w,canCreateWorktree:f,onActionComplete:n,onOpenPlan:a})}),e[13]=f,e[14]=n,e[15]=a,e[16]=w,e[17]=g,e[18]=x):x=e[18],x};function p0(t){return t.activeProjectId}function g0(t){return t.projects}function f0(t){return t.homeDirectory}function h0(t){return t.directories}const cr=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),il=512*1024,x0=new TextEncoder,b0=new TextDecoder,vo=t=>{const e=x0.encode(t);if(e.byteLength<=il)return{text:t,byteLength:e.byteLength};let n=e.byteLength-il;for(;n<e.byteLength&&(e[n]&192)===128;)n+=1;const a=e.subarray(n);return{text:b0.decode(a),byteLength:a.byteLength}},Ea=(t,e)=>`${t}\0${e}`,wo=(t,e)=>{let n=null;for(const a of t.keys())e(a)&&(n??=new Map(t),n.delete(a));return n},y0="terminal-store";let Wd=!1,Gd=0;const Gi=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Gd+=1,`tab-${Date.now().toString(36)}-${Gd.toString(36)}`),jo=t=>typeof t=="object"&&t!==null,v0=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 ko=(t,e)=>({id:t,terminalSessionId:null,lifecycle:"idle",label:e,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),No=t=>({tabs:[t],activeTabId:t.id}),Zs=(t,e)=>t.tabs.findIndex(n=>n.id===e);let So=null,Co=null;const w0=t=>{if(Co&&So?.sessions===t.sessions&&So.nextTabId===t.nextTabId)return Co;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 So={sessions:t.sessions,nextTabId:t.nextTabId},Co=e,e},j0=()=>{const t=vf(()=>mf());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=fn()(Ja(vi((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=Gi(),d=ko(o,"Terminal");return r.set(a,No(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(Ea(Es(n),a))??cr,createTab:n=>{const a=Es(n);if(!a)return"tab-invalid";const i=Gi();return t(r=>{const o=new Map(r.sessions),d=o.get(a),c=r.nextTabId+1,u=`Terminal ${(d?.tabs.length??0)+1}`,g=ko(i,u);return d?o.set(a,{...d,tabs:[...d.tabs,g]}):o.set(a,No(g)),{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||Zs(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=Zs(p,a);if(u<0||p.tabs[u]?.label===o)return d;const g=[...p.tabs];return g[u]={...g[u],label:o},c.set(r,{...p,tabs:g}),{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=Zs(c,a);if(p<0)return o;const u=i?.trim()||null;if(c.tabs[p]?.iconKey===u)return o;const g=[...c.tabs];return g[p]={...g[p],iconKey:u},d.set(r,{...c,tabs:g}),{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=Zs(d,a);if(c<0)return r;const p=d.tabs.filter(f=>f.id!==a),u=Object.fromEntries(Object.entries(r.projectActionRuns).filter(([,f])=>!(f.directory===i&&f.tabId===a))),g=Object.keys(u).length!==Object.keys(r.projectActionRuns).length,m=Ea(i,a),w=r.buffers.has(m)?wo(r.buffers,f=>f===m):null;if(p.length===0){const f=Gi(),x=ko(f,"Terminal");return o.set(i,No(x)),{sessions:o,nextTabId:r.nextTabId+1,...w?{buffers:w}:{},...g?{projectActionRuns:u}:{}}}let h=d.activeTabId;return d.activeTabId===a&&(h=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),o.set(i,{...d,tabs:p,activeTabId:h}),{sessions:o,...w?{buffers:w}:{},...g?{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=Zs(c,a);if(p<0)return o;const u=c.tabs[p],g=i!==null&&u.terminalSessionId!==i,m=i?"running":u.terminalSessionId?"exited":u.lifecycle,w={...u,terminalSessionId:i,lifecycle:m,isConnecting:!1},h=Ea(r,a),f=g&&o.buffers.has(h)?wo(o.buffers,k=>k===h):null,x=[...c.tabs];return x[p]=w,d.set(r,{...c,tabs:x}),{sessions:d,...f?{buffers:f}:{}}})},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=Zs(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=Zs(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||Zs(c,a)<0)return d;const p=Ea(o,a),u=d.buffers.get(p)??cr;if(u.lastSequence>r)return d;const g=vo(i);if(u.lastSequence===r&&u.byteLength===g.byteLength&&u.chunks.map(h=>h.data).join("")===g.text)return d;const m=d.nextChunkId,w=new Map(d.buffers);return w.set(p,{chunks:g.text?[{id:m,data:g.text,byteLength:g.byteLength}]:[],byteLength:g.byteLength,lastSequence:r}),{buffers:w,nextChunkId:g.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||Zs(p,a)<0)return c;const u=Ea(d,a),g=c.buffers.get(u)??cr;if(r!==void 0&&r<=g.lastSequence)return c;const m=c.nextChunkId,w=vo(i),h=o!==void 0&&o!==i?vo(o).text:void 0,f={id:m,data:w.text,...h!==void 0?{replayData:h}:{},byteLength:w.byteLength},x=[...g.chunks,f];let k=g.byteLength+f.byteLength;for(;k>il&&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??g.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=Zs(p,a);if(u<0)return d;const g=p.tabs[u],m=r.autoOpened??g.previewAutoOpened,w=r.locked??g.previewUrlLocked;if(g.previewUrl===i&&g.previewAutoOpened===m&&g.previewUrlLocked===w)return d;const h=[...p.tabs];return h[u]={...g,previewUrl:i,previewAutoOpened:m,previewUrlLocked:w},c.set(o,{...p,tabs:h}),{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=Zs(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=Ea(a,""),d=wo(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:y0,storage:j0(),partialize:w0,merge:(t,e)=>{if(!jo(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"||!jo(p))continue;const u=Array.isArray(p.tabs)?p.tabs:[],g=[],m=new Map;for(const x of u){if(!jo(x))continue;const k=typeof x.id=="string"?x.id:null;if(!k)continue;const y=v0(k);y!==null&&(i=Math.max(i,y));const C=y===null?k:Gi();m.set(k,C),g.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(g.length===0)continue;const w=typeof p.activeTabId=="string"?p.activeTabId:null,h=w?m.get(w)??w:null,f=h?g.some(x=>x.id===h):!1;a.set(c,{tabs:g,activeTabId:f?h:g[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"&&!Wd){Wd=!0;const t=ss.persist,e=()=>{ss.getState().hasHydrated||ss.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}function k0(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 N0(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 Io=["\x1B[0m","\x1B[m"],S0=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},qd=t=>{const e=S0(t);return e?`\x1B[0;48;2;${e[0]};${e[1]};${e[2]}m`:null},C0=(t,e,n)=>{const a=e+t;if(!n)return{data:a,carry:""};let i=0;const r=Math.max(...Io.map(c=>c.length))-1;for(let c=1;c<=Math.min(r,a.length);c+=1){const p=a.slice(-c);Io.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 Io)d=d.replaceAll(c,n);return{data:d,carry:o}},I0=(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))}},P0=(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 T0=null;const A0=()=>T0??=nh.load(),E0=(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))}},Tm=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},g)=>{const m=l.useRef(null),w=l.useRef(null),h=l.useRef(null),f=l.useRef(n),x=l.useRef(a),k=l.useRef(null),y=l.useRef(null),C=l.useRef(null),O=l.useRef(""),j=l.useRef(""),N=l.useRef(qd(i.background)),b=l.useRef(!1),I=l.useRef(0),B=l.useRef(u),T=l.useRef(!1),[D,S]=l.useState(0),[F,R]=l.useState(0);f.current=n,x.current=a,B.current=u,N.current=qd(i.background),l.useLayoutEffect(()=>{const Z=m.current;if(!Z)return;const W=E0(Z,r,o);y.current=W,W&&x.current(W.cols,W.rows)},[r,o]);const z=l.useCallback(()=>{const Z=m.current,W=w.current;if(!Z||!W||!h.current||!B.current)return;const A=Z.getBoundingClientRect();if(!(A.width<24||A.height<24))try{h.current.fit();const X={cols:W.cols,rows:W.rows};(!k.current||k.current.cols!==X.cols||k.current.rows!==X.rows)&&(k.current=X,x.current(X.cols,X.rows)),T.current||(T.current=!0,S(te=>te+1))}catch{}},[]),q=l.useCallback(()=>{if(b.current||!O.current||!w.current)return;const Z=w.current,W=O.current;O.current="";const A=C0(W,j.current,N.current);if(j.current=A.carry,!A.data){O.current&&q();return}b.current=!0;const X=I.current;Z.write(A.data,()=>{w.current!==Z||I.current!==X||(b.current=!1,O.current&&q())})},[]),H=l.useCallback(()=>{C.current=null,O.current="",j.current="",b.current=!1,I.current+=1;const Z=w.current;if(!Z){R(W=>W+1);return}try{Z.reset();const W=N.current;W&&Z.write(`${W}\x1B[2J\x1B[H`)}catch{R(W=>W+1)}},[]);return l.useEffect(()=>{const Z=m.current;if(!Z)return;let W=!1,A=null,X=null,te=null,E=null,P=[];const _=()=>{A&&B.current&&(A.options.cursorBlink=!0)},L=G=>{G.relatedTarget instanceof Node&&Z.contains(G.relatedTarget)||A&&(A.options.cursorBlink=!1)},V=()=>{A&&B.current&&Z.contains(document.activeElement)&&(A.options.cursorBlink=!0)},Y=()=>{A&&(A.options.cursorBlink=!1)};return Z.addEventListener("focusin",_),Z.addEventListener("focusout",L),window.addEventListener("focus",V),window.addEventListener("blur",Y),A0().then(G=>{if(W)return;A=new th({...N0(r,o,i,G,!1),...y.current??{}});const me=new sh;A.loadAddon(me),A.open(Z),w.current=A,h.current=me,P=[A.onData(xe=>f.current(xe))],X=new ResizeObserver(()=>{te&&clearTimeout(te),te=setTimeout(z,80)}),X.observe(Z),z();const ae=N.current;ae&&A.write(`${ae}\x1B[2J\x1B[H`),E=requestAnimationFrame(z)}),()=>{W=!0;const G=document.activeElement;G instanceof HTMLElement&&Z.contains(G)&&(G.blur(),window.Capacitor?.getPlatform?.()==="android"&&sc(async()=>{const{Keyboard:ae}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ae}},__vite__mapDeps([0,1])).then(({Keyboard:ae})=>ae.hide()).catch(()=>{})),X?.disconnect(),te&&clearTimeout(te),E!==null&&cancelAnimationFrame(E),Z.removeEventListener("focusin",_),Z.removeEventListener("focusout",L),window.removeEventListener("focus",V),window.removeEventListener("blur",Y),P.forEach(me=>me.dispose()),A?.dispose(),w.current=null,h.current=null,k.current=null,C.current=null,O.current="",j.current="",b.current=!1,I.current+=1,T.current=!1}},[z,r,o,F,i]),l.useEffect(()=>{const Z=w.current,W=m.current;!Z||!W||(Z.options.cursorBlink=u&&document.hasFocus()&&W.contains(document.activeElement))},[u,D]),l.useEffect(()=>{if(!w.current)return;if(e.length===0){C.current!==null&&H();return}const W=C.current;let A=-1;if(W!==null){for(let E=e.length-1;E>=0;E-=1){const P=e[E].id;if(P===W){A=E;break}if(P<W)break}if(A<0){H();return}}const X=A<0,te=A>=0?e.slice(A+1):e;O.current+=te.map(E=>X?E.replayData??E.data:E.data).join(""),C.current=e.at(-1)?.id??null,q()},[e,q,D,H]),l.useEffect(()=>{if(!p||!u)return;const Z=requestAnimationFrame(()=>w.current?.focus());return()=>cancelAnimationFrame(Z)},[p,u,D,t]),l.useEffect(()=>{const Z=m.current;if(!c||!Z)return;const W=A=>{const X=A;if(!X.isComposing)switch(X.inputType){case"insertText":X.data&&f.current(X.data);break;case"insertLineBreak":case"insertParagraph":f.current("\r");break;case"deleteContentBackward":f.current("");break}};return Z.addEventListener("beforeinput",W),()=>Z.removeEventListener("beforeinput",W)},[c,D]),l.useEffect(()=>{const Z=m.current,W=w.current;if(!c||!Z||!W)return;let A=null,X=null,te="idle",E=0,P=0,_=0,L=0,V=null;const Y=Math.max(12,o+2),G=()=>{window.Capacitor?.getPlatform?.()==="android"&&sc(async()=>{const{Keyboard:ge}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ge}},__vite__mapDeps([0,1])).then(({Keyboard:ge})=>ge.show()).catch(()=>{})},me=()=>{X&&(clearTimeout(X),X=null)},ae=(ce,ge)=>{const oe=Z.querySelector("canvas");return oe?I0(ce,ge,oe.getBoundingClientRect(),W.cols,W.rows):null},xe=(ce,ge)=>{const oe=Z.querySelector("canvas");if(!oe)return;const de=oe.getBoundingClientRect(),le=de.left+(ge.column+.5)/W.cols*de.width,he=de.top+(ge.row+.5)/W.rows*de.height;oe.dispatchEvent(new MouseEvent(ce,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:le,clientY:he}))},be=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ie=ce=>{ce.pointerType!=="touch"||A!==null||(A=ce.pointerId,te="pending",E=ce.clientX,P=ce.clientY,_=ce.clientY,L=0,V=null,Z.setPointerCapture(ce.pointerId),X=setTimeout(()=>{if(X=null,A!==ce.pointerId||te!=="pending")return;const ge=ae(E,P);if(!ge)return;const oe=W.buffer.active,de=Math.max(0,oe.length-W.rows-oe.viewportY+ge.row),le=oe.getLine(de),he=Array.from({length:W.cols},(Ke,Fe)=>le?.getCell(Fe)?.getChars()??""),De=P0(he,ge.column),Le={column:De.startColumn,row:ge.row};V={column:De.endColumn,row:ge.row},te="selecting",xe("mousedown",Le),xe("mousemove",V)},350))},pe=ce=>{if(A!==ce.pointerId)return;if(te==="selecting"){const de=ae(ce.clientX,ce.clientY);de&&(!V||de.column!==V.column||de.row!==V.row)&&(V=de,xe("mousemove",de)),ce.cancelable&&ce.preventDefault();return}if(te==="pending"){if(Math.hypot(ce.clientX-E,ce.clientY-P)<8)return;me(),te="scrolling"}if(te!=="scrolling")return;const ge=_-ce.clientY;_=ce.clientY,L+=ge;const oe=Math.trunc(L/Y);oe&&(W.scrollLines(oe),L-=oe*Y),ce.cancelable&&ce.preventDefault()},Ie=ce=>{if(A!==ce.pointerId)return;const ge=te==="pending",oe=te==="selecting";me(),Z.hasPointerCapture(ce.pointerId)&&Z.releasePointerCapture(ce.pointerId),A=null,te="idle",oe&&be(),ge&&(W.focus(),G())},re=ce=>{if(A!==ce.pointerId)return;const ge=te==="selecting";me(),Z.hasPointerCapture(ce.pointerId)&&Z.releasePointerCapture(ce.pointerId),A=null,te="idle",ge&&be()};return Z.addEventListener("pointerdown",ie),Z.addEventListener("pointermove",pe,{passive:!1}),Z.addEventListener("pointerup",Ie),Z.addEventListener("pointercancel",re),()=>{me(),Z.removeEventListener("pointerdown",ie),Z.removeEventListener("pointermove",pe),Z.removeEventListener("pointerup",Ie),Z.removeEventListener("pointercancel",re)}},[c,o,D]),l.useImperativeHandle(g,()=>({focus:()=>w.current?.focus(),fit:z,getSelection:()=>{const Z=w.current,W=Z?.getSelectionPosition(),A=Z?.getSelection()??"";return!W||!A.trim()?null:{text:A,startLine:W.start.y+1,endLine:W.end.y+1}}}),[z]),s.jsx("div",{ref:m,"data-terminal-owner":"main",className:fe("terminal-viewport-container h-full w-full overflow-hidden touch-none",d)})});Tm.displayName="TerminalViewport";const D0="\x1B",R0=new RegExp(`${D0}\\[[0-9;?]*[ -/]*[@-~]`,"g"),M0=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,L0=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,F0=/Serving HTTP on .*? port (\d{2,5})/i,O0=new Set([".",",",";",":","!","?"]),z0=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(O0.has(n)){e=e.slice(0,-1);continue}break}return e},Jd=t=>{let e=z0(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},K0=t=>{if(!t)return null;const e=t.replace(R0,""),n=e.match(F0);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(!L0.test(i))continue;const r=Array.from(i.matchAll(M0));if(r.length===0)continue;const o=r.find(d=>{try{return!!new URL(Jd(d[1])).port}catch{return!1}});return Jd((o??r[0])[1])}return null},B0=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)}},_0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},U0=(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 _0[t]},Am=t=>{const e=t[0]?.toUpperCase();return!e||e<"A"||e>"Z"?null:String.fromCharCode(e.charCodeAt(0)&31)},$0=(t,e)=>t&&(e==="ctrl"?Am(t)??t:t.length===1&&t!=="\x1B"?`\x1B${t}`:t),Yd={cols:80,rows:24},CS=({visible:t})=>{const{t:e}=ot(),{terminal:n,runtime:a}=Ha(),{currentTheme:i}=Wa(),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}=kg(),d=je(Te=>Te.terminalFontSize),c=je(Te=>Te.terminalShell),p=je(Te=>Te.terminalLoginShells.includes(Te.terminalShell)),{isMobile:u,isTablet:g,hasTouchOnlyPointer:m}=Hs(),w=u||g,h=(w||m)&&a.platform==="web",f=a.platform!=="vscode",x=je(Te=>Te.showTerminalQuickKeysOnDesktop),k=w||x,y=es(Te=>Te.currentSessionId),C=es(Te=>Te.newSessionDraft),O=y!==null||C?.open===!0,j=ol()??null,N=ss(Te=>j?Te.sessions.get(j):void 0),b=ss(Te=>Te.hasHydrated),I=ss(Te=>Te.ensureDirectory),B=ss(Te=>Te.createTab),T=ss(Te=>Te.setActiveTab),D=ss(Te=>Te.closeTab),S=ss(Te=>Te.setTabSessionId),F=ss(Te=>Te.setTabLifecycle),R=ss(Te=>Te.setConnecting),z=ss(Te=>Te.appendToBuffer),q=ss(Te=>Te.replaceBuffer),H=ss(Te=>Te.setTabPreviewUrl),Z=ui(Te=>Te.addDraft),W=je(Te=>Te.openContextPreview),A=l.useMemo(()=>N?f?N.activeTabId??N.tabs[0]?.id??null:N.tabs[0]?.id??null:null,[N,f]),X=l.useMemo(()=>{if(N)return A?N.tabs.find(Te=>Te.id===A)??N.tabs[0]:N.tabs[0]},[N,A]),te=l.useMemo(()=>(N?.tabs??[]).map(Te=>({icon:(()=>{const ne=Te.iconKey?Zu[Te.iconKey]??"terminal":"terminal";return s.jsx(K,{name:ne,className:"h-4 w-4"})})(),id:Te.id,label:Te.label,title:Te.label,closeLabel:e("terminalView.tabs.closeTabTitle")})),[N?.tabs,e]),E=X?.terminalSessionId??null,P=X?.lifecycle??"idle",_=ss(Te=>j&&A?Te.getBuffer(j,A).chunks:cr.chunks),L=X?.isConnecting??!1,V=X?.previewUrl??null,[Y,G]=l.useState(null),[me,ae]=l.useState(!1),[xe,be]=l.useState(!1),[ie,pe]=l.useState(null),[Ie,re]=l.useState(!1),ce=l.useRef(null),ge=l.useRef(null),oe=l.useRef(A),de=l.useRef(E),le=l.useRef(j),he=l.useRef(null),De=l.useRef(null),Le=l.useRef(new Set),Ke=l.useRef(""),Fe=l.useRef(new Set),Me=l.useRef(0),Be=l.useCallback(()=>{Ke.current="",Fe.current.clear(),Me.current+=1},[]),Ge=l.useCallback(()=>{h||typeof document<"u"&&!document.hasFocus()||he.current?.focus()},[h]),Ve=l.useCallback(()=>{h||he.current?.focus()},[h]),He=je(Te=>Te.activeMainTab)==="terminal",_e=t??He,[Oe,se]=l.useState(_e);l.useEffect(()=>{_e&&se(!0)},[_e]),l.useEffect(()=>{de.current=E},[E]),l.useEffect(()=>{!E||!n.updateAppearance||n.updateAppearance(E,r.current).catch(()=>{})},[i.colors.surface.background,i.colors.syntax.base.foreground,i.metadata.variant,n,E]),l.useEffect(()=>{oe.current=A,Be()},[A,Be]),l.useEffect(()=>{le.current=j},[j]),l.useEffect(()=>{!k&&ie!==null&&pe(null)},[k,ie,pe]),l.useEffect(()=>{!E&&ie!==null&&pe(null)},[E,ie,pe]);const ye=l.useCallback(()=>{ce.current?.(),ce.current=null,ge.current=null,be(!1)},[]);l.useEffect(()=>()=>{ye(),de.current=null},[ye]);const ke=l.useCallback((Te,ne,Pe)=>{if(!Pe)return;const Xe=`${Ke.current}${Pe}`.replace(/\r\n|\r/g,`
|
|
40
|
+
`),Re=Xe.split(`
|
|
41
|
+
`),Ye=Xe.endsWith(`
|
|
42
|
+
`)?Re.join(`
|
|
43
|
+
`):Re.slice(0,-1).join(`
|
|
44
|
+
`);if(Ke.current=Xe.endsWith(`
|
|
45
|
+
`)?"":(Re[Re.length-1]??"").slice(-1024),!Ye)return;const We=K0(Ye);if(!We||Fe.current.has(We))return;const et=Me.current;Fe.current.add(We),B0(We).then(kt=>{if(Fe.current.delete(We),!kt||Me.current!==et)return;const Et=ss.getState().getDirectoryState(Te)?.tabs.find(Ot=>Ot.id===ne);!Et||Et.previewUrlLocked||Et.previewUrl===We||H(Te,ne,We,{locked:!1,autoOpened:!1})})},[H]),ze=l.useCallback((Te,ne,Pe)=>{if(ge.current===Pe)return;ye(),ge.current=Pe;const Xe=n.connect(Pe,{onEvent:Re=>{if(ge.current===Pe)switch(Re.type){case"snapshot":{R(Te,ne,!1),G(null),ae(!1),be(!1),Ge(),q(Te,ne,Re.data??"",Re.sequence??0),ke(Te,ne,Re.data??""),Re.status==="exited"&&F(Te,ne,"exited");break}case"reconnecting":{G(null),ae(!1),be(!0);break}case"data":{Re.data&&(z(Te,ne,Re.data,Re.sequence,Re.replayData),ke(Te,ne,Re.data));break}case"exit":{const Ye=typeof Re.exitCode=="number"?Re.exitCode:null,We=typeof Re.signal=="number"?Re.signal:null,kt=!!ss.getState().getDirectoryState(Te)?.tabs.find(Et=>Et.id===ne)?.label?.startsWith("Action:");z(Te,ne,e("terminalView.stream.processExitedMessage",{exitCodeSegment:Ye!==null?e("terminalView.stream.processExitedWithCode",{exitCode:Ye}):"",signalSegment:We!==null?e("terminalView.stream.processExitedWithSignal",{signal:We}):""})),F(Te,ne,"exited"),R(Te,ne,!1),G(kt?null:e("terminalView.error.sessionEnded")),ae(!1),be(!1),ye();break}}},onError:(Re,Ye)=>{if(ge.current===Pe){if(!Ye){G(null),ae(!1);return}if(be(!1),Re.code==="SESSION_NOT_FOUND"&&!ss.getState().getDirectoryState(Te)?.tabs.find(et=>et.id===ne)?.label?.startsWith("Action:")){G(null),ae(!1),R(Te,ne,!1),S(Te,ne,null),F(Te,ne,"idle"),ye();return}G(e("terminalView.error.connectionFailed",{message:Re.message})),ae(!0),R(Te,ne,!1),F(Te,ne,"exited"),S(Te,ne,null),ye()}}});ce.current=()=>{Xe.close(),ge.current=null}},[z,q,ye,Ge,ke,R,F,S,e,n]);l.useEffect(()=>{let Te=!1;if(!b||!Oe)return;if(!j){G(e(O?"terminalView.empty.noWorkingDirectory":"terminalView.empty.selectSession")),ye();return}return(async()=>{const Pe=j;if(!le.current||le.current!==Pe)return;if(!ss.getState().getDirectoryState(Pe)){I(Pe);return}const Re=ss.getState().getDirectoryState(Pe);if(!Re||Re.tabs.length===0)return;const Ye=f?Re.activeTabId??Re.tabs[0]?.id??null:Re.tabs[0]?.id??null;if(!Ye)return;const We=Re.tabs.find(Qt=>Qt.id===Ye)??Re.tabs[0],et=We?.terminalSessionId??null,kt=We?.lifecycle??"idle",Et=!!We?.label?.startsWith("Action:"),Ot=ss.getState().getBuffer(Pe,Ye),Zt=Ot.byteLength>0||Ot.chunks.length>0;if(!et){if(kt==="exited"){R(Pe,Ye,!1);return}if(Et&&Zt){R(Pe,Ye,!1);return}const Qt=`${Pe}\0${Ye}`;if(Le.current.has(Qt))return;const St=De.current??Yd;Le.current.add(Qt),G(null),ae(!1),be(!1),R(Pe,Ye,!0);try{const Pt=await n.createSession({cwd:Pe,sessionId:Ye,cols:St.cols,rows:St.rows,shell:c,loginShell:p,...r.current}),Se=!Te&&le.current===Pe&&oe.current===Ye;if(!ss.getState().getDirectoryState(Pe)?.tabs.find(At=>At.id===Ye)){try{await n.close(Pt.sessionId)}catch{}return}if(S(Pe,Ye,Pt.sessionId),!Se)return;const mt=De.current;mt&&(mt.cols!==St.cols||mt.rows!==St.rows)&&n.resize({sessionId:Pt.sessionId,...mt}).catch(()=>{});return}catch(Pt){const Se=ss.getState().getDirectoryState(Pe)?.tabs.find(ut=>ut.id===Ye);if(!Se||Se.terminalSessionId||(R(Pe,Ye,!1),le.current!==Pe||oe.current!==Ye))return;G(Pt instanceof Error?Pt.message:e("terminalView.error.startSessionFailed")),ae(!0),be(!1);return}finally{Le.current.delete(Qt)}}!et||Te||(de.current=et,ze(Pe,Ye,et))})(),()=>{Te=!0,de.current=null,ye()}},[O,j,E,P,A,Oe,f,b,I,R,F,S,ze,ye,e,n,p,c]),l.useEffect(()=>{if(!_e||h)return;if(typeof window>"u"){Ge();return}const Te=window.requestAnimationFrame(()=>{Ge()});return()=>{window.cancelAnimationFrame(Te)}},[A,Ge,_e,h]);const $=l.useCallback(async()=>{if(!j||Ie)return;const Te=ss.getState().getDirectoryState(j),ne=f?A??Te?.activeTabId??Te?.tabs[0]?.id??null:Te?.tabs[0]?.id??null;if(!ne)return;const Pe=Te?.tabs.find(Xe=>Xe.id===ne)?.terminalSessionId??null;if(!(!Pe||!n.restartSession)){re(!0),G(null),ae(!1),be(!1),ye(),Be();try{const Xe=De.current??Yd,Re=await n.restartSession(Pe,{cwd:j,shell:c,loginShell:p,...Xe,...r.current});if(ss.getState().getDirectoryState(j)?.tabs.find(We=>We.id===ne)?.terminalSessionId!==Pe||(S(j,ne,Re.sessionId),F(j,ne,"running"),le.current!==j||oe.current!==ne))return;de.current=Re.sessionId,ze(j,ne,Re.sessionId)}catch(Xe){if(ss.getState().getDirectoryState(j)?.tabs.find(Ye=>Ye.id===ne)?.terminalSessionId!==Pe||le.current!==j||oe.current!==ne)return;G(Xe instanceof Error?Xe.message:e("terminalView.error.restartFailed")),ae(!1),be(!1),de.current=Pe,ze(j,ne,Pe)}finally{re(!1)}}},[A,ye,j,f,Ie,Be,F,S,ze,e,n,p,c]),Ee=l.useCallback(async()=>{await $()},[$]),J=l.useCallback(()=>{if(!j)return;const Te=B(j);T(j,Te),G(null),ae(!1),be(!1),ye()},[B,ye,j,T]),v=l.useCallback(()=>{const Te=he.current?.getSelection(),ne=y??(C?.open?"draft":null);!Te||!ne||!X||!j||Z({directory:j,sessionKey:ne},{source:"terminal",fileLabel:X.label,startLine:Te.startLine,endLine:Te.endLine,code:Te.text,language:X.terminalSessionId??X.id,text:""})},[X,Z,y,j,C?.open]),ue=l.useCallback(Te=>{j&&(T(j,Te),G(null),ae(!1),be(!1),ye())},[ye,j,T]),Ne=l.useCallback(Te=>{if(!j)return;Te===A&&ye(),G(null),ae(!1),be(!1);const ne=ss.getState().getDirectoryState(j)?.tabs.find(Pe=>Pe.id===Te)?.terminalSessionId;(async()=>{ne&&await n.close(ne),D(j,Te)})().catch(Pe=>G(Pe instanceof Error?Pe.message:e("terminalView.error.sessionEnded")))},[A,D,ye,j,e,n]),we=l.useCallback(Te=>{if(!Te||xe)return;let ne=Te,Pe=!1;ie&&Te.length>0&&(ne=$0(Te,ie),Pe=!0);const Xe=de.current;Xe&&(n.sendInput(Xe,ne).catch(Re=>{xe||G(Re instanceof Error?Re.message:e("terminalView.error.sendInputFailed"))}),Pe&&(pe(null),Ve()))},[ie,Ve,xe,pe,e,n]),qe=l.useCallback((Te,ne)=>{const Pe=De.current;if((!Pe||Pe.cols!==Te||Pe.rows!==ne)&&(De.current={cols:Te,rows:ne}),!_e)return;const Xe=de.current;Xe&&n.resize({sessionId:Xe,cols:Te,rows:ne}).catch(()=>{})},[_e,n]),it=l.useCallback(Te=>{pe(ne=>ne===Te?null:Te),Ve()},[Ve,pe]),st=l.useCallback(Te=>{const ne=U0(Te,ie);ne&&(we(ne),pe(null),Ve())},[ie,Ve,we,pe]),rt=l.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),lt=l.useCallback(Te=>{if(Te.repeat)return;const ne=Te.key;if(!ne||ne==="Control"||ne==="Meta"||ne==="Alt"||ne==="Shift")return;const Pe=ne.length===1?ne.toLowerCase():ne;if(Pe in rt){Te.preventDefault(),Te.stopPropagation(),st(rt[Pe]);return}if(ie!=="ctrl")return;const Xe=Te.code??"",Re=ne.length===1&&/[a-zA-Z]/.test(ne)?ne.toUpperCase():Xe.startsWith("Key")&&Xe.length===4?Xe.slice(3).toUpperCase():null;if(Re&&Re.length===1&&Re>="A"&&Re<="Z"){const Ye=Am(Re);if(!Ye)return;Te.preventDefault(),Te.stopPropagation(),we(Ye),pe(null),Ve()}},[ie,Ve,st,we,rt,pe]);l.useEffect(()=>{if(!(!k||!ie||!E))return window.addEventListener("keydown",lt),()=>window.removeEventListener("keydown",lt)},[ie,lt,k,E]);const xt=l.useMemo(()=>{const Te=ti[fi].stack;if(typeof window>"u")return(ti[o]??ti[fi]).stack;const Pe=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Pe&&Pe.trim().length>0?Pe.trim():(ti[o]??ti[fi]).stack??Te},[o]),bt=l.useMemo(()=>k0(i),[i]),Nt=`${j??"no-dir"}::${A??"no-tab"}`;if(l.useEffect(()=>{if(!_e||h)return;const Te=he.current;if(!Te)return;const ne=()=>{Te.fit()};if(typeof window<"u"){const Pe=window.requestAnimationFrame(()=>{ne(),Ge()}),Xe=[220,400].map(Re=>window.setTimeout(ne,Re));return()=>{window.cancelAnimationFrame(Pe),Xe.forEach(Re=>window.clearTimeout(Re))}}ne()},[Ge,_e,h,Nt,E]),l.useEffect(()=>{if(!_e||!h)return;let Te=null;const ne=()=>{Te!==null&&window.cancelAnimationFrame(Te),Te=window.requestAnimationFrame(()=>{Te=null,he.current?.fit()})};return window.addEventListener("oc:keyboard-settled",ne),()=>{window.removeEventListener("oc:keyboard-settled",ne),Te!==null&&window.cancelAnimationFrame(Te)}},[_e,Nt,h]),!O)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:$,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 Ce=!E||L||Ie||xe,Qe=Oe,tt=w?"lg":"xs",at=w?"w-10 p-0":"w-9 p-0",gt=Te=>{w&&Te.preventDefault()},wt=s.jsxs(s.Fragment,{children:[s.jsx(ee,{type:"button",size:tt,variant:"outline",onPointerDown:gt,onClick:()=>st("esc"),disabled:Ce,children:e("terminalView.quickKeys.escape")}),s.jsxs(ee,{type:"button",size:tt,variant:"outline",className:at,onPointerDown:gt,onClick:()=>st("tab"),disabled:Ce,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:tt,variant:"chip","aria-pressed":ie==="ctrl",className:w?"px-3":"px-2",onPointerDown:gt,onClick:()=>it("ctrl"),disabled:Ce,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:tt,variant:"chip","aria-pressed":ie==="alt",className:w?"px-3":"px-2",onPointerDown:gt,onClick:()=>it("alt"),disabled:Ce,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:tt,variant:"outline",className:at,onPointerDown:gt,onClick:()=>st("arrow-up"),disabled:Ce,children:[s.jsx(K,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowUpAria")})]}),s.jsxs(ee,{type:"button",size:tt,variant:"outline",className:at,onPointerDown:gt,onClick:()=>st("arrow-left"),disabled:Ce,children:[s.jsx(K,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowLeftAria")})]}),s.jsxs(ee,{type:"button",size:tt,variant:"outline",className:at,onPointerDown:gt,onClick:()=>st("arrow-down"),disabled:Ce,children:[s.jsx(K,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowDownAria")})]}),s.jsxs(ee,{type:"button",size:tt,variant:"outline",className:at,onPointerDown:gt,onClick:()=>st("arrow-right"),disabled:Ce,children:[s.jsx(K,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowRightAria")})]}),s.jsxs(ee,{type:"button",size:tt,variant:"outline",className:at,onPointerDown:gt,onClick:()=>st("enter"),disabled:Ce,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:[f&&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(pa,{items:te,activeId:A,onSelect:ue,onClose:Ne,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:J,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:()=>{$()},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:v,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&&W(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&&f&&N?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:wt}):null,!w&&k&&(!f||!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(Tm,{ref:Te=>{he.current=Te},sessionKey:Nt,chunks:_,onInput:we,onResize:qe,theme:bt,fontFamily:xt,fontSize:d,enableTouchScroll:h,autoFocus:_e,isVisible:_e},Nt):null}),!xe&&Y&&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:Y}),me&&w&&s.jsx(ee,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Ee,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]})},Em={"?":{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"}},V0=Em.M;function H0(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 W0(t){const e=H0(t);return Em[e]??V0}const G0=l.memo(function(e){const n=Ze.c(58),{file:a,actionLabel:i,actionSymbol:r,onAction:o,onViewDiff:d,onRevert:c,isReverting:p,stats:u,rowPaddingClassName:g,indentPx:m,actionAtStart:w,showRevert:h}=e,f=m===void 0?0:m,x=w===void 0?!1:w,k=h===void 0?!0:h;let y;n[0]!==a?(y=W0(a),n[0]=a,n[1]=y):y=n[1];const C=y,{t:O}=ot(),j=C.description,N=u?.insertions??0,b=u?.deletions??0;let I;n[2]!==o||n[3]!==d?(I=xe=>{xe.key===" "?(xe.preventDefault(),o()):xe.key==="Enter"&&(xe.preventDefault(),d())},n[2]=o,n[3]=d,n[4]=I):I=n[4];const B=I;let T;n[5]!==o?(T=xe=>{xe.preventDefault(),xe.stopPropagation(),o()},n[5]=o,n[6]=T):T=n[6];const D=T;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 R;n[9]!==i||n[10]!==r||n[11]!==D?(R=s.jsx("button",{type:"button",onClick:D,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]=D,n[12]=R):R=n[12];const z=R,q=`group flex items-center gap-2 py-1.5 cursor-pointer ${g??"px-3"}`;let H;n[13]!==f?(H=f>0?{paddingLeft:`${f}px`}:void 0,n[13]=f,n[14]=H):H=n[14];const Z=x?z:null;let W;n[15]!==C.color?(W={color:C.color},n[15]=C.color,n[16]=W):W=n[16];let A;n[17]!==C.code||n[18]!==j||n[19]!==W?(A=s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:W,title:j,"aria-label":j,children:C.code}),n[17]=C.code,n[18]=j,n[19]=W,n[20]=A):A=n[20];let X;n[21]!==a.path?(X=s.jsx(Ng,{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 ge;n[25]===Symbol.for("react.memo_cache_sentinel")?(ge={direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},n[25]=ge):ge=n[25],te=s.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:ge,title:a.path,children:a.path});break e}const be=a.path.slice(0,xe),ie=a.path.slice(xe);let pe;n[26]===Symbol.for("react.memo_cache_sentinel")?(pe={direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},n[26]=pe):pe=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 re=s.jsx("span",{className:"text-foreground",children:ie.slice(1)});let ce;n[28]!==re?(ce=s.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[Ie,re]}),n[28]=re,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:pe,children:be}),ce]})}n[23]=a.path,n[24]=te}else te=n[24];let E;n[30]===Symbol.for("react.memo_cache_sentinel")?(E={color:"var(--status-success)"},n[30]=E):E=n[30];let P;n[31]!==N?(P=s.jsxs("span",{style:E,children:["+",N]}),n[31]=N,n[32]=P):P=n[32];let _,L;n[33]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),L={color:"var(--status-error)"},n[33]=_,n[34]=L):(_=n[33],L=n[34]);let V;n[35]!==b?(V=s.jsxs("span",{style:L,children:["-",b]}),n[35]=b,n[36]=V):V=n[36];let Y;n[37]!==P||n[38]!==V?(Y=s.jsxs("span",{className:"shrink-0 typography-micro",children:[P,_,V]}),n[37]=P,n[38]=V,n[39]=Y):Y=n[39];let G;n[40]!==a.path||n[41]!==F||n[42]!==p||n[43]!==k||n[44]!==O?(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":O("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:O("gitView.changes.revertFileTooltip")})]}):null,n[40]=a.path,n[41]=F,n[42]=p,n[43]=k,n[44]=O,n[45]=G):G=n[45];const me=x?null:z;let ae;return n[46]!==B||n[47]!==d||n[48]!==H||n[49]!==Z||n[50]!==A||n[51]!==X||n[52]!==te||n[53]!==Y||n[54]!==G||n[55]!==me||n[56]!==q?(ae=s.jsxs("div",{className:q,role:"button",tabIndex:0,onClick:d,onKeyDown:B,style:H,children:[Z,A,X,te,Y,G,me]}),n[46]=B,n[47]=d,n[48]=H,n[49]=Z,n[50]=A,n[51]=X,n[52]=te,n[53]=Y,n[54]=G,n[55]=me,n[56]=q,n[57]=ae):ae=n[57],ae}),Qd=14,Dm=t=>t.replace(/\\/g,"/").replace(/^\/+/,"").trim(),Xd=(t,e)=>({id:`dir:${t}`,path:t,name:e,children:new Map,directFiles:[],files:[]}),q0=t=>{const e=Xd("","");for(const n of t){const a=Dm(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=Xd(d,c);u.files.push(n),o.children.set(c,u),o=u}}o.directFiles.push(n)}return e},J0=(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:${Dm(c.path)}`,kind:"file",depth:r,file:c})};return a(t,0),n},Y0=1e3,Zd=34,Po=30,qi="pl-0 pr-2",To=(t,e)=>`${t} ${e}`,IS=({groups:t,diffStats:e,revertingPaths:n,isRevertingAll:a=!1,headerBackgroundClassName:i="bg-sidebar",onVisiblePathsChange:r,onRevertAll:o,onRevertDirectory:d})=>{const{t:c}=ot(),p=l.useRef(null),g=je(P=>P.gitChangesViewMode)==="tree",m=l.useMemo(()=>t.filter(P=>P.entries.length>0),[t]),[w,h]=l.useState(new Set),[f,x]=l.useState(new Set),[k,y]=l.useState(!1),[C,O]=l.useState(null),j=l.useMemo(()=>m.map(P=>q0(P.entries)),[m]),N=l.useMemo(()=>{const P=[];return m.forEach((_,L)=>{Array.from(j[L]?.children.values()??[]).forEach(V=>{P.push(To(_.id,V.path))})}),P},[j,m]);l.useEffect(()=>{g&&x(P=>{const _=new Set,L=new Set(N);return P.forEach(V=>{(V.slice(V.indexOf(" ")+1).includes("/")||L.has(V))&&_.add(V)}),N.forEach(V=>_.add(V)),_})},[g,N]);const b=l.useMemo(()=>{const P=[];return m.forEach((_,L)=>{if(P.push({type:"header",key:`header:${_.id}`,groupIndex:L}),!w.has(_.id)){if(g){const V=new Set;f.forEach(G=>{G.startsWith(`${_.id} `)&&V.add(G.slice(_.id.length+1))}),J0(j[L],V).forEach(G=>{G.kind==="file"?P.push({type:"file",key:`${_.id}:${G.key}`,groupIndex:L,file:G.file,depth:G.depth}):P.push({type:"directory",key:`${_.id}:${G.key}`,groupIndex:L,directory:G.directory,depth:G.depth})});return}_.entries.forEach(V=>{P.push({type:"file",key:`${_.id}:file:${V.path}`,groupIndex:L,file:V,depth:0})})}}),o&&m.length>0&&P.push({type:"revert-all",key:"revert-all"}),P},[w,f,g,o,j,m]),I=b.length,B=I>=Y0,T=ah({count:I,enabled:B,getScrollElement:()=>p.current,estimateSize:()=>Zd,overscan:12,getItemKey:P=>b[P]?.key??P}),D=T.getVirtualItems(),S=l.useMemo(()=>{if(!B)return 0;const P=p.current?.scrollTop??0;return D.find(L=>L.end>P)?.index??0},[B,D,p]);l.useEffect(()=>{if(!r)return;const P=_=>_&&_.type==="file"?_.file.path:null;if(I===0){r([]);return}if(!B){const _=[];for(const L of b)if(L.type==="file"&&(_.push(L.file.path),_.length>=Po))break;r(_);return}r(b.slice(S,S+Math.ceil((p.current?.clientHeight??0)/Zd)+Po).map(_=>P(_)).filter(_=>!!_).slice(0,Po))},[r,I,b,B,S]);const F=l.useCallback(P=>{h(_=>{const L=new Set(_);return L.has(P)?L.delete(P):L.add(P),L})},[]),R=l.useCallback((P,_)=>{x(L=>{const V=new Set(L),Y=To(P,_);return V.has(Y)?V.delete(Y):V.add(Y),V})},[]),z=l.useMemo(()=>{const P=new Set;return m.forEach(_=>_.entries.forEach(L=>P.add(L.path))),Array.from(P)},[m]),q=z.length,H=C?a||C.paths.some(P=>n.has(P)):!1,Z=l.useCallback(async()=>{!o||a||z.length===0||(await o(z),y(!1))},[z,a,o]),W=l.useCallback(async()=>{!d||!C||H||(await d(C.paths),O(null))},[H,d,C]),A=l.useCallback((P,_)=>{const L=w.has(P.id),V=P.entries.length;return s.jsxs("div",{className:fe("sticky top-0 z-10 flex items-center gap-2 py-2",i,qi,!_&&"mt-1 border-t border-border/40"),children:[s.jsx("button",{type:"button",onClick:()=>P.onActionAll(P.entries.map(Y=>Y.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":P.actionAllLabel,title:P.actionAllLabel,children:P.actionSymbol}),s.jsxs("button",{type:"button",onClick:()=>F(P.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:P.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((P,_,L)=>{const V=f.has(To(P.id,_.path)),Y=_.files.map(me=>me.path),G=a||Y.some(me=>n.has(me));return s.jsxs("div",{className:fe("group flex items-center gap-2 py-1.5",qi),style:{paddingLeft:`${L*Qd}px`},children:[s.jsxs("button",{type:"button",onClick:()=>R(P.id,_.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:_.path}):c("gitView.changes.expandDirectoryAria",{path:_.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:_.path,children:_.name}),s.jsx("span",{className:"ml-auto shrink-0 typography-micro text-muted-foreground",children:_.files.length})]}),P.showRevertActions!==!1&&d?s.jsx("button",{type:"button",onClick:()=>O({path:_.path,paths:Y,count:Y.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:_.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:()=>P.onActionAll(_.files.map(me=>me.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(P.actionSymbol==="+"?"gitView.changes.stageDirectoryAria":"gitView.changes.unstageDirectoryAria",{path:_.path}),title:c(P.actionSymbol==="+"?"gitView.changes.stageDirectoryAria":"gitView.changes.unstageDirectoryAria",{path:_.path}),children:P.actionSymbol})]})},[f,a,d,n,c,R]),te=l.useCallback((P,_)=>{if(P.type==="revert-all")return s.jsx("div",{className:fe("flex justify-end py-2",qi),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[P.groupIndex];if(!L)return null;if(P.type==="header")return A(L,_);if(P.type==="directory")return X(L,P.directory,P.depth);const V=P.file;return s.jsx(G0,{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:qi,indentPx:P.depth*Qd,actionAtStart:!g,showRevert:L.showRevertActions!==!1})},[e,a,g,X,A,n,c,m]),E=l.useCallback(P=>{const _=b[P],L=b[P-1];return!_||!L||_.type!=="file"&&_.type!=="directory"||L.type!=="file"&&L.type!=="directory"?!1:L.groupIndex===_.groupIndex},[b]);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(Sg,{ref:p,className:"overlay-scrollbar-target overlay-scrollbar-container min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto",children:B?s.jsx("div",{style:{height:T.getTotalSize(),position:"relative"},children:D.map(P=>{const _=b[P.index];return _?s.jsx("div",{"data-index":P.index,ref:T.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${P.start}px)`},className:fe(E(P.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(_,P.index===0)},_.key):null})}):s.jsx("div",{role:"list","aria-label":c("gitView.changes.changedFilesAria"),children:b.map((P,_)=>s.jsx("div",{className:fe("relative",E(_)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:te(P,_===0)},P.key))})}),s.jsx(Cg,{containerRef:p,disableHorizontal:!0})]}),s.jsx(Kt,{open:k,onOpenChange:P=>{!a&&!P&&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:q===1?c("gitView.changes.revertAllDescriptionSingle",{count:q}):c("gitView.changes.revertAllDescriptionPlural",{count:q})})]}),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:P=>{!H&&!P&&O(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:()=>O(null),disabled:H,children:c("gitView.common.cancel")}),s.jsx(ee,{variant:"destructive",size:"sm",onClick:()=>{W()},disabled:H||!C,children:c(H?"gitView.changes.reverting":"gitView.changes.revertDirectory")})]})]})})]})},Ao=38,Ji=200,Q0=t=>{const e=Ze.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:g}=ot(),m=l.useRef(null),w=je(X0);let h;e[0]===Symbol.for("react.memo_cache_sentinel")?(h=()=>{const B=m.current;if(!B)return;const T=document.activeElement===B,D=()=>{B.style.height=`${Ao}px`;const F=B.scrollHeight,R=Math.min(Math.max(F,Ao),Ji);B.style.height=`${R}px`,B.style.overflowY=F>Ji?"auto":"hidden",F>Ji&&!T&&(B.scrollTop=B.scrollHeight)};D();const S=window.requestAnimationFrame(D);return()=>{window.cancelAnimationFrame(S)}},e[0]=h):h=e[0];let f;e[1]!==n?(f=[n],e[1]=n,e[2]=f):f=e[2],l.useLayoutEffect(h,f);let x;e[3]!==a?(x=B=>a(B.target.value),e[3]=a,e[4]=x):x=e[4];let k;e[5]!==i||e[6]!==g?(k=i??g("gitView.commit.messagePlaceholder"),e[5]=i,e[6]=g,e[7]=k):k=e[7];const y=p?"on":"off",C=p?"sentences":"off",O=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 b;e[10]===Symbol.for("react.memo_cache_sentinel")?(b={minHeight:Ao,maxHeight:Ji},e[10]=b):b=e[10];let I;return e[11]!==c||e[12]!==O||e[13]!==N||e[14]!==x||e[15]!==k||e[16]!==y||e[17]!==C||e[18]!==n?(I=s.jsx("textarea",{ref:m,value:n,onChange:x,placeholder:k,rows:1,disabled:c,autoCorrect:y,autoCapitalize:C,spellCheck:O,className:N,style:b}),e[11]=c,e[12]=O,e[13]=N,e[14]=x,e[15]=k,e[16]=y,e[17]=C,e[18]=n,e[19]=I):I=e[19],I};function X0(t){return t.inputSpellcheckEnabled}const Z0=t=>{const e=Ze.c(30),{highlights:n,onInsert:a}=t,{t:i}=ot();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 g;e[10]!==o||e[11]!==p?(g=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]=g):g=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 h;e[17]!==g||e[18]!==w?(h=s.jsxs(bs,{children:[g,w]}),e[17]=g,e[18]=w,e[19]=h):h=e[19];let f;e[20]!==c||e[21]!==h?(f=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c,h]}),e[20]=c,e[21]=h,e[22]=f):f=e[22];let x;e[23]!==n?(x=n.map(eN),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]!==f||e[28]!==k?(y=s.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-transparent px-3 py-2",children:[f,k]}),e[27]=f,e[28]=k,e[29]=y):y=e[29],y};function eN(t,e){return s.jsx("li",{className:"typography-meta text-foreground",children:t},`${t}-${e}`)}const PS=t=>{const e=Ze.c(75),{stagedCount:n,commitMessage:a,onCommitMessageChange:i,generatedHighlights:r,onInsertHighlights:o,onGenerateMessage:d,isGeneratingMessage:c,onCommit:p,onCommitAndPush:u,commitAction:g,hasPendingIndexMutation:m,gitmojiEnabled:w,onOpenGitmojiPicker:h}=t,f=m===void 0?!1:m,{t:x}=ot(),k=n>0;let y;e[0]!==g||e[1]!==a||e[2]!==f||e[3]!==k?(y=a.trim()&&k&&g===null&&!f,e[0]=g,e[1]=a,e[2]=f,e[3]=k,e[4]=y):y=e[4];const C=y,{isMobile:O,hasTouchInput:j}=Hs();let N;e[5]!==x?(N=x("gitView.commit.title"),e[5]=x,e[6]=N):N=e[6];let b;e[7]!==N?(b=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:N}),e[7]=N,e[8]=b):b=e[8];let I;e[9]!==k||e[10]!==x?(I=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]=I):I=e[11];let B;e[12]!==b||e[13]!==I?(B=s.jsxs("div",{className:"flex w-full items-baseline gap-2 px-0 pt-2 pb-1",children:[b,I]}),e[12]=b,e[13]=I,e[14]=B):B=e[14];let T;e[15]!==r||e[16]!==o?(T=s.jsx(Z0,{highlights:r,onInsert:o}),e[15]=r,e[16]=o,e[17]=T):T=e[17];let D;e[18]!==x?(D=x("gitView.commit.messagePlaceholder"),e[18]=x,e[19]=D):D=e[19];const S=g!==null;let F;e[20]!==a||e[21]!==j||e[22]!==O||e[23]!==i||e[24]!==D||e[25]!==S?(F=s.jsx(Q0,{value:a,onChange:i,placeholder:D,disabled:S,hasTouchInput:j,isMobile:O}),e[20]=a,e[21]=j,e[22]=O,e[23]=i,e[24]=D,e[25]=S,e[26]=F):F=e[26];let R;e[27]!==w||e[28]!==h||e[29]!==x?(R=w&&s.jsxs(ee,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[s.jsx(K,{name:"emotion-happy",className:"size-4"}),x("gitView.commit.addGitmoji")]}),e[27]=w,e[28]=h,e[29]=x,e[30]=R):R=e[30];const z=c||g!==null||f||n===0;let q;e[31]!==x?(q=x("gitView.commit.generateAria"),e[31]=x,e[32]=q):q=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 W;e[37]!==Z?(W=s.jsx("span",{className:"commit-actions__label",children:Z}),e[37]=Z,e[38]=W):W=e[38];let A;e[39]!==d||e[40]!==z||e[41]!==q||e[42]!==H||e[43]!==W?(A=s.jsxs(ee,{variant:"outline",size:"sm",onClick:d,disabled:z,type:"button","aria-label":q,className:"commit-actions__btn",children:[H,W]}),e[39]=d,e[40]=z,e[41]=q,e[42]=H,e[43]=W,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 E;e[46]!==x?(E=x("gitView.commit.commitAria"),e[46]=x,e[47]=E):E=e[47];let P;e[48]!==g||e[49]!==x?(P=g==="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]=g,e[49]=x,e[50]=P):P=e[50];let _;e[51]!==p||e[52]!==te||e[53]!==E||e[54]!==P?(_=s.jsx(ee,{size:"sm",variant:"outline",onClick:p,disabled:te,className:"commit-actions__btn whitespace-nowrap","aria-label":E,children:P}),e[51]=p,e[52]=te,e[53]=E,e[54]=P,e[55]=_):_=e[55];let L;e[56]!==C||e[57]!==g||e[58]!==c||e[59]!==O||e[60]!==u||e[61]!==x?(L=O?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:g==="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:g==="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]=g,e[58]=c,e[59]=O,e[60]=u,e[61]=x,e[62]=L):L=e[62];let V;e[63]!==A||e[64]!==_||e[65]!==L?(V=s.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[A,X,_,L]}),e[63]=A,e[64]=_,e[65]=L,e[66]=V):V=e[66];let Y;e[67]!==F||e[68]!==R||e[69]!==V||e[70]!==T?(Y=s.jsxs("div",{className:"flex flex-col gap-3 px-0 pt-1 pb-3",children:[T,F,R,V]}),e[67]=F,e[68]=R,e[69]=V,e[70]=T,e[71]=Y):Y=e[71];let G;return e[72]!==Y||e[73]!==B?(G=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[B,Y]}),e[72]=Y,e[73]=B,e[74]=G):G=e[74],G},eu=5e5,tN=`
|
|
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
|
+
`,sN=`
|
|
68
|
+
${tN}
|
|
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 nN(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 tu(t){const e=t.length>400?`${t.slice(0,200)}${t.slice(-200)}`:t;return`${t.length}:${nN(e)}`}const aN=(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
|
+
`)},iN=(t,e)=>t===e?!0:!t||!e?!1:t.start===e.start&&t.end===e.end&&t.side===e.side,rN=t=>t==="auto"||t==="scroll"||t==="overlay",oN=t=>{let e=t?.parentElement??null;for(;e;){const n=window.getComputedStyle(e);if(rN(n.overflowY))return e;e=e.parentElement}return null},lN=(t,e)=>{if(!t||!e||typeof window>"u")return()=>{};const n=oN(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)}},cN=(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)}},Yi=new WeakMap,dN={lineHeight:24,hunkSeparatorHeight:24,spacing:0};function uN(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 mN(t){if(typeof document>"u")return null;const e=uN(t);let n=Yi.get(e.key);if(!n){const i=new dh;i.setup(e.root,e.content),n={virtualizer:i,refs:0},Yi.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=Yi.get(e.key);i&&(i.refs-=1,!(i.refs>0)&&(i.virtualizer.cleanUp(),Yi.delete(e.key)))}}}const pN=(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)}},TS=({original:t,modified:e,fileDiff:n,language:a,fileName:i,renderSideBySide:r,wrapLines:o,layout:d="fill",enableComments:c=!0})=>{const p=jr(),u=p?.currentTheme.metadata.variant==="dark",g=p?.availableThemes.find(oe=>oe.metadata.id===p.lightThemeId)??pr(!1),m=p?.availableThemes.find(oe=>oe.metadata.id===p.darkThemeId)??pr(!0),{isMobile:w}=Hs(),h=zu({source:"diff",fileLabel:i||"unknown",language:a,getCodeForRange:oe=>aN(t,e,n,oe),toStoreRange:oe=>({startLine:oe.start,endLine:oe.end,side:oe.side==="deletions"?"original":"modified"}),fromDraftRange:oe=>({start:oe.startLine,end:oe.endLine,side:oe.side==="original"?"deletions":"additions"})}),{drafts:f,selection:x,setSelection:k,commentText:y,setCommentText:C,editingDraftId:O,saveComment:j,cancel:N,startEdit:b,deleteDraft:I}=h,B=ve.useRef(null),T=ve.useRef(null),D=ve.useRef(""),S=ve.useRef(!1),F=ve.useRef(null);ve.useEffect(()=>{B.current=x},[x]),ve.useEffect(()=>{T.current=O},[O]),ve.useEffect(()=>{D.current=y},[y]);const R=ve.useCallback(oe=>{if(!c||S.current)return;const de=B.current;if(!(!oe&&de&&D.current.trim())){if(w&&de&&oe&&oe.side===de.side){const le=Math.min(de.start,oe.start),he=Math.max(de.end,oe.end);k({...oe,start:le,end:he})}else k(oe);oe&&(T.current||C(""))}},[c,w,C,k]),z=ve.useCallback(()=>{N()},[N]),q=ve.useCallback(oe=>{const de=document.createElement("div");de.style.position="relative";const le=nr(oe.metadata);return de.dataset.annotationId=le,de.dataset.annotationSide=oe.side,de.dataset.annotationLine=String(oe.lineNumber),de},[]),H=ve.useCallback((oe,de)=>{j(oe,de??x??void 0)},[j,x]),Z=ve.useCallback(oe=>{k(oe);const de=P.current;if(de)try{S.current=!0,de.setSelectedLines(oe),F.current=oe}catch{}finally{S.current=!1}},[k]),W=ve.useCallback(oe=>{const de=oe.closest("[data-line-type]")?.getAttribute("data-line-type")??oe.getAttribute("data-line-type");if(de==="change-deletion")return"deletions";if(de==="change-addition")return"additions";const le=oe.getAttribute("data-column-side")??oe.getAttribute("data-side")??oe.closest("[data-column-side]")?.getAttribute("data-column-side");if(le==="deletions"||le==="left"||le==="original")return"deletions";if(le==="additions"||le==="right"||le==="modified")return"additions";const he=oe.closest("[data-line-type]");if(he instanceof HTMLElement){const De=he.getBoundingClientRect(),Le=oe.getBoundingClientRect(),Ke=De.left+De.width/2;return Le.left+Le.width/2<Ke?"deletions":"additions"}return"additions"},[]);dr(g),dr(m);const A=`${g.metadata.id}:${m.metadata.id}:${u?"dark":"light"}`,X=ve.useMemo(()=>{if(n){const oe=n.deletionLines.reduce((le,he)=>le+he.length,0),de=n.additionLines.reduce((le,he)=>le+he.length,0);return Math.max(oe,de)>eu}return Math.max(t.length,e.length)>eu},[n,e.length,t.length]),te=ve.useRef(null),E=ve.useRef(null),P=ve.useRef(null),_=ve.useRef(null),L=ve.useRef(null),V=ve.useRef(null),Y=ve.useRef(void 0),G=ve.useRef(void 0),me=ve.useRef(void 0),ae=ve.useRef(void 0),[,xe]=l.useReducer(oe=>oe+1,0),be=_o(X?"unified":r?"split":"unified"),ie=ve.useMemo(()=>mr(g),[g]),pe=ve.useMemo(()=>mr(m),[m]);l.useLayoutEffect(()=>{const oe=te.current;if(!oe)return;const de=oe.querySelector("diffs-container");if(!de)return;const le=u?pe:ie,he=(_e,Oe)=>_e.colors?.[Oe],De=he(ie,"terminal.ansiGreen"),Le=he(ie,"terminal.ansiRed"),Ke=he(ie,"terminal.ansiBlue"),Fe=he(pe,"terminal.ansiGreen"),Me=he(pe,"terminal.ansiRed"),Be=he(pe,"terminal.ansiBlue");de.style.setProperty("--shiki-light",ie.fg),de.style.setProperty("--shiki-light-bg",ie.bg),De&&de.style.setProperty("--shiki-light-addition-color",De),Le&&de.style.setProperty("--shiki-light-deletion-color",Le),Ke&&de.style.setProperty("--shiki-light-modified-color",Ke),de.style.setProperty("--shiki-dark",pe.fg),de.style.setProperty("--shiki-dark-bg",pe.bg),Fe&&de.style.setProperty("--shiki-dark-addition-color",Fe),Me&&de.style.setProperty("--shiki-dark-deletion-color",Me),Be&&de.style.setProperty("--shiki-dark-modified-color",Be),de.style.setProperty("--diffs-bg",le.bg),de.style.setProperty("--diffs-fg",le.fg);const Ge=u?Fe:De,Ve=u?Me:Le,Ue=u?Be:Ke;Ge&&de.style.setProperty("--diffs-addition-color-override",Ge),Ve&&de.style.setProperty("--diffs-deletion-color-override",Ve),Ue&&de.style.setProperty("--diffs-modified-color-override",Ue);const He=de.shadowRoot?.querySelector("pre");He&&(He.style.setProperty("--shiki-light",ie.fg),He.style.setProperty("--shiki-light-bg",ie.bg),De&&He.style.setProperty("--shiki-light-addition-color",De),Le&&He.style.setProperty("--shiki-light-deletion-color",Le),Ke&&He.style.setProperty("--shiki-light-modified-color",Ke),He.style.setProperty("--shiki-dark",pe.fg),He.style.setProperty("--shiki-dark-bg",pe.bg),Fe&&He.style.setProperty("--shiki-dark-addition-color",Fe),Me&&He.style.setProperty("--shiki-dark-deletion-color",Me),Be&&He.style.setProperty("--shiki-dark-modified-color",Be),He.style.setProperty("--diffs-bg",le.bg),He.style.setProperty("--diffs-fg",le.fg),Ge&&He.style.setProperty("--diffs-addition-color-override",Ge),Ve&&He.style.setProperty("--diffs-deletion-color-override",Ve),Ue&&He.style.setProperty("--diffs-modified-color-override",Ue))},[pe,A,u,ie]);const Ie=ve.useMemo(()=>({theme:{dark:m.metadata.id,light:g.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?R:void 0,unsafeCSS:sN,renderAnnotation:c?q:void 0}),[m.metadata.id,c,u,X,g.metadata.id,r,o,R,q]),re=ve.useMemo(()=>c?px({drafts:f,editingDraftId:O,selection:x}):[],[O,c,f,x]),ce=ve.useRef(re);if(ve.useEffect(()=>{ce.current=re},[re]),ve.useEffect(()=>{const oe=E.current;return()=>{P.current?.cleanUp(),P.current=null,_.current?.release(),_.current=null,L.current=null,V.current=null,Y.current=void 0,G.current=void 0,me.current=void 0,ae.current=void 0,oe&&(oe.innerHTML="")}},[]),ve.useEffect(()=>{if(typeof window>"u")return;const oe=E.current,de=te.current;if(!oe||!be)return;const le=lN(de,oe);let he=_.current;he||(he=mN(oe),_.current=he),_.current=he;const De=he?.virtualizer??null,Le=n?void 0:{name:i||"",contents:t,lang:a,cacheKey:`old:${A}:${i}:${tu(t)}`},Ke=n?void 0:{name:i||"",contents:e,lang:a,cacheKey:`new:${A}:${i}:${tu(e)}`},Fe=n?G.current!==n:G.current!==void 0||!Le||!Ke||!me.current||!ae.current||!nc(me.current,Le)||!nc(ae.current,Ke),Me=P.current,Be=!!(Me&&(L.current!==De||V.current!==be||De&&(Y.current!==Ie.hunkSeparators||Fe)));Be&&(Me?.cleanUp(),P.current=null,oe.innerHTML="");let Ge=P.current;const Ve=!Be&&Me?!oh(Me.options,Ie):!1;if(Ge?Ge.setOptions(Ie):(Ge=he?new lh(Ie,he.virtualizer,dN,be):new ch(Ie,be),P.current=Ge,F.current=null),L.current=De,V.current=be,Y.current=De?Ie.hunkSeparators:void 0,G.current=n,me.current=Le,ae.current=Ke,n)Ge.render({fileDiff:n,forceRender:Ve,lineAnnotations:ce.current,containerWrapper:oe});else{if(!Le||!Ke)return;Ge.render({oldFile:Le,newFile:Ke,forceRender:Ve,lineAnnotations:ce.current,containerWrapper:oe})}const Ue=cN(oe,()=>{le(),pN(Ge,he,xe)});return()=>{Ue(),le()}},[A,n,i,a,e,Ie,t,be]),ve.useEffect(()=>{const oe=P.current;if(oe){try{oe.setLineAnnotations(re)}catch(de){console.error("Failed to apply diff line annotations",de);try{oe.setLineAnnotations([])}catch{}}requestAnimationFrame(()=>{if(P.current===oe){try{oe.rerender()}catch{}xe()}})}},[re]),ve.useEffect(()=>{const oe=P.current;if(!oe||x!==null)return;const de=F.current;if(!iN(x,de))try{S.current=!0,oe.setSelectedLines(x),F.current=x}catch{}finally{S.current=!1}},[x]),ve.useEffect(()=>{if(!c)return;const oe=E.current;if(!oe)return;let de=null,le=()=>{};const he=()=>{const Le=oe.querySelector("diffs-container")?.shadowRoot;if(!Le){de=requestAnimationFrame(he);return}const Ke=Fe=>{if(!(Fe instanceof MouseEvent)||Fe.button!==0||!(Fe.target instanceof Element))return;const Me=Fe.target.closest("[data-column-number]");if(!(Me instanceof HTMLElement))return;const Be=Me.getAttribute("data-column-number"),Ge=Be?parseInt(Be,10):NaN;if(Number.isNaN(Ge))return;const Ve=W(Me);R({start:Ge,end:Ge,side:Ve}),Fe.preventDefault(),Fe.stopPropagation()};Le.addEventListener("click",Ke,!0),le=()=>{Le.removeEventListener("click",Ke,!0)}};return he(),()=>{de!==null&&cancelAnimationFrame(de),le()}},[A,c,i,R,W]),ve.useEffect(()=>{const oe=E.current;if(!oe)return;let de=null,le=null;const De=setTimeout(()=>{const Le=oe.querySelector("diffs-container");if(!(Le instanceof HTMLElement))return;const Ke=Le.shadowRoot;de=new MutationObserver(()=>{le&&cancelAnimationFrame(le),le=requestAnimationFrame(()=>{xe(),le=null})}),de.observe(Le,{childList:!0,subtree:!0}),Ke&&de.observe(Ke,{childList:!0,subtree:!0})},100);return()=>{clearTimeout(De),le&&cancelAnimationFrame(le),de?.disconnect()}},[A,i]),typeof window>"u")return null;const ge=c?s.jsx(fx,{diffRootRef:te,drafts:f,selection:x,editingDraftId:O,commentText:y,onTextChange:C,fileLabel:i?.split("/").pop()??"",onSave:H,onCancel:z,onEdit:oe=>{Z({start:oe.startLine,end:oe.endLine,side:oe.side==="original"?"deletions":"additions"}),b(oe)},onDelete:I}):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(zs,{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:E,className:"size-full"})})}),ge]})}):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:E,className:"w-full"})}),ge]})},gN=9e4,fN=15e3,hN=5*6e4,xN=[2e3,5e3],bN=6e4,yN=2*6e4,vN=5*6e4,wN=4,su=720*6e4,jN="openchamber.github-pr-status",yr=200,kN=t=>t==="closed"||t==="merged",NN=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},SN=t=>NN(t)?bN:t?.checks&&t.checks.state!=="pending"?vN:yN,CN=(t,e,n)=>JSON.stringify([pn(),t,e,n??"auto"]),Da=new Map,Ra=new Map,un=new Map,Eo=new Map;let Qi=0;const IN=2;let vr=0;const Rm=[],PN=()=>vr<IN?(vr+=1,Promise.resolve()):new Promise(t=>{Rm.push(t)}),TN=()=>{const t=Rm.shift();if(t){t();return}vr=Math.max(0,vr-1)},Oa=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null,paramsRevision:0}),wr=t=>t?.params?.directory&&t.params.branch?{directory:t.params.directory,branch:t.params.branch,runtimeKey:t.params.runtimeKey??t.identity?.runtimeKey??pn(),remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null}:!t?.identity?.directory||!t.identity.branch?null:t.identity,kl=t=>{const e=wr(t);return!e?.directory||!e.branch?null:JSON.stringify([e.runtimeKey,e.directory,e.branch,e.remoteName??"auto"])},rl=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}},AN=(t,e)=>{const n=rl(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=rl(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},AS=(t,e,n)=>{const a=pn();let i=null;for(const[r,o]of Object.entries(t)){if(!o.status)continue;const d=rl(r);!d||d.runtimeKey!==a||d.directory!==e||d.branch!==n||(!i||o.lastRefreshAt>i.lastRefreshAt)&&(i=o)}return i?.status??null},Mm=(t,e)=>Object.entries(t).filter(([,n])=>kl(n)===e).map(([n])=>n),EN=(t,e)=>{const n=e.runtimeKey??pn(),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}}},Xi=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},DN=(t,e,n)=>{const a=Mm(t,e),i=a.map(c=>Xi(t[c])).filter(c=>!!c);if(i.length===0)return null;const r=Xi(t[n]);if(r&&kl(t[n])===e)return r;const o=a.map(c=>t[c]).find(c=>!!(c?.resolvedRemoteName&&Xi(c)));if(o)return Xi(o);const d=i.find(c=>!!c.remoteName);return d||(i[0]??null)},RN=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:wr(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),MN=t=>({...Oa(),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}),LN=t=>{const e=Object.entries(t);return e.length<=yr?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,yr))},Lm=fn()(vi((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,resetForRuntimeSwitch:()=>{Qi+=1;for(const n of Da.values())window.clearInterval(n);for(const n of Ra.values())n.forEach(a=>window.clearTimeout(a));Da.clear(),Ra.clear(),un.clear(),Eo.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=AN(a.entries,n),r=i?{...Oa(),status:i.status,isInitialStatusResolved:!0,resolvedRemoteName:i.resolvedRemoteName??i.status?.resolvedRemoteName??null}:Oa();return{entries:LN({...a.entries,[n]:r})}})},setParams:(n,a)=>{t(i=>{const r=i.entries[n]??Oa();return{entries:{...i.entries,[n]:EN(r,a)}}})},startWatching:n=>{if(t(r=>{const o=r.entries[n]??Oa();return{entries:{...r.entries,[n]:{...o,watchers:o.watchers+1}}}}),Da.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=Ra.get(n)??[];d.push(o),Ra.set(n,d)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),xN.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<hN)return;t(u=>{const g=u.entries[n];return g?{entries:{...u.entries,[n]:{...g,lastDiscoveryPollAt:p}}}:u}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(kN(r.status?.pr?.state))return;const d=Date.now()-r.lastRefreshAt,c=SN(r.status);d<c||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},fN);Da.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=Da.get(n);typeof i=="number"&&window.clearInterval(i),Da.delete(n);const r=Ra.get(n);r&&r.length>0&&r.forEach(o=>{window.clearTimeout(o)}),Ra.delete(n)},refresh:async(n,a)=>{const i=e(),r=i.entries[n],o=kl(r);if(!r||!o)return;const d=Mm(i.entries,o),c=d.some(x=>!!i.entries[x]?.status?.pr);if(a?.onlyExistingPr&&!c)return;const p=Eo.get(o)??0;if(!a?.force&&Date.now()-p<gN||un.has(o))return;const u=DN(i.entries,o,n);if(!u)return;const g=Symbol(o),m=Qi,w=r.paramsRevision,h=r.params?.runtimeKey??r.identity?.runtimeKey??pn(),f=()=>m===Qi&&h===pn()&&un.get(o)===g&&e().entries[n]?.paramsRevision===w;if(un.set(o,g),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(!f())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}}),un.get(o)===g&&un.delete(o);return}if(!u.github?.prStatus){if(!f())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}}),un.get(o)===g&&un.delete(o);return}try{t(k=>({...k,activeRequestCount:k.activeRequestCount+1,totalRequestCount:k.totalRequestCount+1})),await PN();let x;try{if(!f())return;Eo.set(o,Date.now()),x=await u.github.prStatus(u.directory,u.branch,u.remoteName??void 0,{force:a?.force})}finally{TN()}if(!f())return;t(k=>{const y={...k.entries};return d.forEach(C=>{const O=y[C];if(!O)return;const j=O.status?.fetchedAt,N=x.fetchedAt;if(typeof j=="number"&&typeof N=="number"&&N<j){y[C]={...O,error:null,isLoading:a?.silent?O.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?O.isInitialStatusResolved:!0,lastRefreshAt:Date.now()};return}const b=O.status?.pr,I=x.pr,T=!!(I&&b&&I.number===b.number&&(!I.body||!I.body.trim())&&typeof b.body=="string"&&b.body.trim().length>0)&&I&&b?.body?{...x,pr:{...I,body:b.body}}:x,D=T.resolvedRemoteName??O.resolvedRemoteName??u.remoteName??null,S=wr(O)??{runtimeKey:h,directory:u.directory,branch:u.branch,remoteName:u.remoteName??null};y[C]={...O,status:T,error:null,isLoading:a?.silent?O.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?O.isInitialStatusResolved:!0,lastRefreshAt:Date.now(),resolvedRemoteName:D,identity:{...S,remoteName:D??S.remoteName??null}}}),{entries:y}})}catch(x){if(!f())return;const k=x instanceof Error?x.message:String(x);t(y=>{const C={...y.entries};return d.forEach(O=>{const j=C[O];j&&(C[O]={...j,error:k||"Failed to load PR status",isLoading:a?.silent?j.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?j.isInitialStatusResolved:!0})}),{entries:C}})}finally{un.get(o)===g&&un.delete(o),m===Qi&&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:CN(o,d,r.remoteName??null)}).filter(r=>!!r)));await Ig(i,wN,r=>e().refresh(r,a))},updateStatus:(n,a)=>{t(i=>{const r=i.entries[n]??Oa();return{entries:{...i.entries,[n]:{...r,status:a(r.status)}}}})}}),{name:jN,storage:Pr(),version:2,migrate:(t,e)=>e<2?{entries:{}}:t,partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=wr(e);if(!n?.directory||!n.branch)return!1;const a=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return a>0&&Date.now()-a<su}).sort(([,e],[,n])=>Math.max(n.lastRefreshAt,n.lastDiscoveryPollAt)-Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt)).slice(0,yr).map(([e,n])=>[e,RN(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)<su)).slice(0,yr).map(([i,r])=>[i,MN(r)]))}}})),FN=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"},ON=t=>{const e=FN(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}},zN=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??""}`,KN=300,Ma=new Map,ES=t=>{const e=Ze.c(2);let n;return e[0]!==t?(n=a=>{if(!t)return null;const i=a.entries[t],r=i?ON(i):null;if(!r)return Ma.delete(t),null;const o=zN(r),d=Ma.get(t);if(d&&d.sig===o)return d.summary;if(!d&&Ma.size>=KN){const c=Ma.keys().next().value;c!==void 0&&Ma.delete(c)}return Ma.set(t,{sig:o,summary:r}),r},e[0]=t,e[1]=n):n=e[1],Lm(n)},DS=()=>{vu(),Ps.reconnectToRuntimeBaseUrl(),hu()},RS=t=>{es.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),je.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),t.previousRuntimeKey&&Pg.getState().stopRunningRunsForRuntime(t.previousRuntimeKey),vu(),ss.getState().clearAll(),Ps.reconnectToRuntimeBaseUrl(),pt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),is.getState().resetForRuntimeSwitch(),Lo.getState().resetForRuntimeSwitch(),Tg.setState({statusById:new Map}),Ag(),Eg.getState().reset(),pf.getState().resetForRuntimeSwitch(),Sr.getState().resetForRuntimeSwitch(t.runtimeKey),Lm.getState().resetForRuntimeSwitch(),Dg.getState().resetForRuntimeSwitch(t.runtimeKey),gf.getState().resetForRuntimeSwitch(t.runtimeKey),es.getState().restoreForRuntimeSwitch(t.runtimeKey),je.getState().restoreForRuntimeSwitch(t.runtimeKey),hu(),queueMicrotask(()=>{ff()})};export{qn as $,Lu as A,b1 as B,IS as C,jS as D,da as E,ua as F,ma as G,xS as H,Hw as I,Ww as J,mc as K,Vs as L,Jj as M,kS as N,dS as O,TS as P,Yn as Q,Lm as R,$k as S,CS as T,x1 as U,AS as V,wS as W,CN as X,Jn as Y,pS as Z,An as _,Jt as a,Gn as a0,vm as a1,jm as a2,Hv as a3,ES as a4,Av as a5,yo as a6,t0 as a7,$1 as a8,cS as a9,Ub as aa,Wu as ab,Uo as ac,Bb as ad,zu as ae,Vo as af,Ho as ag,Bu as ah,mx as ai,$o as aj,Fu as ak,bS as al,Yw as b,PS as c,pa as d,SS as e,ws as f,fd as g,$a as h,NS as i,RS as j,vS as k,yS as l,uS as m,mS as n,gS as o,ik as p,lS as q,DS as r,Ss as s,ss as t,Ru as u,Dv as v,Ev as w,fS as x,hS as y,Zu as z};
|