swayrouter 1.0.2 → 1.0.4
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/CHANGELOG.md +16 -0
- package/dashboard/dist/assets/{CliTools-Ch3gKuNw.js → CliTools-5DLXOz1A.js} +1 -1
- package/dashboard/dist/assets/{Combo-BBCldjWi.js → Combo-BCvuw7s2.js} +1 -1
- package/dashboard/dist/assets/{ConsoleLog-wywAYcPT.js → ConsoleLog-BwgJ9V8I.js} +4 -4
- package/dashboard/dist/assets/{Dashboard-DxzyF41b.js → Dashboard-B-tNs8a1.js} +1 -1
- package/dashboard/dist/assets/{Header-C_9Su9BF.js → Header-9KXz4S67.js} +1 -1
- package/dashboard/dist/assets/{Keys-D0ufgcsc.js → Keys-DE32cEsn.js} +1 -1
- package/dashboard/dist/assets/Login-z7dbRqrR.js +1 -0
- package/dashboard/dist/assets/{ManageApiKey-CVXsmW2B.js → ManageApiKey-DF3A1CXL.js} +1 -1
- package/dashboard/dist/assets/{OAuthCallback-D_UZYcF6.js → OAuthCallback-I8fzY5zi.js} +1 -1
- package/dashboard/dist/assets/Provider-Caq5lvsq.js +4 -0
- package/dashboard/dist/assets/{ProviderModelAccordion-BAifkfVR.js → ProviderModelAccordion-GZSOrZZu.js} +1 -1
- package/dashboard/dist/assets/{Proxy-CU15VJ--.js → Proxy-DJVhsf4E.js} +1 -1
- package/dashboard/dist/assets/QuotaMonitor-BA4GOxkV.js +1 -0
- package/dashboard/dist/assets/{Settings-Dt4y2dC0.js → Settings-eEpS37LF.js} +1 -1
- package/dashboard/dist/assets/{Setup-DSDUwU7N.js → Setup-D9G2dVUf.js} +1 -1
- package/dashboard/dist/assets/{StatusBadge-1nAOyHU2.js → StatusBadge-DClAYX7v.js} +1 -1
- package/dashboard/dist/assets/{SwayChat-Bup7up6D.js → SwayChat-DS0GBQKQ.js} +2 -2
- package/dashboard/dist/assets/Usage-CRQCq5jc.js +4 -0
- package/dashboard/dist/assets/{accordion-DOOPDDgt.js → accordion-BkSdf_dl.js} +1 -1
- package/dashboard/dist/assets/{admin-extras-api-CCdu5TFM.js → admin-extras-api-ppLkXcD9.js} +1 -1
- package/dashboard/dist/assets/{api-keys-api-ifAC2Ok3.js → api-keys-api-CsdHmg2W.js} +1 -1
- package/dashboard/dist/assets/{card-CC0Omjcv.js → card-BOVhvx7W.js} +1 -1
- package/dashboard/dist/assets/{checkbox-7SZBrmbN.js → checkbox-DU_0LpXJ.js} +1 -1
- package/dashboard/dist/assets/{connections-api-_N54UD3S.js → connections-api-CQHf0Hwe.js} +1 -1
- package/dashboard/dist/assets/{copy-button-qBvM6H9z.js → copy-button-nPFbNAXf.js} +1 -1
- package/dashboard/dist/assets/{currency-api-SV9CBf5e.js → currency-api-CDXu9UhW.js} +1 -1
- package/dashboard/dist/assets/{flip-button-BGgkjtl0.js → flip-button-C_PNv8Iq.js} +1 -1
- package/dashboard/dist/assets/{frame-cUiti6Lq.js → frame-BLwA8c3u.js} +1 -1
- package/dashboard/dist/assets/index-CN-Y5gO6.css +1 -0
- package/dashboard/dist/assets/index-x5tLD3Ye.js +10 -0
- package/dashboard/dist/assets/{ripple-button-l8aMiVVG.js → ripple-button-BV_KcZ7W.js} +1 -1
- package/dashboard/dist/assets/{segmented-CqmEnQjZ.js → segmented-BBSMiP-0.js} +1 -1
- package/dashboard/dist/assets/select-DELc8FMO.js +1 -0
- package/dashboard/dist/assets/{skeleton-7uJDiIXe.js → skeleton-CFSSp0e0.js} +1 -1
- package/dashboard/dist/assets/{table-D0M60Tu1.js → table-lcAgAODE.js} +1 -1
- package/dashboard/dist/assets/{tabs-C6YkuulG.js → tabs-CSBJRjaH.js} +1 -1
- package/dashboard/dist/assets/{tunnel-api-DDPsBaDV.js → tunnel-api-CdE1F_Ct.js} +1 -1
- package/dashboard/dist/index.html +2 -2
- package/package.json +1 -1
- package/src/executors/index.js +3 -2
- package/src/executors/opencode-go.js +46 -39
- package/src/executors/opencode.js +54 -31
- package/src/handlers/chatCore.js +3 -2
- package/src/providers/registry/index.js +5 -4
- package/src/providers/registry/opencode-go.js +16 -22
- package/src/providers/registry/opencode-zen.js +34 -0
- package/src/providers/registry/opencode.js +16 -12
- package/src/routes/api/providers/[id]/models/route.js +28 -0
- package/src/routes/api/providers/[id]/test/testUtils.js +15 -6
- package/src/routes/api/providers/catalog/route.js +3 -1
- package/src/routes/api/providers/suggested-models/filters.js +7 -2
- package/src/routes/api/providers/validate/route.js +14 -11
- package/src/types/provider.ts +1 -1
- package/src/utils/opencode.js +225 -0
- package/dashboard/dist/assets/Login-BeKpipS_.js +0 -1
- package/dashboard/dist/assets/Provider-BU7JfTqm.js +0 -4
- package/dashboard/dist/assets/QuotaMonitor-HzGK7bcc.js +0 -1
- package/dashboard/dist/assets/Usage-eWnrPQ_v.js +0 -4
- package/dashboard/dist/assets/index-B6j-9zHy.js +0 -10
- package/dashboard/dist/assets/index-C-_l0yYz.css +0 -1
- package/dashboard/dist/assets/select-D8pUtMXp.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as i,j as r}from"./react-vendor-xnYrwzsL.js";import{C as A,b as S}from"./card-
|
|
1
|
+
import{r as i,j as r}from"./react-vendor-xnYrwzsL.js";import{C as A,b as S}from"./card-BOVhvx7W.js";import{r as O,p as R,b as P}from"./index-x5tLD3Ye.js";import{p as D,r as f,s as E,c as I,a as M,g as T}from"./oauth-callback-CqYQzyd7.js";import{a as z,L}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./query-vendor-DVevaSVS.js";import"./motion-vendor-g5fpGzmJ.js";const b=3e3;function v({className:e}){return r.jsx("svg",{viewBox:"0 0 18 18",className:e,fill:"none","aria-hidden":"true",children:r.jsx("path",{className:"oauth-checkmark",d:"M2.5 9.25 6.5 13.25 15.5 5",pathLength:"1"})})}function K(){const e=i.useMemo(()=>D(window.location.search),[]),[a,s]=i.useState("processing"),[j,o]=i.useState("Returning to Sway Router…"),[h,y]=i.useState(()=>e.provider||(e.state?f(e.state):void 0)),n=h?O(h):void 0,p=n?R(n):"OAuth",c=n?P(n):null;i.useEffect(()=>{const u=window.opener;if(!!!(e.code||e.error)){s("manual"),o("No OAuth result was returned. Close this tab and try again.");return}const l=e.provider||(e.state?f(e.state):void 0);l&&y(l);const g=l?{...e,provider:l}:e,x=E(g);if(e.state&&I(e.state),!u||u.closed){if(!x){s("manual"),o(e.errorDescription||e.error?"Authorization failed. Close this tab and retry from the provider dialog.":"Authorization completed. Close this tab and return to the provider dialog.");return}s(e.error?"error":"success"),o(e.errorDescription||e.error?e.errorDescription||e.error||"Authorization failed.":"You can close this window.");const m=window.setTimeout(()=>{window.closed||window.close()},b);return()=>window.clearTimeout(m)}try{const m=M(g),w=T(window.location.origin);if(w.length===0)throw new Error("Invalid callback origin");for(const k of w)u.postMessage(m,k);e.error?(s("error"),o(e.errorDescription||e.error||"Authorization failed.")):(s("success"),o("You can close this window."))}catch{if(!x){s("manual"),o("The callback could not reach the provider dialog. Close this tab and retry.");return}s(e.error?"error":"success"),o(e.errorDescription||e.error?e.errorDescription||e.error||"Authorization failed.":"You can close this window.")}const N=window.setTimeout(()=>{window.closed||window.close()},b);return()=>window.clearTimeout(N)},[e]);const C=a==="success"?"Connected successfully":a==="error"?"Connection could not be completed":a==="manual"?"Return to Sway Router":"Completing authorization",t=a==="success",d=a==="error";return r.jsx("div",{className:"flex min-h-svh w-full items-center justify-center bg-background p-4 text-foreground",children:r.jsxs(A,{className:"w-full max-w-[420px] items-stretch border-border bg-card p-4 text-center",children:[r.jsxs("div",{className:"inline-flex self-start items-center gap-2 text-[13px] font-semibold tracking-[0.01em] text-foreground",children:[r.jsx("img",{src:"/logo/sway.svg",alt:"Sway Router",className:"h-6 w-6 rounded-md object-contain"}),r.jsx("span",{children:"Sway Router"})]}),r.jsxs("div",{className:"relative mt-7 self-center",children:[r.jsx("div",{className:t&&c?"flex h-14 w-14 items-center justify-center rounded-2xl border border-white/30 bg-white outline outline-1 outline-white/15 outline-offset-2":`flex h-14 w-14 items-center justify-center rounded-2xl border ${d?"border-destructive/35 bg-destructive/10 text-destructive":t?"border-success/35 bg-success/10 text-success":"border-primary/35 bg-primary/10 text-primary"}`,"aria-label":t?p:void 0,children:t&&c?r.jsx("img",{src:c,alt:p,className:"h-8 w-8 object-contain invert"}):t?r.jsx(v,{className:"h-7 w-7"}):d?r.jsx(z,{className:"h-7 w-7","aria-hidden":"true"}):r.jsx(L,{className:"h-7 w-7 animate-spin","aria-hidden":"true"})}),t&&c?r.jsx("span",{className:"absolute -bottom-2 -right-2 flex h-6 w-6 items-center justify-center rounded-full border-2 border-card bg-[#16a34a] text-white",children:r.jsx(v,{className:"h-4.5 w-4.5"})}):null]}),r.jsx(S,{className:"mt-5 text-[21px] leading-tight tracking-[-0.02em]",children:C}),t?null:r.jsx("p",{className:"mt-2.5 text-sm leading-6 text-muted-foreground",children:j}),r.jsxs("div",{className:"mt-5 inline-flex self-center items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 py-1.5 text-[11px] leading-none text-foreground",children:[r.jsx("span",{className:`relative top-px h-1.5 w-1.5 shrink-0 rounded-full ${d?"bg-destructive":t?"bg-success":"bg-primary"}`,"aria-hidden":"true"}),r.jsx("span",{className:"leading-4",children:"OAuth Success"})]}),r.jsx("p",{className:"mt-4 text-xs leading-5 text-muted-foreground/70",children:t?"You can close this window manually.":"Return to the provider dialog to continue."})]})})}export{K as default};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{j as e,r as o}from"./react-vendor-xnYrwzsL.js";import{u as Ss,a as ct,d as As,b as Zn}from"./query-vendor-DVevaSVS.js";import{H as Ts}from"./Header-9KXz4S67.js";import{R as E}from"./ripple-button-BV_KcZ7W.js";import{I as ne,T as ln,c as ce,D as Ut,m as $t,n as Qt,o as Vt,q as Wt,g as Z,v as kn,s as wn,b as Ms,e as ee,S as ms,w as hs,h as Qn,x as Ps,y as Ct,z as Es,A as Ls,t as kt,C as _t,a as es,E as Is}from"./index-x5tLD3Ye.js";import{g as Ks,s as Rs,a as Os,r as Fs,b as ts,c as qs,p as Ds,d as fs,t as ns,e as zs,f as Bs,h as ps,u as _s,i as zn,j as Us,k as ss,l as is,m as $s,n as Bn,o as an,q as Qs,v as Vs,w as Ws,x as Hs,y as Js,z as Gs,A as Ys}from"./connections-api-CQHf0Hwe.js";import{a as Xs,c as Zs,u as ei,d as ti,l as ni}from"./admin-extras-api-ppLkXcD9.js";import{b as si,d as ii,v as rs,e as ri,f as ai,a as oi,h as as,i as li}from"./oauth-callback-CqYQzyd7.js";import{S as pe}from"./StatusBadge-DClAYX7v.js";import{S as ci,a as di,b as ui,c as mi}from"./select-DELc8FMO.js";import{S as jt}from"./segmented-BBSMiP-0.js";import{ag as Sn,ad as Hn,L as cn,X as Jn,q as xs,ah as hi,ai as fi,aj as pi,ak as xi,a8 as gi,a9 as vi,ac as An,al as yi,am as bi,an as wi,ao as ki,af as jn,A as ji,ab as Ci,ap as Ni,aq as Si,h as gs}from"./icons-vendor-CUx7SB5V.js";import{A as Gn,m as dt}from"./motion-vendor-g5fpGzmJ.js";import{T as vs,a as ys,b as Cn,c as bs}from"./tabs-CSBJRjaH.js";import{F as ws,a as ks,c as js}from"./frame-BLwA8c3u.js";import{S as Ai}from"./skeleton-CFSSp0e0.js";import{F as Ti}from"./flip-button-C_PNv8Iq.js";import{C as Mi}from"./checkbox-DU_0LpXJ.js";import"./ui-vendor-BuM9f2NY.js";function Tn(n,s){if(s)return"Connect";const i=(n||"apikey").toLowerCase();return i.includes("oauth")||i.includes("device")||i.includes("import")||i==="local"?"Connect":"Add connection"}function Pi(n,s){return Tn(n,s)==="Add connection"?"Add":"Connect"}const Ei=[{value:"builder-id",label:"Builder ID",mobileLabel:"Builder ID",description:"Personal AWS account"},{value:"iam",label:"AWS IAM",mobileLabel:"AWS IAM",description:"Enterprise AWS SSO"},{value:"api-key",label:"API Key",mobileLabel:"API Key",description:"Long-lived Kiro / CodeWhisperer key"},{value:"import-token",label:"Token",mobileLabel:"Token",description:"Paste a refresh token from Kiro"},{value:"cli-proxy",label:"CLIProxyAPI",mobileLabel:"CLI Proxy",description:"Paste auth JSON from CLIProxyAPI / Kiro"}];function Li({value:n,region:s,startUrl:i,onChange:a,onRegionChange:u,onStartUrlChange:c}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(jt,{size:"sm",value:n,onChange:a,options:Ei.map(h=>({value:h.value,label:h.label,mobileLabel:h.mobileLabel,hint:h.description})),className:"w-full"}),n==="iam"?e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ne,{placeholder:"AWS region (default: us-east-1)",value:s,onChange:h=>u(h.target.value)}),e.jsx(ne,{placeholder:"AWS Start URL (https://...)",value:i,onChange:h=>c(h.target.value)})]}):null]})}function Ii({mode:n,refreshToken:s,clientId:i,clientSecret:a,profileArn:u,cliProxyJson:c,onRefreshTokenChange:h,onClientIdChange:y,onClientSecretChange:C,onProfileArnChange:N,onCliProxyJsonChange:K}){return n==="import-token"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Kiro refresh token (aorAAAAAG...)",value:s,onChange:A=>h(A.target.value)}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ne,{placeholder:"Client ID (optional for IAM)",value:i,onChange:A=>y(A.target.value)}),e.jsx(ne,{type:"password",placeholder:"Client secret (optional for IAM)",value:a,onChange:A=>C(A.target.value)})]}),e.jsx(ne,{placeholder:"Profile ARN (optional)",value:u,onChange:A=>N(A.target.value)})]}):n==="cli-proxy"?e.jsx("textarea",{className:"min-h-36 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Paste CLIProxyAPI Kiro auth JSON…",value:c,onChange:A=>K(A.target.value)}):null}function Ki({region:n,onChange:s}){return e.jsx(ne,{placeholder:"AWS region (default: us-east-1)",value:n,onChange:i=>s(i.target.value)})}function Ri({authLabel:n,apiKey:s,region:i,checking:a,keyValid:u,checkMsg:c,submitError:h,proxyPoolId:y,proxyOptions:C,showKiroRegion:N,onApiKeyChange:K,onRegionChange:A,onCheck:b,onProxyPoolChange:F}){var z;return e.jsxs("div",{className:"space-y-2",children:[N?e.jsx(Ki,{region:i,onChange:A}):null,e.jsx("label",{htmlFor:"connection-api-key",className:"text-xs font-medium text-muted-foreground",children:n}),e.jsx(ne,{id:"connection-api-key",type:"password",placeholder:"API Key",value:s,"aria-invalid":!!h,"aria-describedby":h?"connection-submit-error":void 0,onChange:T=>K(T.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(E,{size:"sm",variant:"outline",disabled:!s.trim()||a,onClick:()=>void b(),children:a?e.jsx(ln,{children:"Checking…"}):"Check"}),u===!0?e.jsx(pe,{tone:"ok",children:"Valid"}):u===!1?e.jsx(pe,{tone:"err",children:"Invalid"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Validate before add"})]}),c&&u===!1?e.jsx("p",{className:ce("text-xs",u?"text-success":"text-destructive"),children:c}):null,e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-xs text-muted-foreground",children:"Proxy pool"}),e.jsxs(ci,{value:y,onValueChange:T=>F(T??"pool_none"),children:[e.jsx(di,{className:"w-full",children:e.jsx("span",{className:"truncate",children:((z=C.find(T=>T.id===y))==null?void 0:z.name)??"None (direct)"})}),e.jsx(ui,{children:C.map(T=>e.jsx(mi,{value:T.id,children:T.name},T.id))})]})]})]})}function Oi({isDeviceFlow:n,isOAuthFlow:s,isKiroIam:i,authLink:a,userCode:u,deviceStatus:c,deviceCode:h,bootLoading:y,linkCopied:C,oauthCode:N,kiroStartUrl:K,onStartKiroAuthorization:A,onOpenAuthLink:b,onCopyAuthLink:F,onOauthCodeChange:z}){return e.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-surface p-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:n?"Verification":"Authorize"}),a?e.jsx("code",{className:"block break-all rounded-md border border-border bg-background px-2.5 py-2 font-mono text-[11px] text-foreground",children:a}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No auth URL yet"}),n&&u?e.jsxs("p",{className:"text-sm",children:["User code:"," ",e.jsx("span",{className:"font-mono text-base font-semibold tracking-wider text-foreground",children:u})]}):null,n&&c?e.jsx("p",{className:"text-xs text-muted-foreground",children:c}):null,e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[i&&!h?e.jsx(E,{size:"sm",onClick:()=>void A(),disabled:y||!K.trim(),children:"Start authorization"}):null,e.jsx(E,{size:"sm",onClick:b,disabled:!a,children:"Open in browser"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>void F(),disabled:!a,children:C?e.jsxs(e.Fragment,{children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hn,{className:"h-3.5 w-3.5"}),"Copy link"]})})]}),s?e.jsxs("div",{className:"space-y-1.5 pt-1",children:[e.jsx("label",{className:"block text-xs text-muted-foreground",children:"Fallback: paste the authorization code manually if needed"}),e.jsx(ne,{className:"font-mono text-xs",placeholder:"code from /callback",value:N,onChange:T=>z(T.target.value)})]}):null,e.jsx("p",{className:"text-[11px] text-muted-foreground",children:s?"Open the link → finish sign-in. The callback auto-saves the connection and updates this dialog. Manual code paste is available if needed.":"Open the link, enter the user code, authorize — this dialog polls automatically."})]})}function Fi({value:n,modes:s,onChange:i,label:a}){return e.jsx(jt,{size:"sm",value:n,onChange:i,options:s.map(u=>({value:u,label:a(u)})),className:"w-full"})}function qi({value:n,onChange:s}){return e.jsx(vs,{value:n,onValueChange:i=>s(i),children:e.jsxs(ys,{className:"w-full",children:[e.jsx(Cn,{value:"single",className:"flex-1",children:"Single API Key"}),e.jsx(Cn,{value:"bulk",className:"flex-1",children:"Bulk API Key"})]})})}function Di({raw:n,rows:s,activeIndex:i,activeRow:a,checking:u,validCount:c,onRawChange:h,onCheck:y}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["1 key per line; optionally use ",e.jsx("code",{children:"name|key"}),". Unnamed rows receive ",e.jsx("code",{children:"swayrouter-account1…N"})," automatically."]}),e.jsx("textarea",{id:"bulk-api-keys",className:"min-h-36 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-xs",placeholder:`name|sk-1
|
|
2
|
+
sk-2`,value:n,onChange:C=>h(C.target.value)}),u&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Gn,{initial:!1,mode:"wait",children:e.jsxs(dt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.32,ease:"easeOut"},className:"flex min-h-8 items-center gap-2 px-2 py-1 text-xs",children:[a.checking?e.jsx(cn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Sn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Jn,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}),e.jsx("span",{className:"shrink-0 font-medium",children:a.checking?"Checking":a.valid===!0?"Valid":"Error"}),e.jsx("span",{className:"min-w-0 truncate font-medium",children:a.name}),e.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:[a.apiKey.slice(0,14),"…"]}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[(i??0)+1," / ",s.length]})]},`${i}-${a.checking?"checking":a.valid===!0?"valid":"error"}`)})}):!u&&s.length>0?e.jsxs(dt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},className:"flex flex-wrap items-center gap-2 px-0 py-0 text-xs",role:"status","aria-live":"polite",children:[e.jsxs(pe,{tone:"ok",children:["Valid: ",c," API Key"]}),e.jsxs(pe,{tone:"err",children:["Error: ",s.filter(C=>C.valid===!1).length," API Key"]})]}):null,e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!n.trim()||u,onClick:()=>void y(),children:u?e.jsxs("span",{className:"inline-flex items-center gap-0.5",children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):"Check all"})})]})}function zi({providerId:n,token:s,machineId:i,importing:a,message:u,hasError:c,onTokenChange:h,onMachineIdChange:y,onAutoImport:C}){return e.jsxs("div",{className:"space-y-2",children:[n==="cursor"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(E,{size:"sm",variant:"outline",disabled:a,onClick:()=>void C(),children:a?e.jsx(ln,{children:"Detecting…"}):"Auto-detect from this device"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Reads Cursor's local state.vscdb"})]}),u?e.jsx("p",{className:ce("text-xs",c?"text-destructive":"text-success"),role:"status",children:u}):null]}):null,e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Access token…",value:s,onChange:N=>h(N.target.value)}),n==="cursor"?e.jsx(ne,{placeholder:"Machine ID (cursorAuth machine id)",value:i,onChange:N=>y(N.target.value)}):null]})}function Bi({raw:n,rows:s,activeIndex:i,activeRow:a,onRawChange:u,onCheck:c,validCount:h,checking:y}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["One account per line. Supported formats: ",e.jsx("code",{children:"accessToken"}),", ",e.jsx("code",{children:"refreshToken"}),", or ",e.jsx("code",{children:"accessToken|refreshToken"}),". A single token is detected automatically. Multiple accounts receive automatic names."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"codebuddy-token",className:"text-xs font-medium text-muted-foreground",children:"Access / Refresh Tokens"}),e.jsx("textarea",{id:"codebuddy-token",className:"min-h-36 w-full resize-y overflow-x-auto whitespace-pre rounded-md border border-input bg-surface px-3 py-2 font-mono text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:`access-token-1
|
|
3
|
+
refresh-token-2
|
|
4
|
+
access-token-3|refresh-token-3`,value:n,autoComplete:"off",spellCheck:!1,wrap:"off",onChange:C=>u(C.target.value)})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!n.trim()||y,onClick:()=>void c(),children:y?e.jsx(ln,{children:"Checking…"}):"Check all"})}),y&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Gn,{initial:!1,mode:"wait",children:e.jsxs(dt.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},exit:{opacity:0,y:-14},transition:{duration:.2,ease:"easeOut"},className:"flex min-h-8 items-center gap-2 px-2 py-1 text-xs",children:[a.checking?e.jsx(cn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Sn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Jn,{className:"h-3.5 w-3.5 shrink-0 text-destructive"}),e.jsx("span",{className:"shrink-0 font-medium",children:a.checking?"Checking":a.valid===!0?"Valid":"Error"}),e.jsxs("span",{className:"min-w-0 flex-1 truncate",children:["Account ",(i??0)+1]}),e.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[(i??0)+1," / ",s.length]})]},`${i}-${a.checking?"checking":a.valid===!0?"valid":"error"}`)})}):!y&&s.length>0?e.jsxs(dt.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},className:"flex flex-wrap items-center gap-2 px-0 py-0 text-xs",role:"status","aria-live":"polite",children:[e.jsxs(pe,{tone:"ok",children:["Valid: ",h," account",h===1?"":"s"]}),e.jsxs(pe,{tone:"err",children:["Error: ",s.filter(C=>C.valid===!1).length," account",s.filter(C=>C.valid===!1).length===1?"":"s"]})]}):null,n.trim()?null:e.jsx("p",{className:"text-xs text-muted-foreground",role:"status",children:"At least one access token or refresh token is required."})]})}function _i(n){return n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{const i=s.split("|").map(a=>a.trim());return i.length===1&&i[0]?{credentialToken:i[0],valid:null}:i.length===2&&i[0]&&i[1]?{accessToken:i[0],refreshToken:i[1],valid:null}:{valid:!1,msg:"Use one token or accessToken|refreshToken"}})}const Ui=new Set(["claude","codex","xai"]),$i=200,Qi=1e3;function Vi({open:n,provider:s,flow:i,onOpenChange:a,onSubmit:u}){var yn;const[c,h]=o.useState(""),[y,C]=o.useState(""),[N,K]=o.useState(""),[A,b]=o.useState(""),[F,z]=o.useState(""),[T,G]=o.useState(""),[U,_]=o.useState("pool_none"),[Y,$]=o.useState(()=>[{id:"pool_none",name:"None (direct)"}]),[xe,R]=o.useState(!1),[Ie,Ke]=o.useState(!1),[Re,ge]=o.useState(null),[Ue,te]=o.useState(null),[ve,B]=o.useState(null),[O,ie]=o.useState(null),[re,ye]=o.useState(null),[Oe,L]=o.useState(null),[S,ae]=o.useState(null),[ut,de]=o.useState(5),[Fe,oe]=o.useState(null),[be,je]=o.useState(null),[qe,mt]=o.useState(null),[Xe,Nt]=o.useState(null),[he,St]=o.useState("builder-id"),[ht,At]=o.useState("us-east-1"),[Jt,Tt]=o.useState(""),[Gt,ft]=o.useState(""),[dn,Mt]=o.useState(""),[Ze,De]=o.useState(""),[Pt,Yt]=o.useState(""),[Et,Lt]=o.useState(""),[pt,$e]=o.useState(!1),[Mn,et]=o.useState(null),[Pn,tt]=o.useState(!1),[le,nt]=o.useState("single"),[xt,st]=o.useState(""),[It,Se]=o.useState([]),[Kt,gt]=o.useState(!1),[Xt,Ce]=o.useState(null),[Rt,Zt]=o.useState(!1),[ze,He]=o.useState([]),[vt,Be]=o.useState(!1),[it,Ae]=o.useState(null);function Ot(m,p){return p==="apikey"?m==="qoder"?"API Key (PAT)":"API Key":p==="device"?"Device Code":p==="import"?m==="codebuddy-cn"||m==="codebuddy-intl"?"AT/RT":"Import Token":p}const[Ft,ue]=o.useState(null),[en,Qe]=o.useState(!1),[qt,Te]=o.useState(!1),[P,rt]=o.useState(!1),J=o.useRef(!1),Je=o.useRef(null),Ne=o.useRef(!1),Dt=o.useRef(null),d=o.useRef(null);function Me(m=!1){rt(m)}function se(){d.current&&(clearTimeout(d.current),d.current=null)}function we(){const m=Dt.current;Dt.current=null,m&&!m.closed&&m.close()}function Ge(m){const p=Je.current;!p||m&&p!==m||(Je.current=null,Me(!1),p&&qs(p).catch(()=>{}))}const fe=o.useRef(u);fe.current=u;const Pe=o.useRef(c);Pe.current=c;const H=(s==null?void 0:s.id)==="kiro",yt=(s==null?void 0:s.id)==="codebuddy-cn"||(s==null?void 0:s.id)==="codebuddy-intl",ke=(yn=s==null?void 0:s.authModes)!=null&&yn.length?s.authModes:null,at=!!(ke&&ke.length>1),[tn,un]=o.useState((ke==null?void 0:ke[0])??"auto"),Ee=H?he==="api-key"||he==="import-token"||he==="cli-proxy"?he==="api-key"?"apikey":"import":"device":ke&&ke.includes(tn)?tn:i??(ke!=null&&ke.includes("device")?"device":"apikey"),Ye=It.filter(m=>m.valid===!0),mn=Xt===null?null:It[Xt]??null,ot=ze.filter(m=>m.valid===!0),En=it===null?null:ze[it]??null;function zt(m){return m.split(/\r?\n/).map(p=>p.trim()).filter(Boolean).map(p=>{const w=p.includes("|")?p.split("|").map(x=>x.trim()):p.includes(",")?p.split(",").map(x=>x.trim()):[p];return{name:w.length>=2?w[0]:"",apiKey:w.length>=2?w[1]:w[0],valid:null,msg:void 0}})}async function hn(){if(!s)return;const m=zt(xt);if(!m.length)return;gt(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;Se([...p]),Ce(0);try{for(let x=0;x<p.length;x+=1){Ce(x);const M=p[x].apiKey.trim();if(w.has(M)){p[x]={...p[x],valid:!1,checking:!1,msg:"Duplicate API key in this batch"},Se([...p]);continue}w.add(M),p[x]={...p[x],checking:!0},Se([...p]);try{const q=await ns({provider:s.id,apiKey:p[x].apiKey});p[x]={...p[x],valid:q.valid===!0,checking:!1,msg:q.valid===!0?"ok":q.error||"fail"}}catch(q){p[x]={...p[x],valid:!1,checking:!1,msg:Z(q,"error")}}Se([...p]),await new Promise(q=>{window.setTimeout(q,Qi)})}}finally{Ce(null),gt(!1)}}async function fn(){if(!(!s||!Ye.length)){Zt(!0),B(null);try{await u({name:s.name,authFlow:"apikey",bulkKeys:Ye.map(({name:m,apiKey:p},w)=>{const x=m.trim();return{name:x||`swayrouter-account${w+1}`,apiKey:p.trim(),autoName:!x}})})}catch(m){B(Z(m,"Failed to add connections"))}finally{Zt(!1)}}}const Q=Ee,Ve=Q==="apikey"||!!(s!=null&&s.isCustom),We=Q==="oauth",lt=Q==="device",nn=We||lt,pn=qt&&nn;function xn(m){J.current=!0,se(),St(m),nt("single"),ge(null),te(null),B(null),ue(null),ye(null),L(null),ae(null),oe(null),ie(null)}async function gn(){if(!s||s.id!=="kiro")return;const m=he==="iam"?"idc":"builder-id",p=Jt.trim();if(m==="idc"&&!p){ue("AWS IAM Identity Center requires a Start URL");return}J.current=!0,se(),Te(!0),ue(null),oe(null),ye(null),L(null),ae(null),ie(null);try{const w=await ts("kiro",{authMethod:m,region:ht.trim()||"us-east-1",startUrl:p||void 0}),x=typeof w.device_code=="string"&&w.device_code||typeof w.deviceCode=="string"&&w.deviceCode||null;if(!x)throw new Error("Kiro did not return a device code");const M=typeof w.user_code=="string"&&w.user_code||typeof w.userCode=="string"&&w.userCode||null,q=typeof w.verification_uri_complete=="string"&&w.verification_uri_complete||typeof w.verificationUriComplete=="string"&&w.verificationUriComplete||typeof w.verification_uri=="string"&&w.verification_uri||typeof w.verificationUri=="string"&&w.verificationUri||null;ye(x),ae(M),ie(q),L(typeof w.codeVerifier=="string"?w.codeVerifier:null),de(typeof w.interval=="number"&&w.interval>0?w.interval:5),oe("Waiting for you to authorize…")}catch(w){ue(Z(w,"Failed to start Kiro authorization"))}finally{Te(!1)}}if(o.useEffect(()=>{var m;n&&(un(((m=s==null?void 0:s.authModes)==null?void 0:m[0])??"auto"),St("builder-id"),At("us-east-1"),Tt(""),ft(""),Mt(""),De(""),Yt(""),Lt(""),b(""),te(null),$e(!1),et(null),tt(!1),nt("single"),st(""),Se([]),Ce(null),He([]),Be(!1),Ae(null))},[n,s==null?void 0:s.id]),o.useEffect(()=>{if(!n)return;let m=!1;async function p(){try{const w=await Xs();if(m)return;$([{id:"pool_none",name:"None (direct)"},...w.map(x=>({id:x.id,name:String(x.name||x.id)}))])}catch{}}return p(),()=>{m=!0}},[n]),o.useEffect(()=>{if(!n||!s)return;h(""),C(""),K(""),z(""),G(""),_("pool_none"),R(!1),Te(!1),Ke(!1),ge(null),te(null),B(null),Qe(!1),ue(null),oe(null),ye(null),L(null),ae(null),je(null),mt(null),Nt(null),ie(null),nt("single"),st(""),Se([]),Ce(null),gt(!1),Zt(!1),J.current=!1;const m=s.id;let p=!1;async function w(){if(Q==="oauth"){Te(!0);try{const x=Ks(m),M=await Rs(m,x);if(p)return;const q=M.authUrl||M.url||M.authorizeUrl||null,t=typeof M.state=="string"?M.state:null,r=typeof M.codeVerifier=="string"?M.codeVerifier:null,l=typeof M.redirectUri=="string"&&M.redirectUri?M.redirectUri:x;ie(typeof q=="string"?q:null),je(t),t&&si(t,m),mt(r),Nt(l),Ne.current=!1;const g=(typeof M.flowType=="string"?M.flowType:null)==="authorization_code_pkce"||Ui.has(m);if(!q||!t||!l||g&&!r)throw new Error("OAuth provider returned incomplete authorization data");if(m==="codex"||m==="xai"){const k=window.location.port||(window.location.protocol==="https:"?"443":"80");try{const f=t,j=r,V=l;if(!f||!j||!V)throw new Error("OAuth provider returned incomplete authorization data");const W=await Os(m,{appPort:k});if(!W.success)throw new Error(W.reason==="port_busy"?"The OAuth callback port is already in use":"The OAuth callback listener could not start");if(Je.current=m,Me(!1),(await Fs(m,{state:f,codeVerifier:j,redirectUri:V})).success!==!0)throw new Error("The OAuth session could not be registered");if(p)return;Me(!0)}catch(f){ue(Z(f,"Automatic callback setup unavailable. Paste the browser callback code below.")),Ge(m)}}}catch(x){p||ue(Z(x,"Failed to start OAuth"))}finally{p||Te(!1)}return}if(Q==="device"){if(m==="kiro"){he==="builder-id"&&gn();return}Te(!0);try{const x=await ts(s.id);if(p)return;const M=typeof x.device_code=="string"&&x.device_code||typeof x.deviceCode=="string"&&x.deviceCode||null,q=typeof x.user_code=="string"&&x.user_code||typeof x.userCode=="string"&&x.userCode||null,t=typeof x.verification_uri_complete=="string"&&x.verification_uri_complete||typeof x.verificationUriComplete=="string"&&x.verificationUriComplete||typeof x.verification_uri=="string"&&x.verification_uri||typeof x.verificationUri=="string"&&x.verificationUri||null;ye(M),ae(q),ie(t),L(typeof x.codeVerifier=="string"?x.codeVerifier:null);const r=typeof x.interval=="number"&&x.interval>0?x.interval:5;de(r),oe("Waiting for you to authorize…")}catch(x){p||ue(Z(x,"Failed to start device code"))}finally{p||Te(!1)}}}return w(),()=>{p=!0,J.current=!0,se(),we(),Ge(s.id)}},[n,s,Q,he]),o.useEffect(()=>{if(!n||!s||Q!=="oauth"||!P||!be)return;let m=!1,p=0;const w=s.id,x=s.name,M=be,q=200,t=async()=>{if(!(m||Ne.current)){p+=1;try{const r=await Ds(w,M);if(m||Ne.current)return;if(r.status==="done"){Ne.current=!0,se(),we(),Ge(w),R(!0);try{await fe.current({name:Pe.current.trim()||x,alreadySaved:!0})}catch{ue("Connection saved, but the provider list could not refresh")}finally{R(!1)}return}if(r.status==="error"){Ne.current=!0,se(),we(),Ge(w),ue(r.error||"OAuth sign-in failed");return}}catch{}!m&&!Ne.current&&p<q?d.current=setTimeout(()=>void t(),1500):!m&&!Ne.current&&(ue("OAuth sign-in timed out. Use the manual code fallback."),Ge(w))}};return d.current=setTimeout(()=>void t(),750),()=>{m=!0,se()}},[n,s,Q,P,be]),o.useEffect(()=>{if(!n||!s||Q!=="oauth")return;const m=s.id,p=s.name,w=be;if(!w)return;let x=window.location.origin;if(Xe)try{x=new URL(Xe).origin}catch{return}const M=f=>rs(oi(f),{origin:x,eventOrigin:x,expectedState:w,expectedProvider:m});function q(f){if(!Ne.current){if(f.error){f.state&&as(f.state),ue(f.errorDescription||f.error||"OAuth sign-in failed");return}!f.code||!f.state||(as(f.state),Ne.current=!0,G(f.code),oe(null),R(!0),(async()=>{try{await fe.current({name:Pe.current.trim()||p,authFlow:"oauth",oauthCode:f.code,oauthState:f.state,oauthCodeVerifier:qe||void 0,oauthRedirectUri:Xe||void 0}),we()}catch(j){Ne.current=!1,ue(Z(j,"OAuth sign-in completed, but the token exchange failed. Restart the connection flow and try again."))}finally{R(!1)}})())}}function t(f){const j=rs(f.data,{origin:x,eventOrigin:f.origin,expectedState:w,expectedProvider:m,eventSource:f.source,expectedSource:Dt.current});j&&q(j)}const r=w,l=li(r);function v(f){const j=f===void 0?ii(r):ai(f),V=j?M(j):null;V&&q(V)}function g(f){f.key===l&&v(f.newValue)}v(),window.addEventListener("message",t),window.addEventListener("storage",g);const k=window.setInterval(()=>v(),500);return()=>{window.removeEventListener("message",t),window.removeEventListener("storage",g),window.clearInterval(k)}},[n,s,Q,be,qe,Xe]),o.useEffect(()=>()=>{J.current=!0,se(),we(),Ge()},[]),o.useEffect(()=>{if(!n||!s||Q!=="device"||!re)return;J.current=!1;let m=null,p=!1;const w=s.id,x=s.name,M=Oe||void 0,q=Math.max(2,ut)*1e3;async function t(){if(!(p||J.current||!re)){try{const r=await fs(w,{deviceCode:re,codeVerifier:M,displayName:Pe.current.trim()||x});if(p||J.current)return;if(r.success){oe("Authorized — connection saved"),R(!0);try{await fe.current({name:Pe.current.trim()||x,alreadySaved:!0})}catch{oe("Authorized — refresh the list if not visible")}finally{R(!1)}return}r.pending?oe("Still waiting for authorization…"):r.error&&oe(r.error)}catch(r){p||oe(Z(r,"Poll failed"))}!p&&!J.current&&(m=setTimeout(t,q))}}return m=setTimeout(t,q),()=>{p=!0,J.current=!0,m&&clearTimeout(m)}},[n,s==null?void 0:s.id,s==null?void 0:s.name,Q,re,Oe,ut]),o.useEffect(()=>{ge(null),te(null),B(null)},[y]),!s)return null;const Ln=Tn(s.authType,s.noAuth),In=Pi(s.authType,s.noAuth),bt=!xe&&!pn&&(Ve?Re===!0&&y.trim().length>0:Q==="import"?yt?ot.length>0&&!vt:H?he==="import-token"?Gt.trim().length>0:Et.trim().length>0:N.trim().length>0&&((s==null?void 0:s.id)!=="cursor"||F.trim().length>0):Q==="oauth"?T.trim().length>0:Q==="device"?!!re:!0);async function vn(){if(!(!s||!y.trim())){Ke(!0),te(null);try{const m=await ns({provider:s.id,apiKey:y.trim(),...H?{providerSpecificData:{region:ht.trim()||"us-east-1"}}:{}}),p=m.valid===!0;ge(p),te(p?"Key valid":m.error||"Key invalid")}catch(m){ge(!1),te(Z(m,"Check failed"))}finally{Ke(!1)}}}async function Kn(){if(!s||!A.trim())return;const m=_i(A);if(!m.length)return;Be(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;He([...p]),Ae(0);try{for(let x=0;x<p.length;x+=1){Ae(x);const M=p[x];if(M.valid===!1){He([...p]);continue}const q=M.credentialToken||`${M.accessToken}|${M.refreshToken}`;if(w.has(q)){p[x]={...M,valid:!1,checking:!1,msg:"Duplicate token pair in this batch"},He([...p]);continue}w.add(q),p[x]={...M,checking:!0},He([...p]);try{const t=await zs({provider:s.id,...M.credentialToken?{credentialToken:M.credentialToken}:{accessToken:M.accessToken,refreshToken:M.refreshToken}});p[x]={...M,valid:t.valid===!0,checking:!1,msg:t.valid===!0?"ok":t.error||"Token invalid"}}catch(t){p[x]={...M,valid:!1,checking:!1,msg:Z(t,"Token validation failed")}}He([...p]),x<p.length-1&&await new Promise(t=>{window.setTimeout(t,$i)})}}finally{Ae(null),Be(!1)}}async function Rn(){if(!(!s||s.id!=="cursor")){$e(!0),et(null),tt(!1);try{const m=await Bs();if(!m.found||!m.accessToken||!m.machineId)throw new Error(m.error||"Cursor credentials were not found on this device");K(m.accessToken),z(m.machineId),et("Cursor token and Machine ID filled automatically")}catch(m){tt(!0),et(Z(m,"Could not detect Cursor credentials"))}finally{$e(!1)}}}async function On(){if(O)try{await navigator.clipboard.writeText(O),Qe(!0),window.setTimeout(()=>Qe(!1),1500)}catch{}}function Fn(){if(!O)return;const m=window.open(O,"sway-oauth","popup,width=600,height=700");Dt.current=m,m||ue("The browser blocked the authorization window. Open the URL above manually or allow popups for this dashboard.")}async function qn(){if(!(!s||!bt)){R(!0),B(null);try{const m=c.trim(),p=We?ri(T,be):null;await u({name:m,autoName:Ve&&!m,authFlow:Q,apiKey:Ve&&y.trim()||void 0,importToken:Q==="import"&&!H&&!yt&&N.trim()||void 0,codeBuddyToken:Q==="import"&&yt&&ot.length===1&&ot[0].credentialToken||void 0,codeBuddyTokens:Q==="import"&&yt?ot.map((w,x)=>{const M=ot.length===1?m:"";return{...w.credentialToken?{credentialToken:w.credentialToken}:{accessToken:w.accessToken,refreshToken:w.refreshToken},name:M||`swayrouter-account${x+1}`,autoName:!M}}):void 0,machineId:Q==="import"&&F.trim()||void 0,kiroAuthMode:H?he:void 0,kiroRegion:H?ht.trim()||"us-east-1":void 0,kiroRefreshToken:H&&Gt.trim()||void 0,kiroClientId:H&&dn.trim()||void 0,kiroClientSecret:H&&Ze.trim()||void 0,kiroProfileArn:H&&Pt.trim()||void 0,kiroCliProxyJson:H&&Et.trim()||void 0,oauthCode:p==null?void 0:p.code,oauthState:p==null?void 0:p.state,oauthCodeVerifier:We&&qe||void 0,oauthRedirectUri:We&&Xe||void 0,deviceCode:lt&&re||void 0,deviceCodeVerifier:lt&&Oe||void 0,proxyPoolId:Ve?U:null})}catch(m){B(Z(m,"Failed to add connection"))}finally{R(!1)}}}const Dn=le==="bulk"&&Ve?"Add connections":Ln;return e.jsx(Ut,{open:n,onOpenChange:a,children:e.jsxs($t,{children:[e.jsx(Qt,{children:e.jsxs(Vt,{children:[Dn," — ",s.name]})}),e.jsxs("div",{className:ce("px-6",Ve&&le==="bulk"?"space-y-2 pb-4":"space-y-3 pb-4"),children:[!H&&at&&ke?e.jsx(Fi,{value:tn,modes:ke,label:m=>Ot((s==null?void 0:s.id)??"",m),onChange:m=>{un(m),nt("single"),st(""),Se([]),Ce(null),B(null)}}):null,H?e.jsx(Li,{value:he,region:ht,startUrl:Jt,onChange:xn,onRegionChange:At,onStartUrlChange:Tt}):null,Ve&&!H?e.jsx(qi,{value:le,onChange:nt}):null,Ve&&!H&&le==="bulk"?e.jsx(Di,{raw:xt,rows:It,activeIndex:Xt,activeRow:mn,checking:Kt,validCount:Ye.length,onRawChange:m=>{st(m),Se([]),Ce(null),B(null)},onCheck:hn}):null,le==="single"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{htmlFor:"connection-account-name",className:"text-xs font-medium text-muted-foreground",children:["Account name ",e.jsx("span",{className:"font-normal text-muted-foreground/70",children:"(optional)"})]}),e.jsx(ne,{id:"connection-account-name",placeholder:"Auto: swayrouter-account",value:c,"aria-invalid":!!ve,"aria-describedby":ve?"connection-submit-error":void 0,onChange:m=>{h(m.target.value),B(null)}})]}),Ft?e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive",children:Ft}):null,pn?e.jsx("p",{className:"text-xs text-muted-foreground",children:e.jsx(ln,{children:"Starting auth flow…"})}):null,Q==="import"?yt?e.jsx(Bi,{raw:A,rows:ze,activeIndex:it,activeRow:En,checking:vt,validCount:ot.length,onRawChange:m=>{b(m),He([]),Ae(null),B(null)},onCheck:Kn}):H?e.jsx(Ii,{mode:he,refreshToken:Gt,clientId:dn,clientSecret:Ze,profileArn:Pt,cliProxyJson:Et,onRefreshTokenChange:ft,onClientIdChange:Mt,onClientSecretChange:De,onProfileArnChange:Yt,onCliProxyJsonChange:Lt}):e.jsx(zi,{providerId:s.id,token:N,machineId:F,importing:pt,message:Mn,hasError:Pn,onTokenChange:K,onMachineIdChange:z,onAutoImport:Rn}):Q==="local"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Local provider — no key required."}):nn?e.jsx(Oi,{isDeviceFlow:lt,isOAuthFlow:We,isKiroIam:H&&he==="iam",authLink:O,userCode:S,deviceStatus:Fe,deviceCode:re,bootLoading:qt,linkCopied:en,oauthCode:T,kiroStartUrl:Jt,onStartKiroAuthorization:gn,onOpenAuthLink:Fn,onCopyAuthLink:On,onOauthCodeChange:G}):e.jsx(Ri,{authLabel:Ot(s.id,"apikey"),apiKey:y,region:ht,checking:Ie,keyValid:Re,checkMsg:Ue,submitError:ve,proxyPoolId:U,proxyOptions:Y,showKiroRegion:H,onApiKeyChange:m=>{C(m),B(null)},onRegionChange:At,onCheck:vn,onProxyPoolChange:_}),ve?e.jsx("p",{id:"connection-submit-error",className:"text-xs text-destructive",role:"alert",children:ve}):null]}):null]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(E,{disabled:le==="bulk"?Rt||Kt||Ye.length===0:!bt,className:ce((le==="bulk"?Rt||Kt||Ye.length===0:!bt)&&"opacity-40"),onClick:()=>void(le==="bulk"?fn():qn()),children:le==="bulk"?Rt?"Adding…":"Add":xe?e.jsx(ln,{children:lt||We?"Waiting…":"Saving…"}):lt?"Poll now":We&&!T.trim()?"Waiting for browser…":In})]})]})})}function os({open:n,onOpenChange:s,onCreate:i,initial:a,submitLabel:u="Create"}){const[c,h]=o.useState(""),[y,C]=o.useState(""),[N,K]=o.useState(""),[A,b]=o.useState("openai-compatible"),[F,z]=o.useState("chat");o.useEffect(()=>{!n||!a||(h(a.name||""),C(a.alias||""),K(a.baseUrl||""),b(a.nodeType==="anthropic-compatible"?"anthropic-compatible":"openai-compatible"),z(a.apiType==="responses"?"responses":"chat"),Y(null),U(!1))},[n,a]);const T=!!a,[G,U]=o.useState(!1),[_,Y]=o.useState(null);return o.useEffect(()=>{n&&(a||(h(""),C(""),K(""),b("openai-compatible"),z("chat"),Y(null),U(!1)))},[n,a]),e.jsx(Ut,{open:n,onOpenChange:s,children:e.jsxs($t,{children:[e.jsx(Qt,{children:e.jsx(Vt,{children:T?"Edit custom provider":"Custom provider"})}),e.jsxs("div",{className:"space-y-3 px-6 pb-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-name",className:"text-xs font-medium text-muted-foreground",children:"Name"}),e.jsx(ne,{id:"custom-provider-name",placeholder:"My provider",value:c,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{h($.target.value),Y(null)}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-prefix",className:"text-xs font-medium text-muted-foreground",children:"Prefix"}),e.jsx(ne,{id:"custom-provider-prefix",placeholder:"my-llm",value:y,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{C($.target.value),Y(null)}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/70",children:"Must be unique across custom providers."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"custom-provider-base-url",className:"text-xs font-medium text-muted-foreground",children:"Base URL"}),e.jsx(ne,{id:"custom-provider-base-url",placeholder:"https://api.example.com/v1",value:N,onChange:$=>K($.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"API format"}),e.jsx(jt,{size:"sm",value:A,onChange:b,options:[{value:"openai-compatible",label:"OpenAI"},{value:"anthropic-compatible",label:"Claude"}]})]}),A==="openai-compatible"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Endpoint style (OpenAI only)"}),e.jsx(jt,{size:"sm",value:F,onChange:z,options:[{value:"chat",label:"Chat"},{value:"responses",label:"Responses"}]})]}):e.jsx("p",{className:"rounded-md border border-border bg-surface px-3 py-2 text-xs text-muted-foreground",children:"Claude-compatible nodes use the Messages API only — no Chat / Responses toggle (BACKEND custom nodes)."}),_?e.jsx("p",{id:"custom-provider-error",className:"text-sm text-destructive",role:"alert",children:_}):null]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(E,{disabled:G,onClick:()=>{if(!c.trim()||!y.trim()){Y("Name and prefix required");return}U(!0),i({name:c.trim(),prefix:y.trim().toLowerCase().replace(/\s+/g,"-"),baseUrl:N.trim()||void 0,type:A,apiType:A==="openai-compatible"?F:void 0}).catch($=>{Y(Z($,"Failed to save custom provider"))}).finally(()=>U(!1))},children:u})]})]})})}function _n({label:n,hint:s,children:i}){return e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:n}),i,s?e.jsx("span",{className:"block text-[10px] text-muted-foreground/70",children:s}):null]})}function Wi({conn:n,onOpenChange:s,onSave:i}){var $,xe;const[a,u]=o.useState(""),[c,h]=o.useState(!1),[y,C]=o.useState(""),[N,K]=o.useState(null),[A,b]=o.useState(!1);o.useEffect(()=>{n&&(u(n.name||""),C(""),K(null))},[n]);const F=String((n==null?void 0:n.authType)||"").trim().toLowerCase(),z=typeof(($=n==null?void 0:n.providerSpecificData)==null?void 0:$.authMethod)=="string"?n.providerSpecificData.authMethod.trim().toLowerCase():"",T=F||z,G=n?kn(n.provider):"apikey",U=T==="apikey"||T==="api_key"||T==="api-key"||!T&&G==="apikey",_=T.includes("oauth")||T==="access_token"||!T&&(G==="oauth"||G==="device")?"OAuth":T.includes("cookie")?"Cookie":T==="local"||T==="none"||!T&&G==="local"?"No authentication":T.includes("import")||T==="imported"?"Imported token":U?"API Key":T||"Managed credentials";async function Y(){if(n){b(!0),K(null);try{const R=await ps(n.id),Ie=R.valid===!0;K({label:Ie?"Active":R.error||"Failed",ok:Ie})}catch(R){K({label:Z(R,"Test failed"),ok:!1})}finally{b(!1)}}}return e.jsx(Ut,{open:!!n,onOpenChange:s,children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsx(Vt,{children:"Edit connection"}),e.jsx(wn,{children:(n==null?void 0:n.name)||((xe=n==null?void 0:n.id)==null?void 0:xe.slice(0,8))})]}),e.jsxs("div",{className:"space-y-3 px-6",children:[e.jsx(_n,{label:"Name",children:e.jsx(ne,{value:a,onChange:R=>u(R.target.value)})}),U?e.jsxs(_n,{label:"API Key",hint:"Leave empty to keep current key",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ne,{type:"password",value:y,onChange:R=>C(R.target.value),placeholder:"sk-… or paste new key",className:"flex-1"}),e.jsx(E,{size:"sm",variant:"outline",disabled:A,"aria-busy":A,"aria-label":A?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void Y(),children:A?e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),N?e.jsx("p",{className:ce("mt-1 text-[11px]",N.ok?"text-success":"text-destructive"),children:N.label}):null]}):e.jsxs(_n,{label:"Authentication",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/25 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:_}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Credentials are managed by this connection."})]}),e.jsx(E,{size:"sm",variant:"outline",disabled:A,"aria-busy":A,"aria-label":A?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void Y(),children:A?e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),N?e.jsx("p",{className:ce("mt-1 text-[11px]",N.ok?"text-success":"text-destructive"),children:N.label}):null]})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(E,{disabled:c,onClick:()=>{h(!0),i(a.trim(),y).finally(()=>h(!1))},children:"Save"})]})]})})}function Cs({id:n,color:s,size:i=24,fallbackIcon:a}){const u=Ms(n);if(u){const c=Math.max(4,Math.round(i/5));return e.jsx("span",{"aria-hidden":"true",className:"block shrink-0",style:{width:i,height:i,borderRadius:c,backgroundColor:s||"currentColor",WebkitMaskImage:`url(${u})`,maskImage:`url(${u})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}})}return e.jsx(a,{className:"shrink-0",style:{width:i*.85,height:i*.85,color:s||void 0}})}function Hi({byProvider:n,filter:s,hiddenProviders:i,loading:a,query:u,providerListRef:c,selectedId:h,sorted:y,onFilterChange:C,onQueryChange:N,onSelectProvider:K,onToggleProviderHidden:A}){return e.jsxs(ws,{className:ce("flex shrink-0 flex-col overflow-hidden","w-full h-[30dvh] max-h-[30dvh] min-h-[13rem] sm:h-[30dvh] sm:max-h-[30dvh] lg:h-full lg:max-h-none lg:min-h-0 lg:w-[300px] xl:w-[340px]"),children:[e.jsxs(ks,{className:"space-y-1.5 border-b border-border p-2.5 sm:space-y-2 sm:p-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(xs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ne,{className:ce("pl-8",u?"pr-8":void 0),placeholder:"Search providers…",value:u,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:b=>N(b.target.value)}),u?e.jsx(ee,{label:"Clear search",children:e.jsx("button",{type:"button","aria-label":"Clear provider search",className:"absolute right-2.5 top-1/2 -translate-y-1/2 rounded p-0.5 text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",onClick:()=>N(""),children:e.jsx(Jn,{className:"h-4 w-4"})})}):null]}),e.jsx(jt,{size:"sm",value:s,onChange:C,options:[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"idle",label:"Idle"}]})]}),e.jsx(js,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsx(ms,{overscrollContain:!0,scrollFade:!0,scrollbarGutter:!0,viewportRef:c,className:"min-h-0 flex-1",children:e.jsx("div",{className:"p-2",children:a?e.jsx("div",{className:"space-y-2 p-1",children:Array.from({length:6}).map((b,F)=>e.jsx(Ai,{className:"h-14 w-full rounded-lg"},F))}):y.length===0?e.jsx("p",{className:"p-6 text-center text-sm text-muted-foreground",children:"No providers match"}):e.jsx("ul",{className:"space-y-1",children:y.map(b=>{const F=n.get(b.id)||[],z=b.id===h?F.length:b.connected||0,T=b.id===h?F.filter(R=>R.isActive!==!1).length:z,G=b.id===h?F.length-T:0,U=h===b.id,_=i.includes(b.id),Y=hs(b.id),$=b.isCustom?"apikey":kn(b.id,b.authType,b.noAuth),xe=$==="apikey"?hi:$==="oauth"||$==="device"?fi:$==="import"?pi:xi;return e.jsx("li",{"data-provider-id":b.id,children:e.jsxs("div",{className:ce("group relative flex w-full items-center rounded-lg transition-colors duration-100",U?"text-foreground":"hover:bg-surface-hover/70",_&&"opacity-55"),children:[U?e.jsx(dt.span,{layoutId:"provider-highlight",className:"absolute inset-0 rounded-lg bg-white/15",transition:{type:"spring",stiffness:520,damping:36,mass:.4}}):null,e.jsxs("button",{type:"button",onClick:()=>K(b.id),className:ce("relative z-10 flex min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-2 text-left outline-none focus-visible:ring-1 focus-visible:ring-white/20 sm:gap-3 sm:px-3 sm:py-2.5"),children:[e.jsxs("span",{className:"relative z-10 flex size-7 shrink-0 items-center justify-center rounded-lg bg-white p-1.5 outline outline-1 outline-white/30 outline-offset-2 sm:size-8",children:[e.jsx(Cs,{id:b.id,color:"var(--background)",size:20,fallbackIcon:Y}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 flex h-3.5 w-3.5 items-center justify-center rounded-full border border-border/60 bg-card/90 text-muted-foreground",children:e.jsx(xe,{className:"h-2 w-2"})})]}),e.jsxs("div",{className:"relative z-10 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 sm:gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium sm:text-sm",children:b.name}),e.jsx(Qn,{variant:"outline",size:"sm",className:"max-w-[5.5rem] truncate font-mono text-[9px] text-muted-foreground sm:max-w-none sm:text-[10px]",children:b.alias||b.id})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[10px] text-muted-foreground sm:gap-x-2 sm:text-[11px]",children:[Ps(b.authType,b.noAuth,b.authModes).map(R=>e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded border border-border bg-background/50 px-1 py-px font-medium sm:gap-1 sm:px-1.5",children:[e.jsx(xe,{className:"h-2.5 w-2.5"}),R]},R)),z>0?e.jsxs(e.Fragment,{children:[G>0?e.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-muted px-1 py-px text-[10px] font-medium text-muted-foreground sm:gap-1 sm:px-1.5 sm:text-[11px]",children:[G," off"]}):null,e.jsxs(pe,{tone:"ok",className:"text-[10px] font-medium sm:text-[11px]",children:[z," connection",z===1?"":"s"]})]}):e.jsx("span",{className:"text-muted-foreground/60",children:"no connections"})]})]})]}),e.jsx(ee,{label:_?"Show provider":"Hide provider",children:e.jsx("button",{type:"button","aria-label":_?`Show ${b.name}`:`Hide ${b.name}`,"aria-pressed":_,onClick:()=>A(b.id),className:"relative z-10 mr-1 flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-[background-color,opacity,color] hover:bg-surface-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring group-hover:opacity-100 sm:mr-2",children:_?e.jsx(gi,{className:"size-3.5"}):e.jsx(vi,{className:"size-3.5"})})})]})},b.id)})})})})})]})}function Ht({busy:n,onTest:s,onStop:i,label:a="Test",disabled:u,compact:c}){return n?e.jsx(ee,{label:"Cancel test",disabled:!c,children:e.jsxs(E,{size:"sm",variant:"outline",onClick:i,"aria-label":c?"Cancel test":void 0,className:ce(c&&"h-7 w-7 p-0",!c&&"gap-1.5"),children:[e.jsx(cn,{className:"h-3.5 w-3.5 animate-spin"}),c?null:"Cancel"]})}):e.jsx(ee,{label:a,disabled:!c,children:e.jsx(E,{size:"sm",variant:"outline",disabled:u,onClick:s,"aria-label":c?a:void 0,className:c?"h-7 px-2 text-[11px]":void 0,children:a})})}function Nn(n,s){const i=String(n||"").trim();if(!i)return i;const a=String(s||"").trim().toLowerCase();if(!(a==="clinepass"||a==="cline-pass"||/^(?:clinepass|cline-pass)\//i.test(i)))return i;let c=i.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,"");return c=c.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,""),`clinepass/${c}`}const Ji=["vision","pdf","audioInput","videoInput","imageOutput","audioOutput","search","tools","reasoning"];function Vn(n){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n,i={};for(const a of Ji)typeof s[a]=="boolean"&&(i[a]=s[a]);if((typeof s.thinkingFormat=="string"||s.thinkingFormat===null)&&(i.thinkingFormat=s.thinkingFormat),typeof s.thinkingCanDisable=="boolean"&&(i.thinkingCanDisable=s.thinkingCanDisable),s.thinkingRange&&typeof s.thinkingRange=="object"&&!Array.isArray(s.thinkingRange)){const a=s.thinkingRange,u={};Number.isFinite(Number(a.min))&&(u.min=Number(a.min)),Number.isFinite(Number(a.max))&&(u.max=Number(a.max)),i.thinkingRange=u}else s.thinkingRange===null&&(i.thinkingRange=null);for(const a of["contextWindow","maxOutput"])Number.isFinite(Number(s[a]))&&(i[a]=Number(s[a]));return Object.keys(i).length?i:void 0}const Gi=[["vision","Vision"],["pdf","PDF"],["audioInput","Audio"],["videoInput","Video"],["imageOutput","Image out"],["audioOutput","Audio out"],["search","Search"],["tools","Tools"],["reasoning","Reasoning"]];function Yi(n){return n?Gi.filter(([s])=>n[s]===!0).map(([s,i])=>({key:s,label:i})):[]}function Un(n,s){return Array.isArray(n)?n.flatMap(i=>{if(!i||typeof i!="object"||Array.isArray(i))return[];const a=i,u=typeof a.id=="string"?a.id.trim():typeof a.model=="string"?a.model.trim():"",c=Nn(u,s);if(!c)return[];const h=typeof a.name=="string"&&a.name.trim()?a.name.trim():c,y=Array.isArray(a.thinkingLevels)?a.thinkingLevels.filter(C=>typeof C=="string"):void 0;return[{id:c,name:h,caps:Vn(a.capabilities??a.caps),...y?{thinkingLevels:y}:{}}]}):[]}function ls(n,s){if(!n)return!0;const i=n.trim().toLowerCase(),a=s.trim().toLowerCase();return i===a||i===a.replace(/^clinepass\//,"")||/^cline-pass\//.test(i)||/^clinepass\/cline-pass\//.test(i)}function Xi(n,s){var a;const i=new Map;for(const u of n){const c=Nn(u.id,u.provider_alias||u.provider_id||u.owned_by||s);if(!c)continue;const h=c===u.id?u:{...u,id:c},y=i.get(c);if(!y){i.set(c,h);continue}const C=ls(y.name,c)&&!ls(h.name,c)?h.name:y.name||h.name;i.set(c,{...y,name:C,provider_alias:y.provider_alias||h.provider_alias,provider_id:y.provider_id||h.provider_id,owned_by:y.owned_by||h.owned_by,caps:{...h.caps,...y.caps},thinkingLevels:(a=y.thinkingLevels)!=null&&a.length?y.thinkingLevels:h.thinkingLevels})}return[...i.values()]}function Zi({selected:n,visibleModels:s,models:i,modelNames:a,modelsLoading:u,modelsUnavailable:c,importingModels:h,testConnId:y,batchKind:C,modelTestLock:N,testingModels:K,modelQuery:A,newModel:b,addingModel:F,modelResults:z,pinnedFor:T,copied:G,onImportModels:U,onTestAllModels:_,onStopTests:Y,onStopModel:$,onModelQueryChange:xe,onNewModelChange:R,onAddModel:Ie,onTogglePin:Ke,onCopyModelId:Re,onTestModel:ge,onRemoveModel:Ue,disabledModelIds:te,onToggleDisabled:ve}){return e.jsx(bs,{value:"models",className:"flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden",children:e.jsx("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain touch-pan-y [-webkit-overflow-scrolling:touch]",children:e.jsxs("div",{className:"min-w-0 space-y-3 p-3 sm:p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.length," models"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.id==="codebuddy-cn"||n.id==="codebuddy-intl"?e.jsx("span",{className:"self-center text-xs text-muted-foreground",children:"Add models manually"}):n.id!=="qoder"?e.jsx(ee,{label:y?"Fetch GET {base}/models with this connection’s key":"Needs a connection (API key) on this provider — or set base URL on a custom node",children:e.jsx(E,{size:"sm",variant:"outline",disabled:h,onClick:()=>void U(),children:h?"Importing…":"Import"})}):null,i.length>0?e.jsx(Ht,{busy:C==="model",label:"Test all",disabled:!y||N||C!==null&&C!=="model"||K.size>0&&C!=="model",onTest:()=>void _(),onStop:Y}):null]})]}),e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:flex",children:[e.jsx(ne,{placeholder:"Search models…",value:A,onChange:B=>xe(B.target.value),className:"min-w-0 sm:flex-1"}),e.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2 sm:contents",children:[e.jsx(ne,{placeholder:"model-id",value:b,disabled:F,onChange:B=>R(B.target.value),onKeyDown:B=>{B.key==="Enter"&&Ie()},className:"min-w-0"}),e.jsxs(E,{size:"sm",variant:"outline",disabled:F||!b.trim(),onClick:()=>void Ie(),className:"w-full sm:w-auto",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Add"]})]})]}),u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading models…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:A.trim()?"No models match your search.":c?"Upstream model catalog unavailable — add a slug above or retry.":"No models — add a slug above."}):e.jsx(dt.div,{layout:!0,className:"space-y-1",children:s.map(B=>{const O=B.id,ie=z[O],re=K.has(O),ye=Yi(B.caps),Oe=C==="model"||re,L=T.includes(O),S=te.has(O);return e.jsx(dt.div,{layout:!0,transition:{layout:{type:"spring",stiffness:520,damping:36,mass:.4}},className:ce("rounded-md border border-border bg-background px-2.5 py-2 hover:border-foreground/30",S&&"border-warning/40 bg-warning/[0.03]"),children:e.jsxs("div",{className:"group flex flex-wrap items-center gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:[a.get(O)?e.jsx("span",{className:"min-w-0 max-w-[45%] truncate text-xs font-medium",children:a.get(O)}):null,e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",children:O}),S?e.jsx(Qn,{size:"sm",variant:"warning",children:"Disabled"}):null,re||ie?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[re?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${O}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,ie?e.jsx(ee,{label:ie.message||ie.label,children:e.jsx(pe,{tone:ie.ok?"ok":"err",className:"max-w-[9rem] truncate text-[10px] font-semibold",children:ie.label})}):null]}):null,ye.length>0?e.jsx("div",{className:"order-last flex min-w-0 w-full shrink-0 flex-nowrap items-center gap-1 overflow-x-auto pb-0.5 sm:order-none sm:w-auto sm:flex-wrap sm:overflow-visible sm:pb-0","aria-label":"Model capabilities",children:ye.map(ae=>e.jsx(ee,{label:ae.label,children:e.jsx(Qn,{size:"sm",variant:"outline","aria-label":ae.label,className:"shrink-0",children:ae.label})},ae.key))}):null]}),e.jsxs("div",{className:"flex w-full shrink-0 items-center justify-end gap-1 border-t border-border/60 pt-1.5 sm:w-auto sm:justify-start sm:border-0 sm:pt-0",children:[e.jsx(ee,{label:L?"Unpin":"Pin to top",children:e.jsx("button",{type:"button","aria-label":L?"Unpin model":"Pin model to top",onClick:()=>Ke(O),className:ce("inline-flex h-7 w-7 items-center justify-center rounded-md border p-0 transition-colors duration-150",L?"border-transparent bg-white/15 text-foreground":"border-transparent text-muted-foreground hover:border-border hover:bg-surface-hover hover:text-foreground"),children:e.jsx(Gn,{initial:!1,mode:"wait",children:e.jsx(dt.span,{initial:{opacity:0,scale:.7,rotate:-18},animate:{opacity:1,scale:1,rotate:0},exit:{opacity:0,scale:.7,rotate:18},transition:{duration:.14},className:"block",children:L?e.jsx(yi,{className:"h-3.5 w-3.5"}):e.jsx(bi,{className:"h-3.5 w-3.5"})},L?"pinned":"unpinned")})})}),e.jsx(ee,{label:G===O?"Copied":"Copy model ID",children:e.jsx("button",{type:"button","aria-label":"Copy model ID",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground",onClick:()=>void Re(O),children:G===O?e.jsx(Sn,{className:"h-3.5 w-3.5"}):e.jsx(Hn,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:S?"Enable routing for model":"Disable routing for model",children:e.jsx("button",{type:"button","aria-label":S?"Enable routing for model":"Disable routing for model","aria-pressed":S,onClick:()=>void ve(O),className:ce("inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground",S&&"text-warning hover:text-warning"),children:S?e.jsx(wi,{className:"h-3.5 w-3.5"}):e.jsx(ki,{className:"h-3.5 w-3.5"})})}),e.jsx("span",{className:"sm:hidden",children:e.jsx(Ht,{compact:!0,busy:Oe,disabled:!y||N||C==="conn"||!re&&K.size>=4,onTest:()=>void ge(O,y),onStop:()=>C==="model"?Y():$(O)})}),e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Ht,{busy:Oe,disabled:!y||N||C==="conn"||!re&&K.size>=4,onTest:()=>void ge(O,y),onStop:()=>C==="model"?Y():$(O)})}),e.jsx(ee,{label:"Remove",children:e.jsx("button",{type:"button","aria-label":"Remove model",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-destructive",onClick:()=>void Ue(O),children:e.jsx(jn,{className:"h-3.5 w-3.5"})})})]})]})},O)})})]})})})}const er=["auto","low","medium","high","xhigh","max"],$n=["auto","low","medium","high","max"],tr={openai:er,claude:$n,deepseek:["auto","low","high","max"],groq:["auto","low","medium","high"],openrouter:$n,kimi:$n,glm:["auto","low","medium","high"],minimax:["auto","low","medium","high"],kiro:["auto","low","medium","high"],codex:["auto","low","medium","high","xhigh"],github:["auto","low","medium","high"],cursor:["auto","low","medium","high"],"gemini-cli":["auto","low","medium","high"],"grok-cli":["auto","low","medium","high"],"ollama-local":["auto","low","medium","high"],antigravity:["auto","low","medium","high"],qwen:["auto","low","medium","high"],"codebuddy-cn":["auto","low","medium","high"]},nr=["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"],cs={"x-high":"xhigh",maximum:"max"};function Yn(n){const s=String(n||"").trim().toLowerCase();return s?s in cs?cs[s]:["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"].includes(s)?s:null:null}function sr(n){if(!Array.isArray(n==null?void 0:n.options))return[];const s=n.options.flatMap(u=>{const c=Yn(u);return c?[c]:[]}),i=[...new Set(s)];if(!i.length)return[];const a=i.every(u=>["auto","on","off"].includes(u));return!i.includes("auto")&&!a&&i.unshift("auto"),i}function ir(n){return Array.isArray(n)?n.flatMap(s=>{const i=Yn(s);return i?[i]:[]}):[]}function rr(n,s,i){if((i==null?void 0:i.modelAware)===!1)return Wn(n,i);const a=s.map(c=>new Set(ir(c))).filter(c=>c.size>0);return a.length?["auto",...nr.filter(c=>c!=="auto"&&c!=="none"&&a.some(h=>h.has(c)))]:n.startsWith("openai-compatible-")||n.startsWith("anthropic-compatible-")?null:Wn(n,i)}function Wn(n,s){if(n.startsWith("openai-compatible-")||n.startsWith("anthropic-compatible-"))return["auto","low","medium","high","max"];const i=sr(s);return i.length>0?i:tr[n]||null}function ar(n,s){const i=Wn(n,s),a=Yn(s==null?void 0:s.defaultMode);return a&&(i!=null&&i.includes(a))?a:!(i!=null&&i.length)||i.includes("auto")?"auto":i.includes("high")?"high":i[0]}function or(n){return n==="auto"?"Auto":n==="xhigh"?"xHigh":n==="thinking"?"Thinking":n.charAt(0).toUpperCase()+n.slice(1)}function lr(n){if(!n)return null;const s=Date.parse(n);if(!Number.isFinite(s))return null;const i=Math.max(0,Math.floor((Date.now()-s)/1e3));if(i<10)return"just now";if(i<60)return`${i}s ago`;const a=Math.floor(i/60);if(a<60)return`${a}m ago`;const u=Math.floor(a/60);return u<24?`${u}h ago`:`${Math.floor(u/24)}d ago`}function cr({selected:n,connsAll:s,conns:i,strategy:a,strategyPending:u,stickyDraft:c,thinkingLevels:h,thinkingValue:y,thinkingPending:C,selectedKeys:N,connectionsCapped:K,totalConnections:A,batchKind:b,testingConnId:F,togglingConnId:z,connQuery:T,connListRef:G,connVirtualizer:U,connResults:_,onStrategyChange:Y,onStickyDraftChange:$,onSaveSticky:xe,onThinkingChange:R,onRequestBulkDelete:Ie,onClearSelection:Ke,onToggleSelection:Re,onSelectAll:ge,onTestConnections:Ue,onTestConnection:te,onStopTests:ve,onConnQueryChange:B,onOpenAddConnection:O,onMovePriority:ie,onToggleConnection:re,onEditConnection:ye,onDeleteConnection:Oe}){return e.jsx(bs,{value:"connections",className:"flex min-h-0 min-w-0 flex-1 basis-0 flex-col overflow-hidden p-1.5 sm:p-5",children:e.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 basis-0 flex-col gap-1.5 overflow-hidden sm:gap-3",children:[e.jsxs("div",{className:"flex shrink-0 flex-wrap items-end justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5 sm:space-y-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5 sm:gap-x-3 sm:gap-y-2",children:[e.jsxs("div",{className:"flex min-w-0 basis-full items-center gap-1.5 sm:basis-auto sm:gap-2",children:[e.jsx("span",{className:"text-[11px] font-medium text-muted-foreground sm:hidden",children:"Routing"}),e.jsx("span",{className:"hidden whitespace-nowrap text-xs font-medium text-muted-foreground sm:inline",children:"Account routing:"}),e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden sm:flex-none",children:e.jsx(jt,{size:"sm",className:"w-full min-w-0 sm:w-auto sm:min-w-[15rem] sm:flex-none",value:a,disabled:u,onChange:Y,options:[{value:"fill-first",label:"Fill-first",mobileLabel:"Fill"},{value:"round-robin",label:"Round-robin",mobileLabel:"Round"},{value:"least-inflight",label:"Least-inflight",mobileLabel:"Least"}]})})]}),e.jsxs("div",{className:ce("inline-flex items-center gap-1.5 sm:gap-1.5",a!=="round-robin"&&"hidden sm:inline-flex"),children:[e.jsx("label",{htmlFor:"provider-sticky-limit",className:"text-xs font-medium text-muted-foreground",children:"Sticky"}),e.jsx(ne,{id:"provider-sticky-limit",size:"sm",type:"number",min:1,value:c,disabled:u||a!=="round-robin",onChange:L=>$(L.target.value),className:"w-14 shrink-0"}),e.jsx(E,{size:"sm",variant:"outline",disabled:u||a!=="round-robin",onClick:xe,children:"Save"})]})]}),h&&h.length>0?e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-2",children:[e.jsx("span",{className:"shrink-0 text-xs font-medium text-muted-foreground",children:"Thinking Mode:"}),e.jsx("div",{className:"w-full min-w-0 max-w-[26rem] overflow-hidden pb-0.5 sm:flex-none sm:overflow-visible sm:pb-0",children:e.jsx(jt,{size:"compact",value:y,disabled:C,onChange:R,options:h.map(L=>({value:L,label:or(L),compactLabel:L==="minimal"?"Min":L==="medium"?"Med":L==="thinking"?"Think":L==="ultra"?"Ultra":void 0})),className:"w-full min-w-0 gap-1 p-1"})})]}):null]}),s.length>0?e.jsx("div",{className:"flex w-full shrink-0 flex-wrap items-center justify-start gap-2 sm:justify-end xl:w-auto",children:N.size>0?e.jsxs(e.Fragment,{children:[e.jsxs(E,{size:"sm",variant:"destructive",onClick:Ie,children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),"Delete selected"]}),e.jsx(E,{size:"sm",variant:"outline",onClick:Ke,children:"Unselect"}),e.jsx(Ht,{busy:b==="conn"||i.some(L=>F===L.id),label:"Test selected",onTest:()=>void Ue([...N]),onStop:ve})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"outline",onClick:ge,children:"Select all"}),e.jsx(Ht,{busy:b==="conn"||i.some(L=>F===L.id),label:"Test all",onTest:()=>void Ue(i.map(L=>L.id)),onStop:ve})]})}):null]}),K?e.jsxs("div",{className:"shrink-0 rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-[11px] text-warning",children:["Showing the first ",s.length.toLocaleString()," of ",A.toLocaleString()," connections. Use search to find accounts beyond this limit."]}):null,s.length>0?e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(xs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(ne,{className:"h-8 pl-8 text-xs",placeholder:"Search name, id, key hint…",value:T,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:L=>B(L.target.value)})]}):null,s.length===0?e.jsx("div",{className:"rounded-lg border border-dashed border-border px-4 py-10 text-center text-sm text-muted-foreground",children:n.noAuth?"No connection required":e.jsxs(e.Fragment,{children:["No connections yet",e.jsx("div",{className:"mt-3",children:e.jsxs(E,{size:"sm",onClick:O,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),Tn(n.authType,n.noAuth)]})})]})}):i.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border px-4 py-8 text-center text-sm text-muted-foreground",children:['No matches for "',T,'"']}):e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:e.jsx(ms,{overscrollContain:!0,scrollFade:!0,viewportRef:G,className:"absolute inset-0",children:e.jsx("div",{className:"touch-pan-y [-webkit-overflow-scrolling:touch]",children:e.jsx("div",{className:"relative w-full",style:{height:`${U.getTotalSize()}px`},children:U.getVirtualItems().map(L=>{const S=i[L.index];if(!S)return null;const ae=L.index,ut=N.has(S.id),de=_[S.id],Fe=F===S.id,oe=S.isActive===!1,be=S.testStatus==="stale"||S.testStatus==="expired",je=S.healthStatus&&S.healthStatus!=="unknown"?S.healthStatus:S.testStatus==="active"?"healthy":S.testStatus==="error"?"error":null,qe=S.lastTested?lr(S.lastTested):null;return e.jsx("div",{"data-index":L.index,ref:U.measureElement,className:"absolute left-0 top-0 w-full pb-1",style:{transform:`translateY(${L.start}px)`},children:e.jsx("div",{className:ce("rounded-lg border bg-surface px-2 py-1.5 sm:p-3 transition-[border-color,background-color] duration-150 ease-out",ut?"border-foreground/40":oe?"border-border/70 bg-muted/30 text-muted-foreground opacity-60":"border-border hover:border-border/80 hover:bg-surface-hover/40"),children:e.jsxs("div",{className:"flex flex-nowrap items-center gap-1 sm:gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 sm:gap-2.5",children:[e.jsx(Mi,{checked:ut,onCheckedChange:()=>{Re(S.id)}}),e.jsxs("div",{className:"hidden shrink-0 flex-col gap-0.5 sm:flex",children:[e.jsx(ee,{label:"Move up",children:e.jsx("button",{type:"button",disabled:ae===0,onClick:()=>void ie(S.id,-1),"aria-label":"Move up",className:"rounded p-0.5 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-30",children:e.jsx(ji,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:"Move down",children:e.jsx("button",{type:"button",disabled:ae===i.length-1,onClick:()=>void ie(S.id,1),"aria-label":"Move down",className:"rounded p-0.5 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground disabled:opacity-30",children:e.jsx(Ci,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx("span",{className:"truncate text-[13px] font-medium leading-tight sm:text-sm",children:S.name||S.email||S.id.slice(0,8)}),Fe?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${S.name||S.email||S.id}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,de&&!de.ok?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"hidden max-w-[4.5rem] shrink truncate text-[10px] font-medium text-destructive sm:inline sm:max-w-none",children:de.label}),e.jsx(ee,{label:"Copy full error",children:e.jsx("button",{type:"button",className:"hidden rounded p-0.5 text-muted-foreground hover:text-foreground sm:inline-flex","aria-label":"Copy full error",onClick:mt=>{mt.stopPropagation(),navigator.clipboard.writeText(de.message||"").catch(()=>{})},children:e.jsx(Hn,{className:"h-3 w-3"})})})]}):null]}),e.jsxs("div",{className:"mt-0.5 hidden flex-wrap items-center gap-x-1.5 text-[11px] text-muted-foreground sm:flex",children:[e.jsxs("span",{children:["#",ae+1]}),je?e.jsx(ee,{label:S.healthError||(je==="healthy"?"Connection is healthy":"Connection has an error"),children:e.jsx(pe,{tone:je==="healthy"?"ok":"err",className:"max-w-[10rem] truncate text-[10px]",children:je==="healthy"?"OK":"Error"})}):null,qe?e.jsxs("span",{children:["checked ",qe]}):null,be?e.jsx(ee,{label:S.lastError||"Credentials may be expired; reconnect this provider.",children:e.jsx(pe,{tone:"warn",className:"max-w-[10rem] truncate text-[10px]",children:"Stale"})}):null,oe?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:"off"})]}):null]}),de||je||qe||be?e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 sm:hidden",children:[de?e.jsx(ee,{label:de.message||de.label,children:e.jsx(pe,{tone:de.ok?"ok":"err",className:"text-[10px] font-semibold",children:de.ok?"Success":de.label})}):je?e.jsx(pe,{tone:je==="healthy"?"ok":"err",className:"text-[10px] font-semibold",children:je==="healthy"?"Healthy":"Error"}):null,qe?e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["checked ",qe]}):null,be?e.jsx(pe,{tone:"warn",className:"text-[10px] font-semibold",children:"Stale"}):null]}):null]})]}),e.jsxs("div",{className:"ml-auto flex shrink-0 flex-nowrap items-center gap-0.5 sm:gap-1.5",children:[e.jsx(Ti,{active:S.isActive!==!1,disabled:z===S.id,onToggle:()=>void re(S.id),activeLabel:"",inactiveLabel:""}),e.jsx(ee,{label:Fe?"Stop":"Test",children:e.jsx(E,{size:"icon-sm",variant:"outline",className:"h-7 w-7 sm:hidden","aria-label":Fe?"Stop test":"Test connection",onClick:()=>Fe?ve():void te(S.id),children:Fe?e.jsx(Ni,{className:"h-3 w-3 fill-current"}):e.jsx(Si,{className:"h-3.5 w-3.5 fill-current"})})}),e.jsx("span",{className:"hidden sm:inline-flex [&>button]:h-7 [&>button]:text-sm",children:e.jsx(Ht,{busy:Fe,onTest:()=>void te(S.id),onStop:ve})}),e.jsx(ee,{label:"Edit",children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",onClick:()=>ye(S),"aria-label":"Edit connection",children:[e.jsx(gs,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Edit"})]})}),e.jsx(ee,{label:"Delete",children:e.jsxs(E,{size:"sm",variant:"outline",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",onClick:()=>Oe(S.id),"aria-label":"Delete connection",children:[e.jsx(jn,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})]})})},S.id)})})})})})]})})}function dr({selected:n,conns:s,activeConns:i,onEditCustom:a,onDeleteCustom:u,onAddConnection:c}){return e.jsxs(ks,{className:"flex shrink-0 flex-row flex-wrap items-start justify-between gap-2 border-b border-border p-3 sm:gap-3 sm:p-5",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-white p-1.5 outline outline-1 outline-white/30 outline-offset-2 sm:h-9 sm:w-9",children:e.jsx(Cs,{id:n.id,color:"var(--background)",size:24,fallbackIcon:hs(n.id)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-base font-semibold sm:text-lg",children:n.name}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground sm:mt-1 sm:gap-2 sm:text-sm",children:[e.jsx("span",{className:"font-mono text-xs",children:n.alias||n.id}),s.length>0?e.jsx(pe,{tone:"ok",children:"Active"}):e.jsx(pe,{tone:"muted",children:"Idle"}),e.jsxs("span",{children:[s.length," connection",s.length===1?"":"s",s.filter(h=>h.healthStatus==="healthy").length>0?` · ${s.filter(h=>h.healthStatus==="healthy").length} OK`:"",s.filter(h=>h.healthStatus==="error").length>0?` · ${s.filter(h=>h.healthStatus==="error").length} error${s.filter(h=>h.healthStatus==="error").length===1?"":"s"}`:"",i.length<s.length?` · ${s.length-i.length} off`:""]}),n.isCustom&&n.baseUrl?e.jsx("span",{className:"hidden truncate text-xs sm:inline",children:n.baseUrl}):null]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.isCustom?e.jsxs(e.Fragment,{children:[e.jsx(ee,{label:"Edit custom provider",children:e.jsxs(E,{size:"sm",variant:"outline",className:"px-2 sm:px-3","aria-label":"Edit custom provider",onClick:a,children:[e.jsx(gs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Edit"})]})}),e.jsx(ee,{label:"Remove custom provider",children:e.jsxs(E,{size:"sm",variant:"destructive",className:"px-2 sm:px-3","aria-label":"Remove custom provider",onClick:u,children:[e.jsx(jn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Remove"})]})})]}):null,n.noAuth?null:e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs(E,{size:"sm",className:"px-2 sm:px-3",onClick:c,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:Tn(n.authType,n.noAuth)}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})})]})]})}function ur({deleteId:n,bulkDeleteIds:s,bulkDeleting:i,deleteProvider:a,connections:u,onCloseDelete:c,onDeleteConnection:h,onCloseBulkDelete:y,onDeleteSelectedConnections:C,onCloseProvider:N,onRemoveProvider:K}){const A=a?u.filter(b=>b.provider===a.id):[];return e.jsxs(e.Fragment,{children:[e.jsx(Ut,{open:!!n,onOpenChange:b=>!b&&c(),children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsx(Vt,{children:"Delete connection?"}),e.jsx(wn,{children:"Removes this key / session."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:c,children:"Cancel"}),e.jsx(E,{variant:"destructive",onClick:h,children:"Delete"})]})]})}),e.jsx(Ut,{open:!!s,onOpenChange:b=>{!b&&!i&&y()},children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsxs(Vt,{children:["Delete ",(s==null?void 0:s.length)??0," selected connections?"]}),e.jsx(wn,{children:"This will remove the selected keys or sessions. This action cannot be undone."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",disabled:i,onClick:y,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:i,onClick:C,children:i?"Deleting…":"Delete"})]})]})}),e.jsx(Ut,{open:!!a,onOpenChange:b=>{b||N()},children:e.jsxs($t,{children:[e.jsxs(Qt,{children:[e.jsxs(Vt,{children:["Remove ",a==null?void 0:a.name,"?"]}),e.jsx(wn,{children:A.length>0?e.jsxs(e.Fragment,{children:["This provider has ",e.jsxs("strong",{children:[A.length," connection(s)"]})," that will also be deleted:",e.jsx("ul",{className:"mt-2 list-disc pl-4 text-xs",children:A.map(b=>e.jsx("li",{children:b.name||b.id},b.id))})]}):"This will remove the provider from the list."})]}),e.jsxs(Wt,{children:[e.jsx(E,{variant:"outline",onClick:N,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:!a,onClick:()=>{a&&K(a)},children:"Remove"})]})]})})]})}async function Xn(n){const{data:s}=await Ct.get("/models/custom");return s.models??[]}async function mr(n,s){let i=0;for(const u of s)try{const c=typeof u=="string"?{id:u}:u,h=await Ns(n,c.id,c.name,c.capabilities);i+=h.added}catch{}const a=await Xn();return{added:i,total:a.length,models:a}}async function Ns(n,s,i,a){const{data:u}=await Ct.post("/models/custom",{providerAlias:n,id:s,name:i,capabilities:a}),c=await Xn();return{added:u.added===!0?1:0,total:c.length,models:c}}async function hr(n,s){const{data:i}=await Ct.delete("/models/custom",{params:{providerAlias:n,id:s}});return{success:i.success!==!1,removed:i.success!==!1}}async function fr(){const{data:n}=await Ct.get("/models/disabled");return n.disabled??{}}async function pr(n,s){await Ct.post("/models/disabled",{providerAlias:n,ids:s})}async function xr(n,s){await Ct.delete("/models/disabled",{params:{providerAlias:n,id:s}})}function gr(n,s){return n!==s}const vr=50,ds=1e3;function qr(n,s=42){let i=n.trim();if(!i)return"Failed";i=i.replace(/^\s*(?:error|err|failed?)\s*[:\-]\s*/i,""),i=i.replace(/^\s*status\s+\d{3}\s*[:\-]?\s*/i,"");try{const a=JSON.parse(i);if(a&&typeof a=="object"){const u=a,c=u.error??u.message??u.detail;if(typeof c=="string")i=c.trim();else if(c&&typeof c=="object"){const h=c;i=String(h.message??h.type??h.code??i).trim()}}}catch{}return i=i.replace(/\s+/g," ").replace(/[.。]+$/,""),i.length<=s?i:`${i.slice(0,Math.max(1,s-1)).trimEnd()}…`}function on(n){const s=n.status??null,i=(n.message||n.error||"").trim(),a=n.latencyMs!=null&&Number.isFinite(Number(n.latencyMs))?Math.round(Number(n.latencyMs)):null;if(n.ok){const h=a!=null?`OK · ${a}ms`:"OK";return{ok:!0,label:h,message:h,status:s,detail:null}}let u="";if(s!=null&&String(s).trim()!==""){const h=String(s).trim();isNaN(Number(h))||(u=h)}if(!u&&i){const h=i.match(/^(\d{3})[:\s]/);if(h)u=h[1];else{const y=i.match(/\bHTTP\s+(\d{3})\b/i);if(y)u=y[1];else if(i.startsWith("status ")){const C=i.replace(/^status\s+/,"").match(/^(\d{3})/);C&&(u=C[1])}}}const c=u?`Error ${u}`:"Error";return{ok:!1,label:c,message:i||c,status:s,detail:n.detail&&n.detail!==i?n.detail:null}}function us(n){var s,i;if(_t.isAxiosError(n)){const a=n,u=((s=a.response)==null?void 0:s.status)??null,c=(i=a.response)==null?void 0:i.data;let h="";typeof(c==null?void 0:c.error)=="string"?h=c.error:c!=null&&c.error&&typeof c.error=="object"&&(h=c.error.message||c.error.type||c.error.code||"");const y=typeof(c==null?void 0:c.error)=="string"?c.error:"";h=(/^(?:test failed|internal server error)$/i.test(y)?c==null?void 0:c.message:y)||(c==null?void 0:c.message)||a.message||"Test failed";let N=null;try{c&&(N=JSON.stringify(c,null,2))}catch{N=null}return on({ok:!1,status:u,message:h,detail:N})}return on({ok:!1,message:Z(n,"Test failed")})}function Dr(){var p,w,x,M,q;const n=Ss(),s="nr-selected-provider",[i,a]=o.useState(()=>{try{return localStorage.getItem(s)}catch{return null}});function u(t){if(gr(i,t)){vt(null),ze([]),et({}),tt({}),te(new Set),a(t);try{t?localStorage.setItem(s,t):localStorage.removeItem(s)}catch{}}}const[c,h]=o.useState(""),[y,C]=o.useState("all"),[N,K]=o.useState(()=>{try{const t=JSON.parse(localStorage.getItem("nr-hidden-providers")||"[]");return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}),[A,b]=o.useState(!1),[F,z]=o.useState(null),[T,G]=o.useState(null),[U,_]=o.useState(null),[Y,$]=o.useState(!1),[xe,R]=o.useState(null),[Ie,Ke]=o.useState(!1),[Re,ge]=o.useState(null),[Ue,te]=o.useState(new Set),[ve,B]=o.useState(0),[O,ie]=o.useState({}),[re,ye]=o.useState(""),[Oe,L]=o.useState(!1),[S,ae]=o.useState(!1),[ut,de]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-pinned-models")||"{}")}catch{return{}}}),[Fe,oe]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-hidden-models")||"{}")}catch{return{}}}),[be,je]=o.useState("");function qe(t,r){oe(l=>{const v={...l,[t]:Array.from(new Set([...l[t]||[],r]))};try{localStorage.setItem("nr-hidden-models",JSON.stringify(v))}catch{}return v})}function mt(t,r){r.length&&oe(l=>{const v=new Set(r.map(V=>V.trim()).filter(Boolean)),g=new Set([...v].map(V=>V.slice(V.lastIndexOf("/")+1))),f=(l[t]||[]).filter(V=>{const W=String(V),me=W.slice(W.lastIndexOf("/")+1);return!v.has(W)&&!g.has(me)}),j={...l};f.length?j[t]=f:delete j[t];try{localStorage.setItem("nr-hidden-models",JSON.stringify(j))}catch{}return j})}const[Xe,Nt]=o.useState(0),[he,St]=o.useState(""),[ht,At]=o.useState(null),[Jt,Tt]=o.useState(null),[Gt,ft]=o.useState(()=>new Set),[dn,Mt]=o.useState(!1),Ze=o.useRef(!1),De=o.useRef(new Map),Pt=4,[Yt,Et]=o.useState(null),[Lt,pt]=o.useState(null),$e=o.useRef(null),[Mn,et]=o.useState({}),[Pn,tt]=o.useState({}),[le,nt]=o.useState("connections"),xt=o.useRef(null),st=o.useRef(null),It=o.useRef(0),[Se,Kt]=o.useState(""),[gt,Xt]=o.useState(""),[Ce,Rt]=o.useState(1),[Zt,ze]=o.useState([]),[He,vt]=o.useState(null);o.useEffect(()=>{const t=window.setTimeout(()=>{Xt(Se.trim())},250);return()=>window.clearTimeout(t)},[Se]);const Be=ct({queryKey:["connections",i,Ce,gt],queryFn:()=>Gs({provider:i,page:Ce,pageSize:vr,search:gt||void 0}),enabled:!!i,retry:!1,refetchInterval:3e4});o.useEffect(()=>{Rt(1),vt(null),ze([])},[i,gt]),o.useEffect(()=>{var r;const t=((r=Be.data)==null?void 0:r.connections)??[];if(i){if(!t.length&&Ce===1){ze([]),vt(i);return}ze(l=>{const v=Ce===1?[]:l,g=new Set(v.map(k=>k.id));return[...v,...t.filter(k=>!g.has(k.id))].slice(0,ds)}),vt(i)}},[Be.data,Ce,i]);const it=He===i?Zt:[],Ae=(p=Be.data)==null?void 0:p.pagination,Ot=!!(Ae!=null&&Ae.hasNext&&it.length>=ds);o.useEffect(()=>{const t=st.current;if(!t)return;const r=()=>{It.current=t.scrollTop};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[]),o.useLayoutEffect(()=>{const t=st.current;t&&(t.scrollTop=It.current)},[i]),o.useEffect(()=>{const t=xt.current;if(!t||le!=="connections")return;const r=()=>{var v;const l=(v=Be.data)==null?void 0:v.pagination;!(l!=null&&l.hasNext)||Be.isFetching||Ot||t.scrollTop+t.clientHeight>=t.scrollHeight-240&&Rt(g=>g+1)};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[Ot,(w=Be.data)==null?void 0:w.pagination,Be.isFetching,le]);const Ft=ct({queryKey:["providers-available"],queryFn:Ys,retry:!1}),ue=ct({queryKey:["settings"],queryFn:Is,retry:!1}),en=ct({queryKey:["nodes"],queryFn:ni,retry:!1}),Qe=ct({queryKey:["custom-models"],queryFn:()=>Xn(),enabled:!!i,staleTime:0,refetchOnMount:"always",retry:!1,placeholderData:t=>t}),qt=ct({queryKey:["disabled-models"],queryFn:fr,retry:!1}),Te=ct({queryKey:["available-models",Xe],queryFn:async()=>((await Ct.get("/models")).data.models??[]).map(r=>({id:Nn(r.routedModel||r.fullModel,r.provider),name:r.name||r.model,provider_alias:r.provider,provider_id:r.provider,owned_by:r.provider,caps:Vn(r.caps),thinkingLevels:Array.isArray(r.thinkingLevels)?r.thinkingLevels:void 0})),retry:!1});function P(t,r="default"){r==="success"?kt.success(t):r==="error"?kt.error(t):r==="warning"?kt.warning(t):kt(t)}const rt=o.useMemo(()=>{const t=Ft.data??[],r=new Set(t.map(g=>g.id)),l=en.data??[],v=[];for(const g of l)r.has(g.id)||v.push({id:g.id,alias:g.prefix||g.id,name:g.name||g.prefix||g.id,authType:"apikey",isCustom:!0,baseUrl:g.baseUrl,nodeType:g.type,apiType:g.apiType,icon:"sway",connected:0});return[...t,...v]},[Ft.data,en.data]),J=ue.data,Je=o.useMemo(()=>{const t=new Map;return i&&t.set(i,it),t},[it,i]),Ne=o.useMemo(()=>{let t=[...rt];if(y==="active"?t=t.filter(r=>(r.connected||0)>0):y==="idle"&&(t=t.filter(r=>(r.connected||0)===0)),c.trim()){const r=c.toLowerCase();t=t.filter(l=>l.name.toLowerCase().includes(r)||l.id.toLowerCase().includes(r)||(l.alias||"").toLowerCase().includes(r))}return t.sort((r,l)=>{const v=N.includes(r.id)?1:0,g=N.includes(l.id)?1:0;if(v!==g)return v-g;const k=r.connected||0,f=l.connected||0;return(k>0?1:0)!=(f>0?1:0)?f-k:(r.name||r.id).localeCompare(l.name||l.id)}),t},[rt,Je,y,N,c]);function Dt(t){K(r=>{const l=r.includes(t)?r.filter(v=>v!==t):[...r,t];try{localStorage.setItem("nr-hidden-providers",JSON.stringify(l))}catch{}return l})}o.useEffect(()=>{if(rt.length===0||i&&rt.some(r=>r.id===i))return;let t=null;try{t=localStorage.getItem(s)}catch{t=null}if(t&&rt.some(r=>r.id===t)){a(t);return}},[rt,Je,i]),o.useEffect(()=>{te(new Set),Kt(""),ye(""),nt("connections")},[i]),o.useEffect(()=>{const t=Es(J,i||"");St(String(t))},[i,J]);const d=Ne.find(t=>t.id===i)||null,Me=o.useMemo(()=>{const t=d?[...Je.get(d.id)||[]]:[];return t.sort((r,l)=>(r.priority??999)-(l.priority??999)||r.id.localeCompare(l.id)),t},[d,Je]),se=Me,we=As({count:se.length,getScrollElement:()=>xt.current,estimateSize:()=>typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches?64:72,overscan:10,getItemKey:t=>{var r;return((r=se[t])==null?void 0:r.id)??t},enabled:le==="connections"});o.useLayoutEffect(()=>{if(le!=="connections")return;let t=0;const r=requestAnimationFrame(()=>{we.measure(),t=requestAnimationFrame(()=>{we.measure()})});return()=>{cancelAnimationFrame(r),cancelAnimationFrame(t)}},[le,se.length,i,we]),o.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 639px)"),r=()=>{we.measure()};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[we]),o.useEffect(()=>{const t=xt.current;if(!t||typeof ResizeObserver>"u")return;const r=new ResizeObserver(()=>{we.measure()});return r.observe(t),()=>r.disconnect()},[we,le,i]);const Ge=o.useMemo(()=>Me.filter(t=>t.isActive!==!1),[Me]),fe=[...Ue][0]||((x=Ge[0])==null?void 0:x.id)||((M=se[0])==null?void 0:M.id),Pe=_s(d),H=ct({queryKey:["connection-models",d==null?void 0:d.id,fe,Xe],queryFn:async()=>{const t=await ss(fe);return Un(t.models,d==null?void 0:d.id)},enabled:!!(Pe&&fe),retry:!1}),yt=d?Ls(J,d.id):"fill-first",ke={"qd/ultimate":"Ultimate","qd/auto":"Auto","qd/performance":"Performance","qd/efficient":"Efficient","qd/lite":"Lite","qd/qmodel_preview":"Qwen3.8-Max-Preview","qd/qmodel_latest":"Qwen3.7-Max","qd/qmodel":"Qwen3.7-Plus","qd/kmodel_latest":"Kimi-K3","qd/kmodel":"Kimi-K2.7-Code","qd/gm51model":"GLM-5.2","qd/dmodel":"DeepSeek-V4-Pro","qd/dfmodel":"DeepSeek-V4-Flash","qd/mmodel":"MiniMax-M3"},at=o.useMemo(()=>{if(!d)return[];const t=[],r=d.id,l=new Set([r,d.alias||""].filter(Boolean).map(g=>g.toLowerCase())),v=[...Qe.data??[],...(O[r]??[]).map(g=>({providerAlias:r,id:g.id,name:g.name,capabilities:g.caps,thinkingLevels:g.thinkingLevels}))];for(const g of v)l.has(g.providerAlias.toLowerCase())&&t.push({id:Nn(g.id,g.providerAlias),name:g.name||g.id,caps:Vn(g.capabilities),thinkingLevels:Array.isArray(g.thinkingLevels)?g.thinkingLevels:void 0});if(Pe)t.push(...H.data??[]),!fe&&(r==="codebuddy-cn"||r==="codebuddy-intl"||r==="opencode"||r==="opencode-zen"||r==="opencode-go")&&t.push(...Un(d.models,r));else{const g=new Set([r,d.alias||""].map(k=>k.trim().toLowerCase()).filter(Boolean));for(const k of Te.data??[])[k.provider_alias,k.provider_id,k.owned_by].filter(j=>!!j).map(j=>j.trim().toLowerCase()).some(j=>g.has(j))&&t.push(k)}return Xi(t,r)},[H.data,ve,Qe.data,O,Te.data,d,fe,Pe]),tn=Pe?Qe.isLoading||Qe.isFetching||H.isLoading||H.isFetching:Qe.isLoading||Qe.isFetching||Te.isLoading||Te.isFetching,un=Pe&&!!H.error,Ee=d?rr(d.id,at.map(t=>t.thinkingLevels),d.thinkingConfig):null,Ye=d?(q=J==null?void 0:J.providerThinking)==null?void 0:q[d.id]:void 0,mn=d?ar(d.id,d.thinkingConfig):"auto",ot=d?Ye&&(Ee!=null&&Ee.includes(Ye))?Ye:Ee!=null&&Ee.includes(mn)?mn:(Ee==null?void 0:Ee[0])||"auto":"auto",En=o.useMemo(()=>{const t=new Map(Object.entries(ke));for(const r of at)r.name&&t.set(r.id,r.name);return t},[at]),zt=d?ut[d.id]||[]:[],hn=o.useMemo(()=>{const t=be.trim().toLowerCase(),r=new Set(d?Fe[d.id]||[]:[]);let l=at.filter(f=>!r.has(f.id));if(t&&(l=l.filter(f=>f.id.toLowerCase().includes(t)||(f.name||"").toLowerCase().includes(t))),!zt.length)return[...l].sort((f,j)=>f.id.localeCompare(j.id));const v=new Set(zt),g=l.filter(f=>v.has(f.id)),k=l.filter(f=>!v.has(f.id)).sort((f,j)=>f.id.localeCompare(j.id));return[...g,...k]},[Fe,at,be,zt,d]),fn=o.useMemo(()=>{var r,l;if(!d)return new Set;const t=[...((r=qt.data)==null?void 0:r[d.id])??[],...d.alias?((l=qt.data)==null?void 0:l[d.alias])??[]:[]];return new Set(t)},[qt.data,d]);async function Q(t){if(d)try{fn.has(t)?(await xr(d.id,t),P(`Enabled ${t.split("/").pop()}`)):(await pr(d.id,[t]),P(`Disabled ${t.split("/").pop()}`)),await n.invalidateQueries({queryKey:["disabled-models"]})}catch(r){P(Z(r,"Failed to update model availability"),"error")}}function Ve(t){d&&de(r=>{const l=r[d.id]||[],v=l.includes(t)?l.filter(k=>k!==t):[...l,t],g={...r,[d.id]:v};try{localStorage.setItem("nr-pinned-models",JSON.stringify(g))}catch{}return g})}function We(){var t;(t=$e.current)==null||t.abort();for(const r of De.current.values())r.abort();De.current.clear(),$e.current=null,Ze.current=!1,Mt(!1),Tt(null),ft(new Set),pt(null),P("Tests stopped")}function lt(t){const r=De.current.get(t);r&&(r.abort(),P("Model test stopped"))}async function nn(t,r){Tt(t);try{const l=await ps(t,void 0,{signal:r}),v=l.valid===!0,g=l.testedAt||new Date().toISOString(),k={testStatus:v?"active":"error",lastTested:g,lastError:v?l.error||null:l.error||"Connection test failed",healthStatus:v?"healthy":"error",healthError:v?l.error||null:l.error||"Connection test failed",healthLatencyMs:l.latencyMs??0};return et(f=>({...f,[t]:on({ok:v,message:l.error||(v?"Valid":"Failed"),latencyMs:l.latencyMs})})),ze(f=>f.map(j=>j.id===t?{...j,...k}:j)),n.setQueriesData({queryKey:["connections"]},f=>f&&{...f,connections:(f.connections||[]).map(j=>j.id===t?{...j,...k}:j)}),v}catch(l){if(_t.isCancel(l)||(l==null?void 0:l.code)==="ERR_CANCELED")return!1;const v=us(l),g=new Date().toISOString();return et(k=>({...k,[t]:v})),ze(k=>k.map(f=>f.id===t?{...f,testStatus:"error",lastTested:g,lastError:v.message,healthStatus:"error",healthError:v.message,healthLatencyMs:0}:f)),!1}finally{Tt(l=>l===t?null:l)}}async function pn(t){if(!t.length)return P("Nothing to test");const r=new AbortController;$e.current=r,pt("conn");let l=0;const v=4;for(let g=0;g<t.length&&!r.signal.aborted;g+=v){const k=t.slice(g,g+v),f=await Promise.all(k.map(j=>nn(j,r.signal)));l+=f.filter(Boolean).length}r.signal.aborted||P(`Connections: ${l}/${t.length} passed`),pt(null)}async function xn(t,r,l){if(!r)return P("Add a connection first"),!1;if(!l){if(Ze.current||Lt==="conn"||De.current.has(t))return!1;if(De.current.size>=Pt)return P(`Up to ${Pt} model tests can run at once`),!1}const v=l?null:new AbortController,g=l||v.signal;v&&De.current.set(t,v),ft(k=>{const f=new Set(k);return f.add(t),f});try{const k=await Us(r,{model:t,signal:g});if(!Array.isArray(k.results)){const W=k.message||k.error||"No model test results returned";return tt(me=>({...me,[t]:on({ok:!1,message:W})})),!1}const f=t.includes("/")?t.slice(t.lastIndexOf("/")+1):t,j=(k.results??[]).find(W=>{const me=String(W.modelId||"");return me===f||me===t||t.endsWith(`/${me}`)||me.endsWith(`/${f}`)}),V=!!(j!=null&&j.ok);return tt(W=>({...W,[t]:on({ok:V,status:j==null?void 0:j.status,message:((j==null?void 0:j.error)||"").trim()||(V?"OK":"Failed"),latencyMs:j==null?void 0:j.latencyMs})})),V}catch(k){return _t.isCancel(k)||(k==null?void 0:k.code)==="ERR_CANCELED"||tt(f=>({...f,[t]:us(k)})),!1}finally{ft(k=>{const f=new Set(k);return f.delete(t),f}),v&&De.current.delete(t)}}async function gn(){var t,r;if(d){if(d.id==="codebuddy-cn"||d.id==="codebuddy-intl"){P("CodeBuddy uses the static registry — add new models manually","default");return}ae(!0);try{const l={provider:d.id},v=new Set([d.id,d.alias].filter(Boolean).map(D=>D.trim().toLowerCase())),g=(en.data??[]).find(D=>D.id===d.id),k=(r=(t=Me.find(D=>{var I;return v.has(String(D.provider||"").trim().toLowerCase())&&typeof((I=D.providerSpecificData)==null?void 0:I.baseUrl)=="string"}))==null?void 0:t.providerSpecificData)==null?void 0:r.baseUrl,f=d.baseUrl||d.modelsFetcherUrl||(g==null?void 0:g.baseUrl)||(typeof k=="string"?k:void 0);f&&(l.baseUrl=f);const j=D=>D.flatMap(I=>{if(!I||typeof I!="object")return[];const X=I,Le=typeof X.id=="string"?X.id:typeof X.name=="string"?X.name:"";if(!Le.trim())return[];const _e=X.capabilities??X.caps;return[{id:Le.trim(),...typeof X.name=="string"&&X.name.trim()?{name:X.name.trim()}:{},..._e&&typeof _e=="object"?{capabilities:_e}:{}}]}),V=async()=>{const D=await ss(fe,!0),I=String(D.provider||"").trim().toLowerCase();if(I&&!v.has(I))throw new Error(`Model catalog returned ${D.provider}, expected ${d.name}`);return{ok:!0,success:!0,models:j(D.models??[])}};let W;if(fe)try{W=await V()}catch(D){if(!l.baseUrl||Pe||d.id==="clinepass"||d.id==="cline-pass")throw D;W=await is(l)}else W=await is(l);if(!W.ok&&!W.success){P(W.message||W.error||"Import failed","error");return}const me=W.models??[];if(!me.length){P(W.message||"No models returned","warning");return}const bn=me.map(D=>typeof D=="string"?D:D.id);mt(d.id,bn);const{added:wt,models:sn}=await mr(d.id,me),rn=sn.filter(D=>v.has(String(D.providerAlias||"").trim().toLowerCase())),Bt=rn.length;n.setQueryData(["custom-models"],sn),ie(D=>({...D,[d.id]:Un(rn,d.id)})),B(D=>D+1),Nt(D=>D+1),await n.invalidateQueries({queryKey:["custom-models"]}),await n.invalidateQueries({queryKey:["connection-models"]}),await n.invalidateQueries({queryKey:["available-models"]}),await n.invalidateQueries({queryKey:["sway-chat","models"]}),await n.refetchQueries({queryKey:["custom-models"],type:"active"}),await n.refetchQueries({queryKey:["connection-models"],type:"active"}),P(wt>0?`Imported ${wt} new ${wt===1?"model":"models"} · Total ${Bt} ${Bt===1?"Model":"Models"}`:`No new models · Total ${Bt} Models`,wt>0?"success":"default")}catch(l){P(Z(l,"Import failed"),"error")}finally{ae(!1)}}}async function Ln(){const t=re.trim();if(!(!d||!t||Oe)){L(!0);try{const r=await Ns(d.id,t);mt(d.id,[t]),n.setQueryData(["custom-models"],r.models),B(l=>l+1),Nt(l=>l+1),await n.invalidateQueries({queryKey:["custom-models"]}),await n.invalidateQueries({queryKey:["available-models"]}),await n.invalidateQueries({queryKey:["sway-chat","models"]}),ye(""),kt.success(`Added ${t}`)}catch(r){kt.error(Z(r,"Failed to add model"))}finally{L(!1)}}}async function In(){if(!fe)return P("Add a connection first");if(Ze.current)return;if(De.current.size>0)return P("Stop individual model tests before running Test all");const t=hn.map(g=>g.id);if(!t.length)return P("No models");Ze.current=!0,Mt(!0),pt("model");const r=new AbortController;$e.current=r;const l=new Array(t.length);let v=0;try{const g=Math.min(Pt,t.length),k=async()=>{for(;;){const f=v++;if(f>=t.length||r.signal.aborted)return;l[f]=await xn(t[f],fe,r.signal)}};if(await Promise.all(Array.from({length:g},()=>k())),!r.signal.aborted){const f=l.filter(V=>V!==void 0).length,j=l.filter(Boolean).length;P(`Models: ${j}/${f} passed`)}}catch(g){!_t.isCancel(g)&&(g==null?void 0:g.code)!=="ERR_CANCELED"&&P(Z(g,"Model test failed"),"error")}finally{ft(new Set),pt(null),$e.current===r&&($e.current=null),Ze.current=!1,Mt(!1)}}const bt=Zn({mutationFn:async t=>{if(!d)return;const r=(J==null?void 0:J.providerStrategies)||{},l={...r[d.id]||{}};return t.strategy&&(l.fallbackStrategy=t.strategy),t.sticky&&(l.stickyRoundRobinLimit=t.sticky),es({providerStrategies:{...r,[d.id]:l}})},onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]})}}),vn=Zn({mutationFn:async t=>{if(d)return es({providerThinking:{...(J==null?void 0:J.providerThinking)||{},[d.id]:t}})},onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]})}});async function Kn(t){const r=it.find(l=>l.id===t);if(!(!r||Yt)){Et(t);try{const l=await $s(t,r.isActive!==!1);ze(v=>v.map(g=>g.id===l.id?{...g,...l}:g)),n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),P(`${l.name||r.name||"Connection"} ${l.isActive===!1?"disabled":"enabled"}`,"success")}catch(l){P(Z(l,"Failed to update connection"),"error")}finally{Et(null)}}}async function Rn(t,r){const l=se.findIndex(V=>V.id===t);if(l<0)return;const v=l+r;if(v<0||v>=se.length)return;const g=se[l],k=se[v],f=g.priority??(l+1)*10,j=k.priority??(v+1)*10;await Promise.all([zn(g.id,{priority:j}),zn(k.id,{priority:f})]),n.invalidateQueries({queryKey:["connections"]})}async function On(t){try{await Bn(t),n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),G(null),P("Connection deleted","success")}catch(r){P(Z(r,"Failed to delete connection"),"error")}}async function Fn(){if(!(U!=null&&U.length)||Y)return;const t=U;$(!0);const r=[];try{for(const v of t)try{await Bn(v)}catch{r.push(v)}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]});const l=t.length-r.length;l===t.length?(te(new Set),_(null),P(`${l} connection${l===1?"":"s"} deleted`,"success")):l>0?(te(new Set(r)),_(null),P(`Deleted ${l} of ${t.length} connections`,"warning")):P("Could not delete the selected connections","error")}finally{$(!1)}}async function qn(t){var v,g,k,f,j,V,W,me,bn,wt,sn,rn,Bt,D;if(!d)return;if(t.alreadySaved){n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),b(!1),P("Connection added");return}const r=t.proxyPoolId&&t.proxyPoolId!=="pool_none"?t.proxyPoolId:null;if((v=t.codeBuddyTokens)!=null&&v.length){if(d.id!=="codebuddy-cn"&&d.id!=="codebuddy-intl")throw new Error("Token batches are only supported for CodeBuddy");let I=0,X=0;for(const Le of t.codeBuddyTokens)try{await an({provider:d.id,credentialToken:Le.credentialToken,accessToken:Le.accessToken,refreshToken:Le.refreshToken,name:Le.name,autoName:Le.autoName,proxyPoolId:null}),I+=1}catch(_e){if(_t.isAxiosError(_e)&&((g=_e.response)==null?void 0:g.status)===409){X+=1;continue}throw _e}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),b(!1),P(X>0?`Added ${I} connections, skipped ${X} duplicates`:`Added ${I} connections`,X>0?"warning":"success");return}if((k=t.bulkKeys)!=null&&k.length){let I=0,X=0;for(const Le of t.bulkKeys)try{await an({provider:d.id,apiKey:Le.apiKey,name:Le.name,autoName:Le.autoName,proxyPoolId:r}),I+=1}catch(_e){if(_t.isAxiosError(_e)&&((f=_e.response)==null?void 0:f.status)===409){X+=1;continue}throw _e}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),b(!1),P(X>0?`Added ${I} connections, skipped ${X} duplicates`:`Added ${I} connections`,X>0?"warning":"success");return}const l=t.authFlow??kn(d.id,d.authType,d.noAuth);if(d.id==="kiro"&&t.kiroAuthMode==="api-key"){if(!((j=t.apiKey)!=null&&j.trim()))throw new Error("API key required");const I=await Qs({apiKey:t.apiKey.trim(),region:t.kiroRegion,name:t.name,autoName:t.autoName});if(!I.success)throw new Error(I.error||"Kiro API key validation failed")}else if(d.id==="kiro"&&t.kiroAuthMode==="import-token"){if(!((V=t.kiroRefreshToken)!=null&&V.trim()))throw new Error("Refresh token required");const I=await Vs({refreshToken:t.kiroRefreshToken.trim(),clientId:((W=t.kiroClientId)==null?void 0:W.trim())||void 0,clientSecret:((me=t.kiroClientSecret)==null?void 0:me.trim())||void 0,region:t.kiroRegion,profileArn:((bn=t.kiroProfileArn)==null?void 0:bn.trim())||void 0,name:t.name,autoName:t.autoName});if(!I.success)throw new Error(I.error||"Kiro token import failed")}else if(d.id==="kiro"&&t.kiroAuthMode==="cli-proxy"){if(!((wt=t.kiroCliProxyJson)!=null&&wt.trim()))throw new Error("CLIProxyAPI JSON required");let I;try{I=JSON.parse(t.kiroCliProxyJson)}catch{throw new Error("CLIProxyAPI JSON is invalid")}if(!I||typeof I!="object"||Array.isArray(I))throw new Error("CLIProxyAPI JSON must be an object");const X=await Ws({cliProxyAuth:I,name:t.name,autoName:t.autoName});if(!X.success)throw new Error(X.error||"CLIProxyAPI import failed")}else if(l==="import"&&(d.id==="codebuddy-cn"||d.id==="codebuddy-intl")){if(!((sn=t.codeBuddyToken)!=null&&sn.trim()))throw new Error("An access token or refresh token is required.");await an({provider:d.id,credentialToken:t.codeBuddyToken.trim(),name:t.name,autoName:t.autoName,proxyPoolId:null})}else if(l==="import"){if(!((rn=t.importToken)!=null&&rn.trim()))throw new Error("Access token required");const I=await Hs(d.id,{accessToken:t.importToken.trim(),displayName:t.name,machineId:t.machineId});if(!I.success)throw new Error(I.error||"Token import failed")}else if(l==="oauth"){if(!((Bt=t.oauthCode)!=null&&Bt.trim()))throw new Error("Paste the OAuth code from the browser callback");await Js(d.id,{code:t.oauthCode.trim(),state:t.oauthState,codeVerifier:t.oauthCodeVerifier,redirectUri:t.oauthRedirectUri,displayName:t.name})}else if(l==="device"){if(!t.deviceCode)throw new Error("Device code not started — wait for user code");const I=await fs(d.id,{deviceCode:t.deviceCode,codeVerifier:t.deviceCodeVerifier,displayName:t.name});if(I.pending)throw new Error("Still waiting for device authorization — keep polling");if(!I.success)throw new Error(I.error||"Device authorization failed")}else if(l==="local")await an({provider:d.id,name:t.name,autoName:t.autoName,proxyPoolId:r});else{if(!((D=t.apiKey)!=null&&D.trim()))throw new Error("API key required");await an({provider:d.id,apiKey:t.apiKey,name:t.name,autoName:t.autoName,proxyPoolId:r})}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),b(!1),P("Connection added")}function Dn(t){const r=Me.filter(l=>l.provider===t.id);(async()=>{for(const l of r)try{await Bn(l.id)}catch{}ti(t.id).then(()=>{n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),n.invalidateQueries({queryKey:["connections"]}),P("Provider removed")})})(),R(null)}const yn=Ft.isLoading,m=d?d.isCustom?"apikey":kn(d.id,d.authType,d.noAuth):null;return e.jsxs("div",{className:ce("flex min-h-full h-auto w-full flex-col gap-1.5 overflow-visible sm:gap-3 lg:h-full lg:gap-4 lg:overflow-hidden"),children:[e.jsx(Ts,{className:"mb-0 sm:mb-0 shrink-0",title:"Providers",actions:e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(E,{size:"sm",onClick:()=>Ke(!0),children:[e.jsx(An,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Custom provider"}),e.jsx("span",{className:"sm:hidden",children:"Custom"})]})})}),e.jsxs("div",{className:"flex min-h-0 flex-none flex-col gap-2 overflow-visible sm:gap-3 lg:flex-1 lg:flex-row lg:gap-4 lg:overflow-hidden",children:[e.jsx(Hi,{byProvider:Je,filter:y,hiddenProviders:N,loading:yn,query:c,providerListRef:st,selectedId:i,sorted:Ne,onFilterChange:C,onQueryChange:h,onSelectProvider:u,onToggleProviderHidden:Dt}),e.jsx(ws,{className:"flex min-h-[32rem] min-w-0 flex-none flex-col overflow-hidden lg:min-h-0 lg:flex-1",children:d?e.jsxs(e.Fragment,{children:[e.jsx(dr,{selected:d,conns:se,activeConns:Ge,onEditCustom:()=>ge(d),onDeleteCustom:()=>R(d),onAddConnection:()=>b(!0)}),e.jsx(js,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsxs(vs,{value:le,onValueChange:nt,defaultValue:"connections",className:"flex min-h-0 h-full flex-1 flex-col overflow-hidden",children:[e.jsx("div",{className:"shrink-0 border-b border-border px-2 py-2 sm:px-5 sm:py-3",children:e.jsxs(ys,{children:[e.jsx(Cn,{value:"connections",children:"Connection"}),e.jsx(Cn,{value:"models",children:"Models"})]})}),e.jsx(cr,{selected:d,connsAll:Me,conns:se,strategy:yt,strategyPending:bt.isPending,stickyDraft:he,thinkingLevels:Ee,thinkingValue:ot,thinkingPending:vn.isPending,selectedKeys:Ue,connectionsCapped:Ot,totalConnections:(Ae==null?void 0:Ae.totalItems)??Me.length,batchKind:Lt,testingConnId:Jt,togglingConnId:Yt,connQuery:Se,connListRef:xt,connVirtualizer:we,connResults:Mn,onStrategyChange:t=>bt.mutate({strategy:t}),onStickyDraftChange:St,onSaveSticky:()=>{const t=Math.max(1,parseInt(he,10)||1);bt.mutate({sticky:t}),St(String(t))},onThinkingChange:t=>vn.mutate(t),onRequestBulkDelete:()=>_([...Ue]),onClearSelection:()=>te(new Set),onToggleSelection:t=>{te(r=>{const l=new Set(r);return l.has(t)?l.delete(t):l.add(t),l})},onSelectAll:()=>te(new Set(se.map(t=>t.id))),onTestConnections:t=>pn(t),onTestConnection:t=>{nn(t)},onStopTests:We,onConnQueryChange:Kt,onOpenAddConnection:()=>b(!0),onMovePriority:(t,r)=>Rn(t,r),onToggleConnection:t=>Kn(t),onEditConnection:z,onDeleteConnection:G}),e.jsx(Zi,{selected:d,visibleModels:hn,models:at,modelNames:En,modelsLoading:tn,modelsUnavailable:un,importingModels:S,testConnId:fe,batchKind:Lt,modelTestLock:dn,testingModels:Gt,modelQuery:be,newModel:re,addingModel:Oe,modelResults:Pn,pinnedFor:zt,copied:ht,onImportModels:()=>void gn(),onTestAllModels:()=>void In(),onStopTests:We,onStopModel:lt,onModelQueryChange:je,onNewModelChange:ye,onAddModel:()=>void Ln(),onTogglePin:Ve,onCopyModelId:async t=>{await navigator.clipboard.writeText(t),At(t),window.setTimeout(()=>At(null),1e3)},onTestModel:(t,r)=>void xn(t,r),onRemoveModel:async t=>{let r=!1;try{const l=await hr(d.id,t);r=(l==null?void 0:l.removed)===!0}catch{}finally{qe(d.id,t),B(l=>l+1),Nt(l=>l+1),n.invalidateQueries({queryKey:["sway-chat","models"]})}kt(`${r?"Removed":"Hidden"} ${t.split("/").pop()}`)},disabledModelIds:fn,onToggleDisabled:Q})]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground",children:"Select a provider"})})]}),e.jsx(Vi,{open:A,provider:d,flow:m,onOpenChange:b,onSubmit:async t=>{try{await qn(t)}catch(r){throw P(Z(r,"Add failed"),"error"),r}}}),e.jsx(Wi,{conn:F,onOpenChange:t=>!t&&z(null),onSave:async(t,r)=>{F&&(await zn(F.id,{name:t,...r.trim()?{apiKey:r.trim()}:{}}),n.invalidateQueries({queryKey:["connections"]}),z(null),P("Updated"))}}),e.jsx(ur,{deleteId:T,bulkDeleteIds:U,bulkDeleting:Y,deleteProvider:xe,connections:Me,onCloseDelete:()=>G(null),onDeleteConnection:()=>T?On(T):void 0,onCloseBulkDelete:()=>_(null),onDeleteSelectedConnections:Fn,onCloseProvider:()=>R(null),onRemoveProvider:Dn}),e.jsx(os,{open:Ie,onOpenChange:Ke,onCreate:async t=>{const r=await Zs(t);n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),Ke(!1),u(r.id),P("Custom provider created")}}),e.jsx(os,{open:!!Re,onOpenChange:t=>{t||ge(null)},initial:Re,submitLabel:"Save",onCreate:async t=>{if(!Re)return;const r=await ei(Re.id,t);n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),n.invalidateQueries({queryKey:["connections"]}),ge(null),u(r.id),P("Custom provider updated")}})]})}export{qr as compactErrorReason,Dr as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as x,j as e}from"./react-vendor-xnYrwzsL.js";import{A as f,a as u,b as h,c as j}from"./accordion-
|
|
1
|
+
import{r as x,j as e}from"./react-vendor-xnYrwzsL.js";import{A as f,a as u,b as h,c as j}from"./accordion-BkSdf_dl.js";import{b as v,c as t,p as b}from"./index-x5tLD3Ye.js";import{a3 as N}from"./icons-vendor-CUx7SB5V.js";function w({provider:o,className:a}){const s=v(o),[n,i]=x.useState(!1);return!n&&s?e.jsx("img",{"data-slot":"provider-model-icon",src:s,alt:"",width:20,height:20,className:t("shrink-0 rounded-[4px] object-contain",a),onError:()=>i(!0)}):e.jsx(N,{"aria-hidden":"true","data-slot":"provider-model-icon",className:t("shrink-0 text-muted-foreground",a)})}function k({groups:o,query:a="",empty:s,renderItem:n,className:i}){if(o.length===0)return s??null;const d=a.trim().toLowerCase(),c=!!d,m=o.map(r=>r.provider).join("|"),p=c?o.map(r=>r.provider):[o[0].provider];return e.jsx(f,{multiple:!0,defaultValue:p,className:t("w-full",i),children:o.map(r=>e.jsxs(u,{value:r.provider,className:"border-border/70 px-1 last:border-b-0",children:[e.jsx(h,{className:t("w-fit flex-none justify-start gap-1.5 py-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground","hover:text-foreground sm:py-2.5"),children:e.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(w,{provider:r.provider,className:"size-4"}),e.jsx("span",{className:"truncate",children:b(r.provider)}),e.jsx("span",{className:"rounded-full border border-border/70 px-1.5 py-0.5 text-[9px] font-normal normal-case tracking-normal text-muted-foreground/80",children:r.items.length})]})}),e.jsx(j,{className:"min-w-0 pb-1",children:e.jsx("ul",{className:"space-y-0.5",children:r.items.map(l=>e.jsx("li",{children:n(l,r.provider)},l.id))})})]},r.provider))},`${c?`search:${d}`:"browse"}:${m}`)}export{k as P,w as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n,j as e}from"./react-vendor-xnYrwzsL.js";import{u as rs,a as me}from"./query-vendor-DVevaSVS.js";import{H as ns}from"./Header-C_9Su9BF.js";import{F as ls}from"./flip-button-BGgkjtl0.js";import{R as d}from"./ripple-button-l8aMiVVG.js";import{S as D}from"./StatusBadge-1nAOyHU2.js";import{C as xe}from"./checkbox-7SZBrmbN.js";import{I as v,e as A,D as H,m as V,n as G,o as X,s as ue,F as pe,q as he,g as w,p as os,t as fe}from"./index-B6j-9zHy.js";import{F as is,c as cs}from"./frame-cUiti6Lq.js";import{S as Me}from"./segmented-CqmEnQjZ.js";import{S as ds}from"./skeleton-7uJDiIXe.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as I}from"./table-D0M60Tu1.js";import{h as ps,i as hs,j as Le,t as fs,k as ys,a as js,l as gs}from"./admin-extras-api-CCdu5TFM.js";import{i as vs,z as bs}from"./connections-api-_N54UD3S.js";import{p as Ns}from"./live-mode-CHShLY4E.js";import{p as Ke,ac as Re,q as Cs,L as ye,aq as ws,ar as Ss,h as ks,af as Ps,a as Ts,ag as Ds}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const Be=100,He=500;function Ve({pool:r,testing:x,onToggle:S,onTest:f,onManage:u,onEdit:b,onDelete:p}){return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-1.5",children:[e.jsx(ls,{active:r.isActive!==!1,onToggle:S,activeLabel:"",inactiveLabel:""}),e.jsx(A,{label:x?"Testing…":"Test",children:e.jsxs(d,{size:"sm",variant:"outline",disabled:x,onClick:f,"aria-label":x?"Testing proxy pool":"Test proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[x?e.jsx(ye,{className:"size-4 animate-spin","aria-hidden":"true"}):e.jsx(ws,{className:"size-4 fill-current sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:x?"Testing…":"Test"})]})}),e.jsx(A,{label:"Manage",children:e.jsxs(d,{size:"sm",variant:"outline",onClick:u,"aria-label":"Manage connections",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(Ss,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Manage"})]})}),e.jsx(A,{label:"Edit",children:e.jsxs(d,{size:"sm",variant:"outline",onClick:b,"aria-label":"Edit proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(ks,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Edit"})]})}),e.jsx(A,{label:"Delete",children:e.jsxs(d,{size:"sm",variant:"destructive",onClick:p,"aria-label":"Delete proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(Ps,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})}function zs({progress:r}){const x=r.error?"Failed":r.completed?"Ready":`Step ${r.current+1} of ${r.steps.length}`;return e.jsxs("div",{className:"rounded-lg border border-border/70 bg-muted/10 p-3",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-xs font-medium",children:"Deployment progress"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:x})]}),e.jsx("ol",{className:"space-y-2.5",children:r.steps.map((S,f)=>{const u=r.completed||f<r.current,b=!!r.error&&f===r.current,p=!r.completed&&!r.error&&f===r.current,h=r.completed||f<r.current;return e.jsxs("li",{className:"relative flex min-h-5 items-start gap-2.5",children:[f<r.steps.length-1?e.jsx("span",{className:`absolute left-[7px] top-5 h-[calc(100%-4px)] w-px ${h?"bg-primary/70":"bg-border"}`,"aria-hidden":"true"}):null,e.jsx("span",{className:`relative z-10 flex size-4 shrink-0 items-center justify-center rounded-full border bg-background ${b?"border-destructive text-destructive":u?"border-primary bg-primary text-primary-foreground":p?"border-primary text-primary":"border-border text-muted-foreground"}`,children:b?e.jsx(Ts,{className:"size-3","aria-hidden":"true"}):u?e.jsx(Ds,{className:"size-3","aria-hidden":"true"}):p?e.jsx(ye,{className:"size-3 animate-spin","aria-hidden":"true"}):e.jsx("span",{className:"size-1.5 rounded-full bg-current","aria-hidden":"true"})}),e.jsx("span",{className:`pt-px text-xs ${b?"text-destructive":p?"font-medium text-foreground":u?"text-foreground":"text-muted-foreground"}`,children:S})]},S)})}),r.error?e.jsx("p",{className:"mt-3 text-xs text-destructive",children:r.error}):null]})}function Xs(){var $e,Fe;const r=rs(),[x,S]=n.useState(""),[f,u]=n.useState(!1),[b,p]=n.useState(!1),[h,je]=n.useState("vercel"),[Y,ge]=n.useState(""),[_,ve]=n.useState(""),[W,be]=n.useState(""),[k,Ne]=n.useState(!1),[Ce,q]=n.useState(null),[P,M]=n.useState(null),[Z,E]=n.useState(null),[we,Se]=n.useState(null),[N,T]=n.useState(!1),[m,ke]=n.useState(null),[y,O]=n.useState(new Set),[J,ee]=n.useState(""),[Pe,se]=n.useState(""),[Q,Te]=n.useState(!1);n.useEffect(()=>{const s=window.setTimeout(()=>{se(J.trim())},250);return()=>window.clearTimeout(s)},[J]),n.useEffect(()=>{if(!k)return;const s=window.setInterval(()=>{q(t=>{if(!t||t.completed||t.error)return t;const a=Math.max(0,t.steps.length-2);return t.current>=a?t:{...t,current:t.current+1}})},2500);return()=>window.clearInterval(s)},[k]);const[L,te]=n.useState(""),[K,ae]=n.useState(""),[re,ne]=n.useState(""),[le,oe]=n.useState("http"),[ie,ce]=n.useState(!1),De=me({queryKey:["proxy-pools"],queryFn:js,enabled:Ns(),retry:!1}),Ge=me({queryKey:["proxy-pool-provider-nodes"],queryFn:gs,enabled:!!m,retry:!1}),U=De.data??[],Xe=De.isLoading,j=me({queryKey:["proxy-pool-connections",Pe],queryFn:()=>bs({page:1,pageSize:Be,search:Pe||void 0}),enabled:!!m,retry:!1}),$=n.useMemo(()=>{var t;return[...((t=j.data)==null?void 0:t.connections)??[]].sort((a,o)=>{const i=a.provider.localeCompare(o.provider);return i||String(a.name||a.email||a.id).localeCompare(String(o.name||o.email||o.id))})},[j.data]),ze=n.useMemo(()=>{const s=new Map;for(const t of $){const a=s.get(t.provider)??[];a.push(t),s.set(t.provider,a)}return[...s.entries()]},[$]);function Ye(s,t){var i,l;const a=(Ge.data??[]).find(g=>g.id===s);if(a!=null&&a.name)return a.name;const o=(l=(i=t.find(g=>{var C;return typeof((C=g.providerSpecificData)==null?void 0:C.nodeName)=="string"}))==null?void 0:i.providerSpecificData)==null?void 0:l.nodeName;return typeof o=="string"&&o.trim()?o.trim():os(s)}const R=n.useMemo(()=>$.map(s=>s.id),[$]),We=R.filter(s=>y.has(s)).length,de=n.useMemo(()=>{const s=x.trim().toLowerCase();return s?U.filter(t=>(t.name||"").toLowerCase().includes(s)||(t.proxyUrl||"").toLowerCase().includes(s)||t.id.toLowerCase().includes(s)):U},[U,x]);function c(s,t="default"){t==="success"?fe.success(s):t==="error"?fe.error(s):fe(s)}function F(){te(""),ae(""),ne(""),oe("http"),ce(!1)}function B(){je("vercel"),ge(""),ve(""),be(""),q(null)}async function Ze(){if(h==="cloudflare"&&!W.trim())return c("Cloudflare Account ID required","error");if(!_.trim())return c("Deployment token required","error");q({steps:h==="vercel"?["Create deployment","Wait for deployment","Check relay","Save proxy pool"]:["Upload worker","Enable subdomain","Check relay","Save proxy pool"],current:0,completed:!1,error:null});let t;h==="vercel"?t={type:"vercel",vercelToken:_.trim(),projectName:Y.trim()||void 0}:t={type:"cloudflare",accountId:W.trim(),apiToken:_.trim(),projectName:Y.trim()||void 0},Ne(!0);try{await ps(t),await r.invalidateQueries({queryKey:["proxy-pools"]}),q(a=>a&&{...a,current:a.steps.length-1,completed:!0}),c(`${h[0].toUpperCase()}${h.slice(1)} relay deployed`,"success"),p(!1),B()}catch(a){const o=w(a,"Relay deployment failed");q(i=>i&&{...i,error:o}),c(o,"error")}finally{Ne(!1)}}function Ie(s){M(s),te(s.name||""),ae(s.proxyUrl||""),ne(s.noProxy||""),oe(s.type||"http"),ce(s.strictProxy===!0)}async function Je(){if(!L.trim()||!K.trim())return c("Name and proxy URL required","error");T(!0);try{const s={name:L.trim(),proxyUrl:K.trim(),noProxy:re.trim(),type:le,strictProxy:ie};await hs(s),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool created","success"),u(!1),F()}catch(s){c(w(s,"Create failed"),"error")}finally{T(!1)}}async function es(){if(P){T(!0);try{const s={name:L.trim(),proxyUrl:K.trim(),noProxy:re.trim(),type:le,strictProxy:ie};await Le(P.id,s),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool updated","success"),M(null),F()}catch(s){c(w(s,"Update failed"),"error")}finally{T(!1)}}}async function Ae(s){const t=s.isActive===!1;try{await Le(s.id,{isActive:t}),await r.invalidateQueries({queryKey:["proxy-pools"]})}catch(a){c(w(a,"Toggle failed"),"error")}}async function qe(s){Se(s);try{const t=await fs(s);await r.invalidateQueries({queryKey:["proxy-pools"]}),t.ok?c(`Proxy OK${t.ip?` · ${t.ip}`:""}`,"success"):c(t.error||"Proxy test failed","error")}catch(t){c(w(t,"Test failed"),"error")}finally{Se(null)}}function ss(s){var a;const t=(a=s.providerSpecificData)==null?void 0:a.proxyPoolId;return typeof t=="string"&&t.trim()?t:typeof s.proxyPoolId=="string"&&s.proxyPoolId.trim()?s.proxyPoolId:null}function Ee(s){ke(s),O(new Set),ee(""),se("")}function ts(s){O(t=>{const a=new Set(t);return a.has(s)?a.delete(s):a.add(s),a})}function Oe(s){s.length&&O(t=>{const a=new Set(t),o=s.every(i=>a.has(i));for(const i of s)o?a.delete(i):a.add(i);return a})}async function Ue(s){if(!y.size){c("Select at least one connection","error");return}if(y.size>He){c(`Assign up to ${He} connections at a time`,"error");return}Te(!0);const t=[...y],a=[];for(let l=0;l<t.length;l+=12){const g=t.slice(l,l+12);a.push(...await Promise.allSettled(g.map(C=>vs(C,{proxyPoolId:s}))))}const o=a.filter(l=>l.status==="fulfilled").length,i=a.length-o;await Promise.all([r.invalidateQueries({queryKey:["proxy-pool-connections"]}),r.invalidateQueries({queryKey:["proxy-pools"]}),r.invalidateQueries({queryKey:["connections"]})]),O(new Set),Te(!1),i?c(`${o} updated, ${i} failed`,"error"):c(s?`${o} connection(s) assigned`:`${o} connection(s) set to direct`,"success")}async function as(){if(Z){T(!0);try{await ys(Z),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool deleted","success"),E(null)}catch(s){c(w(s,"Delete failed"),"error")}finally{T(!1)}}}return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{title:"Proxy Pools",actions:U.length>0?e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsxs(d,{size:"sm",variant:"outline",onClick:()=>{B(),p(!0)},children:[e.jsx(Ke,{className:"h-4 w-4 fill-current"}),"Deploy"]}),e.jsxs(d,{size:"sm",onClick:()=>{F(),u(!0)},children:[e.jsx(Re,{className:"h-4 w-4"}),"Add pool"]})]}):null}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx("span",{className:"sr-only",children:"Search proxy pools"}),e.jsx(Cs,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(v,{value:x,onChange:s=>S(s.target.value),placeholder:"Search pools…",className:"pl-9"})]}),e.jsx(is,{className:"overflow-hidden",children:e.jsx(cs,{className:"p-0",children:e.jsx("div",{className:"min-w-0",children:Xe?e.jsx("div",{className:"space-y-2 p-4",children:Array.from({length:3}).map((s,t)=>e.jsx(ds,{className:"h-12 w-full"},t))}):U.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-16 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No proxy pools"}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsxs(d,{size:"sm",onClick:()=>{F(),u(!0)},children:[e.jsx(Re,{className:"h-4 w-4"}),"Add first pool"]}),e.jsxs(d,{size:"sm",variant:"outline",onClick:()=>{B(),p(!0)},children:[e.jsx(Ke,{className:"h-4 w-4 fill-current"}),"Deploy relay"]})]})]}):de.length===0?e.jsx("div",{className:"px-4 py-16 text-center text-sm text-muted-foreground",children:"No proxy pools match your search."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-hidden rounded-xl border border-border/70 bg-card sm:hidden",children:e.jsx("div",{className:"divide-y divide-border/70",children:de.map(s=>e.jsxs("article",{className:"min-w-0 space-y-2.5 p-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.name||s.id}),s.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]}),e.jsx(A,{label:s.proxyUrl||"—",children:e.jsx("p",{className:"mt-1 truncate font-mono text-[11px] text-muted-foreground",children:s.proxyUrl||"—"})})]}),e.jsx(D,{tone:s.testStatus==="ok"||s.testStatus==="active"?"ok":s.testStatus==="error"?"err":"muted",className:"shrink-0 text-[10px]",children:s.testStatus==="active"?"ok":s.testStatus||"unknown"})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0 uppercase",children:s.type||"http"}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"min-w-0 truncate",children:[s.boundConnectionCount??0," connections"]})]}),e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ae(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ie(s),onDelete:()=>E(s.id)})]},s.id))})}),e.jsx("div",{className:"hidden min-w-0 sm:block",children:e.jsxs(ms,{variant:"card",className:"min-w-[44rem] text-[13px] [&_tbody]:before:hidden [&_tbody_tr_td]:!bg-transparent [&_tbody_tr:hover_td]:!bg-transparent [&_tbody_tr[data-state=selected]_td]:!bg-transparent",children:[e.jsx(xs,{className:"bg-transparent text-[10px] uppercase text-muted-foreground",children:e.jsxs(Qe,{className:"border-b border-border/80 bg-transparent hover:bg-transparent",children:[e.jsx(z,{className:"px-4 py-2 font-medium",children:"Name"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"URL"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Type"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Connections"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Test"}),e.jsx(z,{className:"px-4 py-2 font-medium text-right",children:"Actions"})]})}),e.jsx(us,{children:de.map(s=>e.jsxs(Qe,{className:"border-b border-border/60 last:border-0 bg-transparent hover:bg-transparent data-[state=selected]:bg-transparent",children:[e.jsx(I,{className:"max-w-[14rem] bg-transparent px-4 py-2",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.name||s.id}),s.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]})}),e.jsx(I,{className:"max-w-[24rem] truncate bg-transparent px-3 py-2 font-mono text-xs text-muted-foreground",children:e.jsx(A,{label:s.proxyUrl||"—",children:e.jsx("span",{className:"block truncate",children:s.proxyUrl||"—"})})}),e.jsx(I,{className:"bg-transparent px-3 py-2 text-xs uppercase text-muted-foreground",children:s.type||"http"}),e.jsx(I,{className:"bg-transparent px-3 py-2 text-xs text-muted-foreground",children:s.boundConnectionCount??0}),e.jsx(I,{className:"bg-transparent px-3 py-2",children:e.jsx(D,{tone:s.testStatus==="ok"||s.testStatus==="active"?"ok":s.testStatus==="error"?"err":"muted",className:"w-fit text-[10px]",children:s.testStatus==="active"?"ok":s.testStatus||"unknown"})}),e.jsx(I,{className:"bg-transparent px-4 py-2",children:e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ae(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ie(s),onDelete:()=>E(s.id)})})]},s.id))})]})})]})})})}),e.jsx(H,{open:f||!!P,onOpenChange:s=>{s||(u(!1),M(null),F())},children:e.jsxs(V,{className:"max-h-[90vh]",children:[e.jsxs(G,{children:[e.jsx(X,{children:P?"Edit proxy pool":"Add proxy pool"}),e.jsx(ue,{children:"Used as connection outbound proxy."})]}),e.jsxs(pe,{className:"space-y-4",children:[e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(v,{value:L,onChange:s=>te(s.target.value),placeholder:"US residential"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Proxy URL (HTTP/HTTPS/SOCKS5)"}),e.jsx(v,{value:K,onChange:s=>ae(s.target.value),placeholder:"http://user:pass@host:port or host:port"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"No-proxy"}),e.jsx(v,{value:re,onChange:s=>ne(s.target.value),placeholder:"localhost,127.0.0.1"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Type"}),e.jsx(Me,{size:"sm",value:le,onChange:oe,options:[{value:"http",label:"HTTP"},{value:"socks5",label:"SOCKS5"}]})]}),e.jsxs("label",{className:"flex items-start gap-2.5 rounded-lg border border-border/70 p-3",children:[e.jsx(xe,{checked:ie,onCheckedChange:s=>ce(s===!0),disabled:N,"aria-describedby":"strict-proxy-help"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:"Require proxy"}),e.jsx("span",{id:"strict-proxy-help",className:"mt-0.5 block text-xs text-muted-foreground",children:"Fail requests when this proxy is unavailable instead of falling back to a direct connection."})]})]})]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>{u(!1),M(null)},disabled:N,children:"Cancel"}),e.jsx(d,{onClick:()=>void(P?es():Je()),disabled:N,children:N?"Saving…":P?"Save":"Create"})]})]})}),e.jsx(H,{open:b,onOpenChange:s=>{p(s),s||B()},children:e.jsxs(V,{className:"max-h-[90vh]",children:[e.jsx(G,{children:e.jsx(X,{children:"Deploy relay"})}),e.jsxs(pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Platform"}),e.jsx(Me,{size:"sm",value:h,onChange:s=>je(s),options:[{value:"vercel",label:"Vercel"},{value:"cloudflare",label:"Cloudflare"}]})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Project name (optional)"}),e.jsx(v,{value:Y,onChange:s=>ge(s.target.value),placeholder:"sway-router-relay",autoComplete:"off"})]}),h==="cloudflare"?e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Account ID"}),e.jsx(v,{value:W,onChange:s=>be(s.target.value),placeholder:"Cloudflare account ID",autoComplete:"off"})]}):null,e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:h==="vercel"?"Vercel API token":"Cloudflare API token"}),e.jsx(v,{type:"password",value:_,onChange:s=>ve(s.target.value),placeholder:"Token",autoComplete:"off"})]}),Ce?e.jsx(zs,{progress:Ce}):null]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>p(!1),disabled:k,children:"Cancel"}),e.jsxs(d,{onClick:()=>void Ze(),disabled:k,children:[k?e.jsx(ye,{className:"size-4 animate-spin"}):null,k?"Deploying…":"Deploy"]})]})]})}),e.jsx(H,{open:!!m,onOpenChange:s=>{s||(ke(null),O(new Set),ee(""),se(""))},children:e.jsxs(V,{className:"max-h-[90vh] max-w-3xl",children:[e.jsxs(G,{children:[e.jsxs(X,{children:["Manage ",(m==null?void 0:m.name)||"proxy pool"]}),e.jsx(ue,{children:"Assign existing provider connections to this pool without recreating their credentials."})]}),e.jsxs(pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(v,{value:J,onChange:s=>ee(s.target.value),placeholder:"Search provider, name, email, or ID…",className:"min-w-[14rem] flex-1"}),e.jsx(d,{size:"sm",variant:"outline",disabled:!R.length||Q,onClick:()=>Oe(R),children:We===R.length?"Clear visible":"Select visible"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:j.isLoading?"Loading connections…":`${(($e=j.data)==null?void 0:$e.pagination.totalItems)??$.length} connection(s) · ${y.size} selected`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(d,{size:"sm",disabled:!y.size||Q,onClick:()=>void Ue((m==null?void 0:m.id)||null),children:Q?"Assigning…":"Assign selected"}),e.jsx(d,{size:"sm",variant:"outline",disabled:!y.size||Q,onClick:()=>void Ue(null),children:"Set direct"})]})]}),j.error?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:w(j.error,"Failed to load connections")}):ze.length===0&&!j.isLoading?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No existing connections match this search."}):e.jsxs(e.Fragment,{children:[(Fe=j.data)!=null&&Fe.pagination.hasNext?e.jsxs("p",{className:"rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-xs text-warning",children:["Showing the first ",Be," matches. Use search to find other connections."]}):null,e.jsx("div",{className:"max-h-[50vh] space-y-2 overflow-y-auto pr-1",children:ze.map(([s,t])=>{const a=t.map(l=>l.id),o=a.filter(l=>y.has(l)).length,i=o===a.length;return e.jsxs("div",{className:"rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/70 bg-muted/30 px-3 py-2",children:[e.jsx(xe,{checked:i,indeterminate:o>0&&!i,onCheckedChange:()=>Oe(a),"aria-label":`Select all ${s} connections`}),e.jsx("span",{className:"font-medium",children:Ye(s,t)}),e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:s}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o,"/",a.length]})]}),e.jsx("div",{className:"divide-y divide-border/60",children:t.map(l=>{const g=ss(l),C=g===(m==null?void 0:m.id),_e=l.name||l.email||l.id.slice(0,8);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 hover:bg-muted/20",children:[e.jsx(xe,{checked:y.has(l.id),onCheckedChange:()=>ts(l.id),"aria-label":`Select ${_e}`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:_e}),e.jsxs("span",{className:"block truncate text-xs text-muted-foreground",children:[l.email&&l.name?`${l.email} · `:"",l.authType||"connection"," · ",l.id.slice(0,8)]})]}),e.jsx(D,{tone:l.isActive===!1?"muted":C?"ok":"muted",className:"shrink-0 text-[10px]",children:C?"This pool":g?"Other pool":"Direct"}),l.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]},l.id)})})]},s)})})]})]})]})}),e.jsx(H,{open:!!Z,onOpenChange:s=>{s||E(null)},children:e.jsxs(V,{children:[e.jsxs(G,{children:[e.jsx(X,{children:"Delete pool?"}),e.jsx(ue,{children:"Detach all connections using this pool before deleting it. Bound pools cannot be deleted."})]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>E(null),disabled:N,children:"Cancel"}),e.jsx(d,{variant:"destructive",onClick:as,disabled:N,children:N?"Deleting…":"Delete"})]})]})})]})}export{Xs as default};
|
|
1
|
+
import{r as n,j as e}from"./react-vendor-xnYrwzsL.js";import{u as rs,a as me}from"./query-vendor-DVevaSVS.js";import{H as ns}from"./Header-9KXz4S67.js";import{F as ls}from"./flip-button-C_PNv8Iq.js";import{R as d}from"./ripple-button-BV_KcZ7W.js";import{S as D}from"./StatusBadge-DClAYX7v.js";import{C as xe}from"./checkbox-DU_0LpXJ.js";import{I as v,e as A,D as H,m as V,n as G,o as X,s as ue,F as pe,q as he,g as w,p as os,t as fe}from"./index-x5tLD3Ye.js";import{F as is,c as cs}from"./frame-BLwA8c3u.js";import{S as Me}from"./segmented-BBSMiP-0.js";import{S as ds}from"./skeleton-CFSSp0e0.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as I}from"./table-lcAgAODE.js";import{h as ps,i as hs,j as Le,t as fs,k as ys,a as js,l as gs}from"./admin-extras-api-ppLkXcD9.js";import{i as vs,z as bs}from"./connections-api-CQHf0Hwe.js";import{p as Ns}from"./live-mode-CHShLY4E.js";import{p as Ke,ac as Re,q as Cs,L as ye,aq as ws,ar as Ss,h as ks,af as Ps,a as Ts,ag as Ds}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const Be=100,He=500;function Ve({pool:r,testing:x,onToggle:S,onTest:f,onManage:u,onEdit:b,onDelete:p}){return e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-end gap-1.5",children:[e.jsx(ls,{active:r.isActive!==!1,onToggle:S,activeLabel:"",inactiveLabel:""}),e.jsx(A,{label:x?"Testing…":"Test",children:e.jsxs(d,{size:"sm",variant:"outline",disabled:x,onClick:f,"aria-label":x?"Testing proxy pool":"Test proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[x?e.jsx(ye,{className:"size-4 animate-spin","aria-hidden":"true"}):e.jsx(ws,{className:"size-4 fill-current sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:x?"Testing…":"Test"})]})}),e.jsx(A,{label:"Manage",children:e.jsxs(d,{size:"sm",variant:"outline",onClick:u,"aria-label":"Manage connections",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(Ss,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Manage"})]})}),e.jsx(A,{label:"Edit",children:e.jsxs(d,{size:"sm",variant:"outline",onClick:b,"aria-label":"Edit proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(ks,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Edit"})]})}),e.jsx(A,{label:"Delete",children:e.jsxs(d,{size:"sm",variant:"destructive",onClick:p,"aria-label":"Delete proxy pool",className:"h-7 w-7 px-0 sm:w-auto sm:px-3 sm:text-sm",children:[e.jsx(Ps,{className:"size-4 sm:hidden","aria-hidden":"true"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})}function zs({progress:r}){const x=r.error?"Failed":r.completed?"Ready":`Step ${r.current+1} of ${r.steps.length}`;return e.jsxs("div",{className:"rounded-lg border border-border/70 bg-muted/10 p-3",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-xs font-medium",children:"Deployment progress"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:x})]}),e.jsx("ol",{className:"space-y-2.5",children:r.steps.map((S,f)=>{const u=r.completed||f<r.current,b=!!r.error&&f===r.current,p=!r.completed&&!r.error&&f===r.current,h=r.completed||f<r.current;return e.jsxs("li",{className:"relative flex min-h-5 items-start gap-2.5",children:[f<r.steps.length-1?e.jsx("span",{className:`absolute left-[7px] top-5 h-[calc(100%-4px)] w-px ${h?"bg-primary/70":"bg-border"}`,"aria-hidden":"true"}):null,e.jsx("span",{className:`relative z-10 flex size-4 shrink-0 items-center justify-center rounded-full border bg-background ${b?"border-destructive text-destructive":u?"border-primary bg-primary text-primary-foreground":p?"border-primary text-primary":"border-border text-muted-foreground"}`,children:b?e.jsx(Ts,{className:"size-3","aria-hidden":"true"}):u?e.jsx(Ds,{className:"size-3","aria-hidden":"true"}):p?e.jsx(ye,{className:"size-3 animate-spin","aria-hidden":"true"}):e.jsx("span",{className:"size-1.5 rounded-full bg-current","aria-hidden":"true"})}),e.jsx("span",{className:`pt-px text-xs ${b?"text-destructive":p?"font-medium text-foreground":u?"text-foreground":"text-muted-foreground"}`,children:S})]},S)})}),r.error?e.jsx("p",{className:"mt-3 text-xs text-destructive",children:r.error}):null]})}function Xs(){var $e,Fe;const r=rs(),[x,S]=n.useState(""),[f,u]=n.useState(!1),[b,p]=n.useState(!1),[h,je]=n.useState("vercel"),[Y,ge]=n.useState(""),[_,ve]=n.useState(""),[W,be]=n.useState(""),[k,Ne]=n.useState(!1),[Ce,q]=n.useState(null),[P,M]=n.useState(null),[Z,E]=n.useState(null),[we,Se]=n.useState(null),[N,T]=n.useState(!1),[m,ke]=n.useState(null),[y,O]=n.useState(new Set),[J,ee]=n.useState(""),[Pe,se]=n.useState(""),[Q,Te]=n.useState(!1);n.useEffect(()=>{const s=window.setTimeout(()=>{se(J.trim())},250);return()=>window.clearTimeout(s)},[J]),n.useEffect(()=>{if(!k)return;const s=window.setInterval(()=>{q(t=>{if(!t||t.completed||t.error)return t;const a=Math.max(0,t.steps.length-2);return t.current>=a?t:{...t,current:t.current+1}})},2500);return()=>window.clearInterval(s)},[k]);const[L,te]=n.useState(""),[K,ae]=n.useState(""),[re,ne]=n.useState(""),[le,oe]=n.useState("http"),[ie,ce]=n.useState(!1),De=me({queryKey:["proxy-pools"],queryFn:js,enabled:Ns(),retry:!1}),Ge=me({queryKey:["proxy-pool-provider-nodes"],queryFn:gs,enabled:!!m,retry:!1}),U=De.data??[],Xe=De.isLoading,j=me({queryKey:["proxy-pool-connections",Pe],queryFn:()=>bs({page:1,pageSize:Be,search:Pe||void 0}),enabled:!!m,retry:!1}),$=n.useMemo(()=>{var t;return[...((t=j.data)==null?void 0:t.connections)??[]].sort((a,o)=>{const i=a.provider.localeCompare(o.provider);return i||String(a.name||a.email||a.id).localeCompare(String(o.name||o.email||o.id))})},[j.data]),ze=n.useMemo(()=>{const s=new Map;for(const t of $){const a=s.get(t.provider)??[];a.push(t),s.set(t.provider,a)}return[...s.entries()]},[$]);function Ye(s,t){var i,l;const a=(Ge.data??[]).find(g=>g.id===s);if(a!=null&&a.name)return a.name;const o=(l=(i=t.find(g=>{var C;return typeof((C=g.providerSpecificData)==null?void 0:C.nodeName)=="string"}))==null?void 0:i.providerSpecificData)==null?void 0:l.nodeName;return typeof o=="string"&&o.trim()?o.trim():os(s)}const R=n.useMemo(()=>$.map(s=>s.id),[$]),We=R.filter(s=>y.has(s)).length,de=n.useMemo(()=>{const s=x.trim().toLowerCase();return s?U.filter(t=>(t.name||"").toLowerCase().includes(s)||(t.proxyUrl||"").toLowerCase().includes(s)||t.id.toLowerCase().includes(s)):U},[U,x]);function c(s,t="default"){t==="success"?fe.success(s):t==="error"?fe.error(s):fe(s)}function F(){te(""),ae(""),ne(""),oe("http"),ce(!1)}function B(){je("vercel"),ge(""),ve(""),be(""),q(null)}async function Ze(){if(h==="cloudflare"&&!W.trim())return c("Cloudflare Account ID required","error");if(!_.trim())return c("Deployment token required","error");q({steps:h==="vercel"?["Create deployment","Wait for deployment","Check relay","Save proxy pool"]:["Upload worker","Enable subdomain","Check relay","Save proxy pool"],current:0,completed:!1,error:null});let t;h==="vercel"?t={type:"vercel",vercelToken:_.trim(),projectName:Y.trim()||void 0}:t={type:"cloudflare",accountId:W.trim(),apiToken:_.trim(),projectName:Y.trim()||void 0},Ne(!0);try{await ps(t),await r.invalidateQueries({queryKey:["proxy-pools"]}),q(a=>a&&{...a,current:a.steps.length-1,completed:!0}),c(`${h[0].toUpperCase()}${h.slice(1)} relay deployed`,"success"),p(!1),B()}catch(a){const o=w(a,"Relay deployment failed");q(i=>i&&{...i,error:o}),c(o,"error")}finally{Ne(!1)}}function Ie(s){M(s),te(s.name||""),ae(s.proxyUrl||""),ne(s.noProxy||""),oe(s.type||"http"),ce(s.strictProxy===!0)}async function Je(){if(!L.trim()||!K.trim())return c("Name and proxy URL required","error");T(!0);try{const s={name:L.trim(),proxyUrl:K.trim(),noProxy:re.trim(),type:le,strictProxy:ie};await hs(s),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool created","success"),u(!1),F()}catch(s){c(w(s,"Create failed"),"error")}finally{T(!1)}}async function es(){if(P){T(!0);try{const s={name:L.trim(),proxyUrl:K.trim(),noProxy:re.trim(),type:le,strictProxy:ie};await Le(P.id,s),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool updated","success"),M(null),F()}catch(s){c(w(s,"Update failed"),"error")}finally{T(!1)}}}async function Ae(s){const t=s.isActive===!1;try{await Le(s.id,{isActive:t}),await r.invalidateQueries({queryKey:["proxy-pools"]})}catch(a){c(w(a,"Toggle failed"),"error")}}async function qe(s){Se(s);try{const t=await fs(s);await r.invalidateQueries({queryKey:["proxy-pools"]}),t.ok?c(`Proxy OK${t.ip?` · ${t.ip}`:""}`,"success"):c(t.error||"Proxy test failed","error")}catch(t){c(w(t,"Test failed"),"error")}finally{Se(null)}}function ss(s){var a;const t=(a=s.providerSpecificData)==null?void 0:a.proxyPoolId;return typeof t=="string"&&t.trim()?t:typeof s.proxyPoolId=="string"&&s.proxyPoolId.trim()?s.proxyPoolId:null}function Ee(s){ke(s),O(new Set),ee(""),se("")}function ts(s){O(t=>{const a=new Set(t);return a.has(s)?a.delete(s):a.add(s),a})}function Oe(s){s.length&&O(t=>{const a=new Set(t),o=s.every(i=>a.has(i));for(const i of s)o?a.delete(i):a.add(i);return a})}async function Ue(s){if(!y.size){c("Select at least one connection","error");return}if(y.size>He){c(`Assign up to ${He} connections at a time`,"error");return}Te(!0);const t=[...y],a=[];for(let l=0;l<t.length;l+=12){const g=t.slice(l,l+12);a.push(...await Promise.allSettled(g.map(C=>vs(C,{proxyPoolId:s}))))}const o=a.filter(l=>l.status==="fulfilled").length,i=a.length-o;await Promise.all([r.invalidateQueries({queryKey:["proxy-pool-connections"]}),r.invalidateQueries({queryKey:["proxy-pools"]}),r.invalidateQueries({queryKey:["connections"]})]),O(new Set),Te(!1),i?c(`${o} updated, ${i} failed`,"error"):c(s?`${o} connection(s) assigned`:`${o} connection(s) set to direct`,"success")}async function as(){if(Z){T(!0);try{await ys(Z),await r.invalidateQueries({queryKey:["proxy-pools"]}),c("Pool deleted","success"),E(null)}catch(s){c(w(s,"Delete failed"),"error")}finally{T(!1)}}}return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ns,{title:"Proxy Pools",actions:U.length>0?e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e.jsxs(d,{size:"sm",variant:"outline",onClick:()=>{B(),p(!0)},children:[e.jsx(Ke,{className:"h-4 w-4 fill-current"}),"Deploy"]}),e.jsxs(d,{size:"sm",onClick:()=>{F(),u(!0)},children:[e.jsx(Re,{className:"h-4 w-4"}),"Add pool"]})]}):null}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx("span",{className:"sr-only",children:"Search proxy pools"}),e.jsx(Cs,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(v,{value:x,onChange:s=>S(s.target.value),placeholder:"Search pools…",className:"pl-9"})]}),e.jsx(is,{className:"overflow-hidden",children:e.jsx(cs,{className:"p-0",children:e.jsx("div",{className:"min-w-0",children:Xe?e.jsx("div",{className:"space-y-2 p-4",children:Array.from({length:3}).map((s,t)=>e.jsx(ds,{className:"h-12 w-full"},t))}):U.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-16 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No proxy pools"}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2",children:[e.jsxs(d,{size:"sm",onClick:()=>{F(),u(!0)},children:[e.jsx(Re,{className:"h-4 w-4"}),"Add first pool"]}),e.jsxs(d,{size:"sm",variant:"outline",onClick:()=>{B(),p(!0)},children:[e.jsx(Ke,{className:"h-4 w-4 fill-current"}),"Deploy relay"]})]})]}):de.length===0?e.jsx("div",{className:"px-4 py-16 text-center text-sm text-muted-foreground",children:"No proxy pools match your search."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-hidden rounded-xl border border-border/70 bg-card sm:hidden",children:e.jsx("div",{className:"divide-y divide-border/70",children:de.map(s=>e.jsxs("article",{className:"min-w-0 space-y-2.5 p-3",children:[e.jsxs("div",{className:"flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.name||s.id}),s.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]}),e.jsx(A,{label:s.proxyUrl||"—",children:e.jsx("p",{className:"mt-1 truncate font-mono text-[11px] text-muted-foreground",children:s.proxyUrl||"—"})})]}),e.jsx(D,{tone:s.testStatus==="ok"||s.testStatus==="active"?"ok":s.testStatus==="error"?"err":"muted",className:"shrink-0 text-[10px]",children:s.testStatus==="active"?"ok":s.testStatus||"unknown"})]}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"shrink-0 uppercase",children:s.type||"http"}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"min-w-0 truncate",children:[s.boundConnectionCount??0," connections"]})]}),e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ae(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ie(s),onDelete:()=>E(s.id)})]},s.id))})}),e.jsx("div",{className:"hidden min-w-0 sm:block",children:e.jsxs(ms,{variant:"card",className:"min-w-[44rem] text-[13px] [&_tbody]:before:hidden [&_tbody_tr_td]:!bg-transparent [&_tbody_tr:hover_td]:!bg-transparent [&_tbody_tr[data-state=selected]_td]:!bg-transparent",children:[e.jsx(xs,{className:"bg-transparent text-[10px] uppercase text-muted-foreground",children:e.jsxs(Qe,{className:"border-b border-border/80 bg-transparent hover:bg-transparent",children:[e.jsx(z,{className:"px-4 py-2 font-medium",children:"Name"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"URL"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Type"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Connections"}),e.jsx(z,{className:"px-3 py-2 font-medium",children:"Test"}),e.jsx(z,{className:"px-4 py-2 font-medium text-right",children:"Actions"})]})}),e.jsx(us,{children:de.map(s=>e.jsxs(Qe,{className:"border-b border-border/60 last:border-0 bg-transparent hover:bg-transparent data-[state=selected]:bg-transparent",children:[e.jsx(I,{className:"max-w-[14rem] bg-transparent px-4 py-2",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:s.name||s.id}),s.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]})}),e.jsx(I,{className:"max-w-[24rem] truncate bg-transparent px-3 py-2 font-mono text-xs text-muted-foreground",children:e.jsx(A,{label:s.proxyUrl||"—",children:e.jsx("span",{className:"block truncate",children:s.proxyUrl||"—"})})}),e.jsx(I,{className:"bg-transparent px-3 py-2 text-xs uppercase text-muted-foreground",children:s.type||"http"}),e.jsx(I,{className:"bg-transparent px-3 py-2 text-xs text-muted-foreground",children:s.boundConnectionCount??0}),e.jsx(I,{className:"bg-transparent px-3 py-2",children:e.jsx(D,{tone:s.testStatus==="ok"||s.testStatus==="active"?"ok":s.testStatus==="error"?"err":"muted",className:"w-fit text-[10px]",children:s.testStatus==="active"?"ok":s.testStatus||"unknown"})}),e.jsx(I,{className:"bg-transparent px-4 py-2",children:e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ae(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ie(s),onDelete:()=>E(s.id)})})]},s.id))})]})})]})})})}),e.jsx(H,{open:f||!!P,onOpenChange:s=>{s||(u(!1),M(null),F())},children:e.jsxs(V,{className:"max-h-[90vh]",children:[e.jsxs(G,{children:[e.jsx(X,{children:P?"Edit proxy pool":"Add proxy pool"}),e.jsx(ue,{children:"Used as connection outbound proxy."})]}),e.jsxs(pe,{className:"space-y-4",children:[e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Name"}),e.jsx(v,{value:L,onChange:s=>te(s.target.value),placeholder:"US residential"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Proxy URL (HTTP/HTTPS/SOCKS5)"}),e.jsx(v,{value:K,onChange:s=>ae(s.target.value),placeholder:"http://user:pass@host:port or host:port"})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"No-proxy"}),e.jsx(v,{value:re,onChange:s=>ne(s.target.value),placeholder:"localhost,127.0.0.1"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Type"}),e.jsx(Me,{size:"sm",value:le,onChange:oe,options:[{value:"http",label:"HTTP"},{value:"socks5",label:"SOCKS5"}]})]}),e.jsxs("label",{className:"flex items-start gap-2.5 rounded-lg border border-border/70 p-3",children:[e.jsx(xe,{checked:ie,onCheckedChange:s=>ce(s===!0),disabled:N,"aria-describedby":"strict-proxy-help"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium",children:"Require proxy"}),e.jsx("span",{id:"strict-proxy-help",className:"mt-0.5 block text-xs text-muted-foreground",children:"Fail requests when this proxy is unavailable instead of falling back to a direct connection."})]})]})]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>{u(!1),M(null)},disabled:N,children:"Cancel"}),e.jsx(d,{onClick:()=>void(P?es():Je()),disabled:N,children:N?"Saving…":P?"Save":"Create"})]})]})}),e.jsx(H,{open:b,onOpenChange:s=>{p(s),s||B()},children:e.jsxs(V,{className:"max-h-[90vh]",children:[e.jsx(G,{children:e.jsx(X,{children:"Deploy relay"})}),e.jsxs(pe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Platform"}),e.jsx(Me,{size:"sm",value:h,onChange:s=>je(s),options:[{value:"vercel",label:"Vercel"},{value:"cloudflare",label:"Cloudflare"}]})]}),e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Project name (optional)"}),e.jsx(v,{value:Y,onChange:s=>ge(s.target.value),placeholder:"sway-router-relay",autoComplete:"off"})]}),h==="cloudflare"?e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Account ID"}),e.jsx(v,{value:W,onChange:s=>be(s.target.value),placeholder:"Cloudflare account ID",autoComplete:"off"})]}):null,e.jsxs("label",{className:"block space-y-1.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:h==="vercel"?"Vercel API token":"Cloudflare API token"}),e.jsx(v,{type:"password",value:_,onChange:s=>ve(s.target.value),placeholder:"Token",autoComplete:"off"})]}),Ce?e.jsx(zs,{progress:Ce}):null]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>p(!1),disabled:k,children:"Cancel"}),e.jsxs(d,{onClick:()=>void Ze(),disabled:k,children:[k?e.jsx(ye,{className:"size-4 animate-spin"}):null,k?"Deploying…":"Deploy"]})]})]})}),e.jsx(H,{open:!!m,onOpenChange:s=>{s||(ke(null),O(new Set),ee(""),se(""))},children:e.jsxs(V,{className:"max-h-[90vh] max-w-3xl",children:[e.jsxs(G,{children:[e.jsxs(X,{children:["Manage ",(m==null?void 0:m.name)||"proxy pool"]}),e.jsx(ue,{children:"Assign existing provider connections to this pool without recreating their credentials."})]}),e.jsxs(pe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(v,{value:J,onChange:s=>ee(s.target.value),placeholder:"Search provider, name, email, or ID…",className:"min-w-[14rem] flex-1"}),e.jsx(d,{size:"sm",variant:"outline",disabled:!R.length||Q,onClick:()=>Oe(R),children:We===R.length?"Clear visible":"Select visible"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:j.isLoading?"Loading connections…":`${(($e=j.data)==null?void 0:$e.pagination.totalItems)??$.length} connection(s) · ${y.size} selected`}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(d,{size:"sm",disabled:!y.size||Q,onClick:()=>void Ue((m==null?void 0:m.id)||null),children:Q?"Assigning…":"Assign selected"}),e.jsx(d,{size:"sm",variant:"outline",disabled:!y.size||Q,onClick:()=>void Ue(null),children:"Set direct"})]})]}),j.error?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:w(j.error,"Failed to load connections")}):ze.length===0&&!j.isLoading?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No existing connections match this search."}):e.jsxs(e.Fragment,{children:[(Fe=j.data)!=null&&Fe.pagination.hasNext?e.jsxs("p",{className:"rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-xs text-warning",children:["Showing the first ",Be," matches. Use search to find other connections."]}):null,e.jsx("div",{className:"max-h-[50vh] space-y-2 overflow-y-auto pr-1",children:ze.map(([s,t])=>{const a=t.map(l=>l.id),o=a.filter(l=>y.has(l)).length,i=o===a.length;return e.jsxs("div",{className:"rounded-lg border border-border",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/70 bg-muted/30 px-3 py-2",children:[e.jsx(xe,{checked:i,indeterminate:o>0&&!i,onCheckedChange:()=>Oe(a),"aria-label":`Select all ${s} connections`}),e.jsx("span",{className:"font-medium",children:Ye(s,t)}),e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:s}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o,"/",a.length]})]}),e.jsx("div",{className:"divide-y divide-border/60",children:t.map(l=>{const g=ss(l),C=g===(m==null?void 0:m.id),_e=l.name||l.email||l.id.slice(0,8);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 hover:bg-muted/20",children:[e.jsx(xe,{checked:y.has(l.id),onCheckedChange:()=>ts(l.id),"aria-label":`Select ${_e}`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:_e}),e.jsxs("span",{className:"block truncate text-xs text-muted-foreground",children:[l.email&&l.name?`${l.email} · `:"",l.authType||"connection"," · ",l.id.slice(0,8)]})]}),e.jsx(D,{tone:l.isActive===!1?"muted":C?"ok":"muted",className:"shrink-0 text-[10px]",children:C?"This pool":g?"Other pool":"Direct"}),l.isActive===!1?e.jsx(D,{tone:"muted",className:"shrink-0 text-[10px]",children:"Off"}):null]},l.id)})})]},s)})})]})]})]})}),e.jsx(H,{open:!!Z,onOpenChange:s=>{s||E(null)},children:e.jsxs(V,{children:[e.jsxs(G,{children:[e.jsx(X,{children:"Delete pool?"}),e.jsx(ue,{children:"Detach all connections using this pool before deleting it. Bound pools cannot be deleted."})]}),e.jsxs(he,{children:[e.jsx(d,{variant:"outline",onClick:()=>E(null),disabled:N,children:"Cancel"}),e.jsx(d,{variant:"destructive",onClick:as,disabled:N,children:N?"Deleting…":"Delete"})]})]})})]})}export{Xs as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as v,j as e,L as de}from"./react-vendor-xnYrwzsL.js";import{u as ce,a as ue,e as H}from"./query-vendor-DVevaSVS.js";import{g as G,c as C,P as me,Q as xe,C as he,p as Q,e as _,t as q,w as fe,R as pe,b as ge,h as ve}from"./index-x5tLD3Ye.js";import{H as be}from"./Header-9KXz4S67.js";import{R as z}from"./ripple-button-BV_KcZ7W.js";import{S as y}from"./StatusBadge-DClAYX7v.js";import{F as A,a as D,c as F,d as X}from"./frame-BLwA8c3u.js";import{S as N}from"./skeleton-CFSSp0e0.js";import{z as je,B as Ne}from"./connections-api-CQHf0Hwe.js";import{p as V}from"./live-mode-CHShLY4E.js";import{aa as B,i as Y,ay as we}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const ye=new Set(["github","gemini-cli","antigravity","claude","codex","kiro","qoder","ollama","glm","glm-cn","minimax","minimax-cn","vercel-ai-gateway","codebuddy-cn","codebuddy-intl","grok-cli","kimi","deepseek"]),Ce=25,L=200,Ee=6,I=3,P=[];let O=0;function Z(){var t;for(;O<Ee&&P.length>0;){const r=P.shift();if(!r)return;if((t=r.signal)!=null&&t.aborted){r.cleanup(),r.reject(r.signal.reason??new DOMException("Quota request aborted","AbortError"));continue}O+=1,r.started=!0,r.run().then(r.resolve).catch(r.reject).finally(()=>{r.cleanup(),O-=1,Z()})}}function Re(t,r){return new Promise((n,a)=>{if(r!=null&&r.aborted){a(r.reason??new DOMException("Quota request aborted","AbortError"));return}const i={run:async()=>t(),resolve:n,reject:a,signal:r,started:!1,cleanup:()=>{}},l=()=>{if(i.started)return;const m=P.indexOf(i);m!==-1&&(P.splice(m,1),i.cleanup(),a((r==null?void 0:r.reason)??new DOMException("Quota request aborted","AbortError")))};r==null||r.addEventListener("abort",l,{once:!0}),i.cleanup=()=>r==null?void 0:r.removeEventListener("abort",l),P.push(i),Z()})}const T=["expired","authentication","unauthorized","401","re-authorize"];function Pe(t){if(!t)return!1;const r=t.toLowerCase();return T.some(n=>r.includes(n))}function Me(t){var n,a;if(he.isAxiosError(t)){if(((n=t.response)==null?void 0:n.status)===401)return!0;const i=(a=t.response)==null?void 0:a.data,l=(i==null?void 0:i.error)||(i==null?void 0:i.message)||"";if(T.some(m=>l.toLowerCase().includes(m)))return!0}const r=t instanceof Error?t.message:"";return T.some(i=>r.toLowerCase().includes(i))}function ke(t,r){return!r||r<=0?0:!t||t<0?100:t>=r?0:Math.round((r-t)/r*100)}function Qe(t,r){const n=r==null?void 0:r.quotas;if(!n||typeof n!="object")return[];const a=t.toLowerCase();return Object.entries(n).flatMap(([i,l])=>{const m=Number.isFinite(Number(l.used))?Number(l.used):0,c=Number.isFinite(Number(l.total))?Number(l.total):0,x=a==="codex"&&l.remaining!==void 0?Math.max(0,Math.round(Number(l.remaining))):l.remainingPercentage!==void 0?Math.max(0,Math.round(Number(l.remainingPercentage))):ke(m,c);return a==="qoder"&&i==="organization"&&c<=0?[]:[{name:a==="antigravity"?l.displayName||i:a==="qoder"?i==="user"?"Personal":i==="organization"?"Organization":i:i,used:m,total:c,remaining:x,resetAt:l.resetAt??null,recurring:l.recurring!==!1,unlimited:l.unlimited===!0||c<=0,unit:l.unit}]})}function Ae(t){if(!t)return null;const r=new Date(t).getTime()-Date.now();if(!Number.isFinite(r)||r<=0)return null;const n=Math.ceil(r/6e4);if(n<60)return`${n}m`;const a=Math.floor(n/60);return a<24?`${a}h ${n%60}m`:`${Math.floor(a/24)}d ${a%24}h ${n%60}m`}function j(t){return Number.isFinite(t)?Math.round(t).toLocaleString("id-ID"):"0"}function Fe(t){return t>70?{text:"text-success",bg:"bg-success",bgLight:"bg-success/10"}:t>=30?{text:"text-warning",bg:"bg-warning",bgLight:"bg-warning/10"}:{text:"text-destructive",bg:"bg-destructive",bgLight:"bg-destructive/10"}}function $e(t){if(t.loading)return null;if(t.authExpired)return e.jsx(y,{tone:"warn",children:"Auth expired"});if(t.error)return e.jsx(y,{tone:"err",children:"Error"});if(t.conn.isActive===!1)return e.jsx(y,{tone:"muted",children:"Disabled"});if(t.quotas.length===0)return e.jsx(y,{tone:"muted",children:"No quota"});const r=Math.min(...t.quotas.map(n=>n.remaining));return r<=0?e.jsx(y,{tone:"err",children:"Limit reached"}):r<30?e.jsx(y,{tone:"warn",children:"Low quota"}):e.jsx(y,{tone:"ok",children:"OK"})}function J({provider:t}){const r=fe(t),n=pe(t),a=ge(t);return e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg",style:{backgroundColor:`${n}1f`,color:n},children:a?e.jsx("span",{"aria-hidden":"true",className:"block h-4 w-4 shrink-0",style:{backgroundColor:n,WebkitMaskImage:`url(${a})`,maskImage:`url(${a})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}}):e.jsx(r,{className:"h-4 w-4"})})}function Xe(){const t=ce(),[r,n]=v.useState(null),[a,i]=v.useState({}),[,l]=v.useState(0);v.useEffect(()=>{const s=window.setInterval(()=>{l(o=>o+1)},6e4);return()=>window.clearInterval(s)},[]);const m=ue({queryKey:["quota-provider-counts"],queryFn:Ne,enabled:V(),retry:!1}),c=v.useMemo(()=>(m.data??[]).map(s=>({...s,provider:String(s.provider||"").trim()})).filter(s=>ye.has(s.provider)&&s.total>0),[m.data]);v.useEffect(()=>{i(s=>{const o={};for(const u of c)o[u.provider]=Math.max(1,s[u.provider]??1);return o})},[c]);const x=v.useMemo(()=>c.flatMap(s=>{const o=a[s.provider]??1;return Array.from({length:o},(u,d)=>({provider:s.provider,page:d+1}))}),[c,a]),f=H({queries:x.map(s=>({queryKey:["quota-connections",s.provider,s.page],queryFn:()=>je({provider:s.provider,page:s.page,pageSize:Ce}),enabled:V(),retry:!1,staleTime:3e4}))}),E=v.useMemo(()=>{const s=new Map;return x.forEach((o,u)=>{var b,h;const d=((h=(b=f[u])==null?void 0:b.data)==null?void 0:h.connections)??[],p=s.get(o.provider)??[],M=new Set(p.map(w=>w.id));s.set(o.provider,[...p,...d.filter(w=>!M.has(w.id))])}),s},[f,x]),ee=v.useMemo(()=>{var o,u,d;const s=new Map;for(const p of c){const b=x.map((g,le)=>g.provider===p.provider?le:-1).filter(g=>g>=0).map(g=>f[g]),h=b[b.length-1],w=(o=h==null?void 0:h.data)==null?void 0:o.pagination,k=((u=E.get(p.provider))==null?void 0:u.length)??0,W=k>=L&&k<p.total;s.set(p.provider,{loading:!!((d=b[0])!=null&&d.isPending),fetching:b.some(g=>g==null?void 0:g.isFetching),error:b.some(g=>g==null?void 0:g.isError),hasNext:!W&&(!!(w!=null&&w.hasNext)||k<p.total),capped:W,loaded:k})}return s},[f,E,x,c]),$=v.useMemo(()=>c.flatMap(s=>E.get(s.provider)??[]),[E,c]),S=H({queries:$.map(s=>({queryKey:["quota-usage",s.id],queryFn:({signal:o})=>Re(()=>xe(s.id,o),o),enabled:!!s.id,retry:!1,staleTime:3e4}))}),te=v.useMemo(()=>{const s=new Map;return $.forEach((o,u)=>{var b;const d=S[u];let p;if(!d||d.isPending)p={conn:o,loading:!0,fetching:!!(d!=null&&d.isFetching),error:null,authExpired:!1,usage:null,quotas:[],message:null,resetCredits:0,plan:null};else if(d.isError){const h=G(d.error,"Failed to fetch quota");p={conn:o,loading:!1,fetching:d.isFetching,error:h,authExpired:Me(d.error),usage:null,quotas:[],message:h,resetCredits:0,plan:null}}else{const h=d.data??{};p={conn:o,loading:!1,fetching:d.isFetching,error:null,authExpired:Pe(h.message),usage:h,quotas:Qe(o.provider,h),message:h.message??null,resetCredits:((b=h.resetCredits)==null?void 0:b.availableCount)??0,plan:h.plan??null}}const M=s.get(o.provider)??[];s.set(o.provider,[...M,p])}),s},[$,S]);function R(s,o="default"){o==="success"?q.success(s):o==="error"?q.error(s):q(s)}async function se(){await Promise.all([t.invalidateQueries({queryKey:["quota-provider-counts"]}),t.invalidateQueries({queryKey:["quota-connections"]}),t.invalidateQueries({queryKey:["quota-usage"]})]),R("Refreshed","success")}function re(s,o){Promise.all([t.invalidateQueries({queryKey:["quota-connections",s]}),...o.map(u=>t.invalidateQueries({queryKey:["quota-usage",u.conn.id]}))])}function ne(s){t.invalidateQueries({queryKey:["quota-usage",s]})}function oe(s){var u;if((((u=E.get(s))==null?void 0:u.length)??0)>=L){R(`Quota view is limited to ${j(L)} accounts per provider`);return}i(d=>({...d,[s]:(d[s]??1)+1}))}async function ie(s){if(!r){n(s.id);try{const o=await me(s.id);o.reset===!1||o.code==="no_credit"?R(o.message||"No Codex reset credits available","error"):R("Codex quota reset","success"),await t.invalidateQueries({queryKey:["quota-usage",s.id]})}catch(o){R(G(o,"Reset failed"),"error")}finally{n(null)}}}const K=m.isLoading,ae=!K&&c.length===0,U=m.isFetching||f.some(s=>s==null?void 0:s.isFetching)||S.some(s=>s==null?void 0:s.isFetching);return e.jsxs("div",{className:"min-w-0 max-w-full space-y-4 overflow-x-hidden",children:[e.jsx(be,{title:"Quota",actions:e.jsxs(z,{size:"sm",variant:"outline",disabled:U,onClick:()=>void se(),children:[e.jsx(B,{className:C("h-3.5 w-3.5",U&&"animate-spin")}),"Refresh"]})}),m.isError?e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:"Unable to load live quota providers. Check your session and backend connection."}):null,K?e.jsx("div",{className:"space-y-4",children:["provider-skeleton-a","provider-skeleton-b"].map(s=>e.jsxs(A,{children:[e.jsxs(D,{className:"flex flex-row items-center gap-3 p-4",children:[e.jsx(N,{className:"h-9 w-9 rounded-lg"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(N,{className:"h-4 w-28"}),e.jsx(N,{className:"h-3 w-44"})]})]}),e.jsx(F,{className:"grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((o,u)=>e.jsx(N,{className:"h-48 w-full rounded-xl"},u))})]},s))}):ae?e.jsx(A,{children:e.jsxs(F,{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:"No providers connected"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Connect an OAuth provider to track API quota limits and usage."})]})}):e.jsx("div",{className:"space-y-4",children:c.map(s=>{const o=te.get(s.provider)??[],u=ee.get(s.provider)??{loading:!0,fetching:!1,error:!1,hasNext:!1,capped:!1,loaded:0};return e.jsx(Se,{group:s,cards:o,pageState:u,onRefreshProvider:()=>re(s.provider,o),onRefreshCard:ne,onLoadMore:()=>oe(s.provider),onResetCodex:ie,resettingId:r},s.provider)})})]})}function Se({group:t,cards:r,pageState:n,onRefreshProvider:a,onRefreshCard:i,onLoadMore:l,onResetCodex:m,resettingId:c}){return e.jsxs(A,{className:"min-w-0 max-w-full overflow-hidden",children:[e.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(J,{provider:t.provider}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate text-sm font-semibold",children:Q(t.provider)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:n.loaded>0?`${n.loaded} of ${j(t.total)} accounts loaded`:`${j(t.total)} accounts`})]})]}),e.jsx(_,{label:`Refresh ${Q(t.provider)} quota`,children:e.jsx("button",{type:"button",onClick:a,disabled:n.fetching,className:"grid h-8 w-8 shrink-0 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground disabled:opacity-50","aria-label":`Refresh ${Q(t.provider)} quota`,children:e.jsx(B,{className:C("h-3.5 w-3.5",n.fetching&&"animate-spin")})})})]}),e.jsxs(F,{className:"min-w-0 p-3",children:[n.error?e.jsxs("div",{className:"mb-3 rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["Some ",Q(t.provider)," accounts could not be loaded. Refresh this section to retry."]}):null,n.loading&&r.length===0?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((x,f)=>e.jsx(N,{className:"h-48 w-full rounded-xl"},f))}):r.length>0?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:r.map(x=>e.jsx(qe,{card:x,onRefresh:()=>i(x.conn.id),onResetCodex:()=>m(x.conn),resetting:c===x.conn.id},x.conn.id))}):e.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No accounts available for this provider."})]}),n.hasNext||n.capped?e.jsxs(X,{className:"flex items-center justify-between gap-3 border-t border-border p-3",children:[e.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:n.capped?`Showing ${j(n.loaded)} of ${j(t.total)} accounts. Quota loading is capped for performance.`:`Showing ${j(n.loaded)} of ${j(t.total)} accounts`}),n.hasNext?e.jsxs(z,{size:"sm",variant:"outline",onClick:l,disabled:n.fetching,children:[e.jsx(Y,{className:"h-3.5 w-3.5"}),n.fetching?"Loading…":"Load more"]}):null]}):null]})}function qe({card:t,onRefresh:r,onResetCodex:n,resetting:a}){const{conn:i}=t,[l,m]=v.useState(!1),c=t.authExpired?"Re-authorize the connection first":t.resetCredits<=0?"No Codex reset credits available":"Spend one Codex reset credit to reset the quota window",x=l?t.quotas:t.quotas.slice(0,I);return e.jsxs(A,{className:"flex min-w-0 flex-col overflow-hidden",children:[e.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(J,{provider:i.provider}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"truncate text-sm font-medium leading-tight",children:i.name||i.email||i.provider}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:i.email&&i.name?i.email:`Connection ID · ${i.id}`})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[$e(t),e.jsx(_,{label:"Refresh quota",children:e.jsx("button",{type:"button",onClick:r,disabled:t.fetching,className:"grid h-7 w-7 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground disabled:opacity-50","aria-label":t.fetching?"Refreshing quota":"Refresh quota",children:e.jsx(B,{className:C("h-3.5 w-3.5",t.fetching&&"animate-spin")})})})]})]}),e.jsxs(F,{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-3 p-4",children:[t.plan?e.jsx(ve,{variant:"outline",className:"w-fit text-[10px]",children:t.plan}):null,e.jsx("div",{className:"min-h-[3.5rem] flex-1",children:t.loading?e.jsxs("div",{className:"space-y-2",children:[e.jsx(N,{className:"h-4 w-full"}),e.jsx(N,{className:"h-1.5 w-full"}),e.jsx(N,{className:"h-3 w-2/3"})]}):t.authExpired?e.jsxs("div",{className:"rounded-lg border border-warning/25 bg-warning/10 px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-warning",children:"Authentication expired"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:t.message||t.error}),e.jsx(de,{to:"/dashboard/provider",className:"mt-1.5 inline-block text-[11px] font-medium text-warning underline underline-offset-2",children:"Re-authorize in Providers"})]}):t.error?e.jsxs("div",{className:"rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-destructive",children:"Failed to load quota"}),e.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:t.error})]}):t.quotas.length>0?e.jsxs("div",{className:"space-y-3",children:[t.message?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:t.message}):null,x.map(f=>e.jsx(Le,{quota:f},`${f.name}-${f.unit??""}`)),t.quotas.length>I?e.jsxs("button",{type:"button",onClick:()=>m(f=>!f),className:"inline-flex items-center gap-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(Y,{className:C("h-3 w-3 transition-transform",l&&"rotate-180")}),l?"Show less":`Show ${t.quotas.length-I} more`]}):null]}):t.message?e.jsx("div",{className:"rounded-lg border border-border bg-surface px-3 py-2 text-[11px] text-muted-foreground",children:t.message}):e.jsx("div",{className:"py-6 text-center text-[11px] text-muted-foreground",children:"No quota data available"})})]}),i.provider==="codex"?e.jsxs(X,{className:"flex items-center justify-between gap-2 border-t border-border p-4",children:[e.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[t.resetCredits," reset credit",t.resetCredits===1?"":"s"]}),e.jsx(_,{label:c,children:e.jsxs(z,{size:"sm",variant:"outline",onClick:n,disabled:t.resetCredits<=0||t.authExpired||a||t.loading,children:[e.jsx(we,{className:"h-3.5 w-3.5"}),a?"Resetting…":"Reset quota"]})})]}):null]})}function Le({quota:t}){const r=Fe(t.remaining),n=Ae(t.resetAt),a=t.recurring?"Reset":"Expires";return e.jsxs("div",{className:"min-w-0 space-y-1.5 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"min-w-0 truncate text-xs font-medium",children:t.name}),e.jsxs("span",{className:C("shrink-0 text-xs font-medium tabular-nums",r.text),children:[t.remaining,"%"]})]}),t.unlimited?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Unlimited"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:C("h-1.5 overflow-hidden rounded-full",r.bgLight),children:e.jsx("div",{className:C("h-full rounded-full transition-all duration-300",r.bg),style:{width:`${Math.min(t.remaining,100)}%`}})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] text-muted-foreground",children:[e.jsxs("span",{className:"tabular-nums",children:[j(t.used)," / ",t.total>0?j(t.total):"∞"]}),n?e.jsxs("span",{className:"tabular-nums",children:[a," in ",n]}):null]})]})]})}export{Xe as default};
|