swayrouter 1.3.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dashboard/dist/assets/{CliTools-BA3qQ4Y-.js → CliTools-BIvAMkEP.js} +1 -1
- package/dashboard/dist/assets/{Combo-CoYmIAt0.js → Combo-DZ0yCwJq.js} +1 -1
- package/dashboard/dist/assets/{ConsoleLog-DEJBcRXY.js → ConsoleLog-DYc8yWoO.js} +1 -1
- package/dashboard/dist/assets/{Dashboard-0H0FmS_z.js → Dashboard-BGpeqNLd.js} +1 -1
- package/dashboard/dist/assets/{Header-DjeUJuR7.js → Header-bX_7xlVV.js} +1 -1
- package/dashboard/dist/assets/{Keys-D5i0CJPw.js → Keys-DUR_KMaU.js} +1 -1
- package/dashboard/dist/assets/{Login-Bmyb9mgb.js → Login-j-Fu6nmK.js} +1 -1
- package/dashboard/dist/assets/{ManageApiKey--COl62Nm.js → ManageApiKey-CChQc5sm.js} +1 -1
- package/dashboard/dist/assets/{OAuthCallback-DH2M63oY.js → OAuthCallback-CuMYq0kD.js} +1 -1
- package/dashboard/dist/assets/Provider-CKuPL89U.js +4 -0
- package/dashboard/dist/assets/{ProviderModelAccordion-Cuk2_DWf.js → ProviderModelAccordion-qY8m5iA3.js} +1 -1
- package/dashboard/dist/assets/{Proxy-C2UzXL2r.js → Proxy-DaEipiQW.js} +1 -1
- package/dashboard/dist/assets/{QuotaMonitor-gk5otjdB.js → QuotaMonitor-9oxr_V-M.js} +1 -1
- package/dashboard/dist/assets/{Settings-DlOhYL96.js → Settings-oBD2zi37.js} +1 -1
- package/dashboard/dist/assets/{Setup-3-yf1tvY.js → Setup-BfPMueRP.js} +1 -1
- package/dashboard/dist/assets/{StatusBadge-iBeqU7Qd.js → StatusBadge-DwoF6JKt.js} +1 -1
- package/dashboard/dist/assets/{SwayChat-BlbMT8HI.js → SwayChat-BN0OcHod.js} +1 -1
- package/dashboard/dist/assets/{Usage-C1uKYlTO.js → Usage-BZG-TSrV.js} +1 -1
- package/dashboard/dist/assets/{accordion-DovdZQJu.js → accordion-oO6QoOCj.js} +1 -1
- package/dashboard/dist/assets/{admin-extras-api-5xk7DmbO.js → admin-extras-api-LcymBrBl.js} +1 -1
- package/dashboard/dist/assets/{api-keys-api-DVdIV17Y.js → api-keys-api-DRZ4baCv.js} +1 -1
- package/dashboard/dist/assets/{card-DvGOwuMw.js → card-BtEmYJoF.js} +1 -1
- package/dashboard/dist/assets/{checkbox-ClXwjb6M.js → checkbox-Bp15fhqx.js} +1 -1
- package/dashboard/dist/assets/{connections-api-DlH7CVMr.js → connections-api-eXKpSjaP.js} +1 -1
- package/dashboard/dist/assets/{copy-button-CCsXIvkJ.js → copy-button-CmI5h4W6.js} +1 -1
- package/dashboard/dist/assets/{currency-api-CHfn9Y-I.js → currency-api-7hE88WWd.js} +1 -1
- package/dashboard/dist/assets/{flip-button-CDurxfqc.js → flip-button-D37ibV3U.js} +1 -1
- package/dashboard/dist/assets/{frame-CY26iHQE.js → frame-C_Vz9WkQ.js} +1 -1
- package/dashboard/dist/assets/{index-CkR38iPY.js → index-B7c_Oeni.js} +2 -2
- package/dashboard/dist/assets/{ripple-button-BrLlmKvT.js → ripple-button-Bi2qoFsd.js} +1 -1
- package/dashboard/dist/assets/{segmented-CxobJihW.js → segmented-JQkY0jOQ.js} +1 -1
- package/dashboard/dist/assets/{select-DfWoWPVg.js → select-i3aesCPb.js} +1 -1
- package/dashboard/dist/assets/{skeleton-81lPHspy.js → skeleton-CUHI70xv.js} +1 -1
- package/dashboard/dist/assets/{table-CEyzPvr7.js → table-BMmCRvDh.js} +1 -1
- package/dashboard/dist/assets/{tabs-DkTPKASE.js → tabs-CMGiJtvA.js} +1 -1
- package/dashboard/dist/assets/{tunnel-api-m02RsElG.js → tunnel-api-5eluT04C.js} +1 -1
- package/dashboard/dist/index.html +1 -1
- package/package.json +1 -1
- package/dashboard/dist/assets/Provider-DubAFZl3.js +0 -4
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{j as e,r as o}from"./react-vendor-xnYrwzsL.js";import{u as Ts,a as ft,d as Ms,b as ts}from"./query-vendor-DVevaSVS.js";import{H as Ps}from"./Header-bX_7xlVV.js";import{R as E}from"./ripple-button-Bi2qoFsd.js";import{I as re,T as un,c as me,D as Vt,m as Wt,n as Ht,o as Jt,q as Gt,g as Z,v as wn,s as bn,b as Es,e as ee,S as fs,w as ps,h as Wn,x as Ls,y as St,z as Is,A as Ks,t as Ct,C as $t,a as ns,E as Rs}from"./index-B7c_Oeni.js";import{g as Os,s as Fs,a as Ds,r as qs,b as ss,c as Bs,p as zs,d as xs,t as is,e as _s,f as Us,h as gs,u as $s,i as _n,j as Qs,k as Vs,l as rs,m as as,n as Ws,o as Un,q as dn,v as Hs,w as Js,x as Gs,y as Ys,z as Xs,A as Zs,B as ei}from"./connections-api-eXKpSjaP.js";import{a as ti,c as ni,u as si,d as ii,l as ri}from"./admin-extras-api-LcymBrBl.js";import{b as ai,d as oi,v as os,e as li,f as ci,a as di,h as ls,i as ui}from"./oauth-callback-CqYQzyd7.js";import{S as ce}from"./StatusBadge-DwoF6JKt.js";import{S as mi,a as hi,b as fi,c as pi}from"./select-i3aesCPb.js";import{S as Nt}from"./segmented-JQkY0jOQ.js";import{ag as Nn,ad as Gn,L as mn,X as Yn,q as vs,ah as xi,ai as gi,aj as vi,ak as yi,a8 as bi,a9 as wi,ac as Sn,al as ki,am as ji,an as Ci,ao as Ni,af as kn,A as Si,ab as Ai,ap as Ti,aq as Mi,h as ys}from"./icons-vendor-CUx7SB5V.js";import{A as Xn,m as pt}from"./motion-vendor-g5fpGzmJ.js";import{T as bs,a as ws,b as jn,c as ks}from"./tabs-CMGiJtvA.js";import{F as js,a as Cs,c as Ns}from"./frame-C_Vz9WkQ.js";import{S as Pi}from"./skeleton-CUHI70xv.js";import{F as Ei}from"./flip-button-D37ibV3U.js";import{C as Li}from"./checkbox-Bp15fhqx.js";import"./ui-vendor-BuM9f2NY.js";function An(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 Ii(n,s){return An(n,s)==="Add connection"?"Add":"Connect"}const Ki=[{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 Ri({value:n,region:s,startUrl:i,onChange:a,onRegionChange:u,onStartUrlChange:d}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Nt,{size:"sm",value:n,onChange:a,options:Ki.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(re,{placeholder:"AWS region (default: us-east-1)",value:s,onChange:h=>u(h.target.value)}),e.jsx(re,{placeholder:"AWS Start URL (https://...)",value:i,onChange:h=>d(h.target.value)})]}):null]})}function Oi({mode:n,refreshToken:s,clientId:i,clientSecret:a,profileArn:u,cliProxyJson:d,onRefreshTokenChange:h,onClientIdChange:w,onClientSecretChange:N,onProfileArnChange:S,onCliProxyJsonChange:I}){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:C=>h(C.target.value)}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(re,{placeholder:"Client ID (optional for IAM)",value:i,onChange:C=>w(C.target.value)}),e.jsx(re,{type:"password",placeholder:"Client secret (optional for IAM)",value:a,onChange:C=>N(C.target.value)})]}),e.jsx(re,{placeholder:"Profile ARN (optional)",value:u,onChange:C=>S(C.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:d,onChange:C=>I(C.target.value)}):null}function Fi({region:n,onChange:s}){return e.jsx(re,{placeholder:"AWS region (default: us-east-1)",value:n,onChange:i=>s(i.target.value)})}function Di({authLabel:n,apiKey:s,region:i,checking:a,keyValid:u,checkMsg:d,submitError:h,proxyPoolId:w,proxyOptions:N,showKiroRegion:S,onApiKeyChange:I,onRegionChange:C,onCheck:v,onProxyPoolChange:D}){var z;return e.jsxs("div",{className:"space-y-2",children:[S?e.jsx(Fi,{region:i,onChange:C}):null,e.jsx("label",{htmlFor:"connection-api-key",className:"text-xs font-medium text-muted-foreground",children:n}),e.jsx(re,{id:"connection-api-key",type:"password",placeholder:"API Key",value:s,"aria-invalid":!!h,"aria-describedby":h?"connection-submit-error":void 0,onChange:A=>I(A.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 v(),children:a?e.jsx(un,{children:"Checking…"}):"Check"}),u===!0?e.jsx(ce,{tone:"ok",children:"Valid"}):u===!1?e.jsx(ce,{tone:"err",children:"Invalid"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Validate before add"})]}),d&&u===!1?e.jsx("p",{className:me("text-xs",u?"text-success":"text-destructive"),children:d}):null,e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-xs text-muted-foreground",children:"Proxy pool"}),e.jsxs(mi,{value:w,onValueChange:A=>D(A??"pool_none"),children:[e.jsx(hi,{className:"w-full",children:e.jsx("span",{className:"truncate",children:((z=N.find(A=>A.id===w))==null?void 0:z.name)??"None (direct)"})}),e.jsx(fi,{children:N.map(A=>e.jsx(pi,{value:A.id,children:A.name},A.id))})]})]})]})}function qi({isDeviceFlow:n,isOAuthFlow:s,isKiroIam:i,authLink:a,userCode:u,deviceStatus:d,deviceCode:h,bootLoading:w,linkCopied:N,oauthCode:S,kiroStartUrl:I,onStartKiroAuthorization:C,onOpenAuthLink:v,onCopyAuthLink:D,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&&d?e.jsx("p",{className:"text-xs text-muted-foreground",children:d}):null,e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[i&&!h?e.jsx(E,{size:"sm",onClick:()=>void C(),disabled:w||!I.trim(),children:"Start authorization"}):null,e.jsx(E,{size:"sm",onClick:v,disabled:!a,children:"Open in browser"}),e.jsx(E,{size:"sm",variant:"outline",onClick:()=>void D(),disabled:!a,children:N?e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gn,{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(re,{className:"font-mono text-xs",placeholder:"code from /callback",value:S,onChange:A=>z(A.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 Bi({value:n,modes:s,onChange:i,label:a}){return e.jsx(Nt,{size:"sm",value:n,onChange:i,options:s.map(u=>({value:u,label:a(u)})),className:"w-full"})}function zi({value:n,onChange:s}){return e.jsx(bs,{value:n,onValueChange:i=>s(i),children:e.jsxs(ws,{className:"w-full",children:[e.jsx(jn,{value:"single",className:"flex-1",children:"Single API Key"}),e.jsx(jn,{value:"bulk",className:"flex-1",children:"Bulk API Key"})]})})}function _i({raw:n,rows:s,activeIndex:i,activeRow:a,checking:u,validCount:d,onRawChange:h,onCheck:w}){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:N=>h(N.target.value)}),u&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Xn,{initial:!1,mode:"wait",children:e.jsxs(pt.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(mn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Nn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Yn,{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(pt.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(ce,{tone:"ok",children:["Valid: ",d," API Key"]}),e.jsxs(ce,{tone:"err",children:["Error: ",s.filter(N=>N.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 w(),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 Ui({providerId:n,token:s,machineId:i,importing:a,message:u,hasError:d,onTokenChange:h,onMachineIdChange:w,onAutoImport:N}){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 N(),children:a?e.jsx(un,{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:me("text-xs",d?"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:S=>h(S.target.value)}),n==="cursor"?e.jsx(re,{placeholder:"Machine ID (cursorAuth machine id)",value:i,onChange:S=>w(S.target.value)}):null]})}function $i({raw:n,rows:s,activeIndex:i,activeRow:a,onRawChange:u,onCheck:d,validCount:h,checking:w}){const[N,S]=o.useState(0),I=Math.max(1,n.split(/\r?\n/).length);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.jsxs("div",{className:"relative flex h-36 max-h-36 overflow-hidden rounded-md border border-input bg-surface focus-within:outline-none focus-within:ring-2 focus-within:ring-ring",children:[e.jsx("div",{"aria-hidden":"true",className:"pointer-events-none h-36 w-10 shrink-0 overflow-hidden border-r border-border/70 bg-background/90 py-2 text-right font-mono text-xs leading-5 text-muted-foreground/75",children:e.jsx("div",{style:{transform:`translateY(-${N}px)`},children:Array.from({length:I},(C,v)=>e.jsx("div",{className:"px-2",children:v+1},v))})}),e.jsx("textarea",{id:"codebuddy-token",className:"h-36 max-h-36 min-h-36 min-w-0 flex-1 resize-none overflow-auto bg-transparent px-3 py-2 font-mono text-xs leading-5 text-foreground outline-none placeholder:text-muted-foreground/70",placeholder:`access-token-1
|
|
3
|
+
refresh-token-2
|
|
4
|
+
access-token-3|refresh-token-3`,value:n,autoComplete:"off",spellCheck:!1,wrap:"off","data-scrollbar-visible":"true",onChange:C=>u(C.target.value),onScroll:C=>S(C.currentTarget.scrollTop)})]})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!n.trim()||w,onClick:()=>void d(),children:w?e.jsx(un,{children:"Checking…"}):"Check all"})}),w&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Xn,{initial:!1,mode:"wait",children:e.jsxs(pt.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(mn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(Nn,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Yn,{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"}`)})}):!w&&s.length>0?e.jsxs(pt.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(ce,{tone:"ok",children:["Valid: ",h," account",h===1?"":"s"]}),e.jsxs(ce,{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 Qi(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 Vi=new Set(["claude","codex","xai"]),Wi=200,Hi=1e3;function Ji({open:n,provider:s,flow:i,onOpenChange:a,onSubmit:u}){var vn;const[d,h]=o.useState(""),[w,N]=o.useState(""),[S,I]=o.useState(""),[C,v]=o.useState(""),[D,z]=o.useState(""),[A,J]=o.useState(""),[Q,U]=o.useState("pool_none"),[G,V]=o.useState(()=>[{id:"pool_none",name:"None (direct)"}]),[be,O]=o.useState(!1),[De,qe]=o.useState(!1),[Be,we]=o.useState(null),[He,ne]=o.useState(null),[ke,Y]=o.useState(null),[xe,se]=o.useState(null),[R,oe]=o.useState(null),[je,K]=o.useState(null),[M,le]=o.useState(null),[ge,te]=o.useState(5),[ze,de]=o.useState(null),[Ce,Ae]=o.useState(null),[_e,xt]=o.useState(null),[lt,At]=o.useState(null),[ve,Tt]=o.useState("builder-id"),[gt,Mt]=o.useState("us-east-1"),[Xt,Pt]=o.useState(""),[Zt,vt]=o.useState(""),[hn,Et]=o.useState(""),[ct,Ue]=o.useState(""),[Lt,en]=o.useState(""),[It,Kt]=o.useState(""),[yt,Je]=o.useState(!1),[Tn,dt]=o.useState(null),[Mn,Ze]=o.useState(!1),[ue,et]=o.useState("single"),[bt,ut]=o.useState(""),[Rt,Ee]=o.useState([]),[Ot,wt]=o.useState(!1),[tn,Te]=o.useState(null),[Ft,nn]=o.useState(!1),[$e,tt]=o.useState([]),[kt,Qe]=o.useState(!1),[mt,Le]=o.useState(null);function Dt(m,f){return f==="apikey"?m==="qoder"?"API Key (PAT)":"API Key":f==="device"?"Device Code":f==="import"?m==="codebuddy-cn"||m==="codebuddy-intl"?"Access Token":"Import Token":f}const[qt,he]=o.useState(null),[sn,Ge]=o.useState(!1),[Bt,Ie]=o.useState(!1),[P,ht]=o.useState(!1),W=o.useRef(!1),nt=o.useRef(null),Me=o.useRef(!1),zt=o.useRef(null),c=o.useRef(null);function Ke(m=!1){ht(m)}function ae(){c.current&&(clearTimeout(c.current),c.current=null)}function Ne(){const m=zt.current;zt.current=null,m&&!m.closed&&m.close()}function st(m){const f=nt.current;!f||m&&f!==m||(nt.current=null,Ke(!1),f&&Bs(f).catch(()=>{}))}const ye=o.useRef(u);ye.current=u;const Re=o.useRef(d);Re.current=d;const ie=(s==null?void 0:s.id)==="kiro",Ve=(s==null?void 0:s.id)==="codebuddy-cn"||(s==null?void 0:s.id)==="codebuddy-intl",Se=(vn=s==null?void 0:s.authModes)!=null&&vn.length?s.authModes:null,Pn=!!(Se&&Se.length>1),[Ye,fn]=o.useState((Se==null?void 0:Se[0])??"auto"),En=ie?ve==="api-key"||ve==="import-token"||ve==="cli-proxy"?ve==="api-key"?"apikey":"import":"device":Se&&Se.includes(Ye)?Ye:i??(Se!=null&&Se.includes("device")?"device":"apikey"),fe=Rt.filter(m=>m.valid===!0),rn=tn===null?null:Rt[tn]??null,it=$e.filter(m=>m.valid===!0),Ln=mt===null?null:$e[mt]??null;function In(m){return m.split(/\r?\n/).map(f=>f.trim()).filter(Boolean).map(f=>{const k=f.includes("|")?f.split("|").map(p=>p.trim()):f.includes(",")?f.split(",").map(p=>p.trim()):[f];return{name:k.length>=2?k[0]:"",apiKey:k.length>=2?k[1]:k[0],valid:null,msg:void 0}})}async function _t(){if(!s)return;const m=In(bt);if(!m.length)return;wt(!0);const f=m.map(p=>({...p,checking:!1})),k=new Set;Ee([...f]),Te(0);try{for(let p=0;p<f.length;p+=1){Te(p);const T=f[p].apiKey.trim();if(k.has(T)){f[p]={...f[p],valid:!1,checking:!1,msg:"Duplicate API key in this batch"},Ee([...f]);continue}k.add(T),f[p]={...f[p],checking:!0},Ee([...f]);try{const q=await is({provider:s.id,apiKey:f[p].apiKey});f[p]={...f[p],valid:q.valid===!0,checking:!1,msg:q.valid===!0?"ok":q.error||"fail"}}catch(q){f[p]={...f[p],valid:!1,checking:!1,msg:Z(q,"error")}}Ee([...f]),await new Promise(q=>{window.setTimeout(q,Hi)})}}finally{Te(null),wt(!1)}}async function pn(){if(!(!s||!fe.length)){nn(!0),Y(null);try{await u({name:s.name,authFlow:"apikey",bulkKeys:fe.map(({name:m,apiKey:f},k)=>{const p=m.trim();return{name:p||`swayrouter-account${k+1}`,apiKey:f.trim(),autoName:!p}})})}catch(m){Y(Z(m,"Failed to add connections"))}finally{nn(!1)}}}const $=En,Xe=$==="apikey"||!!(s!=null&&s.isCustom),rt=$==="oauth",at=$==="device",xn=rt||at,an=Bt&&xn;function Kn(m){W.current=!0,ae(),Tt(m),et("single"),we(null),ne(null),Y(null),he(null),oe(null),K(null),le(null),de(null),se(null)}async function on(){if(!s||s.id!=="kiro")return;const m=ve==="iam"?"idc":"builder-id",f=Xt.trim();if(m==="idc"&&!f){he("AWS IAM Identity Center requires a Start URL");return}W.current=!0,ae(),Ie(!0),he(null),de(null),oe(null),K(null),le(null),se(null);try{const k=await ss("kiro",{authMethod:m,region:gt.trim()||"us-east-1",startUrl:f||void 0}),p=typeof k.device_code=="string"&&k.device_code||typeof k.deviceCode=="string"&&k.deviceCode||null;if(!p)throw new Error("Kiro did not return a device code");const T=typeof k.user_code=="string"&&k.user_code||typeof k.userCode=="string"&&k.userCode||null,q=typeof k.verification_uri_complete=="string"&&k.verification_uri_complete||typeof k.verificationUriComplete=="string"&&k.verificationUriComplete||typeof k.verification_uri=="string"&&k.verification_uri||typeof k.verificationUri=="string"&&k.verificationUri||null;oe(p),le(T),se(q),K(typeof k.codeVerifier=="string"?k.codeVerifier:null),te(typeof k.interval=="number"&&k.interval>0?k.interval:5),de("Waiting for you to authorize…")}catch(k){he(Z(k,"Failed to start Kiro authorization"))}finally{Ie(!1)}}if(o.useEffect(()=>{var m;n&&(fn(((m=s==null?void 0:s.authModes)==null?void 0:m[0])??"auto"),Tt("builder-id"),Mt("us-east-1"),Pt(""),vt(""),Et(""),Ue(""),en(""),Kt(""),v(""),ne(null),Je(!1),dt(null),Ze(!1),et("single"),ut(""),Ee([]),Te(null),tt([]),Qe(!1),Le(null))},[n,s==null?void 0:s.id]),o.useEffect(()=>{if(!n)return;let m=!1;async function f(){try{const k=await ti();if(m)return;V([{id:"pool_none",name:"None (direct)"},...k.map(p=>({id:p.id,name:String(p.name||p.id)}))])}catch{}}return f(),()=>{m=!0}},[n]),o.useEffect(()=>{if(!n||!s)return;h(""),N(""),I(""),z(""),J(""),U("pool_none"),O(!1),Ie(!1),qe(!1),we(null),ne(null),Y(null),Ge(!1),he(null),de(null),oe(null),K(null),le(null),Ae(null),xt(null),At(null),se(null),et("single"),ut(""),Ee([]),Te(null),wt(!1),nn(!1),W.current=!1;const m=s.id;let f=!1;async function k(){if($==="oauth"){Ie(!0);try{const p=Os(m),T=await Fs(m,p);if(f)return;const q=T.authUrl||T.url||T.authorizeUrl||null,_=typeof T.state=="string"?T.state:null,t=typeof T.codeVerifier=="string"?T.codeVerifier:null,r=typeof T.redirectUri=="string"&&T.redirectUri?T.redirectUri:p;se(typeof q=="string"?q:null),Ae(_),_&&ai(_,m),xt(t),At(r),Me.current=!1;const y=(typeof T.flowType=="string"?T.flowType:null)==="authorization_code_pkce"||Vi.has(m);if(!q||!_||!r||y&&!t)throw new Error("OAuth provider returned incomplete authorization data");if(m==="codex"||m==="xai"){const x=window.location.port||(window.location.protocol==="https:"?"443":"80");try{const g=_,b=t,j=r;if(!g||!b||!j)throw new Error("OAuth provider returned incomplete authorization data");const F=await Ds(m,{appPort:x});if(!F.success)throw new Error(F.reason==="port_busy"?"The OAuth callback port is already in use":"The OAuth callback listener could not start");if(nt.current=m,Ke(!1),(await qs(m,{state:g,codeVerifier:b,redirectUri:j})).success!==!0)throw new Error("The OAuth session could not be registered");if(f)return;Ke(!0)}catch(g){he(Z(g,"Automatic callback setup unavailable. Paste the browser callback code below.")),st(m)}}}catch(p){f||he(Z(p,"Failed to start OAuth"))}finally{f||Ie(!1)}return}if($==="device"){if(m==="kiro"){ve==="builder-id"&&on();return}Ie(!0);try{const p=await ss(s.id);if(f)return;const T=typeof p.device_code=="string"&&p.device_code||typeof p.deviceCode=="string"&&p.deviceCode||null,q=typeof p.user_code=="string"&&p.user_code||typeof p.userCode=="string"&&p.userCode||null,_=typeof p.verification_uri_complete=="string"&&p.verification_uri_complete||typeof p.verificationUriComplete=="string"&&p.verificationUriComplete||typeof p.verification_uri=="string"&&p.verification_uri||typeof p.verificationUri=="string"&&p.verificationUri||null;oe(T),le(q),se(_),K(typeof p.codeVerifier=="string"?p.codeVerifier:null);const t=typeof p.interval=="number"&&p.interval>0?p.interval:5;te(t),de("Waiting for you to authorize…")}catch(p){f||he(Z(p,"Failed to start device code"))}finally{f||Ie(!1)}}}return k(),()=>{f=!0,W.current=!0,ae(),Ne(),st(s.id)}},[n,s,$,ve]),o.useEffect(()=>{if(!n||!s||$!=="oauth"||!P||!Ce)return;let m=!1,f=0;const k=s.id,p=s.name,T=Ce,q=200,_=async()=>{if(!(m||Me.current)){f+=1;try{const t=await zs(k,T);if(m||Me.current)return;if(t.status==="done"){Me.current=!0,ae(),Ne(),st(k),O(!0);try{await ye.current({name:Re.current.trim()||p,alreadySaved:!0})}catch{he("Connection saved, but the provider list could not refresh")}finally{O(!1)}return}if(t.status==="error"){Me.current=!0,ae(),Ne(),st(k),he(t.error||"OAuth sign-in failed");return}}catch{}!m&&!Me.current&&f<q?c.current=setTimeout(()=>void _(),1500):!m&&!Me.current&&(he("OAuth sign-in timed out. Use the manual code fallback."),st(k))}};return c.current=setTimeout(()=>void _(),750),()=>{m=!0,ae()}},[n,s,$,P,Ce]),o.useEffect(()=>{if(!n||!s||$!=="oauth")return;const m=s.id,f=s.name,k=Ce;if(!k)return;let p=window.location.origin;if(lt)try{p=new URL(lt).origin}catch{return}const T=g=>os(di(g),{origin:p,eventOrigin:p,expectedState:k,expectedProvider:m});function q(g){if(!Me.current){if(g.error){g.state&&ls(g.state),he(g.errorDescription||g.error||"OAuth sign-in failed");return}!g.code||!g.state||(ls(g.state),Me.current=!0,J(g.code),de(null),O(!0),(async()=>{try{await ye.current({name:Re.current.trim()||f,authFlow:"oauth",oauthCode:g.code,oauthState:g.state,oauthCodeVerifier:_e||void 0,oauthRedirectUri:lt||void 0}),Ne()}catch(b){Me.current=!1,he(Z(b,"OAuth sign-in completed, but the token exchange failed. Restart the connection flow and try again."))}finally{O(!1)}})())}}function _(g){const b=os(g.data,{origin:p,eventOrigin:g.origin,expectedState:k,expectedProvider:m,eventSource:g.source,expectedSource:zt.current});b&&q(b)}const t=k,r=ui(t);function l(g){const b=g===void 0?oi(t):ci(g),j=b?T(b):null;j&&q(j)}function y(g){g.key===r&&l(g.newValue)}l(),window.addEventListener("message",_),window.addEventListener("storage",y);const x=window.setInterval(()=>l(),500);return()=>{window.removeEventListener("message",_),window.removeEventListener("storage",y),window.clearInterval(x)}},[n,s,$,Ce,_e,lt]),o.useEffect(()=>()=>{W.current=!0,ae(),Ne(),st()},[]),o.useEffect(()=>{if(!n||!s||$!=="device"||!R)return;W.current=!1;let m=null,f=!1;const k=s.id,p=s.name,T=je||void 0,q=Math.max(2,ge)*1e3;async function _(){if(!(f||W.current||!R)){try{const t=await xs(k,{deviceCode:R,codeVerifier:T,displayName:Re.current.trim()||p});if(f||W.current)return;if(t.success){de("Authorized — connection saved"),O(!0);try{await ye.current({name:Re.current.trim()||p,alreadySaved:!0})}catch{de("Authorized — refresh the list if not visible")}finally{O(!1)}return}t.pending?de("Still waiting for authorization…"):t.error&&de(t.error)}catch(t){f||de(Z(t,"Poll failed"))}!f&&!W.current&&(m=setTimeout(_,q))}}return m=setTimeout(_,q),()=>{f=!0,W.current=!0,m&&clearTimeout(m)}},[n,s==null?void 0:s.id,s==null?void 0:s.name,$,R,je,ge]),o.useEffect(()=>{we(null),ne(null),Y(null)},[w]),!s)return null;const Rn=An(s.authType,s.noAuth),On=Ii(s.authType,s.noAuth),ln=!be&&!an&&(Xe?Be===!0&&w.trim().length>0:$==="import"?Ve?it.length>0&&!kt:ie?ve==="import-token"?Zt.trim().length>0:It.trim().length>0:S.trim().length>0&&((s==null?void 0:s.id)!=="cursor"||D.trim().length>0):$==="oauth"?A.trim().length>0:$==="device"?!!R:!0);async function cn(){if(!(!s||!w.trim())){qe(!0),ne(null);try{const m=await is({provider:s.id,apiKey:w.trim(),...ie?{providerSpecificData:{region:gt.trim()||"us-east-1"}}:{}}),f=m.valid===!0;we(f),ne(f?"Key valid":m.error||"Key invalid")}catch(m){we(!1),ne(Z(m,"Check failed"))}finally{qe(!1)}}}async function gn(){if(!s||!C.trim())return;const m=Qi(C);if(!m.length)return;Qe(!0);const f=m.map(p=>({...p,checking:!1})),k=new Set;tt([...f]),Le(0);try{for(let p=0;p<f.length;p+=1){Le(p);const T=f[p];if(T.valid===!1){tt([...f]);continue}const q=T.credentialToken||`${T.accessToken}|${T.refreshToken}`;if(k.has(q)){f[p]={...T,valid:!1,checking:!1,msg:"Duplicate token pair in this batch"},tt([...f]);continue}k.add(q),f[p]={...T,checking:!0},tt([...f]);try{const _=await _s({provider:s.id,...T.credentialToken?{credentialToken:T.credentialToken}:{accessToken:T.accessToken,refreshToken:T.refreshToken}});f[p]={...T,valid:_.valid===!0,checking:!1,msg:_.valid===!0?"ok":_.error||"Token invalid"}}catch(_){f[p]={...T,valid:!1,checking:!1,msg:Z(_,"Token validation failed")}}tt([...f]),p<f.length-1&&await new Promise(_=>{window.setTimeout(_,Wi)})}}finally{Le(null),Qe(!1)}}async function Fn(){if(!(!s||s.id!=="cursor")){Je(!0),dt(null),Ze(!1);try{const m=await Us();if(!m.found||!m.accessToken||!m.machineId)throw new Error(m.error||"Cursor credentials were not found on this device");I(m.accessToken),z(m.machineId),dt("Cursor token and Machine ID filled automatically")}catch(m){Ze(!0),dt(Z(m,"Could not detect Cursor credentials"))}finally{Je(!1)}}}async function Dn(){if(xe)try{await navigator.clipboard.writeText(xe),Ge(!0),window.setTimeout(()=>Ge(!1),1500)}catch{}}function qn(){if(!xe)return;const m=window.open(xe,"sway-oauth","popup,width=600,height=700");zt.current=m,m||he("The browser blocked the authorization window. Open the URL above manually or allow popups for this dashboard.")}async function Bn(){if(!(!s||!ln)){O(!0),Y(null);try{const m=d.trim(),f=rt?li(A,Ce):null;await u({name:m,autoName:Xe&&!m,authFlow:$,apiKey:Xe&&w.trim()||void 0,importToken:$==="import"&&!ie&&!Ve&&S.trim()||void 0,codeBuddyToken:$==="import"&&Ve&&it.length===1&&it[0].credentialToken||void 0,codeBuddyTokens:$==="import"&&Ve?it.map((k,p)=>{const T=it.length===1?m:"";return{...k.credentialToken?{credentialToken:k.credentialToken}:{accessToken:k.accessToken,refreshToken:k.refreshToken},name:T||`swayrouter-account${p+1}`,autoName:!T}}):void 0,machineId:$==="import"&&D.trim()||void 0,kiroAuthMode:ie?ve:void 0,kiroRegion:ie?gt.trim()||"us-east-1":void 0,kiroRefreshToken:ie&&Zt.trim()||void 0,kiroClientId:ie&&hn.trim()||void 0,kiroClientSecret:ie&&ct.trim()||void 0,kiroProfileArn:ie&&Lt.trim()||void 0,kiroCliProxyJson:ie&&It.trim()||void 0,oauthCode:f==null?void 0:f.code,oauthState:f==null?void 0:f.state,oauthCodeVerifier:rt&&_e||void 0,oauthRedirectUri:rt&<||void 0,deviceCode:at&&R||void 0,deviceCodeVerifier:at&&je||void 0,proxyPoolId:Xe?Q:null})}catch(m){Y(Z(m,"Failed to add connection"))}finally{O(!1)}}}const zn=ue==="bulk"&&Xe?"Add connections":Rn;return e.jsx(Vt,{open:n,onOpenChange:a,children:e.jsxs(Wt,{children:[e.jsx(Ht,{children:e.jsxs(Jt,{children:[zn," — ",s.name]})}),e.jsxs("div",{className:me("px-6",Xe&&ue==="bulk"?"space-y-2 pb-4":"space-y-3 pb-4"),children:[!ie&&Pn&&Se?e.jsx(Bi,{value:Ye,modes:Se,label:m=>Dt((s==null?void 0:s.id)??"",m),onChange:m=>{fn(m),et("single"),ut(""),Ee([]),Te(null),Y(null)}}):null,ie?e.jsx(Ri,{value:ve,region:gt,startUrl:Xt,onChange:Kn,onRegionChange:Mt,onStartUrlChange:Pt}):null,Xe&&!ie?e.jsx(zi,{value:ue,onChange:et}):null,Xe&&!ie&&ue==="bulk"?e.jsx(_i,{raw:bt,rows:Rt,activeIndex:tn,activeRow:rn,checking:Ot,validCount:fe.length,onRawChange:m=>{ut(m),Ee([]),Te(null),Y(null)},onCheck:_t}):null,ue==="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(re,{id:"connection-account-name",placeholder:"Auto: swayrouter-account",value:d,"aria-invalid":!!ke,"aria-describedby":ke?"connection-submit-error":void 0,onChange:m=>{h(m.target.value),Y(null)}})]}),qt?e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive",children:qt}):null,an?e.jsx("p",{className:"text-xs text-muted-foreground",children:e.jsx(un,{children:"Starting auth flow…"})}):null,$==="import"?Ve?e.jsx($i,{raw:C,rows:$e,activeIndex:mt,activeRow:Ln,checking:kt,validCount:it.length,onRawChange:m=>{v(m),tt([]),Le(null),Y(null)},onCheck:gn}):ie?e.jsx(Oi,{mode:ve,refreshToken:Zt,clientId:hn,clientSecret:ct,profileArn:Lt,cliProxyJson:It,onRefreshTokenChange:vt,onClientIdChange:Et,onClientSecretChange:Ue,onProfileArnChange:en,onCliProxyJsonChange:Kt}):e.jsx(Ui,{providerId:s.id,token:S,machineId:D,importing:yt,message:Tn,hasError:Mn,onTokenChange:I,onMachineIdChange:z,onAutoImport:Fn}):$==="local"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Local provider — no key required."}):xn?e.jsx(qi,{isDeviceFlow:at,isOAuthFlow:rt,isKiroIam:ie&&ve==="iam",authLink:xe,userCode:M,deviceStatus:ze,deviceCode:R,bootLoading:Bt,linkCopied:sn,oauthCode:A,kiroStartUrl:Xt,onStartKiroAuthorization:on,onOpenAuthLink:qn,onCopyAuthLink:Dn,onOauthCodeChange:J}):e.jsx(Di,{authLabel:Dt(s.id,"apikey"),apiKey:w,region:gt,checking:De,keyValid:Be,checkMsg:He,submitError:ke,proxyPoolId:Q,proxyOptions:G,showKiroRegion:ie,onApiKeyChange:m=>{N(m),Y(null)},onRegionChange:Mt,onCheck:cn,onProxyPoolChange:U}),ke?e.jsx("p",{id:"connection-submit-error",className:"text-xs text-destructive",role:"alert",children:ke}):null]}):null]}),e.jsxs(Gt,{children:[e.jsx(E,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(E,{disabled:ue==="bulk"?Ft||Ot||fe.length===0:!ln,className:me((ue==="bulk"?Ft||Ot||fe.length===0:!ln)&&"opacity-40"),onClick:()=>void(ue==="bulk"?pn():Bn()),children:ue==="bulk"?Ft?"Adding…":"Add":be?e.jsx(un,{children:at||rt?"Waiting…":"Saving…"}):at?"Poll now":rt&&!A.trim()?"Waiting for browser…":On})]})]})})}function cs({open:n,onOpenChange:s,onCreate:i,initial:a,submitLabel:u="Create"}){const[d,h]=o.useState(""),[w,N]=o.useState(""),[S,I]=o.useState(""),[C,v]=o.useState("openai-compatible"),[D,z]=o.useState("chat");o.useEffect(()=>{!n||!a||(h(a.name||""),N(a.alias||""),I(a.baseUrl||""),v(a.nodeType==="anthropic-compatible"?"anthropic-compatible":"openai-compatible"),z(a.apiType==="responses"?"responses":"chat"),G(null),Q(!1))},[n,a]);const A=!!a,[J,Q]=o.useState(!1),[U,G]=o.useState(null);return o.useEffect(()=>{n&&(a||(h(""),N(""),I(""),v("openai-compatible"),z("chat"),G(null),Q(!1)))},[n,a]),e.jsx(Vt,{open:n,onOpenChange:s,children:e.jsxs(Wt,{children:[e.jsx(Ht,{children:e.jsx(Jt,{children:A?"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(re,{id:"custom-provider-name",placeholder:"My provider",value:d,"aria-invalid":!!U,"aria-describedby":U?"custom-provider-error":void 0,onChange:V=>{h(V.target.value),G(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(re,{id:"custom-provider-prefix",placeholder:"my-llm",value:w,"aria-invalid":!!U,"aria-describedby":U?"custom-provider-error":void 0,onChange:V=>{N(V.target.value),G(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(re,{id:"custom-provider-base-url",placeholder:"https://api.example.com/v1",value:S,onChange:V=>I(V.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(Nt,{size:"sm",value:C,onChange:v,options:[{value:"openai-compatible",label:"OpenAI"},{value:"anthropic-compatible",label:"Claude"}]})]}),C==="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(Nt,{size:"sm",value:D,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)."}),U?e.jsx("p",{id:"custom-provider-error",className:"text-sm text-destructive",role:"alert",children:U}):null]}),e.jsxs(Gt,{children:[e.jsx(E,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(E,{disabled:J,onClick:()=>{if(!d.trim()||!w.trim()){G("Name and prefix required");return}Q(!0),i({name:d.trim(),prefix:w.trim().toLowerCase().replace(/\s+/g,"-"),baseUrl:S.trim()||void 0,type:C,apiType:C==="openai-compatible"?D:void 0}).catch(V=>{G(Z(V,"Failed to save custom provider"))}).finally(()=>Q(!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 Gi({conn:n,onOpenChange:s,onSave:i}){var V,be;const[a,u]=o.useState(""),[d,h]=o.useState(!1),[w,N]=o.useState(""),[S,I]=o.useState(null),[C,v]=o.useState(!1);o.useEffect(()=>{n&&(u(n.name||""),N(""),I(null))},[n]);const D=String((n==null?void 0:n.authType)||"").trim().toLowerCase(),z=typeof((V=n==null?void 0:n.providerSpecificData)==null?void 0:V.authMethod)=="string"?n.providerSpecificData.authMethod.trim().toLowerCase():"",A=D||z,J=n?wn(n.provider):"apikey",Q=A==="apikey"||A==="api_key"||A==="api-key"||!A&&J==="apikey",U=A.includes("oauth")||A==="access_token"||!A&&(J==="oauth"||J==="device")?"OAuth":A.includes("cookie")?"Cookie":A==="local"||A==="none"||!A&&J==="local"?"No authentication":A.includes("import")||A==="imported"?"Imported token":Q?"API Key":A||"Managed credentials";async function G(){if(n){v(!0),I(null);try{const O=await gs(n.id),De=O.valid===!0;I({label:De?"Active":O.error||"Failed",ok:De})}catch(O){I({label:Z(O,"Test failed"),ok:!1})}finally{v(!1)}}}return e.jsx(Vt,{open:!!n,onOpenChange:s,children:e.jsxs(Wt,{children:[e.jsxs(Ht,{children:[e.jsx(Jt,{children:"Edit connection"}),e.jsx(bn,{children:(n==null?void 0:n.name)||((be=n==null?void 0:n.id)==null?void 0:be.slice(0,8))})]}),e.jsxs("div",{className:"space-y-3 px-6",children:[e.jsx($n,{label:"Name",children:e.jsx(re,{value:a,onChange:O=>u(O.target.value)})}),Q?e.jsxs($n,{label:"API Key",hint:"Leave empty to keep current key",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(re,{type:"password",value:w,onChange:O=>N(O.target.value),placeholder:"sk-… or paste new key",className:"flex-1"}),e.jsx(E,{size:"sm",variant:"outline",disabled:C,"aria-busy":C,"aria-label":C?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void G(),children:C?e.jsx(mn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),S?e.jsx("p",{className:me("mt-1 text-[11px]",S.ok?"text-success":"text-destructive"),children:S.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:U}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Credentials are managed by this connection."})]}),e.jsx(E,{size:"sm",variant:"outline",disabled:C,"aria-busy":C,"aria-label":C?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void G(),children:C?e.jsx(mn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):"Test"})]}),S?e.jsx("p",{className:me("mt-1 text-[11px]",S.ok?"text-success":"text-destructive"),children:S.label}):null]})]}),e.jsxs(Gt,{children:[e.jsx(E,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(E,{disabled:d,onClick:()=>{h(!0),i(a.trim(),w).finally(()=>h(!1))},children:"Save"})]})]})})}function Ss({id:n,color:s,size:i=24,fallbackIcon:a}){const u=Es(n);if(u){const d=Math.max(4,Math.round(i/5));return e.jsx("span",{"aria-hidden":"true",className:"block shrink-0",style:{width:i,height:i,borderRadius:d,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 Yi({byProvider:n,filter:s,hiddenProviders:i,loading:a,query:u,providerListRef:d,selectedId:h,sorted:w,onFilterChange:N,onQueryChange:S,onSelectProvider:I,onToggleProviderHidden:C}){return e.jsxs(js,{className:me("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(Cs,{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(vs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(re,{className:me("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:v=>S(v.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:()=>S(""),children:e.jsx(Yn,{className:"h-4 w-4"})})}):null]}),e.jsx(Nt,{size:"sm",value:s,onChange:N,options:[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"idle",label:"Idle"}]})]}),e.jsx(Ns,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsx(fs,{overscrollContain:!0,scrollFade:!0,scrollbarGutter:!0,viewportRef:d,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((v,D)=>e.jsx(Pi,{className:"h-14 w-full rounded-lg"},D))}):w.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:w.map(v=>{const D=n.get(v.id)||[],z=v.id===h?D.length:v.connected||0,A=v.id===h?D.filter(O=>O.isActive!==!1).length:z,J=v.id===h?D.length-A:0,Q=h===v.id,U=i.includes(v.id),G=ps(v.id),V=v.isCustom?"apikey":wn(v.id,v.authType,v.noAuth),be=V==="apikey"?xi:V==="oauth"||V==="device"?gi:V==="import"?vi:yi;return e.jsx("li",{"data-provider-id":v.id,children:e.jsxs("div",{className:me("group relative flex w-full items-center rounded-lg transition-colors duration-100",Q?"text-foreground":"hover:bg-surface-hover/70",U&&"opacity-55"),children:[Q?e.jsx(pt.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:()=>I(v.id),className:me("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(Ss,{id:v.id,color:"var(--background)",size:20,fallbackIcon:G}),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(be,{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:v.name}),e.jsx(Wn,{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:v.alias||v.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:[(v.id==="opencode"?["Built-in"]:Ls(v.authType,v.noAuth,v.authModes,v.id)).map(O=>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(be,{className:"h-2.5 w-2.5"}),O]},O)),v.id==="opencode"?e.jsx(ce,{tone:"ok",className:"text-[10px] font-medium sm:text-[11px]",children:"Active"}):null,v.id==="opencode"?null:z>0?e.jsxs(e.Fragment,{children:[J>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:[J," off"]}):null,e.jsxs(ce,{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:U?"Show provider":"Hide provider",children:e.jsx("button",{type:"button","aria-label":U?`Show ${v.name}`:`Hide ${v.name}`,"aria-pressed":U,onClick:()=>C(v.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:U?e.jsx(bi,{className:"size-3.5"}):e.jsx(wi,{className:"size-3.5"})})})]})},v.id)})})})})})]})}function Yt({busy:n,onTest:s,onStop:i,label:a="Test",disabled:u,compact:d}){return n?e.jsx(ee,{label:"Cancel test",disabled:!d,children:e.jsxs(E,{size:"sm",variant:"outline",onClick:i,"aria-label":d?"Cancel test":void 0,className:me(d&&"h-7 w-7 p-0",!d&&"gap-1.5"),children:[e.jsx(mn,{className:"h-3.5 w-3.5 animate-spin"}),d?null:"Cancel"]})}):e.jsx(ee,{label:a,disabled:!d,children:e.jsx(E,{size:"sm",variant:"outline",disabled:u,onClick:s,"aria-label":d?a:void 0,className:d?"h-7 px-2 text-[11px]":void 0,children:a})})}function Cn(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 d=i.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,"");return d=d.replace(/^clinepass\//i,"").replace(/^cline-pass\//i,""),`clinepass/${d}`}const Xi=["vision","pdf","audioInput","videoInput","imageOutput","audioOutput","search","tools","reasoning"];function Hn(n){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n,i={};for(const a of Xi)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 Zi=[["vision","Vision"],["pdf","PDF"],["audioInput","Audio"],["videoInput","Video"],["imageOutput","Image out"],["audioOutput","Audio out"],["search","Search"],["tools","Tools"],["reasoning","Reasoning"]];function er(n){return n?Zi.filter(([s])=>n[s]===!0).map(([s,i])=>({key:s,label:i})):[]}function Qn(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():"",d=Cn(u,s);if(!d)return[];const h=typeof a.name=="string"&&a.name.trim()?a.name.trim():d,w=Array.isArray(a.thinkingLevels)?a.thinkingLevels.filter(N=>typeof N=="string"):void 0;return[{id:d,name:h,caps:Hn(a.capabilities??a.caps),...w?{thinkingLevels:w}:{}}]}):[]}function ds(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 tr(n,s){var a;const i=new Map;for(const u of n){const d=Cn(u.id,u.provider_alias||u.provider_id||u.owned_by||s);if(!d)continue;const h=d===u.id?u:{...u,id:d},w=i.get(d);if(!w){i.set(d,h);continue}const N=ds(w.name,d)&&!ds(h.name,d)?h.name:w.name||h.name;i.set(d,{...w,name:N,provider_alias:w.provider_alias||h.provider_alias,provider_id:w.provider_id||h.provider_id,owned_by:w.owned_by||h.owned_by,caps:{...h.caps,...w.caps},thinkingLevels:(a=w.thinkingLevels)!=null&&a.length?w.thinkingLevels:h.thinkingLevels})}return[...i.values()]}function nr({selected:n,visibleModels:s,models:i,modelNames:a,modelsLoading:u,modelsUnavailable:d,importingModels:h,testConnId:w,batchKind:N,modelTestLock:S,testingModels:I,modelQuery:C,newModel:v,addingModel:D,modelResults:z,pinnedFor:A,copied:J,onImportModels:Q,onTestAllModels:U,onStopTests:G,onStopModel:V,onModelQueryChange:be,onNewModelChange:O,onAddModel:De,onTogglePin:qe,onCopyModelId:Be,onTestModel:we,onRemoveModel:He,disabledModelIds:ne,onToggleDisabled:ke}){const Y=n.noAuth===!0||!!w,xe=n.noAuth===!0;return e.jsx(ks,{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:xe?"Fetch the public model catalog without a connection":w?"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 Q(),children:h?"Importing…":xe?"Refresh":"Import"})}):null,i.length>0?e.jsx(Yt,{busy:N==="model",label:"Test all",disabled:!Y||S||N!==null&&N!=="model"||I.size>0&&N!=="model",onTest:()=>void U(),onStop:G}):null]})]}),e.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]",children:[e.jsx(re,{placeholder:"Search models…",value:C,onChange:se=>be(se.target.value),className:"min-w-0"}),e.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-2 sm:contents",children:[e.jsx(re,{placeholder:"model-id",value:v,disabled:D,onChange:se=>O(se.target.value),onKeyDown:se=>{se.key==="Enter"&&De()},className:"min-w-0"}),e.jsxs(E,{size:"sm",variant:"outline",disabled:D||!v.trim(),onClick:()=>void De(),className:"w-full sm:w-auto",children:[e.jsx(Sn,{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:C.trim()?"No models match your search.":d?"Upstream model catalog unavailable — add a slug above or retry.":n.isCustom||n.nodeType?"No models yet — click Import to fetch this provider’s catalog, or add a slug above.":"No models — add a slug above."}):e.jsx(pt.div,{layout:!0,className:"space-y-1",children:s.map(se=>{const R=se.id,oe=z[R],je=I.has(R),K=er(se.caps),M=N==="model"||je,le=A.includes(R),ge=ne.has(R);return e.jsx(pt.div,{layout:!0,transition:{layout:{type:"spring",stiffness:520,damping:36,mass:.4}},className:me("rounded-md border border-border bg-background px-2.5 py-2 hover:border-foreground/30",ge&&"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(R)?e.jsx("span",{className:"min-w-0 max-w-[45%] truncate text-xs font-medium",children:a.get(R)}):null,e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",children:R}),ge?e.jsx(Wn,{size:"sm",variant:"warning",children:"Disabled"}):null,je||oe?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[je?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${R}`,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,oe?e.jsx(ee,{label:oe.message||oe.label,children:e.jsx(ce,{tone:oe.ok?"ok":"err",className:"max-w-[9rem] truncate text-[10px] font-semibold",children:oe.label})}):null]}):null,K.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:K.map(te=>e.jsx(ee,{label:te.label,children:e.jsx(Wn,{size:"sm",variant:"outline","aria-label":te.label,className:"shrink-0",children:te.label})},te.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:le?"Unpin":"Pin to top",children:e.jsx("button",{type:"button","aria-label":le?"Unpin model":"Pin model to top",onClick:()=>qe(R),className:me("inline-flex h-7 w-7 items-center justify-center rounded-md border p-0 transition-colors duration-150",le?"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(Xn,{initial:!1,mode:"wait",children:e.jsx(pt.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:le?e.jsx(ki,{className:"h-3.5 w-3.5"}):e.jsx(ji,{className:"h-3.5 w-3.5"})},le?"pinned":"unpinned")})})}),e.jsx(ee,{label:J===R?"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 Be(R),children:J===R?e.jsx(Nn,{className:"h-3.5 w-3.5"}):e.jsx(Gn,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:ge?"Enable routing for model":"Disable routing for model",children:e.jsx("button",{type:"button","aria-label":ge?"Enable routing for model":"Disable routing for model","aria-pressed":ge,onClick:()=>void ke(R),className:me("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",ge&&"text-warning hover:text-warning"),children:ge?e.jsx(Ci,{className:"h-3.5 w-3.5"}):e.jsx(Ni,{className:"h-3.5 w-3.5"})})}),e.jsx("span",{className:"sm:hidden",children:e.jsx(Yt,{compact:!0,busy:M,disabled:!Y||S||N==="conn"||!je&&I.size>=4,onTest:()=>void we(R,xe?void 0:w),onStop:()=>N==="model"?G():V(R)})}),e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Yt,{busy:M,disabled:!Y||S||N==="conn"||!je&&I.size>=4,onTest:()=>void we(R,xe?void 0:w),onStop:()=>N==="model"?G():V(R)})}),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 He(R),children:e.jsx(kn,{className:"h-3.5 w-3.5"})})})]})]})},R)})})]})})})}const sr=["auto","low","medium","high","xhigh","max"],Vn=["auto","low","medium","high","max"],ir={openai:sr,claude:Vn,deepseek:["auto","low","high","max"],groq:["auto","low","medium","high"],openrouter:Vn,kimi:Vn,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"]},rr=["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"],us={"x-high":"xhigh",maximum:"max"};function Zn(n){const s=String(n||"").trim().toLowerCase();return s?s in us?us[s]:["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"].includes(s)?s:null:null}function ar(n){if(!Array.isArray(n==null?void 0:n.options))return[];const s=n.options.flatMap(u=>{const d=Zn(u);return d?[d]:[]}),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 or(n){return Array.isArray(n)?n.flatMap(s=>{const i=Zn(s);return i?[i]:[]}):[]}function lr(n,s,i){if((i==null?void 0:i.modelAware)===!1)return Jn(n,i);const a=s.map(d=>new Set(or(d))).filter(d=>d.size>0);return a.length?["auto",...rr.filter(d=>d!=="auto"&&d!=="none"&&a.some(h=>h.has(d)))]:n.startsWith("openai-compatible-")||n.startsWith("anthropic-compatible-")?null:Jn(n,i)}function Jn(n,s){if(n.startsWith("openai-compatible-")||n.startsWith("anthropic-compatible-"))return["auto","low","medium","high","max"];const i=ar(s);return i.length>0?i:ir[n]||null}function cr(n,s){const i=Jn(n,s),a=Zn(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 dr(n){return n==="auto"?"Auto":n==="xhigh"?"xHigh":n==="thinking"?"Thinking":n.charAt(0).toUpperCase()+n.slice(1)}function ur(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 mr({selected:n,connsAll:s,conns:i,strategy:a,strategyPending:u,stickyDraft:d,thinkingLevels:h,thinkingValue:w,thinkingPending:N,selectedKeys:S,connectionsCapped:I,totalConnections:C,batchKind:v,testingConnId:D,togglingConnId:z,connQuery:A,connListRef:J,connVirtualizer:Q,connResults:U,onStrategyChange:G,onStickyDraftChange:V,onSaveSticky:be,onThinkingChange:O,onRequestBulkDelete:De,onClearSelection:qe,onToggleSelection:Be,onSelectAll:we,onTestConnections:He,onTestConnection:ne,onStopTests:ke,onConnQueryChange:Y,onOpenAddConnection:xe,onMovePriority:se,onToggleConnection:R,onEditConnection:oe,onDeleteConnection:je}){return e.jsx(ks,{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(Nt,{size:"sm",className:"w-full min-w-0 sm:w-auto sm:min-w-[15rem] sm:flex-none",value:a,disabled:u,onChange:G,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"},{value:"cache-affine",label:"Cache-affine",mobileLabel:"Cache"}]})})]}),e.jsxs("div",{className:me("inline-flex items-center gap-1.5 sm:gap-1.5",a==="cache-affine"?"hidden":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(re,{id:"provider-sticky-limit",size:"sm",type:"number",min:1,value:d,disabled:u||a!=="round-robin",onChange:K=>V(K.target.value),className:"w-14 shrink-0"}),e.jsx(E,{size:"sm",variant:"outline",disabled:u||a!=="round-robin",onClick:be,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(Nt,{size:"compact",value:w,disabled:N,onChange:O,options:h.map(K=>({value:K,label:dr(K),compactLabel:K==="minimal"?"Min":K==="medium"?"Med":K==="thinking"?"Think":K==="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:S.size>0?e.jsxs(e.Fragment,{children:[e.jsxs(E,{size:"sm",variant:"destructive",onClick:De,children:[e.jsx(kn,{className:"h-3.5 w-3.5"}),"Delete selected"]}),e.jsx(E,{size:"sm",variant:"outline",onClick:qe,children:"Unselect"}),e.jsx(Yt,{busy:v==="conn"||i.some(K=>D===K.id),label:"Test selected",onTest:()=>void He([...S]),onStop:ke})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"outline",onClick:we,children:"Select all"}),e.jsx(Yt,{busy:v==="conn"||i.some(K=>D===K.id),label:"Test all",onTest:()=>void He(i.map(K=>K.id)),onStop:ke})]})}):null]}),I?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 ",C.toLocaleString()," connections. Use search to find accounts beyond this limit."]}):null,s.length>0?e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(vs,{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(re,{className:"h-8 pl-8 text-xs",placeholder:"Search name, id, key hint…",value:A,autoComplete:"off",autoCorrect:"off",autoCapitalize:"none",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true",onChange:K=>Y(K.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:xe,children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),An(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 "',A,'"']}):e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:e.jsx(fs,{overscrollContain:!0,scrollFade:!0,viewportRef:J,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:`${Q.getTotalSize()}px`},children:Q.getVirtualItems().map(K=>{const M=i[K.index];if(!M)return null;const le=K.index,ge=S.has(M.id),te=U[M.id],ze=D===M.id,de=M.isActive===!1,Ce=M.testStatus==="stale"||M.testStatus==="expired",Ae=M.healthStatus&&M.healthStatus!=="unknown"?M.healthStatus:M.testStatus==="active"?"healthy":M.testStatus==="error"?"error":null,_e=M.lastTested?ur(M.lastTested):null;return e.jsx("div",{"data-index":K.index,ref:Q.measureElement,className:"absolute left-0 top-0 w-full pb-1",style:{transform:`translateY(${K.start}px)`},children:e.jsx("div",{className:me("rounded-lg border bg-surface px-2 py-1.5 sm:p-3 transition-[border-color,background-color] duration-150 ease-out",ge?"border-foreground/40":de?"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(Li,{checked:ge,onCheckedChange:()=>{Be(M.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:le===0,onClick:()=>void se(M.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(Si,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:"Move down",children:e.jsx("button",{type:"button",disabled:le===i.length-1,onClick:()=>void se(M.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(Ai,{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:M.name||M.email||M.id.slice(0,8)}),ze?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${M.name||M.email||M.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,te&&!te.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:te.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:xt=>{xt.stopPropagation(),navigator.clipboard.writeText(te.message||"").catch(()=>{})},children:e.jsx(Gn,{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:["#",le+1]}),Ae?e.jsx(ee,{label:M.healthError||(Ae==="healthy"?"Connection is healthy":"Connection has an error"),children:e.jsx(ce,{tone:Ae==="healthy"?"ok":"err",className:"max-w-[10rem] truncate text-[10px]",children:Ae==="healthy"?"OK":"Error"})}):null,_e?e.jsxs("span",{children:["checked ",_e]}):null,Ce?e.jsx(ee,{label:M.lastError||"Credentials may be expired; reconnect this provider.",children:e.jsx(ce,{tone:"warn",className:"max-w-[10rem] truncate text-[10px]",children:"Stale"})}):null,de?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:"off"})]}):null]}),te||Ae||_e||Ce?e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 sm:hidden",children:[te?e.jsx(ee,{label:te.message||te.label,children:e.jsx(ce,{tone:te.ok?"ok":"err",className:"text-[10px] font-semibold",children:te.ok?"Success":te.label})}):Ae?e.jsx(ce,{tone:Ae==="healthy"?"ok":"err",className:"text-[10px] font-semibold",children:Ae==="healthy"?"Healthy":"Error"}):null,_e?e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["checked ",_e]}):null,Ce?e.jsx(ce,{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(Ei,{active:M.isActive!==!1,disabled:z===M.id,onToggle:()=>void R(M.id),activeLabel:"",inactiveLabel:""}),e.jsx(ee,{label:ze?"Stop":"Test",children:e.jsx(E,{size:"icon-sm",variant:"outline",className:"h-7 w-7 sm:hidden","aria-label":ze?"Stop test":"Test connection",onClick:()=>ze?ke():void ne(M.id),children:ze?e.jsx(Ti,{className:"h-3 w-3 fill-current"}):e.jsx(Mi,{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(Yt,{busy:ze,onTest:()=>void ne(M.id),onStop:ke})}),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:()=>oe(M),"aria-label":"Edit connection",children:[e.jsx(ys,{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:()=>je(M.id),"aria-label":"Delete connection",children:[e.jsx(kn,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})]})})},M.id)})})})})})]})})}function hr({selected:n,conns:s,activeConns:i,onEditCustom:a,onDeleteCustom:u,onAddConnection:d}){return e.jsxs(Cs,{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(Ss,{id:n.id,color:"var(--background)",size:24,fallbackIcon:ps(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}),n.id==="opencode"?e.jsxs(e.Fragment,{children:[e.jsx(ce,{tone:"ok",children:"Active"}),e.jsx(ce,{tone:"muted",children:"Built-in"})]}):e.jsxs(e.Fragment,{children:[s.length>0?e.jsx(ce,{tone:"ok",children:"Active"}):e.jsx(ce,{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(ys,{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(kn,{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:d,children:[e.jsx(Sn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:An(n.authType,n.noAuth)}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})})]})]})}function fr({deleteId:n,bulkDeleteIds:s,bulkDeleting:i,deleteProvider:a,connections:u,onCloseDelete:d,onDeleteConnection:h,onCloseBulkDelete:w,onDeleteSelectedConnections:N,onCloseProvider:S,onRemoveProvider:I}){const C=a?u.filter(v=>v.provider===a.id):[];return e.jsxs(e.Fragment,{children:[e.jsx(Vt,{open:!!n,onOpenChange:v=>!v&&d(),children:e.jsxs(Wt,{children:[e.jsxs(Ht,{children:[e.jsx(Jt,{children:"Delete connection?"}),e.jsx(bn,{children:"Removes this key / session."})]}),e.jsxs(Gt,{children:[e.jsx(E,{variant:"outline",onClick:d,children:"Cancel"}),e.jsx(E,{variant:"destructive",onClick:h,children:"Delete"})]})]})}),e.jsx(Vt,{open:!!s,onOpenChange:v=>{!v&&!i&&w()},children:e.jsxs(Wt,{children:[e.jsxs(Ht,{children:[e.jsxs(Jt,{children:["Delete ",(s==null?void 0:s.length)??0," selected connections?"]}),e.jsx(bn,{children:"This will remove the selected keys or sessions. This action cannot be undone."})]}),e.jsxs(Gt,{children:[e.jsx(E,{variant:"outline",disabled:i,onClick:w,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:i,onClick:N,children:i?"Deleting…":"Delete"})]})]})}),e.jsx(Vt,{open:!!a,onOpenChange:v=>{v||S()},children:e.jsxs(Wt,{children:[e.jsxs(Ht,{children:[e.jsxs(Jt,{children:["Remove ",a==null?void 0:a.name,"?"]}),e.jsx(bn,{children:C.length>0?e.jsxs(e.Fragment,{children:["This provider has ",e.jsxs("strong",{children:[C.length," connection(s)"]})," that will also be deleted:",e.jsx("ul",{className:"mt-2 list-disc pl-4 text-xs",children:C.map(v=>e.jsx("li",{children:v.name||v.id},v.id))})]}):"This will remove the provider from the list."})]}),e.jsxs(Gt,{children:[e.jsx(E,{variant:"outline",onClick:S,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:!a,onClick:()=>{a&&I(a)},children:"Remove"})]})]})})]})}async function es(n){const{data:s}=await St.get("/models/custom");return s.models??[]}async function pr(n,s){let i=0;for(const u of s)try{const d=typeof u=="string"?{id:u}:u,h=await As(n,d.id,d.name,d.capabilities);i+=h.added}catch{}const a=await es();return{added:i,total:a.length,models:a}}async function As(n,s,i,a){const{data:u}=await St.post("/models/custom",{providerAlias:n,id:s,name:i,capabilities:a}),d=await es();return{added:u.added===!0?1:0,total:d.length,models:d}}async function xr(n,s){const{data:i}=await St.delete("/models/custom",{params:{providerAlias:n,id:s}});return{success:i.success!==!1,removed:i.success!==!1}}async function gr(){const{data:n}=await St.get("/models/disabled");return n.disabled??{}}async function vr(n,s){await St.post("/models/disabled",{providerAlias:n,ids:s})}async function yr(n,s){await St.delete("/models/disabled",{params:{providerAlias:n,id:s}})}function br(n,s){return n!==s}const wr=50,ms=1e3;function yn(n){return n.id==="opencode"||(n.connected||0)>0}function zr(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,d=u.error??u.message??u.detail;if(typeof d=="string")i=d.trim();else if(d&&typeof d=="object"){const h=d;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 Qt(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 w=i.match(/\bHTTP\s+(\d{3})\b/i);if(w)u=w[1];else if(i.startsWith("status ")){const N=i.replace(/^status\s+/,"").match(/^(\d{3})/);N&&(u=N[1])}}}const d=u?`Error ${u}`:"Error";return{ok:!1,label:d,message:i||d,status:s,detail:n.detail&&n.detail!==i?n.detail:null}}function hs(n){var s,i;if($t.isAxiosError(n)){const a=n,u=((s=a.response)==null?void 0:s.status)??null,d=(i=a.response)==null?void 0:i.data;let h="";typeof(d==null?void 0:d.error)=="string"?h=d.error:d!=null&&d.error&&typeof d.error=="object"&&(h=d.error.message||d.error.type||d.error.code||"");const w=typeof(d==null?void 0:d.error)=="string"?d.error:"";h=(/^(?:test failed|internal server error)$/i.test(w)?d==null?void 0:d.message:w)||(d==null?void 0:d.message)||a.message||"Test failed";let S=null;try{d&&(S=JSON.stringify(d,null,2))}catch{S=null}return Qt({ok:!1,status:u,message:h,detail:S})}return Qt({ok:!1,message:Z(n,"Test failed")})}function _r(){var k,p,T,q,_;const n=Ts(),s="nr-selected-provider",[i,a]=o.useState(()=>{try{return localStorage.getItem(s)}catch{return null}});function u(t){if(br(i,t)){kt(null),$e([]),dt({}),Ze({}),ne(new Set),a(t);try{t?localStorage.setItem(s,t):localStorage.removeItem(s)}catch{}}}const[d,h]=o.useState(""),[w,N]=o.useState("all"),[S,I]=o.useState(()=>{try{const t=JSON.parse(localStorage.getItem("nr-hidden-providers")||"[]");return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}),[C,v]=o.useState(!1),[D,z]=o.useState(null),[A,J]=o.useState(null),[Q,U]=o.useState(null),[G,V]=o.useState(!1),[be,O]=o.useState(null),[De,qe]=o.useState(!1),[Be,we]=o.useState(null),[He,ne]=o.useState(new Set),[ke,Y]=o.useState(0),[xe,se]=o.useState({}),[R,oe]=o.useState(""),[je,K]=o.useState(!1),[M,le]=o.useState(!1),[ge,te]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-pinned-models")||"{}")}catch{return{}}}),[ze,de]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-hidden-models")||"{}")}catch{return{}}}),[Ce,Ae]=o.useState("");function _e(t,r){de(l=>{const y={...l,[t]:Array.from(new Set([...l[t]||[],r]))};try{localStorage.setItem("nr-hidden-models",JSON.stringify(y))}catch{}return y})}function xt(t,r){r.length&&de(l=>{const y=new Set(r.map(F=>F.trim()).filter(Boolean)),x=new Set([...y].map(F=>F.slice(F.lastIndexOf("/")+1))),b=(l[t]||[]).filter(F=>{const H=String(F),pe=H.slice(H.lastIndexOf("/")+1);return!y.has(H)&&!x.has(pe)}),j={...l};b.length?j[t]=b:delete j[t];try{localStorage.setItem("nr-hidden-models",JSON.stringify(j))}catch{}return j})}const[lt,At]=o.useState(0),[ve,Tt]=o.useState(""),[gt,Mt]=o.useState(null),[Xt,Pt]=o.useState(null),[Zt,vt]=o.useState(()=>new Set),[hn,Et]=o.useState(!1),ct=o.useRef(!1),Ue=o.useRef(new Map),Lt=4,[en,It]=o.useState(null),[Kt,yt]=o.useState(null),Je=o.useRef(null),[Tn,dt]=o.useState({}),[Mn,Ze]=o.useState({}),[ue,et]=o.useState("connections"),bt=o.useRef(null),ut=o.useRef(null),Rt=o.useRef(0),[Ee,Ot]=o.useState(""),[wt,tn]=o.useState(""),[Te,Ft]=o.useState(1),[nn,$e]=o.useState([]),[tt,kt]=o.useState(null);o.useEffect(()=>{const t=window.setTimeout(()=>{tn(Ee.trim())},250);return()=>window.clearTimeout(t)},[Ee]);const Qe=ft({queryKey:["connections",i,Te,wt],queryFn:()=>Zs({provider:i,page:Te,pageSize:wr,search:wt||void 0}),enabled:!!i,retry:!1,refetchInterval:3e4});o.useEffect(()=>{Ft(1),kt(null),$e([])},[i,wt]),o.useEffect(()=>{var r;const t=((r=Qe.data)==null?void 0:r.connections)??[];if(i){if(!t.length&&Te===1){$e([]),kt(i);return}$e(l=>{const y=Te===1?[]:l,x=new Set(y.map(g=>g.id));return[...y,...t.filter(g=>!x.has(g.id))].slice(0,ms)}),kt(i)}},[Qe.data,Te,i]);const mt=tt===i?nn:[],Le=(k=Qe.data)==null?void 0:k.pagination,Dt=!!(Le!=null&&Le.hasNext&&mt.length>=ms);o.useEffect(()=>{const t=ut.current;if(!t)return;const r=()=>{Rt.current=t.scrollTop};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[]),o.useLayoutEffect(()=>{const t=ut.current;t&&(t.scrollTop=Rt.current)},[i]),o.useEffect(()=>{const t=bt.current;if(!t||ue!=="connections")return;const r=()=>{var y;const l=(y=Qe.data)==null?void 0:y.pagination;!(l!=null&&l.hasNext)||Qe.isFetching||Dt||t.scrollTop+t.clientHeight>=t.scrollHeight-240&&Ft(x=>x+1)};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[Dt,(p=Qe.data)==null?void 0:p.pagination,Qe.isFetching,ue]);const qt=ft({queryKey:["providers-available"],queryFn:ei,retry:!1}),he=ft({queryKey:["settings"],queryFn:Rs,retry:!1}),sn=ft({queryKey:["nodes"],queryFn:ri,retry:!1}),Ge=ft({queryKey:["custom-models"],queryFn:()=>es(),enabled:!!i,staleTime:0,refetchOnMount:"always",retry:!1,placeholderData:t=>t}),Bt=ft({queryKey:["disabled-models"],queryFn:gr,retry:!1}),Ie=ft({queryKey:["available-models",lt],queryFn:async()=>((await St.get("/models")).data.models??[]).map(r=>({id:Cn(r.routedModel||r.fullModel,r.provider),name:r.name||r.model,provider_alias:r.provider,provider_id:r.provider,owned_by:r.provider,caps:Hn(r.caps),thinkingLevels:Array.isArray(r.thinkingLevels)?r.thinkingLevels:void 0})),retry:!1});function P(t,r="default"){r==="success"?Ct.success(t):r==="error"?Ct.error(t):r==="warning"?Ct.warning(t):Ct(t)}const ht=o.useMemo(()=>{const t=qt.data??[],r=new Set(t.map(x=>x.id)),l=sn.data??[],y=[];for(const x of l)r.has(x.id)||y.push({id:x.id,alias:x.prefix||x.id,name:x.name||x.prefix||x.id,authType:"apikey",isCustom:!0,baseUrl:x.baseUrl,nodeType:x.type,apiType:x.apiType,icon:"sway",connected:0});return[...t,...y]},[qt.data,sn.data]),W=he.data,nt=o.useMemo(()=>{const t=new Map;return i&&t.set(i,mt),t},[mt,i]),Me=o.useMemo(()=>{let t=[...ht];if(w==="active"?t=t.filter(yn):w==="idle"&&(t=t.filter(r=>!yn(r))),d.trim()){const r=d.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 y=S.includes(r.id)?1:0,x=S.includes(l.id)?1:0;if(y!==x)return y-x;const g=yn(r)?1:0,b=yn(l)?1:0;return g!==b?b-g:(r.name||r.id).localeCompare(l.name||l.id)}),t},[ht,nt,w,S,d]);function zt(t){I(r=>{const l=r.includes(t)?r.filter(y=>y!==t):[...r,t];try{localStorage.setItem("nr-hidden-providers",JSON.stringify(l))}catch{}return l})}o.useEffect(()=>{if(ht.length===0||i&&ht.some(r=>r.id===i))return;let t=null;try{t=localStorage.getItem(s)}catch{t=null}if(t&&ht.some(r=>r.id===t)){a(t);return}},[ht,nt,i]),o.useEffect(()=>{ne(new Set),Ot(""),oe(""),et("connections")},[i]),o.useEffect(()=>{const t=Is(W,i||"");Tt(String(t))},[i,W]);const c=Me.find(t=>t.id===i)||null;o.useEffect(()=>{c!=null&&c.noAuth&&et("models")},[i,c==null?void 0:c.noAuth]);const Ke=o.useMemo(()=>{const t=c?[...nt.get(c.id)||[]]:[];return t.sort((r,l)=>(r.priority??999)-(l.priority??999)||r.id.localeCompare(l.id)),t},[c,nt]),ae=Ke,Ne=Ms({count:ae.length,getScrollElement:()=>bt.current,estimateSize:()=>typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches?64:72,overscan:10,getItemKey:t=>{var r;return((r=ae[t])==null?void 0:r.id)??t},enabled:ue==="connections"});o.useLayoutEffect(()=>{if(ue!=="connections")return;let t=0;const r=requestAnimationFrame(()=>{Ne.measure(),t=requestAnimationFrame(()=>{Ne.measure()})});return()=>{cancelAnimationFrame(r),cancelAnimationFrame(t)}},[ue,ae.length,i,Ne]),o.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 639px)"),r=()=>{Ne.measure()};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[Ne]),o.useEffect(()=>{const t=bt.current;if(!t||typeof ResizeObserver>"u")return;const r=new ResizeObserver(()=>{Ne.measure()});return r.observe(t),()=>r.disconnect()},[Ne,ue,i]);const st=o.useMemo(()=>Ke.filter(t=>t.isActive!==!1),[Ke]),ye=[...He][0]||((T=st[0])==null?void 0:T.id)||((q=ae[0])==null?void 0:q.id),Re=$s(c),ie=Re&&!(c!=null&&c.isCustom)&&!(c!=null&&c.nodeType),Ve=ft({queryKey:["connection-models",c==null?void 0:c.id,ye,lt],queryFn:async()=>{const t=await rs(ye);return Qn(t.models,c==null?void 0:c.id)},enabled:!!(ie&&ye),retry:!1}),Se=c?Ks(W,c.id):"fill-first",Pn={"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"},Ye=o.useMemo(()=>{if(!c)return[];const t=[],r=c.id,l=new Set([r,c.alias||""].filter(Boolean).map(x=>x.toLowerCase())),y=[...Ge.data??[],...(xe[r]??[]).map(x=>({providerAlias:r,id:x.id,name:x.name,capabilities:x.caps,thinkingLevels:x.thinkingLevels}))];for(const x of y)l.has(x.providerAlias.toLowerCase())&&t.push({id:Cn(x.id,x.providerAlias),name:x.name||x.id,caps:Hn(x.capabilities),thinkingLevels:Array.isArray(x.thinkingLevels)?x.thinkingLevels:void 0});if(Re)t.push(...Ve.data??[]),!ye&&(r==="codebuddy-cn"||r==="codebuddy-intl"||r==="opencode"||r==="opencode-zen"||r==="opencode-go")&&t.push(...Qn(c.models,r));else{const x=new Set([r,c.alias||""].map(g=>g.trim().toLowerCase()).filter(Boolean));for(const g of Ie.data??[])[g.provider_alias,g.provider_id,g.owned_by].filter(j=>!!j).map(j=>j.trim().toLowerCase()).some(j=>x.has(j))&&t.push(g)}return tr(t,r)},[Ve.data,ke,Ge.data,xe,Ie.data,c,ye,Re]),fn=Re?Ge.isLoading||Ge.isFetching||Ve.isLoading||Ve.isFetching:Ge.isLoading||Ge.isFetching||Ie.isLoading||Ie.isFetching,En=Re&&!!Ve.error,fe=c?lr(c.id,Ye.map(t=>t.thinkingLevels),c.thinkingConfig):null,rn=c?(_=W==null?void 0:W.providerThinking)==null?void 0:_[c.id]:void 0,it=c?cr(c.id,c.thinkingConfig):"auto",Ln=c?rn&&(fe!=null&&fe.includes(rn))?rn:fe!=null&&fe.includes(it)?it:(fe==null?void 0:fe[0])||"auto":"auto",In=o.useMemo(()=>{const t=new Map(Object.entries(Pn));for(const r of Ye)r.name&&t.set(r.id,r.name);return t},[Ye]),_t=c?ge[c.id]||[]:[],pn=o.useMemo(()=>{const t=Ce.trim().toLowerCase(),r=new Set(c?ze[c.id]||[]:[]);let l=Ye.filter(b=>!r.has(b.id));if(t&&(l=l.filter(b=>b.id.toLowerCase().includes(t)||(b.name||"").toLowerCase().includes(t))),!_t.length)return[...l].sort((b,j)=>b.id.localeCompare(j.id));const y=new Set(_t),x=l.filter(b=>y.has(b.id)),g=l.filter(b=>!y.has(b.id)).sort((b,j)=>b.id.localeCompare(j.id));return[...x,...g]},[ze,Ye,Ce,_t,c]),$=o.useMemo(()=>{var r,l;if(!c)return new Set;const t=[...((r=Bt.data)==null?void 0:r[c.id])??[],...c.alias?((l=Bt.data)==null?void 0:l[c.alias])??[]:[]];return new Set(t)},[Bt.data,c]);async function Xe(t){if(c)try{$.has(t)?(await yr(c.id,t),P(`Enabled ${t.split("/").pop()}`)):(await vr(c.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 rt(t){c&&te(r=>{const l=r[c.id]||[],y=l.includes(t)?l.filter(g=>g!==t):[...l,t],x={...r,[c.id]:y};try{localStorage.setItem("nr-pinned-models",JSON.stringify(x))}catch{}return x})}function at(){var t;(t=Je.current)==null||t.abort();for(const r of Ue.current.values())r.abort();Ue.current.clear(),Je.current=null,ct.current=!1,Et(!1),Pt(null),vt(new Set),yt(null),P("Tests stopped")}function xn(t){const r=Ue.current.get(t);r&&(r.abort(),P("Model test stopped"))}async function an(t,r){Pt(t);try{const l=await gs(t,void 0,{signal:r}),y=l.valid===!0,x=l.testedAt||new Date().toISOString(),g={testStatus:y?"active":"error",lastTested:x,lastError:y?l.error||null:l.error||"Connection test failed",healthStatus:y?"healthy":"error",healthError:y?l.error||null:l.error||"Connection test failed",healthLatencyMs:l.latencyMs??0};return dt(b=>({...b,[t]:Qt({ok:y,message:l.error||(y?"Valid":"Failed"),latencyMs:l.latencyMs})})),$e(b=>b.map(j=>j.id===t?{...j,...g}:j)),n.setQueriesData({queryKey:["connections"]},b=>b&&{...b,connections:(b.connections||[]).map(j=>j.id===t?{...j,...g}:j)}),y}catch(l){if($t.isCancel(l)||(l==null?void 0:l.code)==="ERR_CANCELED")return!1;const y=hs(l),x=new Date().toISOString();return dt(g=>({...g,[t]:y})),$e(g=>g.map(b=>b.id===t?{...b,testStatus:"error",lastTested:x,lastError:y.message,healthStatus:"error",healthError:y.message,healthLatencyMs:0}:b)),!1}finally{Pt(l=>l===t?null:l)}}async function Kn(t){if(!t.length)return P("Nothing to test");const r=new AbortController;Je.current=r,yt("conn");let l=0;const y=4;for(let x=0;x<t.length&&!r.signal.aborted;x+=y){const g=t.slice(x,x+y),b=await Promise.all(g.map(j=>an(j,r.signal)));l+=b.filter(Boolean).length}r.signal.aborted||P(`Connections: ${l}/${t.length} passed`),yt(null)}async function on(t,r,l){const y=(c==null?void 0:c.noAuth)===!0;if(!r&&!y)return P("Add a connection first"),!1;if(!l){if(ct.current||Kt==="conn"||Ue.current.has(t))return!1;if(Ue.current.size>=Lt)return P(`Up to ${Lt} model tests can run at once`),!1}const x=l?null:new AbortController,g=l||x.signal;x&&Ue.current.set(t,x),vt(b=>{const j=new Set(b);return j.add(t),j});try{if(y){const pe=(c==null?void 0:c.alias)||(c==null?void 0:c.id)||"opencode",Pe=t.includes("/")?t:`${pe}/${t}`,Oe=await Qs(Pe,{signal:g}),ot=Oe.ok===!0;return Ze(jt=>({...jt,[t]:Qt({ok:ot,status:Oe.status,message:(Oe.error||"").trim()||(ot?"OK":"Failed"),latencyMs:Oe.latencyMs})})),ot}const b=await Vs(r,{model:t,signal:g});if(!Array.isArray(b.results)){const pe=b.message||b.error||"No model test results returned";return Ze(Pe=>({...Pe,[t]:Qt({ok:!1,message:pe})})),!1}const j=t.includes("/")?t.slice(t.lastIndexOf("/")+1):t,F=(b.results??[]).find(pe=>{const Pe=String(pe.modelId||"");return Pe===j||Pe===t||t.endsWith(`/${Pe}`)||Pe.endsWith(`/${j}`)}),H=!!(F!=null&&F.ok);return Ze(pe=>({...pe,[t]:Qt({ok:H,status:F==null?void 0:F.status,message:((F==null?void 0:F.error)||"").trim()||(H?"OK":"Failed"),latencyMs:F==null?void 0:F.latencyMs})})),H}catch(b){return $t.isCancel(b)||(b==null?void 0:b.code)==="ERR_CANCELED"||Ze(j=>({...j,[t]:hs(b)})),!1}finally{vt(b=>{const j=new Set(b);return j.delete(t),j}),x&&Ue.current.delete(t)}}async function Rn(){var t,r;if(c){if(c.id==="codebuddy-cn"||c.id==="codebuddy-intl"){P("CodeBuddy uses the static registry — add new models manually","default");return}le(!0);try{const l={provider:c.id},y=new Set([c.id,c.alias].filter(Boolean).map(B=>B.trim().toLowerCase())),x=(sn.data??[]).find(B=>B.id===c.id),g=(r=(t=Ke.find(B=>{var L;return y.has(String(B.provider||"").trim().toLowerCase())&&typeof((L=B.providerSpecificData)==null?void 0:L.baseUrl)=="string"}))==null?void 0:t.providerSpecificData)==null?void 0:r.baseUrl,b=c.baseUrl||c.modelsFetcherUrl||(x==null?void 0:x.baseUrl)||(typeof g=="string"?g:void 0);b&&(l.baseUrl=b);const j=B=>B.flatMap(L=>{if(!L||typeof L!="object")return[];const X=L,Fe=typeof X.id=="string"?X.id:typeof X.name=="string"?X.name:"";if(!Fe.trim())return[];const We=X.capabilities??X.caps;return[{id:Fe.trim(),...typeof X.name=="string"&&X.name.trim()?{name:X.name.trim()}:{},...We&&typeof We=="object"?{capabilities:We}:{}}]}),F=async()=>{const B=await rs(ye,!0),L=String(B.provider||"").trim().toLowerCase();if(L&&!y.has(L))throw new Error(`Model catalog returned ${B.provider}, expected ${c.name}`);return{ok:!0,success:!0,models:j(B.models??[])}};let H;if(ye)try{H=await F()}catch(B){if(!l.baseUrl||Re||c.id==="clinepass"||c.id==="cline-pass")throw B;H=await as(l)}else H=await as(l);if(!H.ok&&!H.success){P(H.message||H.error||"Import failed","error");return}const pe=H.models??[];if(!pe.length){P(H.message||"No models returned","warning");return}const Pe=pe.map(B=>typeof B=="string"?B:B.id);xt(c.id,Pe);const{added:Oe,models:ot}=await pr(c.id,pe),jt=ot.filter(B=>y.has(String(B.providerAlias||"").trim().toLowerCase())),Ut=jt.length;n.setQueryData(["custom-models"],ot),se(B=>({...B,[c.id]:Qn(jt,c.id)})),Y(B=>B+1),At(B=>B+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(Oe>0?`Imported ${Oe} new ${Oe===1?"model":"models"} · Total ${Ut} ${Ut===1?"Model":"Models"}`:`No new models · Total ${Ut} Models`,Oe>0?"success":"default")}catch(l){P(Z(l,"Import failed"),"error")}finally{le(!1)}}}async function On(){const t=R.trim();if(!(!c||!t||je)){K(!0);try{const r=await As(c.id,t);xt(c.id,[t]),n.setQueryData(["custom-models"],r.models),Y(l=>l+1),At(l=>l+1),await n.invalidateQueries({queryKey:["custom-models"]}),await n.invalidateQueries({queryKey:["available-models"]}),await n.invalidateQueries({queryKey:["sway-chat","models"]}),oe(""),Ct.success(`Added ${t}`)}catch(r){Ct.error(Z(r,"Failed to add model"))}finally{K(!1)}}}async function ln(){const t=(c==null?void 0:c.noAuth)===!0;if(!ye&&!t)return P("Add a connection first");if(ct.current)return;if(Ue.current.size>0)return P("Stop individual model tests before running Test all");const r=pn.map(g=>g.id);if(!r.length)return P("No models");ct.current=!0,Et(!0),yt("model");const l=new AbortController;Je.current=l;const y=new Array(r.length);let x=0;try{const g=Math.min(Lt,r.length),b=async()=>{for(;;){const j=x++;if(j>=r.length||l.signal.aborted)return;y[j]=await on(r[j],t?void 0:ye,l.signal)}};if(await Promise.all(Array.from({length:g},()=>b())),!l.signal.aborted){const j=y.filter(H=>H!==void 0).length,F=y.filter(Boolean).length;P(`Models: ${F}/${j} passed`)}}catch(g){!$t.isCancel(g)&&(g==null?void 0:g.code)!=="ERR_CANCELED"&&P(Z(g,"Model test failed"),"error")}finally{vt(new Set),yt(null),Je.current===l&&(Je.current=null),ct.current=!1,Et(!1)}}const cn=ts({mutationFn:async t=>{if(!c)return;const r=(W==null?void 0:W.providerStrategies)||{},l={...r[c.id]||{}};return t.strategy&&(l.fallbackStrategy=t.strategy),t.sticky&&(l.stickyRoundRobinLimit=t.sticky),ns({providerStrategies:{...r,[c.id]:l}})},onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]})}}),gn=ts({mutationFn:async t=>{if(c)return ns({providerThinking:{...(W==null?void 0:W.providerThinking)||{},[c.id]:t}})},onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]})}});async function Fn(t){const r=mt.find(l=>l.id===t);if(!(!r||en)){It(t);try{const l=await Ws(t,r.isActive!==!1);$e(y=>y.map(x=>x.id===l.id?{...x,...l}:x)),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{It(null)}}}async function Dn(t,r){const l=ae.findIndex(F=>F.id===t);if(l<0)return;const y=l+r;if(y<0||y>=ae.length)return;const x=ae[l],g=ae[y],b=x.priority??(l+1)*10,j=g.priority??(y+1)*10;await Promise.all([_n(x.id,{priority:j}),_n(g.id,{priority:b})]),n.invalidateQueries({queryKey:["connections"]})}async function qn(t){try{await Un(t),n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),J(null),P("Connection deleted","success")}catch(r){P(Z(r,"Failed to delete connection"),"error")}}async function Bn(){if(!(Q!=null&&Q.length)||G)return;const t=Q;V(!0);const r=[];try{for(const y of t)try{await Un(y)}catch{r.push(y)}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]});const l=t.length-r.length;l===t.length?(ne(new Set),U(null),P(`${l} connection${l===1?"":"s"} deleted`,"success")):l>0?(ne(new Set(r)),U(null),P(`Deleted ${l} of ${t.length} connections`,"warning")):P("Could not delete the selected connections","error")}finally{V(!1)}}async function zn(t){var y,x,g,b,j,F,H,pe,Pe,Oe,ot,jt,Ut,B;if(!c)return;if(t.alreadySaved){n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),v(!1),P("Connection added");return}const r=t.proxyPoolId&&t.proxyPoolId!=="pool_none"?t.proxyPoolId:null;if((y=t.codeBuddyTokens)!=null&&y.length){if(c.id!=="codebuddy-cn"&&c.id!=="codebuddy-intl")throw new Error("Token batches are only supported for CodeBuddy");let L=0,X=0;for(const Fe of t.codeBuddyTokens)try{await dn({provider:c.id,credentialToken:Fe.credentialToken,accessToken:Fe.accessToken,refreshToken:Fe.refreshToken,name:Fe.name,autoName:Fe.autoName,proxyPoolId:null}),L+=1}catch(We){if($t.isAxiosError(We)&&((x=We.response)==null?void 0:x.status)===409){X+=1;continue}throw We}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),v(!1),P(X>0?`Added ${L} connections, skipped ${X} duplicates`:`Added ${L} connections`,X>0?"warning":"success");return}if((g=t.bulkKeys)!=null&&g.length){let L=0,X=0;for(const Fe of t.bulkKeys)try{await dn({provider:c.id,apiKey:Fe.apiKey,name:Fe.name,autoName:Fe.autoName,proxyPoolId:r}),L+=1}catch(We){if($t.isAxiosError(We)&&((b=We.response)==null?void 0:b.status)===409){X+=1;continue}throw We}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),v(!1),P(X>0?`Added ${L} connections, skipped ${X} duplicates`:`Added ${L} connections`,X>0?"warning":"success");return}const l=t.authFlow??wn(c.id,c.authType,c.noAuth);if(c.id==="kiro"&&t.kiroAuthMode==="api-key"){if(!((j=t.apiKey)!=null&&j.trim()))throw new Error("API key required");const L=await Hs({apiKey:t.apiKey.trim(),region:t.kiroRegion,name:t.name,autoName:t.autoName});if(!L.success)throw new Error(L.error||"Kiro API key validation failed")}else if(c.id==="kiro"&&t.kiroAuthMode==="import-token"){if(!((F=t.kiroRefreshToken)!=null&&F.trim()))throw new Error("Refresh token required");const L=await Js({refreshToken:t.kiroRefreshToken.trim(),clientId:((H=t.kiroClientId)==null?void 0:H.trim())||void 0,clientSecret:((pe=t.kiroClientSecret)==null?void 0:pe.trim())||void 0,region:t.kiroRegion,profileArn:((Pe=t.kiroProfileArn)==null?void 0:Pe.trim())||void 0,name:t.name,autoName:t.autoName});if(!L.success)throw new Error(L.error||"Kiro token import failed")}else if(c.id==="kiro"&&t.kiroAuthMode==="cli-proxy"){if(!((Oe=t.kiroCliProxyJson)!=null&&Oe.trim()))throw new Error("CLIProxyAPI JSON required");let L;try{L=JSON.parse(t.kiroCliProxyJson)}catch{throw new Error("CLIProxyAPI JSON is invalid")}if(!L||typeof L!="object"||Array.isArray(L))throw new Error("CLIProxyAPI JSON must be an object");const X=await Gs({cliProxyAuth:L,name:t.name,autoName:t.autoName});if(!X.success)throw new Error(X.error||"CLIProxyAPI import failed")}else if(l==="import"&&(c.id==="codebuddy-cn"||c.id==="codebuddy-intl")){if(!((ot=t.codeBuddyToken)!=null&&ot.trim()))throw new Error("An access token or refresh token is required.");await dn({provider:c.id,credentialToken:t.codeBuddyToken.trim(),name:t.name,autoName:t.autoName,proxyPoolId:null})}else if(l==="import"){if(!((jt=t.importToken)!=null&&jt.trim()))throw new Error("Access token required");const L=await Ys(c.id,{accessToken:t.importToken.trim(),displayName:t.name,machineId:t.machineId});if(!L.success)throw new Error(L.error||"Token import failed")}else if(l==="oauth"){if(!((Ut=t.oauthCode)!=null&&Ut.trim()))throw new Error("Paste the OAuth code from the browser callback");await Xs(c.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 L=await xs(c.id,{deviceCode:t.deviceCode,codeVerifier:t.deviceCodeVerifier,displayName:t.name});if(L.pending)throw new Error("Still waiting for device authorization — keep polling");if(!L.success)throw new Error(L.error||"Device authorization failed")}else if(l==="local")await dn({provider:c.id,name:t.name,autoName:t.autoName,proxyPoolId:r});else{if(!((B=t.apiKey)!=null&&B.trim()))throw new Error("API key required");await dn({provider:c.id,apiKey:t.apiKey,name:t.name,autoName:t.autoName,proxyPoolId:r})}n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),v(!1),P("Connection added")}function vn(t){const r=Ke.filter(l=>l.provider===t.id);(async()=>{for(const l of r)try{await Un(l.id)}catch{}ii(t.id).then(()=>{n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),n.invalidateQueries({queryKey:["connections"]}),P("Provider removed")})})(),O(null)}const m=qt.isLoading,f=c?c.isCustom?"apikey":wn(c.id,c.authType,c.noAuth):null;return e.jsxs("div",{className:me("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(Ps,{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:()=>qe(!0),children:[e.jsx(Sn,{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(Yi,{byProvider:nt,filter:w,hiddenProviders:S,loading:m,query:d,providerListRef:ut,selectedId:i,sorted:Me,onFilterChange:N,onQueryChange:h,onSelectProvider:u,onToggleProviderHidden:zt}),e.jsx(js,{className:"flex min-h-[32rem] min-w-0 flex-none flex-col overflow-hidden lg:min-h-0 lg:flex-1",children:c?e.jsxs(e.Fragment,{children:[e.jsx(hr,{selected:c,conns:ae,activeConns:st,onEditCustom:()=>we(c),onDeleteCustom:()=>O(c),onAddConnection:()=>v(!0)}),e.jsx(Ns,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsxs(bs,{value:c.noAuth?"models":ue,onValueChange:et,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(ws,{children:[c.noAuth?null:e.jsx(jn,{value:"connections",children:"Connection"}),e.jsx(jn,{value:"models",children:"Models"})]})}),c.noAuth?null:e.jsx(mr,{selected:c,connsAll:Ke,conns:ae,strategy:Se,strategyPending:cn.isPending,stickyDraft:ve,thinkingLevels:fe,thinkingValue:Ln,thinkingPending:gn.isPending,selectedKeys:He,connectionsCapped:Dt,totalConnections:(Le==null?void 0:Le.totalItems)??Ke.length,batchKind:Kt,testingConnId:Xt,togglingConnId:en,connQuery:Ee,connListRef:bt,connVirtualizer:Ne,connResults:Tn,onStrategyChange:t=>cn.mutate({strategy:t}),onStickyDraftChange:Tt,onSaveSticky:()=>{const t=Math.max(1,parseInt(ve,10)||1);cn.mutate({sticky:t}),Tt(String(t))},onThinkingChange:t=>gn.mutate(t),onRequestBulkDelete:()=>U([...He]),onClearSelection:()=>ne(new Set),onToggleSelection:t=>{ne(r=>{const l=new Set(r);return l.has(t)?l.delete(t):l.add(t),l})},onSelectAll:()=>ne(new Set(ae.map(t=>t.id))),onTestConnections:t=>Kn(t),onTestConnection:t=>{an(t)},onStopTests:at,onConnQueryChange:Ot,onOpenAddConnection:()=>v(!0),onMovePriority:(t,r)=>Dn(t,r),onToggleConnection:t=>Fn(t),onEditConnection:z,onDeleteConnection:J}),e.jsx(nr,{selected:c,visibleModels:pn,models:Ye,modelNames:In,modelsLoading:fn,modelsUnavailable:En,importingModels:M,testConnId:ye,batchKind:Kt,modelTestLock:hn,testingModels:Zt,modelQuery:Ce,newModel:R,addingModel:je,modelResults:Mn,pinnedFor:_t,copied:gt,onImportModels:()=>void Rn(),onTestAllModels:()=>void ln(),onStopTests:at,onStopModel:xn,onModelQueryChange:Ae,onNewModelChange:oe,onAddModel:()=>void On(),onTogglePin:rt,onCopyModelId:async t=>{await navigator.clipboard.writeText(t),Mt(t),window.setTimeout(()=>Mt(null),1e3)},onTestModel:(t,r)=>void on(t,r),onRemoveModel:async t=>{let r=!1;try{const l=await xr(c.id,t);r=(l==null?void 0:l.removed)===!0}catch{}finally{_e(c.id,t),Y(l=>l+1),At(l=>l+1),n.invalidateQueries({queryKey:["sway-chat","models"]})}Ct(`${r?"Removed":"Hidden"} ${t.split("/").pop()}`)},disabledModelIds:$,onToggleDisabled:Xe})]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground",children:"Select a provider"})})]}),e.jsx(Ji,{open:C,provider:c,flow:f,onOpenChange:v,onSubmit:async t=>{try{await zn(t)}catch(r){throw P(Z(r,"Add failed"),"error"),r}}}),e.jsx(Gi,{conn:D,onOpenChange:t=>!t&&z(null),onSave:async(t,r)=>{D&&(await _n(D.id,{name:t,...r.trim()?{apiKey:r.trim()}:{}}),n.invalidateQueries({queryKey:["connections"]}),z(null),P("Updated"))}}),e.jsx(fr,{deleteId:A,bulkDeleteIds:Q,bulkDeleting:G,deleteProvider:be,connections:Ke,onCloseDelete:()=>J(null),onDeleteConnection:()=>A?qn(A):void 0,onCloseBulkDelete:()=>U(null),onDeleteSelectedConnections:Bn,onCloseProvider:()=>O(null),onRemoveProvider:vn}),e.jsx(cs,{open:De,onOpenChange:qe,onCreate:async t=>{const r=await ni(t);n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),qe(!1),u(r.id),P("Custom provider created")}}),e.jsx(cs,{open:!!Be,onOpenChange:t=>{t||we(null)},initial:Be,submitLabel:"Save",onCreate:async t=>{if(!Be)return;const r=await si(Be.id,t);n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),n.invalidateQueries({queryKey:["connections"]}),we(null),u(r.id),P("Custom provider updated")}})]})}export{zr as compactErrorReason,_r 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-oO6QoOCj.js";import{b as v,c as t,p as b}from"./index-B7c_Oeni.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-DjeUJuR7.js";import{F as ls}from"./flip-button-CDurxfqc.js";import{R as d}from"./ripple-button-BrLlmKvT.js";import{S as D}from"./StatusBadge-iBeqU7Qd.js";import{C as xe}from"./checkbox-ClXwjb6M.js";import{I as v,e as I,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-CkR38iPY.js";import{F as is,c as cs}from"./frame-CY26iHQE.js";import{S as Me}from"./segmented-CxobJihW.js";import{S as ds}from"./skeleton-81lPHspy.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as A}from"./table-CEyzPvr7.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-5xk7DmbO.js";import{i as vs,A as bs}from"./connections-api-DlH7CVMr.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(I,{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(I,{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(I,{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(I,{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 Ae(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 Ie(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(I,{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 Ie(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ae(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(A,{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(A,{className:"max-w-[24rem] truncate bg-transparent px-3 py-2 font-mono text-xs text-muted-foreground",children:e.jsx(I,{label:s.proxyUrl||"—",children:e.jsx("span",{className:"block truncate",children:s.proxyUrl||"—"})})}),e.jsx(A,{className:"bg-transparent px-3 py-2 text-xs uppercase text-muted-foreground",children:s.type||"http"}),e.jsx(A,{className:"bg-transparent px-3 py-2 text-xs text-muted-foreground",children:s.boundConnectionCount??0}),e.jsx(A,{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(A,{className:"bg-transparent px-4 py-2",children:e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ie(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ae(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-bX_7xlVV.js";import{F as ls}from"./flip-button-D37ibV3U.js";import{R as d}from"./ripple-button-Bi2qoFsd.js";import{S as D}from"./StatusBadge-DwoF6JKt.js";import{C as xe}from"./checkbox-Bp15fhqx.js";import{I as v,e as I,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-B7c_Oeni.js";import{F as is,c as cs}from"./frame-C_Vz9WkQ.js";import{S as Me}from"./segmented-JQkY0jOQ.js";import{S as ds}from"./skeleton-CUHI70xv.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as A}from"./table-BMmCRvDh.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-LcymBrBl.js";import{i as vs,A as bs}from"./connections-api-eXKpSjaP.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(I,{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(I,{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(I,{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(I,{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 Ae(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 Ie(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(I,{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 Ie(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ae(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(A,{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(A,{className:"max-w-[24rem] truncate bg-transparent px-3 py-2 font-mono text-xs text-muted-foreground",children:e.jsx(I,{label:s.proxyUrl||"—",children:e.jsx("span",{className:"block truncate",children:s.proxyUrl||"—"})})}),e.jsx(A,{className:"bg-transparent px-3 py-2 text-xs uppercase text-muted-foreground",children:s.type||"http"}),e.jsx(A,{className:"bg-transparent px-3 py-2 text-xs text-muted-foreground",children:s.boundConnectionCount??0}),e.jsx(A,{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(A,{className:"bg-transparent px-4 py-2",children:e.jsx(Ve,{pool:s,testing:we===s.id,onToggle:()=>void Ie(s),onTest:()=>void qe(s.id),onManage:()=>Ee(s),onEdit:()=>Ae(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 +1 @@
|
|
|
1
|
-
import{r as v,j as t,L as ce}from"./react-vendor-xnYrwzsL.js";import{u as ue,a as me,e as V}from"./query-vendor-DVevaSVS.js";import{g as G,c as C,P as xe,Q as he,C as fe,p as M,e as T,t as L,w as pe,R as ge,b as ve,h as be}from"./index-CkR38iPY.js";import{H as je}from"./Header-DjeUJuR7.js";import{R as B}from"./ripple-button-BrLlmKvT.js";import{S as y}from"./StatusBadge-iBeqU7Qd.js";import{F as Q,a as D,c as F,d as Y}from"./frame-CY26iHQE.js";import{S as N}from"./skeleton-81lPHspy.js";import{A as Ne,C as we}from"./connections-api-DlH7CVMr.js";import{p as X}from"./live-mode-CHShLY4E.js";import{aa as U,i as Z,ay as ye}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const Ce=new Set(["codebuddy-cn","codebuddy-intl"]);function Ee(e,s){if(!Array.isArray(s)||s.length===0)return"no-quota";const n=s.filter(a=>a.unlimited!==!0&&Number.isFinite(a.remaining));if(n.length===0)return"ok";const l=e.trim().toLowerCase(),o=Ce.has(l)?Math.max(...n.map(a=>a.remaining)):Math.min(...n.map(a=>a.remaining));return o<=0?"limit-reached":o<30?"low-quota":"ok"}const Re=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"]),ke=25,$=200,Pe=6,q=3,_=6e4,k=[];let O=0;function J(){var e;for(;O<Pe&&k.length>0;){const s=k.shift();if(!s)return;if((e=s.signal)!=null&&e.aborted){s.cleanup(),s.reject(s.signal.reason??new DOMException("Quota request aborted","AbortError"));continue}O+=1,s.started=!0,s.run().then(s.resolve).catch(s.reject).finally(()=>{s.cleanup(),O-=1,J()})}}function Ae(e,s){return new Promise((n,l)=>{if(s!=null&&s.aborted){l(s.reason??new DOMException("Quota request aborted","AbortError"));return}const o={run:async()=>e(),resolve:n,reject:l,signal:s,started:!1,cleanup:()=>{}},a=()=>{if(o.started)return;const m=k.indexOf(o);m!==-1&&(k.splice(m,1),o.cleanup(),l((s==null?void 0:s.reason)??new DOMException("Quota request aborted","AbortError")))};s==null||s.addEventListener("abort",a,{once:!0}),o.cleanup=()=>s==null?void 0:s.removeEventListener("abort",a),k.push(o),J()})}const z=["expired","authentication","unauthorized","401","re-authorize"];function Me(e){if(!e)return!1;const s=e.toLowerCase();return z.some(n=>s.includes(n))}function Qe(e){var n,l;if(fe.isAxiosError(e)){if(((n=e.response)==null?void 0:n.status)===401)return!0;const o=(l=e.response)==null?void 0:l.data,a=(o==null?void 0:o.error)||(o==null?void 0:o.message)||"";if(z.some(m=>a.toLowerCase().includes(m)))return!0}const s=e instanceof Error?e.message:"";return z.some(o=>s.toLowerCase().includes(o))}function Fe(e,s){return!s||s<=0?0:!e||e<0?100:e>=s?0:Math.round((s-e)/s*100)}function Ie(e,s){const n=s==null?void 0:s.quotas;if(!n||typeof n!="object")return[];const l=e.toLowerCase();return Object.entries(n).flatMap(([o,a])=>{const m=Number.isFinite(Number(a.used))?Number(a.used):0,c=Number.isFinite(Number(a.total))?Number(a.total):0,x=l==="codex"&&a.remaining!==void 0?Math.max(0,Math.round(Number(a.remaining))):a.remainingPercentage!==void 0?Math.max(0,Math.round(Number(a.remainingPercentage))):Fe(m,c);return l==="qoder"&&o==="organization"&&c<=0?[]:[{name:l==="antigravity"?a.displayName||o:l==="qoder"?o==="user"?"Personal":o==="organization"?"Organization":o:o,used:m,total:c,remaining:x,resetAt:a.resetAt??null,recurring:a.recurring!==!1,unlimited:a.unlimited===!0||c<=0,unit:a.unit}]})}function Se(e){if(!e)return null;const s=new Date(e).getTime()-Date.now();if(!Number.isFinite(s)||s<=0)return null;const n=Math.ceil(s/6e4);if(n<60)return`${n}m`;const l=Math.floor(n/60);return l<24?`${l}h ${n%60}m`:`${Math.floor(l/24)}d ${l%24}h ${n%60}m`}function j(e){return Number.isFinite(e)?Math.round(e).toLocaleString("id-ID"):"0"}function Le(e){return e>70?{text:"text-success",bg:"bg-success",bgLight:"bg-success/10"}:e>=30?{text:"text-warning",bg:"bg-warning",bgLight:"bg-warning/10"}:{text:"text-destructive",bg:"bg-destructive",bgLight:"bg-destructive/10"}}function $e(e){if(e.loading)return null;if(e.authExpired)return t.jsx(y,{tone:"warn",children:"Auth expired"});if(e.error)return t.jsx(y,{tone:"err",children:"Error"});if(e.conn.isActive===!1)return t.jsx(y,{tone:"muted",children:"Disabled"});const s=Ee(e.conn.provider,e.quotas);return s==="no-quota"?t.jsx(y,{tone:"muted",children:"No quota"}):s==="limit-reached"?t.jsx(y,{tone:"err",children:"Limit reached"}):s==="low-quota"?t.jsx(y,{tone:"warn",children:"Low quota"}):t.jsx(y,{tone:"ok",children:"OK"})}function ee({provider:e}){const s=pe(e),n=ge(e),l=ve(e);return t.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg",style:{backgroundColor:`${n}1f`,color:n},children:l?t.jsx("span",{"aria-hidden":"true",className:"block h-4 w-4 shrink-0",style:{backgroundColor:n,WebkitMaskImage:`url(${l})`,maskImage:`url(${l})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}}):t.jsx(s,{className:"h-4 w-4"})})}function Je(){const e=ue(),[s,n]=v.useState(null),[l,o]=v.useState({}),[,a]=v.useState(0);v.useEffect(()=>{const r=window.setInterval(()=>{a(i=>i+1)},6e4);return()=>window.clearInterval(r)},[]);const m=me({queryKey:["quota-provider-counts"],queryFn:we,enabled:X(),retry:!1,refetchInterval:_,refetchIntervalInBackground:!1}),c=v.useMemo(()=>(m.data??[]).map(r=>({...r,provider:String(r.provider||"").trim()})).filter(r=>Re.has(r.provider)&&r.total>0),[m.data]);v.useEffect(()=>{o(r=>{const i={};for(const u of c)i[u.provider]=Math.max(1,r[u.provider]??1);return i})},[c]);const x=v.useMemo(()=>c.flatMap(r=>{const i=l[r.provider]??1;return Array.from({length:i},(u,d)=>({provider:r.provider,page:d+1}))}),[c,l]),f=V({queries:x.map(r=>({queryKey:["quota-connections",r.provider,r.page],queryFn:()=>Ne({provider:r.provider,page:r.page,pageSize:ke}),enabled:X(),retry:!1,staleTime:3e4,refetchInterval:_,refetchIntervalInBackground:!1}))}),E=v.useMemo(()=>{const r=new Map;return x.forEach((i,u)=>{var b,h;const d=((h=(b=f[u])==null?void 0:b.data)==null?void 0:h.connections)??[],p=r.get(i.provider)??[],P=new Set(p.map(w=>w.id));r.set(i.provider,[...p,...d.filter(w=>!P.has(w.id))])}),r},[f,x]),te=v.useMemo(()=>{var i,u,d;const r=new Map;for(const p of c){const b=x.map((g,de)=>g.provider===p.provider?de:-1).filter(g=>g>=0).map(g=>f[g]),h=b[b.length-1],w=(i=h==null?void 0:h.data)==null?void 0:i.pagination,A=((u=E.get(p.provider))==null?void 0:u.length)??0,W=A>=$&&A<p.total;r.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)||A<p.total),capped:W,loaded:A})}return r},[f,E,x,c]),I=v.useMemo(()=>c.flatMap(r=>E.get(r.provider)??[]),[E,c]),S=V({queries:I.map(r=>({queryKey:["quota-usage",r.id],queryFn:({signal:i})=>Ae(()=>he(r.id,i),i),enabled:!!r.id,retry:!1,staleTime:3e4,refetchInterval:_,refetchIntervalInBackground:!1}))}),re=v.useMemo(()=>{const r=new Map;return I.forEach((i,u)=>{var b;const d=S[u];let p;if(!d||d.isPending)p={conn:i,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:i,loading:!1,fetching:d.isFetching,error:h,authExpired:Qe(d.error),usage:null,quotas:[],message:h,resetCredits:0,plan:null}}else{const h=d.data??{};p={conn:i,loading:!1,fetching:d.isFetching,error:null,authExpired:Me(h.message),usage:h,quotas:Ie(i.provider,h),message:h.message??null,resetCredits:((b=h.resetCredits)==null?void 0:b.availableCount)??0,plan:h.plan??null}}const P=r.get(i.provider)??[];r.set(i.provider,[...P,p])}),r},[I,S]);function R(r,i="default"){i==="success"?L.success(r):i==="error"?L.error(r):L(r)}async function se(){await Promise.all([e.invalidateQueries({queryKey:["quota-provider-counts"]}),e.invalidateQueries({queryKey:["quota-connections"]}),e.invalidateQueries({queryKey:["quota-usage"]})]),R("Refreshed","success")}function ne(r,i){Promise.all([e.invalidateQueries({queryKey:["quota-connections",r]}),...i.map(u=>e.invalidateQueries({queryKey:["quota-usage",u.conn.id]}))])}function oe(r){e.invalidateQueries({queryKey:["quota-usage",r]})}function ie(r){var u;if((((u=E.get(r))==null?void 0:u.length)??0)>=$){R(`Quota view is limited to ${j($)} accounts per provider`);return}o(d=>({...d,[r]:(d[r]??1)+1}))}async function ae(r){if(!s){n(r.id);try{const i=await xe(r.id);i.reset===!1||i.code==="no_credit"?R(i.message||"No Codex reset credits available","error"):R("Codex quota reset","success"),await e.invalidateQueries({queryKey:["quota-usage",r.id]})}catch(i){R(G(i,"Reset failed"),"error")}finally{n(null)}}}const K=m.isLoading,le=!K&&c.length===0,H=m.isFetching||f.some(r=>r==null?void 0:r.isFetching)||S.some(r=>r==null?void 0:r.isFetching);return t.jsxs("div",{className:"min-w-0 max-w-full space-y-4 overflow-x-hidden",children:[t.jsx(je,{title:"Quota",actions:t.jsxs(B,{size:"sm",variant:"outline",disabled:H,onClick:()=>void se(),children:[t.jsx(U,{className:C("h-3.5 w-3.5",H&&"animate-spin")}),"Refresh"]})}),m.isError?t.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?t.jsx("div",{className:"space-y-4",children:["provider-skeleton-a","provider-skeleton-b"].map(r=>t.jsxs(Q,{children:[t.jsxs(D,{className:"flex flex-row items-center gap-3 p-4",children:[t.jsx(N,{className:"h-9 w-9 rounded-lg"}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(N,{className:"h-4 w-28"}),t.jsx(N,{className:"h-3 w-44"})]})]}),t.jsx(F,{className:"grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((i,u)=>t.jsx(N,{className:"h-48 w-full rounded-xl"},u))})]},r))}):le?t.jsx(Q,{children:t.jsxs(F,{className:"p-10 text-center",children:[t.jsx("p",{className:"text-sm font-medium",children:"No providers connected"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Connect an OAuth provider to track API quota limits and usage."})]})}):t.jsx("div",{className:"space-y-4",children:c.map(r=>{const i=re.get(r.provider)??[],u=te.get(r.provider)??{loading:!0,fetching:!1,error:!1,hasNext:!1,capped:!1,loaded:0};return t.jsx(qe,{group:r,cards:i,pageState:u,onRefreshProvider:()=>ne(r.provider,i),onRefreshCard:oe,onLoadMore:()=>ie(r.provider),onResetCodex:ae,resettingId:s},r.provider)})})]})}function qe({group:e,cards:s,pageState:n,onRefreshProvider:l,onRefreshCard:o,onLoadMore:a,onResetCodex:m,resettingId:c}){return t.jsxs(Q,{className:"min-w-0 max-w-full overflow-hidden",children:[t.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[t.jsx(ee,{provider:e.provider}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{className:"truncate text-sm font-semibold",children:M(e.provider)}),t.jsx("p",{className:"text-[11px] text-muted-foreground",children:n.loaded>0?`${n.loaded} of ${j(e.total)} accounts loaded`:`${j(e.total)} accounts`})]})]}),t.jsx(T,{label:`Refresh ${M(e.provider)} quota`,children:t.jsx("button",{type:"button",onClick:l,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 ${M(e.provider)} quota`,children:t.jsx(U,{className:C("h-3.5 w-3.5",n.fetching&&"animate-spin")})})})]}),t.jsxs(F,{className:"min-w-0 p-3",children:[n.error?t.jsxs("div",{className:"mb-3 rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["Some ",M(e.provider)," accounts could not be loaded. Refresh this section to retry."]}):null,n.loading&&s.length===0?t.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((x,f)=>t.jsx(N,{className:"h-48 w-full rounded-xl"},f))}):s.length>0?t.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:s.map(x=>t.jsx(_e,{card:x,onRefresh:()=>o(x.conn.id),onResetCodex:()=>m(x.conn),resetting:c===x.conn.id},x.conn.id))}):t.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No accounts available for this provider."})]}),n.hasNext||n.capped?t.jsxs(Y,{className:"flex items-center justify-between gap-3 border-t border-border p-3",children:[t.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:n.capped?`Showing ${j(n.loaded)} of ${j(e.total)} accounts. Quota loading is capped for performance.`:`Showing ${j(n.loaded)} of ${j(e.total)} accounts`}),n.hasNext?t.jsxs(B,{size:"sm",variant:"outline",onClick:a,disabled:n.fetching,children:[t.jsx(Z,{className:"h-3.5 w-3.5"}),n.fetching?"Loading…":"Load more"]}):null]}):null]})}function _e({card:e,onRefresh:s,onResetCodex:n,resetting:l}){const{conn:o}=e,[a,m]=v.useState(!1),c=e.authExpired?"Re-authorize the connection first":e.resetCredits<=0?"No Codex reset credits available":"Spend one Codex reset credit to reset the quota window",x=a?e.quotas:e.quotas.slice(0,q);return t.jsxs(Q,{className:"flex min-w-0 flex-col overflow-hidden",children:[t.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx(ee,{provider:o.provider}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("h3",{className:"truncate text-sm font-medium leading-tight",children:o.name||o.email||o.provider}),t.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:o.email&&o.name?o.email:`Connection ID · ${o.id}`})]})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[$e(e),t.jsx(T,{label:"Refresh quota",children:t.jsx("button",{type:"button",onClick:s,disabled:e.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":e.fetching?"Refreshing quota":"Refresh quota",children:t.jsx(U,{className:C("h-3.5 w-3.5",e.fetching&&"animate-spin")})})})]})]}),t.jsxs(F,{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-3 p-4",children:[e.plan?t.jsx(be,{variant:"outline",className:"w-fit text-[10px]",children:e.plan}):null,t.jsx("div",{className:"min-h-[3.5rem] flex-1",children:e.loading?t.jsxs("div",{className:"space-y-2",children:[t.jsx(N,{className:"h-4 w-full"}),t.jsx(N,{className:"h-1.5 w-full"}),t.jsx(N,{className:"h-3 w-2/3"})]}):e.authExpired?t.jsxs("div",{className:"rounded-lg border border-warning/25 bg-warning/10 px-3 py-2",children:[t.jsx("p",{className:"text-xs font-medium text-warning",children:"Authentication expired"}),t.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:e.message||e.error}),t.jsx(ce,{to:"/dashboard/provider",className:"mt-1.5 inline-block text-[11px] font-medium text-warning underline underline-offset-2",children:"Re-authorize in Providers"})]}):e.error?t.jsxs("div",{className:"rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2",children:[t.jsx("p",{className:"text-xs font-medium text-destructive",children:"Failed to load quota"}),t.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:e.error})]}):e.quotas.length>0?t.jsxs("div",{className:"space-y-3",children:[e.message?t.jsx("p",{className:"text-[11px] text-muted-foreground",children:e.message}):null,x.map(f=>t.jsx(Oe,{quota:f},`${f.name}-${f.unit??""}`)),e.quotas.length>q?t.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:[t.jsx(Z,{className:C("h-3 w-3 transition-transform",a&&"rotate-180")}),a?"Show less":`Show ${e.quotas.length-q} more`]}):null]}):e.message?t.jsx("div",{className:"rounded-lg border border-border bg-surface px-3 py-2 text-[11px] text-muted-foreground",children:e.message}):t.jsx("div",{className:"py-6 text-center text-[11px] text-muted-foreground",children:"No quota data available"})})]}),o.provider==="codex"?t.jsxs(Y,{className:"flex items-center justify-between gap-2 border-t border-border p-4",children:[t.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[e.resetCredits," reset credit",e.resetCredits===1?"":"s"]}),t.jsx(T,{label:c,children:t.jsxs(B,{size:"sm",variant:"outline",onClick:n,disabled:e.resetCredits<=0||e.authExpired||l||e.loading,children:[t.jsx(ye,{className:"h-3.5 w-3.5"}),l?"Resetting…":"Reset quota"]})})]}):null]})}function Oe({quota:e}){const s=Le(e.remaining),n=Se(e.resetAt),l=e.recurring?"Reset":"Expires";return t.jsxs("div",{className:"min-w-0 space-y-1.5 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"min-w-0 truncate text-xs font-medium",children:e.name}),t.jsxs("span",{className:C("shrink-0 text-xs font-medium tabular-nums",s.text),children:[e.remaining,"%"]})]}),e.unlimited?t.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Unlimited"}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:C("h-1.5 overflow-hidden rounded-full",s.bgLight),children:t.jsx("div",{className:C("h-full rounded-full transition-all duration-300",s.bg),style:{width:`${Math.min(e.remaining,100)}%`}})}),t.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] text-muted-foreground",children:[t.jsxs("span",{className:"tabular-nums",children:[j(e.used)," / ",e.total>0?j(e.total):"∞"]}),n?t.jsxs("span",{className:"tabular-nums",children:[l," in ",n]}):null]})]})]})}export{Je as default};
|
|
1
|
+
import{r as v,j as t,L as ce}from"./react-vendor-xnYrwzsL.js";import{u as ue,a as me,e as V}from"./query-vendor-DVevaSVS.js";import{g as G,c as C,P as xe,Q as he,C as fe,p as M,e as T,t as L,w as pe,R as ge,b as ve,h as be}from"./index-B7c_Oeni.js";import{H as je}from"./Header-bX_7xlVV.js";import{R as B}from"./ripple-button-Bi2qoFsd.js";import{S as y}from"./StatusBadge-DwoF6JKt.js";import{F as Q,a as D,c as F,d as Y}from"./frame-C_Vz9WkQ.js";import{S as N}from"./skeleton-CUHI70xv.js";import{A as Ne,C as we}from"./connections-api-eXKpSjaP.js";import{p as X}from"./live-mode-CHShLY4E.js";import{aa as U,i as Z,ay as ye}from"./icons-vendor-CUx7SB5V.js";import"./ui-vendor-BuM9f2NY.js";import"./motion-vendor-g5fpGzmJ.js";const Ce=new Set(["codebuddy-cn","codebuddy-intl"]);function Ee(e,s){if(!Array.isArray(s)||s.length===0)return"no-quota";const n=s.filter(a=>a.unlimited!==!0&&Number.isFinite(a.remaining));if(n.length===0)return"ok";const l=e.trim().toLowerCase(),o=Ce.has(l)?Math.max(...n.map(a=>a.remaining)):Math.min(...n.map(a=>a.remaining));return o<=0?"limit-reached":o<30?"low-quota":"ok"}const Re=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"]),ke=25,$=200,Pe=6,q=3,_=6e4,k=[];let O=0;function J(){var e;for(;O<Pe&&k.length>0;){const s=k.shift();if(!s)return;if((e=s.signal)!=null&&e.aborted){s.cleanup(),s.reject(s.signal.reason??new DOMException("Quota request aborted","AbortError"));continue}O+=1,s.started=!0,s.run().then(s.resolve).catch(s.reject).finally(()=>{s.cleanup(),O-=1,J()})}}function Ae(e,s){return new Promise((n,l)=>{if(s!=null&&s.aborted){l(s.reason??new DOMException("Quota request aborted","AbortError"));return}const o={run:async()=>e(),resolve:n,reject:l,signal:s,started:!1,cleanup:()=>{}},a=()=>{if(o.started)return;const m=k.indexOf(o);m!==-1&&(k.splice(m,1),o.cleanup(),l((s==null?void 0:s.reason)??new DOMException("Quota request aborted","AbortError")))};s==null||s.addEventListener("abort",a,{once:!0}),o.cleanup=()=>s==null?void 0:s.removeEventListener("abort",a),k.push(o),J()})}const z=["expired","authentication","unauthorized","401","re-authorize"];function Me(e){if(!e)return!1;const s=e.toLowerCase();return z.some(n=>s.includes(n))}function Qe(e){var n,l;if(fe.isAxiosError(e)){if(((n=e.response)==null?void 0:n.status)===401)return!0;const o=(l=e.response)==null?void 0:l.data,a=(o==null?void 0:o.error)||(o==null?void 0:o.message)||"";if(z.some(m=>a.toLowerCase().includes(m)))return!0}const s=e instanceof Error?e.message:"";return z.some(o=>s.toLowerCase().includes(o))}function Fe(e,s){return!s||s<=0?0:!e||e<0?100:e>=s?0:Math.round((s-e)/s*100)}function Ie(e,s){const n=s==null?void 0:s.quotas;if(!n||typeof n!="object")return[];const l=e.toLowerCase();return Object.entries(n).flatMap(([o,a])=>{const m=Number.isFinite(Number(a.used))?Number(a.used):0,c=Number.isFinite(Number(a.total))?Number(a.total):0,x=l==="codex"&&a.remaining!==void 0?Math.max(0,Math.round(Number(a.remaining))):a.remainingPercentage!==void 0?Math.max(0,Math.round(Number(a.remainingPercentage))):Fe(m,c);return l==="qoder"&&o==="organization"&&c<=0?[]:[{name:l==="antigravity"?a.displayName||o:l==="qoder"?o==="user"?"Personal":o==="organization"?"Organization":o:o,used:m,total:c,remaining:x,resetAt:a.resetAt??null,recurring:a.recurring!==!1,unlimited:a.unlimited===!0||c<=0,unit:a.unit}]})}function Se(e){if(!e)return null;const s=new Date(e).getTime()-Date.now();if(!Number.isFinite(s)||s<=0)return null;const n=Math.ceil(s/6e4);if(n<60)return`${n}m`;const l=Math.floor(n/60);return l<24?`${l}h ${n%60}m`:`${Math.floor(l/24)}d ${l%24}h ${n%60}m`}function j(e){return Number.isFinite(e)?Math.round(e).toLocaleString("id-ID"):"0"}function Le(e){return e>70?{text:"text-success",bg:"bg-success",bgLight:"bg-success/10"}:e>=30?{text:"text-warning",bg:"bg-warning",bgLight:"bg-warning/10"}:{text:"text-destructive",bg:"bg-destructive",bgLight:"bg-destructive/10"}}function $e(e){if(e.loading)return null;if(e.authExpired)return t.jsx(y,{tone:"warn",children:"Auth expired"});if(e.error)return t.jsx(y,{tone:"err",children:"Error"});if(e.conn.isActive===!1)return t.jsx(y,{tone:"muted",children:"Disabled"});const s=Ee(e.conn.provider,e.quotas);return s==="no-quota"?t.jsx(y,{tone:"muted",children:"No quota"}):s==="limit-reached"?t.jsx(y,{tone:"err",children:"Limit reached"}):s==="low-quota"?t.jsx(y,{tone:"warn",children:"Low quota"}):t.jsx(y,{tone:"ok",children:"OK"})}function ee({provider:e}){const s=pe(e),n=ge(e),l=ve(e);return t.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-lg",style:{backgroundColor:`${n}1f`,color:n},children:l?t.jsx("span",{"aria-hidden":"true",className:"block h-4 w-4 shrink-0",style:{backgroundColor:n,WebkitMaskImage:`url(${l})`,maskImage:`url(${l})`,WebkitMaskPosition:"center",maskPosition:"center",WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"contain",maskSize:"contain"}}):t.jsx(s,{className:"h-4 w-4"})})}function Je(){const e=ue(),[s,n]=v.useState(null),[l,o]=v.useState({}),[,a]=v.useState(0);v.useEffect(()=>{const r=window.setInterval(()=>{a(i=>i+1)},6e4);return()=>window.clearInterval(r)},[]);const m=me({queryKey:["quota-provider-counts"],queryFn:we,enabled:X(),retry:!1,refetchInterval:_,refetchIntervalInBackground:!1}),c=v.useMemo(()=>(m.data??[]).map(r=>({...r,provider:String(r.provider||"").trim()})).filter(r=>Re.has(r.provider)&&r.total>0),[m.data]);v.useEffect(()=>{o(r=>{const i={};for(const u of c)i[u.provider]=Math.max(1,r[u.provider]??1);return i})},[c]);const x=v.useMemo(()=>c.flatMap(r=>{const i=l[r.provider]??1;return Array.from({length:i},(u,d)=>({provider:r.provider,page:d+1}))}),[c,l]),f=V({queries:x.map(r=>({queryKey:["quota-connections",r.provider,r.page],queryFn:()=>Ne({provider:r.provider,page:r.page,pageSize:ke}),enabled:X(),retry:!1,staleTime:3e4,refetchInterval:_,refetchIntervalInBackground:!1}))}),E=v.useMemo(()=>{const r=new Map;return x.forEach((i,u)=>{var b,h;const d=((h=(b=f[u])==null?void 0:b.data)==null?void 0:h.connections)??[],p=r.get(i.provider)??[],P=new Set(p.map(w=>w.id));r.set(i.provider,[...p,...d.filter(w=>!P.has(w.id))])}),r},[f,x]),te=v.useMemo(()=>{var i,u,d;const r=new Map;for(const p of c){const b=x.map((g,de)=>g.provider===p.provider?de:-1).filter(g=>g>=0).map(g=>f[g]),h=b[b.length-1],w=(i=h==null?void 0:h.data)==null?void 0:i.pagination,A=((u=E.get(p.provider))==null?void 0:u.length)??0,W=A>=$&&A<p.total;r.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)||A<p.total),capped:W,loaded:A})}return r},[f,E,x,c]),I=v.useMemo(()=>c.flatMap(r=>E.get(r.provider)??[]),[E,c]),S=V({queries:I.map(r=>({queryKey:["quota-usage",r.id],queryFn:({signal:i})=>Ae(()=>he(r.id,i),i),enabled:!!r.id,retry:!1,staleTime:3e4,refetchInterval:_,refetchIntervalInBackground:!1}))}),re=v.useMemo(()=>{const r=new Map;return I.forEach((i,u)=>{var b;const d=S[u];let p;if(!d||d.isPending)p={conn:i,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:i,loading:!1,fetching:d.isFetching,error:h,authExpired:Qe(d.error),usage:null,quotas:[],message:h,resetCredits:0,plan:null}}else{const h=d.data??{};p={conn:i,loading:!1,fetching:d.isFetching,error:null,authExpired:Me(h.message),usage:h,quotas:Ie(i.provider,h),message:h.message??null,resetCredits:((b=h.resetCredits)==null?void 0:b.availableCount)??0,plan:h.plan??null}}const P=r.get(i.provider)??[];r.set(i.provider,[...P,p])}),r},[I,S]);function R(r,i="default"){i==="success"?L.success(r):i==="error"?L.error(r):L(r)}async function se(){await Promise.all([e.invalidateQueries({queryKey:["quota-provider-counts"]}),e.invalidateQueries({queryKey:["quota-connections"]}),e.invalidateQueries({queryKey:["quota-usage"]})]),R("Refreshed","success")}function ne(r,i){Promise.all([e.invalidateQueries({queryKey:["quota-connections",r]}),...i.map(u=>e.invalidateQueries({queryKey:["quota-usage",u.conn.id]}))])}function oe(r){e.invalidateQueries({queryKey:["quota-usage",r]})}function ie(r){var u;if((((u=E.get(r))==null?void 0:u.length)??0)>=$){R(`Quota view is limited to ${j($)} accounts per provider`);return}o(d=>({...d,[r]:(d[r]??1)+1}))}async function ae(r){if(!s){n(r.id);try{const i=await xe(r.id);i.reset===!1||i.code==="no_credit"?R(i.message||"No Codex reset credits available","error"):R("Codex quota reset","success"),await e.invalidateQueries({queryKey:["quota-usage",r.id]})}catch(i){R(G(i,"Reset failed"),"error")}finally{n(null)}}}const K=m.isLoading,le=!K&&c.length===0,H=m.isFetching||f.some(r=>r==null?void 0:r.isFetching)||S.some(r=>r==null?void 0:r.isFetching);return t.jsxs("div",{className:"min-w-0 max-w-full space-y-4 overflow-x-hidden",children:[t.jsx(je,{title:"Quota",actions:t.jsxs(B,{size:"sm",variant:"outline",disabled:H,onClick:()=>void se(),children:[t.jsx(U,{className:C("h-3.5 w-3.5",H&&"animate-spin")}),"Refresh"]})}),m.isError?t.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?t.jsx("div",{className:"space-y-4",children:["provider-skeleton-a","provider-skeleton-b"].map(r=>t.jsxs(Q,{children:[t.jsxs(D,{className:"flex flex-row items-center gap-3 p-4",children:[t.jsx(N,{className:"h-9 w-9 rounded-lg"}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(N,{className:"h-4 w-28"}),t.jsx(N,{className:"h-3 w-44"})]})]}),t.jsx(F,{className:"grid gap-3 p-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((i,u)=>t.jsx(N,{className:"h-48 w-full rounded-xl"},u))})]},r))}):le?t.jsx(Q,{children:t.jsxs(F,{className:"p-10 text-center",children:[t.jsx("p",{className:"text-sm font-medium",children:"No providers connected"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Connect an OAuth provider to track API quota limits and usage."})]})}):t.jsx("div",{className:"space-y-4",children:c.map(r=>{const i=re.get(r.provider)??[],u=te.get(r.provider)??{loading:!0,fetching:!1,error:!1,hasNext:!1,capped:!1,loaded:0};return t.jsx(qe,{group:r,cards:i,pageState:u,onRefreshProvider:()=>ne(r.provider,i),onRefreshCard:oe,onLoadMore:()=>ie(r.provider),onResetCodex:ae,resettingId:s},r.provider)})})]})}function qe({group:e,cards:s,pageState:n,onRefreshProvider:l,onRefreshCard:o,onLoadMore:a,onResetCodex:m,resettingId:c}){return t.jsxs(Q,{className:"min-w-0 max-w-full overflow-hidden",children:[t.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[t.jsx(ee,{provider:e.provider}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{className:"truncate text-sm font-semibold",children:M(e.provider)}),t.jsx("p",{className:"text-[11px] text-muted-foreground",children:n.loaded>0?`${n.loaded} of ${j(e.total)} accounts loaded`:`${j(e.total)} accounts`})]})]}),t.jsx(T,{label:`Refresh ${M(e.provider)} quota`,children:t.jsx("button",{type:"button",onClick:l,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 ${M(e.provider)} quota`,children:t.jsx(U,{className:C("h-3.5 w-3.5",n.fetching&&"animate-spin")})})})]}),t.jsxs(F,{className:"min-w-0 p-3",children:[n.error?t.jsxs("div",{className:"mb-3 rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2 text-[11px] text-destructive",children:["Some ",M(e.provider)," accounts could not be loaded. Refresh this section to retry."]}):null,n.loading&&s.length===0?t.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Array.from({length:3}).map((x,f)=>t.jsx(N,{className:"h-48 w-full rounded-xl"},f))}):s.length>0?t.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:s.map(x=>t.jsx(_e,{card:x,onRefresh:()=>o(x.conn.id),onResetCodex:()=>m(x.conn),resetting:c===x.conn.id},x.conn.id))}):t.jsx("div",{className:"py-8 text-center text-[11px] text-muted-foreground",children:"No accounts available for this provider."})]}),n.hasNext||n.capped?t.jsxs(Y,{className:"flex items-center justify-between gap-3 border-t border-border p-3",children:[t.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:n.capped?`Showing ${j(n.loaded)} of ${j(e.total)} accounts. Quota loading is capped for performance.`:`Showing ${j(n.loaded)} of ${j(e.total)} accounts`}),n.hasNext?t.jsxs(B,{size:"sm",variant:"outline",onClick:a,disabled:n.fetching,children:[t.jsx(Z,{className:"h-3.5 w-3.5"}),n.fetching?"Loading…":"Load more"]}):null]}):null]})}function _e({card:e,onRefresh:s,onResetCodex:n,resetting:l}){const{conn:o}=e,[a,m]=v.useState(!1),c=e.authExpired?"Re-authorize the connection first":e.resetCredits<=0?"No Codex reset credits available":"Spend one Codex reset credit to reset the quota window",x=a?e.quotas:e.quotas.slice(0,q);return t.jsxs(Q,{className:"flex min-w-0 flex-col overflow-hidden",children:[t.jsxs(D,{className:"flex flex-row items-start justify-between gap-3 p-4",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx(ee,{provider:o.provider}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("h3",{className:"truncate text-sm font-medium leading-tight",children:o.name||o.email||o.provider}),t.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:o.email&&o.name?o.email:`Connection ID · ${o.id}`})]})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[$e(e),t.jsx(T,{label:"Refresh quota",children:t.jsx("button",{type:"button",onClick:s,disabled:e.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":e.fetching?"Refreshing quota":"Refresh quota",children:t.jsx(U,{className:C("h-3.5 w-3.5",e.fetching&&"animate-spin")})})})]})]}),t.jsxs(F,{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-3 p-4",children:[e.plan?t.jsx(be,{variant:"outline",className:"w-fit text-[10px]",children:e.plan}):null,t.jsx("div",{className:"min-h-[3.5rem] flex-1",children:e.loading?t.jsxs("div",{className:"space-y-2",children:[t.jsx(N,{className:"h-4 w-full"}),t.jsx(N,{className:"h-1.5 w-full"}),t.jsx(N,{className:"h-3 w-2/3"})]}):e.authExpired?t.jsxs("div",{className:"rounded-lg border border-warning/25 bg-warning/10 px-3 py-2",children:[t.jsx("p",{className:"text-xs font-medium text-warning",children:"Authentication expired"}),t.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:e.message||e.error}),t.jsx(ce,{to:"/dashboard/provider",className:"mt-1.5 inline-block text-[11px] font-medium text-warning underline underline-offset-2",children:"Re-authorize in Providers"})]}):e.error?t.jsxs("div",{className:"rounded-lg border border-destructive/25 bg-destructive/10 px-3 py-2",children:[t.jsx("p",{className:"text-xs font-medium text-destructive",children:"Failed to load quota"}),t.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:e.error})]}):e.quotas.length>0?t.jsxs("div",{className:"space-y-3",children:[e.message?t.jsx("p",{className:"text-[11px] text-muted-foreground",children:e.message}):null,x.map(f=>t.jsx(Oe,{quota:f},`${f.name}-${f.unit??""}`)),e.quotas.length>q?t.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:[t.jsx(Z,{className:C("h-3 w-3 transition-transform",a&&"rotate-180")}),a?"Show less":`Show ${e.quotas.length-q} more`]}):null]}):e.message?t.jsx("div",{className:"rounded-lg border border-border bg-surface px-3 py-2 text-[11px] text-muted-foreground",children:e.message}):t.jsx("div",{className:"py-6 text-center text-[11px] text-muted-foreground",children:"No quota data available"})})]}),o.provider==="codex"?t.jsxs(Y,{className:"flex items-center justify-between gap-2 border-t border-border p-4",children:[t.jsxs("span",{className:"text-[11px] tabular-nums text-muted-foreground",children:[e.resetCredits," reset credit",e.resetCredits===1?"":"s"]}),t.jsx(T,{label:c,children:t.jsxs(B,{size:"sm",variant:"outline",onClick:n,disabled:e.resetCredits<=0||e.authExpired||l||e.loading,children:[t.jsx(ye,{className:"h-3.5 w-3.5"}),l?"Resetting…":"Reset quota"]})})]}):null]})}function Oe({quota:e}){const s=Le(e.remaining),n=Se(e.resetAt),l=e.recurring?"Reset":"Expires";return t.jsxs("div",{className:"min-w-0 space-y-1.5 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"min-w-0 truncate text-xs font-medium",children:e.name}),t.jsxs("span",{className:C("shrink-0 text-xs font-medium tabular-nums",s.text),children:[e.remaining,"%"]})]}),e.unlimited?t.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Unlimited"}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:C("h-1.5 overflow-hidden rounded-full",s.bgLight),children:t.jsx("div",{className:C("h-full rounded-full transition-all duration-300",s.bg),style:{width:`${Math.min(e.remaining,100)}%`}})}),t.jsxs("div",{className:"flex items-center justify-between gap-2 text-[10px] text-muted-foreground",children:[t.jsxs("span",{className:"tabular-nums",children:[j(e.used)," / ",e.total>0?j(e.total):"∞"]}),n?t.jsxs("span",{className:"tabular-nums",children:[l," in ",n]}):null]})]})]})}export{Je as default};
|