@openchamber/web 1.17.0 → 1.17.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/README.md +3 -0
- package/dist/assets/{DiagramView-CRjw8BGO.js → DiagramView-CI2JhNxs.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-BjjFniUt.js → MarkdownRendererImpl-Bq-wtyiF.js} +3 -3
- package/dist/assets/{OnboardingScreen-JuiKjRTI.js → OnboardingScreen-B6BqjJ0l.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-S2EvRz-E.js → SessionSwitcherDropdown-DepVWyeA.js} +1 -1
- package/dist/assets/{SettingsWindow-PzqMjCEx.js → SettingsWindow-Xj4Uy_Fr.js} +1 -1
- package/dist/assets/{document-attachments-DZf4VoiD.js → document-attachments-C5tUWELq.js} +1 -1
- package/dist/assets/{es-CErIcckI.js → es-DSTFcl6A.js} +1 -1
- package/dist/assets/{fr-z5ORYrou.js → fr-CEeK5ifb.js} +1 -1
- package/dist/assets/index-DUBtXIPQ.css +1 -0
- package/dist/assets/{index-DMCrPMIW.js → index-Dld5wFqI.js} +3 -3
- package/dist/assets/{ja-ecPbYMn0.js → ja-pu3u7ZOY.js} +1 -1
- package/dist/assets/{ko-CASkpaQH.js → ko-CStr_CJ-.js} +1 -1
- package/dist/assets/{main-BTLr2DyB.js → main-DBG0rE6P.js} +36 -36
- package/dist/assets/{main-DQ-uX_zf.js → main-Xc2GeALp.js} +2 -2
- package/dist/assets/{markdownCore-C4XTgyYU.js → markdownCore-Bn8Ywh-t.js} +2 -2
- package/dist/assets/miniChat-D5FFElbH.js +2 -0
- package/dist/assets/mobile-B4K4IpE7.js +2 -0
- package/dist/assets/{pl-BYtGQyDI.js → pl-nD08d1Bo.js} +1 -1
- package/dist/assets/{pt-BR-D8dONk68.js → pt-BR-DqcoQ-nE.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-Cbdusroc.js → renderElectronMiniChatApp-B-rksap7.js} +2 -2
- package/dist/assets/renderMobileApp-U-jxDI_G.js +16 -0
- package/dist/assets/runtimeEndpointReset-fpfBYOyW.js +174 -0
- package/dist/assets/{uk-C8z1P8tg.js → uk-DkX7DsWk.js} +1 -1
- package/dist/assets/{useAppFontEffects-DrLhDSC3.js → useAppFontEffects-CZdEKvZ8.js} +129 -127
- package/dist/assets/{vendor-.bun-DvcSrJLa.js → vendor-.bun-BzW0Lgld.js} +1 -1
- package/dist/assets/{zh-CN-BwJPtjKq.js → zh-CN-DlqHNM1o.js} +1 -1
- package/dist/assets/{zh-TW-C7FpgD-Y.js → zh-TW-DeKAHBhV.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +31 -2
- package/server/lib/openchamber-sessions/routes.js +30 -30
- package/server/lib/openchamber-sessions/routes.test.js +38 -0
- package/server/lib/opencode/DOCUMENTATION.md +7 -2
- package/server/lib/opencode/env-runtime.js +18 -0
- package/server/lib/opencode/env-runtime.test.js +12 -0
- package/server/lib/opencode/feature-routes-runtime.js +2 -0
- package/server/lib/opencode/lifecycle.js +18 -6
- package/server/lib/opencode/lifecycle.test.js +67 -1
- package/server/lib/opencode/proxy.js +32 -2
- package/server/lib/opencode/routes-upgrade.test.js +113 -0
- package/server/lib/opencode/routes.js +69 -36
- package/server/lib/opencode/server-utils-runtime.js +2 -0
- package/server/lib/opencode/settings-helpers.js +3 -0
- package/server/lib/opencode/settings-helpers.test.js +8 -0
- package/server/lib/opencode/upgrade-capability.js +36 -0
- package/server/lib/opencode/upgrade-capability.test.js +57 -0
- package/server/lib/quota/providers/codex.js +18 -0
- package/server/lib/quota/providers/codex.test.js +28 -0
- package/server/lib/scheduled-tasks/runtime.js +44 -18
- package/server/lib/scheduled-tasks/runtime.test.js +12 -1
- package/server/lib/session-goal/DOCUMENTATION.md +12 -3
- package/server/lib/system-prompt/DOCUMENTATION.md +36 -0
- package/server/lib/system-prompt/runtime.js +68 -0
- package/server/lib/system-prompt/runtime.test.js +76 -0
- package/server/opencode-proxy.test.js +49 -0
- package/dist/assets/index-Csh1A7Eh.css +0 -1
- package/dist/assets/miniChat-ComIlrTa.js +0 -2
- package/dist/assets/mobile-DUYXEkKA.js +0 -2
- package/dist/assets/renderMobileApp-m9MPmIZT.js +0 -16
- package/dist/assets/runtimeEndpointReset-B0yQKPe0.js +0 -174
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import{an as Ou,b as Ye,ao as zu,j as s,r as ge,ap as Bu,aq as Ku,a as cn,d as Da,p as ii,R as l,L as zs,ad as Uu,ae as _u,ac as $u,af as Vu,aa as Hu,ab as Wu,ag as Gu,ar as qu,as as Ju,at as Qu,u as Yu,l as Xu,n as Zu,w as em,C as tm,S as sm,au as nm,a8 as am,D as im,q as rm,av as om,aw as lm,ax as cm,ay as dm,az as um,Y as nn,aA as mm,aB as ra,aC as Ho,aD as pm,aE as gm,aF as Cr,aG as fm,aH as hm,aI as xm,aJ as Wo,aK as Ji,aL as Go,k as Ki,aM as hd,aN as Ro,aO as nr,aP as xd,aQ as qo,aR as bm,aS as ym,aT as vm,aU as wm,aV as Jo,aW as Re,aX as vi,aY as jm,aZ as km,a_ as Nm,a$ as Sm,b0 as Cm,b1 as bd,b2 as Im,b3 as Pm,b4 as Am,_ as Qo,b5 as Em,a9 as Tm,b6 as Yo,b7 as Rm,b8 as Dm,b9 as Mm,ba as Lm}from"./vendor-.bun-BzW0Lgld.js";import{e0 as ar,E as Qi,y as le,e1 as Ui,e2 as _i,e3 as $i,b as rs,f as it,I as L,aN as Ps,aO as As,aP as Ds,Z as Do,aw as Fm,g as yd,o as In,bb as Lt,ba as Ft,b9 as zt,by as Bs,G as oo,B as Q,bn as Mo,C as Zn,bO as lo,b6 as Pn,e4 as ir,aL as _s,t as G,a6 as vd,e5 as ea,e6 as Om,e7 as zm,dQ as Bm,e8 as Km,e9 as Um,ea as _m,K as ds,eb as $m,df as Vm,dg as Hm,dh as Wm,bw as Gm,aH as ys,aJ as vs,bx as qm,aK as ws,b2 as ri,ec as Jm,ed as Na,b8 as Ut,bH as qt,bI as Zt,z as tt,ee as si,aG as bs,ef as Xo,a0 as pt,c8 as At,c9 as Et,ca as Vt,cb as Tt,cc as yt,bm as js,b3 as ni,eg as Kn,dx as Cs,eh as Qm,ei as wd,ej as Ym,ek as Xm,el as rr,em as Nn,en as Ia,b5 as jd,eo as Zm,ep,eq as tp,er as sp,es as np,et as ap,eu as jn,ev as ip,D as oi,bE as Zo,w as rp,bG as co,an as kd,O as op,P as Nd,Q as Sd,cp as lp,Y as el,dr as cp,dL as Cd,dA as Id,dC as dp,ew as up,u as uo,cJ as mp,ex as tl,ey as pp,ez as gp,eA as sl,eB as fp,eC as hp,eD as xp,eE as bp,aM as yp,eF as vp,R as wp,T as jp,h as li,eG as kp,eH as Np,c0 as Sp,as as Pa,ar as Pd,aq as Cp,eI as Ip,eJ as nl,at as Pp,au as Ap,ap as Ep,aR as Tp,aS as Rp,aT as Ad,eK as Ir,eL as al,eM as Dp,eN as Mp,eO as Lp,eP as Fp,dD as or,a1 as kn,eQ as Op,eR as zp,eS as Bp,eT as Kp,eU as Up,eV as Pr,eW as il,eX as _p,eY as $p,eZ as Vp,e_ as Hp,e$ as Wp,f0 as Ar,f1 as Gp,a$ as rl,f2 as va,a_ as qp,f3 as Jp,f4 as ol,f5 as ll,bJ as Qp,a8 as Mn,_ as Yp,i as Ed,cn as Qa,d$ as Td,F as Xp,S as Zp,f6 as eg,f7 as tg,f8 as cl,bP as mo,bQ as po,bR as go,bS as fo,bT as wn,bU as Xs,ce as Sa,N as Za,f9 as dl,bz as sg,fa as Rd,cg as ng,dH as ag,m as Dd,fb as Er,am as ig,bg as wi,ck as rg,fc as og,fd as lg,dB as cg,fe as dg,ff as ug,cL as mg,fg as Md,dZ as pg,dm as gg,fh as fg,fi as hg,cO as xg}from"./useAppFontEffects-CZdEKvZ8.js";import{d as Yi,ah as lr,r as gt,o as Is,e as Ls,ai as bg,aj as ul,ak as yg,al as vg,G as os,_ as Sn,u as Ne,x as Ma,m as Lo,a as on,b as ml,v as kt,am as wg,an as pl,ao as Hs,f as La,k as ln,w as ss,H as gl,ap as fl,aq as hl,K as Ba,p as jg,ar as kg,j as Ng,as as wa,at as Sg,J as Cg,au as Ig,av as Pg,aw as Ag,s as Eg,ax as Tg,ay as Ld,R as Rg,az as Dg,Q as Mg,aA as xl,aB as Lg,aC as Fg,L as Og,aD as bl,aE as yl,aF as vl,aG as ei,aH as zg,aI as Bg,aJ as wl,P as Fd,aK as Kg,aL as Ug,aM as _g,aN as $g,aO as Vg,aP as Hg,ag as Wg,a6 as Gg,aQ as Ka,aR as qg,aS as Jg,aT as Qg,aU as Od,S as Yg,T as Xg,q as Zg}from"./index-Dld5wFqI.js";import{g as ef,s as tf}from"./mobileLayoutPreference-Dio-WWkI.js";function sf(){return new Worker(Ou,{type:"module"})}const nf=["typescript","javascript","tsx","jsx","json","markdown"],ho={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let jl,kl;const Nl=t=>{const e=ho[t],n=new zu({workerFactory:sf,poolSize:e.poolSize,totalASTLRUCacheSize:e.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:nf,lineDiffType:e.lineDiffType,preferredHighlighter:"shiki-wasm"});return n.initialize(),n},af=t=>{if(!(typeof window>"u"))return t==="split"?(kl??=Nl("split"),kl):(jl??=Nl("unified"),jl)},rf=t=>{const e=Ye.c(7),{children:n,renderTheme:a}=t,i=xo("unified"),r=xo("split");let o,d;e[0]!==a||e[1]!==r||e[2]!==i?(o=()=>{i&&i.setRenderOptions({theme:a,lineDiffType:ho.unified.lineDiffType}),r&&r.setRenderOptions({theme:a,lineDiffType:ho.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]),ge.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},Bk=t=>{const e=Ye.c(11),{children:n}=t,a=ar();let i,r;if(e[0]!==a?.availableThemes||e[1]!==a?.darkThemeId||e[2]!==a?.lightThemeId){const p=Yi(!1),u=Yi(!0),f=a?.lightThemeId??p.metadata.id,m=a?.darkThemeId??u.metadata.id;r=a?.availableThemes.find(b=>b.metadata.id===f)??p,i=a?.availableThemes.find(b=>b.metadata.id===m)??u,Qi(r),Qi(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(rf,{renderTheme:d,children:n}),e[8]=n,e[9]=d,e[10]=c):c=e[10],c},xo=t=>{const e=Ye.c(2),n=t===void 0?"unified":t;let a;return e[0]!==n?(a=af(n),e[0]=n,e[1]=a):a=e[1],a};function of(t){const e=Ye.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 Xi=ge.forwardRef((t,e)=>{const n=Ye.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=le("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(Bu,{className:le("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(Ku,{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});Xi.displayName="Switch";const ji=()=>{try{const e=rs.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=Is.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[McpConfigStore] Error resolving config directory:",t)}return null},Sl=t=>t?Object.entries(t).map(([e,n])=>({key:e,value:n})):[],Cl=t=>{const e=t.filter(n=>n.key.trim());if(e.length!==0)return Object.fromEntries(e.map(n=>[n.key.trim(),n.value]))},ki=t=>typeof t!="string"?void 0:t.trim()||void 0,Tr=800,lf=5e3,cf="__default__",bo=new Map,Rr=new Map,zd=t=>t?.trim()||cf,Dr=t=>{bo.delete(zd(t))},Ta=cn()(Da(ii((t,e)=>({mcpServers:[],selectedMcpName:null,isLoading:!1,mcpDraft:null,setSelectedMcp:n=>t({selectedMcpName:n}),setMcpDraft:n=>t({mcpDraft:n}),loadMcpConfigs:async n=>{const a=ji(),i=zd(a),r=Date.now(),o=bo.get(i)??0,d=e().mcpServers.length>0;if(!n?.force&&d&&r-o<lf)return!0;const c=Rr.get(i);if(!n?.force&&c)return c;const p=(async()=>{t({isLoading:!0});try{const u=a?`?directory=${encodeURIComponent(a)}`:"",f=await gt(`/api/config/mcp${u}`,{headers:a?{"x-opencode-directory":a}:void 0});if(!f.ok)throw new Error("Failed to load MCP configs");const m=await f.json();return t({mcpServers:m,isLoading:!1}),bo.set(i,Date.now()),!0}catch(u){return console.error("[McpConfigStore] Failed to load MCP configs:",u),t({isLoading:!1}),!1}})();Rr.set(i,p);try{return await p}finally{Rr.delete(i)}},createMcp:async n=>{Ui("Creating MCP server configuration…");let a=!1;try{const i=Il(n),r=ji(),o=r?`?directory=${encodeURIComponent(r)}`:"",d=await gt(`/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 Dr(r),c?.requiresReload?(a=!0,await _i({message:c.message,delayMs:c.reloadDelayMs??Tr,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||$i()}},updateMcp:async(n,a)=>{Ui("Updating MCP server configuration…");let i=!1;try{const r=Il(a),o=ji(),d=o?`?directory=${encodeURIComponent(o)}`:"",c=await gt(`/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 Dr(o),p?.requiresReload?(i=!0,await _i({message:p.message,delayMs:p.reloadDelayMs??Tr,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||$i()}},deleteMcp:async n=>{Ui("Deleting MCP server configuration…");let a=!1;try{const i=ji(),r=i?`?directory=${encodeURIComponent(i)}`:"",o=await gt(`/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 Dr(i),d?.requiresReload&&(a=!0,await _i({message:d.message,delayMs:d.reloadDelayMs??Tr,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||$i()}},getMcpByName:n=>e().mcpServers.find(a=>a.name===n)}),{name:"mcp-config-store",storage:lr(),partialize:t=>({selectedMcpName:t.selectedMcpName})}),{name:"mcp-config-store"}));function Il(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=Cl(t.environment)??{}),t.headers!==void 0&&(e.headers=Cl(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:ki(t.oauthClientId),clientSecret:ki(t.oauthClientSecret),scope:ki(t.oauthScope),redirectUri:ki(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 df={},uf={},vn=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},ga=t=>vn(t)??"__global__",Jn=t=>{const e=vn(t);return e?Is.getScopedApiClient(e):Is.getApiClient()},gs=cn()(Da((t,e)=>({byDirectory:{},diagnosticsByDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:n=>{const a=ga(n??Ls.getState().currentDirectory);return e().byDirectory[a]??df},getDiagnosticForDirectory:n=>{const a=ga(n??Ls.getState().currentDirectory);return e().diagnosticsByDirectory[a]??uf},getErrorForDirectory:n=>{const a=ga(n??Ls.getState().currentDirectory);return e().lastErrorKeys[a]??null},refresh:async n=>{const a=vn(n?.directory??Ls.getState().currentDirectory),i=ga(a);n?.silent||t(r=>({loadingKeys:{...r.loadingKeys,[i]:!0},lastErrorKeys:{...r.lastErrorKeys,[i]:null}}));try{const d=(await Jn(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=vn(a??Ls.getState().currentDirectory),r=ga(i),o=Jn(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=vn(a??Ls.getState().currentDirectory);await Jn(i).mcp.disconnect({name:n},{throwOnError:!0}),await e().refresh({directory:i,silent:!0})},startAuth:async(n,a)=>{const i=vn(a??Ls.getState().currentDirectory),d=(await Jn(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=vn(i??Ls.getState().currentDirectory);await Jn(r).mcp.auth.callback({name:n,code:a},{throwOnError:!0}),await e().refresh({directory:r,silent:!0})},clearAuth:async(n,a)=>{const i=vn(a??Ls.getState().currentDirectory);await Jn(i).mcp.auth.remove({name:n},{throwOnError:!0}),await e().refresh({directory:i,silent:!0})},testConnection:async(n,a)=>{const i=vn(a??Ls.getState().currentDirectory),r=ga(i),o=Jn(i),c=e().getStatusForDirectory(i)[n]?.status==="connected";let p,u;try{await o.mcp.connect({name:n},{throwOnError:!0})}catch(b){p=b instanceof Error?b.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 f=e().getStatusForDirectory(i)[n],m=f;if(!c&&f?.status==="connected"){try{await o.mcp.disconnect({name:n},{throwOnError:!0})}catch(b){u=`Connection test succeeded, but cleanup disconnect failed: ${b instanceof Error?b.message:"Disconnect failed"}`}await e().refresh({directory:i,silent:!0})}return{status:m??e().getStatusForDirectory(i)[n],error:p,warning:u}}}))),mf=(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}},pf=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Kk=({active:t,className:e,headerAction:n,listClassName:a,hideHeader:i=!1,mobileListDensity:r=!1})=>{const{t:o}=it(),c=Ls(w=>w.currentDirectory)??null,p=gs(w=>w.getStatusForDirectory(c)),u=gs(w=>w.refresh),f=gs(w=>w.connect),m=gs(w=>w.disconnect),b=Ta(w=>w.mcpServers),h=Ta(w=>w.loadMcpConfigs),[g,x]=l.useState(!1),[v,N]=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 P=l.useMemo(()=>{const w=new Set(Object.keys(p));for(const j of b)j?.name&&w.add(j.name);return Array.from(w).sort((j,y)=>j.localeCompare(y))},[b,p]),F=l.useCallback(w=>{if(w?.preventDefault(),g)return;x(!0);const j=new Promise(y=>setTimeout(y,500));Promise.all([u({directory:c}),j]).finally(()=>{x(!1)})},[g,u,c]);return s.jsxs("div",{className:le("w-full",e),children:[i?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)]",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-2.5",children:[s.jsxs("div",{className:"min-w-0 flex items-baseline gap-2",children:[s.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:o("mcpDropdown.title")}),c&&s.jsx("div",{className:"truncate typography-micro text-muted-foreground",children:c.split("/").pop()||c})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n,s.jsx("button",{type:"button",className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",disabled:g,onClick:F,"aria-label":o("mcpDropdown.actions.refreshAria"),children:s.jsx(L,{name:"refresh",className:le("h-4 w-4",g&&"animate-spin")})})]})]})}),s.jsx("div",{className:le("max-h-64 overflow-y-auto",r?"space-y-1 py-3":"px-3 py-2.5",a),children:s.jsxs("div",{className:le(!r&&P.length>0&&"rounded-xl bg-[var(--surface-muted)] p-1.5"),children:[P.map(w=>{const j=p[w],y=pf(j),R=j?.status==="connected",_=v===w,B=mf(j,o);return s.jsxs("div",{className:le("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(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx("span",{className:le("rounded-full flex-shrink-0",r?"h-2.5 w-2.5":"h-2 w-2",y==="success"&&"bg-status-success",y==="error"&&"bg-status-error",y==="warning"&&"bg-status-warning",y==="default"&&"bg-muted-foreground/40"),"aria-label":B})}),s.jsx(Ds,{side:"left",children:s.jsx("p",{children:B})})]}),s.jsx("span",{className:le("truncate",r?"text-[17px] leading-6 font-medium":"typography-ui-label"),children:w})]})}),s.jsx(Xi,{checked:R,disabled:_,className:"data-[checked]:bg-status-info",onCheckedChange:async D=>{N(w);try{D?await f(w,c):await m(w,c)}finally{N(null)}}})]},w)}),P.length===0&&s.jsx("div",{className:"px-4 py-5 typography-ui-label text-muted-foreground text-center",children:o("mcpDropdown.empty.configureInConfig")})]})})]})},Pl="openchamber.update-install-id";function gf(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const t=window.localStorage.getItem(Pl)?.trim();if(t)return t;const e=crypto.randomUUID();return window.localStorage.setItem(Pl,e),e}catch{return}}function ff(){if(typeof window>"u")return"unknown";try{const{deviceType:t}=Fm();return t}catch{return"unknown"}}function hf(){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 xf(){const t=yd();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 bf(t){const e=Ne.getState().reportUsage,n=new URLSearchParams({reportUsage:e?"true":"false"});if(n.set("deviceClass",ff()),n.set("arch",hf()),n.set("platform",xf()),e&&(t==="desktop"||t==="mobile")){const a=gf();a&&n.set("installId",a)}return t==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",Ma()?"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 Ni(t,e){try{const n=bf(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 gt(`/api/openchamber/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"}});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 yf(){return Do()?"mobile":vg()?"desktop":os()?"vscode":Sn()?"web":null}const Al={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Bd=cn()((t,e)=>({...Al,checkForUpdates:async()=>{const n=yf();if(!n)return null;t({checking:!0,error:null,runtimeType:n});try{let a=null,i=null;if(n==="desktop"){const r="1.17.1",[o,d]=await Promise.allSettled([ul(),Ni("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 Ni("web"),i=a?.nextSuggestedCheckInSec??null):n==="vscode"?i=(await Ni("vscode"))?.nextSuggestedCheckInSec??null:n==="mobile"&&(a=await Ni("mobile","1.17.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 ul();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 yg(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 bg())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(Al)}})),El="https://github.com/openchamber/openchamber/releases";function vf(t){const e=new Date(`${t}T00:00:00`);return Number.isNaN(e.getTime())?t:new Intl.DateTimeFormat(Mo(),{year:"numeric",month:"short",day:"numeric"}).format(e)}function wf(t){return t.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Tl(t){return t.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function jf(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 kf(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 Rl=2e3,Nf=600*1e3;async function Sf(){try{const t=await gt("/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 Cf(){try{return(await gt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function If(t,e=Math.ceil(Nf/Rl),n=Rl){for(let a=0;a<e;a++){try{const i=await gt("/api/openchamber/update-check",{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 Cf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Dl=({open:t,onOpenChange:e,info:n,downloading:a,downloaded:i,progress:r,error:o,onDownload:d,onRestart:c,runtimeType:p="desktop"})=>{const{t:u}=it(),[f,m]=ge.useState(!1),[b,h]=ge.useState("idle"),[g,x]=ge.useState(null),v=n?.version?n.releaseUrl||`${El}/tag/v${n.version}`:El,N=n?.downloadUrl||v,P=r?.total?Math.round(r.downloaded/r.total*100):0,F=p==="web",w=p==="mobile",j=n?.updateCommand||"openchamber update";ge.useEffect(()=>{t||(h("idle"),x(null))},[t]);const y=async()=>{(await Zn(j)).ok&&(m(!0),setTimeout(()=>m(!1),2e3))},R=ge.useCallback(async T=>{await In(T)},[]),_=ge.useCallback(async()=>{h("updating"),x(null);const T=await Sf();if(!T.success){h("error"),x(T.error||u("updateDialog.error.updateFailed"));return}T.autoRestart&&(h("restarting"),await new Promise(O=>setTimeout(O,2e3))),h("reconnecting"),await If(n?.currentVersion)?window.location.reload():(h("error"),x(u("updateDialog.error.takingLonger")))},[n?.currentVersion,u]),B=ge.useCallback(()=>{R(N)},[R,N]),D=b!=="idle"&&b!=="error",k=ge.useMemo(()=>{if(!n?.body)return null;const T=n.body.trim();if(!T)return null;const M=kf(T);if(M.length===0)return{kind:"raw",title:u("updateDialog.changelog.title"),content:Tl(T)};const O=[...M].sort((V,U)=>jf(V.version,U.version));return{kind:"sections",title:u("updateDialog.changelog.title"),sections:O.map(V=>({version:V.version,dateLabel:vf(V.date),content:Tl(wf(V.raw)||T)}))}},[n?.body,u]);return s.jsx(Lt,{open:t,onOpenChange:D?void 0:e,children:s.jsxs(Ft,{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(zt,{className:"flex items-center gap-2.5",children:[s.jsx(L,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:u(b==="restarting"||b==="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:[F&&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(L,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&u("updateDialog.status.installingUpdate"),b==="restarting"&&u("updateDialog.status.serverRestarting"),b==="reconnecting"&&u("updateDialog.status.waitingForServer")]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:u("updateDialog.status.autoReloadHint")})]}),k&&!D&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Bs,{className:"max-h-[400px] p-0",fillContainer:!1,children:k.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:T=>{const O=T.target.closest("a");O&&O.href&&(T.preventDefault(),T.stopPropagation(),R(O.href))},children:s.jsx(oo,{content:k.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:k.sections.map(T=>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",T.version]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:T.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:M=>{const V=M.target.closest("a");V&&V.href&&(M.preventDefault(),M.stopPropagation(),R(V.href))},children:s.jsx(oo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})})]},T.version))})})}),F&&b==="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(L,{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:j}),s.jsx("button",{onClick:y,className:le("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:u(f?"updateDialog.actions.copied":"updateDialog.actions.copyCommand"),children:f?s.jsx(L,{name:"check",className:"h-4 w-4"}):s.jsx(L,{name:"clipboard",className:"h-4 w-4"})})]})]}),!F&&!w&&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:[P,"%"]})]}),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:`${P}%`}})})]}),(o||g)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:o||g})})]}),s.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[s.jsxs("a",{href:v,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(L,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!F&&!w&&!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(L,{name:"download",className:"h-4 w-4"}),u("updateDialog.actions.downloadUpdate")]}),!F&&!w&&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(L,{name:"loader",className:"h-4 w-4 animate-spin"}),u("updateDialog.status.downloading")]}),!F&&!w&&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(L,{name:"restart",className:"h-4 w-4"}),u("updateDialog.actions.restartToUpdate")]}),w&&s.jsxs(Q,{onClick:B,size:"default",children:[s.jsx(L,{name:"external-link",className:"h-4 w-4"}),u("updateDialog.actions.openMobileUpdate")]}),F&&!D&&s.jsxs("button",{onClick:_,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[s.jsx(L,{name:"download",className:"h-4 w-4"}),u("updateDialog.actions.updateNow")]}),F&&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(L,{name:"loader",className:"h-4 w-4 animate-spin"}),u("updateDialog.status.updating")]})]})]})]})})},Ht=t=>{const e=Ye.c(22),{children:n,className:a,contentClassName:i}=t,{t:r}=it(),[o,d]=l.useState(!1),c=l.useRef(null);let p,u;e[0]!==o?(p=()=>{if(!o)return;const P=F=>{const w=c.current;w&&F.target instanceof Node&&w.contains(F.target)||d(!1)};return document.addEventListener("pointerdown",P,!0),()=>document.removeEventListener("pointerdown",P,!0)},u=[o],e[0]=o,e[1]=p,e[2]=u):(p=e[1],u=e[2]),l.useEffect(p,u);let f;e[3]!==r?(f=r("settings.common.infoAria"),e[3]=r,e[4]=f):f=e[4];let m;e[5]===Symbol.for("react.memo_cache_sentinel")?(m=P=>{P.preventDefault(),P.stopPropagation(),d(Pf)},e[5]=m):m=e[5];let b;e[6]!==a?(b=le("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]=b):b=e[7];let h;e[8]===Symbol.for("react.memo_cache_sentinel")?(h=s.jsx(L,{name:"information",className:"h-3.5 w-3.5"}),e[8]=h):h=e[8];let g;e[9]!==o||e[10]!==f||e[11]!==b?(g=s.jsx(As,{asChild:!0,children:s.jsx("button",{ref:c,type:"button","aria-label":f,"aria-expanded":o,onClick:m,className:b,children:h})}),e[9]=o,e[10]=f,e[11]=b,e[12]=g):g=e[12];let x;e[13]!==i?(x=le("max-w-sm",i),e[13]=i,e[14]=x):x=e[14];let v;e[15]!==n||e[16]!==x?(v=s.jsx(Ds,{sideOffset:8,className:x,children:n}),e[15]=n,e[16]=x,e[17]=v):v=e[17];let N;return e[18]!==o||e[19]!==g||e[20]!==v?(N=s.jsxs(Ps,{open:o,onOpenChange:d,children:[g,v]}),e[18]=o,e[19]=g,e[20]=v,e[21]=N):N=e[21],N};function Pf(t){return!t}const yn="w-full min-w-40 max-w-48",Gt="settings",Xn="w-full min-w-40 max-w-48",Ts="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",ta=le(lo(),"w-full min-w-40 max-w-48"),Ws="w-full max-w-[24rem]",Ml="min-w-0 flex-1",Ua="flex w-full min-w-0 items-center gap-2",_a="typography-meta shrink-0 text-muted-foreground tabular-nums",$a="space-y-4",Rs="space-y-1.5",yo="typography-settings-page-title text-muted-foreground",Fo="typography-settings-section-title text-foreground",dn=Fo,Af="typography-settings-group-title text-foreground",Kt="typography-settings-field-label text-foreground",Kd="typography-settings-description text-muted-foreground",rn="typography-meta text-muted-foreground",Ll="typography-meta font-medium text-foreground",Ef="typography-settings-section-title text-foreground",ot=t=>{const e=Ye.c(20),{title:n,description:a,titleAccessory:i,info:r,headerAction:o,children:d,divider:c,className:p,contentClassName:u,settingsItem:f}=t,m=c===void 0?!0:c,b=n!=null||a!=null||o!=null||r!=null,h=m?"border-t border-border/60 py-8":"pb-8";let g;e[0]!==p||e[1]!==h?(g=le("space-y-5",h,p),e[0]=p,e[1]=h,e[2]=g):g=e[2];let x;e[3]!==a||e[4]!==b||e[5]!==o||e[6]!==r||e[7]!==n||e[8]!==i?(x=b?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:Fo,children:n}):n,i,r!=null?s.jsx(Ht,{children:r}):null]}):null,a!=null?s.jsx("div",{className:Kd,children:a}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,e[3]=a,e[4]=b,e[5]=o,e[6]=r,e[7]=n,e[8]=i,e[9]=x):x=e[9];let v;e[10]!==u?(v=le(u),e[10]=u,e[11]=v):v=e[11];let N;e[12]!==d||e[13]!==v?(N=s.jsx("div",{className:v,children:d}),e[12]=d,e[13]=v,e[14]=N):N=e[14];let P;return e[15]!==f||e[16]!==g||e[17]!==x||e[18]!==N?(P=s.jsxs("section",{"data-settings-item":f,className:g,children:[x,N]}),e[15]=f,e[16]=g,e[17]=x,e[18]=N,e[19]=P):P=e[19],P},Yn=t=>{const e=Ye.c(5),{children:n,className:a}=t;let i;e[0]!==a?(i=le("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},An=t=>{const e=Ye.c(6),{children:n,className:a,as:i}=t,r=i===void 0?"h3":i;let o;e[0]!==a?(o=le(Af,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},Ys=t=>{const e=Ye.c(16),{title:n,description:a,info:i,children:r,className:o,contentClassName:d,settingsItem:c}=t;let p;e[0]!==o?(p=le("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(An,{children:n}),i!=null?s.jsx(Ht,{children:i}):null]}):null,a!=null?s.jsx("p",{className:rn,children:a}):null]}):null,e[2]=a,e[3]=i,e[4]=n,e[5]=u):u=e[5];let f;e[6]!==d?(f=le(d),e[6]=d,e[7]=f):f=e[7];let m;e[8]!==r||e[9]!==f?(m=s.jsx("div",{className:f,children:r}),e[8]=r,e[9]=f,e[10]=m):m=e[10];let b;return e[11]!==c||e[12]!==p||e[13]!==u||e[14]!==m?(b=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]=b):b=e[15],b},ls=t=>{const e=Ye.c(25),{label:n,description:a,info:i,descriptionPlacement:r,children:o,settingsItem:d,className:c,controlClassName:p}=t,u=r===void 0?"before":r;let f;e[0]!==a?(f=a!=null?s.jsx("p",{className:rn,children:a}):null,e[0]=a,e[1]=f):f=e[1];const m=f;let b;e[2]!==c?(b=le("space-y-2",c),e[2]=c,e[3]=b):b=e[3];let h;e[4]!==n?(h=s.jsx("div",{className:Kt,children:n}),e[4]=n,e[5]=h):h=e[5];let g;e[6]!==i?(g=i!=null?s.jsx(Ht,{children:i}):null,e[6]=i,e[7]=g):g=e[7];let x;e[8]!==h||e[9]!==g?(x=s.jsxs("div",{className:"flex items-center gap-1.5",children:[h,g]}),e[8]=h,e[9]=g,e[10]=x):x=e[10];const v=u==="before"?m:null;let N;e[11]!==x||e[12]!==v?(N=s.jsxs("div",{className:"space-y-0.5",children:[x,v]}),e[11]=x,e[12]=v,e[13]=N):N=e[13];let P;e[14]!==p?(P=le("flex min-w-0 max-w-[24rem] items-center gap-2",p),e[14]=p,e[15]=P):P=e[15];let F;e[16]!==o||e[17]!==P?(F=s.jsx("div",{className:P,children:o}),e[16]=o,e[17]=P,e[18]=F):F=e[18];const w=u==="after"?m:null;let j;return e[19]!==d||e[20]!==F||e[21]!==w||e[22]!==b||e[23]!==N?(j=s.jsxs("div",{"data-settings-item":d,className:b,children:[N,F,w]}),e[19]=d,e[20]=F,e[21]=w,e[22]=b,e[23]=N,e[24]=j):j=e[24],j},Jt=t=>{const e=Ye.c(25),{label:n,description:a,info:i,children:r,settingsItem:o,className:d,controlClassName:c,alignEnd:p}=t,u=p===void 0?!0:p;let f;e[0]!==d?(f=le("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",d),e[0]=d,e[1]=f):f=e[1];let m;e[2]!==n?(m=s.jsx("div",{className:Kt,children:n}),e[2]=n,e[3]=m):m=e[3];let b;e[4]!==i?(b=i!=null?s.jsx(Ht,{children:i}):null,e[4]=i,e[5]=b):b=e[5];let h;e[6]!==m||e[7]!==b?(h=s.jsxs("div",{className:"flex items-center gap-1.5",children:[m,b]}),e[6]=m,e[7]=b,e[8]=h):h=e[8];let g;e[9]!==a?(g=a!=null?s.jsx("p",{className:le(rn,"mt-0.5"),children:a}):null,e[9]=a,e[10]=g):g=e[10];let x;e[11]!==h||e[12]!==g?(x=s.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[h,g]}),e[11]=h,e[12]=g,e[13]=x):x=e[13];const v=u&&"@xl:justify-end";let N;e[14]!==c||e[15]!==v?(N=le("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",v,c),e[14]=c,e[15]=v,e[16]=N):N=e[16];let P;e[17]!==r||e[18]!==N?(P=s.jsx("div",{className:N,children:r}),e[17]=r,e[18]=N,e[19]=P):P=e[19];let F;return e[20]!==o||e[21]!==P||e[22]!==f||e[23]!==x?(F=s.jsxs("div",{"data-settings-item":o,className:f,children:[x,P]}),e[20]=o,e[21]=P,e[22]=f,e[23]=x,e[24]=F):F=e[24],F},Aa=t=>{const e=Ye.c(6),{children:n,className:a,settingsItem:i}=t;let r;e[0]!==a?(r=le("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},wt=t=>{const e=Ye.c(39),{checked:n,onChange:a,label:i,description:r,disabled:o,ariaLabel:d,settingsItem:c,className:p,labelAccessory:u,info:f}=t,m=o===void 0?!1:o;let b;e[0]!==n||e[1]!==m||e[2]!==a?(b=()=>{m||a(!n)},e[0]=n,e[1]=m,e[2]=a,e[3]=b):b=e[3];const h=b,g=r!=null,x=g?"items-start":"items-center",v=m&&"cursor-not-allowed opacity-60";let N;e[4]!==p||e[5]!==x||e[6]!==v?(N=le("group flex cursor-pointer gap-2 py-0.5",x,v,p),e[4]=p,e[5]=x,e[6]=v,e[7]=N):N=e[7];const P=m?-1:0,F=m||void 0;let w;e[8]!==h?(w=T=>{(T.key===" "||T.key==="Enter")&&(T.preventDefault(),h())},e[8]=h,e[9]=w):w=e[9];let j;e[10]!==d||e[11]!==n||e[12]!==m||e[13]!==a?(j=s.jsx(Pn,{checked:n,onChange:a,disabled:m,ariaLabel:d}),e[10]=d,e[11]=n,e[12]=m,e[13]=a,e[14]=j):j=e[14];let y;e[15]!==i?(y=s.jsx("span",{className:Kt,children:i}),e[15]=i,e[16]=y):y=e[16];let R;e[17]!==f?(R=f!=null?s.jsx(Ht,{children:f}):null,e[17]=f,e[18]=R):R=e[18];let _;e[19]!==u||e[20]!==y||e[21]!==R?(_=s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[y,u,R]}),e[19]=u,e[20]=y,e[21]=R,e[22]=_):_=e[22];let B;e[23]!==r||e[24]!==g?(B=g?s.jsx("span",{className:rn,children:r}):null,e[23]=r,e[24]=g,e[25]=B):B=e[25];let D;e[26]!==_||e[27]!==B?(D=s.jsxs("div",{className:"flex min-w-0 flex-col",children:[_,B]}),e[26]=_,e[27]=B,e[28]=D):D=e[28];let k;return e[29]!==n||e[30]!==c||e[31]!==D||e[32]!==N||e[33]!==P||e[34]!==F||e[35]!==w||e[36]!==j||e[37]!==h?(k=s.jsxs("div",{"data-settings-item":c,className:N,role:"button",tabIndex:P,"aria-pressed":n,"aria-disabled":F,onClick:h,onKeyDown:w,children:[j,D]}),e[29]=n,e[30]=c,e[31]=D,e[32]=N,e[33]=P,e[34]=F,e[35]=w,e[36]=j,e[37]=h,e[38]=k):k=e[38],k},zn=t=>{const e=Ye.c(33),{selected:n,onSelect:a,label:i,description:r,ariaLabel:o,disabled:d,className:c}=t,p=d===void 0?!1:d,u=r!=null?"items-start":"items-center",f=p&&"cursor-not-allowed opacity-60";let m;e[0]!==c||e[1]!==u||e[2]!==f?(m=le("flex cursor-pointer gap-2 py-0.5",u,f,c),e[0]=c,e[1]=u,e[2]=f,e[3]=m):m=e[3];const b=p?-1:0,h=p||void 0;let g,x;e[4]!==p||e[5]!==a?(g=()=>{p||a()},x=_=>{(_.key===" "||_.key==="Enter")&&(_.preventDefault(),p||a())},e[4]=p,e[5]=a,e[6]=g,e[7]=x):(g=e[6],x=e[7]);const v=r!=null?"mt-0.5":void 0;let N;e[8]!==o||e[9]!==p||e[10]!==a||e[11]!==n||e[12]!==v?(N=s.jsx(ir,{checked:n,onChange:a,disabled:p,ariaLabel:o,className:v}),e[8]=o,e[9]=p,e[10]=a,e[11]=n,e[12]=v,e[13]=N):N=e[13];const P=n?"text-foreground":"text-foreground/50";let F;e[14]!==P?(F=le("typography-settings-field-label font-normal",P),e[14]=P,e[15]=F):F=e[15];let w;e[16]!==i||e[17]!==F?(w=s.jsx("span",{className:F,children:i}),e[16]=i,e[17]=F,e[18]=w):w=e[18];let j;e[19]!==r?(j=r!=null?s.jsx("span",{className:rn,children:r}):null,e[19]=r,e[20]=j):j=e[20];let y;e[21]!==w||e[22]!==j?(y=s.jsxs("div",{className:"flex min-w-0 flex-col",children:[w,j]}),e[21]=w,e[22]=j,e[23]=y):y=e[23];let R;return e[24]!==n||e[25]!==N||e[26]!==y||e[27]!==m||e[28]!==b||e[29]!==h||e[30]!==g||e[31]!==x?(R=s.jsxs("div",{className:m,role:"button",tabIndex:b,"aria-pressed":n,"aria-disabled":h,onClick:g,onKeyDown:x,children:[N,y]}),e[24]=n,e[25]=N,e[26]=y,e[27]=m,e[28]=b,e[29]=h,e[30]=g,e[31]=x,e[32]=R):R=e[32],R},Bn=t=>{const e=Ye.c(6),{"aria-label":n,children:a,className:i}=t;let r;e[0]!==i?(r=le(Rs,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 Zs(t){const e=Ye.c(13),{value:n,options:a,onChange:i,className:r,"aria-label":o}=t;let d;e[0]!==r?(d=le("flex flex-wrap items-center gap-1",r),e[0]=r,e[1]=d):d=e[1];let c;if(e[2]!==i||e[3]!==a||e[4]!==n){let u;e[6]!==i||e[7]!==n?(u=f=>s.jsx(Q,{type:"button",variant:"chip",size:"xs",disabled:f.disabled,"aria-pressed":n===f.value,className:"!font-normal",onClick:()=>i(f.value),children:f.label},f.value),e[6]=i,e[7]=n,e[8]=u):u=e[8],c=a.map(u),e[2]=i,e[3]=a,e[4]=n,e[5]=c}else c=e[5];let p;return e[9]!==o||e[10]!==d||e[11]!==c?(p=s.jsx("div",{role:"group","aria-label":o,className:d,children:c}),e[9]=o,e[10]=d,e[11]=c,e[12]=p):p=e[12],p}const Fl="https://github.com/openchamber/openchamber",Tf="https://discord.gg/ZYRSdnwwKA",Ol="https://x.com/openchamber_dev",Rf=800,Ud=({initialUpdateDialogOpen:t=!1})=>{const{t:e}=it(),[n,a]=l.useState(t),[i,r]=l.useState(!1),[o,d]=l.useState(null),[c,p]=l.useState(null),u=Bd(zs(g=>({info:g.info,checking:g.checking,available:g.available,error:g.error,downloading:g.downloading,downloaded:g.downloaded,progress:g.progress,runtimeType:g.runtimeType,checkForUpdates:g.checkForUpdates,downloadUpdate:g.downloadUpdate,restartToUpdate:g.restartToUpdate}))),{isMobile:f}=_s(),m=o||u.info?.currentVersion||"unknown";l.useEffect(()=>{let g=!1;return(async()=>{try{const v=await gt("/api/system/info",{method:"GET",headers:{Accept:"application/json"}});if(!v.ok)return;const N=await v.json().catch(()=>null),P=typeof N?.openchamberVersion=="string"&&N.openchamberVersion.trim().length>0?N.openchamberVersion.trim():null;g||d(P)}catch{g||d(null)}})(),()=>{g=!0}},[]),l.useEffect(()=>{let g=!1;return(async()=>{try{const v=await gt("/api/opencode/upgrade-status",{method:"GET",headers:{Accept:"application/json"}});if(!v.ok)return;const N=await v.json().catch(()=>null),P=typeof N?.currentVersion=="string"&&N.currentVersion.trim().length>0?N.currentVersion.trim():null;g||p(P)}catch{g||p(null)}})(),()=>{g=!0}},[]);const b=l.useRef(!1);l.useEffect(()=>{if(u.checking)r(!0),b.current=!0;else if(i){const g=setTimeout(()=>{r(!1),b.current&&!u.available&&!u.error&&(G.success(e("settings.openchamber.about.toast.latestVersion")),b.current=!1)},Rf);return()=>clearTimeout(g)}},[e,u.checking,i,u.available,u.error]);const h=u.checking||i;return f?s.jsxs("div",{className:"w-full space-y-6 pb-2",children:[s.jsxs("div",{className:"flex flex-col items-center text-center",children:[s.jsx(vd,{width:72,height:72}),s.jsx("h2",{className:`mt-4 ${Ef}`,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(Q,{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(L,{name:"loader",className:"size-4 animate-spin"}):s.jsx(L,{name:"refresh",className:"size-4"}),e(h?"settings.openchamber.about.state.checking":"settings.openchamber.about.actions.checkForUpdates")]}),!h&&u.available&&s.jsxs(Q,{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(L,{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:Fl,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(L,{name:"github-fill",className:"size-5"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:Tf,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(L,{name:"discord-fill",className:"size-5"}),s.jsx("span",{children:"Discord"})]})]}),s.jsxs("a",{href:Ol,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(L,{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(Dl,{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(ot,{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:Kt,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:Kt,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(L,{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(Q,{size:"sm",variant:"default",onClick:()=>a(!0),children:[s.jsx(L,{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(Q,{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:Fl,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(L,{name:"github-fill",className:"h-4 w-4"}),s.jsx("span",{children:"GitHub"})]}),s.jsxs("a",{href:Ol,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(L,{name:"twitter-xfill",className:"h-4 w-4"}),s.jsx("span",{children:"@openchamber_dev"})]})]})]}),s.jsx(Dl,{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})]})},Uk=t=>!(t.dismissed==="true"||t.sessionShown==="true"||t.hasActiveToast),Df=t=>!(!t.version||t.seenVersions.has(t.version)||t.dismissedVersion!==null&&t.dismissedVersion===t.version),Mf=t=>{if(t===null||typeof t!="object")return"";const e=t.version;return typeof e!="string"?"":e.trim()},Lf=t=>!t||t.upgrade?.supported!==!0||t.available!==!0||typeof t.latestVersion!="string"?"":t.latestVersion.trim(),fa="opencode-update-available",Si="opencode-upgrade-progress",Ff=5e3,Of=[1e4,6e4],zl="opencode-update-toast-dismissed-version",_k=()=>{const{t}=it(),e=Ne(o=>o.showOpenCodeUpdateNotifications),n=ge.useRef(new Set),a=ge.useRef(!1);ge.useEffect(()=>{e||G.dismiss(fa)},[e]);const i=ge.useCallback(()=>{G.dismiss(Si),ea({message:t("opencodeUpdate.toast.reload.message"),mode:"projects",scopes:["all"]}).catch(()=>{})},[t]),r=ge.useCallback(async()=>{if(!a.current){a.current=!0,G.dismiss(fa),G.message(t("opencodeUpdate.toast.upgrading.title"),{id:Si,description:t("opencodeUpdate.toast.upgrading.description"),duration:1/0,icon:s.jsx(L,{name:"refresh",className:"h-4 w-4 animate-spin text-muted-foreground"})});try{const o=await gt("/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"));G.success(t("opencodeUpdate.toast.updated.title"),{id:Si,description:d?.version?t("opencodeUpdate.toast.updated.descriptionWithVersion",{version:d.version}):t("opencodeUpdate.toast.updated.description"),duration:1/0,icon:s.jsx(L,{name:"check",className:"h-4 w-4 text-[var(--status-success)]"}),action:{label:t("opencodeUpdate.toast.actions.reload"),onClick:i}})}catch(o){G.error(t("opencodeUpdate.toast.failed.title"),{id:Si,description:o instanceof Error?o.message:t("opencodeUpdate.toast.failed.description"),duration:1/0})}finally{a.current=!1}}},[i,t]);return ge.useEffect(()=>{const o=m=>{if(!Ne.getState().showOpenCodeUpdateNotifications){G.dismiss(fa);return}Df({version:m,dismissedVersion:ml().getItem(zl),seenVersions:n.current})&&(n.current.add(m),G.info(t("opencodeUpdate.toast.available.title"),{id:fa,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:()=>{ml().setItem(zl,m),kt({openCodeUpdateToastDismissedVersion:m}),G.dismiss(fa)}}}))};let d=!1;const c=[],p=async(m,b=on())=>{try{const h=await gt("/api/opencode/upgrade-status",{headers:{Accept:"application/json"}});if(!h.ok)throw new Error(h.statusText||"OpenCode upgrade status check failed");const g=await h.json().catch(()=>null),x=Lf(g);!d&&b===on()&&x&&o(x)}catch{const h=Of[m];!d&&b===on()&&h!==void 0&&c.push(setTimeout(()=>{p(m+1,b)},h))}},u=m=>{Mf(m.detail)&&p(0)};e&&c.push(setTimeout(()=>{p(0)},Ff));const f=Lo(({runtimeKey:m})=>{n.current.clear(),G.dismiss(fa),Ne.getState().showOpenCodeUpdateNotifications&&p(0,m)});return window.addEventListener("openchamber:opencode-update-available",u),()=>{d=!0;for(const m of c)clearTimeout(m);f(),window.removeEventListener("openchamber:opencode-update-available",u)}},[r,e,t]),null},$k=()=>{const t=Ye.c(3),[e,n]=l.useState(zf),{isUpdating:a}=e;let i,r;if(t[0]===Symbol.for("react.memo_cache_sentinel")?(i=()=>zm(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(vd,{width:80,height:80,isAnimated:!0})}),t[2]=o):o=t[2],o};function zf(){return Om()}class Bf 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(Bm,{className:"w-full max-w-md",children:[s.jsx(Km,{className:"text-center",children:s.jsxs(Um,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(L,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(_m,{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(Q,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(L,{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 Kf(t){const e=Ye.c(22),{t:n}=it();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(Bf,{...t,texts:p}),e[19]=t,e[20]=p,e[21]=u):u=e[21],u}const Vk=t=>{const e=Ye.c(6),{active:n,readOnly:a}=t,i=n===void 0?!0:n,r=a===void 0?!1:a,d=ds(Uf)||void 0;let c;e[0]!==i||e[1]!==r?(c=s.jsx($m,{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(Kf,{sessionId:d,children:c}),e[3]=d,e[4]=c,e[5]=p):p=e[5],p};function Uf(t){return t.currentSessionId}function Un(t){const e=Ye.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(Uu,{...n}),e[2]=n,e[3]=a):a=e[3],a}function _n(t){const e=Ye.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(_u,{...n}),e[2]=n,e[3]=a):a=e[3],a}function $n(t){const e=Ye.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=le("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=le(Vm,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($u,{"data-slot":"dropdown-menu-content",style:c,className:p,...r,children:n}),e[12]=n,e[13]=r,e[14]=c,e[15]=p,e[16]=u):u=e[16];let f;return e[17]!==d||e[18]!==u?(f=s.jsx(Hu,{children:s.jsx(Wu,{className:d,children:u})}),e[17]=d,e[18]=u,e[19]=f):f=e[19],f}function En(t){const e=Ye.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=le(Hm,n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx(Vu,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r}function Hk(t){const e=Ye.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=le(Wm,n),e[3]=n,e[4]=i):i=e[4];let r;return e[5]!==a||e[6]!==i?(r=s.jsx(Gu,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r}const _d=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),ci=t=>{const e=Ye.c(39),{className:n}=t,{t:a}=it(),i=rs(_f),r=rs($f),o=rs(Vf),d=os();let c;e[0]!==i?(c=[...i].sort(Hf),e[0]=i,e[1]=c):c=e[1];const p=c;let u;e:{if(p.length===0){u=null;break e}let M;e[2]!==r||e[3]!==p?(M=p.find(O=>O.id===r)??p[0],e[2]=r,e[3]=p,e[4]=M):M=e[4],u=M}const f=u;if(d||p.length===0)return null;let m;e[5]!==f||e[6]!==a?(m=f?.label&&f.label.trim().length>0?f.label:f?.path.split("/").filter(Boolean).pop()||f?.path||a("settings.shared.projectSelector.fallbackProject"),e[5]=f,e[6]=a,e[7]=m):m=e[7];const b=m;let h;e[8]!==b?(h=_d(b),e[8]=b,e[9]=h):h=e[9];const g=h;let x;e[10]!==n?(x=le(n),e[10]=n,e[11]=x):x=e[11];let v;e[12]!==a?(v=a("settings.shared.projectSelector.switchProjectAria"),e[12]=a,e[13]=v):v=e[13];let N;e[14]!==a?(N=a("settings.shared.projectSelector.switchProjectTitle"),e[14]=a,e[15]=N):N=e[15];let P,F;e[16]===Symbol.for("react.memo_cache_sentinel")?(P=le("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"),F=s.jsx(L,{name:"folder",className:"h-4 w-4 opacity-70"}),e[16]=P,e[17]=F):(P=e[16],F=e[17]);let w;e[18]!==g?(w=s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:g}),e[18]=g,e[19]=w):w=e[19];let j;e[20]===Symbol.for("react.memo_cache_sentinel")?(j=s.jsx(L,{name:"arrow-down-s",className:"size-4 opacity-50"}),e[20]=j):j=e[20];let y;e[21]!==w||e[22]!==v||e[23]!==N?(y=s.jsx(ys,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":v,title:N,className:P,children:[F,w,j]})}),e[21]=w,e[22]=v,e[23]=N,e[24]=y):y=e[24];const R=f?.id??"";let _;e[25]!==o?(_=M=>{M&&o(M)},e[25]=o,e[26]=_):_=e[26];let B;e[27]!==p?(B=p.map(Wf),e[27]=p,e[28]=B):B=e[28];let D;e[29]!==R||e[30]!==_||e[31]!==B?(D=s.jsx(vs,{align:"start",className:"w-auto",children:s.jsx(qm,{value:R,onValueChange:_,children:B})}),e[29]=R,e[30]=_,e[31]=B,e[32]=D):D=e[32];let k;e[33]!==y||e[34]!==D?(k=s.jsxs(ws,{children:[y,D]}),e[33]=y,e[34]=D,e[35]=k):k=e[35];let T;return e[36]!==k||e[37]!==x?(T=s.jsx("div",{className:x,children:k}),e[36]=k,e[37]=x,e[38]=T):T=e[38],T};function _f(t){return t.projects}function $f(t){return t.activeProjectId}function Vf(t){return t.setActiveProject}function Hf(t,e){return(t.label||t.path).localeCompare(e.label||e.path)}function Wf(t){const e=t.label?.trim()?t.label.trim():t.path.split("/").filter(Boolean).pop()||t.path,n=_d(e);return s.jsx(Gm,{value:t.id,children:s.jsx("span",{className:"min-w-0 truncate typography-ui",children:n})},t.id)}function Gf(t,e){return`opencode:sidebar-group:${t}:${e}`}const vo=t=>{const e=Ye.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=Gf(i,n),e[0]=n,e[1]=i,e[2]=c):c=e[2];const p=c,u=l.useId();let f;e[3]!==d||e[4]!==p?(f=()=>{try{const D=localStorage.getItem(p);if(D!==null)return D==="true"}catch{}return d},e[3]=d,e[4]=p,e[5]=f):f=e[5];const[m,b]=ge.useState(f);let h,g;e[6]!==m||e[7]!==p?(h=()=>{try{localStorage.setItem(p,String(m))}catch{}},g=[p,m],e[6]=m,e[7]=p,e[8]=h,e[9]=g):(h=e[8],g=e[9]),ge.useEffect(h,g);let x;e[10]===Symbol.for("react.memo_cache_sentinel")?(x=()=>b(qf),e[10]=x):x=e[10];let v;e[11]===Symbol.for("react.memo_cache_sentinel")?(v=le("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]=v):v=e[11];const N=!m&&"-rotate-90";let P;e[12]!==N?(P=le("h-3.5 w-3.5 flex-shrink-0 transition-transform duration-200",N),e[12]=N,e[13]=P):P=e[13];let F;e[14]!==P?(F=s.jsx(L,{name:"arrow-down-s",className:P}),e[14]=P,e[15]=F):F=e[15];let w;e[16]!==n?(w=s.jsx("span",{className:"flex-1 truncate",children:n}),e[16]=n,e[17]=w):w=e[17];let j;e[18]!==a?(j=s.jsx("span",{className:"ml-1 tabular-nums opacity-60",children:a}),e[18]=a,e[19]=j):j=e[19];let y;e[20]!==u||e[21]!==m||e[22]!==F||e[23]!==w||e[24]!==j?(y=s.jsxs("button",{type:"button",onClick:x,"aria-expanded":m,"aria-controls":u,className:v,children:[F,w,j]}),e[20]=u,e[21]=m,e[22]=F,e[23]=w,e[24]=j,e[25]=y):y=e[25];const R=!m;let _;e[26]!==o||e[27]!==u||e[28]!==R?(_=s.jsx("div",{id:u,hidden:R,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]=R,e[29]=_):_=e[29];let B;return e[30]!==y||e[31]!==_?(B=s.jsxs("div",{children:[y,_]}),e[30]=y,e[31]=_,e[32]=B):B=e[32],B};function qf(t){return!t}const Jf=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},Qf=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())},Bl=t=>{const e=Qf(Jf(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},Yf=({onItemSelect:t})=>{const{t:e}=it(),[n,a]=l.useState(null),[i,r]=l.useState(""),[o,d]=l.useState(null),[c,p]=l.useState(null),[u,f]=l.useState(!1),[m,b]=l.useState(null),{selectedAgentName:h,agents:g,setSelectedAgent:x,setAgentDraft:v,createAgent:N,deleteAgent:P,loadAgents:F}=ri(zs(S=>({selectedAgentName:S.selectedAgentName,agents:S.agents,setSelectedAgent:S.setSelectedAgent,setAgentDraft:S.setAgentDraft,createAgent:S.createAgent,deleteAgent:S.deleteAgent,loadAgents:S.loadAgents})));l.useEffect(()=>{F()},[F]);const w="bg-background",j=()=>{const S="new-agent";let W=S,Z=1;for(;g.some(A=>A.name===W);)W=`${S}-${Z}`,Z++;v({name:W,scope:"user"}),x(W),t?.()},y=async S=>{if(Na(S)){G.error(e("settings.agents.sidebar.toast.builtInCannotDelete"));return}d(S),p("delete")},R=async S=>{Na(S)&&(d(S),p("reset"))},_=()=>{d(null),p(null)},B=async()=>{if(!(!o||!c)){f(!0);try{const S=await P(o.name,o.scope);S.ok?(S.requiresManualRestart?G.warning(e("settings.agents.page.toast.savedManualRestart")):c==="delete"?G.success(e("settings.agents.sidebar.toast.agentDeleted",{name:o.name})):G.success(e("settings.agents.sidebar.toast.agentReset",{name:o.name})),_()):c==="delete"?G.error(e("settings.agents.sidebar.toast.deleteFailed")):G.error(e("settings.agents.sidebar.toast.resetFailed"))}catch(S){const W=S instanceof Error?S.message:"",Z=/built-in|not deletable|not found/i.test(W);c==="delete"?G.error(e(Z?"settings.agents.sidebar.toast.definitionNotFound":"settings.agents.sidebar.toast.deleteFailed")):G.error(e("settings.agents.sidebar.toast.resetFailed"))}f(!1)}},D=S=>{const W=S.name;let Z=1,A=`${W}-copy`;for(;g.some(H=>H.name===A);)Z++,A=`${W}-copy-${Z}`;const C=S,z=S.model?.providerID&&S.model?.modelID?`${S.model.providerID}/${S.model.modelID}`:null,$=S;v({name:A,scope:C.scope||"user",description:S.description,model:z,variant:S.variant,temperature:S.temperature,top_p:S.topP,prompt:S.prompt,mode:S.mode,permission:Bl(S.permission),disable:$.disable}),x(A)},k=S=>{r(S.name),a(S)},T=async()=>{if(!n)return;const S=i.trim().replace(/\s+/g,"-");if(!S){G.error(e("settings.agents.sidebar.toast.agentNameRequired"));return}if(S===n.name){a(null);return}if(g.some(C=>C.name===S)){G.error(e("settings.agents.sidebar.toast.agentExists"));return}const W=n.model?.providerID&&n.model?.modelID?`${n.model.providerID}/${n.model.modelID}`:null,Z=n,A=await N({name:S,description:n.description,model:W,variant:n.variant,temperature:n.temperature,top_p:n.topP,prompt:n.prompt,mode:n.mode,permission:Bl(n.permission),disable:Z.disable,scope:Z.scope});if(A.ok){const C=await P(n.name,Z.scope);C.ok?(A.requiresManualRestart||C.requiresManualRestart?G.warning(e("settings.agents.page.toast.savedManualRestart")):G.success(e("settings.agents.sidebar.toast.agentRenamed",{name:S})),x(S)):G.error(e("settings.agents.sidebar.toast.removeOldAfterRenameFailed"))}else G.error(e("settings.agents.sidebar.toast.renameFailed"));a(null)},M=S=>{switch(S){case"primary":return s.jsx(L,{name:"ai-agent",className:"h-3 w-3 text-primary"});case"all":return s.jsx(L,{name:"ai-agent-fill",className:"h-3 w-3 text-primary"});case"subagent":return s.jsx(L,{name:"robot",className:"h-3 w-3 text-primary"});default:return null}},O=g.filter(S=>!Jm(S)),V=O.filter(Na),U=O.filter(S=>!Na(S)),{groupedCustomAgents:Y,ungroupedCustomAgents:X}=ge.useMemo(()=>{const S={},W=[];for(const A of U){const C=A;C.group?(S[C.group]||(S[C.group]=[]),S[C.group].push(A)):W.push(A)}return{groupedCustomAgents:Object.keys(S).sort((A,C)=>A.localeCompare(C)).map(A=>({name:A,agents:S[A]})),ungroupedCustomAgents:W}},[U]);return s.jsxs("div",{className:le("flex h-full flex-col",w),children:[s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[s.jsx("h2",{className:`${dn} mb-3`,children:e("settings.agents.sidebar.title")}),s.jsx(ci,{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:O.length})}),s.jsx(Q,{size:"sm","data-settings-item":"agents.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:j,children:s.jsx(L,{name:"add",className:"h-3.5 w-3.5"})})]})]}),s.jsx(Bs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:O.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(L,{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:[V.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")}),V.map(S=>s.jsx(Mr,{agent:S,isSelected:h===S.name,onSelect:()=>{x(S.name),t?.()},onReset:()=>R(S),onDuplicate:()=>D(S),getAgentModeIcon:M,isMenuOpen:m===S.name,onMenuOpenChange:W=>b(W?S.name:null)},S.name))]}),U.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")}),Y.map(({name:S,agents:W})=>s.jsx(vo,{label:S,count:W.length,storageKey:"agents",children:W.map(Z=>s.jsx(Mr,{agent:Z,isSelected:h===Z.name,onSelect:()=>{x(Z.name),t?.()},onRename:()=>k(Z),onDelete:()=>y(Z),onDuplicate:()=>D(Z),getAgentModeIcon:M,isMenuOpen:m===Z.name,onMenuOpenChange:A=>b(A?Z.name:null)},Z.name))},S)),X.map(S=>s.jsx(Mr,{agent:S,isSelected:h===S.name,onSelect:()=>{x(S.name),t?.()},onRename:()=>k(S),onDelete:()=>y(S),onDuplicate:()=>D(S),getAgentModeIcon:M,isMenuOpen:m===S.name,onMenuOpenChange:W=>b(W?S.name:null)},S.name))]})]})}),s.jsx(Lt,{open:o!==null&&c!==null,onOpenChange:S=>{!S&&!u&&_()},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:e(c==="delete"?"settings.agents.sidebar.dialog.deleteTitle":"settings.agents.sidebar.dialog.resetTitle")}),s.jsx(qt,{children:c==="delete"?e("settings.agents.sidebar.dialog.deleteDescription",{name:o?.name??""}):e("settings.agents.sidebar.dialog.resetDescription",{name:o?.name??""})})]}),s.jsxs(Zt,{children:[s.jsx(Q,{size:"sm",variant:"ghost",onClick:_,disabled:u,children:e("settings.common.actions.cancel")}),s.jsx(Q,{size:"sm",onClick:B,disabled:u,children:e(c==="delete"?"settings.common.actions.delete":"settings.common.actions.reset")})]})]})}),s.jsx(Lt,{open:n!==null,onOpenChange:S=>!S&&a(null),children:s.jsxs(Ft,{children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:e("settings.agents.sidebar.renameDialog.title")}),s.jsx(qt,{children:e("settings.agents.sidebar.renameDialog.description",{name:n?.name??""})})]}),s.jsx(tt,{value:i,onChange:S=>r(S.target.value),placeholder:e("settings.agents.sidebar.renameDialog.placeholder"),className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&T()}}),s.jsxs(Zt,{children:[s.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>a(null),children:e("settings.common.actions.cancel")}),s.jsx(Q,{size:"sm",onClick:T,children:e("settings.common.actions.rename")})]})]})})]})},Mr=t=>{const e=Ye.c(52),{agent:n,isSelected:a,onSelect:i,onDelete:r,onReset:o,onRename:d,onDuplicate:c,getAgentModeIcon:p,isMenuOpen:u,onMenuOpenChange:f}=t,{t:m}=it(),b=n;let h;e[0]===Symbol.for("react.memo_cache_sentinel")?(h=si(),e[0]=h):h=e[0];const g=h,[x,v]=l.useState(!1);let N;e[1]!==r||e[2]!==c||e[3]!==d||e[4]!==o||e[5]!==m?(N=Z=>s.jsxs(s.Fragment,{children:[d&&s.jsxs(Z,{onClick:A=>{A.stopPropagation(),d()},children:[s.jsx(L,{name:"edit",className:"h-4 w-4 mr-px"}),m("settings.common.actions.rename")]}),s.jsxs(Z,{onClick:A=>{A.stopPropagation(),c()},children:[s.jsx(L,{name:"file-copy",className:"h-4 w-4 mr-px"}),m("settings.common.actions.duplicate")]}),o&&s.jsxs(Z,{onClick:A=>{A.stopPropagation(),o()},children:[s.jsx(L,{name:"restart",className:"h-4 w-4 mr-px"}),m("settings.common.actions.reset")]}),r&&s.jsxs(Z,{onClick:A=>{A.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{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]=N):N=e[6];const P=N,F=a?"bg-interactive-selection":"hover:bg-interactive-hover";let w;e[7]!==F?(w=le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",F),e[7]=F,e[8]=w):w=e[8];let j;e[9]===Symbol.for("react.memo_cache_sentinel")?(j=g?void 0:Z=>{Z.preventDefault(),v(!0)},e[9]=j):j=e[9];let y;e[10]!==w?(y=s.jsx("div",{className:w,onContextMenu:j}),e[10]=w,e[11]=y):y=e[11];let R;e[12]!==n.name?(R=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n.name}),e[12]=n.name,e[13]=R):R=e[13];let _;e[14]!==n.mode||e[15]!==p?(_=p(n.mode),e[14]=n.mode,e[15]=p,e[16]=_):_=e[16];let B;e[17]!==n||e[18]!==b.scope||e[19]!==m?(B=(b.scope||Na(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:Na(n)?m("settings.agents.sidebar.badge.system"):b.scope}),e[17]=n,e[18]=b.scope,e[19]=m,e[20]=B):B=e[20];let D;e[21]!==R||e[22]!==_||e[23]!==B?(D=s.jsxs("div",{className:"flex items-center gap-1.5",children:[R,_,B]}),e[21]=R,e[22]=_,e[23]=B,e[24]=D):D=e[24];let k;e[25]!==n.description?(k=n.description&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n.description}),e[25]=n.description,e[26]=k):k=e[26];let T;e[27]!==i||e[28]!==D||e[29]!==k?(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:[D,k]}),e[27]=i,e[28]=D,e[29]=k,e[30]=T):T=e[30];let M;e[31]!==f?(M=Z=>{Z&&v(!1),f(Z)},e[31]=f,e[32]=M):M=e[32];let O;e[33]===Symbol.for("react.memo_cache_sentinel")?(O=s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[33]=O):O=e[33];let V;e[34]!==P?(V=s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:P(bs)}),e[34]=P,e[35]=V):V=e[35];let U;e[36]!==u||e[37]!==M||e[38]!==V?(U=s.jsxs(ws,{open:u,onOpenChange:M,children:[O,V]}),e[36]=u,e[37]=M,e[38]=V,e[39]=U):U=e[39];let Y;e[40]!==T||e[41]!==U?(Y=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[T,U]}),e[40]=T,e[41]=U,e[42]=Y):Y=e[42];let X;e[43]!==Y||e[44]!==y?(X=s.jsx(_n,{render:y,children:Y}),e[43]=Y,e[44]=y,e[45]=X):X=e[45];let S;e[46]!==P?(S=s.jsx($n,{className:"w-fit min-w-20",children:P(En)}),e[46]=P,e[47]=S):S=e[47];let W;return e[48]!==x||e[49]!==X||e[50]!==S?(W=s.jsxs(Un,{open:x,onOpenChange:v,children:[X,S]}),e[48]=x,e[49]=X,e[50]=S,e[51]=W):W=e[51],W},us=t=>{const e=Ye.c(21),{children:n,className:a,outerClassName:i,title:r,titleLeading:o,titleAccessory:d,description:c,headerEnd:p,showSaveStatus:u}=t,f=u===void 0?!1:u,m=r!=null||c!=null||p!=null||f,b=typeof r=="string"||typeof r=="number",h=o!=null||d!=null;let g;e[0]!==i?(g=le("h-full",i),e[0]=i,e[1]=g):g=e[1];let x;e[2]!==a?(x=le("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 v;e[4]!==c||e[5]!==m||e[6]!==h||e[7]!==p||e[8]!==b||e[9]!==f||e[10]!==r||e[11]!==d||e[12]!==o?(v=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?b?h?s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o,s.jsx("h1",{className:le(yo,"min-w-0 truncate"),children:r}),d]}):s.jsx("h1",{className:yo,children:r}):r:null,c!=null?typeof c=="string"||typeof c=="number"?s.jsx("p",{className:Kd,children:c}):c:null]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[p,f&&s.jsx(Zf,{})]})]}),e[4]=c,e[5]=m,e[6]=h,e[7]=p,e[8]=b,e[9]=f,e[10]=r,e[11]=d,e[12]=o,e[13]=v):v=e[13];let N;e[14]!==n||e[15]!==x||e[16]!==v?(N=s.jsxs("div",{className:x,children:[v,n]}),e[14]=n,e[15]=x,e[16]=v,e[17]=N):N=e[17];let P;return e[18]!==g||e[19]!==N?(P=s.jsx(Bs,{outerClassName:g,className:"w-full @container",children:N}),e[18]=g,e[19]=N,e[20]=P):P=e[20],P},Xf=500,Zf=()=>{const t=Ye.c(13),{t:e}=it(),n=l.useSyncExternalStore(wg,pl,pl),[a,i]=l.useState(!1);let r,o;if(t[0]!==n?(r=()=>{if(n!=="saving"){i(!1);return}const u=setTimeout(()=>i(!0),Xf);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(L,{name:"error-warning",className:"size-3.5"}),t[3]=u):u=t[3];let f;t[4]!==e?(f=e("settings.common.status.saveFailed"),t[4]=e,t[5]=f):f=t[5];let m;return t[6]!==f?(m=s.jsxs("div",{"aria-live":"assertive",className:"flex shrink-0 items-center gap-1.5 typography-meta text-[var(--status-error)]",children:[u,s.jsx("span",{children:f})]}),t[6]=f,t[7]=m):m=t[7],m}if(n!=="saving"||!a)return null;let d;t[8]===Symbol.for("react.memo_cache_sentinel")?(d=s.jsx(L,{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},eh=["allow","ask","deny"],Ya=t=>t==="allow"||t==="ask"||t==="deny",wo=()=>({global:null,keys:{}}),th=t=>{const e=wo();if(t==null)return e;if(typeof t=="string")return Ya(t)&&(e.global=t),e;if(typeof t!="object"||Array.isArray(t))return e;for(const[n,a]of Object.entries(t)){if(n==="*"){Ya(a)&&(e.global=a);continue}const i={action:null,patterns:[]};if(Ya(a))i.action=a;else if(a&&typeof a=="object"&&!Array.isArray(a))for(const[r,o]of Object.entries(a))Ya(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},sh=(t,e)=>JSON.stringify(jo(t))===JSON.stringify(jo(e)),Ln=t=>JSON.parse(JSON.stringify(t)),nh=["edit","external_directory","doom_loop","plan_enter","plan_exit"],ah=new Set(["read","edit","glob","grep","list","bash","task","external_directory","lsp","skill"]),Kl=new Set(["write","patch","apply_patch","multiedit","invalid"]),ih=t=>t.split(/[_-]/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" "),rh=({agent:t})=>{const{t:e}=it(),n=ri(C=>C.updateAgent),[a,i]=l.useState(wo),[r,o]=l.useState(wo),[d,c]=l.useState(!0),[p,u]=l.useState(!1),[f,m]=l.useState(!1),[b,h]=l.useState({}),[g,x]=l.useState([]),[v,N]=l.useState(""),[P,F]=l.useState(0),w=t.name;l.useEffect(()=>{let C=!1;return c(!0),u(!1),(async()=>{try{const z=Xo(),$=z?`?directory=${encodeURIComponent(z)}`:"",H=await gt(`/api/config/agents/${encodeURIComponent(w)}/config${$}`,{headers:{"Cache-Control":"no-cache",...z?{"x-opencode-directory":z}:{}}});if(!H.ok)throw new Error(String(H.status));const J=await H.json().catch(()=>null);if(C)return;const ee=th(J?.config?.permission);i(Ln(ee)),o(ee)}catch{C||u(!0)}finally{C||c(!1)}})(),()=>{C=!0}},[w,P]),l.useEffect(()=>{let C=!1;return(async()=>{try{const z=await Is.listToolIds({directory:Xo()});!C&&Array.isArray(z)&&x(z.filter($=>typeof $=="string"&&!Kl.has($)))}catch{}})(),()=>{C=!0}},[w]);const j=l.useMemo(()=>{const C=t.permission;if(!Array.isArray(C))return[];const z=[];for(const $ of C){if(!$||typeof $!="object")continue;const{permission:H,pattern:J,action:ee}=$;typeof H=="string"&&typeof J=="string"&&Ya(ee)&&z.push({permission:H,pattern:J,action:ee})}return z},[t]),y=l.useCallback(C=>{const z=j.find(H=>H.permission===C&&H.pattern==="*");if(z)return z.action;const $=j.find(H=>H.permission==="*"&&H.pattern==="*");return $?$.action:null},[j]),R=l.useCallback(C=>{const z=r.keys[C]?.patterns??[],$=new Set(z.map(H=>H.pattern));return j.filter(H=>H.permission===C&&H.pattern!=="*"&&!$.has(H.pattern))},[j,r.keys]),_=l.useMemo(()=>{const C=new Set;for(const z of g)C.add(z);for(const z of nh)C.add(z);for(const z of Object.keys(r.keys))C.add(z);for(const z of Kl)C.delete(z);return Array.from(C).sort((z,$)=>z.localeCompare($))},[g,r.keys]),B=l.useMemo(()=>!sh(r,a),[r,a]),D=C=>{o(z=>({...z,global:C}))},k=(C,z)=>{o($=>{const H=Ln($),J=H.keys[C]??{action:null,patterns:[]};return J.action=z,J.action===null&&J.patterns.length===0?delete H.keys[C]:H.keys[C]=J,H})},T=(C,z,$,H)=>{o(J=>{const ee=Ln(J),ue=ee.keys[C]??{action:null,patterns:[]};return ue.patterns[z]={pattern:$,action:H},ee.keys[C]=ue,ee})},M=C=>{o(z=>{const $=Ln(z),H=$.keys[C]??{action:null,patterns:[]};return H.patterns.push({pattern:"",action:"allow"}),$.keys[C]=H,$}),h(z=>({...z,[C]:!0}))},O=(C,z)=>{o($=>{const H=Ln($),J=H.keys[C];return J?(J.patterns.splice(z,1),J.action===null&&J.patterns.length===0&&delete H.keys[C],H):$})},V=()=>{const C=v.trim();!C||C==="*"||(o(z=>{if(z.keys[C])return z;const $=Ln(z);return $.keys[C]={action:"ask",patterns:[]},$}),h(z=>({...z,[C]:!0})),N(""))},U=async()=>{m(!0);try{const C=jo(r),z=await n(w,{permission:C});z.ok?(i(Ln(r)),G.success(z.requiresManualRestart?e("settings.agents.page.permissionsEditor.toast.savedRestartRequired"):e("settings.agents.page.permissionsEditor.toast.saved"))):G.error(e("settings.agents.page.permissionsEditor.toast.saveFailed"))}finally{m(!1)}},Y=()=>{o(Ln(a))},X=C=>e(C==="allow"?"settings.agents.page.permissionsEditor.action.allow":C==="ask"?"settings.agents.page.permissionsEditor.action.ask":"settings.agents.page.permissionsEditor.action.deny"),S=e("settings.agents.page.permissionsEditor.action.inherit"),W=e("settings.agents.page.permissionsEditor.action.default"),Z=C=>[...C?[{value:"inherit",label:C}]:[],...eh.map(z=>({value:z,label:X(z)}))],A=(C,z,$,H=S)=>s.jsx(Zs,{value:C??"inherit",options:Z(H),onChange:J=>z(J==="inherit"?null:J),"aria-label":$});return d?s.jsx(ot,{title:e("settings.agents.page.section.toolPermissions"),children:s.jsx("p",{className:rn,children:e("common.loading")})}):p?s.jsx(ot,{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(Q,{variant:"outline",size:"xs",onClick:()=>F(C=>C+1),children:e("settings.agents.page.permissionsEditor.actions.retry")})]})}):s.jsxs(ot,{title:e("settings.agents.page.section.toolPermissions"),settingsItem:"agents.permissions",info:e("settings.agents.page.permissionsEditor.sectionInfo"),headerAction:B?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Q,{variant:"ghost",size:"xs",className:"!font-normal",onClick:Y,disabled:f,children:e("settings.agents.page.permissionsEditor.actions.discard")}),s.jsx(Q,{size:"xs",className:"!font-normal",onClick:()=>{U()},disabled:f,children:e(f?"settings.common.actions.saving":"settings.agents.page.permissionsEditor.actions.save")})]}):void 0,contentClassName:"space-y-4",children:[s.jsxs("div",{className:"flex flex-col gap-2 pb-2 @xl:flex-row @xl:items-center @xl:justify-between",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:Kt,children:e("settings.agents.page.permissionsEditor.defaultLabel")}),s.jsx(Ht,{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:X(y("*")??"allow")})})]}),A(r.global,D,e("settings.agents.page.permissionsEditor.defaultAria"),W)]}),s.jsx("div",{children:_.map(C=>{const z=r.keys[C]??{action:null,patterns:[]},$=R(C),H=ah.has(C)||z.patterns.length>0,J=H||$.length>0,ee=b[C]===!0,ue=y(C);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:J?()=>h(re=>({...re,[C]:!ee})):void 0,className:le("flex min-w-0 items-center gap-1.5 text-left",!J&&"cursor-default"),"aria-expanded":J?ee:void 0,children:[s.jsx(L,{name:ee&&J?"arrow-down-s":"arrow-right-s",className:le("h-3.5 w-3.5 shrink-0 text-muted-foreground",!J&&"opacity-0")}),s.jsx("span",{className:Kt,children:ih(C)}),s.jsx("span",{className:"typography-micro font-mono text-muted-foreground/70",children:C}),z.action===null&&ue!==null&&s.jsx("span",{className:"typography-micro text-muted-foreground",children:e("settings.agents.page.permissionsEditor.effectiveHint",{action:X(ue)})}),z.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(z.patterns.length)})})]}),A(z.action,re=>k(C,re),e("settings.agents.page.permissionsEditor.keyAria",{key:C}))]}),ee&&J&&s.jsxs("div",{className:"mt-2 space-y-2 pl-5",children:[z.patterns.map((re,xe)=>s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(tt,{value:re.pattern,onChange:be=>T(C,xe,be.target.value,re.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(Zs,{value:re.action,options:Z(),onChange:be=>T(C,xe,re.pattern,be),"aria-label":e("settings.agents.page.permissionsEditor.patternActionAria",{key:C})}),s.jsx(Q,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive",onClick:()=>O(C,xe),"aria-label":e("settings.agents.page.permissionsEditor.actions.removeRuleAria"),children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})})]},xe)),H&&s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>M(C),children:[s.jsx(L,{name:"add",className:"mr-1 h-3.5 w-3.5"}),e("settings.agents.page.permissionsEditor.actions.addRule")]}),$.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(Ht,{children:e("settings.agents.page.permissionsEditor.sessionRulesInfo")})]}),$.map(re=>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:re.pattern}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:X(re.action)})]},`${re.pattern}-${re.action}`))]})]})]},C)})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t border-border/40 pt-3",children:[s.jsx(tt,{value:v,onChange:C=>N(C.target.value),onKeyDown:C=>{C.key==="Enter"&&(C.preventDefault(),V())},placeholder:e("settings.agents.page.permissionsEditor.customKeyPlaceholder"),className:"h-8 w-full max-w-[16rem] font-mono text-xs"}),s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:V,disabled:!v.trim(),children:[s.jsx(L,{name:"add",className:"mr-1 h-3.5 w-3.5"}),e("settings.agents.page.permissionsEditor.actions.addKey")]})]})]})},oh=(t,e)=>{const n=Kn(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):[]},lh=()=>{const{t}=it(),e=pt(A=>A.providers),{selectedAgentName:n,getAgentByName:a,createAgent:i,updateAgent:r,agents:o,agentDraft:d,setAgentDraft:c}=ri(zs(A=>({selectedAgentName:A.selectedAgentName,getAgentByName:A.getAgentByName,createAgent:A.createAgent,updateAgent:A.updateAgent,agents:A.agents,agentDraft:A.agentDraft,setAgentDraft:A.setAgentDraft}))),p=n?a(n):null,u=!!(d&&d.name===n&&!p),[f,m]=l.useState(""),[b,h]=l.useState("user"),[g,x]=l.useState(""),[v,N]=l.useState("subagent"),[P,F]=l.useState(""),[w,j]=l.useState(""),[y,R]=l.useState(void 0),[_,B]=l.useState(void 0),[D,k]=l.useState(""),[T,M]=l.useState(!1),O=l.useRef(null),V=l.useMemo(()=>oh(e,P),[P,e]),U=V.length>0,Y=w||"__default",X=U,S=l.useMemo(()=>w&&!V.includes(w)?[w,...V]:V,[w,V]);l.useEffect(()=>{if(u&&d){const A=d.name||"",C=d.scope||"user",z=d.description||"",$=d.mode||"subagent",H=d.model||"",J=d.variant||"",ee=d.temperature??void 0,ue=d.top_p??void 0,re=d.prompt||"";m(A),h(C),x(z),N($),F(H),j(J),R(ee),B(ue),k(re),O.current={draftName:A,draftScope:C,description:z,mode:$,model:H,variant:J,temperature:ee,topP:ue,prompt:re};return}if(p&&n===p.name){const A=p.description||"",C=p.mode||"subagent",z=p.model?.providerID&&p.model?.modelID?`${p.model.providerID}/${p.model.modelID}`:"",$=p.variant||"",H=p.temperature??void 0,J=p.topP??void 0,ee=p.prompt||"";x(A),N(C),F(z),j($),R(H),B(J),k(ee),O.current={draftName:"",draftScope:"user",description:A,mode:C,model:z,variant:$,temperature:H,topP:J,prompt:ee}}},[d,u,p,n]);const W=l.useMemo(()=>{const A=O.current;return A?!!(u&&(f!==A.draftName||b!==A.draftScope)||g!==A.description||v!==A.mode||P!==A.model||w!==A.variant||y!==A.temperature||_!==A.topP||D!==A.prompt):!1},[g,f,b,u,v,P,D,y,_,w]),Z=async()=>{const A=u?f.trim().replace(/\s+/g,"-"):n?.trim();if(!A){G.error(t("settings.agents.sidebar.toast.agentNameRequired"));return}if(u&&o.some(C=>C.name===A)){G.error(t("settings.agents.sidebar.toast.agentExists"));return}M(!0);try{const C=P.trim(),z=w.trim(),$=D.trim(),H={name:A,...g.trim()?{description:g.trim()}:{},mode:v,model:C===""?null:C,variant:z===""?null:z||void 0,temperature:y??null,top_p:_??null,prompt:$||(u?void 0:null),...u&&b?{scope:b}:{}};let J;u?(J=await i(H),J.ok&&c(null)):J=await r(A,H),J.ok?J.requiresManualRestart?G.warning(t("settings.agents.page.toast.savedManualRestart")):G.success(t(u?"settings.agents.page.toast.created":"settings.agents.page.toast.updated")):G.error(t(u?"settings.agents.page.toast.createFailed":"settings.agents.page.toast.updateFailed"))}catch(C){console.error("Error saving agent:",C);const z=C instanceof Error&&C.message?C.message:t("settings.agents.page.toast.saveUnexpectedError");G.error(z)}finally{M(!1)}};return n?s.jsxs(us,{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(ot,{title:t("settings.agents.page.section.identityRole"),divider:!1,contentClassName:"space-y-0",children:[u&&s.jsxs(Jt,{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(tt,{value:f,onChange:A=>m(A.target.value),placeholder:t("settings.agents.page.field.agentNamePlaceholder"),className:"h-7 w-40 px-2"})]}),s.jsxs(At,{value:b,onValueChange:A=>h(A),children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[100px]",children:s.jsx(Vt,{placeholder:t("settings.agents.page.field.scopePlaceholder")})}),s.jsxs(Tt,{align:"end",children:[s.jsx(yt,{value:"user",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.global")})]})}),s.jsx(yt,{value:"project",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.project")})]})})]})]})]}),s.jsx(ls,{label:t("settings.common.field.description"),controlClassName:"w-full max-w-none",children:s.jsx(js,{value:g,onChange:A=>x(A.target.value),placeholder:t("settings.agents.page.field.descriptionPlaceholder"),rows:2,className:"w-full resize-none min-h-[60px] bg-transparent"})}),s.jsx(ls,{settingsItem:"agents.mode",label:t("settings.agents.page.field.mode"),info:t("settings.agents.page.field.modeTooltip"),children:s.jsx(Zs,{"aria-label":t("settings.agents.page.field.mode"),value:v,onChange:N,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(ot,{title:t("settings.agents.page.section.modelParameters"),contentClassName:"space-y-3",children:[s.jsx(Jt,{settingsItem:"agents.model",label:t("settings.agents.page.field.overrideModel"),children:s.jsx(ni,{providerId:Kn(P)?.providerId??"",modelId:Kn(P)?.modelId??"",onChange:(A,C)=>{F(A&&C?`${A}/${C}`:""),j("")},className:ta})}),s.jsx(Jt,{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:X?s.jsxs(At,{value:Y,onValueChange:A=>j(A==="__default"?"":A),children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{placeholder:t("settings.agents.page.field.variantPlaceholder"),children:A=>A==="__default"?t("chat.modelControls.default"):A})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"__default",children:t("chat.modelControls.default")}),S.map(A=>s.jsx(yt,{value:A,children:A},A))]})]}):s.jsxs(s.Fragment,{children:[s.jsx(tt,{value:w,onChange:A=>j(A.target.value),placeholder:t("settings.agents.page.field.variantPlaceholder"),disabled:!P&&!w,className:"h-8 w-40 rounded-md px-3"}),w&&s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>j(""),className:Ts,"aria-label":t("settings.common.actions.clear"),title:t("settings.common.actions.clear"),children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})})]})}),s.jsxs(Jt,{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(Cs,{value:y,fallbackValue:.7,onValueChange:R,onClear:()=>R(void 0),min:0,max:2,step:.1,inputMode:"decimal",placeholder:"—",emptyLabel:"—",className:"w-16"}),y!==void 0&&s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>R(void 0),className:Ts,"aria-label":t("settings.agents.page.field.clearTemperatureAria"),title:t("settings.common.actions.clear"),children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})})]}),s.jsxs(Jt,{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(Cs,{value:_,fallbackValue:.9,onValueChange:B,onClear:()=>B(void 0),min:0,max:1,step:.1,inputMode:"decimal",placeholder:"—",emptyLabel:"—",className:"w-16"}),_!==void 0&&s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>B(void 0),className:Ts,"aria-label":t("settings.agents.page.field.clearTopPAria"),title:t("settings.common.actions.clear"),children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})})]})]}),s.jsx(ot,{title:t("settings.agents.page.section.systemPrompt"),settingsItem:"agents.system-prompt",children:s.jsx(js,{value:D,onChange:A=>k(A.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(rh,{agent:p}),s.jsx("div",{className:"pb-8",children:s.jsx(Q,{onClick:Z,disabled:T||!W,size:"xs",className:"!font-normal",children:t(T?"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(L,{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")})]})})},ch="~/.config/opencode/AGENTS.md",$d=async(t,e)=>{const n=await t.json().catch(()=>null);return typeof n?.error=="string"&&n.error.trim()?n.error:e},dh=t=>t.length>0&&!t.endsWith(`
|
|
2
|
+
`)?`${t}
|
|
3
|
+
`:t,Ci={prompt:"",optimizeSystemPrompt:!1,responseStyleEnabled:!1,responseStylePreset:"concise",responseStyleCustomInstructions:""},uh=(t,e)=>t==="custom"?e:Xm(t),mh=t=>t==="custom"?"custom":wd(t)?t:"concise",Ul={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"},Lr=async(t,e)=>{Hs("saving");try{const n=await gt("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(await $d(n,e));Hs("saved")}catch(n){throw Hs("error"),n}},ph=()=>{const{t}=it(),e=Qm(),[n,a]=l.useState(""),[i,r]=l.useState(!1),[o,d]=l.useState(Ci.responseStyleEnabled),[c,p]=l.useState(Ci.responseStylePreset),[u,f]=l.useState(Ci.responseStyleCustomInstructions),[m,b]=l.useState(!0),[h,g]=l.useState(!1),[x,v]=l.useState(!1),[N,P]=l.useState(""),[F,w]=l.useState(!1),j=l.useRef(null);l.useEffect(()=>{const k=new AbortController;return(async()=>{try{const[M,O]=await Promise.all([gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"},signal:k.signal}),gt("/api/behavior/agents-md",{method:"GET",headers:{Accept:"application/json"},signal:k.signal})]);let V=Ci;if(M.ok){const U=await M.json();V={...V,optimizeSystemPrompt:U.optimizeSystemPrompt===!0,responseStyleEnabled:U.responseStyleEnabled===!0,responseStylePreset:mh(U.responseStylePreset),responseStyleCustomInstructions:typeof U.responseStyleCustomInstructions=="string"?U.responseStyleCustomInstructions:""},typeof U.globalBehaviorPrompt=="string"&&(V={...V,prompt:U.globalBehaviorPrompt})}if(!V.prompt.trim()&&O.ok){const U=await O.json();typeof U.content=="string"&&(V={...V,prompt:U.content})}a(V.prompt),r(V.optimizeSystemPrompt),w(V.optimizeSystemPrompt),d(V.responseStyleEnabled),p(V.responseStylePreset),f(V.responseStyleCustomInstructions),P(V.prompt),j.current={enabled:V.responseStyleEnabled,preset:V.responseStylePreset,custom:V.responseStyleCustomInstructions}}catch(M){M.name!=="AbortError"&&console.warn("Failed to load behavior settings:",M)}finally{b(!1)}})(),()=>k.abort()},[]),l.useEffect(()=>{if(m)return;const k=j.current;if(k&&k.enabled===o&&k.preset===c&&k.custom===u)return;const T={enabled:o,preset:c,custom:u},M=setTimeout(async()=>{try{await Lr({responseStyleEnabled:T.enabled,responseStylePreset:T.preset,responseStyleCustomInstructions:T.custom},t("settings.behavior.page.toast.saveFailed")),j.current=T}catch(O){const V=O instanceof Error?O.message:t("settings.behavior.page.toast.saveFailed");G.error(V)}},400);return()=>clearTimeout(M)},[o,c,u,m,t]);const y=uh(c,u),R=n!==N,_=i!==F,B=async()=>{g(!0);try{const k=dh(n),T=await gt("/api/behavior/agents-md",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({content:k})});if(!T.ok)throw new Error(await $d(T,t("settings.behavior.page.toast.saveFailed")));await Lr({globalBehaviorPrompt:k},t("settings.behavior.page.toast.saveFailed")),a(k),P(k),G.success(t("settings.behavior.page.toast.saved"))}catch(k){console.error("Failed to save behavior:",k);const T=k instanceof Error?k.message:t("settings.behavior.page.toast.saveFailed");G.error(T)}finally{g(!1)}},D=async()=>{v(!0);try{await Lr({optimizeSystemPrompt:i},t("settings.behavior.page.toast.saveFailed")),w(i)}catch(k){const T=k instanceof Error?k.message:t("settings.behavior.page.toast.saveFailed");G.error(T),v(!1);return}try{await ea({message:t("settings.behavior.page.systemPromptOptimization.restarting"),mode:"projects",scopes:["all"]})}catch(k){const T=k instanceof Error?k.message:t("settings.behavior.page.toast.saveFailed");G.error(T)}finally{v(!1)}};return s.jsxs(us,{title:t("settings.behavior.page.title"),description:t("settings.page.behavior.description"),showSaveStatus:!0,children:[!e&&s.jsxs(ot,{title:t("settings.behavior.page.section.systemPromptOptimization"),divider:!1,settingsItem:"behavior.system-prompt-optimization",contentClassName:"space-y-3",children:[s.jsx(wt,{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(Q,{type:"button",size:"xs",onClick:()=>{D()},disabled:m||x||!_,className:"!font-normal",children:t(x?"settings.common.actions.saving":"settings.openchamber.opencodeCli.actions.saveAndReload")})]}),s.jsxs(ot,{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:ch})})]}),settingsItem:"behavior.system-prompt",contentClassName:"space-y-3",children:[s.jsx(js,{value:n,onChange:k=>a(k.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(Q,{onClick:B,disabled:h||!R||m,size:"xs",className:"!font-normal",children:t(h?"settings.common.actions.saving":"settings.common.actions.saveChanges")})]}),s.jsxs(ot,{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(wt,{checked:o,onChange:d,disabled:m,label:t("settings.behavior.page.responseStyle.enable"),ariaLabel:t("settings.behavior.page.responseStyle.enableAria")}),s.jsx(Jt,{label:t("settings.behavior.page.responseStyle.preset"),alignEnd:!1,children:s.jsxs(At,{value:c,onValueChange:k=>p(k),disabled:m||!o,children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{children:k=>k==="custom"?t("settings.behavior.page.responseStyle.option.custom"):wd(k)?t(Ul[k]):null})}),s.jsxs(Tt,{children:[Ym.map(k=>s.jsx(yt,{value:k,children:t(Ul[k])},k)),s.jsx(yt,{value:"custom",children:t("settings.behavior.page.responseStyle.option.custom")})]})]})}),s.jsx(js,{value:y,onChange:k=>f(k.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"})]})]})},gh=t=>{const e=Ye.c(169),{onItemSelect:n}=t,{t:a}=it(),[i,r]=l.useState(null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,f]=l.useState(null),[m,b]=l.useState(!1),[h,g]=l.useState(null),{selectedCommandName:x,commands:v,setSelectedCommand:N,setCommandDraft:P,createCommand:F,deleteCommand:w,loadCommands:j}=rr(zs(fh)),y=Nn(hh),R=Nn(xh);let _,B;e[0]!==j||e[1]!==R?(_=()=>{j(),R()},B=[j,R],e[0]=j,e[1]=R,e[2]=_,e[3]=B):(_=e[2],B=e[3]),l.useEffect(_,B);let D;e[4]!==y?(D=new Set(y.map(bh)),e[4]=y,e[5]=D):D=e[5];const k=D;let T;if(e[6]!==v||e[7]!==k){let Se;e[9]!==k?(Se=qe=>!k.has(qe.name),e[9]=k,e[10]=Se):Se=e[10],T=v.filter(Se),e[6]=v,e[7]=k,e[8]=T}else T=e[8];const M=T;let O,V;e[11]!==x||e[12]!==N||e[13]!==k?(O=()=>{x&&k.has(x)&&N(null)},V=[x,N,k],e[11]=x,e[12]=N,e[13]=k,e[14]=O,e[15]=V):(O=e[14],V=e[15]),l.useEffect(O,V);let U;e[16]!==v||e[17]!==n||e[18]!==P||e[19]!==N?(U=()=>{let Se="new-command",qe=1;for(;v.some(Ze=>Ze.name===Se);)Se=`new-command-${qe}`,qe++;P({name:Se,scope:"user"}),N(Se),n?.()},e[16]=v,e[17]=n,e[18]=P,e[19]=N,e[20]=U):U=e[20];const Y=U;let X;e[21]!==a?(X=async Se=>{if(Ia(Se)){G.error(a("settings.commands.sidebar.toast.builtInCannotDelete"));return}p(Se),f("delete")},e[21]=a,e[22]=X):X=e[22];const S=X;let W;e[23]===Symbol.for("react.memo_cache_sentinel")?(W=async Se=>{Ia(Se)&&(p(Se),f("reset"))},e[23]=W):W=e[23];const Z=W;let A;e[24]===Symbol.for("react.memo_cache_sentinel")?(A=()=>{p(null),f(null)},e[24]=A):A=e[24];const C=A;let z;e[25]!==c||e[26]!==u||e[27]!==w||e[28]!==a?(z=async()=>{if(!c||!u)return;b(!0),await w(c.name)?(u==="delete"?G.success(a("settings.commands.sidebar.toast.commandDeleted",{name:c.name})):G.success(a("settings.commands.sidebar.toast.commandReset",{name:c.name})),C()):u==="delete"?G.error(a("settings.commands.sidebar.toast.deleteFailed")):G.error(a("settings.commands.sidebar.toast.resetFailed")),b(!1)},e[25]=c,e[26]=u,e[27]=w,e[28]=a,e[29]=z):z=e[29];const $=z;let H;e[30]!==v||e[31]!==P||e[32]!==N?(H=Se=>{const qe=Se.name;let Ze=1,nt=`${qe}-copy`;for(;v.some(ft=>ft.name===nt);)Ze++,nt=`${qe}-copy-${Ze}`;P({name:nt,scope:Se.scope||"user",description:Se.description,template:Se.template,agent:Se.agent,model:Se.model}),N(nt)},e[30]=v,e[31]=P,e[32]=N,e[33]=H):H=e[33];const J=H;let ee;e[34]===Symbol.for("react.memo_cache_sentinel")?(ee=Se=>{d(Se.name),r(Se)},e[34]=ee):ee=e[34];const ue=ee;let re;e[35]!==v||e[36]!==F||e[37]!==w||e[38]!==i||e[39]!==o||e[40]!==N||e[41]!==a?(re=async()=>{if(!i)return;const Se=o.trim().replace(/\s+/g,"-");if(!Se){G.error(a("settings.commands.sidebar.toast.commandNameRequired"));return}if(Se===i.name){r(null);return}if(v.some(Ze=>Ze.name===Se)){G.error(a("settings.commands.sidebar.toast.commandExists"));return}await F({name:Se,description:i.description,template:i.template,agent:i.agent,model:i.model})?await w(i.name)?(G.success(`Command renamed to "${Se}"`),N(Se)):G.error(a("settings.commands.sidebar.toast.removeOldAfterRenameFailed")):G.error(a("settings.commands.sidebar.toast.renameFailed")),r(null)},e[35]=v,e[36]=F,e[37]=w,e[38]=i,e[39]=o,e[40]=N,e[41]=a,e[42]=re):re=e[42];const xe=re;let be,he,ye,fe,ae,ce;if(e[43]!==M||e[44]!==Y||e[45]!==S||e[46]!==J||e[47]!==n||e[48]!==h||e[49]!==x||e[50]!==N||e[51]!==a){const Se=M.filter(Ia),qe=M.filter(yh);e[58]===Symbol.for("react.memo_cache_sentinel")?(ae=le("flex h-full flex-col","bg-background"),e[58]=ae):ae=e[58];let Ze;e[59]!==a?(Ze=a("settings.commands.sidebar.title"),e[59]=a,e[60]=Ze):Ze=e[60];let nt;e[61]!==Ze?(nt=s.jsx("h2",{className:`${dn} mb-3`,children:Ze}),e[61]=Ze,e[62]=nt):nt=e[62];let ft;e[63]===Symbol.for("react.memo_cache_sentinel")?(ft=s.jsx(ci,{className:"mb-3"}),e[63]=ft):ft=e[63];let vt;e[64]!==M.length||e[65]!==a?(vt=a("settings.commands.sidebar.total",{count:M.length}),e[64]=M.length,e[65]=a,e[66]=vt):vt=e[66];let St;e[67]!==vt?(St=s.jsx("span",{className:"typography-meta text-muted-foreground",children:vt}),e[67]=vt,e[68]=St):St=e[68];let de;e[69]===Symbol.for("react.memo_cache_sentinel")?(de=s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),e[69]=de):de=e[69];let ie;e[70]!==Y?(ie=s.jsx(Q,{size:"sm","data-settings-item":"commands.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:Y,children:de}),e[70]=Y,e[71]=ie):ie=e[71];let we;e[72]!==St||e[73]!==ie?(we=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[St,ie]}),e[72]=St,e[73]=ie,e[74]=we):we=e[74],e[75]!==nt||e[76]!==we?(ce=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[nt,ft,we]}),e[75]=nt,e[76]=we,e[77]=ce):ce=e[77],be=Bs,he="flex-1 min-h-0",ye="space-y-1 px-3 py-2",fe=M.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(L,{name:"terminal-box",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:a("settings.commands.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:a("settings.commands.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[Se.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:a("settings.commands.sidebar.section.builtIn")}),[...Se].sort(vh).map(me=>s.jsx(_l,{command:me,isSelected:x===me.name,onSelect:()=>{N(me.name),n?.()},onReset:()=>Z(me),onDuplicate:()=>J(me),isMenuOpen:h===me.name,onMenuOpenChange:Je=>g(Je?me.name:null)},me.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(wh).map(me=>s.jsx(_l,{command:me,isSelected:x===me.name,onSelect:()=>{N(me.name),n?.()},onRename:()=>ue(me),onDelete:()=>S(me),onDuplicate:()=>J(me),isMenuOpen:h===me.name,onMenuOpenChange:Je=>g(Je?me.name:null)},me.name))]})]}),e[43]=M,e[44]=Y,e[45]=S,e[46]=J,e[47]=n,e[48]=h,e[49]=x,e[50]=N,e[51]=a,e[52]=be,e[53]=he,e[54]=ye,e[55]=fe,e[56]=ae,e[57]=ce}else be=e[52],he=e[53],ye=e[54],fe=e[55],ae=e[56],ce=e[57];let pe;e[78]!==be||e[79]!==he||e[80]!==ye||e[81]!==fe?(pe=s.jsx(be,{outerClassName:he,className:ye,children:fe}),e[78]=be,e[79]=he,e[80]=ye,e[81]=fe,e[82]=pe):pe=e[82];const q=c!==null&&u!==null;let te;e[83]!==m?(te=Se=>{!Se&&!m&&C()},e[83]=m,e[84]=te):te=e[84];let ne;e[85]!==u||e[86]!==a?(ne=a(u==="delete"?"settings.commands.sidebar.dialog.deleteTitle":"settings.commands.sidebar.dialog.resetTitle"),e[85]=u,e[86]=a,e[87]=ne):ne=e[87];let oe;e[88]!==ne?(oe=s.jsx(zt,{children:ne}),e[88]=ne,e[89]=oe):oe=e[89];let Ae;e[90]!==c?.name||e[91]!==u||e[92]!==a?(Ae=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]=Ae):Ae=e[93];let je;e[94]!==Ae?(je=s.jsx(qt,{children:Ae}),e[94]=Ae,e[95]=je):je=e[95];let Ie;e[96]!==oe||e[97]!==je?(Ie=s.jsxs(Ut,{children:[oe,je]}),e[96]=oe,e[97]=je,e[98]=Ie):Ie=e[98];let Te;e[99]!==a?(Te=a("settings.common.actions.cancel"),e[99]=a,e[100]=Te):Te=e[100];let Me;e[101]!==m||e[102]!==Te?(Me=s.jsx(Q,{size:"sm",variant:"ghost",onClick:C,disabled:m,children:Te}),e[101]=m,e[102]=Te,e[103]=Me):Me=e[103];let He;e[104]!==u||e[105]!==a?(He=a(u==="delete"?"settings.common.actions.delete":"settings.common.actions.reset"),e[104]=u,e[105]=a,e[106]=He):He=e[106];let Ve;e[107]!==$||e[108]!==m||e[109]!==He?(Ve=s.jsx(Q,{size:"sm",onClick:$,disabled:m,children:He}),e[107]=$,e[108]=m,e[109]=He,e[110]=Ve):Ve=e[110];let Ue;e[111]!==Me||e[112]!==Ve?(Ue=s.jsxs(Zt,{children:[Me,Ve]}),e[111]=Me,e[112]=Ve,e[113]=Ue):Ue=e[113];let ze;e[114]!==Ie||e[115]!==Ue?(ze=s.jsxs(Ft,{className:"max-w-md",children:[Ie,Ue]}),e[114]=Ie,e[115]=Ue,e[116]=ze):ze=e[116];let Be;e[117]!==q||e[118]!==te||e[119]!==ze?(Be=s.jsx(Lt,{open:q,onOpenChange:te,children:ze}),e[117]=q,e[118]=te,e[119]=ze,e[120]=Be):Be=e[120];const Ge=i!==null;let Fe;e[121]===Symbol.for("react.memo_cache_sentinel")?(Fe=Se=>!Se&&r(null),e[121]=Fe):Fe=e[121];let ve;e[122]!==a?(ve=a("settings.commands.sidebar.renameDialog.title"),e[122]=a,e[123]=ve):ve=e[123];let De;e[124]!==ve?(De=s.jsx(zt,{children:ve}),e[124]=ve,e[125]=De):De=e[125];const Ke=i?.name??"";let We;e[126]!==a||e[127]!==Ke?(We=a("settings.commands.sidebar.renameDialog.description",{name:Ke}),e[126]=a,e[127]=Ke,e[128]=We):We=e[128];let Pe;e[129]!==We?(Pe=s.jsx(qt,{children:We}),e[129]=We,e[130]=Pe):Pe=e[130];let at;e[131]!==De||e[132]!==Pe?(at=s.jsxs(Ut,{children:[De,Pe]}),e[131]=De,e[132]=Pe,e[133]=at):at=e[133];let se;e[134]===Symbol.for("react.memo_cache_sentinel")?(se=Se=>d(Se.target.value),e[134]=se):se=e[134];let I;e[135]!==a?(I=a("settings.commands.sidebar.renameDialog.placeholder"),e[135]=a,e[136]=I):I=e[136];let Ee;e[137]!==xe?(Ee=Se=>{Se.key==="Enter"&&xe()},e[137]=xe,e[138]=Ee):Ee=e[138];let Le;e[139]!==o||e[140]!==I||e[141]!==Ee?(Le=s.jsx(tt,{value:o,onChange:se,placeholder:I,className:"text-foreground placeholder:text-muted-foreground",onKeyDown:Ee}),e[139]=o,e[140]=I,e[141]=Ee,e[142]=Le):Le=e[142];let _e;e[143]===Symbol.for("react.memo_cache_sentinel")?(_e=()=>r(null),e[143]=_e):_e=e[143];let Xe;e[144]!==a?(Xe=a("settings.common.actions.cancel"),e[144]=a,e[145]=Xe):Xe=e[145];let ct;e[146]!==Xe?(ct=s.jsx(Q,{size:"sm",variant:"ghost",onClick:_e,children:Xe}),e[146]=Xe,e[147]=ct):ct=e[147];let ut;e[148]!==a?(ut=a("settings.common.actions.rename"),e[148]=a,e[149]=ut):ut=e[149];let lt;e[150]!==xe||e[151]!==ut?(lt=s.jsx(Q,{size:"sm",onClick:xe,children:ut}),e[150]=xe,e[151]=ut,e[152]=lt):lt=e[152];let rt;e[153]!==ct||e[154]!==lt?(rt=s.jsxs(Zt,{children:[ct,lt]}),e[153]=ct,e[154]=lt,e[155]=rt):rt=e[155];let mt;e[156]!==at||e[157]!==Le||e[158]!==rt?(mt=s.jsxs(Ft,{children:[at,Le,rt]}),e[156]=at,e[157]=Le,e[158]=rt,e[159]=mt):mt=e[159];let xt;e[160]!==Ge||e[161]!==mt?(xt=s.jsx(Lt,{open:Ge,onOpenChange:Fe,children:mt}),e[160]=Ge,e[161]=mt,e[162]=xt):xt=e[162];let It;return e[163]!==ae||e[164]!==ce||e[165]!==pe||e[166]!==Be||e[167]!==xt?(It=s.jsxs("div",{className:ae,children:[ce,pe,Be,xt]}),e[163]=ae,e[164]=ce,e[165]=pe,e[166]=Be,e[167]=xt,e[168]=It):It=e[168],It},_l=t=>{const e=Ye.c(47),{command:n,isSelected:a,onSelect:i,onDelete:r,onReset:o,onRename:d,onDuplicate:c,isMenuOpen:p,onMenuOpenChange:u}=t,{t:f}=it();let m;e[0]===Symbol.for("react.memo_cache_sentinel")?(m=si(),e[0]=m):m=e[0];const b=m,[h,g]=l.useState(!1);let x;e[1]!==r||e[2]!==c||e[3]!==d||e[4]!==o||e[5]!==f?(x=X=>s.jsxs(s.Fragment,{children:[d&&s.jsxs(X,{onClick:S=>{S.stopPropagation(),d()},children:[s.jsx(L,{name:"edit",className:"h-4 w-4 mr-px"}),f("settings.common.actions.rename")]}),s.jsxs(X,{onClick:S=>{S.stopPropagation(),c()},children:[s.jsx(L,{name:"file-copy",className:"h-4 w-4 mr-px"}),f("settings.common.actions.duplicate")]}),o&&s.jsxs(X,{onClick:S=>{S.stopPropagation(),o()},children:[s.jsx(L,{name:"restart",className:"h-4 w-4 mr-px"}),f("settings.common.actions.reset")]}),r&&s.jsxs(X,{onClick:S=>{S.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{name:"delete-bin",className:"h-4 w-4 mr-px"}),f("settings.common.actions.delete")]})]}),e[1]=r,e[2]=c,e[3]=d,e[4]=o,e[5]=f,e[6]=x):x=e[6];const v=x,N=a?"bg-interactive-selection":"hover:bg-interactive-hover";let P;e[7]!==N?(P=le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",N),e[7]=N,e[8]=P):P=e[8];let F;e[9]===Symbol.for("react.memo_cache_sentinel")?(F=b?void 0:X=>{X.preventDefault(),g(!0)},e[9]=F):F=e[9];let w;e[10]!==P?(w=s.jsx("div",{className:P,onContextMenu:F}),e[10]=P,e[11]=w):w=e[11];let j;e[12]!==n.name?(j=s.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",n.name]}),e[12]=n.name,e[13]=j):j=e[13];let y;e[14]!==n||e[15]!==f?(y=(n.scope||Ia(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:Ia(n)?f("settings.agents.sidebar.badge.system"):n.scope}),e[14]=n,e[15]=f,e[16]=y):y=e[16];let R;e[17]!==j||e[18]!==y?(R=s.jsxs("div",{className:"flex items-center gap-2",children:[j,y]}),e[17]=j,e[18]=y,e[19]=R):R=e[19];let _;e[20]!==n.description?(_=n.description&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n.description}),e[20]=n.description,e[21]=_):_=e[21];let B;e[22]!==i||e[23]!==_||e[24]!==R?(B=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:[R,_]}),e[22]=i,e[23]=_,e[24]=R,e[25]=B):B=e[25];let D;e[26]!==u?(D=X=>{X&&g(!1),u(X)},e[26]=u,e[27]=D):D=e[27];let k;e[28]===Symbol.for("react.memo_cache_sentinel")?(k=s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[28]=k):k=e[28];let T;e[29]!==v?(T=s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:v(bs)}),e[29]=v,e[30]=T):T=e[30];let M;e[31]!==p||e[32]!==D||e[33]!==T?(M=s.jsxs(ws,{open:p,onOpenChange:D,children:[k,T]}),e[31]=p,e[32]=D,e[33]=T,e[34]=M):M=e[34];let O;e[35]!==B||e[36]!==M?(O=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[B,M]}),e[35]=B,e[36]=M,e[37]=O):O=e[37];let V;e[38]!==O||e[39]!==w?(V=s.jsx(_n,{render:w,children:O}),e[38]=O,e[39]=w,e[40]=V):V=e[40];let U;e[41]!==v?(U=s.jsx($n,{className:"w-fit min-w-20",children:v(En)}),e[41]=v,e[42]=U):U=e[42];let Y;return e[43]!==h||e[44]!==V||e[45]!==U?(Y=s.jsxs(Un,{open:h,onOpenChange:g,children:[V,U]}),e[43]=h,e[44]=V,e[45]=U,e[46]=Y):Y=e[46],Y};function fh(t){return{selectedCommandName:t.selectedCommandName,commands:t.commands,setSelectedCommand:t.setSelectedCommand,setCommandDraft:t.setCommandDraft,createCommand:t.createCommand,deleteCommand:t.deleteCommand,loadCommands:t.loadCommands}}function hh(t){return t.skills}function xh(t){return t.loadSkills}function bh(t){return t.name}function yh(t){return!Ia(t)}function vh(t,e){return t.name.localeCompare(e.name)}function wh(t,e){return t.name.localeCompare(e.name)}const jh=()=>{const{t}=it(),{selectedCommandName:e,getCommandByName:n,createCommand:a,updateCommand:i,commands:r,commandDraft:o,setCommandDraft:d}=rr(zs(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,f]=l.useState(""),[m,b]=l.useState("user"),[h,g]=l.useState(""),[x,v]=l.useState(""),[N,P]=l.useState(""),[F,w]=l.useState(""),[j,y]=l.useState(!1),R=l.useRef(null);l.useEffect(()=>{if(p&&o){const D=o.name||"",k=o.scope||"user",T=o.description||"",M=o.agent||"",O=o.model||"",V=o.template||"";f(D),b(k),g(T),v(M),P(O),w(V),R.current={draftName:D,draftScope:k,description:T,agent:M,model:O,template:V}}else if(c){const D=c.description||"",k=c.agent||"",T=c.model||"",M=c.template||"";g(D),v(k),P(T),w(M),R.current={draftName:"",draftScope:"user",description:D,agent:k,model:T,template:M}}},[c,p,e,r,o]);const _=l.useMemo(()=>{const D=R.current;return D?!!(p&&(u!==D.draftName||m!==D.draftScope)||h!==D.description||x!==D.agent||N!==D.model||F!==D.template):!1},[x,h,u,m,p,N,F]),B=async()=>{const D=p?u.trim().replace(/\s+/g,"-"):e?.trim();if(!D){G.error(t("settings.commands.sidebar.toast.commandNameRequired"));return}if(!F.trim()){G.error(t("settings.commands.page.toast.templateRequired"));return}if(p&&r.some(k=>k.name===D)){G.error(t("settings.commands.sidebar.toast.commandExists"));return}y(!0);try{const k=x.trim(),T=N.trim(),M=F.trim(),O={name:D,description:h.trim()||void 0,agent:k===""?null:k,model:T===""?null:T,template:M,scope:p?m:void 0};let V;p?(V=await a(O),V&&d(null)):V=await i(D,O),V?G.success(t(p?"settings.commands.page.toast.created":"settings.commands.page.toast.updated")):G.error(t(p?"settings.commands.page.toast.createFailed":"settings.commands.page.toast.updateFailed"))}catch(k){console.error("Error saving command:",k),G.error(t("settings.commands.page.toast.saveUnexpectedError"))}finally{y(!1)}};return e?s.jsxs(us,{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(ot,{title:t("settings.commands.page.section.identity"),divider:!1,contentClassName:"space-y-0",children:[p&&s.jsxs(Jt,{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(tt,{value:u,onChange:D=>f(D.target.value),placeholder:t("settings.commands.page.field.commandNamePlaceholder"),className:"h-7 w-40 px-2"})]}),s.jsxs(At,{value:m,onValueChange:D=>b(D),children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[100px]",children:s.jsx(Vt,{placeholder:t("settings.agents.page.field.scopePlaceholder")})}),s.jsxs(Tt,{align:"end",children:[s.jsx(yt,{value:"user",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.global")})]})}),s.jsx(yt,{value:"project",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(L,{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(js,{value:h,onChange:D=>g(D.target.value),placeholder:t("settings.commands.page.field.descriptionPlaceholder"),rows:2,className:"w-full resize-none min-h-[60px] bg-transparent"})})]})]}),s.jsxs(ot,{title:t("settings.commands.page.section.executionContext"),contentClassName:"space-y-0",children:[s.jsx(Jt,{settingsItem:"commands.agent",label:t("settings.commands.page.field.overrideAgent"),children:s.jsx(jd,{agentName:x,onChange:D=>v(D),className:ta})}),s.jsx(Jt,{settingsItem:"commands.model",label:t("settings.agents.page.field.overrideModel"),children:s.jsx(ni,{providerId:Kn(N)?.providerId??"",modelId:Kn(N)?.modelId??"",onChange:(D,k)=>{P(D&&k?`${D}/${k}`:"")},className:ta})})]}),s.jsxs(ot,{title:t("settings.commands.page.section.template"),settingsItem:"commands.template",children:[s.jsx(js,{value:F,onChange:D=>w(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(Q,{onClick:B,disabled:j||!_,size:"xs",className:"!font-normal",children:t(j?"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(L,{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")})]})})},$l=t=>{switch(t){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"idle"}},Vl=t=>{const e=Ye.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=le("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},kh=t=>{const e=Ye.c(120),{onItemSelect:n}=t,{t:a}=it(),{mcpServers:i,selectedMcpName:r,setSelectedMcp:o,setMcpDraft:d,loadMcpConfigs:c,deleteMcp:p}=Ta(zs(Nh)),u=Ls(Sh);let f;e[0]!==u?(f=Pe=>Pe.getStatusForDirectory(u??null),e[0]=u,e[1]=f):f=e[1];const m=gs(f),b=gs(Ch),h=gs(Ih),[g,x]=l.useState(null),[v,N]=l.useState(!1),[P,F]=l.useState(null),[w,j]=l.useState(null),[y,R]=l.useState(!1);let _;e[2]!==i?(_=i.filter(Ph),e[2]=i,e[3]=_):_=e[3];const B=_;let D;e[4]!==i?(D=i.filter(Ah),e[4]=i,e[5]=D):D=e[5];const k=D;let T,M;e[6]!==c?(T=()=>{c()},M=[c],e[6]=c,e[7]=T,e[8]=M):(T=e[7],M=e[8]),l.useEffect(T,M);let O;e[9]!==u||e[10]!==h||e[11]!==y||e[12]!==b?(O=()=>{if(y)return;R(!0);const Pe=new Promise(Eh);Promise.all([b({directory:u,silent:!0}),Pe]).then(()=>{const at=h(u);at&&G.error(at)}).finally(()=>{R(!1)})},e[9]=u,e[10]=h,e[11]=y,e[12]=b,e[13]=O):O=e[13];const V=O;let U;e[14]!==i||e[15]!==n||e[16]!==d||e[17]!==o?(U=()=>{let Pe="new-mcp-server",at=1;for(;i.some(I=>I.name===Pe);)Pe=`new-mcp-server-${at}`,at++;d({name:Pe,scope:"user",type:"local",command:[],url:"",environment:[],headers:[],oauthEnabled:!0,oauthClientId:"",oauthClientSecret:"",oauthScope:"",oauthRedirectUri:"",timeout:"",enabled:!0}),o(Pe),n?.()},e[14]=i,e[15]=n,e[16]=d,e[17]=o,e[18]=U):U=e[18];const Y=U;let X;e[19]!==p||e[20]!==g||e[21]!==a?(X=async()=>{if(!g)return;N(!0);const Pe=await p(g.name);Pe.ok?Pe.reloadFailed?G.warning(Pe.message||`MCP server "${g.name}" deleted, but OpenCode reload failed`,{description:Pe.warning||a("settings.mcp.sidebar.toast.refreshListIfStale")}):G.success(Pe.message||a("settings.mcp.sidebar.toast.serverDeleted",{name:g.name})):G.error(a("settings.mcp.sidebar.toast.deleteFailed")),x(null),N(!1)},e[19]=p,e[20]=g,e[21]=a,e[22]=X):X=e[22];const S=X;let W;e[23]!==a?(W=(Pe,at)=>s.jsxs(at,{onClick:se=>{se.stopPropagation(),x(Pe)},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{name:"delete-bin",className:"h-4 w-4 mr-px"}),a("settings.common.actions.delete")]}),e[23]=a,e[24]=W):W=e[24];const Z=W;let A;e[25]===Symbol.for("react.memo_cache_sentinel")?(A=le("flex h-full flex-col","bg-background"),e[25]=A):A=e[25];let C;e[26]!==a?(C=a("settings.mcp.sidebar.title"),e[26]=a,e[27]=C):C=e[27];let z;e[28]!==C?(z=s.jsx("h2",{className:dn,children:C}),e[28]=C,e[29]=z):z=e[29];let $;e[30]!==a?($=a("settings.mcp.sidebar.actions.refreshStatusAria"),e[30]=a,e[31]=$):$=e[31];let H;e[32]!==a?(H=a("settings.mcp.sidebar.actions.refreshStatusTitle"),e[32]=a,e[33]=H):H=e[33];const J=y&&"animate-spin";let ee;e[34]!==J?(ee=le("h-4 w-4",J),e[34]=J,e[35]=ee):ee=e[35];let ue;e[36]!==ee?(ue=s.jsx(L,{name:"refresh",className:ee}),e[36]=ee,e[37]=ue):ue=e[37];let re;e[38]!==V||e[39]!==y||e[40]!==$||e[41]!==H||e[42]!==ue?(re=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:y,onClick:V,"aria-label":$,title:H,children:ue}),e[38]=V,e[39]=y,e[40]=$,e[41]=H,e[42]=ue,e[43]=re):re=e[43];let xe;e[44]!==z||e[45]!==re?(xe=s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[z,re]}),e[44]=z,e[45]=re,e[46]=xe):xe=e[46];let be;e[47]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx(ci,{className:"mb-3"}),e[47]=be):be=e[47];let he;e[48]!==i.length||e[49]!==a?(he=a("settings.mcp.sidebar.total",{count:i.length}),e[48]=i.length,e[49]=a,e[50]=he):he=e[50];let ye;e[51]!==he?(ye=s.jsx("span",{className:"typography-meta text-muted-foreground",children:he}),e[51]=he,e[52]=ye):ye=e[52];let fe;e[53]!==a?(fe=a("settings.mcp.sidebar.actions.addServerTitle"),e[53]=a,e[54]=fe):fe=e[54];let ae;e[55]===Symbol.for("react.memo_cache_sentinel")?(ae=s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),e[55]=ae):ae=e[55];let ce;e[56]!==Y||e[57]!==fe?(ce=s.jsx(Q,{size:"sm","data-settings-item":"mcp.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:Y,title:fe,children:ae}),e[56]=Y,e[57]=fe,e[58]=ce):ce=e[58];let pe;e[59]!==ye||e[60]!==ce?(pe=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[ye,ce]}),e[59]=ye,e[60]=ce,e[61]=pe):pe=e[61];let q;e[62]!==xe||e[63]!==pe?(q=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[xe,be,pe]}),e[62]=xe,e[63]=pe,e[64]=q):q=e[64];let te;e[65]!==i.length||e[66]!==m||e[67]!==n||e[68]!==P||e[69]!==B||e[70]!==Z||e[71]!==w||e[72]!==r||e[73]!==d||e[74]!==o||e[75]!==a||e[76]!==k?(te=s.jsx(Bs,{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(L,{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:[B.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")}),B.map(Pe=>{const at=m[Pe.name],se=$l(at?.status),I=r===Pe.name,Ee=si();return s.jsxs(Un,{open:w===Pe.name,onOpenChange:Le=>j(Le?Pe.name:null),children:[s.jsxs(_n,{render:s.jsx("div",{className:le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",I?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:Ee?void 0:Le=>{Le.preventDefault(),j(Pe.name)}}),children:[s.jsxs("button",{onClick:()=>{o(Pe.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(Vl,{tone:se,enabled:Pe.enabled}),s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:Pe.name}),s.jsx("span",{title:Pe.type==="local"?a("settings.mcp.sidebar.serverType.localTitle"):a("settings.mcp.sidebar.serverType.remoteTitle"),children:Pe.type==="local"?s.jsx(L,{name:"server",className:"h-3 w-3 text-muted-foreground/60 flex-shrink-0"}):s.jsx(L,{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:Pe.type==="local"?Pe.command?.join(" ")??"":Pe.url??""})]}),s.jsxs(ws,{open:P===Pe.name,onOpenChange:Le=>{Le&&j(null),F(Le?Pe.name:null)},children:[s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:Z(Pe,bs)})]})]}),s.jsx($n,{className:"w-fit min-w-20",children:Z(Pe,En)})]},Pe.name)})]}),k.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")}),k.map(Pe=>{const at=m[Pe.name],se=$l(at?.status),I=r===Pe.name,Ee=si();return s.jsxs(Un,{open:w===Pe.name,onOpenChange:Le=>j(Le?Pe.name:null),children:[s.jsxs(_n,{render:s.jsx("div",{className:le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",I?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:Ee?void 0:Le=>{Le.preventDefault(),j(Pe.name)}}),children:[s.jsxs("button",{onClick:()=>{o(Pe.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(Vl,{tone:se,enabled:Pe.enabled}),s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:Pe.name}),s.jsx("span",{title:Pe.type==="local"?a("settings.mcp.sidebar.serverType.localTitle"):a("settings.mcp.sidebar.serverType.remoteTitle"),children:Pe.type==="local"?s.jsx(L,{name:"server",className:"h-3 w-3 text-muted-foreground/60 flex-shrink-0"}):s.jsx(L,{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:Pe.type==="local"?Pe.command?.join(" ")??"":Pe.url??""})]}),s.jsxs(ws,{open:P===Pe.name,onOpenChange:Le=>{Le&&j(null),F(Le?Pe.name:null)},children:[s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:Z(Pe,bs)})]})]}),s.jsx($n,{className:"w-fit min-w-20",children:Z(Pe,En)})]},Pe.name)})]})]})}),e[65]=i.length,e[66]=m,e[67]=n,e[68]=P,e[69]=B,e[70]=Z,e[71]=w,e[72]=r,e[73]=d,e[74]=o,e[75]=a,e[76]=k,e[77]=te):te=e[77];const ne=g!==null;let oe;e[78]!==v?(oe=Pe=>{!Pe&&!v&&x(null)},e[78]=v,e[79]=oe):oe=e[79];let Ae;e[80]!==a?(Ae=a("settings.mcp.sidebar.deleteDialog.title"),e[80]=a,e[81]=Ae):Ae=e[81];let je;e[82]!==Ae?(je=s.jsx(zt,{children:Ae}),e[82]=Ae,e[83]=je):je=e[83];const Ie=g?.name||"";let Te;e[84]!==a||e[85]!==Ie?(Te=a("settings.mcp.sidebar.deleteDialog.descriptionPrefix",{name:Ie}),e[84]=a,e[85]=Ie,e[86]=Te):Te=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 He;e[88]!==Te?(He=s.jsxs(qt,{children:[Te," ",Me,"."]}),e[88]=Te,e[89]=He):He=e[89];let Ve;e[90]!==je||e[91]!==He?(Ve=s.jsxs(Ut,{children:[je,He]}),e[90]=je,e[91]=He,e[92]=Ve):Ve=e[92];let Ue;e[93]===Symbol.for("react.memo_cache_sentinel")?(Ue=()=>x(null),e[93]=Ue):Ue=e[93];let ze;e[94]!==a?(ze=a("settings.common.actions.cancel"),e[94]=a,e[95]=ze):ze=e[95];let Be;e[96]!==v||e[97]!==ze?(Be=s.jsx(Q,{size:"sm",variant:"ghost",onClick:Ue,disabled:v,children:ze}),e[96]=v,e[97]=ze,e[98]=Be):Be=e[98];let Ge;e[99]!==v||e[100]!==a?(Ge=a(v?"settings.mcp.sidebar.actions.deleting":"settings.common.actions.delete"),e[99]=v,e[100]=a,e[101]=Ge):Ge=e[101];let Fe;e[102]!==S||e[103]!==v||e[104]!==Ge?(Fe=s.jsx(Q,{size:"sm",onClick:S,disabled:v,children:Ge}),e[102]=S,e[103]=v,e[104]=Ge,e[105]=Fe):Fe=e[105];let ve;e[106]!==Be||e[107]!==Fe?(ve=s.jsxs(Zt,{children:[Be,Fe]}),e[106]=Be,e[107]=Fe,e[108]=ve):ve=e[108];let De;e[109]!==Ve||e[110]!==ve?(De=s.jsxs(Ft,{className:"max-w-md",children:[Ve,ve]}),e[109]=Ve,e[110]=ve,e[111]=De):De=e[111];let Ke;e[112]!==ne||e[113]!==oe||e[114]!==De?(Ke=s.jsx(Lt,{open:ne,onOpenChange:oe,children:De}),e[112]=ne,e[113]=oe,e[114]=De,e[115]=Ke):Ke=e[115];let We;return e[116]!==q||e[117]!==te||e[118]!==Ke?(We=s.jsxs("div",{className:A,children:[q,te,Ke]}),e[116]=q,e[117]=te,e[118]=Ke,e[119]=We):We=e[119],We};function Nh(t){return{mcpServers:t.mcpServers,selectedMcpName:t.selectedMcpName,setSelectedMcp:t.setSelectedMcp,setMcpDraft:t.setMcpDraft,loadMcpConfigs:t.loadMcpConfigs,deleteMcp:t.deleteMcp}}function Sh(t){return t.currentDirectory}function Ch(t){return t.refresh}function Ih(t){return t.getErrorForDirectory}function Ph(t){return t.scope==="project"}function Ah(t){return t.scope!=="project"}function Eh(t){return setTimeout(t,500)}function an(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Va(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function tn(t,e){return e!==void 0?{ok:!1,error:t,parsed:e}:{ok:!1,error:t}}function Ii(t,e,n){const a=Th(n),i=typeof n.url=="string"?n.url.trim():"",r=Hl(n,"env","environment"),o=Hl(n,"headers"),d=Rh(n),c=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.clientId??"").trim():"",p=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.clientSecret??"").trim():"",u=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.scope??"").trim():"",f=typeof n.oauth=="object"&&n.oauth!==null?String(n.oauth.redirectUri??"").trim():"",m=Dh(n),b=Mh(n);return{ok:!0,name:t,type:e,command:a,url:i,environment:r,headers:o,oauthEnabled:d,oauthClientId:c,oauthClientSecret:p,oauthScope:u,oauthRedirectUri:f,timeout:m,enabled:b}}function Th(t){const e=t.command,n=t.args;if(Va(e)&&Va(n))return[...e,...n];if(Va(e))return e;if(typeof e=="string"&&e.trim()){const a=e.trim().split(/\s+/);return Va(n)?[...a,...n]:a}return Va(n)?n:[]}function Hl(t,...e){for(const n of e){const a=t[n];if(!an(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 Rh(t){if(t.oauth===!1||t.oauth===null||t.oauth===void 0||!an(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 Dh(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 Mh(t){return"disabled"in t&&t.disabled===!0?!1:"enabled"in t?!!t.enabled:!0}function Lh(t){const e=t.mcpServers;if(an(e)){const a=Object.keys(e);if(a.length===1){const i=a[0],r=e[i];if(an(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"&&an(i)});if(n.length===1){const a=n[0],i=t[a];if(Vd(i))return{name:a,entry:i}}return null}function Vd(t){return t.type==="local"||t.type==="remote"||Array.isArray(t.command)||typeof t.url=="string"||Array.isArray(t.args)}function Fh(t,e){let n;try{const d=t.trim();if(!d)return tn("No JSON content provided");n=JSON.parse(d)}catch(d){return tn(d instanceof Error?`Invalid JSON: ${d.message}`:"Invalid JSON")}if(!an(n))return tn("Expected a JSON object, not an array or primitive");const a=n,i=a.mcpServers;if(an(i)){const d=Object.keys(i);if(d.length===0)return tn("mcpServers object is empty",n);if(d.length>1)return tn("Paste one server at a time. Found "+d.length+" servers in mcpServers",n);const c=d[0],p=i[c];return an(p)?Ii(c,Pi(p),p):tn("Server entry is not a valid object",n)}const r=a.mcp;if(an(r)){const d=Object.keys(r);if(d.length===0)return tn("mcp object is empty",n);if(d.length>1)return tn("Paste one server at a time. Found "+d.length+" servers in mcp",n);const c=d[0],p=r[c];return an(p)?Ii(c,Pi(p),p):tn("Server entry in mcp is not a valid object",n)}const o=Lh(a);if(o)return Ii(o.name,Pi(o.entry),o.entry);if(Vd(a)){const d=Pi(a),c=typeof a.name=="string"&&a.name.trim()?a.name.trim():e?.fallbackName;return Ii(c,d,a)}return tn("No recognizable MCP server configuration found in JSON",n)}function Pi(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 Oh(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 zh="/mcp/oauth/callback",Bh=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}},Kh=t=>{const e=Uh(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}},Hd=t=>{const e=t.get("state");return typeof e!="string"?null:e.trim()||null},Uh=t=>{if(typeof t!="string"||!t.trim())return null;const e=Bh(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}},sa=Ju,na=t=>{const e=Ye.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&&ge.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=le("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(qu,{className:c,...r,...d}),e[10]=r,e[11]=d,e[12]=c,e[13]=p):p=e[13],p},aa=t=>{const e=Ye.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=le("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(Qu,{className:i,...a}),e[5]=a,e[6]=i,e[7]=r):r=e[7],r};function _h(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 $h(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:Kh(n.searchParams),stateKey:Hd(n.searchParams)}}catch{}return{code:e,context:null,stateKey:null}}const Vh=({value:t,onChange:e,pasteCommandTitle:n,pasteCommandLabel:a,pasteSuccess:i,clipboardReadFailed:r,preview:o})=>{const[d,c]=l.useState(()=>t.join(`
|
|
4
|
+
`)),p=l.useRef(t);l.useEffect(()=>{JSON.stringify(p.current)!==JSON.stringify(t)&&(p.current=t,c(t.join(`
|
|
5
|
+
`)))},[t]);const u=m=>{const b=m.split(`
|
|
6
|
+
`).filter(h=>h.trim().length>0);e(b)},f=async()=>{try{const b=(await navigator.clipboard.readText()).trim(),h=b.includes(`
|
|
7
|
+
`)?b.split(`
|
|
8
|
+
`).filter(g=>g.trim()):_h(b);c(h.join(`
|
|
9
|
+
`)),e(h),G.success(i(h.length))}catch{G.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(Q,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:f,type:"button",title:n,children:[s.jsx(L,{name:"clipboard",className:"h-3 w-3"}),a]})}),s.jsx(js,{value:d,onChange:m=>{c(m.target.value),u(m.target.value)},onBlur:()=>{const m=d.split(`
|
|
10
|
+
`).map(b=>b.trimEnd()).join(`
|
|
11
|
+
`);c(m),u(m)},placeholder:`npx
|
|
12
|
+
-y
|
|
13
|
+
@modelcontextprotocol/server-postgres
|
|
14
|
+
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,b)=>s.jsxs("span",{className:"block",children:[s.jsxs("span",{className:"text-muted-foreground select-none mr-2",children:["[",b,"]"]}),m]},b))})})]})]})},Hh=t=>t.toUpperCase().replace(/[^A-Z0-9_]/g,"_"),Wl=({value:t,onChange:e,keyTransform:n=Hh,keyPlaceholder:a="API_KEY",keyInputClassName:i="w-36 shrink-0 font-mono typography-meta uppercase",pasteLabel:r="Paste .env",pasteTitle:o="Paste KEY=VALUE lines from clipboard",noPairsFoundError:d,importSuccess:c,clipboardReadFailed:p,keyLabel:u,valueLabel:f,valuePlaceholder:m,hideValueTitle:b,showValueTitle:h,addVariable:g,plainTextWarning:x,removeVariableAria:v})=>{const[N,P]=l.useState(new Set),F=()=>e([...t,{key:"",value:""}]),w=B=>{e(t.filter((D,k)=>k!==B)),P(D=>{const k=new Set(D);return k.delete(B),k})},j=(B,D,k)=>{const T=[...t];T[B]={...T[B],[D]:k},e(T)},y=B=>{P(D=>{const k=new Set(D);return k.has(B)?k.delete(B):k.add(B),k})},R=async()=>{try{const B=await navigator.clipboard.readText(),D=[];for(const T of B.split(`
|
|
15
|
+
`)){const M=T.trim();if(!M||M.startsWith("#"))continue;const O=M.indexOf("=");if(O===-1)continue;const V=M.slice(0,O).trim();let U=M.slice(O+1).trim();(U.startsWith('"')&&U.endsWith('"')||U.startsWith("'")&&U.endsWith("'"))&&(U=U.slice(1,-1)),V&&D.push({key:V,value:U})}if(D.length===0){G.error(d);return}const k=[...t];for(const T of D){const M=k.findIndex(O=>O.key===T.key);M!==-1?k[M]=T:k.push(T)}e(k),G.success(c(D.length))}catch{G.error(p)}},_=t.some(B=>B.value.length>0);return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"typography-micro text-muted-foreground w-32 shrink-0",children:u}),s.jsx("span",{className:"typography-micro text-muted-foreground",children:f})]}),s.jsxs(Q,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:R,type:"button",title:o,children:[s.jsx(L,{name:"clipboard",className:"h-3 w-3"}),r]})]}),s.jsx("div",{className:"space-y-1.5",children:t.map((B,D)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tt,{value:B.key,onChange:k=>j(D,"key",n(k.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(tt,{type:N.has(D)?"text":"password",value:B.value,onChange:k=>j(D,"value",k.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:()=>y(D),className:"absolute right-2 text-muted-foreground/60 hover:text-muted-foreground",title:N.has(D)?b:h,children:N.has(D)?s.jsx(L,{name:"eye-off",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"eye",className:"h-3.5 w-3.5"})})]}),s.jsx(Q,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 shrink-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>w(D),"aria-label":v,children:s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},D))}),s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:F,type:"button",children:[s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),g]}),_&&s.jsx("p",{className:"typography-micro text-muted-foreground/60",children:x})]})},Gl=t=>{const e=Ye.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 b=le("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:b,children:["● ",h]});break e}d=le("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},Wh=(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")}},Gh=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)]"}},qh=(t,e,n,a)=>!!(t==="failed"||t==="needs_auth"||t==="needs_client_registration"||e||n||a),ql=(t,e)=>{if(typeof window>"u")return null;const n=new URL(zh,La()||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()},Jh=async t=>{const e=await gt("/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")}},Qh=async t=>{const e=await gt(`/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},Ha=async t=>{typeof t!="string"||!t.trim()||await gt(`/api/mcp/auth/pending?state=${encodeURIComponent(t.trim())}`,{method:"DELETE"}).catch(()=>{})},Fr=(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},Yh=(t,e)=>{const n=typeof e=="string"&&e.trim()?e.trim():"__global__";return`${t??"__none__"}::${n}`},Xh=()=>{const{t}=it(),e=l.useCallback((Ce,jt)=>t(Ce,jt),[t]),{selectedMcpName:n,mcpServers:a,mcpDraft:i,setMcpDraft:r,setSelectedMcp:o,getMcpByName:d,createMcp:c,updateMcp:p,deleteMcp:u}=Ta(zs(Ce=>({selectedMcpName:Ce.selectedMcpName,mcpServers:Ce.mcpServers,mcpDraft:Ce.mcpDraft,setMcpDraft:Ce.setMcpDraft,setSelectedMcp:Ce.setSelectedMcp,getMcpByName:Ce.getMcpByName,createMcp:Ce.createMcp,updateMcp:Ce.updateMcp,deleteMcp:Ce.deleteMcp}))),f=Ls(Ce=>Ce.currentDirectory),m=l.useMemo(()=>os(),[]),b=gs(Ce=>Ce.getStatusForDirectory(f??null)),h=gs(Ce=>Ce.getDiagnosticForDirectory(f??null)),g=gs(Ce=>Ce.refresh),x=gs(Ce=>Ce.connect),v=gs(Ce=>Ce.disconnect),N=gs(Ce=>Ce.startAuth),P=gs(Ce=>Ce.completeAuth),F=gs(Ce=>Ce.clearAuth),w=gs(Ce=>Ce.testConnection),j=n?d(n):null,y=!!(i&&i.name===n&&!j),[R,_]=l.useState(""),[B,D]=l.useState("user"),[k,T]=l.useState("local"),[M,O]=l.useState([]),[V,U]=l.useState(""),[Y,X]=l.useState([]),[S,W]=l.useState([]),[Z,A]=l.useState(!0),[C,z]=l.useState(""),[$,H]=l.useState(""),[J,ee]=l.useState(""),[ue,re]=l.useState(""),[xe,be]=l.useState(""),[he,ye]=l.useState(!0),[fe,ae]=l.useState(!1),[ce,pe]=l.useState(!1),[q,te]=l.useState(!1),[ne,oe]=l.useState(!1),[Ae,je]=l.useState(!1),[Ie,Te]=l.useState(!1),[Me,He]=l.useState(!1),[Ve,Ue]=l.useState(!1),[ze,Be]=l.useState(null),[Ge,Fe]=l.useState(null),[ve,De]=l.useState(""),[Ke,We]=l.useState(!1),Pe=l.useRef(0),at=l.useRef(!1),[se,I]=l.useState(!1),[Ee,Le]=l.useState(!1),[_e,Xe]=l.useState(""),[ct,ut]=l.useState(null),lt=l.useMemo(()=>Yh(n,f),[f,n]),rt=l.useRef(lt),mt=l.useRef(null),xt=l.useCallback(()=>{Be(null),Fe(null),De(""),We(!1),Pe.current=0,Ue(!1),je(!1),Te(!1),at.current=!1},[]),It=l.useCallback(()=>{Xe(""),ut(null),Le(!0)},[]),Se=l.useCallback(async()=>{try{const Ce=await navigator.clipboard.readText();Xe(Ce),ut(null)}catch{G.error(t("settings.mcp.page.toast.clipboardReadFailed"))}},[t]),qe=l.useCallback(()=>{const Ce=Fh(_e,{fallbackName:R});if(!Ce.ok){ut(Ce.error);return}const Qe=Oh(Ce,{name:R,scope:B,type:k,command:M,url:V,environment:Y,headers:S,oauthEnabled:Z,oauthClientId:C,oauthClientSecret:$,oauthScope:J,oauthRedirectUri:ue,timeout:xe,enabled:he},{isNewServer:y});_(Qe.name),T(Qe.type),O(Qe.command??[]),U(Qe.url??""),X(Qe.environment??[]),W(Qe.headers??[]),A(Qe.oauthEnabled??!1),z(Qe.oauthClientId??""),H(Qe.oauthClientSecret??""),ee(Qe.oauthScope??""),re(Qe.oauthRedirectUri??""),be(Qe.timeout??""),ye(Qe.enabled??!0),Le(!1),Xe(""),ut(null),G.success(t("settings.mcp.page.toast.configImported"))},[_e,R,B,k,M,V,Y,S,Z,C,$,J,ue,xe,he,y,t]);l.useEffect(()=>{if(y&&i){_(i.name),D(i.scope||"user"),T(i.type),O(i.command),U(i.url),X(i.environment),W(i.headers),A(i.oauthEnabled),z(i.oauthClientId),H(i.oauthClientSecret),ee(i.oauthScope),re(i.oauthRedirectUri),be(i.timeout),ye(i.enabled),I(!1),mt.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(j){D(j.scope==="project"?"project":"user");const Ce=Sl(j.environment),jt=j.type==="remote"?j:null,Qe=Sl(jt?.headers),ht=jt?.oauth,Nt=ht&&typeof ht=="object"?ht:null,Pt=ht!==!1,Mt=j.type,cs=Mt==="local"?j.command??[]:[],$s=Mt==="remote"?j.url??"":"",Yt=typeof jt?.timeout=="number"&&Number.isFinite(jt.timeout)?String(jt.timeout):"";T(Mt),O(cs),U($s),X(Ce),W(Qe),A(Pt),z(Pt?Nt?.clientId??"":""),H(Pt?Nt?.clientSecret??"":""),ee(Pt?Nt?.scope??"":""),re(Pt?Nt?.redirectUri??"":""),be(Yt),ye(j.enabled),I(!1),mt.current={mcpType:Mt,command:cs,url:$s,envEntries:Ce,headerEntries:Qe,oauthEnabled:Pt,oauthClientId:Pt?Nt?.clientId??"":"",oauthClientSecret:Pt?Nt?.clientSecret??"":"",oauthScope:Pt?Nt?.scope??"":"",oauthRedirectUri:Pt?Nt?.redirectUri??"":"",timeout:Yt,enabled:j.enabled}}},[j,y,i]);const Ze=l.useMemo(()=>{const Ce=mt.current;return Ce?k!==Ce.mcpType||he!==Ce.enabled||JSON.stringify(M)!==JSON.stringify(Ce.command)||V!==Ce.url||JSON.stringify(Y)!==JSON.stringify(Ce.envEntries)||JSON.stringify(S)!==JSON.stringify(Ce.headerEntries)||Z!==Ce.oauthEnabled||C!==Ce.oauthClientId||$!==Ce.oauthClientSecret||J!==Ce.oauthScope||ue!==Ce.oauthRedirectUri||xe!==Ce.timeout:!1},[k,M,V,Y,S,Z,C,$,J,ue,xe,he]),nt=async()=>{const Ce=y?R.trim():n??"";if(!Ce){G.error(t("settings.mcp.page.toast.nameRequired"));return}if(y&&a.some(Qe=>Qe.name===Ce)){G.error(t("settings.mcp.page.toast.serverNameExists"));return}if(k==="local"&&M.filter(Boolean).length===0){G.error(t("settings.mcp.page.toast.localCommandRequired"));return}if(k==="remote"&&!V.trim()){G.error(t("settings.mcp.page.toast.remoteUrlRequired"));return}const jt={name:Ce,scope:B,type:k,command:M,url:V,environment:Y,headers:S,oauthEnabled:Z,oauthClientId:C,oauthClientSecret:$,oauthScope:J,oauthRedirectUri:ue,timeout:xe,enabled:he};ae(!0);try{const Qe=y?await c(jt):await p(Ce,jt);Qe.ok?(await Ha(Ge),xt(),y&&(r(null),o(Ce)),await g({directory:f,silent:!0}),Qe.reloadFailed?G.warning(Qe.message||t(y?"settings.mcp.page.toast.serverCreatedReloadFailed":"settings.mcp.page.toast.savedReloadFailed"),{description:Qe.warning||t("settings.mcp.page.toast.retryRefreshHint")}):G.success(Qe.message||t(y?"settings.mcp.page.toast.serverCreatedReloading":"settings.mcp.page.toast.savedReloading"))):G.error(t("settings.mcp.page.toast.saveFailed"))}catch(Qe){G.error(Qe instanceof Error?Qe.message:t("settings.mcp.page.toast.unexpectedError"))}finally{ae(!1)}},ft=async()=>{if(!n)return;te(!0);const Ce=await u(n);Ce.ok?(await Ha(Ge),xt(),Ce.reloadFailed?G.warning(Ce.message||t("settings.mcp.page.toast.serverDeletedReloadFailed",{name:n}),{description:Ce.warning||t("settings.mcp.page.toast.refreshListIfStale")}):G.success(Ce.message||t("settings.mcp.page.toast.serverDeleted",{name:n})),pe(!1)):G.error(t("settings.mcp.page.toast.deleteFailed")),te(!1)},vt=async()=>{if(n){oe(!0);try{if(b[n]?.status==="connected")await v(n,f),G.success(t("settings.mcp.page.toast.disconnected"));else{await x(n,f),await g({directory:f,silent:!0});const jt=gs.getState().getStatusForDirectory(f??null)[n];jt?.status==="connected"?G.success(t("settings.mcp.page.toast.connected")):jt?.status==="needs_auth"?G.message(t("settings.mcp.page.toast.connectionNeedsAuthorization")):jt?.status==="needs_client_registration"?G.message(t("settings.mcp.page.toast.connectionNeedsClientRegistration")):jt?.status==="failed"?G.error(jt.error||t("settings.mcp.page.toast.connectionFailed")):G.message(t("settings.mcp.page.toast.connectionAttemptFinished"));return}await g({directory:f,silent:!0})}catch(Ce){G.error(Ce instanceof Error?Ce.message:t("settings.mcp.page.toast.connectionFailed"))}finally{oe(!1)}}},St=l.useCallback(()=>y?(G.error(t("settings.mcp.page.toast.createServerBeforeLiveActions")),!1):Ze?(G.error(t("settings.mcp.page.toast.saveBeforeLiveActions")),!1):!0,[Ze,y,t]),de=l.useCallback(async(Ce=!1)=>{try{await g({directory:f,silent:Ce})}catch(jt){Ce||G.error(jt instanceof Error?jt.message:t("settings.mcp.page.toast.refreshStatusFailed"))}},[f,g,t]);l.useEffect(()=>{de(!0)},[de]),l.useEffect(()=>{rt.current=lt,oe(!1),He(!1),xt()},[xt,lt]);const ie=l.useCallback(async()=>{if(!n||k!=="remote"||!St())return;je(!0);const Ce=lt;let jt=null;try{const Qe=gs.getState().getStatusForDirectory(f??null)[n]?.status;at.current=Qe==="needs_auth"||Qe==="needs_client_registration";const ht=ql(n,f);if(!ht)throw new Error(t("settings.mcp.page.toast.oauthRedirectUrlBuildFailed"));if(!ue.trim()&&!m){const cs=await p(n,{oauthEnabled:Z,oauthClientId:C,oauthClientSecret:$,oauthScope:J,oauthRedirectUri:ht});if(!cs.ok)throw new Error(t("settings.mcp.page.toast.oauthBrowserCallbackSaveFailed"));if(cs.reloadFailed)throw new Error(cs.warning||cs.message||t("settings.mcp.page.toast.openCodeReloadFailedAfterCallbackSave"));if(rt.current!==Ce)return;re(ht),mt.current=mt.current?{...mt.current,oauthRedirectUri:ht}:mt.current}const Nt=await N(n,f),Pt=Hd(new URL(Nt).searchParams);if(Pt&&(jt=Pt,await Jh({state:Pt,name:n,directory:f})),rt.current!==Ce)return;Be(Nt),Fe(Pt??null),We(!0),Pe.current=0;const Mt=await In(Nt);if(rt.current!==Ce)return;Mt?G.message(t(m?"settings.mcp.page.toast.completeAuthorizationInBrowserWithPaste":"settings.mcp.page.toast.completeAuthorizationInBrowser")):G.error(t("settings.mcp.page.toast.openAuthorizationUrlFailed"))}catch(Qe){await Ha(jt),rt.current===Ce&&G.error(Fr(Qe,t("settings.mcp.page.toast.authorizationStartFailed"),e))}finally{rt.current===Ce&&je(!1)}},[f,m,k,C,$,Z,ue,J,St,lt,n,N,t,e,p]),we=l.useCallback(async()=>{if(!n||!St())return;Te(!0);const Ce=lt;try{if(await F(n,f),rt.current!==Ce)return;Be(null),Fe(null),De(""),We(!1),Pe.current=0,await Ha(Ge),G.success(t("settings.mcp.page.toast.savedAuthorizationRemoved"))}catch(jt){rt.current===Ce&&G.error(Fr(jt,t("settings.mcp.page.toast.clearAuthorizationFailed"),e))}finally{rt.current===Ce&&Te(!1)}},[Ge,F,f,St,lt,n,t,e]),me=l.useCallback(async()=>{if(!ze)return;if((await Zn(ze)).ok){G.success(t("settings.mcp.page.toast.authorizationUrlCopied"));return}G.error(t("settings.mcp.page.toast.authorizationUrlCopyFailed"))},[ze,t]),Je=l.useCallback(async()=>{const Ce=$h(ve);if(!Ce.code){G.error(t("settings.mcp.page.toast.pasteCallbackOrCodeFirst"));return}const jt=Ce.stateKey?await Qh(Ce.stateKey):null,Qe=Ce.context??jt,ht=Qe?.name??n,Nt=Qe?.directory??f;if(!ht){G.error(t("settings.mcp.page.toast.missingServerDetails"));return}if(!Qe&&!St())return;Ue(!0);const Pt=lt;try{if(await P(ht,Ce.code,Nt),await Ha(Ce.stateKey??Ge),rt.current!==Pt)return;De(""),Be(null),Fe(null),We(!1),Pe.current=0,G.success(ht===n?t("settings.mcp.page.toast.authorizationCompleted"):t("settings.mcp.page.toast.authorizationCompletedFor",{name:ht}))}catch(Mt){rt.current===Pt&&G.error(Fr(Mt,t("settings.mcp.page.toast.authorizationCompleteFailed"),e))}finally{rt.current===Pt&&Ue(!1)}},[ve,Ge,P,f,St,lt,n,t,e]),$e=l.useCallback(async()=>{if(!(!n||!St())){if(!he){G.error(t("settings.mcp.page.toast.enableServerBeforeTest"));return}He(!0);try{const Ce=await w(n,f),jt=Ce.status?.status;Ce.warning?G.warning(Ce.warning):jt==="connected"?G.success(t("settings.mcp.page.toast.connectionTestSucceeded")):jt==="needs_auth"?G.message(t("settings.mcp.page.toast.connectionNeedsAuthorization")):jt==="needs_client_registration"?G.message(t("settings.mcp.page.toast.connectionNeedsClientRegistration")):jt==="failed"?G.error(Ce.status?.error||Ce.error||t("settings.mcp.page.toast.connectionTestFailed")):Ce.error?G.error(Ce.error):G.message(t("settings.mcp.page.toast.connectionTestFinished"))}catch(Ce){G.error(Ce instanceof Error?Ce.message:t("settings.mcp.page.toast.connectionTestFailed"))}finally{He(!1)}}},[f,he,St,n,t,w]);if(l.useEffect(()=>{if(!Ke||!n)return;const Ce=window.setInterval(()=>{(async()=>{Pe.current+=1,await g({directory:f,silent:!0});const jt=gs.getState().getStatusForDirectory(f??null)[n];if(jt){if(at.current&&jt.status!=="needs_auth"&&jt.status!=="needs_client_registration"){We(!1),Pe.current=0,at.current=!1,Be(null),De(""),jt.status==="connected"&&G.success(t("settings.mcp.page.toast.authorizationCompleted"));return}if(!at.current&&jt.status==="failed"){We(!1),Pe.current=0,at.current=!1,G.error(jt.error||t("settings.mcp.page.toast.authorizationFailed"));return}Pe.current>=30&&(We(!1),Pe.current=0,at.current=!1,G.message(t("settings.mcp.page.toast.authorizationStillInProgress")))}})()},2e3);return()=>{window.clearInterval(Ce)}},[f,Ke,g,n,t]),!n)return s.jsx("div",{className:"flex h-full items-center justify-center",children:s.jsxs("div",{className:"text-center text-muted-foreground",children:[s.jsx(L,{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=b[n],bt=n?h[n]:void 0,Dt=et??bt,Qt=et?.status==="connected",_t=et?.status==="needs_auth"||et?.status==="needs_client_registration",as=m?null:ql(n,f),is=Wh(Dt?.status,e,Dt&&"error"in Dt?Dt.error:void 0),$t=Ce=>{switch(Ce){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 Ce}};return s.jsxs(s.Fragment,{children:[s.jsxs(us,{title:y?t("settings.mcp.page.header.newServer"):n,titleAccessory:y?void 0:s.jsx(Gl,{status:Dt?.status,enabled:he,getStatusLabel:$t,variant:"pill"}),description:y?t("settings.mcp.page.header.configureNewServer"):t("settings.mcp.page.header.transport",{type:t(k==="local"?"settings.mcp.page.transport.local":"settings.mcp.page.transport.remote")}),headerEnd:y?void 0:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(Q,{variant:Qt?"outline":"default",size:"xs",className:"!font-normal",onClick:vt,disabled:ne||!he,children:t(ne?"settings.mcp.page.actions.working":Qt?"settings.mcp.page.actions.disconnect":"settings.mcp.page.actions.connect")}),k==="remote"&&s.jsxs(s.Fragment,{children:[s.jsx(Q,{variant:_t?"default":"outline",size:"xs",className:"!font-normal",onClick:()=>{ie()},disabled:Ae||!he,children:t(Ae?"settings.mcp.page.actions.starting":_t?"settings.mcp.page.actions.authorize":"settings.mcp.page.actions.reauthorize")}),s.jsx(Q,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:()=>{we()},disabled:Ie||!he,children:t(Ie?"settings.mcp.page.actions.clearing":"settings.mcp.page.actions.clearAuth")})]}),Qt&&s.jsx(Q,{variant:"ghost",size:"xs",className:"!font-normal gap-1 text-muted-foreground",onClick:()=>{$e()},disabled:Me||!he,children:t(Me?"settings.mcp.page.actions.testing":"settings.mcp.page.actions.test")})]}),showSaveStatus:!1,children:[!y&&qh(Dt?.status,ze,_t,Ke)&&s.jsx(ot,{divider:!1,children:s.jsxs("div",{className:le("rounded-lg border p-3",Gh(Dt?.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:Kt,children:t("settings.mcp.page.status.runtimeStatus")}),s.jsx(Gl,{status:Dt?.status,enabled:he,getStatusLabel:$t})]}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:is}),s.jsx("p",{className:"typography-micro text-muted-foreground/80",children:B==="project"?t("settings.mcp.page.status.projectScopedTo",{directory:f??t("settings.mcp.page.status.activeProject")}):t("settings.mcp.page.status.userScoped")})]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:!Qt&&s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{$e()},disabled:Me||!he,children:t(Me?"settings.mcp.page.actions.testing":"settings.mcp.page.actions.testConnection")})}),ze&&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:ze}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{In(ze)},children:[s.jsx(L,{name:"external-link",className:"h-3.5 w-3.5"}),t("settings.mcp.page.actions.openInBrowser")]}),s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{me()},children:[s.jsx(L,{name:"clipboard",className:"h-3.5 w-3.5"}),t("settings.mcp.page.actions.copyLink")]})]})]})}),k==="remote"&&(_t||Ke||ze)&&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(An,{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(js,{value:ve,onChange:Ce=>De(Ce.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(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Je()},disabled:Ve,children:t(Ve?"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(ot,{title:t("settings.mcp.page.server.title"),divider:!1,settingsItem:"mcp.server",contentClassName:"space-y-0",children:[y&&s.jsxs(Jt,{label:t("settings.mcp.page.server.name"),children:[s.jsx(tt,{value:R,onChange:Ce=>_(Ce.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(At,{value:B,onValueChange:Ce=>D(Ce),children:[s.jsx(Et,{size:Gt,className:"!h-7 !w-7 !min-w-0 !px-0 !py-0 justify-center [&>svg:last-child]:hidden",title:t(B==="user"?"settings.common.scope.global":"settings.common.scope.project"),children:B==="user"?s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"})}),s.jsxs(Tt,{align:"end",children:[s.jsx(yt,{value:"user",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.global")})]})}),s.jsx(yt,{value:"project",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"}),s.jsx("span",{children:t("settings.common.scope.project")})]})})]})]})]}),y&&s.jsx("div",{className:"py-1.5",children:s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:It,type:"button",title:t("settings.mcp.page.server.importJsonTitle"),children:[s.jsx(L,{name:"file-code",className:"h-3.5 w-3.5"}),t("settings.mcp.page.server.importJson")]})}),s.jsx(wt,{checked:he,onChange:ye,label:t("settings.mcp.page.server.enable"),ariaLabel:t("settings.mcp.page.server.enableAria")}),s.jsx(ls,{label:t("settings.mcp.page.server.transportMode"),children:s.jsx(Zs,{"aria-label":t("settings.mcp.page.server.transportMode"),value:k,onChange:T,options:[{value:"local",label:t("settings.mcp.page.transport.local")},{value:"remote",label:t("settings.mcp.page.transport.remote")}]})})]}),s.jsx(ot,{title:t(k==="local"?"settings.mcp.page.connection.command":"settings.mcp.page.connection.serverUrl"),settingsItem:"mcp.command",children:k==="local"?s.jsx(Vh,{value:M,onChange:O,pasteCommandTitle:t("settings.mcp.page.connection.pasteCommandTitle"),pasteCommandLabel:t("settings.mcp.page.connection.pasteCommand"),pasteSuccess:Ce=>t("settings.mcp.page.toast.pastedArgumentsCount",{count:Ce}),clipboardReadFailed:t("settings.mcp.page.toast.clipboardReadFailed"),preview:Ce=>t("settings.mcp.page.connection.previewArgs",{count:Ce})}):s.jsx(tt,{value:V,onChange:Ce=>U(Ce.target.value),placeholder:t("settings.mcp.page.connection.serverUrlPlaceholder"),className:"font-mono typography-meta"})}),k==="remote"&&s.jsx(ot,{title:t("settings.mcp.page.advanced.title"),settingsItem:"mcp.advanced",children:s.jsxs(sa,{open:se,onOpenChange:I,children:[s.jsxs(na,{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(Z?"settings.mcp.page.advanced.autoDetect":"settings.mcp.page.advanced.custom")," · ",S.length," ",t("settings.mcp.page.advanced.headers"),xe?` · ${xe}ms`:"",")"]})]}),se?s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"}):s.jsx(L,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]}),s.jsx(aa,{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:Kt,children:t("settings.mcp.page.advanced.timeoutMs")}),s.jsx(Ht,{children:t("settings.mcp.page.advanced.timeoutHint")})]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx(tt,{type:"number",min:"1",step:"1",value:xe,onChange:Ce=>be(Ce.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(An,{as:"div",className:"mb-2",children:[t("settings.mcp.page.advanced.requestHeaders"),S.length>0&&s.jsxs("span",{className:"ml-1.5 typography-micro text-muted-foreground font-normal",children:["(",S.length,")"]})]}),s.jsx(Wl,{value:S,onChange:W,keyTransform:Ce=>Ce.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:Ce=>t("settings.mcp.page.toast.importedVariablesCount",{count:Ce}),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(wt,{checked:Z,onChange:A,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(tt,{value:C,onChange:Ce=>z(Ce.target.value),placeholder:t("settings.mcp.page.advanced.oauthClientIdPlaceholder"),className:"font-mono typography-meta",disabled:!Z,"data-bwignore":"true","data-1p-ignore":"true"}),s.jsx(tt,{value:$,onChange:Ce=>H(Ce.target.value),placeholder:t("settings.mcp.page.advanced.oauthClientSecretPlaceholder"),className:"font-mono typography-meta",disabled:!Z,"data-bwignore":"true","data-1p-ignore":"true"}),s.jsx(tt,{value:J,onChange:Ce=>ee(Ce.target.value),placeholder:t("settings.mcp.page.advanced.oauthScopesPlaceholder"),className:"font-mono typography-meta",disabled:!Z,"data-bwignore":"true","data-1p-ignore":"true"}),s.jsx(tt,{value:ue,onChange:Ce=>re(Ce.target.value),placeholder:t("settings.mcp.page.advanced.oauthRedirectUriPlaceholder"),className:"font-mono typography-meta",disabled:!Z,"data-bwignore":"true","data-1p-ignore":"true"})]}),as&&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:as})]})]})]})})]})}),s.jsx(ot,{title:t("settings.mcp.page.env.title"),titleAccessory:Y.length>0?s.jsxs("span",{className:"typography-micro text-muted-foreground font-normal",children:["(",Y.length,")"]}):null,settingsItem:"mcp.environment",children:Y.length===0?s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal gap-1.5",onClick:()=>X([{key:"",value:""}]),children:[s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),t("settings.mcp.page.env.addEnvironmentVariable")]}):s.jsx(Wl,{value:Y,onChange:X,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:Ce=>t("settings.mcp.page.toast.importedVariablesCount",{count:Ce}),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(Q,{onClick:nt,disabled:fe||!Ze&&!y,size:"xs",className:"!font-normal",children:t(fe?"settings.common.actions.saving":y?"settings.common.actions.create":"settings.common.actions.saveChanges")}),!y&&s.jsx(Q,{variant:"destructive",size:"xs",className:"!font-normal",onClick:()=>pe(!0),children:t("settings.common.actions.delete")})]})," "]}),s.jsx(Lt,{open:Ee,onOpenChange:Ce=>{Ce||(Le(!1),Xe(""),ut(null))},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.mcp.page.importDialog.title")}),s.jsx(qt,{children:t("settings.mcp.page.importDialog.description")})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(js,{value:_e,onChange:Ce=>{Xe(Ce.target.value),ut(null)},placeholder:`{
|
|
16
|
+
"mcpServers": {
|
|
17
|
+
"postgres": {
|
|
18
|
+
"command": "npx",
|
|
19
|
+
"args": ["-y", "@modelcontextprotocol/server-postgres"]
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}`,rows:8,className:"font-mono typography-meta resize-y",spellCheck:!1,"data-bwignore":"true","data-1p-ignore":"true"}),ct&&s.jsx("p",{className:"typography-micro text-[var(--status-error)]",children:ct}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal gap-1",onClick:Se,type:"button",children:[s.jsx(L,{name:"clipboard",className:"h-3.5 w-3.5"}),t("settings.mcp.page.importDialog.pasteFromClipboard")]})})]}),s.jsxs(Zt,{children:[s.jsx(Q,{variant:"outline",onClick:()=>{Le(!1),Xe(""),ut(null)},className:"text-foreground",children:t("settings.common.actions.cancel")}),s.jsx(Q,{onClick:qe,disabled:!_e.trim(),size:"sm",children:t("settings.common.actions.import")})]})]})}),s.jsx(Lt,{open:ce,onOpenChange:Ce=>{!Ce&&!q&&pe(!1)},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.mcp.page.deleteDialog.title",{name:n??""})}),s.jsxs(qt,{children:[t("settings.mcp.page.deleteDialog.descriptionPrefix")," ",s.jsx("code",{className:"text-foreground",children:"opencode.json"}),"."," ",t("settings.mcp.page.deleteDialog.descriptionSuffix")]})]}),s.jsxs(Zt,{children:[s.jsx(Q,{variant:"outline",onClick:()=>pe(!1),disabled:q,className:"text-foreground",children:t("settings.common.actions.cancel")}),s.jsx(Q,{variant:"destructive",size:"sm",onClick:ft,disabled:q,children:t(q?"settings.mcp.page.actions.deleting":"settings.common.actions.delete")})]})]})})]})},Zh=280,Jl=4,ex=({transform:t})=>({...t,y:0}),tx=t=>{const e=Ye.c(18),{id:n,children:a,className:i}=t;let r;e[0]!==n?(r={id:n},e[0]=n,e[1]=r):r=e[1];const{attributes:o,listeners:d,setNodeRef:c,transform:p,transition:u,isDragging:f}=em(r);let m;e[2]!==p?(m=tm.Transform.toString(p),e[2]=p,e[3]=m):m=e[3];let b;e[4]!==m||e[5]!==u?(b={transform:m,transition:u},e[4]=m,e[5]=u,e[6]=b):b=e[6];const h=f&&"opacity-50";let g;e[7]!==i||e[8]!==h?(g=le("h-full rounded-md",i,h),e[7]=i,e[8]=h,e[9]=g):g=e[9];let x;return e[10]!==o||e[11]!==a||e[12]!==n||e[13]!==d||e[14]!==c||e[15]!==b||e[16]!==g?(x=s.jsx("div",{ref:c,"data-sortable-tab-id":n,style:b,className:g,...o,...d,children:a}),e[10]=o,e[11]=a,e[12]=n,e[13]=d,e[14]=c,e[15]=b,e[16]=g,e[17]=x):x=e[17],x},sx=t=>{const e=Ye.c(6),{id:n,children:a,className:i}=t;let r;e[0]!==i?(r=le("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},ia=t=>{const e=Ye.c(132),{items:n,activeId:a,onSelect:i,onClose:r,onReorder:o,layoutMode:d,variant:c,activePillInsetClassName:p,activePillButtonClassName:u,inactiveTabsIconOnly:f,animateActivePill:m,activePillLowercase:b,className:h}=t,g=d===void 0?"scrollable":d,x=c===void 0?"default":c,v=f===void 0?!1:f,N=b===void 0?!0:b,{t:P}=it(),F=Ne(nx),{isTablet:w}=_s(),j=F||w,y=l.useRef(null);let R;e[0]===Symbol.for("react.memo_cache_sentinel")?(R={left:!1,right:!1},e[0]=R):R=e[0];const[_,B]=l.useState(R);let D;e[1]!==n?(D=n.map(ax),e[1]=n,e[2]=D):D=e[2];const k=D,T=g==="scrollable",M=x==="default",O=x==="active-pill",U=O||x==="animated",Y=M,X=U||Y,S=O&&T,W=U,Z=m??U,A=typeof o=="function",C=A?tx:sx;let z;e[3]===Symbol.for("react.memo_cache_sentinel")?(z=new Map,e[3]=z):z=e[3];const $=l.useRef(z),[H,J]=l.useState(null),[ee,ue]=l.useState(!1),[re,xe]=l.useState(null),be=l.useRef(!1),he=l.useRef(0),ye=l.useRef(a),fe=l.useRef(null);let ae;e:{if(!X||!re||!a||re===a){ae=0;break e}const we=n.findIndex(Je=>Je.id===re),me=n.findIndex(Je=>Je.id===a);if(we<0||me<0){ae=0;break e}ae=we>me?Jl:-Jl}const ce=ae;let pe;e[4]===Symbol.for("react.memo_cache_sentinel")?(pe={activationConstraint:{distance:8}},e[4]=pe):pe=e[4];const q=Yu(Xu(Zu,pe)),te=ix;let ne;e[5]===Symbol.for("react.memo_cache_sentinel")?(ne=(we,me)=>{if(me){$.current.set(we,me);return}$.current.delete(we)},e[5]=ne):ne=e[5];const oe=ne;let Ae;e[6]!==a||e[7]!==X?(Ae=()=>{if(!X||!a){J(rx);return}const we=y.current,me=$.current.get(a);if(!we||!me){J(ox);return}let Je=0,$e=0,et=me;for(;et&&et!==we;)Je=Je+et.offsetLeft,$e=$e+et.offsetTop,et=et.offsetParent;const bt={left:Je,top:$e,width:me.offsetWidth,height:me.offsetHeight};J(Dt=>te(Dt,bt)?Dt:bt)},e[6]=a,e[7]=X,e[8]=Ae):Ae=e[8];const je=Ae;let Ie;e[9]!==T?(Ie=()=>{if(!T){B({left:!1,right:!1});return}const we=y.current;if(!we){B({left:!1,right:!1});return}B({left:we.scrollLeft>2,right:we.scrollLeft+we.clientWidth<we.scrollWidth-2})},e[9]=T,e[10]=Ie):Ie=e[10];const Te=Ie;let Me;e[11]!==T||e[12]!==Te?(Me=()=>{if(!T){B({left:!1,right:!1});return}const we=y.current;if(!we)return;Te(),we.addEventListener("scroll",Te,{passive:!0});const me=new ResizeObserver(Te);return me.observe(we),()=>{we.removeEventListener("scroll",Te),me.disconnect()}},e[11]=T,e[12]=Te,e[13]=Me):Me=e[13];let He;e[14]!==T||e[15]!==n.length||e[16]!==Te?(He=[T,n.length,Te],e[14]=T,e[15]=n.length,e[16]=Te,e[17]=He):He=e[17],l.useEffect(Me,He);let Ve;e[18]!==a||e[19]!==je||e[20]!==X?(Ve=()=>{if(!X){J(null);return}je();const we=y.current;if(!we)return;const me=new ResizeObserver(()=>{performance.now()-he.current>Zh&&ue(!1),je()});if(me.observe(we),a){const Je=$.current.get(a);Je&&me.observe(Je)}return()=>{me.disconnect()}},e[18]=a,e[19]=je,e[20]=X,e[21]=Ve):Ve=e[21];let Ue;e[22]!==a||e[23]!==n.length||e[24]!==je||e[25]!==X?(Ue=[a,n.length,je,X],e[22]=a,e[23]=n.length,e[24]=je,e[25]=X,e[26]=Ue):Ue=e[26],l.useEffect(Ve,Ue);let ze;e[27]!==je?(ze=()=>{je()},e[27]=je,e[28]=ze):ze=e[28],l.useLayoutEffect(ze);let Be;e[29]!==k?(Be=k.join("\0"),e[29]=k,e[30]=Be):Be=e[30];const Ge=Be;let Fe,ve;e[31]!==a||e[32]!==Ge||e[33]!==X?(Fe=()=>{if(!X){be.current=!1,ue(!1);return}const we=fe.current!==Ge;if(fe.current=Ge,!be.current){be.current=!0,ye.current=a;return}const me=ye.current!==a;if(ye.current=a,!me||we){ue(!1);return}he.current=performance.now(),ue(!0)},ve=[a,Ge,X],e[31]=a,e[32]=Ge,e[33]=X,e[34]=Fe,e[35]=ve):(Fe=e[34],ve=e[35]),l.useLayoutEffect(Fe,ve);let De;e[36]!==a||e[37]!==T||e[38]!==Te?(De=()=>{if(!T||!a)return;const we=y.current;if(!we)return;const me=window.requestAnimationFrame(()=>{const Je=typeof window.CSS?.escape=="function"?window.CSS.escape(a):a.replace(/"/g,'\\"'),$e=we.querySelector(`[data-sortable-tab-id="${Je}"]`);$e&&($e.scrollIntoView({block:"nearest",inline:"nearest"}),Te())});return()=>{window.cancelAnimationFrame(me)}},e[36]=a,e[37]=T,e[38]=Te,e[39]=De):De=e[39];let Ke;e[40]!==a||e[41]!==T||e[42]!==n.length||e[43]!==Te?(Ke=[a,T,n.length,Te],e[40]=a,e[41]=T,e[42]=n.length,e[43]=Te,e[44]=Ke):Ke=e[44],l.useEffect(De,Ke);let We;e[45]!==o?(We=we=>{if(!o)return;const{active:me,over:Je}=we;!Je||me.id===Je.id||o(String(me.id),String(Je.id))},e[45]=o,e[46]=We):We=e[46];const Pe=We;let at;e[47]!==h?(at=le("relative flex h-full min-w-0 flex-1",h),e[47]=h,e[48]=at):at=e[48];let se;e[49]!==T||e[50]!==_||e[51]!==U?(se=T&&_.left?s.jsx("div",{className:le("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",U?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e[49]=T,e[50]=_,e[51]=U,e[52]=se):se=e[52];let I;e[53]!==T||e[54]!==_||e[55]!==U?(I=T&&_.right?s.jsx("div",{className:le("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",U?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e[53]=T,e[54]=_,e[55]=U,e[56]=I):I=e[56];const Ee=U?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",Le=U&&"@container/pill-tabs",_e=U&&"pill-tabs__track",Xe=U&&(p??"gap-0.5 py-0.5"),ct=Y&&"items-center overflow-y-hidden",ut=W&&"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",lt=T?"overflow-x-auto scrollbar-none":"overflow-x-hidden";let rt;e[57]!==Ee||e[58]!==Le||e[59]!==_e||e[60]!==Xe||e[61]!==ct||e[62]!==ut||e[63]!==lt?(rt=le("relative flex h-full min-w-0 flex-1",Ee,Le,_e,Xe,ct,ut,lt),e[57]=Ee,e[58]=Le,e[59]=_e,e[60]=Xe,e[61]=ct,e[62]=ut,e[63]=lt,e[64]=rt):rt=e[64];let mt;e[65]!==T?(mt=T?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,e[65]=T,e[66]=mt):mt=e[66];let xt;e[67]!==P?(xt=P("sortableTabsStrip.aria.tabs"),e[67]=P,e[68]=xt):xt=e[68];let It;e[69]!==ce||e[70]!==H||e[71]!==ee||e[72]!==Z||e[73]!==U?(It=U&&H?s.jsx("div",{className:le("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)]",Z&&ee&&"pill-tabs__indicator--is-animated"),style:{transform:`translate3d(${H.left+ce}px, ${H.top}px, 0)`,width:`${H.width}px`,height:`${H.height}px`}}):null,e[69]=ce,e[70]=H,e[71]=ee,e[72]=Z,e[73]=U,e[74]=It):It=e[74];let Se;e[75]!==ce||e[76]!==H||e[77]!==ee||e[78]!==Y?(Se=Y&&H?s.jsx("div",{className:le("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",ee&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${H.left+ce}px, 0, 0)`,width:`${H.width}px`},"aria-hidden":!0}):null,e[75]=ce,e[76]=H,e[77]=ee,e[78]=Y,e[79]=Se):Se=e[79];let qe;if(e[80]!==C||e[81]!==a||e[82]!==u||e[83]!==N||e[84]!==j||e[85]!==v||e[86]!==O||e[87]!==F||e[88]!==T||e[89]!==n||e[90]!==r||e[91]!==i||e[92]!==S||e[93]!==U||e[94]!==X){let we;e[96]!==C||e[97]!==a||e[98]!==u||e[99]!==N||e[100]!==j||e[101]!==v||e[102]!==O||e[103]!==F||e[104]!==T||e[105]!==r||e[106]!==i||e[107]!==S||e[108]!==U||e[109]!==X?(we=me=>{const Je=me.id===a,$e=v&&U&&!Je&&!!me.icon,et=!$e,bt=!!me.icon,Dt=v&&U&&Je&&!T&&!S,Qt=me.closable!==!1&&!!r,_t=Qt&&!!me.icon,as=T||S?void 0:U?Dt?"flex-none basis-auto":F?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",is=Qt?Ce=>{Ce.button===1&&(Ce.preventDefault(),Ce.stopPropagation(),r?.(me.id))}:void 0,$t=Qt?lx:void 0;return s.jsx(C,{id:me.id,className:as,children:s.jsxs("div",{ref:Ce=>oe(me.id,Ce),onAuxClick:is,onMouseDown:$t,className:le("group flex h-full min-w-0 flex-nowrap items-center",T||S?"shrink-0":U?"w-full":"w-full min-w-0",U?"relative z-10 bg-transparent":Je?"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":Je,"aria-label":$e?me.title??me.label:void 0,onClick:()=>i(me.id),onPointerDown:X?()=>{ue(!0),xe(me.id)}:void 0,onPointerUp:X?()=>xe(null):void 0,onPointerLeave:X?()=>xe(null):void 0,onPointerCancel:X?()=>xe(null):void 0,className:le(U?"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",U&&N?"lowercase":null,U&&($e?"gap-0":"gap-1.5"),U?S?"shrink-0 whitespace-nowrap px-3 text-center":T?"max-w-56 shrink-0 px-3 text-center":$e?"px-2 !min-w-0 text-center":Dt?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":T?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",U?u??(O?F?"h-[38px]":"h-[31px]":"h-7"):null,U?Je?"text-foreground":"text-muted-foreground hover:text-foreground":null,U?"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:me.title??me.label,children:U?s.jsxs(s.Fragment,{children:[bt?s.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[s.jsx("span",{className:le("flex items-center justify-center transition-opacity",_t&&(j?"opacity-0":"group-hover:opacity-0")),children:me.icon}),_t?s.jsx("span",{role:"button",tabIndex:-1,className:le("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",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:cx,onClick:Ce=>{Ce.stopPropagation(),r?.(me.id)},"aria-label":me.closeLabel??`Close ${me.label} tab`,title:me.closeLabel??`Close ${me.label} tab`,children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,et?s.jsx("span",{className:"animated-tabs__label truncate",children:me.label}):null]}):s.jsxs("span",{className:le("flex min-w-0 flex-nowrap items-center gap-1.5",!T&&"justify-center"),children:[bt?s.jsxs("span",{className:le("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",Je?"text-[var(--primary-base)]":"text-muted-foreground"),children:[s.jsx("span",{className:le("flex items-center justify-center transition-opacity",_t&&(j?"opacity-0":"group-hover:opacity-0")),children:me.icon}),_t?s.jsx("span",{role:"button",tabIndex:-1,className:le("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",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:dx,onClick:Ce=>{Ce.stopPropagation(),r?.(me.id)},"aria-label":me.closeLabel??`Close ${me.label} tab`,title:me.closeLabel??`Close ${me.label} tab`,children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,s.jsx("span",{className:"truncate leading-[1.2]",children:me.label})]})}),Qt&&!_t?s.jsx("button",{type:"button",onPointerDown:ux,onClick:Ce=>{Ce.stopPropagation(),r?.(me.id)},className:le("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",U?"-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",U?Je?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":Je?"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":me.closeLabel??`Close ${me.label} tab`,title:me.closeLabel??`Close ${me.label} tab`,children:s.jsx(L,{name:"close",className:"h-3 w-3"})}):null]})},me.id)},e[96]=C,e[97]=a,e[98]=u,e[99]=N,e[100]=j,e[101]=v,e[102]=O,e[103]=F,e[104]=T,e[105]=r,e[106]=i,e[107]=S,e[108]=U,e[109]=X,e[110]=we):we=e[110],qe=n.map(we),e[80]=C,e[81]=a,e[82]=u,e[83]=N,e[84]=j,e[85]=v,e[86]=O,e[87]=F,e[88]=T,e[89]=n,e[90]=r,e[91]=i,e[92]=S,e[93]=U,e[94]=X,e[95]=qe}else qe=e[95];let Ze;e[111]!==rt||e[112]!==mt||e[113]!==xt||e[114]!==It||e[115]!==Se||e[116]!==qe?(Ze=s.jsxs("div",{ref:y,className:rt,style:mt,role:"tablist","aria-label":xt,children:[It,Se,qe]}),e[111]=rt,e[112]=mt,e[113]=xt,e[114]=It,e[115]=Se,e[116]=qe,e[117]=Ze):Ze=e[117];let nt;e[118]!==at||e[119]!==se||e[120]!==I||e[121]!==Ze?(nt=s.jsxs("div",{className:at,children:[se,I,Ze]}),e[118]=at,e[119]=se,e[120]=I,e[121]=Ze,e[122]=nt):nt=e[122];const ft=nt;if(!A)return ft;let vt;e[123]===Symbol.for("react.memo_cache_sentinel")?(vt=[ex],e[123]=vt):vt=e[123];let St;e[124]!==k||e[125]!==ft?(St=s.jsx(sm,{items:k,strategy:nm,children:ft}),e[124]=k,e[125]=ft,e[126]=St):St=e[126];let de;e[127]===Symbol.for("react.memo_cache_sentinel")?(de=s.jsx(am,{dropAnimation:null}),e[127]=de):de=e[127];let ie;return e[128]!==Pe||e[129]!==q||e[130]!==St?(ie=s.jsxs(im,{sensors:q,collisionDetection:rm,onDragEnd:Pe,modifiers:vt,children:[St,de]}),e[128]=Pe,e[129]=q,e[130]=St,e[131]=ie):ie=e[131],ie};function nx(t){return t.isMobile}function ax(t){return t.id}function ix(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 rx(t){return t===null?t:null}function ox(t){return t===null?t:null}function lx(t){t.button===1&&t.preventDefault()}function cx(t){t.stopPropagation()}function dx(t){t.stopPropagation()}function ux(t){t.stopPropagation()}const Vi=()=>{try{const e=rs.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=Is.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[PluginsStore] Error resolving config directory:",t)}return null},mx=800,px=5e3,gx="__default__",ko=new Map,Or=new Map,fx=1500,Wd=t=>t?.trim()||gx,hx=t=>{ko.delete(Wd(t))},fs=cn()(Da(ii((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=Vi(),i=Wd(a),r=Date.now(),o=ko.get(i)??0,d=e().entries.length>0||e().files.length>0;if(!n?.force&&d&&r-o<px)return!0;const c=Or.get(i);if(!n?.force&&c)return c;const p=(async()=>{t({isLoading:!0});try{const u=await gt(Fn("/api/config/plugins",a),{headers:Wa(a)});if(!u.ok)throw new Error("Failed to load plugins");const f=await Hi(u);return t({entries:f.entries??[],files:f.files??[],isLoading:!1}),ko.set(i,Date.now()),n?.force||e().loadRegistryInfo(),!0}catch(u){return console.error("[PluginsStore] Failed to load plugins:",u),t({isLoading:!1}),!1}})();Or.set(i,p);try{return await p}finally{Or.delete(i)}},loadRegistryInfo:async n=>{const a=bx(n?.specs??e().entries.map(i=>i.spec));if(a.length===0){t({isLoadingRegistry:!1});return}t({isLoadingRegistry:!0});try{const i=Vi(),r={...e().registryInfo};for(const o of yx(a)){const d=await gt(xx(o,n?.force===!0,i),{headers:Wa(i)});if(!d.ok)throw new Error("Failed to load plugin registry info");const c=await Hi(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 ha("Creating plugin entry…",async i=>await gt(Fn("/api/config/plugins/entry",i),{method:"POST",headers:Ai(i),body:JSON.stringify(Ql(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 ha("Updating plugin entry…",async d=>await gt(Fn(`/api/config/plugins/entry/${encodeURIComponent(n)}`,d),{method:"PATCH",headers:Ai(d),body:JSON.stringify(Ql(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 ha("Deleting plugin entry…",async r=>await gt(Fn(`/api/config/plugins/entry/${encodeURIComponent(n)}`,r),{method:"DELETE",headers:Wa(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=Vi(),i=await gt(Fn(`/api/config/plugins/file/${encodeURIComponent(n)}`,a),{headers:Wa(a)});if(!i.ok)throw new Error("Failed to read plugin file");return await Hi(i)}catch(a){return console.error("[PluginsStore] Failed to read plugin file:",a),null}},createFile:async n=>ha("Creating plugin file…",async a=>await gt(Fn("/api/config/plugins/file",a),{method:"POST",headers:Ai(a),body:JSON.stringify(n)}),e),updateFile:async(n,a)=>ha("Updating plugin file…",async i=>await gt(Fn(`/api/config/plugins/file/${encodeURIComponent(n)}`,i),{method:"PUT",headers:Ai(i),body:JSON.stringify(a)}),e),deleteFile:async n=>{const a=await ha("Deleting plugin file…",async i=>await gt(Fn(`/api/config/plugins/file/${encodeURIComponent(n)}`,i),{method:"DELETE",headers:Wa(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:lr(),partialize:t=>({selectedId:t.selectedId})}),{name:"plugins-store"}));function Fn(t,e){const n=e?`?directory=${encodeURIComponent(e)}`:"";return`${t}${n}`}function xx(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 bx(t){return Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))}function yx(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>fx?(e.push(n),n=[i],a=r.length):(n.push(i),a=o)}return n.length>0&&e.push(n),e}function Wa(t){return t?{"x-opencode-directory":t}:void 0}function Ai(t){return{"Content-Type":"application/json",...t?{"x-opencode-directory":t}:{}}}function Ql(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 ha(t,e,n){Ui(t);let a=!1;try{const i=Vi(),r=await e(i),o=await Hi(r).catch(()=>null);if(!r.ok)throw new Error(o?.error||"Failed to update plugin configuration");return hx(i),o?.requiresReload&&(a=!0,await _i({message:o.message,delayMs:o.reloadDelayMs??mx,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||$i()}}async function Hi(t){return await t.json()}const vx=/^[a-z0-9][a-z0-9-_.]*\.(js|ts|mjs|cjs)$/;function wx(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 jx=({open:t,onOpenChange:e,defaultScope:n="user"})=>{const{t:a}=it(),i=fs(O=>O.createEntry),r=fs(O=>O.createFile),[o,d]=l.useState("npm"),[c,p]=l.useState(""),[u,f]=l.useState(""),[m,b]=l.useState(""),[h,g]=l.useState(""),[x,v]=l.useState(n),[N,P]=l.useState(!1),F=l.useCallback(()=>{p(""),f(""),b(""),g(""),v(n)},[n]);l.useEffect(()=>{t&&(d("npm"),F())},[t,F]);const w=O=>{O!==o&&(d(O),F())},j=l.useMemo(()=>wx(u),[u]),y=!j.ok,R=o==="file"&&m.trim()!==""&&!vx.test(m.trim()),_=(o==="npm"||o==="path")&&c.trim()==="",B=o==="file"&&h.trim()==="",D=o==="file"&&m.trim()==="",k=N||y||o==="npm"&&_||o==="path"&&_||o==="file"&&(D||R||B),T=async()=>{if(!k){P(!0);try{let O;o==="file"?O=await r({fileName:m.trim(),content:h,scope:x}):O=await i({spec:c.trim(),options:j.ok?j.value:void 0,scope:x}),O.ok?(G.success(O.message||a("settings.plugins.toast.created")),O.reloadFailed&&G.warning(a("settings.plugins.toast.reloadFailed")),e(!1)):G.error(O.message||a("settings.plugins.sidebar.toast.deleteFailed"))}finally{P(!1)}}},M=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(Lt,{open:t,onOpenChange:O=>{!O&&N||e(O)},children:s.jsxs(Ft,{className:"max-w-xl",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:a("settings.plugins.dialog.add.title")}),s.jsx(qt,{children:a("settings.plugins.sidebar.empty.description")})]}),s.jsx(ia,{items:M,activeId:o,onSelect:O=>w(O),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(tt,{id:"plugin-spec",value:c,onChange:O=>p(O.target.value),placeholder:a("settings.plugins.page.field.spec.placeholder"),"aria-invalid":_?!1:void 0,disabled:N}),_&&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(js,{id:"plugin-options",value:u,onChange:O=>f(O.target.value),rows:5,className:"font-mono",hasError:y,disabled:N}),y&&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(tt,{id:"plugin-filename",value:m,onChange:O=>b(O.target.value),placeholder:"my-plugin.ts","aria-invalid":R||void 0,disabled:N}),R&&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(js,{id:"plugin-content",value:h,onChange:O=>g(O.target.value),rows:16,className:"font-mono",disabled:N})]})]}),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(O=>{const V=x===O,U=a(O==="user"?"settings.plugins.scope.user":"settings.plugins.scope.project");return s.jsxs("button",{type:"button",onClick:()=>v(O),disabled:N,className:"flex items-center gap-2 py-1 text-left disabled:opacity-50",children:[s.jsx(ir,{checked:V,onChange:()=>v(O),ariaLabel:U}),s.jsx("span",{className:le("typography-ui-label font-normal",V?"text-foreground":"text-foreground/60"),children:U})]},O)})})]})]}),s.jsxs(Zt,{children:[s.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>e(!1),disabled:N,children:a("settings.plugins.dialog.add.action.cancel")}),s.jsxs(Q,{size:"sm",onClick:()=>{T()},disabled:k,children:[N?s.jsx(L,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}):null,a("settings.plugins.dialog.add.action.submit")]})]})]})})},kx=t=>{const e=Ye.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=fs(a),{t:r}=it();if(!i)return null;const o=Nx;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(L,{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(L,{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(L,{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(L,{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(L,{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(L,{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(L,{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 Nx(t,e){return s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-xs",children:t})}),s.jsx(Ds,{children:e})]})}const Gd=t=>{const e=Ye.c(26),{header:n,footer:a,children:i,className:r,variant:o}=t,d=o===void 0?"sidebar":o,c=os(),p=l.useRef(null),[u,f]=l.useState(!1),[m,b]=l.useState(!1),h=d==="background"||c?"bg-background":"bg-sidebar",g=h==="bg-background"?"var(--surface-background)":"var(--surface-muted)";let x;e[0]===Symbol.for("react.memo_cache_sentinel")?(x=()=>{const k=p.current;if(!k){f(!1),b(!1);return}if(!(k.scrollHeight>k.clientHeight+1)){f(!1),b(!1);return}f(k.scrollTop>1),b(k.scrollTop+k.clientHeight<k.scrollHeight-1)},e[0]=x):x=e[0];const v=x;let N;e[1]===Symbol.for("react.memo_cache_sentinel")?(N=()=>{v()},e[1]=N):N=e[1];let P;e[2]!==i?(P=[i,v],e[2]=i,e[3]=P):P=e[3],l.useEffect(N,P);let F,w;e[4]===Symbol.for("react.memo_cache_sentinel")?(F=()=>{const k=p.current;if(!k)return;const T=()=>v();return k.addEventListener("scroll",T,{passive:!0}),()=>k.removeEventListener("scroll",T)},w=[v],e[4]=F,e[5]=w):(F=e[4],w=e[5]),l.useEffect(F,w);let j;e[6]!==h||e[7]!==r?(j=le("flex h-full flex-col",h,r),e[6]=h,e[7]=r,e[8]=j):j=e[8];let y;e[9]!==i?(y=s.jsx(Bs,{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]=y):y=e[10];let R;e[11]!==g||e[12]!==u?(R=u&&s.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-4",style:{background:`linear-gradient(to bottom, ${g} 0%, transparent 100%)`}}),e[11]=g,e[12]=u,e[13]=R):R=e[13];let _;e[14]!==g||e[15]!==m?(_=m&&s.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 h-6",style:{background:`linear-gradient(to top, ${g} 0%, transparent 100%)`}}),e[14]=g,e[15]=m,e[16]=_):_=e[16];let B;e[17]!==_||e[18]!==y||e[19]!==R?(B=s.jsxs("div",{className:"relative flex flex-1 min-h-0 flex-col",children:[y,R,_]}),e[17]=_,e[18]=y,e[19]=R,e[20]=B):B=e[20];let D;return e[21]!==a||e[22]!==n||e[23]!==B||e[24]!==j?(D=s.jsxs("div",{className:j,children:[n,B,a]}),e[21]=a,e[22]=n,e[23]=B,e[24]=j,e[25]=D):D=e[25],D},No=t=>{const e=Ye.c(23),{title:n,metadata:a,selected:i,onSelect:r,icon:o,actions:d,className:c}=t,p=i===void 0?!1:i,u=d&&d.length>0,f=p?"bg-interactive-selection":"hover:bg-interactive-hover";let m;e[0]!==c||e[1]!==f?(m=le("group relative flex items-center rounded-md px-1.5 py-0.5 transition-all duration-200",f,c),e[0]=c,e[1]=f,e[2]=m):m=e[2];let b;e[3]!==n?(b=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n}),e[3]=n,e[4]=b):b=e[4];let h;e[5]!==o||e[6]!==b?(h=s.jsxs("div",{className:"flex items-center gap-1.5",children:[o,b]}),e[5]=o,e[6]=b,e[7]=h):h=e[7];let g;e[8]!==a?(g=a&&s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:a}),e[8]=a,e[9]=g):g=e[9];let x;e[10]!==r||e[11]!==h||e[12]!==g?(x=s.jsxs("button",{onClick:r,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[h,g]}),e[10]=r,e[11]=h,e[12]=g,e[13]=x):x=e[13];let v;e[14]!==d||e[15]!==u?(v=u&&s.jsxs(ws,{children:[s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:d.map(Sx)})]}),e[14]=d,e[15]=u,e[16]=v):v=e[16];let N;e[17]!==x||e[18]!==v?(N=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[x,v]}),e[17]=x,e[18]=v,e[19]=N):N=e[19];let P;return e[20]!==m||e[21]!==N?(P=s.jsx("div",{className:m,children:N}),e[20]=m,e[21]=N,e[22]=P):P=e[22],P};function Sx(t){const e=t.icon;return s.jsxs(bs,{onClick:n=>{n.stopPropagation(),t.onClick()},className:le(t.destructive&&"text-destructive focus:text-destructive"),children:[e&&s.jsx(L,{name:e,className:"h-4 w-4 mr-px"}),t.label]},t.label)}const Cx=t=>t.parsedKind==="npm"?"code-box":"folder",Ix=t=>{const e=Ye.c(144),{onItemSelect:n,onAddClick:a}=t,{t:i}=it(),{entries:r,files:o,selectedId:d,setSelected:c,deleteEntry:p,deleteFile:u,loadPlugins:f}=fs(zs(Px)),m=fs(Ax),b=fs(Ex),h=fs(Tx),g=fs(Rx),[x,v]=l.useState(null),[N,P]=l.useState(!1),[F,w]=l.useState(!1);let j,y;e[0]!==f?(j=()=>{f()},y=[f],e[0]=f,e[1]=j,e[2]=y):(j=e[1],y=e[2]),l.useEffect(j,y);let R,_;e[3]===Symbol.for("react.memo_cache_sentinel")?(R=()=>{const Se=()=>w(!0);return window.addEventListener("openchamber:settings-open-plugin-add",Se),()=>window.removeEventListener("openchamber:settings-open-plugin-add",Se)},_=[],e[3]=R,e[4]=_):(R=e[3],_=e[4]),l.useEffect(R,_);let B;if(e[5]!==r||e[6]!==m){B={userEntries:0,projectEntries:0};for(const Se of r){const qe=m[Se.spec];qe?.kind==="npm-ok"&&qe.hasUpdate&&(Se.scope==="user"?B.userEntries=B.userEntries+1:Se.scope==="project"&&(B.projectEntries=B.projectEntries+1))}e[5]=r,e[6]=m,e[7]=B}else B=e[7];const D=B;let k;e[8]!==r?(k=r.filter(Dx),e[8]=r,e[9]=k):k=e[9];const T=k;let M;e[10]!==r?(M=r.filter(Mx),e[10]=r,e[11]=M):M=e[11];const O=M;let V;e[12]!==o?(V=o.filter(Lx),e[12]=o,e[13]=V):V=e[13];const U=V;let Y;e[14]!==o?(Y=o.filter(Fx),e[14]=o,e[15]=Y):Y=e[15];const X=Y,S=r.length+o.length,W=S===0;let Z;e[16]!==a?(Z=()=>{a?a():w(!0)},e[16]=a,e[17]=Z):Z=e[17];const A=Z;let C;e[18]!==n||e[19]!==c?(C=Se=>{c(Se),n?.()},e[18]=n,e[19]=c,e[20]=C):C=e[20];const z=C;let $;e[21]!==r||e[22]!==m||e[23]!==i||e[24]!==g?($=async Se=>{const qe=r.find(vt=>vt.id===Se);if(!qe)return;const Ze=m[qe.spec];if(!Ze||Ze.kind!=="npm-ok"||!Ze.hasUpdate||!Ze.latestVersion)return;const nt=Ze.latestVersion;(await g(Se)).ok?G.success(i("settings.plugins.toast.updatedToLatest",{version:nt})):G.error(i("settings.plugins.toast.refreshFailed"))},e[21]=r,e[22]=m,e[23]=i,e[24]=g,e[25]=$):$=e[25];const H=$;let J;e[26]!==h||e[27]!==i?(J=async()=>{G.info(i("settings.plugins.toast.refreshing"));try{await h({force:!0})}catch{G.error(i("settings.plugins.toast.refreshFailed"))}},e[26]=h,e[27]=i,e[28]=J):J=e[28];const ee=J;let ue;e[29]!==p||e[30]!==u||e[31]!==x||e[32]!==i?(ue=async()=>{if(!x)return;P(!0);const Se=x.kind==="entry"?await p(x.id):await u(x.id);Se.ok?G.success(Se.message||i("settings.plugins.sidebar.toast.deleted",{name:x.label})):G.error(i("settings.plugins.sidebar.toast.deleteFailed")),v(null),P(!1)},e[29]=p,e[30]=u,e[31]=x,e[32]=i,e[33]=ue):ue=e[33];const re=ue;let xe;e[34]!==z||e[35]!==H||e[36]!==m||e[37]!==d||e[38]!==i?(xe=Se=>{const qe=m[Se.spec],Ze=qe?.kind==="npm-ok"&&qe.hasUpdate&&!!qe.latestVersion,nt=[];return Ze&&nt.push({label:i("settings.plugins.sidebar.actions.updateToLatest"),icon:"arrow-up-s",onClick:()=>{H(Se.id)}}),nt.push({label:i("settings.common.actions.delete"),icon:"delete-bin",destructive:!0,onClick:()=>v({kind:"entry",id:Se.id,label:Se.spec})}),s.jsx(No,{title:s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Se.spec}),s.jsx(kx,{spec:Se.spec})]}),metadata:Se.parsedKind==="npm"?i("settings.plugins.sidebar.kind.npm"):i("settings.plugins.sidebar.kind.path"),selected:d===Se.id,onSelect:()=>z(Se.id),icon:s.jsx(L,{name:Cx(Se),className:"h-4 w-4 flex-shrink-0 text-muted-foreground/70"}),actions:nt},Se.id)},e[34]=z,e[35]=H,e[36]=m,e[37]=d,e[38]=i,e[39]=xe):xe=e[39];const be=xe;let he;e[40]!==z||e[41]!==d||e[42]!==i?(he=Se=>s.jsx(No,{title:Se.fileName,metadata:i("settings.plugins.sidebar.kind.file"),selected:d===Se.id,onSelect:()=>z(Se.id),icon:s.jsx(L,{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:()=>v({kind:"file",id:Se.id,label:Se.fileName})}]},Se.id),e[40]=z,e[41]=d,e[42]=i,e[43]=he):he=e[43];const ye=he;let fe;e[44]!==i?(fe=(Se,qe,Ze)=>{const nt=Ze===void 0?0:Ze;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[Se,nt>0&&s.jsx("span",{className:"ml-2 normal-case font-normal text-[var(--status-success)]",children:i(nt===1?"settings.plugins.sidebar.group.updatesAvailable_one":"settings.plugins.sidebar.group.updatesAvailable_other",{count:nt})})]}),qe]})},e[44]=i,e[45]=fe):fe=e[45];const ae=fe;let ce;e[46]!==i?(ce=i("settings.plugins.sidebar.title"),e[46]=i,e[47]=ce):ce=e[47];let pe;e[48]!==ce?(pe=s.jsx("div",{className:"mb-3 flex items-center justify-between gap-3",children:s.jsx("h2",{className:dn,children:ce})}),e[48]=ce,e[49]=pe):pe=e[49];let q;e[50]!==i||e[51]!==S?(q=i("settings.plugins.sidebar.total",{count:S}),e[50]=i,e[51]=S,e[52]=q):q=e[52];let te;e[53]!==q?(te=s.jsx("span",{className:"typography-meta text-muted-foreground",children:q}),e[53]=q,e[54]=te):te=e[54];let ne;e[55]!==ee?(ne=()=>{ee()},e[55]=ee,e[56]=ne):ne=e[56];let oe;e[57]!==i?(oe=i("settings.plugins.sidebar.actions.refresh"),e[57]=i,e[58]=oe):oe=e[58];let Ae;e[59]!==i?(Ae=i("settings.plugins.sidebar.actions.refresh"),e[59]=i,e[60]=Ae):Ae=e[60];const je=b?"size-4 animate-spin":"size-4";let Ie;e[61]!==je?(Ie=s.jsx(L,{name:"refresh",className:je}),e[61]=je,e[62]=Ie):Ie=e[62];let Te;e[63]!==b||e[64]!==ne||e[65]!==oe||e[66]!==Ae||e[67]!==Ie?(Te=s.jsx(Q,{type:"button","data-settings-item":"plugins.create",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:ne,disabled:b,"aria-label":oe,title:Ae,children:Ie}),e[63]=b,e[64]=ne,e[65]=oe,e[66]=Ae,e[67]=Ie,e[68]=Te):Te=e[68];let Me;e[69]!==i?(Me=i("settings.plugins.sidebar.actions.addTitle"),e[69]=i,e[70]=Me):Me=e[70];let He;e[71]!==i?(He=i("settings.plugins.sidebar.actions.addTitle"),e[71]=i,e[72]=He):He=e[72];let Ve;e[73]===Symbol.for("react.memo_cache_sentinel")?(Ve=s.jsx(L,{name:"add",className:"size-4"}),e[73]=Ve):Ve=e[73];let Ue;e[74]!==A||e[75]!==Me||e[76]!==He?(Ue=s.jsx(Q,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:A,"aria-label":Me,title:He,children:Ve}),e[74]=A,e[75]=Me,e[76]=He,e[77]=Ue):Ue=e[77];let ze;e[78]!==Te||e[79]!==Ue?(ze=s.jsxs("div",{className:"flex items-center gap-1",children:[Te,Ue]}),e[78]=Te,e[79]=Ue,e[80]=ze):ze=e[80];let Be;e[81]!==te||e[82]!==ze?(Be=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[te,ze]}),e[81]=te,e[82]=ze,e[83]=Be):Be=e[83];let Ge;e[84]!==pe||e[85]!==Be?(Ge=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[pe,Be]}),e[84]=pe,e[85]=Be,e[86]=Ge):Ge=e[86];let Fe;e[87]!==W||e[88]!==O||e[89]!==X||e[90]!==be||e[91]!==ye||e[92]!==ae||e[93]!==i||e[94]!==D||e[95]!==T||e[96]!==U?(Fe=W?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(L,{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:[T.length>0&&ae(i("settings.plugins.sidebar.group.userEntries"),T.map(be),D.userEntries),U.length>0&&ae(i("settings.plugins.sidebar.group.userFiles"),U.map(ye)),O.length>0&&ae(i("settings.plugins.sidebar.group.projectEntries"),O.map(be),D.projectEntries),X.length>0&&ae(i("settings.plugins.sidebar.group.projectFiles"),X.map(ye))]}),e[87]=W,e[88]=O,e[89]=X,e[90]=be,e[91]=ye,e[92]=ae,e[93]=i,e[94]=D,e[95]=T,e[96]=U,e[97]=Fe):Fe=e[97];let ve;e[98]!==Ge||e[99]!==Fe?(ve=s.jsx(Gd,{variant:"background",header:Ge,children:Fe}),e[98]=Ge,e[99]=Fe,e[100]=ve):ve=e[100];let De;e[101]!==F?(De=s.jsx(jx,{open:F,onOpenChange:w}),e[101]=F,e[102]=De):De=e[102];const Ke=x!==null;let We;e[103]!==N?(We=Se=>{!Se&&!N&&v(null)},e[103]=N,e[104]=We):We=e[104];let Pe;e[105]!==i?(Pe=i("settings.plugins.sidebar.deleteDialog.title"),e[105]=i,e[106]=Pe):Pe=e[106];let at;e[107]!==Pe?(at=s.jsx(zt,{children:Pe}),e[107]=Pe,e[108]=at):at=e[108];const se=x?.label??"";let I;e[109]!==i||e[110]!==se?(I=i("settings.plugins.sidebar.deleteDialog.description",{name:se}),e[109]=i,e[110]=se,e[111]=I):I=e[111];let Ee;e[112]!==I?(Ee=s.jsx(qt,{children:I}),e[112]=I,e[113]=Ee):Ee=e[113];let Le;e[114]!==at||e[115]!==Ee?(Le=s.jsxs(Ut,{children:[at,Ee]}),e[114]=at,e[115]=Ee,e[116]=Le):Le=e[116];let _e;e[117]===Symbol.for("react.memo_cache_sentinel")?(_e=()=>v(null),e[117]=_e):_e=e[117];let Xe;e[118]!==i?(Xe=i("settings.common.actions.cancel"),e[118]=i,e[119]=Xe):Xe=e[119];let ct;e[120]!==N||e[121]!==Xe?(ct=s.jsx(Q,{size:"sm",variant:"ghost",onClick:_e,disabled:N,children:Xe}),e[120]=N,e[121]=Xe,e[122]=ct):ct=e[122];let ut;e[123]!==N||e[124]!==i?(ut=i(N?"settings.plugins.sidebar.actions.deleting":"settings.common.actions.delete"),e[123]=N,e[124]=i,e[125]=ut):ut=e[125];let lt;e[126]!==re||e[127]!==N||e[128]!==ut?(lt=s.jsx(Q,{size:"sm",variant:"destructive",onClick:re,disabled:N,children:ut}),e[126]=re,e[127]=N,e[128]=ut,e[129]=lt):lt=e[129];let rt;e[130]!==ct||e[131]!==lt?(rt=s.jsxs(Zt,{children:[ct,lt]}),e[130]=ct,e[131]=lt,e[132]=rt):rt=e[132];let mt;e[133]!==Le||e[134]!==rt?(mt=s.jsxs(Ft,{className:"max-w-md",children:[Le,rt]}),e[133]=Le,e[134]=rt,e[135]=mt):mt=e[135];let xt;e[136]!==Ke||e[137]!==We||e[138]!==mt?(xt=s.jsx(Lt,{open:Ke,onOpenChange:We,children:mt}),e[136]=Ke,e[137]=We,e[138]=mt,e[139]=xt):xt=e[139];let It;return e[140]!==ve||e[141]!==De||e[142]!==xt?(It=s.jsxs(s.Fragment,{children:[ve,De,xt]}),e[140]=ve,e[141]=De,e[142]=xt,e[143]=It):It=e[143],It};function Px(t){return{entries:t.entries,files:t.files,selectedId:t.selectedId,setSelected:t.setSelected,deleteEntry:t.deleteEntry,deleteFile:t.deleteFile,loadPlugins:t.loadPlugins}}function Ax(t){return t.registryInfo}function Ex(t){return t.isLoadingRegistry}function Tx(t){return t.loadRegistryInfo}function Rx(t){return t.updateToLatest}function Dx(t){return t.scope==="user"}function Mx(t){return t.scope==="project"}function Lx(t){return t.scope==="user"}function Fx(t){return t.scope==="project"}const Ox=({entryId:t,spec:e})=>{const{t:n}=it(),a=fs(f=>f.registryInfo[e]),i=fs(f=>f.updateToLatest),[r,o]=l.useState(!1);if(!a)return null;if(a.kind==="npm-ok"){if(!a.hasUpdate||!a.latestVersion)return null;const f=a.latestVersion,m=a.currentVersion??"",b=async()=>{o(!0);try{(await i(t)).ok?G.success(n("settings.plugins.toast.updatedToLatest",{version:f})):G.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(L,{name:"arrow-up",className:"h-5 w-5 text-[var(--status-success)] shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"typography-label text-[var(--status-success)]",children:n("settings.plugins.registry.banner.updateAvailable.title")}),s.jsx("p",{className:"typography-micro text-muted-foreground mt-0.5",children:n("settings.plugins.registry.banner.updateAvailable.description",{current:m,latest:f})})]}),s.jsx(Q,{variant:"default",size:"sm",onClick:()=>{b()},disabled:r,children:n("settings.plugins.registry.banner.updateAvailable.action",{latest:f})})]})}if(a.kind==="path-ok")return null;if(a.kind==="npm-network")return s.jsxs("div",{className:"rounded-md border border-border bg-card p-3 flex items-start gap-3",children:[s.jsx(L,{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(L,{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 zx(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 qd(t){return!t||Object.keys(t).length===0?"":JSON.stringify(t,null,2)}function Yl(t){return{mode:"entry",scope:t.scope,spec:t.spec,optionsJson:qd(t.options),fileName:"",content:""}}function Xl(t,e){return{mode:"file",scope:t.scope,spec:"",optionsJson:"",fileName:t.fileName,content:e}}const Zl=t=>{const e=Ye.c(4),{scope:n,label:a}=t;let i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i=le("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},Bx=()=>{const{t}=it(),e=fs(x=>x.selectedId),n=fs(x=>x.entries),a=fs(x=>x.files),i=fs(x=>x.draft),r=fs(x=>x.setDraft),o=fs(x=>x.updateEntry),d=fs(x=>x.updateFile),c=fs(x=>x.readFile),p=l.useMemo(()=>e?n.find(x=>x.id===e)??null:null,[n,e]),u=l.useMemo(()=>e?a.find(x=>x.id===e)??null:null,[a,e]),[f,m]=l.useState(!1),[b,h]=l.useState(!1),g=l.useRef(new Map);if(l.useEffect(()=>{let x=!1;return p?(r(Yl(p)),()=>{x=!0}):u?(h(!0),(async()=>{const v=await c(u.id);if(x)return;h(!1);const N=v?.content??"";g.current.set(u.id,N),r(Xl(u,N))})(),()=>{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(L,{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=zx(i.optionsJson),v=x.ok,N=i.spec!==p.spec||i.optionsJson!==qd(p.options),P=()=>{r(Yl(p))},F=async()=>{if(!v)return;const w=i.spec.trim();if(!w){G.error(t("settings.plugins.validation.specRequired"));return}m(!0);try{const j=await o(p.id,{spec:w,options:x.value});j.ok?j.reloadFailed?G.warning(j.message||t("settings.plugins.toast.reloadFailed"),{description:j.warning}):G.success(j.message||t("settings.plugins.toast.updated")):G.error(j.message||t("settings.plugins.toast.reloadFailed"))}finally{m(!1)}};return s.jsxs(us,{title:t("settings.plugins.page.header.entry"),titleAccessory:s.jsx(Zl,{scope:p.scope,label:p.scope==="project"?t("settings.plugins.sidebar.group.projectEntries"):t("settings.plugins.sidebar.group.userEntries")}),showSaveStatus:!1,children:[s.jsx(ot,{divider:!1,children:s.jsx(Ox,{entryId:p.id,spec:p.spec})}),s.jsx(ot,{title:t("settings.plugins.page.field.spec"),settingsItem:"plugins.spec",children:s.jsx(tt,{value:i.spec,onChange:w=>r({...i,spec:w.target.value}),placeholder:t("settings.plugins.page.field.spec.placeholder"),className:"font-mono typography-meta",spellCheck:!1})}),s.jsxs(ot,{title:t("settings.plugins.page.field.options"),settingsItem:"plugins.options",children:[s.jsx(js,{value:i.optionsJson,onChange:w=>r({...i,optionsJson:w.target.value}),rows:10,className:le("font-mono typography-meta min-h-[200px]",!v&&"border-[var(--status-error-border)]"),spellCheck:!1,placeholder:"{ }"}),!v&&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(Q,{variant:"default",size:"sm",onClick:()=>{F()},disabled:!N||!v||f,children:t("settings.plugins.page.action.save")}),s.jsx(Q,{variant:"outline",size:"sm",onClick:P,disabled:!N||f,children:t("settings.plugins.page.action.discard")})]})]})]})}if(u&&i&&i.mode==="file"){const x=g.current.get(u.id)??"",v=i.content!==x||i.fileName!==u.fileName,N=()=>{(async()=>{h(!0);const w=(await c(u.id))?.content??"";h(!1),g.current.set(u.id,w),r(Xl(u,w))})()},P=async()=>{m(!0);try{const F=await d(u.id,{content:i.content});F.ok?(g.current.set(u.id,i.content),F.reloadFailed?G.warning(F.message||t("settings.plugins.toast.reloadFailed"),{description:F.warning}):G.success(F.message||t("settings.plugins.toast.updated"))):G.error(F.message||t("settings.plugins.toast.reloadFailed"))}finally{m(!1)}};return s.jsx(us,{title:t("settings.plugins.page.header.file"),titleAccessory:s.jsxs(s.Fragment,{children:[s.jsx(Zl,{scope:u.scope,label:u.scope==="project"?t("settings.plugins.sidebar.group.projectFiles"):t("settings.plugins.sidebar.group.userFiles")}),s.jsx("span",{className:le("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(ot,{title:t("settings.plugins.page.field.content"),divider:!1,settingsItem:"plugins.content",children:[s.jsx(js,{value:i.content,onChange:F=>r({...i,content:F.target.value}),rows:16,className:"font-mono typography-meta min-h-[320px]",spellCheck:!1,disabled:b}),s.jsxs("div",{className:"flex items-center gap-2 pt-3",children:[s.jsx(Q,{variant:"default",size:"sm",onClick:()=>{P()},disabled:!v||f||b,children:t("settings.plugins.page.action.save")}),s.jsx(Q,{variant:"outline",size:"sm",onClick:N,disabled:f||b,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(L,{name:"loader-4",className:"mx-auto mb-3 h-6 w-6 animate-spin opacity-50"})})})},Kx="<built-in>",ja=t=>t?.path===Kx,Ux=t=>{const e=Ye.c(150),{onItemSelect:n}=t,{t:a}=it(),[i,r]=l.useState(null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,f]=l.useState(!1),[m,b]=l.useState(null),{selectedSkillName:h,skills:g,setSelectedSkill:x,setSkillDraft:v,createSkill:N,deleteSkill:P,getSkillDetail:F}=Nn(zs(_x));let w;e[0]!==n||e[1]!==x||e[2]!==v||e[3]!==g?(w=()=>{let Se="new-skill",qe=1;for(;g.some(Ze=>Ze.name===Se);)Se=`new-skill-${qe}`,qe++;v({name:Se,scope:"user",source:"opencode",description:""}),x(Se),n?.()},e[0]=n,e[1]=x,e[2]=v,e[3]=g,e[4]=w):w=e[4];const j=w;let y;e[5]===Symbol.for("react.memo_cache_sentinel")?(y=async Se=>{ja(Se)||p(Se)},e[5]=y):y=e[5];const R=y;let _;e[6]!==c||e[7]!==P||e[8]!==a?(_=async()=>{if(!c)return;if(ja(c)){p(null);return}f(!0),await P(c.name)?(G.success(a("settings.skills.sidebar.toast.skillDeleted",{name:c.name})),p(null)):G.error(a("settings.skills.sidebar.toast.deleteSkillFailed")),f(!1)},e[6]=c,e[7]=P,e[8]=a,e[9]=_):_=e[9];const B=_;let D;e[10]!==F||e[11]!==x||e[12]!==v||e[13]!==g||e[14]!==a?(D=async Se=>{if(ja(Se))return;const qe=Se.name;let Ze=1,nt=`${qe}-copy`;for(;g.some(vt=>vt.name===nt);)Ze++,nt=`${qe}-copy-${Ze}`;const ft=await F(Se.name);if(!ft){G.error(a("settings.skills.sidebar.toast.duplicateLoadFailed"));return}v({name:nt,scope:Se.scope||"user",source:Se.source||"opencode",description:(ft.sources.md.fields.includes("description"),""),instructions:""}),x(nt)},e[10]=F,e[11]=x,e[12]=v,e[13]=g,e[14]=a,e[15]=D):D=e[15];const k=D;let T;e[16]===Symbol.for("react.memo_cache_sentinel")?(T=Se=>{ja(Se)||(d(Se.name),r(Se))},e[16]=T):T=e[16];const M=T;let O;e[17]!==N||e[18]!==P||e[19]!==F||e[20]!==i||e[21]!==o||e[22]!==x||e[23]!==g||e[24]!==a?(O=async()=>{if(!i)return;if(ja(i)){r(null);return}const Se=o.trim().replace(/\s+/g,"-").toLowerCase();if(!Se){G.error(a("settings.skills.page.toast.skillNameRequired"));return}if(Se===i.name){r(null);return}if(g.some(nt=>nt.name===Se)){G.error(a("settings.skills.page.toast.skillExists"));return}if(!await F(i.name)){G.error(a("settings.skills.sidebar.toast.renameLoadFailed")),r(null);return}await N({name:Se,description:"Renamed skill",scope:i.scope,source:i.source})?await P(i.name)?(G.success(`Skill renamed to "${Se}"`),x(Se)):G.error(a("settings.skills.sidebar.toast.removeOldAfterRenameFailed")):G.error(a("settings.skills.sidebar.toast.renameFailed")),r(null)},e[17]=N,e[18]=P,e[19]=F,e[20]=i,e[21]=o,e[22]=x,e[23]=g,e[24]=a,e[25]=O):O=e[25];const V=O;let U;e[26]!==g?(U=g.filter($x),e[26]=g,e[27]=U):U=e[27];const Y=U;let X;e[28]!==g?(X=g.filter(Vx),e[28]=g,e[29]=X):X=e[29];const S=X;let W;e[30]===Symbol.for("react.memo_cache_sentinel")?(W=function(qe){const Ze={},nt=[];for(const vt of qe)vt.group?(Ze[vt.group]||(Ze[vt.group]=[]),Ze[vt.group].push(vt)):nt.push(vt);const ft=Object.keys(Ze).sort(Hx).map(vt=>({name:vt,skills:[...Ze[vt]].sort(Wx)}));return nt.sort(Gx),{sortedGroups:ft,ungrouped:nt}},e[30]=W):W=e[30];const Z=W;let A;e[31]!==Y?(A=Z(Y),e[31]=Y,e[32]=A):A=e[32];const C=A;let z;e[33]!==S?(z=Z(S),e[33]=S,e[34]=z):z=e[34];const $=z;let H;e[35]===Symbol.for("react.memo_cache_sentinel")?(H=le("flex h-full flex-col","bg-background"),e[35]=H):H=e[35];let J;e[36]!==a?(J=a("settings.skills.sidebar.title"),e[36]=a,e[37]=J):J=e[37];let ee;e[38]!==J?(ee=s.jsx("h2",{className:`${dn} mb-3`,children:J}),e[38]=J,e[39]=ee):ee=e[39];let ue;e[40]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(ci,{className:"mb-3"}),e[40]=ue):ue=e[40];let re;e[41]!==g.length||e[42]!==a?(re=a("settings.skills.sidebar.total",{count:g.length}),e[41]=g.length,e[42]=a,e[43]=re):re=e[43];let xe;e[44]!==re?(xe=s.jsx("span",{className:"typography-meta text-muted-foreground",children:re}),e[44]=re,e[45]=xe):xe=e[45];let be;e[46]===Symbol.for("react.memo_cache_sentinel")?(be=s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),e[46]=be):be=e[46];let he;e[47]!==j?(he=s.jsx(Q,{size:"sm","data-settings-item":"skills.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:j,children:be}),e[47]=j,e[48]=he):he=e[48];let ye;e[49]!==xe||e[50]!==he?(ye=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[xe,he]}),e[49]=xe,e[50]=he,e[51]=ye):ye=e[51];let fe;e[52]!==ee||e[53]!==ye?(fe=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[ee,ue,ye]}),e[52]=ee,e[53]=ye,e[54]=fe):fe=e[54];let ae;e[55]!==C||e[56]!==$||e[57]!==k||e[58]!==n||e[59]!==m||e[60]!==Y||e[61]!==h||e[62]!==x||e[63]!==g.length||e[64]!==a||e[65]!==S?(ae=s.jsx(Bs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:g.length===0?s.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[s.jsx(L,{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:[Y.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")}),C.sortedGroups.map(Se=>{const{name:qe,skills:Ze}=Se;return s.jsx(vo,{label:qe,count:Ze.length,storageKey:"project-skills",children:Ze.map(nt=>s.jsx(Ei,{skill:nt,isSelected:h===nt.name,onSelect:()=>{x(nt.name),n?.()},onRename:()=>M(nt),onDelete:()=>R(nt),onDuplicate:()=>k(nt),isMenuOpen:m===nt.name,onMenuOpenChange:ft=>b(ft?nt.name:null)},nt.name))},qe)}),C.ungrouped.map(Se=>s.jsx(Ei,{skill:Se,isSelected:h===Se.name,onSelect:()=>{x(Se.name),n?.()},onRename:()=>M(Se),onDelete:()=>R(Se),onDuplicate:()=>k(Se),isMenuOpen:m===Se.name,onMenuOpenChange:qe=>b(qe?Se.name:null)},Se.name))]}),S.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")}),$.sortedGroups.map(Se=>{const{name:qe,skills:Ze}=Se;return s.jsx(vo,{label:qe,count:Ze.length,storageKey:"user-skills",children:Ze.map(nt=>s.jsx(Ei,{skill:nt,isSelected:h===nt.name,onSelect:()=>{x(nt.name),n?.()},onRename:()=>M(nt),onDelete:()=>R(nt),onDuplicate:()=>k(nt),isMenuOpen:m===nt.name,onMenuOpenChange:ft=>b(ft?nt.name:null)},nt.name))},qe)}),$.ungrouped.map(Se=>s.jsx(Ei,{skill:Se,isSelected:h===Se.name,onSelect:()=>{x(Se.name),n?.()},onRename:()=>M(Se),onDelete:()=>R(Se),onDuplicate:()=>k(Se),isMenuOpen:m===Se.name,onMenuOpenChange:qe=>b(qe?Se.name:null)},Se.name))]})]})}),e[55]=C,e[56]=$,e[57]=k,e[58]=n,e[59]=m,e[60]=Y,e[61]=h,e[62]=x,e[63]=g.length,e[64]=a,e[65]=S,e[66]=ae):ae=e[66];const ce=c!==null;let pe;e[67]!==u?(pe=Se=>{!Se&&!u&&p(null)},e[67]=u,e[68]=pe):pe=e[68];let q;e[69]!==a?(q=a("settings.skills.sidebar.deleteDialog.title"),e[69]=a,e[70]=q):q=e[70];let te;e[71]!==q?(te=s.jsx(zt,{children:q}),e[71]=q,e[72]=te):te=e[72];const ne=c?.name??"";let oe;e[73]!==a||e[74]!==ne?(oe=a("settings.skills.sidebar.deleteDialog.description",{name:ne}),e[73]=a,e[74]=ne,e[75]=oe):oe=e[75];let Ae;e[76]!==oe?(Ae=s.jsx(qt,{children:oe}),e[76]=oe,e[77]=Ae):Ae=e[77];let je;e[78]!==te||e[79]!==Ae?(je=s.jsxs(Ut,{children:[te,Ae]}),e[78]=te,e[79]=Ae,e[80]=je):je=e[80];let Ie;e[81]===Symbol.for("react.memo_cache_sentinel")?(Ie=()=>p(null),e[81]=Ie):Ie=e[81];let Te;e[82]!==a?(Te=a("settings.common.actions.cancel"),e[82]=a,e[83]=Te):Te=e[83];let Me;e[84]!==u||e[85]!==Te?(Me=s.jsx(Q,{size:"sm",className:"text-foreground hover:bg-interactive-hover hover:text-foreground",variant:"ghost",onClick:Ie,disabled:u,children:Te}),e[84]=u,e[85]=Te,e[86]=Me):Me=e[86];let He;e[87]!==a?(He=a("settings.common.actions.delete"),e[87]=a,e[88]=He):He=e[88];let Ve;e[89]!==B||e[90]!==u||e[91]!==He?(Ve=s.jsx(Q,{size:"sm",onClick:B,disabled:u,children:He}),e[89]=B,e[90]=u,e[91]=He,e[92]=Ve):Ve=e[92];let Ue;e[93]!==Me||e[94]!==Ve?(Ue=s.jsxs(Zt,{children:[Me,Ve]}),e[93]=Me,e[94]=Ve,e[95]=Ue):Ue=e[95];let ze;e[96]!==je||e[97]!==Ue?(ze=s.jsxs(Ft,{className:"max-w-md",children:[je,Ue]}),e[96]=je,e[97]=Ue,e[98]=ze):ze=e[98];let Be;e[99]!==ce||e[100]!==pe||e[101]!==ze?(Be=s.jsx(Lt,{open:ce,onOpenChange:pe,children:ze}),e[99]=ce,e[100]=pe,e[101]=ze,e[102]=Be):Be=e[102];const Ge=i!==null;let Fe;e[103]===Symbol.for("react.memo_cache_sentinel")?(Fe=Se=>!Se&&r(null),e[103]=Fe):Fe=e[103];let ve;e[104]!==a?(ve=a("settings.skills.sidebar.renameDialog.title"),e[104]=a,e[105]=ve):ve=e[105];let De;e[106]!==ve?(De=s.jsx(zt,{children:ve}),e[106]=ve,e[107]=De):De=e[107];const Ke=i?.name??"";let We;e[108]!==a||e[109]!==Ke?(We=a("settings.skills.sidebar.renameDialog.description",{name:Ke}),e[108]=a,e[109]=Ke,e[110]=We):We=e[110];let Pe;e[111]!==We?(Pe=s.jsx(qt,{children:We}),e[111]=We,e[112]=Pe):Pe=e[112];let at;e[113]!==De||e[114]!==Pe?(at=s.jsxs(Ut,{children:[De,Pe]}),e[113]=De,e[114]=Pe,e[115]=at):at=e[115];let se;e[116]===Symbol.for("react.memo_cache_sentinel")?(se=Se=>d(Se.target.value),e[116]=se):se=e[116];let I;e[117]!==a?(I=a("settings.skills.sidebar.renameDialog.placeholder"),e[117]=a,e[118]=I):I=e[118];let Ee;e[119]!==V?(Ee=Se=>{Se.key==="Enter"&&V()},e[119]=V,e[120]=Ee):Ee=e[120];let Le;e[121]!==o||e[122]!==I||e[123]!==Ee?(Le=s.jsx(tt,{value:o,onChange:se,placeholder:I,className:"text-foreground placeholder:text-muted-foreground",onKeyDown:Ee}),e[121]=o,e[122]=I,e[123]=Ee,e[124]=Le):Le=e[124];let _e;e[125]===Symbol.for("react.memo_cache_sentinel")?(_e=()=>r(null),e[125]=_e):_e=e[125];let Xe;e[126]!==a?(Xe=a("settings.common.actions.cancel"),e[126]=a,e[127]=Xe):Xe=e[127];let ct;e[128]!==Xe?(ct=s.jsx(Q,{size:"sm",className:"text-foreground hover:bg-interactive-hover hover:text-foreground",variant:"ghost",onClick:_e,children:Xe}),e[128]=Xe,e[129]=ct):ct=e[129];let ut;e[130]!==a?(ut=a("settings.common.actions.rename"),e[130]=a,e[131]=ut):ut=e[131];let lt;e[132]!==V||e[133]!==ut?(lt=s.jsx(Q,{size:"sm",onClick:V,children:ut}),e[132]=V,e[133]=ut,e[134]=lt):lt=e[134];let rt;e[135]!==ct||e[136]!==lt?(rt=s.jsxs(Zt,{children:[ct,lt]}),e[135]=ct,e[136]=lt,e[137]=rt):rt=e[137];let mt;e[138]!==at||e[139]!==Le||e[140]!==rt?(mt=s.jsxs(Ft,{children:[at,Le,rt]}),e[138]=at,e[139]=Le,e[140]=rt,e[141]=mt):mt=e[141];let xt;e[142]!==Ge||e[143]!==mt?(xt=s.jsx(Lt,{open:Ge,onOpenChange:Fe,children:mt}),e[142]=Ge,e[143]=mt,e[144]=xt):xt=e[144];let It;return e[145]!==fe||e[146]!==ae||e[147]!==Be||e[148]!==xt?(It=s.jsxs("div",{className:H,children:[fe,ae,Be,xt]}),e[145]=fe,e[146]=ae,e[147]=Be,e[148]=xt,e[149]=It):It=e[149],It},Ei=t=>{const e=Ye.c(49),{skill:n,isSelected:a,onSelect:i,onDelete:r,onRename:o,onDuplicate:d,isMenuOpen:c,onMenuOpenChange:p}=t,{t:u}=it();let f;e[0]===Symbol.for("react.memo_cache_sentinel")?(f=si(),e[0]=f):f=e[0];const m=f;let b;e[1]!==n.source||e[2]!==u?(b=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]=b):b=e[3];const h=b;let g;e[4]!==n?(g=ja(n),e[4]=n,e[5]=g):g=e[5];const x=g,[v,N]=l.useState(!1);let P;e[6]!==r||e[7]!==d||e[8]!==o||e[9]!==u?(P=S=>s.jsxs(s.Fragment,{children:[s.jsxs(S,{onClick:W=>{W.stopPropagation(),o()},children:[s.jsx(L,{name:"edit",className:"h-4 w-4 mr-px"}),u("settings.common.actions.rename")]}),s.jsxs(S,{onClick:W=>{W.stopPropagation(),d()},children:[s.jsx(L,{name:"file-copy",className:"h-4 w-4 mr-px"}),u("settings.common.actions.duplicate")]}),s.jsxs(S,{onClick:W=>{W.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{name:"delete-bin",className:"h-4 w-4 mr-px"}),u("settings.common.actions.delete")]})]}),e[6]=r,e[7]=d,e[8]=o,e[9]=u,e[10]=P):P=e[10];const F=P,w=!x&&v,j=a?"bg-interactive-selection":"hover:bg-interactive-hover";let y;e[11]!==j?(y=le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",j),e[11]=j,e[12]=y):y=e[12];let R;e[13]!==x?(R=!m&&!x?S=>{S.preventDefault(),N(!0)}:void 0,e[13]=x,e[14]=R):R=e[14];let _;e[15]!==y||e[16]!==R?(_=s.jsx("div",{className:y,onContextMenu:R}),e[15]=y,e[16]=R,e[17]=_):_=e[17];let B;e[18]!==n.name?(B=s.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:n.name}),e[18]=n.name,e[19]=B):B=e[19];let D;e[20]!==n.scope?(D=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[20]=n.scope,e[21]=D):D=e[21];let k;e[22]!==h?(k=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[22]=h,e[23]=k):k=e[23];let T;e[24]!==B||e[25]!==D||e[26]!==k?(T=s.jsxs("div",{className:"flex items-center gap-1.5",children:[B,D,k]}),e[24]=B,e[25]=D,e[26]=k,e[27]=T):T=e[27];let M;e[28]!==i||e[29]!==T?(M=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:T}),e[28]=i,e[29]=T,e[30]=M):M=e[30];let O;e[31]!==x||e[32]!==c||e[33]!==p||e[34]!==F?(O=x?null:s.jsxs(ws,{open:c,onOpenChange:S=>{S&&N(!1),p(S)},children:[s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:F(bs)})]}),e[31]=x,e[32]=c,e[33]=p,e[34]=F,e[35]=O):O=e[35];let V;e[36]!==M||e[37]!==O?(V=s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[M,O]}),e[36]=M,e[37]=O,e[38]=V):V=e[38];let U;e[39]!==V||e[40]!==_?(U=s.jsx(_n,{render:_,children:V}),e[39]=V,e[40]=_,e[41]=U):U=e[41];let Y;e[42]!==x||e[43]!==F?(Y=x?null:s.jsx($n,{className:"w-fit min-w-20",children:F(En)}),e[42]=x,e[43]=F,e[44]=Y):Y=e[44];let X;return e[45]!==U||e[46]!==Y||e[47]!==w?(X=s.jsxs(Un,{open:w,onOpenChange:N,children:[U,Y]}),e[45]=U,e[46]=Y,e[47]=w,e[48]=X):X=e[48],X};function _x(t){return{selectedSkillName:t.selectedSkillName,skills:t.skills,setSelectedSkill:t.setSelectedSkill,setSkillDraft:t.setSkillDraft,createSkill:t.createSkill,deleteSkill:t.deleteSkill,getSkillDetail:t.getSkillDetail}}function $x(t){return t.scope==="project"}function Vx(t){return t.scope==="user"}function Hx(t,e){return t.localeCompare(e)}function Wx(t,e){return t.name.localeCompare(e.name)}function Gx(t,e){return t.name.localeCompare(e.name)}const qx=t=>t!==null&&typeof t=="object"&&"updateStatus"in t&&typeof t.updateStatus=="function",Jx=t=>{const e=document.createElement("div");e.className="cm-vim-panel";const n=dm(t);if(!n)return{top:!1,dom:e};n.state.statusbar=e;const a=n.state.vimPlugin;return qx(a)&&a.updateStatus(),{top:!1,dom:e,destroy(){n.state.statusbar===e&&(n.state.statusbar=null)}}};function ec(t){return t?[om(),lm.of(Jx),cm()]:[]}const Qx={next:"Next match",prev:"Previous match",select:"Select all matches",replace:"Replace",replaceAll:"Replace all",close:"Close"},Yx={case:"Match case",re:"Regular expression",word:"Match whole word"};function Xx(t){const e=t.querySelector(".cm-search");if(e){for(const[n,a]of Object.entries(Qx)){const i=e.querySelector(`button[name="${n}"]`);i&&!i.title&&(i.title=a)}for(const[n,a]of Object.entries(Yx)){const r=e.querySelector(`input[name="${n}"]`)?.parentElement;r&&!r.title&&(r.title=a)}}}const zr=new WeakMap;function Zx(t,e){const n=Ji(t.state);if(!n.valid)return zr.delete(t),0;const a=zr.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 zr.set(t,{query:n,doc:t.state.doc,total:r}),r}function eb(t){const e=Ji(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 tc(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=Zx(e,n),o=r===0?0:eb(e);i.textContent=r===0?"":`${o}/${r}`}const sc=new ra,nc=new ra,ac=new ra,ic=new ra,rc=new ra,oc=new ra,lc=new ra,cc=t=>t,Br=bm,tb=ym,sb=vm;class nb extends wm{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 dc=(t,e)=>!t||t.length===0?[]:xd.define({create(n){const a=new Ro,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,nr.widget({widget:new nb(r.id,e),block:!0,side:1}))}return a.finish()},update(n,a){return n.map(a.changes)},provide:n=>nn.decorations.from(n)}),uc=t=>{if(!t)return[];const e=Math.max(1,t.start),n=Math.max(e,t.end);return hd.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 Ro;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,nr.line({class:"oc-cm-selected-line"}))}return i.finish()}},{decorations:a=>a.decorations})};function mc({value:t,onChange:e,extensions:n,className:a,readOnly:i,lineNumbersConfig:r,highlightLines:o,onViewReady:d,onViewDestroy:c,blockWidgets:p,enableSearch:u,searchOpen:f,onSearchOpenChange:m,vimMode:b}){const h=l.useRef(null),g=l.useRef(null),x=l.useRef(t),v=l.useRef(e),N=l.useRef(d),P=l.useRef(c),F=l.useRef(m),w=l.useRef(p),j=l.useRef(b),y=l.useRef(new Map),[R,_]=l.useState([]),B=l.useCallback(k=>{const T=(k??[]).map(M=>{const O=y.current.get(M.id);return O?{id:M.id,content:M.content,container:O}:null}).filter(M=>M!==null);_(M=>M.length===T.length&&M.every((O,V)=>{const U=T[V];return O.id===U.id&&O.content===U.content&&O.container===U.container})?M:T)},[]),D=l.useCallback(k=>{const T=h.current,M=k??g.current;if(!T||!M)return;const O=M.dom.querySelector(".cm-gutters"),V=O instanceof HTMLElement?O.getBoundingClientRect().width:0;T.style.setProperty("--oc-editor-gutter-width",`${V}px`)},[]);return l.useEffect(()=>{x.current=t},[t]),l.useEffect(()=>{v.current=e},[e]),l.useEffect(()=>{N.current=d,P.current=c},[d,c]),l.useEffect(()=>{F.current=m},[m]),l.useEffect(()=>{w.current=p,B(p)},[p,B]),l.useEffect(()=>{if(!h.current)return;const k=(()=>{if(typeof document>"u")return null;const M=document.querySelector('meta[name="csp-nonce"]')?.getAttribute("content");if(M)return M;const O=window.__OPENCHAMBER_CSP_NONCE__;return typeof O=="string"&&O.length>0?O:null})(),T=um.create({doc:x.current,extensions:[...k?[nn.cspNonce.of(k)]:[],mm({fixed:!0}),sc.of(Ho(r)),pm(),gm.of(" "),lc.of(ec(b)),Cr.of([fm,...hm,...xm]),nn.updateListener.of(M=>{D(M.view),(M.viewportChanged||M.geometryChanged)&&B(w.current);const O=Wo(M.startState),V=Wo(M.state);O!==V&&F.current?.(V);const U=!Ji(M.startState).eq(Ji(M.state));if(V&&(O!==V||U||M.docChanged||M.selectionSet)&&tc(M.view.dom,M.view,O!==V||U||M.docChanged),!M.docChanged)return;const Y=M.state.doc.toString();x.current=Y,v.current(Y),B(w.current)}),nc.of(nn.editable.of(!i)),ac.of(n??[]),ic.of(uc(o)),rc.of(dc(p,y.current)),oc.of(u?[Go({top:!0}),Cr.of(cc(qo))]:[])]});return g.current=new nn({state:T,parent:h.current}),Br(g.current,g.current.state.doc.length,200),g.current.requestMeasure(),requestAnimationFrame(()=>{D(g.current),B(w.current)}),g.current&&N.current?.(g.current),()=>{P.current?.(),g.current?.destroy(),g.current=null,_([])}},[w,D,B]),l.useEffect(()=>{const k=g.current;k&&(k.dispatch({effects:[sc.reconfigure(Ho(r)),nc.reconfigure(nn.editable.of(!i)),ac.reconfigure(n??[]),ic.reconfigure(uc(o)),rc.reconfigure(dc(p,y.current)),oc.reconfigure(u?[Go({top:!0}),Cr.of(cc(qo))]:[])]}),Br(k,k.state.doc.length,200),k.requestMeasure(),requestAnimationFrame(()=>{D(k),B(w.current)}))},[n,o,r,i,p,u,D,B]),l.useEffect(()=>{const k=g.current;if(!k){j.current=b;return}j.current!==b&&(j.current=b,k.dispatch({effects:lc.reconfigure(ec(b))}))},[b]),l.useEffect(()=>{const k=g.current;!k||u===!1||(f?(tb(k),requestAnimationFrame(()=>{Xx(k.dom),tc(k.dom,k,!0)})):sb(k))},[f,u]),l.useEffect(()=>{const k=g.current;if(!k)return;const T=k.state.doc.toString();T!==t&&(k.dispatch({changes:{from:0,to:T.length,insert:t}}),Br(k,k.state.doc.length,300),k.requestMeasure(),requestAnimationFrame(()=>D(k)))},[t,D]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:h,className:le("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)}),R.map(k=>Ki.createPortal(k.content,k.container,k.id))]})}const ab=t=>{const e=Ye.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(L,{name:"eye",className:"size-4","aria-hidden":"true"}):s.jsx(L,{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(As,{asChild:!0,children:s.jsx(Q,{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(Ds,{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(Ps,{children:[c,p]}),e[8]=c,e[9]=p,e[10]=u):u=e[10],u},Os=cn()(Da(ii((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 ap();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 np();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 sp();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=ln()?.settings;if(i)try{const o=(await i.load())?.settings||{};a=n(o.defaultGitIdentityId)}catch{}}if(a===null)try{const i=await gt("/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 kt({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 Hs("saving"),await tp(a),Hs("saved"),await e().loadProfiles(),!0}catch(a){return Hs("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 Hs("saving"),await ep(n,r),Hs("saved"),await e().loadProfiles(),!0}catch(i){return Hs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return Hs("saving"),await Zm(n),Hs("saved"),e().selectedProfileId===n&&t({selectedProfileId:null}),await e().loadProfiles(),!0}catch(a){return Hs("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:lr(),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Os);const ib=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,rb=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},ob=async()=>{try{const t=ln()?.settings;if(t)return(await t.load())?.settings||{};const e=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return e.ok?await e.json().catch(()=>null):null}catch{return null}},lb=t=>{const e=Ye.c(162),{open:n,onOpenChange:a}=t,{t:i}=it(),r=jn(cb),o=jn(db),d=jn(ub),c=jn(mb),p=jn(pb),u=Os(gb),f=Os(fb),[m,b]=l.useState(""),[h,g]=l.useState(""),[x,v]=l.useState("");let N;e[0]===Symbol.for("react.memo_cache_sentinel")?(N=[],e[0]=N):N=e[0];const[P,F]=l.useState(N),[w,j]=l.useState(null),[y,R]=l.useState(!1);let _;e[1]===Symbol.for("react.memo_cache_sentinel")?(_=[],e[1]=_):_=e[1];const[B,D]=l.useState(_),[k,T]=l.useState(null),M=l.useRef(0);let O;e[2]===Symbol.for("react.memo_cache_sentinel")?(O=qe=>{M.current=M.current+1,R(!1),j(null),qe?.clearIdentity&&(D([]),T(null))},e[2]=O):O=e[2];const V=O;let U,Y;e[3]!==f||e[4]!==n?(U=()=>{n&&(M.current=M.current+1,b(""),g(""),v(""),j(null),R(!1),D([]),T(null),f(),(async()=>{const qe=await ob(),Ze=Array.isArray(qe?.skillCatalogs)?qe?.skillCatalogs:[];F(Ze||[])})())},Y=[n,f],e[3]=f,e[4]=n,e[5]=U,e[6]=Y):(U=e[5],Y=e[6]),l.useEffect(U,Y);let X;e[7]!==h?(X=h.trim(),e[7]=h,e[8]=X):X=e[8];const S=X;let W;e[9]!==x?(W=x.trim(),e[9]=x,e[10]=W):W=e[10];const Z=W;let A;if(e[11]!==P||e[12]!==S||e[13]!==Z){let qe;e[15]!==S||e[16]!==Z?(qe=Ze=>{const nt=(Ze.source||"").trim(),ft=(Ze.subpath||"").trim();return nt===S&&ft===Z},e[15]=S,e[16]=Z,e[17]=qe):qe=e[17],A=P.some(qe),e[11]=P,e[12]=S,e[13]=Z,e[14]=A}else A=e[14];const C=A;let z;e[18]!==u||e[19]!==k||e[20]!==m||e[21]!==r||e[22]!==h||e[23]!==x||e[24]!==i?(z=async()=>{const qe=h.trim();if(!qe){G.error(i("settings.skills.catalog.add.toast.repositoryRequired"));return}m.trim()||b(rb(qe)),R(!1),j(null);const Ze=M.current+1;M.current=Ze;const nt=await r({source:qe,subpath:x.trim()||void 0,gitIdentityId:k||void 0});if(M.current!==Ze)return;if(!nt.ok){if(nt.error?.kind==="authRequired"){if(os()){G.error(i("settings.skills.catalog.shared.toast.privateRepoNotSupportedVsCode"));return}const vt=nt.error.identities||[];if(D(vt),!k&&vt.length>0){const St=u&&u!=="global"&&vt.some(de=>de.id===u)?u:vt[0].id;T(St)}G.error(i("settings.skills.catalog.add.toast.authenticationRequiredScan"));return}G.error(nt.error?.message||i("settings.skills.catalog.add.toast.scanFailed"));return}const ft=nt.items?.length||0;if(j(ft),ft===0){G.error(i("settings.skills.catalog.add.toast.noSkillsFound")),R(!1);return}D([]),R(!0),G.success(i("settings.skills.catalog.shared.toast.foundSkills",{count:ft}))},e[18]=u,e[19]=k,e[20]=m,e[21]=r,e[22]=h,e[23]=x,e[24]=i,e[25]=z):z=e[25];const $=z;let H;e[26]!==P||e[27]!==k||e[28]!==C||e[29]!==m||e[30]!==o||e[31]!==d||e[32]!==a||e[33]!==y||e[34]!==c||e[35]!==h||e[36]!==x||e[37]!==i?(H=async()=>{const qe=m.trim(),Ze=h.trim(),nt=x.trim();if(!qe){G.error(i("settings.skills.catalog.add.toast.catalogNameRequired"));return}if(!Ze){G.error(i("settings.skills.catalog.add.toast.repositoryRequired"));return}if(!y){G.error(i("settings.skills.catalog.add.toast.scanBeforeAdd"));return}if(C){G.error(i("settings.skills.catalog.add.toast.catalogAlreadyExists"));return}const ft={id:ib(),label:qe,source:Ze,...nt?{subpath:nt}:{},...k?{gitIdentityId:k}:{}},vt=[...P,ft];try{await kt({skillCatalogs:vt}),F(vt),G.success(i("settings.skills.catalog.add.toast.catalogAdded")),await o({refresh:!0}),await d(ft.id,{refresh:!0}),c(ft.id),a(!1)}catch(St){const de=St;G.error(de instanceof Error?de.message:i("settings.skills.catalog.add.toast.saveFailed"))}},e[26]=P,e[27]=k,e[28]=C,e[29]=m,e[30]=o,e[31]=d,e[32]=a,e[33]=y,e[34]=c,e[35]=h,e[36]=x,e[37]=i,e[38]=H):H=e[38];const J=H;let ee;e[39]!==i?(ee=i("settings.skills.catalog.add.title"),e[39]=i,e[40]=ee):ee=e[40];let ue;e[41]!==ee?(ue=s.jsx(zt,{children:ee}),e[41]=ee,e[42]=ue):ue=e[42];let re;e[43]!==i?(re=i("settings.skills.catalog.add.descriptionPrefix"),e[43]=i,e[44]=re):re=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 he;e[48]!==re||e[49]!==be?(he=s.jsxs(qt,{children:[re," ",xe,be]}),e[48]=re,e[49]=be,e[50]=he):he=e[50];let ye;e[51]!==ue||e[52]!==he?(ye=s.jsxs(Ut,{children:[ue,he]}),e[51]=ue,e[52]=he,e[53]=ye):ye=e[53];let fe;e[54]!==i?(fe=i("settings.skills.catalog.add.field.catalogName"),e[54]=i,e[55]=fe):fe=e[55];let ae;e[56]!==fe?(ae=s.jsx("label",{className:"typography-ui-label text-foreground",children:fe}),e[56]=fe,e[57]=ae):ae=e[57];let ce;e[58]===Symbol.for("react.memo_cache_sentinel")?(ce=qe=>b(qe.target.value),e[58]=ce):ce=e[58];let pe;e[59]!==i?(pe=i("settings.skills.catalog.add.field.catalogNamePlaceholder"),e[59]=i,e[60]=pe):pe=e[60];let q;e[61]!==m||e[62]!==pe?(q=s.jsx(tt,{value:m,onChange:ce,placeholder:pe}),e[61]=m,e[62]=pe,e[63]=q):q=e[63];let te;e[64]!==ae||e[65]!==q?(te=s.jsxs("div",{className:"space-y-2",children:[ae,q]}),e[64]=ae,e[65]=q,e[66]=te):te=e[66];let ne;e[67]!==i?(ne=i("settings.skills.catalog.add.field.repository"),e[67]=i,e[68]=ne):ne=e[68];let oe;e[69]!==ne?(oe=s.jsx("label",{className:"typography-ui-label text-foreground",children:ne}),e[69]=ne,e[70]=oe):oe=e[70];let Ae;e[71]!==i?(Ae=i("settings.skills.catalog.add.field.repositoryHint"),e[71]=i,e[72]=Ae):Ae=e[72];let je;e[73]!==Ae?(je=s.jsx(Ht,{children:Ae}),e[73]=Ae,e[74]=je):je=e[74];let Ie;e[75]!==oe||e[76]!==je?(Ie=s.jsxs("div",{className:"flex items-center gap-1",children:[oe,je]}),e[75]=oe,e[76]=je,e[77]=Ie):Ie=e[77];let Te;e[78]===Symbol.for("react.memo_cache_sentinel")?(Te=qe=>{g(qe.target.value),V({clearIdentity:!0})},e[78]=Te):Te=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 He;e[81]!==h||e[82]!==Me?(He=s.jsx(tt,{value:h,onChange:Te,placeholder:Me}),e[81]=h,e[82]=Me,e[83]=He):He=e[83];let Ve;e[84]!==Ie||e[85]!==He?(Ve=s.jsxs("div",{className:"space-y-2",children:[Ie,He]}),e[84]=Ie,e[85]=He,e[86]=Ve):Ve=e[86];let Ue;e[87]!==i?(Ue=i("settings.skills.catalog.add.field.optionalSubpath"),e[87]=i,e[88]=Ue):Ue=e[88];let ze;e[89]!==Ue?(ze=s.jsx("label",{className:"typography-ui-label text-foreground",children:Ue}),e[89]=Ue,e[90]=ze):ze=e[90];let Be;e[91]===Symbol.for("react.memo_cache_sentinel")?(Be=qe=>{v(qe.target.value),V({clearIdentity:!0})},e[91]=Be):Be=e[91];let Ge;e[92]!==i?(Ge=i("settings.skills.catalog.shared.field.subpathPlaceholder"),e[92]=i,e[93]=Ge):Ge=e[93];let Fe;e[94]!==x||e[95]!==Ge?(Fe=s.jsx(tt,{value:x,onChange:Be,placeholder:Ge}),e[94]=x,e[95]=Ge,e[96]=Fe):Fe=e[96];let ve;e[97]!==ze||e[98]!==Fe?(ve=s.jsxs("div",{className:"space-y-2",children:[ze,Fe]}),e[97]=ze,e[98]=Fe,e[99]=ve):ve=e[99];let De;e[100]!==k||e[101]!==B||e[102]!==i?(De=B.length>0&&!os()?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(Ht,{className:"ml-1",children:i("settings.skills.catalog.shared.auth.footerHint")})]}),s.jsxs(At,{value:k||"",onValueChange:qe=>{T(qe),V()},children:[s.jsx(Et,{className:"w-fit",children:s.jsx("span",{children:B.find(qe=>qe.id===k)?.name||i("settings.skills.catalog.shared.auth.chooseIdentity")})}),s.jsx(Tt,{align:"start",children:B.map(hb)})]})]}):null,e[100]=k,e[101]=B,e[102]=i,e[103]=De):De=e[103];let Ke;e[104]!==w||e[105]!==i?(Ke=w!==null?s.jsx("div",{className:"typography-meta text-muted-foreground",children:i("settings.skills.catalog.add.scanResult",{count:w})}):null,e[104]=w,e[105]=i,e[106]=Ke):Ke=e[106];let We;e[107]!==C||e[108]!==i?(We=C?s.jsx("div",{className:"typography-meta text-muted-foreground",children:i("settings.skills.catalog.add.duplicateMessage")}):null,e[107]=C,e[108]=i,e[109]=We):We=e[109];let Pe;e[110]!==te||e[111]!==Ve||e[112]!==ve||e[113]!==De||e[114]!==Ke||e[115]!==We?(Pe=s.jsxs("div",{className:"space-y-4",children:[te,Ve,ve,De,Ke,We]}),e[110]=te,e[111]=Ve,e[112]=ve,e[113]=De,e[114]=Ke,e[115]=We,e[116]=Pe):Pe=e[116];let at;e[117]!==a?(at=()=>a(!1),e[117]=a,e[118]=at):at=e[118];let se;e[119]!==i?(se=i("settings.common.actions.cancel"),e[119]=i,e[120]=se):se=e[120];let I;e[121]!==at||e[122]!==se?(I=s.jsx(Q,{size:"sm",variant:"ghost",onClick:at,children:se}),e[121]=at,e[122]=se,e[123]=I):I=e[123];let Ee;e[124]!==$?(Ee=()=>{$()},e[124]=$,e[125]=Ee):Ee=e[125];let Le;e[126]!==p||e[127]!==h?(Le=p||!h.trim(),e[126]=p,e[127]=h,e[128]=Le):Le=e[128];let _e;e[129]===Symbol.for("react.memo_cache_sentinel")?(_e=s.jsx(L,{name:"git-repository",className:"h-4 w-4"}),e[129]=_e):_e=e[129];let Xe;e[130]!==p||e[131]!==i?(Xe=i(p?"settings.skills.catalog.shared.actions.scanning":"settings.skills.catalog.shared.actions.scan"),e[130]=p,e[131]=i,e[132]=Xe):Xe=e[132];let ct;e[133]!==Ee||e[134]!==Le||e[135]!==Xe?(ct=s.jsxs(Q,{size:"sm",className:"gap-2",variant:"ghost",onClick:Ee,disabled:Le,children:[_e,Xe]}),e[133]=Ee,e[134]=Le,e[135]=Xe,e[136]=ct):ct=e[136];let ut;e[137]!==J?(ut=()=>{J()},e[137]=J,e[138]=ut):ut=e[138];let lt;e[139]!==C||e[140]!==m||e[141]!==y||e[142]!==h?(lt=!y||C||!m.trim()||!h.trim(),e[139]=C,e[140]=m,e[141]=y,e[142]=h,e[143]=lt):lt=e[143];let rt;e[144]!==i?(rt=i("settings.skills.catalog.add.actions.addCatalog"),e[144]=i,e[145]=rt):rt=e[145];let mt;e[146]!==ut||e[147]!==lt||e[148]!==rt?(mt=s.jsx(Q,{size:"sm",onClick:ut,disabled:lt,children:rt}),e[146]=ut,e[147]=lt,e[148]=rt,e[149]=mt):mt=e[149];let xt;e[150]!==I||e[151]!==ct||e[152]!==mt?(xt=s.jsxs(Zt,{children:[I,ct,mt]}),e[150]=I,e[151]=ct,e[152]=mt,e[153]=xt):xt=e[153];let It;e[154]!==ye||e[155]!==Pe||e[156]!==xt?(It=s.jsxs(Ft,{className:"max-w-xl",children:[ye,Pe,xt]}),e[154]=ye,e[155]=Pe,e[156]=xt,e[157]=It):It=e[157];let Se;return e[158]!==a||e[159]!==n||e[160]!==It?(Se=s.jsx(Lt,{open:n,onOpenChange:a,children:It}),e[158]=a,e[159]=n,e[160]=It,e[161]=Se):Se=e[161],Se};function cb(t){return t.scanRepo}function db(t){return t.loadCatalog}function ub(t){return t.loadSource}function mb(t){return t.setSelectedSource}function pb(t){return t.isScanning}function gb(t){return t.defaultGitIdentityId}function fb(t){return t.loadDefaultGitIdentityId}function hb(t){return s.jsx(yt,{value:t.id,children:t.name},t.id)}const xb=t=>{const e=Ye.c(85),{open:n,onOpenChange:a,conflicts:i,onConfirm:r}=t,{t:o}=it();let d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d={},e[0]=d):d=e[0];const[c,p]=l.useState(d);let u,f;e[1]!==i||e[2]!==n?(u=()=>{if(!n)return;const J={};for(const ee of i)J[ee.skillName]="skip";p(J)},f=[n,i],e[1]=i,e[2]=n,e[3]=u,e[4]=f):(u=e[3],f=e[4]),l.useEffect(u,f);let m;e[5]!==i?(m=J=>{const ee={};for(const ue of i)ee[ue.skillName]=J;p(ee)},e[5]=i,e[6]=m):m=e[6];const b=m;let h;e[7]!==i||e[8]!==c?(h=i.length>0&&i.every(J=>c[J.skillName]),e[7]=i,e[8]=c,e[9]=h):h=e[9];const g=h;let x;e[10]!==o?(x=o("settings.skills.catalog.conflicts.title"),e[10]=o,e[11]=x):x=e[11];let v;e[12]!==x?(v=s.jsx(zt,{children:x}),e[12]=x,e[13]=v):v=e[13];let N;e[14]!==o?(N=o("settings.skills.catalog.conflicts.description"),e[14]=o,e[15]=N):N=e[15];let P;e[16]!==N?(P=s.jsx(qt,{children:N}),e[16]=N,e[17]=P):P=e[17];let F;e[18]!==v||e[19]!==P?(F=s.jsxs(Ut,{children:[v,P]}),e[18]=v,e[19]=P,e[20]=F):F=e[20];let w;e[21]!==i.length||e[22]!==o?(w=o("settings.skills.catalog.conflicts.count",{count:i.length}),e[21]=i.length,e[22]=o,e[23]=w):w=e[23];let j;e[24]!==w?(j=s.jsx("span",{className:"typography-meta text-muted-foreground",children:w}),e[24]=w,e[25]=j):j=e[25];let y;e[26]!==b?(y=()=>b("skip"),e[26]=b,e[27]=y):y=e[27];let R;e[28]!==o?(R=o("settings.skills.catalog.conflicts.actions.skipAll"),e[28]=o,e[29]=R):R=e[29];let _;e[30]!==y||e[31]!==R?(_=s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:y,children:R}),e[30]=y,e[31]=R,e[32]=_):_=e[32];let B;e[33]!==b?(B=()=>b("overwrite"),e[33]=b,e[34]=B):B=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 k;e[37]!==B||e[38]!==D?(k=s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:B,children:D}),e[37]=B,e[38]=D,e[39]=k):k=e[39];let T;e[40]!==_||e[41]!==k?(T=s.jsxs("div",{className:"flex items-center gap-2",children:[_,k]}),e[40]=_,e[41]=k,e[42]=T):T=e[42];let M;e[43]!==j||e[44]!==T?(M=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[j,T]}),e[43]=j,e[44]=T,e[45]=M):M=e[45];let O;if(e[46]!==i||e[47]!==c||e[48]!==o){let J;e[50]!==c||e[51]!==o?(J=ee=>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:ee.skillName}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:o("settings.skills.catalog.conflicts.installedIn",{scope:ee.scope==="project"?o("settings.skills.catalog.conflicts.scope.project"):o("settings.skills.catalog.conflicts.scope.user"),source:ee.source==="agents"?o("settings.skills.catalog.conflicts.source.agents"):o("settings.skills.catalog.conflicts.source.opencode")})})]}),s.jsxs(At,{value:c[ee.skillName]||"skip",onValueChange:ue=>p(re=>({...re,[ee.skillName]:ue})),children:[s.jsx(Et,{className:"w-fit",children:s.jsx("span",{className:"capitalize",children:(c[ee.skillName]||"skip")==="overwrite"?o("settings.skills.catalog.conflicts.decision.overwrite"):o("settings.skills.catalog.conflicts.decision.skip")})}),s.jsxs(Tt,{align:"end",children:[s.jsx(yt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:o("settings.skills.catalog.conflicts.decision.skip")}),s.jsx(yt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:o("settings.skills.catalog.conflicts.decision.overwrite")})]})]})]},ee.skillName),e[50]=c,e[51]=o,e[52]=J):J=e[52],O=i.map(J),e[46]=i,e[47]=c,e[48]=o,e[49]=O}else O=e[49];let V;e[53]!==O?(V=s.jsx("div",{className:"space-y-2",children:O}),e[53]=O,e[54]=V):V=e[54];let U;e[55]!==M||e[56]!==V?(U=s.jsxs("div",{className:"space-y-3",children:[M,V]}),e[55]=M,e[56]=V,e[57]=U):U=e[57];let Y;e[58]!==a?(Y=()=>a(!1),e[58]=a,e[59]=Y):Y=e[59];let X;e[60]!==o?(X=o("settings.common.actions.cancel"),e[60]=o,e[61]=X):X=e[61];let S;e[62]!==Y||e[63]!==X?(S=s.jsx(Q,{size:"sm",variant:"ghost",onClick:Y,children:X}),e[62]=Y,e[63]=X,e[64]=S):S=e[64];let W;e[65]!==c||e[66]!==r?(W=()=>r(c),e[65]=c,e[66]=r,e[67]=W):W=e[67];const Z=!g;let A;e[68]!==o?(A=o("settings.skills.catalog.conflicts.actions.continue"),e[68]=o,e[69]=A):A=e[69];let C;e[70]!==W||e[71]!==Z||e[72]!==A?(C=s.jsx(Q,{size:"sm",onClick:W,disabled:Z,children:A}),e[70]=W,e[71]=Z,e[72]=A,e[73]=C):C=e[73];let z;e[74]!==S||e[75]!==C?(z=s.jsxs(Zt,{children:[S,C]}),e[74]=S,e[75]=C,e[76]=z):z=e[76];let $;e[77]!==F||e[78]!==U||e[79]!==z?($=s.jsxs(Ft,{className:"max-w-2xl",children:[F,U,z]}),e[77]=F,e[78]=U,e[79]=z,e[80]=$):$=e[80];let H;return e[81]!==a||e[82]!==n||e[83]!==$?(H=s.jsx(Lt,{open:n,onOpenChange:a,children:$}),e[81]=a,e[82]=n,e[83]=$,e[84]=H):H=e[84],H},Oo=[{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 ti(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 Jd(t){if(t==="user-claude")return{scope:"user",source:"claude"};if(t==="project-claude")return{scope:"project",source:"claude"};const e=Oo.find(n=>n.value===t);return e?{scope:e.scope,source:e.source}:{scope:"user",source:"opencode"}}const bb=t=>{const e=Ye.c(124),{open:n,onOpenChange:a,item:i}=t,{t:r}=it(),o=jn(yb),d=jn(vb),[c,p]=l.useState("user"),[u,f]=l.useState("opencode"),m=rs(wb),b=rs(jb),[h,g]=l.useState(null),[x,v]=l.useState(!1);let N;e[0]===Symbol.for("react.memo_cache_sentinel")?(N=[],e[0]=N):N=e[0];const[P,F]=l.useState(N),[w,j]=l.useState(null);let y,R;e[1]!==b||e[2]!==n?(y=()=>{n&&(p("user"),f("opencode"),g(b),v(!1),F([]),j(null))},R=[n,b],e[1]=b,e[2]=n,e[3]=y,e[4]=R):(y=e[3],R=e[4]),l.useEffect(y,R);let _;e[5]!==r?(_=Fe=>{switch(Fe){case"project-opencode":return r("settings.skills.location.option.projectOpencode.label");case"user-agents":return r("settings.skills.location.option.userAgents.label");case"project-agents":return r("settings.skills.location.option.projectAgents.label");default:return r("settings.skills.location.option.userOpencode.label")}},e[5]=r,e[6]=_):_=e[6];const B=_;let D;e[7]!==r?(D=Fe=>{switch(Fe){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 k=D;let T;e:{if(m.length===0){T=null;break e}if(h&&m.some(Fe=>Fe.id===h)){T=h;break e}if(b&&m.some(Fe=>Fe.id===b)){T=b;break e}T=m[0]?.id??null}const M=T;let O;e:{if(c!=="project"){O=null;break e}const Fe=M;if(!Fe){O=null;break e}let ve;if(e[9]!==Fe||e[10]!==m){let Ke;e[12]!==Fe?(Ke=We=>We.id===Fe,e[12]=Fe,e[13]=Ke):Ke=e[13],ve=m.find(Ke),e[9]=Fe,e[10]=m,e[11]=ve}else ve=e[11];O=ve?.path??null}const V=O;let U;e[14]!==o||e[15]!==i||e[16]!==a||e[17]!==r?(U=async Fe=>{const ve={skillDir:Fe.skillDir};i?.clawdhub&&(ve.clawdhub={slug:i.clawdhub.slug,version:i.clawdhub.version});const De=await o({source:Fe.source,subpath:Fe.subpath,gitIdentityId:i?.gitIdentityId,scope:Fe.scope,targetSource:Fe.targetSource,selections:[ve],conflictPolicy:"prompt",conflictDecisions:Fe.conflictDecisions},{directory:Fe.directoryOverride??null});if(De.ok){G.success(r("settings.skills.catalog.installSkill.toast.installed")),a(!1);return}if(De.error?.kind==="conflicts"){j({source:Fe.source,subpath:Fe.subpath,scope:Fe.scope,targetSource:Fe.targetSource,skillDir:Fe.skillDir,directoryOverride:Fe.directoryOverride??null}),F(De.error.conflicts),v(!0);return}if(De.error?.kind==="authRequired"){G.error(De.error.message||r("settings.skills.catalog.installSkill.toast.authRequired"));return}G.error(De.error?.message||r("settings.skills.catalog.installSkill.toast.installFailed"))},e[14]=o,e[15]=i,e[16]=a,e[17]=r,e[18]=U):U=e[18];const Y=U;if(!i)return null;let X;e[19]!==r?(X=r("settings.skills.catalog.installSkill.title"),e[19]=r,e[20]=X):X=e[20];let S;e[21]!==X?(S=s.jsx(zt,{children:X}),e[21]=X,e[22]=S):S=e[22];let W;e[23]!==r?(W=r("settings.skills.catalog.installSkill.descriptionPrefix"),e[23]=r,e[24]=W):W=e[24];let Z;e[25]!==i.skillName?(Z=s.jsx("span",{className:"font-semibold text-foreground",children:i.skillName}),e[25]=i.skillName,e[26]=Z):Z=e[26];let A;e[27]!==r?(A=r("settings.skills.catalog.installSkill.descriptionSuffix"),e[27]=r,e[28]=A):A=e[28];let C;e[29]!==W||e[30]!==Z||e[31]!==A?(C=s.jsxs(qt,{children:[W," ",Z," ",A]}),e[29]=W,e[30]=Z,e[31]=A,e[32]=C):C=e[32];let z;e[33]!==S||e[34]!==C?(z=s.jsxs(Ut,{children:[S,C]}),e[33]=S,e[34]=C,e[35]=z):z=e[35];let $;e[36]!==r?($=r("settings.skills.catalog.installSkill.field.destination"),e[36]=r,e[37]=$):$=e[37];let H;e[38]!==$?(H=s.jsx("span",{className:"typography-ui-label text-foreground",children:$}),e[38]=$,e[39]=H):H=e[39];let J;e[40]!==c||e[41]!==u?(J=ti(c,u),e[40]=c,e[41]=u,e[42]=J):J=e[42];let ee;e[43]===Symbol.for("react.memo_cache_sentinel")?(ee=Fe=>{const ve=Jd(Fe);p(ve.scope),f(ve.source==="agents"?"agents":"opencode")},e[43]=ee):ee=e[43];let ue;e[44]!==c?(ue=c==="user"?s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"}),e[44]=c,e[45]=ue):ue=e[45];let re;e[46]!==u?(re=u==="agents"?s.jsx(L,{name:"robot-2",className:"h-3.5 w-3.5"}):null,e[46]=u,e[47]=re):re=e[47];let xe;e[48]!==B||e[49]!==c||e[50]!==u?(xe=B(ti(c,u)),e[48]=B,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 he;e[54]!==ue||e[55]!==re||e[56]!==be?(he=s.jsxs(Et,{className:"w-fit gap-1.5",children:[ue,re,be]}),e[54]=ue,e[55]=re,e[56]=be,e[57]=he):he=e[57];let ye;e[58]!==k||e[59]!==B?(ye=Oo.map(Fe=>s.jsx(yt,{value:Fe.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:[Fe.scope==="user"?s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"}),Fe.source==="agents"?s.jsx(L,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:B(Fe.value)})]}),s.jsx("span",{className:"typography-micro text-muted-foreground ml-5",children:k(Fe.value)})]})},Fe.value)),e[58]=k,e[59]=B,e[60]=ye):ye=e[60];let fe;e[61]!==ye?(fe=s.jsx(Tt,{align:"start",children:ye}),e[61]=ye,e[62]=fe):fe=e[62];let ae;e[63]!==J||e[64]!==he||e[65]!==fe?(ae=s.jsxs(At,{value:J,onValueChange:ee,children:[he,fe]}),e[63]=J,e[64]=he,e[65]=fe,e[66]=ae):ae=e[66];let ce;e[67]!==H||e[68]!==ae?(ce=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[H,ae]}),e[67]=H,e[68]=ae,e[69]=ce):ce=e[69];let pe;e[70]!==m||e[71]!==M||e[72]!==c||e[73]!==r?(pe=c==="project"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:r("settings.skills.catalog.installSkill.field.project")}),m.length===0?s.jsx("span",{className:"typography-meta text-muted-foreground",children:r("settings.skills.catalog.installSkill.field.noProjects")}):s.jsxs(At,{value:M??"",onValueChange:Fe=>g(Fe),disabled:m.length===1,children:[s.jsx(Et,{className:"w-fit",children:s.jsx(Vt,{placeholder:r("settings.skills.catalog.installSkill.field.chooseProjectPlaceholder")})}),s.jsx(Tt,{align:"start",children:m.map(kb)})]})]}),e[70]=m,e[71]=M,e[72]=c,e[73]=r,e[74]=pe):pe=e[74];let q;e[75]!==i.warnings?(q=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]=q):q=e[76];let te;e[77]!==ce||e[78]!==pe||e[79]!==q?(te=s.jsxs("div",{className:"mt-2 space-y-3",children:[ce,pe,q]}),e[77]=ce,e[78]=pe,e[79]=q,e[80]=te):te=e[80];let ne;e[81]!==a?(ne=()=>a(!1),e[81]=a,e[82]=ne):ne=e[82];let oe;e[83]!==r?(oe=r("settings.common.actions.cancel"),e[83]=r,e[84]=oe):oe=e[84];let Ae;e[85]!==ne||e[86]!==oe?(Ae=s.jsx(Q,{size:"sm",variant:"ghost",onClick:ne,children:oe}),e[85]=ne,e[86]=oe,e[87]=Ae):Ae=e[87];const je=d||!i.installable||c==="project"&&!V;let Ie;e[88]!==V||e[89]!==Y||e[90]!==i.repoSource||e[91]!==i.repoSubpath||e[92]!==i.skillDir||e[93]!==c||e[94]!==u?(Ie=()=>{Y({source:i.repoSource,subpath:i.repoSubpath,scope:c,targetSource:u,skillDir:i.skillDir,directoryOverride:V})},e[88]=V,e[89]=Y,e[90]=i.repoSource,e[91]=i.repoSubpath,e[92]=i.skillDir,e[93]=c,e[94]=u,e[95]=Ie):Ie=e[95];let Te;e[96]!==d||e[97]!==r?(Te=r(d?"settings.skills.catalog.installSkill.actions.installing":"settings.skills.catalog.installSkill.actions.install"),e[96]=d,e[97]=r,e[98]=Te):Te=e[98];let Me;e[99]!==je||e[100]!==Ie||e[101]!==Te?(Me=s.jsx(Q,{size:"sm",disabled:je,onClick:Ie,children:Te}),e[99]=je,e[100]=Ie,e[101]=Te,e[102]=Me):Me=e[102];let He;e[103]!==Ae||e[104]!==Me?(He=s.jsxs(Zt,{children:[Ae,Me]}),e[103]=Ae,e[104]=Me,e[105]=He):He=e[105];let Ve;e[106]!==z||e[107]!==te||e[108]!==He?(Ve=s.jsxs(Ft,{className:"max-w-md",children:[z,te,He]}),e[106]=z,e[107]=te,e[108]=He,e[109]=Ve):Ve=e[109];let Ue;e[110]!==a||e[111]!==n||e[112]!==Ve?(Ue=s.jsx(Lt,{open:n,onOpenChange:a,children:Ve}),e[110]=a,e[111]=n,e[112]=Ve,e[113]=Ue):Ue=e[113];let ze;e[114]!==w||e[115]!==Y?(ze=Fe=>{w&&(Y({source:w.source,subpath:w.subpath,scope:w.scope,targetSource:w.targetSource,skillDir:w.skillDir,conflictDecisions:Fe,directoryOverride:w.directoryOverride??null}),v(!1))},e[114]=w,e[115]=Y,e[116]=ze):ze=e[116];let Be;e[117]!==P||e[118]!==x||e[119]!==ze?(Be=s.jsx(xb,{open:x,onOpenChange:v,conflicts:P,onConfirm:ze}),e[117]=P,e[118]=x,e[119]=ze,e[120]=Be):Be=e[120];let Ge;return e[121]!==Ue||e[122]!==Be?(Ge=s.jsxs(s.Fragment,{children:[Ue,Be]}),e[121]=Ue,e[122]=Be,e[123]=Ge):Ge=e[123],Ge};function yb(t){return t.installSkills}function vb(t){return t.isInstalling}function wb(t){return t.projects}function jb(t){return t.activeProjectId}function kb(t){return s.jsx(yt,{value:t.id,children:t.label||t.path},t.id)}const Nb=async()=>{try{const t=ln()?.settings;if(t)return(await t.load())?.settings||{};const e=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return e.ok?await e.json().catch(()=>null):null}catch{return null}},Sb=({mode:t,onModeChange:e,showModeTabs:n=!0})=>{const{t:a}=it(),{sources:i,itemsBySource:r,selectedSourceId:o,setSelectedSource:d,loadCatalog:c,loadSource:p,loadMoreClawdHub:u,isLoadingCatalog:f,isLoadingSource:m,isLoadingMore:b,loadedSourceIds:h,clawdhubHasMoreBySource:g,lastCatalogError:x}=jn(zs(S=>({sources:S.sources,itemsBySource:S.itemsBySource,selectedSourceId:S.selectedSourceId,setSelectedSource:S.setSelectedSource,loadCatalog:S.loadCatalog,loadSource:S.loadSource,loadMoreClawdHub:S.loadMoreClawdHub,isLoadingCatalog:S.isLoadingCatalog,isLoadingSource:S.isLoadingSource,isLoadingMore:S.isLoadingMore,loadedSourceIds:S.loadedSourceIds,clawdhubHasMoreBySource:S.clawdhubHasMoreBySource,lastCatalogError:S.lastCatalogError}))),[v,N]=l.useState(""),[P,F]=l.useState(!1),[w,j]=l.useState(!1),[y,R]=l.useState(null),[_,B]=l.useState(!1),[D,k]=l.useState(!1);l.useEffect(()=>{c()},[c]),l.useEffect(()=>{o&&(h[o]||p(o))},[o,h,p]);const T=l.useMemo(()=>o?r[o]||[]:[],[r,o]),M=l.useMemo(()=>{const S=v.trim().toLowerCase();return S?T.filter(W=>{const Z=W.skillName.toLowerCase(),A=(W.description||"").toLowerCase(),C=(W.frontmatterName||"").toLowerCase();return Z.includes(S)||A.includes(S)||C.includes(S)}):T},[T,v]),O=l.useMemo(()=>i.find(S=>S.id===o)||null,[i,o]),V=!!(o&&o.startsWith("custom:")),U=O?.source==="clawdhub:registry"||O?.sourceType==="clawdhub",Y=!!(o&&(g[o]??!0)),X=async()=>{if(!(!o||!V)){B(!0);try{const S=await Nb(),Z=(Array.isArray(S?.skillCatalogs)?S?.skillCatalogs:[]).filter(A=>A.id!==o);await kt({skillCatalogs:Z}),await c({refresh:!0}),k(!1)}finally{B(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsxs(us,{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(ia,{items:[{id:"manual",label:a("settings.skills.catalog.page.mode.manual")},{id:"external",label:a("settings.skills.catalog.page.mode.external")}],activeId:t,onSelect:S=>e(S),layoutMode:"fit",variant:"animated",animateActivePill:!1,className:"h-full"})})}),s.jsxs(ot,{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(At,{value:o||"",onValueChange:S=>d(S),children:[s.jsx(Et,{size:Gt,className:le(yn,"w-fit"),children:s.jsx(Vt,{placeholder:a("settings.skills.catalog.page.field.selectSourcePlaceholder"),children:O?.label})}),s.jsx(Tt,{align:"start",children:i.map(S=>s.jsx(yt,{value:S.id,children:S.label},S.id))})]}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal h-6 w-6 px-0",onClick:()=>{o?p(o,{refresh:!0}):c({refresh:!0})},disabled:f||m,title:a("settings.skills.catalog.page.actions.refreshTitle"),children:s.jsx(L,{name:"refresh",className:le("h-3.5 w-3.5",(f||m)&&"animate-spin")})}),V&&s.jsx(Q,{variant:"ghost",size:"xs",className:"!font-normal h-6 w-6 px-0 text-[var(--status-error)] hover:text-[var(--status-error)]",onClick:()=>k(!0),disabled:_,title:a("settings.skills.catalog.page.actions.removeCatalogTitle"),children:s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"})}),s.jsxs(Q,{"data-settings-item":"skills.catalog.add-catalog",size:"xs",className:"!font-normal gap-1",onClick:()=>F(!0),children:[s.jsx(L,{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(L,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),s.jsx(tt,{value:v,onChange:S=>N(S.target.value),placeholder:a("settings.skills.catalog.shared.field.searchSkillsPlaceholder"),className:"h-7 pl-8 w-full sm:w-64"})]}),s.jsx("span",{className:"typography-meta text-muted-foreground mt-1 block",children:f?a("settings.skills.catalog.page.loading.catalog"):a("settings.skills.catalog.page.foundCount",{count:M.length})})]})]}),x&&s.jsx(ot,{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(ot,{children:[M.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(L,{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:M.map(S=>{const W=S.installed?.isInstalled,Z=S.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:S.skillName}),W&&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:Z||a("settings.skills.catalog.page.badge.unknown")})}),!S.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")})]}),S.description?s.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:S.description}):s.jsx("div",{className:"typography-meta text-muted-foreground/50 mt-0.5 italic",children:a("settings.skills.catalog.shared.noDescription")}),S.clawdhub&&s.jsxs("div",{className:"typography-micro text-muted-foreground mt-1.5 flex items-center gap-3",children:[S.clawdhub.owner&&s.jsxs("span",{children:[a("settings.skills.catalog.page.byOwnerPrefix")," ",s.jsx("span",{className:"font-medium text-foreground/80",children:S.clawdhub.owner})]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(L,{name:"download",className:"h-3 w-3"}),S.clawdhub.downloads?.toLocaleString()??0]}),(S.clawdhub.stars??0)>0&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(L,{name:"star",className:"h-3 w-3"}),S.clawdhub.stars]}),s.jsxs("span",{className:"bg-[var(--surface-muted)] px-1.5 py-0.5 rounded",children:["v",S.clawdhub.version]})]}),S.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:S.warnings.join(" · ")}):null]}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal shrink-0",disabled:!S.installable,onClick:()=>{R(S),j(!0)},children:a("settings.skills.catalog.shared.actions.install")})]})},`${S.sourceId}:${S.skillDir}`)})}),U&&Y&&!m&&M.length>0&&s.jsx("div",{className:"flex justify-center mt-2",children:s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{u()},disabled:b,children:a(b?"settings.skills.catalog.page.loading.more":"settings.skills.catalog.page.actions.loadMoreSkills")})})]})]}),s.jsx(lb,{open:P,onOpenChange:F}),s.jsx(bb,{open:w,onOpenChange:j,item:y}),s.jsx(Lt,{open:D,onOpenChange:S=>{_||k(S)},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:a("settings.skills.catalog.page.removeDialog.title")}),s.jsx(qt,{children:a("settings.skills.catalog.page.removeDialog.description")})]}),s.jsxs(Zt,{children:[s.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>k(!1),disabled:_,children:a("settings.common.actions.cancel")}),s.jsx(Q,{size:"sm",variant:"destructive",onClick:()=>{X()},disabled:_,children:a("settings.skills.catalog.page.actions.removeCatalog")})]})]})})]})};function pc(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=nn.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=Jo.define([{tag:[Re.comment,Re.docComment,Re.meta,Re.documentMeta],class:"cm-comment"},{tag:[Re.keyword,Re.controlKeyword,Re.moduleKeyword,Re.definitionKeyword,Re.modifier],class:"cm-keyword"},{tag:[Re.operatorKeyword,Re.operator,Re.derefOperator,Re.updateOperator,Re.definitionOperator,Re.typeOperator,Re.controlOperator,Re.logicOperator,Re.bitwiseOperator,Re.arithmeticOperator,Re.compareOperator],class:"cm-operator"},{tag:[Re.punctuation,Re.separator,Re.bracket,Re.paren,Re.brace,Re.squareBracket,Re.angleBracket],class:"cm-punctuation"},{tag:[Re.string,Re.regexp,Re.attributeValue,Re.special(Re.string),Re.monospace],class:"cm-string"},{tag:Re.escape,class:"cm-string-2"},{tag:[Re.number,Re.bool,Re.atom,Re.null,Re.self],class:"cm-number"},{tag:[Re.function(Re.variableName),Re.function(Re.definition(Re.variableName)),Re.function(Re.propertyName),Re.standard(Re.variableName),Re.special(Re.variableName)],class:"cm-builtin"},{tag:Re.definition(Re.variableName),class:"cm-def"},{tag:[Re.variableName,Re.local(Re.variableName),Re.constant(Re.variableName),Re.literal],class:"cm-variable"},{tag:Re.propertyName,class:"cm-property"},{tag:Re.attributeName,class:"cm-attribute"},{tag:[Re.className,Re.typeName,Re.namespace],class:"cm-variable-3"},{tag:[Re.tagName,Re.labelName,Re.annotation,Re.macroName],class:"cm-tag"},{tag:Re.link,class:"cm-link"},{tag:[Re.heading,Re.heading1,Re.heading2,Re.heading3,Re.heading4,Re.heading5,Re.heading6],class:"cm-keyword"}]),p=Jo.define([{tag:[Re.comment,Re.docComment,Re.meta,Re.documentMeta],color:t.colors.syntax.base.comment},{tag:[Re.keyword,Re.controlKeyword,Re.moduleKeyword,Re.definitionKeyword,Re.modifier],color:t.colors.syntax.base.keyword},{tag:[Re.operatorKeyword,Re.operator,Re.derefOperator,Re.updateOperator,Re.definitionOperator,Re.typeOperator,Re.controlOperator,Re.logicOperator,Re.bitwiseOperator,Re.arithmeticOperator,Re.compareOperator],color:t.colors.syntax.base.operator},{tag:[Re.string,Re.regexp,Re.attributeValue,Re.special(Re.string),Re.monospace],color:t.colors.syntax.base.string},{tag:Re.escape,color:r.stringEscape||t.colors.syntax.base.string},{tag:[Re.number,Re.bool,Re.atom,Re.null,Re.self],color:t.colors.syntax.base.number},{tag:[Re.function(Re.variableName),Re.function(Re.definition(Re.variableName)),Re.function(Re.propertyName),Re.standard(Re.variableName),Re.special(Re.variableName)],color:t.colors.syntax.base.function},{tag:Re.definition(Re.variableName),color:r.variableGlobal||t.colors.syntax.base.variable},{tag:[Re.variableName,Re.local(Re.variableName),Re.constant(Re.variableName),Re.literal],color:t.colors.syntax.base.variable},{tag:Re.propertyName,color:r.variableProperty||t.colors.syntax.base.variable},{tag:Re.attributeName,color:r.variableOther||t.colors.syntax.base.variable},{tag:[Re.className,Re.typeName,Re.namespace],color:t.colors.syntax.base.type},{tag:[Re.tagName,Re.labelName,Re.annotation,Re.macroName],color:r.tag||t.colors.syntax.base.keyword},{tag:Re.link,color:r.url||t.colors.syntax.base.function,textDecoration:"underline"},{tag:[Re.punctuation,Re.separator,Re.bracket,Re.paren,Re.brace,Re.squareBracket,Re.angleBracket],color:r.punctuation||t.colors.syntax.base.comment}]);return e?.syntaxColors===!1?[d]:[d,vi(jm,{fallback:!0}),vi(km),vi(c),vi(p)]}const Cb=180,Qd=Nm.define(),Ib=1,Pb=2,Ab=4,gc=new Map,Eb=(t,e)=>{const n=`${t}|${e}`,a=gc.get(n);if(a)return a;let i="";t&&(i+=`color:${t};`),e&Ib&&(i+="font-style:italic;"),e&Pb&&(i+="font-weight:bold;"),e&Ab&&(i+="text-decoration:underline;");const r=nr.mark({attributes:{style:i}});return gc.set(n,r),r},Tb=(t,e)=>{const n=new Ro,a=t.state.doc,i=Math.min(e.length,a.lines);for(let r=0;r<i;r+=1){const o=e[r];if(!o||o.length===0)continue;const d=a.line(r+1);let c=d.from;for(const[p,u,f]of o){if(p<=0)continue;const m=c,b=Math.min(c+p,d.to);c+=p,!(b<=m)&&(!u&&!f||n.add(m,b,Eb(u,f)))}}return n.finish()},Rb=xd.define({create(){return nr.none},update(t,e){let n=t.map(e.changes);for(const a of e.effects)a.is(Qd)&&(n=a.value);return n},provide:t=>nn.decorations.from(t)}),Db=t=>hd.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)},Cb)}async tokenize(e){const n=++this.generation,a=e.state.doc.toString(),i=await ip(a,t.language,t.themeName,t.theme);i&&n===this.generation&&e.state.doc.length===a.length&&e.dispatch({effects:Qd.of(Tb(e,i))})}destroy(){this.timer&&clearTimeout(this.timer)}}),Mb=t=>[Rb,Db(t)],Lb=()=>{const t=Ye.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(Sb,{mode:"external",onModeChange:Ub,showModeTabs:!1}),t[0]=e):e=t[0],e},Fb="SKILL.md",Ob="h-[clamp(320px,58dvh,680px)] min-h-[260px] max-h-[calc(100dvh-220px)]",Wi=(t,e)=>{const n=Sm({description:t}).trimEnd(),a=e.trimStart();return`---
|
|
23
|
+
${n}
|
|
24
|
+
---${a?`
|
|
25
|
+
|
|
26
|
+
${a}`:`
|
|
27
|
+
`}`},zb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Yd=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=Cm(e[1]);if(zb(a)){const i=a.description;typeof i=="string"&&(n=i)}}catch{n=null}return{description:n,instructions:e[2].replace(/^\r?\n/,"")}},Bb=(t,e)=>{const n=Yd(t);return Wi(e,n.instructions)},Kb=()=>{const{t}=it(),{currentTheme:e}=oi(),{selectedSkillName:n,getSkillByName:a,getSkillDetail:i,createSkill:r,updateSkill:o,skills:d,skillDraft:c,setSkillDraft:p,setSelectedSkill:u}=Nn(zs(ve=>({selectedSkillName:ve.selectedSkillName,getSkillByName:ve.getSkillByName,getSkillDetail:ve.getSkillDetail,createSkill:ve.createSkill,updateSkill:ve.updateSkill,skills:ve.skills,skillDraft:ve.skillDraft,setSkillDraft:ve.setSkillDraft,setSelectedSkill:ve.setSelectedSkill}))),f=n?a(n):null,m=!!(c&&c.name===n&&!f),b=!!(n&&!f&&!c),h=f?.path==="<built-in>";l.useEffect(()=>{b&&u(null)},[b,u]);const[g,x]=l.useState(""),[v,N]=l.useState("user"),[P,F]=l.useState("opencode"),[w,j]=l.useState(""),[y,R]=l.useState(""),[_,B]=l.useState(()=>Wi("","")),[D,k]=l.useState("edit"),[T,M]=l.useState([]),[O,V]=l.useState([]),[U,Y]=l.useState(!1),[X,S]=l.useState(!1),[W,Z]=l.useState(""),[A,C]=l.useState(""),[z,$]=l.useState(!1),[H,J]=l.useState(""),[ee,ue]=l.useState(""),[re,xe]=l.useState(null),[be,he]=l.useState(!1),[ye,fe]=l.useState(""),[ae,ce]=l.useState(null),[pe,q]=l.useState(!1),te=m?g.trim()!==""||w.trim()!==""||y.trim()!==""||O.length>0:w!==W||y!==A,ne=re?ee!==ye:H.trim()!=="",oe=l.useCallback(ve=>{switch(ve){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]),Ae=l.useCallback(ve=>{switch(ve){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 De=c.description||"",Ke=c.instructions||"";x(c.name||""),N(c.scope||"user"),F(c.source==="agents"?"agents":"opencode"),j(De),R(Ke),B(Wi(De,Ke)),Z(""),C(""),M([]),V(c.pendingFiles||[])}else if(n&&f){S(!0);try{const De=await i(n);if(De){const Ke=De.sources.md,We=Ke.description||"",Pe=Ke.instructions||"";j(We),R(Pe),B(Wi(We,Pe)),Z(We),C(Pe),M(Ke.supportingFiles||[])}}catch(De){console.error("Failed to load skill details:",De)}finally{S(!1)}}})()},[f,m,n,d,c,i]);const je=Ne(ve=>ve.editorFontSize),Ie=l.useMemo(()=>{const ve=[pc(e,{fontSize:je})],De=Zo(Fb);return De&&ve.push(De),ve.push(nn.lineWrapping),ve},[e,je]),Te=l.useMemo(()=>{const ve=H.trim()||"supporting-file.md",De=rp(ve),Ke=!!De&&De!=="markdown",We=[pc(e,Ke?{syntaxColors:!1,fontSize:je}:{fontSize:je})],Pe=Zo(ve);return Pe&&We.push(Pe),Ke&&De&&We.push(Mb({language:De,themeName:e.metadata.id,theme:co(e)})),We.push(nn.lineWrapping),We},[e,H,je]),Me=l.useCallback(ve=>{j(ve),B(De=>Bb(De,ve))},[]),He=l.useCallback(ve=>{B(ve);const De=Yd(ve);j(De.description??""),R(De.instructions)},[]),Ve=async()=>{const ve=m?g.trim().replace(/\s+/g,"-").toLowerCase():n?.trim();if(!ve){G.error(t("settings.skills.page.toast.skillNameRequired"));return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(ve)||ve.length>64){G.error(t("settings.skills.page.toast.invalidSkillName"));return}if(!w.trim()){G.error(t("settings.skills.page.toast.descriptionRequired"));return}if(m&&d.some(De=>De.name===ve)){G.error(t("settings.skills.page.toast.skillExists"));return}Y(!0);try{const De={name:ve,description:w.trim(),instructions:y.trim()||void 0,scope:m?v:void 0,source:m?P:void 0,targetPath:m?void 0:f?.path,supportingFiles:m&&O.length>0?O:void 0};let Ke;m?(Ke=await r(De),Ke&&(p(null),V([]),u(ve))):(Ke=await o(ve,De),Ke&&(Z(w.trim()),C(y.trim()))),Ke?G.success(t(m?"settings.skills.page.toast.skillCreated":"settings.skills.page.toast.skillUpdated")):G.error(t(m?"settings.skills.page.toast.createSkillFailed":"settings.skills.page.toast.updateSkillFailed"))}catch(De){console.error("Error saving skill:",De),G.error(t("settings.skills.page.toast.saveUnexpectedError"))}finally{Y(!1)}},Ue=()=>{xe(null),J(""),ue(""),fe(""),$(!0)},ze=async ve=>{if(xe(ve),J(ve),m){const Ke=O.find(We=>We.path===ve)?.content||"";ue(Ke),fe(Ke),$(!0);return}if(n){he(!0),$(!0);try{const{readSupportingFile:De}=Nn.getState(),Ke=await De(n,ve);ue(Ke||""),fe(Ke||"")}catch{G.error(t("settings.skills.page.toast.loadFileContentFailed")),ue(""),fe("")}finally{he(!1)}}},Be=async()=>{if(!H.trim()){G.error(t("settings.skills.page.toast.fileNameRequired"));return}const ve=H.trim(),De=re!==null;if(m){if(De)V(Pe=>Pe.map(at=>at.path===re?{path:ve,content:ee}:at)),G.success(t("settings.skills.page.toast.fileUpdated",{path:ve}));else{if(O.some(Pe=>Pe.path===ve)){G.error(t("settings.skills.page.toast.fileExists"));return}V(Pe=>[...Pe,{path:ve,content:ee}]),G.success(t("settings.skills.page.toast.fileAdded",{path:ve}))}$(!1),xe(null);return}if(!n){G.error(t("settings.skills.page.toast.noSkillSelected"));return}const{writeSupportingFile:Ke}=Nn.getState();if(await Ke(n,ve,ee)){G.success(De?t("settings.skills.page.toast.fileUpdated",{path:ve}):t("settings.skills.page.toast.fileCreated",{path:ve})),$(!1),xe(null);const Pe=await i(n);Pe&&M(Pe.sources.md.supportingFiles||[])}else G.error(t(De?"settings.skills.page.toast.updateFileFailed":"settings.skills.page.toast.createFileFailed"))},Ge=ve=>{if(m){V(De=>De.filter(Ke=>Ke.path!==ve)),G.success(t("settings.skills.page.toast.fileRemoved",{path:ve}));return}n&&ce(ve)},Fe=async()=>{if(!ae||!n)return;q(!0);const{deleteSupportingFile:ve}=Nn.getState();if(await ve(n,ae)){G.success(t("settings.skills.page.toast.fileDeleted",{path:ae}));const Ke=await i(n);Ke&&M(Ke.sources.md.supportingFiles||[]),ce(null)}else G.error(t("settings.skills.page.toast.deleteFileFailed"));q(!1)};return!n&&!c||b?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(L,{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")})]})}):X?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(us,{title:m?t("settings.skills.page.title.newSkill"):n,description:f?t("settings.skills.page.subtitle.skillLocation",{location:oe(ti(f.scope,f.source))}):t("settings.skills.page.subtitle.newSkill"),showSaveStatus:!1,children:[s.jsxs(ot,{title:t("settings.skills.page.section.basicInformation"),divider:!1,settingsItem:"skills.basic-information",contentClassName:"space-y-0",children:[m&&s.jsxs(Jt,{label:t("settings.skills.page.field.skillNameLocation"),info:t("settings.skills.page.field.skillNameHint"),children:[s.jsx(tt,{value:g,onChange:ve=>x(ve.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:t("settings.skills.page.field.skillNamePlaceholder"),className:"h-7 w-40 px-2"}),s.jsxs(At,{value:ti(v,P),onValueChange:ve=>{const De=Jd(ve);N(De.scope),F(De.source==="agents"?"agents":"opencode")},children:[s.jsxs(Et,{size:Gt,className:"w-fit gap-1.5",children:[v==="user"?s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"}),P==="agents"?s.jsx(L,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:oe(ti(v,P))})]}),s.jsx(Tt,{align:"start",children:Oo.map(ve=>s.jsx(yt,{value:ve.value,children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[ve.scope==="user"?s.jsx(L,{name:"user-3",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"folder",className:"h-3.5 w-3.5"}),ve.source==="agents"?s.jsx(L,{name:"robot-2",className:"h-3.5 w-3.5"}):null,s.jsx("span",{children:oe(ve.value)})]}),s.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:Ae(ve.value)})]})},ve.value))})]})]}),s.jsx(ls,{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(js,{value:w,onChange:ve=>Me(ve.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(ot,{title:t("settings.skills.page.section.instructions"),headerAction:s.jsx(ab,{currentMode:D==="preview"?"preview":"edit",onToggle:()=>k(ve=>ve==="preview"?"edit":"preview")}),settingsItem:"skills.instructions",children:s.jsx("div",{className:le("overflow-hidden rounded-md border border-[var(--surface-subtle)] bg-background",Ob),children:D==="preview"?s.jsx(Bs,{outerClassName:"h-full",className:"h-full",children:s.jsx("div",{className:"min-h-full px-4 py-3",children:s.jsx(oo,{content:_,className:"typography-markdown-body",stripFrontmatter:!0,enableFileReferences:!1})})}):s.jsx(mc,{value:_,onChange:He,readOnly:h,extensions:Ie,className:"h-full",enableSearch:!0})})}),s.jsx(ot,{title:t("settings.skills.page.section.supportingFiles"),headerAction:s.jsxs(Q,{variant:"outline",size:"xs",className:"!font-normal gap-1",onClick:Ue,disabled:h,children:[s.jsx(L,{name:"add",className:"h-3.5 w-3.5"})," ",t("settings.skills.page.actions.addFile")]}),settingsItem:"skills.supporting-files",children:(()=>{const ve=m?O:T;return ve.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:ve.map(De=>s.jsxs("div",{className:"flex items-center gap-2 py-1.5 cursor-pointer group",onClick:()=>ze(De.path),children:[s.jsx(L,{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:De.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(Q,{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(),Ge(De.path)},children:s.jsx(L,{name:"delete-bin",className:"h-3 w-3"})})]},De.path))})})()}),s.jsx(ot,{children:s.jsx(Q,{onClick:Ve,disabled:h||U||!te,size:"xs",className:"!font-normal",children:t(U?"settings.common.actions.saving":m?"settings.skills.page.actions.createSkill":"settings.common.actions.saveChanges")})})]}),s.jsx(Lt,{open:ae!==null,onOpenChange:ve=>{!ve&&!pe&&ce(null)},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.skills.page.deleteFileDialog.title")}),s.jsx(qt,{children:t("settings.skills.page.deleteFileDialog.description",{path:ae??""})})]}),s.jsxs(Zt,{children:[s.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>ce(null),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(Q,{size:"sm",variant:"destructive",onClick:Fe,disabled:pe,children:t("settings.common.actions.delete")})]})]})}),s.jsx(Lt,{open:z,onOpenChange:ve=>{$(ve),ve||xe(null)},children:s.jsxs(Ft,{className:"max-w-3xl max-h-[85vh] flex flex-col",children:[s.jsxs(Ut,{className:"flex-shrink-0",children:[s.jsx(zt,{children:t(re?"settings.skills.page.fileDialog.titleEdit":"settings.skills.page.fileDialog.titleAdd")}),s.jsx(qt,{children:t(re?"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:Kt,children:t("settings.skills.page.fileDialog.field.filePath")}),!re&&s.jsx(Ht,{children:t("settings.skills.page.fileDialog.field.filePathHint")})]}),s.jsx(tt,{value:H,onChange:ve=>J(ve.target.value),placeholder:t("settings.skills.page.fileDialog.field.filePathPlaceholder"),className:"text-foreground placeholder:text-muted-foreground focus-visible:ring-[var(--primary-base)]",disabled:re!==null})]}),s.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[s.jsx("label",{className:`${Kt} 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(mc,{value:ee,onChange:ue,extensions:Te,className:"h-full",enableSearch:!0})})]})]}),s.jsxs(Zt,{className:"mt-4",children:[s.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>{$(!1),xe(null)},children:t("settings.common.actions.cancel")}),s.jsx(Q,{size:"sm",onClick:Be,disabled:be||!ne,children:t(re?"settings.common.actions.saveChanges":"settings.skills.page.actions.createFile")})]})]})})]})},fc=t=>{const e=Ye.c(2),{view:n}=t,a=n===void 0?"installed":n;let i;return e[0]!==a?(i=a==="catalog"?s.jsx(Lb,{}):s.jsx(Kb,{}),e[0]=a,e[1]=i):i=e[1],i};function Ub(){}const _b=t=>{const e=Ye.c(38),{onItemSelect:n}=t,{t:a}=it(),i=rs($b),r=Ne(Vb),o=Ne(Hb),{currentTheme:d}=oi();let c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c=os(),e[0]=c):c=e[0];const p=c,u=Wb;let f,m;e[1]!==i||e[2]!==r||e[3]!==o?(f=()=>{if(i.length===0){r!==null&&o(null);return}r&&i.some(y=>y.id===r)||o(i[0].id)},m=[i,r,o],e[1]=i,e[2]=r,e[3]=o,e[4]=f,e[5]=m):(f=e[4],m=e[5]),l.useEffect(f,m);let b;e[6]===Symbol.for("react.memo_cache_sentinel")?(b=le("border-b px-3","pt-4 pb-3"),e[6]=b):b=e[6];let h;e[7]!==a?(h=a("settings.page.projects.title"),e[7]=a,e[8]=h):h=e[8];let g;e[9]!==h?(g=s.jsx("h2",{className:`${dn} mb-3`,children:h}),e[9]=h,e[10]=g):g=e[10];let x;e[11]!==i.length||e[12]!==a?(x=a("settings.projects.sidebar.total",{count:i.length}),e[11]=i.length,e[12]=a,e[13]=x):x=e[13];let v;e[14]!==x?(v=s.jsx("span",{className:"typography-meta text-muted-foreground",children:x}),e[14]=x,e[15]=v):v=e[15];let N;e[16]!==a?(N=!p&&s.jsx(Q,{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(L,{name:"add",className:"size-4"})}),e[16]=a,e[17]=N):N=e[17];let P;e[18]!==v||e[19]!==N?(P=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[v,N]}),e[18]=v,e[19]=N,e[20]=P):P=e[20];let F;e[21]!==P||e[22]!==g?(F=s.jsxs("div",{className:b,children:[g,P]}),e[21]=P,e[22]=g,e[23]=F):F=e[23];let w;if(e[24]!==d||e[25]!==n||e[26]!==i||e[27]!==r||e[28]!==o){let y;e[30]!==d||e[31]!==n||e[32]!==r||e[33]!==o?(y=R=>{const _=R.id===r,B=R.icon?op[R.icon]:null,D=R.color?Nd[R.color]??null:null,k=B?s.jsx(L,{name:B,className:le("h-4 w-4",_?"text-foreground":"text-muted-foreground/70"),style:D?{color:D}:void 0}):s.jsx(L,{name:"folder",className:le("h-4 w-4",_?"text-foreground":"text-muted-foreground/70"),style:D?{color:D}:void 0}),T=R.iconImage?s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:R.iconBackground?{backgroundColor:R.iconBackground}:void 0,children:s.jsx(Sd,{project:R,options:{themeVariant:d.metadata.variant,iconColor:d.colors.surface.foreground},className:"h-full w-full object-contain",fallback:k})}):k;return s.jsx(No,{title:R.label||R.path,icon:T,selected:_,onSelect:()=>{o(R.id),n?.()}},R.id)},e[30]=d,e[31]=n,e[32]=r,e[33]=o,e[34]=y):y=e[34],w=i.map(y),e[24]=d,e[25]=n,e[26]=i,e[27]=r,e[28]=o,e[29]=w}else w=e[29];let j;return e[35]!==F||e[36]!==w?(j=s.jsx(Gd,{variant:"background",header:F,children:w}),e[35]=F,e[36]=w,e[37]=j):j=e[37],j};function $b(t){return t.projects}function Vb(t){return t.settingsProjectsSelectedId}function Hb(t){return t.setSettingsProjectsSelectedId}function Wb(){kd.requestDirectoryDialog()}const ai=Ws,Cn=t=>{const e=Ye.c(11),{title:n,description:a,info:i,settingsItem:r,titleAccessory:o,headerAction:d,children:c,className:p,contentClassName:u,divider:f}=t,m=f===void 0?!0:f;let b;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?(b=s.jsx(ot,{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]=b):b=e[10],b},Gb=450,qb=({projectRef:t=null,sections:e="all"})=>{const{t:n}=it(),{isMobile:a,isTablet:i}=_s(),r=a||i,o=rs(A=>A.getActiveProject()),d=t?.path??o?.path??null,c=ds(A=>A.getWorktreeMetadata),p=lp(),u=Ls(A=>A.homeDirectory),[f,m]=l.useState([]),[b,h]=l.useState(!1),[g,x]=l.useState(!1),[v,N]=l.useState(null),[P,F]=l.useState(null),[w,j]=l.useState([]),[y,R]=l.useState(!1),_=l.useRef(!1),B=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(!(!B||P===!1))try{const A=await el(B);j(A)}catch{}},[B,P]);l.useEffect(()=>{if(!d)return;let A=!1;return F(null),(async()=>{try{const C=await cp(d);if(A)return;F(C)}catch{}})(),()=>{A=!0}},[d]),l.useEffect(()=>{if(!B){j([]),R(!1);return}if(P===!1){j([]),R(!1);return}let A=!1;return R(!0),j([]),(async()=>{try{const C=await el(B);if(A)return;j(C)}catch{}finally{A||R(!1)}})(),()=>{A=!0}},[B,P]),l.useEffect(()=>{if(!B)return;let A=!1;return x(!0),(async()=>{try{const[C,z]=await Promise.all([Cd(B),Id(B)]);if(!A){const $=C.length>0?C:[""];m($),N(JSON.stringify($)),h(z)}}catch{A||(m([""]),N(JSON.stringify([""])),h(!1))}finally{A||x(!1)}})(),()=>{A=!0}},[B]);const k=l.useCallback(async A=>{if(!B)return!1;const C=A.filter(z=>z.trim().length>0);try{return await dp(B,C)?(N(JSON.stringify(A)),!0):(G.error(n("settings.openchamber.worktrees.setup.toast.saveFailed")),!1)}catch{return G.error(n("settings.openchamber.worktrees.setup.toast.saveFailed")),!1}},[B,n]),T=l.useMemo(()=>v===null?!1:v!==JSON.stringify(f),[v,f]);l.useEffect(()=>{if(!T||g||_.current)return;const A=window.setTimeout(()=>{_.current||(_.current=!0,(async()=>{try{await k(f)}finally{_.current=!1}})())},Gb);return()=>{window.clearTimeout(A)}},[T,g,k,f]);const M=l.useCallback((A,C)=>{m(z=>{const $=[...z];return $[A]=C,$})},[]),O=l.useCallback(()=>{m(A=>[...A,""])},[]),V=l.useCallback(A=>{m(C=>{const z=C.filter(($,H)=>H!==A);return z.length>0?z:[""]})},[]),U=l.useCallback(()=>{!T||_.current||(_.current=!0,(async()=>{try{await k(f)}finally{_.current=!1}})())},[T,k,f]),Y=l.useCallback(A=>{h(A),B&&up(B,A)},[B]),X=l.useCallback(A=>{const C=be=>be.replace(/\\/g,"/").replace(/\/+$/,""),z=C(A.path),$=p.filter(be=>{const he=c(be.id);if(he?.path&&C(he.path)===z)return!0;const ye=be.directory;return!!(ye&&C(ye)===z)}),H=new Set($.map(be=>be.id)),J=[...uo.getState().activeSessions,...uo.getState().archivedSessions],ee=be=>{const he=J.filter(fe=>{const ae=fe.parentID;return ae&&be.has(ae)});if(he.length===0)return[];const ye=new Set(he.map(fe=>fe.id));return[...he,...ee(ye)]},ue=ee(H),re=new Set,xe=[...$,...ue].filter(be=>re.has(be.id)?!1:(re.add(be.id),!0));kd.requestDelete({sessions:xe,mode:"worktree",worktree:A})},[p,c]),S=l.useMemo(()=>p.map(A=>A.id).join(","),[p]);l.useEffect(()=>{P&&d&&D()},[S,P,d,D]);const W=s.jsxs(Ht,{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")]}),Z=s.jsx(Ht,{children:n("settings.openchamber.worktrees.list.tooltip")});return d?P===!1?s.jsx(Cn,{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(Cn,{title:n("settings.projects.page.section.worktree"),settingsItem:"projects.worktree",titleAccessory:W,children:g?s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.setup.loading")}):s.jsxs("div",{className:le("space-y-2",ai),children:[f.map((A,C)=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(tt,{value:A,onChange:z=>M(C,z.target.value),onBlur:U,placeholder:n("settings.openchamber.worktrees.setup.commandPlaceholder"),className:"h-7 min-w-0 flex-1 font-mono text-xs"}),s.jsx(Q,{type:"button",variant:"ghost",size:"icon",onClick:()=>V(C),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(L,{name:"close",className:"h-4 w-4"})})]},C)),s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:O,children:[s.jsx(L,{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(Pn,{checked:b,onChange:Y,ariaLabel:n("settings.openchamber.worktrees.setup.waitForCommandsAria")}),s.jsx("span",{className:le("typography-ui-label font-normal",b?"text-foreground":"text-foreground/60"),children:n("settings.openchamber.worktrees.setup.waitForCommands")})]})]})}):null,s.jsx(Cn,{title:n("settings.openchamber.worktrees.list.title"),titleAccessory:Z,children:y?s.jsx("p",{className:"typography-meta text-muted-foreground",children:n("settings.openchamber.worktrees.list.loading")}):w.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:n("settings.openchamber.worktrees.list.empty")}):s.jsx("div",{className:le("space-y-1",e==="all"&&ai),children:w.map(A=>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:A.label||A.branch||n("settings.openchamber.worktrees.list.detachedHead")})}),s.jsx("p",{className:"typography-micro truncate text-muted-foreground/60",children:mp(A.path,u)})]}),s.jsx("button",{type:"button",onClick:()=>X(A),className:le("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:A.branch||A.label||A.path}),children:s.jsx(L,{name:"delete-bin",className:"h-4 w-4"})})]},A.path))})})]}):s.jsx(Cn,{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")})})},hc=(t,e)=>e.updatedAtMs-t.updatedAtMs,xs=cn((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([hp(),sl()]),i={};for(const r of a.sort(hc))i[r.id]=r;e().listenerReady||await xp(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 fp();t({importCandidates:n,isImportsLoading:!1})}catch(n){t({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await sl(),a={};for(const i of n.sort(hc))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 gp({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=bp(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 pp(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})})),Xd=[{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"}],Zd=Object.fromEntries(Xd.map(t=>[t.key,t.Icon])),Jb="openchamber:project-actions-updated",Qb=t=>{const e=(t||"").trim().replace(/\\/g,"/");return e?e==="/"?"/":e.length>1?e.replace(/\/+$/,""):e:""},Wk=(t,e)=>`${Qb(t)}::${e}`,Yb=t=>{const e=t.trim();return!e||e==="0.0.0.0"||e==="::"?"127.0.0.1":e},xc=t=>{if(typeof t!="number"||!Number.isFinite(t))return null;const e=Math.round(t);return e<1||e>65535?null:e},Xb=(t,e)=>{if(!e.enabled||e.type!=="local")return null;const n=xc(e.localPort),a=xc(e.remotePort);if(!n||!a)return null;const i=Yb(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}`}},eu=t=>{const e=[];for(const n of t)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const a of n.portForwards){const i=Xb(n,a);i&&e.push(i)}return e},Gk=(t,e)=>{const n=(t||"").trim();return n&&eu(e).find(r=>r.id===n)?.url||null},Zb=450,ey=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,ty=()=>({id:ey(),name:"",command:"",icon:"play"}),sy=({projectRef:t})=>{const{t:e}=it(),n=l.useMemo(()=>ss(),[]),a=xs(j=>j.instances),i=xs(j=>j.load),[r,o]=l.useState([]),[d,c]=l.useState(!1),[p,u]=l.useState(null),[f,m]=l.useState({}),b=l.useRef(!1),h=l.useRef(null);l.useEffect(()=>{n&&i().catch(()=>{})},[n,i]),l.useEffect(()=>{let j=!1;return c(!0),(async()=>{try{const y=await yp(t);if(j)return;o(y.actions),u(JSON.stringify({actions:y.actions}))}catch{if(j)return;o([]),u(JSON.stringify({actions:[]}))}finally{j||c(!1)}})(),()=>{j=!0}},[t]);const g=l.useMemo(()=>n?eu(a):[],[a,n]),x=l.useMemo(()=>r.some(y=>y.name.trim().length===0||y.command.trim().length===0)?e("settings.projects.actions.validation.fillNameAndCommand"):null,[r,e]),v=l.useMemo(()=>p===null?!1:p!==JSON.stringify({actions:r}),[r,p]),N=l.useCallback(async j=>await vp(t,{actions:j,primaryActionId:null})?(u(JSON.stringify({actions:j})),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Jb,{detail:{projectId:t.id}})),!0):(G.error(e("settings.projects.actions.toast.saveFailed")),!1),[t,e]);l.useEffect(()=>{if(!v||d||x||b.current)return;const j=window.setTimeout(()=>{b.current||(b.current=!0,(async()=>{try{await N(r)}finally{b.current=!1}})())},Zb);return()=>{window.clearTimeout(j)}},[r,v,d,N,x]),l.useEffect(()=>{if(!v||!x||d){x||(h.current=null);return}const j=window.setTimeout(()=>{h.current!==x&&(h.current=x,G.error(x))},1e3);return()=>{window.clearTimeout(j)}},[v,d,x]);const P=l.useCallback(()=>{const j=ty();o(y=>[...y,j]),m(y=>({...y,[j.id]:!0}))},[]),F=l.useCallback(j=>{o(y=>y.filter(R=>R.id!==j)),m(y=>{const R={...y};return delete R[j],R})},[]),w=l.useCallback((j,y)=>{o(R=>R.map(_=>_.id===j?y(_):_))},[]);return s.jsxs(Cn,{title:e("settings.projects.actions.title"),info:e("settings.projects.actions.description"),settingsItem:"projects.actions",headerAction:s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:P,children:[s.jsx(L,{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:le("space-y-0",ai),children:r.map(j=>{const y=j.icon||"play",R=Zd[y]||"play",_=f[j.id]??!1,B=j.name.trim()||e("settings.projects.actions.state.untitled");return s.jsxs(sa,{open:_,onOpenChange:D=>{m(k=>({...k,[j.id]:D}))},className:"py-1.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs(na,{className:"group flex-1 justify-start gap-2 rounded-md px-0 pr-1 py-1 hover:bg-[var(--interactive-hover)] focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",children:[_?s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(L,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground"}),s.jsx(L,{name:R,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:B})})]}),s.jsx(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal h-7 w-7 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>F(j.id),children:s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsx(aa,{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(ws,{children:[s.jsx(ys,{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(L,{name:R,className:"h-4 w-4"})})}),s.jsx(vs,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Xd.map(D=>{const k=D.Icon,T=(j.icon||"play")===D.key;return s.jsx("button",{type:"button",onClick:()=>w(j.id,M=>({...M,icon:D.key})),className:le("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",T&&"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(L,{name:k,className:"h-4 w-4"})},D.key)})})})]}),s.jsx(tt,{value:j.name,onChange:D=>w(j.id,k=>({...k,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(js,{value:j.command,onChange:D=>w(j.id,k=>({...k,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":j.autoOpenUrl===!0,onClick:()=>w(j.id,D=>({...D,...D.autoOpenUrl===!0?{autoOpenUrl:void 0}:{autoOpenUrl:!0}})),onKeyDown:D=>{(D.key===" "||D.key==="Enter")&&(D.preventDefault(),w(j.id,k=>({...k,...k.autoOpenUrl===!0?{autoOpenUrl:void 0}:{autoOpenUrl:!0}})))},children:[s.jsx(Pn,{checked:j.autoOpenUrl===!0,onChange:D=>w(j.id,k=>({...k,...D?{autoOpenUrl:!0}:{autoOpenUrl:void 0}})),ariaLabel:e("settings.projects.actions.field.autoOpenUrlForAria",{title:B})}),s.jsx("span",{className:"typography-ui-label font-normal text-foreground/80",children:e("settings.projects.actions.field.autoOpenUrlDescription")})]})]}),j.autoOpenUrl===!0?s.jsxs("div",{className:"mt-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tt,{value:j.openUrl||"",onChange:D=>w(j.id,k=>({...k,openUrl:D.target.value})),placeholder:e("settings.projects.actions.field.overrideUrlPlaceholder"),className:"h-7 w-full max-w-[24rem]"}),s.jsx(Ht,{contentClassName:"max-w-xs",children:e("settings.projects.actions.field.overrideUrlTooltip")})]}),n?s.jsxs("div",{className:"mt-2",children:[s.jsx("p",{className:"typography-meta mb-0.5 text-muted-foreground",children:e("settings.projects.actions.field.desktopSshForward")}),g.length>0?s.jsxs(At,{value:j.desktopOpenSshForward&&g.some(D=>D.id===j.desktopOpenSshForward)?j.desktopOpenSshForward:"__none__",onValueChange:D=>{w(j.id,k=>({...k,...D==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:D}}))},children:[s.jsx(Et,{size:Gt,className:"w-full",children:s.jsx(Vt,{placeholder:e("settings.projects.actions.field.useOutputManualUrl")})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"__none__",children:e("settings.projects.actions.field.useOutputManualUrl")}),g.map(D=>s.jsx(yt,{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]})]})})]},j.id)})}),x&&r.length>0?s.jsx("p",{className:"typography-meta text-[var(--status-warning)]",children:x}):null]})},ny=t=>{const e=Ye.c(123),{form:n}=t,{t:a}=it(),{currentTheme:i}=oi(),{name:r,setName:o,icon:d,setIcon:c,color:p,setColor:u,iconBackground:f,setIconBackground:m,parsedDefaultModel:b,handleDefaultModelChange:h,isUploadingIcon:g,isRemovingCustomIcon:x,isDiscoveringIcon:v,pendingRemoveImageIcon:N,setPendingRemoveImageIcon:P,pendingUploadIconPreviewUrl:F,setPreviewImageFailed:w,hasPendingUploadImageIcon:j,hasCustomIcon:y,effectiveHasImageIcon:R,hasRemovableImageIcon:_,showImagePreview:B,fileInputRef:D,handleUploadIcon:k,handleRemoveImageIcon:T,handleDiscoverIcon:M,currentIconImage:O,project:V}=n;if(!V)return null;const U=p?Nd[p]??null:null;let Y;e[0]!==a?(Y=a("settings.projects.page.field.projectName"),e[0]=a,e[1]=Y):Y=e[1];let X;e[2]!==o?(X=Pe=>o(Pe.target.value),e[2]=o,e[3]=X):X=e[3];let S;e[4]!==a?(S=a("settings.projects.page.field.projectNamePlaceholder"),e[4]=a,e[5]=S):S=e[5];let W;e[6]===Symbol.for("react.memo_cache_sentinel")?(W=le("h-8 rounded-md px-3",ai),e[6]=W):W=e[6];let Z;e[7]!==r||e[8]!==X||e[9]!==S?(Z=s.jsx(tt,{value:r,onChange:X,placeholder:S,className:W}),e[7]=r,e[8]=X,e[9]=S,e[10]=Z):Z=e[10];let A;e[11]!==Y||e[12]!==Z?(A=s.jsx(Cn,{title:Y,settingsItem:"projects.name",divider:!1,children:Z}),e[11]=Y,e[12]=Z,e[13]=A):A=e[13];let C;e[14]!==a?(C=a("settings.projects.page.field.defaultModel"),e[14]=a,e[15]=C):C=e[15];let z;e[16]!==a?(z=a("settings.projects.page.field.defaultModelDescription"),e[16]=a,e[17]=z):z=e[17];const $=b.providerId,H=b.modelId;let J;e[18]===Symbol.for("react.memo_cache_sentinel")?(J=le("h-8 min-h-8 rounded-md px-3 max-w-48",ai),e[18]=J):J=e[18];let ee;e[19]!==h||e[20]!==b.modelId||e[21]!==b.providerId?(ee=s.jsx(ni,{providerId:$,modelId:H,onChange:h,className:J}),e[19]=h,e[20]=b.modelId,e[21]=b.providerId,e[22]=ee):ee=e[22];let ue;e[23]!==ee||e[24]!==C||e[25]!==z?(ue=s.jsx(Cn,{title:C,info:z,settingsItem:"projects.default-model",children:ee}),e[23]=ee,e[24]=C,e[25]=z,e[26]=ue):ue=e[26];let re;e[27]!==a?(re=a("settings.projects.page.field.accentColor"),e[27]=a,e[28]=re):re=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 he;e[31]!==be?(he=le("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",be),e[31]=be,e[32]=he):he=e[32];let ye;e[33]!==a?(ye=a("settings.projects.page.field.none"),e[33]=a,e[34]=ye):ye=e[34];let fe;e[35]===Symbol.for("react.memo_cache_sentinel")?(fe=s.jsx(L,{name:"close",className:"h-4 w-4 text-muted-foreground"}),e[35]=fe):fe=e[35];let ae;e[36]!==xe||e[37]!==he||e[38]!==ye?(ae=s.jsx("button",{type:"button",onClick:xe,className:he,title:ye,children:fe}),e[36]=xe,e[37]=he,e[38]=ye,e[39]=ae):ae=e[39];let ce;e[40]!==p||e[41]!==u?(ce=wp.map(Pe=>s.jsx("button",{type:"button",onClick:()=>u(Pe.key),className:le("h-7 w-7 rounded-md border transition-colors",p===Pe.key?"border-2 border-foreground ring-1 ring-[var(--primary-base)]/40":"border-transparent hover:border-border/70"),style:{backgroundColor:Pe.cssVar},title:Pe.label},Pe.key)),e[40]=p,e[41]=u,e[42]=ce):ce=e[42];let pe;e[43]!==ae||e[44]!==ce?(pe=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[ae,ce]}),e[43]=ae,e[44]=ce,e[45]=pe):pe=e[45];let q;e[46]!==re||e[47]!==pe?(q=s.jsx(Cn,{title:re,settingsItem:"projects.accent-color",children:pe}),e[46]=re,e[47]=pe,e[48]=q):q=e[48];let te;e[49]!==a?(te=a("settings.projects.page.field.projectIcon"),e[49]=a,e[50]=te):te=e[50];let ne;e[51]!==k?(ne=Pe=>{const at=Pe.target.files?.[0]??null;k(at),Pe.currentTarget.value=""},e[51]=k,e[52]=ne):ne=e[52];let oe;e[53]!==D||e[54]!==ne?(oe=s.jsx("input",{ref:D,type:"file",accept:"image/png,image/jpeg,image/svg+xml,.png,.jpg,.jpeg,.svg",className:"hidden",onChange:ne}),e[53]=D,e[54]=ne,e[55]=oe):oe=e[55];let Ae;e[56]!==c?(Ae=()=>c(null),e[56]=c,e[57]=Ae):Ae=e[57];const je=d===null?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-border/40 hover:border-border hover:bg-[var(--surface-muted)]";let Ie;e[58]!==je?(Ie=le("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",je),e[58]=je,e[59]=Ie):Ie=e[59];let Te;e[60]!==a?(Te=a("settings.projects.page.field.none"),e[60]=a,e[61]=Te):Te=e[61];let Me;e[62]===Symbol.for("react.memo_cache_sentinel")?(Me=s.jsx(L,{name:"close",className:"h-4 w-4 text-muted-foreground"}),e[62]=Me):Me=e[62];let He;e[63]!==Ae||e[64]!==Ie||e[65]!==Te?(He=s.jsx("button",{type:"button",onClick:Ae,className:Ie,title:Te,children:Me}),e[63]=Ae,e[64]=Ie,e[65]=Te,e[66]=He):He=e[66];let Ve;e[67]!==U||e[68]!==d||e[69]!==c?(Ve=jp.map(Pe=>{const at=Pe.Icon;return s.jsx("button",{type:"button",onClick:()=>c(Pe.key),className:le("h-7 w-7 rounded-md border transition-colors flex items-center justify-center",d===Pe.key?"border-2 border-foreground bg-[var(--primary-base)]/10":"border-transparent hover:border-border hover:bg-[var(--surface-muted)]"),title:Pe.label,children:s.jsx(L,{name:at,className:"w-4 h-4",style:U&&d===Pe.key?{color:U}:void 0})},Pe.key)}),e[67]=U,e[68]=d,e[69]=c,e[70]=Ve):Ve=e[70];let Ue;e[71]!==He||e[72]!==Ve?(Ue=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[He,Ve]}),e[71]=He,e[72]=Ve,e[73]=Ue):Ue=e[73];let ze;e[74]!==O||e[75]!==i||e[76]!==R||e[77]!==j||e[78]!==f||e[79]!==F||e[80]!==V||e[81]!==w||e[82]!==B||e[83]!==a?(ze=R&&B&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"typography-meta text-muted-foreground",children:a("settings.projects.page.field.preview")}),s.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-md border border-border/60 bg-[var(--surface-elevated)] p-1",children:s.jsx("span",{className:"inline-flex h-4 w-4 items-center justify-center overflow-hidden rounded-[2px]",style:f?{backgroundColor:f}:void 0,children:j&&F?s.jsx("img",{src:F,alt:"",className:"h-full w-full object-contain",draggable:!1,onError:()=>w(!0)}):s.jsx(Sd,{project:{...V,iconImage:O??V.iconImage},options:{themeVariant:i.metadata.variant,iconColor:i.colors.surface.foreground},className:"h-full w-full object-contain",onError:()=>w(!0)})})})]}),e[74]=O,e[75]=i,e[76]=R,e[77]=j,e[78]=f,e[79]=F,e[80]=V,e[81]=w,e[82]=B,e[83]=a,e[84]=ze):ze=e[84];let Be;e[85]!==R||e[86]!==f||e[87]!==m||e[88]!==a?(Be=R&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"color",value:f??"#000000",onChange:Pe=>m(Pe.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(tt,{value:f??"",onChange:Pe=>m(Pe.target.value),placeholder:"#000000",className:"h-7 w-[8rem]"}),s.jsx(Q,{type:"button",size:"xs",variant:"outline",onClick:()=>m(null),className:"h-7 w-7 p-0","aria-label":a("settings.projects.page.field.clearIconBackgroundAria"),title:a("settings.projects.page.field.clearBackground"),disabled:!f,children:s.jsx(L,{name:"close",className:"h-3.5 w-3.5"})})]}),e[85]=R,e[86]=f,e[87]=m,e[88]=a,e[89]=Be):Be=e[89];let Ge;e[90]!==D||e[91]!==M||e[92]!==y||e[93]!==v||e[94]!==g||e[95]!==a?(Ge=!y&&s.jsxs(s.Fragment,{children:[s.jsx(Q,{size:"xs",className:"h-6 !font-normal",onClick:()=>D.current?.click(),disabled:g,children:a(g?"settings.projects.page.actions.uploading":"settings.projects.page.actions.uploadIcon")}),s.jsx(Q,{size:"xs",className:"h-6 !font-normal",variant:"outline",onClick:()=>{M()},disabled:v,children:a(v?"settings.projects.page.actions.discovering":"settings.projects.page.actions.discoverFavicon")})]}),e[90]=D,e[91]=M,e[92]=y,e[93]=v,e[94]=g,e[95]=a,e[96]=Ge):Ge=e[96];let Fe;e[97]!==T||e[98]!==_||e[99]!==x||e[100]!==a?(Fe=_&&s.jsx(Q,{size:"xs",className:"!font-normal",variant:"outline",onClick:()=>{T()},disabled:x,children:a(x?"settings.projects.page.actions.removing":"settings.projects.page.actions.removeProjectIcon")}),e[97]=T,e[98]=_,e[99]=x,e[100]=a,e[101]=Fe):Fe=e[101];let ve;e[102]!==x||e[103]!==N||e[104]!==P||e[105]!==a?(ve=N&&s.jsx(Q,{size:"xs",className:"!font-normal",variant:"outline",onClick:()=>P(!1),disabled:x,children:a("settings.projects.page.actions.undoRemove")}),e[102]=x,e[103]=N,e[104]=P,e[105]=a,e[106]=ve):ve=e[106];let De;e[107]!==Ge||e[108]!==Fe||e[109]!==ve?(De=s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[Ge,Fe,ve]}),e[107]=Ge,e[108]=Fe,e[109]=ve,e[110]=De):De=e[110];let Ke;e[111]!==te||e[112]!==oe||e[113]!==Ue||e[114]!==ze||e[115]!==Be||e[116]!==De?(Ke=s.jsxs(Cn,{title:te,settingsItem:"projects.icon",contentClassName:"space-y-3",children:[oe,Ue,ze,Be,De]}),e[111]=te,e[112]=oe,e[113]=Ue,e[114]=ze,e[115]=Be,e[116]=De,e[117]=Ke):Ke=e[117];let We;return e[118]!==ue||e[119]!==q||e[120]!==Ke||e[121]!==A?(We=s.jsxs(s.Fragment,{children:[A,ue,q,Ke]}),e[118]=ue,e[119]=q,e[120]=Ke,e[121]=A,e[122]=We):We=e[122],We},ay=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,iy=t=>{if(!t)return null;const e=t.trim();return e&&ay.test(e)?e.toLowerCase():null},ry=t=>{const{t:e}=it(),n=rs(re=>re.uploadProjectIcon),a=rs(re=>re.removeProjectIcon),i=rs(re=>re.discoverProjectIcon),r=rs(re=>t?re.projects.find(xe=>xe.id===t.id)?.iconImage??null:null),[o,d]=l.useState(""),[c,p]=l.useState(null),[u,f]=l.useState(null),[m,b]=l.useState(null),[h,g]=l.useState(void 0),[x,v]=l.useState(!1),[N,P]=l.useState(!1),[F,w]=l.useState(!1),[j,y]=l.useState(!1),[R,_]=l.useState(null),[B,D]=l.useState(null),[k,T]=l.useState(!1),M=l.useRef(null),O=l.useCallback(()=>{_(null),D(re=>(re&&URL.revokeObjectURL(re),null))},[]),V=t?.id??null;l.useEffect(()=>{if(!t){d(""),p(null),f(null),b(null),g(void 0);return}d(t.label??""),p(t.icon??null),f(t.color??null),b(t.iconBackground??null),g(t.defaultModel),y(!1),O(),T(!1)},[t,O]),l.useEffect(()=>()=>{O()},[O]);const U=l.useMemo(()=>Kn(h)??{providerId:"",modelId:""},[h]),Y=!!t?.iconImage,X=!!(R&&B),S=t?.iconImage?.source==="custom",W=Y&&!j||X,Z=W,A=!!(t&&Y&&!j),C=!k&&(X||A),z=!!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)||j||!!R),$=l.useCallback((re,xe)=>{g(re&&xe?`${re}/${xe}`:void 0)},[]),H=l.useCallback(re=>{!t||!re||x||(y(!1),T(!1),_(re),D(xe=>(xe&&URL.revokeObjectURL(xe),URL.createObjectURL(re))))},[x,t]),J=l.useCallback(()=>{!t||!Z||N||(X&&O(),y(!!Y),T(!1))},[O,X,Z,Y,N,t]),ee=l.useCallback(async()=>{if(!(!t||F)){O(),y(!1),T(!1),w(!0);try{const re=await i(t.id);if(!re.ok){G.error(re.error||e("settings.projects.page.toast.discoverIconFailed"));return}if(re.skipped){G.success(e("settings.projects.page.toast.customIconAlreadySet"));return}G.success(e("settings.projects.page.toast.iconDiscovered"))}finally{w(!1)}}},[O,i,F,t,e]),ue=l.useCallback(async re=>{const xe=re?.silent===!0;if(!t)return null;const be=o.trim();if(!be)return null;if(R){v(!0);const ye=await n(t.id,R);if(v(!1),!ye.ok)return G.error(ye.error||e("settings.projects.page.toast.uploadIconFailed")),null;xe||G.success(e("settings.projects.page.toast.iconUpdated")),O(),y(!1)}const he=j&&!!t.iconImage;if(he){P(!0);const ye=await a(t.id);if(P(!1),!ye.ok)return G.error(ye.error||e("settings.projects.page.toast.removeIconFailed")),null;xe||G.success(e("settings.projects.page.toast.iconRemoved")),y(!1),b(null)}return{label:be,icon:c,color:u,iconBackground:iy(he?null:m),defaultModel:h??null}},[O,u,h,c,m,o,j,R,t,a,e,n]);return l.useEffect(()=>{T(!1)},[V,r?.updatedAt]),{name:o,setName:d,icon:c,setIcon:p,color:u,setColor:f,iconBackground:m,setIconBackground:b,defaultModel:h,parsedDefaultModel:U,handleDefaultModelChange:$,isUploadingIcon:x,isRemovingCustomIcon:N,isDiscoveringIcon:F,pendingRemoveImageIcon:j,setPendingRemoveImageIcon:y,pendingUploadIconFile:R,pendingUploadIconPreviewUrl:B,previewImageFailed:k,setPreviewImageFailed:T,hasStoredImageIcon:Y,hasPendingUploadImageIcon:X,hasCustomIcon:S,effectiveHasImageIcon:W,hasRemovableImageIcon:Z,showStoredImagePreview:A,showImagePreview:C,fileInputRef:M,clearPendingUploadIcon:O,handleUploadIcon:H,handleRemoveImageIcon:J,handleDiscoverIcon:ee,hasChanges:z,prepareSaveData:ue,currentIconImage:r,project:t}},oy=450,ly=(t,e)=>{const{t:n}=it(),{hasChanges:a,name:i,icon:r,color:o,iconBackground:d,defaultModel:c,pendingRemoveImageIcon:p,pendingUploadIconFile:u,isUploadingIcon:f,isRemovingCustomIcon:m,prepareSaveData:b}=t,h=l.useRef(!1);l.useEffect(()=>{if(!a||!i.trim()||f||m||h.current)return;const g=window.setTimeout(()=>{h.current||(h.current=!0,(async()=>{try{const x=await b({silent:!0});if(x)try{await e(x)}catch{G.error(n("settings.projects.page.toast.saveFailed"))}}finally{h.current=!1}})())},oy);return()=>{window.clearTimeout(g)}},[o,c,a,r,d,m,f,i,e,p,u,b,n])},cy=t=>{const e=Ye.c(16),{project:n,onIdentitySave:a,showWorktrees:i}=t,r=i===void 0?!0:i,o=ry(n);let d;e:{if(!n){d=null;break e}let g;e[0]!==n.id||e[1]!==n.path?(g={id:n.id,path:n.path},e[0]=n.id,e[1]=n.path,e[2]=g):g=e[2],d=g}const c=d;let p;if(e[3]!==a?(p=async g=>{await a(g)},e[3]=a,e[4]=p):p=e[4],ly(o,p),!n||!c)return null;let f;e[5]!==o?(f=s.jsx(ny,{form:o}),e[5]=o,e[6]=f):f=e[6];let m;e[7]!==c?(m=s.jsx(sy,{projectRef:c}),e[7]=c,e[8]=m):m=e[8];let b;e[9]!==c||e[10]!==r?(b=r?s.jsx(qb,{projectRef:c}):null,e[9]=c,e[10]=r,e[11]=b):b=e[11];let h;return e[12]!==f||e[13]!==m||e[14]!==b?(h=s.jsxs("div",{className:"space-y-0",children:[f,m,b]}),e[12]=f,e[13]=m,e[14]=b,e[15]=h):h=e[15],h},dy=()=>{const t=Ye.c(30),{t:e}=it(),n=rs(uy),a=rs(my),i=Ne(py),r=Ne(gy);let o;e:{if(!i){o=null;break e}let x;t[0]!==n||t[1]!==i?(x=n.find(v=>v.id===i)??null,t[0]=n,t[1]=i,t[2]=x):x=t[2],o=x}const d=o;let c,p;t[3]!==n||t[4]!==i||t[5]!==r?(c=()=>{if(n.length===0){r(null);return}i&&n.some(x=>x.id===i)||r(n[0].id)},p=[n,i,r],t[3]=n,t[4]=i,t[5]=r,t[6]=c,t[7]=p):(c=t[6],p=t[7]),l.useEffect(c,p);let u;t[8]!==d||t[9]!==a?(u=async x=>{d&&a(d.id,{label:x.label,icon:x.icon,color:x.color,iconBackground:x.iconBackground,defaultModel:x.defaultModel??null})},t[8]=d,t[9]=a,t[10]=u):u=t[10];const f=u;if(!d){let x;t[11]!==e?(x=e("settings.page.projects.title"),t[11]=e,t[12]=x):x=t[12];let v;t[13]!==e?(v=e("settings.projects.page.empty.noProjects"),t[13]=e,t[14]=v):v=t[14];let N;t[15]!==v?(N=s.jsx("p",{className:"typography-meta text-muted-foreground",children:v}),t[15]=v,t[16]=N):N=t[16];let P;return t[17]!==x||t[18]!==N?(P=s.jsx(us,{title:x,showSaveStatus:!0,children:N}),t[17]=x,t[18]=N,t[19]=P):P=t[19],P}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 b=m;let h;t[23]!==f||t[24]!==d?(h=s.jsx(cy,{project:d,onIdentitySave:f}),t[23]=f,t[24]=d,t[25]=h):h=t[25];let g;return t[26]!==b||t[27]!==d.path||t[28]!==h?(g=s.jsx(us,{title:b,description:d.path,showSaveStatus:!0,outerClassName:"bg-background",children:h}),t[26]=b,t[27]=d.path,t[28]=h,t[29]=g):g=t[29],g};function uy(t){return t.projects}function my(t){return t.updateProjectMeta}function py(t){return t.settingsProjectsSelectedId}function gy(t){return t.setSettingsProjectsSelectedId}const So=()=>Math.floor(2e4+Math.random()*3e4),fy=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")},hy=()=>{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"},bc=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}},yc=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"}},xy=new Set(["config_resolved","auth_check","master_connecting","remote_probe","installing","updating","server_detecting","server_starting","forwarding"]),tu=t=>!!(t&&xy.has(t)),vc=t=>t==="ready"?"bg-[var(--status-success)] animate-pulse":t==="error"?"bg-[var(--status-error)] animate-pulse":t==="degraded"||tu(t)?"bg-[var(--status-warning)] animate-pulse":"bg-muted-foreground/40",by=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}`,yy=()=>({id:`forward-${Date.now()}-${Math.random().toString(16).slice(2)}`,enabled:!0,type:"local",localHost:"127.0.0.1",localPort:So(),remoteHost:"127.0.0.1",remotePort:80}),vy=t=>t.trim().replace(/\*/g,"host").replace(/\?/g,"x")||"user@host",bn=t=>{const e=Ye.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(Ht,{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 ${Kt}`,children:[i,r]}),e[4]=i,e[5]=r,e[6]=o):o=e[6],o},wy=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"}},wc=(t,e)=>{const n=(t||"").trim();return`${!n||n==="127.0.0.1"||n==="::1"?"localhost":n}:${e||0}`},jy=t=>{const e=(t||"").trim();return!e||e==="0.0.0.0"||e==="::"?"127.0.0.1":e},ky=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}`},Co=(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}),Ny=t=>t.trim().toLowerCase()==="authorization",Kr=t=>{const e={};for(const n of t){const a=n.name.trim(),i=n.value.trim();a&&i&&!Ny(a)&&(e[a]=i)}return Object.keys(e).length>0?e:void 0},Sy=t=>Object.entries(t||{}).map(([e,n])=>Co(e,n)),su=()=>{if(typeof window>"u")return null;const e=La()||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}},jc=t=>{try{const e=new URL(t).hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}catch{return!1}},Cy=async()=>{const t=wa(La())||window.location.origin;if(!ss()||!Ma())return t;let e;try{e=await gt("/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 Ld(),i=su();return!a||!i?t:`http://${a}:${i}`},Ur=t=>{const e=t.trim();if(e)try{window.location.assign(e)}catch{window.location.href=e}},Iy=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}},Py=()=>{const{t}=it(),e=Ne(K=>K.timeFormatPreference),{clientAuth:n}=li(),a=ss(),i=xs(K=>K.instances),r=xs(K=>K.statusesById),o=xs(K=>K.importCandidates),d=xs(K=>K.isLoading),c=xs(K=>K.isImportsLoading),p=xs(K=>K.isSaving),u=xs(K=>K.error),f=xs(K=>K.load),m=xs(K=>K.loadImports),b=xs(K=>K.refreshStatuses),h=xs(K=>K.upsertInstance),g=xs(K=>K.createFromCommand),x=xs(K=>K.removeInstance),v=xs(K=>K.connect),N=xs(K=>K.disconnect),P=xs(K=>K.retry),F=Ne(K=>K.settingsRemoteInstancesSelectedId),w=Ne(K=>K.setSettingsRemoteInstancesSelectedId),j=l.useMemo(()=>F&&i.find(K=>K.id===F)||null,[i,F]),[y,R]=l.useState(null),[_,B]=l.useState(!1),[D,k]=l.useState(!1),[T,M]=l.useState(null),[O,V]=l.useState([]),[U,Y]=l.useState(null),[X,S]=l.useState(""),[W,Z]=l.useState(!1),[A,C]=l.useState({}),[z,$]=l.useState(!1),[H,J]=l.useState(!1),[ee,ue]=l.useState(()=>Date.now()),[re,xe]=l.useState([]),[be,he]=l.useState({}),[ye,fe]=l.useState("local"),[ae,ce]=l.useState(!1),[pe,q]=l.useState(!1),[te,ne]=l.useState(""),[oe,Ae]=l.useState(""),[je,Ie]=l.useState(""),[Te,Me]=l.useState([]),[He,Ve]=l.useState(""),[Ue,ze]=l.useState(null),[Be,Ge]=l.useState(!1),[Fe,ve]=l.useState(!1),[De,Ke]=l.useState(null),[We,Pe]=l.useState(""),[at,se]=l.useState(""),[I,Ee]=l.useState(""),[Le,_e]=l.useState([]),[Xe,ct]=l.useState([]),[ut,lt]=l.useState([]),[rt,mt]=l.useState(!1),[xt,It]=l.useState(""),[Se,qe]=l.useState(null),[Ze,nt]=l.useState(null),[ft,vt]=l.useState(null),[St,de]=l.useState(null),[ie,we]=l.useState(!1),[me,Je]=l.useState(!1),[$e,et]=l.useState("configure"),[bt,Dt]=l.useState(!1),[Qt,_t]=l.useState("relay"),[as,is]=l.useState(!0),[$t,Ce]=l.useState(null),jt=l.useMemo(()=>Xe.filter(K=>!!K.revokedAt).length,[Xe]),[Qe,ht]=l.useState(!1),[Nt,Pt]=l.useState("ssh user@example.com"),[Mt,cs]=l.useState("");l.useEffect(()=>{f(),m()},[f,m]);const $s=l.useCallback(async()=>{ce(!0),ze(null);try{const K=await gl();xe(K.hosts||[]),fe(K.defaultHostId||"local")}catch(K){ze(K instanceof Error?K.message:String(K))}finally{ce(!1)}},[]);l.useEffect(()=>{$s()},[$s]);const Yt=l.useCallback(async(K,ke=ye)=>{q(!0),ze(null);try{await fl({hosts:K,defaultHostId:ke,initialHostChoiceCompleted:!0}),xe(K),fe(ke)}catch(st){ze(st instanceof Error?st.message:String(st))}finally{q(!1)}},[ye]),oa=l.useCallback(async()=>{const K=hl(oe);if(!K){ze(t("desktopHostSwitcher.error.invalidUrl"));return}const ke=K.persistedUrl,dt={id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,label:te.trim()||Ba(ke),url:ke,apiUrl:ke,...je.trim()?{clientToken:je.trim()}:{},...Kr(Te)?{requestHeaders:Kr(Te)}:{}};await Yt([dt,...re],ye),ne(""),Ae(""),Ie(""),Me([]),Ge(!1),K.redeemUrl&&Ur(K.redeemUrl)},[ye,Te,re,te,je,oe,Yt,t]),Hn=l.useCallback(async()=>{const K=jg(He);if(!K){ze(t("settings.remoteInstances.direct.error.invalidConnectLink"));return}const ke=await kg().catch(()=>""),st=JSON.stringify({pairingId:K.pairingId,secret:K.secret,clientLabel:K.label||"OpenChamber Desktop",clientKind:"desktop",deviceName:"OpenChamber Desktop",devicePlatform:hy(),...ke?{dedupeKey:`desktop:${ke}`}:{}}),dt={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:st},Ot=async Bt=>{if(!Bt.ok)return null;const ks=await Bt.json().catch(()=>null);return(typeof ks?.clientToken=="string"?ks.clientToken.trim():"")||null},hs=[...K.candidates].sort((Bt,ks)=>(Bt.type==="relay"?1:0)-(ks.type==="relay"?1:0));let es=null;for(const Bt of hs){if(Bt.type==="relay"){const Us=Ng({relayUrl:Bt.relayUrl,serverId:Bt.serverId,hostEncPubJwk:Bt.hostEncPubJwk,...Bt.grant?{grant:Bt.grant}:{}});try{const fn=await Us.fetch("/api/client-auth/pairing/redeem",dt),hn=await Ot(fn);if(hn){es={kind:"relay",relay:{relayUrl:Bt.relayUrl,serverId:Bt.serverId,hostEncPubJwk:Bt.hostEncPubJwk},token:hn};break}}catch{}finally{Us.close()}continue}const ks=wa(Bt.url);if(ks)try{const Us=await fetch(`${ks}/api/client-auth/pairing/redeem`,dt),fn=await Ot(Us);if(fn){es={kind:"direct",url:ks,token:fn};break}}catch{}}if(!es){ze(t("desktopHostSwitcher.error.invalidUrl"));return}const Vs=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`host-${Date.now()}-${Math.random().toString(16).slice(2)}`,qs=K.candidates.find(Bt=>Bt.type==="relay"),Js=es.kind==="relay"?es.relay:qs?{relayUrl:qs.relayUrl,serverId:qs.serverId,hostEncPubJwk:qs.hostEncPubJwk}:void 0,Oa=K.candidates.filter(Bt=>Bt.type!=="relay").map(Bt=>wa(Bt.url)).find(Bt=>!!Bt),Gn=es.kind==="direct"?es.url:Oa,{token:za}=es,Rt=Gn||(Js?Sg(Js.serverId):null);if(!Rt){ze(t("desktopHostSwitcher.error.invalidUrl"));return}const ns={url:Rt,apiUrl:Gn||void 0,clientToken:za,...Js?{relay:Js}:{}},gn=re.find(Bt=>Js?Bt.relay?.serverId===Js.serverId:!Bt.relay&&wa(Bt.apiUrl||Bt.url)===Rt);if(gn){const Bt=re.map(ks=>ks.id===gn.id?{...ks,label:K.label||ks.label,...ns}:ks);await Yt(Bt,ye)}else await Yt([{id:Vs(),label:K.label||Ba(Rt),...ns},...re],ye);Ve(""),ze(null),ve(!1)},[He,ye,re,Yt,t]),dr=l.useCallback(async K=>{const ke=re.filter(dt=>dt.id!==K);await Yt(ke,ye===K?"local":ye),De===K&&Ke(null)},[ye,De,re,Yt]),ur=l.useCallback(K=>{Ke(K.id),Pe(K.label),se(K.apiUrl||K.url),Ee(K.clientToken||""),_e(Sy(K.requestHeaders)),ze(null)},[]),mr=l.useCallback(async()=>{if(!De)return;const K=hl(at);if(!K){ze(t("desktopHostSwitcher.error.invalidUrl"));return}const ke=K.persistedUrl,st=re.map(dt=>dt.id===De?{...dt,label:We.trim()||Ba(ke),url:ke,apiUrl:ke,clientToken:I.trim()||void 0,requestHeaders:Kr(Le)}:dt);await Yt(st,ye),Ke(null),K.redeemUrl&&Ur(K.redeemUrl)},[ye,Le,We,I,at,De,re,Yt,t]),di=l.useCallback(async()=>{const K=Nt.trim();if(!K){G.error(t("settings.remoteInstances.page.toast.sshCommandRequired"));return}const ke=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{await g(ke,K,Mt.trim()||t("settings.remoteInstances.sidebar.newSshInstanceName")),w(ke),ht(!1),Pt("ssh user@example.com"),cs(""),G.success(t("settings.remoteInstances.page.toast.instanceCreated"))}catch(st){G.error(t("settings.remoteInstances.sidebar.toast.createFailed"),{description:st instanceof Error?st.message:String(st)})}},[g,w,Nt,Mt,t]),pr=l.useCallback(async K=>{await Yt(re,K)},[re,Yt]);l.useEffect(()=>{if(!a||re.length===0)return;let K=!1;return Promise.all(re.map(async ke=>{const st=()=>Tg(ke.relay).catch(()=>({status:"unreachable",latencyMs:0}));if(ke.relay&&!ke.apiUrl)return[ke.id,await st()];const dt=wa(Cg(ke));if(!dt)return[ke.id,ke.relay?await st():{status:"unreachable",latencyMs:0}];const Ot=await Ig(dt,{clientToken:ke.clientToken||null,requestHeaders:ke.requestHeaders||null}).catch(()=>({status:"unreachable",latencyMs:0}));if(Ot.status==="unreachable"&&ke.relay){const hs=await st();if(hs.status==="ok")return[ke.id,hs]}return[ke.id,Ot]})).then(ke=>{K||he(Object.fromEntries(ke))}),()=>{K=!0}},[re,a]);const Ks=l.useCallback(async K=>{if(n){K?.silent||mt(!0),K?.silent||qe(null);try{const[ke,st]=await Promise.all([n.listClients(),n.listPendingPairings().catch(()=>null)]);ct(ke),st&<(st)}catch(ke){K?.silent||qe(ke instanceof Error?ke.message:String(ke))}finally{K?.silent||mt(!1)}}},[n]),la=l.useRef(!1);l.useEffect(()=>{if(!(!me||$e!=="result"||!ft)){if(ut.some(K=>K.id===ft)){la.current=!0;return}la.current&&(vt(null),Je(!1),Xe.some(K=>K.pairingId===ft)&&G.success(t("settings.remoteInstances.clientAuth.addDevice.connectedToast")))}},[me,$e,ft,ut,Xe,t]);const gr=l.useCallback(async K=>{if(n)try{await n.cancelPairing(K),lt(ke=>ke.filter(st=>st.id!==K)),await Ks({silent:!0})}catch(ke){qe(ke instanceof Error?ke.message:String(ke))}},[n,Ks]);l.useEffect(()=>{if(!n)return;Ks();const K=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ks({silent:!0})},5e3);return()=>window.clearInterval(K)},[n,Ks]);const ui=l.useCallback(async()=>{if(n?.getPairingTransports)try{const dt=await n.getPairingTransports();return{localUrl:dt.local,lanUrl:dt.lan,relayAvailable:dt.relayAvailable}}catch{}const K=su(),ke=K?`http://127.0.0.1:${K}`:jc(window.location.origin)?window.location.origin:null;let st=null;try{const dt=wa(await Cy());st=dt&&!jc(dt)?dt:null}catch{}return{localUrl:ke,lanUrl:st,relayAvailable:!0}},[n]),fr=l.useCallback(async()=>{qe(null),nt(null),de(null),we(!1),vt(null),et("configure"),is(!0),Je(!0);const K=await ui();Ce(K),_t(K.relayAvailable?"relay":K.lanUrl?"lan":"local")},[ui]),hr=l.useCallback(async()=>{if(!(!n?.createPairingSession||!$t)){qe(null),Dt(!0);try{const K=xt.trim()||void 0;let ke,st,dt=!0;Qt==="local"?(ke=$t.localUrl??void 0,st=!1):Qt==="lan"?(ke=$t.lanUrl??void 0,st=as):as&&$t.lanUrl?(ke=$t.lanUrl,st=!0):(dt=!1,st=!0);const{pairing:Ot,server:hs}=await n.createPairingSession({label:K,allowedClientKinds:["mobile","desktop"],serverUrl:ke,includeRelay:st,includeDirect:dt}),es=Pg({pairingId:Ot.id,secret:Ot.secret,label:hs.label,fingerprint:Ot.fingerprint??void 0,expiresAt:Ot.expiresAt,candidates:hs.candidates}),Vs=Ag(es);nt(Vs),de(await bd.toDataURL(Vs,{width:1024,margin:2,errorCorrectionLevel:"L"})),we(!1),la.current=!1,vt(Ot.id),et("result"),await Ks({silent:!0})}catch(K){qe(K instanceof Error?K.message:String(K))}finally{Dt(!1)}}},[n,$t,Qt,as,xt,Ks]),xr=l.useCallback(()=>{Ze&&Zn(Ze).then(K=>{K.ok&&(we(!0),window.setTimeout(()=>we(!1),2e3))})},[Ze]),br=l.useCallback(async K=>{if(!n)return;const ke=K.clientKind==="desktop-local";qe(null);try{if(await n.revokeClient(K.id),ke&&ss()){const st=await gl();await fl({hosts:st.hosts,defaultHostId:st.defaultHostId,initialHostChoiceCompleted:st.initialHostChoiceCompleted,localClientToken:null}),ct(dt=>dt.map(Ot=>Ot.id===K.id?{...Ot,revokedAt:new Date().toISOString()}:Ot)),Eg({apiBaseUrl:La(),clientToken:null,runtimeKey:"local"});return}await Ks()}catch(st){qe(st instanceof Error?st.message:String(st))}},[n,Ks]),yr=l.useCallback(async()=>{if(n){qe(null);try{await n.purgeRevokedClients(),await Ks()}catch(K){qe(K instanceof Error?K.message:String(K))}}},[n,Ks]);l.useEffect(()=>{R(j)},[j]),l.useEffect(()=>{if(!F)return;const K=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||b()},2e3);return()=>{window.clearInterval(K)}},[b,F]),l.useEffect(()=>{let K=null,ke=Date.now();const st=()=>{const Ot=Date.now();Ot-ke>=1e3&&(ue(Ot),ke=Ot),K=requestAnimationFrame(st)};(typeof document>"u"||document.visibilityState==="visible")&&(K=requestAnimationFrame(st));const dt=()=>{document.visibilityState==="visible"&&K===null?K=requestAnimationFrame(st):document.visibilityState!=="visible"&&K!==null&&(cancelAnimationFrame(K),K=null)};return document.addEventListener("visibilitychange",dt),()=>{document.removeEventListener("visibilitychange",dt),K!==null&&cancelAnimationFrame(K)}},[]);const Fs=F?r[F]:null,en=Fs?.phase,ca=en==="ready",un=en==="degraded",Tn=tu(en),Rn=ca||(Tn||un),vr=Fs?Math.max(0,ee-Fs.updatedAtMs):0,da=un&&vr>12e3,wr=l.useMemo(()=>!y||!j?!1:JSON.stringify(y)!==JSON.stringify(j),[y,j]),ms=l.useCallback(K=>{R(ke=>ke&&K(ke))},[]),jr=l.useCallback(async()=>{if(!y)return;const K=Iy(y);if(!K.sshCommand.trim()){G.error(t("settings.remoteInstances.page.toast.sshCommandRequired"));return}if(!(K.localForward.bindHost==="0.0.0.0"&&!window.confirm(t("settings.remoteInstances.page.confirm.bindAllInterfaces")))){if(K.auth.sshPassword?.enabled&&K.auth.sshPassword.value?.trim()&&K.auth.sshPassword.store!=="settings"){const ke=window.confirm(t("settings.remoteInstances.page.confirm.storeSshPasswordPlaintext"));K.auth.sshPassword.store=ke?"settings":"never",ke||(K.auth.sshPassword.value=void 0)}if(K.auth.openchamberPassword?.enabled&&K.auth.openchamberPassword.value?.trim()&&K.auth.openchamberPassword.store!=="settings"){const ke=window.confirm(t("settings.remoteInstances.page.confirm.storeUiPasswordPlaintext"));K.auth.openchamberPassword.store=ke?"settings":"never",ke||(K.auth.openchamberPassword.value=void 0)}try{await h(K),G.success(t("settings.remoteInstances.page.toast.instanceSaved"))}catch(ke){G.error(t("settings.remoteInstances.page.toast.saveFailed"),{description:ke instanceof Error?ke.message:String(ke)})}}},[y,t,h]),ua=l.useCallback(async(K,ke)=>{const st=`ssh-${Date.now()}-${Math.random().toString(16).slice(2)}`;try{return await g(st,`ssh ${ke}`,K),w(st),G.success(t("settings.remoteInstances.page.toast.instanceCreated")),!0}catch(dt){return G.error(t("settings.remoteInstances.sidebar.toast.createFailed"),{description:dt instanceof Error?dt.message:String(dt)}),!1}},[g,w,t]),mn=l.useCallback(()=>{W||(Y(null),S(""))},[W]),ma=l.useCallback((K,ke)=>{if(ke){Y(K),S(vy(K));return}ua(K,K)},[ua]),pa=l.useCallback(async()=>{const K=U,ke=X.trim();if(K){if(!ke){G.error(t("settings.remoteInstances.page.toast.destinationRequired"));return}Z(!0);try{await ua(K,ke)&&(Y(null),S(""))}finally{Z(!1)}}},[ua,X,U,t]),Dn=l.useCallback(async()=>{if(j)try{await v(j.id);return}catch(K){if(!fy(K)||!window.confirm(t("settings.remoteInstances.sidebar.confirm.localPortInUseRetry")))throw K;const st={...j,localForward:{...j.localForward,preferredLocalPort:So()}};await h(st),await v(st.id),G.success(t("settings.remoteInstances.sidebar.toast.retriedWithRandomPort"))}},[v,j,t,h]),pn=l.useCallback(async K=>(await kp(K,600)).map(st=>ky(st)),[]),Oe=l.useCallback(async()=>{if(y){B(!0),k(!0),M(null);try{const K=await pn(y.id);V(K)}catch(K){V([]),M(K instanceof Error?K.message:String(K))}finally{k(!1)}}},[y,pn]);l.useEffect(()=>{if(!_||!y)return;let K=!1;const ke=async()=>{try{const dt=await pn(y.id);K||(V(dt),M(null))}catch(dt){K||M(dt instanceof Error?dt.message:String(dt))}};ke();const st=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||ke()},1e3);return()=>{K=!0,window.clearInterval(st)}},[y,_,pn]);const ts=l.useMemo(()=>O.join(`
|
|
28
|
+
`),[O]),mi=l.useCallback(()=>{if(!ts.trim()){G.error(t("settings.remoteInstances.page.toast.noLogsToCopy"));return}Zn(ts).then(K=>{K.ok&&G.success(t("settings.remoteInstances.page.toast.logsCopied"))})},[ts,t]),pi=l.useCallback(async()=>{if(y)try{await Np(y.id),V([]),G.success(t("settings.remoteInstances.page.toast.logsCleared"))}catch(K){G.error(t("settings.remoteInstances.page.toast.clearLogsFailed"),{description:K instanceof Error?K.message:String(K)})}},[y,t]),gi=l.useCallback(async()=>{if(!Fs?.localUrl){G.error(t("settings.remoteInstances.page.toast.instanceUrlUnavailable"));return}const K=Fs.localUrl.trim();if(!K){G.error(t("settings.remoteInstances.page.toast.instanceUrlUnavailable"));return}Ur(K)},[Fs?.localUrl,t]),fi=l.useCallback(()=>{if(!y)return;$(!0),(Rn?N(y.id):Dn()).catch(ke=>{const st=Rn?ca?"settings.remoteInstances.page.toast.disconnectFailed":"settings.remoteInstances.page.toast.cancelConnectionFailed":"settings.remoteInstances.page.toast.connectFailed";G.error(t(st),{description:ke instanceof Error?ke.message:String(ke)})}).finally(()=>{$(!1)})},[Rn,Dn,N,y,ca,t]),hi=l.useCallback(()=>{if(!y||Tn)return;J(!0),(un?N(y.id).then(()=>Dn()):P(y.id)).catch(ke=>{G.error(t("settings.remoteInstances.page.toast.retryFailed"),{description:ke instanceof Error?ke.message:String(ke)})}).finally(()=>{J(!1)})},[Dn,N,y,Tn,un,P,t]),xi=t(Tn?"settings.remoteInstances.page.actions.connecting":un?da?"settings.remoteInstances.page.actions.reconnectNow":"settings.remoteInstances.page.actions.reconnecting":"settings.remoteInstances.sidebar.actions.retry"),bi=!z&&!H&&(en==="error"||en==="idle"||!en||un&&da)&&!Tn,kr=t(ca?"settings.remoteInstances.sidebar.actions.disconnect":Rn?"settings.remoteInstances.page.actions.cancel":"settings.remoteInstances.sidebar.actions.connect");if(!y)return s.jsxs(us,{title:t("settings.page.remoteInstances.title"),children:[n?s.jsxs(ot,{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(Q,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{fr()},children:[s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.clientAuth.actions.addDevice")]})}),s.jsxs("div",{className:"space-y-2.5",children:[jt>0?s.jsx("div",{className:"flex justify-end",children:s.jsx(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{yr()},children:t("settings.remoteInstances.clientAuth.actions.clearRevoked")})}):null,rt&&Xe.length===0&&ut.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.state.loading")}):Xe.length===0&&ut.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.state.empty")}):s.jsxs(s.Fragment,{children:[ut.map(K=>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:K.label||t("settings.remoteInstances.clientAuth.field.labelPlaceholder")}),K.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(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{gr(K.id)},children:t("settings.common.actions.cancel")})]},`pending-${K.id}`)),Xe.map(K=>{const ke=K.clientKind==="desktop-local",st=K.lastUsedAt?Date.parse(K.lastUsedAt):Number.NaN,dt=!K.revokedAt&&(ke||Number.isFinite(st)&&Date.now()-st<9e4),Ot=K.revokedAt?t("settings.remoteInstances.clientAuth.state.revoked"):dt?K.lastTransport==="relay"&&!ke?t("settings.remoteInstances.clientAuth.state.connectedRelay"):t("settings.remoteInstances.clientAuth.state.connectedDirect"):Number.isFinite(st)?t("settings.remoteInstances.clientAuth.lastUsed",{date:Sp(st,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:le("h-2 w-2 shrink-0 rounded-full",K.revokedAt?"bg-muted-foreground/20":dt?"bg-[var(--status-success)]":"bg-muted-foreground/30")}),s.jsx("p",{className:"typography-ui-label text-foreground truncate",children:K.label}),bc(K.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:bc(K.devicePlatform)}):null,ke?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:le("typography-micro truncate",dt&&!K.revokedAt?"text-[var(--status-success)]":"text-muted-foreground"),children:Ot})]})}),s.jsx(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{br(K)},disabled:!!K.revokedAt,children:t("settings.remoteInstances.clientAuth.actions.revoke")})]},K.id)})]})]}),Se?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Se}):null]}):null,a?s.jsxs(ot,{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(Q,{type:"button",size:"xs",className:"!font-normal",onClick:()=>ve(!0),disabled:pe,children:t("settings.remoteInstances.direct.import.action")}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ge(!0),disabled:pe,children:[s.jsx(L,{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:ae?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.direct.state.loading")}):re.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.direct.state.empty")}):re.map(K=>{const ke=be[K.id],st=ke?ke.status==="ok"?"desktopHostSwitcher.status.connected":ke.status==="auth"?"desktopHostSwitcher.status.authRequired":ke.status==="update-recommended"?"desktopHostSwitcher.status.updateRecommended":ke.status==="incompatible"?"desktopHostSwitcher.status.incompatible":ke.status==="wrong-service"?"desktopHostSwitcher.status.wrongService":"desktopHostSwitcher.status.unreachable":"desktopHostSwitcher.status.checking",dt=ke?.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:le("h-2 w-2 shrink-0 rounded-full",ke?dt?"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:Ba(K.label)}),ye===K.id?s.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:t("desktopHostSwitcher.header.default")}):null,s.jsxs("span",{className:le("typography-micro shrink-0",dt?"text-[var(--status-success)]":"text-muted-foreground"),children:[t(st),dt&&typeof ke?.latencyMs=="number"?t("desktopHostSwitcher.status.ping",{ms:Math.max(0,Math.round(ke.latencyMs))}):""]})]}),s.jsx("p",{className:le("typography-micro text-muted-foreground truncate",K.apiUrl&&"font-mono"),children:K.relay&&!K.apiUrl?t("mobile.connect.relay.badge"):Ba(K.apiUrl||K.url)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{pr(K.id)},disabled:pe||ye===K.id,"aria-label":t("desktopHostSwitcher.actions.setAsDefaultAria"),children:ye===K.id?s.jsx(L,{name:"star-fill",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"star",className:"h-3.5 w-3.5"})}),K.relay&&!K.apiUrl?null:s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>ur(K),disabled:pe,children:[s.jsx(L,{name:"pencil",className:"h-3.5 w-3.5"}),t("desktopHostSwitcher.actions.edit")]}),s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{dr(K.id)},disabled:pe,children:[s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.delete")]})]})]})},K.id)})}),Ue?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Ue}):null]}):null,a?s.jsx(Lt,{open:Be,onOpenChange:Ge,children:s.jsxs(Ft,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.remoteInstances.direct.actions.add")}),s.jsx(qt,{children:t("settings.remoteInstances.direct.addDialog.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:K=>{K.preventDefault(),oa()},children:[s.jsx(tt,{className:"h-8",value:te,onChange:K=>ne(K.target.value),placeholder:t("settings.remoteInstances.direct.field.labelPlaceholder"),disabled:pe}),s.jsx(tt,{className:"h-8",value:oe,onChange:K=>Ae(K.target.value),placeholder:t("settings.remoteInstances.direct.field.urlPlaceholder"),disabled:pe,autoFocus:!0}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(tt,{className:"h-8",value:je,onChange:K=>Ie(K.target.value),placeholder:t("settings.remoteInstances.direct.field.tokenPlaceholder"),type:"password",disabled:pe}),s.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:t("settings.remoteInstances.direct.note")})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(An,{children:t("settings.remoteInstances.direct.headers.title")}),s.jsx(Ht,{children:t("settings.remoteInstances.direct.headers.description")})]}),Te.map(K=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(tt,{className:"h-8 font-mono text-xs",value:K.name,onChange:ke=>Me(st=>st.map(dt=>dt.id===K.id?{...dt,name:ke.target.value}:dt)),placeholder:t("settings.remoteInstances.direct.headers.field.namePlaceholder"),disabled:pe}),s.jsx(tt,{className:"h-8 font-mono text-xs",value:K.value,onChange:ke=>Me(st=>st.map(dt=>dt.id===K.id?{...dt,value:ke.target.value}:dt)),placeholder:t("settings.remoteInstances.direct.headers.field.valuePlaceholder"),type:"password",disabled:pe}),s.jsx("button",{type:"button",onClick:()=>Me(ke=>ke.filter(st=>st.id!==K.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":t("settings.remoteInstances.direct.headers.removeAria"),disabled:pe,children:s.jsx(L,{name:"close",className:"h-4 w-4"})})]},K.id)),s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>Me(K=>[...K,Co()]),disabled:pe,children:[s.jsx(L,{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(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ge(!1),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:pe||!oe.trim(),children:t("settings.remoteInstances.direct.actions.add")})]})]})]})}):null,a?s.jsx(Lt,{open:!!De,onOpenChange:K=>{K||Ke(null)},children:s.jsxs(Ft,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("desktopHostSwitcher.actions.edit")}),s.jsx(qt,{children:t("settings.remoteInstances.direct.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:K=>{K.preventDefault(),mr()},children:[s.jsx(tt,{className:"h-8",value:We,onChange:K=>Pe(K.target.value),placeholder:t("settings.remoteInstances.direct.field.labelPlaceholder"),disabled:pe}),s.jsx(tt,{className:"h-8",value:at,onChange:K=>se(K.target.value),placeholder:t("settings.remoteInstances.direct.field.urlPlaceholder"),disabled:pe,autoFocus:!0}),s.jsx(tt,{className:"h-8",value:I,onChange:K=>Ee(K.target.value),placeholder:t("settings.remoteInstances.direct.field.tokenPlaceholder"),type:"password",disabled:pe}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(An,{children:t("settings.remoteInstances.direct.headers.title")}),s.jsx(Ht,{children:t("settings.remoteInstances.direct.headers.description")})]}),Le.map(K=>s.jsxs("div",{className:"flex w-full gap-2",children:[s.jsx(tt,{className:"h-8 font-mono text-xs",value:K.name,onChange:ke=>_e(st=>st.map(dt=>dt.id===K.id?{...dt,name:ke.target.value}:dt)),placeholder:t("settings.remoteInstances.direct.headers.field.namePlaceholder"),disabled:pe}),s.jsx(tt,{className:"h-8 font-mono text-xs",value:K.value,onChange:ke=>_e(st=>st.map(dt=>dt.id===K.id?{...dt,value:ke.target.value}:dt)),placeholder:t("settings.remoteInstances.direct.headers.field.valuePlaceholder"),type:"password",disabled:pe}),s.jsx("button",{type:"button",onClick:()=>_e(ke=>ke.filter(st=>st.id!==K.id)),className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-[var(--status-error-background)] hover:text-[var(--status-error)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":t("settings.remoteInstances.direct.headers.removeAria"),disabled:pe,children:s.jsx(L,{name:"close",className:"h-4 w-4"})})]},K.id)),s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>_e(K=>[...K,Co()]),disabled:pe,children:[s.jsx(L,{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(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Ke(null),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:pe,children:t("settings.common.actions.saveChanges")})]})]})]})}):null,a?s.jsx(Lt,{open:Fe,onOpenChange:ve,children:s.jsxs(Ft,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.remoteInstances.direct.import.action")}),s.jsx(qt,{children:t("settings.remoteInstances.direct.import.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:K=>{K.preventDefault(),Hn()},children:[s.jsx(tt,{className:"h-8",value:He,onChange:K=>Ve(K.target.value),placeholder:t("settings.remoteInstances.direct.import.placeholder"),disabled:pe,autoFocus:!0}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>ve(!1),disabled:pe,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:pe||!He.trim(),children:t("settings.remoteInstances.direct.import.action")})]})]})]})}):null,s.jsx(Lt,{open:me,onOpenChange:Je,children:s.jsxs(Ft,{className:$e==="result"?"sm:max-w-lg":"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t($e==="result"?"settings.remoteInstances.clientAuth.qrDialogTitle":"settings.remoteInstances.clientAuth.actions.addDevice")}),s.jsx(qt,{children:t($e==="result"?"settings.remoteInstances.clientAuth.qrScanHint":"settings.remoteInstances.clientAuth.addDevice.subtitle")})]}),$e==="configure"?s.jsxs("form",{className:"space-y-4",onSubmit:K=>{K.preventDefault(),hr()},children:[s.jsx(tt,{className:"h-8",value:xt,onChange:K=>It(K.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:!!$t?.relayAvailable},{key:"lan",label:t("settings.remoteInstances.clientAuth.addDevice.transport.lan"),hint:t("settings.remoteInstances.clientAuth.addDevice.transport.lanHint"),available:!!$t?.lanUrl},{key:"local",label:t("settings.remoteInstances.clientAuth.addDevice.transport.local"),hint:t("settings.remoteInstances.clientAuth.addDevice.transport.localHint"),available:!!$t?.localUrl}].map(K=>{const ke=Qt===K.key;return s.jsxs("div",{className:le("flex items-start gap-2 py-0.5",K.available?"cursor-pointer":"opacity-45"),onClick:()=>{K.available&&_t(K.key)},role:"presentation",children:[s.jsx(ir,{checked:ke,disabled:!K.available,onChange:()=>_t(K.key),ariaLabel:K.label,className:"mt-0.5"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:le("typography-ui-label font-normal",ke?"text-foreground":"text-foreground/70"),children:K.label}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:K.hint})]})]},K.key)})}),Qt==="lan"?s.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[s.jsx(Pn,{checked:as,onChange:is,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,Qt==="relay"&&$t?.lanUrl?s.jsxs("label",{className:"flex w-fit cursor-pointer items-center gap-2 pt-1",children:[s.jsx(Pn,{checked:as,onChange:is,ariaLabel:t("settings.remoteInstances.clientAuth.addDevice.fallback.preferLocal")}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:t("settings.remoteInstances.clientAuth.addDevice.fallback.preferLocal")})]}):null]}),Se?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:Se}):null,s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>Je(!1),disabled:bt,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:bt||!$t,children:t("settings.remoteInstances.clientAuth.addDevice.create")})]})]}):s.jsxs("div",{className:"space-y-3",children:[St?s.jsx("div",{className:"flex justify-center",children:s.jsx("img",{src:St,alt:t("settings.remoteInstances.clientAuth.qrAlt"),className:"w-full max-w-[420px] rounded-md bg-white p-4"})}):null,Ze?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:Ze}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal shrink-0",onClick:xr,children:[s.jsx(L,{name:ie?"check":"file-copy",className:le("h-3.5 w-3.5",ie&&"text-[var(--status-success)]")}),t(ie?"settings.remoteInstances.clientAuth.actions.copied":"settings.common.actions.copyAll")]})]}):null,s.jsx("div",{className:"flex justify-end",children:s.jsx(Q,{type:"button",size:"xs",className:"!font-normal",onClick:()=>Je(!1),children:t("settings.remoteInstances.clientAuth.addDevice.done")})})]})]})}),a?s.jsx(ot,{title:t("settings.remoteInstances.sidebar.title"),description:t("settings.remoteInstances.sidebar.total",{count:i.length}),headerAction:s.jsxs(Q,{type:"button",size:"xs",className:"!font-normal",onClick:()=>ht(!0),children:[s.jsx(L,{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(K=>{const ke=r[K.id],st=K.nickname?.trim()||K.sshParsed?.destination||K.id,dt=ke?.phase,Ot=dt==="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 ${vc(dt)}`}),s.jsx("p",{className:"typography-ui-label text-foreground truncate",children:st})]}),s.jsxs("p",{className:"typography-micro text-muted-foreground truncate",children:[t(yc(dt)),ke?.localUrl?` · ${ke.localUrl}`:""]})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{(Ot?N(K.id):v(K.id)).catch(es=>G.error(t(Ot?"settings.remoteInstances.sidebar.toast.disconnectFailed":"settings.remoteInstances.sidebar.toast.connectFailed"),{description:es instanceof Error?es.message:String(es)}))},children:[Ot?s.jsx(L,{name:"stop",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"plug-2",className:"h-3.5 w-3.5"}),t(Ot?"settings.remoteInstances.sidebar.actions.disconnect":"settings.remoteInstances.sidebar.actions.connect")]}),s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>w(K.id),children:[s.jsx(L,{name:"pencil",className:"h-3.5 w-3.5"}),t("desktopHostSwitcher.actions.edit")]}),s.jsxs(Q,{type:"button",variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{window.confirm(t("settings.remoteInstances.page.confirm.removeInstance"))&&x(K.id).catch(es=>G.error(t("settings.remoteInstances.page.toast.removeInstanceFailed"),{description:es instanceof Error?es.message:String(es)}))},children:[s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.common.actions.delete")]})]})]},K.id)})}):null,a?s.jsx(Lt,{open:Qe,onOpenChange:ht,children:s.jsxs(Ft,{className:"sm:max-w-lg",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.remoteInstances.sidebar.actions.addSshInstance")}),s.jsx(qt,{children:t("settings.remoteInstances.page.section.instanceDescription")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:K=>{K.preventDefault(),di()},children:[s.jsx(tt,{className:"h-8",value:Mt,onChange:K=>cs(K.target.value),placeholder:t("settings.remoteInstances.page.field.nicknamePlaceholder"),disabled:p}),s.jsx(tt,{className:"h-8",value:Nt,onChange:K=>Pt(K.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(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>ht(!1),disabled:p,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:p||!Nt.trim(),children:t("settings.common.actions.create")})]})]})]})}):null,a?s.jsx(ot,{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(K=>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:[K.host,K.pattern?` ${t("settings.remoteInstances.page.import.patternSuffix")}`:""]}),s.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:K.sshCommand})]}),s.jsx(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{ma(K.host,K.pattern)},children:t("settings.common.actions.import")})]},`${K.source}:${K.host}`))})}):null,s.jsx(Lt,{open:!!U,onOpenChange:K=>{K||mn()},children:s.jsxs(Ft,{className:"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.remoteInstances.page.patternDialog.title")}),s.jsx(qt,{children:U?t("settings.remoteInstances.page.patternDialog.descriptionWithHost",{host:U}):t("settings.remoteInstances.page.patternDialog.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:K=>{K.preventDefault(),pa()},children:[s.jsx(tt,{value:X,onChange:K=>S(K.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(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:mn,disabled:W,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:W,children:t("settings.remoteInstances.page.actions.create")})]})]})]})})]});const Wn=y.remoteOpenchamber.mode==="managed",Fa=y.nickname?.trim()||y.sshParsed?.destination||y.id;return s.jsx(Lt,{open:!!y,onOpenChange:K=>{K||w(null)},children:s.jsxs(Ft,{className:"sm:max-w-4xl max-h-[90vh] overflow-auto",children:[s.jsxs("div",{className:"mb-6 px-1",children:[s.jsx("h1",{className:`${yo} truncate`,children:Fa}),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 ${vc(en)}`}),s.jsx("span",{children:t(yc(en))}),Fs?.localUrl?s.jsx("span",{className:"font-mono text-foreground/80",children:Fs.localUrl}):null,da?s.jsx("span",{children:t("settings.remoteInstances.page.status.reconnectStale")}):null]})]}),s.jsxs(ot,{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(Q,{type:"button",variant:Rn?"outline":"default",size:"xs",className:"!font-normal",onClick:fi,disabled:z||H,children:[Rn?s.jsx(L,{name:"stop",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"plug-2",className:"h-3.5 w-3.5"}),kr]}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:hi,disabled:!bi,children:[s.jsx(L,{name:"refresh",className:`h-3.5 w-3.5 ${Tn||un&&!da?"animate-spin":""}`}),xi]}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Oe()},children:[s.jsx(L,{name:"terminal-window",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.logs")]}),s.jsxs(Q,{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(y.id).then(()=>{w(null),G.success(t("settings.remoteInstances.page.toast.instanceRemoved"))}).catch(ke=>{G.error(t("settings.remoteInstances.page.toast.removeInstanceFailed"),{description:ke instanceof Error?ke.message:String(ke)})})},children:[s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.sidebar.actions.remove")]})]}),Fs?.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:Fs.localUrl})]}):null]}),s.jsxs(ot,{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(tt,{className:"h-7 md:max-w-xl",value:y.sshCommand,onChange:K=>ms(ke=>({...ke,sshCommand:K.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(tt,{className:"h-7 md:max-w-sm",value:y.nickname||"",onChange:K=>ms(ke=>({...ke,nickname:K.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(Cs,{containerClassName:"w-fit",min:5,max:240,step:1,className:"w-16 tabular-nums",value:y.connectionTimeoutSec,onValueChange:K=>{ms(ke=>({...ke,connectionTimeoutSec:Number.isFinite(K)?K:ke.connectionTimeoutSec}))}})]})]}),s.jsxs(ot,{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(bn,{label:t("settings.remoteInstances.page.field.mode"),hint:t("settings.remoteInstances.page.field.modeHint")})}),s.jsxs(At,{value:y.remoteOpenchamber.mode,onValueChange:K=>ms(ke=>({...ke,remoteOpenchamber:{...ke.remoteOpenchamber,mode:K==="external"?"external":"managed"}})),children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Vt,{placeholder:t("settings.remoteInstances.page.field.modePlaceholder")})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"managed",children:t("settings.remoteInstances.page.field.modeManaged")}),s.jsx(yt,{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(bn,{label:t("settings.remoteInstances.page.field.preferredRemotePort"),hint:t("settings.remoteInstances.page.field.preferredRemotePortHint")})}),s.jsx(Cs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:y.remoteOpenchamber.preferredPort,onValueChange:K=>{ms(ke=>({...ke,remoteOpenchamber:{...ke.remoteOpenchamber,preferredPort:Number.isFinite(K)&&K>0?K:void 0}}))},onClear:()=>{ms(K=>({...K,remoteOpenchamber:{...K.remoteOpenchamber,preferredPort:void 0}}))},emptyLabel:t("settings.remoteInstances.page.field.auto")})]}),Wn?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(bn,{label:t("settings.remoteInstances.page.field.installMethod"),hint:t("settings.remoteInstances.page.field.installMethodHint")})}),s.jsxs(At,{value:y.remoteOpenchamber.installMethod,onValueChange:K=>ms(ke=>({...ke,remoteOpenchamber:{...ke.remoteOpenchamber,installMethod:K==="npm"||K==="download_release"||K==="upload_bundle"?K:"bun"}})),children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Vt,{placeholder:t("settings.remoteInstances.page.field.selectInstallMethodPlaceholder")})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"bun",children:"bun"}),s.jsx(yt,{value:"npm",children:"npm"}),s.jsx(yt,{value:"download_release",children:t("settings.remoteInstances.page.field.installMethodDownloadRelease")}),s.jsx(yt,{value:"upload_bundle",children:t("settings.remoteInstances.page.field.installMethodUploadBundle")})]})]})]}):null,Wn?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(bn,{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(Xi,{checked:y.remoteOpenchamber.keepRunning,onCheckedChange:K=>ms(ke=>({...ke,remoteOpenchamber:{...ke.remoteOpenchamber,keepRunning:K}}))})})]}):null]}),s.jsxs(ot,{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(bn,{label:t("settings.remoteInstances.page.field.bindHost"),hint:t("settings.remoteInstances.page.field.bindHostHint")})}),s.jsxs(At,{value:y.localForward.bindHost,onValueChange:K=>{K==="0.0.0.0"&&!window.confirm(t("settings.remoteInstances.page.confirm.bindAllInterfaces"))||ms(ke=>({...ke,localForward:{...ke.localForward,bindHost:K==="localhost"||K==="0.0.0.0"?K:"127.0.0.1"}}))},children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Vt,{placeholder:t("settings.remoteInstances.page.field.selectBindHostPlaceholder")})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"127.0.0.1",children:"127.0.0.1"}),s.jsx(yt,{value:"localhost",children:"localhost"}),s.jsx(yt,{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(bn,{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(Cs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-20 tabular-nums",value:y.localForward.preferredLocalPort,onValueChange:K=>{ms(ke=>({...ke,localForward:{...ke.localForward,preferredLocalPort:Number.isFinite(K)&&K>0?K:void 0}}))},onClear:()=>{ms(K=>({...K,localForward:{...K.localForward,preferredLocalPort:void 0}}))},emptyLabel:t("settings.remoteInstances.page.field.auto")}),s.jsx(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal h-7 w-7 px-0",title:t("settings.remoteInstances.page.actions.pickRandomPort"),onClick:()=>ms(K=>({...K,localForward:{...K.localForward,preferredLocalPort:So()}})),children:s.jsx(L,{name:"shuffle",className:"h-3.5 w-3.5"})})]})]})]}),s.jsxs(ot,{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(tt,{className:"h-7 md:max-w-sm",type:"password",value:y.auth.sshPassword?.value||"",onChange:K=>ms(ke=>({...ke,auth:{...ke.auth,sshPassword:{enabled:K.target.value.trim().length>0,value:K.target.value,store:ke.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(tt,{className:"h-7 md:max-w-sm",type:"password",value:y.auth.openchamberPassword?.value||"",onChange:K=>ms(ke=>({...ke,auth:{...ke.auth,openchamberPassword:{enabled:K.target.value.trim().length>0,value:K.target.value,store:ke.auth.openchamberPassword?.store||"never"}}})),placeholder:t("settings.remoteInstances.page.field.uiPasswordPlaceholder")})]})]}),s.jsxs(ot,{title:t("settings.remoteInstances.page.section.portForwards"),info:t("settings.remoteInstances.page.section.portForwardsDescription"),contentClassName:"space-y-2",children:[y.portForwards.length===0?s.jsx("p",{className:"typography-micro text-muted-foreground/80",children:t("settings.remoteInstances.page.empty.noExtraForwards")}):null,y.portForwards.map((K,ke)=>{const st=Rt=>{ms(ns=>({...ns,portForwards:ns.portForwards.map((gn,Bt)=>Bt===ke?Rt(gn):gn)}))},dt=K.type==="remote"?"Local target":"Local listen",Ot=K.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.",hs=K.type==="remote"?"Remote listen":"Remote target",es=K.type==="remote"?"Remote host and port where SSH creates the -R listener.":"Remote host and port that receives traffic from local -L listener.",Vs=wc(K.localHost||"localhost",K.localPort),qs=wc(K.remoteHost||"localhost",K.remotePort),Js=K.type==="local"&&typeof K.localPort=="number"&&K.localPort>0,Oa=Js?`http://${jy(K.localHost)}:${K.localPort}`:"",Gn=!!A[K.id],za=K.type==="local"?t("settings.remoteInstances.page.forwardType.local"):K.type==="remote"?t("settings.remoteInstances.page.forwardType.remote"):t("settings.remoteInstances.page.forwardType.dynamic");return s.jsxs(sa,{open:Gn,onOpenChange:Rt=>{C(ns=>({...ns,[K.id]:Rt}))},className:`${ke>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(na,{className:"flex items-center gap-2 group",children:[s.jsx(L,{name:"arrow-down-s",className:`h-4 w-4 text-muted-foreground transition-transform ${Gn?"rotate-180":""}`}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:by(K)}),s.jsx("span",{className:"typography-micro text-muted-foreground/70 shrink-0",children:za})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Xi,{checked:K.enabled,onCheckedChange:Rt=>st(ns=>({...ns,enabled:Rt})),"aria-label":t("settings.remoteInstances.page.actions.enableForwardAria")}),s.jsx(Q,{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:()=>ms(Rt=>({...Rt,portForwards:Rt.portForwards.filter(ns=>ns.id!==K.id)})),children:s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"})})]})]}),s.jsx(aa,{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(bn,{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(wy(K.type))})]})})}),s.jsxs(At,{value:K.type,onValueChange:Rt=>st(ns=>({...ns,type:Rt==="dynamic"||Rt==="remote"?Rt:"local"})),children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[140px]",children:s.jsx(Vt,{placeholder:t("settings.remoteInstances.page.field.typePlaceholder")})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"local",children:t("settings.remoteInstances.page.forwardType.local")}),s.jsx(yt,{value:"remote",children:t("settings.remoteInstances.page.forwardType.remote")}),s.jsx(yt,{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(bn,{label:dt,hint:Ot})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(tt,{className:"h-7 w-32",value:K.localHost||"127.0.0.1",onChange:Rt=>st(ns=>({...ns,localHost:Rt.target.value})),placeholder:t("settings.remoteInstances.page.field.localHostPlaceholder")}),s.jsx("span",{className:"text-muted-foreground",children:":"}),s.jsx(Cs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:K.localPort,onValueChange:Rt=>{st(ns=>({...ns,localPort:Number.isFinite(Rt)&&Rt>0?Rt:void 0}))},onClear:()=>{st(Rt=>({...Rt,localPort:void 0}))},emptyLabel:t("settings.remoteInstances.page.field.auto")})]})]}),K.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(bn,{label:hs,hint:es})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(tt,{className:"h-7 w-32",value:K.remoteHost||"",onChange:Rt=>st(ns=>({...ns,remoteHost:Rt.target.value})),placeholder:t("settings.remoteInstances.page.field.remoteHostPlaceholder")}),s.jsx("span",{className:"text-muted-foreground",children:":"}),s.jsx(Cs,{containerClassName:"w-fit",min:1,max:65535,step:1,className:"w-16 tabular-nums",value:K.remotePort,onValueChange:Rt=>{st(ns=>({...ns,remotePort:Number.isFinite(Rt)&&Rt>0?Rt:void 0}))},onClear:()=>{st(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:K.type==="dynamic"?s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"computer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:Vs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.localSocks5")})]}):K.type==="remote"?s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"server",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.remote")}),s.jsx(L,{name:"arrow-right",className:"h-3.5 w-3.5"}),s.jsx(L,{name:"computer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:Vs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.local")})]}):s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"computer",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"font-mono text-foreground",children:Vs}),s.jsx("span",{children:t("settings.remoteInstances.page.preview.local")}),s.jsx(L,{name:"arrow-right",className:"h-3.5 w-3.5"}),s.jsx(L,{name:"server",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.remote")})]})}),Js?s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{In(Oa).then(Rt=>{Rt||G.error(t("settings.remoteInstances.page.toast.openLocalEndpointFailed"))})},children:[s.jsx(L,{name:"external-link",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.openLocal")]}):null]})]})})]},K.id)}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal mt-1",onClick:()=>{const K=yy();ms(ke=>({...ke,portForwards:[...ke.portForwards,K]})),C(ke=>({...ke,[K.id]:!0}))},children:[s.jsx(L,{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(Q,{type:"button",size:"xs",className:"!font-normal",onClick:()=>{jr()},disabled:!wr||p,children:t("settings.common.actions.saveChanges")}),Fs?.localUrl?s.jsxs(s.Fragment,{children:[s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{Zn(Fs.localUrl||"").then(K=>{K.ok&&G.success(t("settings.remoteInstances.page.toast.localUrlCopied"))})},children:[s.jsx(L,{name:"file-copy",className:"h-3.5 w-3.5"}),t("settings.remoteInstances.page.actions.copyLocalUrl")]}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{gi()},children:[s.jsx(L,{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(Lt,{open:_,onOpenChange:B,children:s.jsxs(Ft,{className:"sm:max-w-2xl",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.remoteInstances.page.logsDialog.title")}),s.jsx(qt,{children:y?.nickname?.trim()||y?.sshParsed?.destination||y?.id||t("settings.remoteInstances.page.logsDialog.selectedInstanceFallback")})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:mi,disabled:D||!ts.trim(),children:[s.jsx(L,{name:"file-copy",className:"h-3.5 w-3.5"}),t("settings.common.actions.copyAll")]}),s.jsxs(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{pi()},disabled:D,children:[s.jsx(L,{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")}):T?s.jsx("div",{className:"typography-meta text-[var(--status-error)]",children:T}):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:O.length>0?O.join(`
|
|
29
|
+
`):t("settings.remoteInstances.page.logsDialog.empty")})]})}),s.jsx(Lt,{open:!!U,onOpenChange:K=>{K||mn()},children:s.jsxs(Ft,{className:"sm:max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:t("settings.remoteInstances.page.patternDialog.title")}),s.jsx(qt,{children:U?t("settings.remoteInstances.page.patternDialog.descriptionWithHost",{host:U}):t("settings.remoteInstances.page.patternDialog.description")})]}),s.jsxs("form",{className:"space-y-3",onSubmit:K=>{K.preventDefault(),pa()},children:[s.jsx(tt,{value:X,onChange:K=>S(K.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(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:mn,disabled:W,children:t("settings.common.actions.cancel")}),s.jsx(Q,{type:"submit",size:"xs",className:"!font-normal",disabled:W,children:t("settings.common.actions.create")})]})]})]})})]})})},Ay="__add_provider__",Ey=()=>{const t=Is.getDirectory();return typeof t=="string"&&t.trim().length>0?t.trim():null},Ty=({onItemSelect:t})=>{const{t:e}=it(),n=pt(m=>m.providers),a=pt(m=>m.selectedProviderId),i=pt(m=>m.setSelectedProvider),r=rs(m=>m.activeProjectId),[o,d]=l.useState({}),c=l.useMemo(()=>Ey(),[r]);l.useEffect(()=>{if(n.length===0){d({});return}let m=!1;return(async()=>{const h=n.map(async g=>{try{const x=c?`?directory=${encodeURIComponent(c)}`:"",v=await gt(`/api/provider/${encodeURIComponent(g.id)}/source${x}`,{method:"GET",headers:{Accept:"application/json"}});if(!v.ok)return;const N=await v.json().catch(()=>null),P=N?.sources??N?.data?.sources;if(!P||m)return;d(F=>({...F,[g.id]:P}))}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]),f=l.useMemo(()=>n.filter(m=>!o[m.id]?.project?.exists),[n,o]);return s.jsxs("div",{className:le("flex h-full flex-col",p),children:[s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[s.jsx("h2",{className:`${dn} mb-3`,children:e("settings.providers.sidebar.title")}),s.jsx(ci,{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(Q,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:()=>{i(Ay),t?.()},"aria-label":e("settings.providers.sidebar.actions.connectProviderAria"),title:e("settings.providers.sidebar.actions.connectProviderTitle"),children:s.jsx(L,{name:"add",className:"h-3.5 w-3.5"})})]})]}),s.jsx(Bs,{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(L,{name:"stack",className:"mx-auto mb-3 h-10 w-10 opacity-50"}),s.jsx("p",{className:"typography-ui-label font-medium",children:e("settings.providers.sidebar.empty.title")}),s.jsx("p",{className:"typography-meta mt-1 opacity-75",children:e("settings.providers.sidebar.empty.description")})]}):s.jsxs(s.Fragment,{children:[f.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:e("settings.providers.sidebar.section.userProviders")}),f.map(m=>s.jsx(kc,{provider:m,selectedProviderId:a,onSelect:()=>{i(m.id),t?.()}},m.id))]}),u.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:le("px-2 pb-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground",f.length>0?"pt-3":"pt-2"),children:e("settings.providers.sidebar.section.projectProviders")}),u.map(m=>s.jsx(kc,{provider:m,selectedProviderId:a,onSelect:()=>{i(m.id),t?.()}},m.id))]})]})})]})},kc=t=>{const e=Ye.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=le("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(Pa,{providerId:n.id,className:"h-4 w-4 flex-shrink-0"}),e[2]=n.id,e[3]=u):u=e[3];const f=n.name||n.id;let m;e[4]!==f?(m=s.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:f}),e[4]=f,e[5]=m):m=e[5];let b;e[6]!==r?(b=s.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:r}),e[6]=r,e[7]=b):b=e[7];let h;e[8]!==i||e[9]!==u||e[10]!==m||e[11]!==b?(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,b]}),e[8]=i,e[9]=u,e[10]=m,e[11]=b,e[12]=h):h=e[12];let g;return e[13]!==n.id||e[14]!==p||e[15]!==h?(g=s.jsx("div",{className:p,children:h},d),e[13]=n.id,e[14]=p,e[15]=h,e[16]=g):g=e[16],g},Ry=t=>t,Dy=t=>new Intl.NumberFormat(Mo(),{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}).format(t),Nc=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const e=Dy(t);return e.endsWith(".0")?e.slice(0,-2):e},Ti="__add_provider__",Ra=t=>typeof t=="object"&&t!==null,Sc=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()},My=t=>{if(!Ra(t))return{};const e={};for(const[n,a]of Object.entries(t))Array.isArray(a)&&(e[n]=a.filter(i=>Ra(i)));return e},Ly=t=>{if(typeof t=="string")return{id:t};if(!Ra(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}},Fy=t=>{let e=[];Array.isArray(t)?e=t:Ra(t)&&(Array.isArray(t.all)?e=t.all:Array.isArray(t.providers)&&(e=t.providers));const n=e.map(i=>Ly(i)).filter(i=>!!i),a=new Set;return n.filter(i=>a.has(i.id)?!1:(a.add(i.id),!0))},Oy=()=>{const{t}=it(),e=pt(q=>q.providers),n=pt(q=>q.selectedProviderId),a=pt(q=>q.setSelectedProvider),i=pt(q=>q.getModelMetadata),r=Ne(q=>q.hiddenModels),o=Ne(q=>q.toggleHiddenModel),d=Ne(q=>q.hideAllModels),c=Ne(q=>q.showAllModels),[p,u]=l.useState({}),[f,m]=l.useState(!1),[b,h]=l.useState({}),[g,x]=l.useState(null),[v,N]=l.useState(""),[P,F]=l.useState(null),[w,j]=l.useState({}),[y,R]=l.useState({}),[_,B]=l.useState([]),[D,k]=l.useState(!1),[T,M]=l.useState(null),[O,V]=l.useState(""),[U,Y]=l.useState(""),[X,S]=l.useState(!1),[W,Z]=l.useState({}),[A,C]=l.useState(!1),z=n===Ti;l.useEffect(()=>{!n&&e.length>0&&a(e[0].id)},[e,n,a]),l.useEffect(()=>{if(!z)return;let q=!0;return(async()=>{m(!0);try{const ne=await Is.getSdkClient().provider.auth();if(ne.error)throw new Error(`provider.auth failed: ${String(ne.error)}`);if(!q)return;u(My(ne.data))}catch(ne){if(!q)return;console.error("Failed to load provider auth methods:",ne),G.error(t("settings.providers.page.toast.authMethodsLoadFailed"))}finally{q&&m(!1)}})(),()=>{q=!1}},[z,t]),l.useEffect(()=>{if(!Ry(z))return;let q=!0;return(async()=>{k(!0),M(null);try{const ne=await Is.getSdkClient().provider.list();if(ne.error)throw new Error(`provider.list failed: ${String(ne.error)}`);if(!q)return;B(Fy(ne.data))}catch(ne){if(!q)return;console.error("Failed to load available providers:",ne),M(t("settings.providers.page.state.unableToLoadProviderList"))}finally{q&&k(!1)}})(),()=>{q=!1}},[z,t]);const $=l.useMemo(()=>new Set(e.map(q=>q.id)),[e]),H=l.useMemo(()=>_.filter(q=>!$.has(q.id)).sort((q,te)=>{const ne=(q.name||q.id).toLowerCase(),oe=(te.name||te.id).toLowerCase();return ne.localeCompare(oe)}),[_,$]);l.useEffect(()=>{n===Ti&&O&&!H.some(q=>q.id===O)&&V("")},[n,O,H]),l.useEffect(()=>{if(n===Ti){C(!0);return}C(!1)},[n,t]),l.useEffect(()=>{if(!n||n===Ti)return;let q=!1;return(async()=>{try{const ne=await gt(`/api/provider/${encodeURIComponent(n)}/source`,{method:"GET",headers:{Accept:"application/json"}}),oe=await ne.json().catch(()=>null);if(!ne.ok)throw new Error(oe?.error||t("settings.providers.page.toast.providerSourcesLoadFailed"));const Ae=oe?.sources??oe?.data?.sources;!q&&Ae&&Z(je=>({...je,[n]:Ae}))}catch(ne){q||console.error("Failed to load provider sources:",ne)}})(),()=>{q=!0}},[n,t]);const J=e.find(q=>q.id===n),ee=n?W[n]:void 0,ue=async q=>{const te=b[q]?.trim()??"";if(!te){G.error(t("settings.providers.page.toast.apiKeyRequired"));return}const ne=`api:${q}`;x(ne);try{if((await Is.getSdkClient().auth.set({providerID:q,auth:{type:"api",key:te}})).error)throw new Error(t("settings.providers.page.toast.apiKeySaveFailed"));G.success(t("settings.providers.page.toast.apiKeySaved")),h(Ae=>({...Ae,[q]:""})),await ea({scopes:["providers"],mode:"active"}),a(q)}catch(oe){console.error("Failed to save API key:",oe),G.error(t("settings.providers.page.toast.apiKeySaveFailed"))}finally{x(null)}},re=async(q,te)=>{const ne=`oauth:${q}:${te}`;x(ne);try{const oe=await Is.getSdkClient().provider.oauth.authorize({providerID:q,method:te});if(oe.error)throw new Error(t("settings.providers.page.toast.oauthStartFailed"));const Ae=Ra(oe.data)?oe.data:{},je=Ae.data,Ie=Ra(je)?je:Ae,Te=typeof Ie.url=="string"&&Ie.url||typeof Ie.verification_uri_complete=="string"&&Ie.verification_uri_complete||typeof Ie.verification_uri=="string"&&Ie.verification_uri||void 0,Me=typeof Ie.instructions=="string"&&Ie.instructions||typeof Ie.message=="string"&&Ie.message||void 0,He=typeof Ie.user_code=="string"&&Ie.user_code||typeof Ie.code=="string"&&Ie.code||typeof Ie.userCode=="string"&&Ie.userCode||void 0;if(!Te&&!Me&&!He)throw new Error(t("settings.providers.page.toast.oauthDetailsMissing"));const Ve=`${q}:${te}`;R(Ue=>({...Ue,[Ve]:{url:Te,instructions:Me,userCode:He}})),Te&&In(Te),F({providerId:q,methodIndex:te}),G.message(t("settings.providers.page.toast.completeOAuthInBrowser"))}catch(oe){console.error("Failed to start OAuth flow:",oe),G.error(t("settings.providers.page.toast.oauthStartFailed"))}finally{x(null)}},xe=async(q,te)=>{const ne=`${q}:${te}`,oe=w[ne]?.trim(),Ae=`oauth-complete:${q}:${te}`;x(Ae);try{const je={method:te};if(oe&&(je.code=oe),(await Is.getSdkClient().provider.oauth.callback({providerID:q,method:je.method,code:je.code})).error)throw new Error(t("settings.providers.page.toast.oauthCompleteFailed"));G.success(t("settings.providers.page.toast.oauthCompleted")),j(Te=>({...Te,[ne]:""})),F(null),await ea({scopes:["providers"],mode:"active"}),a(q)}catch(je){console.error("Failed to complete OAuth flow:",je),G.error(t("settings.providers.page.toast.oauthCompleteFailed"))}finally{x(null)}},be=async q=>{const te=await Zn(q);if(te.ok){G.success(t("settings.providers.page.toast.oauthLinkCopied"));return}console.error("Failed to copy OAuth link:",te.error),G.error(t("settings.providers.page.toast.oauthLinkCopyFailed"))},he=async q=>{const te=await Zn(q);if(te.ok){G.success(t("settings.providers.page.toast.deviceCodeCopied"));return}console.error("Failed to copy device code:",te.error),G.error(t("settings.providers.page.toast.deviceCodeCopyFailed"))},ye=async q=>{const te=`disconnect:${q}`;x(te);try{const ne=await gt(`/api/provider/${encodeURIComponent(q)}/auth?scope=all`,{method:"DELETE",headers:{Accept:"application/json"}}),oe=await ne.json().catch(()=>null);if(!ne.ok)throw new Error(oe?.error||t("settings.providers.page.toast.providerDisconnectFailed"));G.success(t("settings.providers.page.toast.providerDisconnected")),await ea({scopes:["providers"],mode:"active"})}catch(ne){console.error("Failed to disconnect provider:",ne),G.error(t("settings.providers.page.toast.providerDisconnectFailed"))}finally{x(null)}};if(!z&&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(L,{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(z)return s.jsxs(us,{title:t("settings.providers.page.connect.title"),showSaveStatus:!1,children:[s.jsx(ot,{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")}),D?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.state.loading")}):T?s.jsx("p",{className:"typography-meta text-muted-foreground",children:T}):H.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.connect.allProvidersConnected")}):s.jsxs(ws,{open:X,onOpenChange:q=>{S(q),q||Y("")},children:[s.jsx(ys,{asChild:!0,children:s.jsxs("button",{type:"button",className:ta,children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[O?s.jsx(Pa,{providerId:O,className:"h-3.5 w-3.5 flex-shrink-0"}):null,s.jsx("span",{className:le("truncate typography-ui-label font-normal",O?"text-foreground":"text-muted-foreground"),children:O?H.find(q=>q.id===O)?.name||O:t("settings.providers.page.connect.selectProviderPlaceholder")})]}),s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/50"})]})}),s.jsxs(vs,{align:"start",className:"w-[280px] p-0",onCloseAutoFocus:q=>q.preventDefault(),children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-[var(--surface-subtle)] px-3 py-2",onKeyDown:q=>q.stopPropagation(),children:[s.jsx(L,{name:"search",className:"h-4 w-4 text-muted-foreground"}),s.jsx("input",{type:"text",value:U,onChange:q=>Y(q.target.value),onKeyDown:q=>q.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(Bs,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const q=H.filter(te=>{const ne=U.toLowerCase();return(te.name||te.id).toLowerCase().includes(ne)||te.id.toLowerCase().includes(ne)});return q.length===0?s.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:t("settings.providers.page.connect.noProvidersFound")}):q.map(te=>s.jsxs(bs,{onSelect:()=>{V(te.id),S(!1),Y("")},className:"flex items-center justify-between",children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(Pa,{providerId:te.id,className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"truncate",children:te.name||te.id})]}),O===te.id&&s.jsx(L,{name:"check",className:"h-4 w-4 text-[var(--primary-base)]"})]},te.id))})()})]})]})]})}),O&&s.jsx(ot,{title:t("settings.providers.page.auth.title"),settingsItem:"providers.auth",contentClassName:"space-y-4",children:f?s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.providers.page.auth.loadingMethods")}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"py-1.5",children:[s.jsxs("label",{className:"typography-ui-label text-foreground flex items-center gap-1.5",children:[t("settings.providers.page.auth.apiKeyLabel"),s.jsx(Ht,{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(tt,{type:"password",value:b[O]??"",onChange:q=>h(te=>({...te,[O]:q.target.value})),placeholder:t("settings.providers.page.auth.apiKeyPlaceholder"),className:"flex-1 font-mono text-xs"}),s.jsx(Q,{size:"xs",className:"!font-normal shrink-0",onClick:()=>ue(O),disabled:g===`api:${O}`,children:g===`api:${O}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.saveKey")})]})]}),(()=>{const te=(p[O]??[]).filter(ne=>Sc(ne)==="oauth");return te.length===0?null:s.jsx("div",{className:"space-y-4 border-t border-[var(--surface-subtle)] pt-2",children:te.map((ne,oe)=>{const Ae=ne.label||ne.name||t("settings.providers.page.auth.oauthMethodFallback",{index:String(oe+1)}),je=`${O}:${oe}`,Ie=P?.providerId===O&&P?.methodIndex===oe;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:Ae}),(ne.description||ne.help)&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:String(ne.description||ne.help)})]}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>re(O,oe),disabled:g===`oauth:${O}:${oe}`,children:t("settings.providers.page.actions.connect")})]}),y[je]?.instructions&&s.jsx("p",{className:"typography-meta text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-2 py-1.5 rounded",children:y[je]?.instructions}),y[je]?.userCode&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(tt,{value:y[je]?.userCode,readOnly:!0,className:"font-mono text-center tracking-widest"}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>he(y[je]?.userCode??""),children:t("settings.providers.page.actions.copyCode")})]}),y[je]?.url&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(tt,{value:y[je]?.url,readOnly:!0,className:"text-xs text-muted-foreground"}),s.jsxs("div",{className:"flex gap-1 shrink-0",children:[s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>In(y[je]?.url??""),children:t("settings.providers.page.actions.open")}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>be(y[je]?.url??""),children:t("settings.providers.page.actions.copy")})]})]}),Ie&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(tt,{value:w[je]??"",onChange:Te=>j(Me=>({...Me,[je]:Te.target.value})),placeholder:t("settings.providers.page.auth.pasteAuthorizationCodePlaceholder"),className:"font-mono text-xs"}),s.jsx(Q,{size:"xs",className:"!font-normal",onClick:()=>xe(O,oe),disabled:g===`oauth-complete:${O}:${oe}`,children:g===`oauth-complete:${O}:${oe}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.complete")})]})]},`${O}-${Ae}`)})})})()]})})]});if(!J)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(L,{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 fe=Array.isArray(J.models)?J.models:[],ce=(p[J.id]??[]).filter(q=>Sc(q)==="oauth"),pe=fe.filter(q=>{const te=typeof q?.name=="string"?q.name:"",ne=typeof q?.id=="string"?q.id:"",oe=v.trim().toLowerCase();return oe?te.toLowerCase().includes(oe)||ne.toLowerCase().includes(oe):!0});return s.jsxs(us,{title:J.name||J.id,titleLeading:s.jsx(Pa,{providerId:J.id,className:"h-5 w-5 shrink-0"}),description:s.jsx("span",{className:"font-mono typography-settings-description text-muted-foreground",children:J.id}),showSaveStatus:!1,children:[s.jsx(ot,{title:t("settings.providers.page.auth.title"),divider:!1,headerAction:s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>C(q=>!q),children:t(A?"settings.providers.page.actions.hide":"settings.providers.page.actions.reconnect")}),settingsItem:"providers.auth",children:A?f?s.jsx("div",{className:"py-1.5 typography-meta text-muted-foreground",children:t("settings.providers.page.auth.loadingMethods")}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"py-1.5",children:[s.jsxs("label",{className:"typography-ui-label text-foreground flex items-center gap-1.5",children:[t("settings.providers.page.auth.apiKeyLabel"),s.jsx(Ht,{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(tt,{type:"password",value:b[J.id]??"",onChange:q=>h(te=>({...te,[J.id]:q.target.value})),placeholder:t("settings.providers.page.auth.apiKeyPlaceholder"),className:"flex-1 font-mono text-xs"}),s.jsx(Q,{size:"xs",className:"!font-normal shrink-0",onClick:()=>ue(J.id),disabled:g===`api:${J.id}`,children:g===`api:${J.id}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.saveKey")})]})]}),ce.length>0&&s.jsx("div",{className:"space-y-4 border-t border-[var(--surface-subtle)] pt-2",children:ce.map((q,te)=>{const ne=q.label||q.name||t("settings.providers.page.auth.oauthMethodFallback",{index:String(te+1)}),oe=`${J.id}:${te}`,Ae=P?.providerId===J.id&&P?.methodIndex===te;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"typography-ui-label text-foreground",children:ne}),(q.description||q.help)&&s.jsx("div",{className:"typography-meta text-muted-foreground",children:String(q.description||q.help)})]}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>re(J.id,te),disabled:g===`oauth:${J.id}:${te}`,children:t("settings.providers.page.actions.connect")})]}),y[oe]?.instructions&&s.jsx("p",{className:"typography-meta text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-2 py-1.5 rounded",children:y[oe]?.instructions}),y[oe]?.userCode&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(tt,{value:y[oe]?.userCode,readOnly:!0,className:"font-mono text-center tracking-widest"}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>he(y[oe]?.userCode??""),children:t("settings.providers.page.actions.copyCode")})]}),y[oe]?.url&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(tt,{value:y[oe]?.url,readOnly:!0,className:"text-xs text-muted-foreground"}),s.jsxs("div",{className:"flex gap-1 shrink-0",children:[s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>In(y[oe]?.url??""),children:t("settings.providers.page.actions.open")}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>be(y[oe]?.url??""),children:t("settings.providers.page.actions.copy")})]})]}),Ae&&s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[s.jsx(tt,{value:w[oe]??"",onChange:je=>j(Ie=>({...Ie,[oe]:je.target.value})),placeholder:t("settings.providers.page.auth.pasteAuthorizationCodePlaceholder"),className:"font-mono text-xs"}),s.jsx(Q,{size:"xs",className:"!font-normal",onClick:()=>xe(J.id,te),disabled:g===`oauth-complete:${J.id}:${te}`,children:g===`oauth-complete:${J.id}:${te}`?t("settings.providers.page.actions.saving"):t("settings.providers.page.actions.complete")})]})]},`${J.id}-${ne}`)})})]}):s.jsxs("div",{className:"flex items-center gap-1.5 py-1.5",children:[s.jsx(L,{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(Ht,{children:t("settings.providers.page.auth.useReconnectHint")})]})}),s.jsx(ot,{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:ee&&(ee.auth.exists||ee.user.exists||ee.project.exists||ee.custom?.exists)?s.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t("settings.providers.page.connectionDetails.configuredIn")," ",[ee.auth.exists?t("settings.providers.page.connectionDetails.source.authCredentials"):null,ee.user.exists?t("settings.providers.page.connectionDetails.source.userConfig"):null,ee.project.exists?t("settings.providers.page.connectionDetails.source.projectConfig"):null,ee.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(Q,{variant:"ghost",size:"xs",className:"!font-normal text-[var(--status-error)] hover:text-[var(--status-error)]",onClick:()=>ye(J.id),disabled:g===`disconnect:${J.id}`,children:g===`disconnect:${J.id}`?t("settings.providers.page.actions.disconnecting"):t("settings.providers.page.actions.disconnect")})]})}),s.jsxs(ot,{title:t("settings.providers.page.models.title"),titleAccessory:fe.length>0?s.jsxs("span",{className:"typography-micro text-muted-foreground font-normal",children:["(",fe.length,")"]}):null,headerAction:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>{const q=fe.map(te=>typeof te?.id=="string"?te.id:"").filter(te=>te.length>0);d(J.id,q)},children:t("settings.providers.page.actions.hideAll")}),s.jsx(Q,{variant:"outline",size:"xs",className:"!font-normal",onClick:()=>c(J.id),children:t("settings.providers.page.actions.showAll")})]}),settingsItem:"providers.models",children:[s.jsxs("div",{className:"relative mb-2",children:[s.jsx(L,{name:"search",className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),s.jsx(tt,{value:v,onChange:q=>N(q.target.value),placeholder:t("settings.providers.page.models.filterPlaceholder"),className:"h-7 pl-8 w-full"})]}),pe.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:pe.map(q=>{const te=typeof q?.id=="string"?q.id:"",ne=typeof q?.name=="string"?q.name:te,oe=te?i(J.id,te):void 0,Ae=r.some(Me=>Me.providerID===J.id&&Me.modelID===te),je=Nc(oe?.limit?.context),Ie=Nc(oe?.limit?.output),Te=[];return oe?.tool_call&&Te.push({key:"tools",icon:"tools",label:t("settings.providers.page.models.capability.toolCalling")}),oe?.reasoning&&Te.push({key:"reasoning",icon:"brain-ai-3",label:t("settings.providers.page.models.capability.reasoning")}),oe?.attachment&&Te.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:le("flex items-center gap-3",Ae&&"opacity-50"),children:[s.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:ne}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[(je||Ie)&&s.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0 bg-[var(--surface-muted)] px-1.5 py-0.5 rounded",children:[je?`${je} ${t("settings.providers.page.models.tokenBadge.context")}`:"",je&&Ie?" · ":"",Ie?`${Ie} ${t("settings.providers.page.models.tokenBadge.output")}`:""]}),Te.length>0&&s.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:Te.map(({key:Me,icon:He,label:Ve})=>s.jsx("span",{className:"flex h-5 w-5 rounded items-center justify-center text-muted-foreground bg-[var(--surface-muted)]",title:Ve,"aria-label":Ve,children:s.jsx(L,{name:He,className:"h-3 w-3"})},Me))}),s.jsx("button",{type:"button",onClick:()=>o(J.id,te),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(Ae?"settings.providers.page.models.actions.showModelInSelectors":"settings.providers.page.models.actions.hideModelFromSelectors"),"aria-label":t(Ae?"settings.providers.page.models.actions.showModel":"settings.providers.page.models.actions.hideModel"),children:Ae?s.jsx(L,{name:"eye-off",className:"h-3.5 w-3.5"}):s.jsx(L,{name:"eye",className:"h-3.5 w-3.5"})})]})]})},te)})})]})]})},Vn=[{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:"neuralwatt",name:"NeuralWatt"}];function Cc(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 zy=[{id:"gemini-auth",label:"Gemini",matcher:t=>t.startsWith("gemini/"),order:1},{id:"antigravity-auth",label:"Antigravity",matcher:t=>t.startsWith("antigravity/"),order:2}],nu={google:zy};function au(t,e){const n=nu[e]??[];for(const a of n)if(a.matcher(t))return a;return null}function By(t){return nu[t]??[]}function Ky(t){return[...t].sort((e,n)=>e.order-n.order)}function qk(t,e){const n=new Map;for(const a of Object.keys(t)){const r=au(a,e)?.id??null;n.has(r)||n.set(r,[]),n.get(r).push(a)}return n}function Uy(t,e,n){const a=new Map;for(const i of t){const r=e(i),d=au(r,n)?.id??null;a.has(d)||a.set(d,[]),a.get(d).push(i)}return a}function _y(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 zo=6e4,Ic=t=>{const e=Vn.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))):zo,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,b]of Object.entries(p))Array.isArray(b)&&(c[m]=b.filter(h=>typeof h=="string"));const u={},f=t?.usageExpandedFamilies;if(f&&typeof f=="object")for(const[m,b]of Object.entries(f))Array.isArray(b)&&(u[m]=b.filter(h=>typeof h=="string"));return{autoRefresh:n,refreshIntervalMs:a,displayMode:i,showPredValues:r,dropdownProviderIds:d,selectedModels:c,expandedFamilies:u}},$y=async()=>{const t=ln()?.settings;if(t)try{const n=(await t.load())?.settings;return Ic(n??null)}catch{}if(!os()){const e=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(e.ok){const n=await e.json().catch(()=>null);return Ic(n)}}return{autoRefresh:!1,refreshIntervalMs:zo,displayMode:"usage",showPredValues:!1,dropdownProviderIds:Vn.map(e=>e.id),selectedModels:{},expandedFamilies:{}}},Wt=cn()(Da((t,e)=>({results:[],selectedProviderId:null,isLoading:!1,isFetchingProvider:{},lastUpdated:null,error:null,autoRefresh:!1,refreshIntervalMs:zo,displayMode:"usage",showPredValues:!1,dropdownProviderIds:Vn.map(n=>n.id),selectedModels:{},expandedFamilies:{},loadSettings:async()=>{try{const n=await $y();t(n)}catch(n){console.warn("Failed to load usage settings:",n)}},fetchAllQuotas:async()=>{t({isLoading:!0,error:null});const n=Vn.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 gt(`/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}})),kt({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}}}),kt({usageExpandedFamilies:e().expandedFamilies})},applyDefaultSelections:(n,a)=>{if((e().selectedModels[n]?.length??0)>0)return;const r=_y(n,a);r.length!==0&&(t(o=>({selectedModels:{...o.selectedModels,[n]:r}})),kt({usageSelectedModels:e().selectedModels}))}}),{name:"quota-store"})),Vy=()=>{const t=Ye.c(5),e=Wt(Hy),n=Wt(Wy),a=Wt(Gy);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 Hy(t){return t.autoRefresh}function Wy(t){return t.refreshIntervalMs}function Gy(t){return t.fetchAllQuotas}const qy=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)},Jy=t=>{const e=Ye.c(122),{onItemSelect:n}=t,{t:a}=it(),i=Wt(Qy),r=Wt(Yy),o=Wt(Xy),d=Wt(Zy),c=Wt(ev),p=Wt(tv),u=Wt(sv),f=Wt(nv),m=Wt(av),b=Wt(iv),h=Wt(rv),g=Wt(ov),x=Wt(lv),v=Wt(cv);let N,P;e[0]!==v?(N=()=>{v()},P=[v],e[0]=v,e[1]=N,e[2]=P):(N=e[1],P=e[2]),l.useEffect(N,P);const F=dv;let w;e[3]!==m?(w=Ke=>{m(Ke),F({usageAutoRefresh:Ke})},e[3]=m,e[4]=w):w=e[4];const j=w;let y;e[5]!==b?(y=Ke=>{const We=Number(Ke);Number.isFinite(We)&&(b(We),F({usageRefreshIntervalMs:We}))},e[5]=b,e[6]=y):y=e[6];const R=y;let _;e[7]!==h?(_=Ke=>{Ke!=="usage"&&Ke!=="remaining"||(h(Ke),F({usageDisplayMode:Ke}))},e[7]=h,e[8]=_):_=e[8];const B=_;let D;e[9]!==x?(D=Ke=>{x(Ke),F({usageShowPredValues:Ke})},e[9]=x,e[10]=D):D=e[10];const k=D;let T;e[11]===Symbol.for("react.memo_cache_sentinel")?(T=le("flex h-full flex-col","bg-background"),e[11]=T):T=e[11];let M;e[12]!==a?(M=a("settings.usage.sidebar.title"),e[12]=a,e[13]=M):M=e[13];let O;e[14]!==M?(O=s.jsx("h2",{className:`${dn} mb-3`,children:M}),e[14]=M,e[15]=O):O=e[15];let V;e[16]!==a?(V=a("settings.usage.sidebar.total",{count:Vn.length}),e[16]=a,e[17]=V):V=e[17];let U;e[18]!==V?(U=s.jsx("span",{className:"typography-meta text-muted-foreground",children:V}),e[18]=V,e[19]=U):U=e[19];let Y;e[20]!==a?(Y=a("settings.usage.sidebar.actions.toggleAutoRefreshAria"),e[20]=a,e[21]=Y):Y=e[21];let X;e[22]!==j||e[23]!==Y||e[24]!==p?(X=s.jsx(As,{asChild:!0,children:s.jsx("span",{className:"inline-flex",children:s.jsx(Pn,{checked:p,onChange:j,ariaLabel:Y})})}),e[22]=j,e[23]=Y,e[24]=p,e[25]=X):X=e[25];let S;e[26]!==a?(S=a("settings.usage.sidebar.tooltip.autoRefresh"),e[26]=a,e[27]=S):S=e[27];let W;e[28]!==S?(W=s.jsx(Ds,{side:"bottom",children:S}),e[28]=S,e[29]=W):W=e[29];let Z;e[30]!==X||e[31]!==W?(Z=s.jsxs(Ps,{children:[X,W]}),e[30]=X,e[31]=W,e[32]=Z):Z=e[32];const A=String(u),C=!p;let z;e[33]!==a?(z=a("settings.usage.sidebar.field.intervalPlaceholder"),e[33]=a,e[34]=z):z=e[34];let $;e[35]!==z?($=s.jsx(Et,{className:"w-fit",children:s.jsx(Vt,{placeholder:z})}),e[35]=z,e[36]=$):$=e[36];let H;e[37]===Symbol.for("react.memo_cache_sentinel")?(H=s.jsxs(Tt,{children:[s.jsx(yt,{value:"30000",children:"30s"}),s.jsx(yt,{value:"60000",children:"1m"}),s.jsx(yt,{value:"300000",children:"5m"})]}),e[37]=H):H=e[37];let J;e[38]!==R||e[39]!==A||e[40]!==C||e[41]!==$?(J=s.jsxs(At,{value:A,onValueChange:R,disabled:C,children:[$,H]}),e[38]=R,e[39]=A,e[40]=C,e[41]=$,e[42]=J):J=e[42];let ee;e[43]!==d?(ee=()=>d(),e[43]=d,e[44]=ee):ee=e[44];let ue;e[45]!==a?(ue=a("settings.usage.sidebar.actions.refreshAria"),e[45]=a,e[46]=ue):ue=e[46];let re;e[47]!==a?(re=a("settings.usage.sidebar.actions.refreshTitle"),e[47]=a,e[48]=re):re=e[48];const xe=c&&"animate-spin";let be;e[49]!==xe?(be=le("h-3.5 w-3.5",xe),e[49]=xe,e[50]=be):be=e[50];let he;e[51]!==be?(he=s.jsx(L,{name:"refresh",className:be}),e[51]=be,e[52]=he):he=e[52];let ye;e[53]!==c||e[54]!==ee||e[55]!==ue||e[56]!==re||e[57]!==he?(ye=s.jsx(Q,{size:"sm",variant:"ghost",className:"h-7 w-7 px-0 text-muted-foreground",onClick:ee,"aria-label":ue,title:re,disabled:c,children:he}),e[53]=c,e[54]=ee,e[55]=ue,e[56]=re,e[57]=he,e[58]=ye):ye=e[58];let fe;e[59]!==Z||e[60]!==J||e[61]!==ye?(fe=s.jsxs("div",{className:"flex items-center gap-2",children:[Z,J,ye]}),e[59]=Z,e[60]=J,e[61]=ye,e[62]=fe):fe=e[62];let ae;e[63]!==U||e[64]!==fe?(ae=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[U,fe]}),e[63]=U,e[64]=fe,e[65]=ae):ae=e[65];let ce;e[66]!==a?(ce=a("settings.usage.sidebar.field.display"),e[66]=a,e[67]=ce):ce=e[67];let pe;e[68]!==ce?(pe=s.jsx("span",{className:"typography-micro text-muted-foreground",children:ce}),e[68]=ce,e[69]=pe):pe=e[69];let q;e[70]!==a?(q=a("settings.usage.sidebar.field.displayModePlaceholder"),e[70]=a,e[71]=q):q=e[71];let te;e[72]!==q?(te=s.jsx(Et,{className:"w-fit",children:s.jsx(Vt,{placeholder:q})}),e[72]=q,e[73]=te):te=e[73];let ne;e[74]!==a?(ne=a("settings.usage.sidebar.field.displayModeUsage"),e[74]=a,e[75]=ne):ne=e[75];let oe;e[76]!==ne?(oe=s.jsx(yt,{value:"usage",children:ne}),e[76]=ne,e[77]=oe):oe=e[77];let Ae;e[78]!==a?(Ae=a("settings.usage.sidebar.field.displayModeRemaining"),e[78]=a,e[79]=Ae):Ae=e[79];let je;e[80]!==Ae?(je=s.jsx(yt,{value:"remaining",children:Ae}),e[80]=Ae,e[81]=je):je=e[81];let Ie;e[82]!==oe||e[83]!==je?(Ie=s.jsxs(Tt,{children:[oe,je]}),e[82]=oe,e[83]=je,e[84]=Ie):Ie=e[84];let Te;e[85]!==B||e[86]!==te||e[87]!==Ie||e[88]!==f?(Te=s.jsxs(At,{value:f,onValueChange:B,children:[te,Ie]}),e[85]=B,e[86]=te,e[87]=Ie,e[88]=f,e[89]=Te):Te=e[89];let Me;e[90]!==pe||e[91]!==Te?(Me=s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[pe,Te]}),e[90]=pe,e[91]=Te,e[92]=Me):Me=e[92];let He;e[93]!==a?(He=a("settings.usage.sidebar.field.showPredictions"),e[93]=a,e[94]=He):He=e[94];let Ve;e[95]!==He?(Ve=s.jsx("span",{className:"typography-micro text-muted-foreground",children:He}),e[95]=He,e[96]=Ve):Ve=e[96];let Ue;e[97]!==a?(Ue=a("settings.usage.sidebar.field.showPredictions"),e[97]=a,e[98]=Ue):Ue=e[98];let ze;e[99]!==k||e[100]!==g||e[101]!==Ue?(ze=s.jsx(Pn,{checked:g,onChange:k,ariaLabel:Ue}),e[99]=k,e[100]=g,e[101]=Ue,e[102]=ze):ze=e[102];let Be;e[103]!==Ve||e[104]!==ze?(Be=s.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[Ve,ze]}),e[103]=Ve,e[104]=ze,e[105]=Be):Be=e[105];let Ge;e[106]!==ae||e[107]!==Me||e[108]!==Be||e[109]!==O?(Ge=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[O,ae,Me,Be]}),e[106]=ae,e[107]=Me,e[108]=Be,e[109]=O,e[110]=Ge):Ge=e[110];let Fe;e[111]!==n||e[112]!==i||e[113]!==r||e[114]!==o||e[115]!==a?(Fe=Vn.map(Ke=>{const We=i.find(Le=>Le.providerId===Ke.id),Pe=qy(We?.usage),at=Pd(Pe),se=Ke.id===r,I=We?.configured??!1,Ee=I?at==="critical"?{backgroundColor:"var(--status-error)"}:at==="warn"?{backgroundColor:"var(--status-warning)"}:{backgroundColor:"var(--status-success)"}:{backgroundColor:"var(--surface-muted-foreground)",opacity:.4};return s.jsx("div",{className:le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",se?"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:Ee}),s.jsx(Pa,{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}),!I&&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]=Fe):Fe=e[116];let ve;e[117]!==Fe?(ve=s.jsx(Bs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:Fe}),e[117]=Fe,e[118]=ve):ve=e[118];let De;return e[119]!==Ge||e[120]!==ve?(De=s.jsxs("div",{className:T,children:[Ge,ve]}),e[119]=Ge,e[120]=ve,e[121]=De):De=e[121],De};function Qy(t){return t.results}function Yy(t){return t.selectedProviderId}function Xy(t){return t.setSelectedProvider}function Zy(t){return t.fetchAllQuotas}function ev(t){return t.isLoading}function tv(t){return t.autoRefresh}function sv(t){return t.refreshIntervalMs}function nv(t){return t.displayMode}function av(t){return t.setAutoRefresh}function iv(t){return t.setRefreshInterval}function rv(t){return t.setDisplayMode}function ov(t){return t.showPredValues}function lv(t){return t.setShowPredValues}function cv(t){return t.loadSettings}async function dv(t){try{await kt(t)}catch(e){console.warn("Failed to save usage settings:",e)}}const uv=t=>{const e=Ye.c(20),{percent:n,tonePercent:a,className:i,expectedMarkerPercent:r}=t;let o;e[0]!==n?(o=Cp(n)??0,e[0]=n,e[1]=o):o=e[1];const d=o,c=a??n;let p;e[2]!==c?(p=Pd(c),e[2]=c,e[3]=p):p=e[3];const u=p,f=r!=null?Math.max(0,Math.min(100,r)):null;let m;e[4]!==u?(m=u==="critical"?{backgroundColor:"var(--status-error)"}:u==="warn"?{backgroundColor:"var(--status-warning)"}:{backgroundColor:"var(--status-success)"},e[4]=u,e[5]=m):m=e[5];const b=m;let h;e[6]!==i?(h=le("relative h-2.5 rounded-full bg-[var(--interactive-border)] overflow-hidden",i),e[6]=i,e[7]=h):h=e[7];const g=`${d}%`;let x;e[8]!==b||e[9]!==g?(x={...b,width:g},e[8]=b,e[9]=g,e[10]=x):x=e[10];let v;e[11]!==d||e[12]!==x?(v=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]=v):v=e[13];let N;e[14]!==f?(N=f!=null&&f>0&&f<100&&s.jsx("div",{className:"absolute top-0 h-full w-0.5 bg-foreground",style:{left:`${f}%`},title:`Expected usage if spread evenly: ${Math.round(f)}% of quota`,"aria-hidden":"true"}),e[14]=f,e[15]=N):N=e[15];let P;return e[16]!==h||e[17]!==v||e[18]!==N?(P=s.jsxs("div",{className:h,children:[v,N]}),e[16]=h,e[17]=v,e[18]=N,e[19]=P):P=e[19],P},mv=t=>{const e=Ye.c(67),{paceInfo:n,className:a,compact:i}=t,r=i===void 0?!1:i,{t:o}=it();let d;e[0]!==n.status?(d=Ip(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 y;e[2]!==o?(y=o("settings.usage.pace.status.onTrack"),e[2]=o,e[3]=y):y=e[3],p=y;break e}case"slightly-fast":{let y;e[4]!==o?(y=o("settings.usage.pace.status.slightlyFast"),e[4]=o,e[5]=y):y=e[5],p=y;break e}case"too-fast":{let y;e[6]!==o?(y=o("settings.usage.pace.status.tooFast"),e[6]=o,e[7]=y):y=e[7],p=y;break e}case"exhausted":{let y;e[8]!==o?(y=o("settings.usage.pace.status.usedUp"),e[8]=o,e[9]=y):y=e[9],p=y;break e}}p=void 0}const u=p;let f;e[10]!==n.predictText||e[11]!==o?(f=o("settings.usage.pace.predictionTooltip",{prediction:n.predictText}),e[10]=n.predictText,e[11]=o,e[12]=f):f=e[12];const m=f;if(r){let y;e[13]!==a?(y=le("flex items-center gap-1.5",a),e[13]=a,e[14]=y):y=e[14];let R;e[15]!==c?(R={backgroundColor:c},e[15]=c,e[16]=R):R=e[16];let _;e[17]!==u||e[18]!==R?(_=s.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:R,title:u}),e[17]=u,e[18]=R,e[19]=_):_=e[19];let B;e[20]!==c?(B={color:c},e[20]=c,e[21]=B):B=e[21];const D=n.isExhausted?void 0:m;let k;e[22]!==n.isExhausted||e[23]!==n.predictText||e[24]!==n.remainingSeconds||e[25]!==o?(k=n.isExhausted?s.jsx(s.Fragment,{children:o("settings.usage.pace.wait",{duration:nl(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]=k):k=e[26];let T;e[27]!==k||e[28]!==B||e[29]!==D?(T=s.jsx("span",{className:"typography-micro tabular-nums",style:B,title:D,children:k}),e[27]=k,e[28]=B,e[29]=D,e[30]=T):T=e[30];let M;return e[31]!==T||e[32]!==y||e[33]!==_?(M=s.jsxs("div",{className:y,children:[_,T]}),e[31]=T,e[32]=y,e[33]=_,e[34]=M):M=e[34],M}let b;e[35]!==a?(b=le("flex items-center justify-between gap-2",a),e[35]=a,e[36]=b):b=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 g;e[41]!==h?(g=s.jsx("div",{className:"flex items-center gap-1.5",children:h}),e[41]=h,e[42]=g):g=e[42];let x;e[43]!==c?(x={color:c},e[43]=c,e[44]=x):x=e[44];let v;e[45]!==n.isExhausted||e[46]!==n.predictText||e[47]!==n.remainingSeconds||e[48]!==m||e[49]!==u||e[50]!==o?(v=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:nl(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]=v):v=e[51];let N;e[52]!==x||e[53]!==v?(N=s.jsx("span",{className:"typography-micro tabular-nums",style:x,children:v}),e[52]=x,e[53]=v,e[54]=N):N=e[54];let P;e[55]!==c?(P={backgroundColor:c},e[55]=c,e[56]=P):P=e[56];let F;e[57]!==u||e[58]!==P?(F=s.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0",style:P,title:u}),e[57]=u,e[58]=P,e[59]=F):F=e[59];let w;e[60]!==N||e[61]!==F?(w=s.jsxs("div",{className:"flex items-center gap-1.5",children:[N,F]}),e[60]=N,e[61]=F,e[62]=w):w=e[62];let j;return e[63]!==w||e[64]!==b||e[65]!==g?(j=s.jsxs("div",{className:b,children:[g,w]}),e[63]=w,e[64]=b,e[65]=g,e[66]=j):j=e[66],j},_r=t=>{const e=Ye.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=Wt(pv),f=Wt(gv),m=Ne(fv),b=u==="remaining"?a.remainingPercent:a.usedPercent,h=u==="remaining"?"remaining":"used";let g;e[0]!==b||e[1]!==a.valueLabel?(g=Pp(a.valueLabel,b),e[0]=b,e[1]=a.valueLabel,e[2]=g):g=e[2];const x=g,v=a.resetAfterFormatted??a.resetAtFormatted;let N;e[3]!==v||e[4]!==m||e[5]!==a.resetAt?(N=Ap(a.resetAt,v,m),e[3]=v,e[4]=m,e[5]=a.resetAt,e[6]=N):N=e[6];const P=N;let F;e[7]!==n?(F=Ep(n),e[7]=n,e[8]=F):F=e[8];const w=F;let j;e[9]!==n||e[10]!==a.resetAt||e[11]!==a.usedPercent||e[12]!==a.windowSeconds?(j=Tp(a.usedPercent,a.resetAt,a.windowSeconds,n),e[9]=n,e[10]=a.resetAt,e[11]=a.usedPercent,e[12]=a.windowSeconds,e[13]=j):j=e[13];const y=j;let R;e:{if(!y||y.dailyAllocationPercent===null){R=null;break e}const $=Rp(y.elapsedRatio);R=u==="remaining"?100-$:$}const _=R;let B;e[14]!==d||e[15]!==c||e[16]!==p?(B=c&&s.jsx(Pn,{checked:p,onChange:$=>d?.($),ariaLabel:"Show in dropdown"}),e[14]=d,e[15]=c,e[16]=p,e[17]=B):B=e[17];let D;e[18]!==w?(D=s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:w}),e[18]=w,e[19]=D):D=e[19];let k;e[20]!==i?(k=i&&s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:i}),e[20]=i,e[21]=k):k=e[21];let T;e[22]!==D||e[23]!==k?(T=s.jsxs("div",{className:"min-w-0 flex flex-col",children:[D,k]}),e[22]=D,e[23]=k,e[24]=T):T=e[24];let M;e[25]!==T||e[26]!==B?(M=s.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[B,T]}),e[25]=T,e[26]=B,e[27]=M):M=e[27];const O=x==="-"?"":x;let V;e[28]!==O?(V=s.jsx("div",{className:"typography-ui-label text-foreground tabular-nums flex items-center justify-end",children:O}),e[28]=O,e[29]=V):V=e[29];let U;e[30]!==M||e[31]!==V?(U=s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[M,V]}),e[30]=M,e[31]=V,e[32]=U):U=e[32];let Y;e[33]!==b||e[34]!==_||e[35]!==a.usedPercent?(Y=s.jsx(uv,{percent:b,tonePercent:a.usedPercent,expectedMarkerPercent:_,className:"h-1.5"}),e[33]=b,e[34]=_,e[35]=a.usedPercent,e[36]=Y):Y=e[36];const X=P?`Resets ${P}`:"";let S;e[37]!==X?(S=s.jsx("span",{className:"typography-micro text-muted-foreground",children:X}),e[37]=X,e[38]=S):S=e[38];let W;e[39]!==h?(W=s.jsx("span",{className:"typography-micro text-muted-foreground",children:h}),e[39]=h,e[40]=W):W=e[40];let Z;e[41]!==S||e[42]!==W?(Z=s.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[S,W]}),e[41]=S,e[42]=W,e[43]=Z):Z=e[43];let A;e[44]!==Y||e[45]!==Z?(A=s.jsxs("div",{className:"mt-2.5",children:[Y,Z]}),e[44]=Y,e[45]=Z,e[46]=A):A=e[46];let C;e[47]!==y||e[48]!==f?(C=y&&f&&s.jsx("div",{className:"mt-1.5",children:s.jsx(mv,{paceInfo:y})}),e[47]=y,e[48]=f,e[49]=C):C=e[49];let z;return e[50]!==U||e[51]!==A||e[52]!==C?(z=s.jsxs("div",{className:"py-3",children:[U,A,C]}),e[50]=U,e[51]=A,e[52]=C,e[53]=z):z=e[53],z};function pv(t){return t.displayMode}function gv(t){return t.showPredValues}function fv(t){return t.timeFormatPreference}const hv=({providerId:t,providerName:e})=>{const{t:n}=it(),[a,i]=l.useState(null),[r,o]=l.useState({}),[d,c]=l.useState(!1),p=`/api/quota/credentials/${t}`;l.useEffect(()=>{gt(p).then(async m=>{if(!m.ok)throw new Error;const b=await m.json();i(b),o(b.workspaceId?{workspaceId:b.workspaceId}:{})}).catch(()=>i({configured:!1}))},[p]);const u=async(m,b,h)=>{c(!0);try{const g=await gt(m,{method:b,headers:h?{"Content-Type":"application/json"}:void 0,body:h?JSON.stringify(h):void 0}),x=await g.json().catch(()=>null);if(!g.ok)throw new Error(x?.error);x?.configured!==void 0&&i(x),o(v=>v.workspaceId?{workspaceId:v.workspaceId}:{}),G.success(n("settings.providers.page.quotaCredentials.saved",{provider:e}))}catch(g){G.error(g instanceof Error&&g.message?g.message:n("settings.providers.page.openCodeGo.saveFailed"))}finally{c(!1)}},f=(m,b,h)=>s.jsxs("label",{className:"block typography-ui-label text-foreground",children:[b,s.jsx(tt,{className:"mt-1 h-7 font-mono text-xs",type:m==="workspaceId"?"text":"password",autoComplete:"off",value:r[m]??"",onChange:g=>o(x=>({...x,[m]:g.target.value})),placeholder:a?.secretMasked??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"&&f("workspaceId",n("settings.providers.page.openCodeGo.workspaceId"),"wrk_..."),t==="opencode-go"&&f("authCookie",n("settings.providers.page.openCodeGo.authCookie"),"auth=..."),t==="ollama-cloud"&&f("cookie",n("settings.providers.page.openCodeGo.authCookie"),"session=..."),t==="cursor"&&f("accessToken",n("settings.providers.page.quotaCredentials.accessToken"),n("settings.providers.page.quotaCredentials.tokenPlaceholder")),t==="cursor"&&f("refreshToken",n("settings.providers.page.quotaCredentials.refreshToken"),n("settings.providers.page.quotaCredentials.tokenPlaceholder")),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Q,{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(Q,{variant:"outline",size:"xs",disabled:d,onClick:()=>u(`${p}/validate`,"POST"),children:n("settings.providers.page.openCodeGo.validate")}),t==="cursor"&&s.jsx(Q,{variant:"outline",size:"xs",disabled:d,onClick:()=>u(`${p}/import`,"POST"),children:n("settings.providers.page.actions.connect")}),a?.configured&&s.jsx(Q,{variant:"destructive",size:"xs",disabled:d,onClick:()=>u(p,"DELETE"),children:n("settings.providers.page.openCodeGo.delete")})]})]})]})},xv=(t,e)=>{if(!t)return"-";try{return Ad(t,e,{fallback:"-"})}catch{return"-"}},bv=()=>{const{t}=it(),e=Ne(M=>M.timeFormatPreference),n=Wt(M=>M.results),a=Wt(M=>M.selectedProviderId),i=Wt(M=>M.setSelectedProvider),r=Wt(M=>M.loadSettings),o=Wt(M=>M.fetchAllQuotas),d=Wt(M=>M.isLoading),c=Wt(M=>M.lastUpdated),p=Wt(M=>M.error),u=Wt(M=>M.dropdownProviderIds),f=Wt(M=>M.setDropdownProviderIds),m=Wt(M=>M.selectedModels),b=Wt(M=>M.toggleModelSelected),h=Wt(M=>M.applyDefaultSelections);Vy(),l.useEffect(()=>{r(),o()},[r,o]),l.useEffect(()=>{if(a||n.length===0)return;const M=n.find(O=>O.configured)?.providerId;i(M??Vn[0]?.id??null)},[n,a,i]);const g=n.find(M=>M.providerId===a)??null,v=Vn.find(M=>M.id===a)?.name??a??t("settings.usage.sidebar.title"),N=g?.usage,P=a?u.includes(a):!1,F=a==="opencode-go"||a==="ollama-cloud"||a==="cursor",w=l.useCallback(M=>{if(!a)return;const O=M?Array.from(new Set([...u,a])):u.filter(V=>V!==a);f(O),kt({usageDropdownProviders:O})},[u,a,f]),j=l.useMemo(()=>N?.models?Object.entries(N.models).map(([M,O])=>({name:M,windows:O})).filter(M=>Object.keys(M.windows.windows).length>0):[],[N?.models]);l.useEffect(()=>{a&&j.length>0&&h(a,j.map(M=>M.name))},[a,j,h]);const y=l.useMemo(()=>!a||j.length===0?new Map:Uy(j,M=>M.name,a),[j,a]),R=l.useMemo(()=>{if(!a)return[];const M=By(a);return Ky(M)},[a]),[_,B]=l.useState(()=>({})),D=l.useCallback(M=>{B(O=>({...O,[M]:!O[M]}))},[]),k=l.useCallback(M=>{if(!a)return;b(a,M);const O=m[a]??[],U=O.includes(M)?O.filter(X=>X!==M):[...O,M],Y={...m,[a]:U};kt({usageSelectedModels:Y})},[a,m,b]),T=a?m[a]??[]:[];return a?s.jsxs(us,{title:t("settings.usage.page.header.providerUsage",{provider:v}),titleLeading:s.jsx(Pa,{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:xv(c,e)}),showSaveStatus:!0,children:[s.jsx(ot,{divider:!1,settingsItem:"usage.header-menu",children:s.jsx(wt,{checked:P,onChange:w,label:t("settings.usage.page.options.showInHeader"),ariaLabel:t("settings.usage.page.options.showInHeaderAria"),info:t("settings.usage.page.options.showInHeaderTooltip")})}),!g&&s.jsx("p",{className:"typography-ui-label text-foreground pb-8",children:t("settings.usage.page.state.noData")}),p&&s.jsxs("div",{className:"mb-8 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] px-4 py-3",children:[s.jsx("p",{className:"typography-ui-label font-medium text-[var(--status-error)]",children:t("settings.usage.page.state.refreshFailedTitle")}),s.jsx("p",{className:"typography-meta text-[var(--status-error)]/80 mt-1",children:p})]}),g&&!g.configured&&!F&&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(hv,{providerId:a,providerName:v}),N?.windows&&Object.keys(N.windows).length>0&&s.jsx(ot,{settingsItem:"usage.model-quotas",children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:Object.entries(N.windows).map(([M,O])=>s.jsx(_r,{title:M,window:O},M))})}),j.length>0&&s.jsxs(ot,{title:t("settings.usage.page.section.modelQuotas"),contentClassName:"space-y-3",children:[R.map(M=>{const O=y.get(M.id)??[];if(O.length===0)return null;const V=_[M.id]??!1;return s.jsx("section",{className:"p-2",children:s.jsxs(sa,{open:!V,onOpenChange:()=>D(M.id),children:[s.jsxs(na,{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:M.label}),s.jsxs("span",{className:"typography-micro text-muted-foreground",children:["(",O.length,")"]})]}),V?s.jsx(L,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"}):s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]}),s.jsx(aa,{children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)] mt-1",children:O.map(U=>{const Y=Object.entries(U.windows.windows);if(Y.length===0)return null;const[X,S]=Y[0],W=T.includes(U.name);return s.jsx(_r,{title:X,subtitle:Cc(U.name),window:S,showToggle:!0,toggleEnabled:W,onToggle:()=>k(U.name)},U.name)})})})]})},M.id)}),(()=>{const M=y.get(null)??[];if(M.length===0)return null;const O=_.other??!1;return s.jsx("section",{className:"p-2",children:s.jsxs(sa,{open:!O,onOpenChange:()=>D("other"),children:[s.jsxs(na,{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:["(",M.length,")"]})]}),O?s.jsx(L,{name:"arrow-right-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"}):s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground group-hover:text-foreground transition-colors"})]}),s.jsx(aa,{children:s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)] mt-1",children:M.map(V=>{const U=Object.entries(V.windows.windows);if(U.length===0)return null;const[Y,X]=U[0],S=T.includes(V.name);return s.jsx(_r,{title:Y,subtitle:Cc(V.name),window:X,showToggle:!0,toggleEnabled:S,onToggle:()=>k(V.name)},V.name)})})})]})})})()]}),g?.configured&&N&&Object.keys(N.windows??{}).length===0&&j.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")})})},yv="git.commit.generate",Io=cn(t=>({selectedPromptId:yv,setSelectedPromptId:e=>{t(n=>n.selectedPromptId===e?n:{selectedPromptId:e})}})),vv=t=>{const e=Ye.c(23),{onItemSelect:n}=t,{t:a}=it(),i=Io(wv),r=Io(jv);let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o={groupKey:"settings.magicPrompts.sidebar.group.git",items:[{id:"git.commit.generate",titleKey:"settings.magicPrompts.sidebar.item.gitCommitGenerate"},{id:"git.pr.generate",titleKey:"settings.magicPrompts.sidebar.item.gitPrGenerate"},{id:"git.conflict.resolve",titleKey:"settings.magicPrompts.sidebar.item.gitConflictResolve"},{id:"git.integrate.cherrypick.resolve",titleKey:"settings.magicPrompts.sidebar.item.gitCherrypickConflictResolve"}]},e[0]=o):o=e[0];let d;e[1]===Symbol.for("react.memo_cache_sentinel")?(d={groupKey:"settings.magicPrompts.sidebar.group.github",items:[{id:"github.pr.review",titleKey:"settings.magicPrompts.sidebar.item.githubPrReview"},{id:"github.issue.review",titleKey:"settings.magicPrompts.sidebar.item.githubIssueReview"},{id:"github.pr.checks.review",titleKey:"settings.magicPrompts.sidebar.item.githubPrFailedChecksReview"},{id:"github.pr.comments.review",titleKey:"settings.magicPrompts.sidebar.item.githubPrCommentsReview"},{id:"github.pr.comment.single",titleKey:"settings.magicPrompts.sidebar.item.githubSinglePrCommentReview"}]},e[1]=d):d=e[1];let c;e[2]===Symbol.for("react.memo_cache_sentinel")?(c={groupKey:"settings.magicPrompts.sidebar.group.planning",items:[{id:"plan.todo",titleKey:"settings.magicPrompts.sidebar.item.planTodo"},{id:"plan.improve",titleKey:"settings.magicPrompts.sidebar.item.planImprove"},{id:"plan.implement",titleKey:"settings.magicPrompts.sidebar.item.planImplement"}]},e[2]=c):c=e[2];let p;e[3]===Symbol.for("react.memo_cache_sentinel")?(p=[o,d,c,{groupKey:"settings.magicPrompts.sidebar.group.session",items:[{id:"session.explore",titleKey:"settings.magicPrompts.sidebar.item.sessionExplore"},{id:"session.summary",titleKey:"settings.magicPrompts.sidebar.item.sessionSummary"},{id:"session.review",titleKey:"settings.magicPrompts.sidebar.item.sessionWorkspaceReview"},{id:"session.plan",titleKey:"settings.magicPrompts.sidebar.item.sessionFeaturePlan"},{id:"session.craftGoal",titleKey:"settings.magicPrompts.sidebar.item.sessionCraftGoal"},{id:"session.catchup",titleKey:"settings.magicPrompts.sidebar.item.sessionCatchUp"},{id:"session.debug",titleKey:"settings.magicPrompts.sidebar.item.sessionDebug"},{id:"session.weigh",titleKey:"settings.magicPrompts.sidebar.item.sessionWeigh"},{id:"session.fusion",titleKey:"settings.magicPrompts.sidebar.item.sessionFusion"}]}],e[3]=p):p=e[3];const u=p;let f;e[4]!==a?(f=a("settings.magicPrompts.sidebar.title"),e[4]=a,e[5]=f):f=e[5];let m;e[6]!==f?(m=s.jsx("h2",{className:dn,children:f}),e[6]=f,e[7]=m):m=e[7];let b;e[8]!==a?(b=a("settings.magicPrompts.sidebar.description"),e[8]=a,e[9]=b):b=e[9];let h;e[10]!==b?(h=s.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:b}),e[10]=b,e[11]=h):h=e[11];let g;e[12]!==m||e[13]!==h?(g=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[m,h]}),e[12]=m,e[13]=h,e[14]=g):g=e[14];let x;e[15]!==n||e[16]!==i||e[17]!==r||e[18]!==a?(x=s.jsx(Bs,{outerClassName:"flex-1 min-h-0",className:"space-y-3 px-3 py-2 overflow-x-hidden",children:u.map(N=>s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"typography-micro px-1 text-muted-foreground",children:a(N.groupKey)}),N.items.map(P=>{const F=i===P.id;return s.jsx("button",{type:"button",onClick:()=>{r(P.id),n?.()},className:le("flex w-full items-center rounded-md px-2 py-1.5 text-left transition-colors",F?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-ui-label truncate font-normal",children:a(P.titleKey)})},P.id)})]},N.groupKey))}),e[15]=n,e[16]=i,e[17]=r,e[18]=a,e[19]=x):x=e[19];let v;return e[20]!==x||e[21]!==g?(v=s.jsxs("div",{className:"flex h-full flex-col bg-background",children:[g,x]}),e[20]=x,e[21]=g,e[22]=v):v=e[22],v};function wv(t){return t.selectedPromptId}function jv(t){return t.setSelectedPromptId}const Pc={"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"}]}},Ac=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),$r=t=>t.endsWith(".visible"),kv=()=>{const{t}=it(),e=l.useCallback(j=>t(j),[t]),n=Io(j=>j.selectedPromptId),[a,i]=l.useState(!0),[r,o]=l.useState({}),[d,c]=l.useState({}),[p,u]=l.useState({}),[f,m]=l.useState({}),[b,h]=l.useState(!1);l.useEffect(()=>{let j=!0;return(async()=>{i(!0);try{const R=await Fp();if(!j)return;o(R)}catch(R){console.warn("Failed to load magic prompts:",R),G.error(t("settings.magicPrompts.page.toast.loadFailed"))}finally{j&&i(!1)}})(),()=>{j=!1}},[t]);const g=Pc[n]??Pc["git.commit.generate"],x=l.useCallback(j=>Ac(r,j)?r[j]:Ir(j),[r]),v=l.useCallback(j=>d[j]??x(j),[d,x]),N=l.useCallback((j,y)=>{c(R=>R[j]===y?R:{...R,[j]:y})},[]),P=l.useCallback(async j=>{const y=v(j);if($r(j)&&y.trim().length===0){G.error(t("settings.magicPrompts.page.toast.visiblePromptRequired"));return}u(R=>({...R,[j]:!0}));try{const R=y===Ir(j)?await al(j):await Dp(j,y);o(R.overrides),G.success(t("settings.magicPrompts.page.toast.saved"))}catch(R){const _=R instanceof Error?R.message:String(R);G.error(t("settings.magicPrompts.page.toast.saveFailed"),{description:_})}finally{u(R=>({...R,[j]:!1}))}},[v,t]),F=l.useCallback(async j=>{m(y=>({...y,[j]:!0}));try{const y=await al(j);o(y.overrides),c(R=>({...R,[j]:Ir(j)})),G.success(t("settings.magicPrompts.page.toast.resetSuccess"))}catch(y){const R=y instanceof Error?y.message:String(y);G.error(t("settings.magicPrompts.page.toast.resetFailed"),{description:R})}finally{m(y=>({...y,[j]:!1}))}},[t]),w=l.useCallback(async()=>{h(!0);try{const j=await Mp();o(j.overrides),c({}),G.success(t("settings.magicPrompts.page.toast.resetAllSuccess"))}catch(j){const y=j instanceof Error?j.message:String(j);G.error(t("settings.magicPrompts.page.toast.resetAllFailed"),{description:y})}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(us,{title:e(g.titleKey),titleAccessory:s.jsx(Ht,{contentClassName:"max-w-xs",children:e(g.descriptionKey)}),headerEnd:s.jsx(Q,{"data-settings-item":"magic-prompts.reset-overrides",variant:"outline",size:"sm",onClick:()=>{w()},disabled:b||Object.keys(r).length===0,children:t(b?"settings.magicPrompts.page.actions.resetting":"settings.magicPrompts.page.actions.resetAllOverrides")}),showSaveStatus:!1,children:g.blocks.map((j,y)=>{const R=Lp(j.id),_=x(j.id),B=v(j.id),D=Ac(r,j.id),k=B!==_,T=$r(j.id)&&B.trim().length===0,M=p[j.id]===!0,O=f[j.id]===!0;return s.jsxs(ot,{title:e(j.titleKey),info:R.description,description:R.placeholders&&R.placeholders.length>0?`${t("settings.magicPrompts.page.placeholdersLabel")} ${R.placeholders.map(V=>`{{${V.key}}}`).join(", ")}`:void 0,divider:y>0,settingsItem:$r(j.id)?"magic-prompts.visible-prompt":"magic-prompts.instructions",contentClassName:"space-y-3",children:[s.jsx(js,{value:B,onChange:V=>N(j.id,V.target.value),className:"min-h-[220px] font-mono text-sm"}),T&&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(k?"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(Q,{variant:"outline",size:"sm",onClick:()=>{F(j.id)},disabled:!D||M||O,children:t(O?"settings.magicPrompts.page.actions.resetting":"settings.magicPrompts.page.actions.resetToDefault")}),s.jsx(Q,{size:"sm",onClick:()=>{P(j.id)},disabled:!k||M||O||T,children:t(M?"settings.common.actions.saving":"settings.magicPrompts.page.actions.save")})]})]})]},j.id)})})},Nv=t=>{const e=Ye.c(89),{onItemSelect:n}=t,{t:a}=it(),[i,r]=l.useState(null),[o,d]=l.useState(null),[c,p]=l.useState(null),{selectedSnippetName:u,snippets:f,setSelectedSnippet:m,setSnippetDraft:b,deleteSnippet:h,loadSnippets:g}=or(zs(Sv));let x,v;e[0]!==g?(x=()=>{g()},v=[g],e[0]=g,e[1]=x,e[2]=v):(x=e[1],v=e[2]),l.useEffect(x,v);let N;e[3]!==n||e[4]!==m||e[5]!==b||e[6]!==f?(N=async()=>{const ae=new Set(f.map(Cv));let ce="new-snippet",pe=1;for(;ae.has(ce);)ce=`new-snippet-${pe++}`;b({name:ce,scope:"global"}),m(ce),n?.()},e[3]=n,e[4]=m,e[5]=b,e[6]=f,e[7]=N):N=e[7];const P=N;let F;e[8]!==i||e[9]!==h||e[10]!==a?(F=async()=>{if(!i)return;await h(i.name)?(G.success(a("settings.snippets.sidebar.toast.deleted")),r(null)):G.error(a("settings.snippets.sidebar.toast.deleteFailed"))},e[8]=i,e[9]=h,e[10]=a,e[11]=F):F=e[11];const w=F;let j;e[12]!==f?(j=[...f].sort(Iv),e[12]=f,e[13]=j):j=e[13];const y=j;let R;e[14]===Symbol.for("react.memo_cache_sentinel")?(R=le("flex h-full flex-col","bg-background"),e[14]=R):R=e[14];let _;e[15]!==a?(_=a("settings.snippets.sidebar.title"),e[15]=a,e[16]=_):_=e[16];let B;e[17]!==_?(B=s.jsx("h2",{className:`${dn} mb-3`,children:_}),e[17]=_,e[18]=B):B=e[18];let D;e[19]!==f.length||e[20]!==a?(D=a("settings.snippets.sidebar.total",{count:f.length}),e[19]=f.length,e[20]=a,e[21]=D):D=e[21];let k;e[22]!==D?(k=s.jsx("span",{className:"typography-meta text-muted-foreground",children:D}),e[22]=D,e[23]=k):k=e[23];let T;e[24]!==a?(T=a("settings.snippets.sidebar.actions.create"),e[24]=a,e[25]=T):T=e[25];let M;e[26]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),e[26]=M):M=e[26];let O;e[27]!==P||e[28]!==T?(O=s.jsx(Q,{size:"sm","data-settings-item":"snippets.create",variant:"ghost",className:"h-7 w-7 px-0 -my-1 text-muted-foreground",onClick:P,"aria-label":T,children:M}),e[27]=P,e[28]=T,e[29]=O):O=e[29];let V;e[30]!==k||e[31]!==O?(V=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[k,O]}),e[30]=k,e[31]=O,e[32]=V):V=e[32];let U;e[33]!==V||e[34]!==B?(U=s.jsxs("div",{className:"border-b px-3 pt-4 pb-3",children:[B,V]}),e[33]=V,e[34]=B,e[35]=U):U=e[35];let Y;if(e[36]!==n||e[37]!==o||e[38]!==c||e[39]!==u||e[40]!==m||e[41]!==y||e[42]!==a){let ae;e[44]!==n||e[45]!==o||e[46]!==c||e[47]!==u||e[48]!==m||e[49]!==a?(ae=ce=>s.jsxs(Un,{open:c===ce.name,onOpenChange:pe=>p(pe?ce.name:null),children:[s.jsxs(_n,{render:s.jsx("div",{className:le("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 select-none",u===ce.name?"bg-interactive-selection":"hover:bg-interactive-hover"),onContextMenu:pe=>{pe.preventDefault(),p(ce.name)}}),children:[s.jsxs("button",{onClick:()=>{m(ce.name),n?.()},className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["#",ce.name]}),s.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:a(`snippets.source.${ce.source}`)})]}),s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:ce.description||ce.content.replace(/\s+/g," ").substring(0,80)})]}),s.jsxs(ws,{open:o===ce.name,onOpenChange:pe=>{pe&&p(null),d(pe?ce.name:null)},children:[s.jsx(ys,{asChild:!0,children:s.jsx(Q,{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(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),s.jsx(vs,{align:"end",className:"w-fit min-w-20",children:s.jsxs(bs,{onClick:pe=>{pe.stopPropagation(),r(ce)},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{name:"delete-bin",className:"h-4 w-4 mr-px"}),a("settings.common.actions.delete")]})})]})]}),s.jsx($n,{className:"w-fit min-w-20",children:s.jsxs(En,{onClick:pe=>{pe.stopPropagation(),r(ce)},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{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]=ae):ae=e[50],Y=y.map(ae),e[36]=n,e[37]=o,e[38]=c,e[39]=u,e[40]=m,e[41]=y,e[42]=a,e[43]=Y}else Y=e[43];let X;e[51]!==Y?(X=s.jsx(Bs,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:Y}),e[51]=Y,e[52]=X):X=e[52];const S=i!==null;let W;e[53]===Symbol.for("react.memo_cache_sentinel")?(W=ae=>{ae||r(null)},e[53]=W):W=e[53];let Z;e[54]!==a?(Z=a("settings.snippets.sidebar.dialog.deleteTitle"),e[54]=a,e[55]=Z):Z=e[55];let A;e[56]!==Z?(A=s.jsx(zt,{children:Z}),e[56]=Z,e[57]=A):A=e[57];const C=i?.name??"";let z;e[58]!==a||e[59]!==C?(z=a("settings.snippets.sidebar.dialog.deleteDescription",{name:C}),e[58]=a,e[59]=C,e[60]=z):z=e[60];let $;e[61]!==z?($=s.jsx(qt,{children:z}),e[61]=z,e[62]=$):$=e[62];let H;e[63]!==A||e[64]!==$?(H=s.jsxs(Ut,{children:[A,$]}),e[63]=A,e[64]=$,e[65]=H):H=e[65];let J;e[66]===Symbol.for("react.memo_cache_sentinel")?(J=()=>r(null),e[66]=J):J=e[66];let ee;e[67]!==a?(ee=a("settings.common.actions.cancel"),e[67]=a,e[68]=ee):ee=e[68];let ue;e[69]!==ee?(ue=s.jsx(Q,{size:"sm",variant:"ghost",onClick:J,children:ee}),e[69]=ee,e[70]=ue):ue=e[70];let re;e[71]!==a?(re=a("settings.common.actions.delete"),e[71]=a,e[72]=re):re=e[72];let xe;e[73]!==w||e[74]!==re?(xe=s.jsx(Q,{size:"sm",onClick:w,children:re}),e[73]=w,e[74]=re,e[75]=xe):xe=e[75];let be;e[76]!==ue||e[77]!==xe?(be=s.jsxs(Zt,{children:[ue,xe]}),e[76]=ue,e[77]=xe,e[78]=be):be=e[78];let he;e[79]!==H||e[80]!==be?(he=s.jsxs(Ft,{className:"max-w-md",children:[H,be]}),e[79]=H,e[80]=be,e[81]=he):he=e[81];let ye;e[82]!==S||e[83]!==he?(ye=s.jsx(Lt,{open:S,onOpenChange:W,children:he}),e[82]=S,e[83]=he,e[84]=ye):ye=e[84];let fe;return e[85]!==U||e[86]!==X||e[87]!==ye?(fe=s.jsxs("div",{className:R,children:[U,X,ye]}),e[85]=U,e[86]=X,e[87]=ye,e[88]=fe):fe=e[88],fe};function Sv(t){return{selectedSnippetName:t.selectedSnippetName,snippets:t.snippets,setSelectedSnippet:t.setSelectedSnippet,setSnippetDraft:t.setSnippetDraft,deleteSnippet:t.deleteSnippet,loadSnippets:t.loadSnippets}}function Cv(t){return t.name}function Iv(t,e){return t.name.localeCompare(e.name)}const Pv=()=>{const{t}=it(),{selectedSnippetName:e,snippets:n,snippetDraft:a,setSnippetDraft:i,updateSnippet:r,createSnippet:o}=or(zs(R=>({selectedSnippetName:R.selectedSnippetName,snippets:R.snippets,snippetDraft:R.snippetDraft,setSnippetDraft:R.setSnippetDraft,updateSnippet:R.updateSnippet,createSnippet:R.createSnippet}))),d=l.useMemo(()=>e?n.find(R=>R.name===e||R.aliases.includes(e))??null:null,[e,n]),c=!!(a&&a.name===e&&!d),[p,u]=l.useState(""),[f,m]=l.useState("global"),[b,h]=l.useState(""),[g,x]=l.useState(""),[v,N]=l.useState(""),[P,F]=l.useState(!1),w=l.useRef(null);l.useEffect(()=>{if(c&&a){const R={draftName:a.name||"",draftScope:a.scope||"global",description:a.description||"",aliases:(a.aliases||[]).join(", "),content:a.content||""};u(R.draftName),m(R.draftScope),h(R.description),x(R.aliases),N(R.content),w.current=R}else if(d){const R={draftName:"",draftScope:"global",description:d.description??"",aliases:d.aliases.join(", "),content:d.content};h(R.description),x(R.aliases),N(R.content),w.current=R}},[d,c,e,a]);const j=l.useMemo(()=>{const R=w.current;return R?c&&p!==R.draftName||c&&f!==R.draftScope?!0:b!==R.description||g!==R.aliases||v!==R.content:!1},[g,v,b,p,f,c]),y=async()=>{const R=c?p.trim().replace(/\s+/g,"-"):e?.trim();if(!R){G.error(t("settings.snippets.page.toast.nameRequired"));return}if(!v.trim()){G.error(t("settings.snippets.page.toast.contentRequired"));return}const _=g.split(",").map(B=>B.trim()).filter(Boolean);F(!0);try{if(!(c?await o(R,v,{aliases:_,description:b,scope:f}):await r(R,{content:v,aliases:_,description:b}))){G.error(t("settings.snippets.page.toast.saveFailed"));return}G.success(t("settings.snippets.page.toast.saved")),c&&i(null)}finally{F(!1)}};return e?s.jsxs(us,{title:c?t("settings.snippets.page.title.new"):`#${e}`,description:d?d.filePath:void 0,showSaveStatus:!1,children:[s.jsxs(ot,{divider:!1,contentClassName:"space-y-0",children:[c?s.jsxs(Jt,{label:"#",children:[s.jsx(tt,{value:p,onChange:R=>u(R.target.value),placeholder:t("settings.snippets.page.field.namePlaceholder"),className:"h-7 w-44 px-2"}),s.jsxs(At,{value:f,onValueChange:R=>m(R),children:[s.jsx(Et,{size:Gt,className:"w-fit min-w-[100px]",children:s.jsx(Vt,{})}),s.jsxs(Tt,{align:"end",children:[s.jsx(yt,{value:"global",children:t("settings.common.scope.global")}),s.jsx(yt,{value:"project",children:t("settings.common.scope.project")})]})]})]}):null,s.jsx(ls,{label:t("settings.common.field.description"),children:s.jsx(tt,{value:b,onChange:R=>h(R.target.value),placeholder:t("settings.snippets.page.field.descriptionPlaceholder"),className:"h-7 w-full max-w-sm px-2"})}),s.jsx(ls,{label:t("settings.snippets.page.field.aliases"),children:s.jsx(tt,{value:g,onChange:R=>x(R.target.value),placeholder:t("settings.snippets.page.field.aliasesPlaceholder"),className:"h-7 w-full max-w-sm px-2"})})]}),s.jsxs(ot,{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(Ht,{children:t("settings.snippets.page.hint")})]}),s.jsx(js,{value:v,onChange:R=>N(R.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(Q,{onClick:y,disabled:P||!j,size:"xs",className:"!font-normal",children:t(P?"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(L,{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")})]})})},iu=()=>{const{t}=it(),e=pt(f=>f.settingsGitmojiEnabled),n=pt(f=>f.setSettingsGitmojiEnabled),a=Rg(),i=Ne(f=>f.gitChangesViewMode),r=Ne(f=>f.setGitChangesViewMode),[o,d]=l.useState(!0),c=l.useMemo(()=>[{id:"flat",label:t("settings.openchamber.git.option.flatList")},{id:"tree",label:t("settings.openchamber.git.option.treeView")}],[t]);l.useEffect(()=>{(async()=>{try{let m=null;if(!m){const b=ln()?.settings;if(b)try{const g=(await b.load())?.settings;g&&(m={gitmojiEnabled:typeof g.gitmojiEnabled=="boolean"?g.gitmojiEnabled:void 0,gitChangesViewMode:g.gitChangesViewMode==="flat"||g.gitChangesViewMode==="tree"?g.gitChangesViewMode:void 0})}catch{}}if(!m){const b=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});b.ok&&(m=await b.json())}m&&(typeof m.gitmojiEnabled=="boolean"&&n(m.gitmojiEnabled),(m.gitChangesViewMode==="flat"||m.gitChangesViewMode==="tree")&&r(m.gitChangesViewMode))}catch(m){console.warn("Failed to load git settings:",m)}finally{d(!1)}})()},[r,n]);const p=l.useCallback(async f=>{n(f);try{await kt({gitmojiEnabled:f})}catch(m){console.warn("Failed to save gitmoji setting:",m)}},[n]),u=l.useCallback(f=>{f!==i&&(r(f),kt({gitChangesViewMode:f}))},[i,r]);return o?null:s.jsx(ot,{title:t("settings.openchamber.git.title"),children:s.jsxs("div",{className:Rs,children:[s.jsx(Ys,{settingsItem:"git.changes-view",title:t("settings.openchamber.git.changesViewTitle"),children:s.jsx(Bn,{"aria-label":t("settings.openchamber.git.changesViewAria"),children:c.map(f=>s.jsx(zn,{selected:i===f.id,onSelect:()=>{u(f.id)},label:f.label,ariaLabel:t("settings.openchamber.git.optionAria",{option:f.label})},f.id))})}),s.jsx(wt,{settingsItem:"git.gitmoji",checked:e,onChange:f=>{p(f)},label:t("settings.openchamber.git.enableGitmoji"),ariaLabel:t("settings.openchamber.git.enableGitmojiAria")}),s.jsx(wt,{settingsItem:"git.gitignored-files",checked:a,onChange:Dg,label:t("settings.openchamber.git.showGitignored"),ariaLabel:t("settings.openchamber.git.showGitignoredAria")})]})})},ru=()=>{const{t}=it(),{isMobile:e}=_s(),n=ln()?.github,a=kn(k=>k.status),i=kn(k=>k.isLoading),r=kn(k=>k.hasChecked),o=kn(k=>k.refreshStatus),d=kn(k=>k.setStatus),c=l.useCallback(async k=>{await In(k)},[]),[p,u]=l.useState(!1),[f,m]=l.useState(null),[b,h]=l.useState(null),g=l.useRef(null),x=l.useCallback(()=>{g.current!=null&&(window.clearInterval(g.current),g.current=null),h(null)},[]);l.useEffect(()=>((async()=>{try{r||await o(n)}catch(k){console.warn("Failed to load GitHub auth status:",k)}})(),()=>{x()}),[r,o,n,x]);const v=l.useCallback(async()=>{u(!0);try{const k=n?await n.authStart():await(async()=>{const M=await gt("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),O=await M.json().catch(()=>null);if(!M.ok||!O||!("deviceCode"in O))throw new Error(O?.error||M.statusText);return O})();m(k),h(Math.max(1,k.interval)*1e3);const T=k.verificationUriComplete||k.verificationUri;c(T)}catch(k){console.error("Failed to start GitHub connect:",k),G.error(t("settings.github.page.toast.startConnectFailed"))}finally{u(!1)}},[c,n,t]),N=l.useCallback(async k=>{if(n)return n.authComplete(k);const T=await gt("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:k})}),M=await T.json().catch(()=>null);if(!T.ok||!M)throw new Error(M?.error||T.statusText);return M},[n]);l.useEffect(()=>{if(!(!f?.deviceCode||!b)&&g.current==null)return g.current=window.setInterval(()=>{(async()=>{try{const k=await N(f.deviceCode);if(k.connected){G.success(t("settings.github.page.toast.connected")),m(null),x(),await o(n,{force:!0});return}k.status==="slow_down"&&h(T=>T?T+5e3:5e3),(k.status==="expired_token"||k.status==="access_denied")&&(G.error(k.error||t("settings.github.page.toast.authorizationFailed")),m(null),x())}catch(k){console.warn("GitHub polling failed:",k)}})()},b),()=>{g.current!=null&&(window.clearInterval(g.current),g.current=null)}},[f,b,N,o,n,x,t]);const P=l.useCallback(async k=>{u(!0);try{if(n)await n.authSetGhCliDisabled(k);else{const T=await gt("/api/github/auth/gh-cli",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({disabled:k})}),M=await T.json().catch(()=>null);if(!T.ok)throw new Error(M?.error||T.statusText)}G.success(t(k?"settings.github.page.toast.ghCliDisabled":"settings.github.page.toast.ghCliEnabled")),await o(n,{force:!0})}catch(T){console.error("Failed to update gh CLI setting:",T),G.error(t("settings.github.page.toast.ghCliUpdateFailed"))}finally{u(!1)}},[o,n,t]),F=l.useCallback(async()=>{u(!0);try{if(x(),m(null),n)await n.authDisconnect();else{const k=await gt("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!k.ok)throw new Error(k.statusText)}G.success(t("settings.github.page.toast.disconnected")),await o(n,{force:!0})}catch(k){console.error("Failed to disconnect GitHub:",k),G.error(t("settings.github.page.toast.disconnectFailed"))}finally{u(!1)}},[o,n,x,t]),w=l.useCallback(async k=>{if(k){u(!0);try{const T=n?await n.authActivate(k):await(async()=>{const M=await gt("/api/github/auth/activate",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({accountId:k})}),O=await M.json().catch(()=>null);if(!M.ok||!O)throw new Error(O?.error||M.statusText);return O})();d(T),G.success(t("settings.github.page.toast.accountSwitched"))}catch(T){console.error("Failed to switch GitHub account:",T),G.error(t("settings.github.page.toast.accountSwitchFailed"))}finally{u(!1)}}},[n,d,t]);if(i)return null;const j=!!a?.connected,y=a?.user,_=(a?.accounts??[]).filter(k=>!k.current),B=a?.ghCli??null,D=B?.active?t("settings.github.page.accountSource.cli"):t("settings.github.page.accountSource.oauth");return s.jsxs(s.Fragment,{children:[s.jsxs(ot,{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:[j?s.jsxs("div",{className:le("px-4 py-3",e?"flex flex-col gap-3":"flex items-center justify-between gap-4"),children:[s.jsxs("div",{className:le("flex min-w-0 items-center gap-4",e?"w-full":void 0),children:[y?.avatarUrl?s.jsx("img",{src:y.avatarUrl,alt:y.login?t("settings.github.page.avatarAlt.withLogin",{login:y.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:y?.name?.trim()||y?.login||"GitHub"}),s.jsxs("div",{className:le("flex items-center gap-2 typography-meta text-muted-foreground mt-0.5",e?"flex-wrap":"truncate"),children:[s.jsx(L,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"font-mono",children:y?.login||t("settings.github.page.label.unknownUser")}),y?.email&&s.jsx("span",{className:"opacity-50",children:"•"}),y?.email&&s.jsx("span",{children:y.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})}),B?.active&&s.jsx("div",{className:"typography-micro text-muted-foreground/70 mt-0.5",children:t("settings.github.page.ghCli.activeDescription")})]})]}),B?.active?s.jsx(Q,{size:"sm",variant:"outline",onClick:()=>P(!0),disabled:p,className:le(e?"w-full":void 0),children:t("settings.github.page.ghCli.actions.disable")}):s.jsx(Q,{size:"sm",variant:"outline",onClick:F,disabled:p,className:le("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(Q,{size:"sm",variant:"default",onClick:v,disabled:p,children:t("settings.github.page.actions.connect")})]}),_.length>0&&s.jsxs("div",{className:"mt-2 border-t border-[var(--surface-subtle)] pt-2 px-2 pb-1",children:[s.jsx("div",{className:"typography-micro text-muted-foreground mb-2 px-1",children:t("settings.github.page.label.otherAccounts")}),s.jsx("div",{className:"space-y-1",children:_.map(k=>{const T=k.user,M=k.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:[T?.avatarUrl?s.jsx("img",{src:T.avatarUrl,alt:T.login?t("settings.github.page.avatarAlt.withLogin",{login:T.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(L,{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:T?.name?.trim()||T?.login||"GitHub"}),T?.login&&s.jsxs("span",{className:"typography-micro text-muted-foreground truncate",children:[s.jsx("span",{className:"font-mono",children:T.login}),s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{children:M})]})]})]}),s.jsx(Q,{size:"sm",variant:"ghost",onClick:()=>w(k.id),disabled:p,children:t("settings.github.page.actions.switchTo")})]},k.id)})})]})]}),j&&s.jsx("div",{className:"mt-2 px-2 pb-2",children:s.jsx(Q,{size:"sm",variant:"outline",onClick:v,disabled:p,className:le(e?"w-full":void 0),children:t("settings.github.page.actions.addAccount")})}),f&&s.jsxs("div",{className:"mt-4 rounded-lg bg-[var(--surface-elevated)]/70 p-4 border border-[var(--interactive-border)]",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(An,{children:t("settings.github.page.flow.title")}),s.jsx("p",{className:"typography-meta text-muted-foreground",children:t("settings.github.page.flow.description")})]}),s.jsxs("div",{className:"flex items-center justify-between gap-3 mt-4",children:[s.jsx("div",{className:"font-mono text-xl tracking-widest text-foreground bg-[var(--surface-muted)] px-3 py-1.5 rounded-md border border-[var(--interactive-border)]",children:f.userCode}),s.jsx(Q,{size:"sm",asChild:!0,children:s.jsx("a",{href:f.verificationUriComplete||f.verificationUri,target:"_blank",rel:"noopener noreferrer",children:t("settings.github.page.actions.openGithub")})})]}),s.jsxs("div",{className:"mt-4 flex items-center justify-between",children:[s.jsx("span",{className:"typography-micro text-muted-foreground animate-pulse",children:t("settings.github.page.flow.waiting")}),s.jsx(Q,{size:"sm",variant:"ghost",disabled:p,onClick:()=>{x(),m(null)},children:t("settings.common.actions.cancel")})]})]})]}),B?.available&&!B?.active&&(!B.user||B.disabled)&&s.jsx(ot,{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:le("px-4 py-3",e?"flex flex-col gap-3":"flex items-center justify-between gap-4"),children:[s.jsxs("div",{className:le("flex min-w-0 items-center gap-4",e?"w-full":void 0),children:[B.user?.avatarUrl?s.jsx("img",{src:B.user.avatarUrl,alt:B.user.login?t("settings.github.page.avatarAlt.withLogin",{login:B.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(L,{name:"github-fill",className:"h-4 w-4 text-muted-foreground"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[!B.disabled&&B.user&&s.jsx("div",{className:"typography-ui-label text-foreground truncate",children:B.user.name?.trim()||B.user.login||"GitHub"}),!B.disabled&&B.user?.login&&s.jsxs("div",{className:le("flex items-center gap-2 typography-meta text-muted-foreground mt-0.5",e?"flex-wrap":"truncate"),children:[s.jsx(L,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"font-mono",children:B.user.login}),B.user.email&&s.jsx("span",{className:"opacity-50",children:"•"}),B.user.email&&s.jsx("span",{children:B.user.email})]}),s.jsx("div",{className:le("typography-meta text-muted-foreground",B.disabled?"opacity-60":void 0),children:B.disabled?t("settings.github.page.ghCli.disabledDescription"):t("settings.github.page.ghCli.fallbackDescription")})]})]}),s.jsx(Q,{size:"sm",variant:"outline",onClick:()=>P(!B.disabled),disabled:p,className:le(e?"w-full":void 0),children:B.disabled?t("settings.github.page.ghCli.actions.enable"):t("settings.github.page.ghCli.actions.disable")})]})})})]})},Ec=[{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)"}],Av=[{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"}],Ev=({open:t,onOpenChange:e,profileId:n,importData:a})=>{const{t:i}=it(),r=Os($=>$.getProfileById),o=Os($=>$.createProfile),d=Os($=>$.updateProfile),c=Os($=>$.deleteProfile),p=l.useMemo(()=>n&&n!=="new"&&!a?r(n):null,[n,r,a]),u=n==="new"||a!=null,f=n==="global",[m,b]=l.useState(""),[h,g]=l.useState(""),[x,v]=l.useState(""),[N,P]=l.useState("ssh"),[F,w]=l.useState(""),[j,y]=l.useState(!1),[R,_]=l.useState(""),[B,D]=l.useState(""),[k,T]=l.useState("keyword"),[M,O]=l.useState("branch"),[V,U]=l.useState(!1),[Y,X]=l.useState(!1),[S,W]=l.useState(!1);l.useEffect(()=>{if(t){if(a){const $=a.host.split("/"),H=$.length>=3?$[$.length-1]:a.host;b(H),g(a.username),v(""),P("token"),w(""),y(!1),_(""),D(a.host),T("string"),O("code")}else if(u)b(""),g(""),v(""),P("ssh"),w(""),y(!1),_(""),D(""),T("keyword"),O("branch");else if(p)b(p.name),g(p.userName),v(p.userEmail),P(p.authType||"ssh"),w(p.sshKey||""),y(p.signCommits===!0),_(p.signingKey||""),D(p.host||""),T(p.color||"keyword"),O(p.icon||"branch");else if(f){const $=r("global");$&&(b($.name),g($.userName),v($.userEmail),P($.authType||"ssh"),w($.sshKey||""),y(!1),_(""),D($.host||""),T($.color||"keyword"),O($.icon||"branch"))}}},[t,n,p,u,a,f,r]);const Z=async()=>{if(!h.trim()||!x.trim()){G.error(i("settings.gitIdentities.editor.toast.userNameEmailRequired"));return}if(N==="token"&&!B.trim()){G.error(i("settings.gitIdentities.editor.toast.hostRequiredForToken"));return}if(j&&!R.trim()){G.error(i("settings.gitIdentities.editor.toast.signingKeyRequired"));return}U(!0);try{const $={name:m.trim()||h.trim(),userName:h.trim(),userEmail:x.trim(),authType:N,sshKey:N==="ssh"&&F.trim()||null,signCommits:j,signingKey:R.trim()||null,host:N==="token"&&B.trim()||null,color:k,icon:M};let H;if(u)H=await o($);else if(n)H=await d(n,$);else return;H?(G.success(i(u?"settings.gitIdentities.editor.toast.profileCreated":"settings.gitIdentities.editor.toast.profileUpdated")),e(!1)):G.error(i(u?"settings.gitIdentities.editor.toast.createProfileFailed":"settings.gitIdentities.editor.toast.updateProfileFailed"))}catch($){console.error("Error saving profile:",$),G.error(i("settings.gitIdentities.editor.toast.saveUnexpectedError"))}finally{U(!1)}},A=async()=>{if(!(!n||u)){W(!0);try{await c(n)?(G.success(i("settings.gitIdentities.editor.toast.profileDeleted")),X(!1),e(!1)):G.error(i("settings.gitIdentities.editor.toast.deleteProfileFailed"))}catch($){console.error("Error deleting profile:",$),G.error(i("settings.gitIdentities.editor.toast.deleteUnexpectedError"))}finally{W(!1)}}},C=l.useMemo(()=>Ec.find(H=>H.key===k)?.cssVar||"var(--syntax-keyword)",[k]),z=a?i("settings.gitIdentities.editor.title.importCredential"):u?i("settings.gitIdentities.editor.title.newIdentity"):f?i("settings.gitIdentities.editor.title.globalIdentity"):p?.name||i("settings.gitIdentities.editor.title.editIdentity");return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{open:t,onOpenChange:e,children:s.jsxs(Ft,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:z}),s.jsx(qt,{children:i(f?"settings.gitIdentities.editor.description.globalReadOnly":u?"settings.gitIdentities.editor.description.newProfile":"settings.gitIdentities.editor.description.editProfile")})]}),s.jsxs("div",{className:"space-y-5 py-2",children:[!f&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:`${Kt} block mb-1.5`,children:i("settings.gitIdentities.editor.field.profileName")}),s.jsx(tt,{value:m,onChange:$=>b($.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:Ec.map($=>s.jsx("button",{type:"button",onClick:()=>T($.key),className:le("w-6 h-6 rounded-md border-2 transition-all cursor-pointer",k===$.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:$.cssVar},title:$.label},$.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:Av.map($=>{const H=$.Icon;return s.jsx("button",{type:"button",onClick:()=>O($.key),className:le("w-7 h-7 rounded-md border-2 transition-all flex items-center justify-center cursor-pointer",M===$.key?"border-[var(--interactive-border)] bg-[var(--surface-muted)]":"border-transparent hover:border-[var(--interactive-border)] hover:bg-[var(--surface-muted)]/50"),title:$.label,children:s.jsx(L,{name:H,className:"w-3.5 h-3.5",style:{color:M===$.key?C:"var(--surface-muted-foreground)"}})},$.key)})})]})]}),!f&&s.jsx("div",{className:"border-t border-border/40"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:Kt,children:i("settings.gitIdentities.editor.field.userName")}),!f&&s.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),s.jsx(Ht,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.userNameTooltip")})]}),s.jsx(tt,{value:h,onChange:$=>g($.target.value),placeholder:i("settings.gitIdentities.editor.field.userNamePlaceholder"),required:!f,readOnly:f,disabled:f,className:"h-8"})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:Kt,children:i("settings.gitIdentities.editor.field.emailAddress")}),!f&&s.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),s.jsx(Ht,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.emailAddressTooltip")})]}),s.jsx(tt,{type:"email",value:x,onChange:$=>v($.target.value),placeholder:i("settings.gitIdentities.editor.field.emailAddressPlaceholder"),required:!f,readOnly:f,disabled:f,className:"h-8"})]})]}),!f&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"border-t border-border/40"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:i("settings.gitIdentities.editor.field.authMethod")}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(Q,{size:"sm",type:"button",variant:"chip","aria-pressed":N==="ssh",onClick:()=>P("ssh"),children:[s.jsx(L,{name:"lock-2",className:"w-3.5 h-3.5 mr-1"})," SSH"]}),s.jsxs(Q,{size:"sm",type:"button",variant:"chip","aria-pressed":N==="token",onClick:()=>P("token"),children:[s.jsx(L,{name:"key",className:"w-3.5 h-3.5 mr-1"})," ",i("settings.gitIdentities.editor.field.authToken")]})]})]}),N==="ssh"&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:Kt,children:i("settings.gitIdentities.editor.field.sshKeyPath")}),s.jsx(Ht,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.sshKeyPathTooltip")})]}),s.jsx(tt,{value:F,onChange:$=>w($.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(wt,{checked:j,onChange:y,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:Kt,children:i("settings.gitIdentities.editor.field.signingKey")})}),s.jsx(tt,{value:R,onChange:$=>_($.target.value),placeholder:i("settings.gitIdentities.editor.field.signingKeyPlaceholder"),disabled:!j,className:"h-8 font-mono text-xs"})]})]}),N==="token"&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[s.jsx("label",{className:Kt,children:i("settings.gitIdentities.editor.field.host")}),s.jsx("span",{className:"text-[var(--status-error)] text-xs",children:"*"}),s.jsx(Ht,{contentClassName:"max-w-xs",children:i("settings.gitIdentities.editor.field.hostTooltip")})]}),s.jsx(tt,{value:B,onChange:$=>D($.target.value),placeholder:i("settings.gitIdentities.editor.field.hostPlaceholder"),required:!0,className:"h-8 font-mono text-xs"})]})]})]})]}),s.jsxs(Zt,{className:"gap-2",children:[!f&&!u&&s.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>X(!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(L,{name:"delete-bin",className:"w-3.5 h-3.5 mr-1"})," ",i("settings.common.actions.delete")]}),s.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>e(!1),className:"text-foreground hover:bg-interactive-hover hover:text-foreground",children:i(f?"settings.gitIdentities.editor.actions.close":"settings.common.actions.cancel")}),!f&&s.jsx(Q,{size:"sm",onClick:Z,disabled:V,children:i(V?"settings.common.actions.saving":u?"settings.gitIdentities.editor.actions.create":"settings.gitIdentities.editor.actions.save")})]})]})}),s.jsx(Lt,{open:Y,onOpenChange:$=>{S||X($)},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:i("settings.gitIdentities.page.deleteDialog.title")}),s.jsx(qt,{children:i("settings.gitIdentities.page.deleteDialog.description",{name:p?.name||m})})]}),s.jsxs(Zt,{children:[s.jsx(Q,{variant:"ghost",onClick:()=>X(!1),disabled:S,children:i("settings.common.actions.cancel")}),s.jsx(Q,{size:"sm",variant:"destructive",onClick:()=>{A()},disabled:S,children:i("settings.common.actions.delete")})]})]})})]})},Tv={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart"},Rv={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Dv=()=>{const t=Ye.c(113),{t:e}=it(),{profiles:n,globalIdentity:a,defaultGitIdentityId:i,deleteProfile:r,loadProfiles:o,loadGlobalIdentity:d,loadDiscoveredCredentials:c,loadDefaultGitIdentityId:p,setDefaultGitIdentityId:u,getUnimportedCredentials:f}=Os(zs(Lv)),[m,b]=l.useState(!1),[h,g]=l.useState(null),[x,v]=l.useState(null),[N,P]=l.useState(null),[F,w]=l.useState(!1);let j,y;t[0]!==p||t[1]!==c||t[2]!==d||t[3]!==o?(j=()=>{o(),d(),c(),p()},y=[o,d,c,p],t[0]=p,t[1]=c,t[2]=d,t[3]=o,t[4]=j,t[5]=y):(j=t[4],y=t[5]),l.useEffect(j,y);let R,_,B,D,k,T,M,O,V,U,Y,X,S,W;if(t[6]!==i||t[7]!==N||t[8]!==r||t[9]!==f||t[10]!==a||t[11]!==n||t[12]!==u||t[13]!==e){const je=f();let Ie;t[28]===Symbol.for("react.memo_cache_sentinel")?(Ie=(Ge,Fe)=>{g(Ge),v(Fe??null),b(!0)},t[28]=Ie):Ie=t[28];const Te=Ie;let Me;t[29]!==i||t[30]!==u||t[31]!==e?(Me=async Ge=>{const Fe=i===Ge?null:Ge;if(!await u(Fe)){G.error(e("settings.gitIdentities.page.toast.updateDefaultFailed"));return}G.success(e(Fe?"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 He=Me;let Ve;t[33]!==N||t[34]!==r||t[35]!==e?(Ve=async()=>{if(!N)return;w(!0),await r(N.id)?(G.success(e("settings.gitIdentities.page.toast.profileDeleted",{name:N.name})),P(null)):G.error(e("settings.gitIdentities.page.toast.deleteProfileFailed")),w(!1)},t[33]=N,t[34]=r,t[35]=e,t[36]=Ve):Ve=t[36],B=Ve,_=us,t[37]!==e?(D=e("settings.page.git.title"),t[37]=e,t[38]=D):D=t[38],k=!0,t[39]===Symbol.for("react.memo_cache_sentinel")?(T=s.jsx(ru,{}),t[39]=T):T=t[39],R=ot,t[40]!==e?(X=e("settings.gitIdentities.page.section.title"),t[40]=e,t[41]=X):X=t[41];let Ue,ze;t[42]===Symbol.for("react.memo_cache_sentinel")?(Ue=()=>Te("new"),ze=s.jsx(L,{name:"add",className:"w-3.5 h-3.5 mr-1"}),t[42]=Ue,t[43]=ze):(Ue=t[42],ze=t[43]);let Be;t[44]!==e?(Be=e("settings.common.badge.new"),t[44]=e,t[45]=Be):Be=t[45],t[46]!==Be?(S=s.jsxs(Q,{size:"sm",variant:"outline",onClick:Ue,children:[ze," ",Be]}),t[46]=Be,t[47]=S):S=t[47],W="git.identities",M="rounded-lg bg-[var(--surface-elevated)]/70 overflow-hidden flex flex-col",O=a&&s.jsx(Tc,{profile:a,isDefault:i==="global",onEdit:()=>Te("global"),onToggleDefault:()=>He("global"),isReadOnly:!0,hasBorder:n.length>0||je.length>0}),V=n.map((Ge,Fe)=>s.jsx(Tc,{profile:Ge,isDefault:i===Ge.id,onEdit:()=>Te(Ge.id),onToggleDefault:()=>He(Ge.id),onDelete:()=>P(Ge),hasBorder:Fe<n.length-1||je.length>0},Ge.id)),U=!a&&n.length===0&&je.length===0&&s.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground",children:[s.jsx(L,{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")})]}),Y=je.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")})}),je.map((Ge,Fe)=>s.jsx(Mv,{credential:Ge,onImport:()=>Te("new",{host:Ge.host,username:Ge.username}),hasBorder:Fe<je.length-1},`${Ge.host}-${Ge.username}`))]}),t[6]=i,t[7]=N,t[8]=r,t[9]=f,t[10]=a,t[11]=n,t[12]=u,t[13]=e,t[14]=R,t[15]=_,t[16]=B,t[17]=D,t[18]=k,t[19]=T,t[20]=M,t[21]=O,t[22]=V,t[23]=U,t[24]=Y,t[25]=X,t[26]=S,t[27]=W}else R=t[14],_=t[15],B=t[16],D=t[17],k=t[18],T=t[19],M=t[20],O=t[21],V=t[22],U=t[23],Y=t[24],X=t[25],S=t[26],W=t[27];let Z;t[48]!==M||t[49]!==O||t[50]!==V||t[51]!==U||t[52]!==Y?(Z=s.jsxs("div",{className:M,children:[O,V,U,Y]}),t[48]=M,t[49]=O,t[50]=V,t[51]=U,t[52]=Y,t[53]=Z):Z=t[53];let A;t[54]!==R||t[55]!==Z||t[56]!==X||t[57]!==S||t[58]!==W?(A=s.jsx(R,{title:X,headerAction:S,settingsItem:W,children:Z}),t[54]=R,t[55]=Z,t[56]=X,t[57]=S,t[58]=W,t[59]=A):A=t[59];let C;t[60]===Symbol.for("react.memo_cache_sentinel")?(C=s.jsx(iu,{}),t[60]=C):C=t[60];let z;t[61]!==_||t[62]!==D||t[63]!==k||t[64]!==T||t[65]!==A?(z=s.jsxs(_,{title:D,showSaveStatus:k,children:[T,A,C]}),t[61]=_,t[62]=D,t[63]=k,t[64]=T,t[65]=A,t[66]=z):z=t[66];let $;t[67]!==x||t[68]!==m||t[69]!==h?($=s.jsx(Ev,{open:m,onOpenChange:b,profileId:h,importData:x}),t[67]=x,t[68]=m,t[69]=h,t[70]=$):$=t[70];const H=N!==null;let J;t[71]!==F?(J=je=>{F||je||P(null)},t[71]=F,t[72]=J):J=t[72];let ee;t[73]!==e?(ee=e("settings.gitIdentities.page.deleteDialog.title"),t[73]=e,t[74]=ee):ee=t[74];let ue;t[75]!==ee?(ue=s.jsx(zt,{children:ee}),t[75]=ee,t[76]=ue):ue=t[76];const re=N?.name??"";let xe;t[77]!==e||t[78]!==re?(xe=e("settings.gitIdentities.page.deleteDialog.description",{name:re}),t[77]=e,t[78]=re,t[79]=xe):xe=t[79];let be;t[80]!==xe?(be=s.jsx(qt,{children:xe}),t[80]=xe,t[81]=be):be=t[81];let he;t[82]!==ue||t[83]!==be?(he=s.jsxs(Ut,{children:[ue,be]}),t[82]=ue,t[83]=be,t[84]=he):he=t[84];let ye;t[85]===Symbol.for("react.memo_cache_sentinel")?(ye=()=>P(null),t[85]=ye):ye=t[85];let fe;t[86]!==e?(fe=e("settings.common.actions.cancel"),t[86]=e,t[87]=fe):fe=t[87];let ae;t[88]!==F||t[89]!==fe?(ae=s.jsx(Q,{variant:"ghost",onClick:ye,disabled:F,children:fe}),t[88]=F,t[89]=fe,t[90]=ae):ae=t[90];let ce;t[91]!==B?(ce=()=>{B()},t[91]=B,t[92]=ce):ce=t[92];let pe;t[93]!==e?(pe=e("settings.common.actions.delete"),t[93]=e,t[94]=pe):pe=t[94];let q;t[95]!==F||t[96]!==ce||t[97]!==pe?(q=s.jsx(Q,{size:"sm",variant:"destructive",onClick:ce,disabled:F,children:pe}),t[95]=F,t[96]=ce,t[97]=pe,t[98]=q):q=t[98];let te;t[99]!==ae||t[100]!==q?(te=s.jsxs(Zt,{children:[ae,q]}),t[99]=ae,t[100]=q,t[101]=te):te=t[101];let ne;t[102]!==he||t[103]!==te?(ne=s.jsxs(Ft,{className:"max-w-md",children:[he,te]}),t[102]=he,t[103]=te,t[104]=ne):ne=t[104];let oe;t[105]!==H||t[106]!==J||t[107]!==ne?(oe=s.jsx(Lt,{open:H,onOpenChange:J,children:ne}),t[105]=H,t[106]=J,t[107]=ne,t[108]=oe):oe=t[108];let Ae;return t[109]!==z||t[110]!==$||t[111]!==oe?(Ae=s.jsxs(s.Fragment,{children:[z,$,oe]}),t[109]=z,t[110]=$,t[111]=oe,t[112]=Ae):Ae=t[112],Ae},Tc=t=>{const e=Ye.c(56),{profile:n,isDefault:a,onEdit:i,onToggleDefault:r,onDelete:o,isReadOnly:d,hasBorder:c}=t,{t:p}=it(),[u,f]=l.useState(!1),m=Tv[n.icon||"branch"]||"git-branch",b=Rv[n.color||""],h=n.authType||"ssh";let g;e[0]!==i?(g=A=>{A.currentTarget===A.target&&(A.key!=="Enter"&&A.key!==" "||(A.preventDefault(),i()))},e[0]=i,e[1]=g):g=e[1];const x=g;let v;e[2]!==a||e[3]!==d||e[4]!==o||e[5]!==r||e[6]!==p?(v=A=>s.jsxs(s.Fragment,{children:[s.jsx(A,{onClick:C=>{C.stopPropagation(),r()},children:p(a?"settings.gitIdentities.page.actions.unsetDefault":"settings.gitIdentities.page.actions.setAsDefault")}),!d&&o&&s.jsxs(A,{onClick:C=>{C.stopPropagation(),o()},className:"text-destructive focus:text-destructive",children:[s.jsx(L,{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]=v):v=e[7];const N=v,P=c&&"border-b border-[var(--surface-subtle)]";let F;e[8]!==P?(F=le("group flex items-center justify-between gap-3 px-4 py-2.5 transition-colors hover:bg-[var(--interactive-hover)]/30 cursor-pointer",P),e[8]=P,e[9]=F):F=e[9];let w;e[10]===Symbol.for("react.memo_cache_sentinel")?(w=A=>{A.preventDefault(),f(!0)},e[10]=w):w=e[10];let j;e[11]!==x||e[12]!==i||e[13]!==F?(j=s.jsx("div",{className:F,onClick:i,role:"button",tabIndex:0,onKeyDown:x,onContextMenu:w}),e[11]=x,e[12]=i,e[13]=F,e[14]=j):j=e[14];let y;e[15]!==b?(y={color:b},e[15]=b,e[16]=y):y=e[16];let R;e[17]!==m||e[18]!==y?(R=s.jsx(L,{name:m,className:"w-4 h-4 shrink-0",style:y}),e[17]=m,e[18]=y,e[19]=R):R=e[19];let _;e[20]!==n.name?(_=s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:n.name}),e[20]=n.name,e[21]=_):_=e[21];let B;e[22]!==h?(B=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]=B):B=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 k;e[27]!==d||e[28]!==p?(k=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]=k):k=e[29];let T;e[30]!==B||e[31]!==D||e[32]!==k||e[33]!==_?(T=s.jsxs("div",{className:"flex items-center gap-1.5",children:[_,B,D,k]}),e[30]=B,e[31]=D,e[32]=k,e[33]=_,e[34]=T):T=e[34];const M=h==="token"&&n.host?n.host:n.userEmail;let O;e[35]!==M?(O=s.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:M}),e[35]=M,e[36]=O):O=e[36];let V;e[37]!==T||e[38]!==O?(V=s.jsxs("div",{className:"min-w-0",children:[T,O]}),e[37]=T,e[38]=O,e[39]=V):V=e[39];let U;e[40]!==V||e[41]!==R?(U=s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[R,V]}),e[40]=V,e[41]=R,e[42]=U):U=e[42];let Y;e[43]===Symbol.for("react.memo_cache_sentinel")?(Y=s.jsx(ys,{asChild:!0,children:s.jsx(Q,{size:"icon",variant:"ghost",className:"h-6 w-6 shrink-0 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",onClick:Fv,children:s.jsx(L,{name:"more-2",className:"h-3.5 w-3.5"})})}),e[43]=Y):Y=e[43];let X;e[44]!==N?(X=s.jsxs(ws,{children:[Y,s.jsx(vs,{align:"end",className:"w-fit min-w-28",children:N(bs)})]}),e[44]=N,e[45]=X):X=e[45];let S;e[46]!==U||e[47]!==X||e[48]!==j?(S=s.jsxs(_n,{render:j,children:[U,X]}),e[46]=U,e[47]=X,e[48]=j,e[49]=S):S=e[49];let W;e[50]!==N?(W=s.jsx($n,{className:"w-fit min-w-28",children:N(En)}),e[50]=N,e[51]=W):W=e[51];let Z;return e[52]!==u||e[53]!==S||e[54]!==W?(Z=s.jsxs(Un,{open:u,onOpenChange:f,children:[S,W]}),e[52]=u,e[53]=S,e[54]=W,e[55]=Z):Z=e[55],Z},Mv=t=>{const e=Ye.c(21),{credential:n,onImport:a,hasBorder:i}=t,{t:r}=it();let o;e[0]!==n.host?(o=n.host.split("/"),e[0]=n.host,e[1]=o):o=e[1];const d=o,c=d.length>=3?d[d.length-1]:n.host,p=n.host.includes("/"),u=i&&"border-b border-[var(--surface-subtle)]";let f;e[2]!==u?(f=le("flex items-center justify-between gap-3 px-4 py-2.5 transition-colors hover:bg-[var(--interactive-hover)]/30",u),e[2]=u,e[3]=f):f=e[3];let m;e[4]!==c?(m=s.jsx("span",{className:"typography-ui-label text-foreground truncate block",children:c}),e[4]=c,e[5]=m):m=e[5];const b=p?n.host:n.username;let h;e[6]!==b?(h=s.jsx("span",{className:"typography-micro text-muted-foreground/60 truncate block leading-tight",children:b}),e[6]=b,e[7]=h):h=e[7];let g;e[8]!==m||e[9]!==h?(g=s.jsxs("div",{className:"min-w-0",children:[m,h]}),e[8]=m,e[9]=h,e[10]=g):g=e[10];let x;e[11]===Symbol.for("react.memo_cache_sentinel")?(x=s.jsx(L,{name:"download",className:"h-3 w-3"}),e[11]=x):x=e[11];let v;e[12]!==r?(v=r("settings.gitIdentities.page.actions.import"),e[12]=r,e[13]=v):v=e[13];let N;e[14]!==a||e[15]!==v?(N=s.jsxs(Q,{size:"sm",variant:"ghost",onClick:a,className:"gap-1 shrink-0",children:[x,v]}),e[14]=a,e[15]=v,e[16]=N):N=e[16];let P;return e[17]!==N||e[18]!==f||e[19]!==g?(P=s.jsxs("div",{className:f,children:[g,N]}),e[17]=N,e[18]=f,e[19]=g,e[20]=P):P=e[20],P};function Lv(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 Fv(t){return t.stopPropagation()}const ou=()=>{const t=Op();return{displayMode:t,installed:t!=="browser",browserTab:t==="browser"}},Ov=()=>{const t=Ye.c(2),[e,n]=l.useState(zv);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(ou())};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 zv(){return ou()}const Bv=[{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"}],Kv=[{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"}],Uv=[{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"}],Ga="OpenChamber - AI Coding Assistant",Rc=[{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"}],Dc=[{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"}],_v=[{value:"default",labelKey:"settings.openchamber.visual.option.mobileLayout.default"},{value:"new",labelKey:"settings.openchamber.visual.option.mobileLayout.new"}],Vr=t=>t==="portrait"||t==="landscape"?t:"system",$v=[{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"}],Vv=[{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"}],Mc=[{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"}],Hv=[{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"}],Lc=[{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"}],Fc=[{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"}],Wv=[{id:"steer",labelKey:"settings.openchamber.visual.option.followUpBehavior.steer.label"},{id:"queue",labelKey:"settings.openchamber.visual.option.followUpBehavior.queue.label"}],Gv=t=>t==="markdown"?"markdown":"plain",qv=[{id:"left",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsLeft"},{id:"right",labelKey:"settings.openchamber.desktopNetwork.option.windowControlsRight"}],cr=({visibleSettings:t})=>{const{locale:e,locales:n,setLocale:a,label:i,t:r}=it(),o=l.useCallback(E=>r(E),[r]),{isMobile:d}=_s(),{terminal:c}=li(),{browserTab:p}=Ov(),u=Mg(),f=Ne(E=>E.showReasoningTraces),m=Ne(E=>E.sessionRecapEnabled),b=Ne(E=>E.sessionSuggestionEnabled),h=Ne(E=>E.setSessionRecapEnabled),g=Ne(E=>E.setSessionSuggestionEnabled),x=Ne(E=>E.sessionGoalEnabled),v=Ne(E=>E.setSessionGoalEnabled),N=Ne(E=>E.sessionGoalDefaultBudgetEnabled),P=Ne(E=>E.setSessionGoalDefaultBudgetEnabled),F=Ne(E=>E.sessionGoalDefaultBudget),w=Ne(E=>E.setSessionGoalDefaultBudget),j=Ne(E=>E.setShowReasoningTraces),y=Ne(E=>E.collapsibleThinkingBlocks),R=Ne(E=>E.setCollapsibleThinkingBlocks),_=Ne(E=>E.mermaidRenderingMode),B=Ne(E=>E.setMermaidRenderingMode),D=Ne(E=>E.userMessageRenderingMode),k=Ne(E=>E.setUserMessageRenderingMode),T=Ne(E=>E.collapsibleUserMessages),M=Ne(E=>E.setCollapsibleUserMessages),O=Ne(E=>E.stickyUserHeader),V=Ne(E=>E.promptNavigatorEnabled),U=Ne(E=>E.setStickyUserHeader),Y=Ne(E=>E.setPromptNavigatorEnabled),X=Ne(E=>E.expandedEditorToolbar),S=Ne(E=>E.setExpandedEditorToolbar),W=Ne(E=>E.wideChatLayoutEnabled),Z=Ne(E=>E.setWideChatLayoutEnabled),A=Ne(E=>E.codeBlockLineWrap),C=Ne(E=>E.setCodeBlockLineWrap),z=Ne(E=>E.chatRenderMode),$=Ne(E=>E.setChatRenderMode),H=Ne(E=>E.activityRenderMode),J=Ne(E=>E.setActivityRenderMode),ee=Ne(E=>E.fontSize),ue=Ne(E=>E.setFontSize),re=Ne(E=>E.terminalFontSize),xe=Ne(E=>E.setTerminalFontSize),be=Ne(E=>E.terminalShell),he=Ne(E=>E.setTerminalShell),ye=Ne(E=>E.terminalLoginShells),fe=Ne(E=>E.setTerminalLoginShells),ae=Ne(E=>E.editorFontSize),ce=Ne(E=>E.setEditorFontSize),pe=Ne(E=>E.uiFont),q=Ne(E=>E.setUiFont),te=Ne(E=>E.monoFont),ne=Ne(E=>E.setMonoFont),oe=Ne(E=>E.padding),Ae=Ne(E=>E.setPadding),je=Ne(E=>E.inputBarOffset),Ie=Ne(E=>E.setInputBarOffset),Te=Ne(E=>E.mobileKeyboardMode),Me=Ne(E=>E.setMobileKeyboardMode),He=Ne(E=>E.diffLayoutPreference),Ve=Ne(E=>E.setDiffLayoutPreference),Ue=Ne(E=>E.showTerminalQuickKeysOnDesktop),ze=Ne(E=>E.setShowTerminalQuickKeysOnDesktop),Be=Ne(E=>E.fileEditorKeymap),Ge=Ne(E=>E.setFileEditorKeymap),Fe=xl(E=>E.followUpBehavior),ve=xl(E=>E.setFollowUpBehavior),De=Ne(E=>E.persistChatDraft),Ke=Ne(E=>E.setPersistChatDraft),We=Ne(E=>E.inputSpellcheckEnabled),Pe=Ne(E=>E.setInputSpellcheckEnabled),at=Ne(E=>E.showToolFileIcons),se=Ne(E=>E.setShowToolFileIcons),I=Ne(E=>E.showTurnChangedFiles),Ee=Ne(E=>E.setShowTurnChangedFiles),Le=Ne(E=>E.showExpandedBashTools),_e=Ne(E=>E.setShowExpandedBashTools),Xe=Ne(E=>E.showExpandedEditTools),ct=Ne(E=>E.setShowExpandedEditTools),ut=Ne(E=>E.timeFormatPreference),lt=Ne(E=>E.setTimeFormatPreference),rt=Ne(E=>E.weekStartPreference),mt=Ne(E=>E.setWeekStartPreference),xt=Ne(E=>E.showSplitAssistantMessageActions),It=Ne(E=>E.setShowSplitAssistantMessageActions),Se=Ne(E=>E.allowPromptingSubagentSessions),qe=Ne(E=>E.setAllowPromptingSubagentSessions),Ze=Ne(E=>E.draftStartersVisible),nt=Ne(E=>E.setDraftStartersVisible),ft=pt(E=>E.settingsMessageStreamTransport),vt=pt(E=>E.setSettingsMessageStreamTransport),St=ft,de=pt(E=>E.settingsDefaultFileViewerPreview),ie=pt(E=>E.setSettingsDefaultFileViewerPreview),we=Ne(E=>E.isSettingsDialogOpen),{themeMode:me,setThemeMode:Je,availableThemes:$e,customThemesLoading:et,reloadCustomThemes:bt,lightThemeId:Dt,darkThemeId:Qt,setLightThemePreference:_t,setDarkThemePreference:as}=oi(),[is,$t]=l.useState(!1),Ce=l.useMemo(()=>ss()&&typeof window<"u"&&window.__OPENCHAMBER_ELECTRON__?.macVibrancySupported===!0,[]),jt=typeof window<"u"&&window.__OPENCHAMBER_ELECTRON__?.macVibrancy===!0,[Qe,ht]=l.useState(jt),[Nt,Pt]=l.useState(!1),Mt=l.useMemo(()=>ss()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",[]),cs=Ne(E=>E.dockBadgeEnabled),$s=Ne(E=>E.setDockBadgeEnabled),Yt=Lg(),oa=Ne(E=>E.desktopWindowControlsPosition),Hn=Ne(E=>E.setDesktopWindowControlsPosition),[dr,ur]=l.useState(0),mr=Ne(E=>E.reportUsage),di=Ne(E=>E.setReportUsage),pr=l.useCallback(E=>{di(E),kt({reportUsage:E})},[di]),Ks=l.useCallback(E=>{Hn(E),kt({desktopWindowControlsPosition:E})},[Hn]),la=(we||d||os())&&(t?t.includes("chatRenderMode"):!0);l.useEffect(()=>{if(!la)return;let E=null,Ct=Date.now();const Ns=()=>{const xn=Date.now();xn-Ct>=420&&(ur(qn=>(qn+1)%24),Ct=xn),E=requestAnimationFrame(Ns)};(typeof document>"u"||document.visibilityState==="visible")&&(E=requestAnimationFrame(Ns));const ps=()=>{document.visibilityState==="visible"&&E===null?E=requestAnimationFrame(Ns):document.visibilityState!=="visible"&&E!==null&&(cancelAnimationFrame(E),E=null)};return document.addEventListener("visibilitychange",ps),()=>{document.removeEventListener("visibilitychange",ps),E!==null&&cancelAnimationFrame(E)}},[la]);const gr=l.useCallback(E=>{k(E),kt({userMessageRenderingMode:E})},[k]),ui=l.useCallback(E=>{U(E),kt({stickyUserHeader:E})},[U]),fr=l.useCallback(E=>{Y(E),kt({promptNavigatorEnabled:E})},[Y]),hr=l.useCallback(E=>{nt(E),kt({draftStartersVisible:E})},[nt]),xr=l.useCallback(E=>{S(E),kt({expandedEditorToolbar:E})},[S]),br=l.useCallback(E=>{M(E),kt({collapsibleUserMessages:E})},[M]),yr=l.useCallback(E=>{Z(E),kt({wideChatLayoutEnabled:E})},[Z]),Fs=l.useCallback(E=>{It(E),kt({showSplitAssistantMessageActions:E})},[It]),en=l.useCallback(E=>{Pe(E),kt({inputSpellcheckEnabled:E})},[Pe]),ca=l.useCallback(E=>{$(E),kt({chatRenderMode:E})},[$]),un=l.useCallback(E=>{vt(E),kt({messageStreamTransport:E})},[vt]),Tn=l.useCallback(E=>{J(E),kt({activityRenderMode:E})},[J]),$o=l.useCallback(E=>{B(E),kt({mermaidRenderingMode:E})},[B]),Rn=l.useCallback(E=>{se(E),kt({showToolFileIcons:E})},[se]),vr=l.useCallback(E=>{Ee(E),kt({showTurnChangedFiles:E})},[Ee]),da=l.useCallback(E=>{ie(E),kt({defaultFileViewerPreview:E}),window.dispatchEvent(new CustomEvent("openchamber:file-viewer-preview-mode-changed",{detail:{enabled:E}}))},[ie]),wr=l.useCallback(E=>{_e(E),kt({showExpandedBashTools:E})},[_e]),ms=l.useCallback(E=>{ct(E),kt({showExpandedEditTools:E})},[ct]),jr=l.useCallback(E=>{lt(E),kt({timeFormatPreference:E})},[lt]),ua=l.useCallback(E=>{mt(E),kt({weekStartPreference:E})},[mt]),mn=l.useMemo(()=>$e.filter(E=>E.metadata.variant==="light").sort((E,Ct)=>E.metadata.name.localeCompare(Ct.metadata.name)),[$e]),ma=l.useMemo(()=>$e.filter(E=>E.metadata.variant==="dark").sort((E,Ct)=>E.metadata.name.localeCompare(Ct.metadata.name)),[$e]),pa=l.useMemo(()=>mn.find(E=>E.metadata.id===Dt)??mn[0],[mn,Dt]),Dn=l.useMemo(()=>ma.find(E=>E.metadata.id===Qt)??ma[0],[ma,Qt]),pn=l.useCallback((E,Ct)=>{const Ns=Ct==="dark"?" Dark":" Light";return E.endsWith(Ns)?E.slice(0,-Ns.length):E},[]),Oe=E=>t?t.includes(E):!0,ts=os(),mi=Oe("theme")&&!ts,pi=Oe("windowControlsPosition")&&Yt,gi=Oe("theme")||Oe("timeFormat")||Oe("weekStart"),fi=d&&Sn()&&!ss()&&!ts,hi=ts?gi:Oe("theme")||pi||fi||Oe("pwaInstallName")||Oe("pwaOrientation")||Oe("timeFormat")||Oe("weekStart"),xi=Oe("fontSize")||Oe("terminalFontSize")||Oe("editorFontSize")||Oe("spacing")||Oe("inputBarOffset")&&d,bi=Oe("terminalQuickKeys")&&!d||(Oe("terminalShell")||Oe("terminalLoginShell"))&&!ts||Oe("fileEditorKeymap")||Oe("expandedEditorToolbar")&&!ts,kr=Oe("mermaidRendering")||Oe("sessionGoal")&&!ts||Oe("userMessageRendering")||Oe("chatRenderMode")||Oe("messageTransport")||Oe("activityRenderMode")&&z==="sorted"||Oe("collapsibleUserMessages")||Oe("stickyUserHeader")||Oe("promptNavigatorEnabled")&&!ts||Oe("wideChatLayout")||Oe("codeBlockLineWrap")||Oe("splitAssistantMessageActions")||Oe("subagentReadOnlyBanner")||Oe("diffLayout")||Oe("dotfiles")||Oe("fileViewerPreview")||Oe("reasoning")||Oe("followUpBehavior")||Oe("persistDraft")||Oe("showToolFileIcons")||Oe("expandedTools")||!d&&Oe("inputSpellcheck"),Wn=Oe("chatRenderMode")||Oe("activityRenderMode")&&z==="sorted",Fa=Oe("messageTransport"),K=Oe("userMessageRendering")||Oe("mermaidRendering")||Oe("diffLayout")&&!ts||Oe("followUpBehavior"),ke=Oe("sessionAssist")||Oe("sessionGoal")&&!ts||Oe("subagentReadOnlyBanner")||Oe("collapsibleUserMessages")||Oe("stickyUserHeader")||Oe("promptNavigatorEnabled")&&!ts||Oe("wideChatLayout")||Oe("codeBlockLineWrap")||Oe("splitAssistantMessageActions")||Oe("dotfiles")||Oe("fileViewerPreview")||Oe("persistDraft")||Oe("showToolFileIcons")||Oe("showTurnChangedFiles")||!d&&Oe("inputSpellcheck")||Oe("reasoning")||Oe("expandedTools"),st=hi||xi||bi,dt=Oe("pwaInstallName")&&Sn()&&p&&!ss()&&!ts,Ot=Oe("pwaOrientation")&&Sn()&&!ss()&&!ts,hs=Oe("mobileKeyboardMode")&&Sn()&&!ss()&&!ts&&Fg(),es=(Oe("terminalShell")||Oe("terminalLoginShell"))&&!ts,[Vs,qs]=l.useState([]),[Js,Oa]=l.useState(0);l.useEffect(()=>Lo(()=>{qs([]),Oa(E=>E+1)}),[]),l.useEffect(()=>{let E=!1;if(!(!es||!c.listShells))return c.listShells().then(Ct=>{E||qs(Ct)}).catch(()=>{E||qs([])}),()=>{E=!0}},[es,c,Js]);const Gn=l.useMemo(()=>{const E=Vs.filter(Ct=>Ct.id!=="auto");return be==="auto"||E.some(Ct=>Ct.id===be)?E:[{id:be,name:be,supportsLogin:!1},...E]},[Vs,be]),za=Vs.find(E=>E.id===be)?.supportsLogin===!0,Rt=ye.includes(be),ns=E=>{fe(E?[...ye.filter(Ct=>Ct!==be),be]:ye.filter(Ct=>Ct!==be))},[gn,Bt]=l.useState(()=>ef()),[ks,Us]=l.useState(""),[fn,hn]=l.useState("system"),Ru=l.useMemo(()=>{const E=Lc.find(Ct=>Ct.id===ut);return o(E?.labelKey??"settings.openchamber.visual.option.timeFormat.auto.label")},[ut,o]),Du=l.useMemo(()=>{const E=Fc.find(Ct=>Ct.id===rt);return o(E?.labelKey??"settings.openchamber.visual.option.weekStart.auto.label")},[rt,o]),Mu=l.useMemo(()=>{const E=Rc.find(Ct=>Ct.id===fn);return E?o(E.labelKey):void 0},[fn,o]),Lu=l.useMemo(()=>{const E=Dc.find(Ct=>Ct.id===Te);return E?o(E.labelKey):void 0},[Te,o]),Fu=l.useCallback(E=>{E!==gn&&(Bt(E),tf(E),window.location.reload())},[gn]),Nr=l.useCallback(async E=>{if(typeof window>"u")return;const Ct=window,ps=E.trim().replace(/\s+/g," ").slice(0,64);if(await kt({pwaAppName:ps}),typeof Ct.__OPENCHAMBER_SET_PWA_INSTALL_NAME__=="function"){const xn=Ct.__OPENCHAMBER_SET_PWA_INSTALL_NAME__(ps);Us(xn);return}Us(ps||Ga),Ct.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},[]),Vo=l.useCallback(async E=>{if(typeof window>"u")return;const Ct=window,Ns=Vr(E);if(await kt({pwaOrientation:Ns}),typeof Ct.__OPENCHAMBER_SET_PWA_ORIENTATION__=="function"){const ps=Ct.__OPENCHAMBER_SET_PWA_ORIENTATION__(Ns);hn(ps);return}hn(Ns),Ct.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},[]);return l.useEffect(()=>{if(typeof window>"u"||!dt&&!Ot&&!hs)return;let E=!1;return(async()=>{try{const Ns=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"},cache:"no-store"});if(!Ns.ok){E||Us(Ga);return}const ps=await Ns.json().catch(()=>({})),qn=(typeof ps?.pwaAppName=="string"?ps.pwaAppName:"").trim().replace(/\s+/g," ").slice(0,64),yi=Vr(ps?.pwaOrientation),Sr=wl(ps?.mobileKeyboardMode);E||(dt&&Us(qn||Ga),Ot&&hn(yi),hs&&Me(Sr))}catch{E||(dt&&Us(Ga),Ot&&hn("system"),hs&&Me("native"))}})(),()=>{E=!0}},[Me,hs,dt,Ot]),s.jsxs("div",{className:"space-y-0",children:[hi&&s.jsxs("div",{className:"space-y-0",children:[mi&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.colorModeAndTheme"),divider:!1,children:[s.jsxs(Yn,{children:[s.jsxs("div",{className:$a,children:[s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.section.colorMode"),children:Bv.map(E=>s.jsx(zn,{selected:me===E.value,onSelect:()=>Je(E.value),label:o(E.labelKey),ariaLabel:o(E.labelKey)},E.value))}),fi&&s.jsx(Aa,{children:s.jsx(ls,{label:r("settings.openchamber.visual.section.mobileLayout"),children:s.jsx(Zs,{value:gn,options:_v.map(E=>({value:E.value,label:o(E.labelKey)})),onChange:Fu,"aria-label":r("settings.openchamber.visual.section.mobileLayout")})})})]}),s.jsxs("div",{className:$a,children:[s.jsx(ls,{label:r("settings.openchamber.visual.field.lightTheme"),settingsItem:"appearance.light-theme",children:s.jsxs(At,{value:pa?.metadata.id??"",onValueChange:_t,children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.selectLightThemeAria"),size:Gt,className:yn,children:s.jsx(Vt,{placeholder:r("settings.openchamber.visual.field.selectThemePlaceholder"),children:pa?pn(pa.metadata.name,"light"):void 0})}),s.jsx(Tt,{children:mn.map(E=>s.jsx(yt,{value:E.metadata.id,children:pn(E.metadata.name,"light")},E.metadata.id))})]})}),s.jsx(ls,{label:r("settings.openchamber.visual.field.darkTheme"),settingsItem:"appearance.dark-theme",children:s.jsxs(At,{value:Dn?.metadata.id??"",onValueChange:as,children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.selectDarkThemeAria"),size:Gt,className:yn,children:s.jsx(Vt,{placeholder:r("settings.openchamber.visual.field.selectThemePlaceholder"),children:Dn?pn(Dn.metadata.name,"dark"):void 0})}),s.jsx(Tt,{children:ma.map(E=>s.jsx(yt,{value:E.metadata.id,children:pn(E.metadata.name,"dark")},E.metadata.id))})]})}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsxs("button",{type:"button",disabled:et||is,onClick:()=>{const E=Date.now();$t(!0),bt().finally(()=>{const Ct=Date.now()-E;if(Ct<500){window.setTimeout(()=>{$t(!1)},500-Ct);return}$t(!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(L,{name:"restart",className:le("h-3.5 w-3.5",is&&"animate-spin")}),r(is?"settings.openchamber.visual.actions.reloadingThemes":"settings.openchamber.visual.actions.reloadThemes")]}),s.jsx(Ht,{children:r("settings.openchamber.visual.field.themeImportInfoTooltip")})]})]})]}),Ce&&s.jsxs(Aa,{settingsItem:"appearance.window-transparency",className:"flex flex-col gap-1.5",children:[s.jsx(wt,{checked:Qe,onChange:ht,disabled:Nt,label:r("settings.openchamber.visual.field.macVibrancy"),info:r("settings.openchamber.visual.field.macVibrancyHint"),ariaLabel:r("settings.openchamber.visual.field.macVibrancy")}),Qe!==jt&&s.jsx("div",{className:"pl-6",children:s.jsx(Q,{variant:"outline",size:"sm",disabled:Nt,onClick:()=>{Pt(!0),Og("desktop_set_vibrancy",{enabled:Qe})},children:r(Nt?"settings.openchamber.visual.actions.restarting":"settings.openchamber.visual.actions.saveAndRestart")})})]}),Mt&&s.jsx(Aa,{settingsItem:"appearance.dock-badge",children:s.jsx(wt,{checked:cs,onChange:$s,label:r("settings.openchamber.visual.field.dockBadge"),info:r("settings.openchamber.visual.field.dockBadgeHint"),ariaLabel:r("settings.openchamber.visual.field.dockBadge")})})]}),pi&&s.jsx(ot,{title:r("settings.openchamber.desktopNetwork.field.windowControlsPosition"),description:r("settings.openchamber.desktopNetwork.field.windowControlsPositionDescription"),divider:mi,settingsItem:"sessions.desktop-window-controls-position",children:s.jsx(Zs,{value:oa,options:qv.map(E=>({value:E.id,label:o(E.labelKey)})),onChange:Ks,"aria-label":r("settings.openchamber.desktopNetwork.field.windowControlsPositionAria")})}),gi&&s.jsx(ot,{title:r("settings.openchamber.visual.section.localization"),children:s.jsxs(Yn,{children:[s.jsx(ls,{label:r("settings.appearance.language.label"),info:r("settings.appearance.language.description"),settingsItem:"appearance.language",children:s.jsxs(At,{value:e,onValueChange:E=>a(E),children:[s.jsx(Et,{"aria-label":r("settings.appearance.language.select"),size:Gt,className:yn,children:s.jsx(Vt,{children:i(e)})}),s.jsx(Tt,{children:n.map(E=>s.jsx(yt,{value:E,children:i(E)},E))})]})}),(Oe("timeFormat")||Oe("weekStart"))&&s.jsxs("div",{className:$a,children:[Oe("timeFormat")&&s.jsx(ls,{label:r("settings.openchamber.visual.field.timeFormat"),settingsItem:"appearance.time-format",children:s.jsxs(At,{value:ut,onValueChange:E=>jr(E),children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.selectTimeFormatAria"),size:Gt,className:yn,children:s.jsx(Vt,{children:Ru})}),s.jsx(Tt,{children:Lc.map(E=>s.jsx(yt,{value:E.id,children:o(E.labelKey)},E.id))})]})}),Oe("weekStart")&&s.jsx(ls,{label:r("settings.openchamber.visual.field.weekStartsOn"),settingsItem:"appearance.week-start",children:s.jsxs(At,{value:rt,onValueChange:E=>ua(E),children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.selectWeekStartAria"),size:Gt,className:yn,children:s.jsx(Vt,{children:Du})}),s.jsx(Tt,{children:Fc.map(E=>s.jsx(yt,{value:E.id,children:o(E.labelKey)},E.id))})]})})]})]})}),(dt||Ot||hs)&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.appInstall"),contentClassName:$a,children:[dt&&s.jsxs(Jt,{label:r("settings.openchamber.visual.field.installAppName"),info:r("settings.openchamber.visual.field.installAppNameHint"),settingsItem:"appearance.pwa-install-name",alignEnd:!1,controlClassName:Ws,children:[s.jsx(tt,{value:ks,onChange:E=>{Us(E.target.value)},onBlur:()=>{Nr(ks)},onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),Nr(ks))},className:"min-w-0 flex-1",maxLength:64,"aria-label":r("settings.openchamber.visual.field.pwaInstallAppNameAria")}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Us(Ga),Nr("")},className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetInstallAppNameAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]}),Ot&&s.jsxs(Jt,{label:r("settings.openchamber.visual.field.installOrientation"),description:r("settings.openchamber.visual.field.installOrientationHint"),settingsItem:"appearance.pwa-orientation",alignEnd:!1,controlClassName:Ws,children:[s.jsxs(At,{value:fn,onValueChange:E=>{const Ct=Vr(E);hn(Ct),Vo(Ct)},children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.pwaInstallOrientationAria"),size:Gt,className:Ml,children:s.jsx(Vt,{placeholder:r("settings.openchamber.visual.field.selectOrientationPlaceholder"),children:Mu})}),s.jsx(Tt,{children:Rc.map(E=>s.jsx(yt,{value:E.id,children:o(E.labelKey)},E.id))})]}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>{hn("system"),Vo("system")},disabled:fn==="system",className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetInstallOrientationAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]}),hs&&s.jsxs(Jt,{label:r("settings.openchamber.visual.field.mobileKeyboardMode"),info:r("settings.openchamber.visual.field.mobileKeyboardModeHint"),settingsItem:"appearance.mobile-keyboard-mode",alignEnd:!1,controlClassName:Ws,children:[s.jsxs(At,{value:Te,onValueChange:E=>{const Ct=wl(E);Me(Ct),kt({mobileKeyboardMode:Ct})},children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.mobileKeyboardModeAria"),size:Gt,className:Ml,children:s.jsx(Vt,{placeholder:r("settings.openchamber.visual.field.selectMobileKeyboardModePlaceholder"),children:Lu})}),s.jsx(Tt,{children:Dc.map(E=>s.jsx(yt,{value:E.id,children:o(E.labelKey)},E.id))})]}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>{Me("native"),kt({mobileKeyboardMode:"native"})},disabled:Te==="native",className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetMobileKeyboardModeAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})]})]}),xi&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.densityAndType"),contentClassName:$a,children:[Oe("fontSize")&&!d||Oe("terminalFontSize")?s.jsxs(Yn,{children:[Oe("fontSize")&&!d&&s.jsxs(ls,{label:r("settings.openchamber.visual.field.interfaceFont"),settingsItem:"appearance.interface-font-size",controlClassName:"w-full",children:[s.jsxs(At,{value:pe,onValueChange:E=>q(E),children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.selectInterfaceFontAria"),size:Gt,className:yn,children:s.jsx(Vt,{children:bl.find(E=>E.id===pe)?.label})}),s.jsx(Tt,{children:bl.map(E=>s.jsx(yt,{value:E.id,children:s.jsx("span",{style:{fontFamily:E.stack},children:E.label})},E.id))})]}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>q(yl),disabled:pe===yl,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetInterfaceFontAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]}),Oe("terminalFontSize")&&s.jsxs(ls,{label:r("settings.openchamber.visual.field.codeFont"),controlClassName:"w-full",children:[s.jsxs(At,{value:te,onValueChange:E=>ne(E),children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.selectCodeFontAria"),size:Gt,className:yn,children:s.jsx(Vt,{children:vl.find(E=>E.id===te)?.label})}),s.jsx(Tt,{children:vl.map(E=>s.jsx(yt,{value:E.id,children:s.jsx("span",{style:{fontFamily:E.stack},children:E.label})},E.id))})]}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>ne(ei),disabled:te===ei,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetCodeFontAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})]}):null,Oe("fontSize")&&!d||Oe("terminalFontSize")||Oe("editorFontSize")?s.jsxs(Yn,{children:[Oe("fontSize")&&!d&&s.jsx(ls,{label:r("settings.openchamber.visual.field.interfaceFontSize"),controlClassName:"w-full",children:s.jsxs("div",{className:Ua,children:[s.jsx(Cs,{value:ee,onValueChange:ue,min:50,max:200,step:5,"aria-label":r("settings.openchamber.visual.field.fontSizePercentageAria")}),s.jsx("span",{className:_a,children:"%"}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>ue(100),disabled:ee===100,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetFontSizeAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})}),Oe("terminalFontSize")&&s.jsx(ls,{label:r("settings.openchamber.visual.field.terminalFontSize"),settingsItem:"appearance.terminal-font-size",controlClassName:"w-full",children:s.jsxs("div",{className:Ua,children:[s.jsx(Cs,{value:re,onValueChange:xe,min:9,max:52,step:1}),s.jsx("span",{className:_a,children:"px"}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>xe(13),disabled:re===13,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetTerminalFontSizeAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})}),Oe("editorFontSize")&&s.jsx(ls,{label:r("settings.openchamber.visual.field.editorFontSize"),settingsItem:"appearance.editor-font-size",controlClassName:"w-full",children:s.jsxs("div",{className:Ua,children:[s.jsx(Cs,{value:ae,onValueChange:ce,min:9,max:32,step:1}),s.jsx("span",{className:_a,children:"px"}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>ce(13),disabled:ae===13,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetEditorFontSizeAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null,Oe("spacing")||Oe("inputBarOffset")&&d?s.jsxs(Yn,{children:[Oe("spacing")&&s.jsx(ls,{label:r("settings.openchamber.visual.field.spacingDensity"),settingsItem:"appearance.spacing-density",controlClassName:"w-full",children:s.jsxs("div",{className:Ua,children:[s.jsx(Cs,{value:oe,onValueChange:Ae,min:50,max:200,step:5}),s.jsx("span",{className:_a,children:"%"}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>Ae(100),disabled:oe===100,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetSpacingAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})}),Oe("inputBarOffset")&&d&&s.jsx(ls,{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:Ua,children:[s.jsx(Cs,{value:je,onValueChange:Ie,min:0,max:100,step:5}),s.jsx("span",{className:_a,children:"px"}),s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:()=>Ie(0),disabled:je===0,className:Ts,"aria-label":r("settings.openchamber.visual.actions.resetInputBarOffsetAria"),title:r("settings.common.actions.reset"),children:s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"})})]})})]}):null]}),bi&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.navigation"),contentClassName:"space-y-4",children:[Oe("fileEditorKeymap")&&s.jsx(Ys,{title:r("settings.openchamber.visual.field.fileEditorKeymap"),settingsItem:"appearance.file-editor-keymap",children:s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.field.fileEditorKeymap"),children:["default","vim"].map(E=>s.jsx(zn,{selected:Be===E,onSelect:()=>Ge(E),label:r(`settings.openchamber.visual.option.fileEditorKeymap.${E}`),ariaLabel:r(`settings.openchamber.visual.option.fileEditorKeymap.${E}`)},E))})}),s.jsxs("div",{className:Rs,children:[Oe("expandedEditorToolbar")&&!ts&&s.jsx(wt,{checked:X,onChange:xr,label:r("settings.openchamber.visual.field.expandedEditorToolbar"),ariaLabel:r("settings.openchamber.visual.field.expandedEditorToolbarAria"),settingsItem:"appearance.expanded-editor-toolbar"}),Oe("terminalQuickKeys")&&!d&&s.jsx(wt,{checked:Ue,onChange:ze,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")}),es&&s.jsx(ls,{label:r("settings.openchamber.visual.field.terminalShell"),info:r("settings.openchamber.visual.field.terminalShellHint"),settingsItem:"appearance.terminal-shell",className:"pt-2",children:s.jsxs(At,{value:be,onValueChange:E=>{zg(E)&&he(E)},children:[s.jsx(Et,{"aria-label":r("settings.openchamber.visual.field.terminalShellAria"),size:Gt,className:yn,children:s.jsx(Vt,{})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"auto",children:r("settings.openchamber.visual.option.terminalShell.auto")}),Gn.map(E=>s.jsx(yt,{value:E.id,children:E.name},E.id))]})]})}),es&&za&&s.jsx(wt,{checked:Rt,onChange:ns,label:r("settings.openchamber.visual.field.terminalLoginShell"),ariaLabel:r("settings.openchamber.visual.field.terminalLoginShell"),settingsItem:"appearance.terminal-login-shell"})]})]}),kr&&s.jsxs(s.Fragment,{children:[Wn&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.chatDisplay"),divider:st,contentClassName:"space-y-6",children:[Oe("chatRenderMode")&&s.jsx(Ys,{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:Vv.map(E=>{const Ct=z===E.id,Ns=dr%12;return s.jsxs("button",{type:"button",onClick:()=>ca(E.id),"aria-pressed":Ct,className:le("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",Ct?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[s.jsx("span",{className:le("typography-ui-label",Ct?"text-foreground":"text-muted-foreground"),children:o(E.labelKey)}),s.jsx("div",{className:"mt-2 w-full rounded-md border border-border/60 bg-muted/30 p-2",children:E.id==="live"?s.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(ps=>{const xn=ps*3+1,qn=Ns-xn+1,yi=qn<=0?0:qn===1?42:qn===2?68:92,Sr=yi>0;return s.jsxs("div",{className:le("flex items-center gap-1.5 transition-all duration-300 motion-reduce:transition-none",Sr?"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:`${yi}%`}})]},ps)})}):s.jsx("div",{className:"space-y-1.5",children:[0,1,2].map(ps=>{const xn=Ns>=(ps+1)*3;return s.jsxs("div",{className:le("flex items-center gap-1.5 transition-all duration-300 motion-reduce:transition-none",xn?"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%"}})]},ps)})})})]},E.id)})})}),Oe("activityRenderMode")&&z==="sorted"&&s.jsx(Ys,{title:r("settings.openchamber.visual.section.activityDefault"),children:s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.section.activityDefaultAria"),children:Hv.map(E=>s.jsx(zn,{selected:H===E.id,onSelect:()=>Tn(E.id),label:o(E.labelKey),ariaLabel:r("settings.openchamber.visual.field.activityDefaultModeAria",{option:o(E.labelKey)})},E.id))})})]}),Fa&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.messageStreamTransport"),divider:Wn||st,settingsItem:"chat.message-transport",contentClassName:"space-y-2",children:[s.jsx(Zs,{value:St,options:Mc.map(E=>({value:E.id,label:o(E.labelKey)})),onChange:un,"aria-label":r("settings.openchamber.visual.section.messageStreamTransport")}),(()=>{const E=Mc.find(Ct=>Ct.id===St);return E?.descriptionKey?s.jsx("span",{className:"typography-meta text-muted-foreground",children:o(E.descriptionKey)}):null})()]}),K&&s.jsx(ot,{title:r("settings.openchamber.visual.section.chatMessageOptions"),divider:Wn||Fa||st,children:s.jsxs(Yn,{className:"lg:gap-y-6",children:[Oe("userMessageRendering")&&s.jsx(Ys,{title:r("settings.openchamber.visual.section.userMessageRendering"),children:s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.section.userMessageRenderingAria"),children:$v.map(E=>s.jsx(zn,{selected:Gv(D)===E.id,onSelect:()=>gr(E.id),label:o(E.labelKey),ariaLabel:r("settings.openchamber.visual.field.userMessageRenderingAria",{option:o(E.labelKey)})},E.id))})}),Oe("mermaidRendering")&&s.jsx(Ys,{title:r("settings.openchamber.visual.section.mermaidRendering"),children:s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.section.mermaidRenderingAria"),children:Uv.map(E=>s.jsx(zn,{selected:_===E.id,onSelect:()=>$o(E.id),label:o(E.labelKey),ariaLabel:r("settings.openchamber.visual.field.mermaidRenderingAria",{option:o(E.labelKey)})},E.id))})}),Oe("diffLayout")&&!ts&&s.jsx(Ys,{title:r("settings.openchamber.visual.section.diffLayout"),children:s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.section.diffLayoutAria"),children:Kv.map(E=>s.jsx(zn,{selected:He===E.id,onSelect:()=>Ve(E.id),label:o(E.labelKey),ariaLabel:r("settings.openchamber.visual.field.diffLayoutAria",{option:o(E.labelKey)})},E.id))})}),Oe("followUpBehavior")&&s.jsx(Ys,{title:r("settings.openchamber.visual.section.followUpBehavior"),settingsItem:"chat.follow-up-behavior",children:s.jsx(Bn,{"aria-label":r("settings.openchamber.visual.section.followUpBehaviorAria"),children:Wv.map(E=>s.jsx(zn,{selected:Fe===E.id,onSelect:()=>ve(E.id),label:o(E.labelKey),ariaLabel:r("settings.openchamber.visual.field.followUpBehaviorAria",{option:o(E.labelKey)})},E.id))})})]})}),ke&&s.jsxs(s.Fragment,{children:[Oe("expandedTools")&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.showToolsOpenedByDefault"),divider:Wn||Fa||K||st,contentClassName:Rs,children:[s.jsx(wt,{checked:Le,onChange:wr,label:r("settings.openchamber.visual.field.bash"),ariaLabel:r("settings.openchamber.visual.field.showExpandedBashToolsAria")}),s.jsx(wt,{checked:Xe,onChange:ms,label:r("settings.openchamber.visual.field.editTools"),ariaLabel:r("settings.openchamber.visual.field.showExpandedEditToolsAria")})]}),s.jsxs(ot,{title:r("settings.openchamber.visual.section.sessionAssistance"),settingsItem:"chat.session-assistance",contentClassName:Rs,children:[s.jsx(wt,{checked:Ze,onChange:hr,label:r("settings.openchamber.visual.field.draftStartersVisible"),ariaLabel:r("settings.openchamber.visual.field.draftStartersVisibleAria"),settingsItem:"chat.draft-starters-visible"}),Oe("sessionAssist")&&s.jsxs(s.Fragment,{children:[s.jsx(wt,{checked:m,onChange:h,label:r("settings.openchamber.visual.field.sessionRecap"),ariaLabel:r("settings.openchamber.visual.field.sessionRecapAria"),settingsItem:"chat.session-recap"}),s.jsx(wt,{checked:b,onChange:g,label:r("settings.openchamber.visual.field.sessionSuggestion"),ariaLabel:r("settings.openchamber.visual.field.sessionSuggestionAria"),settingsItem:"chat.session-suggestion"})]}),Oe("subagentReadOnlyBanner")&&s.jsx(wt,{checked:Se,onChange:qe,label:r("settings.openchamber.visual.field.allowPromptingSubagentSessions"),ariaLabel:r("settings.openchamber.visual.field.allowPromptingSubagentSessionsAria"),settingsItem:"chat.subagent-read-only-banner"})]}),Oe("sessionGoal")&&!ts&&s.jsxs(ot,{title:r("settings.openchamber.visual.goal.sectionTitle"),info:r("settings.openchamber.visual.goal.description"),contentClassName:Rs,children:[s.jsx(wt,{checked:x,onChange:v,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(wt,{checked:N,onChange:P,disabled:!x,label:r("settings.openchamber.visual.goal.budgetLabel"),ariaLabel:r("settings.openchamber.visual.goal.budgetAria")}),x&&N?s.jsx(Cs,{value:F,onValueChange:E=>{typeof E=="number"&&Number.isFinite(E)&&E>0&&w(Math.floor(E))},min:1e3,max:1e8,step:5e4}):null]})]}),Oe("reasoning")&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.reasoning"),settingsItem:"chat.reasoning",contentClassName:Rs,children:[s.jsx(wt,{checked:f,onChange:j,label:r("settings.openchamber.visual.field.showReasoningTraces"),ariaLabel:r("settings.openchamber.visual.field.showReasoningTracesAria"),settingsItem:"chat.reasoning-traces"}),f&&s.jsx(wt,{checked:y,onChange:R,label:r("settings.openchamber.visual.field.collapsibleThinkingBlocks"),ariaLabel:r("settings.openchamber.visual.field.collapsibleThinkingBlocksAria")})]}),(Oe("collapsibleUserMessages")||Oe("stickyUserHeader")||Oe("promptNavigatorEnabled")&&!ts||Oe("wideChatLayout")||Oe("splitAssistantMessageActions")||Oe("codeBlockLineWrap"))&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.messageAppearance"),settingsItem:"chat.message-appearance",contentClassName:Rs,children:[Oe("collapsibleUserMessages")&&s.jsx(wt,{checked:T,onChange:br,label:r("settings.openchamber.visual.field.collapsibleUserMessages"),ariaLabel:r("settings.openchamber.visual.field.collapsibleUserMessagesAria"),settingsItem:"chat.collapsible-user-messages"}),Oe("stickyUserHeader")&&s.jsx(wt,{checked:O,onChange:ui,label:r("settings.openchamber.visual.field.stickyUserHeader"),ariaLabel:r("settings.openchamber.visual.field.stickyUserHeaderAria"),settingsItem:"chat.sticky-user-header"}),Oe("promptNavigatorEnabled")&&!ts&&s.jsx(wt,{checked:V,onChange:fr,label:r("settings.openchamber.visual.field.promptNavigatorEnabled"),ariaLabel:r("settings.openchamber.visual.field.promptNavigatorEnabledAria"),settingsItem:"chat.prompt-navigator"}),Oe("wideChatLayout")&&s.jsx(wt,{checked:W,onChange:yr,label:r("settings.openchamber.visual.field.wideChatLayout"),ariaLabel:r("settings.openchamber.visual.field.wideChatLayoutAria"),settingsItem:"chat.wide-layout"}),Oe("splitAssistantMessageActions")&&s.jsx(wt,{checked:xt,onChange:Fs,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")}),Oe("codeBlockLineWrap")&&s.jsx(wt,{checked:A,onChange:C,label:r("settings.openchamber.visual.field.codeBlockLineWrap"),ariaLabel:r("settings.openchamber.visual.field.codeBlockLineWrapAria"),settingsItem:"chat.code-block-line-wrap"})]}),(Oe("showToolFileIcons")||Oe("showTurnChangedFiles")||Oe("dotfiles")&&!os()||Oe("fileViewerPreview"))&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.toolsAndFiles"),settingsItem:"chat.tools-and-files",contentClassName:Rs,children:[Oe("showToolFileIcons")&&s.jsx(wt,{checked:at,onChange:Rn,label:r("settings.openchamber.visual.field.showToolFileIcons"),ariaLabel:r("settings.openchamber.visual.field.showToolFileIconsAria"),settingsItem:"chat.tool-file-icons"}),Oe("showTurnChangedFiles")&&s.jsx(wt,{checked:I,onChange:vr,label:r("settings.openchamber.visual.field.showTurnChangedFiles"),ariaLabel:r("settings.openchamber.visual.field.showTurnChangedFilesAria"),settingsItem:"chat.changed-files"}),Oe("dotfiles")&&!os()&&s.jsx(wt,{checked:u,onChange:Bg,label:r("settings.openchamber.visual.field.showDotfiles"),ariaLabel:r("settings.openchamber.visual.field.showDotfilesAria"),settingsItem:"chat.dotfiles"}),Oe("fileViewerPreview")&&s.jsx(wt,{checked:de,onChange:da,label:r("settings.openchamber.defaults.field.openFilesPreview"),ariaLabel:r("settings.openchamber.defaults.field.openFilesPreviewAria")})]}),(Oe("persistDraft")||!d&&Oe("inputSpellcheck"))&&s.jsxs(ot,{title:r("settings.openchamber.visual.section.composer"),settingsItem:"chat.composer",contentClassName:Rs,children:[Oe("persistDraft")&&s.jsx(wt,{checked:De,onChange:Ke,label:r("settings.openchamber.visual.field.persistDraftMessages"),ariaLabel:r("settings.openchamber.visual.field.persistDraftMessagesAria"),settingsItem:"chat.persist-drafts"}),!d&&Oe("inputSpellcheck")&&s.jsx(wt,{checked:We,onChange:en,label:r("settings.openchamber.visual.field.enableSpellcheckInTextInputs"),ariaLabel:r("settings.openchamber.visual.field.enableSpellcheckInTextInputsAria"),settingsItem:"chat.spellcheck"})]})]})]}),Oe("reportUsage")&&s.jsx(ot,{title:r("settings.openchamber.visual.section.privacy"),children:s.jsx(wt,{checked:mr,onChange:pr,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"})})]})},Jv=1,Qv=365,Oc=30,Yv=[{value:"archive",labelKey:"settings.openchamber.sessionRetention.action.archive"},{value:"delete",labelKey:"settings.openchamber.sessionRetention.action.delete"}],lu=()=>{const t=Ye.c(87),{t:e}=it(),n=Ne(Xv),a=Ne(Zv),i=Ne(ew),r=Ne(tw),o=Ne(sw),d=Ne(nw);let c;t[0]===Symbol.for("react.memo_cache_sentinel")?(c={autoRun:!1},t[0]=c):c=t[0];const{candidates:p,isRunning:u,runCleanup:f,action:m}=zp(c),b=p.length;let h;t[1]!==f||t[2]!==e?(h=async()=>{const ue=await f({force:!0});if(ue.completedIds.length===0&&ue.failedIds.length===0){G.message(ue.action==="archive"?e("settings.openchamber.sessionRetention.toast.noneEligibleArchive"):e("settings.openchamber.sessionRetention.toast.noneEligibleDelete"));return}ue.completedIds.length>0&&G.success(ue.action==="archive"?e("settings.openchamber.sessionRetention.toast.archivedCount",{count:ue.completedIds.length}):e("settings.openchamber.sessionRetention.toast.deletedCount",{count:ue.completedIds.length})),ue.failedIds.length>0&&G.error(ue.action==="archive"?e("settings.openchamber.sessionRetention.toast.failedArchiveCount",{count:ue.failedIds.length}):e("settings.openchamber.sessionRetention.toast.failedDeleteCount",{count:ue.failedIds.length}))},t[1]=f,t[2]=e,t[3]=h):h=t[3];const g=h;let x;t[4]!==e?(x=e("settings.openchamber.sessionRetention.title"),t[4]=e,t[5]=x):x=t[5];let v;t[6]!==e?(v=e("settings.openchamber.sessionRetention.tooltip"),t[6]=e,t[7]=v):v=t[7];let N;t[8]!==e?(N=e("settings.openchamber.sessionRetention.field.enableAutoCleanup"),t[8]=e,t[9]=N):N=t[9];let P;t[10]!==e?(P=e("settings.openchamber.sessionRetention.field.enableAutoCleanupAria"),t[10]=e,t[11]=P):P=t[11];let F;t[12]!==n||t[13]!==r||t[14]!==N||t[15]!==P?(F=s.jsx(wt,{settingsItem:"sessions.auto-cleanup",checked:n,onChange:r,label:N,ariaLabel:P}),t[12]=n,t[13]=r,t[14]=N,t[15]=P,t[16]=F):F=t[16];let w;t[17]!==e?(w=e("settings.openchamber.sessionRetention.field.retentionPeriod"),t[17]=e,t[18]=w):w=t[18];let j;t[19]!==e?(j=e("settings.openchamber.sessionRetention.field.retentionPeriodAria"),t[19]=e,t[20]=j):j=t[20];let y;t[21]!==a||t[22]!==o||t[23]!==j?(y=s.jsx(Cs,{value:a,onValueChange:o,min:Jv,max:Qv,step:1,"aria-label":j,className:"w-20 tabular-nums"}),t[21]=a,t[22]=o,t[23]=j,t[24]=y):y=t[24];let R;t[25]!==e?(R=e("settings.openchamber.sessionRetention.field.days"),t[25]=e,t[26]=R):R=t[26];let _;t[27]!==R?(_=s.jsx("span",{className:"typography-ui-label text-muted-foreground",children:R}),t[27]=R,t[28]=_):_=t[28];let B;t[29]!==o?(B=()=>o(Oc),t[29]=o,t[30]=B):B=t[30];const D=a===Oc;let k;t[31]!==e?(k=e("settings.openchamber.sessionRetention.actions.resetRetentionAria"),t[31]=e,t[32]=k):k=t[32];let T;t[33]!==e?(T=e("settings.common.actions.reset"),t[33]=e,t[34]=T):T=t[34];let M;t[35]===Symbol.for("react.memo_cache_sentinel")?(M=s.jsx(L,{name:"restart",className:"h-3.5 w-3.5"}),t[35]=M):M=t[35];let O;t[36]!==B||t[37]!==D||t[38]!==k||t[39]!==T?(O=s.jsx(Q,{size:"sm",type:"button",variant:"ghost",onClick:B,disabled:D,className:Ts,"aria-label":k,title:T,children:M}),t[36]=B,t[37]=D,t[38]=k,t[39]=T,t[40]=O):O=t[40];let V;t[41]!==_||t[42]!==O||t[43]!==w||t[44]!==y?(V=s.jsxs(Jt,{settingsItem:"sessions.retention-period",label:w,children:[y,_,O]}),t[41]=_,t[42]=O,t[43]=w,t[44]=y,t[45]=V):V=t[45];let U;t[46]!==e?(U=e("settings.openchamber.sessionRetention.field.whenSessionsExpire"),t[46]=e,t[47]=U):U=t[47];let Y;t[48]!==e?(Y=Yv.map(ue=>({value:ue.value,label:e(ue.labelKey)})),t[48]=e,t[49]=Y):Y=t[49];let X;t[50]!==i||t[51]!==d||t[52]!==Y?(X=s.jsx(Zs,{value:i,onChange:d,options:Y}),t[50]=i,t[51]=d,t[52]=Y,t[53]=X):X=t[53];let S;t[54]!==U||t[55]!==X?(S=s.jsx(Jt,{settingsItem:"sessions.retention-action",label:U,children:X}),t[54]=U,t[55]=X,t[56]=S):S=t[56];let W;t[57]!==V||t[58]!==S?(W=s.jsxs(Aa,{className:"space-y-0",children:[V,S]}),t[57]=V,t[58]=S,t[59]=W):W=t[59];let Z;t[60]!==e?(Z=e("settings.openchamber.sessionRetention.manualCleanup.title"),t[60]=e,t[61]=Z):Z=t[61];let A;t[62]!==u||t[63]!==e?(A=e(u?"settings.openchamber.sessionRetention.actions.cleaningUp":"settings.openchamber.sessionRetention.actions.runCleanupNow"),t[62]=u,t[63]=e,t[64]=A):A=t[64];let C;t[65]!==g||t[66]!==u||t[67]!==A?(C=s.jsx(Q,{type:"button",variant:"outline",size:"xs",onClick:g,disabled:u,className:"!font-normal",children:A}),t[65]=g,t[66]=u,t[67]=A,t[68]=C):C=t[68];let z;t[69]!==Z||t[70]!==C?(z=s.jsx(Jt,{label:Z,children:C}),t[69]=Z,t[70]=C,t[71]=z):z=t[71];let $;t[72]!==m||t[73]!==b||t[74]!==e?($=m==="archive"?e("settings.openchamber.sessionRetention.manualCleanup.eligibleArchiveNow",{count:b}):e("settings.openchamber.sessionRetention.manualCleanup.eligibleDeleteNow",{count:b}),t[72]=m,t[73]=b,t[74]=e,t[75]=$):$=t[75];let H;t[76]!==$?(H=s.jsx("p",{className:"typography-meta text-muted-foreground",children:$}),t[76]=$,t[77]=H):H=t[77];let J;t[78]!==z||t[79]!==H?(J=s.jsxs("div",{className:"mt-1 py-1.5 space-y-1",children:[z,H]}),t[78]=z,t[79]=H,t[80]=J):J=t[80];let ee;return t[81]!==x||t[82]!==W||t[83]!==v||t[84]!==J||t[85]!==F?(ee=s.jsxs(ot,{title:x,info:v,children:[F,W,J]}),t[81]=x,t[82]=W,t[83]=v,t[84]=J,t[85]=F,t[86]=ee):ee=t[86],ee};function Xv(t){return t.autoDeleteEnabled}function Zv(t){return t.autoDeleteAfterDays}function ew(t){return t.sessionRetentionAction}function tw(t){return t.setAutoDeleteEnabled}function sw(t){return t.setAutoDeleteAfterDays}function nw(t){return t.setSessionRetentionAction}const zc=(t,e,n)=>!t||!Number.isFinite(t)?e:new Intl.DateTimeFormat(Mo(),{dateStyle:"medium",timeStyle:"short",hour12:n==="auto"?void 0:n==="12h"}).format(t),cu=()=>{const{t}=it(),e=Ne(y=>y.timeFormatPreference),[n,a]=l.useState(!1),[i,r]=l.useState(!0),[o,d]=l.useState(!1),[c,p]=l.useState(null),[u,f]=l.useState(!1),[m,b]=l.useState([]),[h,g]=l.useState(Bp),[x,v]=l.useState(""),N=l.useMemo(()=>Kp(),[]),P=l.useCallback(async()=>{r(!0),v("");try{const y=await Up();b(y)}catch(y){const R=y instanceof Error?y.message:t("settings.openchamber.passkeys.toast.loadFailed");v(R)}finally{r(!1)}},[t]);l.useEffect(()=>{let y=!1;return(async()=>{try{if(!N.supported){y||(a(!1),r(!1));return}y||a(!0)}catch{y||a(!1)}if(!y){const R=await Pr();if(g(R),!R.enabled){b([]),r(!1);return}await P()}})(),()=>{y=!0,il()}},[P,N.supported]);const F=l.useCallback(async()=>{if(!h.enabled){const y=t("settings.openchamber.passkeys.toast.enableUiPasswordFirst");v(y),G.message(y);return}if(!n){v(N.reason),G.message(N.reason);return}if(o){il(),d(!1);return}v(""),d(!0);try{await _p(),g(await Pr()),await P(),G.success(t("settings.openchamber.passkeys.toast.added"))}catch(y){if($p(y)){G.message(t("settings.openchamber.passkeys.toast.setupCanceled"));return}const R=y instanceof Error?y.message:t("settings.openchamber.passkeys.toast.addFailed");v(R),G.error(R)}finally{d(!1)}},[o,P,h.enabled,N.reason,n,t]),w=l.useCallback(async y=>{p(y),v("");try{await Vp(y),g(await Pr()),await P(),G.success(t("settings.openchamber.passkeys.toast.removed"))}catch(R){const _=R instanceof Error?R.message:t("settings.openchamber.passkeys.toast.removeFailed");v(_),G.error(_)}finally{p(null)}},[P,t]),j=l.useCallback(async()=>{f(!0),v("");try{await Hp(),window.location.reload()}catch(y){const R=y instanceof Error?y.message:t("settings.openchamber.passkeys.toast.clearAuthFailed");v(R),G.error(R),f(!1)}},[t]);return s.jsxs(ot,{title:t("settings.openchamber.passkeys.title"),children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs(Jt,{label:t("settings.openchamber.passkeys.field.currentDevice"),children:[s.jsx(Q,{type:"button",variant:o?"secondary":"outline",size:"xs",onClick:()=>{F()},disabled:i||u,className:"!font-normal",children:t(o?"settings.openchamber.passkeys.actions.cancelSetup":"settings.openchamber.passkeys.actions.add")}),s.jsx(Q,{type:"button",variant:"ghost",size:"xs",onClick:()=>{j()},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:N.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(y=>s.jsxs(Jt,{label:s.jsx("span",{className:"truncate",children:y.label}),alignEnd:!1,controlClassName:"justify-between sm:flex-1",children:[s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:y.lastUsedAt?t("settings.openchamber.passkeys.item.lastUsed",{time:zc(y.lastUsedAt,t("settings.openchamber.passkeys.time.neverUsed"),e)}):t("settings.openchamber.passkeys.item.added",{time:zc(y.createdAt,t("settings.openchamber.passkeys.time.neverUsed"),e)})}),s.jsx(Q,{type:"button",variant:"ghost",size:"xs",onClick:()=>{w(y.id)},disabled:c===y.id,className:"!font-normal text-muted-foreground hover:text-foreground",children:c===y.id?t("settings.openchamber.passkeys.actions.removing"):t("settings.common.actions.delete")})]},y.id))})]}),x&&s.jsx("div",{className:"mt-1 py-1.5",children:s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:x})})]})},Bc=t=>{const e=Kn(t);return e||{providerId:"",modelId:""}},du=()=>{const{t}=it(),e=pt(S=>S.setProvider),n=pt(S=>S.setModel),a=pt(S=>S.setAgent),i=pt(S=>S.setCurrentVariant),r=pt(S=>S.setSettingsDefaultModel),o=pt(S=>S.setSettingsDefaultVariant),d=pt(S=>S.setSettingsDefaultAgent),c=Ne(S=>S.showDeletionDialog),p=Ne(S=>S.setShowDeletionDialog),u=pt(S=>S.providers),[f,m]=l.useState(),[b,h]=l.useState(),[g,x]=l.useState(),[v,N]=l.useState(!0),[P,F]=l.useState(),[w,j]=l.useState(),[y,R]=l.useState(!0),_=l.useMemo(()=>Bc(f),[f]);l.useEffect(()=>{(async()=>{try{let W=null;if(!W){const Z=ln()?.settings;if(Z)try{const C=(await Z.load())?.settings;if(C){const z=C;W={defaultModel:typeof C.defaultModel=="string"?C.defaultModel:void 0,defaultVariant:typeof z.defaultVariant=="string"?z.defaultVariant:void 0,defaultAgent:typeof C.defaultAgent=="string"?C.defaultAgent:void 0,smallModelUseDefault:typeof z.smallModelUseDefault=="boolean"?z.smallModelUseDefault:void 0,smallModelOverride:typeof z.smallModelOverride=="string"?z.smallModelOverride:void 0}}}catch{}}if(!W){const Z=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});Z.ok&&(W=await Z.json())}if(W){const Z=typeof W.defaultModel=="string"&&W.defaultModel.trim().length>0?W.defaultModel.trim():void 0,A=typeof W.defaultVariant=="string"&&W.defaultVariant.trim().length>0?W.defaultVariant.trim():void 0,C=typeof W.defaultAgent=="string"&&W.defaultAgent.trim().length>0?W.defaultAgent.trim():void 0;Z!==void 0&&m(Z),A!==void 0&&h(A),C!==void 0&&x(C),typeof W.smallModelUseDefault=="boolean"&&N(W.smallModelUseDefault),typeof W.smallModelOverride=="string"&&W.smallModelOverride.trim()&&F(W.smallModelOverride.trim())}}catch(W){console.warn("Failed to load defaults settings:",W)}finally{R(!1)}})()},[]);const B=l.useCallback(async(S,W)=>{const Z=S&&W?`${S}/${W}`:void 0;m(Z),h(void 0),o(void 0),i(void 0),r(Z),S&&W&&u.find(C=>C.id===S)&&(e(S),n(W));try{await kt({defaultModel:Z??"",defaultVariant:""});const A=await gt("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:Z})});A.ok||console.warn("Failed to save default model to server:",A.status,A.statusText)}catch(A){console.warn("Failed to save default model:",A)}},[u,i,n,e,r,o]),D="__default__",k=l.useCallback(S=>S===D?t("settings.openchamber.defaults.option.default"):S.charAt(0).toUpperCase()+S.slice(1),[t]),T=l.useCallback(async S=>{const W=S===D?void 0:S||void 0;h(W),o(W),i(W);try{await kt({defaultVariant:W??""})}catch(Z){console.warn("Failed to save default variant:",Z)}},[i,o]),M=l.useCallback(async S=>{const W=S||void 0;x(W),d(W),S&&a(S);try{await kt({defaultAgent:W??""})}catch(Z){console.warn("Failed to save default agent:",Z)}},[a,d]),O=l.useCallback(async S=>{N(S);try{await kt({smallModelUseDefault:S})}catch(W){console.warn("Failed to save small model preference:",W)}},[]),V=l.useCallback(async(S,W)=>{const Z=S&&W?`${S}/${W}`:void 0;F(Z);try{await kt({smallModelOverride:Z??""})}catch(A){console.warn("Failed to save small model override:",A)}},[]),U=l.useMemo(()=>Bc(P),[P]);l.useEffect(()=>{if(v||w!==void 0)return;let S=!1;return(async()=>{try{const W=await gt("/api/small-model",{method:"GET",headers:{Accept:"application/json"}});if(!W.ok)return;const Z=await W.json().catch(()=>null);!S&&Array.isArray(Z?.authenticatedProviders)&&j(Z.authenticatedProviders.filter(A=>typeof A=="string"))}catch{}})(),()=>{S=!0}},[v,w]);const Y=l.useMemo(()=>{if(!_.providerId||!_.modelId)return[];const Z=u.find(A=>A.id===_.providerId)?.models.find(A=>A.id===_.modelId)?.variants;return Z?Object.keys(Z):[]},[_.modelId,_.providerId,u]),X=Y.length>0;return l.useEffect(()=>{!X&&b&&(h(void 0),o(void 0),i(void 0),kt({defaultVariant:""}).catch(()=>{}))},[b,i,o,X]),y?null:s.jsx(s.Fragment,{children:s.jsx(ot,{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")," ",_.providerId?s.jsxs("span",{className:"text-foreground",children:[_.providerId,"/",_.modelId,X?` (${b??t("settings.openchamber.defaults.option.defaultLowercase")})`:""]}):s.jsx("span",{className:"text-foreground",children:t("settings.openchamber.defaults.summaryOpenCodeDefault")}),g&&s.jsxs(s.Fragment,{children:[" / ",s.jsx("span",{className:"text-foreground",children:g})]})]}),s.jsxs("div",{children:[s.jsx(Jt,{settingsItem:"sessions.default-model",label:t("settings.openchamber.defaults.field.defaultModel"),children:s.jsx(ni,{providerId:_.providerId,modelId:_.modelId,onChange:B,className:ta})}),s.jsx(Jt,{settingsItem:"sessions.default-thinking",label:t("settings.openchamber.defaults.field.defaultThinking"),children:s.jsxs(At,{value:b??D,onValueChange:T,disabled:!X,children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{placeholder:t("settings.openchamber.defaults.field.thinkingPlaceholder"),children:k(b??D)})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:D,children:t("settings.openchamber.defaults.option.default")}),Y.map(S=>s.jsx(yt,{value:S,children:k(S)},S))]})]})}),s.jsx(Jt,{settingsItem:"sessions.default-agent",label:t("settings.openchamber.defaults.field.defaultAgent"),children:s.jsx(jd,{agentName:g||"",onChange:M,className:ta})})]}),s.jsx(Aa,{className:Rs,children:s.jsx(wt,{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(An,{children:t("settings.openchamber.defaults.smallModel.title")}),s.jsx(Ht,{children:t("settings.openchamber.defaults.smallModel.description")})]}),s.jsx(wt,{settingsItem:"sessions.small-model",checked:v,onChange:S=>{O(S)},label:t("settings.openchamber.defaults.smallModel.useDefault"),ariaLabel:t("settings.openchamber.defaults.smallModel.useDefaultAria")}),v?null:s.jsx(Jt,{label:t("settings.openchamber.defaults.smallModel.overrideModel"),children:s.jsx(ni,{providerId:U.providerId,modelId:U.modelId,onChange:V,allowedProviderIds:w,className:ta})})]})]})})})},Kc={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"}},aw={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"},iw=()=>{const{t}=it(),e=l.useMemo(()=>ss(),[]),n=l.useMemo(()=>os(),[]),a=l.useMemo(()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",[]),i=!e&&!n&&!a,r=Ne(A=>A.nativeNotificationsEnabled),o=Ne(A=>A.setNativeNotificationsEnabled),d=Ne(A=>A.notificationMode),c=Ne(A=>A.setNotificationMode),p=Ne(A=>A.notifyOnSubtasks),u=Ne(A=>A.setNotifyOnSubtasks),f=Ne(A=>A.notifyOnCompletion),m=Ne(A=>A.setNotifyOnCompletion),b=Ne(A=>A.notifyOnError),h=Ne(A=>A.setNotifyOnError),g=Ne(A=>A.notifyOnQuestion),x=Ne(A=>A.setNotifyOnQuestion),v=Ne(A=>A.notificationTemplates),N=Ne(A=>A.setNotificationTemplates),[P,F]=l.useState("default"),[w,j]=l.useState(!1),[y,R]=l.useState(!1),[_,B]=l.useState(!1);l.useEffect(()=>{if(!i){j(!1),R(!1);return}typeof Notification<"u"&&F(Notification.permission);const A=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;j(A),(async()=>{if(!A){R(!1);return}try{const z=await navigator.serviceWorker.getRegistration();if(!z){R(!1);return}const $=await z.pushManager.getSubscription();R(!!$)}catch{R(!1)}})()},[i]);const D=async A=>{if(e){o(A);return}if(!i){o(A);return}if(A&&typeof Notification<"u"&&Notification.permission==="default")try{const C=await Notification.requestPermission();F(C),C==="granted"?o(!0):G.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.description")})}catch(C){console.error("Failed to request notification permission:",C),G.error(t("settings.notifications.page.toast.requestPermissionFailed"))}else o(!!(A&&P==="granted"))},k=e||n||a||i&&typeof Notification<"u"&&Notification.permission==="granted",T=(A,C,z)=>{N({...v,[A]:{...v[A],[C]:z}})},M=A=>{const C="=".repeat((4-A.length%4)%4),z=(A+C).replace(/-/g,"+").replace(/_/g,"/"),$=atob(z),H=new Uint8Array($.length);for(let J=0;J<$.length;J+=1)H[J]=$.charCodeAt(J);return H},O=async(A,C,z)=>{let $=null;const H=new Promise((J,ee)=>{$=setTimeout(()=>{ee(new Error(z))},C)});try{return await Promise.race([A,H])}finally{$&&clearTimeout($)}},V=async A=>{if(A.active)return;const C=A.installing||A.waiting;C&&C.state!=="activated"&&await O(new Promise(z=>{const $=()=>{C.state==="activated"&&(C.removeEventListener("statechange",$),z())};C.addEventListener("statechange",$),$()}),15e3,"Service worker activation timed out")},U=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const A=[{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 C=null;for(const z of A)try{const $=z.opts?navigator.serviceWorker.register("/sw.js",z.opts):navigator.serviceWorker.register("/sw.js");return await O($,1e4,`Service worker registration timed out (${z.label})`)}catch($){C=$}throw C instanceof Error?C:new Error("Service worker registration failed")},Y=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const A=await navigator.serviceWorker.getRegistration();if(A)return A;const C=await U();try{await C.update()}catch{}return await V(C),C},X=A=>{const C=A,z=[`type=${typeof A}`,`toString=${String(A)}`,`name=${String(C?.name??"")}`,`message=${String(C?.message??"")}`];let $="";try{$=JSON.stringify(A)}catch{}return{summary:z.filter(Boolean).join(" | "),json:$,stack:typeof C?.stack=="string"?C.stack:""}},S=async()=>{const A=ln();if(!A?.notifications){G.error(t("settings.notifications.page.toast.notificationsApiUnavailable"));return}try{await A.notifications.notifyAgentCompletion({title:t("settings.notifications.page.testNotification.title"),body:t("settings.notifications.page.testNotification.body"),tag:"openchamber-test"})?G.success(t("settings.notifications.page.toast.testNotificationSent")):G.error(t("settings.notifications.page.toast.testNotificationFailed"))}catch(C){console.error("Test notification failed:",C),G.error(t("settings.notifications.page.toast.testNotificationFailed"))}},W=async()=>{if(!w){G.error(t("settings.notifications.page.toast.pushUnsupported"));return}const A=ln();if(!A?.push){G.error(t("settings.notifications.page.toast.pushApiUnavailable"));return}B(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const re=await Notification.requestPermission();if(F(re),re!=="granted"){G.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.enableInBrowser")});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){G.error(t("settings.notifications.page.toast.permissionDenied.title"),{description:t("settings.notifications.page.toast.permissionDenied.enableInBrowser")});return}const C=await A.push.getVapidPublicKey();if(!C?.publicKey){G.error(t("settings.notifications.page.toast.pushKeyLoadFailed"));return}const z=await Y();await V(z);const $=await z.pushManager.getSubscription();if(!("pushManager"in z)||!z.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const J=($??await O(z.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:M(C.publicKey)}),15e3,"Push subscription timed out")).toJSON(),ee=J.keys;if(!J.endpoint||!ee?.p256dh||!ee.auth)throw new Error("Push subscription missing keys");if(!(await O(A.push.subscribe({endpoint:J.endpoint,keys:{p256dh:ee.p256dh,auth:ee.auth},origin:typeof window<"u"?window.location.origin:void 0,platform:yd()}),15e3,"Push subscribe request timed out"))?.ok){G.error(t("settings.notifications.page.toast.enableBackgroundFailed"));return}R(!0),G.success(t("settings.notifications.page.toast.backgroundEnabled"))}catch(C){console.error("[Push] Enable failed:",C);const z=X(C);G.error(t("settings.notifications.page.toast.enableBackgroundFailed"),{description:z.summary})}finally{B(!1)}},Z=async()=>{if(!w){R(!1);return}const A=ln();if(!A?.push){G.error(t("settings.notifications.page.toast.pushApiUnavailable"));return}B(!0);try{const z=await(await Y()).pushManager.getSubscription();if(!z){R(!1);return}const $=z.endpoint;await z.unsubscribe(),await A.push.unsubscribe({endpoint:$}),R(!1),G.success(t("settings.notifications.page.toast.backgroundDisabled"))}finally{B(!1)}};return s.jsxs(s.Fragment,{children:[s.jsxs(ot,{settingsItem:"notifications.delivery",title:t("settings.notifications.page.delivery.title"),divider:!1,children:[s.jsxs("div",{className:Rs,children:[s.jsx(wt,{checked:r&&k,onChange:A=>{D(A)},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&&k&&!a&&s.jsxs(s.Fragment,{children:[s.jsx(wt,{checked:d==="always",onChange:A=>c(A?"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(Q,{type:"button",variant:"outline",size:"sm",onClick:()=>{S()},children:t("settings.notifications.page.delivery.testAction")})})]})]}),i&&s.jsxs("div",{className:"mt-1",children:[P==="denied"&&s.jsx("p",{className:"typography-meta text-[var(--status-error)] mt-1",children:t("settings.notifications.page.delivery.permissionDenied")}),P==="granted"&&!r&&s.jsx("p",{className:"typography-meta text-muted-foreground/70 mt-1",children:t("settings.notifications.page.delivery.permissionGrantedButDisabled")})]})]}),r&&k&&s.jsxs(s.Fragment,{children:[s.jsx(ot,{settingsItem:"notifications.events",title:t("settings.notifications.page.events.title"),children:s.jsxs("div",{className:Rs,children:[s.jsx(wt,{checked:f,onChange:m,label:t("settings.notifications.page.events.completionLabel"),ariaLabel:t("settings.notifications.page.events.completionAria")}),s.jsx(wt,{checked:p,onChange:u,label:t("settings.notifications.page.events.subtaskLabel"),ariaLabel:t("settings.notifications.page.events.subtaskAria")}),s.jsx(wt,{checked:b,onChange:h,label:t("settings.notifications.page.events.errorLabel"),ariaLabel:t("settings.notifications.page.events.errorAria")}),s.jsx(wt,{checked:g,onChange:x,label:t("settings.notifications.page.events.questionLabel"),ariaLabel:t("settings.notifications.page.events.questionAria")})]})}),!a&&s.jsx(ot,{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(Yn,{className:"gap-2 md:grid-cols-2 md:gap-3 lg:gap-3",children:["completion","subtask","error","question"].map(A=>s.jsxs("section",{className:"p-2",children:[s.jsx(An,{className:"capitalize",children:t(aw[A])}),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(tt,{value:v[A].title,onChange:C=>T(A,"title",C.target.value),className:"h-7",placeholder:t(Kc[A].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(tt,{value:v[A].message,onChange:C=>T(A,"message",C.target.value),className:"h-7",placeholder:t(Kc[A].messageKey)})]})]})]},A))})})]}),i&&s.jsx(ot,{settingsItem:"notifications.push",title:t("settings.notifications.page.push.title"),children:s.jsx(wt,{checked:w?y:!1,disabled:!w||_,onChange:A=>{A?W():Z()},label:t("settings.notifications.page.push.enableLabel"),description:w?void 0:t("settings.notifications.page.push.unsupportedHint"),info:w?t("settings.notifications.page.push.supportedHint"):void 0,ariaLabel:t("settings.notifications.page.push.enableAria"),labelAccessory:_?s.jsx("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-current text-muted-foreground animate-busy-pulse","aria-label":t("settings.notifications.page.push.loadingAria")}):null})})]})},Ms=t=>{if(!t)return;t.pause();const{src:e}=t;e.startsWith("blob:")&&URL.revokeObjectURL(e),t.removeAttribute("src"),t.load()},rw=[{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"}],Uc=t=>{const e=Ye.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},ow=({selectedModelId:t,onSelect:e})=>{const{t:n}=it(),a=ge.useCallback(m=>n(m),[n]),[i,r]=ge.useState(new Map),[o,d]=ge.useState(null),c=ge.useCallback(async()=>{try{const m=await gt("/api/dictation/status",{query:{provider:"local"}});if(!m.ok)return;const b=await m.json();Array.isArray(b?.models)&&r(new Map(b.models.map(h=>[h.id,h])))}catch{}},[]);ge.useEffect(()=>{c()},[c]);const p=Array.from(i.values()).some(m=>m.downloading);ge.useEffect(()=>{if(!p)return;const m=setInterval(()=>{c()},2e3);return()=>clearInterval(m)},[p,c]);const u=async m=>{d(m);try{await gt(`/api/dictation/models/${encodeURIComponent(m)}/download`,{method:"POST"}),await c()}catch{}finally{d(null)}},f=async m=>{d(m);try{await gt(`/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:rw.map(m=>{const b=t===m.id,h=i.get(m.id)??null;return s.jsx("div",{className:le("rounded-lg border border-[var(--interactive-border)] p-3",b&&"border-[var(--primary-base)] bg-[var(--primary-base)]/5"),children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 cursor-pointer items-start gap-2",role:"button",tabIndex:0,onClick:()=>e(m.id),onKeyDown:g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),e(m.id))},children:[s.jsx("div",{className:"pt-0.5",children:s.jsx(ir,{checked:b,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:le("typography-ui-label font-normal",b?"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(Uc,{value:m.accuracy,label:n("settings.voice.page.stt.meta.accuracy")}),s.jsx(Uc,{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(Q,{variant:"ghost",size:"xs",className:"h-6 w-6 p-0 text-muted-foreground hover:text-[var(--status-error)]",disabled:o===m.id,onClick:()=>{f(m.id)},title:n("settings.voice.page.stt.modelDelete"),"aria-label":n("settings.voice.page.stt.modelDelete"),children:s.jsx(L,{name:"delete-bin",className:"h-4 w-4"})}),s.jsx(L,{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(L,{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(Q,{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(L,{name:"download",className:"h-4 w-4"})})})]})},m.id)})})},Hr=[{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)"}],Wr="kokoro-en-v0_19",lw=()=>{const{t}=it(),[e,n]=ge.useState(null),[a,i]=ge.useState(!1),r=ge.useCallback(async()=>{try{const d=await gt("/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===Wr):null;p&&n(p)}catch{}},[]);ge.useEffect(()=>{r()},[r]),ge.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/${Wr}/download`:`/api/dictation/models/${Wr}`;await gt(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(L,{name:"checkbox-circle",className:"h-4 w-4 text-[var(--status-success)]","aria-label":t("settings.voice.page.stt.modelInstalled")}),s.jsx(Q,{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(L,{name:"delete-bin",className:"h-4 w-4"})})]}):e.downloading?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(L,{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(Q,{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(L,{name:"download",className:"h-4 w-4"})}),e.downloadError?s.jsx("span",{className:"typography-meta text-[var(--status-error)]",children:e.downloadError}):null]}):null},cw=[{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"}],dw=()=>{const{t}=it(),{isMobile:e}=_s(),n=pt(I=>I.voiceProvider),a=pt(I=>I.setVoiceProvider),i=pt(I=>I.speechRate),r=pt(I=>I.setSpeechRate),o=pt(I=>I.speechPitch),d=pt(I=>I.setSpeechPitch),c=pt(I=>I.speechVolume),p=pt(I=>I.setSpeechVolume),u=pt(I=>I.sayVoice),f=pt(I=>I.setSayVoice),m=pt(I=>I.localTtsVoiceId),b=pt(I=>I.setLocalTtsVoiceId),{speak:h,stop:g,isPlaying:x,error:v}=Wp(),N=ge.useCallback(()=>{if(x){g();return}const I=Hr.find(Ee=>Ee.id===m)?.label??String(m);h(t("settings.voice.page.preview.voiceLine",{voiceName:I}),{speakerId:m,speed:pt.getState().speechRate})},[x,m,h,g,t]),P=pt(I=>I.browserVoice),F=pt(I=>I.setBrowserVoice),w=pt(I=>I.openaiVoice),j=pt(I=>I.setOpenaiVoice),y=pt(I=>I.openaiApiKey),R=pt(I=>I.setOpenaiApiKey),_=pt(I=>I.openaiCompatibleUrl),B=pt(I=>I.setOpenaiCompatibleUrl),D=pt(I=>I.openaiCompatibleApiKey),k=pt(I=>I.setOpenaiCompatibleApiKey),T=pt(I=>I.openaiCompatibleVoice),M=pt(I=>I.setOpenaiCompatibleVoice),O=pt(I=>I.openaiCompatibleTtsModel),V=pt(I=>I.setOpenaiCompatibleTtsModel),U=pt(I=>I.showMessageTTSButtons),Y=pt(I=>I.ttsInputMode),X=pt(I=>I.setTtsInputMode),S=pt(I=>I.sttProvider),W=pt(I=>I.setSttProvider),Z=pt(I=>I.sttServerUrl),A=pt(I=>I.setSttServerUrl),C=pt(I=>I.sttApiKey),z=pt(I=>I.setSttApiKey),$=pt(I=>I.sttModel),H=pt(I=>I.setSttModel),J=pt(I=>I.sttLocalModel),ee=pt(I=>I.setSttLocalModel),ue=pt(I=>I.sttLanguage),re=pt(I=>I.setSttLanguage),xe=pt(I=>I.setShowMessageTTSButtons),be=pt(I=>I.dictationEnabled),he=pt(I=>I.setDictationEnabled),[ye,fe]=ge.useState(!1),[ae,ce]=ge.useState([]),[pe,q]=ge.useState(!1),[te,ne]=ge.useState(null),[oe,Ae]=ge.useState(!1),[je,Ie]=ge.useState(!1),[Te,Me]=ge.useState(null),[He,Ve]=ge.useState(!1),[Ue,ze]=ge.useState(null),[Be,Ge]=ge.useState([]),[Fe,ve]=ge.useState(!1);ge.useEffect(()=>((async()=>{const Ee=await Ar.waitForVoices();Ge(Ee)})(),"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=()=>{Ge(window.speechSynthesis.getVoices())}),()=>{"speechSynthesis"in window&&(window.speechSynthesis.onvoiceschanged=null)}),[]);const De=ge.useMemo(()=>Be.filter(I=>I.lang).sort((I,Ee)=>{const Le=I.lang.startsWith("en"),_e=Ee.lang.startsWith("en");if(Le&&!_e)return-1;if(!Le&&_e)return 1;const Xe=I.lang.localeCompare(Ee.lang);return Xe!==0?Xe:I.name.localeCompare(Ee.name)}),[Be]),Ke=ge.useCallback(()=>{if(Fe){Ar.cancelSpeech(),ve(!1);return}const I=Be.find(Xe=>Xe.name===P),Ee=I?.name??t("settings.voice.page.preview.browserVoiceFallback"),Le=t("settings.voice.page.preview.voiceLine",{voiceName:Ee});ve(!0);const _e=new SpeechSynthesisUtterance(Le);_e.rate=i,_e.pitch=o,_e.volume=c,I&&(_e.voice=I,_e.lang=I.lang),_e.onend=()=>ve(!1),_e.onerror=()=>ve(!1),window.speechSynthesis.cancel(),window.speechSynthesis.speak(_e)},[P,Be,i,o,c,Fe,t]);ge.useEffect(()=>()=>{Fe&&Ar.cancelSpeech()},[Fe]),ge.useEffect(()=>{if(!U||n!=="openai"&&n!=="openai-compatible"){Ae(y.trim().length>0);return}(async()=>{try{const _e=(await(await gt("/api/tts/status")).json()).available,Xe=y.trim().length>0;Ae(_e||Xe)}catch{Ae(y.trim().length>0)}})()},[y,U,n]),ge.useEffect(()=>{if(!U){fe(!1),ce([]);return}gt("/api/tts/say/status").then(I=>I.json()).then(I=>{if(fe(I.available),I.voices){const Ee=I.voices.filter((Le,_e,Xe)=>Xe.findIndex(ct=>ct.name===Le.name)===_e).sort((Le,_e)=>Le.name.localeCompare(_e.name));ce(Ee)}}).catch(()=>{fe(!1)})},[U]);const We=ge.useCallback(async()=>{if(te){Ms(te),ne(null),q(!1);return}q(!0);let I=null;try{const Ee=await gt("/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(!Ee.ok)throw new Error("Preview failed");const Le=await Ee.blob(),_e=URL.createObjectURL(Le);I=new Audio(_e),I.onended=()=>{Ms(I),ne(null),q(!1)},I.onerror=()=>{Ms(I),ne(null),q(!1)},ne(I),await I.play()}catch{Ms(I),ne(null),q(!1)}},[u,i,te,t]);ge.useEffect(()=>()=>{Ms(te)},[te]);const Pe=ge.useCallback(async()=>{if(Te){Ms(Te),Me(null),Ie(!1);return}Ie(!0);let I=null;try{const Ee=await gt("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t("settings.voice.page.preview.voiceLine",{voiceName:w}),voice:w,speed:i,apiKey:y||void 0})});if(!Ee.ok){const Xe=await Ee.json().catch(()=>({error:"Unknown error"}));throw new Error(Xe.error||`HTTP ${Ee.status}`)}const Le=await Ee.blob(),_e=URL.createObjectURL(Le);I=new Audio(_e),I.onended=()=>{Ms(I),Me(null),Ie(!1)},I.onerror=()=>{Ms(I),Me(null),Ie(!1)},Me(I),await I.play()}catch{Ms(I),Me(null),Ie(!1)}},[w,i,Te,y,t]);ge.useEffect(()=>()=>{Ms(Te)},[Te]);const at=ge.useCallback(async()=>{if(Ue){Ms(Ue),ze(null),Ve(!1);return}if(!_.trim())return;Ve(!0);let I=null;try{const Ee=await gt("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t("settings.voice.page.preview.customServerLine"),voice:T,model:O||void 0,speed:i,baseURL:_,apiKey:D||void 0})});if(!Ee.ok){const Xe=await Ee.json().catch(()=>({error:"Unknown error"}));throw new Error(Xe.error||`HTTP ${Ee.status}`)}const Le=await Ee.blob(),_e=URL.createObjectURL(Le);I=new Audio(_e),I.onended=()=>{Ms(I),ze(null),Ve(!1)},I.onerror=()=>{Ms(I),ze(null),Ve(!1)},ze(I),await I.play()}catch{Ms(I),ze(null),Ve(!1)}},[_,T,O,D,i,Ue,t]);ge.useEffect(()=>()=>{Ms(Ue)},[Ue]);const se="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(ot,{settingsItem:"voice.playback",title:t("settings.voice.page.section.playbackAndSummary"),divider:!1,contentClassName:"space-y-4",children:[s.jsx(wt,{checked:U,onChange:xe,label:t("settings.voice.page.field.messageReadAloudButton"),ariaLabel:t("settings.voice.page.field.messageReadAloudButtonAria")}),U&&s.jsxs(s.Fragment,{children:[s.jsx(Ys,{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(Zs,{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")},...ye?[{value:"say",label:s.jsxs(s.Fragment,{children:[s.jsx(L,{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:le(Kt,!oe&&"text-[var(--status-error)]"),children:t("settings.voice.page.field.apiKey")}),s.jsx("span",{className:le(rn,!oe&&"text-[var(--status-error)]/80"),children:t(oe&&!y?"settings.voice.page.field.apiKeyHintUsingConfig":oe?"settings.voice.page.field.apiKeyHintProvide":"settings.voice.page.field.apiKeyHintRequired")}),s.jsxs("div",{className:le("relative",Ws),children:[s.jsx("input",{type:"password",value:y,onChange:I=>R(I.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"}),y&&s.jsx("button",{type:"button",onClick:()=>R(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(L,{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:le(Kt,!_.trim()&&"text-[var(--status-error)]"),children:t("settings.voice.page.field.serverUrl")}),s.jsx(Ht,{children:t("settings.voice.page.field.serverUrlHint")})]}),s.jsxs("div",{className:le("relative",Ws),children:[s.jsx("input",{type:"text",value:_,onChange:I=>B(I.target.value),placeholder:"http://localhost:8880/v1",className:"w-full h-7 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary/50 focus:border-primary/70"}),_&&s.jsx("button",{type:"button",onClick:()=>B(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(L,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:Kt,children:"API Key"}),s.jsx("span",{className:rn,children:"Optional"}),s.jsxs("div",{className:le("relative",Ws),children:[s.jsx("input",{type:"password",value:D,onChange:I=>k(I.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:()=>k(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(L,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:Kt,children:t("settings.voice.page.field.model")}),s.jsx("div",{className:le("relative",Ws),children:s.jsx("input",{type:"text",value:O,onChange:I=>V(I.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:Kt,children:t("settings.voice.page.field.voice")}),s.jsx(Ht,{children:t("settings.voice.page.field.voiceIdentifierHint")})]}),s.jsxs("div",{className:le("flex items-center gap-2",Ws),children:[s.jsx("div",{className:"relative min-w-0 flex-1",children:s.jsx("input",{type:"text",value:T,onChange:I=>M(I.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(Q,{size:"xs",variant:"ghost",onClick:at,title:t("settings.voice.page.actions.preview"),disabled:!_.trim(),children:He?s.jsx(L,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(L,{name:"play",className:"w-3.5 h-3.5"})})]})]})]}),n==="local"&&s.jsx(lw,{}),s.jsxs(Jt,{label:t("settings.voice.page.field.voice"),children:[n==="local"&&s.jsxs(s.Fragment,{children:[s.jsxs(At,{value:String(m),onValueChange:I=>b(Number.parseInt(I,10)||0),children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder"),children:I=>Hr.find(Ee=>String(Ee.id)===I)?.label??I})}),s.jsx(Tt,{children:Hr.map(I=>s.jsx(yt,{value:String(I.id),children:I.label},I.id))})]}),s.jsx(Q,{size:"xs",variant:"ghost",onClick:N,title:t("settings.voice.page.actions.preview"),children:x?s.jsx(L,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(L,{name:"play",className:"w-3.5 h-3.5"})}),v?s.jsx("span",{className:"typography-meta text-[var(--status-error)]",children:v}):null]}),n==="openai"&&oe&&s.jsxs(s.Fragment,{children:[s.jsxs(At,{value:w,onValueChange:j,children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder")})}),s.jsx(Tt,{children:cw.map(I=>s.jsx(yt,{value:I.value,children:I.label},I.value))})]}),s.jsx(Q,{size:"xs",variant:"ghost",onClick:Pe,title:t("settings.voice.page.actions.preview"),children:je?s.jsx(L,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(L,{name:"play",className:"w-3.5 h-3.5"})})]}),n==="openai-compatible"&&s.jsx("span",{className:rn,children:t("settings.voice.page.field.configuredAbove")}),n==="say"&&ye&&ae.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs(At,{value:u,onValueChange:f,children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{placeholder:t("settings.voice.page.field.selectVoicePlaceholder")})}),s.jsx(Tt,{children:ae.map(I=>s.jsx(yt,{value:I.name,children:I.name},I.name))})]}),s.jsx(Q,{size:"xs",variant:"ghost",onClick:We,title:t("settings.voice.page.actions.preview"),children:pe?s.jsx(L,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(L,{name:"play",className:"w-3.5 h-3.5"})})]}),n==="browser"&&De.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs(At,{value:P||"$auto",onValueChange:I=>F(I==="$auto"?"":I),children:[s.jsx(Et,{size:Gt,className:Xn,children:s.jsx(Vt,{placeholder:t("settings.voice.page.field.auto")})}),s.jsxs(Tt,{children:[s.jsx(yt,{value:"$auto",children:t("settings.voice.page.field.auto")}),De.map(I=>s.jsxs(yt,{value:I.name,children:[I.name," (",I.lang,")"]},I.name))]})]}),s.jsx(Q,{size:"xs",variant:"ghost",onClick:Ke,title:t("settings.voice.page.actions.preview"),children:Fe?s.jsx(L,{name:"stop",className:"w-3.5 h-3.5"}):s.jsx(L,{name:"play",className:"w-3.5 h-3.5"})})]})]}),s.jsxs(Jt,{label:t("settings.voice.page.field.speechRate"),children:[!e&&s.jsx("input",{type:"range",min:.5,max:2,step:.1,value:i,onChange:I=>r(Number(I.target.value)),className:se}),s.jsx(Cs,{value:i,onValueChange:r,min:.5,max:2,step:.1,className:"w-16 tabular-nums"})]}),s.jsxs(Jt,{label:t("settings.voice.page.field.speechPitch"),children:[!e&&s.jsx("input",{type:"range",min:.5,max:2,step:.1,value:o,onChange:I=>d(Number(I.target.value)),className:se}),s.jsx(Cs,{value:o,onValueChange:d,min:.5,max:2,step:.1,className:"w-16 tabular-nums"})]}),s.jsxs(Jt,{label:t("settings.voice.page.field.speechVolume"),children:[!e&&s.jsx("input",{type:"range",min:0,max:1,step:.1,value:c,onChange:I=>p(Number(I.target.value)),className:se}),e?s.jsx(Cs,{value:Math.round(c*100),onValueChange:I=>p(I/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(Ys,{title:t("settings.voice.page.field.ttsInputMode"),children:s.jsx(Zs,{value:Y,onChange:X,"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(ot,{settingsItem:"voice.speech-recognition",title:t("settings.voice.page.section.speechRecognition"),contentClassName:"space-y-4",children:[s.jsx(wt,{checked:be,onChange:he,label:t("settings.voice.page.field.enableVoiceInput"),ariaLabel:t("settings.voice.page.field.enableVoiceInputAria")}),be&&s.jsxs(s.Fragment,{children:[s.jsx(Ys,{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(Zs,{value:S,onChange:W,"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")}]})}),S==="local"&&s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:Kt,children:t("settings.voice.page.field.model")}),s.jsx(ow,{selectedModelId:J,onSelect:ee})]}),S==="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:le(Kt,!Z.trim()&&"text-[var(--status-error)]"),children:t("settings.voice.page.field.serverUrl")}),s.jsx(Ht,{children:t("settings.voice.page.field.sttServerUrlHint")})]}),s.jsxs("div",{className:le("relative",Ws),children:[s.jsx("input",{type:"text",value:Z,onChange:I=>A(I.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"}),Z&&s.jsx("button",{type:"button",onClick:()=>A(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(L,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:Kt,children:"API Key"}),s.jsx("span",{className:rn,children:"Optional"}),s.jsxs("div",{className:le("relative",Ws),children:[s.jsx("input",{type:"password",value:C,onChange:I=>z(I.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"}),C&&s.jsx("button",{type:"button",onClick:()=>z(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:s.jsx(L,{name:"close",className:"w-3.5 h-3.5"})})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("span",{className:Kt,children:t("settings.voice.page.field.model")}),s.jsx("div",{className:le("relative",Ws),children:s.jsx("input",{type:"text",value:$,onChange:I=>H(I.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:Kt,children:t("settings.voice.page.field.language")}),s.jsx(Ht,{children:t("settings.voice.page.field.sttLanguageHint")})]}),s.jsx("div",{className:"relative max-w-[8rem]",children:s.jsx("input",{type:"text",value:ue,onChange:I=>re(I.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"})})]})]})]})]})]})},Ri=[{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}],Di=[{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}],uw="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/",mw="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/local-management/configuration-file/",Gr=[{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"}],pw=[".yml",".yaml",".json"],gw="settings.openchamber.tunnel.error.invalidConfigExtension",qa=t=>{const e=t.trim().toLowerCase();return pw.some(n=>e.endsWith(n))},fw=t=>t==="ngrok"?"ngrok":"cloudflared",uu=()=>{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"},hw=(t,e=uu())=>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/",qr=(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():fw(n),i=typeof e?.platform=="string"&&e.platform.trim().length>0?e.platform.trim():uu(),r=typeof e?.installCommand=="string"&&e.installCommand.trim().length>0?e.installCommand.trim():hw(n,i);return{provider:n,dependency:a,installCommand:r}},mu=t=>t==="cloudflare"?"Cloudflare":t==="ngrok"?"Ngrok":t,_c=t=>{const e=Ye.c(11),{provider:n}=t;let a;e[0]!==n?(a=mu(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=le("size-4 shrink-0",d),e[2]=d,e[3]=c):c=e[3];let p;e[4]!==c?(p=s.jsx(L,{name:"cloud",className:c}),e[4]=c,e[5]=p):p=e[5];let u;e[6]!==i?(u=s.jsx("span",{children:i}),e[6]=i,e[7]=u):u=e[7];let f;return e[8]!==p||e[9]!==u?(f=s.jsxs("span",{className:"flex items-center gap-2",children:[p,u]}),e[8]=p,e[9]=u,e[10]=f):f=e[10],f},On=t=>t==="quick"?"quick":t==="managed-remote"?"managed-remote":t==="managed-local"?"managed-local":"quick",Po=(t,e,n)=>t.find(i=>i.ms===e)?.value||n,$c=(t,e,n)=>{const a=Po(t,e,n);return t.find(i=>i.value===a)?.label||a},Vc=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`},xw=(t,e)=>Ad(t,e,{hour:"2-digit",precision:"second"}),Gi=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()}},bw=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=Gi(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},yw=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,vw=()=>{const{t}=it(),e=Ne(de=>de.timeFormatPreference),n=l.useCallback(de=>t(de),[t]),[a,i]=l.useState("checking"),[r,o]=l.useState(null),[d,c]=l.useState(null),[p,u]=l.useState(null),[f,m]=l.useState(null),[b,h]=l.useState(null),[g,x]=l.useState(!1),[v,N]=l.useState(!1),[P,F]=l.useState(!1),[w,j]=l.useState("cloudflare"),[y,R]=l.useState(()=>qr("cloudflare")),[_,B]=l.useState([]),[D,k]=l.useState("quick"),[T,M]=l.useState(null),[O,V]=l.useState([]),[U,Y]=l.useState({}),[X,S]=l.useState(""),[W,Z]=l.useState({}),[A,C]=l.useState(new Set),[z,$]=l.useState(!1),[H,J]=l.useState(""),[ee,ue]=l.useState(""),[re,xe]=l.useState(""),[be,he]=l.useState(1800*1e3),[ye,fe]=l.useState(480*60*1e3),[ae,ce]=l.useState(""),[pe,q]=l.useState([]),[te,ne]=l.useState(()=>Date.now()),[oe,Ae]=l.useState(null),je=t(gw),Ie=l.useRef(null),Te=l.useMemo(()=>T?!qa(T):!1,[T]),Me=l.useMemo(()=>O.find(de=>de.id===X)||O[0]||null,[O,X]),He=l.useMemo(()=>pe.map(de=>{const ie=de.expiresAt<=te,we=de.status==="active"&&!ie,me=we?Vc(de.expiresAt-te):de.inactiveReason==="expired"||ie?"expired":"inactive",Je=me==="expired"?t("settings.openchamber.tunnel.state.expired"):de.inactiveReason==="tunnel-revoked"?t("settings.openchamber.tunnel.state.revoked"):t("settings.openchamber.tunnel.state.inactive"),$e=On(de.mode);return{...de,isActive:we,mode:$e,remainingTextForSession:me,inactiveLabel:Je}}),[te,pe,t]),Ve=l.useMemo(()=>r?.connectUrl?r.bootstrapExpiresAt===null?!0:r.bootstrapExpiresAt>te:!1,[te,r?.bootstrapExpiresAt,r?.connectUrl]),Ue=l.useMemo(()=>!r||a!=="active"&&a!=="stopping"?!1:d===D,[d,a,r,D]),ze=l.useMemo(()=>!r||a!=="active"||!d?!1:d!==D,[d,a,r,D]),Be=l.useMemo(()=>{if(typeof oe=="number"&&Number.isFinite(oe)&&oe>0)return oe;if(typeof window>"u")return null;const ie=La()||window.location.href;let we=0;try{we=Number(new URL(ie).port)}catch{we=Number(window.location.port)}return Number.isFinite(we)&&we>0?we:null},[oe]),Ge=l.useMemo(()=>_.find(de=>de.provider===w)??null,[_,w]),Fe=l.useMemo(()=>{const de=new Set(Ge?.modes?.map(ie=>ie.key).filter(ie=>ie==="quick"||ie==="managed-remote"||ie==="managed-local"));return de.size===0?Gr:Gr.filter(ie=>de.has(ie.value))},[Ge]),ve=l.useMemo(()=>Fe.some(de=>de.value==="managed-remote"||de.value==="managed-local"),[Fe]),De=l.useMemo(()=>y.provider===w?y:qr(w),[y,w]),Ke=l.useCallback(async de=>{await In(de)},[]),We=l.useCallback((de,ie)=>(R(qr(ie,de)),de.available===!0),[]),Pe=l.useCallback(async(de,ie)=>{try{const we=await gt("/api/openchamber/tunnel/check",{query:{provider:de},...ie?{signal:ie}:{}});if(!we.ok)return null;const me=await we.json();if(ie?.aborted)return null;const Je=We(me,de);return i($e=>$e==="checking"||$e==="starting"||$e==="active"||$e==="stopping"?$e:Je?"idle":"not-available"),Je}catch{return null}},[We]),at=l.useCallback(async de=>{try{const[ie,we,me,Je]=await Promise.all([gt("/api/openchamber/tunnel/check",{signal:de}),gt("/api/openchamber/tunnel/status",{signal:de}),gt("/api/config/settings",{signal:de,headers:{Accept:"application/json"}}),gt("/api/openchamber/tunnel/providers",{signal:de})]),$e=await ie.json(),et=await we.json(),bt=me.ok?await me.json():{},Dt=Je.ok?await Je.json():{},Qt=et.ttlConfig?.bootstrapTtlMs??(bt?.tunnelBootstrapTtlMs===null?null:typeof bt?.tunnelBootstrapTtlMs=="number"?bt.tunnelBootstrapTtlMs:1800*1e3),_t=typeof et.ttlConfig?.sessionTtlMs=="number"?et.ttlConfig.sessionTtlMs:typeof bt?.tunnelSessionTtlMs=="number"?bt.tunnelSessionTtlMs:480*60*1e3,as=On(et.mode??bt?.tunnelMode),is=typeof bt?.tunnelProvider=="string"&&bt.tunnelProvider.trim().length>0?bt.tunnelProvider.trim().toLowerCase():"cloudflare",$t=typeof bt?.managedLocalTunnelConfigPath=="string"&&bt.managedLocalTunnelConfigPath.trim()||null,Ce=We($e,is),jt=bw(et?.managedRemoteTunnelPresets),Qe=typeof et.managedRemoteTunnelHostname=="string"?et.managedRemoteTunnelHostname:"",ht=jt.length>0?jt:Qe?[{id:`legacy-${Gi(Qe)}`,name:Qe,hostname:Gi(Qe)}]:[],Nt=ht[0]?.id||"";if(he(Qt),fe(_t),j(is),B(Array.isArray(Dt?.providers)?Dt.providers:[]),k(as),M($t),V(ht),S(Nt),q(Array.isArray(et.activeSessions)?et.activeSessions:[]),c(et.activeTunnelMode?On(et.activeTunnelMode):et.active&&et.mode?On(et.mode):null),C(new Set(Array.isArray(et.managedRemoteTunnelTokenPresetIds)?et.managedRemoteTunnelTokenPresetIds:[])),Ae(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(Ce?"idle":"not-available")}catch{de.aborted||(i("error"),m(t("settings.openchamber.tunnel.toast.checkAvailabilityFailed")))}},[We,t]);l.useEffect(()=>{const de=new AbortController;return at(de.signal),()=>de.abort()},[at]),l.useEffect(()=>{if(!r?.connectUrl){u(null);return}let de=!1;return bd.toDataURL(r.connectUrl,{width:256,margin:2,color:{dark:"#000000",light:"#ffffff"}}).then(ie=>{de||u(ie)}).catch(()=>{de||u(null)}),()=>{de=!0}},[r?.connectUrl]),l.useEffect(()=>{if(!r?.bootstrapExpiresAt){ce(t("settings.openchamber.tunnel.state.noExpiry"));return}let de=null,ie=Date.now();const we=()=>{const $e=r.bootstrapExpiresAt?r.bootstrapExpiresAt-Date.now():0;$e<=0?ce(t("settings.openchamber.tunnel.state.expired")):ce(Vc($e))},me=()=>{const $e=Date.now();$e-ie>=1e3&&(we(),ie=$e),de=requestAnimationFrame(me)};we(),(typeof document>"u"||document.visibilityState==="visible")&&(de=requestAnimationFrame(me));const Je=()=>{document.visibilityState==="visible"&&de===null?de=requestAnimationFrame(me):document.visibilityState!=="visible"&&de!==null&&(cancelAnimationFrame(de),de=null)};return document.addEventListener("visibilitychange",Je),()=>{document.removeEventListener("visibilitychange",Je),de!==null&&cancelAnimationFrame(de)}},[t,r?.bootstrapExpiresAt]),l.useEffect(()=>{let de=null,ie=Date.now();const we=()=>{const Je=Date.now();Je-ie>=1e3&&(ne(Je),ie=Je),de=requestAnimationFrame(we)};(typeof document>"u"||document.visibilityState==="visible")&&(de=requestAnimationFrame(we));const me=()=>{document.visibilityState==="visible"&&de===null?de=requestAnimationFrame(we):document.visibilityState!=="visible"&&de!==null&&(cancelAnimationFrame(de),de=null)};return document.addEventListener("visibilitychange",me),()=>{document.removeEventListener("visibilitychange",me),de!==null&&cancelAnimationFrame(de)}},[]),l.useEffect(()=>{if(a==="starting"||a==="stopping"||a==="checking")return;let de=!1;const ie=async()=>{try{const me=await gt("/api/openchamber/tunnel/status");if(!me.ok||de)return;const Je=await me.json();if(de)return;q(Array.isArray(Je.activeSessions)?Je.activeSessions:[]),C(new Set(Array.isArray(Je.managedRemoteTunnelTokenPresetIds)?Je.managedRemoteTunnelTokenPresetIds:[])),Ae(typeof Je.localPort=="number"?Je.localPort:null)}catch{}},we=window.setInterval(()=>{typeof document<"u"&&document.visibilityState!=="visible"||ie()},5e3);return()=>{de=!0,window.clearInterval(we)}},[a]);const se=l.useCallback(async de=>{F(!0);try{await kt(de),Object.prototype.hasOwnProperty.call(de,"tunnelMode")&&de.tunnelMode&&k(de.tunnelMode),Object.prototype.hasOwnProperty.call(de,"tunnelProvider")&&typeof de.tunnelProvider=="string"&&j(de.tunnelProvider),Object.prototype.hasOwnProperty.call(de,"managedLocalTunnelConfigPath")&&M(de.managedLocalTunnelConfigPath??null),Object.prototype.hasOwnProperty.call(de,"managedRemoteTunnelPresets")&&de.managedRemoteTunnelPresets&&V(de.managedRemoteTunnelPresets)}catch{G.error(t("settings.openchamber.tunnel.toast.saveSettingsFailed"))}finally{F(!1)}},[t]),I=l.useCallback(async(de,ie)=>{N(!0);try{await kt({tunnelBootstrapTtlMs:de,tunnelSessionTtlMs:ie})}catch{G.error(t("settings.openchamber.tunnel.toast.saveTtlFailed"))}finally{N(!1)}},[t]),Ee=l.useCallback(async de=>{const ie=de.token.trim();if(ie)try{const we={...W,[de.presetId]:ie};await kt({managedRemoteTunnelPresetTokens:we}),C(me=>{const Je=new Set(me);return Je.add(de.presetId),Je})}catch{G.error(t("settings.openchamber.tunnel.toast.saveTokenFailed"))}},[W,t]),Le=l.useCallback(async de=>{h(null),m(null);const ie=_.find(me=>me.provider===de),we=ie?.modes?.some(me=>me.key===D)?D:On(ie?.modes?.[0]?.key);await se({tunnelProvider:de,tunnelMode:we}),Pe(de)},[_,Pe,se,D]),_e=l.useCallback(async()=>{const de=await Fd({filters:[{name:"Config",extensions:["yml","yaml","json"]}]});if(de.success&&typeof de.path=="string"&&de.path.trim().length>0){const ie=de.path.trim();if(!qa(ie)){G.error(je);return}M(ie),await se({managedLocalTunnelConfigPath:ie});return}Ie.current?.click()},[je,se]),Xe=l.useCallback(de=>{const ie=de.trim();M(ie.length>0?ie:null)},[]),ct=l.useCallback(async()=>{if(T&&!qa(T)){G.error(je);return}await se({managedLocalTunnelConfigPath:T})},[je,T,se]),ut=l.useCallback(async()=>{M(null),await se({managedLocalTunnelConfigPath:null})},[se]),lt=l.useCallback(async de=>{const ie=de.target.files?.[0];if(!ie)return;const we=ie.name.trim();if(we.length!==0){if(!qa(we)){G.error(je);return}M(we),await se({managedLocalTunnelConfigPath:we}),de.target.value=""}},[je,se]),rt=l.useCallback(async()=>{if(m(null),h(null),D==="managed-local"&&T&&!qa(T)){m(je),G.error(je);return}i("starting");try{let de="",ie="";if(D==="managed-remote"){if(!Me){i("idle"),h(t("settings.openchamber.tunnel.toast.selectOrAddManagedRemoteFirst")),G.error(t("settings.openchamber.tunnel.toast.selectOrAddManagedRemoteFirst"));return}de=Me.hostname,ie=(W[Me.id]||"").trim(),await se({tunnelMode:"managed-remote",managedRemoteTunnelPresets:O})}const we=await gt("/api/openchamber/tunnel/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:w,mode:D,...D==="managed-remote"&&Me?{managedRemoteTunnelPresetId:Me.id,managedRemoteTunnelPresetName:Me.name}:{},...D==="managed-remote"&&de?{managedRemoteTunnelHostname:de}:{},...D==="managed-remote"&&ie?{managedRemoteTunnelToken:ie}:{},...D==="managed-local"&&T?{configPath:T}:{}})}),me=await we.json();if(!we.ok||!me.ok){if(D==="managed-remote"&&typeof me.error=="string"&&me.error.includes("Managed remote tunnel token is required")){i("idle"),h(t("settings.openchamber.tunnel.toast.managedRemoteTokenRequiredBeforeStarting")),G.error(t("settings.openchamber.tunnel.toast.addManagedRemoteTokenBeforeStarting"));return}i("error"),m(me.error||t("settings.openchamber.tunnel.toast.startFailed")),G.error(me.error||t("settings.openchamber.tunnel.toast.startFailed"));return}const Je=typeof me.url=="string"?me.url:"";if(!Je){i("error"),m(t("settings.openchamber.tunnel.toast.startedButNoPublicUrl")),G.error(t("settings.openchamber.tunnel.toast.startedButNoPublicUrl"));return}if(o({url:Je,connectUrl:typeof me.connectUrl=="string"?me.connectUrl:null,bootstrapExpiresAt:typeof me.bootstrapExpiresAt=="number"?me.bootstrapExpiresAt:null}),c(me.activeTunnelMode?On(me.activeTunnelMode):me.mode?On(me.mode):D),q(Array.isArray(me.activeSessions)?me.activeSessions:[]),Array.isArray(me.managedRemoteTunnelTokenPresetIds)&&C(new Set(me.managedRemoteTunnelTokenPresetIds)),typeof me.localPort=="number"&&Ae(me.localPort),typeof me.mode=="string"&&k(On(me.mode)),i("active"),me.replacedTunnel){const $e=typeof me.revokedBootstrapCount=="number"?me.revokedBootstrapCount:0,et=typeof me.invalidatedSessionCount=="number"?me.invalidatedSessionCount:0;$e===1&&et===1?G.warning(t("settings.openchamber.tunnel.toast.replacedTunnelSingleSingle")):$e===1?G.warning(t("settings.openchamber.tunnel.toast.replacedTunnelSingleManySessions",{invalidatedSessionCount:et})):et===1?G.warning(t("settings.openchamber.tunnel.toast.replacedTunnelManyLinksSingleSession",{revokedBootstrapCount:$e})):G.warning(t("settings.openchamber.tunnel.toast.replacedTunnelManyMany",{revokedBootstrapCount:$e,invalidatedSessionCount:et}))}else G.success(t("settings.openchamber.tunnel.toast.linkReady"))}catch{i("error"),m(t("settings.openchamber.tunnel.toast.startFailed")),G.error(t("settings.openchamber.tunnel.toast.startFailed"))}},[je,O,se,Me,W,t,w,D,T]),mt=l.useCallback(async()=>{i("stopping");try{await gt("/api/openchamber/tunnel/stop",{method:"POST"});const de=await gt("/api/openchamber/tunnel/status");if(de.ok){const ie=await de.json();q(Array.isArray(ie.activeSessions)?ie.activeSessions:[]),C(new Set(Array.isArray(ie.managedRemoteTunnelTokenPresetIds)?ie.managedRemoteTunnelTokenPresetIds:[])),Ae(typeof ie.localPort=="number"?ie.localPort:null)}o(null),c(null),u(null),i("idle"),G.success(t("settings.openchamber.tunnel.toast.stopped"))}catch{i("error"),m(t("settings.openchamber.tunnel.toast.stopFailed")),G.error(t("settings.openchamber.tunnel.toast.stopFailed"))}},[t]),xt=l.useCallback(async()=>{if(r?.connectUrl)try{await navigator.clipboard.writeText(r.connectUrl),x(!0),G.success(t("settings.openchamber.tunnel.toast.connectLinkCopied")),setTimeout(()=>x(!1),2e3)}catch{G.error(t("settings.openchamber.tunnel.toast.copyUrlFailed"))}},[t,r?.connectUrl]),It=l.useCallback(async de=>{const ie=Ri.find(we=>we.value===de);ie&&(he(ie.ms),await I(ie.ms,ye))},[I,ye]),Se=l.useCallback(async de=>{const ie=Di.find(we=>we.value===de);!ie||ie.ms===null||(fe(ie.ms),await I(be,ie.ms))},[be,I]),qe=l.useCallback(async de=>{h(null),m(null),a!=="active"&&a!=="stopping"&&a!=="starting"&&i("idle"),await se({tunnelMode:de,managedRemoteTunnelPresets:O})},[O,se,a]),Ze=l.useCallback(async(de,ie)=>{try{await kt({managedRemoteTunnelPresets:ie})}catch{G.error(t("settings.openchamber.tunnel.toast.saveSelectedManagedRemoteFailed"))}},[t]),nt=l.useCallback(de=>{const ie=O.find(we=>we.id===de);ie&&(S(ie.id),h(null),Ze(ie,O))},[O,Ze]),ft=l.useCallback(async()=>{const de=H.trim(),ie=Gi(ee),we=re.trim();if(!de){G.error(t("settings.openchamber.tunnel.toast.tunnelNameRequired"));return}if(!ie){G.error(t("settings.openchamber.tunnel.toast.managedRemoteHostnameRequired"));return}if(!we){G.error(t("settings.openchamber.tunnel.toast.managedRemoteTokenRequired"));return}if(O.some($e=>$e.hostname===ie)){G.error(t("settings.openchamber.tunnel.toast.hostnameAlreadyExists"));return}const me={id:yw(),name:de,hostname:ie},Je=[...O,me];V(Je),S(me.id),Y($e=>({...$e,[me.id]:!0})),Z($e=>({...$e,[me.id]:we})),h(null),$(!1),J(""),ue(""),xe(""),await se({tunnelMode:"managed-remote",managedRemoteTunnelPresets:Je,managedRemoteTunnelPresetTokens:{...W,[me.id]:we}}),await Ee({presetId:me.id,presetName:me.name,hostname:me.hostname,token:we}),G.success(t("settings.openchamber.tunnel.toast.managedRemoteSaved"))},[O,ee,H,re,Ee,se,W,t]),vt=l.useCallback(async de=>{const ie=O.find(et=>et.id===de);if(!ie)return;const we=O.filter(et=>et.id!==ie.id),me=we[0]?.id||"",Je=X===ie.id?me:X,$e=Object.fromEntries(Object.entries(W).filter(([et,bt])=>et!==ie.id&&bt.trim().length>0));V(we),S(Je),Y(et=>{const bt={...et};return delete bt[ie.id],bt}),Z(et=>{const bt={...et};return delete bt[ie.id],bt}),C(et=>{const bt=new Set(et);return bt.delete(ie.id),bt}),h(null),await se({managedRemoteTunnelPresets:we,managedRemoteTunnelPresetTokens:$e}),G.success(t("settings.openchamber.tunnel.toast.managedRemoteRemoved"))},[O,se,X,W,t]),St="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(ot,{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:[He.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(L,{name:"information",className:"size-4 text-[var(--status-info)]"}),s.jsx("p",{className:Ll,children:t("settings.openchamber.tunnel.section.redeemedAccessLinks")})]}),s.jsx("div",{className:"space-y-1",children:He.map(de=>{const ie=de.mode==="quick",we=de.mode==="managed-remote",me=ie?"border-[var(--status-warning-border)] bg-[var(--status-warning-background)] text-[var(--status-warning)]":we?"border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)]":"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)]",Je=de.isActive?ie?"text-[var(--status-warning)]":we?"text-[var(--status-info)]":"text-[var(--status-success)]":"text-muted-foreground/50",$e=t(ie?"settings.openchamber.tunnel.badge.quick":we?"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(L,{name:"checkbox-blank-circle-fill",className:le("size-2.5 shrink-0",Je)}),s.jsx("span",{className:le("typography-micro rounded border px-1.5 py-0.5 uppercase",me),children:$e}),s.jsx("span",{className:"typography-meta text-muted-foreground/80",children:t("settings.openchamber.tunnel.session.redeemedAt",{time:xw(de.createdAt,e)})}),s.jsx("span",{className:"typography-meta text-foreground",children:de.isActive?t("settings.openchamber.tunnel.session.expiresIn",{remaining:de.remainingTextForSession}):de.inactiveLabel===t("settings.openchamber.tunnel.state.inactive")?t("settings.openchamber.tunnel.state.inactive"):t("settings.openchamber.tunnel.session.inactiveWithReason",{reason:de.inactiveLabel})})]},de.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(L,{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:Ll,children:t("settings.openchamber.tunnel.notAvailable.dependencyNotFound",{dependency:De.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:De.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:Kt,children:t("settings.openchamber.tunnel.field.provider")}),s.jsxs(At,{value:w,onValueChange:de=>{Le(de)},disabled:P||a==="starting"||a==="stopping",children:[s.jsx(Et,{size:Gt,className:"max-w-[16rem]",children:s.jsx(Vt,{placeholder:t("settings.openchamber.tunnel.field.providerPlaceholder"),children:mu(w)})}),s.jsxs(Tt,{children:[_.length>0?_.map(de=>s.jsx(yt,{value:de.provider,children:s.jsx(_c,{provider:de.provider})},de.provider)):s.jsx(yt,{value:"cloudflare",children:s.jsx(_c,{provider:"cloudflare"})}),s.jsx(yt,{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:Kt,children:t("settings.openchamber.tunnel.field.tunnelType")}),s.jsx("div",{className:"flex flex-wrap items-center gap-1",children:Fe.map(de=>s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx(Q,{variant:"chip",size:"xs","aria-pressed":D===de.value,className:"!font-normal",onClick:()=>{qe(de.value)},disabled:P||a==="starting"||a==="stopping",children:n(de.labelKey)})}),s.jsx(Ds,{sideOffset:8,className:"max-w-xs",children:n(de.tooltipKey)})]},de.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:le(Kt,"shrink-0"),children:t("settings.openchamber.tunnel.field.connectLinkTtl")}),s.jsxs(At,{value:Po(Ri,be,"1800000"),onValueChange:de=>{It(de)},disabled:v||P||a==="starting"||a==="stopping",children:[s.jsx(Et,{size:Gt,className:"max-w-[11rem] min-w-0",children:s.jsx(Vt,{className:"truncate",children:$c(Ri,be,"1800000")})}),s.jsx(Tt,{children:Ri.map(de=>s.jsx(yt,{value:de.value,children:de.label},de.value))})]})]}),s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:le(Kt,"shrink-0"),children:t("settings.openchamber.tunnel.field.tunnelSessionTtl")}),s.jsxs(At,{value:Po(Di,ye,"28800000"),onValueChange:de=>{Se(de)},disabled:v||P||a==="starting"||a==="stopping",children:[s.jsx(Et,{size:Gt,className:"max-w-[11rem] min-w-0",children:s.jsx(Vt,{className:"truncate",children:$c(Di,ye,"28800000")})}),s.jsx(Tt,{children:Di.map(de=>s.jsx(yt,{value:de.value,children:de.label},de.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(L,{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")}),ve&&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 Be=="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:",Be]})]})}),s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx(An,{children:t("settings.openchamber.tunnel.section.savedManagedRemoteTunnels")}),s.jsxs(Q,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>$(de=>!de),disabled:a==="starting"||a==="stopping"||P,children:[s.jsx(L,{name:"add",className:"h-3.5 w-3.5"}),t("settings.common.actions.create")]})]}),O.length>0?s.jsx("div",{className:"overflow-hidden rounded-md border border-[var(--surface-subtle)]",children:O.map((de,ie)=>{const we=W[de.id]||"",me=A.has(de.id),Je=U[de.id]??!1;return s.jsx("div",{className:le(ie<O.length-1&&"border-b border-[var(--surface-subtle)]"),children:s.jsxs(sa,{open:Je,onOpenChange:$e=>{Y(et=>({...et,[de.id]:$e})),$e&&nt(de.id)},className:"py-1.5",children:[s.jsxs("div",{className:"flex items-start gap-2 px-3",children:[s.jsxs(na,{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"||P,children:[Je?s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 text-muted-foreground"}):s.jsx(L,{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:de.name})]}),s.jsx(Q,{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:de.name}),onClick:()=>{vt(de.id)},disabled:a==="starting"||a==="stopping"||P,children:s.jsx(L,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsx(aa,{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:de.hostname})]}),s.jsx(tt,{type:"password",value:we,onChange:$e=>{const et=$e.target.value;h(null),Z(bt=>({...bt,[de.id]:et}))},onBlur:$e=>{const et=$e.currentTarget.value.trim();et&&Ee({presetId:de.id,presetName:de.name,hostname:de.hostname,token:et})},placeholder:t(me?"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(Q,{variant:"ghost",size:"xs",className:"!font-normal",disabled:a==="starting"||a==="stopping"||we.trim().length===0,onClick:()=>{Ee({presetId:de.id,presetName:de.name,hostname:de.hostname,token:we})},children:t("settings.openchamber.tunnel.actions.saveToken")})})]})})]})},de.id)})}):s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t("settings.openchamber.tunnel.empty.noManagedRemoteTunnels")}),z&&s.jsxs("div",{className:"space-y-2 rounded-md border border-[var(--surface-subtle)] p-2",children:[s.jsx(tt,{value:H,onChange:de=>J(de.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetNamePlaceholder"),className:"h-7",disabled:P||a==="starting"||a==="stopping"}),s.jsx(tt,{value:ee,onChange:de=>ue(de.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetHostnamePlaceholder"),className:"h-7",disabled:P||a==="starting"||a==="stopping"}),s.jsx(tt,{type:"password",value:re,onChange:de=>xe(de.target.value),placeholder:t("settings.openchamber.tunnel.field.newPresetTokenPlaceholder"),className:"h-7",disabled:P||a==="starting"||a==="stopping"}),typeof Be=="number"&&s.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:[t("settings.openchamber.tunnel.note.cloudflareConnectorTargetUse")," ",s.jsxs("code",{children:["http://localhost:",Be]}),"."]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Q,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{ft()},disabled:P||a==="starting"||a==="stopping",children:t("settings.common.actions.saveChanges")}),s.jsx(Q,{variant:"ghost",size:"xs",className:"!font-normal",onClick:()=>{$(!1),J(""),ue(""),xe("")},disabled:P||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(Ht,{children:t("settings.openchamber.tunnel.tooltip.tokensSavedPath")})]}),!Me&&b&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:b})]}),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:Kt,children:t("settings.openchamber.tunnel.field.configurationFile")}),s.jsx("input",{ref:Ie,type:"file",accept:".yml,.yaml,.json",className:"hidden",onChange:de=>{lt(de)}}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tt,{value:T||"",onChange:de=>{Xe(de.target.value)},onBlur:()=>{ct()},placeholder:t("settings.openchamber.tunnel.field.configurationFilePlaceholder"),className:"h-7",disabled:a==="starting"||a==="stopping"||P}),s.jsx(Q,{variant:"outline",size:"xs",className:"h-7 w-7 p-0","aria-label":t("settings.openchamber.tunnel.actions.browseConfigFileAria"),onClick:()=>{_e()},disabled:a==="starting"||a==="stopping"||P,children:s.jsx(L,{name:"folder",className:"size-3.5"})}),T&&s.jsx(Q,{variant:"ghost",size:"xs",className:"h-7 w-7 p-0","aria-label":t("settings.openchamber.tunnel.actions.clearConfigFileAria"),onClick:()=>{ut()},disabled:a==="starting"||a==="stopping"||P,children:s.jsx(L,{name:"close",className:"size-3.5"})})]}),s.jsx("p",{className:"typography-meta text-muted-foreground/70",children:t(T?"settings.openchamber.tunnel.note.customConfigUsed":"settings.openchamber.tunnel.note.defaultConfigUsed")}),Te&&s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:je})]})}),!Ue&&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(L,{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(uw)},children:[t("settings.openchamber.tunnel.actions.openManagedRemoteDocs"),s.jsx(L,{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(mw)},children:[t("settings.openchamber.tunnel.actions.openManagedLocalDocs"),s.jsx(L,{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(Gr.find(de=>de.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:Kt,children:t("settings.openchamber.tunnel.field.managedRemoteTunnelToConnect")}),s.jsxs(At,{value:X||(O[0]?.id??""),onValueChange:de=>{nt(de)},disabled:P||a==="starting"||a==="stopping"||O.length<=1,children:[s.jsx(Et,{size:Gt,children:s.jsx(Vt,{placeholder:t("settings.openchamber.tunnel.field.selectSavedTunnelPlaceholder"),children:Me?.name})}),s.jsx(Tt,{fitContent:!0,children:O.map(de=>s.jsx(yt,{value:de.id,children:de.name},de.id))})]})]}),ze&&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(L,{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(Q,{size:"sm",variant:"outline",onClick:rt,disabled:a==="starting"||P||D==="managed-remote"&&!Me||D==="managed-local"&&Te,className:le(St,a==="starting"&&"opacity-70"),children:a==="starting"?s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"loader-4",className:"size-3.5 animate-spin"})," ",t("settings.openchamber.tunnel.actions.startingTunnel")]}):t("settings.openchamber.tunnel.actions.startTunnel")})]})]}),Ue&&r&&s.jsxs("section",{"data-settings-item":"tunnel.start",className:"space-y-4 px-2 pb-2 pt-0",children:[s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"size-2 shrink-0 rounded-full bg-[var(--status-success)]"}),s.jsx("p",{className:"typography-meta font-medium text-foreground",children:t("settings.openchamber.tunnel.state.tunnelReady")})]}),s.jsxs("div",{children:[s.jsx("p",{className:"typography-meta mb-1 text-muted-foreground/70",children:t("settings.openchamber.tunnel.field.publicUrlHint")}),s.jsx("code",{className:"typography-code block truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:r.url})]}),Ve&&r.connectUrl&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("p",{className:"typography-meta mb-1 text-muted-foreground/70",children:t("settings.openchamber.tunnel.field.connectLink")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"typography-code flex-1 truncate rounded bg-muted/50 px-2 py-1 text-xs text-foreground",children:r.connectUrl}),s.jsxs(Q,{size:"sm",variant:"ghost",onClick:xt,className:"shrink-0 gap-1.5",children:[g?s.jsx(L,{name:"check",className:"size-3.5 text-[var(--status-success)]"}):s.jsx(L,{name:"file-copy",className:"size-3.5"}),t(g?"settings.openchamber.tunnel.actions.copied":"settings.common.actions.copyAll")]})]}),s.jsxs("p",{className:"typography-meta mt-1 text-muted-foreground/70",children:[t("settings.openchamber.tunnel.field.expires"),": ",r.bootstrapExpiresAt?ae: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(Q,{size:"sm",variant:"outline",onClick:rt,disabled:a==="stopping"||P||D==="managed-local"&&Te,className:St,children:[s.jsx(L,{name:"restart",className:"size-3.5"}),t("settings.openchamber.tunnel.actions.newConnectLink")]}),s.jsx(Q,{size:"sm",variant:"ghost",onClick:mt,disabled:a==="stopping"||P,className:"gap-2 text-[var(--status-error)]",children:a==="stopping"?s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"loader-4",className:"size-3.5 animate-spin"})," ",t("settings.openchamber.tunnel.actions.stopping")]}):t("settings.openchamber.tunnel.actions.stopTunnel")})]})})]}),a==="error"&&f&&s.jsxs("section",{className:"space-y-3 px-2 pb-2 pt-0",children:[s.jsx("p",{className:"typography-meta text-[var(--status-error)]",children:f}),s.jsx(Q,{size:"sm",variant:"ghost",onClick:rt,children:t("settings.openchamber.tunnel.actions.retry")})]})]})})},pu=()=>{const{t}=it(),[e,n]=ge.useState(""),[a,i]=ge.useState(!0),[r,o]=ge.useState(!1),d=Ne(g=>g.showOpenCodeUpdateNotifications),c=Ne(g=>g.setShowOpenCodeUpdateNotifications),p=Ne(g=>g.agentControlToolEnabled),u=Ne(g=>g.setAgentControlToolEnabled);ge.useEffect(()=>{let g=!1;return(async()=>{try{const x=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!x.ok)return;const v=await x.json().catch(()=>null);if(g||!v)return;const N=typeof v.opencodeBinary=="string"?v.opencodeBinary.trim():"";n(N)}catch{}finally{g||i(!1)}})(),()=>{g=!0}},[]);const f=ge.useCallback(async()=>{if(!(typeof window>"u")&&ss())try{const g=await Fd();g.success&&g.path&&g.path.trim().length>0&&n(g.path.trim())}catch{}},[]),m=ge.useCallback(async()=>{o(!0);try{const g=e.trim(),x=g.length>=2&&(g.startsWith('"')&&g.endsWith('"')||g.startsWith("'")&&g.endsWith("'"))?g.slice(1,-1).trim():g;await kt({opencodeBinary:x}),await ea({message:t("settings.openchamber.opencodeCli.actions.restartingOpenCode"),mode:"projects",scopes:["all"]})}finally{o(!1)}},[t,e]),b=ge.useCallback(g=>{c(g),kt({showOpenCodeUpdateNotifications:g})},[c]),h=ge.useCallback(g=>{u(g),kt({agentControlToolEnabled:g})},[u]);return s.jsx(ot,{title:t("settings.openchamber.opencodeCli.title"),children:s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs(Jt,{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(tt,{value:e,onChange:g=>n(g.target.value),placeholder:t("settings.openchamber.opencodeCli.field.binaryPathPlaceholder"),disabled:a||r,className:"h-8 min-w-0 flex-1 font-mono text-xs"}),s.jsx(Q,{type:"button",variant:"outline",size:"xs",onClick:f,disabled:a||r||!ss(),className:Ts,"aria-label":t("settings.openchamber.opencodeCli.actions.browseAria"),title:t("settings.openchamber.opencodeCli.actions.browse"),children:s.jsx(L,{name:"folder",className:"h-4 w-4"})})]}),s.jsxs(Aa,{className:Rs,children:[s.jsx(wt,{settingsItem:"sessions.opencode-update-notifications",checked:d,onChange:b,label:t("settings.openchamber.opencodeCli.field.showUpdateNotifications"),ariaLabel:t("settings.openchamber.opencodeCli.field.showUpdateNotificationsAria")}),s.jsx(wt,{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(Q,{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")})})]})]})})},gu=()=>{const{t}=it(),e=ss()&&Ma(),n=e&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",[a,i]=ge.useState(!1),[r,o]=ge.useState(!1),[d,c]=ge.useState(""),[p,u]=ge.useState(""),[f,m]=ge.useState(!1),[b,h]=ge.useState(!1),[g,x]=ge.useState(null),[v,N]=ge.useState(!0),[P,F]=ge.useState(!1),[w,j]=ge.useState(!1),[y,R]=ge.useState(!1),[_,B]=ge.useState(!1),[D,k]=ge.useState(!1),[T,M]=ge.useState(!1),[O,V]=ge.useState(!1),[U,Y]=ge.useState(!0),[X,S]=ge.useState(!0),[W,Z]=ge.useState(!1),[A,C]=ge.useState(!1),[z,$]=ge.useState(!1),[H,J]=ge.useState(null),[ee,ue]=ge.useState(null);ge.useEffect(()=>{if(!e){N(!1);return}let ne=!1;return(async()=>{try{const oe=await gt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!oe.ok)throw new Error(t("settings.openchamber.desktopNetwork.error.loadFailed"));const Ae=await oe.json().catch(()=>null);if(ne)return;const je=Ae?.desktopLanAccessEnabled===!0,Ie=typeof Ae?.desktopUiPassword=="string"?Ae.desktopUiPassword:"";i(je),o(je),c(Ie),u(Ie),h(Ae?.desktopLanAccessActive===!0),x(typeof Ae?.desktopLanAccessBlockedReason=="string"?Ae.desktopLanAccessBlockedReason:null);const Te=Ae?.desktopMacMenuBarEnabled!==!1;Y(Te),S(Te),J(null)}catch(oe){ne||J(oe instanceof Error?oe.message:t("settings.openchamber.desktopNetwork.error.loadFailed"))}finally{ne||N(!1)}})(),()=>{ne=!0}},[e,t]),ge.useEffect(()=>{if(!e){j(!1);return}let ne=!1;return(async()=>{const oe=await Kg();ne||(j(oe?.supported===!0),R(oe?.enabled===!0))})(),()=>{ne=!0}},[e]),ge.useEffect(()=>{if(!e){k(!1);return}let ne=!1;return(async()=>{const oe=await Ug();ne||(k(oe?.supported===!0),M(oe?.enabled===!0))})(),()=>{ne=!0}},[e]),ge.useEffect(()=>{if(!e){Z(!1);return}let ne=!1;return(async()=>{const oe=await _g();ne||(Z(oe?.supported===!0),C(oe?.enabled===!0))})(),()=>{ne=!0}},[e]),ge.useEffect(()=>{if(!e||!r){ue(null);return}let ne=!1;return(async()=>{const oe=await Ld();ne||ue(oe)})(),()=>{ne=!0}},[r,e]);const re=r!==a||p!==d||X!==U,xe=ge.useMemo(()=>{if(typeof window>"u")return null;const oe=La()||window.location.href;let Ae=0;try{Ae=Number(new URL(oe).port)}catch{Ae=Number(window.location.port)}return Number.isFinite(Ae)&&Ae>0?Ae:null},[]),be=r&&b&&ee&&xe?`http://${ee}:${xe}`:null,he=r&&!p.trim(),ye=a&&!b&&g==="missing-password",fe=v||P||!re||he,ae=ge.useCallback(ne=>{u(ne),ne.trim()||o(!1)},[]),ce=ge.useCallback(async()=>{if(!w||_)return;const ne=!y;R(ne),B(!0),J(null);try{const oe=await $g(ne);if(!oe?.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.launchAtLoginUnsupported"));R(oe.enabled)}catch(oe){R(!ne),J(oe instanceof Error?oe.message:t("settings.openchamber.desktopNetwork.error.launchAtLoginSaveFailed"))}finally{B(!1)}},[_,y,w,t]),pe=ge.useCallback(async()=>{if(!D||O)return;const ne=!T;M(ne),V(!0),J(null);try{const oe=await Vg(ne);if(!oe)throw new Error(t("settings.openchamber.desktopNetwork.error.minimizeToTraySaveFailed"));if(!oe.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.minimizeToTrayUnsupported"));M(oe.enabled)}catch(oe){M(!ne),J(oe instanceof Error?oe.message:t("settings.openchamber.desktopNetwork.error.minimizeToTraySaveFailed"))}finally{V(!1)}},[O,T,D,t]),q=ge.useCallback(async()=>{if(!W||z)return;const ne=!A;C(ne),$(!0),J(null);try{const oe=await Hg(ne);if(!oe?.supported)throw new Error(t("settings.openchamber.desktopNetwork.error.keepAwakeUnsupported"));C(oe.enabled)}catch(oe){C(!ne),J(oe instanceof Error?oe.message:t("settings.openchamber.desktopNetwork.error.keepAwakeSaveFailed"))}finally{$(!1)}},[z,A,W,t]),te=ge.useCallback(async()=>{if(re){F(!0),J(null);try{if(!(await gt("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({desktopLanAccessEnabled:r,desktopUiPassword:p,desktopMacMenuBarEnabled:X})})).ok)throw new Error(t("settings.openchamber.desktopNetwork.error.saveFailed"));if(i(r),c(p),Y(X),!await Wg())throw new Error(t("settings.openchamber.desktopNetwork.error.savedRestartFailed"))}catch(ne){J(ne instanceof Error?ne.message:t("settings.openchamber.desktopNetwork.error.saveFailed")),F(!1)}}},[X,p,r,re,t]);return e?s.jsx(ot,{title:t("settings.openchamber.desktopNetwork.title"),children:s.jsxs("div",{className:"space-y-3",children:[w||n||D||W?s.jsxs("div",{className:Rs,children:[w?s.jsx(wt,{settingsItem:"sessions.desktop-launch-at-login",checked:y,onChange:ne=>{ne!==y&&ce()},disabled:_,label:t("settings.openchamber.desktopNetwork.field.launchAtLogin"),info:t("settings.openchamber.desktopNetwork.field.launchAtLoginDescription"),ariaLabel:t("settings.openchamber.desktopNetwork.field.launchAtLoginAria")}):null,n?s.jsx(wt,{settingsItem:"sessions.desktop-mac-menu-bar",checked:X,onChange:S,disabled:v||P,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(wt,{settingsItem:"sessions.desktop-minimize-to-tray",checked:T,onChange:ne=>{ne!==T&&pe()},disabled:O,label:t("settings.openchamber.desktopNetwork.field.minimizeToTray"),info:t("settings.openchamber.desktopNetwork.field.minimizeToTrayDescription"),ariaLabel:t("settings.openchamber.desktopNetwork.field.minimizeToTrayAria")}):null,W?s.jsx(wt,{settingsItem:"sessions.desktop-keep-awake",checked:A,onChange:ne=>{ne!==A&&q()},disabled:z,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(ls,{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(tt,{id:"desktop-ui-password",type:f?"text":"password",className:"h-8 min-w-0 flex-1",value:p,onChange:ne=>ae(ne.target.value),placeholder:t("settings.openchamber.desktopPassword.field.passwordPlaceholder"),disabled:v||P,required:r,"aria-invalid":he}),s.jsx(Q,{type:"button",variant:"ghost",size:"xs",onClick:()=>m(ne=>!ne),className:Ts,"aria-label":t(f?"settings.openchamber.desktopPassword.actions.hidePassword":"settings.openchamber.desktopPassword.actions.showPassword"),"aria-pressed":f,children:s.jsx(L,{name:f?"eye-off":"eye",className:"h-4 w-4"})})]}),s.jsx("div",{className:Rs,children:s.jsx(wt,{settingsItem:"sessions.desktop-lan-access",checked:r,onChange:o,disabled:v||P,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")}),he||ye?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")})}),H?s.jsx("div",{className:"typography-micro text-[var(--status-error)]",children:H}):null,be?s.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[t(re&&!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(Q,{type:"button",size:"xs",onClick:te,disabled:fe,className:"shrink-0 !font-normal",children:t(P?"settings.common.actions.saving":"settings.openchamber.desktopNetwork.actions.saveAndRestart")})})]})}):null},ww=new Set(["shift","control","alt","meta"]),jw=t=>{if(ww.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=Jp(t.key);return n?(e.push(n),va(e.join("+"))):null},kw=()=>{const t=Ye.c(54),{t:e}=it();let n;t[0]!==e?(n=z=>e(z),t[0]=e,t[1]=n):n=t[1];const a=n,i=Ne(Nw),r=Ne(Sw),o=Ne(Cw),d=Ne(Iw);let c;if(t[2]===Symbol.for("react.memo_cache_sentinel")){e:{const z=Gp();if(!os()){c=z;break e}c=z.filter(Pw)}t[2]=c}else c=t[2];const p=c;let u;t[3]!==a?(u=(z,$)=>{const H=`settings.openchamber.keyboardShortcuts.action.${z}.label`,J=a(H);return J===H?$:J},t[3]=a,t[4]=u):u=t[4];const f=u,[m,b]=l.useState(null);let h;t[5]===Symbol.for("react.memo_cache_sentinel")?(h={},t[5]=h):h=t[5];const[g,x]=l.useState(h),[v,N]=l.useState(""),[P,F]=l.useState(""),[w,j]=l.useState(null),y=Aw;let R;t[6]!==i?(R=(z,$)=>{const H=va($);for(const J of p){if(J.id===z)continue;const ee=rl(J.id,i);if(va(ee)===H)return J.id}return null},t[6]=i,t[7]=R):R=t[7];const _=R;let B;t[8]!==_||t[9]!==r||t[10]!==i||t[11]!==e?(B=(z,$)=>{const H=va($),J=_(z,H);if(J){j({actionId:z,combo:H,conflictActionId:J}),N("");return}const ee={...i,[z]:H};r(z,H),y(ee),j(null),N(""),F(ol(H)?e("settings.openchamber.keyboardShortcuts.warning.riskyBrowserShortcut"):""),x(ue=>{const re={...ue};return delete re[z],re})},t[8]=_,t[9]=r,t[10]=i,t[11]=e,t[12]=B):B=t[12];const D=B;let k;t[13]!==w||t[14]!==r||t[15]!==i||t[16]!==e?(k=()=>{if(!w)return;const z={...i,[w.conflictActionId]:ll,[w.actionId]:w.combo};r(w.conflictActionId,ll),r(w.actionId,w.combo),y(z),j(null),N(""),F(ol(w.combo)?e("settings.openchamber.keyboardShortcuts.warning.riskyBrowserShortcut"):""),x($=>{const H={...$};return delete H[w.actionId],H})},t[13]=w,t[14]=r,t[15]=i,t[16]=e,t[17]=k):k=t[17];const T=k;let M;t[18]!==o||t[19]!==i?(M=z=>{const $={...i};delete $[z],o(z),y($),x(H=>{const J={...H};return delete J[z],J}),j(null),N(""),F("")},t[18]=o,t[19]=i,t[20]=M):M=t[20];const O=M;let V;t[21]!==e?(V=e("settings.openchamber.keyboardShortcuts.title"),t[21]=e,t[22]=V):V=t[22];let U;t[23]!==e?(U=e("settings.openchamber.keyboardShortcuts.tooltip"),t[23]=e,t[24]=U):U=t[24];let Y;t[25]!==d?(Y=()=>{d(),y({}),x({}),j(null),N(""),F("")},t[25]=d,t[26]=Y):Y=t[26];let X;t[27]!==e?(X=e("settings.openchamber.keyboardShortcuts.actions.resetAll"),t[27]=e,t[28]=X):X=t[28];let S;t[29]!==Y||t[30]!==X?(S=s.jsx(Q,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:Y,children:X}),t[29]=Y,t[30]=X,t[31]=S):S=t[31];let W;t[32]!==T||t[33]!==v||t[34]!==w||t[35]!==e||t[36]!==P?(W=(v||P||w)&&s.jsxs("div",{className:"mb-2 space-y-2",children:[w&&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(Q,{type:"button",size:"xs",className:"!font-normal",onClick:T,children:e("settings.openchamber.keyboardShortcuts.actions.overwrite")}),s.jsx(Q,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>j(null),children:e("settings.common.actions.cancel")})]})]}),v&&s.jsx("div",{className:"rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3 typography-meta text-foreground",children:v}),P&&s.jsx("div",{className:"rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3 typography-meta text-foreground",children:P})]}),t[32]=T,t[33]=v,t[34]=w,t[35]=e,t[36]=P,t[37]=W):W=t[37];let Z;t[38]!==f||t[39]!==m||t[40]!==g||t[41]!==O||t[42]!==D||t[43]!==i||t[44]!==e?(Z=p.map((z,$)=>{const H=rl(z.id,i),J=g[z.id],ee=J??H,ue=typeof J=="string"&&va(J)!==va(H);return s.jsx("div",{className:le("py-1.5",$>0&&"border-t border-border/40"),children:s.jsxs(Jt,{label:f(z.id,z.label),alignEnd:!1,children:[s.jsx(tt,{readOnly:!0,value:m===z.id?e("settings.openchamber.keyboardShortcuts.field.pressKeys"):qp(ee),onFocus:()=>{b(z.id),N("")},onBlur:()=>{m===z.id&&b(null)},onKeyDown:re=>{if(re.preventDefault(),re.stopPropagation(),re.key==="Escape"){b(null);return}const xe=jw(re);xe&&(x(be=>({...be,[z.id]:xe})),b(null),j(null),N(""))},className:"h-7 w-40 min-w-0 typography-ui-label text-center"}),s.jsx(Q,{type:"button",variant:"secondary",size:"xs",className:"!font-normal",onClick:()=>{const re=g[z.id];if(!re){N(e("settings.openchamber.keyboardShortcuts.error.captureFirst"));return}D(z.id,re)},disabled:!ue,children:e("settings.common.actions.saveChanges")}),s.jsx(Q,{type:"button",size:"xs",className:"!font-normal",variant:"ghost",onClick:()=>O(z.id),children:e("settings.common.actions.reset")})]})},z.id)}),t[38]=f,t[39]=m,t[40]=g,t[41]=O,t[42]=D,t[43]=i,t[44]=e,t[45]=Z):Z=t[45];let A;t[46]!==Z?(A=s.jsx("div",{children:Z}),t[46]=Z,t[47]=A):A=t[47];let C;return t[48]!==S||t[49]!==W||t[50]!==A||t[51]!==V||t[52]!==U?(C=s.jsxs(ot,{settingsItem:"shortcuts.keyboard-shortcuts",title:V,divider:!1,info:U,headerAction:S,children:[W,A]}),t[48]=S,t[49]=W,t[50]=A,t[51]=V,t[52]=U,t[53]=C):C=t[53],C};function Nw(t){return t.shortcutOverrides}function Sw(t){return t.setShortcutOverride}function Cw(t){return t.clearShortcutOverride}function Iw(t){return t.resetAllShortcutOverrides}function Pw(t){return t.id!=="toggle_prompt_navigator"}function Aw(t){kt({shortcutOverrides:t})}const fu=()=>{const t=Ye.c(2),[e,n]=l.useState(0);let a,i;return t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>Lo(()=>n(Uw)),i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),l.useEffect(a,i),e},Ew=t=>{const e=Ye.c(78),{section:n}=t,{t:a}=it(),{isMobile:i}=_s();fu();let r;e[0]!==i?(r=i&&Sn(),e[0]=i,e[1]=r):r=e[1];const o=r;let d;e[2]===Symbol.for("react.memo_cache_sentinel")?(d=os(),e[2]=d):d=e[2];const c=d;let p;e[3]===Symbol.for("react.memo_cache_sentinel")?(p=ss()&&Ma(),e[3]=p):p=e[3];const u=p;if(!n){let W,Z,A,C,z,$;e[4]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx(cr,{}),Z=s.jsx(du,{}),A=u&&s.jsx(gu,{}),C=!c&&s.jsx(pu,{}),z=s.jsx(lu,{}),$=Sn()&&!ss()&&!c&&!Do()&&s.jsx(cu,{}),e[4]=W,e[5]=Z,e[6]=A,e[7]=C,e[8]=z,e[9]=$):(W=e[4],Z=e[5],A=e[6],C=e[7],z=e[8],$=e[9]);let H;e[10]!==o?(H=o&&s.jsx(Ud,{}),e[10]=o,e[11]=H):H=e[11];let J;return e[12]!==H?(J=s.jsxs(us,{showSaveStatus:!0,className:"openchamber-page-body space-y-3 sm:space-y-6",children:[W,Z,A,C,z,$,H]}),e[12]=H,e[13]=J):J=e[13],J}let f;e[14]!==n?(f=()=>{switch(n){case"general":return s.jsx(Rw,{});case"visual":return s.jsx(Dw,{});case"chat":return s.jsx(Mw,{});case"sessions":return s.jsx(Lw,{});case"shortcuts":return s.jsx(Tw,{});case"git":return s.jsx(Fw,{});case"github":return s.jsx(Ow,{});case"notifications":return s.jsx(zw,{});case"voice":return s.jsx(Bw,{});case"tunnel":return s.jsx(Kw,{});default:return null}},e[14]=n,e[15]=f):f=e[15];const m=f;let b;e[16]!==a?(b=a("settings.page.general.title"),e[16]=a,e[17]=b):b=e[17];let h;e[18]!==a?(h=a("settings.page.appearance.title"),e[18]=a,e[19]=h):h=e[19];let g;e[20]!==a?(g=a("settings.page.chat.title"),e[20]=a,e[21]=g):g=e[21];let x;e[22]!==a?(x=a("settings.page.sessions.title"),e[22]=a,e[23]=x):x=e[23];let v;e[24]!==a?(v=a("settings.page.shortcuts.title"),e[24]=a,e[25]=v):v=e[25];let N;e[26]!==a?(N=a("settings.page.git.title"),e[26]=a,e[27]=N):N=e[27];let P;e[28]!==a?(P=a("settings.page.git.title"),e[28]=a,e[29]=P):P=e[29];let F;e[30]!==a?(F=a("settings.page.notifications.title"),e[30]=a,e[31]=F):F=e[31];let w;e[32]!==a?(w=a("settings.page.voice.title"),e[32]=a,e[33]=w):w=e[33];let j;e[34]!==a?(j=a("settings.page.tunnel.title"),e[34]=a,e[35]=j):j=e[35];let y;e[36]!==N||e[37]!==P||e[38]!==F||e[39]!==w||e[40]!==j||e[41]!==b||e[42]!==h||e[43]!==g||e[44]!==x||e[45]!==v?(y={general:b,visual:h,chat:g,sessions:x,shortcuts:v,git:N,github:P,notifications:F,voice:w,tunnel:j},e[36]=N,e[37]=P,e[38]=F,e[39]=w,e[40]=j,e[41]=b,e[42]=h,e[43]=g,e[44]=x,e[45]=v,e[46]=y):y=e[46];const R=y[n];let _;e[47]!==a?(_=a("settings.page.general.description"),e[47]=a,e[48]=_):_=e[48];let B;e[49]!==a?(B=a("settings.page.appearance.description"),e[49]=a,e[50]=B):B=e[50];let D;e[51]!==a?(D=a("settings.page.chat.description"),e[51]=a,e[52]=D):D=e[52];let k;e[53]!==a?(k=a("settings.page.sessions.description"),e[53]=a,e[54]=k):k=e[54];let T;e[55]!==a?(T=a("settings.page.shortcuts.description"),e[55]=a,e[56]=T):T=e[56];let M;e[57]!==a?(M=a("settings.page.notifications.description"),e[57]=a,e[58]=M):M=e[58];let O;e[59]!==a?(O=a("settings.page.voice.description"),e[59]=a,e[60]=O):O=e[60];let V;e[61]!==a?(V=a("settings.page.tunnel.description"),e[61]=a,e[62]=V):V=e[62];let U;e[63]!==_||e[64]!==B||e[65]!==D||e[66]!==k||e[67]!==T||e[68]!==M||e[69]!==O||e[70]!==V?(U={general:_,visual:B,chat:D,sessions:k,shortcuts:T,git:void 0,github:void 0,notifications:M,voice:O,tunnel:V},e[63]=_,e[64]=B,e[65]=D,e[66]=k,e[67]=T,e[68]=M,e[69]=O,e[70]=V,e[71]=U):U=e[71];const Y=U[n];let X;e[72]!==m?(X=m(),e[72]=m,e[73]=X):X=e[73];let S;return e[74]!==Y||e[75]!==R||e[76]!==X?(S=s.jsx(us,{title:R,description:Y,showSaveStatus:!0,className:"openchamber-page-body",children:X}),e[74]=Y,e[75]=R,e[76]=X,e[77]=S):S=e[77],S},Tw=()=>{const t=Ye.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(kw,{}),t[0]=e):e=t[0],e},Rw=()=>{const t=Ye.c(7);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=os(),t[0]=e):e=t[0];const n=e;fu();let a;t[1]===Symbol.for("react.memo_cache_sentinel")?(a=ss()&&Ma(),t[1]=a):a=t[1];const i=a;let r;t[2]===Symbol.for("react.memo_cache_sentinel")?(r=Sn()&&!ss()&&!n&&!Do(),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(gu,{}),c=o&&s.jsx(cu,{}),p=!n&&s.jsx(pu,{}),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(cr,{visibleSettings:["fileEditorKeymap","expandedEditorToolbar",...n?[]:["terminalQuickKeys"],...n?[]:["terminalShell"],...n?[]:["terminalLoginShell"],"messageTransport","reportUsage"]})]}),t[6]=u):u=t[6],u},Dw=()=>{const t=Ye.c(2);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=os(),t[0]=e):e=t[0];const n=e;let a;return t[1]===Symbol.for("react.memo_cache_sentinel")?(a=s.jsx(cr,{visibleSettings:["theme","windowControlsPosition","pwaInstallName","pwaOrientation","mobileKeyboardMode","timeFormat",...n?[]:["weekStart"],"fontSize","terminalFontSize","editorFontSize","spacing","inputBarOffset"]}),t[1]=a):a=t[1],a},Mw=()=>{const t=Ye.c(2);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=os(),t[0]=e):e=t[0];const n=e;let a;return t[1]===Symbol.for("react.memo_cache_sentinel")?(a=s.jsx(cr,{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},Lw=()=>{const t=Ye.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsxs(s.Fragment,{children:[s.jsx(du,{}),s.jsx(lu,{})]}),t[0]=e):e=t[0],e},Fw=()=>{const t=Ye.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(iu,{}),t[0]=e):e=t[0],e},Ow=()=>{const t=Ye.c(1);if(os())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(ru,{}),t[0]=e):e=t[0],e},zw=()=>{const t=Ye.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(iw,{}),t[0]=e):e=t[0],e},Bw=()=>{const t=Ye.c(1);if(os())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(dw,{}),t[0]=e):e=t[0],e},Kw=()=>{const t=Ye.c(1);if(os())return null;let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=s.jsx(vw,{}),t[0]=e):e=t[0],e};function Uw(t){return t+1}const hu=[{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}],_w={sessions:"sessions",agents:"agents",commands:"commands",mcp:"mcp",skills:"skills.installed",providers:"providers",usage:"usage","git-identities":"git",settings:"home"};function Ca(t){const e=t.trim().toLowerCase();return hu.find(n=>n.slug===e)??null}function Bo(t){const e=(t??"").trim().toLowerCase();if(!e)return"home";const n=_w[e];if(n)return n;const a=Ca(e);return a?a.slug:"home"}const $w=[{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.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.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-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},{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.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 Hc(t){return t.trim().toLocaleLowerCase()}function Vw({query:t,runtimeCtx:e,visiblePageSlugs:n,t:a,getPageTitle:i}){const r=Hc(t);if(!r)return[];const o=n?new Set(n):null,d=r.split(/\s+/).filter(Boolean);return $w.flatMap(c=>{if(o&&!o.has(c.page))return[];const p=Ca(c.page);if(!p||p.isAvailable&&!p.isAvailable(e)||c.isAvailable&&!c.isAvailable(e))return[];const u=a(c.titleKey),f=c.descriptionKey?a(c.descriptionKey):null,m=Hc([u,f,i(c.page),...c.keywords??[]].filter(Boolean).join(" "));return d.every(b=>m.includes(b))?[{...c,title:u,description:f,pageTitle:i(c.page)}]:[]})}const Wc=256,Gc=280,xu="__openchamberSettingsDetail",Hw=["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"],Ww=["general","projects","opencode","content"],Gw={icon:"chat-thread"},qw="__add_provider__";function Jw(t,e){const n=os(),a=!t&&Sn();return{isVSCode:n,isWeb:a,isDesktop:t,isMobile:e}}function qc(t,e){return t.isAvailable?t.isAvailable(e):!0}function Ao(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ja(t,e){const n=new Set(e);let a=t,i=1;for(;n.has(a);)a=`${t}-${i}`,i+=1;return a}function Jr(t){if(!Ao(t))return null;const e=t[xu];if(!Ao(e))return null;const n=e.page,a=e.stage;return typeof n!="string"||a!=="page-content"?null:{page:Bo(n),stage:a}}function Qw(){return typeof window>"u"||!Ao(window.history.state)?{}:window.history.state}function bu(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 Gw.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 Yw=t=>{const e=Ye.c(123),{onClose:n,forceMobile:a,isWindowed:i,visiblePageSlugs:r,initialMobileStage:o}=t,d=o===void 0?"nav":o,{t:c}=it(),p=_s(),u=a??p.isMobile,f=Ne(Xw),m=Ne(Zw),b=Ne(e1);let h;e[0]!==f?(h=Bo(f),e[0]=f,e[1]=h):h=e[1];const g=h,[x,v]=l.useState(d),N=l.useRef(null);let P,F;e[2]!==u||e[3]!==b||e[4]!==g?(P=()=>{!u&&g==="home"&&b("general")},F=[u,b,g],e[2]=u,e[3]=b,e[4]=g,e[5]=P,e[6]=F):(P=e[5],F=e[6]),l.useEffect(P,F);const[w,j]=l.useState(""),[y,R]=l.useState(null),[_,B]=l.useState(0),D=l.useRef(null);let k;e[7]===Symbol.for("react.memo_cache_sentinel")?(k=[],e[7]=k):k=e[7];const T=l.useRef(k),M=l.useRef(0),O=l.useRef(!1);let V;e[8]===Symbol.for("react.memo_cache_sentinel")?(V=ss(),e[8]=V):V=e[8];const U=V;let Y;e[9]===Symbol.for("react.memo_cache_sentinel")?(Y=ss()&&Ma(),e[9]=Y):Y=e[9];const X=Y;let S;e[10]===Symbol.for("react.memo_cache_sentinel")?(S=ss()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="darwin",e[10]=S):S=e[10];const W=S;let Z;e[11]===Symbol.for("react.memo_cache_sentinel")?(Z=ss()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="win32",e[11]=Z):Z=e[11];const A=Z;let C;e[12]===Symbol.for("react.memo_cache_sentinel")?(C=ss()&&typeof window<"u"&&window.__OPENCHAMBER_PLATFORM__==="linux",e[12]=C):C=e[12];const z=C;let $;e[13]!==u?($=Jw(U,u),e[13]=u,e[14]=$):$=e[14];const H=$;let J;if(e[15]!==u||e[16]!==H||e[17]!==r){const Qe=r?new Set(r):null;let ht;e[19]!==H?(ht=Mt=>qc(Mt,H),e[19]=H,e[20]=ht):ht=e[20];let Nt;e[21]!==H.isVSCode?(Nt=Mt=>!(H.isVSCode&&Mt.slug==="projects"),e[21]=H.isVSCode,e[22]=Nt):Nt=e[22];let Pt;e[23]!==u?(Pt=Mt=>!(u&&Mt.slug==="shortcuts"),e[23]=u,e[24]=Pt):Pt=e[24],J=hu.filter(t1).filter(Mt=>!Qe||Qe.has(Mt.slug)).filter(ht).filter(Nt).filter(Pt),e[15]=u,e[16]=H,e[17]=r,e[18]=J}else J=e[18];const ee=J;let ue;e[25]===Symbol.for("react.memo_cache_sentinel")?(ue=new Map(Hw.map(s1)),e[25]=ue):ue=e[25];const re=ue;let xe;if(e[26]!==ee){let Qe;e[28]===Symbol.for("react.memo_cache_sentinel")?(Qe=(ht,Nt)=>(re.get(ht.slug)??999)-(re.get(Nt.slug)??999),e[28]=Qe):Qe=e[28],xe=ee.slice().sort(Qe),e[26]=ee,e[27]=xe}else xe=e[27];const be=xe,he=rs(n1);let ye;e[29]!==m||e[30]!==i||e[31]!==H.isVSCode||e[32]!==g?(ye=()=>{if(!(!m&&!H.isVSCode&&!i)){if(g==="agents"){ri.getState().loadAgents();return}if(g==="commands"){rr.getState().loadCommands();return}if(g==="mcp"){Ta.getState().loadMcpConfigs();return}if(g==="plugins"){fs.getState().loadPlugins();return}(g==="skills.installed"||g==="skills.catalog")&&(Nn.getState().loadSkills(),jn.getState().loadCatalog()),g==="snippets"&&or.getState().loadSnippets()}},e[29]=m,e[30]=i,e[31]=H.isVSCode,e[32]=g,e[33]=ye):ye=e[33];let fe;e[34]!==he||e[35]!==m||e[36]!==i||e[37]!==H.isVSCode||e[38]!==g?(fe=[he,m,i,H.isVSCode,g],e[34]=he,e[35]=m,e[36]=i,e[37]=H.isVSCode,e[38]=g,e[39]=fe):fe=e[39],l.useEffect(ye,fe);let ae;e[40]!==u||e[41]!==b?(ae=Qe=>{if(b(Qe),N.current=Qe,!u)return;const ht=Ca(Qe);if(!ht||ht.slug==="home"){v("nav");return}v(ht.kind==="split"?"page-sidebar":"page-content")},e[40]=u,e[41]=b,e[42]=ae):ae=e[42];const ce=ae;let pe;e[43]!==g?(pe=Ca(g),e[43]=g,e[44]=pe):pe=e[44];const q=pe;let te;e[45]===Symbol.for("react.memo_cache_sentinel")?(te={general:"general",appearance:"visual",chat:"chat",shortcuts:"shortcuts",sessions:"sessions",notifications:"notifications",voice:"voice",tunnel:"tunnel"},e[45]=te):te=e[45];const ne=te;let oe;e[46]!==c?(oe=Qe=>{switch(Qe){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[46]=c,e[47]=oe):oe=e[47];const Ae=oe;let je;e[48]!==Ae||e[49]!==H||e[50]!==w||e[51]!==c||e[52]!==r?(je=Vw({query:w,runtimeCtx:{...H,isDesktopLocalOrigin:X,isMac:W,isWindows:A,isLinux:z},visiblePageSlugs:r,t:c,getPageTitle:Ae}),e[48]=Ae,e[49]=H,e[50]=w,e[51]=c,e[52]=r,e[53]=je):je=e[53];const Ie=je,Te=c1;let Me;if(e[54]!==Ie){Me=[];const Qe=new Map;for(const ht of Ie){let Nt=Qe.get(ht.page);Nt||(Nt={page:ht.page,pageTitle:ht.pageTitle,results:[]},Qe.set(ht.page,Nt),Me.push(Nt)),Nt.results.push(ht)}e[54]=Ie,e[55]=Me}else Me=e[55];const He=Me;let Ve;e[56]===Symbol.for("react.memo_cache_sentinel")?(Ve=()=>{B(0),M.current=0,O.current=!1},e[56]=Ve):Ve=e[56];let Ue;e[57]!==w?(Ue=[w],e[57]=w,e[58]=Ue):Ue=e[58],l.useEffect(Ve,Ue);let ze,Be;e[59]!==_?(ze=()=>{M.current=_},Be=[_],e[59]=_,e[60]=ze,e[61]=Be):(ze=e[60],Be=e[61]),l.useEffect(ze,Be);let Ge,Fe;e[62]!==_?(Ge=()=>{T.current[_]?.scrollIntoView({block:"nearest"})},Fe=[_],e[62]=_,e[63]=Ge,e[64]=Fe):(Ge=e[63],Fe=e[64]),l.useEffect(Ge,Fe);let ve,De;e[65]!==_||e[66]!==Ie.length?(ve=()=>{_>=Ie.length&&B(Math.max(0,Ie.length-1)),T.current.length=Ie.length},De=[_,Ie.length],e[65]=_,e[66]=Ie.length,e[67]=ve,e[68]=De):(ve=e[67],De=e[68]),l.useEffect(ve,De);let Ke;e[69]!==u||e[70]!==ce?(Ke=Qe=>{const ht=Te(Qe);R(ht),ce(Qe.page),u&&v("page-content"),Qe.id==="plugins.create"&&typeof window<"u"&&window.setTimeout(d1,50)},e[69]=u,e[70]=ce,e[71]=Ke):Ke=e[71];const We=Ke;let Pe;e[72]!==We||e[73]!==w||e[74]!==Ie?(Pe=Qe=>{if(w.trim()){if(Qe.key==="Escape"){Qe.preventDefault(),j("");return}if(Ie.length!==0){if(Qe.key==="ArrowDown"){Qe.preventDefault(),O.current=!0,B(ht=>(ht+1)%Ie.length);return}if(Qe.key==="ArrowUp"){Qe.preventDefault(),O.current=!0,B(ht=>(ht-1+Ie.length)%Ie.length);return}if(Qe.key==="Enter"){Qe.preventDefault();const ht=(M.current%Ie.length+Ie.length)%Ie.length,Nt=Ie[ht]??Ie[0];Nt&&We(Nt)}}}},e[72]=We,e[73]=w,e[74]=Ie,e[75]=Pe):Pe=e[75];const at=Pe;let se;e[76]!==y?(se=()=>{const Qe=y;if(!Qe)return;let ht=!1;const Nt=window.requestAnimationFrame(()=>{if(ht)return;const Pt=typeof CSS<"u"&&CSS.escape?CSS.escape(Qe):Qe.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),Mt=D.current?.querySelector(`[data-settings-item="${Pt}"]`);Mt&&(R(null),Mt.scrollIntoView({block:"center",behavior:"smooth"}),Mt.setAttribute("data-settings-search-highlight","true"),window.setTimeout(()=>{Mt.removeAttribute("data-settings-search-highlight")},1600))});return()=>{ht=!0,window.cancelAnimationFrame(Nt)}},e[76]=y,e[77]=se):se=e[77];let I;e[78]!==y||e[79]!==g?(I=[y,g],e[78]=y,e[79]=g,e[80]=I):I=e[80],l.useEffect(se,I);let Ee;e[81]!==c?(Ee=()=>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:Fo,children:c("settings.view.unavailable.title")}),s.jsx("p",{className:"typography-ui text-muted-foreground mt-1",children:c("settings.view.unavailable.description")})]})}),e[81]=c,e[82]=Ee):Ee=e[82];const Le=Ee,_e=u1;let Xe;e[83]!==Le||e[84]!==H||e[85]!==c?(Xe=Qe=>{const ht=Ca(Qe);if(ht&&!qc(ht,H))return Le();switch(Qe){case"projects":return s.jsx(dy,{});case"remote-instances":return s.jsx(Py,{});case"agents":return s.jsx(lh,{});case"behavior":return s.jsx(ph,{});case"commands":return s.jsx(jh,{});case"mcp":return s.jsx(Xh,{});case"plugins":return s.jsx(Bx,{});case"skills.installed":return s.jsx(fc,{view:"installed"});case"skills.catalog":return s.jsx(fc,{view:"catalog"});case"providers":return s.jsx(Oy,{});case"usage":return s.jsx(bv,{});case"about":return s.jsx(us,{title:c("settings.page.about.title"),showSaveStatus:!1,children:s.jsx(Ud,{})});case"magic-prompts":return s.jsx(kv,{});case"snippets":return s.jsx(Pv,{});case"git":return s.jsx(Dv,{});case"general":case"appearance":case"chat":case"shortcuts":case"sessions":case"notifications":case"voice":case"tunnel":{const Nt=ne[Qe]??"visual";return s.jsx(Ew,{section:Nt})}default:return null}},e[83]=Le,e[84]=H,e[85]=c,e[86]=Xe):Xe=e[86];const ct=Xe;let ut,lt;e[87]!==u||e[88]!==x||e[89]!==g?(ut=()=>{if(!u||x!=="nav"||g==="home"||N.current===g)return;const Qe=Ca(g);!Qe||Qe.slug==="home"||(N.current=g,v(Qe.kind==="split"?"page-sidebar":"page-content"))},lt=[u,x,g],e[87]=u,e[88]=x,e[89]=g,e[90]=ut,e[91]=lt):(ut=e[90],lt=e[91]),l.useEffect(ut,lt);const rt=u&&x!=="nav",mt=u&&x==="page-content"&&g==="skills.installed",xt=x==="page-content"&&q?.kind==="split"&&!mt;let It;e[92]!==mt||e[93]!==rt||e[94]!==c?(It=c(mt?"settings.view.actions.back":rt?"settings.view.actions.backToSettings":"settings.view.actions.closeSettings"),e[92]=mt,e[93]=rt,e[94]=c,e[95]=It):It=e[95];const Se=It,qe=Qp();let Ze;e[96]!==H.isVSCode?(Ze=Qe=>{if(typeof window>"u"||H.isVSCode)return;const ht=Jr(window.history.state);ht?.page===Qe&&ht.stage==="page-content"||window.history.pushState({...Qw(),[xu]:{page:Qe,stage:"page-content"}},"",window.location.href)},e[96]=H.isVSCode,e[97]=Ze):Ze=e[97];const nt=Ze;let ft;e[98]!==nt||e[99]!==g?(ft=()=>{v("page-content"),g==="skills.installed"&&nt(g)},e[98]=nt,e[99]=g,e[100]=ft):ft=e[100];const vt=ft;let St;e[101]!==mt||e[102]!==H.isVSCode||e[103]!==g?(St=()=>{if(mt){if((typeof window<"u"?Jr(window.history.state):null)?.page===g&&!H.isVSCode){window.history.back();return}v("page-sidebar");return}v("nav")},e[101]=mt,e[102]=H.isVSCode,e[103]=g,e[104]=St):St=e[104];const de=St;let ie,we;e[105]!==u||e[106]!==H.isVSCode||e[107]!==g?(ie=()=>{if(!u||H.isVSCode)return;const Qe=ht=>{if(g!=="skills.installed")return;if(Jr(ht.state)?.page==="skills.installed"){v("page-content");return}v(m1)};return window.addEventListener("popstate",Qe),()=>{window.removeEventListener("popstate",Qe)}},we=[u,H.isVSCode,g],e[105]=u,e[106]=H.isVSCode,e[107]=g,e[108]=ie,e[109]=we):(ie=e[108],we=e[109]),l.useEffect(ie,we);let me;e[110]===Symbol.for("react.memo_cache_sentinel")?(me=()=>{v("page-sidebar")},e[110]=me):me=e[110];const Je=me,$e=()=>{const Qe=w.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(L,{name:"search",className:"h-4 w-4 shrink-0"}),s.jsx("input",{value:w,onChange:ht=>j(ht.target.value),onKeyDown:at,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"}),Qe&&s.jsx("button",{type:"button",onClick:()=>j(""),"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(L,{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:Qe?Ie.length>0?(()=>{let ht=0;return He.map(Nt=>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:Nt.pageTitle}),Nt.results.map(Pt=>{const Mt=ht;ht=ht+1;const cs=Mt===_,$s=!!Pt.description;return s.jsxs("button",{type:"button",ref:Yt=>{T.current[Mt]=Yt},onMouseMove:()=>{O.current=!1,B(Mt)},onClick:()=>We(Pt),className:le("flex w-full flex-col rounded-md px-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",$s?"min-h-11 py-1.5":"py-2",cs?"bg-interactive-selection":"hover:bg-interactive-hover"),children:[s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Pt.title}),$s&&s.jsx("span",{className:"typography-micro text-muted-foreground/70 line-clamp-2",children:Pt.description})]},Pt.id)})]},Nt.page))})():s.jsx("div",{className:"px-2 py-6 text-center typography-ui text-muted-foreground",children:c("settings.view.search.noResults")}):(()=>{const ht=new Map;for(const Pt of be){const Mt=Pt.group,cs=ht.get(Mt);cs?cs.push(Pt):ht.set(Mt,[Pt])}return Ww.map(Pt=>({group:Pt,pages:ht.get(Pt)??[]})).filter(p1).map((Pt,Mt)=>{const{group:cs,pages:$s}=Pt;return s.jsxs("div",{className:"space-y-0.5",children:[s.jsx("div",{className:le("px-3 pb-1 typography-micro font-semibold uppercase tracking-wide text-muted-foreground sm:px-2 sm:pb-0.5",Mt===0?"pt-1":"pt-4 sm:pt-3"),children:c(`settings.view.nav.group.${cs}`)}),$s.map(Yt=>{const oa=g===Yt.slug,Hn=bu(Yt.slug);return!Hn&&Yt.slug!=="mcp"?null:s.jsx(Ps,{children:s.jsx(As,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>ce(Yt.slug),"aria-current":oa?"page":void 0,className:le("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",oa?"bg-interactive-selection text-foreground":"text-foreground hover:bg-interactive-hover"),children:[Yt.slug==="mcp"?s.jsx(of,{className:"h-[18px] w-[18px] shrink-0 sm:h-4 sm:w-4"}):s.jsx(L,{name:Hn,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:Ae(Yt.slug)}),Yt.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")})]})]})})},Yt.slug)})]},cs)})})()})}),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:!H.isVSCode&&s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsxs("button",{type:"button",className:le("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:f1,children:[s.jsx(L,{name:"restart",className:"h-4 w-4 shrink-0"}),s.jsx("span",{children:c("settings.view.actions.reloadOpenCode")})]})}),s.jsx(Ds,{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(Mn,{children:$e()})})});if(!q)return s.jsx("div",{className:"flex-1 bg-background"});if(x==="page-sidebar"){if(q.kind!=="split"){const ht=ct(g);return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(Mn,{children:ht})})}return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(Mn,{children:_e(g,{onItemSelect:vt})})})}const Qe=ct(g);return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(Mn,{children:Qe})})};let bt;e[111]!==q||e[112]!==ct||e[113]!==H.isVSCode||e[114]!==g?(bt=()=>!q||g==="home"?null:q.kind==="split"?s.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden",children:[s.jsx("div",{className:le("border-r",H.isVSCode?"bg-background":"bg-sidebar"),style:{width:Gc,minWidth:Gc,borderColor:"var(--interactive-border)"},children:s.jsx(Mn,{children:_e(g,{})})}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(Mn,{children:ct(g)})})]}):s.jsx("div",{className:"h-full min-h-0 overflow-y-scroll overflow-x-hidden bg-background",children:s.jsx(Mn,{children:ct(g)})}),e[111]=q,e[112]=ct,e[113]=H.isVSCode,e[114]=g,e[115]=bt):bt=e[115];const Dt=bt,Qt="true";let _t;e[116]===Symbol.for("react.memo_cache_sentinel")?(_t=le("relative flex h-full min-h-0 flex-col overflow-hidden bg-background"),e[116]=_t):_t=e[116];const as=u?s.jsxs("div",{className:le("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 border-b px-3","bg-background"),style:{borderColor:"var(--interactive-border)"},children:[rt||n?s.jsx("button",{type:"button",onClick:rt?de:n,"aria-label":Se,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(L,{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"):q?Ae(q.slug):c("settings.view.home.title")}),xt&&s.jsx("button",{type:"button",onClick:Je,"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(L,{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:qe}),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(L,{name:"close",className:"h-5 w-5"})})]}):s.jsxs(s.Fragment,{children:[rt&&s.jsx("div",{className:le("absolute left-3 z-50",i?"top-2":"top-3"),children:s.jsx("button",{type:"button",onClick:de,"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(L,{name:"arrow-left-s",className:"h-5 w-5"})})}),n&&s.jsx("div",{className:le("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:qe}),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(L,{name:"close",className:"h-5 w-5"})})})]}),is="flex flex-1 min-h-0 overflow-hidden",$t=u?et():s.jsxs(s.Fragment,{children:[s.jsx("div",{className:le("relative flex h-full min-h-0 flex-col overflow-hidden border-r",U?"bg-sidebar":H.isVSCode?"bg-background":"bg-sidebar"),style:{width:`${Wc}px`,minWidth:`${Wc}px`,borderColor:"var(--interactive-border)"},children:s.jsx(Mn,{children:$e()})}),s.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:Dt()})]});let Ce;e[117]!==$t?(Ce=s.jsx("div",{className:is,children:$t}),e[117]=$t,e[118]=Ce):Ce=e[118];let jt;return e[119]!==_t||e[120]!==as||e[121]!==Ce?(jt=s.jsxs("div",{ref:D,"data-settings-view":Qt,className:_t,children:[as,Ce]}),e[119]=_t,e[120]=as,e[121]=Ce,e[122]=jt):jt=e[122],jt};function Xw(t){return t.settingsPage}function Zw(t){return t.isSettingsDialogOpen}function e1(t){return t.setSettingsPage}function t1(t){return t.slug!=="home"}function s1(t,e){return[t,e]}function n1(t){return t.activeProjectId}function a1(t){return t.name}function i1(t){return t.name}function r1(t){return t.name}function o1(t){return t.name}function l1(t){return t.name}function c1(t){if(t.id.startsWith("agents.")){const e=ri.getState(),n=Ja("new-agent",e.agents.map(a1));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=rr.getState(),n=Ja("new-command",e.commands.map(i1));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=Ta.getState(),n=Ja("new-mcp-server",e.mcpServers.map(r1));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=or.getState(),n=Ja("new-snippet",e.snippets.map(o1));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=Nn.getState(),n=Ja("new-skill",e.skills.map(l1));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(qw),t.id==="plugins.create"?"plugins.spec":t.id}function d1(){window.dispatchEvent(new CustomEvent("openchamber:settings-open-plugin-add"))}function u1(t,e){switch(t){case"projects":return s.jsx(_b,{onItemSelect:e.onItemSelect});case"agents":return s.jsx(Yf,{onItemSelect:e.onItemSelect});case"commands":return s.jsx(gh,{onItemSelect:e.onItemSelect});case"mcp":return s.jsx(kh,{onItemSelect:e.onItemSelect});case"plugins":return s.jsx(Ix,{onItemSelect:e.onItemSelect});case"skills.installed":return s.jsx(Ux,{onItemSelect:e.onItemSelect});case"providers":return s.jsx(Ty,{onItemSelect:e.onItemSelect});case"usage":return s.jsx(Jy,{onItemSelect:e.onItemSelect});case"magic-prompts":return s.jsx(vv,{onItemSelect:e.onItemSelect});case"snippets":return s.jsx(Nv,{onItemSelect:e.onItemSelect});default:return null}}function m1(t){return t==="page-content"?"page-sidebar":t}function p1(t){return t.pages.length>0}function g1(){}function f1(){ea({message:"Restarting OpenCode…",mode:"projects",scopes:["all"]}).catch(g1)}const Jk=Object.freeze(Object.defineProperty({__proto__:null,SettingsView:Yw,getSettingsNavIcon:bu},Symbol.toStringTag,{value:"Module"})),Eo=512*1024,yu=new TextEncoder,h1=new TextDecoder,Jc=t=>yu.encode(t).byteLength,Qr=t=>{const e=yu.encode(t);if(e.byteLength<=Eo)return t;let n=e.byteLength-Eo;for(;n<e.byteLength&&(e[n]&192)===128;)n+=1;return h1.decode(e.subarray(n))},x1="terminal-store";let Qc=!1,Yc=0;const Mi=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Yc+=1,`tab-${Date.now().toString(36)}-${Yc.toString(36)}`),Yr=t=>typeof t=="object"&&t!==null,b1=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 Xr=(t,e)=>({id:t,terminalSessionId:null,lifecycle:"idle",label:e,iconKey:null,bufferChunks:[],bufferLength:0,lastSequence:-1,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Zr=t=>({tabs:[t],activeTabId:t.id}),Qs=(t,e)=>t.tabs.findIndex(n=>n.id===e),Xt=cn()(Da(ii((t,e)=>({sessions: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=Mi(),d=Xr(o,"Terminal");return r.set(a,Zr(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]},createTab:n=>{const a=Es(n);if(!a)return"tab-invalid";const i=Mi();return t(r=>{const o=new Map(r.sessions),d=o.get(a),c=r.nextTabId+1,u=`Terminal ${(d?.tabs.length??0)+1}`,f=Xr(i,u);return d?o.set(a,{...d,tabs:[...d.tabs,f]}):o.set(a,Zr(f)),{sessions:o,nextTabId:c}}),i},setActiveTab:(n,a)=>{const i=Es(n);t(r=>{const o=new Map(r.sessions),d=o.get(i);return!d||d.activeTabId===a||Qs(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=Qs(p,a);if(u<0||p.tabs[u]?.label===o)return d;const f=[...p.tabs];return f[u]={...f[u],label:o},c.set(r,{...p,tabs:f}),{sessions:c}})},setTabIconKey:(n,a,i)=>{const r=Es(n);t(o=>{const d=new Map(o.sessions),c=d.get(r);if(!c)return o;const p=Qs(c,a);if(p<0)return o;const u=i?.trim()||null;if(c.tabs[p]?.iconKey===u)return o;const f=[...c.tabs];return f[p]={...f[p],iconKey:u},d.set(r,{...c,tabs:f}),{sessions:d}})},closeTab:(n,a)=>{const i=Es(n);t(r=>{const o=new Map(r.sessions),d=o.get(i);if(!d)return r;const c=Qs(d,a);if(c<0)return r;const p=d.tabs.filter(b=>b.id!==a),u=Object.fromEntries(Object.entries(r.projectActionRuns).filter(([,b])=>!(b.directory===i&&b.tabId===a))),f=Object.keys(u).length!==Object.keys(r.projectActionRuns).length;if(p.length===0){const b=Mi(),h=Xr(b,"Terminal");return o.set(i,Zr(h)),{sessions:o,nextTabId:r.nextTabId+1,...f?{projectActionRuns:u}:{}}}let m=d.activeTabId;return d.activeTabId===a&&(m=p[Math.min(c,p.length-1)]?.id??p[0]?.id??null),o.set(i,{...d,tabs:p,activeTabId:m}),{sessions:o,...f?{projectActionRuns:u}:{}}})},setTabSessionId:(n,a,i)=>{const r=Es(n);t(o=>{const d=new Map(o.sessions),c=d.get(r);if(!c)return o;const p=Qs(c,a);if(p<0)return o;const u=c.tabs[p],f=i!==null&&u.terminalSessionId!==i,m=i?"running":u.terminalSessionId?"exited":u.lifecycle,b={...u,terminalSessionId:i,lifecycle:m,isConnecting:!1,...f?{bufferChunks:[],bufferLength:0,lastSequence:-1}:{}},h=[...c.tabs];return h[p]=b,d.set(r,{...c,tabs:h}),{sessions:d}})},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=Qs(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=Qs(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)return d;const p=Qs(c,a);if(p<0||c.tabs[p].lastSequence>r)return d;const u=Qr(i),f=Jc(u),m=c.tabs[p];if(m.lastSequence===r&&m.bufferLength===f&&m.bufferChunks.map(v=>v.data).join("")===u)return d;const b=d.nextChunkId,h=u?[{id:b,data:u,byteLength:f}]:[],g=[...c.tabs];g[p]={...g[p],bufferChunks:h,bufferLength:f,lastSequence:r};const x=new Map(d.sessions);return x.set(o,{...c,tabs:g}),{sessions:x,nextChunkId:u?b+1:b}})},appendToBuffer:(n,a,i,r,o)=>{if(!i)return;const d=Es(n);t(c=>{const p=new Map(c.sessions),u=p.get(d);if(!u)return c;const f=Qs(u,a);if(f<0)return c;const m=u.tabs[f];if(r!==void 0&&r<=m.lastSequence)return c;const b=c.nextChunkId,h=Qr(i),g=o!==void 0&&o!==i?Qr(o):void 0,x={id:b,data:h,...g!==void 0?{replayData:g}:{},byteLength:Jc(h)},v=[...m.bufferChunks,x];let N=m.bufferLength+x.byteLength;for(;N>Eo&&v.length>1;){const F=v.shift();if(!F)break;N-=F.byteLength}const P=[...u.tabs];return P[f]={...m,bufferChunks:v,bufferLength:N,lastSequence:r??m.lastSequence},p.set(d,{...u,tabs:P}),{sessions:p,nextChunkId:b+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=Qs(p,a);if(u<0)return d;const f=p.tabs[u],m=r.autoOpened??f.previewAutoOpened,b=r.locked??f.previewUrlLocked;if(f.previewUrl===i&&f.previewAutoOpened===m&&f.previewUrlLocked===b)return d;const h=[...p.tabs];return h[u]={...f,previewUrl:i,previewAutoOpened:m,previewUrlLocked:b},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=Qs(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=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,d])=>d.directory!==a));return{sessions:r,projectActionRuns:o}})},clearAll:()=>{t({sessions:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:x1,storage:Im(()=>Gg()),partialize:t=>({sessions:Array.from(t.sessions.entries()).map(([e,n])=>[e,{activeTabId:n.activeTabId,tabs:n.tabs.map(a=>({id:a.id,label:a.label,iconKey:a.iconKey,createdAt:a.createdAt}))}]),nextTabId:t.nextTabId}),merge:(t,e)=>{if(!Yr(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"||!Yr(p))continue;const u=Array.isArray(p.tabs)?p.tabs:[],f=[],m=new Map;for(const x of u){if(!Yr(x))continue;const v=typeof x.id=="string"?x.id:null;if(!v)continue;const N=b1(v);N!==null&&(i=Math.max(i,N));const P=N===null?v:Mi();m.set(v,P),f.push({id:P,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(),bufferChunks:[],bufferLength:0,lastSequence:-1,isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(f.length===0)continue;const b=typeof p.activeTabId=="string"?p.activeTabId:null,h=b?m.get(b)??b:null,g=h?f.some(x=>x.id===h):!1;a.set(c,{tabs:f,activeTabId:g?h:f[0].id})}const r=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,o=Math.max(e.nextTabId,r,i+1);return{...e,sessions:a,nextChunkId:1,nextTabId:o,hasHydrated:!0}}})));if(typeof window<"u"&&!Qc){Qc=!0;const t=Xt.persist,e=()=>{Xt.getState().hasHydrated||Xt.setState({hasHydrated:!0})};t?.hasHydrated?.()?e():t?.onFinishHydration?t.onFinishHydration(e):e()}function y1(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 v1(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 eo=["\x1B[0m","\x1B[m"],w1=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},Xc=t=>{const e=w1(t);return e?`\x1B[0;48;2;${e[0]};${e[1]};${e[2]}m`:null},j1=(t,e,n)=>{const a=e+t;if(!n)return{data:a,carry:""};let i=0;const r=Math.max(...eo.map(c=>c.length))-1;for(let c=1;c<=Math.min(r,a.length);c+=1){const p=a.slice(-c);eo.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 eo)d=d.replaceAll(c,n);return{data:d,carry:o}},k1=(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))}},N1=(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 S1=null;const C1=()=>S1??=Em.load(),vu=l.forwardRef(({sessionKey:t,chunks:e,onInput:n,onResize:a,theme:i,fontFamily:r,fontSize:o,className:d,enableTouchScroll:c=!1,autoFocus:p=!0,isVisible:u=!0},f)=>{const m=l.useRef(null),b=l.useRef(null),h=l.useRef(null),g=l.useRef(n),x=l.useRef(a),v=l.useRef(null),N=l.useRef(null),P=l.useRef(""),F=l.useRef(""),w=l.useRef(Xc(i.background)),j=l.useRef(!1),y=l.useRef(u),R=l.useRef(!1),[_,B]=l.useState(0),[D,k]=l.useState(0);g.current=n,x.current=a,y.current=u,w.current=Xc(i.background);const T=l.useCallback(()=>{const V=m.current,U=b.current;if(!V||!U||!h.current||!y.current)return;const Y=V.getBoundingClientRect();if(!(Y.width<24||Y.height<24))try{h.current.fit();const X={cols:U.cols,rows:U.rows};(!v.current||v.current.cols!==X.cols||v.current.rows!==X.rows)&&(v.current=X,x.current(X.cols,X.rows)),R.current||(R.current=!0,B(S=>S+1))}catch{}},[]),M=l.useCallback(()=>{if(j.current||!P.current||!b.current)return;const V=b.current,U=P.current;P.current="";const Y=j1(U,F.current,w.current);if(F.current=Y.carry,!Y.data){P.current&&M();return}j.current=!0,V.write(Y.data,()=>{b.current===V&&(j.current=!1,P.current&&M())})},[]),O=l.useCallback(()=>{N.current=null,P.current="",F.current="",j.current=!1,k(V=>V+1)},[]);return l.useEffect(()=>{const V=m.current;if(!V)return;let U=!1,Y=null,X=null,S=null,W=null,Z=[];const A=()=>{Y&&y.current&&(Y.options.cursorBlink=!0)},C=H=>{H.relatedTarget instanceof Node&&V.contains(H.relatedTarget)||Y&&(Y.options.cursorBlink=!1)},z=()=>{Y&&y.current&&V.contains(document.activeElement)&&(Y.options.cursorBlink=!0)},$=()=>{Y&&(Y.options.cursorBlink=!1)};return V.addEventListener("focusin",A),V.addEventListener("focusout",C),window.addEventListener("focus",z),window.addEventListener("blur",$),C1().then(H=>{if(U)return;Y=new Pm(v1(r,o,i,H,!1));const J=new Am;Y.loadAddon(J),Y.open(V),b.current=Y,h.current=J,Z=[Y.onData(ue=>g.current(ue))],X=new ResizeObserver(()=>{S&&clearTimeout(S),S=setTimeout(T,80)}),X.observe(V),T();const ee=w.current;ee&&Y.write(`${ee}\x1B[2J\x1B[H`),W=requestAnimationFrame(T)}),()=>{U=!0;const H=document.activeElement;H instanceof HTMLElement&&V.contains(H)&&(H.blur(),window.Capacitor?.getPlatform?.()==="android"&&Qo(async()=>{const{Keyboard:ee}=await import("./vendor-.bun-BzW0Lgld.js").then(ue=>ue.cx);return{Keyboard:ee}},[]).then(({Keyboard:ee})=>ee.hide()).catch(()=>{})),X?.disconnect(),S&&clearTimeout(S),W!==null&&cancelAnimationFrame(W),V.removeEventListener("focusin",A),V.removeEventListener("focusout",C),window.removeEventListener("focus",z),window.removeEventListener("blur",$),Z.forEach(J=>J.dispose()),Y?.dispose(),b.current=null,h.current=null,v.current=null,N.current=null,P.current="",F.current="",j.current=!1,R.current=!1}},[T,r,o,D,i]),l.useEffect(()=>{const V=b.current,U=m.current;!V||!U||(V.options.cursorBlink=u&&document.hasFocus()&&U.contains(document.activeElement))},[u,_]),l.useEffect(()=>{if(!b.current)return;if(e.length===0){N.current!==null&&O();return}const U=N.current,Y=U===null?-1:e.findIndex(W=>W.id===U);if(U!==null&&Y<0){O();return}const X=Y<0,S=Y>=0?e.slice(Y+1):e;P.current+=S.map(W=>X?W.replayData??W.data:W.data).join(""),N.current=e.at(-1)?.id??null,M()},[e,M,_,O]),l.useEffect(()=>{if(!p||!u)return;const V=requestAnimationFrame(()=>b.current?.focus());return()=>cancelAnimationFrame(V)},[p,u,_,t]),l.useEffect(()=>{const V=m.current;if(!c||!V)return;const U=Y=>{const X=Y;if(!X.isComposing)switch(X.inputType){case"insertText":X.data&&g.current(X.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return V.addEventListener("beforeinput",U),()=>V.removeEventListener("beforeinput",U)},[c,_]),l.useEffect(()=>{const V=m.current,U=b.current;if(!c||!V||!U)return;let Y=null,X=null,S="idle",W=0,Z=0,A=0,C=0,z=null;const $=Math.max(12,o+2),H=()=>{window.Capacitor?.getPlatform?.()==="android"&&Qo(async()=>{const{Keyboard:ae}=await import("./vendor-.bun-BzW0Lgld.js").then(ce=>ce.cx);return{Keyboard:ae}},[]).then(({Keyboard:ae})=>ae.show()).catch(()=>{})},J=()=>{X&&(clearTimeout(X),X=null)},ee=(fe,ae)=>{const ce=V.querySelector("canvas");return ce?k1(fe,ae,ce.getBoundingClientRect(),U.cols,U.rows):null},ue=(fe,ae)=>{const ce=V.querySelector("canvas");if(!ce)return;const pe=ce.getBoundingClientRect(),q=pe.left+(ae.column+.5)/U.cols*pe.width,te=pe.top+(ae.row+.5)/U.rows*pe.height;ce.dispatchEvent(new MouseEvent(fe,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:q,clientY:te}))},re=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},xe=fe=>{fe.pointerType!=="touch"||Y!==null||(Y=fe.pointerId,S="pending",W=fe.clientX,Z=fe.clientY,A=fe.clientY,C=0,z=null,V.setPointerCapture(fe.pointerId),X=setTimeout(()=>{if(X=null,Y!==fe.pointerId||S!=="pending")return;const ae=ee(W,Z);if(!ae)return;const ce=U.buffer.active,pe=Math.max(0,ce.length-U.rows-ce.viewportY+ae.row),q=ce.getLine(pe),te=Array.from({length:U.cols},(Ae,je)=>q?.getCell(je)?.getChars()??""),ne=N1(te,ae.column),oe={column:ne.startColumn,row:ae.row};z={column:ne.endColumn,row:ae.row},S="selecting",ue("mousedown",oe),ue("mousemove",z)},350))},be=fe=>{if(Y!==fe.pointerId)return;if(S==="selecting"){const pe=ee(fe.clientX,fe.clientY);pe&&(!z||pe.column!==z.column||pe.row!==z.row)&&(z=pe,ue("mousemove",pe)),fe.cancelable&&fe.preventDefault();return}if(S==="pending"){if(Math.hypot(fe.clientX-W,fe.clientY-Z)<8)return;J(),S="scrolling"}if(S!=="scrolling")return;const ae=A-fe.clientY;A=fe.clientY,C+=ae;const ce=Math.trunc(C/$);ce&&(U.scrollLines(ce),C-=ce*$),fe.cancelable&&fe.preventDefault()},he=fe=>{if(Y!==fe.pointerId)return;const ae=S==="pending",ce=S==="selecting";J(),V.hasPointerCapture(fe.pointerId)&&V.releasePointerCapture(fe.pointerId),Y=null,S="idle",ce&&re(),ae&&(U.focus(),H())},ye=fe=>{if(Y!==fe.pointerId)return;const ae=S==="selecting";J(),V.hasPointerCapture(fe.pointerId)&&V.releasePointerCapture(fe.pointerId),Y=null,S="idle",ae&&re()};return V.addEventListener("pointerdown",xe),V.addEventListener("pointermove",be,{passive:!1}),V.addEventListener("pointerup",he),V.addEventListener("pointercancel",ye),()=>{J(),V.removeEventListener("pointerdown",xe),V.removeEventListener("pointermove",be),V.removeEventListener("pointerup",he),V.removeEventListener("pointercancel",ye)}},[c,o,_]),l.useImperativeHandle(f,()=>({focus:()=>b.current?.focus(),fit:T,getSelection:()=>{const V=b.current,U=V?.getSelectionPosition(),Y=V?.getSelection()??"";return!U||!Y.trim()?null:{text:Y,startLine:U.start.y+1,endLine:U.end.y+1}}}),[T]),s.jsx("div",{ref:m,"data-terminal-owner":"main",className:le("terminal-viewport-container h-full w-full overflow-hidden touch-none",d)})});vu.displayName="TerminalViewport";const I1="\x1B",P1=new RegExp(`${I1}\\[[0-9;?]*[ -/]*[@-~]`,"g"),A1=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,E1=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,T1=/Serving HTTP on .*? port (\d{2,5})/i,R1=new Set([".",",",";",":","!","?"]),D1=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(R1.has(n)){e=e.slice(0,-1);continue}break}return e},Zc=t=>{let e=D1(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},M1=t=>{if(!t)return null;const e=t.replace(P1,""),n=e.match(T1);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(`
|
|
30
|
+
`);for(const i of a){if(!E1.test(i))continue;const r=Array.from(i.matchAll(A1));if(r.length===0)continue;const o=r.find(d=>{try{return!!new URL(Zc(d[1])).port}catch{return!1}});return Zc((o??r[0])[1])}return null},L1=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 gt("/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)}},F1={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},O1=(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 F1[t]},wu=t=>{const e=t[0]?.toUpperCase();return!e||e<"A"||e>"Z"?null:String.fromCharCode(e.charCodeAt(0)&31)},z1=(t,e)=>t&&(e==="ctrl"?wu(t)??t:t.length===1&&t!=="\x1B"?`\x1B${t}`:t),Qk=({visible:t})=>{const{t:e}=it(),{terminal:n,runtime:a}=li(),{currentTheme:i}=oi(),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}=Yp(),d=Ne(ie=>ie.terminalFontSize),c=Ne(ie=>ie.terminalShell),p=Ne(ie=>ie.terminalLoginShells.includes(ie.terminalShell)),{isMobile:u,isTablet:f,hasTouchOnlyPointer:m}=_s(),b=u||f,h=(b||m)&&a.platform==="web",g=a.platform!=="vscode",x=Ne(ie=>ie.showTerminalQuickKeysOnDesktop),v=b||x,N=ds(ie=>ie.currentSessionId),P=ds(ie=>ie.newSessionDraft),F=N!==null||P?.open===!0,w=Ed()??null,j=Xt(ie=>w?ie.sessions.get(w):void 0),y=Xt(ie=>ie.hasHydrated),R=Xt(ie=>ie.ensureDirectory),_=Xt(ie=>ie.createTab),B=Xt(ie=>ie.setActiveTab),D=Xt(ie=>ie.closeTab),k=Xt(ie=>ie.setTabSessionId),T=Xt(ie=>ie.setTabLifecycle),M=Xt(ie=>ie.setConnecting),O=Xt(ie=>ie.appendToBuffer),V=Xt(ie=>ie.replaceBuffer),U=Xt(ie=>ie.setTabPreviewUrl),Y=Qa(ie=>ie.addDraft),X=Ne(ie=>ie.openContextPreview),S=l.useMemo(()=>j?g?j.activeTabId??j.tabs[0]?.id??null:j.tabs[0]?.id??null:null,[j,g]),W=l.useMemo(()=>{if(j)return S?j.tabs.find(ie=>ie.id===S)??j.tabs[0]:j.tabs[0]},[j,S]),Z=l.useMemo(()=>(j?.tabs??[]).map(ie=>({icon:(()=>{const we=ie.iconKey?Zd[ie.iconKey]??"terminal":"terminal";return s.jsx(L,{name:we,className:"h-4 w-4"})})(),id:ie.id,label:ie.label,title:ie.label,closeLabel:e("terminalView.tabs.closeTabTitle")})),[j?.tabs,e]),A=W?.terminalSessionId??null,C=W?.lifecycle??"idle",z=W?.bufferChunks??[],$=W?.isConnecting??!1,H=W?.previewUrl??null,[J,ee]=l.useState(null),[ue,re]=l.useState(!1),[xe,be]=l.useState(!1),[he,ye]=l.useState(null),[fe,ae]=l.useState(!1),[ce,pe]=l.useState(!1),q=l.useRef(null),te=l.useRef(null),ne=l.useRef(S),oe=l.useRef(A),Ae=l.useRef(w),je=l.useRef(null),Ie=l.useRef(null),Te=l.useRef(!1),Me=l.useRef(""),He=l.useRef(new Set),Ve=l.useRef(0),Ue=l.useCallback(()=>{Me.current="",He.current.clear(),Ve.current+=1},[]),ze=l.useCallback(()=>{h||typeof document<"u"&&!document.hasFocus()||je.current?.focus()},[h]),Be=l.useCallback(()=>{h||je.current?.focus()},[h]),Fe=Ne(ie=>ie.activeMainTab)==="terminal",ve=t??Fe,[De,Ke]=l.useState(ve);l.useEffect(()=>{ve&&Ke(!0)},[ve]),l.useEffect(()=>{Te.current=ve},[ve]),l.useEffect(()=>{oe.current=A},[A]),l.useEffect(()=>{!A||!n.updateAppearance||n.updateAppearance(A,r.current).catch(()=>{})},[i.colors.surface.background,i.colors.syntax.base.foreground,i.metadata.variant,n,A]),l.useEffect(()=>{ne.current=S,Ue()},[S,Ue]),l.useEffect(()=>{Ae.current=w},[w]),l.useEffect(()=>{!v&&he!==null&&ye(null)},[v,he,ye]),l.useEffect(()=>{!A&&he!==null&&ye(null)},[A,he,ye]);const We=l.useCallback(()=>{q.current?.(),q.current=null,te.current=null,be(!1)},[]);l.useEffect(()=>()=>{We(),oe.current=null},[We]);const Pe=l.useCallback((ie,we,me)=>{if(!me)return;const Je=`${Me.current}${me}`.replace(/\r\n|\r/g,`
|
|
31
|
+
`),$e=Je.split(`
|
|
32
|
+
`),et=Je.endsWith(`
|
|
33
|
+
`)?$e.join(`
|
|
34
|
+
`):$e.slice(0,-1).join(`
|
|
35
|
+
`);if(Me.current=Je.endsWith(`
|
|
36
|
+
`)?"":($e[$e.length-1]??"").slice(-1024),!et)return;const bt=M1(et);if(!bt||He.current.has(bt))return;const Dt=Ve.current;He.current.add(bt),L1(bt).then(Qt=>{if(He.current.delete(bt),!Qt||Ve.current!==Dt)return;const _t=Xt.getState().getDirectoryState(ie)?.tabs.find(as=>as.id===we);!_t||_t.previewUrlLocked||_t.previewUrl===bt||U(ie,we,bt,{locked:!1,autoOpened:!1})})},[U]),at=l.useCallback((ie,we,me)=>{if(te.current===me)return;We(),te.current=me;const Je=n.connect(me,{onEvent:$e=>{if(te.current===me)switch($e.type){case"snapshot":{M(ie,we,!1),ee(null),re(!1),be(!1),ze(),V(ie,we,$e.data??"",$e.sequence??0),Pe(ie,we,$e.data??""),$e.status==="exited"&&T(ie,we,"exited");break}case"reconnecting":{ee(null),re(!1),be(!0);break}case"data":{$e.data&&(O(ie,we,$e.data,$e.sequence,$e.replayData),Pe(ie,we,$e.data));break}case"exit":{const et=typeof $e.exitCode=="number"?$e.exitCode:null,bt=typeof $e.signal=="number"?$e.signal:null,Qt=!!Xt.getState().getDirectoryState(ie)?.tabs.find(_t=>_t.id===we)?.label?.startsWith("Action:");O(ie,we,e("terminalView.stream.processExitedMessage",{exitCodeSegment:et!==null?e("terminalView.stream.processExitedWithCode",{exitCode:et}):"",signalSegment:bt!==null?e("terminalView.stream.processExitedWithSignal",{signal:bt}):""})),T(ie,we,"exited"),M(ie,we,!1),ee(Qt?null:e("terminalView.error.sessionEnded")),re(!1),be(!1),We();break}}},onError:($e,et)=>{if(te.current===me){if(!et){ee(null),re(!1);return}if(be(!1),$e.code==="SESSION_NOT_FOUND"&&!Xt.getState().getDirectoryState(ie)?.tabs.find(Dt=>Dt.id===we)?.label?.startsWith("Action:")){ee(null),re(!1),M(ie,we,!1),k(ie,we,null),T(ie,we,"idle"),We();return}ee(e("terminalView.error.connectionFailed",{message:$e.message})),re(!0),M(ie,we,!1),T(ie,we,"exited"),k(ie,we,null),We()}}});q.current=()=>{Je.close(),te.current=null}},[O,V,We,ze,Pe,M,T,k,e,n]);l.useEffect(()=>{let ie=!1;if(!y||!De)return;if(!w){ee(e(F?"terminalView.empty.noWorkingDirectory":"terminalView.empty.selectSession")),We();return}return(async()=>{const me=w;if(!Ae.current||Ae.current!==me)return;if(!Xt.getState().getDirectoryState(me)){R(me);return}const $e=Xt.getState().getDirectoryState(me);if(!$e||$e.tabs.length===0)return;const et=g?$e.activeTabId??$e.tabs[0]?.id??null:$e.tabs[0]?.id??null;if(!et)return;const bt=$e.tabs.find(is=>is.id===et)??$e.tabs[0];let Dt=bt?.terminalSessionId??null;const Qt=bt?.lifecycle??"idle",_t=!!bt?.label?.startsWith("Action:"),as=(bt?.bufferLength??0)>0||(bt?.bufferChunks?.length??0)>0;if(!Dt){if(Qt==="exited"){M(me,et,!1);return}if(_t&&as){M(me,et,!1);return}const is=Ie.current;if(!is&&Te.current)return;ee(null),re(!1),be(!1),M(me,et,!0);try{const $t=await n.createSession({cwd:me,sessionId:et,cols:is?.cols,rows:is?.rows,shell:c,loginShell:p,...r.current}),Ce=!ie&&Ae.current===me&&ne.current===et;if(!Xt.getState().getDirectoryState(me)?.tabs.find(Qe=>Qe.id===et)){try{await n.close($t.sessionId)}catch{}return}if(k(me,et,$t.sessionId),!Ce)return;Dt=$t.sessionId}catch($t){ie||(ee($t instanceof Error?$t.message:e("terminalView.error.startSessionFailed")),re(!0),be(!1),M(me,et,!1));return}}!Dt||ie||(oe.current=Dt,at(me,et,Dt))})(),()=>{ie=!0,oe.current=null,We()}},[F,w,A,C,S,De,ce,g,y,R,M,T,k,at,We,e,n,p,c]),l.useEffect(()=>{if(!ve||h)return;if(typeof window>"u"){ze();return}const ie=window.requestAnimationFrame(()=>{ze()});return()=>{window.cancelAnimationFrame(ie)}},[S,ze,ve,h]);const se=l.useCallback(async()=>{if(!w||fe)return;const ie=Xt.getState().getDirectoryState(w),we=g?S??ie?.activeTabId??ie?.tabs[0]?.id??null:ie?.tabs[0]?.id??null;if(!we)return;const me=ie?.tabs.find(Je=>Je.id===we)?.terminalSessionId??null;if(!(!me||!n.restartSession)){ae(!0),ee(null),re(!1),be(!1),We(),Ue();try{const Je=Ie.current??{cols:80,rows:24},$e=await n.restartSession(me,{cwd:w,shell:c,loginShell:p,...Je,...r.current});if(Xt.getState().getDirectoryState(w)?.tabs.find(bt=>bt.id===we)?.terminalSessionId!==me||(k(w,we,$e.sessionId),T(w,we,"running"),Ae.current!==w||ne.current!==we))return;oe.current=$e.sessionId,at(w,we,$e.sessionId)}catch(Je){if(Xt.getState().getDirectoryState(w)?.tabs.find(et=>et.id===we)?.terminalSessionId!==me||Ae.current!==w||ne.current!==we)return;ee(Je instanceof Error?Je.message:e("terminalView.error.restartFailed")),re(!1),be(!1),oe.current=me,at(w,we,me)}finally{ae(!1)}}},[S,We,w,g,fe,Ue,T,k,at,e,n,p,c]),I=l.useCallback(async()=>{await se()},[se]),Ee=l.useCallback(()=>{if(!w)return;const ie=_(w);B(w,ie),ee(null),re(!1),be(!1),We()},[_,We,w,B]),Le=l.useCallback(()=>{const ie=je.current?.getSelection(),we=N??(P?.open?"draft":null);!ie||!we||!W||!w||Y({directory:w,sessionKey:we},{source:"terminal",fileLabel:W.label,startLine:ie.startLine,endLine:ie.endLine,code:ie.text,language:W.terminalSessionId??W.id,text:""})},[W,Y,N,w,P?.open]),_e=l.useCallback(ie=>{w&&(B(w,ie),ee(null),re(!1),be(!1),We())},[We,w,B]),Xe=l.useCallback(ie=>{if(!w)return;ie===S&&We(),ee(null),re(!1),be(!1);const we=Xt.getState().getDirectoryState(w)?.tabs.find(me=>me.id===ie)?.terminalSessionId;(async()=>{we&&await n.close(we),D(w,ie)})().catch(me=>ee(me instanceof Error?me.message:e("terminalView.error.sessionEnded")))},[S,D,We,w,e,n]),ct=l.useCallback(ie=>{if(!ie||xe)return;let we=ie,me=!1;he&&ie.length>0&&(we=z1(ie,he),me=!0);const Je=oe.current;Je&&(n.sendInput(Je,we).catch($e=>{xe||ee($e instanceof Error?$e.message:e("terminalView.error.sendInputFailed"))}),me&&(ye(null),Be()))},[he,Be,xe,ye,e,n]),ut=l.useCallback((ie,we)=>{const me=Ie.current;if(me?(me.cols!==ie||me.rows!==we)&&(Ie.current={cols:ie,rows:we}):(Ie.current={cols:ie,rows:we},oe.current||pe(!0)),!Te.current)return;const Je=oe.current;Je&&n.resize({sessionId:Je,cols:ie,rows:we}).catch(()=>{})},[n]),lt=l.useCallback(ie=>{ye(we=>we===ie?null:ie),Be()},[Be,ye]),rt=l.useCallback(ie=>{const we=O1(ie,he);we&&(ct(we),ye(null),Be())},[he,Be,ct,ye]),mt=l.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),xt=l.useCallback(ie=>{if(ie.repeat)return;const we=ie.key;if(!we||we==="Control"||we==="Meta"||we==="Alt"||we==="Shift")return;const me=we.length===1?we.toLowerCase():we;if(me in mt){ie.preventDefault(),ie.stopPropagation(),rt(mt[me]);return}if(he!=="ctrl")return;const Je=ie.code??"",$e=we.length===1&&/[a-zA-Z]/.test(we)?we.toUpperCase():Je.startsWith("Key")&&Je.length===4?Je.slice(3).toUpperCase():null;if($e&&$e.length===1&&$e>="A"&&$e<="Z"){const et=wu($e);if(!et)return;ie.preventDefault(),ie.stopPropagation(),ct(et),ye(null),Be()}},[he,Be,rt,ct,mt,ye]);l.useEffect(()=>{if(!(!v||!he||!A))return window.addEventListener("keydown",xt),()=>window.removeEventListener("keydown",xt)},[he,xt,v,A]);const It=l.useMemo(()=>{const ie=Ka[ei].stack;if(typeof window>"u")return(Ka[o]??Ka[ei]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(Ka[o]??Ka[ei]).stack??ie},[o]),Se=l.useMemo(()=>y1(i),[i]),qe=l.useMemo(()=>`${w??"no-dir"}::${S??"no-tab"}::${A??"no-terminal"}`,[w,S,A]);if(l.useEffect(()=>{if(!ve||h)return;const ie=je.current;if(!ie)return;const we=()=>{ie.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{we(),ze()}),Je=[220,400].map($e=>window.setTimeout(we,$e));return()=>{window.cancelAnimationFrame(me),Je.forEach($e=>window.clearTimeout($e))}}we()},[ze,ve,h,qe,A]),l.useEffect(()=>{if(!ve||!h)return;let ie=null;const we=()=>{ie!==null&&window.cancelAnimationFrame(ie),ie=window.requestAnimationFrame(()=>{ie=null,je.current?.fit()})};return window.addEventListener("oc:keyboard-settled",we),()=>{window.removeEventListener("oc:keyboard-settled",we),ie!==null&&window.cancelAnimationFrame(ie)}},[ve,qe,h]),!F)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(!w)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:se,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 Ze=!A||$||fe||xe,nt=De,ft=b?"lg":"xs",vt=b?"w-10 p-0":"w-9 p-0",St=ie=>{b&&ie.preventDefault()},de=s.jsxs(s.Fragment,{children:[s.jsx(Q,{type:"button",size:ft,variant:"outline",onPointerDown:St,onClick:()=>rt("esc"),disabled:Ze,children:e("terminalView.quickKeys.escape")}),s.jsxs(Q,{type:"button",size:ft,variant:"outline",className:vt,onPointerDown:St,onClick:()=>rt("tab"),disabled:Ze,children:[s.jsx(L,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.tabAria")})]}),s.jsxs(Q,{type:"button",size:ft,variant:"chip","aria-pressed":he==="ctrl",className:b?"px-3":"px-2",onPointerDown:St,onClick:()=>lt("ctrl"),disabled:Ze,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(Q,{type:"button",size:ft,variant:"chip","aria-pressed":he==="alt",className:b?"px-3":"px-2",onPointerDown:St,onClick:()=>lt("alt"),disabled:Ze,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(Q,{type:"button",size:ft,variant:"outline",className:vt,onPointerDown:St,onClick:()=>rt("arrow-up"),disabled:Ze,children:[s.jsx(L,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowUpAria")})]}),s.jsxs(Q,{type:"button",size:ft,variant:"outline",className:vt,onPointerDown:St,onClick:()=>rt("arrow-left"),disabled:Ze,children:[s.jsx(L,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowLeftAria")})]}),s.jsxs(Q,{type:"button",size:ft,variant:"outline",className:vt,onPointerDown:St,onClick:()=>rt("arrow-down"),disabled:Ze,children:[s.jsx(L,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowDownAria")})]}),s.jsxs(Q,{type:"button",size:ft,variant:"outline",className:vt,onPointerDown:St,onClick:()=>rt("arrow-right"),disabled:Ze,children:[s.jsx(L,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:e("terminalView.quickKeys.arrowRightAria")})]}),s.jsxs(Q,{type:"button",size:ft,variant:"outline",className:vt,onPointerDown:St,onClick:()=>rt("enter"),disabled:Ze,children:[s.jsx(L,{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:le("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",b?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[g&&j?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[s.jsx("div",{className:le("min-w-0 flex-1",b?"h-8":"h-7"),children:s.jsx(ia,{items:Z,activeId:S,onSelect:_e,onClose:Xe,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),s.jsx(Q,{type:"button",size:"xs",variant:"ghost",className:le("shrink-0",b?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ee,title:e("terminalView.tabs.newTabTitle"),children:s.jsx(L,{name:"add",className:`${b?"h-[18px] w-[18px]":"h-4 w-4"}`})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Q,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{se()},disabled:fe,title:e("terminalView.actions.restart"),"aria-label":e("terminalView.actions.restart"),children:s.jsx(L,{name:"restart",className:"h-4 w-4"})}),s.jsx(Q,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:Le,title:e("terminalView.actions.attachSelection"),"aria-label":e("terminalView.actions.attachSelection"),children:s.jsx(L,{name:"attachment-2",className:"h-4 w-4"})}),H?s.jsxs(Q,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{w&&X(w,H)},title:e("terminalView.preview.openTitle"),children:[s.jsx(L,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:e("terminalView.preview.open")})]}):null]})]}):null,!b&&v&&g&&j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:de}):null,!b&&v&&(!g||!j)?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:de}):null]}),s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Se.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:nt?s.jsx(vu,{ref:ie=>{je.current=ie},sessionKey:qe,chunks:z,onInput:ct,onResize:ut,theme:Se,fontFamily:It,fontSize:d,enableTouchScroll:h,autoFocus:ve,isVisible:ve},qe):null}),!xe&&J&&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:J}),ue&&b&&s.jsx(Q,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:I,disabled:fe,title:e("terminalView.actions.hardRestartTitle"),type:"button",children:e("terminalView.actions.hardRestart")})]})]}),b&&v?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:de})}):null]})},B1=["chat","git","diff","terminal","files","diagram"],K1=["settings","agents","commands","skills","providers","usage","git-identities"],Gs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function ed(t){const e=U1();return{sessionId:_1(e),tab:$1(e),settingsPath:V1(e),diffFile:H1(e)}}function U1(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function _1(t){const e=t.get(Gs.SESSION);return!e||e.trim().length===0?null:e.trim()}function $1(t){const e=t.get(Gs.TAB);if(!e)return null;const n=e.toLowerCase().trim();return B1.includes(n)?n:null}function V1(t){const e=t.get(Gs.SETTINGS);if(!e)return null;const n=e.toLowerCase().trim();return n.length===0?null:n==="openchamber"||n==="general"||n==="preferences"?"home":(K1.includes(n),n)}function H1(t){const e=t.get(Gs.FILE);if(!e||e.trim().length===0)return null;try{return decodeURIComponent(e.trim())}catch{return e.trim()}}function td(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Gs.SESSION)||t.has(Gs.TAB)||t.has(Gs.SETTINGS)||t.has(Gs.FILE)}catch{return!1}}const W1="chat";function ju(t){const e=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&e.set(Gs.SESSION,t.sessionId),t.isSettingsOpen){const n=t.settingsPath.trim().length>0?t.settingsPath:"home";return e.set(Gs.SETTINGS,n),e}return t.tab!==W1&&e.set(Gs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&e.set(Gs.FILE,t.diffFile),e}function G1(t,e){const n=typeof window<"u"?window.location.pathname:"/",a=t.toString();return a?`${n}?${a}`:n}function q1(t){if(typeof window>"u")return!0;try{const e=new URLSearchParams(window.location.search),n=ju(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 sd(t,e={}){if(!(typeof window>"u")&&!(J1()||Td())&&!(!e.force&&q1(t)))try{const n=ju(t),a=G1(n);e.replace?window.history.replaceState({...window.history.state,route:t},"",a):window.history.pushState({route:t},"",a)}catch{}}function J1(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function Q1(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function Yk(){const t=l.useMemo(()=>Q1(),[]),e=l.useMemo(()=>Td(),[]),n=l.useRef(!1),a=l.useRef(!1),i=ds(m=>m.setCurrentSession),r=Ne(m=>m.setActiveMainTab),o=Ne(m=>m.setSettingsDialogOpen),d=Ne(m=>m.setSettingsPage),c=Ne(m=>m.navigateToDiff),p=l.useCallback(async m=>{if(!a.current){a.current=!0;try{if(m.sessionId){const b=ds.getState().currentSessionId;if(m.sessionId!==b){const h=ds.getState().getDirectoryForSession(m.sessionId);i(m.sessionId,h)}}if(m.settingsPath){d(Bo(m.settingsPath)),o(!0);return}Ne.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=ds.getState(),b=Ne.getState();return{sessionId:m.currentSessionId,tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),f=l.useCallback((m={})=>{if(t||e||a.current)return;const b=u();sd(b,m)},[t,e,u]);l.useEffect(()=>{if(n.current||(n.current=!0,!td()))return;const m=ed();(async()=>(await p(m),!t&&!e&&sd({...u(),sessionId:m.sessionId??ds.getState().currentSessionId,tab:m.tab??Ne.getState().activeMainTab,settingsPath:m.settingsPath??Ne.getState().settingsPage,diffFile:m.diffFile??Ne.getState().pendingDiffFile},{replace:!0,force:!0})))()},[p,u,t,e]),l.useEffect(()=>{if(t||e)return;let m=ds.getState().currentSessionId;return ds.subscribe(h=>{const g=h.currentSessionId;g===m||a.current||(m=g,f())})},[t,e,f]),l.useEffect(()=>{if(t||e)return;let m=Ne.getState().activeMainTab,b=Ne.getState().isSettingsDialogOpen,h=Ne.getState().settingsPage,g=Ne.getState().pendingDiffFile;return Ne.subscribe(v=>{if(a.current)return;const N=v.activeMainTab!==m,P=v.isSettingsDialogOpen!==b,F=v.settingsPage!==h,w=v.pendingDiffFile!==g&&v.activeMainTab==="diff";m=v.activeMainTab,b=v.isSettingsDialogOpen,h=v.settingsPage,g=v.pendingDiffFile,(N||P||F||w)&&f()})},[t,e,f]),l.useEffect(()=>{if(typeof window>"u"||t||e)return;const m=()=>{const b=ed();if(td())p(b);else{const h=Ne.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 Xk(){const t=Ye.c(5),e=Bd(X1),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=Y1,u=f=>{d||(c=window.setTimeout(async()=>{const m=await n.current(),b=typeof m=="number"&&Number.isFinite(m)?p(m):36e5;u(b)},f))};return u(3e3),()=>{d=!0,c!==null&&window.clearTimeout(c)}},o=[],t[3]=r,t[4]=o):(r=t[3],o=t[4]),l.useEffect(r,o)}function Y1(t){const e=Math.round(t*1e3);return Math.max(3e5,Math.min(864e5,e))}function X1(t){return t.checkForUpdates}const ku={"?":{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"}},Z1=ku.M;function ej(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 tj(t){const e=ej(t);return ku[e]??Z1}const sj=l.memo(function(e){const n=Ye.c(58),{file:a,actionLabel:i,actionSymbol:r,onAction:o,onViewDiff:d,onRevert:c,isReverting:p,stats:u,rowPaddingClassName:f,indentPx:m,actionAtStart:b,showRevert:h}=e,g=m===void 0?0:m,x=b===void 0?!1:b,v=h===void 0?!0:h;let N;n[0]!==a?(N=tj(a),n[0]=a,n[1]=N):N=n[1];const P=N,{t:F}=it(),w=P.description,j=u?.insertions??0,y=u?.deletions??0;let R;n[2]!==o||n[3]!==d?(R=xe=>{xe.key===" "?(xe.preventDefault(),o()):xe.key==="Enter"&&(xe.preventDefault(),d())},n[2]=o,n[3]=d,n[4]=R):R=n[4];const _=R;let B;n[5]!==o?(B=xe=>{xe.preventDefault(),xe.stopPropagation(),o()},n[5]=o,n[6]=B):B=n[6];const D=B;let k;n[7]!==c?(k=xe=>{xe.preventDefault(),xe.stopPropagation(),c()},n[7]=c,n[8]=k):k=n[8];const T=k;let M;n[9]!==i||n[10]!==r||n[11]!==D?(M=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]=M):M=n[12];const O=M,V=`group flex items-center gap-2 py-1.5 cursor-pointer ${f??"px-3"}`;let U;n[13]!==g?(U=g>0?{paddingLeft:`${g}px`}:void 0,n[13]=g,n[14]=U):U=n[14];const Y=x?O:null;let X;n[15]!==P.color?(X={color:P.color},n[15]=P.color,n[16]=X):X=n[16];let S;n[17]!==P.code||n[18]!==w||n[19]!==X?(S=s.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:X,title:w,"aria-label":w,children:P.code}),n[17]=P.code,n[18]=w,n[19]=X,n[20]=S):S=n[20];let W;n[21]!==a.path?(W=s.jsx(Xp,{filePath:a.path,className:"h-3.5 w-3.5 shrink-0"}),n[21]=a.path,n[22]=W):W=n[22];let Z;if(n[23]!==a.path){e:{const xe=a.path.lastIndexOf("/");if(xe===-1){let pe;n[25]===Symbol.for("react.memo_cache_sentinel")?(pe={direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},n[25]=pe):pe=n[25],Z=s.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:pe,title:a.path,children:a.path});break e}const be=a.path.slice(0,xe),he=a.path.slice(xe);let ye;n[26]===Symbol.for("react.memo_cache_sentinel")?(ye={direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},n[26]=ye):ye=n[26];let fe;n[27]===Symbol.for("react.memo_cache_sentinel")?(fe=s.jsx("span",{className:"text-muted-foreground",children:"/"}),n[27]=fe):fe=n[27];const ae=s.jsx("span",{className:"text-foreground",children:he.slice(1)});let ce;n[28]!==ae?(ce=s.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[fe,ae]}),n[28]=ae,n[29]=ce):ce=n[29],Z=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:ye,children:be}),ce]})}n[23]=a.path,n[24]=Z}else Z=n[24];let A;n[30]===Symbol.for("react.memo_cache_sentinel")?(A={color:"var(--status-success)"},n[30]=A):A=n[30];let C;n[31]!==j?(C=s.jsxs("span",{style:A,children:["+",j]}),n[31]=j,n[32]=C):C=n[32];let z,$;n[33]===Symbol.for("react.memo_cache_sentinel")?(z=s.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),$={color:"var(--status-error)"},n[33]=z,n[34]=$):(z=n[33],$=n[34]);let H;n[35]!==y?(H=s.jsxs("span",{style:$,children:["-",y]}),n[35]=y,n[36]=H):H=n[36];let J;n[37]!==C||n[38]!==H?(J=s.jsxs("span",{className:"shrink-0 typography-micro",children:[C,z,H]}),n[37]=C,n[38]=H,n[39]=J):J=n[39];let ee;n[40]!==a.path||n[41]!==T||n[42]!==p||n[43]!==v||n[44]!==F?(ee=v?s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx("button",{type:"button",onClick:T,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":F("gitView.changes.revertFileAria",{path:a.path}),children:p?s.jsx(L,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(L,{name:"arrow-go-back",className:"size-3.5"})})}),s.jsx(Ds,{sideOffset:8,children:F("gitView.changes.revertFileTooltip")})]}):null,n[40]=a.path,n[41]=T,n[42]=p,n[43]=v,n[44]=F,n[45]=ee):ee=n[45];const ue=x?null:O;let re;return n[46]!==_||n[47]!==d||n[48]!==U||n[49]!==Y||n[50]!==S||n[51]!==W||n[52]!==Z||n[53]!==J||n[54]!==ee||n[55]!==ue||n[56]!==V?(re=s.jsxs("div",{className:V,role:"button",tabIndex:0,onClick:d,onKeyDown:_,style:U,children:[Y,S,W,Z,J,ee,ue]}),n[46]=_,n[47]=d,n[48]=U,n[49]=Y,n[50]=S,n[51]=W,n[52]=Z,n[53]=J,n[54]=ee,n[55]=ue,n[56]=V,n[57]=re):re=n[57],re}),nd=14,Nu=t=>t.replace(/\\/g,"/").replace(/^\/+/,"").trim(),ad=(t,e)=>({id:`dir:${t}`,path:t,name:e,children:new Map,directFiles:[],files:[]}),nj=t=>{const e=ad("","");for(const n of t){const a=Nu(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=ad(d,c);u.files.push(n),o.children.set(c,u),o=u}}o.directFiles.push(n)}return e},aj=(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:${Nu(c.path)}`,kind:"file",depth:r,file:c})};return a(t,0),n},ij=1e3,id=34,to=30,Li="pl-0 pr-2",so=(t,e)=>`${t} ${e}`,Zk=({groups:t,diffStats:e,revertingPaths:n,isRevertingAll:a=!1,headerBackgroundClassName:i="bg-sidebar",onVisiblePathsChange:r,onRevertAll:o,onRevertDirectory:d})=>{const{t:c}=it(),p=l.useRef(null),f=Ne(C=>C.gitChangesViewMode)==="tree",m=l.useMemo(()=>t.filter(C=>C.entries.length>0),[t]),[b,h]=l.useState(new Set),[g,x]=l.useState(new Set),[v,N]=l.useState(!1),[P,F]=l.useState(null),w=l.useMemo(()=>m.map(C=>nj(C.entries)),[m]),j=l.useMemo(()=>{const C=[];return m.forEach((z,$)=>{Array.from(w[$]?.children.values()??[]).forEach(H=>{C.push(so(z.id,H.path))})}),C},[w,m]);l.useEffect(()=>{f&&x(C=>{const z=new Set,$=new Set(j);return C.forEach(H=>{(H.slice(H.indexOf(" ")+1).includes("/")||$.has(H))&&z.add(H)}),j.forEach(H=>z.add(H)),z})},[f,j]);const y=l.useMemo(()=>{const C=[];return m.forEach((z,$)=>{if(C.push({type:"header",key:`header:${z.id}`,groupIndex:$}),!b.has(z.id)){if(f){const H=new Set;g.forEach(ee=>{ee.startsWith(`${z.id} `)&&H.add(ee.slice(z.id.length+1))}),aj(w[$],H).forEach(ee=>{ee.kind==="file"?C.push({type:"file",key:`${z.id}:${ee.key}`,groupIndex:$,file:ee.file,depth:ee.depth}):C.push({type:"directory",key:`${z.id}:${ee.key}`,groupIndex:$,directory:ee.directory,depth:ee.depth})});return}z.entries.forEach(H=>{C.push({type:"file",key:`${z.id}:file:${H.path}`,groupIndex:$,file:H,depth:0})})}}),o&&m.length>0&&C.push({type:"revert-all",key:"revert-all"}),C},[b,g,f,o,w,m]),R=y.length,_=R>=ij,B=Tm({count:R,enabled:_,getScrollElement:()=>p.current,estimateSize:()=>id,overscan:12,getItemKey:C=>y[C]?.key??C}),D=B.getVirtualItems(),k=l.useMemo(()=>{if(!_)return 0;const C=p.current?.scrollTop??0;return D.find($=>$.end>C)?.index??0},[_,D,p]);l.useEffect(()=>{if(!r)return;const C=z=>z&&z.type==="file"?z.file.path:null;if(R===0){r([]);return}if(!_){const z=[];for(const $ of y)if($.type==="file"&&(z.push($.file.path),z.length>=to))break;r(z);return}r(y.slice(k,k+Math.ceil((p.current?.clientHeight??0)/id)+to).map(z=>C(z)).filter(z=>!!z).slice(0,to))},[r,R,y,_,k]);const T=l.useCallback(C=>{h(z=>{const $=new Set(z);return $.has(C)?$.delete(C):$.add(C),$})},[]),M=l.useCallback((C,z)=>{x($=>{const H=new Set($),J=so(C,z);return H.has(J)?H.delete(J):H.add(J),H})},[]),O=l.useMemo(()=>{const C=new Set;return m.forEach(z=>z.entries.forEach($=>C.add($.path))),Array.from(C)},[m]),V=O.length,U=P?a||P.paths.some(C=>n.has(C)):!1,Y=l.useCallback(async()=>{!o||a||O.length===0||(await o(O),N(!1))},[O,a,o]),X=l.useCallback(async()=>{!d||!P||U||(await d(P.paths),F(null))},[U,d,P]),S=l.useCallback((C,z)=>{const $=b.has(C.id),H=C.entries.length;return s.jsxs("div",{className:le("sticky top-0 z-10 flex items-center gap-2 py-2",i,Li,!z&&"mt-1 border-t border-border/40"),children:[s.jsx("button",{type:"button",onClick:()=>C.onActionAll(C.entries.map(J=>J.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.actionAllLabel,title:C.actionAllLabel,children:C.actionSymbol}),s.jsxs("button",{type:"button",onClick:()=>T(C.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":!$,children:[s.jsx("h3",{className:"truncate typography-ui-header font-semibold text-foreground",children:C.title}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:H}),s.jsx(L,{name:"arrow-down-s",className:le("size-3.5 shrink-0 text-muted-foreground transition-transform",$&&"-rotate-90")})]})]})},[b,i,T]),W=l.useCallback((C,z,$)=>{const H=g.has(so(C.id,z.path)),J=z.files.map(ue=>ue.path),ee=a||J.some(ue=>n.has(ue));return s.jsxs("div",{className:le("group flex items-center gap-2 py-1.5",Li),style:{paddingLeft:`${$*nd}px`},children:[s.jsxs("button",{type:"button",onClick:()=>M(C.id,z.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":H?c("gitView.changes.collapseDirectoryAria",{path:z.path}):c("gitView.changes.expandDirectoryAria",{path:z.path}),children:[H?s.jsx(L,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):s.jsx(L,{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:z.path,children:z.name}),s.jsx("span",{className:"ml-auto shrink-0 typography-micro text-muted-foreground",children:z.files.length})]}),C.showRevertActions!==!1&&d?s.jsx("button",{type:"button",onClick:()=>F({path:z.path,paths:J,count:J.length}),disabled:ee,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:z.path}),title:c("gitView.changes.revertDirectoryTooltip"),children:ee?s.jsx(L,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(L,{name:"arrow-go-back",className:"size-3.5"})}):null,s.jsx("button",{type:"button",onClick:()=>C.onActionAll(z.files.map(ue=>ue.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":c(C.actionSymbol==="+"?"gitView.changes.stageDirectoryAria":"gitView.changes.unstageDirectoryAria",{path:z.path}),title:c(C.actionSymbol==="+"?"gitView.changes.stageDirectoryAria":"gitView.changes.unstageDirectoryAria",{path:z.path}),children:C.actionSymbol})]})},[g,a,d,n,c,M]),Z=l.useCallback((C,z)=>{if(C.type==="revert-all")return s.jsx("div",{className:le("flex justify-end py-2",Li),children:s.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>N(!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(L,{name:"arrow-go-back",className:"size-3.5"}),c("gitView.changes.revertAll")]})});const $=m[C.groupIndex];if(!$)return null;if(C.type==="header")return S($,z);if(C.type==="directory")return W($,C.directory,C.depth);const H=C.file;return s.jsx(sj,{file:H,actionLabel:$.getActionLabel(H.path),actionSymbol:$.actionSymbol,onAction:()=>$.onActionFile(H.path),stats:e?.[H.path],onViewDiff:()=>$.onViewDiff(H.path),onRevert:()=>$.onRevertFile(H.path),isReverting:n.has(H.path)||a,rowPaddingClassName:Li,indentPx:C.depth*nd,actionAtStart:!f,showRevert:$.showRevertActions!==!1})},[e,a,f,W,S,n,c,m]),A=l.useCallback(C=>{const z=y[C],$=y[C-1];return!z||!$||z.type!=="file"&&z.type!=="directory"||$.type!=="file"&&$.type!=="directory"?!1:$.groupIndex===z.groupIndex},[y]);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(Zp,{ref:p,className:"overlay-scrollbar-target overlay-scrollbar-container min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto",children:_?s.jsx("div",{style:{height:B.getTotalSize(),position:"relative"},children:D.map(C=>{const z=y[C.index];return z?s.jsx("div",{"data-index":C.index,ref:B.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${C.start}px)`},className:le(A(C.index)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:Z(z,C.index===0)},z.key):null})}):s.jsx("div",{role:"list","aria-label":c("gitView.changes.changedFilesAria"),children:y.map((C,z)=>s.jsx("div",{className:le("relative",A(z)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:Z(C,z===0)},C.key))})}),s.jsx(eg,{containerRef:p,disableHorizontal:!0})]}),s.jsx(Lt,{open:v,onOpenChange:C=>{!a&&!C&&N(!1)},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:c("gitView.changes.revertAllDialogTitle")}),s.jsx(qt,{children:V===1?c("gitView.changes.revertAllDescriptionSingle",{count:V}):c("gitView.changes.revertAllDescriptionPlural",{count:V})})]}),s.jsxs(Zt,{children:[s.jsx(Q,{variant:"outline",size:"sm",onClick:()=>N(!1),disabled:a,children:c("gitView.common.cancel")}),s.jsx(Q,{variant:"destructive",size:"sm",onClick:()=>{Y()},disabled:a,children:c(a?"gitView.changes.reverting":"gitView.changes.revertAll")})]})]})}),s.jsx(Lt,{open:!!P,onOpenChange:C=>{!U&&!C&&F(null)},children:s.jsxs(Ft,{className:"max-w-md",children:[s.jsxs(Ut,{children:[s.jsx(zt,{children:c("gitView.changes.revertDirectoryDialogTitle")}),s.jsx(qt,{children:P?P.count===1?c("gitView.changes.revertDirectoryDescriptionSingle",{count:P.count,path:P.path}):c("gitView.changes.revertDirectoryDescriptionPlural",{count:P.count,path:P.path}):null})]}),s.jsxs(Zt,{children:[s.jsx(Q,{variant:"outline",size:"sm",onClick:()=>F(null),disabled:U,children:c("gitView.common.cancel")}),s.jsx(Q,{variant:"destructive",size:"sm",onClick:()=>{X()},disabled:U||!P,children:c(U?"gitView.changes.reverting":"gitView.changes.revertDirectory")})]})]})})]})},no=38,Fi=200,rj=t=>{const e=Ye.c(20),{value:n,onChange:a,placeholder:i,disabled:r,hasTouchInput:o,isMobile:d}=t,c=r===void 0?!1:r,p=o===void 0?!1:o,u=d===void 0?!1:d,{t:f}=it(),m=l.useRef(null),b=Ne(oj);let h;e[0]===Symbol.for("react.memo_cache_sentinel")?(h=()=>{const _=m.current;if(!_)return;const B=document.activeElement===_,D=()=>{_.style.height=`${no}px`;const T=_.scrollHeight,M=Math.min(Math.max(T,no),Fi);_.style.height=`${M}px`,_.style.overflowY=T>Fi?"auto":"hidden",T>Fi&&!B&&(_.scrollTop=_.scrollHeight)};D();const k=window.requestAnimationFrame(D);return()=>{window.cancelAnimationFrame(k)}},e[0]=h):h=e[0];let g;e[1]!==n?(g=[n],e[1]=n,e[2]=g):g=e[2],l.useLayoutEffect(h,g);let x;e[3]!==a?(x=_=>a(_.target.value),e[3]=a,e[4]=x):x=e[4];let v;e[5]!==i||e[6]!==f?(v=i??f("gitView.commit.messagePlaceholder"),e[5]=i,e[6]=f,e[7]=v):v=e[7];const N=p?"on":"off",P=p?"sentences":"off",F=u||b,w=c&&"opacity-50";let j;e[8]!==w?(j=le("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)]",w),e[8]=w,e[9]=j):j=e[9];let y;e[10]===Symbol.for("react.memo_cache_sentinel")?(y={minHeight:no,maxHeight:Fi},e[10]=y):y=e[10];let R;return e[11]!==c||e[12]!==F||e[13]!==j||e[14]!==x||e[15]!==v||e[16]!==N||e[17]!==P||e[18]!==n?(R=s.jsx("textarea",{ref:m,value:n,onChange:x,placeholder:v,rows:1,disabled:c,autoCorrect:N,autoCapitalize:P,spellCheck:F,className:j,style:y}),e[11]=c,e[12]=F,e[13]=j,e[14]=x,e[15]=v,e[16]=N,e[17]=P,e[18]=n,e[19]=R):R=e[19],R};function oj(t){return t.inputSpellcheckEnabled}const lj=t=>{const e=Ye.c(30),{highlights:n,onInsert:a}=t,{t:i}=it();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(L,{name:"arrow-down",className:"size-4"}),e[9]=u):u=e[9];let f;e[10]!==o||e[11]!==p?(f=s.jsx(As,{asChild:!0,children:s.jsx(Q,{variant:"ghost",size:"icon",className:"size-6",onClick:o,"aria-label":p,children:u})}),e[10]=o,e[11]=p,e[12]=f):f=e[12];let m;e[13]!==i?(m=i("gitView.commit.aiHighlights.insertTooltip"),e[13]=i,e[14]=m):m=e[14];let b;e[15]!==m?(b=s.jsx(Ds,{sideOffset:8,children:m}),e[15]=m,e[16]=b):b=e[16];let h;e[17]!==f||e[18]!==b?(h=s.jsxs(Ps,{children:[f,b]}),e[17]=f,e[18]=b,e[19]=h):h=e[19];let g;e[20]!==c||e[21]!==h?(g=s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c,h]}),e[20]=c,e[21]=h,e[22]=g):g=e[22];let x;e[23]!==n?(x=n.map(cj),e[23]=n,e[24]=x):x=e[24];let v;e[25]!==x?(v=s.jsx("ul",{className:"space-y-1",children:x}),e[25]=x,e[26]=v):v=e[26];let N;return e[27]!==g||e[28]!==v?(N=s.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-transparent px-3 py-2",children:[g,v]}),e[27]=g,e[28]=v,e[29]=N):N=e[29],N};function cj(t,e){return s.jsx("li",{className:"typography-meta text-foreground",children:t},`${t}-${e}`)}const eN=t=>{const e=Ye.c(75),{stagedCount:n,commitMessage:a,onCommitMessageChange:i,generatedHighlights:r,onInsertHighlights:o,onGenerateMessage:d,isGeneratingMessage:c,onCommit:p,onCommitAndPush:u,commitAction:f,hasPendingIndexMutation:m,gitmojiEnabled:b,onOpenGitmojiPicker:h}=t,g=m===void 0?!1:m,{t:x}=it(),v=n>0;let N;e[0]!==f||e[1]!==a||e[2]!==g||e[3]!==v?(N=a.trim()&&v&&f===null&&!g,e[0]=f,e[1]=a,e[2]=g,e[3]=v,e[4]=N):N=e[4];const P=N,{isMobile:F,hasTouchInput:w}=_s();let j;e[5]!==x?(j=x("gitView.commit.title"),e[5]=x,e[6]=j):j=e[6];let y;e[7]!==j?(y=s.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:j}),e[7]=j,e[8]=y):y=e[8];let R;e[9]!==v||e[10]!==x?(R=v?null:s.jsx("span",{className:"min-w-0 truncate typography-meta text-muted-foreground",children:x("gitView.commit.stageFilesHint")}),e[9]=v,e[10]=x,e[11]=R):R=e[11];let _;e[12]!==y||e[13]!==R?(_=s.jsxs("div",{className:"flex w-full items-baseline gap-2 px-0 pt-2 pb-1",children:[y,R]}),e[12]=y,e[13]=R,e[14]=_):_=e[14];let B;e[15]!==r||e[16]!==o?(B=s.jsx(lj,{highlights:r,onInsert:o}),e[15]=r,e[16]=o,e[17]=B):B=e[17];let D;e[18]!==x?(D=x("gitView.commit.messagePlaceholder"),e[18]=x,e[19]=D):D=e[19];const k=f!==null;let T;e[20]!==a||e[21]!==w||e[22]!==F||e[23]!==i||e[24]!==D||e[25]!==k?(T=s.jsx(rj,{value:a,onChange:i,placeholder:D,disabled:k,hasTouchInput:w,isMobile:F}),e[20]=a,e[21]=w,e[22]=F,e[23]=i,e[24]=D,e[25]=k,e[26]=T):T=e[26];let M;e[27]!==b||e[28]!==h||e[29]!==x?(M=b&&s.jsxs(Q,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[s.jsx(L,{name:"emotion-happy",className:"size-4"}),x("gitView.commit.addGitmoji")]}),e[27]=b,e[28]=h,e[29]=x,e[30]=M):M=e[30];const O=c||f!==null||g||n===0;let V;e[31]!==x?(V=x("gitView.commit.generateAria"),e[31]=x,e[32]=V):V=e[32];let U;e[33]!==c?(U=c?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{name:"ai-generate-2",className:"size-4 text-primary"}),e[33]=c,e[34]=U):U=e[34];let Y;e[35]!==x?(Y=x("gitView.commit.generate"),e[35]=x,e[36]=Y):Y=e[36];let X;e[37]!==Y?(X=s.jsx("span",{className:"commit-actions__label",children:Y}),e[37]=Y,e[38]=X):X=e[38];let S;e[39]!==d||e[40]!==O||e[41]!==V||e[42]!==U||e[43]!==X?(S=s.jsxs(Q,{variant:"outline",size:"sm",onClick:d,disabled:O,type:"button","aria-label":V,className:"commit-actions__btn",children:[U,X]}),e[39]=d,e[40]=O,e[41]=V,e[42]=U,e[43]=X,e[44]=S):S=e[44];let W;e[45]===Symbol.for("react.memo_cache_sentinel")?(W=s.jsx("div",{className:"flex-1"}),e[45]=W):W=e[45];const Z=!P||c;let A;e[46]!==x?(A=x("gitView.commit.commitAria"),e[46]=x,e[47]=A):A=e[47];let C;e[48]!==f||e[49]!==x?(C=f==="commit"?s.jsxs(s.Fragment,{children:[s.jsx(L,{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(L,{name:"git-commit",className:"size-4"}),s.jsx("span",{className:"commit-actions__label",children:x("gitView.commit.commit")})]}),e[48]=f,e[49]=x,e[50]=C):C=e[50];let z;e[51]!==p||e[52]!==Z||e[53]!==A||e[54]!==C?(z=s.jsx(Q,{size:"sm",variant:"outline",onClick:p,disabled:Z,className:"commit-actions__btn whitespace-nowrap","aria-label":A,children:C}),e[51]=p,e[52]=Z,e[53]=A,e[54]=C,e[55]=z):z=e[55];let $;e[56]!==P||e[57]!==f||e[58]!==c||e[59]!==F||e[60]!==u||e[61]!==x?($=F?s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx(Q,{variant:"default",size:"sm",onClick:()=>u(),disabled:!P||c,className:"h-7 w-7 p-0","aria-label":x("gitView.commit.pushAria"),children:f==="commitAndPush"?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{name:"arrow-up",className:"size-3.5"})})}),s.jsx(Ds,{side:"top",children:s.jsx("p",{children:x("gitView.commit.push")})})]}):s.jsx(Q,{size:"sm",variant:"default",onClick:()=>u(),disabled:!P||c,className:"commit-actions__btn","aria-label":x("gitView.commit.pushAria"),children:f==="commitAndPush"?s.jsxs(s.Fragment,{children:[s.jsx(L,{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(L,{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]=P,e[57]=f,e[58]=c,e[59]=F,e[60]=u,e[61]=x,e[62]=$):$=e[62];let H;e[63]!==S||e[64]!==z||e[65]!==$?(H=s.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[S,W,z,$]}),e[63]=S,e[64]=z,e[65]=$,e[66]=H):H=e[66];let J;e[67]!==T||e[68]!==M||e[69]!==H||e[70]!==B?(J=s.jsxs("div",{className:"flex flex-col gap-3 px-0 pt-1 pb-3",children:[B,T,M,H]}),e[67]=T,e[68]=M,e[69]=H,e[70]=B,e[71]=J):J=e[71];let ee;return e[72]!==J||e[73]!==_?(ee=s.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[_,J]}),e[72]=J,e[73]=_,e[74]=ee):ee=e[74],ee},dj=t=>{const e=Ye.c(44),{syncAction:n,remotes:a,onFetch:i,onSync:r,onRemoveRemote:o,disabled:d,removingRemoteName:c,aheadCount:p,behindCount:u,trackingRemoteName:f,hasUncommittedChanges:m}=t,b=a===void 0?[]:a,h=c===void 0?null:c,g=p===void 0?0:p,x=u===void 0?0:u,v=m===void 0?!1:m,{t:N}=it(),P=l.useRef(!1),F=!!h,w=b.find(q=>q.name===f)??b[0],j=x>0&&v,y=d||n!==null||F||!w||j,R=d||n!==null||F||b.length===0,_=g>0||x>0;let B;e[0]!==N?(B=N("gitView.sync.sync"),e[0]=N,e[1]=B):B=e[1];const D=x>0?`↓${x}`:null,k=g>0?`↑${g}`:null;let T;e[2]!==B||e[3]!==D||e[4]!==k?(T=[B,D,k].filter(Boolean),e[2]=B,e[3]=D,e[4]=k,e[5]=T):T=e[5];const M=T.join(" "),O=j?N("gitView.sync.commitOrStashTooltip"):w?_?N("gitView.sync.syncChangesTooltip",{ahead:g,behind:x}):N("gitView.sync.syncChanges"):N("gitView.sync.noRemoteTooltip"),V=()=>{w&&r(w)},U="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",Y=j?0:void 0;let X;e[6]===Symbol.for("react.memo_cache_sentinel")?(X=le("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]=X):X=e[6];let S;e[7]!==N?(S=N("gitView.sync.syncChanges"),e[7]=N,e[8]=S):S=e[8];let W;e[9]!==n?(W=n==="sync"?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{name:"refresh",className:"size-4"}),e[9]=n,e[10]=W):W=e[10];let Z;e[11]!==M?(Z=s.jsx("span",{className:"whitespace-nowrap tabular-nums",children:M}),e[11]=M,e[12]=Z):Z=e[12];let A;e[13]!==V||e[14]!==y||e[15]!==S||e[16]!==W||e[17]!==Z?(A=s.jsxs("button",{type:"button",onClick:V,disabled:y,className:X,"aria-label":S,children:[W,Z]}),e[13]=V,e[14]=y,e[15]=S,e[16]=W,e[17]=Z,e[18]=A):A=e[18];let C;e[19]!==Y||e[20]!==A?(C=s.jsx(As,{asChild:!0,children:s.jsx("span",{className:"inline-flex",tabIndex:Y,children:A})}),e[19]=Y,e[20]=A,e[21]=C):C=e[21];let z;e[22]!==O?(z=s.jsx(Ds,{sideOffset:8,children:O}),e[22]=O,e[23]=z):z=e[23];let $;e[24]!==C||e[25]!==z?($=s.jsxs(Ps,{children:[C,z]}),e[24]=C,e[25]=z,e[26]=$):$=e[26];const H=ws;let J;e[27]===Symbol.for("react.memo_cache_sentinel")?(J=le("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]=J):J=e[27];let ee;e[28]!==N?(ee=N("gitView.sync.moreActionsAria"),e[28]=N,e[29]=ee):ee=e[29];let ue;e[30]===Symbol.for("react.memo_cache_sentinel")?(ue=s.jsx(L,{name:"arrow-down-s",className:"size-4"}),e[30]=ue):ue=e[30];let re;e[31]!==R||e[32]!==ee?(re=s.jsx(ys,{asChild:!0,children:s.jsx("button",{type:"button",className:J,disabled:R,"aria-label":ee,children:ue})}),e[31]=R,e[32]=ee,e[33]=re):re=e[33];const xe=vs,be="start",he=-40,ye="w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",fe=b.map(q=>s.jsx(bs,{onSelect:te=>{if(P.current){te.preventDefault(),P.current=!1;return}i(q)},children:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx(L,{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:N("gitView.sync.fetchFromRemote",{name:q.name})}),s.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:q.fetchUrl})]})}),o&&q.name!==f?s.jsx(Q,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:n!==null||F,onPointerDown:te=>{P.current=!0,te.preventDefault(),te.stopPropagation()},onClick:te=>{P.current=!0,te.preventDefault(),te.stopPropagation(),o(q)},"aria-label":N("gitView.header.removeRemoteAria",{name:q.name}),title:N("gitView.header.removeRemoteTitle",{name:q.name}),children:h===q.name?s.jsx(L,{name:"loader-4",className:"size-3.5 animate-spin"}):s.jsx(L,{name:"close",className:"size-3.5"})}):null]})},q.name));let ae;e[34]!==xe||e[35]!==fe?(ae=s.jsx(xe,{align:be,alignOffset:he,className:ye,children:fe}),e[34]=xe,e[35]=fe,e[36]=ae):ae=e[36];let ce;e[37]!==H||e[38]!==re||e[39]!==ae?(ce=s.jsxs(H,{children:[re,ae]}),e[37]=H,e[38]=re,e[39]=ae,e[40]=ce):ce=e[40];let pe;return e[41]!==$||e[42]!==ce?(pe=s.jsxs("div",{className:U,children:[$,ce]}),e[41]=$,e[42]=ce,e[43]=pe):pe=e[43],pe};function uj(t){const e=Ye.c(85),{draft:n,onEdit:a,onDelete:i,className:r,maxWidth:o}=t,{t:d}=it(),p=ar()?.currentTheme,[u,f]=ge.useState(!1),[m,b]=ge.useState(!1),h=typeof n.text=="string"?n.text:"";let g;e[0]!==h?(g=h.length>150||h.split(`
|
|
37
|
+
`).length>3,e[0]=h,e[1]=g):g=e[1];const x=g;let v;e[2]!==r?(v=le("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]=v):v=e[3];const N=p?.colors?.surface?.elevated,P=p?.colors?.interactive?.border,F=o?`${Math.max(200,Math.floor(o))}px`:void 0;let w;e[4]!==N||e[5]!==P||e[6]!==F?(w={backgroundColor:N,borderColor:P,maxWidth:F},e[4]=N,e[5]=P,e[6]=F,e[7]=w):w=e[7];let j;e[8]===Symbol.for("react.memo_cache_sentinel")?(j=q=>{q.preventDefault(),b(!0)},e[8]=j):j=e[8];let y;e[9]!==v||e[10]!==w?(y=s.jsx("div",{className:v,style:w,"data-comment-card":"true",onContextMenu:j}),e[9]=v,e[10]=w,e[11]=y):y=e[11];let R;e[12]!==n.fileLabel?(R=s.jsx("span",{className:"truncate max-w-[200px]",title:n.fileLabel,children:n.fileLabel}),e[12]=n.fileLabel,e[13]=R):R=e[13];let _;e[14]===Symbol.for("react.memo_cache_sentinel")?(_=s.jsx("span",{children:"•"}),e[14]=_):_=e[14];let B;e[15]!==n.endLine||e[16]!==n.startLine||e[17]!==d?(B=d("inlineComment.range.lines",{start:n.startLine,end:n.endLine}),e[15]=n.endLine,e[16]=n.startLine,e[17]=d,e[18]=B):B=e[18];let D;e[19]!==B?(D=s.jsx("span",{children:B}),e[19]=B,e[20]=D):D=e[20];let k;e[21]!==n.side?(k=n.side&&s.jsxs("span",{children:["(",n.side,")"]}),e[21]=n.side,e[22]=k):k=e[22];let T;e[23]!==D||e[24]!==k||e[25]!==R?(T=s.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground mb-1.5",children:[R,_,D,k]}),e[23]=D,e[24]=k,e[25]=R,e[26]=T):T=e[26];const M=u||!x,O=!u&&x&&"line-clamp-3";let V;e[27]!==O?(V=le("text-sm whitespace-pre-wrap break-words leading-relaxed",O),e[27]=O,e[28]=V):V=e[28];let U;e[29]!==h||e[30]!==V?(U=s.jsx("div",{className:V,children:h}),e[29]=h,e[30]=V,e[31]=U):U=e[31];let Y;e[32]!==x||e[33]!==u||e[34]!==d?(Y=x&&s.jsx(na,{asChild:!0,children:s.jsx(Q,{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(L,{name:"arrow-up-s",className:"size-3 mr-1"}),d("inlineComment.actions.showLess")]}):s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"arrow-down-s",className:"size-3 mr-1"}),d("inlineComment.actions.showMore")]})})}),e[32]=x,e[33]=u,e[34]=d,e[35]=Y):Y=e[35];let X;e[36]===Symbol.for("react.memo_cache_sentinel")?(X=s.jsx(aa,{}),e[36]=X):X=e[36];let S;e[37]!==M||e[38]!==U||e[39]!==Y?(S=s.jsxs(sa,{open:M,onOpenChange:f,children:[U,Y,X]}),e[37]=M,e[38]=U,e[39]=Y,e[40]=S):S=e[40];let W;e[41]!==T||e[42]!==S?(W=s.jsxs("div",{className:"flex-1 min-w-0",children:[T,S]}),e[41]=T,e[42]=S,e[43]=W):W=e[43];let Z;e[44]===Symbol.for("react.memo_cache_sentinel")?(Z=s.jsx(ys,{asChild:!0,children:s.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1 text-muted-foreground hover:text-foreground",children:s.jsx(L,{name:"more",className:"size-4"})})}),e[44]=Z):Z=e[44];let A;e[45]===Symbol.for("react.memo_cache_sentinel")?(A=s.jsx(L,{name:"edit",className:"size-4 mr-2"}),e[45]=A):A=e[45];let C;e[46]!==d?(C=d("inlineComment.actions.editComment"),e[46]=d,e[47]=C):C=e[47];let z;e[48]!==a||e[49]!==C?(z=s.jsxs(bs,{onClick:a,children:[A,C]}),e[48]=a,e[49]=C,e[50]=z):z=e[50];let $;e[51]===Symbol.for("react.memo_cache_sentinel")?($=s.jsx(L,{name:"delete-bin",className:"size-4 mr-2"}),e[51]=$):$=e[51];let H;e[52]!==d?(H=d("inlineComment.actions.deleteComment"),e[52]=d,e[53]=H):H=e[53];let J;e[54]!==i||e[55]!==H?(J=s.jsxs(bs,{onClick:i,className:"text-destructive",children:[$,H]}),e[54]=i,e[55]=H,e[56]=J):J=e[56];let ee;e[57]!==z||e[58]!==J?(ee=s.jsxs(ws,{children:[Z,s.jsxs(vs,{align:"end",children:[z,J]})]}),e[57]=z,e[58]=J,e[59]=ee):ee=e[59];let ue;e[60]!==W||e[61]!==ee?(ue=s.jsxs("div",{className:"flex items-start justify-between gap-2 p-3",children:[W,ee]}),e[60]=W,e[61]=ee,e[62]=ue):ue=e[62];let re;e[63]!==ue||e[64]!==y?(re=s.jsx(_n,{render:y,children:ue}),e[63]=ue,e[64]=y,e[65]=re):re=e[65];let xe;e[66]===Symbol.for("react.memo_cache_sentinel")?(xe=s.jsx(L,{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 he;e[69]!==a||e[70]!==be?(he=s.jsxs(En,{onClick:a,children:[xe,be]}),e[69]=a,e[70]=be,e[71]=he):he=e[71];let ye;e[72]===Symbol.for("react.memo_cache_sentinel")?(ye=s.jsx(L,{name:"delete-bin",className:"size-4 mr-2"}),e[72]=ye):ye=e[72];let fe;e[73]!==d?(fe=d("inlineComment.actions.deleteComment"),e[73]=d,e[74]=fe):fe=e[74];let ae;e[75]!==i||e[76]!==fe?(ae=s.jsxs(En,{onClick:i,className:"text-destructive focus:text-destructive",children:[ye,fe]}),e[75]=i,e[76]=fe,e[77]=ae):ae=e[77];let ce;e[78]!==he||e[79]!==ae?(ce=s.jsxs($n,{children:[he,ae]}),e[78]=he,e[79]=ae,e[80]=ce):ce=e[80];let pe;return e[81]!==m||e[82]!==re||e[83]!==ce?(pe=s.jsxs(Un,{open:m,onOpenChange:b,children:[re,ce]}),e[81]=m,e[82]=re,e[83]=ce,e[84]=pe):pe=e[84],pe}function rd(t){const e=Ye.c(62),{initialText:n,onTextChange:a,onSave:i,onCancel:r,fileLabel:o,lineRange:d,isEditing:c,className:p,maxWidth:u}=t,f=n===void 0?"":n,m=c===void 0?!1:c,{t:b}=it(),g=ar()?.currentTheme,{isMobile:x}=_s(),[v,N]=l.useState(f),P=ge.useRef(null);let F;e[0]!==a?(F=ne=>{N(ne),a?.(ne)},e[0]=a,e[1]=F):F=e[1];const w=F,j=ge.useRef(d);let y,R;e[2]!==d?(y=()=>{d&&(j.current=d)},R=[d],e[2]=d,e[3]=y,e[4]=R):(y=e[3],R=e[4]),ge.useEffect(y,R);const _=bj,B=_(d);let D,k;e[5]!==x?(D=()=>{const ne=P.current;if(!ne)return;const oe=ne.closest(".overlay-scrollbar-container"),Ae=oe?.scrollTop??window.scrollY,je=oe?.scrollLeft??window.scrollX;if(x){ne.scrollIntoView({behavior:"auto",block:"nearest"});try{ne.focus({preventScroll:!0})}catch{ne.focus()}return}try{ne.focus({preventScroll:!0})}catch{ne.focus()}const Ie=ne.value.length;try{ne.setSelectionRange(Ie,Ie)}catch{}requestAnimationFrame(()=>{oe?(oe.scrollTop=Ae,oe.scrollLeft=je):window.scrollTo({top:Ae,left:je})})},k=[x],e[5]=x,e[6]=D,e[7]=k):(D=e[6],k=e[7]),ge.useEffect(D,k);let T;e[8]!==r||e[9]!==i||e[10]!==v?(T=ne=>{(ne.metaKey||ne.ctrlKey)&&ne.key==="Enter"?(ne.preventDefault(),v.trim()&&i(v,_(j.current))):ne.key==="Escape"&&(ne.preventDefault(),r())},e[8]=r,e[9]=i,e[10]=v,e[11]=T):T=e[11];const M=T;let O;e[12]!==i||e[13]!==v?(O=ne=>{ne.stopPropagation(),v.trim()&&i(v,_(j.current))},e[12]=i,e[13]=v,e[14]=O):O=e[14];const V=O;let U;e[15]!==p?(U=le("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]=U):U=e[16];const Y=g?.colors?.surface?.elevated,X=g?.colors?.interactive?.border,S=u?`${Math.max(200,Math.floor(u))}px`:void 0;let W;e[17]!==Y||e[18]!==X||e[19]!==S?(W={backgroundColor:Y,borderColor:X,maxWidth:S},e[17]=Y,e[18]=X,e[19]=S,e[20]=W):W=e[20];const Z="true",A=xj,C=hj,z="p-3",$=(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:"•"}),B&&s.jsx("span",{children:b("inlineComment.range.lines",{start:B.start,end:B.end})})]});let H;e[21]!==w?(H=ne=>w(ne.target.value),e[21]=w,e[22]=H):H=e[22];let J;e[23]!==x||e[24]!==b?(J=b(x?"inlineComment.input.placeholderShort":"inlineComment.input.placeholder"),e[23]=x,e[24]=b,e[25]=J):J=e[25];let ee;e[26]!==M||e[27]!==H||e[28]!==J||e[29]!==v?(ee=s.jsx(js,{simple:!0,ref:P,value:v,onChange:H,onKeyDown:M,placeholder:J,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]=M,e[27]=H,e[28]=J,e[29]=v,e[30]=ee):ee=e[30];let ue;e[31]!==b?(ue=b("inlineComment.actions.cancel"),e[31]=b,e[32]=ue):ue=e[32];let re;e[33]!==r||e[34]!==ue?(re=s.jsx(Q,{variant:"ghost",size:"sm",onClick:r,onPointerDown:fj,onTouchStart:gj,className:"h-8 text-muted-foreground hover:text-foreground",children:ue}),e[33]=r,e[34]=ue,e[35]=re):re=e[35];let xe;e[36]!==v?(xe=v.trim(),e[36]=v,e[37]=xe):xe=e[37];const be=!xe,he=g?.colors?.status?.success,ye=g?.colors?.status?.successForeground;let fe;e[38]!==he||e[39]!==ye?(fe={backgroundColor:he,color:ye},e[38]=he,e[39]=ye,e[40]=fe):fe=e[40];let ae;e[41]!==m||e[42]!==b?(ae=b(m?"inlineComment.actions.save":"inlineComment.actions.comment"),e[41]=m,e[42]=b,e[43]=ae):ae=e[43];let ce;e[44]!==V||e[45]!==be||e[46]!==fe||e[47]!==ae?(ce=s.jsx(Q,{size:"sm",onClick:V,onPointerDown:pj,onTouchStart:mj,disabled:be,className:"h-8 min-w-[80px]",style:fe,children:ae}),e[44]=V,e[45]=be,e[46]=fe,e[47]=ae,e[48]=ce):ce=e[48];let pe;e[49]!==re||e[50]!==ce?(pe=s.jsxs("div",{className:"flex items-center justify-end gap-2 mt-3",children:[re,ce]}),e[49]=re,e[50]=ce,e[51]=pe):pe=e[51];let q;e[52]!==$||e[53]!==ee||e[54]!==pe?(q=s.jsxs("div",{className:z,children:[$,ee,pe]}),e[52]=$,e[53]=ee,e[54]=pe,e[55]=q):q=e[55];let te;return e[56]!==U||e[57]!==W||e[58]!==A||e[59]!==C||e[60]!==q?(te=s.jsx("div",{className:U,style:W,"data-comment-input":Z,onPointerDown:A,onTouchStart:C,children:q}),e[56]=U,e[57]=W,e[58]=A,e[59]=C,e[60]=q,e[61]=te):te=e[61],te}function mj(t){return t.stopPropagation()}function pj(t){return t.stopPropagation()}function gj(t){return t.stopPropagation()}function fj(t){return t.stopPropagation()}function hj(t){return t.stopPropagation()}function xj(t){return t.stopPropagation()}function bj(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 yj=t=>{const e=Math.min(t.startLine,t.endLine),n=Math.max(t.startLine,t.endLine);return{...t,startLine:e,endLine:n}},od=t=>{const e=Math.min(t.start,t.end),n=Math.max(t.start,t.end);return{...t,start:e,end:n}};function vj(t){const e=Ye.c(47),{t:n}=it(),{source:a,fileLabel:i,language:r,getCodeForRange:o,toStoreRange:d,fromDraftRange:c}=t,p=ds(Sj),u=ds(Nj),f=Ed();let m;e[0]!==p?(m=J=>p?J.getDirectoryForSession(p):null,e[0]=p,e[1]=m):m=e[1];const b=ds(m),h=Qa(kj),g=Qa(jj),x=Qa(wj),[v,N]=l.useState(null),[P,F]=l.useState(""),[w,j]=l.useState(null),y=p??(u?"draft":null),R=b??f;let _;e:{if(!y||!R){_=null;break e}let J;e[2]!==R||e[3]!==y?(J={directory:R,sessionKey:y},e[2]=R,e[3]=y,e[4]=J):J=e[4],_=J}const B=_;let D;e[5]!==B?(D=B?tg(on(),B.directory,B.sessionKey):null,e[5]=B,e[6]=D):D=e[6];const k=D;let T;e[7]!==k?(T=J=>k?J.drafts[k]??cl:cl,e[7]=k,e[8]=T):T=e[8];const M=Qa(T);let O;e:{if(!B||!i){let ee;e[9]===Symbol.for("react.memo_cache_sentinel")?(ee=[],e[9]=ee):ee=e[9],O=ee;break e}let J;if(e[10]!==i||e[11]!==M||e[12]!==a){let ee;e[14]!==i||e[15]!==a?(ee=ue=>ue.source===a&&ue.fileLabel===i,e[14]=i,e[15]=a,e[16]=ee):ee=e[16],J=M.filter(ee),e[10]=i,e[11]=M,e[12]=a,e[13]=J}else J=e[13];O=J}const V=O;let U;e[17]===Symbol.for("react.memo_cache_sentinel")?(U=()=>{N(null),F(""),j(null)},e[17]=U):U=e[17];const Y=U;let X;e[18]===Symbol.for("react.memo_cache_sentinel")?(X=()=>{Y()},e[18]=X):X=e[18];const S=X;let W;e[19]!==c?(W=J=>{const ee=od(c(J));N(ee),F(J.text),j(J.id)},e[19]=c,e[20]=W):W=e[20];const Z=W;let A;e[21]!==w||e[22]!==x||e[23]!==B?(A=J=>{B&&(x(B,J.id),w===J.id&&Y())},e[21]=w,e[22]=x,e[23]=B,e[24]=A):A=e[24];const C=A;let z;e[25]!==h||e[26]!==w||e[27]!==i||e[28]!==o||e[29]!==r||e[30]!==v||e[31]!==a||e[32]!==n||e[33]!==B||e[34]!==d||e[35]!==g?(z=(J,ee)=>{const ue=ee??v,re=J.trim();if(!ue||!re||!i)return;if(!B){G.error(n("inlineComment.toast.selectSessionToSave"));return}const xe=od(ue),be=yj(d(xe)),he=o(xe);w?g(B,w,{fileLabel:i,startLine:be.startLine,endLine:be.endLine,side:be.side,code:he,language:r,text:re}):h(B,{source:a,fileLabel:i,startLine:be.startLine,endLine:be.endLine,side:be.side,code:he,language:r,text:re}),Y()},e[25]=h,e[26]=w,e[27]=i,e[28]=o,e[29]=r,e[30]=v,e[31]=a,e[32]=n,e[33]=B,e[34]=d,e[35]=g,e[36]=z):z=e[36];const $=z;let H;return e[37]!==P||e[38]!==C||e[39]!==V||e[40]!==w||e[41]!==c||e[42]!==$||e[43]!==v||e[44]!==y||e[45]!==Z?(H={sessionKey:y,drafts:V,selection:v,setSelection:N,commentText:P,setCommentText:F,editingDraftId:w,setEditingDraftId:j,reset:Y,cancel:S,startEdit:Z,deleteDraft:C,saveComment:$,fromDraftRange:c},e[37]=P,e[38]=C,e[39]=V,e[40]=w,e[41]=c,e[42]=$,e[43]=v,e[44]=y,e[45]=Z,e[46]=H):H=e[46],H}function wj(t){return t.removeDraft}function jj(t){return t.updateDraft}function kj(t){return t.addDraft}function Nj(t){return t.newSessionDraft?.open}function Sj(t){return t.currentSessionId}const qi=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}`},Cj=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 Ij(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 ld(t){if(!(!t||t<=0))return Math.max(200,Math.floor(t))}function Pj(t){const{diffRootRef:e,drafts:n,selection:a,editingDraftId:i,commentText:r,onTextChange:o,fileLabel:d,onSave:c,onCancel:p,onEdit:u,onDelete:f}=t,[m,b]=l.useState(0),[h,g]=l.useState(null),x=l.useMemo(()=>!a||i?null:qi({type:"new",selection:a}),[i,a]),v=l.useMemo(()=>{const F=n.map(w=>qi({type:w.id===i?"edit":"saved",draft:w}));return x&&F.push(x),F},[n,i,x]),N=l.useCallback(F=>{const w=e.current;if(!w)return null;const j=w.querySelector("diffs-container");if(!(j instanceof HTMLElement))return null;const y=j.querySelector(`[data-annotation-id="${F}"]`);if(y instanceof HTMLElement)return y;const R=j.shadowRoot;return R?R.querySelector(`[data-annotation-id="${F}"]`):null},[e]);l.useEffect(()=>{if(v.length===0)return;let F=!1,w=0;const j=12,y=()=>{F||v.every(_=>!!N(_))||w>=j||(w+=1,requestAnimationFrame(()=>{F||(b(_=>_+1),y())}))};return y(),()=>{F=!0}},[v,N]),l.useEffect(()=>{const F=e.current;if(!F)return;const w=()=>{const y=getComputedStyle(F),R=Ij(y.getPropertyValue("--oc-context-panel-width")),_=F.getBoundingClientRect(),B=R??_.width;g(B>0?B:null)};w();const j=new ResizeObserver(()=>{w()});return j.observe(F),window.addEventListener("resize",w),()=>{j.disconnect(),window.removeEventListener("resize",w)}},[e]);const P=l.useCallback(F=>{const j=e.current?.getBoundingClientRect(),y=F.closest("[data-annotation-content]"),R=y instanceof HTMLElement?y.getBoundingClientRect():F.getBoundingClientRect(),_=[R.width];j&&_.push(j.right-R.left);const B=_.filter(D=>Number.isFinite(D)&&D>0);return B.length>0?ld(Math.min(...B)):ld(h)},[e,h]);return s.jsxs(s.Fragment,{children:[n.map(F=>{const w=qi({type:F.id===i?"edit":"saved",draft:F}),j=N(w);if(!j)return null;const y=P(j);return F.id===i?Ki.createPortal(s.jsx(rd,{initialText:r,onTextChange:o,fileLabel:d,lineRange:{start:F.startLine,end:F.endLine,side:F.side==="original"?"deletions":"additions"},isEditing:!0,onSave:c,onCancel:p,maxWidth:y}),j,`draft-edit-${F.id}`):Ki.createPortal(s.jsx(uj,{draft:F,onEdit:()=>u(F),onDelete:()=>f(F),maxWidth:y}),j,`draft-card-${F.id}`)}),a&&!i&&x&&(()=>{const F=N(x);if(!F)return null;const w=P(F);return Ki.createPortal(s.jsx(rd,{initialText:r,onTextChange:o,fileLabel:d,lineRange:a,isEditing:!1,onSave:c,onCancel:p,maxWidth:w}),F,x)})()]})}const cd=5e5,Aj=`
|
|
38
|
+
:host {
|
|
39
|
+
font-family: var(--font-mono);
|
|
40
|
+
font-size: var(--text-code);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
pre, [data-code] {
|
|
44
|
+
font-family: var(--font-mono);
|
|
45
|
+
font-size: var(--text-code);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/* Mobile touch selection support */
|
|
49
|
+
[data-line-number] {
|
|
50
|
+
touch-action: manipulation;
|
|
51
|
+
-webkit-tap-highlight-color: transparent;
|
|
52
|
+
cursor: pointer;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/* Ensure interactive line numbers work on touch */
|
|
56
|
+
pre[data-interactive-line-numbers] [data-line-number] {
|
|
57
|
+
touch-action: manipulation;
|
|
58
|
+
}
|
|
59
|
+
`,Ej=`
|
|
60
|
+
${Aj}
|
|
61
|
+
|
|
62
|
+
:host {
|
|
63
|
+
--diffs-bg-separator-override: var(--surface-elevated);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
[data-diff-header],
|
|
67
|
+
[data-diff] {
|
|
68
|
+
[data-separator] {
|
|
69
|
+
height: 24px !important;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
[data-separator="line-info-basic"] {
|
|
74
|
+
height: 24px !important;
|
|
75
|
+
background: var(--diffs-bg) !important;
|
|
76
|
+
position: relative;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
[data-diff-type="single"] [data-gutter],
|
|
80
|
+
[data-diff-type="split"] [data-deletions] [data-gutter] {
|
|
81
|
+
[data-separator-wrapper] {
|
|
82
|
+
position: absolute;
|
|
83
|
+
left: 100%;
|
|
84
|
+
display: flex;
|
|
85
|
+
align-items: center;
|
|
86
|
+
gap: unset;
|
|
87
|
+
width: max-content;
|
|
88
|
+
background: transparent;
|
|
89
|
+
color: var(--diffs-fg-number);
|
|
90
|
+
font-family: var(--diffs-header-font-family, var(--font-sans));
|
|
91
|
+
font-size: 0.75rem;
|
|
92
|
+
line-height: 1;
|
|
93
|
+
margin-left: calc(-2ch - 2px);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
[data-separator-wrapper][data-separator-multi-button] {
|
|
97
|
+
margin-left: calc(-3ch - 2px);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
[data-expand-button],
|
|
101
|
+
[data-separator-content] {
|
|
102
|
+
display: block;
|
|
103
|
+
align-self: unset;
|
|
104
|
+
min-width: unset;
|
|
105
|
+
min-height: unset;
|
|
106
|
+
padding: 0;
|
|
107
|
+
flex-shrink: 0;
|
|
108
|
+
grid-column: unset;
|
|
109
|
+
border: none;
|
|
110
|
+
width: auto;
|
|
111
|
+
height: auto;
|
|
112
|
+
background-color: transparent;
|
|
113
|
+
color: inherit;
|
|
114
|
+
font: inherit;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
[data-expand-button]:not([data-expand-all-button]) {
|
|
118
|
+
&[data-expand-down]::before {
|
|
119
|
+
content: '\\2191';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
&[data-expand-up]::before {
|
|
123
|
+
content: '\\2193';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
&[data-expand-both]::before {
|
|
127
|
+
content: '\\2195';
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
svg {
|
|
131
|
+
display: none;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
[data-separator-content] {
|
|
136
|
+
background: transparent;
|
|
137
|
+
margin-left: calc(2px + 1ch);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
[data-expand-all-button] {
|
|
141
|
+
position: relative;
|
|
142
|
+
margin-left: 14px;
|
|
143
|
+
text-transform: lowercase;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
[data-expand-all-button]::before {
|
|
147
|
+
content: '';
|
|
148
|
+
display: block;
|
|
149
|
+
position: absolute;
|
|
150
|
+
top: 50%;
|
|
151
|
+
left: -8px;
|
|
152
|
+
margin-top: -1px;
|
|
153
|
+
width: 3px;
|
|
154
|
+
height: 3px;
|
|
155
|
+
border-radius: 2px;
|
|
156
|
+
background-color: var(--diffs-fg-number);
|
|
157
|
+
pointer-events: none;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
[data-separator-content]:hover,
|
|
161
|
+
[data-expand-button]:hover,
|
|
162
|
+
[data-expand-all-button]:hover {
|
|
163
|
+
color: var(--diffs-fg);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
[data-expand-all-button]:hover {
|
|
167
|
+
text-decoration: underline;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
`;function Tj(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 dd(t){const e=t.length>400?`${t.slice(0,200)}${t.slice(-200)}`:t;return`${t.length}:${Tj(e)}`}const Rj=(t,e,n,a)=>{const i=a.side==="deletions",o=(n?(i?n.deletionLines:n.additionLines).join(""):i?t:e).split(`
|
|
171
|
+
`),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(`
|
|
172
|
+
`)},Dj=(t,e)=>t===e?!0:!t||!e?!1:t.start===e.start&&t.end===e.end&&t.side===e.side,Mj=t=>t==="auto"||t==="scroll"||t==="overlay",Lj=t=>{let e=t?.parentElement??null;for(;e;){const n=window.getComputedStyle(e);if(Mj(n.overflowY))return e;e=e.parentElement}return null},Fj=(t,e)=>{if(!t||!e||typeof window>"u")return()=>{};const n=Lj(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)}},Oj=(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)}},Oi=new WeakMap,zj={lineHeight:24,hunkSeparatorHeight:24,spacing:0};function Bj(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 Kj(t){if(typeof document>"u")return null;const e=Bj(t);let n=Oi.get(e.key);if(!n){const i=new Lm;i.setup(e.root,e.content),n={virtualizer:i,refs:0},Oi.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=Oi.get(e.key);i&&(i.refs-=1,!(i.refs>0)&&(i.virtualizer.cleanUp(),Oi.delete(e.key)))}}}const Uj=(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)}},tN=({original:t,modified:e,fileDiff:n,language:a,fileName:i,renderSideBySide:r,wrapLines:o,layout:d="fill",enableComments:c=!0})=>{const p=ar(),u=p?.currentTheme.metadata.variant==="dark",f=p?.availableThemes.find(q=>q.metadata.id===p.lightThemeId)??Yi(!1),m=p?.availableThemes.find(q=>q.metadata.id===p.darkThemeId)??Yi(!0),{isMobile:b}=_s(),h=vj({source:"diff",fileLabel:i||"unknown",language:a,getCodeForRange:q=>Rj(t,e,n,q),toStoreRange:q=>({startLine:q.start,endLine:q.end,side:q.side==="deletions"?"original":"modified"}),fromDraftRange:q=>({start:q.startLine,end:q.endLine,side:q.side==="original"?"deletions":"additions"})}),{drafts:g,selection:x,setSelection:v,commentText:N,setCommentText:P,editingDraftId:F,saveComment:w,cancel:j,startEdit:y,deleteDraft:R}=h,_=ge.useRef(null),B=ge.useRef(null),D=ge.useRef(""),k=ge.useRef(!1),T=ge.useRef(null);ge.useEffect(()=>{_.current=x},[x]),ge.useEffect(()=>{B.current=F},[F]),ge.useEffect(()=>{D.current=N},[N]);const M=ge.useCallback(q=>{if(!c||k.current)return;const te=_.current;if(!(!q&&te&&D.current.trim())){if(b&&te&&q&&q.side===te.side){const ne=Math.min(te.start,q.start),oe=Math.max(te.end,q.end);v({...q,start:ne,end:oe})}else v(q);q&&(B.current||P(""))}},[c,b,P,v]),O=ge.useCallback(()=>{j()},[j]),V=ge.useCallback(q=>{const te=document.createElement("div");te.style.position="relative";const ne=qi(q.metadata);return te.dataset.annotationId=ne,te.dataset.annotationSide=q.side,te.dataset.annotationLine=String(q.lineNumber),te},[]),U=ge.useCallback((q,te)=>{w(q,te??x??void 0)},[w,x]),Y=ge.useCallback(q=>{v(q);const te=C.current;if(te)try{k.current=!0,te.setSelectedLines(q),T.current=q}catch{}finally{k.current=!1}},[v]),X=ge.useCallback(q=>{const te=q.closest("[data-line-type]")?.getAttribute("data-line-type")??q.getAttribute("data-line-type");if(te==="change-deletion")return"deletions";if(te==="change-addition")return"additions";const ne=q.getAttribute("data-column-side")??q.getAttribute("data-side")??q.closest("[data-column-side]")?.getAttribute("data-column-side");if(ne==="deletions"||ne==="left"||ne==="original")return"deletions";if(ne==="additions"||ne==="right"||ne==="modified")return"additions";const oe=q.closest("[data-line-type]");if(oe instanceof HTMLElement){const Ae=oe.getBoundingClientRect(),je=q.getBoundingClientRect(),Ie=Ae.left+Ae.width/2;return je.left+je.width/2<Ie?"deletions":"additions"}return"additions"},[]);Qi(f),Qi(m);const S=`${f.metadata.id}:${m.metadata.id}:${u?"dark":"light"}`,W=ge.useMemo(()=>{if(n){const q=n.deletionLines.reduce((ne,oe)=>ne+oe.length,0),te=n.additionLines.reduce((ne,oe)=>ne+oe.length,0);return Math.max(q,te)>cd}return Math.max(t.length,e.length)>cd},[n,e.length,t.length]),Z=ge.useRef(null),A=ge.useRef(null),C=ge.useRef(null),z=ge.useRef(null),$=ge.useRef(null),H=ge.useRef(null),J=ge.useRef(void 0),ee=ge.useRef(void 0),ue=ge.useRef(void 0),re=ge.useRef(void 0),[,xe]=l.useReducer(q=>q+1,0),be=xo(W?"unified":r?"split":"unified"),he=ge.useMemo(()=>co(f),[f]),ye=ge.useMemo(()=>co(m),[m]);l.useLayoutEffect(()=>{const q=Z.current;if(!q)return;const te=q.querySelector("diffs-container");if(!te)return;const ne=u?ye:he,oe=(Ge,Fe)=>Ge.colors?.[Fe],Ae=oe(he,"terminal.ansiGreen"),je=oe(he,"terminal.ansiRed"),Ie=oe(he,"terminal.ansiBlue"),Te=oe(ye,"terminal.ansiGreen"),Me=oe(ye,"terminal.ansiRed"),He=oe(ye,"terminal.ansiBlue");te.style.setProperty("--shiki-light",he.fg),te.style.setProperty("--shiki-light-bg",he.bg),Ae&&te.style.setProperty("--shiki-light-addition-color",Ae),je&&te.style.setProperty("--shiki-light-deletion-color",je),Ie&&te.style.setProperty("--shiki-light-modified-color",Ie),te.style.setProperty("--shiki-dark",ye.fg),te.style.setProperty("--shiki-dark-bg",ye.bg),Te&&te.style.setProperty("--shiki-dark-addition-color",Te),Me&&te.style.setProperty("--shiki-dark-deletion-color",Me),He&&te.style.setProperty("--shiki-dark-modified-color",He),te.style.setProperty("--diffs-bg",ne.bg),te.style.setProperty("--diffs-fg",ne.fg);const Ve=u?Te:Ae,Ue=u?Me:je,ze=u?He:Ie;Ve&&te.style.setProperty("--diffs-addition-color-override",Ve),Ue&&te.style.setProperty("--diffs-deletion-color-override",Ue),ze&&te.style.setProperty("--diffs-modified-color-override",ze);const Be=te.shadowRoot?.querySelector("pre");Be&&(Be.style.setProperty("--shiki-light",he.fg),Be.style.setProperty("--shiki-light-bg",he.bg),Ae&&Be.style.setProperty("--shiki-light-addition-color",Ae),je&&Be.style.setProperty("--shiki-light-deletion-color",je),Ie&&Be.style.setProperty("--shiki-light-modified-color",Ie),Be.style.setProperty("--shiki-dark",ye.fg),Be.style.setProperty("--shiki-dark-bg",ye.bg),Te&&Be.style.setProperty("--shiki-dark-addition-color",Te),Me&&Be.style.setProperty("--shiki-dark-deletion-color",Me),He&&Be.style.setProperty("--shiki-dark-modified-color",He),Be.style.setProperty("--diffs-bg",ne.bg),Be.style.setProperty("--diffs-fg",ne.fg),Ve&&Be.style.setProperty("--diffs-addition-color-override",Ve),Ue&&Be.style.setProperty("--diffs-deletion-color-override",Ue),ze&&Be.style.setProperty("--diffs-modified-color-override",ze))},[ye,S,u,he]);const fe=ge.useMemo(()=>({theme:{dark:m.metadata.id,light:f.metadata.id},themeType:u?"dark":"light",diffStyle:r?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info-basic",lineDiffType:"none",maxLineDiffLength:W?0:1e3,maxLineLengthForHighlighting:W?1:1e3,tokenizeMaxLineLength:W?1:1e3,collapsedContextThreshold:0,expansionLineCount:20,overflow:o?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:c,enableHoverUtility:!1,onLineSelected:c?M:void 0,unsafeCSS:Ej,renderAnnotation:c?V:void 0}),[m.metadata.id,c,u,W,f.metadata.id,r,o,M,V]),ae=ge.useMemo(()=>c?Cj({drafts:g,editingDraftId:F,selection:x}):[],[F,c,g,x]),ce=ge.useRef(ae);if(ge.useEffect(()=>{ce.current=ae},[ae]),ge.useEffect(()=>{const q=A.current;return()=>{C.current?.cleanUp(),C.current=null,z.current?.release(),z.current=null,$.current=null,H.current=null,J.current=void 0,ee.current=void 0,ue.current=void 0,re.current=void 0,q&&(q.innerHTML="")}},[]),ge.useEffect(()=>{if(typeof window>"u")return;const q=A.current,te=Z.current;if(!q||!be)return;const ne=Fj(te,q);let oe=z.current;oe||(oe=Kj(q),z.current=oe),z.current=oe;const Ae=oe?.virtualizer??null,je=n?void 0:{name:i||"",contents:t,lang:a,cacheKey:`old:${S}:${i}:${dd(t)}`},Ie=n?void 0:{name:i||"",contents:e,lang:a,cacheKey:`new:${S}:${i}:${dd(e)}`},Te=n?ee.current!==n:ee.current!==void 0||!je||!Ie||!ue.current||!re.current||!Yo(ue.current,je)||!Yo(re.current,Ie),Me=C.current,He=!!(Me&&($.current!==Ae||H.current!==be||Ae&&(J.current!==fe.hunkSeparators||Te)));He&&(Me?.cleanUp(),C.current=null,q.innerHTML="");let Ve=C.current;const Ue=!He&&Me?!Rm(Me.options,fe):!1;if(Ve?Ve.setOptions(fe):(Ve=oe?new Dm(fe,oe.virtualizer,zj,be):new Mm(fe,be),C.current=Ve,T.current=null),$.current=Ae,H.current=be,J.current=Ae?fe.hunkSeparators:void 0,ee.current=n,ue.current=je,re.current=Ie,n)Ve.render({fileDiff:n,forceRender:Ue,lineAnnotations:ce.current,containerWrapper:q});else{if(!je||!Ie)return;Ve.render({oldFile:je,newFile:Ie,forceRender:Ue,lineAnnotations:ce.current,containerWrapper:q})}const ze=Oj(q,()=>{ne(),Uj(Ve,oe,xe)});return()=>{ze(),ne()}},[S,n,i,a,e,fe,t,be]),ge.useEffect(()=>{const q=C.current;if(q){try{q.setLineAnnotations(ae)}catch(te){console.error("Failed to apply diff line annotations",te);try{q.setLineAnnotations([])}catch{}}requestAnimationFrame(()=>{if(C.current===q){try{q.rerender()}catch{}xe()}})}},[ae]),ge.useEffect(()=>{const q=C.current;if(!q||x!==null)return;const te=T.current;if(!Dj(x,te))try{k.current=!0,q.setSelectedLines(x),T.current=x}catch{}finally{k.current=!1}},[x]),ge.useEffect(()=>{if(!c)return;const q=A.current;if(!q)return;let te=null,ne=()=>{};const oe=()=>{const je=q.querySelector("diffs-container")?.shadowRoot;if(!je){te=requestAnimationFrame(oe);return}const Ie=Te=>{if(!(Te instanceof MouseEvent)||Te.button!==0||!(Te.target instanceof Element))return;const Me=Te.target.closest("[data-column-number]");if(!(Me instanceof HTMLElement))return;const He=Me.getAttribute("data-column-number"),Ve=He?parseInt(He,10):NaN;if(Number.isNaN(Ve))return;const Ue=X(Me);M({start:Ve,end:Ve,side:Ue}),Te.preventDefault(),Te.stopPropagation()};je.addEventListener("click",Ie,!0),ne=()=>{je.removeEventListener("click",Ie,!0)}};return oe(),()=>{te!==null&&cancelAnimationFrame(te),ne()}},[S,c,i,M,X]),ge.useEffect(()=>{const q=A.current;if(!q)return;let te=null,ne=null;const Ae=setTimeout(()=>{const je=q.querySelector("diffs-container");if(!(je instanceof HTMLElement))return;const Ie=je.shadowRoot;te=new MutationObserver(()=>{ne&&cancelAnimationFrame(ne),ne=requestAnimationFrame(()=>{xe(),ne=null})}),te.observe(je,{childList:!0,subtree:!0}),Ie&&te.observe(Ie,{childList:!0,subtree:!0})},100);return()=>{clearTimeout(Ae),ne&&cancelAnimationFrame(ne),te?.disconnect()}},[S,i]),typeof window>"u")return null;const pe=c?s.jsx(Pj,{diffRootRef:Z,drafts:g,selection:x,editingDraftId:F,commentText:N,onTextChange:P,fileLabel:i?.split("/").pop()??"",onSave:U,onCancel:O,onEdit:q=>{Y({start:q.startLine,end:q.endLine,side:q.side==="original"?"deletions":"additions"}),y(q)},onDelete:R}):null;return d==="fill"?s.jsx("div",{className:le("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(Bs,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,"data-diff-virtual-content":!0,children:s.jsx("div",{ref:Z,className:"size-full relative",children:s.jsx("div",{ref:A,className:"size-full"})})}),pe]})}):s.jsxs("div",{className:le("relative","w-full"),children:[s.jsx("div",{ref:Z,className:"pierre-diff-wrapper w-full overflow-x-auto overflow-y-visible relative",children:s.jsx("div",{ref:A,className:"w-full"})}),pe]})},_j=()=>{const t=Ye.c(13),[e,n]=ge.useState(!1);let a,i;t[0]===Symbol.for("react.memo_cache_sentinel")?(a=()=>{n(ss())},i=[],t[0]=a,t[1]=i):(a=t[0],i=t[1]),ge.useEffect(a,i);let r;t[2]!==e?(r=async m=>e?await qg(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 Jg():{success:!0},t[4]=e,t[5]=d):d=t[5];const c=d;let p;t[6]!==e?(p=async m=>e?await Qg():{success:!0},t[6]=e,t[7]=p):p=t[7];const u=p;let f;return t[8]!==e||t[9]!==o||t[10]!==c||t[11]!==u?(f={isDesktop:e,requestAccess:o,startAccessing:c,stopAccessing:u},t[8]=e,t[9]=o,t[10]=c,t[11]=u,t[12]=f):f=t[12],f},$j=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Vj=({currentBranch:t,localBranches:e,remoteBranches:n,branchInfo:a,onCheckout:i,onCreate:r,remotes:o=[],disabled:d=!1})=>{const{t:c}=it(),[p,u]=l.useState(!1),[f,m]=l.useState(""),[b,h]=l.useState(!1),[g,x]=l.useState(!1),[v,N]=l.useState(""),[P,F]=l.useState(!1),w=l.useRef(null),j=l.useCallback(U=>{U.stopPropagation()},[]),y=o.length>1,R=l.useMemo(()=>$j(v),[v]),_=l.useMemo(()=>{const U=f.toLowerCase();return U?e.filter(Y=>Y.toLowerCase().includes(U)):e},[f,e]),B=l.useMemo(()=>{const U=f.toLowerCase();return U?n.filter(Y=>Y.toLowerCase().includes(U)):n},[f,n]),D=U=>{if(U===t){u(!1);return}i(U),u(!1),m("")},k=()=>{h(!0),setTimeout(()=>w.current?.focus(),50)},T=async()=>{if(!(!R||P)){if(y){x(!0);return}F(!0);try{await r(R,o[0]),N(""),h(!1),u(!1)}finally{F(!1)}}},M=async U=>{if(!(!R||P)){F(!0);try{await r(R,U),N(""),h(!1),x(!1),u(!1)}finally{F(!1)}}},O=()=>{x(!1)},V=()=>{N(""),h(!1),x(!1)};return l.useEffect(()=>{p||(m(""),h(!1),x(!1),N(""))},[p]),s.jsxs(ws,{open:p,onOpenChange:u,children:[s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx(ys,{asChild:!0,children:s.jsxs(Q,{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(L,{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(L,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),s.jsx(Ds,{sideOffset:8,children:c("gitView.branch.currentBranchTooltip")})]}),s.jsx(vs,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:s.jsxs(mo,{className:"h-full min-h-0",children:[s.jsx(po,{placeholder:c("gitView.branch.searchPlaceholder"),value:f,onValueChange:m,onKeyDown:j}),s.jsxs(go,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[s.jsx(fo,{children:c("gitView.branch.empty")}),s.jsx(wn,{children:g?s.jsxs("div",{className:"px-2 py-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("button",{type:"button",onClick:O,disabled:P,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:s.jsx(L,{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:R})," ",c("gitView.branch.pushToSuffix")]})]}),s.jsx("div",{className:"flex flex-col gap-1",children:o.map(U=>s.jsxs("button",{type:"button",onClick:()=>M(U),disabled:P,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:[P?s.jsx(L,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,U.name]}),s.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:U.pushUrl})]},U.name))})]}):b?s.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[s.jsx("input",{ref:w,placeholder:c("gitView.branch.newBranchPlaceholder"),value:v,onChange:U=>N(U.target.value),onClick:U=>U.stopPropagation(),onKeyDown:U=>{j(U),U.key==="Enter"?(U.preventDefault(),T()):U.key==="Escape"&&(U.preventDefault(),V())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"button",onClick:T,disabled:!R||P,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:P?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{name:"add",className:"size-4"})}),s.jsx("button",{type:"button",onClick:V,disabled:P,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:s.jsx(L,{name:"close",className:"size-4"})})]}):s.jsxs(Xs,{onSelect:k,children:[s.jsx(L,{name:"add",className:"size-4"}),s.jsx("span",{children:c("gitView.branch.create")})]})}),s.jsx(Sa,{}),s.jsxs(wn,{heading:c("gitView.branch.localBranches"),children:[_.map(U=>s.jsxs(Xs,{onSelect:()=>D(U),children:[s.jsxs("span",{className:"flex flex-1 flex-col",children:[s.jsx("span",{className:"typography-ui-label text-foreground",children:U}),(a?.[U]?.ahead||a?.[U]?.behind)&&s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[a[U].ahead||0," ahead ·"," ",a[U].behind||0," behind"]})]}),t===U&&s.jsx("span",{className:"typography-micro text-primary",children:c("gitView.branch.currentBadge")})]},`local-${U}`)),_.length===0&&s.jsx(Xs,{disabled:!0,className:"justify-center",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:c("gitView.branch.noLocalBranches")})})]}),s.jsx(Sa,{}),s.jsxs(wn,{heading:c("gitView.branch.remoteBranches"),children:[B.map(U=>s.jsx(Xs,{onSelect:()=>D(U),children:s.jsx("span",{className:"typography-ui-label text-foreground",children:U})},`remote-${U}`)),B.length===0&&s.jsx(Xs,{disabled:!0,className:"justify-center",children:s.jsx("span",{className:"typography-meta text-muted-foreground",children:c("gitView.branch.noRemoteBranches")})})]})]})]})})]})},Hj=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Wj=({currentBranch:t,onRename:e,showEditButton:n=!0})=>{const{t:a}=it(),[i,r]=l.useState(!1),[o,d]=l.useState(t||""),[c,p]=l.useState(!1),u=l.useRef(null),f=()=>{!t||!e||(d(t),r(!0),setTimeout(()=>u.current?.focus(),0))},m=async()=>{if(!t||!e||!o.trim())return;const g=Hj(o);if(g===t){r(!1);return}p(!0);try{await e(t,g),r(!1),d("")}finally{p(!1)}},b=()=>{r(!1),d("")},h=g=>{g.key==="Enter"?(g.preventDefault(),m()):g.key==="Escape"&&(g.preventDefault(),b())};return i?s.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:s.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:g=>{g.preventDefault(),m()},children:[s.jsx(L,{name:"git-branch",className:"size-4 text-primary"}),s.jsx("input",{ref:u,value:o,onChange:g=>d(g.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:a("gitView.branch.namePlaceholder"),onKeyDown: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(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:b,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(L,{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(L,{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(Q,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:a("gitView.branch.renameTitle"),children:s.jsx(L,{name:"edit",className:"size-4"})})]})]})},Gj={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},qj={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 Su(t){return t&&qj[t]||"var(--primary)"}const ud=t=>{const e=Ye.c(8),{icon:n,className:a,colorToken:i}=t,r=Gj[n??"branch"]??"user-3";let o;e[0]!==i?(o=Su(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(L,{name:r,className:a,style:d}),e[4]=a,e[5]=r,e[6]=d,e[7]=c):c=e[7],c},Cu=t=>{const e=Ye.c(35),{activeProfile:n,identities:a,onSelect:i,isApplying:r,iconOnly:o}=t,d=o===void 0?!1:o,{t:c}=it(),p=r||a.length===0,u=n?.color;let f;e[0]!==u?(f=Su(u),e[0]=u,e[1]=f):f=e[1];let m;e[2]!==f?(m={color:f},e[2]=f,e[3]=m):m=e[3];let b;e[4]!==n?.color||e[5]!==n?.icon||e[6]!==r?(b=r?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(ud,{icon:n?.icon,colorToken:n?.color,className:"size-4"}),e[4]=n?.color,e[5]=n?.icon,e[6]=r,e[7]=b):b=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 g;e[12]===Symbol.for("react.memo_cache_sentinel")?(g=s.jsx(L,{name:"arrow-down-s",className:"size-4 opacity-60"}),e[12]=g):g=e[12];let x;e[13]!==p||e[14]!==m||e[15]!==b||e[16]!==h?(x=s.jsx(As,{asChild:!0,children:s.jsx(ys,{asChild:!0,children:s.jsxs(Q,{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:[b,h,g]})})}),e[13]=p,e[14]=m,e[15]=b,e[16]=h,e[17]=x):x=e[17];let v;e[18]!==c?(v=c("gitView.header.identityTooltip"),e[18]=c,e[19]=v):v=e[19];let N;e[20]!==v?(N=s.jsx(Ds,{sideOffset:8,children:v}),e[20]=v,e[21]=N):N=e[21];let P;e[22]!==N||e[23]!==x?(P=s.jsxs(Ps,{children:[x,N]}),e[22]=N,e[23]=x,e[24]=P):P=e[24];let F;e[25]!==n?.id||e[26]!==a||e[27]!==i||e[28]!==c?(F=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(y=>{const R=n?.id===y.id;return s.jsx(bs,{onSelect:()=>i(y),children:s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(ud,{icon:y.icon,colorToken:y.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:y.name}),s.jsx("span",{className:"typography-meta text-muted-foreground",children:y.userEmail})]}),R?s.jsx(L,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},y.id)}),e[25]=n?.id,e[26]=a,e[27]=i,e[28]=c,e[29]=F):F=e[29];let w;e[30]!==F?(w=s.jsx(vs,{align:"end",className:"w-64",children:F}),e[30]=F,e[31]=w):w=e[31];let j;return e[32]!==P||e[33]!==w?(j=s.jsxs(ws,{children:[P,w]}),e[32]=P,e[33]=w,e[34]=j):j=e[34],j},Jj=t=>{const e=Ye.c(21),{comparison:n,trackingBranch:a,tooltipDelayMs:i}=t,r=i===void 0?1e3:i,{t:o}=it(),d=`${n.remote}/${n.branch}`,c=n.ahead===0&&n.behind===0;let p;e[0]!==o||e[1]!==d||e[2]!==a?(p=a?o("gitView.header.upstreamTooltipTracking",{target:d,tracking:a}):o("gitView.header.upstreamTooltip",{target:d}),e[0]=o,e[1]=d,e[2]=a,e[3]=p):p=e[3];const u=p;let f;e[4]===Symbol.for("react.memo_cache_sentinel")?(f=s.jsx(L,{name:"git-branch",className:"size-3.5 shrink-0"}),e[4]=f):f=e[4];let m;e[5]!==d?(m=s.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:d}),e[5]=d,e[6]=m):m=e[6];let b;e[7]!==n.ahead||e[8]!==n.behind||e[9]!==c||e[10]!==o?(b=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]=b):b=e[11];let h;e[12]!==m||e[13]!==b?(h=s.jsx(As,{asChild:!0,children:s.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[f,m,b]})}),e[12]=m,e[13]=b,e[14]=h):h=e[14];let g;e[15]!==u?(g=s.jsx(Ds,{sideOffset:8,children:u}),e[15]=u,e[16]=g):g=e[16];let x;return e[17]!==h||e[18]!==g||e[19]!==r?(x=s.jsxs(Ps,{delayDuration:r,children:[h,g]}),e[17]=h,e[18]=g,e[19]=r,e[20]=x):x=e[20],x},sN=t=>{const e=Ye.c(67),{status:n,localBranches:a,remoteBranches:i,branchInfo:r,syncAction:o,remotes:d,onFetch:c,onSync:p,onRemoveRemote:u,removingRemoteName:f,onCheckoutBranch:m,onCreateBranch:b,onRenameBranch:h,activeIdentityProfile:g,availableIdentities:x,onSelectIdentity:v,isApplyingIdentity:N,isWorktreeMode:P,onOpenHistory:F,onOpenGraph:w,onOpenStashes:j,onOpenUpdateBranch:y,onOpenReintegrateCommits:R,pullRequest:_,prChecks:B,onOpenPullRequest:D}=t,{t:k}=it();if(!n)return null;let T;e[0]!==w||e[1]!==F||e[2]!==R||e[3]!==j||e[4]!==y||e[5]!==k?(T=F||w||j||y?s.jsxs(ws,{children:[s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsx(ys,{asChild:!0,children:s.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":k("gitView.header.repositoryViews"),children:s.jsx(L,{name:"more-fill",className:"size-4"})})})}),s.jsx(Ds,{sideOffset:8,children:k("gitView.header.repositoryViews")})]}),s.jsxs(vs,{align:"end",children:[F?s.jsxs(bs,{onSelect:F,children:[s.jsx(L,{name:"history",className:"size-4"}),k("gitView.history.title")]}):null,w?s.jsxs(bs,{onSelect:w,children:[s.jsx(L,{name:"git-branch",className:"size-4"}),k("gitView.graph.title")]}):null,j?s.jsxs(bs,{onSelect:j,children:[s.jsx(L,{name:"archive-stack",className:"size-4"}),k("gitView.stashes.title")]}):null,y?s.jsxs(bs,{onSelect:y,children:[s.jsx(L,{name:"git-merge",className:"size-4"}),k("gitView.header.updateBranch")]}):null,R?s.jsxs(bs,{onSelect:R,children:[s.jsx(L,{name:"split-cells-horizontal",className:"size-4"}),k("gitView.integrate.title")]}):null]})]}):null,e[0]=w,e[1]=F,e[2]=R,e[3]=j,e[4]=y,e[5]=k,e[6]=T):T=e[6];let M;e[7]!==T?(M=s.jsx("div",{className:"flex items-center gap-1 shrink-0",children:T}),e[7]=T,e[8]=M):M=e[8];const O=M,V=B?B.state==="success"?"var(--status-success)":B.state==="failure"?"var(--status-error)":"var(--status-warning)":null,U=_?_.state==="merged"?"merged":_.state==="closed"?"closed":_.draft?"draft":B?.state==="failure"||_.mergeable===!1||_.mergeableState==="blocked"||_.mergeableState==="dirty"?"blocked":"open":null;let Y;e[9]!==D||e[10]!==V||e[11]!==U||e[12]!==_||e[13]!==k?(Y=_&&D?s.jsxs(Ps,{children:[s.jsx(As,{asChild:!0,children:s.jsxs(Q,{variant:"ghost",size:"sm",onClick:D,className:"h-8 gap-1.5 px-2 typography-micro",children:[s.jsx(L,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${U})`}}),s.jsx("span",{className:"tabular-nums text-foreground/80",children:k("gitView.pr.numberLabel",{number:_.number})}),V?s.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:V}}):null]})}),s.jsx(Ds,{sideOffset:8,children:k("gitView.header.openPullRequest")})]}):null,e[9]=D,e[10]=V,e[11]=U,e[12]=_,e[13]=k,e[14]=Y):Y=e[14];const X=Y,S=!n;let W;e[15]!==n.tracking?(W=n.tracking?.split("/")[0],e[15]=n.tracking,e[16]=W):W=e[16];const Z=(n.files?.length??0)>0;let A;e[17]!==c||e[18]!==u||e[19]!==p||e[20]!==d||e[21]!==f||e[22]!==n.ahead||e[23]!==n.behind||e[24]!==o||e[25]!==S||e[26]!==W||e[27]!==Z?(A=s.jsx(dj,{syncAction:o,remotes:d,onFetch:c,onSync:p,onRemoveRemote:u,removingRemoteName:f,disabled:S,iconOnly:!0,aheadCount:n.ahead,behindCount:n.behind,trackingRemoteName:W,hasUncommittedChanges:Z}),e[17]=c,e[18]=u,e[19]=p,e[20]=d,e[21]=f,e[22]=n.ahead,e[23]=n.behind,e[24]=o,e[25]=S,e[26]=W,e[27]=Z,e[28]=A):A=e[28];const C=A;let z;e[29]!==n.tracking||e[30]!==n.upstreamComparison?(z=n.upstreamComparison?s.jsx(Jj,{comparison:n.upstreamComparison,trackingBranch:n.tracking,tooltipDelayMs:1e3}):null,e[29]=n.tracking,e[30]=n.upstreamComparison,e[31]=z):z=e[31];const $=z;let H;e[32]!==g||e[33]!==x||e[34]!==N||e[35]!==v?(H=s.jsx(Cu,{activeProfile:g,identities:x,onSelect:v,isApplying:N,iconOnly:!0}),e[32]=g,e[33]=x,e[34]=N,e[35]=v,e[36]=H):H=e[36];const J=H;let ee;e[37]!==r||e[38]!==P||e[39]!==a||e[40]!==m||e[41]!==b||e[42]!==h||e[43]!==i||e[44]!==d||e[45]!==n.current?(ee=s.jsx("div",{className:"min-w-0 flex-1",children:P?s.jsx(Wj,{currentBranch:n.current,onRename:h}):s.jsx(Vj,{currentBranch:n.current,localBranches:a,remoteBranches:i,branchInfo:r,onCheckout:m,onCreate:b,remotes:d})}),e[37]=r,e[38]=P,e[39]=a,e[40]=m,e[41]=b,e[42]=h,e[43]=i,e[44]=d,e[45]=n.current,e[46]=ee):ee=e[46];let ue;e[47]!==J?(ue=s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:J}),e[47]=J,e[48]=ue):ue=e[48];let re;e[49]!==ee||e[50]!==ue?(re=s.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[ee,ue]}),e[49]=ee,e[50]=ue,e[51]=re):re=e[51];let xe;e[52]!==X?(xe=X?s.jsx("div",{className:"shrink-0",children:X}):null,e[52]=X,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 he;e[55]!==$?(he=$?s.jsx("div",{className:"min-w-0 shrink",children:$}):null,e[55]=$,e[56]=he):he=e[56];let ye;e[57]!==C?(ye=s.jsx("div",{className:"shrink-0",children:C}),e[57]=C,e[58]=ye):ye=e[58];let fe;e[59]!==O||e[60]!==xe||e[61]!==he||e[62]!==ye?(fe=s.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[xe,be,he,O,ye]}),e[59]=O,e[60]=xe,e[61]=he,e[62]=ye,e[63]=fe):fe=e[63];let ae;return e[64]!==re||e[65]!==fe?(ae=s.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[re,fe]}),e[64]=re,e[65]=fe,e[66]=ae):ae=e[66],ae},Qj=t=>t==="/",Zi=t=>t.replace(/\\/g,"/"),Ko=t=>{if(!t||Qj(t))return t;let e=t;for(;e.length>1&&e.endsWith("/");)e=e.slice(0,-1);return e},Ea=t=>t.endsWith("/"),Yj=t=>{const e=t.trim();return!e||Ea(e)?e:`${e}/`},Uo=t=>t.lastIndexOf("/"),Iu=t=>{if(Ea(t))return t;const e=Uo(t);return e<0?t:t.slice(0,e+1)},Xj=t=>{const e=Uo(t);return t.slice(e+1)},Pu=t=>{const e=Ko(t.trim());if(!e||e==="~"||e==="~/"||e==="/")return null;const n=Uo(e);return n<0?null:e.startsWith("~/")&&n<=1?"~/":n===0?"/":`${e.slice(0,n)}/`},Zj=t=>Ea(t)&&Pu(t)!==null,ek=(t,e)=>`${Iu(t)}${e}/`,Qn=t=>{if(!t)return null;const e=Ko(Zi(t.trim()));return e?e.toLowerCase():null},md=(t,e)=>{const n=t.trim();return n==="~"?e:n.startsWith("~/")?`${e}${n.slice(1)}`:n},tk=t=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?t.metaKey&&!t.ctrlKey:t.ctrlKey&&!t.metaKey,ao=t=>{if(!t)return;t.focus({preventScroll:!0});const e=t.value.length;t.setSelectionRange(e,e),t.scrollLeft=t.scrollWidth},sk=async()=>{try{const t=await gt("/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 Zi(e.home.trim())}}catch{}return Is.getFilesystemHome().catch(()=>null)},nN=({open:t,onOpenChange:e})=>{const{t:n}=it(),a=Ls(I=>I.homeDirectory),i=rs(I=>I.projects),r=rs(I=>I.addProject),o=Os(I=>I.profiles),d=Os(I=>I.globalIdentity),c=Os(I=>I.defaultGitIdentityId),p=Os(I=>I.loadProfiles),u=Os(I=>I.loadGlobalIdentity),f=Os(I=>I.loadDefaultGitIdentityId),{isDesktop:m,requestAccess:b,startAccessing:h}=_j(),{isMobile:g}=_s(),x=l.useRef(null),v=l.useRef(null),N=l.useRef(new Map),[P,F]=l.useState(""),[w,j]=l.useState("~/"),[y,R]=l.useState([]),[_,B]=l.useState(!1),[D,k]=l.useState(!1),[T,M]=l.useState(0),[O,V]=l.useState(!1),[U,Y]=l.useState(!1),[X,S]=l.useState(0),[W,Z]=l.useState(!1),[A,C]=l.useState(""),[z,$]=l.useState(null),[H,J]=l.useState(!1),ee=P||a,ue=l.useMemo(()=>new Set(i.map(I=>Qn(I.path)).filter(I=>!!I)),[i]);l.useEffect(()=>{if(!t)return;j("~/"),R([]),M(0),V(!1),Y(!1),Z(!1),C(""),$(null),J(!1),requestAnimationFrame(()=>ao(x.current));let I=!1;return(async()=>{const Le=await sk();I||(F(Le||a||""),requestAnimationFrame(()=>ao(x.current)))})(),()=>{I=!0}},[a,t]),l.useEffect(()=>{t&&(p(),u(),f())},[f,p,u,t]);const re=l.useMemo(()=>{const I=new Map;d&&I.set(d.id,d);for(const Ee of o)I.set(Ee.id,Ee);return Array.from(I.values())},[o,d]);l.useEffect(()=>{if(!t||!W||z!==null)return;const I=typeof c=="string"?c.trim():"";if(I&&re.some(Le=>Le.id===I)){$(I);return}const Ee=re.find(Le=>Le.authType==="ssh"||Le.sshKey);Ee&&$(Ee.id)},[re,c,W,t,z]);const xe=l.useMemo(()=>re.find(I=>I.id===z)??null,[re,z]),be=l.useMemo(()=>Iu(w),[w]),he=l.useMemo(()=>Ea(w)?"":Xj(w),[w]),ye=l.useMemo(()=>ee?md(be,ee):"",[be,ee]);l.useEffect(()=>{if(!t||!ye){R([]);return}let I=!1;return B(!0),k(!1),Is.listLocalDirectory(ye).then(Ee=>{if(I)return;k(!1);const Le=Ee.filter(_e=>_e.isDirectory).map(_e=>({name:_e.name,path:Zi(_e.path)})).sort((_e,Xe)=>_e.name.localeCompare(Xe.name));R(Le)}).catch(()=>{I||(R([]),k(!0))}).finally(()=>{I||B(!1)}),()=>{I=!0}},[ye,t]);const fe=l.useMemo(()=>{const I=he.toLowerCase(),Ee=H||he.startsWith(".");return y.filter(Le=>Le.name.toLowerCase().startsWith(I)&&(Ee||!Le.name.startsWith(".")))},[he,y,H]),ae=l.useMemo(()=>{const I=[];Zj(w)&&I.push({type:"up",value:"browse:up",name:"..",path:Pu(w)});for(const Ee of fe){const Le=Qn(Ee.path);I.push({type:"directory",value:`browse:${Ee.path}`,name:Ee.name,path:Ee.path,disabled:!!(Le&&ue.has(Le))})}return I},[ue,fe,w]);l.useEffect(()=>{M(0)},[w,ae.length]);const ce=l.useMemo(()=>ee?Ko(md(w,ee)):"",[ee,w]),pe=Qn(ce),q=!!(pe&&ue.has(pe)),te=l.useMemo(()=>he?fe.find(I=>I.name===he)??null:null,[he,fe]),ne=!!(ce&&!q&&(Ea(w)&&D||!Ea(w)&&he.trim().length>0&&te===null)),oe=!O&&!U&&!q&&!!ce,Ae=oe&&A.trim().length>0,je=ae[T]??null,Ie=!!(je&&(je.type==="up"||je.type==="directory"&&!je.disabled)),Te=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Me=n(q?"directoryExplorerDialog.actions.alreadyAdded":W?O?"directoryExplorerDialog.actions.cloning":"directoryExplorerDialog.actions.cloneAndAdd":O?"directoryExplorerDialog.actions.adding":ne?"directoryExplorerDialog.actions.createAndAdd":"directoryExplorerDialog.actions.addProject");l.useLayoutEffect(()=>{const I=v.current;if(!I)return;const Ee=()=>S(Math.ceil(I.getBoundingClientRect().width));if(Ee(),typeof ResizeObserver>"u")return;const Le=new ResizeObserver(Ee);return Le.observe(I),()=>Le.disconnect()},[Me]),l.useLayoutEffect(()=>{const I=x.current;I&&(I.scrollLeft=I.scrollWidth)},[X,w]),l.useLayoutEffect(()=>{t&&ao(x.current)},[t]),l.useLayoutEffect(()=>{const I=ae[T];I&&N.current.get(I.value)?.scrollIntoView({block:"nearest"})},[T,ae]);const He=l.useCallback(()=>{e(!1)},[e]),Ve=l.useCallback((I,Ee)=>{I.stopPropagation();const Le=Qn(Ee);if(Le&&ue.has(Le))return;r(Ee)||G.error(n("directoryExplorerDialog.toast.failedToAddProject"),{description:n("directoryExplorerDialog.toast.selectValidDirectoryPath")})},[r,ue,n]),Ue=l.useCallback(async I=>{if(!I||O)return;const Ee=Qn(I);if(Ee&&ue.has(Ee))return;let Le=I;V(!0);try{const _e=!W&&ne&&Qn(I)===Qn(ce);if(W){const ct=A.trim();if(!ct){G.error(n("directoryExplorerDialog.toast.cloneUrlRequired"));return}Le=(await Is.cloneRepository({remoteUrl:ct,destinationPath:I,gitIdentityId:xe?.id??null})).path}else _e&&await Is.createDirectory(I);if(!r(Le)){G.error(n("directoryExplorerDialog.toast.failedToAddProject"),{description:n("directoryExplorerDialog.toast.selectValidDirectoryPath")});return}He()}catch(_e){G.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:_e instanceof Error?_e.message:n("directoryExplorerDialog.toast.unknownError")})}finally{V(!1)}},[r,ue,A,He,W,O,xe?.id,ne,ce,n]),ze=l.useCallback(I=>{j(Yj(I))},[]),Be=l.useCallback(I=>{j(ek(w,I.name))},[w]),Ge=l.useCallback(I=>{if(I){if(I.type==="up"){I.path&&ze(I.path);return}I.disabled||Be(I)}},[ze,Be]),Fe=l.useCallback(async()=>{if(!(!m||U)){Y(!0);try{const I=await b(ce);if(!I.success||!I.path){I.error&&I.error!=="Directory selection cancelled"&&G.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:I.error});return}const Ee=await h(I.path);if(!Ee.success){G.error(n("directoryExplorerDialog.toast.failedToOpenDirectory"),{description:Ee.error||n("directoryExplorerDialog.toast.desktopCouldNotGrantAccess")});return}await Ue(I.path)}catch(I){G.error(n("directoryExplorerDialog.toast.failedToSelectDirectory"),{description:I instanceof Error?I.message:n("directoryExplorerDialog.toast.unknownError")})}finally{Y(!1)}}},[Ue,m,U,b,h,n,ce]),ve=l.useCallback(I=>{if(I.key==="ArrowDown"){I.preventDefault(),M(Ee=>Math.min(ae.length-1,Ee+1));return}if(I.key==="ArrowUp"){I.preventDefault(),M(Ee=>Math.max(0,Ee-1));return}if(I.key==="Enter"){if(I.preventDefault(),tk(I)){Ue(ce);return}Ie&&Ge(je);return}I.key==="Backspace"&&w===""&&(I.preventDefault(),He())},[Ge,Ue,He,Ie,je,w,ae.length,ce]),De=s.jsxs("button",{type:"button",onClick:()=>J(I=>!I),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:[H?s.jsx(L,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(L,{name:"checkbox-blank",className:"h-4 w-4"}),n("directoryExplorerDialog.toggle.showHidden")]}),Ke=s.jsxs("div",{className:"px-2.5 py-1.5",children:[W?s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[s.jsx(tt,{value:A,onChange:I=>C(I.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(Cu,{activeProfile:xe,identities:re,onSelect:I=>$(I.id),isApplying:O,iconOnly:!0})]}):null,s.jsxs("div",{className:"relative",children:[s.jsx(L,{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(tt,{ref:x,value:w,onChange:I=>j(Zi(I.target.value)),onKeyDown:ve,placeholder:n("directoryExplorerDialog.pathInput.placeholder"),className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",style:!g&&X>0?{paddingRight:`${X+24}px`}:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),g?null:s.jsx(Q,{ref:v,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:W?!Ae:!oe,onMouseDown:I=>I.preventDefault(),onClick:()=>{Ue(ce)},title:Me,children:Me})]})]}),We=s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:s.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[s.jsx("div",{className:"px-2 pb-1 pt-0.5 typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:n("directoryExplorerDialog.browse.directories")}),_?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:n("directoryExplorerDialog.browse.loading")}):ae.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:ae.map((I,Ee)=>{const Le=Ee===T;return s.jsxs("button",{ref:_e=>{_e?N.current.set(I.value,_e):N.current.delete(I.value)},type:"button",disabled:I.type==="directory"&&I.disabled,onMouseEnter:()=>M(Ee),onMouseDown:_e=>_e.preventDefault(),onClick:()=>Ge(I),className:le("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",Le&&"bg-interactive-selection text-interactive-selection-foreground",!Le&&"hover:bg-interactive-hover/50",I.type==="directory"&&I.disabled&&"cursor-not-allowed opacity-45 hover:bg-transparent"),children:[I.type==="up"?s.jsx(L,{name:"arrow-left-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(L,{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:I.name})}),I.type==="directory"&&I.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")}):I.type==="directory"?s.jsx("button",{type:"button",onMouseDown:_e=>_e.stopPropagation(),onClick:_e=>Ve(_e,I.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(L,{name:"add",className:"h-3.5 w-3.5"})}):null]},I.value)})})]})}),Pe=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Ke,We]}),at=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(L,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(L,{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(L,{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:Te}),s.jsx(L,{name:"corner-down-left",className:"h-3.5 w-3.5"}),n("directoryExplorerDialog.footer.add")]})]}),se=()=>s.jsxs(s.Fragment,{children:[g?null:at,s.jsxs("div",{className:le("flex w-full flex-row justify-end gap-2 sm:w-auto",g&&"justify-stretch"),children:[m?s.jsx(Q,{variant:"ghost",size:"xs",onClick:Fe,disabled:O||U||W,children:n(U?"directoryExplorerDialog.actions.openingFinder":"directoryExplorerDialog.actions.openInFinder")}):null,s.jsx(Q,{variant:"ghost",size:"xs",onClick:()=>Z(I=>!I),disabled:O||U,className:le(g&&"flex-1"),children:n(W?"directoryExplorerDialog.actions.addLocalProject":"directoryExplorerDialog.actions.cloneRepository")}),g?s.jsx(Q,{size:"xs",onClick:()=>{Ue(ce)},disabled:W?!Ae:!oe,className:"flex-1",children:Me}):null]})]});return g?s.jsx(Za,{open:t,onClose:He,title:n("directoryExplorerDialog.title"),className:"h-[88dvh] max-h-[720px] max-w-full",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:se()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:De}),Pe]})}):s.jsx(Lt,{open:t,onOpenChange:e,children:s.jsxs(Ft,{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(zt,{children:n("directoryExplorerDialog.title")}),s.jsx(qt,{className:"mt-2",children:n("directoryExplorerDialog.description")})]}),De]})}),s.jsx("div",{className:"min-h-0 flex-1 px-2 pb-0",children:Pe}),s.jsx(Zt,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:se()})]})})};function pd(t){const{localBranches:e,remoteBranches:n,query:a}=t,i=a.trim();if(!i)return{matching:[],otherLocal:e,otherRemote:n};const r=dl(e,i,u=>u),o=dl(n,i,u=>u),d=[],c=r.other,p=o.other;for(const u of r.matching)d.push({label:u,value:u,source:"local"});for(const u of o.matching)d.push({label:u,value:`remotes/${u}`,source:"remote"});return d.sort((u,f)=>{const m=u.label.localeCompare(f.label,void 0,{sensitivity:"accent"});return m!==0?m:u.source!==f.source?u.source.localeCompare(f.source):u.value.localeCompare(f.value)}),{matching:d,otherLocal:c,otherRemote:p}}const io="oc:lastWorktreeSourceBranch",nk=({mode:t,sourceBranch:e,linkedPr:n,selectedBranch:a})=>t==="existing-branch"?a||null:n?null:e||null,ak=({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 ik({open:t,onOpenChange:e,onSelect:n}){const{t:a}=it(),i=Ne(ae=>ae.isMobile),{github:r}=li(),o=kn(ae=>ae.status),d=kn(ae=>ae.hasChecked),c=Ne(ae=>ae.setSettingsDialogOpen),p=Ne(ae=>ae.setSettingsPage),u=rs(ae=>ae.getActiveProject()),f=u?.path??null,m=ge.useMemo(()=>f&&u?{id:u.id,path:f}:null,[u,f]),[b,h]=ge.useState("issues"),[g,x]=ge.useState(""),[v,N]=ge.useState([]),[P,F]=ge.useState([]),[w,j]=ge.useState(!1),[y,R]=ge.useState(!1),[_,B]=ge.useState(null),[D,k]=ge.useState(null),[T,M]=ge.useState(null),[O,V]=ge.useState(!1),[U,Y]=ge.useState(new Map),[X,S]=ge.useState(1),[W,Z]=ge.useState(!1),A=sg(g,350),C=ge.useCallback(async ae=>{if(!(!f||!r)&&!(d&&o?.connected===!1)){j(!0),B(null),S(1),Z(!1);try{if(b==="issues"&&r.issuesList){const ce=await r.issuesList(f,{page:1,query:ae});ce.connected===!1?(B(a("session.githubIntegration.error.notConnected")),N([])):(N(ce.issues??[]),S(ce.page??1),Z(!!ce.hasMore))}else if(b==="prs"&&r.prsList){const ce=await r.prsList(f,{page:1,query:ae});ce.connected===!1?(B(a("session.githubIntegration.error.notConnected")),F([])):(F(ce.prs??[]),S(ce.page??1),Z(!!ce.hasMore))}}catch(ce){B(ce instanceof Error?ce.message:a("session.githubIntegration.error.loadDataFailed"))}finally{j(!1)}}},[f,r,d,o,b,a]);ge.useEffect(()=>{if(!t||!f||d&&o?.connected===!1||!r)return;if(!A.trim()){C();return}const ae=new AbortController;j(!0),B(null),S(1),Z(!1);const ce=b==="issues"&&r.issuesList?r.issuesList(f,{page:1,query:A.trim()}):b==="prs"&&r.prsList?r.prsList(f,{page:1,query:A.trim()}):null;if(!ce){j(!1);return}return ce.then(pe=>{ae.signal.aborted||("issues"in pe?pe.connected===!1?(B(a("session.githubIntegration.error.notConnected")),N([])):(N(pe.issues??[]),S(pe.page??1),Z(!!pe.hasMore)):"prs"in pe&&(pe.connected===!1?(B(a("session.githubIntegration.error.notConnected")),F([])):(F(pe.prs??[]),S(pe.page??1),Z(!!pe.hasMore))))}).catch(pe=>{ae.signal.aborted||B(pe instanceof Error?pe.message:a("session.githubIntegration.error.loadDataFailed"))}).finally(()=>{ae.signal.aborted||j(!1)}),()=>ae.abort()},[t,f,r,d,o,b,A,C,a]);const z=ge.useCallback(async()=>{if(!(!f||!r)&&!(w||y)&&W){R(!0);try{const ae=X+1;if(b==="issues"&&r.issuesList){const ce=A.trim()?await r.issuesList(f,{page:ae,query:A.trim()}):await r.issuesList(f,{page:ae});ce.connected!==!1&&(N(pe=>[...pe,...ce.issues??[]]),S(ce.page??ae),Z(!!ce.hasMore))}else if(b==="prs"&&r.prsList){const ce=A.trim()?await r.prsList(f,{page:ae,query:A.trim()}):await r.prsList(f,{page:ae});ce.connected!==!1&&(F(pe=>[...pe,...ce.prs??[]]),S(ce.page??ae),Z(!!ce.hasMore))}}catch{}finally{R(!1)}}},[f,r,b,X,W,w,y,A]);ge.useEffect(()=>{if(!t){h("issues"),x(""),N([]),F([]),k(null),M(null),V(!1),B(null),Y(new Map),S(1),Z(!1);return}C()},[t,C]);const $=ge.useCallback(async ae=>{if(!(!m||!ae)&&!U.has(ae))try{const pe=(await Rd(m,{mode:"new",branchName:ae,worktreeName:ae})).errors.find(q=>q.code==="branch_in_use");Y(q=>new Map(q).set(ae,{isValid:!pe,error:pe?a(pe.code==="branch_exists"?"session.githubIntegration.validation.branchAlreadyExists":"session.githubIntegration.validation.branchAlreadyCheckedOut"):null}))}catch{Y(ce=>new Map(ce).set(ae,{isValid:!1,error:a("session.githubIntegration.validation.failed")}))}},[m,U,a]);ge.useEffect(()=>{!t||b!=="prs"||P.forEach(ae=>{ae.head&&$(ae.head)})},[t,b,P,$]);const H=d&&o?.connected===!0,J=()=>{p("github"),c(!0)},ee=ae=>{k(ae),M(null)},ue=ae=>{M(ae),k(null)},re=()=>{D?n({type:"issue",item:D}):T&&n({type:"pr",item:T,includeDiff:O}),e(!1)},xe=()=>{k(null),M(null),V(!1)},be=D||T&&U.get(T.head??"")?.isValid!==!1,he=ae=>ae.head?U.get(ae.head)?.isValid===!1:!0,ye=s.jsx(s.Fragment,{children:H?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"relative mt-2",children:[s.jsx(L,{name:"search",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(tt,{value:g,onChange:ae=>x(ae.target.value),placeholder:a(b==="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:[w&&s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsx(L,{name:"loader-4",className:"h-5 w-5 animate-spin text-muted-foreground"})}),_&&s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-destructive/10 text-destructive",children:[s.jsx(L,{name:"error-warning",className:"h-4 w-4"}),s.jsx("span",{className:"typography-small",children:_})]})}),!w&&!_&&b==="issues"&&s.jsxs("div",{className:"space-y-0.5 min-h-full",children:[v.length>0?v.map(ae=>s.jsx("button",{onClick:()=>ee(ae),className:le("w-full text-left px-2 py-1.5 rounded transition-colors",D?.number===ae.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:["#",ae.number]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"typography-small line-clamp-2",children:ae.title}),ae.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:[ae.sourceRepo.owner,"/",ae.sourceRepo.repo]}):null]})]})},`${ae.sourceRepo?.owner??""}-${ae.sourceRepo?.repo??""}-${ae.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")}),W&&!y&&s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{z()},className:"h-7 text-xs",children:a("session.githubIntegration.actions.loadMore")})}),y&&s.jsx("div",{className:"flex items-center justify-center py-2",children:s.jsx(L,{name:"loader-4",className:"h-4 w-4 animate-spin text-muted-foreground"})})]}),!w&&!_&&b==="prs"&&s.jsxs("div",{className:"space-y-0.5 min-h-full",children:[P.length>0?P.map(ae=>{const ce=he(ae),pe=ae.head?U.get(ae.head):void 0;return s.jsx("button",{onClick:()=>!ce&&ue(ae),disabled:ce,className:le("w-full text-left px-2 py-1.5 rounded transition-colors",T?.number===ae.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:["#",ae.number]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"typography-small line-clamp-1",children:ae.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.jsxs("span",{className:"typography-micro text-muted-foreground",children:[ae.head," → ",ae.base]}),ae.sourceRepo?.source==="upstream"?s.jsxs("span",{className:"typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info",children:[ae.sourceRepo.owner,"/",ae.sourceRepo.repo]}):null,ce&&pe?.error&&s.jsx("span",{className:"typography-micro text-destructive",children:pe.error})]})]})]})},`${ae.sourceRepo?.owner??""}-${ae.sourceRepo?.repo??""}-${ae.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")}),W&&!y&&s.jsx("div",{className:"flex justify-center pt-2",children:s.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{z()},className:"h-7 text-xs",children:a("session.githubIntegration.actions.loadMore")})}),y&&s.jsx("div",{className:"flex items-center justify-center py-2",children:s.jsx(L,{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(L,{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(Q,{onClick:J,size:"sm",children:a("session.githubIntegration.connect.action")})]})}),fe=s.jsxs("div",{className:le("w-full",i?"flex flex-col gap-2":"flex flex-row items-center"),children:[s.jsxs("div",{className:le("flex items-center gap-4",i?"w-full justify-center order-1":"flex-1"),children:[!i&&(D||T)&&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(L,{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:T?.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(L,{name:"close",className:"h-3.5 w-3.5"})})]}),b==="prs"&&T&&s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer h-8",children:[s.jsx(Pn,{checked:O,onChange:ae=>V(ae),ariaLabel:a("session.githubIntegration.includeDiffAria")}),s.jsx("span",{className:"typography-small text-foreground",children:a("session.githubIntegration.includeDiff")})]})]}),s.jsxs("div",{className:le("flex gap-2",i?"w-full order-2":"justify-end"),children:[s.jsx(Q,{variant:"outline",size:"sm",onClick:()=>e(!1),className:le(i&&"flex-1"),children:a("session.githubIntegration.actions.cancel")}),s.jsx(Q,{size:"sm",onClick:re,disabled:!be,className:le(i&&"flex-1"),children:a("session.githubIntegration.actions.select")})]})]});return s.jsx(s.Fragment,{children:i?s.jsx(Za,{open:t,title:a("session.githubIntegration.title"),onClose:()=>e(!1),footer:H?fe:void 0,renderHeader:ae=>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")}),ae]}),s.jsx("div",{className:"w-full",children:s.jsx(ia,{items:[{id:"issues",label:a("session.githubIntegration.tabs.issues"),icon:s.jsx(L,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"prs",label:a("session.githubIntegration.tabs.pullRequests"),icon:s.jsx(L,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],activeId:b,onSelect:ce=>{h(ce),x("")},variant:"active-pill",layoutMode:"fit"})}),(D||T)&&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(L,{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:T?.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(L,{name:"close",className:"h-3.5 w-3.5"})})]})]}),children:ye}):s.jsx(Lt,{open:t,onOpenChange:e,children:s.jsxs(Ft,{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(zt,{className:"flex items-center gap-2 shrink-0",children:[s.jsx(L,{name:"github",className:"h-5 w-5"}),a("session.githubIntegration.title")]}),s.jsx("div",{className:"w-[220px]",children:s.jsx(ia,{items:[{id:"issues",label:a("session.githubIntegration.tabs.issues"),icon:s.jsx(L,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"prs",label:a("session.githubIntegration.tabs.pullRequests"),icon:s.jsx(L,{name:"git-pull-request",className:"h-3.5 w-3.5"})}],activeId:b,onSelect:ae=>{h(ae),x("")},variant:"active-pill",layoutMode:"fit"})})]})}),ye,s.jsx(Zt,{className:"mt-1",children:fe})]})})})}const Xa=t=>t.trim().replace(/^refs\/heads\//,"").replace(/^heads\//,"").replace(/\s+/g,"-").replace(/^\/+|\/+$/g,""),Ss=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),rk=t=>String(t).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"pr-head",gd=(t,e,n)=>{const a=Xa(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-${rk(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}`}},ok=t=>{const e={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
|
|
173
|
+
${JSON.stringify(e,null,2)}`},lk=t=>`GitHub pull request context (JSON)
|
|
174
|
+
${JSON.stringify(t,null,2)}`;function aN({open:t,onOpenChange:e,onWorktreeCreated:n}){const{t:a}=it(),{github:i,git:r}=li(),o=Ne(se=>se.isMobile),d=kn(se=>se.status),c=kn(se=>se.hasChecked),p=rs(se=>se.getActiveProject()),u=p?.path??null,f=ge.useMemo(()=>u&&p?{id:p.id,path:u}:null,[p,u]),[m,b]=ge.useState("new-branch"),[h,g]=ge.useState({branchName:"",worktreeName:"",isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1}),[x,v]=ge.useState({selectedBranch:"",worktreeName:""}),N=ng(u),P=ag(u),F=Dd(se=>se.fetchBranches),w=ge.useMemo(()=>N?.all?N.all.filter(se=>!se.startsWith("remotes/")).sort():[],[N]),j=ge.useMemo(()=>N?.all?N.all.filter(se=>se.startsWith("remotes/")).map(se=>se.replace(/^remotes\//,"")).sort():[],[N]),y=ds(se=>se.availableWorktreesByProject),R=ge.useMemo(()=>{if(!u)return new Set;const se=y.get(u)??[];return new Set(se.map(I=>I.name))},[y,u]),_=ge.useCallback((se=10)=>{for(let I=0;I<se;I++){const Ee=Er();if(!R.has(Ee))return Ee}return`${Er()}-${Date.now().toString(36).slice(-4)}`},[R]),[B,D]=ge.useState(!1),[k,T]=ge.useState(!1),[M,O]=ge.useState(!1),[V,U]=ge.useState(!1),[Y,X]=ge.useState(!1),[S,W]=ge.useState(""),[Z,A]=ge.useState(""),C=ge.useRef(null),z=ge.useRef(null),$=ge.useRef(null),H=ge.useRef(null),J=ge.useCallback(se=>{se.stopPropagation()},[]),ee=ge.useCallback(se=>{let I=se;for(;I&&I!==document.body;){const{overflowY:Ee}=window.getComputedStyle(I);if((Ee==="auto"||Ee==="scroll")&&I.scrollHeight>I.clientHeight)return I;I=I.parentElement}return null},[]),ue=ge.useCallback(se=>{se&&(se.scrollTop=0)},[]),re=ge.useCallback(se=>{const I=se.current?.querySelector('[data-slot="command-list"]')??null;ue(I)},[ue]),xe=ge.useCallback(se=>{const I=ee(se.current);ue(I)},[ee,ue]),be=ge.useMemo(()=>pd({localBranches:w,remoteBranches:j,query:S}),[w,j,S]),he=ge.useMemo(()=>pd({localBranches:w,remoteBranches:j,query:Z}),[w,j,Z]),ye=S.trim().length>0,fe=Z.trim().length>0,ae=be.matching.length>0,ce=he.matching.length>0,pe=!!(u&&r),q=ge.useCallback(()=>{!u||!r||F(u,r)},[u,r,F]);ge.useEffect(()=>{!t||!u||!r||N?.all||F(u,r)},[t,u,r,N?.all,F]),ge.useEffect(()=>{!k&&!V&&W("")},[k,V]),ge.useEffect(()=>{!M&&!Y&&A("")},[M,Y]),ge.useEffect(()=>{k&&re(C),V&&xe($)},[k,V,S,re,xe]),ge.useEffect(()=>{M&&re(z),Y&&xe(H)},[M,Y,Z,re,xe]);const[te,ne]=ge.useState({isValidating:!1,branchError:null,worktreeError:null,touched:!1}),[oe,Ae]=ge.useState(!1),[je,Ie]=ge.useState(null),Te=ge.useCallback(()=>{const se=pt.getState(),I=se.getVisibleAgents();if(se.settingsDefaultAgent){const Ee=I.find(Le=>Le.name===se.settingsDefaultAgent);if(Ee)return Ee.name}return I.find(Ee=>Ee.name==="build")?.name||I[0]?.name},[]),Me=ge.useCallback(()=>{const se=pt.getState(),I=se.settingsDefaultModel;if(!I)return null;const Ee=Kn(I);if(!Ee)return null;const{providerId:Le,modelId:_e}=Ee;return se.getModelMetadata(Le,_e)?{providerID:Le,modelID:_e}:null},[]),He=ge.useCallback((se,I)=>{const Ee=pt.getState(),Le=Ee.settingsDefaultVariant,_e=Ee.currentProviderId===se&&Ee.currentModelId===I?Ee.currentVariant:void 0,ut=Ee.providers.find(lt=>lt.id===se)?.models.find(lt=>lt.id===I)?.variants;if(!ut)return Le||_e||void 0;if(Le&&Object.prototype.hasOwnProperty.call(ut,Le))return Le;if(_e&&Object.prototype.hasOwnProperty.call(ut,_e))return _e},[]),Ve=ge.useCallback(async se=>{if(!u||!i)return;const I=pt.getState(),Ee=ig.getState().lastUsedProvider,Le=Me(),_e=Le?.providerID||I.currentProviderId||Ee?.providerID,Xe=Le?.modelID||I.currentModelId||Ee?.modelID,ct=Te()||I.currentAgentName||void 0;if(!_e||!Xe){G.error(a("session.newWorktree.error.noModelSelected"));return}const ut=He(_e,Xe);if(se.issue){if(!i.issueGet||!i.issueComments)return;const lt=await i.issueGet(u,se.issue.number,{sourceRepo:se.issue.sourceRepo??null});if(lt.connected===!1||!lt.repo||!lt.issue)throw new Error("Failed to load issue context");const rt=await i.issueComments(u,se.issue.number,{sourceRepo:se.issue.sourceRepo??null});if(rt.connected===!1)throw new Error("Failed to load issue comments");const mt=await wi("github.issue.review.visible",{issue_number:String(se.issue.number)}),xt=await wi("github.issue.review.instructions"),It=ok({repo:lt.repo,issue:lt.issue,comments:rt.comments??[]});await ds.getState().sendMessage(mt,_e,Xe,ct,void 0,void 0,[{text:xt,synthetic:!0},{text:It,synthetic:!0}],ut,void 0,{sessionId:se.sessionId}),G.success(a("session.newWorktree.toast.sessionFromIssue"));return}if(se.pr){if(!i.prContext)return;const lt=await i.prContext(u,se.pr.number,{sourceRepo:se.pr.sourceRepo??null,includeDiff:se.includeDiff,includeCheckDetails:!1});if(lt.connected===!1||!lt.repo||!lt.pr)throw new Error("Failed to load PR context");const rt=await wi("github.pr.review.visible",{pr_number:String(se.pr.number)}),mt=await wi("github.pr.review.instructions"),xt=lk(lt);await ds.getState().sendMessage(rt,_e,Xe,ct,void 0,void 0,[{text:mt,synthetic:!0},{text:xt,synthetic:!0}],ut,void 0,{sessionId:se.sessionId}),G.success(a("session.newWorktree.toast.sessionFromPr"))}},[i,u,Te,Me,He,a]),Ue=m==="new-branch"?h:x;ge.useEffect(()=>{if(!t||!N?.all||!u||h.sourceBranch)return;const se=h.sourceBranch;let I=!1;return(async()=>{try{const Le=await rg(u).catch(()=>null);if(I)return;const _e=localStorage.getItem(io),{sourceBranch:Xe,shouldClearSavedSourceBranch:ct}=ak({branches:N.all,savedSourceBranch:_e,rootBranch:Le});if(ct&&localStorage.removeItem(io),I||se)return;Xe&&g(ut=>({...ut,sourceBranch:Xe}))}catch{}})(),()=>{I=!0}},[t,N?.all,u,h.sourceBranch]),ge.useLayoutEffect(()=>{if(!t)return;b("new-branch"),v({selectedBranch:"",worktreeName:""}),T(!1),O(!1),U(!1),X(!1),W(""),A(""),ne({isValidating:!1,branchError:null,worktreeError:null,touched:!1});const se=_();g({branchName:se,worktreeName:se,isSyncingWorktreeName:!0,sourceBranch:"",linkedIssue:null,linkedPr:null,includePrDiff:!1})},[t,_]),ge.useEffect(()=>{if(m!=="new-branch"||!h.isSyncingWorktreeName)return;const se=Xa(h.branchName),I=Ss(se);g(Ee=>({...Ee,worktreeName:I}))},[m,h.branchName,h.isSyncingWorktreeName]);const ze=ge.useCallback(async()=>{if(!f||!te.touched||oe)return;je&&je.abort();const se=new AbortController;Ie(se),ne(I=>({...I,isValidating:!0}));try{const I=m==="new-branch"?h.branchName:x.selectedBranch,Ee=Ue.worktreeName,Le=Xa(I),_e=Ss(Ee);let Xe=null,ct=null;if(Le||(Xe=a("session.newWorktree.error.branchNameRequired")),_e||(ct=a("session.newWorktree.error.worktreeDirectoryRequired")),Le&&_e){const ut=m==="new-branch"?h.linkedPr:null,lt=ut?gd(ut,w,j):null,rt=await Rd(f,{mode:m==="existing-branch"||lt?"existing":"new",branchName:Le,worktreeName:_e,existingBranch:lt?.existingBranch??(m==="existing-branch"?Le:void 0),...lt?.ensureRemoteName?{ensureRemoteName:lt.ensureRemoteName}:{},...lt?.ensureRemoteUrl?{ensureRemoteUrl:lt.ensureRemoteUrl}:{}});if(se.signal.aborted)return;rt.ok||rt.errors.forEach(mt=>{if(mt.code==="worktree_exists"){ct=ct??mt.message;return}mt.code.startsWith("branch_")&&(Xe=Xe??mt.message)})}se.signal.aborted||ne(ut=>({...ut,isValidating:!1,branchError:Xe,worktreeError:ct}))}catch{se.signal.aborted||ne(I=>({...I,isValidating:!1}))}},[f,m,h.branchName,h.linkedPr,x.selectedBranch,Ue.worktreeName,w,j,te.touched,je,oe,a]),Be=m==="new-branch"?h.branchName:x.selectedBranch;ge.useEffect(()=>{if(!t||!f||!te.touched||oe)return;const se=setTimeout(()=>{ze()},300);return()=>clearTimeout(se)},[Ue.worktreeName,Be,t,f,ze,te.touched,oe]);const Ge=async()=>{if(!f||!u){G.error(a("session.newWorktree.error.noActiveProject"));return}ne(_e=>({..._e,touched:!0}));const se=m==="new-branch"?h.branchName:x.selectedBranch,I=Ue.worktreeName,Ee=Xa(se),Le=Ss(I);if(!Ee){G.error(a("session.newWorktree.error.branchNameRequired"));return}if(!Le){G.error(a("session.newWorktree.error.worktreeDirectoryRequired"));return}je&&(je.abort(),Ie(null)),ne(_e=>({..._e,isValidating:!1,branchError:null,worktreeError:null})),Ae(!0);try{const _e=m==="new-branch"?h.linkedPr:null,Xe=m==="new-branch"?h.linkedIssue:null,ct=m==="new-branch"?h.linkedPr:null,ut=m==="new-branch"?h.includePrDiff:!1,lt=!!(Xe||ct),rt=await Cd(f),mt=h.sourceBranch;let xt="";const It=(()=>{if(_e){const ft=gd(_e,w,j);return xt=ft.sourceLabel,{preferredName:Ee||Le,mode:"existing",branchName:Ee,worktreeName:Le,existingBranch:ft.existingBranch,setupCommands:rt,setUpstream:ft.setUpstream,upstreamRemote:ft.upstreamRemote,upstreamBranch:ft.upstreamBranch,returnAfterDirectoryCreated:!0,...ft.ensureRemoteName?{ensureRemoteName:ft.ensureRemoteName}:{},...ft.ensureRemoteUrl?{ensureRemoteUrl:ft.ensureRemoteUrl}:{}}}return xt=m==="new-branch"?mt:"",{preferredName:Ee||Le,mode:m==="existing-branch"?"existing":"new",branchName:m==="existing-branch"?void 0:Ee,worktreeName:Le,existingBranch:m==="existing-branch"?Ee:void 0,setupCommands:rt,returnAfterDirectoryCreated:!0,...mt&&m==="new-branch"?{startRef:mt}:{}}})(),Se=await og(u,It),qe=await lg(f,Se);let Ze=null;if(lt){await Id(f)&&await cg(qe.path);const ft=Xe?`#${Xe.number} ${Xe.title}`.trim():ct?`#${ct.number} ${ct.title}`.trim():a("session.newWorktree.newSessionTitle"),vt=await dg(ft,qe.path,null);if(!vt?.id)throw new Error("Failed to create session");Ze=vt.id,n?.(qe.path,{sessionId:Ze}),e(!1),Ae(!1),ug(vt.id,ft).catch(()=>{});try{ds.getState().initializeNewOpenChamberSession(vt.id,pt.getState().agents)}catch{}}else e(!1),Ae(!1);const nt=nk({mode:m,sourceBranch:h.sourceBranch,linkedPr:!!h.linkedPr,selectedBranch:x.selectedBranch});nt&&localStorage.setItem(io,nt),G.success(a("session.newWorktree.toast.worktreeCreated"),{description:a("session.newWorktree.toast.worktreeCreatedDescription",{target:`${qe.branch||qe.name}${xt?` ${a("session.newWorktree.fromSource",{source:xt})}`:""}`})}),Ze?Ve({sessionId:Ze,directory:qe.path,issue:Xe,pr:ct,includeDiff:ut}).catch(ft=>{const vt=ft instanceof Error?ft.message:a("session.newWorktree.error.sendGitHubContextFailed");G.error(a("session.newWorktree.error.sendGitHubContextFailed"),{description:vt})}):n?.(qe.path)}catch(_e){const Xe=_e instanceof Error?_e.message:a("session.newWorktree.error.createWorktreeFailed");G.error(a("session.newWorktree.error.createWorktreeFailed"),{description:Xe})}finally{Ae(!1)}},Fe=se=>{b(se),ne(I=>({...I,touched:!1,branchError:null,worktreeError:null}))},ve=se=>{if(!se){g(I=>({...I,linkedIssue:null,linkedPr:null,includePrDiff:!1,branchName:""}));return}if(se.type==="issue"){const I=se.item,Ee=`issue-${I.number}-${Er()}`;g(Le=>({...Le,linkedIssue:I,linkedPr:null,includePrDiff:!1,branchName:Ee,worktreeName:Ss(Ee),isSyncingWorktreeName:!0}))}else if(se.type==="pr"){const I=se.item;g(Ee=>({...Ee,linkedPr:I,linkedIssue:null,includePrDiff:se.includeDiff??!1,branchName:I.head,worktreeName:Ss(I.head),isSyncingWorktreeName:!0}))}},De=c&&d?.connected===!0,We=(m==="existing-branch"?!!x.selectedBranch&&!!x.worktreeName&&!te.branchError&&!te.worktreeError:!!Xa(h.branchName)&&!!h.worktreeName&&!te.branchError&&!te.worktreeError)&&!oe,Pe=()=>{g(se=>({...se,linkedIssue:null,linkedPr:null,branchName:"",includePrDiff:!1,isSyncingWorktreeName:!0}))},at=s.jsxs("div",{className:le("flex gap-2",o?"flex-col w-full":"flex-row items-center"),children:[s.jsx("div",{className:le("flex items-center gap-1.5 text-destructive",o?"w-full justify-center order-first":"mr-auto"),children:te.touched&&(te.branchError||te.worktreeError)&&s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"error-warning",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"typography-micro",children:te.branchError||te.worktreeError})]})}),s.jsxs("div",{className:le("flex gap-2",o&&"w-full"),children:[s.jsx(Q,{variant:"outline",size:"sm",onClick:()=>e(!1),disabled:oe,className:le(o&&"flex-1"),children:a("session.newWorktree.actions.cancel")}),s.jsxs(Q,{size:"sm",onClick:Ge,disabled:!We||oe,className:le("gap-1.5",o&&"flex-1"),children:[oe&&s.jsx(L,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),a(oe?"session.newWorktree.actions.creating":"session.newWorktree.actions.createWorktree")]})]})]});return s.jsxs(s.Fragment,{children:[o?s.jsxs(Za,{open:t,title:a("session.newWorktree.title"),onClose:()=>e(!1),footer:at,children:[s.jsx("div",{className:"w-full mb-4",children:s.jsx(ia,{items:[{id:"new-branch",label:a("session.newWorktree.mode.newBranch"),icon:s.jsx(L,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"existing-branch",label:a("session.newWorktree.mode.existingBranch"),icon:s.jsx(L,{name:"git-repository",className:"h-3.5 w-3.5"})}],activeId:m,onSelect:se=>Fe(se),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(Q,{variant:"outline",size:"sm",onClick:()=>U(!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(L,{name:"git-branch",className:"h-4 w-4 text-muted-foreground"})]}),s.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0 shrink-0",onClick:q,disabled:!pe||P,title:a("session.newWorktree.fetchBranches"),children:P?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{name:"refresh",className:"size-4"})})]}),s.jsx(Za,{open:V,title:a("session.newWorktree.selectBranch"),onClose:()=>U(!1),children:s.jsxs("div",{className:"space-y-4",ref:$,children:[s.jsx(tt,{value:S,onChange:se=>W(se.target.value),placeholder:a("session.newWorktree.searchBranches"),className:"h-8"}),P?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):w.length===0&&j.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:[ye&&ae&&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(se=>s.jsx("button",{onClick:()=>{v(I=>({...I,selectedBranch:se.value,worktreeName:Ss(se.label)})),ne(I=>({...I,touched:!0})),U(!1)},className:le("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===se.value?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:se.label})},`${se.source}-${se.value}`))})]}),ye&&!ae&&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(ye?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches")}),s.jsx("div",{className:"space-y-1",children:be.otherLocal.map(se=>s.jsx("button",{onClick:()=>{v(I=>({...I,selectedBranch:se,worktreeName:Ss(se)})),ne(I=>({...I,touched:!0})),U(!1)},className:le("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===se?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:se})},se))})]}),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(ye?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches")}),s.jsx("div",{className:"space-y-1",children:be.otherRemote.map(se=>s.jsx("button",{onClick:()=>{v(I=>({...I,selectedBranch:`remotes/${se}`,worktreeName:Ss(se)})),ne(I=>({...I,touched:!0})),U(!1)},className:le("w-full text-left px-3 py-2.5 rounded-md transition-colors",x.selectedBranch===`remotes/${se}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:se})},`remotes/${se}`))})]})]})]})})]}):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"&&De&&s.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>D(!0),className:"gap-1.5 h-7",children:[s.jsx(L,{name:"github",className:"size-4 text-status-success"}),h.linkedIssue||h.linkedPr?a("session.newWorktree.actions.change"):a("session.newWorktree.actions.startFromGitHubIssuePr")]})]}),s.jsx(tt,{value:h.branchName,onChange:se=>{g(I=>({...I,branchName:se.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>ne(se=>({...se,touched:!0})),placeholder:a("session.newWorktree.branchNamePlaceholder"),disabled:!!h.linkedPr,className:le("h-8",te.touched&&te.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(L,{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(L,{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 se=Ss(m==="new-branch"?h.branchName:"");g(I=>({...I,worktreeName:se,isSyncingWorktreeName:!0}))},disabled:!h.branchName||h.worktreeName===Ss(h.branchName),className:le("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",h.worktreeName===Ss(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(L,{name:"refresh",className:"h-3 w-3"}),s.jsx("span",{children:a("session.newWorktree.actions.reset")})]})]}),s.jsx(tt,{value:Ue.worktreeName,onChange:se=>{m==="new-branch"?g(I=>({...I,worktreeName:se.target.value,isSyncingWorktreeName:!1})):v(I=>({...I,worktreeName:se.target.value}))},onBlur:()=>ne(se=>({...se,touched:!0})),placeholder:a("session.newWorktree.worktreeDirectoryPlaceholder"),className:le("h-8",te.touched&&te.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(Q,{variant:"outline",size:"sm",onClick:()=>X(!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(L,{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(Za,{open:Y,title:a("session.newWorktree.selectSourceBranch"),onClose:()=>X(!1),children:s.jsxs("div",{className:"space-y-4",ref:H,children:[s.jsx(tt,{value:Z,onChange:se=>A(se.target.value),placeholder:a("session.newWorktree.searchBranches"),className:"h-8"}),P?s.jsx("div",{className:"px-2 py-8 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):w.length===0&&j.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:[fe&&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:he.matching.map(se=>s.jsx("button",{onClick:()=>{g(I=>({...I,sourceBranch:se.value})),X(!1)},className:le("w-full text-left px-3 py-2.5 rounded-md transition-colors",h.sourceBranch===se.value?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:se.label})},`${se.source}-${se.value}`))})]}),fe&&!ce&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),he.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(fe?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches")}),s.jsx("div",{className:"space-y-1",children:he.otherLocal.map(se=>s.jsx("button",{onClick:()=>{g(I=>({...I,sourceBranch:se})),X(!1)},className:le("w-full text-left px-3 py-2.5 rounded-md transition-colors",h.sourceBranch===se?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:se})},se))})]}),he.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(fe?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches")}),s.jsx("div",{className:"space-y-1",children:he.otherRemote.map(se=>s.jsx("button",{onClick:()=>{g(I=>({...I,sourceBranch:`remotes/${se}`})),X(!1)},className:le("w-full text-left px-3 py-2.5 rounded-md transition-colors",h.sourceBranch===`remotes/${se}`?"bg-interactive-selection text-interactive-selection-foreground":"hover:bg-interactive-hover"),children:s.jsx("span",{className:"typography-small break-all",children:se})},`remotes/${se}`))})]})]})]})})]}),(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(L,{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:se=>se.stopPropagation(),children:s.jsx(L,{name:"external-link",className:"h-3 w-3"})}),s.jsx("button",{onClick:Pe,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(L,{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(Lt,{open:t,onOpenChange:e,children:s.jsxs(Ft,{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(zt,{className:"flex items-center gap-2 shrink-0",children:[s.jsx(L,{name:"git-branch",className:"h-5 w-5"}),a("session.newWorktree.title")]}),s.jsx("div",{className:"w-[280px] shrink-0",children:s.jsx(ia,{items:[{id:"new-branch",label:a("session.newWorktree.mode.newBranch"),icon:s.jsx(L,{name:"git-branch",className:"h-3.5 w-3.5"})},{id:"existing-branch",label:a("session.newWorktree.mode.existingBranch"),icon:s.jsx(L,{name:"git-repository",className:"h-3.5 w-3.5"})}],activeId:m,onSelect:se=>Fe(se),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(ws,{open:k,onOpenChange:T,children:[s.jsx(ys,{asChild:!0,children:s.jsxs("button",{type:"button",className:le(lo({size:"default"}),"min-w-[220px] max-w-full"),children:[s.jsx("span",{className:le("truncate",x.selectedBranch?"text-foreground":"text-muted-foreground"),children:x.selectedBranch||a("session.newWorktree.chooseBranch")}),s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),s.jsx(vs,{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:C,children:s.jsxs(mo,{shouldFilter:!1,children:[s.jsx(po,{placeholder:a("session.newWorktree.searchBranches"),value:S,onValueChange:W,onKeyDown:J}),s.jsx(go,{disableHorizontal:!0,children:P?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):w.length===0&&j.length===0?s.jsx(fo,{children:a("session.newWorktree.noBranchesFound")}):s.jsxs(s.Fragment,{children:[ye&&ae&&s.jsx(wn,{heading:a("session.newWorktree.matchingBranches"),children:be.matching.map(se=>s.jsx(Xs,{value:se.value,onSelect:()=>{v(I=>({...I,selectedBranch:se.value,worktreeName:Ss(se.label)})),ne(I=>({...I,touched:!0})),T(!1)},children:s.jsx("span",{className:"typography-small break-all",children:se.label})},`${se.source}-${se.value}`))}),ye&&!ae&&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:[ye&&s.jsx(Sa,{}),s.jsx(wn,{heading:a(ye?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches"),children:be.otherLocal.map(se=>s.jsx(Xs,{value:se,onSelect:()=>{v(I=>({...I,selectedBranch:se,worktreeName:Ss(se)})),ne(I=>({...I,touched:!0})),T(!1)},children:s.jsx("span",{className:"typography-small break-all",children:se})},`local-${se}`))})]}),be.otherRemote.length>0&&s.jsxs(s.Fragment,{children:[(be.otherLocal.length>0||ye)&&s.jsx(Sa,{}),s.jsx(wn,{heading:a(ye?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches"),children:be.otherRemote.map(se=>s.jsx(Xs,{value:`remotes/${se}`,onSelect:()=>{v(I=>({...I,selectedBranch:`remotes/${se}`,worktreeName:Ss(se)})),ne(I=>({...I,touched:!0})),T(!1)},children:s.jsx("span",{className:"typography-small break-all",children:se})},`remote-${se}`))})]})]})})]})})]}),s.jsx(Q,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0 shrink-0",onClick:q,disabled:!pe||P,title:a("session.newWorktree.fetchBranches"),children:P?s.jsx(L,{name:"loader-4",className:"size-4 animate-spin"}):s.jsx(L,{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"&&De&&s.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>D(!0),className:"gap-1.5 h-7",children:[s.jsx(L,{name:"github",className:"size-4 text-status-success"}),h.linkedIssue||h.linkedPr?a("session.newWorktree.actions.change"):a("session.newWorktree.actions.startFromGitHubIssuePr")]})]}),s.jsx(tt,{value:h.branchName,onChange:se=>{g(I=>({...I,branchName:se.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>ne(se=>({...se,touched:!0})),placeholder:a("session.newWorktree.branchNamePlaceholder"),disabled:!!h.linkedPr,className:le("h-8",te.touched&&te.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(L,{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(L,{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 se=Ss(m==="new-branch"?h.branchName:"");g(I=>({...I,worktreeName:se,isSyncingWorktreeName:!0}))},disabled:!h.branchName||h.worktreeName===Ss(h.branchName),className:le("flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded",h.worktreeName===Ss(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(L,{name:"refresh",className:"h-3 w-3"}),s.jsx("span",{children:a("session.newWorktree.actions.reset")})]})]}),s.jsx(tt,{value:Ue.worktreeName,onChange:se=>{m==="new-branch"?g(I=>({...I,worktreeName:se.target.value,isSyncingWorktreeName:!1})):v(I=>({...I,worktreeName:se.target.value}))},onBlur:()=>ne(se=>({...se,touched:!0})),placeholder:a("session.newWorktree.worktreeDirectoryPlaceholder"),className:le("h-8",te.touched&&te.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(ws,{open:M,onOpenChange:O,children:[s.jsx(ys,{asChild:!0,children:s.jsxs("button",{type:"button",className:le(lo({size:"default"}),"min-w-[220px] max-w-full"),children:[s.jsx("span",{className:le("truncate",h.sourceBranch?"text-foreground":"text-muted-foreground"),children:h.sourceBranch||a("session.newWorktree.selectSourceBranchPlaceholder")}),s.jsx(L,{name:"arrow-down-s",className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),s.jsx(vs,{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:z,children:s.jsxs(mo,{shouldFilter:!1,children:[s.jsx(po,{placeholder:a("session.newWorktree.searchBranches"),value:Z,onValueChange:A,onKeyDown:J}),s.jsx(go,{disableHorizontal:!0,children:P?s.jsx("div",{className:"px-2 py-4 text-center typography-small text-muted-foreground",children:a("session.newWorktree.loadingBranches")}):w.length===0&&j.length===0?s.jsx(fo,{children:a("session.newWorktree.noBranchesFound")}):s.jsxs(s.Fragment,{children:[fe&&ce&&s.jsx(wn,{heading:a("session.newWorktree.matchingBranches"),children:he.matching.map(se=>s.jsx(Xs,{value:se.value,onSelect:()=>{g(I=>({...I,sourceBranch:se.value})),O(!1)},children:s.jsx("span",{className:"typography-small break-all",children:se.label})},`${se.source}-${se.value}`))}),fe&&!ce&&s.jsx("div",{className:"px-2 py-1 text-center typography-small text-muted-foreground",children:a("session.newWorktree.noMatchingBranches")}),he.otherLocal.length>0&&s.jsxs(s.Fragment,{children:[fe&&s.jsx(Sa,{}),s.jsx(wn,{heading:a(fe?"session.newWorktree.otherLocalBranches":"session.newWorktree.localBranches"),children:he.otherLocal.map(se=>s.jsx(Xs,{value:se,onSelect:()=>{g(I=>({...I,sourceBranch:se})),O(!1)},children:s.jsx("span",{className:"typography-small break-all",children:se})},`local-${se}`))})]}),he.otherRemote.length>0&&s.jsxs(s.Fragment,{children:[(he.otherLocal.length>0||fe)&&s.jsx(Sa,{}),s.jsx(wn,{heading:a(fe?"session.newWorktree.otherRemoteBranches":"session.newWorktree.remoteBranches"),children:he.otherRemote.map(se=>s.jsx(Xs,{value:`remotes/${se}`,onSelect:()=>{g(I=>({...I,sourceBranch:`remotes/${se}`})),O(!1)},children:s.jsx("span",{className:"typography-small break-all",children:se})},`remote-${se}`))})]})]})})]})})]}),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(L,{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:se=>se.stopPropagation(),children:s.jsx(L,{name:"external-link",className:"h-3 w-3"})}),s.jsx("button",{onClick:Pe,className:"text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors",children:s.jsx(L,{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(Zt,{className:"mt-1 flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center gap-1.5 text-destructive",children:te.touched&&(te.branchError||te.worktreeError)&&s.jsxs(s.Fragment,{children:[s.jsx(L,{name:"error-warning",className:"h-3.5 w-3.5"}),s.jsx("span",{className:"typography-micro",children:te.branchError||te.worktreeError})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Q,{variant:"outline",size:"sm",onClick:()=>e(!1),disabled:oe,children:a("session.newWorktree.actions.cancel")}),s.jsxs(Q,{size:"sm",onClick:Ge,disabled:!We||oe,className:"gap-1.5",children:[oe&&s.jsx(L,{name:"loader-4",className:"h-3.5 w-3.5 animate-spin"}),a(oe?"session.newWorktree.actions.creating":"session.newWorktree.actions.createWorktree")]})]})]})]})}),s.jsx(ik,{open:B,onOpenChange:D,onSelect:ve})]})}const ck=9e4,dk=15e3,uk=5*6e4,mk=[2e3,5e3],pk=6e4,gk=2*6e4,fk=5*6e4,hk=4,fd=720*6e4,xk="openchamber.github-pr-status",er=200,bk=t=>t==="closed"||t==="merged",yk=t=>{const e=t?.checks;return e?e.state==="pending"||e.pending>0:!1},vk=t=>yk(t)?pk:t?.checks&&t.checks.state!=="pending"?fk:gk,wk=(t,e,n)=>JSON.stringify([on(),t,e,n??"auto"]),xa=new Map,ba=new Map,sn=new Map,ro=new Map;let zi=0;const jk=2;let tr=0;const Au=[],kk=()=>tr<jk?(tr+=1,Promise.resolve()):new Promise(t=>{Au.push(t)}),Nk=()=>{const t=Au.shift();if(t){t();return}tr=Math.max(0,tr-1)},ka=()=>({status:null,isLoading:!1,error:null,isInitialStatusResolved:!1,lastRefreshAt:0,lastDiscoveryPollAt:0,watchers:0,params:null,identity:null,resolvedRemoteName:null,paramsRevision:0}),sr=t=>t?.params?.directory&&t.params.branch?{directory:t.params.directory,branch:t.params.branch,runtimeKey:t.params.runtimeKey??t.identity?.runtimeKey??on(),remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null}:!t?.identity?.directory||!t.identity.branch?null:t.identity,_o=t=>{const e=sr(t);return!e?.directory||!e.branch?null:JSON.stringify([e.runtimeKey,e.directory,e.branch,e.remoteName??"auto"])},To=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}},Sk=(t,e)=>{const n=To(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=To(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},iN=(t,e,n)=>{const a=on();let i=null;for(const[r,o]of Object.entries(t)){if(!o.status)continue;const d=To(r);!d||d.runtimeKey!==a||d.directory!==e||d.branch!==n||(!i||o.lastRefreshAt>i.lastRefreshAt)&&(i=o)}return i?.status??null},Eu=(t,e)=>Object.entries(t).filter(([,n])=>_o(n)===e).map(([n])=>n),Ck=(t,e)=>{const n=e.runtimeKey??on(),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}}},Bi=t=>!t?.params?.canShow||!t.params.github?.prStatus?null:{...t.params,remoteName:t.params.remoteName??t.resolvedRemoteName??t.identity?.remoteName??null},Ik=(t,e,n)=>{const a=Eu(t,e),i=a.map(c=>Bi(t[c])).filter(c=>!!c);if(i.length===0)return null;const r=Bi(t[n]);if(r&&_o(t[n])===e)return r;const o=a.map(c=>t[c]).find(c=>!!(c?.resolvedRemoteName&&Bi(c)));if(o)return Bi(o);const d=i.find(c=>!!c.remoteName);return d||(i[0]??null)},Pk=t=>({status:t.status,isInitialStatusResolved:t.isInitialStatusResolved,lastRefreshAt:t.lastRefreshAt,lastDiscoveryPollAt:t.lastDiscoveryPollAt,identity:sr(t),resolvedRemoteName:t.resolvedRemoteName??t.status?.resolvedRemoteName??null}),Ak=t=>({...ka(),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}),Ek=t=>{const e=Object.entries(t);return e.length<=er?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,er))},Tu=cn()(ii((t,e)=>({entries:{},activeRequestCount:0,totalRequestCount:0,resetForRuntimeSwitch:()=>{zi+=1;for(const n of xa.values())window.clearInterval(n);for(const n of ba.values())n.forEach(a=>window.clearTimeout(a));xa.clear(),ba.clear(),sn.clear(),ro.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=Sk(a.entries,n),r=i?{...ka(),status:i.status,isInitialStatusResolved:!0,resolvedRemoteName:i.resolvedRemoteName??i.status?.resolvedRemoteName??null}:ka();return{entries:Ek({...a.entries,[n]:r})}})},setParams:(n,a)=>{t(i=>{const r=i.entries[n]??ka();return{entries:{...i.entries,[n]:Ck(r,a)}}})},startWatching:n=>{if(t(r=>{const o=r.entries[n]??ka();return{entries:{...r.entries,[n]:{...o,watchers:o.watchers+1}}}}),xa.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=ba.get(n)??[];d.push(o),ba.set(n,d)};e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0}),mk.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<uk)return;t(u=>{const f=u.entries[n];return f?{entries:{...u.entries,[n]:{...f,lastDiscoveryPollAt:p}}}:u}),e().refresh(n,{force:!0,silent:!0,markInitialResolved:!0});return}if(bk(r.status?.pr?.state))return;const d=Date.now()-r.lastRefreshAt,c=vk(r.status);d<c||e().refresh(n,{force:!0,onlyExistingPr:!0,silent:!0,markInitialResolved:!0})},dk);xa.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=xa.get(n);typeof i=="number"&&window.clearInterval(i),xa.delete(n);const r=ba.get(n);r&&r.length>0&&r.forEach(o=>{window.clearTimeout(o)}),ba.delete(n)},refresh:async(n,a)=>{const i=e(),r=i.entries[n],o=_o(r);if(!r||!o)return;const d=Eu(i.entries,o),c=d.some(x=>!!i.entries[x]?.status?.pr);if(a?.onlyExistingPr&&!c)return;const p=ro.get(o)??0;if(!a?.force&&Date.now()-p<ck||sn.has(o))return;const u=Ik(i.entries,o,n);if(!u)return;const f=Symbol(o),m=zi,b=r.paramsRevision,h=r.params?.runtimeKey??r.identity?.runtimeKey??on(),g=()=>m===zi&&h===on()&&sn.get(o)===f&&e().entries[n]?.paramsRevision===b;if(sn.set(o,f),t(x=>{const v={...x.entries};return d.forEach(N=>{const P=v[N];P&&(v[N]={...P,isLoading:a?.silent?P.isLoading:!0,error:null})}),{entries:v}}),u.githubAuthChecked&&u.githubConnected===!1){if(!g())return;t(x=>{const v={...x.entries};return d.forEach(N=>{const P=v[N];P&&(v[N]={...P,status:{connected:!1},error:null,isLoading:a?.silent?P.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?P.isInitialStatusResolved:!0})}),{entries:v}}),sn.get(o)===f&&sn.delete(o);return}if(!u.github?.prStatus){if(!g())return;t(x=>{const v={...x.entries};return d.forEach(N=>{const P=v[N];P&&(v[N]={...P,status:null,error:"GitHub runtime API unavailable",isLoading:a?.silent?P.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?P.isInitialStatusResolved:!0})}),{entries:v}}),sn.get(o)===f&&sn.delete(o);return}try{t(v=>({...v,activeRequestCount:v.activeRequestCount+1,totalRequestCount:v.totalRequestCount+1})),await kk();let x;try{if(!g())return;ro.set(o,Date.now()),x=await u.github.prStatus(u.directory,u.branch,u.remoteName??void 0,{force:a?.force})}finally{Nk()}if(!g())return;t(v=>{const N={...v.entries};return d.forEach(P=>{const F=N[P];if(!F)return;const w=F.status?.fetchedAt,j=x.fetchedAt;if(typeof w=="number"&&typeof j=="number"&&j<w){N[P]={...F,error:null,isLoading:a?.silent?F.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?F.isInitialStatusResolved:!0,lastRefreshAt:Date.now()};return}const y=F.status?.pr,R=x.pr,B=!!(R&&y&&R.number===y.number&&(!R.body||!R.body.trim())&&typeof y.body=="string"&&y.body.trim().length>0)&&R&&y?.body?{...x,pr:{...R,body:y.body}}:x,D=B.resolvedRemoteName??F.resolvedRemoteName??u.remoteName??null,k=sr(F)??{runtimeKey:h,directory:u.directory,branch:u.branch,remoteName:u.remoteName??null};N[P]={...F,status:B,error:null,isLoading:a?.silent?F.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?F.isInitialStatusResolved:!0,lastRefreshAt:Date.now(),resolvedRemoteName:D,identity:{...k,remoteName:D??k.remoteName??null}}}),{entries:N}})}catch(x){if(!g())return;const v=x instanceof Error?x.message:String(x);t(N=>{const P={...N.entries};return d.forEach(F=>{const w=P[F];w&&(P[F]={...w,error:v||"Failed to load PR status",isLoading:a?.silent?w.isLoading:!1,isInitialStatusResolved:a?.markInitialResolved===!1?w.isInitialStatusResolved:!0})}),{entries:P}})}finally{sn.get(o)===f&&sn.delete(o),m===zi&&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:wk(o,d,r.remoteName??null)}).filter(r=>!!r)));await mg(i,hk,r=>e().refresh(r,a))},updateStatus:(n,a)=>{t(i=>{const r=i.entries[n]??ka();return{entries:{...i.entries,[n]:{...r,status:a(r.status)}}}})}}),{name:xk,storage:lr(),version:2,migrate:(t,e)=>e<2?{entries:{}}:t,partialize:t=>({entries:Object.fromEntries(Object.entries(t.entries).filter(([,e])=>{const n=sr(e);if(!n?.directory||!n.branch)return!1;const a=Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt);return a>0&&Date.now()-a<fd}).sort(([,e],[,n])=>Math.max(n.lastRefreshAt,n.lastDiscoveryPollAt)-Math.max(e.lastRefreshAt,e.lastDiscoveryPollAt)).slice(0,er).map(([e,n])=>[e,Pk(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)<fd)).slice(0,er).map(([i,r])=>[i,Ak(r)]))}}})),Tk=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"},Rk=t=>{const e=Tk(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}},Dk=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??""}`,Mk=300,ya=new Map,rN=t=>{const e=Ye.c(2);let n;return e[0]!==t?(n=a=>{if(!t)return null;const i=a.entries[t],r=i?Rk(i):null;if(!r)return ya.delete(t),null;const o=Dk(r),d=ya.get(t);if(d&&d.sig===o)return d.summary;if(!d&&ya.size>=Mk){const c=ya.keys().next().value;c!==void 0&&ya.delete(c)}return ya.set(t,{sig:o,summary:r}),r},e[0]=t,e[1]=n):n=e[1],Tu(n)},oN=()=>{Od(),Is.reconnectToRuntimeBaseUrl(),Md()},lN=t=>{ds.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),Ne.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),t.previousRuntimeKey&&pg.getState().stopRunningRunsForRuntime(t.previousRuntimeKey),Od(),Xt.getState().clearAll(),Is.reconnectToRuntimeBaseUrl(),pt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),rs.getState().resetForRuntimeSwitch(),uo.getState().resetForRuntimeSwitch(),gg.setState({statusById:new Map}),fg(),hg.getState().reset(),Yg.getState().resetForRuntimeSwitch(),Dd.getState().resetForRuntimeSwitch(t.runtimeKey),Tu.getState().resetForRuntimeSwitch(),xg.getState().resetForRuntimeSwitch(t.runtimeKey),Xg.getState().resetForRuntimeSwitch(t.runtimeKey),ds.getState().restoreForRuntimeSwitch(t.runtimeKey),Ne.getState().restoreForRuntimeSwitch(t.runtimeKey),Md(),queueMicrotask(()=>{Zg()})};export{Hk as $,Ud as A,mv as B,Zk as C,nN as D,sa as E,na as F,aa as G,qk as H,rd as I,By as J,Ky as K,Dl as L,of as M,aN as N,_k as O,tN as P,Vn as Q,vj as R,dj as S,Qk as T,uv as U,od as V,pc as W,Mb as X,mc as Y,ab as Z,$n as _,eN as a,En as a0,_n as a1,Un as a2,Os as a3,Tu as a4,iN as a5,sN as a6,wk as a7,hu as a8,bu as a9,cy as aa,rN as ab,qb as ac,io as ad,ak as ae,Ov as af,Uk as ag,Kh as ah,Hd as ai,yo as aj,zh as ak,Jk as al,Aj as b,lN as c,Xk as d,Yk as e,$k as f,Ta as g,gs as h,Vk as i,Kk as j,Yw as k,Wt as l,Vy as m,Cc as n,Bk as o,uj as p,xs as q,oN as r,Xt as s,Qb as t,Bd as u,Jb as v,Wk as w,Gk as x,Zd as y,ia as z};
|