swayrouter 1.0.6 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dashboard/dist/assets/{CliTools-BpJv-d-C.js → CliTools-aPWuAaGl.js} +1 -1
  2. package/dashboard/dist/assets/{Combo-Omt4WwQh.js → Combo-BLv2ftiC.js} +1 -1
  3. package/dashboard/dist/assets/{ConsoleLog-eVXIhvj0.js → ConsoleLog-XQc0AJjY.js} +1 -1
  4. package/dashboard/dist/assets/{Dashboard-7rUT480n.js → Dashboard-DTZuAXn6.js} +1 -1
  5. package/dashboard/dist/assets/{Header-COXbvTw8.js → Header-BZEBRuoI.js} +1 -1
  6. package/dashboard/dist/assets/{Keys-DWDtxoHL.js → Keys-DoBcUcd1.js} +1 -1
  7. package/dashboard/dist/assets/{Login-BCcXjBao.js → Login-CLA9YPSW.js} +1 -1
  8. package/dashboard/dist/assets/{ManageApiKey-B2FDMilq.js → ManageApiKey-C6AcZdXV.js} +1 -1
  9. package/dashboard/dist/assets/{OAuthCallback-D6xN9_9Z.js → OAuthCallback-CngALmEQ.js} +1 -1
  10. package/dashboard/dist/assets/Provider-gBLoiXWc.js +4 -0
  11. package/dashboard/dist/assets/{ProviderModelAccordion-B4oZRage.js → ProviderModelAccordion-BiCN7K3L.js} +1 -1
  12. package/dashboard/dist/assets/{Proxy-CR_8zOSx.js → Proxy-WdkDbR59.js} +1 -1
  13. package/dashboard/dist/assets/QuotaMonitor-DJnvSQmA.js +1 -0
  14. package/dashboard/dist/assets/{Settings-B_Ivibo0.js → Settings-BqVAj_Z6.js} +1 -1
  15. package/dashboard/dist/assets/{Setup-BIhKefDY.js → Setup-YEZfhKZl.js} +1 -1
  16. package/dashboard/dist/assets/{StatusBadge-i3hGtYCs.js → StatusBadge-CbCgRp1u.js} +1 -1
  17. package/dashboard/dist/assets/{SwayChat-Dr3z_nQj.js → SwayChat-BNkpBa01.js} +1 -1
  18. package/dashboard/dist/assets/{Usage-Cjflh0xL.js → Usage-BtG4T3yX.js} +1 -1
  19. package/dashboard/dist/assets/{accordion-BvVNpO_s.js → accordion-I9hJ3zKn.js} +1 -1
  20. package/dashboard/dist/assets/{admin-extras-api-Cf9et7QD.js → admin-extras-api-CZx9UMQG.js} +1 -1
  21. package/dashboard/dist/assets/{api-keys-api-BAD0B-CB.js → api-keys-api-CoNfm8AZ.js} +1 -1
  22. package/dashboard/dist/assets/{card-CgV3Jkvj.js → card-3Ad838s5.js} +1 -1
  23. package/dashboard/dist/assets/{checkbox-BIZ6J6ao.js → checkbox-MVYpQird.js} +1 -1
  24. package/dashboard/dist/assets/{connections-api-_WoB_gUT.js → connections-api-BReJMHgi.js} +1 -1
  25. package/dashboard/dist/assets/{copy-button-DUrnwcg6.js → copy-button-D9SzZokt.js} +1 -1
  26. package/dashboard/dist/assets/{currency-api-BOt2thYE.js → currency-api-B0hvChGg.js} +1 -1
  27. package/dashboard/dist/assets/{flip-button-C5wry3x-.js → flip-button-yX_RgEC4.js} +1 -1
  28. package/dashboard/dist/assets/{frame-DWGa-WbO.js → frame-R55qLb-9.js} +1 -1
  29. package/dashboard/dist/assets/index-DNuEpqPT.css +1 -0
  30. package/dashboard/dist/assets/{index-C4u3c95A.js → index-Dne9pkEF.js} +2 -2
  31. package/dashboard/dist/assets/{ripple-button-XW6jAEYr.js → ripple-button-BNF8KOIB.js} +1 -1
  32. package/dashboard/dist/assets/{segmented-DUYkOckC.js → segmented-W2XJE85e.js} +1 -1
  33. package/dashboard/dist/assets/{select-C-N9x_xI.js → select-BnilqBos.js} +1 -1
  34. package/dashboard/dist/assets/{skeleton-dOHAk9tt.js → skeleton-CuG5ZRYw.js} +1 -1
  35. package/dashboard/dist/assets/{table-B45T_8mH.js → table-CmYFkpYA.js} +1 -1
  36. package/dashboard/dist/assets/{tabs-DZe4IlCc.js → tabs-j6meB_LR.js} +1 -1
  37. package/dashboard/dist/assets/{tunnel-api-DcYrG4Vr.js → tunnel-api-6Weym8SK.js} +1 -1
  38. package/dashboard/dist/index.html +2 -2
  39. package/package.json +1 -1
  40. package/src/config/errorConfig.js +21 -0
  41. package/src/providers/registry/codebuddy-cn.js +31 -35
  42. package/src/providers/registry/codebuddy-intl.js +22 -27
  43. package/src/routes/api/providers/route.js +1 -0
  44. package/src/services/accountFallback.js +14 -1
  45. package/src/services/combo.js +9 -5
  46. package/src/sse/services/auth.js +14 -9
  47. package/dashboard/dist/assets/Provider-ORHY6wyc.js +0 -4
  48. package/dashboard/dist/assets/QuotaMonitor-qmONCANG.js +0 -1
  49. package/dashboard/dist/assets/index-CN-Y5gO6.css +0 -1
@@ -0,0 +1,4 @@
1
+ import{j as e,r as o}from"./react-vendor-xnYrwzsL.js";import{u as As,a as ht,d as Ts,b as es}from"./query-vendor-DVevaSVS.js";import{H as Ms}from"./Header-BZEBRuoI.js";import{R as E}from"./ripple-button-BNF8KOIB.js";import{I as ie,T as cn,c as me,D as Wt,m as Ht,n as Jt,o as Gt,q as Yt,g as Z,v as jn,s as kn,b as Ps,e as ee,S as hs,w as fs,h as Vn,x as Es,y as At,z as Ls,A as Is,t as Nt,C as Qt,a as ts,E as Ks}from"./index-Dne9pkEF.js";import{g as Rs,s as Os,a as Fs,r as Ds,b as ns,c as qs,p as Bs,d as ps,t as ss,e as zs,f as _s,h as xs,u as Us,i as zn,j as $s,k as Qs,l as is,m as rs,n as Vs,o as _n,q as ln,v as Ws,w as Hs,x as Js,y as Gs,z as Ys,A as Xs,B as Zs}from"./connections-api-BReJMHgi.js";import{a as ei,c as ti,u as ni,d as si,l as ii}from"./admin-extras-api-CZx9UMQG.js";import{b as ri,d as ai,v as as,e as oi,f as li,a as ci,h as os,i as di}from"./oauth-callback-CqYQzyd7.js";import{S as le}from"./StatusBadge-CbCgRp1u.js";import{S as ui,a as mi,b as hi,c as fi}from"./select-BnilqBos.js";import{S as St}from"./segmented-W2XJE85e.js";import{ag as An,ad as Jn,L as dn,X as Gn,q as gs,ah as pi,ai as xi,aj as gi,ak as vi,a8 as yi,a9 as bi,ac as Tn,al as wi,am as ki,an as ji,ao as Ci,af as Cn,A as Ni,ab as Si,ap as Ai,aq as Ti,h as vs}from"./icons-vendor-CUx7SB5V.js";import{A as Yn,m as ft}from"./motion-vendor-g5fpGzmJ.js";import{T as ys,a as bs,b as Nn,c as ws}from"./tabs-j6meB_LR.js";import{F as ks,a as js,c as Cs}from"./frame-R55qLb-9.js";import{S as Mi}from"./skeleton-CuG5ZRYw.js";import{F as Pi}from"./flip-button-yX_RgEC4.js";import{C as Ei}from"./checkbox-MVYpQird.js";import"./ui-vendor-BuM9f2NY.js";function Mn(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 Li(n,s){return Mn(n,s)==="Add connection"?"Add":"Connect"}const Ii=[{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 Ki({value:n,region:s,startUrl:i,onChange:a,onRegionChange:u,onStartUrlChange:d}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(St,{size:"sm",value:n,onChange:a,options:Ii.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(ie,{placeholder:"AWS region (default: us-east-1)",value:s,onChange:h=>u(h.target.value)}),e.jsx(ie,{placeholder:"AWS Start URL (https://...)",value:i,onChange:h=>d(h.target.value)})]}):null]})}function Ri({mode:n,refreshToken:s,clientId:i,clientSecret:a,profileArn:u,cliProxyJson:d,onRefreshTokenChange:h,onClientIdChange:b,onClientSecretChange:N,onProfileArnChange:S,onCliProxyJsonChange:K}){return n==="import-token"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:"min-h-28 w-full rounded-md border border-input bg-surface px-3 py-2 font-mono text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:text-sm",placeholder:"Kiro refresh token (aorAAAAAG...)",value:s,onChange:j=>h(j.target.value)}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(ie,{placeholder:"Client ID (optional for IAM)",value:i,onChange:j=>b(j.target.value)}),e.jsx(ie,{type:"password",placeholder:"Client secret (optional for IAM)",value:a,onChange:j=>N(j.target.value)})]}),e.jsx(ie,{placeholder:"Profile ARN (optional)",value:u,onChange:j=>S(j.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:j=>K(j.target.value)}):null}function Oi({region:n,onChange:s}){return e.jsx(ie,{placeholder:"AWS region (default: us-east-1)",value:n,onChange:i=>s(i.target.value)})}function Fi({authLabel:n,apiKey:s,region:i,checking:a,keyValid:u,checkMsg:d,submitError:h,proxyPoolId:b,proxyOptions:N,showKiroRegion:S,onApiKeyChange:K,onRegionChange:j,onCheck:v,onProxyPoolChange:D}){var z;return e.jsxs("div",{className:"space-y-2",children:[S?e.jsx(Oi,{region:i,onChange:j}):null,e.jsx("label",{htmlFor:"connection-api-key",className:"text-xs font-medium text-muted-foreground",children:n}),e.jsx(ie,{id:"connection-api-key",type:"password",placeholder:"API Key",value:s,"aria-invalid":!!h,"aria-describedby":h?"connection-submit-error":void 0,onChange:A=>K(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(cn,{children:"Checking…"}):"Check"}),u===!0?e.jsx(le,{tone:"ok",children:"Valid"}):u===!1?e.jsx(le,{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(ui,{value:b,onValueChange:A=>D(A??"pool_none"),children:[e.jsx(mi,{className:"w-full",children:e.jsx("span",{className:"truncate",children:((z=N.find(A=>A.id===b))==null?void 0:z.name)??"None (direct)"})}),e.jsx(hi,{children:N.map(A=>e.jsx(fi,{value:A.id,children:A.name},A.id))})]})]})]})}function Di({isDeviceFlow:n,isOAuthFlow:s,isKiroIam:i,authLink:a,userCode:u,deviceStatus:d,deviceCode:h,bootLoading:b,linkCopied:N,oauthCode:S,kiroStartUrl:K,onStartKiroAuthorization:j,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 j(),disabled:b||!K.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(An,{className:"h-3.5 w-3.5"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Jn,{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(ie,{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 qi({value:n,modes:s,onChange:i,label:a}){return e.jsx(St,{size:"sm",value:n,onChange:i,options:s.map(u=>({value:u,label:a(u)})),className:"w-full"})}function Bi({value:n,onChange:s}){return e.jsx(ys,{value:n,onValueChange:i=>s(i),children:e.jsxs(bs,{className:"w-full",children:[e.jsx(Nn,{value:"single",className:"flex-1",children:"Single API Key"}),e.jsx(Nn,{value:"bulk",className:"flex-1",children:"Bulk API Key"})]})})}function zi({raw:n,rows:s,activeIndex:i,activeRow:a,checking:u,validCount:d,onRawChange:h,onCheck:b}){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(Yn,{initial:!1,mode:"wait",children:e.jsxs(ft.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(dn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(An,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Gn,{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(ft.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(le,{tone:"ok",children:["Valid: ",d," API Key"]}),e.jsxs(le,{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 b(),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 _i({providerId:n,token:s,machineId:i,importing:a,message:u,hasError:d,onTokenChange:h,onMachineIdChange:b,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(cn,{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(ie,{placeholder:"Machine ID (cursorAuth machine id)",value:i,onChange:S=>b(S.target.value)}):null]})}function Ui({raw:n,rows:s,activeIndex:i,activeRow:a,onRawChange:u,onCheck:d,validCount:h,checking:b}){const[N,S]=o.useState(0),K=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:K},(j,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:j=>u(j.target.value),onScroll:j=>S(j.currentTarget.scrollTop)})]})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsx(E,{size:"sm",variant:"outline",disabled:!n.trim()||b,onClick:()=>void d(),children:b?e.jsx(cn,{children:"Checking…"}):"Check all"})}),b&&a?e.jsx("div",{className:"overflow-hidden px-1",role:"status","aria-live":"polite",children:e.jsx(Yn,{initial:!1,mode:"wait",children:e.jsxs(ft.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(dn,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground"}):a.valid===!0?e.jsx(An,{className:"h-3.5 w-3.5 shrink-0 text-success"}):e.jsx(Gn,{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"}`)})}):!b&&s.length>0?e.jsxs(ft.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(le,{tone:"ok",children:["Valid: ",h," account",h===1?"":"s"]}),e.jsxs(le,{tone:"err",children:["Error: ",s.filter(j=>j.valid===!1).length," account",s.filter(j=>j.valid===!1).length===1?"":"s"]})]}):null,n.trim()?null:e.jsx("p",{className:"text-xs text-muted-foreground",role:"status",children:"At least one access token or refresh token is required."})]})}function $i(n){return n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).map(s=>{const i=s.split("|").map(a=>a.trim());return i.length===1&&i[0]?{credentialToken:i[0],valid:null}:i.length===2&&i[0]&&i[1]?{accessToken:i[0],refreshToken:i[1],valid:null}:{valid:!1,msg:"Use one token or accessToken|refreshToken"}})}const Qi=new Set(["claude","codex","xai"]),Vi=200,Wi=1e3;function Hi({open:n,provider:s,flow:i,onOpenChange:a,onSubmit:u}){var bn;const[d,h]=o.useState(""),[b,N]=o.useState(""),[S,K]=o.useState(""),[j,v]=o.useState(""),[D,z]=o.useState(""),[A,J]=o.useState(""),[U,_]=o.useState("pool_none"),[G,$]=o.useState(()=>[{id:"pool_none",name:"None (direct)"}]),[ve,F]=o.useState(!1),[Fe,De]=o.useState(!1),[qe,ye]=o.useState(null),[Ve,ne]=o.useState(null),[be,Y]=o.useState(null),[fe,se]=o.useState(null),[O,ae]=o.useState(null),[we,R]=o.useState(null),[M,oe]=o.useState(null),[pe,te]=o.useState(5),[Be,ce]=o.useState(null),[ke,Ne]=o.useState(null),[ze,pt]=o.useState(null),[it,Tt]=o.useState(null),[xe,Mt]=o.useState("builder-id"),[xt,Pt]=o.useState("us-east-1"),[Zt,Et]=o.useState(""),[en,gt]=o.useState(""),[un,Lt]=o.useState(""),[rt,_e]=o.useState(""),[It,tn]=o.useState(""),[Kt,Rt]=o.useState(""),[vt,We]=o.useState(!1),[Pn,at]=o.useState(null),[En,Ye]=o.useState(!1),[de,Xe]=o.useState("single"),[yt,ot]=o.useState(""),[Ot,Me]=o.useState([]),[Ft,bt]=o.useState(!1),[nn,Se]=o.useState(null),[Dt,sn]=o.useState(!1),[Ue,Ze]=o.useState([]),[wt,$e]=o.useState(!1),[lt,Pe]=o.useState(null);function qt(m,p){return p==="apikey"?m==="qoder"?"API Key (PAT)":"API Key":p==="device"?"Device Code":p==="import"?m==="codebuddy-cn"||m==="codebuddy-intl"?"Access Token":"Import Token":p}const[Bt,he]=o.useState(null),[rn,He]=o.useState(!1),[zt,Ee]=o.useState(!1),[P,ct]=o.useState(!1),H=o.useRef(!1),et=o.useRef(null),Ae=o.useRef(!1),_t=o.useRef(null),c=o.useRef(null);function Le(m=!1){ct(m)}function re(){c.current&&(clearTimeout(c.current),c.current=null)}function je(){const m=_t.current;_t.current=null,m&&!m.closed&&m.close()}function tt(m){const p=et.current;!p||m&&p!==m||(et.current=null,Le(!1),p&&qs(p).catch(()=>{}))}const ge=o.useRef(u);ge.current=u;const Ie=o.useRef(d);Ie.current=d;const W=(s==null?void 0:s.id)==="kiro",kt=(s==null?void 0:s.id)==="codebuddy-cn"||(s==null?void 0:s.id)==="codebuddy-intl",Ce=(bn=s==null?void 0:s.authModes)!=null&&bn.length?s.authModes:null,dt=!!(Ce&&Ce.length>1),[an,mn]=o.useState((Ce==null?void 0:Ce[0])??"auto"),Ke=W?xe==="api-key"||xe==="import-token"||xe==="cli-proxy"?xe==="api-key"?"apikey":"import":"device":Ce&&Ce.includes(an)?an:i??(Ce!=null&&Ce.includes("device")?"device":"apikey"),nt=Ot.filter(m=>m.valid===!0),hn=nn===null?null:Ot[nn]??null,ut=Ue.filter(m=>m.valid===!0),Ln=lt===null?null:Ue[lt]??null;function Ut(m){return m.split(/\r?\n/).map(p=>p.trim()).filter(Boolean).map(p=>{const w=p.includes("|")?p.split("|").map(x=>x.trim()):p.includes(",")?p.split(",").map(x=>x.trim()):[p];return{name:w.length>=2?w[0]:"",apiKey:w.length>=2?w[1]:w[0],valid:null,msg:void 0}})}async function fn(){if(!s)return;const m=Ut(yt);if(!m.length)return;bt(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;Me([...p]),Se(0);try{for(let x=0;x<p.length;x+=1){Se(x);const T=p[x].apiKey.trim();if(w.has(T)){p[x]={...p[x],valid:!1,checking:!1,msg:"Duplicate API key in this batch"},Me([...p]);continue}w.add(T),p[x]={...p[x],checking:!0},Me([...p]);try{const q=await ss({provider:s.id,apiKey:p[x].apiKey});p[x]={...p[x],valid:q.valid===!0,checking:!1,msg:q.valid===!0?"ok":q.error||"fail"}}catch(q){p[x]={...p[x],valid:!1,checking:!1,msg:Z(q,"error")}}Me([...p]),await new Promise(q=>{window.setTimeout(q,Wi)})}}finally{Se(null),bt(!1)}}async function pn(){if(!(!s||!nt.length)){sn(!0),Y(null);try{await u({name:s.name,authFlow:"apikey",bulkKeys:nt.map(({name:m,apiKey:p},w)=>{const x=m.trim();return{name:x||`swayrouter-account${w+1}`,apiKey:p.trim(),autoName:!x}})})}catch(m){Y(Z(m,"Failed to add connections"))}finally{sn(!1)}}}const Q=Ke,Je=Q==="apikey"||!!(s!=null&&s.isCustom),Ge=Q==="oauth",mt=Q==="device",on=Ge||mt,xn=zt&&on;function gn(m){H.current=!0,re(),Mt(m),Xe("single"),ye(null),ne(null),Y(null),he(null),ae(null),R(null),oe(null),ce(null),se(null)}async function vn(){if(!s||s.id!=="kiro")return;const m=xe==="iam"?"idc":"builder-id",p=Zt.trim();if(m==="idc"&&!p){he("AWS IAM Identity Center requires a Start URL");return}H.current=!0,re(),Ee(!0),he(null),ce(null),ae(null),R(null),oe(null),se(null);try{const w=await ns("kiro",{authMethod:m,region:xt.trim()||"us-east-1",startUrl:p||void 0}),x=typeof w.device_code=="string"&&w.device_code||typeof w.deviceCode=="string"&&w.deviceCode||null;if(!x)throw new Error("Kiro did not return a device code");const T=typeof w.user_code=="string"&&w.user_code||typeof w.userCode=="string"&&w.userCode||null,q=typeof w.verification_uri_complete=="string"&&w.verification_uri_complete||typeof w.verificationUriComplete=="string"&&w.verificationUriComplete||typeof w.verification_uri=="string"&&w.verification_uri||typeof w.verificationUri=="string"&&w.verificationUri||null;ae(x),oe(T),se(q),R(typeof w.codeVerifier=="string"?w.codeVerifier:null),te(typeof w.interval=="number"&&w.interval>0?w.interval:5),ce("Waiting for you to authorize…")}catch(w){he(Z(w,"Failed to start Kiro authorization"))}finally{Ee(!1)}}if(o.useEffect(()=>{var m;n&&(mn(((m=s==null?void 0:s.authModes)==null?void 0:m[0])??"auto"),Mt("builder-id"),Pt("us-east-1"),Et(""),gt(""),Lt(""),_e(""),tn(""),Rt(""),v(""),ne(null),We(!1),at(null),Ye(!1),Xe("single"),ot(""),Me([]),Se(null),Ze([]),$e(!1),Pe(null))},[n,s==null?void 0:s.id]),o.useEffect(()=>{if(!n)return;let m=!1;async function p(){try{const w=await ei();if(m)return;$([{id:"pool_none",name:"None (direct)"},...w.map(x=>({id:x.id,name:String(x.name||x.id)}))])}catch{}}return p(),()=>{m=!0}},[n]),o.useEffect(()=>{if(!n||!s)return;h(""),N(""),K(""),z(""),J(""),_("pool_none"),F(!1),Ee(!1),De(!1),ye(null),ne(null),Y(null),He(!1),he(null),ce(null),ae(null),R(null),oe(null),Ne(null),pt(null),Tt(null),se(null),Xe("single"),ot(""),Me([]),Se(null),bt(!1),sn(!1),H.current=!1;const m=s.id;let p=!1;async function w(){if(Q==="oauth"){Ee(!0);try{const x=Rs(m),T=await Os(m,x);if(p)return;const q=T.authUrl||T.url||T.authorizeUrl||null,t=typeof T.state=="string"?T.state:null,r=typeof T.codeVerifier=="string"?T.codeVerifier:null,l=typeof T.redirectUri=="string"&&T.redirectUri?T.redirectUri:x;se(typeof q=="string"?q:null),Ne(t),t&&ri(t,m),pt(r),Tt(l),Ae.current=!1;const g=(typeof T.flowType=="string"?T.flowType:null)==="authorization_code_pkce"||Qi.has(m);if(!q||!t||!l||g&&!r)throw new Error("OAuth provider returned incomplete authorization data");if(m==="codex"||m==="xai"){const C=window.location.port||(window.location.protocol==="https:"?"443":"80");try{const f=t,k=r,I=l;if(!f||!k||!I)throw new Error("OAuth provider returned incomplete authorization data");const V=await Fs(m,{appPort:C});if(!V.success)throw new Error(V.reason==="port_busy"?"The OAuth callback port is already in use":"The OAuth callback listener could not start");if(et.current=m,Le(!1),(await Ds(m,{state:f,codeVerifier:k,redirectUri:I})).success!==!0)throw new Error("The OAuth session could not be registered");if(p)return;Le(!0)}catch(f){he(Z(f,"Automatic callback setup unavailable. Paste the browser callback code below.")),tt(m)}}}catch(x){p||he(Z(x,"Failed to start OAuth"))}finally{p||Ee(!1)}return}if(Q==="device"){if(m==="kiro"){xe==="builder-id"&&vn();return}Ee(!0);try{const x=await ns(s.id);if(p)return;const T=typeof x.device_code=="string"&&x.device_code||typeof x.deviceCode=="string"&&x.deviceCode||null,q=typeof x.user_code=="string"&&x.user_code||typeof x.userCode=="string"&&x.userCode||null,t=typeof x.verification_uri_complete=="string"&&x.verification_uri_complete||typeof x.verificationUriComplete=="string"&&x.verificationUriComplete||typeof x.verification_uri=="string"&&x.verification_uri||typeof x.verificationUri=="string"&&x.verificationUri||null;ae(T),oe(q),se(t),R(typeof x.codeVerifier=="string"?x.codeVerifier:null);const r=typeof x.interval=="number"&&x.interval>0?x.interval:5;te(r),ce("Waiting for you to authorize…")}catch(x){p||he(Z(x,"Failed to start device code"))}finally{p||Ee(!1)}}}return w(),()=>{p=!0,H.current=!0,re(),je(),tt(s.id)}},[n,s,Q,xe]),o.useEffect(()=>{if(!n||!s||Q!=="oauth"||!P||!ke)return;let m=!1,p=0;const w=s.id,x=s.name,T=ke,q=200,t=async()=>{if(!(m||Ae.current)){p+=1;try{const r=await Bs(w,T);if(m||Ae.current)return;if(r.status==="done"){Ae.current=!0,re(),je(),tt(w),F(!0);try{await ge.current({name:Ie.current.trim()||x,alreadySaved:!0})}catch{he("Connection saved, but the provider list could not refresh")}finally{F(!1)}return}if(r.status==="error"){Ae.current=!0,re(),je(),tt(w),he(r.error||"OAuth sign-in failed");return}}catch{}!m&&!Ae.current&&p<q?c.current=setTimeout(()=>void t(),1500):!m&&!Ae.current&&(he("OAuth sign-in timed out. Use the manual code fallback."),tt(w))}};return c.current=setTimeout(()=>void t(),750),()=>{m=!0,re()}},[n,s,Q,P,ke]),o.useEffect(()=>{if(!n||!s||Q!=="oauth")return;const m=s.id,p=s.name,w=ke;if(!w)return;let x=window.location.origin;if(it)try{x=new URL(it).origin}catch{return}const T=f=>as(ci(f),{origin:x,eventOrigin:x,expectedState:w,expectedProvider:m});function q(f){if(!Ae.current){if(f.error){f.state&&os(f.state),he(f.errorDescription||f.error||"OAuth sign-in failed");return}!f.code||!f.state||(os(f.state),Ae.current=!0,J(f.code),ce(null),F(!0),(async()=>{try{await ge.current({name:Ie.current.trim()||p,authFlow:"oauth",oauthCode:f.code,oauthState:f.state,oauthCodeVerifier:ze||void 0,oauthRedirectUri:it||void 0}),je()}catch(k){Ae.current=!1,he(Z(k,"OAuth sign-in completed, but the token exchange failed. Restart the connection flow and try again."))}finally{F(!1)}})())}}function t(f){const k=as(f.data,{origin:x,eventOrigin:f.origin,expectedState:w,expectedProvider:m,eventSource:f.source,expectedSource:_t.current});k&&q(k)}const r=w,l=di(r);function y(f){const k=f===void 0?ai(r):li(f),I=k?T(k):null;I&&q(I)}function g(f){f.key===l&&y(f.newValue)}y(),window.addEventListener("message",t),window.addEventListener("storage",g);const C=window.setInterval(()=>y(),500);return()=>{window.removeEventListener("message",t),window.removeEventListener("storage",g),window.clearInterval(C)}},[n,s,Q,ke,ze,it]),o.useEffect(()=>()=>{H.current=!0,re(),je(),tt()},[]),o.useEffect(()=>{if(!n||!s||Q!=="device"||!O)return;H.current=!1;let m=null,p=!1;const w=s.id,x=s.name,T=we||void 0,q=Math.max(2,pe)*1e3;async function t(){if(!(p||H.current||!O)){try{const r=await ps(w,{deviceCode:O,codeVerifier:T,displayName:Ie.current.trim()||x});if(p||H.current)return;if(r.success){ce("Authorized — connection saved"),F(!0);try{await ge.current({name:Ie.current.trim()||x,alreadySaved:!0})}catch{ce("Authorized — refresh the list if not visible")}finally{F(!1)}return}r.pending?ce("Still waiting for authorization…"):r.error&&ce(r.error)}catch(r){p||ce(Z(r,"Poll failed"))}!p&&!H.current&&(m=setTimeout(t,q))}}return m=setTimeout(t,q),()=>{p=!0,H.current=!0,m&&clearTimeout(m)}},[n,s==null?void 0:s.id,s==null?void 0:s.name,Q,O,we,pe]),o.useEffect(()=>{ye(null),ne(null),Y(null)},[b]),!s)return null;const In=Mn(s.authType,s.noAuth),Kn=Li(s.authType,s.noAuth),jt=!ve&&!xn&&(Je?qe===!0&&b.trim().length>0:Q==="import"?kt?ut.length>0&&!wt:W?xe==="import-token"?en.trim().length>0:Kt.trim().length>0:S.trim().length>0&&((s==null?void 0:s.id)!=="cursor"||D.trim().length>0):Q==="oauth"?A.trim().length>0:Q==="device"?!!O:!0);async function yn(){if(!(!s||!b.trim())){De(!0),ne(null);try{const m=await ss({provider:s.id,apiKey:b.trim(),...W?{providerSpecificData:{region:xt.trim()||"us-east-1"}}:{}}),p=m.valid===!0;ye(p),ne(p?"Key valid":m.error||"Key invalid")}catch(m){ye(!1),ne(Z(m,"Check failed"))}finally{De(!1)}}}async function Rn(){if(!s||!j.trim())return;const m=$i(j);if(!m.length)return;$e(!0);const p=m.map(x=>({...x,checking:!1})),w=new Set;Ze([...p]),Pe(0);try{for(let x=0;x<p.length;x+=1){Pe(x);const T=p[x];if(T.valid===!1){Ze([...p]);continue}const q=T.credentialToken||`${T.accessToken}|${T.refreshToken}`;if(w.has(q)){p[x]={...T,valid:!1,checking:!1,msg:"Duplicate token pair in this batch"},Ze([...p]);continue}w.add(q),p[x]={...T,checking:!0},Ze([...p]);try{const t=await zs({provider:s.id,...T.credentialToken?{credentialToken:T.credentialToken}:{accessToken:T.accessToken,refreshToken:T.refreshToken}});p[x]={...T,valid:t.valid===!0,checking:!1,msg:t.valid===!0?"ok":t.error||"Token invalid"}}catch(t){p[x]={...T,valid:!1,checking:!1,msg:Z(t,"Token validation failed")}}Ze([...p]),x<p.length-1&&await new Promise(t=>{window.setTimeout(t,Vi)})}}finally{Pe(null),$e(!1)}}async function On(){if(!(!s||s.id!=="cursor")){We(!0),at(null),Ye(!1);try{const m=await _s();if(!m.found||!m.accessToken||!m.machineId)throw new Error(m.error||"Cursor credentials were not found on this device");K(m.accessToken),z(m.machineId),at("Cursor token and Machine ID filled automatically")}catch(m){Ye(!0),at(Z(m,"Could not detect Cursor credentials"))}finally{We(!1)}}}async function Fn(){if(fe)try{await navigator.clipboard.writeText(fe),He(!0),window.setTimeout(()=>He(!1),1500)}catch{}}function Dn(){if(!fe)return;const m=window.open(fe,"sway-oauth","popup,width=600,height=700");_t.current=m,m||he("The browser blocked the authorization window. Open the URL above manually or allow popups for this dashboard.")}async function qn(){if(!(!s||!jt)){F(!0),Y(null);try{const m=d.trim(),p=Ge?oi(A,ke):null;await u({name:m,autoName:Je&&!m,authFlow:Q,apiKey:Je&&b.trim()||void 0,importToken:Q==="import"&&!W&&!kt&&S.trim()||void 0,codeBuddyToken:Q==="import"&&kt&&ut.length===1&&ut[0].credentialToken||void 0,codeBuddyTokens:Q==="import"&&kt?ut.map((w,x)=>{const T=ut.length===1?m:"";return{...w.credentialToken?{credentialToken:w.credentialToken}:{accessToken:w.accessToken,refreshToken:w.refreshToken},name:T||`swayrouter-account${x+1}`,autoName:!T}}):void 0,machineId:Q==="import"&&D.trim()||void 0,kiroAuthMode:W?xe:void 0,kiroRegion:W?xt.trim()||"us-east-1":void 0,kiroRefreshToken:W&&en.trim()||void 0,kiroClientId:W&&un.trim()||void 0,kiroClientSecret:W&&rt.trim()||void 0,kiroProfileArn:W&&It.trim()||void 0,kiroCliProxyJson:W&&Kt.trim()||void 0,oauthCode:p==null?void 0:p.code,oauthState:p==null?void 0:p.state,oauthCodeVerifier:Ge&&ze||void 0,oauthRedirectUri:Ge&&it||void 0,deviceCode:mt&&O||void 0,deviceCodeVerifier:mt&&we||void 0,proxyPoolId:Je?U:null})}catch(m){Y(Z(m,"Failed to add connection"))}finally{F(!1)}}}const Bn=de==="bulk"&&Je?"Add connections":In;return e.jsx(Wt,{open:n,onOpenChange:a,children:e.jsxs(Ht,{children:[e.jsx(Jt,{children:e.jsxs(Gt,{children:[Bn," — ",s.name]})}),e.jsxs("div",{className:me("px-6",Je&&de==="bulk"?"space-y-2 pb-4":"space-y-3 pb-4"),children:[!W&&dt&&Ce?e.jsx(qi,{value:an,modes:Ce,label:m=>qt((s==null?void 0:s.id)??"",m),onChange:m=>{mn(m),Xe("single"),ot(""),Me([]),Se(null),Y(null)}}):null,W?e.jsx(Ki,{value:xe,region:xt,startUrl:Zt,onChange:gn,onRegionChange:Pt,onStartUrlChange:Et}):null,Je&&!W?e.jsx(Bi,{value:de,onChange:Xe}):null,Je&&!W&&de==="bulk"?e.jsx(zi,{raw:yt,rows:Ot,activeIndex:nn,activeRow:hn,checking:Ft,validCount:nt.length,onRawChange:m=>{ot(m),Me([]),Se(null),Y(null)},onCheck:fn}):null,de==="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(ie,{id:"connection-account-name",placeholder:"Auto: swayrouter-account",value:d,"aria-invalid":!!be,"aria-describedby":be?"connection-submit-error":void 0,onChange:m=>{h(m.target.value),Y(null)}})]}),Bt?e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-xs text-destructive",children:Bt}):null,xn?e.jsx("p",{className:"text-xs text-muted-foreground",children:e.jsx(cn,{children:"Starting auth flow…"})}):null,Q==="import"?kt?e.jsx(Ui,{raw:j,rows:Ue,activeIndex:lt,activeRow:Ln,checking:wt,validCount:ut.length,onRawChange:m=>{v(m),Ze([]),Pe(null),Y(null)},onCheck:Rn}):W?e.jsx(Ri,{mode:xe,refreshToken:en,clientId:un,clientSecret:rt,profileArn:It,cliProxyJson:Kt,onRefreshTokenChange:gt,onClientIdChange:Lt,onClientSecretChange:_e,onProfileArnChange:tn,onCliProxyJsonChange:Rt}):e.jsx(_i,{providerId:s.id,token:S,machineId:D,importing:vt,message:Pn,hasError:En,onTokenChange:K,onMachineIdChange:z,onAutoImport:On}):Q==="local"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Local provider — no key required."}):on?e.jsx(Di,{isDeviceFlow:mt,isOAuthFlow:Ge,isKiroIam:W&&xe==="iam",authLink:fe,userCode:M,deviceStatus:Be,deviceCode:O,bootLoading:zt,linkCopied:rn,oauthCode:A,kiroStartUrl:Zt,onStartKiroAuthorization:vn,onOpenAuthLink:Dn,onCopyAuthLink:Fn,onOauthCodeChange:J}):e.jsx(Fi,{authLabel:qt(s.id,"apikey"),apiKey:b,region:xt,checking:Fe,keyValid:qe,checkMsg:Ve,submitError:be,proxyPoolId:U,proxyOptions:G,showKiroRegion:W,onApiKeyChange:m=>{N(m),Y(null)},onRegionChange:Pt,onCheck:yn,onProxyPoolChange:_}),be?e.jsx("p",{id:"connection-submit-error",className:"text-xs text-destructive",role:"alert",children:be}):null]}):null]}),e.jsxs(Yt,{children:[e.jsx(E,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(E,{disabled:de==="bulk"?Dt||Ft||nt.length===0:!jt,className:me((de==="bulk"?Dt||Ft||nt.length===0:!jt)&&"opacity-40"),onClick:()=>void(de==="bulk"?pn():qn()),children:de==="bulk"?Dt?"Adding…":"Add":ve?e.jsx(cn,{children:mt||Ge?"Waiting…":"Saving…"}):mt?"Poll now":Ge&&!A.trim()?"Waiting for browser…":Kn})]})]})})}function ls({open:n,onOpenChange:s,onCreate:i,initial:a,submitLabel:u="Create"}){const[d,h]=o.useState(""),[b,N]=o.useState(""),[S,K]=o.useState(""),[j,v]=o.useState("openai-compatible"),[D,z]=o.useState("chat");o.useEffect(()=>{!n||!a||(h(a.name||""),N(a.alias||""),K(a.baseUrl||""),v(a.nodeType==="anthropic-compatible"?"anthropic-compatible":"openai-compatible"),z(a.apiType==="responses"?"responses":"chat"),G(null),U(!1))},[n,a]);const A=!!a,[J,U]=o.useState(!1),[_,G]=o.useState(null);return o.useEffect(()=>{n&&(a||(h(""),N(""),K(""),v("openai-compatible"),z("chat"),G(null),U(!1)))},[n,a]),e.jsx(Wt,{open:n,onOpenChange:s,children:e.jsxs(Ht,{children:[e.jsx(Jt,{children:e.jsx(Gt,{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(ie,{id:"custom-provider-name",placeholder:"My provider",value:d,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{h($.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(ie,{id:"custom-provider-prefix",placeholder:"my-llm",value:b,"aria-invalid":!!_,"aria-describedby":_?"custom-provider-error":void 0,onChange:$=>{N($.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(ie,{id:"custom-provider-base-url",placeholder:"https://api.example.com/v1",value:S,onChange:$=>K($.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"API format"}),e.jsx(St,{size:"sm",value:j,onChange:v,options:[{value:"openai-compatible",label:"OpenAI"},{value:"anthropic-compatible",label:"Claude"}]})]}),j==="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(St,{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)."}),_?e.jsx("p",{id:"custom-provider-error",className:"text-sm text-destructive",role:"alert",children:_}):null]}),e.jsxs(Yt,{children:[e.jsx(E,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(E,{disabled:J,onClick:()=>{if(!d.trim()||!b.trim()){G("Name and prefix required");return}U(!0),i({name:d.trim(),prefix:b.trim().toLowerCase().replace(/\s+/g,"-"),baseUrl:S.trim()||void 0,type:j,apiType:j==="openai-compatible"?D:void 0}).catch($=>{G(Z($,"Failed to save custom provider"))}).finally(()=>U(!1))},children:u})]})]})})}function Un({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 Ji({conn:n,onOpenChange:s,onSave:i}){var $,ve;const[a,u]=o.useState(""),[d,h]=o.useState(!1),[b,N]=o.useState(""),[S,K]=o.useState(null),[j,v]=o.useState(!1);o.useEffect(()=>{n&&(u(n.name||""),N(""),K(null))},[n]);const D=String((n==null?void 0:n.authType)||"").trim().toLowerCase(),z=typeof(($=n==null?void 0:n.providerSpecificData)==null?void 0:$.authMethod)=="string"?n.providerSpecificData.authMethod.trim().toLowerCase():"",A=D||z,J=n?jn(n.provider):"apikey",U=A==="apikey"||A==="api_key"||A==="api-key"||!A&&J==="apikey",_=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":U?"API Key":A||"Managed credentials";async function G(){if(n){v(!0),K(null);try{const F=await xs(n.id),Fe=F.valid===!0;K({label:Fe?"Active":F.error||"Failed",ok:Fe})}catch(F){K({label:Z(F,"Test failed"),ok:!1})}finally{v(!1)}}}return e.jsx(Wt,{open:!!n,onOpenChange:s,children:e.jsxs(Ht,{children:[e.jsxs(Jt,{children:[e.jsx(Gt,{children:"Edit connection"}),e.jsx(kn,{children:(n==null?void 0:n.name)||((ve=n==null?void 0:n.id)==null?void 0:ve.slice(0,8))})]}),e.jsxs("div",{className:"space-y-3 px-6",children:[e.jsx(Un,{label:"Name",children:e.jsx(ie,{value:a,onChange:F=>u(F.target.value)})}),U?e.jsxs(Un,{label:"API Key",hint:"Leave empty to keep current key",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ie,{type:"password",value:b,onChange:F=>N(F.target.value),placeholder:"sk-… or paste new key",className:"flex-1"}),e.jsx(E,{size:"sm",variant:"outline",disabled:j,"aria-busy":j,"aria-label":j?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void G(),children:j?e.jsx(dn,{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(Un,{label:"Authentication",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/25 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:_}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Credentials are managed by this connection."})]}),e.jsx(E,{size:"sm",variant:"outline",disabled:j,"aria-busy":j,"aria-label":j?"Testing connection":"Test connection",className:"min-w-14 justify-center",onClick:()=>void G(),children:j?e.jsx(dn,{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(Yt,{children:[e.jsx(E,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(E,{disabled:d,onClick:()=>{h(!0),i(a.trim(),b).finally(()=>h(!1))},children:"Save"})]})]})})}function Ns({id:n,color:s,size:i=24,fallbackIcon:a}){const u=Ps(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 Gi({byProvider:n,filter:s,hiddenProviders:i,loading:a,query:u,providerListRef:d,selectedId:h,sorted:b,onFilterChange:N,onQueryChange:S,onSelectProvider:K,onToggleProviderHidden:j}){return e.jsxs(ks,{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(js,{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(gs,{className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ie,{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(Gn,{className:"h-4 w-4"})})}):null]}),e.jsx(St,{size:"sm",value:s,onChange:N,options:[{value:"all",label:"All"},{value:"active",label:"Active"},{value:"idle",label:"Idle"}]})]}),e.jsx(Cs,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsx(hs,{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(Mi,{className:"h-14 w-full rounded-lg"},D))}):b.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:b.map(v=>{const D=n.get(v.id)||[],z=v.id===h?D.length:v.connected||0,A=v.id===h?D.filter(F=>F.isActive!==!1).length:z,J=v.id===h?D.length-A:0,U=h===v.id,_=i.includes(v.id),G=fs(v.id),$=v.isCustom?"apikey":jn(v.id,v.authType,v.noAuth),ve=$==="apikey"?pi:$==="oauth"||$==="device"?xi:$==="import"?gi:vi;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",U?"text-foreground":"hover:bg-surface-hover/70",_&&"opacity-55"),children:[U?e.jsx(ft.span,{layoutId:"provider-highlight",className:"absolute inset-0 rounded-lg bg-white/15",transition:{type:"spring",stiffness:520,damping:36,mass:.4}}):null,e.jsxs("button",{type:"button",onClick:()=>K(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(Ns,{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(ve,{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(Vn,{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"]:Es(v.authType,v.noAuth,v.authModes,v.id)).map(F=>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(ve,{className:"h-2.5 w-2.5"}),F]},F)),v.id==="opencode"?e.jsx(le,{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(le,{tone:"ok",className:"text-[10px] font-medium sm:text-[11px]",children:[z," connection",z===1?"":"s"]})]}):e.jsx("span",{className:"text-muted-foreground/60",children:"no connections"})]})]})]}),e.jsx(ee,{label:_?"Show provider":"Hide provider",children:e.jsx("button",{type:"button","aria-label":_?`Show ${v.name}`:`Hide ${v.name}`,"aria-pressed":_,onClick:()=>j(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:_?e.jsx(yi,{className:"size-3.5"}):e.jsx(bi,{className:"size-3.5"})})})]})},v.id)})})})})})]})}function Xt({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(dn,{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 Sn(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 Yi=["vision","pdf","audioInput","videoInput","imageOutput","audioOutput","search","tools","reasoning"];function Wn(n){if(!n||typeof n!="object"||Array.isArray(n))return;const s=n,i={};for(const a of Yi)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 Xi=[["vision","Vision"],["pdf","PDF"],["audioInput","Audio"],["videoInput","Video"],["imageOutput","Image out"],["audioOutput","Audio out"],["search","Search"],["tools","Tools"],["reasoning","Reasoning"]];function Zi(n){return n?Xi.filter(([s])=>n[s]===!0).map(([s,i])=>({key:s,label:i})):[]}function $n(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=Sn(u,s);if(!d)return[];const h=typeof a.name=="string"&&a.name.trim()?a.name.trim():d,b=Array.isArray(a.thinkingLevels)?a.thinkingLevels.filter(N=>typeof N=="string"):void 0;return[{id:d,name:h,caps:Wn(a.capabilities??a.caps),...b?{thinkingLevels:b}:{}}]}):[]}function cs(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 er(n,s){var a;const i=new Map;for(const u of n){const d=Sn(u.id,u.provider_alias||u.provider_id||u.owned_by||s);if(!d)continue;const h=d===u.id?u:{...u,id:d},b=i.get(d);if(!b){i.set(d,h);continue}const N=cs(b.name,d)&&!cs(h.name,d)?h.name:b.name||h.name;i.set(d,{...b,name:N,provider_alias:b.provider_alias||h.provider_alias,provider_id:b.provider_id||h.provider_id,owned_by:b.owned_by||h.owned_by,caps:{...h.caps,...b.caps},thinkingLevels:(a=b.thinkingLevels)!=null&&a.length?b.thinkingLevels:h.thinkingLevels})}return[...i.values()]}function tr({selected:n,visibleModels:s,models:i,modelNames:a,modelsLoading:u,modelsUnavailable:d,importingModels:h,testConnId:b,batchKind:N,modelTestLock:S,testingModels:K,modelQuery:j,newModel:v,addingModel:D,modelResults:z,pinnedFor:A,copied:J,onImportModels:U,onTestAllModels:_,onStopTests:G,onStopModel:$,onModelQueryChange:ve,onNewModelChange:F,onAddModel:Fe,onTogglePin:De,onCopyModelId:qe,onTestModel:ye,onRemoveModel:Ve,disabledModelIds:ne,onToggleDisabled:be}){const Y=n.noAuth===!0||!!b,fe=n.noAuth===!0;return e.jsx(ws,{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:fe?"Fetch the public model catalog without a connection":b?"Fetch GET {base}/models with this connection’s key":"Needs a connection (API key) on this provider — or set base URL on a custom node",children:e.jsx(E,{size:"sm",variant:"outline",disabled:h,onClick:()=>void U(),children:h?"Importing…":fe?"Refresh":"Import"})}):null,i.length>0?e.jsx(Xt,{busy:N==="model",label:"Test all",disabled:!Y||S||N!==null&&N!=="model"||K.size>0&&N!=="model",onTest:()=>void _(),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(ie,{placeholder:"Search models…",value:j,onChange:se=>ve(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(ie,{placeholder:"model-id",value:v,disabled:D,onChange:se=>F(se.target.value),onKeyDown:se=>{se.key==="Enter"&&Fe()},className:"min-w-0"}),e.jsxs(E,{size:"sm",variant:"outline",disabled:D||!v.trim(),onClick:()=>void Fe(),className:"w-full sm:w-auto",children:[e.jsx(Tn,{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:j.trim()?"No models match your search.":d?"Upstream model catalog unavailable — add a slug above or retry.":"No models — add a slug above."}):e.jsx(ft.div,{layout:!0,className:"space-y-1",children:s.map(se=>{const O=se.id,ae=z[O],we=K.has(O),R=Zi(se.caps),M=N==="model"||we,oe=A.includes(O),pe=ne.has(O);return e.jsx(ft.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",pe&&"border-warning/40 bg-warning/[0.03]"),children:e.jsxs("div",{className:"group flex flex-wrap items-center gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:[a.get(O)?e.jsx("span",{className:"min-w-0 max-w-[45%] truncate text-xs font-medium",children:a.get(O)}):null,e.jsx("code",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",children:O}),pe?e.jsx(Vn,{size:"sm",variant:"warning",children:"Disabled"}):null,we||ae?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[we?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] text-foreground/90","aria-live":"polite","aria-label":`Checking ${O}`,children:[e.jsx("span",{children:"Checking"}),e.jsxs("span",{className:"inline-flex w-3 justify-start","aria-hidden":"true",children:[e.jsx("span",{className:"animate-pulse",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:150ms]",children:"."}),e.jsx("span",{className:"animate-pulse [animation-delay:300ms]",children:"."})]})]}):null,ae?e.jsx(ee,{label:ae.message||ae.label,children:e.jsx(le,{tone:ae.ok?"ok":"err",className:"max-w-[9rem] truncate text-[10px] font-semibold",children:ae.label})}):null]}):null,R.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:R.map(te=>e.jsx(ee,{label:te.label,children:e.jsx(Vn,{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:oe?"Unpin":"Pin to top",children:e.jsx("button",{type:"button","aria-label":oe?"Unpin model":"Pin model to top",onClick:()=>De(O),className:me("inline-flex h-7 w-7 items-center justify-center rounded-md border p-0 transition-colors duration-150",oe?"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(Yn,{initial:!1,mode:"wait",children:e.jsx(ft.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:oe?e.jsx(wi,{className:"h-3.5 w-3.5"}):e.jsx(ki,{className:"h-3.5 w-3.5"})},oe?"pinned":"unpinned")})})}),e.jsx(ee,{label:J===O?"Copied":"Copy model ID",children:e.jsx("button",{type:"button","aria-label":"Copy model ID",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-foreground",onClick:()=>void qe(O),children:J===O?e.jsx(An,{className:"h-3.5 w-3.5"}):e.jsx(Jn,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:pe?"Enable routing for model":"Disable routing for model",children:e.jsx("button",{type:"button","aria-label":pe?"Enable routing for model":"Disable routing for model","aria-pressed":pe,onClick:()=>void be(O),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",pe&&"text-warning hover:text-warning"),children:pe?e.jsx(ji,{className:"h-3.5 w-3.5"}):e.jsx(Ci,{className:"h-3.5 w-3.5"})})}),e.jsx("span",{className:"sm:hidden",children:e.jsx(Xt,{compact:!0,busy:M,disabled:!Y||S||N==="conn"||!we&&K.size>=4,onTest:()=>void ye(O,fe?void 0:b),onStop:()=>N==="model"?G():$(O)})}),e.jsx("span",{className:"hidden sm:inline-flex",children:e.jsx(Xt,{busy:M,disabled:!Y||S||N==="conn"||!we&&K.size>=4,onTest:()=>void ye(O,fe?void 0:b),onStop:()=>N==="model"?G():$(O)})}),e.jsx(ee,{label:"Remove",children:e.jsx("button",{type:"button","aria-label":"Remove model",className:"inline-flex h-7 w-7 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors duration-100 hover:bg-surface-hover hover:text-destructive",onClick:()=>void Ve(O),children:e.jsx(Cn,{className:"h-3.5 w-3.5"})})})]})]})},O)})})]})})})}const nr=["auto","low","medium","high","xhigh","max"],Qn=["auto","low","medium","high","max"],sr={openai:nr,claude:Qn,deepseek:["auto","low","high","max"],groq:["auto","low","medium","high"],openrouter:Qn,kimi:Qn,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"]},ir=["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"],ds={"x-high":"xhigh",maximum:"max"};function Xn(n){const s=String(n||"").trim().toLowerCase();return s?s in ds?ds[s]:["auto","none","on","off","thinking","minimal","low","medium","high","xhigh","max","ultra"].includes(s)?s:null:null}function rr(n){if(!Array.isArray(n==null?void 0:n.options))return[];const s=n.options.flatMap(u=>{const d=Xn(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 ar(n){return Array.isArray(n)?n.flatMap(s=>{const i=Xn(s);return i?[i]:[]}):[]}function or(n,s,i){if((i==null?void 0:i.modelAware)===!1)return Hn(n,i);const a=s.map(d=>new Set(ar(d))).filter(d=>d.size>0);return a.length?["auto",...ir.filter(d=>d!=="auto"&&d!=="none"&&a.some(h=>h.has(d)))]:n.startsWith("openai-compatible-")||n.startsWith("anthropic-compatible-")?null:Hn(n,i)}function Hn(n,s){if(n.startsWith("openai-compatible-")||n.startsWith("anthropic-compatible-"))return["auto","low","medium","high","max"];const i=rr(s);return i.length>0?i:sr[n]||null}function lr(n,s){const i=Hn(n,s),a=Xn(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 cr(n){return n==="auto"?"Auto":n==="xhigh"?"xHigh":n==="thinking"?"Thinking":n.charAt(0).toUpperCase()+n.slice(1)}function dr(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 ur({selected:n,connsAll:s,conns:i,strategy:a,strategyPending:u,stickyDraft:d,thinkingLevels:h,thinkingValue:b,thinkingPending:N,selectedKeys:S,connectionsCapped:K,totalConnections:j,batchKind:v,testingConnId:D,togglingConnId:z,connQuery:A,connListRef:J,connVirtualizer:U,connResults:_,onStrategyChange:G,onStickyDraftChange:$,onSaveSticky:ve,onThinkingChange:F,onRequestBulkDelete:Fe,onClearSelection:De,onToggleSelection:qe,onSelectAll:ye,onTestConnections:Ve,onTestConnection:ne,onStopTests:be,onConnQueryChange:Y,onOpenAddConnection:fe,onMovePriority:se,onToggleConnection:O,onEditConnection:ae,onDeleteConnection:we}){return e.jsx(ws,{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(St,{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"}]})})]}),e.jsxs("div",{className:me("inline-flex items-center gap-1.5 sm:gap-1.5",a!=="round-robin"&&"hidden sm:inline-flex"),children:[e.jsx("label",{htmlFor:"provider-sticky-limit",className:"text-xs font-medium text-muted-foreground",children:"Sticky"}),e.jsx(ie,{id:"provider-sticky-limit",size:"sm",type:"number",min:1,value:d,disabled:u||a!=="round-robin",onChange:R=>$(R.target.value),className:"w-14 shrink-0"}),e.jsx(E,{size:"sm",variant:"outline",disabled:u||a!=="round-robin",onClick:ve,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(St,{size:"compact",value:b,disabled:N,onChange:F,options:h.map(R=>({value:R,label:cr(R),compactLabel:R==="minimal"?"Min":R==="medium"?"Med":R==="thinking"?"Think":R==="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:Fe,children:[e.jsx(Cn,{className:"h-3.5 w-3.5"}),"Delete selected"]}),e.jsx(E,{size:"sm",variant:"outline",onClick:De,children:"Unselect"}),e.jsx(Xt,{busy:v==="conn"||i.some(R=>D===R.id),label:"Test selected",onTest:()=>void Ve([...S]),onStop:be})]}):e.jsxs(e.Fragment,{children:[e.jsx(E,{size:"sm",variant:"outline",onClick:ye,children:"Select all"}),e.jsx(Xt,{busy:v==="conn"||i.some(R=>D===R.id),label:"Test all",onTest:()=>void Ve(i.map(R=>R.id)),onStop:be})]})}):null]}),K?e.jsxs("div",{className:"shrink-0 rounded-md border border-warning/25 bg-warning/10 px-3 py-2 text-[11px] text-warning",children:["Showing the first ",s.length.toLocaleString()," of ",j.toLocaleString()," connections. Use search to find accounts beyond this limit."]}):null,s.length>0?e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(gs,{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(ie,{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:R=>Y(R.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:fe,children:[e.jsx(Tn,{className:"h-3.5 w-3.5"}),Mn(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(hs,{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:`${U.getTotalSize()}px`},children:U.getVirtualItems().map(R=>{const M=i[R.index];if(!M)return null;const oe=R.index,pe=S.has(M.id),te=_[M.id],Be=D===M.id,ce=M.isActive===!1,ke=M.testStatus==="stale"||M.testStatus==="expired",Ne=M.healthStatus&&M.healthStatus!=="unknown"?M.healthStatus:M.testStatus==="active"?"healthy":M.testStatus==="error"?"error":null,ze=M.lastTested?dr(M.lastTested):null;return e.jsx("div",{"data-index":R.index,ref:U.measureElement,className:"absolute left-0 top-0 w-full pb-1",style:{transform:`translateY(${R.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",pe?"border-foreground/40":ce?"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(Ei,{checked:pe,onCheckedChange:()=>{qe(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:oe===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(Ni,{className:"h-3.5 w-3.5"})})}),e.jsx(ee,{label:"Move down",children:e.jsx("button",{type:"button",disabled:oe===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(Si,{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)}),Be?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:pt=>{pt.stopPropagation(),navigator.clipboard.writeText(te.message||"").catch(()=>{})},children:e.jsx(Jn,{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:["#",oe+1]}),Ne?e.jsx(ee,{label:M.healthError||(Ne==="healthy"?"Connection is healthy":"Connection has an error"),children:e.jsx(le,{tone:Ne==="healthy"?"ok":"err",className:"max-w-[10rem] truncate text-[10px]",children:Ne==="healthy"?"OK":"Error"})}):null,ze?e.jsxs("span",{children:["checked ",ze]}):null,ke?e.jsx(ee,{label:M.lastError||"Credentials may be expired; reconnect this provider.",children:e.jsx(le,{tone:"warn",className:"max-w-[10rem] truncate text-[10px]",children:"Stale"})}):null,ce?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:"off"})]}):null]}),te||Ne||ze||ke?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(le,{tone:te.ok?"ok":"err",className:"text-[10px] font-semibold",children:te.ok?"Success":te.label})}):Ne?e.jsx(le,{tone:Ne==="healthy"?"ok":"err",className:"text-[10px] font-semibold",children:Ne==="healthy"?"Healthy":"Error"}):null,ze?e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["checked ",ze]}):null,ke?e.jsx(le,{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(Pi,{active:M.isActive!==!1,disabled:z===M.id,onToggle:()=>void O(M.id),activeLabel:"",inactiveLabel:""}),e.jsx(ee,{label:Be?"Stop":"Test",children:e.jsx(E,{size:"icon-sm",variant:"outline",className:"h-7 w-7 sm:hidden","aria-label":Be?"Stop test":"Test connection",onClick:()=>Be?be():void ne(M.id),children:Be?e.jsx(Ai,{className:"h-3 w-3 fill-current"}):e.jsx(Ti,{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(Xt,{busy:Be,onTest:()=>void ne(M.id),onStop:be})}),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:()=>ae(M),"aria-label":"Edit connection",children:[e.jsx(vs,{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:()=>we(M.id),"aria-label":"Delete connection",children:[e.jsx(Cn,{className:"size-4 sm:hidden"}),e.jsx("span",{className:"hidden font-medium sm:inline",children:"Delete"})]})})]})]})})},M.id)})})})})})]})})}function mr({selected:n,conns:s,activeConns:i,onEditCustom:a,onDeleteCustom:u,onAddConnection:d}){return e.jsxs(js,{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(Ns,{id:n.id,color:"var(--background)",size:24,fallbackIcon:fs(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(le,{tone:"ok",children:"Active"}),e.jsx(le,{tone:"muted",children:"Built-in"})]}):e.jsxs(e.Fragment,{children:[s.length>0?e.jsx(le,{tone:"ok",children:"Active"}):e.jsx(le,{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(vs,{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(Cn,{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(Tn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:Mn(n.authType,n.noAuth)}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})})]})]})}function hr({deleteId:n,bulkDeleteIds:s,bulkDeleting:i,deleteProvider:a,connections:u,onCloseDelete:d,onDeleteConnection:h,onCloseBulkDelete:b,onDeleteSelectedConnections:N,onCloseProvider:S,onRemoveProvider:K}){const j=a?u.filter(v=>v.provider===a.id):[];return e.jsxs(e.Fragment,{children:[e.jsx(Wt,{open:!!n,onOpenChange:v=>!v&&d(),children:e.jsxs(Ht,{children:[e.jsxs(Jt,{children:[e.jsx(Gt,{children:"Delete connection?"}),e.jsx(kn,{children:"Removes this key / session."})]}),e.jsxs(Yt,{children:[e.jsx(E,{variant:"outline",onClick:d,children:"Cancel"}),e.jsx(E,{variant:"destructive",onClick:h,children:"Delete"})]})]})}),e.jsx(Wt,{open:!!s,onOpenChange:v=>{!v&&!i&&b()},children:e.jsxs(Ht,{children:[e.jsxs(Jt,{children:[e.jsxs(Gt,{children:["Delete ",(s==null?void 0:s.length)??0," selected connections?"]}),e.jsx(kn,{children:"This will remove the selected keys or sessions. This action cannot be undone."})]}),e.jsxs(Yt,{children:[e.jsx(E,{variant:"outline",disabled:i,onClick:b,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:i,onClick:N,children:i?"Deleting…":"Delete"})]})]})}),e.jsx(Wt,{open:!!a,onOpenChange:v=>{v||S()},children:e.jsxs(Ht,{children:[e.jsxs(Jt,{children:[e.jsxs(Gt,{children:["Remove ",a==null?void 0:a.name,"?"]}),e.jsx(kn,{children:j.length>0?e.jsxs(e.Fragment,{children:["This provider has ",e.jsxs("strong",{children:[j.length," connection(s)"]})," that will also be deleted:",e.jsx("ul",{className:"mt-2 list-disc pl-4 text-xs",children:j.map(v=>e.jsx("li",{children:v.name||v.id},v.id))})]}):"This will remove the provider from the list."})]}),e.jsxs(Yt,{children:[e.jsx(E,{variant:"outline",onClick:S,children:"Cancel"}),e.jsx(E,{variant:"destructive",disabled:!a,onClick:()=>{a&&K(a)},children:"Remove"})]})]})})]})}async function Zn(n){const{data:s}=await At.get("/models/custom");return s.models??[]}async function fr(n,s){let i=0;for(const u of s)try{const d=typeof u=="string"?{id:u}:u,h=await Ss(n,d.id,d.name,d.capabilities);i+=h.added}catch{}const a=await Zn();return{added:i,total:a.length,models:a}}async function Ss(n,s,i,a){const{data:u}=await At.post("/models/custom",{providerAlias:n,id:s,name:i,capabilities:a}),d=await Zn();return{added:u.added===!0?1:0,total:d.length,models:d}}async function pr(n,s){const{data:i}=await At.delete("/models/custom",{params:{providerAlias:n,id:s}});return{success:i.success!==!1,removed:i.success!==!1}}async function xr(){const{data:n}=await At.get("/models/disabled");return n.disabled??{}}async function gr(n,s){await At.post("/models/disabled",{providerAlias:n,ids:s})}async function vr(n,s){await At.delete("/models/disabled",{params:{providerAlias:n,id:s}})}function yr(n,s){return n!==s}const br=50,us=1e3;function wn(n){return n.id==="opencode"||(n.connected||0)>0}function Br(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 Vt(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 b=i.match(/\bHTTP\s+(\d{3})\b/i);if(b)u=b[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 ms(n){var s,i;if(Qt.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 b=typeof(d==null?void 0:d.error)=="string"?d.error:"";h=(/^(?:test failed|internal server error)$/i.test(b)?d==null?void 0:d.message:b)||(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 Vt({ok:!1,status:u,message:h,detail:S})}return Vt({ok:!1,message:Z(n,"Test failed")})}function zr(){var p,w,x,T,q;const n=As(),s="nr-selected-provider",[i,a]=o.useState(()=>{try{return localStorage.getItem(s)}catch{return null}});function u(t){if(yr(i,t)){wt(null),Ue([]),at({}),Ye({}),ne(new Set),a(t);try{t?localStorage.setItem(s,t):localStorage.removeItem(s)}catch{}}}const[d,h]=o.useState(""),[b,N]=o.useState("all"),[S,K]=o.useState(()=>{try{const t=JSON.parse(localStorage.getItem("nr-hidden-providers")||"[]");return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}),[j,v]=o.useState(!1),[D,z]=o.useState(null),[A,J]=o.useState(null),[U,_]=o.useState(null),[G,$]=o.useState(!1),[ve,F]=o.useState(null),[Fe,De]=o.useState(!1),[qe,ye]=o.useState(null),[Ve,ne]=o.useState(new Set),[be,Y]=o.useState(0),[fe,se]=o.useState({}),[O,ae]=o.useState(""),[we,R]=o.useState(!1),[M,oe]=o.useState(!1),[pe,te]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-pinned-models")||"{}")}catch{return{}}}),[Be,ce]=o.useState(()=>{try{return JSON.parse(localStorage.getItem("nr-hidden-models")||"{}")}catch{return{}}}),[ke,Ne]=o.useState("");function ze(t,r){ce(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 pt(t,r){r.length&&ce(l=>{const y=new Set(r.map(I=>I.trim()).filter(Boolean)),g=new Set([...y].map(I=>I.slice(I.lastIndexOf("/")+1))),f=(l[t]||[]).filter(I=>{const V=String(I),ue=V.slice(V.lastIndexOf("/")+1);return!y.has(V)&&!g.has(ue)}),k={...l};f.length?k[t]=f:delete k[t];try{localStorage.setItem("nr-hidden-models",JSON.stringify(k))}catch{}return k})}const[it,Tt]=o.useState(0),[xe,Mt]=o.useState(""),[xt,Pt]=o.useState(null),[Zt,Et]=o.useState(null),[en,gt]=o.useState(()=>new Set),[un,Lt]=o.useState(!1),rt=o.useRef(!1),_e=o.useRef(new Map),It=4,[tn,Kt]=o.useState(null),[Rt,vt]=o.useState(null),We=o.useRef(null),[Pn,at]=o.useState({}),[En,Ye]=o.useState({}),[de,Xe]=o.useState("connections"),yt=o.useRef(null),ot=o.useRef(null),Ot=o.useRef(0),[Me,Ft]=o.useState(""),[bt,nn]=o.useState(""),[Se,Dt]=o.useState(1),[sn,Ue]=o.useState([]),[Ze,wt]=o.useState(null);o.useEffect(()=>{const t=window.setTimeout(()=>{nn(Me.trim())},250);return()=>window.clearTimeout(t)},[Me]);const $e=ht({queryKey:["connections",i,Se,bt],queryFn:()=>Xs({provider:i,page:Se,pageSize:br,search:bt||void 0}),enabled:!!i,retry:!1,refetchInterval:3e4});o.useEffect(()=>{Dt(1),wt(null),Ue([])},[i,bt]),o.useEffect(()=>{var r;const t=((r=$e.data)==null?void 0:r.connections)??[];if(i){if(!t.length&&Se===1){Ue([]),wt(i);return}Ue(l=>{const y=Se===1?[]:l,g=new Set(y.map(C=>C.id));return[...y,...t.filter(C=>!g.has(C.id))].slice(0,us)}),wt(i)}},[$e.data,Se,i]);const lt=Ze===i?sn:[],Pe=(p=$e.data)==null?void 0:p.pagination,qt=!!(Pe!=null&&Pe.hasNext&&lt.length>=us);o.useEffect(()=>{const t=ot.current;if(!t)return;const r=()=>{Ot.current=t.scrollTop};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[]),o.useLayoutEffect(()=>{const t=ot.current;t&&(t.scrollTop=Ot.current)},[i]),o.useEffect(()=>{const t=yt.current;if(!t||de!=="connections")return;const r=()=>{var y;const l=(y=$e.data)==null?void 0:y.pagination;!(l!=null&&l.hasNext)||$e.isFetching||qt||t.scrollTop+t.clientHeight>=t.scrollHeight-240&&Dt(g=>g+1)};return t.addEventListener("scroll",r,{passive:!0}),()=>t.removeEventListener("scroll",r)},[qt,(w=$e.data)==null?void 0:w.pagination,$e.isFetching,de]);const Bt=ht({queryKey:["providers-available"],queryFn:Zs,retry:!1}),he=ht({queryKey:["settings"],queryFn:Ks,retry:!1}),rn=ht({queryKey:["nodes"],queryFn:ii,retry:!1}),He=ht({queryKey:["custom-models"],queryFn:()=>Zn(),enabled:!!i,staleTime:0,refetchOnMount:"always",retry:!1,placeholderData:t=>t}),zt=ht({queryKey:["disabled-models"],queryFn:xr,retry:!1}),Ee=ht({queryKey:["available-models",it],queryFn:async()=>((await At.get("/models")).data.models??[]).map(r=>({id:Sn(r.routedModel||r.fullModel,r.provider),name:r.name||r.model,provider_alias:r.provider,provider_id:r.provider,owned_by:r.provider,caps:Wn(r.caps),thinkingLevels:Array.isArray(r.thinkingLevels)?r.thinkingLevels:void 0})),retry:!1});function P(t,r="default"){r==="success"?Nt.success(t):r==="error"?Nt.error(t):r==="warning"?Nt.warning(t):Nt(t)}const ct=o.useMemo(()=>{const t=Bt.data??[],r=new Set(t.map(g=>g.id)),l=rn.data??[],y=[];for(const g of l)r.has(g.id)||y.push({id:g.id,alias:g.prefix||g.id,name:g.name||g.prefix||g.id,authType:"apikey",isCustom:!0,baseUrl:g.baseUrl,nodeType:g.type,apiType:g.apiType,icon:"sway",connected:0});return[...t,...y]},[Bt.data,rn.data]),H=he.data,et=o.useMemo(()=>{const t=new Map;return i&&t.set(i,lt),t},[lt,i]),Ae=o.useMemo(()=>{let t=[...ct];if(b==="active"?t=t.filter(wn):b==="idle"&&(t=t.filter(r=>!wn(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,g=S.includes(l.id)?1:0;if(y!==g)return y-g;const C=wn(r)?1:0,f=wn(l)?1:0;return C!==f?f-C:(r.name||r.id).localeCompare(l.name||l.id)}),t},[ct,et,b,S,d]);function _t(t){K(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(ct.length===0||i&&ct.some(r=>r.id===i))return;let t=null;try{t=localStorage.getItem(s)}catch{t=null}if(t&&ct.some(r=>r.id===t)){a(t);return}},[ct,et,i]),o.useEffect(()=>{ne(new Set),Ft(""),ae(""),Xe("connections")},[i]),o.useEffect(()=>{const t=Ls(H,i||"");Mt(String(t))},[i,H]);const c=Ae.find(t=>t.id===i)||null;o.useEffect(()=>{c!=null&&c.noAuth&&Xe("models")},[i,c==null?void 0:c.noAuth]);const Le=o.useMemo(()=>{const t=c?[...et.get(c.id)||[]]:[];return t.sort((r,l)=>(r.priority??999)-(l.priority??999)||r.id.localeCompare(l.id)),t},[c,et]),re=Le,je=Ts({count:re.length,getScrollElement:()=>yt.current,estimateSize:()=>typeof window<"u"&&window.matchMedia("(max-width: 639px)").matches?64:72,overscan:10,getItemKey:t=>{var r;return((r=re[t])==null?void 0:r.id)??t},enabled:de==="connections"});o.useLayoutEffect(()=>{if(de!=="connections")return;let t=0;const r=requestAnimationFrame(()=>{je.measure(),t=requestAnimationFrame(()=>{je.measure()})});return()=>{cancelAnimationFrame(r),cancelAnimationFrame(t)}},[de,re.length,i,je]),o.useEffect(()=>{if(typeof window>"u")return;const t=window.matchMedia("(max-width: 639px)"),r=()=>{je.measure()};return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[je]),o.useEffect(()=>{const t=yt.current;if(!t||typeof ResizeObserver>"u")return;const r=new ResizeObserver(()=>{je.measure()});return r.observe(t),()=>r.disconnect()},[je,de,i]);const tt=o.useMemo(()=>Le.filter(t=>t.isActive!==!1),[Le]),ge=[...Ve][0]||((x=tt[0])==null?void 0:x.id)||((T=re[0])==null?void 0:T.id),Ie=Us(c),W=ht({queryKey:["connection-models",c==null?void 0:c.id,ge,it],queryFn:async()=>{const t=await is(ge);return $n(t.models,c==null?void 0:c.id)},enabled:!!(Ie&&ge),retry:!1}),kt=c?Is(H,c.id):"fill-first",Ce={"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"},dt=o.useMemo(()=>{if(!c)return[];const t=[],r=c.id,l=new Set([r,c.alias||""].filter(Boolean).map(g=>g.toLowerCase())),y=[...He.data??[],...(fe[r]??[]).map(g=>({providerAlias:r,id:g.id,name:g.name,capabilities:g.caps,thinkingLevels:g.thinkingLevels}))];for(const g of y)l.has(g.providerAlias.toLowerCase())&&t.push({id:Sn(g.id,g.providerAlias),name:g.name||g.id,caps:Wn(g.capabilities),thinkingLevels:Array.isArray(g.thinkingLevels)?g.thinkingLevels:void 0});if(Ie)t.push(...W.data??[]),!ge&&(r==="codebuddy-cn"||r==="codebuddy-intl"||r==="opencode"||r==="opencode-zen"||r==="opencode-go")&&t.push(...$n(c.models,r));else{const g=new Set([r,c.alias||""].map(C=>C.trim().toLowerCase()).filter(Boolean));for(const C of Ee.data??[])[C.provider_alias,C.provider_id,C.owned_by].filter(k=>!!k).map(k=>k.trim().toLowerCase()).some(k=>g.has(k))&&t.push(C)}return er(t,r)},[W.data,be,He.data,fe,Ee.data,c,ge,Ie]),an=Ie?He.isLoading||He.isFetching||W.isLoading||W.isFetching:He.isLoading||He.isFetching||Ee.isLoading||Ee.isFetching,mn=Ie&&!!W.error,Ke=c?or(c.id,dt.map(t=>t.thinkingLevels),c.thinkingConfig):null,nt=c?(q=H==null?void 0:H.providerThinking)==null?void 0:q[c.id]:void 0,hn=c?lr(c.id,c.thinkingConfig):"auto",ut=c?nt&&(Ke!=null&&Ke.includes(nt))?nt:Ke!=null&&Ke.includes(hn)?hn:(Ke==null?void 0:Ke[0])||"auto":"auto",Ln=o.useMemo(()=>{const t=new Map(Object.entries(Ce));for(const r of dt)r.name&&t.set(r.id,r.name);return t},[dt]),Ut=c?pe[c.id]||[]:[],fn=o.useMemo(()=>{const t=ke.trim().toLowerCase(),r=new Set(c?Be[c.id]||[]:[]);let l=dt.filter(f=>!r.has(f.id));if(t&&(l=l.filter(f=>f.id.toLowerCase().includes(t)||(f.name||"").toLowerCase().includes(t))),!Ut.length)return[...l].sort((f,k)=>f.id.localeCompare(k.id));const y=new Set(Ut),g=l.filter(f=>y.has(f.id)),C=l.filter(f=>!y.has(f.id)).sort((f,k)=>f.id.localeCompare(k.id));return[...g,...C]},[Be,dt,ke,Ut,c]),pn=o.useMemo(()=>{var r,l;if(!c)return new Set;const t=[...((r=zt.data)==null?void 0:r[c.id])??[],...c.alias?((l=zt.data)==null?void 0:l[c.alias])??[]:[]];return new Set(t)},[zt.data,c]);async function Q(t){if(c)try{pn.has(t)?(await vr(c.id,t),P(`Enabled ${t.split("/").pop()}`)):(await gr(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 Je(t){c&&te(r=>{const l=r[c.id]||[],y=l.includes(t)?l.filter(C=>C!==t):[...l,t],g={...r,[c.id]:y};try{localStorage.setItem("nr-pinned-models",JSON.stringify(g))}catch{}return g})}function Ge(){var t;(t=We.current)==null||t.abort();for(const r of _e.current.values())r.abort();_e.current.clear(),We.current=null,rt.current=!1,Lt(!1),Et(null),gt(new Set),vt(null),P("Tests stopped")}function mt(t){const r=_e.current.get(t);r&&(r.abort(),P("Model test stopped"))}async function on(t,r){Et(t);try{const l=await xs(t,void 0,{signal:r}),y=l.valid===!0,g=l.testedAt||new Date().toISOString(),C={testStatus:y?"active":"error",lastTested:g,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 at(f=>({...f,[t]:Vt({ok:y,message:l.error||(y?"Valid":"Failed"),latencyMs:l.latencyMs})})),Ue(f=>f.map(k=>k.id===t?{...k,...C}:k)),n.setQueriesData({queryKey:["connections"]},f=>f&&{...f,connections:(f.connections||[]).map(k=>k.id===t?{...k,...C}:k)}),y}catch(l){if(Qt.isCancel(l)||(l==null?void 0:l.code)==="ERR_CANCELED")return!1;const y=ms(l),g=new Date().toISOString();return at(C=>({...C,[t]:y})),Ue(C=>C.map(f=>f.id===t?{...f,testStatus:"error",lastTested:g,lastError:y.message,healthStatus:"error",healthError:y.message,healthLatencyMs:0}:f)),!1}finally{Et(l=>l===t?null:l)}}async function xn(t){if(!t.length)return P("Nothing to test");const r=new AbortController;We.current=r,vt("conn");let l=0;const y=4;for(let g=0;g<t.length&&!r.signal.aborted;g+=y){const C=t.slice(g,g+y),f=await Promise.all(C.map(k=>on(k,r.signal)));l+=f.filter(Boolean).length}r.signal.aborted||P(`Connections: ${l}/${t.length} passed`),vt(null)}async function gn(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(rt.current||Rt==="conn"||_e.current.has(t))return!1;if(_e.current.size>=It)return P(`Up to ${It} model tests can run at once`),!1}const g=l?null:new AbortController,C=l||g.signal;g&&_e.current.set(t,g),gt(f=>{const k=new Set(f);return k.add(t),k});try{if(y){const ue=(c==null?void 0:c.alias)||(c==null?void 0:c.id)||"opencode",Te=t.includes("/")?t:`${ue}/${t}`,Re=await $s(Te,{signal:C}),st=Re.ok===!0;return Ye(Ct=>({...Ct,[t]:Vt({ok:st,status:Re.status,message:(Re.error||"").trim()||(st?"OK":"Failed"),latencyMs:Re.latencyMs})})),st}const f=await Qs(r,{model:t,signal:C});if(!Array.isArray(f.results)){const ue=f.message||f.error||"No model test results returned";return Ye(Te=>({...Te,[t]:Vt({ok:!1,message:ue})})),!1}const k=t.includes("/")?t.slice(t.lastIndexOf("/")+1):t,I=(f.results??[]).find(ue=>{const Te=String(ue.modelId||"");return Te===k||Te===t||t.endsWith(`/${Te}`)||Te.endsWith(`/${k}`)}),V=!!(I!=null&&I.ok);return Ye(ue=>({...ue,[t]:Vt({ok:V,status:I==null?void 0:I.status,message:((I==null?void 0:I.error)||"").trim()||(V?"OK":"Failed"),latencyMs:I==null?void 0:I.latencyMs})})),V}catch(f){return Qt.isCancel(f)||(f==null?void 0:f.code)==="ERR_CANCELED"||Ye(k=>({...k,[t]:ms(f)})),!1}finally{gt(f=>{const k=new Set(f);return k.delete(t),k}),g&&_e.current.delete(t)}}async function vn(){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}oe(!0);try{const l={provider:c.id},y=new Set([c.id,c.alias].filter(Boolean).map(B=>B.trim().toLowerCase())),g=(rn.data??[]).find(B=>B.id===c.id),C=(r=(t=Le.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,f=c.baseUrl||c.modelsFetcherUrl||(g==null?void 0:g.baseUrl)||(typeof C=="string"?C:void 0);f&&(l.baseUrl=f);const k=B=>B.flatMap(L=>{if(!L||typeof L!="object")return[];const X=L,Oe=typeof X.id=="string"?X.id:typeof X.name=="string"?X.name:"";if(!Oe.trim())return[];const Qe=X.capabilities??X.caps;return[{id:Oe.trim(),...typeof X.name=="string"&&X.name.trim()?{name:X.name.trim()}:{},...Qe&&typeof Qe=="object"?{capabilities:Qe}:{}}]}),I=async()=>{const B=await is(ge,!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:k(B.models??[])}};let V;if(ge)try{V=await I()}catch(B){if(!l.baseUrl||Ie||c.id==="clinepass"||c.id==="cline-pass")throw B;V=await rs(l)}else V=await rs(l);if(!V.ok&&!V.success){P(V.message||V.error||"Import failed","error");return}const ue=V.models??[];if(!ue.length){P(V.message||"No models returned","warning");return}const Te=ue.map(B=>typeof B=="string"?B:B.id);pt(c.id,Te);const{added:Re,models:st}=await fr(c.id,ue),Ct=st.filter(B=>y.has(String(B.providerAlias||"").trim().toLowerCase())),$t=Ct.length;n.setQueryData(["custom-models"],st),se(B=>({...B,[c.id]:$n(Ct,c.id)})),Y(B=>B+1),Tt(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(Re>0?`Imported ${Re} new ${Re===1?"model":"models"} · Total ${$t} ${$t===1?"Model":"Models"}`:`No new models · Total ${$t} Models`,Re>0?"success":"default")}catch(l){P(Z(l,"Import failed"),"error")}finally{oe(!1)}}}async function In(){const t=O.trim();if(!(!c||!t||we)){R(!0);try{const r=await Ss(c.id,t);pt(c.id,[t]),n.setQueryData(["custom-models"],r.models),Y(l=>l+1),Tt(l=>l+1),await n.invalidateQueries({queryKey:["custom-models"]}),await n.invalidateQueries({queryKey:["available-models"]}),await n.invalidateQueries({queryKey:["sway-chat","models"]}),ae(""),Nt.success(`Added ${t}`)}catch(r){Nt.error(Z(r,"Failed to add model"))}finally{R(!1)}}}async function Kn(){const t=(c==null?void 0:c.noAuth)===!0;if(!ge&&!t)return P("Add a connection first");if(rt.current)return;if(_e.current.size>0)return P("Stop individual model tests before running Test all");const r=fn.map(C=>C.id);if(!r.length)return P("No models");rt.current=!0,Lt(!0),vt("model");const l=new AbortController;We.current=l;const y=new Array(r.length);let g=0;try{const C=Math.min(It,r.length),f=async()=>{for(;;){const k=g++;if(k>=r.length||l.signal.aborted)return;y[k]=await gn(r[k],t?void 0:ge,l.signal)}};if(await Promise.all(Array.from({length:C},()=>f())),!l.signal.aborted){const k=y.filter(V=>V!==void 0).length,I=y.filter(Boolean).length;P(`Models: ${I}/${k} passed`)}}catch(C){!Qt.isCancel(C)&&(C==null?void 0:C.code)!=="ERR_CANCELED"&&P(Z(C,"Model test failed"),"error")}finally{gt(new Set),vt(null),We.current===l&&(We.current=null),rt.current=!1,Lt(!1)}}const jt=es({mutationFn:async t=>{if(!c)return;const r=(H==null?void 0:H.providerStrategies)||{},l={...r[c.id]||{}};return t.strategy&&(l.fallbackStrategy=t.strategy),t.sticky&&(l.stickyRoundRobinLimit=t.sticky),ts({providerStrategies:{...r,[c.id]:l}})},onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]})}}),yn=es({mutationFn:async t=>{if(c)return ts({providerThinking:{...(H==null?void 0:H.providerThinking)||{},[c.id]:t}})},onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]})}});async function Rn(t){const r=lt.find(l=>l.id===t);if(!(!r||tn)){Kt(t);try{const l=await Vs(t,r.isActive!==!1);Ue(y=>y.map(g=>g.id===l.id?{...g,...l}:g)),n.invalidateQueries({queryKey:["connections"]}),n.invalidateQueries({queryKey:["providers-available"]}),P(`${l.name||r.name||"Connection"} ${l.isActive===!1?"disabled":"enabled"}`,"success")}catch(l){P(Z(l,"Failed to update connection"),"error")}finally{Kt(null)}}}async function On(t,r){const l=re.findIndex(I=>I.id===t);if(l<0)return;const y=l+r;if(y<0||y>=re.length)return;const g=re[l],C=re[y],f=g.priority??(l+1)*10,k=C.priority??(y+1)*10;await Promise.all([zn(g.id,{priority:k}),zn(C.id,{priority:f})]),n.invalidateQueries({queryKey:["connections"]})}async function Fn(t){try{await _n(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 Dn(){if(!(U!=null&&U.length)||G)return;const t=U;$(!0);const r=[];try{for(const y of t)try{await _n(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),_(null),P(`${l} connection${l===1?"":"s"} deleted`,"success")):l>0?(ne(new Set(r)),_(null),P(`Deleted ${l} of ${t.length} connections`,"warning")):P("Could not delete the selected connections","error")}finally{$(!1)}}async function qn(t){var y,g,C,f,k,I,V,ue,Te,Re,st,Ct,$t,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 Oe of t.codeBuddyTokens)try{await ln({provider:c.id,credentialToken:Oe.credentialToken,accessToken:Oe.accessToken,refreshToken:Oe.refreshToken,name:Oe.name,autoName:Oe.autoName,proxyPoolId:null}),L+=1}catch(Qe){if(Qt.isAxiosError(Qe)&&((g=Qe.response)==null?void 0:g.status)===409){X+=1;continue}throw Qe}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((C=t.bulkKeys)!=null&&C.length){let L=0,X=0;for(const Oe of t.bulkKeys)try{await ln({provider:c.id,apiKey:Oe.apiKey,name:Oe.name,autoName:Oe.autoName,proxyPoolId:r}),L+=1}catch(Qe){if(Qt.isAxiosError(Qe)&&((f=Qe.response)==null?void 0:f.status)===409){X+=1;continue}throw Qe}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??jn(c.id,c.authType,c.noAuth);if(c.id==="kiro"&&t.kiroAuthMode==="api-key"){if(!((k=t.apiKey)!=null&&k.trim()))throw new Error("API key required");const L=await Ws({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(!((I=t.kiroRefreshToken)!=null&&I.trim()))throw new Error("Refresh token required");const L=await Hs({refreshToken:t.kiroRefreshToken.trim(),clientId:((V=t.kiroClientId)==null?void 0:V.trim())||void 0,clientSecret:((ue=t.kiroClientSecret)==null?void 0:ue.trim())||void 0,region:t.kiroRegion,profileArn:((Te=t.kiroProfileArn)==null?void 0:Te.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(!((Re=t.kiroCliProxyJson)!=null&&Re.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 Js({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(!((st=t.codeBuddyToken)!=null&&st.trim()))throw new Error("An access token or refresh token is required.");await ln({provider:c.id,credentialToken:t.codeBuddyToken.trim(),name:t.name,autoName:t.autoName,proxyPoolId:null})}else if(l==="import"){if(!((Ct=t.importToken)!=null&&Ct.trim()))throw new Error("Access token required");const L=await Gs(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(!(($t=t.oauthCode)!=null&&$t.trim()))throw new Error("Paste the OAuth code from the browser callback");await Ys(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 ps(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 ln({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 ln({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 Bn(t){const r=Le.filter(l=>l.provider===t.id);(async()=>{for(const l of r)try{await _n(l.id)}catch{}si(t.id).then(()=>{n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),n.invalidateQueries({queryKey:["connections"]}),P("Provider removed")})})(),F(null)}const bn=Bt.isLoading,m=c?c.isCustom?"apikey":jn(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(Ms,{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:()=>De(!0),children:[e.jsx(Tn,{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(Gi,{byProvider:et,filter:b,hiddenProviders:S,loading:bn,query:d,providerListRef:ot,selectedId:i,sorted:Ae,onFilterChange:N,onQueryChange:h,onSelectProvider:u,onToggleProviderHidden:_t}),e.jsx(ks,{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(mr,{selected:c,conns:re,activeConns:tt,onEditCustom:()=>ye(c),onDeleteCustom:()=>F(c),onAddConnection:()=>v(!0)}),e.jsx(Cs,{className:"flex min-h-0 flex-1 flex-col overflow-hidden p-0",children:e.jsxs(ys,{value:c.noAuth?"models":de,onValueChange:Xe,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(bs,{children:[c.noAuth?null:e.jsx(Nn,{value:"connections",children:"Connection"}),e.jsx(Nn,{value:"models",children:"Models"})]})}),c.noAuth?null:e.jsx(ur,{selected:c,connsAll:Le,conns:re,strategy:kt,strategyPending:jt.isPending,stickyDraft:xe,thinkingLevels:Ke,thinkingValue:ut,thinkingPending:yn.isPending,selectedKeys:Ve,connectionsCapped:qt,totalConnections:(Pe==null?void 0:Pe.totalItems)??Le.length,batchKind:Rt,testingConnId:Zt,togglingConnId:tn,connQuery:Me,connListRef:yt,connVirtualizer:je,connResults:Pn,onStrategyChange:t=>jt.mutate({strategy:t}),onStickyDraftChange:Mt,onSaveSticky:()=>{const t=Math.max(1,parseInt(xe,10)||1);jt.mutate({sticky:t}),Mt(String(t))},onThinkingChange:t=>yn.mutate(t),onRequestBulkDelete:()=>_([...Ve]),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(re.map(t=>t.id))),onTestConnections:t=>xn(t),onTestConnection:t=>{on(t)},onStopTests:Ge,onConnQueryChange:Ft,onOpenAddConnection:()=>v(!0),onMovePriority:(t,r)=>On(t,r),onToggleConnection:t=>Rn(t),onEditConnection:z,onDeleteConnection:J}),e.jsx(tr,{selected:c,visibleModels:fn,models:dt,modelNames:Ln,modelsLoading:an,modelsUnavailable:mn,importingModels:M,testConnId:ge,batchKind:Rt,modelTestLock:un,testingModels:en,modelQuery:ke,newModel:O,addingModel:we,modelResults:En,pinnedFor:Ut,copied:xt,onImportModels:()=>void vn(),onTestAllModels:()=>void Kn(),onStopTests:Ge,onStopModel:mt,onModelQueryChange:Ne,onNewModelChange:ae,onAddModel:()=>void In(),onTogglePin:Je,onCopyModelId:async t=>{await navigator.clipboard.writeText(t),Pt(t),window.setTimeout(()=>Pt(null),1e3)},onTestModel:(t,r)=>void gn(t,r),onRemoveModel:async t=>{let r=!1;try{const l=await pr(c.id,t);r=(l==null?void 0:l.removed)===!0}catch{}finally{ze(c.id,t),Y(l=>l+1),Tt(l=>l+1),n.invalidateQueries({queryKey:["sway-chat","models"]})}Nt(`${r?"Removed":"Hidden"} ${t.split("/").pop()}`)},disabledModelIds:pn,onToggleDisabled:Q})]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground",children:"Select a provider"})})]}),e.jsx(Hi,{open:j,provider:c,flow:m,onOpenChange:v,onSubmit:async t=>{try{await qn(t)}catch(r){throw P(Z(r,"Add failed"),"error"),r}}}),e.jsx(Ji,{conn:D,onOpenChange:t=>!t&&z(null),onSave:async(t,r)=>{D&&(await zn(D.id,{name:t,...r.trim()?{apiKey:r.trim()}:{}}),n.invalidateQueries({queryKey:["connections"]}),z(null),P("Updated"))}}),e.jsx(hr,{deleteId:A,bulkDeleteIds:U,bulkDeleting:G,deleteProvider:ve,connections:Le,onCloseDelete:()=>J(null),onDeleteConnection:()=>A?Fn(A):void 0,onCloseBulkDelete:()=>_(null),onDeleteSelectedConnections:Dn,onCloseProvider:()=>F(null),onRemoveProvider:Bn}),e.jsx(ls,{open:Fe,onOpenChange:De,onCreate:async t=>{const r=await ti(t);n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),De(!1),u(r.id),P("Custom provider created")}}),e.jsx(ls,{open:!!qe,onOpenChange:t=>{t||ye(null)},initial:qe,submitLabel:"Save",onCreate:async t=>{if(!qe)return;const r=await ni(qe.id,t);n.invalidateQueries({queryKey:["nodes"]}),n.invalidateQueries({queryKey:["providers-available"]}),n.invalidateQueries({queryKey:["connections"]}),ye(null),u(r.id),P("Custom provider updated")}})]})}export{Br as compactErrorReason,zr 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-BvVNpO_s.js";import{b as v,c as t,p as b}from"./index-C4u3c95A.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
+ 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-I9hJ3zKn.js";import{b as v,c as t,p as b}from"./index-Dne9pkEF.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-COXbvTw8.js";import{F as ls}from"./flip-button-C5wry3x-.js";import{R as d}from"./ripple-button-XW6jAEYr.js";import{S as D}from"./StatusBadge-i3hGtYCs.js";import{C as xe}from"./checkbox-BIZ6J6ao.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-C4u3c95A.js";import{F as is,c as cs}from"./frame-DWGa-WbO.js";import{S as Me}from"./segmented-DUYkOckC.js";import{S as ds}from"./skeleton-dOHAk9tt.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as A}from"./table-B45T_8mH.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-Cf9et7QD.js";import{i as vs,A as bs}from"./connections-api-_WoB_gUT.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-BZEBRuoI.js";import{F as ls}from"./flip-button-yX_RgEC4.js";import{R as d}from"./ripple-button-BNF8KOIB.js";import{S as D}from"./StatusBadge-CbCgRp1u.js";import{C as xe}from"./checkbox-MVYpQird.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-Dne9pkEF.js";import{F as is,c as cs}from"./frame-R55qLb-9.js";import{S as Me}from"./segmented-W2XJE85e.js";import{S as ds}from"./skeleton-CuG5ZRYw.js";import{T as ms,a as xs,b as Qe,c as z,d as us,e as A}from"./table-CmYFkpYA.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-CZx9UMQG.js";import{i as vs,A as bs}from"./connections-api-BReJMHgi.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};
@@ -0,0 +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-Dne9pkEF.js";import{H as je}from"./Header-BZEBRuoI.js";import{R as B}from"./ripple-button-BNF8KOIB.js";import{S as y}from"./StatusBadge-CbCgRp1u.js";import{F as Q,a as D,c as F,d as Y}from"./frame-R55qLb-9.js";import{S as N}from"./skeleton-CuG5ZRYw.js";import{A as Ne,C as we}from"./connections-api-BReJMHgi.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};